code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def list_terms( self, fieldname = None, double = False ): <NEW_LINE> <INDENT> prec = [] <NEW_LINE> if fieldname: <NEW_LINE> <INDENT> for field, value in self.reader.all_terms(): <NEW_LINE> <INDENT> if field == fieldname: <NEW_LINE> <INDENT> if value not in prec: <NEW_LINE> <INDENT> prec.append( value ) <NEW_LINE> yiel... | a choosen field indexed terms generator
@param fieldname: the name of the choosen field
@return : indexed terms | 625941d821bff66bcd684bd6 |
def test_numbered_reference_style_link(self): <NEW_LINE> <INDENT> md = ( '\"Click [here][1] for free stuff\"\n\n[1]: https://www.google.com') <NEW_LINE> output = ['\"Click here for free stuff\"\n\n'] <NEW_LINE> metadata = None <NEW_LINE> title = None <NEW_LINE> self.run_test_check_output(md, output) | :throws AssertionError: If test case fail
:returns: nothing
Test that the parser removes html single line comments | 625941d85fcc89381b1e1946 |
def ListLocations(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | A server-to-client streaming RPC.
| 625941d838b623060ff0b072 |
def load_session(self, url): <NEW_LINE> <INDENT> self.gf_regression.load_session(url) <NEW_LINE> self.stats['fonts'] = self.gf_regression.info['fonts'] | Load a previous gf regression session | 625941d863b5f9789fde736b |
def _create_input_transactions(self, addy: Address) -> None: <NEW_LINE> <INDENT> self._transactions.append(ProposedTransaction( address=addy, tag=self.tag, value=-addy.balance, )) <NEW_LINE> for _ in range(addy.security_level - 1): <NEW_LINE> <INDENT> self._transactions.append(ProposedTransaction( address=addy, tag=sel... | Creates transactions for the specified input address.
:param Address addy:
Input address. | 625941d87047854f462a168c |
def stop(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pf = open(self.pid_file, 'r') <NEW_LINE> pid = int(pf.read().strip()) <NEW_LINE> pf.close() <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> pid = None <NEW_LINE> <DEDENT> if not pid: <NEW_LINE> <INDENT> message = "pid_file %s does not exist. Daemon no... | Stop the daemon | 625941d8fff4ab517eb2f6c2 |
def receive_message(request): <NEW_LINE> <INDENT> return request.ws_stream.receive_message() | Receive a WebSocket frame and return its payload as a text in
unicode or a binary in str.
Args:
request: mod_python request.
Raises:
BadOperationException: when client already terminated. | 625941d850485f2cf553d020 |
def get_color_begin (self, x, y, sample_number, bounces): <NEW_LINE> <INDENT> vec = self.viewport.get_vector_from_camera (x, y, sample_number) <NEW_LINE> return self.get_color (self.camera.position, vec, 1, bounces) | Возвращает цвет, видимый из камеры, для пикселя вьюпорта с указанными координатами | 625941d87d43ff24873a2f26 |
def check_fleet_edges(ai_settings, aliens): <NEW_LINE> <INDENT> for alien in aliens.sprites(): <NEW_LINE> <INDENT> if alien.check_edges(): <NEW_LINE> <INDENT> change_fleet_direction(ai_settings, aliens) <NEW_LINE> break | Handles alien fleet direction changes if any alien ship has reached an edge | 625941d8d53ae8145f87a4f1 |
def has_no_diag(coord, placed): <NEW_LINE> <INDENT> i = coord[0] <NEW_LINE> j = coord[1] <NEW_LINE> while i >= 0 and j >= 0: <NEW_LINE> <INDENT> i -= 1 <NEW_LINE> j -= 1 <NEW_LINE> if (i, j) in placed: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> i = coord[0] <NEW_LINE> j = coord[1] <NEW_LINE> while i ... | : has_no_diag - checks if coord contains any queens in a diagonal path
: coord: x, y board coordinate
: placed: tracks placed coordinates in a given permutation challenge
: Return: True if no impeding diagonal queens; False otherwise | 625941d832920d7e50b28457 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, JobErrorDetails): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941d8925a0f43d254a0fe |
def witch_blocking(self,x,y): <NEW_LINE> <INDENT> if not self.level.is_blocking(x+DX[self.witch.direction], y+DY[self.witch.direction]): <NEW_LINE> <INDENT> self.witch.animation = self.witch.move_towards_player() | Checks if the there is something blocking in the direction the witch is moving | 625941d807d97122c4178b15 |
def _CreateTestKey(self, key_path, time_string): <NEW_LINE> <INDENT> filetime = dfwinreg_fake.Filetime() <NEW_LINE> filetime.CopyFromString(time_string) <NEW_LINE> registry_key = dfwinreg_fake.FakeWinRegistryKey( u'MRU', key_path=key_path, last_written_time=filetime.timestamp, offset=1456) <NEW_LINE> value_data = u'acb... | Creates Registry keys and values for testing.
Args:
key_path: the Windows Registry key path.
time_string: string containing the key last written date and time.
Returns:
A Windows Registry key (instance of dfwinreg.WinRegistryKey). | 625941d873bcbd0ca4b2c2fb |
def WriteMiscellaneousCalibrations(self,StringOrList): <NEW_LINE> <INDENT> HDataQ=self._FunctionWrapper(self._WriteMiscellaneousCalibrations,{'StringOrList':StringOrList}); <NEW_LINE> return HDataQ | Wrapped function for the WriteMiscellaneousCalibrations command; socket is automatically opened/closed
...
From the T400B manual:
(nothing listed; see description for ReadMiscellaneousCalibrations) | 625941d8046cf37aa974cfcb |
def detect_changes(transforms, stage_configs): <NEW_LINE> <INDENT> cached_stages = [False for transform in transforms] <NEW_LINE> for index, (transform, stage_config) in enumerate(zip(transforms, stage_configs)): <NEW_LINE> <INDENT> stage_hash = stage_config.get('sha1', None) <NEW_LINE> if not stage_hash: <NEW_LINE> <I... | Check preceeding stages have not changed AND files match hashes, including parameter files | 625941d85e10d32532c5f1ac |
def get_volume_type(self, volume_id): <NEW_LINE> <INDENT> url = "types/%s" % str(volume_id) <NEW_LINE> resp, body = self.get(url) <NEW_LINE> body = json.loads(body) <NEW_LINE> return resp, body['volume_type'] | Returns the details of a single volume_type. | 625941d815baa723493c41fc |
def SM_addToNZDownCols(*args, **kwargs): <NEW_LINE> <INDENT> return _math.SM_addToNZDownCols(*args, **kwargs) | SM_addToNZDownCols(A, py_x, min_floor=0) | 625941d845492302aab5e54b |
def test_xfs_set_label(self): <NEW_LINE> <INDENT> succ = BlockDev.fs_xfs_mkfs(self.loop_dev, None) <NEW_LINE> self.assertTrue(succ) <NEW_LINE> with mounted(self.loop_dev, self.mount_dir): <NEW_LINE> <INDENT> fi = BlockDev.fs_xfs_get_info(self.loop_dev) <NEW_LINE> <DEDENT> self.assertTrue(fi) <NEW_LINE> self.assertEqual... | Verify that it is possible to set label of an xfs file system | 625941d824f1403a92600dea |
def chargeAtTurn(self, n): <NEW_LINE> <INDENT> damage = self.defaultChargeAtTurn(self.turn) - self.toughness <NEW_LINE> val = self.defaultChargeAtTurn(n) - damage <NEW_LINE> return val | The actual charge of this unit when it has n turns to go.
This takes into account any damage or bonuses that this unit has
received so far. | 625941d8de87d2750b86001a |
def get_api(credsfile = DEFAULT_TWITTER_CREDS_PATH): <NEW_LINE> <INDENT> fn = os.path.expanduser(credsfile) <NEW_LINE> c = json.load(open(fn)) <NEW_LINE> auth = tweepy.OAuthHandler(consumer_key = c['consumer_key'], consumer_secret = c['consumer_secret']) <NEW_LINE> auth.set_access_token(c['access_token'], c['access_tok... | Takes care of the Twitter OAuth authentication process and
creates an API-handler to execute commands on Twitter
Arguments:
- credsfile (str): the full path of the filename that contains a JSON
file with credentials for Twitter
Returns:
A tweepy.api.API object | 625941d863f4b57ef0001399 |
def train(self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100, batch_size=200, verbose=False): <NEW_LINE> <INDENT> num_train, dim = X.shape <NEW_LINE> num_classes = np.max(y) + 1 <NEW_LINE> if self.W is None: <NEW_LINE> <INDENT> self.W = 0.001 * np.random.randn(dim, num_classes) <NEW_LINE> <DEDENT> loss_history = [... | Train this linear classifier using stochastic gradient descent.
Inputs:
- X: A numpy array of shape (N, D) containing training data; there are N
training samples each of dimension D.
- y: A numpy array of shape (N,) containing training labels; y[i] = c
means that X[i] has label 0 <= c < C for C classes.
- learning... | 625941d8ad47b63b2c50a203 |
def register(self, model_or_iterable, admin_class=None, **options): <NEW_LINE> <INDENT> if isinstance(model_or_iterable, ModelBase) and not admin_class: <NEW_LINE> <INDENT> admin_class = ModelAdmin <NEW_LINE> <DEDENT> if isinstance(model_or_iterable, TopLevelDocumentMetaclass) and not admin_class: <NEW_LINE> <INDENT> a... | Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class.
If a model is alre... | 625941d8d486a94d0b98e3cc |
def get_favorite_number(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename) as f_obj: <NEW_LINE> <INDENT> number = json.load(f_obj) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return number | Get stored number if available. | 625941d821a7993f00bc7f79 |
def calc_score(M, current_pos, next_pos, goal): <NEW_LINE> <INDENT> return distance(M, current_pos, next_pos) + distance(M, next_pos, goal) | Score is calculated as sum of these:
* Distance between current_pos and next_pos
* Distance between next_pos and goal as a heuristic estimation of the next_pos | 625941d823e79379d52ee7e7 |
@jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") <NEW_LINE> @merge(buildCoverageStats, "coverage_stats.load") <NEW_LINE> def loadCoverageStats(infiles, outfile): <NEW_LINE> <INDENT> PipelineMappingQC.loadPicardCoverageStats(infiles, outfile) | Import coverage statistics into SQLite | 625941d826238365f5f0f0f7 |
def print_nodes(node,depth,max_depth,num): <NEW_LINE> <INDENT> name = node.GetName() <NEW_LINE> mat = node.GetMatrix() <NEW_LINE> pos = mat.GetTranslation() <NEW_LINE> space=" "*depth <NEW_LINE> print("{:3d} - ".format(num)+space+"{:25s} [{:5.2f},{:5.2f},{:5.2f}]".format(name,pos[0],pos[1],pos[2])) <NEW_LINE> if de... | Print the current node, then find all the nodes in the tree below and recurse. | 625941d80a366e3fb873eaa1 |
def format(self, fmt): <NEW_LINE> <INDENT> val = '' <NEW_LINE> for x in fmt: <NEW_LINE> <INDENT> if x == 'd': <NEW_LINE> <INDENT> val += self._driv <NEW_LINE> <DEDENT> elif x == 'p': <NEW_LINE> <INDENT> val += self._path <NEW_LINE> <DEDENT> elif x == 'n': <NEW_LINE> <INDENT> val += self._name <NEW_LINE> <DEDENT> elif x... | Returns string representing the items specified in the format string
The format string can contain:
.. code::
d - drive letter
p - path
n - name
x - extension
z - file size
t - file time in seconds
And, you can string them together, e.g. `dpnx` returns the fully
qualified name.
On platform... | 625941d816aa5153ce3626fd |
def fill_pn_tables(self, pn_conn): <NEW_LINE> <INDENT> pn_cursor = pn_conn.cursor() <NEW_LINE> for ix in range(len(self.mkt_data)): <NEW_LINE> <INDENT> self.get_billing_contact(pn_cursor, ix) <NEW_LINE> self.get_technical_contact(pn_cursor, ix) <NEW_LINE> self.get_addons_key(pn_cursor, ix) <NEW_LINE> self.get_partner_d... | Call functions to load data into each Postgre table.
The pn_contacts, pn_addons, and pn_partner_details tables
must be loaded first as their UUIDs are needed to load data
into other tables.
:param pn_conn:
:return: None
Called by: store_licenses() | 625941d885dfad0860c3b0e1 |
def trainFromCheci(self): <NEW_LINE> <INDENT> if self._virtual: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.graph.trainFromCheci(self._checi,full_only=True) | 导入车次时调用。仅按照车次,在运行图中查找Train对象。如果找不到,返回None。 | 625941d8d8ef3951e32437c3 |
def has_open_vacancy(self): <NEW_LINE> <INDENT> return self.get_assignments(running=True).count() < self.get_type().get_max_slaves() | Returns if there are free working places. | 625941d8462c4b4f79d1d955 |
def betterEvaluationFunction(currentGameState): <NEW_LINE> <INDENT> foodPos = currentGameState.getFood().asList() <NEW_LINE> current = list(currentGameState.getPacmanPosition()) <NEW_LINE> foodDist = [-manhattanDistance(pos, current) for pos in foodPos] <NEW_LINE> if len(foodDist) == 0: <NEW_LINE> <INDENT> foodDist.app... | Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
evaluation function (question 5).
DESCRIPTION: <write something here so we know what you did> | 625941d867a9b606de4a813e |
def main(working_dir, output, details, nodes_dmp: File, names_dmp: File, gi_taxid_nucl_fp: File) -> TaxIDData: <NEW_LINE> <INDENT> tax_id_data, = output <NEW_LINE> tax_id_data.tax_id_data = taxidtool.build_taxid_data(nodes_dmp, names_dmp, gi_taxid_nucl_fp) <NEW_LINE> return output | Description
Detailed Description
Parameters
----------
Returns
------- | 625941d85510c4643540f665 |
def test_add_botanical_name_renders_page(self, app, db): <NEW_LINE> <INDENT> cn = CommonName(name='Foxglove') <NEW_LINE> db.session.add(cn) <NEW_LINE> db.session.commit() <NEW_LINE> with app.test_client() as tc: <NEW_LINE> <INDENT> rv = tc.get(url_for('seeds.add_botanical_name', cn_id=cn.id), follow_redirects=True) <NE... | Load form page given a valid cn_id. | 625941d82eb69b55b151cb37 |
def save_score(self, score): <NEW_LINE> <INDENT> print(score, self.maxscore) <NEW_LINE> if int(score) >= int(self.maxscore): <NEW_LINE> <INDENT> self.write_maxscore(str(score)) | Saves the score if it's greater than the previous maxscore | 625941d807f4c71912b11709 |
def _partition(total: int, divisor: int) -> tuple[tuple[int, ...], tuple[int, ...]]: <NEW_LINE> <INDENT> multiples = (divisor,) * (total // divisor) <NEW_LINE> remainder = (total % divisor,) if total % divisor else () <NEW_LINE> return multiples, remainder | Given a total and a divisor, return two tuples: A tuple containing `divisor`
repeated the number of times it divides `total`, and length-1 or empty tuple
containing the remainder when `total` is divided by `divisor`. If `divisor` factors
`total`, i.e. if the remainder is 0, then `remainder` is empty. | 625941d81b99ca400220ad37 |
def in_line(first, second, third): <NEW_LINE> <INDENT> vector_1 = [second[0] - first[0], second[1] - first[1]] <NEW_LINE> vector_2 = [third[0] - first[0], third[1] - first[1]] <NEW_LINE> return vector_1[0] * vector_2[1] == vector_1[1] * vector_2[0] | Return whether the third point is on line defined by 2 points. | 625941d80383005118ecf867 |
def data (self, lump, n = None, dtype = None, offset = None, type = None, **kwargs): <NEW_LINE> <INDENT> boffset, flags = self._lumpmetadata.get(lump, (0, 0)) <NEW_LINE> if dtype == None: <NEW_LINE> <INDENT> dtype = dt.get (lump, None) <NEW_LINE> <DEDENT> if offset == None: <NEW_LINE> <INDENT> offset = 0 <NEW_LINE> <DE... | Create a memmap-like object pointing at a given kind of lump | 625941d873bcbd0ca4b2c2fc |
def AccountsUrl(command): <NEW_LINE> <INDENT> return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command) | Generates the Google Accounts URL.
Args:
command: The command to execute.
Returns:
A URL for the given command. | 625941d87cff6e4e81117c0b |
def test_nonint_str(): <NEW_LINE> <INDENT> given, expected = 'x.y.z', wcwidth.list_versions()[-1] <NEW_LINE> warnings.resetwarnings() <NEW_LINE> wcwidth._wcmatch_version.cache_clear() <NEW_LINE> with pytest.warns(UserWarning): <NEW_LINE> <INDENT> result = wcwidth._wcmatch_version(given) <NEW_LINE> <DEDENT> assert resul... | wcwidth._wcmatch_version(u'x.y.z') returns latest (str). | 625941d807f4c71912b1170a |
def __init__(self): <NEW_LINE> <INDENT> this = _mc.new_WindowEvent() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this | __init__(self) -> WindowEvent
1 | 625941d829b78933be1e592e |
def zeros(*args, **kwargs): <NEW_LINE> <INDENT> if len(args) == 1: <NEW_LINE> <INDENT> m = n = args[0] <NEW_LINE> <DEDENT> elif len(args) == 2: <NEW_LINE> <INDENT> m = args[0] <NEW_LINE> n = args[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('zeros expected at most 2 arguments, got %i' % len(args)) <... | Create matrix m x n filled with zeros.
One given dimension will create square matrix n x n.
Example:
>>> from sympy.mpmath import zeros
>>> zeros(2)
matrix(
[['0.0', '0.0'],
['0.0', '0.0']]) | 625941d8460517430c394406 |
def email_url(user_id): <NEW_LINE> <INDENT> return reverse('user:user-email', args=[user_id]) | Return user email URL | 625941d857b8e32f52483722 |
def from_json_to_another_file(): <NEW_LINE> <INDENT> with open('matrix.json') as matrix: <NEW_LINE> <INDENT> with open('even_to_zero.txt', 'w') as file: <NEW_LINE> <INDENT> extract = json.load(matrix) <NEW_LINE> for k, v in extract.items(): <NEW_LINE> <INDENT> for i, num in enumerate(v): <NEW_LINE> <INDENT> if not num ... | Function reads json file - zeroes even numbers of the matrix
and saves it to another file | 625941d87d43ff24873a2f27 |
def _BigUnion(list_of_sets): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for s in list_of_sets: <NEW_LINE> <INDENT> result.extend(list(s)) <NEW_LINE> <DEDENT> return set(result) | Return the set that is the union of the sets or lists in list_of_sets. | 625941d815baa723493c41fd |
def __init__(self): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.daemon = True <NEW_LINE> self.ramp_up = True <NEW_LINE> self.shutdown_lock = Lock() <NEW_LINE> self.should_shutdown = False <NEW_LINE> pid_list = psutil.get_pid_list() <NEW_LINE> self.processes = {} <NEW_LINE> self.processes_info = None <NEW_... | Singletone: Don't call directly. Use get_instance() | 625941d897e22403b379d221 |
def create_feature_importance_dict(df, model): <NEW_LINE> <INDENT> feature_importances_dict = {} <NEW_LINE> feature_importances_prelim = zip(range(df.shape[1]), sorted(zip(df.columns, model.feature_importances_), key = lambda x: x[1], reverse = True ) ) <NEW_LINE> feature_importances_list = [(str(x[1][0]), x[0] + 1, x[... | Accepts a dataframe which is used to extract the feature names (tokenized text features) and a model
which is used to extract the feature_importances. Combines the two to form a list of feature importances
with feature names ranked by the feature importance. Then uses this list to generate a dictionary of the feature | 625941d83539df3088e2e5d1 |
def clearSessionTime(datas): <NEW_LINE> <INDENT> db = DBHelper.DB() <NEW_LINE> result = db.update('update _questionnaire_q_user_info set sessionTime=NULL,modifyTime=now() where {}="{}"' .format(datas['attr'], datas['id'])) <NEW_LINE> return result | 清理sessionTime | 625941d8c4546d3d9de72cbb |
def save_pickle(path, data): <NEW_LINE> <INDENT> with open(path, "wb") as f: <NEW_LINE> <INDENT> pickle.dump(data, f) <NEW_LINE> <DEDENT> print("File saved at ", path) | pickles the tokens dict
:param path: paths to save at
:param data: data to pickle (can be dataframe, model ...) | 625941d8796e427e537b084d |
def _validate(self, sam_template, parameter_values): <NEW_LINE> <INDENT> if parameter_values is None: <NEW_LINE> <INDENT> raise ValueError("`parameter_values` argument is required") <NEW_LINE> <DEDENT> if "Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) or not sam_template["Resources"]... | Validates the template and parameter values and raises exceptions if there's an issue
:param dict sam_template: SAM template
:param dict parameter_values: Dictionary of parameter values provided by the user | 625941d8293b9510aa2c351a |
@pytest.mark.parametrize( ["syndication_format"], [pytest.param("atom"), pytest.param("rss")] ) <NEW_LINE> @pytest.mark.parametrize( ["pretty", "check_fn"], [ pytest.param(False, lambda x: x == 2, id="no"), pytest.param(True, lambda x: x > 10, id="yes"), ], ) <NEW_LINE> def test_args_pretty(testapp, syndication_format,... | Feed processor has to respect pretty argument. | 625941d8ab23a570cc25040a |
def parse_query(query_dict, schema, database): <NEW_LINE> <INDENT> if query_dict is None: <NEW_LINE> <INDENT> return xapian.Query('') <NEW_LINE> <DEDENT> elif query_dict == {}: <NEW_LINE> <INDENT> return xapian.Query() <NEW_LINE> <DEDENT> query_tree = build_query_tree(query_dict) <NEW_LINE> return query_tree.to_query(s... | Given a `query_dict`, will attempt to return a xapian.Query
Required arguments:
``query_dict`` -- A query dict similar to MongoDB style to parse
Returns a xapian.Query
Operator Reference:
Comparison:
equal, key = value, { key:value }
$lt, $gt, the field less or more than the specified value, { field... | 625941d84d74a7450ccd4449 |
@apply_defaults(service=default_service) <NEW_LINE> def create_label(label_name: str, service=None)->dict: <NEW_LINE> <INDENT> logger.info('creating label') <NEW_LINE> label = service.users().labels().create( userId='me', body={ 'messageListVisibility': 'show', 'name': label_name, 'labelListVisibility': 'labelShow'}).e... | Create a label with the specified name in the user's inbox
Args:
label_name(str): Name of the label to create
service (optional, gmail-api-service): the service to use. Default:
the result of `default_service()`
Returns:
dict containing the id and name of the created label | 625941d882261d6c526ab728 |
def cartesian_product(a, b): <NEW_LINE> <INDENT> return np.vstack([np.repeat(a, len(b)), np.tile(b, len(a))]).T | >>> assert (
... cartesian_product([1,2,3], ['a', 'b']) ==
... np.array([['1', 'a'],
... ['1', 'b'],
... ['2', 'a'],
... ['2', 'b'],
... ['3', 'a'],
... ['3', 'b']],
... dtype='<U21')
... ).all() | 625941d891f36d47f21ac77b |
def subplot(*args, **kwargs): <NEW_LINE> <INDENT> if len(args)==0: <NEW_LINE> <INDENT> args=(1,1,1) <NEW_LINE> <DEDENT> if len(args) >= 3 and isinstance(args[2], bool) : <NEW_LINE> <INDENT> warnings.warn("The subplot index argument to subplot() appears" " to be a boolean. Did you intend to use subplots()?") <NEW_LINE> ... | Return a subplot axes positioned by the given grid definition.
Typical call signature::
subplot(nrows, ncols, plot_number)
Where *nrows* and *ncols* are used to notionally split the figure
into ``nrows * ncols`` sub-axes, and *plot_number* is used to identify
the particular subplot that this function is to create ... | 625941d81f037a2d8b946484 |
def _checkCompatibility(self, problem, algo): <NEW_LINE> <INDENT> for space in ('state', 'action'): <NEW_LINE> <INDENT> if problem.DOMAIN[space] == Spaces.Continuous: <NEW_LINE> <INDENT> if algo.DOMAIN[space] == Spaces.Discrete: <NEW_LINE> <INDENT> raise AgentException( "Incompatible %s space: %s algorithms cannot solv... | Make sure the algo can solve the given problem.
This simply validate domains compatibility. Continuous domain
algorithms can solve discrete problems, but discrete domain
algorithms cannot solve continuout problems. | 625941d8adb09d7d5db6ca14 |
def make_temp_model(): <NEW_LINE> <INDENT> s = RDF.MemoryStorage() <NEW_LINE> m = RDF.Model(s) <NEW_LINE> return m | Make a scratch model
| 625941d85fdd1c0f98dc04ba |
def removeConsumers(self,*consumers): <NEW_LINE> <INDENT> for consumer in consumers: <NEW_LINE> <INDENT> if not isinstance(consumer,Cmd): <NEW_LINE> <INDENT> raise ValidationError('CommandHandler.removeConsumers only accepts Cmds') <NEW_LINE> <DEDENT> name = consumer.verb <NEW_LINE> if name not in self.consumers: <NEW_... | Remove a list of consumer Cmds. | 625941d87c178a314d6ef6e9 |
def markov_plot(tmat,scale=1000): <NEW_LINE> <INDENT> ss = getss(tmat) <NEW_LINE> sz_array = ss <NEW_LINE> Tg = mat2DiGraph(tmat) <NEW_LINE> pos=nx.circular_layout(Tg) <NEW_LINE> nx.draw(Tg, pos, arrows=True,node_size=scale*sz_array) | Take a stochastic matrix as input and make a weighted
plot. The size of each node is proprotional to its
population at steady state
tmat : array
A stochastic matrix
scale : int
The amount to scale the node size | 625941d84428ac0f6e5baa7a |
def transform_setting(self, setting): <NEW_LINE> <INDENT> return setting.lower() | Transform the display text for setting to the form it is stored in.
By default, returns a lowercased copy of setting. | 625941d8442bda511e8be69b |
def as_integer_check_division(value_a, value_b, absolute=True, rtol=1.e-5, atol=1.e-8): <NEW_LINE> <INDENT> return as_integer_check(value_a/value_b, absolute=absolute, rtol=rtol, atol=atol) | This function ...
:param value_a:
:param value_b:
:param absolute:
:param rtol:
:param atol:
:return: | 625941d8ac7a0e7691ed434e |
def GetServoPosition4(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> i2cRecv = self.RawRead(COMMAND_GET_PWM4, I2C_MAX_LEN) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> pwmDuty = (i2cRecv[1] << 8) + i2cRecv[2] <NEW_LINE> powerOut = (float(pwmDuty) - self.PWM_MIN_4) / (... | position = GetServoPosition4()
Gets the drive position for servo output #4
0 is central, -1 is maximum left, +1 is maximum right
e.g.
0 -> Central
0.5 -> 50% to the right
1 -> 100% to the right
-0.75 -> 75% to the left
| 625941d89c8ee82313fbb9fb |
def subplots_adjust(self, *args): <NEW_LINE> <INDENT> dimThing = args[0] if args else self.fig.get_window_extent() <NEW_LINE> fWidth, fHeight = [getattr(dimThing, x) for x in ('width', 'height')] <NEW_LINE> self.adj.updateFigSize(fWidth, fHeight) <NEW_LINE> if self._figTitle: <NEW_LINE> <INDENT> kw = { 'm': 10, 'fontsi... | Adjusts spacings. | 625941d8e1aae11d1e749f3f |
def test_specimentype_column_sort(self): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> driver.get(config.TEST_URL + "/gxd") <NEW_LINE> genebox = driver.find_element_by_name('nomenclature') <NEW_LINE> genebox.send_keys("hoxa13") <NEW_LINE> genebox.send_keys(Keys.RETURN) <NEW_LINE> imagetab = driver.find_element_by... | @status: Tests that the specimen type column sort works correctly
The order for the specimen type sort is the order in the EI menu:
*whole mount
*section
*section from whole mount
*optical section
*not specified
*blots
Reverse would be specified as:
*optical section
*section from whole mount
*section
*whole mount
*not... | 625941d8f8510a7c17cf9983 |
def init(self, id): <NEW_LINE> <INDENT> reserve = to_millis(TimeUnit.HOUR) << (FlakeIdGenerator._BITS_NODE_ID + FlakeIdGenerator._BITS_SEQUENCE) <NEW_LINE> return self.new_id().continue_with(lambda f: f.result() >= (id + reserve)) | This method does nothing and will simply tell if the next ID
will be larger than the given ID.
You don't need to call this method on cluster restart - uniqueness is preserved thanks to the
timestamp component of the ID.
This method exists to make :class:`~hazelcast.proxy.FlakeIdGenerator` drop-in replacement
for the de... | 625941d8498bea3a759b9d35 |
def reset(self, val, vartype='', **kwargs): <NEW_LINE> <INDENT> force_dirty = kwargs.get('force_dirty', False) <NEW_LINE> from_input = kwargs.get('from_input') <NEW_LINE> if from_input is not None: <NEW_LINE> <INDENT> self.from_input = from_input <NEW_LINE> <DEDENT> if vartype == 'STRING' or (vartype is None and self.v... | :param val:
:param vartype:
:param kwargs:
force_dirty, defaults to False
from_input, defaults to None
:return: | 625941d85fc7496912cc3c04 |
def setup_build_environment(self, env): <NEW_LINE> <INDENT> legacy_fn = self._get_legacy_environment_method('setup_environment') <NEW_LINE> if legacy_fn: <NEW_LINE> <INDENT> _ = spack.util.environment.EnvironmentModifications() <NEW_LINE> legacy_fn(env, _) | Sets up the build environment for a package.
This method will be called before the current package prefix exists in
Spack's store.
Args:
env (spack.util.environment.EnvironmentModifications): environment
modifications to be applied when the package is built. Package authors
can call methods on it ... | 625941d84c3428357757c5ad |
def smoosh_morse1(alpha_str: str): <NEW_LINE> <INDENT> smorse = '' <NEW_LINE> alpha_list = [] <NEW_LINE> if alpha_str.isalpha(): <NEW_LINE> <INDENT> alpha_list = alpha_list + list(alpha_str.upper()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> morse_dict = dict(zip(ALPHABET.split(s... | Convert a text string into a concatenation of morse code.
:param alpha_str: string of alpha characters
:return smorse: string of dashes and dots | 625941d8be8e80087fb20ec6 |
def pickleFile(func_name, hash_val): <NEW_LINE> <INDENT> return ".pyRecall/"+func_name+"_"+hash_val+".p" | Return string with path and file name of the pickle | 625941d8004d5f362079a5b9 |
def judge(BOLL, short_RSI, long_RSI, start_index): <NEW_LINE> <INDENT> condition_1 = judge_condition_1(BOLL, short_RSI, long_RSI, start_index) <NEW_LINE> condition_2 = judge_condition_2(short_RSI, long_RSI, start_index) <NEW_LINE> condition_3 = judge_condition_3(BOLL, start_index) <NEW_LINE> condition_4 = judge_conditi... | judge whether any condition is satisfied, give 'buy' / 'sell' / 'warning' signals
condition_1: short_RSI在50以下,上穿long_RSI,形成金叉,有价格在BOLL_middle上方,买入信号
condition_2: short_RSI下穿70,下穿long_RSI形成死叉,卖出信号
condition_3: 价格下穿BOLL中轨,卖出信号
condition_4: 价格下穿BOLL上轨,卖出警告
Args:
RSI: RSI, type=pandas.Dataframe, ['id',... | 625941d8b57a9660fec33b0e |
def __init__(self, in_channels, kernel_size, r=2, d=8, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.conv = BlockConv(in_channels * (r ** 2) * d, in_channels, kernel_size, **kwargs) <NEW_LINE> self.pack = partial(packing, r=r) <NEW_LINE> self.conv3d = nn.Conv3d(1, d, kernel_size=(3, 3, 3), stride=(1... | Initializes a PackLayerConv3d object.
Parameters
----------
in_channels : int
Number of input channels
kernel_size : int
Kernel size
r : int
Packing ratio
d : int
Number of 3D features | 625941d86fb2d068a760f327 |
def vectorize_rap(self, path, rhyming_endings, num_lines): <NEW_LINE> <INDENT> vectorized_rap_data = [] <NEW_LINE> artist_lyrics = self.get_artist_lyrics(path) <NEW_LINE> first_line_index = np.random.choice(len(artist_lyrics) - 1) <NEW_LINE> first_lines = artist_lyrics[first_line_index:first_line_index+10] <NEW_LINE> s... | The final function that translates lyrics into numbers, which the neural network will understand and use to predict.
@param model: The neural network model that we will use to predict lyrics for the rap
@param path: A file path containing the artist's real lyrics
@param rhyme_endings: A list created from get_rhymi... | 625941d8ec188e330fd5aa21 |
def colour_field(self, field): <NEW_LINE> <INDENT> red = 0 <NEW_LINE> green = 0 <NEW_LINE> blue = 0 <NEW_LINE> field_surface = pygame.Surface( (self.field_size, self.field_size) ) <NEW_LINE> if field.is_home: <NEW_LINE> <INDENT> green = 255 <NEW_LINE> <DEDENT> if field.food > 0: <NEW_LINE> <INDENT> red = 255 <NEW_LINE>... | calculate colour of field from ant count, food and blocked attribute
| 625941d8d8ef3951e32437c4 |
def test_set_name(self): <NEW_LINE> <INDENT> self.model.set_player("Bob Smith") <NEW_LINE> self.assertEqual("Bob Smith", self.model.players[0]) | Tests if a player's name is set. | 625941d885dfad0860c3b0e2 |
def render_to_response(self, context, **response_kwargs): <NEW_LINE> <INDENT> return super().render_to_response(context, **response_kwargs) | In design, adds to the view counter before rendering the page. We do this as late as possible to try to prevent adding to the view counter in the event of errors
In practice this has been buggy. Possibly flag this for depreciation | 625941d815fb5d323cde0d99 |
def list_by_account( self, resource_group_name, account_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/provi... | Lists the Data Lake Store trusted identity providers within the
specified Data Lake Store account.
:param resource_group_name: The name of the Azure resource group.
:type resource_group_name: str
:param account_name: The name of the Data Lake Store account.
:type account_name: str
:param dict custom_headers: headers t... | 625941d8796e427e537b084e |
def exec(self): <NEW_LINE> <INDENT> error = self.arg('error_description') <NEW_LINE> if error: <NEW_LINE> <INDENT> _router.session().add_error_message(error) <NEW_LINE> <DEDENT> auth_session = _AuthSession(self.arg('state')) <NEW_LINE> return self.redirect(_router.url(auth_session.redirect_uri, query=self.args)) | Authorization.
| 625941d8a219f33f34628bed |
def isWithin(scope): <NEW_LINE> <INDENT> pass | Return True if this context is within the given scope. | 625941d8d268445f265b50f5 |
def layer_column_density(p_min, p_max, nlev=10): <NEW_LINE> <INDENT> levels = 10**np.linspace(np.log10(p_max), np.log10(p_min), nlev) <NEW_LINE> n = density_at_pressure(levels) <NEW_LINE> z = altitude_at_pressure(levels) <NEW_LINE> n_int = np.trapz(n,z) <NEW_LINE> return n_int | Sub-divide atmopheric layer into n discrete levels
space uniformly in log-pressure and integrate number density. | 625941d8d6c5a102081442d3 |
def run_python_code(self, code): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output = eval( code, {"__builtins__": None}, { "tello": self.tello.thing, "connect": self.tello.connect, "disconnect": self.tello.disconnect, "list": self.tello.list, }) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> output = ... | 此处定义了与外部系统(诸如Scratch)沟通的有效消息
list: Scratch 发现设备
connect: scratch 建立连接
disconnect: scratch 断开连接
tello: 可调用的对象,一般被scratch具体功能积木调用,消息是传递面向对象风格的Python代码,如 tello.takeoff() | 625941d876d4e153a657edb9 |
def solve_toeplitz(c_or_cr, b, check_finite=True): <NEW_LINE> <INDENT> if isinstance(c_or_cr, tuple): <NEW_LINE> <INDENT> c, r = c_or_cr <NEW_LINE> c = _asarray_validated(c, check_finite=check_finite).ravel() <NEW_LINE> r = _asarray_validated(r, check_finite=check_finite).ravel() <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | Solve a Toeplitz system using Levinson Recursion
The Toeplitz matrix has constant diagonals, with c as its first column
and r as its first row. If r is not given, ``r == conjugate(c)`` is
assumed.
Parameters
----------
c_or_cr : array_like or tuple of (array_like, array_like)
The vector ``c``, or a tuple of arra... | 625941d84c3428357757c5ae |
def test(filename=None, seed=None, options='', mod_loc=None): <NEW_LINE> <INDENT> if mod_loc is None: <NEW_LINE> <INDENT> mod_loc = os.path.dirname(__file__) <NEW_LINE> <DEDENT> if filename is None: <NEW_LINE> <INDENT> loc = mod_loc <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loc = os.path.join(mod_loc, os.path.basen... | Run tests.
filename -- only run tests in filename. If not set run all tests.
You do not need the full path, the relative path within the
test directory is enough.
seed -- set random seed
options -- options to be passed to py.test (as a string)
mod_loc -- don't use it, it's for internal... | 625941d86e29344779a62897 |
def _getLanguage(self, code): <NEW_LINE> <INDENT> languageset = getUtility(ILanguageSet) <NEW_LINE> return languageset.getLanguageByCode(code) | Convenience shortcut: find a language given its code. | 625941d856ac1b37e6264453 |
def from_cert(certificate, observations=[]): <NEW_LINE> <INDENT> proto = certificate_pb2.X509Description() <NEW_LINE> proto.der = certificate.to_der() <NEW_LINE> try: <NEW_LINE> <INDENT> for sub in [(type_.short_name, to_unicode('.'.join(process_name(value.human_readable())))) for type_, value in certificate.subject()]... | Pulls out interesting fields from certificate, so format of data will
be similar in every database implementation. | 625941d83d592f4c4ed1d2f0 |
def invalidate_cache(self, path=None): <NEW_LINE> <INDENT> pass | Discard any cached directory information
Parameters
----------
path: string or None
If None, clear all listings cached else listings at or under given
path. | 625941d863f4b57ef000139a |
def open_file_browser(self): <NEW_LINE> <INDENT> directory_path = self.data.get_last_selected_directory() <NEW_LINE> file_path = QtGui.QFileDialog.getOpenFileName(self, 'Select Video', directory_path)[0] <NEW_LINE> if file_path: <NEW_LINE> <INDENT> self.data.add_to_recent_files(file_path) <NEW_LINE> self.data.set_last_... | The file browser is opened and the video is played accordingly.
The file browser is opened, the user selection is fetched and the
video is loaded and played in the player. | 625941d8cad5886f8bd27260 |
def v2_playbook_on_stats(self, stats): <NEW_LINE> <INDENT> hosts = sorted(stats.processed.keys()) <NEW_LINE> summary = {} <NEW_LINE> for h in hosts: <NEW_LINE> <INDENT> s = stats.summarize(h) <NEW_LINE> summary[h] = s <NEW_LINE> <DEDENT> custom_stats = {} <NEW_LINE> if self.get_option('show_custom_stats') and stats.cus... | Display info about playbook statistics | 625941d85fcc89381b1e1948 |
def test_number_conserving_dense_fermionic_P_matrix(self): <NEW_LINE> <INDENT> P = compute_P(self.state, self.L, self.N, is_fermionic=True) <NEW_LINE> self.assertAlmostEqual(P[0, 0], 95) <NEW_LINE> self.assertAlmostEqual(P[1, 1], 126) <NEW_LINE> self.assertAlmostEqual(P[2, 2], 155) <NEW_LINE> self.assertAlmostEqual(P[4... | Test several chosen values in a fermionic density matrix.
The matrix is build using the dense representation of the
c^dagger_i*c_j operator. | 625941d838b623060ff0b074 |
def kml2pykml(): <NEW_LINE> <INDENT> from .util import open_pykml_uri <NEW_LINE> parser = OptionParser( usage='usage: %prog FILENAME_or_URL', version=f'%prog {pykml_version}', ) <NEW_LINE> (options, args) = parser.parse_args() <NEW_LINE> if len(args) != 1: <NEW_LINE> <INDENT> parser.error('wrong number of arguments') <... | Parses a KML file and generates a pyKML script | 625941d8be383301e01b570a |
def channel_publish(topic, content): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> async_to_sync(channel_layer.group_send)( 'chat_%s' % topic, { 'type': 'chat.message', 'message': content, } ) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass | type需要与consumer中的receive中一致
group_name是consumer中的room_group_name | 625941d84e696a04525c96d3 |
def get_text(self): <NEW_LINE> <INDENT> text = self.text.replace(self.bottom.text,'').strip() <NEW_LINE> text = text.replace(self.get_progress_text(),'').strip() <NEW_LINE> return text | It returns achivement text ( see detail in http://clip2net.com/s/6u4O0f )
excluding bottom_text and progress_icon_text | 625941d80fa83653e4657241 |
def removeBoxes_1(self, boxes): <NEW_LINE> <INDENT> l = len(boxes) <NEW_LINE> dp = [[[0] * l for _ in range(l)] for _ in range(l)] <NEW_LINE> def dfs(left, right, end_num): <NEW_LINE> <INDENT> if left > right: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if dp[left][right][end_num] == 0: <NEW_LINE> <INDENT> start =... | :type boxes: List[int]
:rtype: int
645MS | 625941d8bf627c535bc13456 |
def serialize_metadata(self, item, key, excluded=None, **context): <NEW_LINE> <INDENT> dataset_assoc = item <NEW_LINE> excluded = [] if excluded is None else excluded <NEW_LINE> metadata = {} <NEW_LINE> for name, spec in dataset_assoc.metadata.spec.items(): <NEW_LINE> <INDENT> if name in excluded: <NEW_LINE> <INDENT> c... | Cycle through metadata and return as dictionary. | 625941d860cbc95b062c67ca |
def highlight_next_match(self): <NEW_LINE> <INDENT> self.text.tag_remove('found.focus', '1.0', tk.END) <NEW_LINE> try: <NEW_LINE> <INDENT> start, end = self.text.tag_nextrange('found', self.start, tk.END) <NEW_LINE> self.text.tag_add('found.focus', start, end) <NEW_LINE> self.text.mark_set(tk.INSERT, start) <NEW_LINE> ... | Highlight the next matching word | 625941d8fb3f5b602dac391d |
def getMin(self): <NEW_LINE> <INDENT> return self.q[-1][1] | :rtype: int | 625941d8bde94217f3683076 |
def get_sen_lengths(sent_file): <NEW_LINE> <INDENT> sents = [x.strip() for x in open(sent_file, 'r')] <NEW_LINE> sen_lengths = [len(sen.split()) for sen in sents] <NEW_LINE> return sents, sen_lengths | Return list of sentences and a list of sentence length per sentence | 625941d83317a56b86939eda |
def svn_wc_add4(*args): <NEW_LINE> <INDENT> return _wc.svn_wc_add4(*args) | svn_wc_add4(svn_wc_context_t * wc_ctx, char const * local_abspath, svn_depth_t depth, char const * copyfrom_url,
svn_revnum_t copyfrom_rev, svn_cancel_func_t cancel_func,
svn_wc_notify_func2_t notify_func, apr_pool_t scratch_pool) -> svn_error_t | 625941d8b7558d58953c5198 |
def bron_kerbosch(self, current, prospective, processed): <NEW_LINE> <INDENT> if not any((prospective, processed)): <NEW_LINE> <INDENT> yield sorted(current) <NEW_LINE> <DEDENT> for node in prospective: <NEW_LINE> <INDENT> for clique in self.bron_kerbosch( current.union({node}), prospective.intersection(self.neighbors(... | Undirected graph Bron-Kerbosch algorithm to find max cliques.
Will not work for self-loops will cause max recursion depth. | 625941d866656f66f7cbc433 |
def decorate_dms_mapping_dict(cls): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if cls.__dict__['project'] == 'personal_umbrella': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass | Class decorator for adding the additional
mapping requirements to the DMS_Claims project | 625941d8ab23a570cc25040b |
def dumps(self, js=None, css=None, rootdir=None): <NEW_LINE> <INDENT> pc_ref = self.get_ref(self.plotcontext) <NEW_LINE> elementid = str(uuid.uuid4()) <NEW_LINE> models = [] <NEW_LINE> for m in self._models.itervalues(): <NEW_LINE> <INDENT> ref = self.get_ref(m) <NEW_LINE> ref["attributes"] = m.vm_serialize() <NEW_LINE... | Returns the HTML contents as a string
**js** and **css** can be "inline" or "relative", and they default
to the values of self.inline_js and self.inline_css.
If these are set to be "relative" (or self.inline_js/css are False),
**rootdir** can be specified to indicate the base directory from which
the path to the vari... | 625941d815fb5d323cde0d9a |
def eh_primo(number): <NEW_LINE> <INDENT> if number < 2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for i in primos: <NEW_LINE> <INDENT> if number % i == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if i > math.sqrt(number): <NEW_LINE> <INDENT> primos.append(number) <NEW_LINE> return True <NEW_LINE... | Retorna True caso number seja primo senão False. | 625941d86e29344779a62898 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.