Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
382,300
def child(self, name=None, **attrs): sub_query = build_query(name, **attrs) query = (, (self.query, sub_query)) obj = UIObjectProxy(self.poco) obj.query = query return obj
Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for more details about the selectors. Args: name: query expression of attribute "name", i.e. the UI elements with ``name`` name will be selected attrs: other query expressio...
382,301
def _post(self, route, data, headers=None, failure_message=None): headers = self._get_headers(headers) response_lambda = ( lambda: requests.post( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) ...
Execute a post request and return the result :param data: :param headers: :return:
382,302
def selectAssemblies(pth, manifest=None): rv = [] if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if manifest: _depNames = set([dep.name for dep in manifest.dependentAssemblies]) for assembly in getAssemblies(pth): if seen.get(assembly.getid().upper(), 0)...
Return a binary's dependent assemblies files that should be included. Return a list of pairs (name, fullpath)
382,303
def add_uid(fastq, cores): uids = partial(append_uids) p = multiprocessing.Pool(cores) chunks = tz.partition_all(10000, read_fastq(fastq)) bigchunks = tz.partition_all(cores, chunks) for bigchunk in bigchunks: for chunk in p.map(uids, list(bigchunk)): for read in chunk: ...
Adds UID:[samplebc cellbc umi] to readname for umi-tools deduplication Expects formatted fastq files with correct sample and cell barcodes.
382,304
def cublasSsbmv(handle, uplo, n, k, alpha, A, lda, x, incx, beta, y, incy): status = _libcublas.cublasSsbmv_v2(handle, _CUBLAS_FILL_MODE[uplo], n, k, ctypes.byref(ctypes.c_float(alpha)), int(A)...
Matrix-vector product for real symmetric-banded matrix.
382,305
def conflict(self, key, **kwargs): try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) message_string = msg....
A helper method that simply raises a validation error.
382,306
def correlation_model(prediction, fm): (_, r_x) = calc_resize_factor(prediction, fm.image_size) fdm = compute_fdm(fm, scale_factor = r_x) return np.corrcoef(fdm.flatten(), prediction.flatten())[0,1]
wraps numpy.corrcoef functionality for model evaluation input: prediction: 2D Matrix the model salience map fm: fixmat Used to compute a FDM to which the prediction is compared.
382,307
def pretty_print(self, as_list=False, show_datetime=True): ppl = [entry.pretty_print(show_datetime) for entry in self.entries] if as_list: return ppl return u"\n".join(ppl)
Return a Unicode string pretty print of the log entries. :param bool as_list: if ``True``, return a list of Unicode strings, one for each entry, instead of a Unicode string :param bool show_datetime: if ``True``, show the date and time of the entries :rtype: string ...
382,308
def random_combination(iterable, nquartets): pool = tuple(iterable) size = len(pool) indices = random.sample(xrange(size), nquartets) return tuple(pool[i] for i in indices)
Random selection from itertools.combinations(iterable, r). Use this if not sampling all possible quartets.
382,309
def to_dict(self): d = {: self.name} if self.visible != True: d[RTS_EXT_NS_YAML + ] = self.visible if self.comment: d[RTS_EXT_NS_YAML + ] = self.comment props = [] for name in self.properties: p = {: name} if self.propertie...
Save this service port into a dictionary.
382,310
def set_typ(self, refobj, typ): try: enum = JB_ReftrackNode.types.index(typ) except ValueError: raise ValueError("The given type %s could not be found in available types: %" % (typ, JB_ReftrackNode.types)) cmds.setAttr("%s.type" % refobj, enum)
Set the type of the given refobj :param refobj: the reftrack node to edit :type refobj: refobj :param typ: the entity type :type typ: str :returns: None :rtype: None :raises: ValueError
382,311
def luns(self): lun_list, smp_list = [], [] if self.ioclass_luns: lun_list = map(lambda l: VNXLun(lun_id=l.lun_id, name=l.name, cli=self._cli), self.ioclass_luns) if self.ioclass_snapshots: smp_list = map(lambda smp: VN...
Aggregator for ioclass_luns and ioclass_snapshots.
382,312
def process_alt(header, ref, alt_str): if "]" in alt_str or "[" in alt_str: return record.BreakEnd(*parse_breakend(alt_str)) elif alt_str[0] == "." and len(alt_str) > 0: return record.SingleBreakEnd(record.FORWARD, alt_str[1:]) elif alt_str[-1] == "." and len(alt_str) > 0: ...
Process alternative value using Header in ``header``
382,313
def select_tasks(self, nids=None, wslice=None, task_class=None): if nids is not None: assert wslice is None tasks = self.tasks_from_nids(nids) elif wslice is not None: tasks = [] for work in self[wslice]: tasks.extend([t for t in ...
Return a list with a subset of tasks. Args: nids: List of node identifiers. wslice: Slice object used to select works. task_class: String or class used to select tasks. Ignored if None. .. note:: nids and wslice are mutually exclusive. If no...
382,314
def stream(self, start_date=values.unset, end_date=values.unset, identity=values.unset, tag=values.unset, limit=None, page_size=None): limits = self._version.read_limits(limit, page_size) page = self.page( start_date=start_date, end_date=end_date, ...
Streams BindingInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param date start_date: Only include usage that ...
382,315
def collect_modules(self): coverage_dir = os.path.join(self.root, ) for name in fnmatch.filter(os.listdir(coverage_dir), "*.html"): if name == : continue with open(os.path.join(coverage_dir, name)) as cover_file: src_file, ...
Generator to obtain lines of interest from coverage report files. Will verify that the source file is within the project tree, relative to the coverage directory.
382,316
def prepare_delete_monarchy(self, node, position=None, save=True): first = None for child in node.children.all(): if first is None: first = child first.move(node.parent, position, save) else: chil...
Prepares a given :class:`CTENode` `node` for deletion, by executing the :const:`DELETE_METHOD_MONARCHY` semantics. Descendant nodes, if present, will be moved; in this case the optional `position` can be a ``callable`` which is invoked prior to each move operation (see :m...
382,317
def lookup_job_tasks(self, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, create...
Yields operations based on the input criteria. If any of the filters are empty or {'*'}, then no filtering is performed on that field. Filtering by both a job id list and job name list is unsupported. Args: statuses: {'*'}, or a list of job status strings to return. Valid status strings ...
382,318
async def listCronJobs(self): crons = [] for iden, cron in self.cell.agenda.list(): useriden = cron[] if not (self.user.admin or useriden == self.user.iden): continue user = self.cell.auth.user(useriden) cron[] = if user is None e...
Get information about all the cron jobs accessible to the current user
382,319
def set_headers(context): safe_add_http_request_context_to_behave_context(context) headers = dict() for row in context.table: headers[row["header_name"]] = row["header_value"] context.http_request_context.headers = headers
Parameters: +--------------+---------------+ | header_name | header_value | +==============+===============+ | header1 | value1 | +--------------+---------------+ | header2 | value2 | +--------------+---------------+
382,320
def plot_spectrogram(self, node_idx=None): r from pygsp.plotting import _plot_spectrogram _plot_spectrogram(self, node_idx=node_idx)
r"""Docstring overloaded at import time.
382,321
def view(self, tempname=): import os if os.system() == 0: six.print_("Starting casaviewer in the background ...") self.unlock() if self.ispersistent(): os.system( + self.name() + ) elif len(tempname) > 0: ...
Display the image using casaviewer. If the image is not persistent, a copy will be made that the user has to delete once viewing has finished. The name of the copy can be given in argument `tempname`. Default is '/tmp/tempimage'.
382,322
async def startlisten(self, vhost = None): servers = self.getservers(vhost) for s in servers: await s.startlisten() return len(servers)
Start listen on current servers :param vhost: return only servers of vhost if specified. '' to return only default servers. None for all servers.
382,323
def srandmember(self, name, number=None): with self.pipe as pipe: f = Future() res = pipe.srandmember(self.redis_key(name), number=number) def cb(): if number is None: f.set(self.valueparse.decode(res.result)) else...
Return a random member of the set. :param name: str the name of the redis key :return: Future()
382,324
def fill(self, doc_contents): for key, content in doc_contents.items(): doc_contents[key] = replace_chars_for_svg_code(content) return super(SVGDocument, self).fill(doc_contents=doc_contents)
Fill the content of the document with the information in doc_contents. This is different from the TextDocument fill function, because this will check for symbools in the values of `doc_content` and replace them to good XML codes before filling the template. Parameters ----------...
382,325
def market_open(self, session, mins) -> Session: if session not in self.exch: return SessNA start_time = self.exch[session][0] return Session(start_time, shift_time(start_time, int(mins)))
Time intervals for market open Args: session: [allday, day, am, pm, night] mins: mintues after open Returns: Session of start_time and end_time
382,326
def make_csv(api_key, api_secret, path_to_csv=None, result_limit=1000, **kwargs): path_to_csv = path_to_csv or os.path.join(os.getcwd(), ) timeout_in_seconds = 2 max_retries = 3 retries = 0 offset = 0 videos = list() jwplatform_client = jwplatform.Client(api_key, api_secret) loggi...
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param path_to_csv: <string> Local system path to desired CSV. Default will be within current workin...
382,327
def nvmlDeviceGetInforomImageVersion(handle): r c_version = create_string_buffer(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE) fn = _nvmlGetFunctionPointer("nvmlDeviceGetInforomImageVersion") ret = fn(handle, c_version, c_uint(NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE)) _nvmlCheckReturn(ret) return byt...
r""" /** * Retrieves the global infoROM image version * * For all products with an inforom. * * Image version just like VBIOS version uniquely describes the exact version of the infoROM flashed on the board * in contrast to infoROM object version which is only an indicator of supported...
382,328
def favorites(self): return bind_api( api=self, path=, payload_type=, payload_list=True, allowed_param=[, , , , , ] )
:reference: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list :allowed_param:'screen_name', 'user_id', 'max_id', 'count', 'since_id', 'max_id'
382,329
def set_font(self, font): self.shellwidget._control.setFont(font) self.shellwidget.font = font
Set IPython widget's font
382,330
def post(self, url, data, charset=CHARSET_UTF8, headers={}): if not in headers: headers[] = if not in headers: headers[] = "application/x-www-form-urlencoded;charset=" + charset rsp = requests.post(url, data, headers=headers, timeou...
response json text
382,331
def storeByteArray(self, context, page, len, data, returnError): returnError.contents.value = self.IllegalStateError raise NotImplementedError("You must override this method.")
please override
382,332
def delete(self): result = yield gen.Task(RedisSession._redis_client.delete, self._key) LOGGER.debug(, self.id, result) self.clear() raise gen.Return(result)
Delete the item from storage :param method callback: The callback method to invoke when done
382,333
def numRef_xml(self, wksht_ref, number_format, values): pt_xml = self.pt_xml(values) return ( ).format(**{ : wksht_ref, : number_format, : pt_xml, ...
Return the ``<c:numRef>`` element specified by the parameters as unicode text.
382,334
def check_effective(func): def wrapper(*args, **kwargs): if ( in kwargs or args and in args[1].get_identifier_namespace()): try: assessment_section_id = kwargs[] except KeyError: assessment_section_id = args[1] if (not...
decorator, tests if an Assessment or Section is effective, raises error if not Side benefit: raised NotFound on AssessmentSections and AssessmentTakens
382,335
def create_2d_gaussian(dim, sigma): if dim % 2 == 0: raise ValueError("Kernel dimension should be odd") kernel = np.zeros((dim, dim), dtype=np.float16) center = dim/2 variance = sigma ** 2 coeff = 1. / (2 * variance) for x in range(0, dim): ...
This function creates a 2d gaussian kernel with the standard deviation denoted by sigma :param dim: integer denoting a side (1-d) of gaussian kernel :param sigma: floating point indicating the standard deviation :returns: a numpy 2d array
382,336
def _regex_strings(self): domain = 0 if domain not in self.domains: self.register_domain(domain=domain) return self.domains[domain]._regex_strings
A property to link into IntentEngine's _regex_strings. Warning: this is only for backwards compatiblility and should not be used if you intend on using domains. Returns: the domains _regex_strings from its IntentEngine
382,337
def _any(objs, query): for obj in objs: if isinstance(obj, Document): if _any(obj.roots, query): return True else: if any(query(ref) for ref in obj.references()): return True else: return False
Whether any of a collection of objects satisfies a given query predicate Args: objs (seq[Model or Document]) : query (callable) Returns: True, if ``query(obj)`` is True for some object in ``objs``, else False
382,338
def unpack(tokens): logger.log_tag("unpack", tokens) if use_computation_graph: tokens = evaluate_tokens(tokens) if isinstance(tokens, ParseResults) and len(tokens) == 1: tokens = tokens[0] return tokens
Evaluate and unpack the given computation graph.
382,339
def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ): bit_offset = 0 bit_count = 10000 missing = [] ret = {} if missing_zonefile_info is None: while True: zfinfo = atlasdb_zonefile_find_missing( bit_offset, b...
Find the set of missing zonefiles, as well as their popularity amongst our neighbors. Only consider zonefiles that are known by at least one peer; otherwise they're missing from our clique (and we'll re-sync our neighborss' inventories every so often to make sure we detect when zonefiles becom...
382,340
def protect_shorthand(text, split_locations): word_matches = list(re.finditer(word_with_period, text)) total_words = len(word_matches) for i, match in enumerate(word_matches): match_start = match.start() match_end = match.end() for char_pos in range(match_start, match_end): ...
Annotate locations in a string that contain periods as being true periods or periods that are a part of shorthand (and thus should not be treated as punctuation marks). Arguments: ---------- text : str split_locations : list<int>, same length as text.
382,341
def put(self, request): edx_video_id = request.data[] profile = request.data[] encode_data = request.data[] video = Video.objects.get(edx_video_id=edx_video_id) profile = Profile.objects.get(profile_name=profile) EncodedVideo.objects.filter(vi...
Update a single profile for a given video. Example request data: { 'edx_video_id': '1234' 'profile': 'hls', 'encode_data': { 'url': 'foo.com/qwe.m3u8' 'file_size': 34 'bitrate': 12 ...
382,342
def layer_from_combo(combo): index = combo.currentIndex() if index < 0: return None layer_id = combo.itemData(index, Qt.UserRole) layer = QgsProject.instance().mapLayer(layer_id) return layer
Get the QgsMapLayer currently selected in a combo. Obtain QgsMapLayer id from the userrole of the QtCombo and return it as a QgsMapLayer. :returns: The currently selected map layer a combo. :rtype: QgsMapLayer
382,343
def api_request(self, method, path): if not hasattr(self, ): ValueError() if method.lower() == : _request = requests.get elif method.lower() == : _request = requests.post domain = self.api_settings[] uri = .format(domain, self.api_se...
Query Sensu api for information.
382,344
def _unpack_object_array(inp, source, prescatter): raise NotImplementedError("Currently not used with record/struct/object improvements") base_rec, attr = source.rsplit(".", 1) new_name = "%s_%s_unpack" % (inp["name"], base_rec.replace(".", "_")) prescatter[base_rec].append((new_name, attr, _to_var...
Unpack Array[Object] with a scatter for referencing in input calls. There is no shorthand syntax for referencing all items in an array, so we explicitly unpack them with a scatter.
382,345
def unpack_frame(message): body = [] returned = dict(cmd=, headers={}, body=) breakdown = message.split() returned[] = breakdown[0] breakdown = breakdown[1:] def headD(field): index = field.find() if index: header = field[:index].strip()...
Called to unpack a STOMP message into a dictionary. returned = { # STOMP Command: 'cmd' : '...', # Headers e.g. 'headers' : { 'destination' : 'xyz', 'message-id' : 'some event', : etc, } # Body: 'body' : '...1...
382,346
def handle(self, url, method): if not self.serve: return HTTPError(503, "Server stopped") handler, args = self.match_url(url, method) if not handler: return HTTPError(404, "Not found:" + url) try: return handler(**args) except HTTPRe...
Execute the handler bound to the specified url and method and return its output. If catchall is true, exceptions are catched and returned as HTTPError(500) objects.
382,347
def get_raw_data_from_buffer(self, filter_func=None, converter_func=None): if self._is_running: raise RuntimeError() if not self.fill_buffer: logging.warning() return [convert_data_array(data_array_from_data_iterable(data_iterable), filter_func=filter_func,...
Reads local data buffer and returns raw data array. Returns ------- data : np.array An array containing data words from the local data buffer.
382,348
def send(self, tid, company_code, session, **kwargs): request = TOPRequest() request[] = tid request[] = company_code for k, v in kwargs.iteritems(): if k not in (, , , ) and v==None: continue request[k] = v self.create(self.execute(request, sessi...
taobao.logistics.online.send 在线订单发货处理(支持货到付款) - 用户调用该接口可实现在线订单发货(支持货到付款) - 调用该接口实现在线下单发货,有两种情况: - 如果不输入运单号的情况:交易状态不会改变,需要调用taobao.logistics.online.confirm确认发货后交易状态才会变成卖家已发货。 - 如果输入运单号的情况发货:交易订单状态会直接变成卖家已发货 。
382,349
def say(*words): * cmd = .format(.join(words)) call = __salt__[]( cmd, output_loglevel=, python_shell=False ) _check_cmd(call) return True
Say some words. words The words to execute the say command with. CLI Example: .. code-block:: bash salt '*' desktop.say <word0> <word1> ... <wordN>
382,350
def maximum_impact_estimation(membership_matrix, max_iters=1000): pr_0 = np.sum(membership_matrix, axis=0) / np.sum(membership_matrix) pr_1 = _update_probabilities(pr_0, membership_matrix) epsilon = np.linalg.norm(pr_1 - pr_0)/100. pr_old = pr_1 check_for_convergence =...
An expectation maximization technique that produces pathway definitions devoid of crosstalk. That is, each gene is mapped to the pathway in which it has the greatest predicted impact; this removes any overlap between pathway definitions. Parameters ----------- membership_matrix : numpy.array(fl...
382,351
def handle_page_location_changed(self, timeout=None): s latest location. t track redirect! No idea what to do!") last_message = messages[-1] self.log.info("Probably a redirect! New content url: ", last_message[][]) resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(last_messa...
If the chrome tab has internally redirected (generally because jerberscript), this will walk the page navigation responses and attempt to fetch the response body for the tab's latest location.
382,352
def values(prev, *keys, **kw): d = next(prev) if isinstance(d, dict): yield [d[k] for k in keys if k in d] for d in prev: yield [d[k] for k in keys if k in d] else: yield [d[i] for i in keys if 0 <= i < len(d)] for d in prev: yield [d[i] for i in ...
values pipe extract value from previous pipe. If previous pipe send a dictionary to values pipe, keys should contains the key of dictionary which you want to get. If previous pipe send list or tuple, :param prev: The previous iterator of pipe. :type prev: Pipe :returns: generator
382,353
def render_request(self, sort=True): if not sort: return ("; ".join( cookie.render_request() for cookie in self.values())) return ("; ".join(sorted( cookie.render_request() for cookie in self.values())))
Render the dict's Cookie objects into a string formatted for HTTP request headers (simple 'Cookie: ' style).
382,354
def retrieve(pdb_id, cache_dir = None): pdb_contents = None xml_contents = None pdb_id = pdb_id.upper() if cache_dir: filename = os.path.join(cache_dir, "%s.pdb" % pdb_id) if os.path.exists(filename): pdb_contents = read_fil...
Creates a PDBML object by using a cached copy of the files if they exists or by retrieving the files from the RCSB.
382,355
def delete_tag(self, tag_name, **kwargs): resp = self._delete(self._u(self._TAG_ENDPOINT_SUFFIX, tag_name), **kwargs) resp.raise_for_status() return resp
delete a tag by name Args: tag_name (string): name of tag to delete
382,356
def usable_id(cls, id, datacenter=None): try: qry_id = int(id) except Exception: qry_id = cls.from_sysdisk(id) or cls.from_label(id, datacenter) if not qry_id: msg = % id cls.error(msg) return qry_id
Retrieve id from input which can be label or id.
382,357
def _random_ipv4_address_from_subnet(self, subnet, network=False): address = str( subnet[self.generator.random.randint( 0, subnet.num_addresses - 1, )], ) if network: address += + str(self.generator.random.randint( su...
Produces a random IPv4 address or network with a valid CIDR from within a given subnet. :param subnet: IPv4Network to choose from within :param network: Return a network address, and not an IP address
382,358
def read_table(self, table_type): if table_type == : entry_class = MPQHashTableEntry elif table_type == : entry_class = MPQBlockTableEntry else: raise ValueError("Invalid table type.") table_offset = self.header[ % table_type] table_...
Read either the hash or block table of a MPQ archive.
382,359
def mark_sacrificed(self,request,queryset): rows_updated = queryset.update(Alive=False, Death=datetime.date.today(), Cause_of_Death=) if rows_updated == 1: message_bit = "1 animal was" else: message_bit = "%s animals were" % rows_updated self.message_user...
An admin action for marking several animals as sacrificed. This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as sacrificed. To use other paramters, mice muse be individually marked as sacrificed. This admin action also shows as the output the number of mice sacrifi...
382,360
def _get_path_for_type(type_): if type_.lower() in CORE_TYPES: return Path( % type_.lower()) elif in type_: namespace, name = type_.split() return Path(, namespace, _get_file_name(name)) else: return Path(, _get_file_name(type_))
Similar to `_get_path_for` but for only type names.
382,361
def begin(self): if self.in_transaction: if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collection, store in self.stores.items(): store.begin() ...
Start a new transaction.
382,362
def create(graph, verbose=True): from turicreate._cython.cy_server import QuietProgress if not isinstance(graph, _SGraph): raise TypeError() with QuietProgress(verbose): params = _tc.extensions._toolkits.graph.degree_count.create( {: graph.__proxy__}) return DegreeCoun...
Compute the in degree, out degree and total degree of each vertex. Parameters ---------- graph : SGraph The graph on which to compute degree counts. verbose : bool, optional If True, print progress updates. Returns ------- out : DegreeCountingModel Examples ------...
382,363
def make_pdb(self): pdb_str = write_pdb( [self], if not self.ampal_parent else self.ampal_parent.id) return pdb_str
Generates a PDB string for the `Monomer`.
382,364
def checkGradient(self,h=1e-6,verbose=True): grad_an = self.LMLgrad() grad_num = {} params0 = self.params.copy() for key in list(self.params.keys()): paramsL = params0.copy() paramsR = params0.copy() grad_num[key] = SP.zeros_like(self.params[k...
utility function to check the gradient of the gp
382,365
def p_function_call_parameter(p): if len(p) == 2: p[0] = ast.Parameter(p[1], False, lineno=p.lineno(1)) else: p[0] = ast.Parameter(p[2], True, lineno=p.lineno(1))
function_call_parameter : expr | AND variable
382,366
def parent(idx, dim, axis=None): idxm = multi_index(idx, dim) if axis is None: axis = dim - numpy.argmin(1*(numpy.array(idxm)[::-1] == 0))-1 if not idx: return idx, axis if idxm[axis] == 0: idxi = parent(parent(idx, dim)[0], dim)[0] while child(idxi+1, dim, axis) <...
Parent node according to Bertran's notation. Parameters ---------- idx : int Index of the child node. dim : int Dimensionality of the problem. axis : int Assume axis direction. Returns ------- out : int Index of parent node with `j<=i`, and `j==i` iff `i...
382,367
def createListRecursively(self,args): resultList = [] dirDict = self.getDirectoryDictionary(args) for key in dirDict: for path,dirs,files in os.walk(key): for d in dirs: resultList.append(os.path.join(path,d)) for f in ...
This is an internal method to create the list of input files (or directories) recursively, starting at the provided directory or directories.
382,368
def check_R_package(self, package): test_package = not bool(launch_R_script("{}/R_templates/test_import.R".format(os.path.dirname(os.path.realpath(__file__))), {"{package}": package}, verbose=True)) return test_package
Execute a subprocess to check the package's availability. Args: package (str): Name of the package to be tested. Returns: bool: `True` if the package is available, `False` otherwise
382,369
def extract_angular(fileobj, keywords, comment_tags, options): parser = AngularGettextHTMLParser() for line in fileobj: parser.feed(encodeutils.safe_decode(line)) for string in parser.strings: yield(string)
Extract messages from angular template (HTML) files. It extract messages from angular template (HTML) files that use angular-gettext translate directive as per https://angular-gettext.rocketeer.be/ :param fileobj: the file-like object the messages should be extracted from :para...
382,370
def right_press(self, event): self.set_current() current = self.canvas.find_withtag("current") if current and current[0] in self.canvas.find_withtag("item"): self.current = current[0] self.item_menu.tk_popup(event.x_root, event.y_root) else: ...
Callback for the right mouse button event to pop up the correct menu. :param event: Tkinter event
382,371
def write(p_file, p_string): if not config().colors(p_file.isatty()): p_string = escape_ansi(p_string) if p_string: p_file.write(p_string + "\n")
Write p_string to file p_file, trailed by a newline character. ANSI codes are removed when the file is not a TTY (and colors are automatically determined).
382,372
def collect(self): if not os.access(self.PROC, os.R_OK): return False file = open(self.PROC, ) for line in file: if not line.startswith(): continue data = line.split() metric_name = metri...
Collect interrupt data
382,373
def question_detail(request, topic_slug, slug): extra_context = { : Topic.objects.published().get(slug=topic_slug), } return object_detail(request, queryset=Question.objects.published(), extra_context=extra_context, template_object_name=, slug=slug)
A detail view of a Question. Templates: :template:`faq/question_detail.html` Context: question A :model:`faq.Question`. topic The :model:`faq.Topic` object related to ``question``.
382,374
def grep(query, directory): dir_contents = os.listdir(directory) results = [] for item in dir_contents: path = os.path.join(directory, item) if os.path.isdir(path): build_and_start(query, path) else: if item.endswith(): results.extend(gre...
This function will search through the directory structure of the application and for each directory it finds it launches an Async task to run itself. For each .py file it finds, it actually greps the file and then returns the found output.
382,375
def plot_structures(self, structures, fontsize=6, **kwargs): import matplotlib.pyplot as plt nrows = len(structures) fig, axes = plt.subplots(nrows=nrows, ncols=1, sharex=True, squeeze=False) for i, (ax, structure) in enumerate(zip(axes.ravel(),...
Plot diffraction patterns for multiple structures on the same figure. Args: structures (Structure): List of structures two_theta_range ([float of length 2]): Tuple for range of two_thetas to calculate in degrees. Defaults to (0, 90). Set to None if you wa...
382,376
def view_task_durations(token, dstore): task = token.split()[1] array = dstore[ + task][] return .join(map(str, array))
Display the raw task durations. Here is an example of usage:: $ oq show task_durations:classical
382,377
def range_interleave(ranges, sizes={}, empty=False): from jcvi.utils.iter import pairwise ranges = range_merge(ranges) interleaved_ranges = [] for ch, cranges in groupby(ranges, key=lambda x: x[0]): cranges = list(cranges) size = sizes.get(ch, None) if size: ch,...
Returns the ranges in between the given ranges. >>> ranges = [("1", 30, 40), ("1", 45, 50), ("1", 10, 30)] >>> range_interleave(ranges) [('1', 41, 44)] >>> ranges = [("1", 30, 40), ("1", 42, 50)] >>> range_interleave(ranges) [('1', 41, 41)] >>> range_interleave(ranges, sizes={"1": 70}) ...
382,378
def body_block_paragraph_render(p_tag, html_flag=True, base_url=None): convert = lambda xml_string: xml_to_html(html_flag, xml_string, base_url) block_content_list = [] tag_content_content = [] nodenames = body_block_nodenames() paragraph_content = u for child_tag in p_tag: ...
paragraphs may wrap some other body block content this is separated out so it can be called from more than one place
382,379
def _inherit_parent_kwargs(self, kwargs): if not self.parent or not self._is_dynamic: return kwargs if not in kwargs: return kwargs
Extract any necessary attributes from parent serializer to propagate down to child serializer.
382,380
def googlenet(pretrained=False, **kwargs): r if pretrained: if not in kwargs: kwargs[] = True if not in kwargs: kwargs[] = False if kwargs[]: warnings.warn( ) original_aux_logits = kwargs[] kwargs[] = True ...
r"""GoogLeNet (Inception v1) model architecture from `"Going Deeper with Convolutions" <http://arxiv.org/abs/1409.4842>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet aux_logits (bool): If True, adds two auxiliary branches that can improve training. Def...
382,381
def _sort_text(definition): prefix = if definition.name.startswith() else return prefix.format(definition.name)
Ensure builtins appear at the bottom. Description is of format <type>: <module>.<item>
382,382
def check_html(html_file, begin): sig = False for html_line in open(html_file).readlines(): uuu = pack_str(html_line).find() if uuu > 0: f_tmpl = html_line.strip().split()[-2].strip() curpath, curfile = os.path.split(html_file) ff_tmpl ...
Checking the HTML
382,383
def get_transformation(self, struct1, struct2): if self._primitive_cell: raise ValueError("get_transformation cannot be used with the " "primitive cell option") struct1, struct2 = self._process_species((struct1, struct2)) s1, s2, fu, s1_superce...
Returns the supercell transformation, fractional translation vector, and a mapping to transform struct2 to be similar to struct1. Args: struct1 (Structure): Reference structure struct2 (Structure): Structure to transform. Returns: supercell (numpy.ndarray(3,...
382,384
def compile_file(self, infile, outfile, outdated=False, force=False): myfile = codecs.open(outfile, , ) if settings.DEBUG: myfile.write(sass.compile(filename=infile)) else: myfile.write(sass.compile(filename=infile, output_s...
Process sass file.
382,385
def get_task_runs(self, json_file=None): if self.project is None: raise ProjectError loader = create_task_runs_loader(self.project.id, self.tasks, json_file, self.all) self.task_runs, self.task_runs_file = loader.load() self....
Load all project Task Runs from Tasks.
382,386
def count(y_true, y_score=None, countna=False): if not countna: return (~np.isnan(to_float(y_true))).sum() else: return len(y_true)
Counts the number of examples. If countna is False then only count labeled examples, i.e. those with y_true not NaN
382,387
def _update_secrets(self): token = self._required_get_and_update() self.dbx = Dropbox(token) try: self.account = self.dbx.users_get_current_account() except AuthError as err: bot.error() sys.exit(1)
update secrets will look for a dropbox token in the environment at SREGISTRY_DROPBOX_TOKEN and if found, create a client. If not, an error message is returned and the client exits.
382,388
def translate_to_international_phonetic_alphabet(self, hide_stress_mark=False): translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else "" for phoneme in self._phoneme_list: translations += phoneme.ipa return translations
转换成国际音标。只要一个元音的时候需要隐藏重音标识 :param hide_stress_mark: :return:
382,389
def setXr(self, Xr): self.Xr = Xr self.gp_block.covar.G = Xr
set genotype data of the set component
382,390
def _get_free_gpu(max_gpu_utilization=40, min_free_memory=0.5, num_gpu=1): def get_gpu_info(): gpu_info = subprocess.check_output(["nvidia-smi", "--format=csv,noheader,nounits", "--query-gpu=index,memory.total,memory.free,memory.used,utilization.gpu"]).decode() gpu_info = gpu_info.split() gpu_inf...
Get available GPUs according to utilization thresholds. Args: :max_gpu_utilization: percent utilization threshold to consider a GPU "free" :min_free_memory: percent free memory to consider a GPU "free" :num_gpu: number of requested GPUs Returns: A tuple of (available_gpus, minimum_free_memory), wh...
382,391
def _validate_client(self, request, data): client = self.get_client(data.get()) if client is None: raise OAuthError({ : , : _("An unauthorized client tried to access" " your resources.") }) form = self.get_req...
:return: ``tuple`` - ``(client or False, data or error)``
382,392
def blog_likes(self, blogname, **kwargs): url = "/v2/blog/{}/likes".format(blogname) return self.send_api_request("get", url, kwargs, [, , , ], True)
Gets the current given user's likes :param limit: an int, the number of likes you want returned (DEPRECATED) :param offset: an int, the like you want to start at, for pagination. :param before: an int, the timestamp for likes you want before. :param after: an int, the timestamp for likes...
382,393
def update_preference_communication_channel_id(self, notification, communication_channel_id, notification_preferences_frequency): path = {} data = {} params = {} path["communication_channel_id"] = communication_channel_id p...
Update a preference. Change the preference for a single notification for a single communication channel
382,394
def _FormatSizeInUnitsOf1024(self, size): magnitude_1024 = 0 used_memory_1024 = float(size) while used_memory_1024 >= 1024: used_memory_1024 /= 1024 magnitude_1024 += 1 if 0 < magnitude_1024 <= 7: return .format( used_memory_1024, self._UNITS_1024[magnitude_1024]) ...
Represents a number of bytes in units of 1024. Args: size (int): size in bytes. Returns: str: human readable string of the size.
382,395
def offset(requestContext, seriesList, factor): for series in seriesList: series.name = "offset(%s,%g)" % (series.name, float(factor)) series.pathExpression = series.name for i, value in enumerate(series): if value is not None: series[i] = value + factor ...
Takes one metric or a wildcard seriesList followed by a constant, and adds the constant to each datapoint. Example:: &target=offset(Server.instance01.threads.busy,10)
382,396
def read_reporting_revisions_get(self, project=None, fields=None, types=None, continuation_token=None, start_date_time=None, include_identity_ref=None, include_deleted=None, include_tag_ref=None, include_latest_only=None, expand=None, include_discussion_changes_only=None, max_page_size=None): route_val...
ReadReportingRevisionsGet. Get a batch of work item revisions with the option of including deleted items :param str project: Project ID or project name :param [str] fields: A list of fields to return in work item revisions. Omit this parameter to get all reportable fields. :param [str] t...
382,397
def set_options(self, options): for key, val in options.items(): key = key.lstrip() if hasattr(self, key): setattr(self, key, val)
Sets the given options as instance attributes (only if they are known). :parameters: options : Dict All known instance attributes and more if the childclass has defined them before this call. :rtype: None
382,398
def create_notification(self, notification_type, label=None, name=None, details=None): return self._notification_manager.create(notification_type, label=label, name=name, details=details)
Defines a notification for handling an alarm.
382,399
def num_equal(result, operator, comparator): if operator == : return len([x for x in result if x < comparator]) elif operator == : return len([x for x in result if x > comparator]) elif operator == : return len([x for x in result if x == comparator]) else: raise Valu...
Returns the number of elements in a list that pass a comparison :param result: The list of results of a dice roll :param operator: Operator in string to perform comparison on: Either '+', '-', or '*' :param comparator: The value to compare :return: