code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def kmeans_xufive(ds, k): <NEW_LINE> <INDENT> m, n = ds.shape <NEW_LINE> result = np.empty(m, dtype=np.int) <NEW_LINE> cores = ds[np.random.choice(np.arange(m), k, replace=False)] <NEW_LINE> while True: <NEW_LINE> <INDENT> d = np.square(np.repeat(ds, k, axis=0).reshape(m, k, n) - cores) <NEW_LINE> distance = np.sqrt(np... | k-means聚类算法
k - 指定分簇数量
ds - ndarray(m, n),m个样本的数据集,每个样本n个属性值 | 625941d9d53ae8145f87a508 |
def transformInput(data): <NEW_LINE> <INDENT> p3py_data = {} <NEW_LINE> p3py_data['seq_args'] = {} <NEW_LINE> p3py_data['global_args'] = {} <NEW_LINE> for key in data.keys(): <NEW_LINE> <INDENT> if('SEQUENCE_' in key.upper()): <NEW_LINE> <INDENT> p3py_data['seq_args'][key.upper()] = data[key] <NEW_LINE> <DEDENT> elif('... | separate input to seq_args and global_args
Args:
data: input data
Returns:
separated input data | 625941d991af0d3eaac9bcb7 |
def all_constraints(self): <NEW_LINE> <INDENT> gp = self.upper_bound_constraints()._gp <NEW_LINE> gp += self.lower_bound_constraints()._gp <NEW_LINE> gp += self.linear_constraints()._gp <NEW_LINE> gp += self.quadratic_constraints()._gp <NEW_LINE> gp += self.SOS_constraints()._gp <NEW_LINE> gp += self.indicator_constrai... | Returns an object instructing the conflict refiner to include
all constraints.
Calling
Cplex.conflict.refine(Cplex.conflict.all_constraints()) or
Cplex.conflict.refine_MIP_start(Cplex.conflict.all_constraints())
will result in every constraint being included in the search
for conflicts with equal preference.
Example ... | 625941d93c8af77a43ae3a3e |
def cos(z) -> None: <NEW_LINE> <INDENT> ... | 返回z的余弦。 | 625941d9b5575c28eb68e29e |
def new(url, basic=True, gdata=False, signature=True, size=False, callback=lambda x: None): <NEW_LINE> <INDENT> if not signature: <NEW_LINE> <INDENT> logging.warning("signature argument has no effect and will be removed" " in a future version.") <NEW_LINE> <DEDENT> return Pafy(url, basic, gdata, signature, size, callba... | Return a new pafy instance given a url or video id.
NOTE: The signature argument has been deprecated and now has no effect,
it will be removed in a future version.
Optional arguments:
basic - fetch basic metadata and streams
gdata - fetch gdata info (upload date, description, category)
size - fetch th... | 625941d9f548e778e58cd81b |
def pullData(): <NEW_LINE> <INDENT> TOKEN = config["TOKEN"] <NEW_LINE> GROUP_ID = config["GROUP_ID"] <NEW_LINE> baseURL = "https://api.groupme.com/v3" <NEW_LINE> auth = "?token="+TOKEN <NEW_LINE> endPoint = "/groups/"+GROUP_ID+"/messages" <NEW_LINE> allMessages = [] <NEW_LINE> messages = json.loads(requests.get( baseUR... | Pull Data from GroupMe API | 625941d9d8ef3951e32437da |
def irc_RPL_WELCOME(self, msg): <NEW_LINE> <INDENT> nick = msg.params[0] <NEW_LINE> if nick != self.nick: <NEW_LINE> <INDENT> self.nick = nick <NEW_LINE> self.on_nick_changed(self.nick) <NEW_LINE> <DEDENT> self.on_welcome() | Received welcome from server, now we can start communicating.
Welcome should include the accepted nick as the first parameter. This
may be different to the nick we requested (e.g. truncated to a maximum
length); if this is the case we store the new nick and fire the
:meth:`on_nick_changed` event. | 625941d956b00c62f0f148f7 |
def _get_or_create_event_type(self, event_type, session=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if session is None: <NEW_LINE> <INDENT> session = self._engine_facade.get_session() <NEW_LINE> <DEDENT> with session.begin(subtransactions=True): <NEW_LINE> <INDENT> et = session.query(models.EventType).filter( m... | Check if an event type with the supplied name is already exists.
If not, we create it and return the record. This may result in a flush. | 625941d90a50d4780f667130 |
def markAllMessagesRead(): <NEW_LINE> <INDENT> global usrPrompt <NEW_LINE> try: <NEW_LINE> <INDENT> inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages'] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('\n Connection Error\n') <NEW_LINE> usrPrompt = 0 <NEW_LINE> main() <NEW_LINE> <DEDENT> for... | Mark all messages as read | 625941d90fa83653e4657256 |
def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = np.array(x) <NEW_LINE> self.y = np.array(y) | Initialize history. | 625941d98da39b475bd65212 |
def get_month_data_range(months_ago=1, include_this_month=False): <NEW_LINE> <INDENT> today = datetime.datetime.now().today() <NEW_LINE> dates_ = [] <NEW_LINE> if include_this_month: <NEW_LINE> <INDENT> next_month = today.replace(day=28) + datetime.timedelta(days=4) <NEW_LINE> start, end = get_last_month_data(next_mont... | A method that generates a list of dictionaries
that describe any given amount of monthly data. | 625941d956ac1b37e6264468 |
def restart_workers(self): <NEW_LINE> <INDENT> self.bot.shutdown_mp() <NEW_LINE> self.bot.handler.workers.__init__(self.bot.handler) <NEW_LINE> self.bot.server = server.init_server(self.bot) | Force all the workers to restart so we get the log message. | 625941d99c8ee82313fbba12 |
def __init__(self, filename, mode=None, multifilestyle="single"): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> if mode is None: <NEW_LINE> <INDENT> if os.path.exists(filename): <NEW_LINE> <INDENT> mode = 'r' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mode = 'w' <NEW_LINE> <DEDENT> <DEDENT> self.mode = mod... | initialises oomultifile from a seekable inputfile or writable outputfile | 625941d9f7d966606f6aa2a4 |
def test_login_required(self): <NEW_LINE> <INDENT> res = self.client.get(INGREDIENTS_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | test that login is req to login | 625941d9cc40096d61595bec |
def _linearize_children(self): <NEW_LINE> <INDENT> return False | Return a flag that is True when we need to call linearize on our subsystems' solvers.
Returns
-------
boolean
Flag for indicating child linearization. | 625941d90a50d4780f667131 |
def tearDown(self): <NEW_LINE> <INDENT> empty_db() | clear out all the testing DB data | 625941d9498bea3a759b9d4b |
def invoke_lambda(self, day: int, payload: Dict): <NEW_LINE> <INDENT> lmbda = get_boto_session().client('lambda') <NEW_LINE> res = lmbda.invoke( FunctionName='aoc-dev-aoc', InvocationType='RequestResponse', Payload=json.dumps(dict( day=current_day, **payload, ))) <NEW_LINE> res = json.loads(res['Payload'].read()) <NEW_... | Invoke lambda for day with payload and return result. | 625941d9ff9c53063f47c48f |
def _compressor_op(self, matrix_compressor, a_matrix_tfvar): <NEW_LINE> <INDENT> use_tpu = self._spec.use_tpu <NEW_LINE> if use_tpu: <NEW_LINE> <INDENT> [b_matrix_out, c_matrix_out] = matrix_compressor.tpu_matrix_compressor(a_matrix_tfvar) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> [b_matrix_out, c_matrix_out ] = tf... | Creates compressor op based on matrix_compressor.
Meant to create the factors once at begin_compression_step.
Args:
matrix_compressor: specifies the matrix compressor object.
a_matrix_tfvar: the tf tensor to be compressed.
Returns:
A TF op which does the compressor update on b and c. | 625941d9d7e4931a7ee9e1bb |
def get_last_played(self, game: str, version: int, userid: UserID, count: int) -> List[Tuple[int, int]]: <NEW_LINE> <INDENT> sql = ( "SELECT DISTINCT(music.songid) AS songid, score_history.timestamp AS timestamp FROM score_history, music " + "WHERE score_history.userid = :userid AND score_history.musicid = music.id " +... | Look up a user's last played songs.
Parameters:
game - String representing a game series.
version - Integer representing which version of the game.
userid - Integer representing a user. Usually looked up with UserData.
count - Number of scores to look up.
Returns:
A list of tuples, containing the ... | 625941d9a8ecb033257d3369 |
def containsOnly(seq, aset): <NEW_LINE> <INDENT> for c in seq: <NEW_LINE> <INDENT> if c not in aset: return False <NEW_LINE> <DEDENT> return True | 检查序列是否仅仅含有aset中的项 | 625941d92ae34c7f2600d3ce |
def __init__(self, stdin=None, stdout=None, stderr=None, encoding="utf8", args=None, db=None): <NEW_LINE> <INDENT> super(Shell, self).__init__() <NEW_LINE> self.exceptions=False <NEW_LINE> self.history_file="~/.sqlite_history" <NEW_LINE> self._db=None <NEW_LINE> self.dbfilename=None <NEW_LINE> if db: <NEW_LINE> <INDENT... | Create instance, set defaults and do argument processing. | 625941d9b545ff76a89140b2 |
def init(self, T, params={}): <NEW_LINE> <INDENT> self.reward = [] <NEW_LINE> self.opt_reward = [] <NEW_LINE> self.dist = [1.0/self.B.N for i in range(self.B.N)] | Initialize the semibandit algorithm for a run.
Args:
T -- maximum number of rounds. | 625941d985dfad0860c3b0f8 |
def copy_prf(self, f_prf): <NEW_LINE> <INDENT> assert f_prf <NEW_LINE> super(CPrfNEW, self).copy_prf(f_prf) <NEW_LINE> self._c_prf_esteira = f_prf.c_prf_esteira <NEW_LINE> self.__f_prf_teto_sv = f_prf.f_prf_teto_sv <NEW_LINE> self.__f_prf_faixa = f_prf.f_prf_faixa <NEW_LINE> self.__f_prf_vel_dec = f_prf.f_prf_vel_dec <... | copy constructor.
cria uma nova performance a partir de uma outra performance.
@param f_prf: performance a ser copiada. | 625941d9aad79263cf390ce1 |
@app.route("/login", methods=["GET", "POST"]) <NEW_LINE> def login(): <NEW_LINE> <INDENT> session.clear() <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> if not request.form.get("username"): <NEW_LINE> <INDENT> return apology("must provide username", 400) <NEW_LINE> <DEDENT> elif not request.form.get("passw... | Log user in | 625941d926238365f5f0f10e |
def test_learner_smoke(mocker, continuous_env, agent_step_ret): <NEW_LINE> <INDENT> output_dir, exp_name = 'tests/tmp_test_outputs', 'learner_test' <NEW_LINE> agent = mocker.Mock() <NEW_LINE> agent.build_graph.return_value = {'saver': 'config'} <NEW_LINE> mocker.patch( 'deeprl.learners.policy_gradient_learner.EpochLogg... | Give it a a test run witha mock agent, see that is produces logs | 625941d9187af65679ca53bc |
def import_file(full_name, path): <NEW_LINE> <INDENT> from importlib import util <NEW_LINE> spec = util.spec_from_file_location(full_name, path) <NEW_LINE> mod = util.module_from_spec(spec) <NEW_LINE> spec.loader.exec_module(mod) <NEW_LINE> return mod | Import a python module from a path. 3.4+ only.
Does not call sys.modules[full_name] = path
:param full_name: name of the package
:param path: path of the package
:return: module | 625941d93c8af77a43ae3a3f |
def __init__(self): <NEW_LINE> <INDENT> self.TotalCount = None <NEW_LINE> self.WatermarkTemplateSet = None <NEW_LINE> self.RequestId = None | :param TotalCount: Number of eligible entries.
:type TotalCount: int
:param WatermarkTemplateSet: List of watermarking template details.
:type WatermarkTemplateSet: list of WatermarkTemplate
:param RequestId: The unique request ID, which is returned for each request. RequestId is required for locating a problem.
:type ... | 625941d9711fe17d82542603 |
def test_get_url(): <NEW_LINE> <INDENT> assert get_url('USD') == settings.FEED_URL_PREFIX + 'usd' + settings.FEED_URL_SUFFIX | Given: currency
When: call get_url
Then: proper url is returned | 625941d9d10714528d5fff83 |
def read_data(self, filename, append = False, rescale = True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> newxdata, newydata = np.loadtxt(filename, unpack = True) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> print("*** Unable to read file: %s" % (filename)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if... | read in the data file | 625941d9baa26c4b54cb13ba |
def values(self, evidence=None): <NEW_LINE> <INDENT> for _, val in self.itervalues(evidence): <NEW_LINE> <INDENT> yield val | Returns a generator of possible values of this variable under consideration of
the evidence given, if any.
Same as ``itervalues()`` but without value indices. | 625941d944b2445a33932331 |
def writeBF2(graph): <NEW_LINE> <INDENT> graph.serialize('BF2specs/bibframe2.rdf', format='pretty-xml') <NEW_LINE> graph.serialize('BF2specs/bibframe2.nt', format='nt') <NEW_LINE> graph.serialize('BF2specs/bibframe2.ttl', format='turtle') | Grab most recent BF2 spec from id.loc.gov, serialize for comparison. | 625941d9377c676e91272445 |
def _get_context(self, scope): <NEW_LINE> <INDENT> if scope != Scope.Transient: <NEW_LINE> <INDENT> context, lock = self._context.get(scope, (None, None)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context, lock = {}, None <NEW_LINE> <DEDENT> if context is None: <NEW_LINE> <INDENT> raise UndefinedScopeError("No scop... | Get the context for the *scope*, that is a dictionary of the
feature instances. Raises a :exc:`yaak.inject.UndefinedScopeError`
if the *scope* is not defined. | 625941d992d797404e304428 |
def main(): <NEW_LINE> <INDENT> numCases = int(sys.stdin.readline()) <NEW_LINE> for scenarioNum in range(1,numCases+1): <NEW_LINE> <INDENT> inputList = sys.stdin.readline().split(" ") <NEW_LINE> p = int(inputList[0]) <NEW_LINE> n = int(inputList[1]) <NEW_LINE> paperDatabase, targetNamesList, nameDictionary = acquireSce... | paperDatabase: List of papers, each one with one or more authors;
authors are represented by integers
targetNamesList: List of author names for which their Erdos number
is desired; authors are represented by strings
nameDictionary: Allows conversion between integer representation
and string representation of author ... | 625941d93346ee7daa2b300a |
def __init__(self, groups=None, name=None, owner=None, status=None): <NEW_LINE> <INDENT> self._groups = groups <NEW_LINE> self._name = name <NEW_LINE> self._owner = owner <NEW_LINE> self._status = status <NEW_LINE> self.discriminator = None | ApiKeyUpdateReq - a model defined in Swagger | 625941d97b180e01f3dc4a96 |
@main.route('/continue-application/<application_id>/<applicant>', methods=['GET', 'POST']) <NEW_LINE> @login_required <NEW_LINE> def continue_application(application_id, applicant): <NEW_LINE> <INDENT> application = Application.query.get(application_id) <NEW_LINE> if applicant not in ('borrower', 'guarantor'): <NEW_LIN... | continue application | 625941d9a8370b7717052b3b |
def get_closest(x0, y0, x1, y1, xmin, ymin, xmax, ymax): <NEW_LINE> <INDENT> if x0 == x1 or y0 == y1: <NEW_LINE> <INDENT> x0, x1 = clamp_axis(x0, x1, xmin, xmax) <NEW_LINE> y0, y1 = clamp_axis(y0, y1, ymin, ymax) <NEW_LINE> return x0, y0, x1, y1 <NEW_LINE> <DEDENT> p0_code = get_zonecode(x0, y0, xmin, ymin, xmax, ymax)... | Return the point or line segment within the min/max bounds that is closest
to the line segment between (x0, y0) and (x1, y1). | 625941d921a7993f00bc7f90 |
def from_json(self, filename: str, silent: bool=False) -> None: <NEW_LINE> <INDENT> file_path = self.root_path / filename <NEW_LINE> try: <NEW_LINE> <INDENT> with open(file_path) as file_: <NEW_LINE> <INDENT> data = json.loads(file_.read()) <NEW_LINE> <DEDENT> <DEDENT> except (FileNotFoundError, IsADirectoryError): <NE... | Load the configuration values from a JSON formatted file.
This allows configuration to be loaded as so
.. code-block:: python
app.config.from_json('config.json')
Arguments:
filename: The filename which when appended to
:attr:`root_path` gives the path to the file.
silent: If True any errors will... | 625941d9091ae356686671f8 |
def test_approved_cycle_and_bill_creation(self): <NEW_LINE> <INDENT> makebills() <NEW_LINE> self.assertEqual(len(mail.outbox), 1) <NEW_LINE> self.assertEqual(len(self.membership.billingcycle_set.all()), 1) <NEW_LINE> membership2 = create_dummy_member('N') <NEW_LINE> membership2.preapprove(self.user) <NEW_LINE> membersh... | makebills: cycle and bill creation | 625941d944b2445a33932332 |
@manager.option('-e', '--endpoint', dest='endpoint_name', help='Name of the endpoint you wish to rotate.') <NEW_LINE> @manager.option('-n', '--new-certificate', dest='new_certificate_name', help='Name of the certificate you wish to rotate to.') <NEW_LINE> @manager.option('-o', '--old-certificate', dest='old_certificate... | Rotates an endpoint and reissues it if it has not already been replaced. If it has
been replaced, will use the replacement certificate for the rotation. | 625941d945492302aab5e563 |
def check(i, answer, count1): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> if answer == 'c' or answer == 'C': <NEW_LINE> <INDENT> count1 += 1 <NEW_LINE> <DEDENT> <DEDENT> if i == 1: <NEW_LINE> <INDENT> if answer == 'd' or answer == 'D': <NEW_LINE> <INDENT> count1 += 1 <NEW_LINE> <DEDENT> <DEDENT> if i == 2: <NEW_... | :type count: object | 625941d95e10d32532c5f1c4 |
def __init__ (self) : <NEW_LINE> <INDENT> self.diffs = [] | diffs - a list of updates. Each update is of
the form [x, y, symbol_prev, symbol_curr] | 625941d91d351010ab855db9 |
def get_repo_issue_milestone_labels(self, repo, issue): <NEW_LINE> <INDENT> iss_id = check_type(issue) <NEW_LINE> return helper(add_query(urlbuilder(self._url[:-1], 'repos', self._user, repo, 'milestone', iss_id, 'labels'), self._token)) | Gets repository issue milestone labels.
Args:
repo: repo name, as string.
issue: issue id, as int. | 625941d93eb6a72ae02ec780 |
def create_training_instances(input_file, tokenizer, max_seq_length, dupe_factor, masked_lm_prob, max_predictions_per_seq, rng, length_dist=None, lengths=None, statistics=None, ngrams=None): <NEW_LINE> <INDENT> all_documents = [[]] <NEW_LINE> wiki_format = ("wiki" in input_file) <NEW_LINE> with tf.gfile.GFile(input_fil... | Create `TrainingInstance`s from raw text. | 625941d9be8e80087fb20edd |
def run( self, n_or_sample: T.Union[int, T.Sequence[int]], iterations: int = 1, *, random: T.Optional[RandomLike] = None, total_mass: TH.QuantityType = None, c_err: T.Union[CERR_Type, None, TE.Literal[False]] = None, observable: T.Optional[str] = None, batch: bool = False, progress: bool = True, **kwargs, ) -> object: ... | Call.
Parameters
----------
n : int (optional)
number of sample points
iterations : int (optional)
Number of iterations. Must be > 0.
random : int or |RandomState| or None (optional, keyword-only)
Random state or seed.
In order that a sequence of samples is different in each element
we here resolv... | 625941d96aa9bd52df037042 |
def __init__(self, *args): <NEW_LINE> <INDENT> this = _openmm.new_LocalCoordinatesSite(*args) <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.this = this | __init__(self, particle1, particle2, particle3, originWeights, xWeights, yWeights, localPosition) -> LocalCoordinatesSite
__init__(self, other) -> LocalCoordinatesSite
Create a new LocalCoordinatesSite virtual site.
Parameters
----------
particle1 : int
the index of the first particle
particle2 : int
the inde... | 625941d95fdd1c0f98dc04d1 |
def createRef(self): <NEW_LINE> <INDENT> r = Reference(Atom(self.nodeName), self.refIds, self.creation) <NEW_LINE> self.refIds[0] += 1 <NEW_LINE> if self.refIds[0] > 0x3ffff: <NEW_LINE> <INDENT> self.refIds[0] = 0 <NEW_LINE> self.refIds[1] += 1 <NEW_LINE> if isinstance(self.refIds[1], long): <NEW_LINE> <INDENT> self.re... | Create an unique erlang reference. | 625941d90c0af96317bb8485 |
def get_dfs_group_info(self): <NEW_LINE> <INDENT> dfs_group_info = dict() <NEW_LINE> conf_str = CE_NC_GET_DFS_GROUP_INFO <NEW_LINE> xml_str = get_nc_config(self.module, conf_str) <NEW_LINE> if "<data/>" in xml_str: <NEW_LINE> <INDENT> return dfs_group_info <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xml_str = xml_str... | get dfs group attributes info. | 625941d967a9b606de4a8155 |
@OpSchema.Inputs(1) <NEW_LINE> def MPIBroadcast(inputs, root, mpi_ranks=None, **kwargs): <NEW_LINE> <INDENT> arguments = ParseArgs(locals()) <NEW_LINE> if mpi_ranks is None: <NEW_LINE> <INDENT> num_nodes = mpi.Size() <NEW_LINE> mpi_ranks = [i for i in range(0, num_nodes)] <NEW_LINE> <DEDENT> if not isinstance(mpi_ranks... | Broadcast a tensor to all nodes in the ``MPIGroup``.
Parameters
----------
inputs : Tensor
The tensor to broadcast.
root : int
The world rank of root node.
mpi_ranks: sequence of int, optional
The world rank of nodes in group. Default is ``None`` (Use All).
Returns
-------
Tensor
The broadcast output.... | 625941d9cc40096d61595bed |
def broadcast_rpc(self, op, req): <NEW_LINE> <INDENT> future_list = [] <NEW_LINE> for slave_conn in self.slave_pool: <NEW_LINE> <INDENT> future_list.append( slave_conn.write_rpc_request( op=op, cmd=req, metadata=ClusterMetadata(ROOT_BRANCH, 0) ) ) <NEW_LINE> <DEDENT> return future_list | Broadcast RPC request to all slaves.
| 625941d9a8370b7717052b3c |
def setParameters(self, n, params): <NEW_LINE> <INDENT> return _Math.InPlaceFilterD_setParameters(self, n, params) | setParameters(InPlaceFilterD self, int n, double const * params) -> int | 625941d9a17c0f6771cbe2ed |
def normalize_image(img): <NEW_LINE> <INDENT> norm = np.zeros(img.shape, dtype=np.float32) <NEW_LINE> norm_bgr = np.zeros(img.shape, dtype=np.uint8) <NEW_LINE> b = img[:,:,0] <NEW_LINE> g = img[:,:,1] <NEW_LINE> r = img[:,:,2] <NEW_LINE> total = r + g + b <NEW_LINE> np.seterr(divide='ignore', invalid='ignore') <NEW_LIN... | Normalizes the BGR image
:param img: image that we want to normalize (needs to be bgr format)
:return: normalized bgr image | 625941d91b99ca400220ad4f |
def compile(pattern, *args, **kwargs): <NEW_LINE> <INDENT> id, p = repr(pattern) + repr(args), pattern <NEW_LINE> if id in _cache and not kwargs: <NEW_LINE> <INDENT> return _cache[id] <NEW_LINE> <DEDENT> if isinstance(pattern, str): <NEW_LINE> <INDENT> p = Pattern.fromstring(pattern, *args, **kwargs) <NEW_LINE> <DEDENT... | Returns a Pattern from the given string or regular expression.
Recently compiled patterns are kept in cache
(if they do not use taxonomies, which are mutable dicts). | 625941d9460517430c39441d |
def get_num_features(fp_size, kernel_size, padding, stride): <NEW_LINE> <INDENT> return (fp_size - kernel_size + 2 * padding) / stride + 1 | Computes the number of features created by a 2d convolution.
See: http://cs231n.github.io/convolutional-networks/ | 625941d9d8ef3951e32437db |
def train(self, verbose=True): <NEW_LINE> <INDENT> for i in xrange(self.epochs): <NEW_LINE> <INDENT> preds = [] <NEW_LINE> for inputs,label in zip(self.trainingSet.input, self.trainingSet.label): <NEW_LINE> <INDENT> pred = self.fire(inputs) <NEW_LINE> preds.append(pred) <NEW_LINE> error = label-int(pred) <NEW_LINE> sel... | Train the perceptron with the perceptron learning algorithm.
Parameters
----------
verbose : boolean
Print logging messages with validation accuracy if verbose is True. | 625941d94f6381625f114cd9 |
def test_admin_required(self): <NEW_LINE> <INDENT> self.site_settings.submission_requires_login = True <NEW_LINE> self.site_settings.display_submit_button = False <NEW_LINE> self.site_settings.save() <NEW_LINE> self.assertFalse(_has_submit_permissions(self.anonymous_request)) <NEW_LINE> self.assertFalse(_has_submit_per... | If login is required and no submit button is displayed, only admin
requests should pass the permissions check. | 625941d92c8b7c6e89b35a5d |
def set_detectors_at(self, detectors_at): <NEW_LINE> <INDENT> idx = 0 <NEW_LINE> for comp in self.components.values(): <NEW_LINE> <INDENT> comp.set_detectors_at(detectors_at[idx : idx + comp.num_ports]) <NEW_LINE> idx += comp.num_ports | set the locations of the detectors in the network | 625941d9d99f1b3c44c67829 |
def get_wanted_item_by_video_path(self, video_path, ignore_case=False): <NEW_LINE> <INDENT> connection = sqlite3.connect(autosubliminal.DBFILE) <NEW_LINE> connection.row_factory = _wanted_item_factory <NEW_LINE> cursor = connection.cursor() <NEW_LINE> cursor.execute(self._query_get_by_video_path_ignore_case if ignore_c... | Get a wanted item by its video path.
:param video_path: the video path
:type video_path: str
:return: the wanted item
:rtype: WantedItem | 625941d9d18da76e23532776 |
def write_data(self): <NEW_LINE> <INDENT> f = open("data.txt","w+") <NEW_LINE> for each in range(0, 6): <NEW_LINE> <INDENT> f.write("This is line %d\r\n" % each) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> return True | open the file and write the data
:return: boolean True | 625941d96fb2d068a760f33e |
def __init__(self, movie_id=None, name=None, description=None, year=None, poster=None, thumb=None, fanart=None, duration=None, remaining=None, geoblocked=None, channel=None, legal=None, aired=None, my_list=None): <NEW_LINE> <INDENT> self.movie_id = movie_id <NEW_LINE> self.name = name <NEW_LINE> self.description = desc... | :type movie_id: str
:type name: str
:type description: str
:type year: int
:type poster: str
:type thumb: str
:type fanart: str
:type duration: int
:type remaining: str
:type geoblocked: bool
:type channel: Optional[str]
:type legal: str
:type aired: str
:type my_list: bool | 625941d924f1403a92600e02 |
def peek(self): <NEW_LINE> <INDENT> assert not self.isEmpty(), "Cannot peek at an empty stack" <NEW_LINE> return self._theItems[-1] | Returns the top item on the stack without removing it. | 625941d9851cf427c661a7ab |
def get_can_gang_info_by_handcard(self, card, hand_card): <NEW_LINE> <INDENT> card_type = Card.cal_card_type(card) <NEW_LINE> card_digit = Card.cal_card_digit(card) <NEW_LINE> return 4 == hand_card.peng_card_vals.count(card)+hand_card.hand_card_info[card_type][card_digit] | 判断某张牌是否可以杠(点杠/补杠)
:param card: 待判断的牌
:param cur_card_list: 当前手牌
:return: 返回是否可杠牌 | 625941d926068e7796caef7f |
def MatchingPursuit(A, b, tol=1E-4, nnz=None, positive=False, orthogonal=False): <NEW_LINE> <INDENT> if orthogonal: <NEW_LINE> <INDENT> return OrthogonalMP(A, b, tol=tol, nnz=nnz, positive=positive) <NEW_LINE> <DEDENT> AT = A.T <NEW_LINE> d, n = A.shape <NEW_LINE> if nnz is None: <NEW_LINE> <INDENT> nnz = n <NEW_LINE> ... | approximately solves min_x |x|_0 s.t. Ax=b using Matching Pursuit
Args:
A: design matrix of size (d, n)
b: measurement vector of length d
tol: solver tolerance
nnz = maximum number of nonzero coefficients (if None set to n)
positive: only allow positive nonzero coefficients
orthogonal: use Orthogonal Matchi... | 625941d973bcbd0ca4b2c314 |
def gte(self, **kwargs): <NEW_LINE> <INDENT> return self._filter('gte', **kwargs) | Filters greater than or equal to a value.
Example:
>>> import mage
>>> mage.connect()
>>> list(mage.AssessmentRun.gte(score=60)) | 625941d9d268445f265b510c |
def setModel(self, model, relayout=True): <NEW_LINE> <INDENT> self._model = model <NEW_LINE> self._reset_model(self.dataTable, model) <NEW_LINE> self._reset_model(self.table_level, DataFrameLevelModel(model, self.palette(), self.font())) <NEW_LINE> self._reset_model(self.table_header, DataFrameHeaderModel( model, 0, se... | Set the model for the data, header/index and level views. | 625941d9ab23a570cc250422 |
def __init__(self, particleEffect, duration=0.0, parent = None, renderParent = None, name=None): <NEW_LINE> <INDENT> id = 'Particle-%d' % TestInterval.particleNum <NEW_LINE> TestInterval.particleNum += 1 <NEW_LINE> if name == None: <NEW_LINE> <INDENT> name = id <NEW_LINE> <DEDENT> self.particleEffect = particleEffect <... | particleEffect is ??
parent is ??
worldRelative is a boolean
loop is a boolean
duration is a float for the time
name is ?? | 625941d9bd1bec0571d908cc |
def flush(self): <NEW_LINE> <INDENT> buffer_full = True <NEW_LINE> while buffer_full: <NEW_LINE> <INDENT> d,v = self.listen() <NEW_LINE> if not d: <NEW_LINE> <INDENT> buffer_full = False | Flush the buffer of old data
| 625941d94428ac0f6e5baa91 |
def product_expansion(self, combinations, dotpath, sweep): <NEW_LINE> <INDENT> new_combinations = [] <NEW_LINE> for i, combo in enumerate(combinations): <NEW_LINE> <INDENT> flag = False <NEW_LINE> for key in sweep: <NEW_LINE> <INDENT> if all(map(lambda t: ".".join(t) in combo, self.parse_ref_dotpath(key))): <NEW_LINE> ... | Takes as input | 625941d9cdde0d52a9e532d3 |
def f_H(q, p, cov_inv): <NEW_LINE> <INDENT> value = 0.5 * ((q.T).dot(cov_inv).dot(q) + (p.T).dot(p)) <NEW_LINE> return float(value) | The Hamiltonian function. See Section 5.3.3.1. | 625941d910dbd63aa1bd2e40 |
def __add__(self, vector2): <NEW_LINE> <INDENT> sumX = self._x + vector2._x <NEW_LINE> sumY = self._y + vector2._y <NEW_LINE> return Vector((sumX, sumY)) | Return the Vector that is self + vector2.
Parameters:
self: a Vector object
vector2: another Vector object
Return value: a Vector object representing self + vector2 | 625941d97d43ff24873a2f3f |
def delete_student_all_record(self): <NEW_LINE> <INDENT> stu_id = self.mysql.find_user_id(STUDENT_ACCOUNT)[0][0] <NEW_LINE> self.mysql.delete_student_assessment_overview(stu_id) <NEW_LINE> self.mysql.delete_student_assessment_record(stu_id) <NEW_LINE> self.mysql.delete_student_wrong_record(stu_id) <NEW_LINE> self.mysql... | 删除学生所有会考做题信息 | 625941d9e1aae11d1e749f57 |
def __init__(self): <NEW_LINE> <INDENT> self.info = {} <NEW_LINE> self.mary_list = [] <NEW_LINE> try: <NEW_LINE> <INDENT> self.info = self.deserialize() <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass | Creates the dict and list for Mary's storage.
Also, it tries to deserialize | 625941d999cbb53fe6792e84 |
def generate( libnames, outname, types, functions, header=None, modname=None, existingTypes=None, errorfunc=None, globalVars=None, deepInspect=False, namelessEnums=False, namespaceFilter=None, macroFiles=None, trailer=None ): <NEW_LINE> <INDENT> dwarves = getDwarves( libnames ) <NEW_LINE> if not dwarves: <NEW_LINE> <IN... | External interface to generate code from a set of binaries, into a python
module.
Parameters:
binaries: list of ELF objects to scan for data.
outname: the name of the python file to create
types: Array of PythonType objects to render in the python
functions: Array of function names to generate return and ar... | 625941d98a43f66fc4b54300 |
def begin(self): <NEW_LINE> <INDENT> if self.updater is None: <NEW_LINE> <INDENT> self.updater = updates.Updater() <NEW_LINE> self.updater.start() | Begin updating. | 625941d9b545ff76a89140b3 |
def torule(self): <NEW_LINE> <INDENT> ctx = self.repo[self.node] <NEW_LINE> summary = '' <NEW_LINE> if ctx.description(): <NEW_LINE> <INDENT> summary = ctx.description().splitlines()[0] <NEW_LINE> <DEDENT> line = '%s %s %d %s' % (self.verb, ctx, ctx.rev(), summary) <NEW_LINE> maxlen = self.repo.ui.configint('histedit',... | build a histedit rule line for an action
by default lines are in the form:
<hash> <rev> <summary> | 625941d997e22403b379d239 |
def clean_train_test(train): <NEW_LINE> <INDENT> train["Month"] = train.Date.apply(lambda x: x.month) <NEW_LINE> train["Year"] = train.Date.apply(lambda x: x.year) <NEW_LINE> train["Day"] = train.Date.apply(lambda x: x.day) <NEW_LINE> c2d = ["Id", "Address", "AddressNumberAndStreet", "WnvPresent", "NumMosquitos"] <NEW_... | Clean up the test / training data. | 625941d91f037a2d8b94649b |
def _epoch_step(self, epoch): <NEW_LINE> <INDENT> running_batch_loss = 0 <NEW_LINE> running_metrics = defaultdict(float) <NEW_LINE> for step, batch in enumerate(self.train_data_loader, 1): <NEW_LINE> <INDENT> batch = recursive_to_cuda(batch, self._device) <NEW_LINE> loss, model_output, grad_norm = self._train_on_batch(... | Execute one training epoch. | 625941d9435de62698dfdeeb |
def set_interact_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('--device', default='0', type=str, required=False, help='生成设备') <NEW_LINE> parser.add_argument('--temperature', default=1, type=float, required=False, help='生成的temperature') <NEW_LINE> parser.add_argument('--t... | Sets up the training arguments. | 625941d945492302aab5e564 |
def _get_recurse_directive_depth(field_name, field_directives): <NEW_LINE> <INDENT> recurse_directive = field_directives['recurse'] <NEW_LINE> optional_directive = field_directives.get('optional', None) <NEW_LINE> if optional_directive: <NEW_LINE> <INDENT> raise GraphQLCompilationError(u'Found both @optional and @recur... | Validate and return the depth parameter of the recurse directive. | 625941d94a966d76dd5512af |
def birthdayCakeCandles(candles): <NEW_LINE> <INDENT> return candles.count(sorted(candles, reverse=True)[0]) | Counts how many candles are tallest | 625941d97c178a314d6ef701 |
def is_ignored(self, pathname, info="PATH"): <NEW_LINE> <INDENT> if pathname in settings.ignored_files: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if ':' + pathname in settings.ignored_files: <NEW_LINE> <INDENT> logging.info("IGNORED %s: %s" % (info, pathname)) <NEW_LINE> return True <NEW_LINE> <DEDENT> for pa... | Is a file (or dir or whatever) to be ignored? | 625941d9187af65679ca53bd |
def NameImport(package, as_name=None, prefix=None): <NEW_LINE> <INDENT> if prefix is None: <NEW_LINE> <INDENT> prefix = u"" <NEW_LINE> <DEDENT> children = [Name(u"import", prefix=prefix), package] <NEW_LINE> if as_name is not None: <NEW_LINE> <INDENT> children.extend([Name(u"as", prefix=u" "), Name(as_name, prefix=u" "... | Accepts a package (Name node), name to import it as (string), and
optional prefix and returns a node:
import <package> [as <as_name>] | 625941d991af0d3eaac9bcb9 |
def wheelEvent(self, event): <NEW_LINE> <INDENT> pass | void Plasma.Containment.wheelEvent(QGraphicsSceneWheelEvent event) | 625941d99c8ee82313fbba13 |
def drive_configuration(): <NEW_LINE> <INDENT> block_devices = [] <NEW_LINE> for device in os.listdir('/sys/block'): <NEW_LINE> <INDENT> if os.path.exists('/sys/block/%s/device' % device): <NEW_LINE> <INDENT> with open('/sys/block/%s/size' % device) as dev: <NEW_LINE> <INDENT> sectors = dev.read() <NEW_LINE> <DEDENT> w... | Get drive (block device) names and sizes | 625941d9287bf620b61d3d00 |
@contextmanager <NEW_LINE> def assert_warning(category, msg): <NEW_LINE> <INDENT> with reset_warning_registry(): <NEW_LINE> <INDENT> with warnings.catch_warnings(record=True) as w: <NEW_LINE> <INDENT> warnings.simplefilter("always") <NEW_LINE> yield <NEW_LINE> <DEDENT> <DEDENT> for warn in w: <NEW_LINE> <INDENT> if (is... | Context manager asserting that a warning is issued.
Parameters
----------
category : class
The class of the expected warning.
msg : str
The text of the expected warning.
Raises
------
AssertionError
If the expected warning is not raised. | 625941d95510c4643540f67d |
def set_index_report_qa(transaction): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> qa_score_outcomes = ( json.loads(transaction.last_message)['data'] ['report_qa_score_outcomes']) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> qa_score_outcomes = {} <NEW_LINE> <DEDENT> qa_string = None <NEW_LINE> if len(qa_s... | Migration script. Index the qa score of the transaction
to the 'qa_score' column | 625941d98e7ae83300e4b26b |
def fromHttp(self, comm_rank, comm_size, data, datadir, separator): <NEW_LINE> <INDENT> pass | Load data from http
Different processors load data from one http file according to th hash
of their own id.
Args:
comm_rank: the id of the processor in MPI communication world
comm_size: the size of the MPI communication world
datadir: the dir of input file
separator: the separator of data | 625941d950485f2cf553d039 |
def __init__(self, Equipments=None, *args, **kw_args): <NEW_LINE> <INDENT> self._Equipments = [] <NEW_LINE> self.Equipments = [] if Equipments is None else Equipments <NEW_LINE> super(CoreEquipmentContainer, self).__init__(*args, **kw_args) | Initialises a new 'CoreEquipmentContainer' instance.
@param Equipments: | 625941d992d797404e304429 |
def change_fleet_direction(ai_settings, aliens): <NEW_LINE> <INDENT> for alien in aliens.sprites(): <NEW_LINE> <INDENT> alien.rect.y += ai_settings.fleet_drop_speed <NEW_LINE> <DEDENT> ai_settings.fleet_direction *= -1 | 整体下移并改变方向 | 625941d9b5575c28eb68e2a0 |
def getNameHistory(username): <NEW_LINE> <INDENT> return urlopen("https://api.mojang.com/user/profiles/" + getUUID(username) + "/names") | It returns a JSON tree of all the name changes that are found for the given username
You might want to use something like json.loads(pycraft.getNameHistory(*username that you want*))[*information that you want*] | 625941d9a8ecb033257d336a |
def sort( self, sort_order: list = None, value_order: str = None, suit_order: list = None ) -> None: <NEW_LINE> <INDENT> sort_order = ["value", "suit"] if not sort_order else sort_order <NEW_LINE> suit_order = ( ["clubs", "diamonds", "spades", "hearts", "none"] if not suit_order else suit_order ) <NEW_LINE> value_order... | Sort a collection of Cards.
Sort a collection of Cards in place according to a given sort order.
Defaults to sorting by Card value ascending and Card suit by
clubs, diamonds, spades, and then hearts.
Args:
sort_order: Specify whether to sort by value, suit, or
both. If both are provided, it will perform t... | 625941d931939e2706e4d105 |
def subtest_createWithAllParams(self): <NEW_LINE> <INDENT> POST_request1 = self.createPlaceBookViaAPI() <NEW_LINE> self.assertEqual(POST_request1.status[:3], '200') <NEW_LINE> now = datetime.now().strftime('%d/%m/%Y %H:%M') <NEW_LINE> self.assertEqual(PlaceBook.get(PlaceBook.id == 1).place_id, 1) <NEW_LINE> self.assert... | Test proper creation of a placebook record upon POST request to the API
with all parameters provided. | 625941d9d486a94d0b98e3e5 |
def clone(self): <NEW_LINE> <INDENT> export_obj = Serialisable() <NEW_LINE> for attr in self.__class__.__dict__: <NEW_LINE> <INDENT> if not attr.startswith('_') and not callable(self.__class__.__dict__[attr]): <NEW_LINE> <INDENT> setattr(export_obj, attr, getattr(self, attr)) <NEW_LINE> <DEDENT> <DEDENT> return export_... | Clone itself into the serialisable object.
:return: Serialisable | 625941d9f8510a7c17cf999c |
@logger.wrap <NEW_LINE> def resolve_branches(trunk, branches=None): <NEW_LINE> <INDENT> dead_literals = set() <NEW_LINE> if branches is None: <NEW_LINE> <INDENT> dead_literals, branches = branchset_to_resolve(trunk) <NEW_LINE> <DEDENT> while branches: <NEW_LINE> <INDENT> logger.info('resolving %d branch(es)', len(branc... | Merges given branches back into trunk updating its branchmap and rest
branches. | 625941d982261d6c526ab741 |
def create_app(config_name): <NEW_LINE> <INDENT> app = Flask(__name__) <NEW_LINE> app.config.from_object(config[config_name]) <NEW_LINE> config[config_name].init_app(app) <NEW_LINE> db.init_app(app) <NEW_LINE> bootstrap.init_app(app) <NEW_LINE> moment.init_app(app) <NEW_LINE> pagedown.init_app(app) <NEW_LINE> login_man... | Initialize an application with defined configuration | 625941d9bde94217f368308d |
def read_cmd(self, address, d_width=4, d_length=1, timeout=10): <NEW_LINE> <INDENT> self.microblaze.write(MAILBOX_OFFSET + MAILBOX_PY2IOP_ADDR_OFFSET, address) <NEW_LINE> cmd_word = get_cmd_word(MAILBOX_FUNC, READ_CMD, d_width, d_length) <NEW_LINE> self.microblaze.write(MAILBOX_OFFSET + MAILBOX_PY2IOP_CMD_OFFSET, cmd_w... | Send a read command to the mailbox.
Parameters
----------
address : int
The address tied to Microblaze processor's memory map.
d_width : int
Command data width.
d_length : int
Command burst length (currently only supporting d_length 1).
timeout : int
Time in milliseconds before function exits with warn... | 625941d930bbd722463cc066 |
def get_nav(id, is_site_map=False): <NEW_LINE> <INDENT> keys = [settings.CACHE_PRE_KEY, get_pre_key(is_site_map), str(id)] <NEW_LINE> key = '.'.join(keys) <NEW_LINE> nav = cache.get(key) <NEW_LINE> return nav | Get the nav from the cache. | 625941d94f6381625f114cda |
def empty(self) -> bool: <NEW_LINE> <INDENT> if self.input_stack or self.output_stack: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Returns whether the queue is empty. | 625941d9287bf620b61d3d01 |
def test_transcribe_and_recognizer(self): <NEW_LINE> <INDENT> input_audio_filename = 'harvard.wav' <NEW_LINE> api = speechrecognition.API.GOOGLE <NEW_LINE> expected_output = 'the stale smell of old beer lingers' <NEW_LINE> app = speechrecognition.SpeechApp() <NEW_LINE> audio = app.transcribe_from_file(input_audio_filen... | This function will take a prerecord input from a file and check
it with the expected transcription.
Since we are reading an audio file to transcribe, it makes sense
to test both the functions in the same test case. | 625941d9f7d966606f6aa2a5 |
def get_cache_context(self): <NEW_LINE> <INDENT> with salt.utils.files.fopen(self.cache_path, 'rb') as cache: <NEW_LINE> <INDENT> return self.serial.load(cache) | Retrieve a context cache from disk | 625941d9f7d966606f6aa2a6 |
def include_dir_files(folder): <NEW_LINE> <INDENT> from os import walk <NEW_LINE> files = [] <NEW_LINE> for (dirpath, _, filenames) in walk(folder): <NEW_LINE> <INDENT> for fn in filenames: <NEW_LINE> <INDENT> if os.path.splitext(fn)[1] in {'.h', '.hpp'}: <NEW_LINE> <INDENT> files.append(os.path.join(dirpath, fn)) <NEW... | Find all C++ header files in folder | 625941d994891a1f4081bd49 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.