Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
353,900
def update_state(self, txn, prev_result, is_committed=True) -> None: self._validate_txn_type(txn) attr_type, path, value, hashed_value, value_bytes = domain.prepare_attr_for_state(txn) self.state.set(path, value_bytes) if attr_type != HASH: self.database_manager.attr...
The state trie stores the hash of the whole attribute data at: the did+attribute name if the data is plaintext (RAW) the did+hash(attribute) if the data is encrypted (ENC) If the attribute is HASH, then nothing is stored in attribute store, the trie stores a blank value for the k...
353,901
def SAT_plan(init, transition, goal, t_max, SAT_solver=dpll_satisfiable): "[Fig. 7.22]" for t in range(t_max): cnf = translate_to_SAT(init, transition, goal, t) model = SAT_solver(cnf) if model is not False: return extract_solution(model) return None
[Fig. 7.22]
353,902
def ping(self): with self._db_conn() as conn: affected_rows = conn.query( % self._manager.table_name, datetime.utcnow(), self._lock_id, self._lock_hash) return bool(affected_rows == 1)
Notify the manager that this lock is still active.
353,903
def refresh_files(self): plugins = {} _plugin_files = glob.glob(os.path.join(self.dir_path, )) for f in glob.glob(os.path.join(self.dir_path, )): if not any(os.path.splitext(f)[0] == os.path.splitext(x)[0] for x in _plugin_files): logging....
Discovers the available plugins and turns each into a module object. This is a seperate function to allow plugins to be updated dynamically by other parts of the application.
353,904
def unit_id(self, unit_id=None): if unit_id is None: return self.__unit_id if 0 <= int(unit_id) < 256: self.__unit_id = int(unit_id) return self.__unit_id else: return None
Get or set unit ID field :param unit_id: unit ID (0 to 255) or None for get value :type unit_id: int or None :returns: unit ID or None if set fail :rtype: int or None
353,905
def fix_spelling(self): if not self.is_tagged(WORDS): self.tokenize_words() text = self.text fixed = vabamorf.fix_spelling(self.word_texts, join=False) spans = self.word_spans assert len(fixed) == len(spans) if len(spans) > 0: newtoks = []...
Fix spelling of the text. Note that this method uses the first suggestion that is given for each misspelled word. It does not perform any sophisticated analysis to determine which one of the suggestions fits best into the context. Returns ------- Text A copy...
353,906
def prebuild_arch(self, arch): path = self.get_build_dir(arch.arch) if not exists(path): info("creating {}".format(path)) shprint(sh.mkdir, , path)
Make the build and target directories
353,907
def _release_version(): with io.open(os.path.join(SETUP_DIRNAME, , ), encoding=) as fh_: exec_locals = {} exec_globals = {} contents = fh_.read() if not isinstance(contents, str): contents = contents.encode() exec(contents, exec_globals, exec_locals) ...
Returns release version
353,908
def mdot(*args): if len(args) < 1: raise ValueError() elif len(args) == 1: return args[0] elif len(args) == 2: return np.dot(args[0], args[1]) else: return np.dot(args[0], mdot(*args[1:]))
Computes a matrix product of multiple ndarrays This is a convenience function to avoid constructs such as np.dot(A, np.dot(B, np.dot(C, D))) and instead use mdot(A, B, C, D). Parameters ---------- *args : an arbitrarily long list of ndarrays that must be compatible for multiplication, i.e....
353,909
def get_concurrency(self): method = endpoint = .format( self.client.sauce_username) return self.client.request(method, endpoint)
Check account concurrency limits.
353,910
def UpdateHunt(hunt_id, client_limit=None, client_rate=None, duration=None): hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED: raise OnlyPausedHuntCanBeModifiedError(hunt_obj) data_store.REL_DB.UpdateHuntObject( hunt_id, client_limit=cli...
Updates a hunt (it must be paused to be updated).
353,911
def StoreRequestsAndResponses(self, new_requests=None, new_responses=None, requests_to_delete=None): to_write = {} if new_requests is not None: for request, timestamp in new_requests: subject = req...
Stores new flow requests and responses to the data store. Args: new_requests: A list of tuples (request, timestamp) to store in the data store. new_responses: A list of tuples (response, timestamp) to store in the data store. requests_to_delete: A list of requests that should be d...
353,912
def parse_xml_node(self, node): self.name = node.getAttributeNS(RTS_NS, ) self.comment = node.getAttributeNS(RTS_EXT_NS, ) if node.hasAttributeNS(RTS_EXT_NS, ): visible = node.getAttributeNS(RTS_EXT_NS, ) if visible.lower() == or visible == : se...
Parse an xml.dom Node object representing a data port into this object.
353,913
def get(cls): if Check().is_url_valid() or PyFunceble.CONFIGURATION["local"]: if "current_test_data" in PyFunceble.INTERN: PyFunceble.INTERN["current_test_data"]["url_syntax_validation"] = True PyFunceble.I...
Execute the logic behind the URL handling. :return: The status of the URL. :rtype: str
353,914
def members(self): if self._members is None: self._members = Feed(self.links["members"], pypump=self._pump) return self._members
:class:`Feed <pypump.models.feed.Feed>` of collection members.
353,915
def _create(self, **kwargs): tmos_ver = self._meta_data[]._meta_data[] legacy = kwargs.pop(, False) publish = kwargs.pop(, False) self._filter_version_specific_options(tmos_ver, **kwargs) if LooseVersion(tmos_ver) < LooseVersion(): return super(Policy, self)...
Allow creation of draft policy and ability to publish a draft Draft policies only exist in 12.1.0 and greater versions of TMOS. But there must be a method to create a draft, then publish it. :raises: MissingRequiredCreationParameter
353,916
def make_serviceitem_servicedll(servicedll, condition=, negate=False, preserve_case=False): document = search = content_type = content = servicedll ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, nega...
Create a node for ServiceItem/serviceDLL :return: A IndicatorItem represented as an Element node
353,917
def get_endpoint(self, session, **kwargs): if self.endpoint is None: try: self._refresh_tokens(session) self._fetch_credentials(session) except: raise AuthorizationFailure() return self.endpoint
Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raise...
353,918
def get(self, *, txid, headers=None): block_list = self.transport.forward_request( method=, path=self.path, params={: txid}, headers=headers, ) return block_list[0] if len(block_list) else None
Get the block that contains the given transaction id (``txid``) else return ``None`` Args: txid (str): Transaction id. headers (dict): Optional headers to pass to the request. Returns: :obj:`list` of :obj:`int`: List of block heights.
353,919
def _setup_logger(self, level, log_file): if logger.handlers: return level = getattr(logging, level.upper()) logger.setLevel(level) formatter = logging.Formatter( ) handler = logging.StreamHandler() logger.addHandler(handler) handl...
Setup log level and log file if set
353,920
def mean_otu_pct_abundance(ra, otuIDs): sids = ra.keys() otumeans = defaultdict(int) for oid in otuIDs: otumeans[oid] = sum([ra[sid][oid] for sid in sids if oid in ra[sid]]) / len(sids) * 100 return otumeans
Calculate the mean OTU abundance percentage. :type ra: Dict :param ra: 'ra' refers to a dictionary keyed on SampleIDs, and the values are dictionaries keyed on OTUID's and their values represent the relative abundance of that OTUID in that SampleID. 'ra' is the output of ...
353,921
def list_statements(self, session_id: int) -> List[Statement]: response = self._client.get(f"/sessions/{session_id}/statements") return [ Statement.from_json(session_id, data) for data in response["statements"] ]
Get all the statements in a session. :param session_id: The ID of the session.
353,922
def host_update(hostid, **kwargs): s docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring) :param visible_name: string with visible name of the host, use instead of parameter to not mess with value supplied from Salt s...
.. versionadded:: 2016.3.0 Update existing hosts .. note:: This function accepts all standard host and host.update properties: keyword argument names differ depending on your zabbix version, see the documentation for `host objects`_ and the documentation for `updating hosts`_. ...
353,923
def ip_in_ipmask(ip, ipmask): mask_ip, mask = str_to_ipmask(ipmask) return ip_in_ip_mask(ip, mask_ip, mask)
Checks whether an ip is contained in an ip subnet where the subnet is a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0)
353,924
def get_methodnames(self, node): nodekey = self.get_nodekey(node) prefix = self._method_prefix if isinstance(nodekey, self.GeneratorType): for nodekey in nodekey: yield self._method_prefix + nodekey else: yield self._method_prefix + nodeke...
Given a node, generate all names for matching visitor methods.
353,925
def collect_read_counts(data, work_dir): out_file = os.path.join(work_dir, "%s-target-coverage.hdf5" % dd.get_sample_name(data)) if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: params = ["-T", "CollectReadCounts", "-I", dd.get_align_bam(data), ...
Count reads in defined bins using CollectReadCounts.
353,926
def getRankMap(self): incEdgesMap = self.getIncEdgesMap() sortedKeys = sorted(incEdgesMap.keys(), reverse = True) rankMap = dict() pos = 1 for key in sortedKeys: cands = incEdgesMap[key] for cand in cands: rankMa...
Returns a dictionary that associates the integer representation of each candidate with its position in the ranking, starting from 1.
353,927
def _fit_ellipsoid_full(locations): a = np.hstack([locations*2, locations**2]) lsq = sp.linalg.lstsq(a, np.ones(locations.shape[0])) x = lsq[0] c = -x[:3] / x[3:] gam = 1 + np.sum(x[:3]**2 / x[3:]) r = np.sqrt(gam / x[3:]) return c, r
identify all 6 ellipsoid parametes (center, radii)
353,928
def isthaichar(ch: str) -> bool: ch_val = ord(ch) if ch_val >= 3584 and ch_val <= 3711: return True return False
Check if a character is Thai เป็นอักษรไทยหรือไม่ :param str ch: input character :return: True or False
353,929
def _signalsForInterface(self, context, prefix=, typeTransform=None): sigs = [] if self._interfaces: for intf in self._interfaces: sigs.extend( intf._signalsForInterface(context, prefix, typeTransform=...
generate _sig for each interface which has no subinterface if already has _sig return it instead :param context: instance of RtlNetlist where signals should be created :param prefix: name prefix for created signals :param typeTransform: optional function (type) returns modified type ...
353,930
def is_blank(self, name): for th in themeable._hierarchy[name]: with suppress(KeyError): return self[th].is_blank() return False
Return True if the themeable *name* is blank This if the *name* is not in the list of themeables then the lookup falls back to inheritance hierarchy is considered. If the none of the themeables in the hierary are present, ``False`` will be returned. Parameters ---------...
353,931
def write(self, data): if not hasattr(data, ): data = six.BytesIO(data) self.jfs.up(self.path, data)
Put, possibly replace, file contents with (new) data
353,932
def distance(p1, p2): return sum((a - b) ** 2 for a, b in zip(p1, p2)) ** 0.5
Computes and returns the distance between two points, `p1` and `p2`. The points can have any number of components.
353,933
def token(cls: Type[OperatorType], keyword: str) -> OperatorType: op = cls(keyword) return op
Return Operator instance from keyword :param keyword: Operator keyword in expression :return:
353,934
def export_txt(cls, feed): objects = cls.objects.in_feed(feed) if not objects.exists(): return column_map = objects.populated_column_map() columns, fields = zip(*column_map) extra_columns = feed.meta.get( , {}).get(cls.__name__...
Export records as a GTFS comma-separated file
353,935
def _merge_derived_parameters(self, other_trajectory, used_runs, rename_dict, allowed_translations, ignore_data): other_der...
Merges derived parameters that have the `run_ALL` in a name. Creates a new parameter with the name of the first new run and links to this parameter to avoid copying in all other runs.
353,936
def l_endian(v): w = struct.pack(, v) return str(binascii.hexlify(w), encoding=)
小端序
353,937
def get_gml_url(self, qi_type, band=): band = band.split()[-1] return self.get_qi_url(.format(qi_type, band))
:param qi_type: type of quality indicator :type qi_type: str :param band: band name :type band: str :return: location of gml file on AWS :rtype: str
353,938
def merge_record_extra(record, target, reserved): for key, value in record.__dict__.items(): if (key not in reserved and not (hasattr(key, "startswith") and key.startswith())): target[key] = value return target
Merges extra attributes from LogRecord object into target dictionary :param record: logging.LogRecord :param target: dict to update :param reserved: dict or list with reserved keys to skip
353,939
def generate_date_tail_boost_queries( field, timedeltas_and_boosts, relative_to=None): relative_to = relative_to or datetime.datetime.now() times = {} for timedelta, boost in timedeltas_and_boosts.items(): date = (relative_to - timedelta).date() times[date] = boost times = s...
Generate a list of RangeQueries usable to boost the scores of more recent documents. Example: ``` queries = generate_date_tail_boost_queries("publish_date", { timedelta(days=90): 1, timedelta(days=30): 2, timedelta(days=10): 4, }) s = Search(BoolQuery(must=....
353,940
def accuracy_gain(self): r if self.population() == 0: return float() random_accuracy = (self.cond_pos_pop() / self.population()) ** 2 + ( self.cond_neg_pop() / self.population() ) ** 2 return self.accuracy() / random_accuracy
r"""Return gain in accuracy. The gain in accuracy is defined as: :math:`G(accuracy) = \frac{accuracy}{random~ accuracy}` Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval) Returns ------- float The gain in accuracy of the confusion table ...
353,941
def get_seconds(self): parsed = self.parse_hh_mm_ss() total_seconds = parsed.second total_seconds += parsed.minute * 60.0 total_seconds += parsed.hour * 60.0 * 60.0 return total_seconds
Gets seconds from raw time :return: Seconds in time
353,942
def upload_as_text(name, filename): location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.upload(filename=filename, as_type=)
Upload the IPList as text from a file. :param str name: name of IPList :param str filename: name of text file to upload :return: None
353,943
def from_blob(self, blob, store=current_store, extra_args=None, extra_kwargs=None): data = io.BytesIO(blob) return self.from_raw_file(data, store, original=True, extra_args=extra_args, extra_kwargs=extra_kwarg...
Stores the ``blob`` (byte string) for the image into the ``store``. :param blob: the byte string for the image :type blob: :class:`str` :param store: the storage to store the image data. :data:`~sqlalchemy_imageattach.context.current_store` by...
353,944
def _generate_game_object(cls, soup, timestamp, game_number): game = Game(timestamp) game.game_type = MlbamUtil.get_attribute(soup.game, , unknown=MlbamConst.UNKNOWN_SHORT) game.game_type_des = cls._get_game_type_des(game.game_type) game.st_fl = cls._get_st_fl(game.gam...
get game data :param soup: Beautifulsoup object :param timestamp: game day :param game_number: game number :return: pitchpx.game.game.Game object
353,945
def copy(src, dst): try: shutil.copytree(src, dst) except OSError as exc: if exc.errno == errno.ENOTDIR: shutil.copy(src, dst) else: raise
Handle the copying of a file or directory. The destination basedir _must_ exist. :param src: A string containing the path of the source to copy. If the source ends with a '/', will become a recursive directory copy of source. :param dst: A string containing the path to the destination. If the ...
353,946
def serialize_dict(self, msg_dict): serialized = json.dumps(msg_dict, namedtuple_as_object=False) if PY2: serialized = serialized.decode("utf-8") serialized = "{}\nend\n".format(serialized) return serialized
Serialize to JSON a message dictionary.
353,947
def rename_to_tmp_name(self): self.client.rename( self.id, % (self.short_id, self.name) )
Rename the container to a hopefully unique temporary container name by prepending the short id.
353,948
def _substitute(self, str): if not self.attr.get("substitute",True):return str return self._regex.sub(lambda mo: self._reflections[mo.string[mo.start():mo.end()]], str.lower())
Substitute words in the string, according to the specified reflections, e.g. "I'm" -> "you are" :type str: str :param str: The string to be mapped :rtype: str
353,949
def auth_user_db(self, username, password): if username is None or username == "": return None user = self.find_user(username=username) if user is None: user = self.find_user(email=username) if user is None or (not user.is_active): log.info(LO...
Method for authenticating user, auth db style :param username: The username or registered email address :param password: The password, will be tested against hashed password on db
353,950
def _add_arg(self, key, value, mask=False): if self.lang == : self._add_arg_python(key, value, mask) elif self.lang == : self._add_arg_java(key, value, mask)
Add CLI Arg for the correct language. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob). mask (boolean, default:False): Indicates whether no mask value.
353,951
def update(self): x, y = mouse() if self.show_grid: x, y = self.grid.snap(x, y) if _ctx._ns["mousedown"] \ and not self.freehand: self._dirty = True ...
Update runs each frame to check for mouse interaction. Alters the path by allowing the user to add new points, drag point handles and move their location. Updates are automatically stored as SVG in the given filename.
353,952
async def status_by_zip(self, zip_code: str) -> dict: try: location = next(( d for d in await self.user_reports() if d[] == zip_code)) except StopIteration: return {} return await self.status_by_coordinates( float(loca...
Get symptom data for the provided ZIP code.
353,953
def get_public_inline_preview_url(self, id, submission_id=None): path = {} data = {} params = {} path["id"] = id if submission_id is not None: params["submission_id"] = submission_id self.logger.debu...
Get public inline preview url. Determine the URL that should be used for inline preview of the file.
353,954
def task_with_callable(the_callable, label=None, schedule=DEFAULT_SCHEDULE, userdata=None, pk_override=None): task = Task() if isinstance(the_callable, str): if pk_override is not None: components = the_callable.split() info = dict( func_type=, ...
Factory function to create a properly initialized task.
353,955
def get_phrases(text=None, tokens=None, postags=None, tagger=, grammar=, regex=None, minlen=2, maxlen=8, output=): global SimpleNP if postags is None: try: tagger = TAGGER_NAMES[tagger]() except: raise Exception("We dons one of our wrapper *Tagger objects d = None if tokens is not ...
Give a text (or POS tag sequence), return the phrases matching the given grammar. Works on documents or sentences. Returns a dict with one or more keys with the phrase information. text: the text of the document. If supplied, we will try to POS tag it. You can also do your own tokenzation and/or tagging and sup...
353,956
def pypi_module_version_is_available(module, version): "Check whether module==version is available on pypi" try: cmd = f"pip install {module}==" result = subprocess.run(cmd.split(), shell=False, check=False, stdout=subprocess.PIPE, stderr=subproces...
Check whether module==version is available on pypi
353,957
def execute(self, i, o): self.set_style("question", fg="blue") if self.needs_config and not self.resolver: self._handle_config(self.option("config")) return self.handle()
Executes the command.
353,958
def move(self, from_path, to_path, **kwargs): data = { : from_path, : to_path, } return self._request(, , data=data, **kwargs)
移动单个文件或目录. :param from_path: 源文件/目录在网盘中的路径(包括文件名)。 .. warning:: * 路径长度限制为1000; * 径中不能包含以下字符:``\\\\ ? | " > < : *``; * 文件名或路径名开头结尾不能是 ``.`` 或空白字符,空白字符包括: ...
353,959
def get_sqlite_core(connection_string, *, cursor_factory=None, edit_connection=None): import sqlite3 as sqlite def opener(): cn = sqlite.connect(connection_string) if cursor_factory: cn.row_factory = cursor_factory if edit_connection: edit_connection(cn) return cn return Inje...
Creates a simple SQLite3 core.
353,960
def formfields_for_xmlobject(model, fields=None, exclude=None, widgets=None, options=None, declared_subforms=None, max_num=None, extra=None): fieldlist = getattr(options, , None) if isinstance(fields, ParsedFieldList): fieldlist = fields elif fields is not None: field...
Returns three sorted dictionaries (:class:`django.utils.datastructures.SortedDict`). * The first is a dictionary of form fields based on the :class:`~eulxml.xmlmap.XmlObject` class fields and their types. * The second is a sorted dictionary of subform classes for any fields of type :class:`~eulx...
353,961
def _evaluate_lookup(self, key, value, negated, db): results = {} for record_key, record_value in db.items(): match = True stripped_key, lookup_class = self._extract_lookup(key) lookup = lookup_class(record_value[stripped_key], value) if negated...
Extract values from DB that match the given criteria
353,962
def update_recurring_item(self, recurring_item_id, recurring_item_dict): return self._create_put_request( resource=RECURRING_ITEMS, billomat_id=recurring_item_id, send_data=recurring_item_dict )
Updates a recurring item :param recurring_item_id: the recurring item id :param recurring_item_dict: dict :return: dict
353,963
def flush_stdout(self): try: contents = self.stdout_interceptor.flush_all() except Exception: return if len(contents) > 0: self.body.append(render_texts.preformatted_text(contents)) self._last_update_time = time.time() return con...
Empties the standard out redirect buffer and renders the contents to the body as a preformatted text box.
353,964
def ConvCnstrMODMaskOptionsDefaults(method=): dflt = copy.deepcopy(ccmodmsk_class_label_lookup(method).Options.defaults) if method == : dflt.update({: 1, : {: 1.2, : 50}}) else: dflt.update({: 1, : {: 10, : False, : 10.0, ...
Get defaults dict for the ConvCnstrMODMask class specified by the ``method`` parameter.
353,965
def contains(self, pat): check_type(pat, str) return _series_bool_result(self, weld_str_contains, pat=pat)
Test if pat is included within elements. Parameters ---------- pat : str Returns ------- Series
353,966
def memory_read8(self, addr, num_bytes, zone=None): return self.memory_read(addr, num_bytes, zone=zone, nbits=8)
Reads memory from the target system in units of bytes. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_bytes (int): number of bytes to read zone (str): memory zone to read from Returns: List of bytes read from the ...
353,967
def predicatesOut(G: Graph, n: Node) -> Set[TriplePredicate]: return {p for p, _ in G.predicate_objects(n)}
predicatesOut(G, n) is the set of predicates in arcsOut(G, n).
353,968
def download(url): filepath = get_file(fname=, origin=url, extract=True) base_dir = os.path.dirname(filepath) weights_file = os.path.join(base_dir, ) params_file = os.path.join(base_dir, ) preprocessor_file = os.path.join(base_dir, ) return weights_file, params_file, preprocessor_file
Download a trained weights, config and preprocessor. Args: url (str): target url.
353,969
def pdf_from_writer(writer: Union[PdfFileWriter, PdfFileMerger]) -> bytes: memfile = io.BytesIO() writer.write(memfile) memfile.seek(0) return memfile.read()
Extracts a PDF (as binary data) from a PyPDF2 writer or merger object.
353,970
def set_allowed_domains(self, allowed_domains): if allowed_domains is not None: allowed_domains = tuple(allowed_domains) self._allowed_domains = allowed_domains
Set the sequence of allowed domains, or None.
353,971
def _proxy(self): if self._context is None: self._context = CompositionContext(self._version, sid=self._solution[], ) return self._context
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: CompositionContext for this CompositionInstance :rtype: twilio.rest.video.v1.composition.CompositionContext
353,972
def argsort2(indexable, key=None, reverse=False): if isinstance(indexable, dict): vk_iter = ((v, k) for k, v in indexable.items()) else: vk_iter = ((v, k) for k, v in enumerate(indexable)) if key is None: indices = [k for v, k in sorted(vk_iter, reverse=reverse)] e...
Returns the indices that would sort a indexable object. This is similar to np.argsort, but it is written in pure python and works on both lists and dictionaries. Args: indexable (list or dict): indexable to sort by Returns: list: indices: list of indices such that sorts the indexable ...
353,973
def unwrap(self, value): globs = value.split(, 1) if globs[0].split(, 1)[0] == self.name: return globs[-1] else: return value
A helper method for unwrapping the loaderplugin fragment out of the provided value (typically a modname) and return it. Note that the filter chaining is very implementation specific to each and every loader plugin and their specific toolchain, so this default implementation is not going...
353,974
def flush(): flush_future = concurrent.Future() if _batch_future and not _batch_future.done(): LOGGER.debug() _flush_wait(flush_future, _batch_future) else: LOGGER.info(, _pending_measurements()) _flush_wait(flush_future, _write_measurements()) re...
Flush all pending measurements to InfluxDB. This will ensure that all measurements that are in the buffer for any database are written. If the requests fail, it will continue to try and submit the metrics until they are successfully written. :rtype: :class:`~tornado.concurrent.Future`
353,975
def onebyone(transform, loglikelihood, parameter_names, prior, start = 0.5, ftol=0.1, disp=0, nsteps=40000, parallel=False, find_uncertainties=False, **args): def minfunc(cube): cube = numpy.array(cube) if (cube <= 1e-10).any() or (cube >= 1-1e-10).any(): return 1e100 params = transform(cube) l = logli...
**Convex optimization based on Brent's method** A strict assumption of one optimum between the parameter limits is used. The bounds are narrowed until it is found, i.e. the likelihood function is flat within the bounds. * If optimum outside bracket, expands bracket until contained. * Thus guaranteed to return lo...
353,976
def get_tags(ctx, archive_name): _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(.join(var.get_tags()), nl=False) print()
Print tags assigned to an archive
353,977
def intelligently_find_filenames(line, TeX=False, ext=False, commas_okay=False): files_included = [] if commas_okay: valid_for_filename = else: valid_for_filename = if ext: valid_for_filename += if TeX: valid_for_filename +=...
Intelligently find filenames. Find the filename in the line. We don't support all filenames! Just eps and ps for now. :param: line (string): the line we want to get a filename out of :return: filename ([string, ...]): what is probably the name of the file(s)
353,978
def read_csv(user_id, records_path, antennas_path=None, attributes_path=None, recharges_path=None, network=False, duration_format=, describe=True, warnings=True, errors=False, drop_duplicates=False): antennas = None if antennas_path is not None: try: with open...
Load user records from a CSV file. Parameters ---------- user_id : str ID of the user (filename) records_path : str Path of the directory all the user files. antennas_path : str, optional Path of the CSV file containing (place_id, latitude, longitude) values. This...
353,979
def formatted(self): ret = "Statistics (times in seconds, lengths in Bytes):\n" if self.enabled: snapshot = sorted(self.snapshot(), key=lambda item: item[1].avg_time, reverse=True) ...
Return a human readable string with the statistics for this container. The operations are sorted by decreasing average time. The three columns for `ServerTime` are included only if the WBEM server has returned WBEM server response times. Example if statistics are enabled:: ...
353,980
def byteToInt(byte): if hasattr(byte, ): return byte return ord(byte) if hasattr(byte, ) else byte[0]
byte -> int Determines whether to use ord() or not to get a byte's value.
353,981
def blob(self): atom_str = ",".join(str(number) for number in self.numbers) edge_str = ",".join("%i_%i_%i" % (i, j, o) for (i, j), o in zip(self.edges, self.orders)) return "%s %s" % (atom_str, edge_str)
A compact text representation of the graph
353,982
def _log_response(response): message = u.format( response.status_code, response.text ) if response.status_code >= 400: logger.warning(message) else: logger.debug(message)
Log out information about a ``Request`` object. After calling ``requests.request`` or one of its convenience methods, the object returned can be passed to this method. If done, information about the object returned is logged. :return: Nothing is returned.
353,983
def start_scheduler(self): t = InfiniteLoopThread( func=self.schedule_next_job, thread_name="SCHEDULER", wait_between_runs=0.5) t.start() return t
Start the scheduler thread. This thread reads the queue of jobs to be scheduled and sends them to the workers. Returns: None
353,984
def _is_referenced_in_argv(method_name): expr = .format(method_name) regex = re.compile(expr) return any(regex.match(arg) for arg in sys.argv)
Various test runners allow one to run a specific test like so: python -m unittest -v <test_module>.<test_name> Return True is the given method name is so referenced. :param method_name: Base name of the method to add. :type method_name: `unicode` :return: Is the given m...
353,985
def map_lrepr( entries: Callable[[], Iterable[Tuple[Any, Any]]], start: str, end: str, meta=None, **kwargs, ) -> str: print_level = kwargs["print_level"] if isinstance(print_level, int) and print_level < 1: return SURPASSED_PRINT_LEVEL kwargs = _process_kwargs(**kwargs) ...
Produce a Lisp representation of an associative collection, bookended with the start and end string supplied. The entries argument must be a callable which will produce tuples of key-value pairs. The keyword arguments will be passed along to lrepr for the sequence elements.
353,986
def _get_dtype_maps(): tmp = [ (np.float32, ), (np.float64, ), (np.uint8, ), (np.int8, ), (np.uint16, ), (np.int16, ), (np.uint32, ), (np.int32, ), (np.uint64, ), (np.int64, ) ] map1, map2 = {}, {} for np_type, itk_type in tm...
Get dictionaries to map numpy data types to ITK types and the other way around.
353,987
def _get_available_extensions(): extensions = [] parsers_dir = os.path.join(os.path.dirname(__file__)) glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py") ext_re = re.compile(glob_filename.replace(, "(?P<ext>\w+)")) for filename in glob.glob(glob_filename): e...
Get a list of available file extensions to make it easy for tab-completion and exception handling.
353,988
def _ircounts2radiance(counts, scale, offset): rad = (counts - offset) / scale return rad.clip(min=0)
Convert IR counts to radiance Reference: [IR]. Args: counts: Raw detector counts scale: Scale [mW-1 m2 cm sr] offset: Offset [1] Returns: Radiance [mW m-2 cm-1 sr-1]
353,989
def evaluate(args): from jcvi.formats.sizes import Sizes p = OptionParser(evaluate.__doc__) p.add_option("--query", help="Chromosome location [default: %default]") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) prediction, reality...
%prog evaluate prediction.bed reality.bed fastafile Make a truth table like: True False --- Reality True TP FP False FN TN |----Prediction Sn = TP / (all true in reality) = TP / (TP + FN) Sp = TP / (all true in prediction) = TP / (TP + FP) Ac = (TP + TN) / (...
353,990
def replay_config(self, switch_ip): LOG.debug("Replaying config for switch ip %(switch_ip)s", {: switch_ip}) try: self._initialize_trunk_interfaces_to_none(switch_ip) except Exception: return nve_bindings = n...
Sends pending config data in OpenStack to Nexus.
353,991
def list_types(pdb_list, sleep_time=.1): proteincrisprproteinproteinproteinproteinprotein if len(pdb_list)*sleep_time > 30: warnings.warn("Because of API limitations, this function\ will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\ If you need grea...
Given a list of PDB IDs, look up their associated structure type Parameters ---------- pdb_list : list of str List of PDB IDs sleep_time : float Time (in seconds) to wait between requests. If this number is too small the API will stop working, but it appears to vary a...
353,992
def to_string_short(self): if hasattr(self, ) and len(self.constrained_by) > 0: return "* {:>30}: {}".format(self.uniquetwig_trunc, self.get_quantity() if hasattr(self, ) else self.get_value()) else: return "{:>32}: {}".format(self.uniquetwig_trunc, self.get_quantity() i...
see also :meth:`to_string` :return: a shorter abreviated string reprentation of the parameter
353,993
def logger(name=None, save=False): logger = logging.getLogger(name) if save: logformat = log_file_path = open(log_file_path, ).write() logger.setLevel(logging.DEBUG) logger_handler = logging.FileHandler(log_file_path) logger_handler.setFormatter(loggin...
Init and configure logger.
353,994
def arp(self): xmlns = get_arp_info = ET.Element(, xmlns=xmlns) results = self._callback(get_arp_info, handler=) result = [] for item in results.findall( % xmlns): ip_address = item.find( % xmlns).text mac_address = item.find( % xmlns).text ...
dict: trill link details
353,995
def cyclone( adata, marker_pairs, gene_names, sample_names, iterations=1000, min_iter=100, min_pairs=50): try: from pypairs import __version__ as pypairsversion from distutils.version import LooseVersion if LooseVersion(pypairsver...
Assigns scores and predicted class to observations [Scialdone15]_ [Fechtner18]_. Calculates scores for each observation and each phase and assigns prediction based on marker pairs indentified by sandbag. This reproduces the approach of [Scialdone15]_ in the implementation of [Fechtner18]_. Parame...
353,996
def egress(self, envelope, http_headers, operation, binding_options): if self._logger.isEnabledFor(logging.INFO): service_name = operation.binding.wsdl.services.keys()[0] self._logger.info(_REQUEST_LOG_LINE, service_name, operation.name, binding_options[]) if self._logg...
Overrides the egress function ror request logging. Args: envelope: An Element with the SOAP request data. http_headers: A dict of the current http headers. operation: The SoapOperation instance. binding_options: An options dict for the SOAP binding. Returns: A tuple of the envelo...
353,997
def remove_alias(path): orm.delete(p for p in model.PathAlias if p.path == path) orm.commit()
Remove a path alias. Arguments: path -- the path to remove the alias of
353,998
def from_dict(cls, d): def _lnk(o): return None if o is None else Lnk.charspan(o[], o[]) def _ep(ep): return ElementaryPredication( nodeid=None, pred=Pred.surface_or_abstract(ep[]), label=ep[], args=ep.get(,...
Decode a dictionary, as from :meth:`to_dict`, into an Mrs object.
353,999
def increment(self): for i in xrange(len(self._counter) - 1, -1, -1): self._counter[i] += 1 if self._counter[i] < 256: break self._counter[i] = 0 else: self._counter = [ 0 ] * len(self._counter)
Increment the counter (overflow rolls back to 0).