Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
368,400
def _parse_welcome(client, command, actor, args): _, _, hostmask = args.rpartition() client.user.update_from_hostmask(hostmask) client.dispatch_event("WELCOME", hostmask)
Parse a WELCOME and update user state, then dispatch a WELCOME event.
368,401
def _set_ownership(self): if self.owner or self.group: args = ( self.path, self.owner if self.owner else -1, self.group if self.group else -1, ) logger.debug("changing ownership bits of %s to %s", self.path, args) ...
set ownership of the directory: user and group :return: None
368,402
def abu_chart(self, cycle, mass_range=None ,ilabel=True, imlabel=True, imlabel_fontsize=8, imagic=False, boxstable=True, lbound=(-12, 0), plotaxis=[0, 0, 0, 0], show=True, color_map=, ifig=None,data_provided=False,thedata=None, sa...
Plots an abundance chart Parameters ---------- cycle : string, integer or list The cycle we are looking in. If it is a list of cycles, this method will then do a plot for each of these cycles and save them all to a file. mass_range : list, optional ...
368,403
def linkage_group_ordering(linkage_records): new_records = dict() for lg_name, linkage_group in itertools.groupby( linkage_records, operator.itemgetter(0) ): new_records[lg_name] = [] for record in linkage_group: init_contig = record[-1] start = record[...
Convert degenerate linkage records into ordered info_frags-like records for comparison purposes. Simple example: >>> linkage_records = [ ... ['linkage_group_1', 31842, 94039, 'sctg_207'], ... ['linkage_group_1', 95303, 95303, 'sctg_207'], ... ['linkage_group_2', 15892, 25865, '...
368,404
def _language_to_voice_code(self, language): voice_code = self.rconf[RuntimeConfiguration.TTS_VOICE_CODE] if voice_code is None: try: voice_code = self.LANGUAGE_TO_VOICE_CODE[language] except KeyError as exc: self.log_exc(u"Language code ...
Translate a language value to a voice code. If you want to mock support for a language by using a voice for a similar language, please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary. :param language: the requested language :type language: :class:`~aeneas.language.Language...
368,405
def get_memory_usage(self): usage = dict( nb_cells_by_array = self.population.count, dtype = self.variable.dtype, ) usage.update(self._memory_storage.get_memory_usage()) if self.simulation.trace: usage_stats = self.simulation.tracer.usa...
Get data about the virtual memory usage of the holder. :returns: Memory usage data :rtype: dict Example: >>> holder.get_memory_usage() >>> { >>> 'nb_arrays': 12, # The holder contains the variable values for 12 different periods ...
368,406
def dict_value_hint(key, mapper=None): if mapper is None: mapper = identity def hinter(data): return mapper(data.get(key)) return hinter
Returns a function that takes a dictionary and returns value of particular key. The returned value can be optionally processed by `mapper` function. To be used as a type hint in :class:`OneOf`.
368,407
def check_missing_references(client): from renku.models.refs import LinkReference missing = [ ref for ref in LinkReference.iter_items(client) if not ref.reference.exists() ] if not missing: return True click.secho( WARNING + + .join( clic...
Find missing references.
368,408
def sel_entries(self): ENTIRE_RECORD = 0xff rsp = self.send_message_with_name() if rsp.entries == 0: return reservation_id = self.get_sel_reservation_id() next_record_id = 0 while True: req = create_request_by_name() req.reserv...
Generator which returns all SEL entries.
368,409
def options(self, request, *args, **kwargs): allow = [] for method in self.http_method_names: if hasattr(self, method): allow.append(method.upper()) r = self.render_to_response(None) r[] = .join(allow) return r
Implements a OPTIONS HTTP method function returning all allowed HTTP methods.
368,410
def location(self): if self._location == : return HOME if self._location == : return NEUTRAL if self._location == : return AWAY
Returns a ``string`` constant to indicate whether the game was played at the team's home venue, the opponent's venue, or at a neutral site.
368,411
def save(self, path): rep = "" for host in self.hosts.keys(): attrs = self.hosts[host] rep = rep + "machine " + host + "\n\tlogin " \ + six.text_type(attrs[0]) + "\n" if attrs[1]: rep = rep + "account " + six.text_type(attrs[1]...
Dump the class data in the format of a .netrc file.
368,412
def write_taxon_info(taxon, include_anc, output): output.write(.format(taxon.ott_id)) output.write(.format(taxon.name)) if taxon.synonyms: output.write(.format(.join(taxon.synonyms))) else: output.write() output.write(.format(taxon.flags)) output.write(.format(taxon.rank)) ...
Writes out data from `taxon` to the `output` stream to demonstrate the attributes of a taxon object. (currently some lines are commented out until the web-services call returns more info. See: https://github.com/OpenTreeOfLife/taxomachine/issues/85 ). If `include_anc` is True, then ancestor info...
368,413
def cached(fun): _cache = {} @wraps(fun) def newfun(a, b, distance_function): frozen_a = frozenset(a) frozen_b = frozenset(b) if (frozen_a, frozen_b) not in _cache: result = fun(a, b, distance_function) _cache[(frozen_a, frozen_b)] = result retu...
memoizing decorator for linkage functions. Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because, the way this is coded (interchangingly using sets and frozensets) is true for this specific case. For other cases that is not necessarily guaranteed.
368,414
def from_requirement(cls, req, changes=None): return cls(req.project_name, req.specs and .join(req.specs[0]) or , changes=changes)
Create an instance from :class:`pkg_resources.Requirement` instance
368,415
def toggle_show_cd_only(self, checked): self.parent_widget.sig_option_changed.emit(, checked) self.show_cd_only = checked if checked: if self.__last_folder is not None: self.set_current_folder(self.__last_folder) elif self.__original_root_index...
Toggle show current directory only mode
368,416
def __add_bank(self, account_id, **kwargs): params = { : account_id } return self.make_call(self.__add_bank, params, kwargs)
Call documentation: `/account/add_bank <https://www.wepay.com/developer/reference/account-2011-01-15#add_bank>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` ...
368,417
def any_ends_with(self, string_list, pattern): try: s_base = basestring except: s_base = str is_string = isinstance(pattern, s_base) if not is_string: return False for s in string_list: if pattern.endswith(s): ...
Returns true iff one of the strings in string_list ends in pattern.
368,418
def incr_obj(obj, **attrs): for name, value in attrs.iteritems(): v = getattr(obj, name, None) if not hasattr(obj, name) or v is None: v = 0 setattr(obj, name, v + value)
Increments context variables
368,419
def _merge_wf_inputs(new, out, wf_outputs, to_ignore, parallel, nested_inputs): internal_generated_ids = [] for vignore in to_ignore: vignore_id = _get_string_vid(vignore) if vignore_id not in [v["id"] for v in wf_outputs]: internal_generated_ids.append(vignore...
Merge inputs for a sub-workflow, adding any not present inputs in out. Skips inputs that are internally generated or generated and ignored, keeping only as inputs those that we do not generate internally.
368,420
def update(self, device_json=None, info_json=None, settings_json=None, avatar_json=None): if device_json: UTILS.update(self._device_json, device_json) if avatar_json: UTILS.update(self._avatar_json, avatar_json) if info_json: UTILS.up...
Update the internal device json data.
368,421
def gammaVectorRDD(sc, shape, scale, numRows, numCols, numPartitions=None, seed=None): return callMLlibFunc("gammaVectorRDD", sc._jsc, float(shape), float(scale), numRows, numCols, numPartitions, seed)
Generates an RDD comprised of vectors containing i.i.d. samples drawn from the Gamma distribution. :param sc: SparkContext used to create the RDD. :param shape: Shape (> 0) of the Gamma distribution :param scale: Scale (> 0) of the Gamma distribution :param numRows: Number of Ve...
368,422
def validate_realms(self, client_key, token, request, uri=None, realms=None): log.debug(, realms, client_key) if request.access_token: tok = request.access_token else: tok = self._tokengetter(client_key=client_key, token=token) ...
Check if the token has permission on those realms.
368,423
def build(self, builder): builder.start(self.__class__.__name__) builder.data(self.country_code) builder.end(self.__class__.__name__)
Build this element :param builder: :return:
368,424
def reboot(name, call=None): if call != : raise SaltCloudException( ) my_info = _get_my_info(name) profile_name = my_info[name][] profile = __opts__[][profile_name] host = profile[] local = salt.client.LocalClient() return local.cmd(host, , [name])
Reboot a vagrant minion. name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot vm_name
368,425
def _system_path(self, subdir, basename=): subdir/basenamesubdir/basename try: return self._file_path(os.path.join(self.system_dir, subdir), basename) except KeyboardInterrupt as e: raise e except Exception: return None
Gets the full path to the 'subdir/basename' file in the system binwalk directory. @subdir - Subdirectory inside the system binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/basename' file.
368,426
def _is_cp_helper(self, choi, atol, rtol): if atol is None: atol = self._atol if rtol is None: rtol = self._rtol return is_positive_semidefinite_matrix(choi, rtol=rtol, atol=atol)
Test if a channel is completely-positive (CP)
368,427
def stream_list(self, id, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC): id = self.__unpack_id(id) return self.__stream("/api/v1/streaming/list?list={}".format(id), listener, run_async=run_async...
Stream events for the current user, restricted to accounts on the given list.
368,428
def dimensioned_streams(dmap): dimensioned = [] for stream in dmap.streams: stream_params = stream_parameters([stream]) if set([str(k) for k in dmap.kdims]) & set(stream_params): dimensioned.append(stream) return dimensioned
Given a DynamicMap return all streams that have any dimensioned parameters i.e parameters also listed in the key dimensions.
368,429
def List(self, listName, exclude_hidden_fields=False): return _List(self._session, listName, self._url, self._verify_ssl, self.users, self.huge_tree, self.timeout, exclude_hidden_fields=exclude_hidden_fields)
Sharepoint Lists Web Service Microsoft Developer Network: The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files.
368,430
def plot_chmap(cube, kidid, ax=None, **kwargs): if ax is None: ax = plt.gca() index = np.where(cube.kidid == kidid)[0] if len(index) == 0: raise KeyError() index = int(index) im = ax.pcolormesh(cube.x, cube.y, cube[:, :, index].T, **kwargs) ax.set_xlabel() ax.set_ylabe...
Plot an intensity map. Args: cube (xarray.DataArray): Cube which the spectrum information is included. kidid (int): Kidid. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.imshow().
368,431
def curtailment(network, carrier=, filename=None): p_by_carrier = network.generators_t.p.groupby\ (network.generators.carrier, axis=1).sum() capacity = network.generators.groupby("carrier").sum().at[carrier, "p_nom"] p_available = network.generators_t.p_max_pu.multiply( network.gene...
Plot curtailment of selected carrier Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis carrier: str Plot curtailemt of this carrier filename: str or None Save figure in this direction Returns ...
368,432
def on_click(self, button, **kwargs): actions = [, , , , ] try: action = actions[button - 1] except (TypeError, IndexError): self.__log_button_event(button, None, None, "Other button") action = "otherclick" m_click = self....
Maps a click event with its associated callback. Currently implemented events are: ============ ================ ========= Event Callback setting Button ID ============ ================ ========= Left click on_leftclick 1 Middle click on_middleclic...
368,433
def get_template_id(self, template_id_short): return self.request.post( url=, data={ : str(template_id_short), } )
获得模板ID 详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html :param template_id_short: 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式 :return: 返回的 JSON 数据包
368,434
def p_objectitem_0(self, p): if DEBUG: self.print_p(p) p[0] = (p[1], p[3])
objectitem : objectkey EQUAL number | objectkey EQUAL BOOL | objectkey EQUAL STRING | objectkey EQUAL object | objectkey EQUAL list
368,435
def apply_boundary_conditions_to_cm(external_indices, cm): cm = cm.copy() cm[external_indices, :] = 0 cm[:, external_indices] = 0 return cm
Remove connections to or from external nodes.
368,436
def act(self, action): action = int(action) assert isinstance(action, int) assert action < self.actions_num, "%r (%s) invalid"%(action, type(action)) for k in self.world_layer.buttons: self.world_layer.buttons[k] = 0 for key in se...
Take one action for one step
368,437
def translate_output_properties(res: , output: Any) -> Any: if isinstance(output, dict): return {res.translate_output_property(k): translate_output_properties(res, v) for k, v in output.items()} if isinstance(output, list): return [translate_output_properties(res, v) for v in output] ...
Recursively rewrite keys of objects returned by the engine to conform with a naming convention specified by the resource's implementation of `translate_output_property`. If output is a `dict`, every key is translated using `translate_output_property` while every value is transformed by recursing. If o...
368,438
def create_single_dialog_train_example(context_dialog_path, candidate_dialog_paths, rng, positive_probability, minimum_context_length=2, max_context_length=20): dialog = translate_dialog_to_lists(context_dialog_path) context_str, next_utterance_ix = create_random_co...
Creates a single example for training set. :param context_dialog_path: :param candidate_dialog_paths: :param rng: :param positive_probability: :return:
368,439
def linkify_s_by_sd(self, services): for servicedep in self: setattr(servicedep, "service_description_string", "undefined") setattr(servicedep, "dependent_service_description_string", "undefined") if getattr(servicedep, , None) is None or\ ...
Add dependency in service objects :return: None
368,440
def _discover_refs(self, remote=False): if remote: cmd_refs = [, , , , , ] sep = ignored_error_codes = [2] else: if self.is_empty(): raise EmptyRepositoryError(repository=self.uri) cmd_refs ...
Get the current list of local or remote refs.
368,441
def callable(self, addr, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None): return Callable(self.project, addr=addr, concrete_only=concrete_only, perform_merge=perform_merge, base_...
A Callable is a representation of a function in the binary that can be interacted with like a native python function. :param addr: The address of the function to use :param concrete_only: Throw an exception if the execution splits into multiple states :param perform_merge: ...
368,442
def _parse_raw_data(self): if self._START_OF_FRAME in self._raw and self._END_OF_FRAME in self._raw: while self._raw[0] != self._START_OF_FRAME and len(self._raw) > 0: self._raw.pop(0) if self._raw[0] == self._START_OF_FRAME: self._raw.pop(0) ...
Parses the incoming data and determines if it is valid. Valid data gets placed into self._messages :return: None
368,443
def update(name, password=None, fullname=None, description=None, home=None, homedrive=None, logonscript=None, profile=None, expiration_date=None, expired=None, account_disabled=None, unlock_account=N...
Updates settings for the windows user. Name is the only required parameter. Settings will only be changed if the parameter is passed a value. .. versionadded:: 2015.8.0 Args: name (str): The user name to update. password (str, optional): New user password in plain text. fullname ...
368,444
def new_section(self, name, params=None): self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self) s = self.sections[name.lower()] if name.lower() in self.decl_sections: s.args = self.decl_sections[name.lower()][] return s
Return a new section
368,445
def get_request_payment(self, bucket): details = self._details( method=b"GET", url_context=self._url_context(bucket=bucket, object_name="?requestPayment"), ) d = self._submit(self._query_factory(details)) d.addCallback(self._parse_get_request_payment) ...
Get the request payment configuration on a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will fire with the name of the payer.
368,446
def code(self): def uniq(seq): seen = set() seen_add = seen.add return [x for x in seq if x not in seen and not seen_add(x)] a = uniq(i for i in self.autos if i is not None) e = uniq(i for i in self.errors if i is not ...
code
368,447
def turbulent_Sieder_Tate(Re, Pr, mu=None, mu_w=None): r Nu = 0.027*Re**0.8*Pr**(1/3.) if mu_w and mu: Nu *= (mu/mu_w)**0.14 return Nu
r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [1]_ and supposedly [2]_. .. math:: Nu = 0.027Re^{4/5}Pr^{1/3}\left(\frac{\mu}{\mu_s}\right)^{0.14} Parameters ---------- Re : float Reynolds number, [-] Pr : float Prandtl number...
368,448
def __delete(self, subscription_plan_id, **kwargs): params = { : subscription_plan_id } return self.make_call(self.__delete, params, kwargs)
Call documentation: `/subscription_plan/delete <https://www.wepay.com/developer/reference/subscription_plan#delete>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorizati...
368,449
def build_vcf_deletion(x, genome_2bit): base1 = genome_2bit[x.chrom1].get(x.start1, x.start1 + 1).upper() id1 = "hydra{0}".format(x.name) return VcfLine(x.chrom1, x.start1, id1, base1, "<DEL>", _vcf_single_end_info(x, "DEL", True))
Provide representation of deletion from BedPE breakpoints.
368,450
def hoverMoveEvent(self, event): super(XNode, self).hoverMoveEvent(event) self._hovered = True hotspot = self.hotspotAt(event.pos()) if not hotspot: hotspot = self.dropzoneAt(event.pos()) old_spot = self._hoverSpot...
Prompts the tool tip for this node based on the inputed event. :param event | <QHoverEvent>
368,451
def _remove_by_pk(self, key, flush=True): try: del self.store[key] except Exception as error: pass if flush: self.flush()
Retrieve value from store. :param key: Key
368,452
def get_serializer_context(self): context = super(SpecialMixin, self).get_serializer_context() context[] = self.kwargs[] return context
Adds ``election_day`` to serializer context.
368,453
def _init_map(self): ItemTextsFormRecord._init_map(self) ItemFilesFormRecord._init_map(self) edXBaseFormRecord._init_map(self) IRTItemFormRecord._init_map(self) TimeValueFormRecord._init_map(self) ProvenanceFormRecord._init_map(self) super(edXItemFormReco...
Have to call these all separately because they are "end" classes, with no super() in them. Non-cooperative.
368,454
def partial_match(self, path, filter_path): if not path or not filter_path: return True if path[-1] == PATH_SEP: path = path[0:-1] if filter_path[-1] == PATH_SEP: filter_path += pi = path.split(PATH_SEP) fi = filter_path.split(PATH_SEP) min_len = min(len...
Partially match a path and a filter_path with wildcards. This function will return True if this path partially match a filter path. This is used for walking through directories with multiple level wildcard.
368,455
def xpath(self, expression): global namespaces return self.tree.xpath(expression, namespaces=namespaces)
Executes an xpath expression using the correct namespaces
368,456
def is_executable(exe_name): if not isinstance(exe_name, str): raise TypeError() def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(exe_name) if not fpath: res = any([is_exe(os.path.join(path, exe_name)) for path...
Check if Input is Executable This methid checks if the input executable exists. Parameters ---------- exe_name : str Executable name Returns ------- Bool result of test Raises ------ TypeError For invalid input type
368,457
def _set_data(self): if getattr(self, , False) and not getattr(self, , False) and not getattr(self, , False): _x = XVariable() _y = YVariable() _x.contribute_to_class(self, , self.data) _y.contribute_to_class(self, , self.data) self[] = zip(se...
This method will be called to set Series data
368,458
def save_to_file(self, filename: str) -> ConfigFile: newclass = ConfigFile(fd=filename, load_hook=self.normal_class_hook[0], dump_hook=self.normal_class_hook[1], safe_load=self.safe_load) return newclass
This converts the NetworkedConfigFile into a normal ConfigFile object. This requires the normal class hooks to be provided.
368,459
def get_view(self, table): request = self.client.tables().get(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id) try: response = request.execute() except http...
Returns the SQL query for a view, or None if it doesn't exist or is not a view. :param table: The table containing the view. :type table: BQTable
368,460
def get_http_info(self, request): if self.is_json_type(request.mimetype): retriever = self.get_json_data else: retriever = self.get_form_data return self.get_http_info_with_retriever(request, retriever)
Determine how to retrieve actual data by using request.mimetype.
368,461
def tplds(self): self.parent.del_objects_by_type() for tpld in self.get_attribute().split(): XenaTpld(parent=self, index=.format(self.index, tpld)) return {t.id: t for t in self.get_objects_by_type()}
:return: dictionary {id: object} of all current tplds. :rtype: dict of (int, xenamanager.xena_port.XenaTpld)
368,462
def error_wrapper(error, errorClass): http_status = 0 if error.check(TwistedWebError): xml_payload = error.value.response if error.value.status: http_status = int(error.value.status) else: error.raiseException() if http_status >= 400: if not xml_payload: ...
We want to see all error messages from cloud services. Amazon's EC2 says that their errors are accompanied either by a 400-series or 500-series HTTP response code. As such, the first thing we want to do is check to see if the error is in that range. If it is, we then need to see if the error message is ...
368,463
def _addr_in_exec_memory_regions(self, addr): for start, end in self._exec_mem_regions: if start <= addr < end: return True return False
Test if the address belongs to an executable memory region. :param int addr: The address to test :return: True if the address belongs to an exectubale memory region, False otherwise :rtype: bool
368,464
def send(self, command, _id=None, result={}, frames=[], threads=None, error_messages=[], warning_messages=[], info_messages=[], exception=None): with self._connection_lock: payload = { : _id, : command, : result, ...
Build a message from parameters and send it to debugger. :param command: The command sent to the debugger client. :type command: str :param _id: Unique id of the sent message. Right now, it's always `None` for messages by debugger to client. :type _i...
368,465
def crab_request(client, action, *args): log.debug(, action) return getattr(client.service, action)(*args)
Utility function that helps making requests to the CRAB service. :param client: A :class:`suds.client.Client` for the CRAB service. :param string action: Which method to call, eg. `ListGewesten` :returns: Result of the SOAP call. .. versionadded:: 0.3.0
368,466
def hms_string(secs): l = hms(secs) def extend10(n): if n < 10: return + str(n) else: return str(n) return extend10(l[0]) + + extend10(l[1]) + + extend10(l[2])
return hours,minutes and seconds string, e.g. 02:00:45
368,467
def display(url): import os oscmd="curl --silent -g --fail --max-time 1800 --user jkavelaars " % (url) logger.debug(oscmd) os.system(oscmd+) return
Display a file in ds9
368,468
def create(input_dataset, target, feature=None, validation_set=, warm_start=, batch_size=256, max_iterations=100, verbose=True): import mxnet as _mx from mxnet import autograd as _autograd from ._model_architecture import Model as _Model from ._sframe_loader import SFr...
Create a :class:`DrawingClassifier` model. Parameters ---------- dataset : SFrame Input data. The columns named by the ``feature`` and ``target`` parameters will be extracted for training the drawing classifier. target : string Name of the column containing the target variable....
368,469
def sort(self): while self.nodes: iterated = False for node in self.leaf_nodes(): iterated = True self.prune_node(node) yield node if not iterated: raise CyclicGraphError("Sorting has found a cyclic grap...
Return an iterable of nodes, toplogically sorted to correctly import dependencies before leaf nodes.
368,470
def describe_arguments(func): argspec = inspect.getargspec(func) if argspec.defaults: positional_args = argspec.args[:-len(argspec.defaults)] keyword_names = argspec.args[-len(argspec.defaults):] for arg, default in zip(keyword_names, argspec.defaults): yield (.for...
Analyze a function's signature and return a data structure suitable for passing in as arguments to an argparse parser's add_argument() method.
368,471
def approve(self, creator): self.approved = True self.creator = creator self.save()
Approve granular permission request setting a Permission entry as approved=True for a specific action from an user on an object instance.
368,472
def identical_blocks(self): identical_blocks = [] for (block_a, block_b) in self._block_matches: if self.blocks_probably_identical(block_a, block_b): identical_blocks.append((block_a, block_b)) return identical_blocks
:returns: A list of block matches which appear to be identical
368,473
def call_decorator(cls, func): @wraps(func) def _wrap(self, *args, **kwargs): try: return func(self, *args, **kwargs) except Exception: self.logger.exception() if not (self.catch_child_exception or False): ...
class function that MUST be specified as decorator to the `__call__` method overriden by sub-classes.
368,474
def hierarchical_key(self, s): s = parseable_str(s) for f in [self.bip32_seed, self.bip32_prv, self.bip32_pub, self.electrum_seed, self.electrum_prv, self.electrum_pub]: v = f(s) if v: return v
Parse text as some kind of hierarchical key. Return a subclass of :class:`Key <pycoin.key.Key>`, or None.
368,475
def print_dataset_summary(self): print() print() if self.raw_data_exists: if self.BIDS.get_subjects(): print( + str(len(self.BIDS.get_subjects()))) print( + .join(self.BIDS.get_subjects())) ...
Prints information about the the BIDS data and the files currently selected.
368,476
def try_lock(self, key, ttl=-1, timeout=0): check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(map_try_lock_codec, key_data, invocation_timeout=MAX_SIZE, key=key_data, thread_id=thread_id()...
Tries to acquire the lock for the specified key. When the lock is not available, * If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately. * If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies ...
368,477
def moma(self, wt_fluxes): reactions = set(self._adjustment_reactions()) v = self._v obj_expr = 0 for f_reaction, f_value in iteritems(wt_fluxes): if f_reaction in reactions: obj_expr += (f_value - v[f_reaction])**2 self._pr...
Minimize the redistribution of fluxes using Euclidean distance. Minimizing the redistribution of fluxes using a quadratic objective function. The distance is minimized by minimizing the sum of (wild type - knockout)^2. Args: wt_fluxes: Dictionary of all the wild type fluxes...
368,478
def outer_id(self, value): if value == self._defaults[] and in self._values: del self._values[] else: self._values[] = value
The outer_id property. Args: value (int). the property value.
368,479
def _fill_scope_refs(name, scope): symbol = scope.resolve(name) if symbol is None: return orig_scope = symbol.scope scope.refs[name] = orig_scope while scope is not orig_scope: scope = scope.get_enclosing_scope() scope.refs[name] = or...
Put referenced name in 'ref' dictionary of a scope. Walks up the scope tree and adds the name to 'ref' of every scope up in the tree until a scope that defines referenced name is reached.
368,480
def aggregate(self, query): if isinstance(query, AggregateRequest): has_schema = query._with_schema has_cursor = bool(query._cursor) cmd = [self.AGGREGATE_CMD, self.index_name] + query.build_args() elif isinstance(query, Cursor): has_schema = Fals...
Issue an aggregation query ### Parameters **query**: This can be either an `AggeregateRequest`, or a `Cursor` An `AggregateResult` object is returned. You can access the rows from its `rows` property, which will always yield the rows of the result
368,481
def pretty_plot_two_axis(x, y1, y2, xlabel=None, y1label=None, y2label=None, width=8, height=None, dpi=300): import palettable.colorbrewer.diverging colors = palettable.colorbrewer.diverging.RdYlBu_4.mpl_colors c1 = colors[0] c2 = colors[-1] golden_ratio = (math.sqrt...
Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib examples. Makes it easier to create plots with different axes. Args: x (np.ndarray/list): Data for x-axis. y1 (dict/np.ndarray/list): Data for y1 axis (left). If a dict, it will be interpreted as a {label: se...
368,482
def get_table_location(self, database_name, table_name): table = self.get_table(database_name, table_name) return table[][]
Get the physical location of the table :param database_name: Name of hive database (schema) @table belongs to :type database_name: str :param table_name: Name of hive table :type table_name: str :return: str
368,483
def serializeContainers(self): container_list = [] mvision_container_list = [] for container in self.containers: print("gui: serialize containers : container=", container) container_list.append(container.serialize()) for contai...
Serializes the current view of open video grids (i.e. the view)
368,484
def hashable(x): if isinstance(x, collections.MutableSequence): return tuple(x) elif isinstance(x, collections.MutableMapping): return tuple([(k,v) for k,v in x.items()]) else: return x
Return a hashable version of the given object x, with lists and dictionaries converted to tuples. Allows mutable objects to be used as a lookup key in cases where the object has not actually been mutated. Lookup will fail (appropriately) in cases where some part of the object has changed. Does not (cu...
368,485
def replace(self, to_replace, value=_NoValue, subset=None): if value is _NoValue: if isinstance(to_replace, dict): value = None else: raise TypeError("value argument is required when to_replace is not a dictionary.") def all_of(t...
Returns a new :class:`DataFrame` replacing a value with another value. :func:`DataFrame.replace` and :func:`DataFrameNaFunctions.replace` are aliases of each other. Values to_replace and value must have the same type and can only be numerics, booleans, or strings. Value can have None. Wh...
368,486
def _os_bootstrap(): global _os_stat, _os_getcwd, _os_environ, _os_listdir global _os_path_join, _os_path_dirname, _os_path_basename global _os_sep names = sys.builtin_module_names join = dirname = environ = listdir = basename = None mindirlen = 0 if in names: from...
Set up 'os' module replacement functions for use during import bootstrap.
368,487
def addSignal(self, s): if s.nargs == -1: s.nargs = len([a for a in marshal.genCompleteTypes(s.sig)]) self.signals[s.name] = s self._xml = None
Adds a L{Signal} to the interface
368,488
def _send(self, line): if not line.endswith(): if line.endswith(): logger.debug() line = line[0:-1] + else: logger.debug( ) line = line + logger.debug( + line.rstrip()) self._so...
Write a line of data to the server. Args: line -- A single line of data to write to the socket.
368,489
def save_weights(sess, output_path, conv_var_names=None, conv_transpose_var_names=None): if not conv_var_names: conv_var_names = [] if not conv_transpose_var_names: conv_transpose_var_names = [] for var in tf.trainable_variables(): filename = .format(output_path, var.name.repl...
Save the weights of the trainable variables, each one in a different file in output_path.
368,490
def _read_message(self): size = int(self.buf.read_line().decode("utf-8")) return self.buf.read(size).decode("utf-8")
Reads a single size-annotated message from the server
368,491
def current_user(self): if not hasattr(self, ) or not in self._serverInfo: url = self._get_url() r = self._session.get(url, headers=self._options[]) r_json = json_loads(r) if in r.headers: r_json[] = r.headers[] else: ...
Returns the username of the current user. :rtype: str
368,492
def show_progress(self, message=None): if self.in_progress_hanging: if message is None: sys.stdout.write() sys.stdout.flush() else: if self.last_message: padding = * max(0, len(self.last_message)-len(message)) ...
If we are in a progress scope, and no log messages have been shown, write out another '.
368,493
def _get_tmaster_processes(self): retval = {} tmaster_cmd_lst = [ self.tmaster_binary, % self.topology_name, % self.topology_id, % self.state_manager_connection, % self.state_manager_root, % self.master_host, % str(self.master_port), % ...
get the command to start the tmaster processes
368,494
def put(self, targetId): json = request.get_json() if in json: logger.info( + targetId) if self._targetController.storeFromHinge(targetId, json[]): logger.info( + targetId) return None, 200 else: return None, 5...
stores a new target. :param targetId: the target to store. :return:
368,495
def build_skeleton(nodes, independencies): nodes = list(nodes) if isinstance(independencies, Independencies): def is_independent(X, Y, Zs): return IndependenceAssertion(X, Y, Zs) in independencies elif callable(independencies): is_independent = ...
Estimates a graph skeleton (UndirectedGraph) from a set of independencies using (the first part of) the PC algorithm. The independencies can either be provided as an instance of the `Independencies`-class or by passing a decision function that decides any conditional independency assertion. ...
368,496
def resume_multiple(self, infohash_list): data = self._process_infohash_list(infohash_list) return self._post(, data=data)
Resume multiple paused torrents. :param infohash_list: Single or list() of infohashes.
368,497
def check_password_confirm(self, form, trigger_action_group=None): pwcol = self.options[] pwconfirmfield = pwcol + "_confirm" if pwcol in form and pwconfirmfield in form and form[pwconfirmfield].data != form[pwcol].data: if self.options["password_confirm_failed_message"]: ...
Checks that the password and the confirm password match in the provided form. Won't do anything if any of the password fields are not in the form.
368,498
def write(self, _force=False, _exists_ok=False, **items): if self.fname and self.fname.exists(): raise ValueError() with self.connection() as db: for table in self.tables: db.execute(table.sql(translate=self.translate)) db.execute() ...
Creates a db file with the core schema. :param force: If `True` an existing db file will be overwritten.
368,499
def add_argument(self, *args, **kwargs): if _HELP not in kwargs: for name in args: name = name.replace("-", "") if name in self.__argmap: kwargs[_HELP] = self.__argmap[name] break return super(ArgumentParser, se...
Add an argument. This method adds a new argument to the current parser. The function is same as ``argparse.ArgumentParser.add_argument``. However, this method tries to determine help messages for the adding argument from some docstrings. If the new arguments belong to some sub ...