code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def next(self): <NEW_LINE> <INDENT> self.hasNext() <NEW_LINE> cnest, cidx = self.stack[-1] <NEW_LINE> self.stack[-1][1] += 1 <NEW_LINE> return cnest[cidx].getInteger() | :rtype: int | 625941c8be7bc26dc91cd65d |
def gather_data(self, data, oid, valid_sub_oids): <NEW_LINE> <INDENT> for label_id in valid_sub_oids: <NEW_LINE> <INDENT> if not valid_sub_oids[label_id] in data: <NEW_LINE> <INDENT> data[valid_sub_oids[label_id]] = {} <NEW_LINE> <DEDENT> request = self.snmp_table(oid+'.'+str(label_id)) <NEW_LINE> for response in reque... | Perform a SNMP GETNEXT over an OID prefix, filter the
response based on valid suboids and append it on a data variable.
:param data: list List to append.
:param oid: str SNMP OID Prefix.
:param valid_sub_oids: dict<key, label> Sub OIDs to keep.
Example:
SNMP GETNEXT dummy response:
1.3.5.5.1.1: 10
1.3.5.5.1.2: 20
... | 625941c85f7d997b87174af2 |
def _parse_(self, text): <NEW_LINE> <INDENT> comment_position = text.find('#') <NEW_LINE> line = text[:comment_position].strip() <NEW_LINE> self.description = text[comment_position + 1:].strip() <NEW_LINE> parts = line.split() <NEW_LINE> if len(parts) != 48: <NEW_LINE> <INDENT> sys.stdout.write("expect 48 space split p... | parse line into Query | 625941c88a43f66fc4b540c2 |
def _create_screenshot_review_with_issue(self, publish=False, comment_text=None): <NEW_LINE> <INDENT> if not comment_text: <NEW_LINE> <INDENT> comment_text = 'Test screenshot comment with an opened issue' <NEW_LINE> <DEDENT> review_request = self.create_review_request(publish=True, submitter=self.user) <NEW_LINE> scree... | Sets up a review for a screenshot that includes an open issue.
If `publish` is True, the review is published. The review request is
always published.
Returns the response from posting the comment, the review object, and
the review request object. | 625941c84e696a04525c94a7 |
def test_get_study_maskings(self): <NEW_LINE> <INDENT> pass | Test case for get_study_maskings
Get available study maskings # noqa: E501 | 625941c892d797404e3041e5 |
def __init__( self, competition_id, features, target, training_data_fname, test_data_fname, scorer=None, file_format="csv", cache=KAGGLE_CACHE_DIR, custom_preprocessor=None): <NEW_LINE> <INDENT> self._competition_id = competition_id <NEW_LINE> self._features = features <NEW_LINE> self._target = target <NEW_LINE> self._... | Initialize Kaggle Competition object.
:params str competition_id: kaggle identifier for the competition. This
is a dash-delimited string, e.g. "allstate-claims-severity"
:params dict[str -> FeatureType] features: a dictionary mapping feature
column names to FeatureTypes.
:params dict[str -> TargetType] target:... | 625941c8956e5f7376d70eca |
def log(to_email, message_sent, status): <NEW_LINE> <INDENT> tz = pytz.timezone('Africa/Nairobi') <NEW_LINE> now = datetime.datetime.now(tz) <NEW_LINE> str_now = now.strftime('%Y-%m-%d %H:%M:%S') <NEW_LINE> with connection.cursor() as cursor: <NEW_LINE> <INDENT> sql = "INSERT INTO outbound " "(email, mess... | Log the message to your database | 625941c8d6c5a102081440a6 |
def subsetsWithDup(self, nums): <NEW_LINE> <INDENT> nums = sorted(nums) <NEW_LINE> ans = set() <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> ans = {(num,)} | {tuple(list(t) + [num]) for t in ans} | ans <NEW_LINE> <DEDENT> return list(ans) + [[]] | :type nums: List[int]
:rtype: List[List[int]] | 625941c8dd821e528d63b205 |
def getGraphcap(filename=None): <NEW_LINE> <INDENT> if filename is None: <NEW_LINE> <INDENT> filename = iraf.osfn(iraf.envget('graphcap', 'dev$graphcap')) <NEW_LINE> <DEDENT> if filename not in graphcapDict: <NEW_LINE> <INDENT> graphcapDict[filename] = graphcap.GraphCap(filename) <NEW_LINE> <DEDENT> return graphcapDict... | Get graphcap file from filename (or cached version if possible) | 625941c8ad47b63b2c509fdb |
def list_running_zones(): <NEW_LINE> <INDENT> zdict = _list_zones("/", li.PATH_TRANSFORM_NONE) <NEW_LINE> rzdict = {} <NEW_LINE> for z_name, (z_path, z_state) in six.iteritems(zdict): <NEW_LINE> <INDENT> if z_state == ZONE_STATE_STR_RUNNING: <NEW_LINE> <INDENT> rzdict[z_name] = z_path <NEW_LINE> <DEDENT> <DEDENT> retur... | Return dictionary with currently running zones of the system in the
following form:
{ zone_name : zone_path, ... } | 625941c823849d37ff7b30ec |
def run(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplemented() | This method is where the main work is done. It is called for each job, with the corresponding args and kwargs
provided to the pool.map or pool.imap_unordered functions. The returned value is passed to the caller as is. | 625941c838b623060ff0ae4a |
def restore(self): <NEW_LINE> <INDENT> if (os.path.exists(self.workdir)): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.workdir = os.path.join(os.path.abspath(os.getcwd()), self.uid) <NEW_LINE> createIfNotExists(self.workdir) <NEW_LINE> copyPfiles(self.workdir) <NEW_LINE> self.cleaned = ... | Restore the class if it comes from a parallel job and its directory
has been removed | 625941c8f8510a7c17cf9758 |
def process_event(self, event): <NEW_LINE> <INDENT> self._pre_process_event(event) <NEW_LINE> current = self._current <NEW_LINE> replacement = self._transitions[current.name][event] <NEW_LINE> if current.on_exit is not None: <NEW_LINE> <INDENT> current.on_exit(current.name, event) <NEW_LINE> <DEDENT> if replacement.on_... | Trigger a state change in response to the provided event. | 625941c81f5feb6acb0c4bad |
def test_regressed_status(self): <NEW_LINE> <INDENT> improved = ComparisonResult(min, True, False, None, [10.], None, None) <NEW_LINE> self.assertEqual(improved.get_test_status(), REGRESSED) | Test getting a test status improvement. | 625941c894891a1f4081bb05 |
def update_review(self, review): <NEW_LINE> <INDENT> querystring = self.db_cur.mogrify( """INSERT INTO reviews (ID, title, rating, date, "full", attr_ID, user_profile) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING;""", tuple(review.__dict__.values()), ) <NEW_LINE> return super().update_record(querystring) | Update a review in the PostgreSQL database
Parameters
----------
review: Review
a Review instance | 625941c8f9cc0f698b140658 |
def get_wb_user_info(access_token, wb_uid): <NEW_LINE> <INDENT> params = cfg.WB_USER_SHOW_PARAMS.copy() <NEW_LINE> params['access_token'] = access_token <NEW_LINE> params['uid'] = wb_uid <NEW_LINE> resp = requests.get(cfg.WB_USER_SHOW_API, params=params) <NEW_LINE> result = resp.json() <NEW_LINE> nickname = result.get(... | 获取微博用户的信息 | 625941c87cff6e4e811179e2 |
def _parse_conv_property_list( n_layers, layer_sizes, layer_strides, layer_paddings, name='conv2d'): <NEW_LINE> <INDENT> layer_properties = [layer_sizes] <NEW_LINE> n_layer_sizes = np.shape(layer_sizes)[0] <NEW_LINE> if n_layer_sizes != n_layers: <NEW_LINE> <INDENT> raise ValueError( "List of {} layer sizes does not ma... | Parse parameters for conv/pool cnn layers and return layer properties. | 625941c87c178a314d6ef4ba |
def only_group(self, groupId=None): <NEW_LINE> <INDENT> return True | By definition, only the group is being searched. | 625941c85166f23b2e1a51b5 |
def test_PATCH_user_detail_writable_role_with_errors(self): <NEW_LINE> <INDENT> self._test_writable_role_with_errors('patch') | Test that a PATCH to user_detail fails when trying to update the
`is_active`, `is_staff`, `is_superuser`, `role` fields with the
wrong role. | 625941c84a966d76dd55106b |
def backwards(self, orm): <NEW_LINE> <INDENT> Flag = orm['waffle.flag'] <NEW_LINE> try: <NEW_LINE> <INDENT> flag = Flag.objects.get(name='feedbackdev') <NEW_LINE> flag.delete() <NEW_LINE> <DEDENT> except Flag.DoesNotExist: <NEW_LINE> <INDENT> pass | Write your backwards methods here. | 625941c8a05bb46b383ec87f |
def main(n, value_limit=MATRIX_VALUE_LIMIT, show_matrix=False): <NEW_LINE> <INDENT> size = 2 * n - 1 <NEW_LINE> matrix = generate_matrix(size, value_limit) <NEW_LINE> if show_matrix: <NEW_LINE> <INDENT> printout_matrix(matrix) <NEW_LINE> <DEDENT> printout_spiral(matrix) | Генерирует матрицу размером 2n-1 x 2n-1,
заполненную рандомными значениями в диапазоне [0..value_limit).
Выводит элементы матрицы по спирали - от центра против часовой стрелки.
:param n: определяет размер матрицы 2n-1 x 2n-1
:param value_limit: Максимальное значение элемента матрицы
:param show_matrix: Флаг, указывающ... | 625941c8b545ff76a8913e73 |
def error(self, str): <NEW_LINE> <INDENT> print("error: " + str) <NEW_LINE> self.scan() | Log the given scan error. | 625941c85510c4643540f443 |
def extra_super_categories(self): <NEW_LINE> <INDENT> return [Semigroups()] | Implement the fact that the algebra of a semigroup is indeed
a (not necessarily unital) algebra.
EXAMPLES::
sage: Semigroups().Algebras(QQ).extra_super_categories()
[Category of semigroups]
sage: Semigroups().Algebras(QQ).super_categories()
[Category of associative algebras over Rational Field,
C... | 625941c8ac7a0e7691ed412a |
def count_integrations(sdfitsfile, target): <NEW_LINE> <INDENT> bintable = _get_bintable(sdfitsfile) <NEW_LINE> whobject = bintable.data['OBJECT'] == target <NEW_LINE> any_sampler = bintable.data['SAMPLER'][whobject][0] <NEW_LINE> whsampler = bintable.data['SAMPLER'][whobject] == any_sampler <NEW_LINE> return (whsample... | Return the number of integrations for a given target
(uses one sampler; assumes same number for all samplers) | 625941c84d74a7450ccd4220 |
def algorithm_list(p_engine, p_username, format, algname): <NEW_LINE> <INDENT> ret = 0 <NEW_LINE> data = DataFormatter() <NEW_LINE> data_header = [ ("Engine name", 30), ("Algorithm name", 30), ("Domain name", 32), ("Syncable", 9), ("Algorithm type", 30), ] <NEW_LINE> data.create_header(data_header) <NEW_LINE> data.for... | Print list of algorithms
param1: p_engine: engine name from configuration
param2: format: output format
param2: algname: algname name to list, all if None
return 0 if algname found | 625941c810dbd63aa1bd2c00 |
def arbitrary_point(self, parameter='t'): <NEW_LINE> <INDENT> t = _symbol(parameter) <NEW_LINE> if t.name in (f.name for f in self.free_symbols): <NEW_LINE> <INDENT> raise ValueError(filldedent('Symbol %s already appears in object ' 'and cannot be used as a parameter.' % t.name)) <NEW_LINE> <DEDENT> return Point(self.c... | A parameterized point on the ellipse.
Parameters
==========
parameter : str, optional
Default value is 't'.
Returns
=======
arbitrary_point : Point
Raises
======
ValueError
When `parameter` already appears in the functions.
See Also
========
sympy.geometry.point.Point
Examples
========
>>> from sympy ... | 625941c8009cb60464c6340f |
def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): <NEW_LINE> <INDENT> names = [ "delete_namespaced_storage_class", "delete_storage_class", ] <NEW_LINE> body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=gr... | Deletes the StorageClass from the currently configured
Kubernetes cluster. | 625941c8fb3f5b602dac36ef |
def predict_proba(model, X_test): <NEW_LINE> <INDENT> return model.predict_proba(X_test) | Get the prediction_proba scores of a model given some test data | 625941c8baa26c4b54cb117d |
def train_evaluate(self, e): <NEW_LINE> <INDENT> top_1_correct, top_5_correct, total = self.eval(self.data_loader) <NEW_LINE> log = "Epoch [{}/{}]--top_1_acc: {:.4f}--top_5_acc: {:.4f}".format( e + 1, self.num_epochs, top_1_correct / total, top_5_correct / total ) <NEW_LINE> write_print(self.output_txt, log) <NEW_LINE>... | Evaluates the performance of the model using the train dataset | 625941c89f2886367277a8ea |
def pipinstall(self, package): <NEW_LINE> <INDENT> subprocess.call([sys.executable, "-m", "pip", "install", package]) | pip install for executable dependencies | 625941c87b25080760e394b6 |
def OnPageChanged(self, page=None, trigger=None): <NEW_LINE> <INDENT> if trigger in ["parm_batch", "fit_batch", "page_add_batch"]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if len(self.parent.Background) == 0: <NEW_LINE> <INDENT> self.BGlist = list() <NEW_LINE> self.UpdateDropdown() <NEW_LINE> self.dropdown.SetVal... | This function is called, when something in the panel
changes. The variable `trigger` is used to prevent this
function from being executed to save stall time of the user.
Forr a list of possible triggers, see the doc string of
`tools`. | 625941c84e696a04525c94a8 |
def setenv(self, name, value): <NEW_LINE> <INDENT> return self._channel.setenv(name, value) | Sets envrionment variable on the channel.
@param name: envrionment variable name
@type name: str
@param value: envrionment variable value
@type value: str
@return: 0 on success or negative on failure
@rtype: int | 625941c8d10714528d5ffd3f |
def select(self, event): <NEW_LINE> <INDENT> point = Point(event.x, event.y) <NEW_LINE> for p in self.rect_points: <NEW_LINE> <INDENT> if point.within_rect(p['point_ul'], p['point_lr']): <NEW_LINE> <INDENT> selected_filename = p['filename'] <NEW_LINE> print('%s' % (selected_filename,)) <NEW_LINE> break <NEW_LINE> <DEDE... | Select an image and skip to the next montage. | 625941c8097d151d1a222eb7 |
@view_config(route_name='tag_view', decorator=use_template('multiple_posts.mako')) <NEW_LINE> def tag_view(request): <NEW_LINE> <INDENT> page_num = request.params.get('p', None) or 1 <NEW_LINE> if request.params.get('sort-ascending', False): <NEW_LINE> <INDENT> sort_desc = False <NEW_LINE> sort_ascending_query_text = '... | Display a page similar to that of
:py:func:`fireblog.views.view_all_posts` but just showing the posts that
have the supplied tag on them. The tag supplied is
``request.matchdict['tag_name']``. | 625941c89f2886367277a8eb |
def __init__( self, *, tags: Optional[Dict[str, str]] = None, identity: Optional["EncryptionSetIdentity"] = None, encryption_type: Optional[Union[str, "DiskEncryptionSetType"]] = None, active_key: Optional["KeyForDiskEncryptionSet"] = None, rotation_to_latest_key_version_enabled: Optional[bool] = None, **kwargs ): <NEW... | :keyword tags: A set of tags. Resource tags.
:paramtype tags: dict[str, str]
:keyword identity: The managed identity for the disk encryption set. It should be given
permission on the key vault before it can be used to encrypt disks.
:paramtype identity: ~azure.mgmt.compute.v2021_12_01.models.EncryptionSetIdentity
:key... | 625941c876d4e153a657eb8d |
def terrain_outliner(context): <NEW_LINE> <INDENT> cvb = context.scene.CVB <NEW_LINE> size = 10 <NEW_LINE> subdivision_per_meter = 8 <NEW_LINE> sketch_path = "/CVB/Region Terrain" <NEW_LINE> collection_add(sketch_path) <NEW_LINE> map_name = "Region Terrain Map" <NEW_LINE> terrain_map = terrain_object.RegionTerrainMap(m... | Check to see if the terrain region map exists and add it if it does not. | 625941c823e79379d52ee5c2 |
def stops_near(request): <NEW_LINE> <INDENT> distance = Decimal(request.GET.get("distance", "1")) <NEW_LINE> d = D(km=distance) <NEW_LINE> center_lat = float(request.GET.get("center_lat", "19.04719036505186")) <NEW_LINE> center_lon = float(request.GET.get("center_lon", "72.87094116210938")) <NEW_LINE> pt = Point([cente... | Returns stop within 'distance' of Point(center_lon, center_lat) as GeoJSON | 625941c85e10d32532c5ef84 |
def restoreIpAddresses(self, s): <NEW_LINE> <INDENT> if len(s) > 12: return [] <NEW_LINE> res = [] <NEW_LINE> self.helper(res, [], s, 0) <NEW_LINE> return res | :type s: str
:rtype: List[str] | 625941c830dc7b76659019c4 |
def detect_molded(self, molded_images, image_metas, verbose=0): <NEW_LINE> <INDENT> assert self.mode == "inference", "Create model in inference mode." <NEW_LINE> assert len(molded_images) == self.config.BATCH_SIZE, "Number of images must be equal to BATCH_SIZE" <NEW_LINE> if verbose: <NEW_LINE> <INDENT> log(... | Runs the detection pipeline, but expect inputs that are
molded already. Used mostly for debugging and inspecting
the model.
运行检测流程,但输入图像已经处理过。 通常用来调试、检查模型。
molded_images: List of images loaded using load_image_gt()
image_metas: image meta data, also retruned by load_image_gt()
Returns a list of dicts, one dict per ... | 625941c89c8ee82313fbb7d1 |
def __iter__(self): <NEW_LINE> <INDENT> yield self.zaehler <NEW_LINE> yield self.nenner | Iterator for Bruch (zaehler, nenner)
:return: Iterator (zaehler, nenner) | 625941c8ab23a570cc2501df |
def get_PointCount(self): <NEW_LINE> <INDENT> return super(IGpDescribeGeometry, self).get_PointCount() | Method IGpDescribeGeometry.get_PointCount
OUTPUT
Count : long* | 625941c8f548e778e58cd5da |
def __iter__(self): <NEW_LINE> <INDENT> return self.get_combinations() | Set up the ArgumentCreator as an iterator | 625941c8ec188e330fd5a7fe |
def _get_sub_package_provider_session(self, sub_package, session_name, proxy=None): <NEW_LINE> <INDENT> agent_key = self._get_agent_key() <NEW_LINE> if session_name in self._provider_sessions[agent_key]: <NEW_LINE> <INDENT> return self._provider_sessions[agent_key][session_name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | Gets the session from a sub-package | 625941c8cc40096d615959ae |
def extract_sample_data(record, sample, vep_data, hotspot_ivals): <NEW_LINE> <INDENT> alleles = [record.REF] + [str(x) for x in record.ALT] <NEW_LINE> call = record.genotype(sample) <NEW_LINE> data = call.data <NEW_LINE> if data.GT is None or not call.called: <NEW_LINE> <INDENT> vep_data = [] <NEW_LINE> varscan_ok = {}... | Given a record, a sample name, and a parsed VEP annotation, return
the sample data. | 625941c876e4537e8c3516cf |
def retrieve_imap(self, username, **kwargs): <NEW_LINE> <INDENT> uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_IMAP) <NEW_LINE> return self.GetEntry(uri, auth_token=None, query=None, **kwargs) | Retrieves imap settings for the specified username
Args:
username: string The name of the user to get the imap settings for
Returns:
A gdata.data.GDEntry of the user's IMAP settings | 625941c897e22403b379cff6 |
def test_get_aliases(self): <NEW_LINE> <INDENT> self.populate() <NEW_LINE> nugid1_aliases = ['nugid1','nugid1a','nugid1b','nugid1c'] <NEW_LINE> self.assertEquals(nugid1_aliases, get_aliases(1)) <NEW_LINE> nugid1_aliases_delim = 'nugid1; nugid1a; nugid1b; nugid1c' <NEW_LINE> self.assertEquals(nugid1_aliases_delim, get_a... | Get all the aliases for this nugid | 625941c85fc7496912cc39db |
def get_favorite_evals(user_id): <NEW_LINE> <INDENT> favorite_rows = db(Favoritos.user_id==user_id).select() <NEW_LINE> raw_evals = [] <NEW_LINE> for row in favorite_rows: <NEW_LINE> <INDENT> raw_evals.append(db(Avaliacoes.id==row.avaliacao_id).select().first()) <NEW_LINE> <DEDENT> return refine_evals(raw_evals) | Retorna uma lista refinada de avaliacoes favoritas de um usuario referenciado por user_id | 625941c86fece00bbac2d79a |
def poke_process(self): <NEW_LINE> <INDENT> if not self.game_thread.pid: <NEW_LINE> <INDENT> self.quit_game() <NEW_LINE> return False <NEW_LINE> <DEDENT> return True | Watch game's process. | 625941c891af0d3eaac9ba75 |
def stop(self): <NEW_LINE> <INDENT> pass | Stop the StreamObject. Stop consuming/producing data. Notify outlets if there are any. Notify our IKNInlet if we have one. | 625941c885dfad0860c3aeb8 |
def test_assignment_str(self): <NEW_LINE> <INDENT> assignment = Assignment.objects.get(id=101) <NEW_LINE> actual_str = assignment.__str__() <NEW_LINE> expected_str = ("'id': 101, 'statement': 'It is you task', " "'grade': 5.5, 'user_id': 101, 'item_id': " "101, 'status': 0, 'started_at': None, " "'finished_at': None, '... | Method that test `__str__` magic method of Assignment instance object. | 625941c866673b3332b920ee |
@app.route('/add-listing', methods=['GET', 'POST']) <NEW_LINE> def item_add(): <NEW_LINE> <INDENT> user = user_utils.user_auth_check(login_session) <NEW_LINE> if user: <NEW_LINE> <INDENT> session = get_db_cursor() <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> item_title = request.form['item_title'] <NEW_L... | lets logged in user add new items to the item databse.
:return: | 625941c8b830903b967e9969 |
def test_restore_empty(self): <NEW_LINE> <INDENT> ui.clean() <NEW_LINE> self._restore() | Can the empty state be evaluated? | 625941c80a50d4780f666eef |
def __init__(self, ncoils=5): <NEW_LINE> <INDENT> self.tongue_coils = [] <NEW_LINE> for i in range(ncoils): <NEW_LINE> <INDENT> self.tongue_coils.append(TongueCoil()) | Construct a tongue-model instance | 625941c85510c4643540f444 |
def colourfulness_correlate(L, L_L, Ch_L, F_C): <NEW_LINE> <INDENT> L = np.asarray(L) <NEW_LINE> L_L = np.asarray(L_L) <NEW_LINE> Ch_L = np.asarray(Ch_L) <NEW_LINE> F_C = np.asarray(F_C) <NEW_LINE> S_C = 1 + 0.47 * np.log10(L) - 0.057 * np.log10(L) ** 2 <NEW_LINE> S_M = 0.7 + 0.02 * L_L - 0.0002 * L_L ** 2 <NEW_LINE> C... | Returns the correlate of *colourfulness* :math:`C_L`.
Parameters
----------
L : numeric or array_like
Absolute luminance :math:`L` of reference white in :math:`cd/m^2`.
L_L : numeric or array_like
Correlate of *Lightness* :math:`L_L`.
Ch_L : numeric or array_like
Correlate of *chroma* :math:`Ch_L`.
F_C : n... | 625941c815fb5d323cde0b6c |
def _infer_dtype_elements(directory, cfg): <NEW_LINE> <INDENT> dtype_elements = dict() <NEW_LINE> for dtype in DTYPES: <NEW_LINE> <INDENT> for mtype in MTYPE_PER_DTYPE[dtype]: <NEW_LINE> <INDENT> this_id = cfg['mappings'][mtype] <NEW_LINE> files_found = glob(op.join(directory, '*%s*' % this_id)) <NEW_LINE> counter = 1 ... | Method to extract mtype/dtypes from data automatically. | 625941c8b545ff76a8913e74 |
def fit_points_to_box_xy(self): <NEW_LINE> <INDENT> nadjusted = 0 <NEW_LINE> boxw = self.bbox[1,:] - self.bbox[0,:] <NEW_LINE> for d in range(2): <NEW_LINE> <INDENT> l = np.where(self.points[:,d] < self.bbox[0,d])[0] <NEW_LINE> if l.shape[0] > 0: <NEW_LINE> <INDENT> self.points[l,d] = self.points[l,d] + boxw[d] <NEW_LI... | Fit the points in a periodic domain to the given bounding box | 625941c82c8b7c6e89b3581f |
def generate(self, label): <NEW_LINE> <INDENT> y = self.__labelLexicon.put(label.split(' ')[0]) <NEW_LINE> if y == -1: <NEW_LINE> <INDENT> raise Exception("Label doesn't exist: %s" % label) <NEW_LINE> <DEDENT> return y | Return the code for the given label.
:type label: list[basestring]
:param label:
:return: li | 625941c84428ac0f6e5ba850 |
def getBeliefDistribution(self): <NEW_LINE> <INDENT> distribution = DiscreteDistribution() <NEW_LINE> for particle in self.particles: <NEW_LINE> <INDENT> if (not particle in distribution): <NEW_LINE> <INDENT> distribution[particle] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> distribution[particle] += 1 <NEW_LINE>... | Return the agent's current belief state, a distribution over ghost
locations conditioned on all evidence and time passage. This method
essentially converts a list of particles into a belief distribution.
This function should return a normalized distribution. | 625941c88a43f66fc4b540c4 |
def get_plugin_apps(self, multiplexer, logdir): <NEW_LINE> <INDENT> return self._routes_mapping | Returns a mapping from routes to handlers offered by this plugin.
Args:
multiplexer: The event multiplexer.
logdir: The path to the directory containing logs.
Returns:
A dictionary mapping from routes to handlers offered by this plugin. | 625941c84e696a04525c94a9 |
def _preprocess_data(self, data: DataEntry, is_train: bool): <NEW_LINE> <INDENT> past_target_vec = data[self.past_target_field].copy() <NEW_LINE> target_length, target_dim = past_target_vec.shape <NEW_LINE> past_observed = (data[self.past_observed_field] > 0) * ( data["past_is_pad"].reshape((-1, 1)) == 0 ) <NEW_LINE> a... | Performs several preprocess operations for computing the empirical CDF.
1) Reshaping the data.
2) Normalizing the target length.
3) Adding noise to avoid zero slopes (training only)
4) Sorting the target to compute the empirical CDF
Parameters
----------
data
DataEntry with input data.
is_train
if is_train is ... | 625941c84a966d76dd55106c |
def setup_platform(hass, config, add_entities, discovery_info=None): <NEW_LINE> <INDENT> name = config.get(CONF_NAME) <NEW_LINE> command = config.get(CONF_COMMAND) <NEW_LINE> payload_off = config.get(CONF_PAYLOAD_OFF) <NEW_LINE> payload_on = config.get(CONF_PAYLOAD_ON) <NEW_LINE> device_class = config.get(CONF_DEVICE_C... | Set up the Command line Binary Sensor. | 625941c816aa5153ce3624d6 |
def get_host_url(self): <NEW_LINE> <INDENT> return self._json_data_obj.get_value_from_json_ref( json_model.JSON_ATTR_HOST_URL ) | Returns the value of the host configured on the json file
| 625941c8d6c5a102081440a8 |
def repair(self): <NEW_LINE> <INDENT> print('[*] DNS API not yet implemented.') <NEW_LINE> self.verify() | Repairs domain -- not yet implemented. | 625941c8ad47b63b2c509fdd |
def findPhotometer(ports=None, device=None): <NEW_LINE> <INDENT> if isinstance(device,basestring): <NEW_LINE> <INDENT> photometers = [getPhotometerByName(device)] <NEW_LINE> <DEDENT> elif isinstance(device,collections.Iterable): <NEW_LINE> <INDENT> photometers = [getPhotometerByName(d) if isinstance(d,basestring) else ... | Try to find a connected photometer/photospectrometer!
PsychoPy will sweep a series of serial ports trying to open them. If a port
successfully opens then it will try to issue a command to the device. If it
responds with one of the expected values then it is assumed to be the
appropriate device.
:parameters:
ports... | 625941c823849d37ff7b30ee |
def show_error(self, err): <NEW_LINE> <INDENT> self.cwd.set(err) <NEW_LINE> self.top.update() <NEW_LINE> sleep(2) <NEW_LINE> if not (hasattr(self, 'last') and self.last): <NEW_LINE> <INDENT> self.last = os.curdir <NEW_LINE> <DEDENT> self.cwd.set(self.last) <NEW_LINE> self.dirs.config(selectbackground='LightSkyBlue') <N... | Show error. | 625941c88e05c05ec3eea3d2 |
@pytest.fixture() <NEW_LINE> def client(): <NEW_LINE> <INDENT> movieListLoader.result = True <NEW_LINE> movieListLoader.data_load_thread = True <NEW_LINE> movieListLoader.movies_data = test_movie_list <NEW_LINE> movieListLoader.people_data = test_people_list <NEW_LINE> with app.test_client() as client: <NEW_LINE> <INDE... | Create "lambda service" / application to handle http request for test case
:return: client - "lambda service" / application to handle http request | 625941c88da39b475bd64fd1 |
def connect(self, url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> try: <NEW_LINE> <INDENT> self.ws = create_connection(self.url, sslopt={'cert_reqs': ssl.CERT_NONE}) <NEW_LINE> self.active = True <NEW_LINE> self.thread.start() <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> msg = traceback.fo... | 连接 | 625941c8baa26c4b54cb117e |
def on_write_all(self): <NEW_LINE> <INDENT> from madgui.online.dialogs import ExportParamWidget <NEW_LINE> self._show_sync_dialog(ExportParamWidget(), self.write_all) | Write all parameters to the online database. | 625941c8a934411ee37516f1 |
def _initSession(self): <NEW_LINE> <INDENT> self.log.debug( f'Initializing session : {self.url}' ) <NEW_LINE> try: <NEW_LINE> <INDENT> self._session.close() <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> self.log.debug( f'Failed to close previous session: {err}' ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <... | Initiailze pydap session for loading data
Initialize a session for a data set given a username, password, and
URL for the data. Any previously open sessions are closed | 625941c83317a56b86939cb8 |
def __iter__(self): <NEW_LINE> <INDENT> return iter(self._data) | Returns an iterator over the list items | 625941c8d7e4931a7ee9df7b |
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Start a new CI run.') <NEW_LINE> parser.add_argument('-p', '--pipeline-id', type=int, default=20, help='pipeline to download the job from') <NEW_LINE> parser.add_argument('--ref', help='git ref name to run on') <NEW_LINE> parser.add_arg... | Parse and return args. | 625941c81f5feb6acb0c4baf |
def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None): <NEW_LINE> <INDENT> if extra_args is None: extra_args = [ None for i in range(num_nodes) ] <NEW_LINE> return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ] | Start multiple newcoinds, return RPC connections to them | 625941c891f36d47f21ac550 |
def gather(self,value): <NEW_LINE> <INDENT> return value | Returns the value. Can be overridden with MPI | 625941c8eab8aa0e5d26dbb6 |
def test_db_signature(self): <NEW_LINE> <INDENT> settings_dict = self.connection.settings_dict <NEW_LINE> test_dbname = self._get_test_db_name() <NEW_LINE> sig = [self.connection.settings_dict['NAME']] <NEW_LINE> if test_dbname == ':memory:': <NEW_LINE> <INDENT> sig.append(self.connection.alias) <NEW_LINE> <DEDENT> ret... | Returns a tuple that uniquely identifies a test database.
This takes into account the special cases of ":memory:" and "" for
SQLite since the databases will be distinct despite having the same
TEST_NAME. See http://www.sqlite.org/inmemorydb.html | 625941c8379a373c97cfaba2 |
def initPeople(self): <NEW_LINE> <INDENT> people = data[self.name] <NEW_LINE> for i in range(0, len(people)) : <NEW_LINE> <INDENT> person = people[i] <NEW_LINE> position = person['position'] <NEW_LINE> self.addRect(position[0], position[1], abs(position[0]-position[2]), abs(position[1]-position[3]), pen=QPen(Qt.red)) <... | This function is for load and draws the labels of a photo when is initialized | 625941c83346ee7daa2b2dc9 |
def update(self): <NEW_LINE> <INDENT> self.update_remote_origin() <NEW_LINE> if sickrage.GIT_RESET: <NEW_LINE> <INDENT> self.reset() <NEW_LINE> <DEDENT> if self.branch == self._find_installed_version(): <NEW_LINE> <INDENT> _, _, exit_status = self._run_git(self._git_path, 'pull -f %s %s' % (sickrage.GIT_REMOTE, self.br... | Calls git pull origin <branch> in order to update SiCKRAGE. Returns a bool depending
on the call's success. | 625941c8f9cc0f698b14065a |
def algorithm_1_decimal(n): <NEW_LINE> <INDENT> result = Decimal(1) <NEW_LINE> for i in range(1, n+1): <NEW_LINE> <INDENT> result = result*Decimal(3) <NEW_LINE> <DEDENT> return Decimal(1)/result | Calculates tn=1/(3^n) | 625941c8d58c6744b4257cbe |
def line2bank(self, cr, uid, ids, payment_type=None, context=None): <NEW_LINE> <INDENT> payment_mode_obj = self.pool.get('payment.mode') <NEW_LINE> line2bank = {} <NEW_LINE> if not ids: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> bank_type = payment_mode_obj.suitable_bank_types(cr, uid, payment_type, context=cont... | Try to return for each Ledger Posting line a corresponding bank
account according to the payment type. This work using one of
the bank of the partner defined on the invoice eventually
associated to the line.
Return the first suitable bank for the corresponding partner. | 625941c8be383301e01b54e6 |
def create_dataset_json(id, version, met_file, ds_file): <NEW_LINE> <INDENT> with open(met_file) as f: <NEW_LINE> <INDENT> md = json.load(f) <NEW_LINE> <DEDENT> ds = { 'creation_timestamp': "%sZ" % datetime.utcnow().isoformat(), 'version': version, 'label': id, 'location': { 'type': 'Polygon', 'coordinates': [ [ [ md['... | Write dataset json. | 625941c83eb6a72ae02ec539 |
def identify(self, request): <NEW_LINE> <INDENT> raise NotImplementedError() | Establish what identity this user claims to have from request.
:param request: Request to extract identity information from.
:type request: :class:`morepath.Request`.
:returns: :class:`morepath.security.Identity` instance or
:attr:`morepath.security.NO_IDENTITY` if identity cannot
be established. | 625941c8cdde0d52a9e53091 |
def key_not_any_of_values(labels_model, label_key, label_values): <NEW_LINE> <INDENT> return labels_model._labeled_model_fk.in_( db.session.query(labels_model._labeled_model_fk) .filter(labels_model.key == label_key, ~labels_model.value.in_(label_values)) .subquery() .select() ) | <key>!=[<val1>,<val1>] | 625941c871ff763f4b5496e8 |
def get_wordnet_pos(self, word): <NEW_LINE> <INDENT> tag = pos_tag([word])[0][1][0].upper() <NEW_LINE> tag_dict = {"J": wordnet.ADJ, "N": wordnet.NOUN, "V": wordnet.VERB, "R": wordnet.ADV} <NEW_LINE> return tag_dict.get(tag, wordnet.NOUN) | Map POS tag to first character lemmatize() accepts | 625941c816aa5153ce3624d7 |
def deleteEventCats(self, eid): <NEW_LINE> <INDENT> pass | Delete an event's categories | 625941c80a366e3fb873e878 |
def get(key, profile=None): <NEW_LINE> <INDENT> if not profile: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> _, cur, table = _connect(profile) <NEW_LINE> q = profile.get("get_query", "SELECT value FROM {} WHERE key=:key".format(table)) <NEW_LINE> res = cur.execute(q, {"key": key}) <NEW_LINE> res = res.fetchone()... | Get a value from sqlite3 | 625941c84c3428357757c386 |
def credit(self, amount): <NEW_LINE> <INDENT> response = self._client._customer.credit( self._profile_id, self._payment_id, amount) <NEW_LINE> transaction = self._client.transaction(response['transaction_id']) <NEW_LINE> transaction.full_response = response <NEW_LINE> return transaction | Creates an unlinked credit on the card for the specified amount. (This
is different from a refunded transaction, which you initiate from an
:class:`AuthorizeTransaction <authorize.client.AuthorizeTransaction>`
instance.) This functionality must be enabled in your Authorize.net
account. Returns an
:class:`AuthorizeTrans... | 625941c8a8ecb033257d312c |
def pythonize_camelcase(origstr): <NEW_LINE> <INDENT> ret = "" <NEW_LINE> for letter in origstr: <NEW_LINE> <INDENT> if letter.isupper(): <NEW_LINE> <INDENT> ret += '_' + letter.lower() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret += letter <NEW_LINE> <DEDENT> <DEDENT> ret = ret.replace("_f_f_t", "_fft") <NEW_LINE... | Turns camelCase into underscore_style | 625941c8ec188e330fd5a7ff |
def _get_pbo(self): <NEW_LINE> <INDENT> return self.val.val | pass by obj | 625941c8e76e3b2f99f3a86b |
def execute(self, sql_query, values=None, close=True, fetch_all=False): <NEW_LINE> <INDENT> self.connect() <NEW_LINE> self.logger.debug(sql_query) <NEW_LINE> try: <NEW_LINE> <INDENT> if values is None: <NEW_LINE> <INDENT> result = self.cursor.execute(sql_query) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = sel... | Execute a sql query, database connection is opened when not
already connected. Connection will be closed based on the close flag.
If fetch_all is True, all results are fetched from query. | 625941c8ab23a570cc2501e0 |
def reset_data(self): <NEW_LINE> <INDENT> self.start=0 <NEW_LINE> self.end=0 <NEW_LINE> self.data=[] | Clean the buffer | 625941c8236d856c2ad44838 |
def train(self): <NEW_LINE> <INDENT> for itr in range(0, self.iterations): <NEW_LINE> <INDENT> if itr % 10 == 0: <NEW_LINE> <INDENT> print("beginning iteration: " + str(itr)) <NEW_LINE> <DEDENT> count = defaultdict(lambda: defaultdict(lambda: 0.0)) <NEW_LINE> total = defaultdict(lambda: 0.0) <NEW_LINE> for pair in self... | train the ibm model 1 | 625941c8046cf37aa974cda7 |
def analog_read(self, pin): <NEW_LINE> <INDENT> buf = bytearray(2) <NEW_LINE> if pin not in self.pin_mapping.analog_pins: <NEW_LINE> <INDENT> raise ValueError("Invalid ADC pin") <NEW_LINE> <DEDENT> self.read( _ADC_BASE, _ADC_CHANNEL_OFFSET + self.pin_mapping.analog_pins.index(pin), buf, ) <NEW_LINE> ret = struct.unpack... | Read the value of an analog pin by number | 625941c8283ffb24f3c55961 |
def execute(self): <NEW_LINE> <INDENT> pass | Run at the end of every control loop iteration. | 625941c87c178a314d6ef4bd |
def matrix(material): <NEW_LINE> <INDENT> dx = material.delta() <NEW_LINE> diffusion = material.diffusion[group] <NEW_LINE> removal = material.removal(group) <NEW_LINE> sections = material.nodes - 1 <NEW_LINE> diag_val = (removal + 2. * diffusion / dx ** 2) <NEW_LINE> offdiag_val = (- diffusion / dx ** 2) <NEW_LINE> di... | General cartesian material matrix | 625941c8d10714528d5ffd40 |
def nextWeekDay(cday: int, offday: int, startday: int = 1, endday: int = 5) -> int: <NEW_LINE> <INDENT> if cday < startday: <NEW_LINE> <INDENT> cday = startday <NEW_LINE> <DEDENT> offday = offday % 7 <NEW_LINE> if cday + offday > endday: <NEW_LINE> <INDENT> cday += offday + (6 - endday) + (startday - 0) <NEW_LINE> <DED... | nextWeekDay - 计算周几向后偏移,譬如周1的2天后是周3,周5的2天后是周2 | 625941c830bbd722463cbe24 |
def op_iSHR( self ): <NEW_LINE> <INDENT> self.BINARY_OP( op.rshift, int, int ) | iSHR
SS: [ ..., <value2>, <value1> ] -> [ ..., (<value1> bitwise-XOR <value2>) ]
: Binary-op; pop 2 args, compute bitwise shift-right from popped args, push result.
#ALU.BITS | 625941c876e4537e8c3516d0 |
def test_increment_counter(self): <NEW_LINE> <INDENT> counter1 = Counter("test1") <NEW_LINE> counter2 = Counter("test2") <NEW_LINE> counter2.count = 2 <NEW_LINE> db.session.add(counter1) <NEW_LINE> db.session.add(counter2) <NEW_LINE> db.session.commit() <NEW_LINE> with self.client: <NEW_LINE> <INDENT> response = self.c... | Ensure that we can increment a counter, and that we get back all counters. | 625941c8925a0f43d2549ed5 |
def mqtt_on_disconnect(self, client, userdata, result_code): <NEW_LINE> <INDENT> self.mqtt_connected = False <NEW_LINE> logging.warning("{}: disconnected from MQTT server {}:{} ({})".format(self.module_type, self.mqtt_broker, self.mqtt_port, result_code)) | Disconnected callback. | 625941c84e696a04525c94aa |
@app.route('/item/<int:id>', methods=['DELETE']) <NEW_LINE> def delete_item(id): <NEW_LINE> <INDENT> user_id = session.get('user_id') <NEW_LINE> if not user_id: <NEW_LINE> <INDENT> return ("You must be logged in to be able to delete items", 401) <NEW_LINE> <DEDENT> item = Item.query.filter_by(id=id).first() <NEW_LINE> ... | Delete an item | 625941c84e4d5625662d4438 |
def length_sq(self): <NEW_LINE> <INDENT> return self.x**2 + self.y**2 | Returns the squared length of the vector | 625941c8097d151d1a222eb9 |
def Sort(ARR, array_history=None): <NEW_LINE> <INDENT> N = len(ARR) <NEW_LINE> for i in range(N): <NEW_LINE> <INDENT> j = i <NEW_LINE> while j > 0 and __lt__(ARR[j], ARR[j-1]): <NEW_LINE> <INDENT> if array_history is not None: array_history.add_history(ARR, {j:'*', j-1:'*'}) <NEW_LINE> _exch(ARR, j, j-1) <NEW_LINE> j -... | Rearranges the array in ascending order, using the natural order. | 625941c815baa723493c3fd4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.