Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
382,200
def vcf2cytosure(store, institute_id, case_name, individual_id): institute_obj, case_obj = institute_and_case(store, institute_id, case_name) for individual in case_obj[]: if individual[] == individual_id: individual_obj = individual return (individual_obj[], individual_obj[])
vcf2cytosure CGH file for inidividual.
382,201
def get_load_time(self, request_type=None, content_type=None, status_code=None, asynchronous=True, **kwargs): entries = self.filter_entries( request_type=request_type, content_type=content_type, status_code=status_code ) if "async" in kwarg...
This method can return the TOTAL load time for the assets or the ACTUAL load time, the difference being that the actual load time takes asynchronous transactions into account. So, if you want the total load time, set asynchronous=False. EXAMPLE: I want to know the load time for...
382,202
def _invoke(self, arguments, autoescape): rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
This method is being swapped out by the async implementation.
382,203
def _match_item(item, any_all=any, ignore_case=False, normalize_values=False, **kwargs): it = get_item_tags(item) return any_all( _match_field( get_field(it, field), pattern, ignore_case=ignore_case, normalize_values=normalize_values ) for field, patterns in kwargs.items() for pattern in patterns )
Match items by metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: item (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath. any_all (callable): A callable to determine if any or all filters m...
382,204
def to_dict(self, prefix=None): conf_obj = dict(self) return self.__dictify__(conf_obj, prefix)
Converts recursively the Config object into a valid dictionary. :param prefix: A string to optionally prefix all key elements in the returned dictonary.
382,205
async def set_max_ch_setpoint(self, temperature, timeout=OTGW_DEFAULT_TIMEOUT): cmd = OTGW_CMD_SET_MAX status = {} ret = await self._wait_for_cmd(cmd, temperature, timeout) if ret is None: return ret = float(ret) stat...
Set the maximum central heating setpoint. This command is only available with boilers that support this function. Return the newly accepted setpoint, or None on failure. This method is a coroutine
382,206
def show_tip(self, point, tip, wrapped_tiplines): if self.isVisible(): if self.tip == tip: return True else: self.hide() text_edit = self._text_edit cursor = text_edit.textCursor() search_pos = c...
Attempts to show the specified tip at the current cursor location.
382,207
def absent(name, auth=None): ret = {: name, : {}, : True, : } __salt__[](auth) subnet = __salt__[](name=name) if subnet: if __opts__[] is True: ret[] = None ret[] = {: subnet.id} ret[] = return ret ...
Ensure a subnet does not exists name Name of the subnet
382,208
def as_select(self, _items=None, **kwargs): attrs = self.extra.copy() attrs.update(kwargs) attrs[] = self.name if not self.optional: attrs[] = True html = [u % get_html_attrs(attrs)] values = [self.to_string(**attrs)] or [] items = _items or s...
Render the field as a `<select>` element. :param **kwargs: Named paremeters used to generate the HTML attributes of each item. It follows the same rules as `get_html_attrs`
382,209
def get_thunk_env(self, k): if k not in self.__items: raise exceptions.EvaluationError( % (k, self)) x = self.__items[k] env = self.env(self) if isinstance(x, framework.BindableThunk): return x.bind(self.__parent_env), env return x, env
Return the thunk AND environment for validating it in for the given key. There might be different envs in case the thunk comes from a different (composed) tuple. If the thunk needs its environment bound on retrieval, that will be done here.
382,210
def update_module(self, modname, underlined=None): try: pymodule = self.project.get_module(modname) self._add_names(pymodule, modname, underlined) except exceptions.ModuleNotFoundError: pass
Update the cache for global names in `modname` module `modname` is the name of a module.
382,211
def check_model(depth, res, aniso, epermH, epermV, mpermH, mpermV, xdirect, verb): r global _min_res if depth is None: depth = [] depth = _check_var(depth, float, 1, ) if depth.size == 0: depth = np.array([-np.infty, ]) elif depth[0] != -np.infty:...
r"""Check the model: depth and corresponding layer parameters. This check-function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a detailed description of the input parameters. Parameters ---------- depth : list Absolute layer inter...
382,212
def option(self, section, option): if self.config.has_section(section): if self.config.has_option(section, option): return (True, self.config.get(section, option)) return (False, + option + ) return (False, + section + )
Returns the value of the option
382,213
def get_input_info_dict(self, signature=None): return self._spec.get_input_info_dict(signature=signature, tags=self._tags)
Describes the inputs required by a signature. Args: signature: A string with the signature to get inputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_input_info_dict() for the given signature, and the graph variant selected...
382,214
def parse_footnote(document, container, elem): "Parse the footnote element." _rid = elem.attrib[_name()] foot = doc.Footnote(_rid) container.elements.append(foot)
Parse the footnote element.
382,215
def get_relationship(self, from_object, relation_type): for rel in self.relationships.get(relation_type, ()): if rel.from_object is from_object: return rel raise KeyError(relation_type)
return a relation ship or None
382,216
def compact(paths): sep = os.path.sep short_paths = set() for path in sorted(paths, key=len): should_skip = any( path.startswith(shortpath.rstrip("*")) and path[len(shortpath.rstrip("*").rstrip(sep))] == sep for shortpath in short_paths ) if ...
Compact a path set to contain the minimal number of paths necessary to contain all paths in the set. If /a/path/ and /a/path/to/a/file.txt are both in the set, leave only the shorter path.
382,217
def _prepare_find(cls, *args, **kw): cls, collection, query, options = cls._prepare_query( cls.FIND_MAPPING, cls.FIND_OPTIONS, *args, **kw ) if in options: raise TypeError("Await is hard-deprecated as reserved keyword in Python 3.7, use wait instead.") if in options and {, } & ...
Execute a find and return the resulting queryset using combined plain and parametric query generation. Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring.
382,218
def _ensure_someone_took_responsability(self, state, _responses): if not state.so_took_responsability: self.debug( , state.factory.descriptor_type) return self._restart_yourself()
Called as a callback for sending *died* notifications to all the partners. Check if someone has offered to restart the agent. If yes, setup expiration call and wait for report. If no, initiate doing it on our own.
382,219
def put(self, id): try: object_ = json_util.loads(self.request.body) toa = self.request.headers.get("Caesium-TOA", None) obj_check = yield self.client.find_one_by_id(id) if not obj_check: self.raise_error(404, "Resource not ...
Update a resource by bson ObjectId :returns: json string representation :rtype: JSON
382,220
def flavor_delete(self, flavor_id): nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return .format(flavor_id)
Delete a flavor
382,221
def show_network(kwargs=None, call=None): if call != : raise SaltCloudSystemExit( ) if not kwargs or not in kwargs: log.error( ) return False conn = get_conn() return _expand_item(conn.ex_get_network(kwargs[]))
Show the details of an existing network. CLI Example: .. code-block:: bash salt-cloud -f show_network gce name=mynet
382,222
def maintain_leases(self): while self._manager.is_active and not self._stop_event.is_set(): p99 = self._manager.ack_histogram.percentile(99) _LOGGER.debug("The current p99 value is %d seconds.", p99) leased_message...
Maintain all of the leases being managed. This method modifies the ack deadline for all of the managed ack IDs, then waits for most of that time (but with jitter), and repeats.
382,223
def p_IndexTypes(self, p): n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
IndexTypes : IndexTypes ',' IndexType | IndexType
382,224
async def rcpt( self, recipient: str, options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SMTPResponse: await self._ehlo_or_helo_if_needed() if options is None: options = [] options_bytes = [option.encode("ascii") for...
Send an SMTP RCPT command, which specifies a single recipient for the message. This command is sent once per recipient and must be preceded by 'MAIL'. :raises SMTPRecipientRefused: on unexpected server response code
382,225
def load(fileobj): with gzip.GzipFile(fileobj=fileobj, mode=) as z: submission = Submission(metadata=json.loads(z.readline())) for line in z: token_id, token = json.loads(line) submission[][token_id] = token return submission
Load the submission from a file-like object :param fileobj: File-like object :return: the loaded submission
382,226
def _gei8(ins): output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True) output.append() output.append() REQUIRES.add() return output
Compares & pops top 2 operands out of the stack, and checks if the 1st operand >= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 8 bit signed version
382,227
def update_subtask(client, subtask_id, revision, title=None, completed=None): if title is not None: _check_title_length(title, client.api) data = { : int(revision), : title, : completed, } data = { key: value for key, value in data.items() if v...
Updates the subtask with the given ID See https://developer.wunderlist.com/documentation/endpoints/subtask for detailed parameter information
382,228
def _handle_func_decl(self, node, scope, ctxt, stream): self._dlog("handling func decl") if node.args is not None: for param in node.args.params: param.is_func_param = True params = self._handle_node(node.ar...
Handle FuncDecl nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
382,229
def dinfdistdown(np, ang, fel, slp, src, statsm, distm, edgecontamination, wg, dist, workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): in_params = {: % (TauDEM.convertstatsmethod(statsm), ...
Run D-inf distance down to stream
382,230
def update_volumes(self): self.log.debug(.format(self.account.account_name, self.region)) ec2 = self.session.resource(, region_name=self.region) try: existing_volumes = EBSVolume.get_all(self.account, self.region) volumes = {x.id: x for x in ec2.volumes.all()} ...
Update list of EBS Volumes for the account / region Returns: `None`
382,231
def get_unicode_from_response(r): warnings.warn(( ), DeprecationWarning) tried_encodings = [] encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: trie...
Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str
382,232
def all_to_public(self): if "private" not in self.modifiers: def public_collection(attribute): for key in self.collection(attribute): if key not in self.publics: self.publics[key.lower()] = 1 public_collection("members"...
Sets all members, types and executables in this module as public as long as it doesn't already have the 'private' modifier.
382,233
def output(self, _filename): txt = "" for c in self.contracts: (name, _inheritance, _var, func_summaries, _modif_summaries) = c.get_summary() txt += blue("\n+ Contract %s\n"%name) public = [(elem[0], (elem[1], elem[2]) ) for elem in func_summari...
_filename is not used Args: _filename(string)
382,234
def get_handler_classes(self): handler_classes = [import_string(handler_cls) for handler_cls in settings.MODERNRPC_HANDLERS] if self.protocol == ALL: return handler_classes else: return [cls for cls in handler_classes if cls.protocol in ensure_sequence(self.pro...
Return the list of handlers to use when receiving RPC requests.
382,235
def set_shared_config(cls, config): assert isinstance(config, dict) cls._sharedInstance.config.update(config) if cls._sharedInstance.instance: cls._sharedInstance.instance = None
This allows to set a config that will be used when calling ``shared_blockchain_instance`` and allows to define the configuration without requiring to actually create an instance
382,236
def _create_simulated_annealing_expander(schedule): def _expander(fringe, iteration, viewer): T = schedule(iteration) current = fringe[0] neighbors = current.expand(local_search=True) if viewer: viewer.event(, [current], [neighbors]) if neighbors: ...
Creates an expander that has a random chance to choose a node that is worse than the current (first) node, but that chance decreases with time.
382,237
def generateRecords(self, records): if self.verbosity>0: print , len(records), for record in records: self.generateRecord(record)
Generate multiple records. Refer to definition for generateRecord
382,238
def calculate_checksum_on_stream( f, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM, chunk_size=DEFAULT_CHUNK_SIZE, ): checksum_calc = get_checksum_calculator_by_dataone_designator(algorithm) while True: chunk = f.read(chunk_size) if not chunk: break ch...
Calculate the checksum of a stream. Args: f: file-like object Only requirement is a ``read()`` method that returns ``bytes``. algorithm: str Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``. chunk_size : int Number of bytes to read from the file and add to the checksu...
382,239
def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): super_args = get_Union_params(superclass) if super_args is None: return is_Union(subclass) elif is_Union(subclass): sub_args = get...
Helper for _issubclass_Union.
382,240
def compare_version(value): import re res = re.match(r, str(value).strip()) if not res: return False operator, value, _ = res.groups() value = tuple(int(x) for x in str(value).split()) if len(value) < 3: value += (0,) version = __version_i...
Determines if the provided version value compares with program version. `value` Version comparison string (e.g. ==1.0, <=1.0, >1.1) Supported operators: <, <=, ==, >, >=
382,241
def format_float(value): string = "{:g}".format(value).replace("e+", "e") string = re.sub("e(-?)0*(\d+)", r"e\1\2", string) return string
Modified form of the 'g' format specifier.
382,242
def get_assessment_offered_bank_session(self, proxy): if not self.supports_assessment_offered_bank(): raise errors.Unimplemented() return sessions.AssessmentOfferedBankSession(proxy=proxy, runtime=self._runtime)
Gets the session for retrieving offered assessments to bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentOfferedBankSession) - an ``AssessmentOfferedBankSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFail...
382,243
def all(cls, include_deactivated=False): if include_deactivated: resources = yield cls.view.get(include_docs=True) else: resources = yield cls.active_view.get(include_docs=True) result = [] for resource in resources[]: parent = cls.parent_re...
Get all sub-resources :param include_deactivated: Include deactivated resources in response :returns: list of SubResource instances :raises: SocketError, CouchException
382,244
def config_logging(debug): if debug: logging.basicConfig(level=logging.DEBUG, format=) logging.debug("Debug mode activated") else: logging.basicConfig(level=logging.INFO, format=)
Config logging level output output
382,245
def update_from( self, obj=None, yaml_env=None, yaml_file=None, json_env=None, json_file=None, env_namespace=None, ): if obj: self.update_from_object(obj) if yaml_env: self.up...
Update dict from several sources at once. This is simply a convenience method that can be used as an alternative to making several calls to the various :meth:`~ConfigLoader.update_from_*` methods. Updates will be applied in the order that the parameters are listed below, with e...
382,246
def parse_file_args(file_obj, file_type, resolver=None, **kwargs): metadata = {} opened = False if ( in kwargs and isinstance(kwargs[], dict)): metadata.update(kwargs[]) if util.is_file(file_obj) and file_type is None:...
Given a file_obj and a file_type try to turn them into a file-like object and a lowercase string of file type. Parameters ----------- file_obj: str: if string represents a file path, returns ------------------------------------------- file_obj: an 'rb' opened ...
382,247
def sequence_content_plot (self): data = OrderedDict() for s_name in sorted(self.fastqc_data.keys()): try: data[s_name] = {self.avg_bp_from_range(d[]): d for d in self.fastqc_data[s_name][]} except KeyError: pass ...
Create the epic HTML for the FastQC sequence content heatmap
382,248
async def emitters(self, key, value): while True: await asyncio.sleep(value[].total_seconds()) await self.channel_layer.send(key, { "type": value[], "message": value[] })
Single-channel emitter
382,249
def add_edge(self, x, y, label=None): self.adjacency_list[x].append((y, label)) if x not in self.reverse_list[y]: self.reverse_list[y].append(x)
Add an edge from distribution *x* to distribution *y* with the given *label*. :type x: :class:`distutils2.database.InstalledDistribution` or :class:`distutils2.database.EggInfoDistribution` :type y: :class:`distutils2.database.InstalledDistribution` or :class:`...
382,250
def dump_simulation(simulation, directory): parent_directory = os.path.abspath(os.path.join(directory, os.pardir)) if not os.path.isdir(parent_directory): os.mkdir(parent_directory) if not os.path.isdir(directory): os.mkdir(directory) if os.listdir(directory): raise Value...
Write simulation data to directory, so that it can be restored later.
382,251
def received_char_count(self, count): n1 = count/100 n2 = (count-(n1*100))/10 n3 = (count-((n1*100)+(n2*10))) self.send(+chr(n1)+chr(n2)+chr(n3))
Set recieved char count limit Args: count: the amount of received characters you want to stop at. Returns: None Raises: None
382,252
def requestAvatar(self, avatarId, mind, *interfaces): if IBoxReceiver in interfaces: return (IBoxReceiver, Adder(avatarId), lambda: None) raise NotImplementedError()
Create Adder avatars for any IBoxReceiver request.
382,253
def sign(self, pkey, digest): if pkey._only_public: raise ValueError("Key has only public part") if not pkey._initialized: raise ValueError("Key is uninitialized") digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if digest_obj == _ffi.NULL: ...
Sign the certificate request with this key and digest type. :param pkey: The private key to sign with. :type pkey: :py:class:`PKey` :param digest: The message digest to use. :type digest: :py:class:`bytes` :return: ``None``
382,254
def __patch_write_method(tango_device_klass, attribute): write_method = getattr(attribute, "fset", None) if write_method: method_name = "__write_{0}__".format(attribute.attr_name) attribute.write_method_name = method_name else: method_name = attribute.write_method_name w...
Checks if method given by it's name for the given DeviceImpl class has the correct signature. If a read/write method doesn't have a parameter (the traditional Attribute), then the method is wrapped into another method which has correct parameter definition to make it work. :param tango_device_klass...
382,255
def fix_text_segment(text, *, fix_entities=, remove_terminal_escapes=True, fix_encoding=True, fix_latin_ligatures=True, fix_character_width=True, uncurl_quotes=True, ...
Apply fixes to text in a single chunk. This could be a line of text within a larger run of `fix_text`, or it could be a larger amount of text that you are certain is in a consistent encoding. See `fix_text` for a description of the parameters.
382,256
def _validate_certificate_url(self, cert_url): parsed_url = urlparse(cert_url) protocol = parsed_url.scheme if protocol.lower() != CERT_CHAIN_URL_PROTOCOL.lower(): raise VerificationException( "Signature Certificate URL has invalid protocol: {}. " ...
Validate the URL containing the certificate chain. This method validates if the URL provided adheres to the format mentioned here : https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#cert-verify-signature-certificate-url :param cert_url: URL for r...
382,257
def get_jwt_value(self, request): from django.utils.encoding import smart_text from django.utils.translation import ugettext as _ from rest_framework import exceptions auth = self.get_authorization(request).split() auth_header_prefix = self.prefix.lower() or i...
This function has been overloaded and it returns the proper JWT auth string. Parameters ---------- request: HttpRequest This is the request that is received by DJango in the view. Returns ------- str This returns the extracted JWT auth toke...
382,258
def delete(filething): t = OggSpeex(filething) filething.fileobj.seek(0) t.delete(filething)
delete(filething) Arguments: filething (filething) Raises: mutagen.MutagenError Remove tags from a file.
382,259
def from_github(user_repo_pair, file=): "build and use a file (default ) from github repo" from urllib.request import urlopen url = .format( user_repo_pair, file) with utils.catch_and_die([Exception], debug=url): resp = urlopen(url) plashstr = resp.read() return utils.run_write_r...
build and use a file (default 'plashfile') from github repo
382,260
def get_trend(timeseries): last = timeseries[][len(timeseries[]) - 1] prev = timeseries[][len(timeseries[]) - 2] trend = last - prev trend_percentage = None if last == 0: if prev > 0: trend_percentage = -100 else: trend_percentage = 0 else: ...
Using the values returned by get_timeseries(), compare the current Metric value with it's previous period's value :param timeseries: data returned from the get_timeseries() method :returns: the last period value and relative change
382,261
def dt_month_name(x): import pandas as pd return pd.Series(_pandas_dt_fix(x)).dt.month_name().values.astype(str)
Returns the month names of a datetime sample in English. :returns: an expression containing the month names extracted from a datetime column. Example: >>> import vaex >>> import numpy as np >>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetim...
382,262
def badge(left_text: str, right_text: str, left_link: Optional[str] = None, right_link: Optional[str] = None, whole_link: Optional[str] = None, logo: Optional[str] = None, left_color: str = , right_color: str = , measurer: Optional[text_measurer.TextMeasurer] = None, em...
Creates a github-style badge as an SVG image. >>> badge(left_text='coverage', right_text='23%', right_color='red') '<svg...</svg>' >>> badge(left_text='build', right_text='green', right_color='green', ... whole_link="http://www.example.com/") '<svg...</svg>' Args: left_text: The ...
382,263
def is_module_reloadable(self, module, modname): if self.has_cython: return False else: if (self.is_module_in_pathlist(module) or self.is_module_in_namelist(modname)): return False else: return ...
Decide if a module is reloadable or not.
382,264
def get_args(stream_spec, overwrite_output=False): nodes = get_stream_spec_nodes(stream_spec) args = [] sorted_nodes, outgoing_edge_maps = topo_sort(nodes) input_nodes = [node for node in sorted_nodes if isinstance(node, InputNode)] output_nodes = [node for node in sorted_nodes if isinstan...
Build command-line arguments to be passed to ffmpeg.
382,265
def ids(self): if config().identifiers() == : ids = self._id_todo_map.keys() else: ids = [str(i + 1) for i in range(self.count())] return set(ids)
Returns set with all todo IDs.
382,266
def prt_gos_flat(self, prt): prtfmt = self.datobj.kws[] _go2nt = self.sortobj.grprobj.go2nt go2nt = {go:_go2nt[go] for go in self.go2nt} prt.write("\n{N} GO IDs:\n".format(N=len(go2nt))) _sortby = self._get_sortgo() for ntgo in sorted(go2nt.values(), key=_sortby)...
Print flat GO list.
382,267
def leave_module(self, node): assert len(self._to_consume) == 1 not_consumed = self._to_consume.pop().to_consume if "__all__" in node.locals: self._check_all(node, not_consumed) self._check_globals(not_consumed) if not self.config...
leave module: check globals
382,268
def insert_image(filename, extnum_filename, auximage, extnum_auximage): with fits.open(auximage) as hdulist: newimage = hdulist[extnum_auximage].data hdulist = fits.open(filename, mode=) oldimage_shape = hdulist[extnum_filename].data.shape if oldimage_shape == newimage.shape: ...
Replace image in filename by another image (same size) in newimage. Parameters ---------- filename : str File name where the new image will be inserted. extnum_filename : int Extension number in filename where the new image will be inserted. Note that the first extension is 1 (a...
382,269
def cli(obj, role, scopes, delete): client = obj[] if delete: client.delete_perm(delete) else: if not role: raise click.UsageError() if not scopes: raise click.UsageError() try: perm = client.create_perm(role, scopes) except Ex...
Add or delete role-to-permission lookup entry.
382,270
def tags(self): if self._tags is None: config = global_config() self._tags = self.create(Tags, config=config) return self._tags
Return a thread local :class:`dossier.web.Tags` client.
382,271
def _get_content_type(self, content_type, filename=None): if content_type is None: content_type = self.content_type if content_type is None and filename is not None: content_type, _ = mimetypes.guess_type(filename) if content_type is None: content_t...
Determine the content type from the current object. The return value will be determined in order of precedence: - The value passed in to this method (if not :data:`None`) - The value stored on the current blob - The default value ('application/octet-stream') :type content_type...
382,272
def copy_memory(self, address, size): start_time = time.time() map_bytes = self._cpu._raw_read(address, size) self._emu.mem_write(address, map_bytes) if time.time() - start_time > 3: logger.info(f"Copying {hr_size(size)} map at {hex(address)} took {time.time() - star...
Copy the bytes from address to address+size into Unicorn Used primarily for copying memory maps :param address: start of buffer to copy :param size: How many bytes to copy
382,273
def create_marker_table(self): if self.marker_table is None: self.marker_table = luigi.configuration.get_config().get(, , ) engine = self.engine with engine.begin() as con: metadata = sqlalchemy.MetaData() if not con.dialect.has_table(con, self.mark...
Create marker table if it doesn't exist. Using a separate connection since the transaction might have to be reset.
382,274
def list2key(self, keyList): for keyCombo in keyList: if not (isinstance(keyCombo, list) or isinstance(keyCombo, tuple)): msg = ( ) raise QtmacsKeysequenceError(msg) if len(keyCombo) != 2: msg = ...
Convert a list of (``QtModifier``, ``QtCore.Qt.Key_*``) tuples into a key sequence. If no error is raised, then the list was accepted. |Args| * ``keyList`` (**list**): eg. (QtCore.Qt.ControlModifier, QtCore.Qt.Key_F). |Returns| **None** |Raises| ...
382,275
def rev_reg_id2cred_def_id__tag(rr_id: str) -> (str, str): return ( .join(rr_id.split()[2:-2]), str(rr_id.split()[-1]) )
Given a revocation registry identifier, return its corresponding credential definition identifier and (stringified int) tag. :param rr_id: revocation registry identifier :return: credential definition identifier and tag
382,276
def export_widgets(self_or_cls, obj, filename, fmt=None, template=None, json=False, json_path=, **kwargs): if fmt not in list(self_or_cls.widgets.keys())+[, None]: raise ValueError("Renderer.export_widget may only export " "registered widg...
Render and export object as a widget to a static HTML file. Allows supplying a custom template formatting string with fields to interpolate 'js', 'css' and the main 'html' containing the widget. Also provides options to export widget data to a json file in the supplied json_path (default...
382,277
def node_transmit(node_id): exp = Experiment(session) what = request_parameter(parameter="what", optional=True) to_whom = request_parameter(parameter="to_whom", optional=True) node = models.Node.query.get(node_id) if node is None: return error_response(error_type="/node/transmit, ...
Transmit to another node. The sender's node id must be specified in the url. As with node.transmit() the key parameters are what and to_whom. However, the values these accept are more limited than for the back end due to the necessity of serialization. If what and to_whom are not specified they w...
382,278
def save_files(self, nodes): metrics = {"Opened": 0, "Cached": 0} for node in nodes: file = node.file if self.__container.get_editor(file): if self.__container.save_file(file): metrics["Opened"] += 1 self.__uncache...
Saves user defined files using give nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool
382,279
def add_extensions(self, extensions): stack = _lib.sk_X509_EXTENSION_new_null() _openssl_assert(stack != _ffi.NULL) stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free) for ext in extensions: if not isinstance(ext, X509Extension): raise ValueError("O...
Add extensions to the certificate signing request. :param extensions: The X.509 extensions to add. :type extensions: iterable of :py:class:`X509Extension` :return: ``None``
382,280
def build_response(content, code=200): response = make_response( jsonify(content), content[] ) response.headers[] = response.headers[] = \ return response
Build response, add headers
382,281
def save_conf(fn=None): if fn is None: fn = cfile() try: os.makedirs(os.path.dirname(fn)) except (OSError, IOError): pass with open(fn, ) as f: yaml.dump(conf, f)
Save current configuration to file as YAML If not given, uses current config directory, ``confdir``, which can be set by INTAKE_CONF_DIR.
382,282
def pause(self, duration_seconds=0, force=False, force_regen_rospec=False): logger.debug(, duration_seconds) if self.state != LLRPClient.STATE_INVENTORYING: if not force: logger.info(, self.getStateName(self.state)) return ...
Pause an inventory operation for a set amount of time.
382,283
def center(self): try: return self._center except AttributeError: pass self._center = Point() return self._center
Center point of the ellipse, equidistant from foci, Point class.\n Defaults to the origin.
382,284
def write(self, notifications): "Connect to the APNS service and send notifications" if not self.factory: log.msg() server, port = ((APNS_SERVER_SANDBOX_HOSTNAME if self.environment == else APNS_SERVER_HOSTNAME), APNS_SERVER_PORT) self.factory = se...
Connect to the APNS service and send notifications
382,285
def redraw_canvas(self): from xdot_parser import XdotAttrParser xdot_parser = XdotAttrParser() canvas = self._component_default() for node in self.nodes: components = xdot_parser.parse_xdot_data( node._draw_ ) canvas.add( *components ) comp...
Parses the Xdot attributes of all graph components and adds the components to a new canvas.
382,286
def _load_candidate_wrapper(self, source_file=None, source_config=None, dest_file=None, file_system=None): return_status = False msg = if source_file and source_config: raise ValueError("Cannot simultaneously set source_file and source_config...
Transfer file to remote device for either merge or replace operations Returns (return_status, msg)
382,287
def add_info(self, entry): entry = entry[8:-1] info = entry.split() if len(info) < 4: return False for v in info: key, value = v.split(, 1) if key == : self.info[value] = {} id_ = value elif key == :...
Parse and store the info field
382,288
def parse_gtf( filepath_or_buffer, chunksize=1024 * 1024, features=None, intern_columns=["seqname", "source", "strand", "frame"], fix_quotes_columns=["attribute"]): if features is not None: features = set(features) dataframes = [] def parse_frame(s): ...
Parameters ---------- filepath_or_buffer : str or buffer object chunksize : int features : set or None Drop entries which aren't one of these features intern_columns : list These columns are short strings which should be interned fix_quotes_columns : list Most common...
382,289
def remove_not_allowed_chars(savepath): split_savepath = os.path.splitdrive(savepath) savepath_without_invalid_chars = re.sub(r, , split_savepath[1]) return split_savepath[0] + savepath_without_invalid_chars
Removes invalid filepath characters from the savepath. :param str savepath: the savepath to work on :return str: the savepath without invalid filepath characters
382,290
def _get_scsi_controller_key(bus_number, scsi_ctrls): keys = [ctrl.key for ctrl in scsi_ctrls if scsi_ctrls and ctrl.busNumber == bus_number] if not keys: raise salt.exceptions.VMwareVmCreationError( t exist'.format(bus_number)) return keys[0]
Returns key number of the SCSI controller keys bus_number Controller bus number from the adapter scsi_ctrls List of SCSI Controller objects (old+newly created)
382,291
def quantize(image, bits_per_channel=None): if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) << shift) + halfbin
Reduces the number of bits per channel in the given image.
382,292
def peek(init, exposes, debug=False): def _peek(store, container, _stack=None): args = [ store.peek(objname, container, _stack=_stack) \ for objname in exposes ] if debug: print(args) return init(*args) return _peek
Default deserializer factory. Arguments: init (callable): type constructor. exposes (iterable): attributes to be peeked and passed to `init`. Returns: callable: deserializer (`peek` routine).
382,293
def get_activity_admin_session_for_objective_bank(self, objective_bank_id, proxy): if not self.supports_activity_admin(): raise errors.Unimplemented() return sessions.ActivityAdminSession(objective_bank_id, proxy, self._runtime)
Gets the ``OsidSession`` associated with the activity admin service for the given objective bank. arg: objective_bank_id (osid.id.Id): the ``Id`` of the objective bank arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityAdminSession) - a `...
382,294
def pickle_dumps(inbox): gc.disable() str_ = cPickle.dumps(inbox[0], cPickle.HIGHEST_PROTOCOL) gc.enable() return str_
Serializes the first element of the input using the pickle protocol using the fastes binary protocol.
382,295
def validate_seal(cls, header: BlockHeader) -> None: check_pow( header.block_number, header.mining_hash, header.mix_hash, header.nonce, header.difficulty)
Validate the seal on the given header.
382,296
def extract_images(bs4, lazy_image_attribute=None): if lazy_image_attribute: images = [image[lazy_image_attribute] for image in bs4.select() if image.has_attr(lazy_image_attribute)] else: images = [image[] for image in bs4.select() if image.has_attr()] image_links = [link...
If lazy attribute is supplied, find image url on that attribute :param bs4: :param lazy_image_attribute: :return:
382,297
def assert_equal(first, second, msg_fmt="{msg}"): if isinstance(first, dict) and isinstance(second, dict): assert_dict_equal(first, second, msg_fmt) elif not first == second: msg = "{!r} != {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
Fail unless first equals second, as determined by the '==' operator. >>> assert_equal(5, 5.0) >>> assert_equal("Hello World!", "Goodbye!") Traceback (most recent call last): ... AssertionError: 'Hello World!' != 'Goodbye!' The following msg_fmt arguments are supported: * msg - the defa...
382,298
def cdssequencethreads(self): for i in range(self.cpus): threads = Thread(target=self.cdssequence, args=()) threads.setDaemon(True) threads.start() for sample in self.metadata.samples: s...
Extracts the sequence of each gene for each strain
382,299
def get_stats_summary(start=None, end=None, **kwargs): return MonthlySummaryReader(start=start, end=end, **kwargs).fetch()
Stats Historical Summary Reference: https://iexcloud.io/docs/api/#stats-historical-summary Data Weighting: ``Free`` Parameters ---------- start: datetime.datetime, default None, optional Start of data retrieval period end: datetime.datetime, default None, optional End of data r...