Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
386,600
def _process_loaded_object(self, path): file_name = os.path.basename(path) name = os.path.splitext(file_name)[0] with open(path) as file: string = file.read() self._instruction_type_to_file_content[name] = string
process the :paramref:`path`. :param str path: the path to load an svg from
386,601
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ : self.title, : self.submit_value, : self.cancel_url }) return context
Add context data to view
386,602
def clean_out_dir(directory): if not isinstance(directory, path): directory = path(directory) for file_path in directory.files(): file_path.remove() for dir_path in directory.dirs(): dir_path.rmtree()
Delete all the files and subdirectories in a directory.
386,603
def dump_copy(self, path, relativePath, name=None, description=None, replace=False, verbose=False): relativePath = os.path.normpath(relativePath) if relativePath == : relativePath = if name is None: _,name = os.pat...
Copy an exisitng system file to the repository. attribute in the Repository with utc timestamp. :Parameters: #. path (str): The full path of the file to copy into the repository. #. relativePath (str): The relative to the repository path of the directory where the file should be...
386,604
def new_pattern(self, id_, name, rows=None): if rows is None: rows = self.new_row_collection() return self._spec.new_pattern(id_, name, rows, self)
Create a new knitting pattern. If rows is :obj:`None` it is replaced with the :meth:`new_row_collection`.
386,605
def get_file(self, sharename, fileid): if not isinstance(fileid, int): raise TypeError(" must be an integer") response = GettRequest().get("/files/%s/%d" % (sharename, fileid)) if response.http_status == 200: return GettFile(self.user, **response.response)
Get a specific file. Does not require authentication. Input: * A sharename * A fileid - must be an integer Output: * A :py:mod:`pygett.files.GettFile` object Example:: file = client.get_file("4ddfds", 0)
386,606
def plot(image, overlay=None, blend=False, alpha=1, cmap=, overlay_cmap=, overlay_alpha=0.9, cbar=False, cbar_length=0.8, cbar_dx=0., cbar_vertical=True, axis=0, nslices=12, slices=None, ncol=None, slice_buffer=None, black_bg=True, bg_thresh_quant=0.01, bg_val_quant=0.99, domain_image_map=None, crop=F...
Plot an ANTsImage. By default, images will be reoriented to 'LAI' orientation before plotting. So, if axis == 0, the images will be ordered from the left side of the brain to the right side of the brain. If axis == 1, the images will be ordered from the anterior (front) of the brain to the poster...
386,607
def user_cache_dir(): r if WINDOWS: path = os.path.join(os.environ.get() or os.environ.get(), , ) elif MACOS: path = os.path.expanduser() else: path = os.path.join(os.environ.get() or os.path.expanduser(), ) return path
r"""Return the per-user cache dir (full path). - Linux, *BSD, SunOS: ~/.cache/glances - macOS: ~/Library/Caches/glances - Windows: {%LOCALAPPDATA%,%APPDATA%}\glances\cache
386,608
def wait_for_service_tasks_state( service_name, expected_task_count, expected_task_states, timeout_sec=120 ): return time_wait( lambda: task_states_predicate(service_name, expected_task_count, expected_task_states), timeout_seconds=timeout_sec)
Returns once the service has at least N tasks in one of the specified state(s) :param service_name: the service name :type service_name: str :param expected_task_count: the expected number of tasks in the specified state(s) :type expected_task_count: int :param expected_task_sta...
386,609
def display_candidates(self, candidates, pdf_file=None): if not pdf_file: pdf_file = os.path.join( self.pdf_path, candidates[0][0].context.sentence.document.name ) if os.path.isfile(pdf_file + ".pdf"): pdf_file += ".pdf" el...
Displays the bounding boxes corresponding to candidates on an image of the pdf boxes is a list of 5-tuples (page, top, left, bottom, right)
386,610
def CheckProg(context, prog_name): res = SCons.Conftest.CheckProg(context, prog_name) context.did_show_result = 1 return res
Simple check if a program exists in the path. Returns the path for the application, or None if not found.
386,611
def readinto(self, b): if not self._readable: raise UnsupportedOperation() with self._seek_lock: seek = self._seek queue = self._read_queue if seek == 0: self._preload_range() ...
Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. Args: b (bytes-like object): buffer. Returns: int: number of bytes read
386,612
def error(self, message=None): if self.__parser__: self.__parser__.error(message) else: self.logger.error(message) sys.exit(2)
Delegates to `ArgumentParser.error`
386,613
def parse_section_entry_points(self, section_options): parsed = self._parse_section_to_dict(section_options, self._parse_list) self[] = parsed
Parses `entry_points` configuration file section. :param dict section_options:
386,614
def _submit(self, pathfile, filedata, filename): if pathfile and os.path.exists(pathfile): files = {: open(pathfile, )} elif filedata: assert filename files = { : (filename, io.BytesIO(filedata))} else: raise ValueError("You must pass either a valid file path, or a bytes array containing the captch...
Submit either a file from disk, or a in-memory file to the solver service, and return the request ID associated with the new captcha task.
386,615
def make_autogen_str(): r import utool as ut def get_regen_cmd(): try: if len(sys.argv) > 0 and ut.checkpath(sys.argv[0]): if ut.is_python_module(sys.argv[0]): python_exe = ut.python_executable(check=False) modname ...
r""" Returns: str: CommandLine: python -m utool.util_ipynb --exec-make_autogen_str --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_ipynb import * # NOQA >>> import utool as ut >>> result = make_autogen_str() >>> print(result)
386,616
def sync_from_spec(redis, schema): def get_experiments_dict(active=True): return dict((experiment.name, experiment) for experiment in get_experiments(redis, active=active)) active_experiments = get_experiments_dict() archived_experiments = get_experiments_dict(active=False) ...
Takes an input experiment spec and creates/modifies/archives the existing experiments to match the spec. If there's an experiment in the spec that currently doesn't exist, it will be created along with the associated choices. If there's an experiment in the spec that currently exists, and the set of ...
386,617
def load_sgems_exp_var(filename): assert os.path.exists(filename) import xml.etree.ElementTree as etree tree = etree.parse(filename) root = tree.getroot() dfs = {} for variogram in root: for attrib in variogram: if attrib.tag == "title": ...
read an SGEM experimental variogram into a sequence of pandas.DataFrames Parameters ---------- filename : (str) an SGEMS experimental variogram XML file Returns ------- dfs : list a list of pandas.DataFrames of x, y, pairs for each division in the experimental vario...
386,618
async def fetch_messages(self, selected: SelectedMailbox, sequence_set: SequenceSet, attributes: FrozenSet[FetchAttribute]) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: ...
Get a list of loaded message objects corresponding to given sequence set. Args: selected: The selected mailbox session. sequence_set: Sequence set of message sequences or UIDs. attributes: Fetch attributes for the messages. Raises: :class:`~pymap...
386,619
def slices(src_path): pages = list_slices(src_path) slices = [] for page in pages: slices.extend(page.slices) return slices
Return slices as a flat list
386,620
def addVariantAnnotationSet(self, variantAnnotationSet): id_ = variantAnnotationSet.getId() self._variantAnnotationSetIdMap[id_] = variantAnnotationSet self._variantAnnotationSetIds.append(id_)
Adds the specified variantAnnotationSet to this dataset.
386,621
def add_external_reference(self,ext_ref): node_ext_refs = self.node.find() ext_refs = None if node_ext_refs == None: ext_refs = CexternalReferences() self.node.append(ext_refs.get_node()) else: ext_refs = CexternalReferences(node_ext_...
Adds an external reference to the role @param ext_ref: the external reference object @type ext_ref: L{CexternalReference}
386,622
def expects_call(self): self._callable = ExpectedCall(self, call_name=self._name, callable=True) return self
The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge ...
386,623
def _execute(self, query, model, adapter, raw=False): values = self.load(model, adapter) return IterableStore(values=values)._execute(query, model=model, adapter=None, raw=raw)
We have to override this because in some situation (such as with Filebackend, or any dummy backend) we have to parse / adapt results *before* when can execute the query
386,624
def delete(self, record_key): title = % self.__class__.__name__ input_fields = { : record_key } for key, value in input_fields.items(): object_title = % (title, key, str(value)) self.fields.validate(value, % key, obj...
a method to delete a record from S3 :param record_key: string with key of record :return: string reporting outcome
386,625
def _find_supported(self, features, mechanism_classes): try: mechanisms = features[SASLMechanisms] except KeyError: logger.error("No sasl mechanisms: %r", list(features)) raise errors.SASLUnavailable( "Remote side does not support SASL") from...
Find the first mechansim class which supports a mechanism announced in the given stream features. :param features: Current XMPP stream features :type features: :class:`~.nonza.StreamFeatures` :param mechanism_classes: SASL mechanism classes to use :type mechanism_classes: iterab...
386,626
def send_message(self, output): file_system_event = None if self.my_action_input: file_system_event = self.my_action_input.file_system_event or None output_action = ActionInput(file_system_event, output, ...
Send a message to the socket
386,627
def process_fastq_minimal(fastq, **kwargs): infastq = handle_compressed_input(fastq) try: df = pd.DataFrame( data=[rec for rec in fq_minimal(infastq) if rec], columns=["timestamp", "lengths"] ) except IndexError: logging.error("Fatal: Incorrect file struc...
Swiftly extract minimal features (length and timestamp) from a rich fastq file
386,628
def build_documentation_lines(self): return [ line_string for key in sorted(self.keys) for line_string in self.build_paramter_string(key) ]
Build a parameter documentation string that can appended to the docstring of a function that uses this :class:`~.Filters` instance to build filters.
386,629
def manage_itstat(self): itst = self.iteration_stats() self.itstat.append(itst) self.display_status(self.fmtstr, itst)
Compute, record, and display iteration statistics.
386,630
def fill_datetime(self): if not self.filled: raise SlotNotFilledError( % (self.name, self.key)) return self._fill_datetime
Returns when the slot was filled. Returns: A datetime.datetime. Raises: SlotNotFilledError if the value hasn't been filled yet.
386,631
def templates(self, name=None, params=None): return self.transport.perform_request(, _make_path(, , name), params=params)
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-templates.html>`_ :arg name: A pattern that returned template names must match :arg format: a short version of the Accept header, e.g. json, yaml :arg h: Comma-separated list of column names to display :arg help: Retu...
386,632
def _read_para_overlay_ttl(self, code, cbit, clen, *, desc, length, version): if clen != 4: raise ProtocolError(f) _ttln = self._read_unpack(2) overlay_ttl = dict( type=desc, critical=cbit, length=clen, ttl=_ttln, ) ...
Read HIP OVERLAY_TTL parameter. Structure of HIP OVERLAY_TTL parameter [RFC 6078]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
386,633
def _process_status(self, status): self._screen_id = status.get(ATTR_SCREEN_ID) self.status_update_event.set()
Process latest status update.
386,634
def c32address(version, hash160hex): if not re.match(r, hash160hex): raise ValueError() c32string = c32checkEncode(version, hash160hex) return .format(c32string)
>>> c32address(22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d') 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> c32address(0, '0000000000000000000000000000000000000000') 'S0000000000000000000002AA028H' >>> c32address(31, '0000000000000000000000000000000000000001') 'SZ00000000000000000005HZ3DVN' >...
386,635
def sign_blob( self, name, payload, delegates=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if "sign_blob" not in self._inner_api_calls: self._inner...
Signs a blob using a service account's system-managed private key. Example: >>> from google.cloud import iam_credentials_v1 >>> >>> client = iam_credentials_v1.IAMCredentialsClient() >>> >>> name = client.service_account_path('[PROJECT]', '[SERVICE_AC...
386,636
def p_casecontent_condition_single(self, p): p[0] = p[1] + (p[3],) p.set_lineno(0, p.lineno(1))
casecontent_condition : casecontent_condition COMMA expression
386,637
def _extract_shape(idx, x, j, cur_center): _a = [] for i in range(len(idx)): if idx[i] == j: if cur_center.sum() == 0: opt_x = x[i] else: _, opt_x = _sbd(cur_center, x[i]) _a.append(opt_x) a = np.array(_a) if len(a) == 0: ...
>>> _extract_shape(np.array([0,1,2]), np.array([[1,2,3], [4,5,6]]), 1, np.array([0,3,4])) array([-1., 0., 1.]) >>> _extract_shape(np.array([0,1,2]), np.array([[-1,2,3], [4,-5,6]]), 1, np.array([0,3,4])) array([-0.96836405, 1.02888681, -0.06052275]) >>> _extract_shape(np.array([1,0,1,0]), np.array([[1...
386,638
def get_library_config(name): try: proc = Popen([, , , name], stdout=PIPE, stderr=PIPE) except OSError: print() exit(1) raw_cflags, err = proc.communicate() if proc.wait(): return known, unknown = parse_cflags(raw_cflags.decode()) if unknown: print(...
Get distutils-compatible extension extras for the given library. This requires ``pkg-config``.
386,639
def _add_parameter(self, parameter): if isinstance(parameter, MethodParameter): parameter = parameter.bind(alloy=self) self._parameters[parameter.name] = parameter for alias in parameter.aliases: self._aliases[alias] = parameter
Force adds a `Parameter` object to the instance.
386,640
def footprint(sobject): n = 0 for a in sobject.__keylist__: v = getattr(sobject, a) if v is None: continue if isinstance(v, Object): n += footprint(v) continue if hasattr(v, ): if len(v): n += 1 cont...
Get the I{virtual footprint} of the object. This is really a count of the attributes in the branch with a significant value. @param sobject: A suds object. @type sobject: L{Object} @return: The branch footprint. @rtype: int
386,641
def find_keys(self, regex, bucket_name=None): log = logging.getLogger(self.cls_logger + ) matched_keys = [] if not isinstance(regex, basestring): log.error(.format(t=regex.__class__.__name__)) return None if bucket_name is None: s3bu...
Finds a list of S3 keys matching the passed regex Given a regular expression, this method searches the S3 bucket for matching keys, and returns an array of strings for matched keys, an empty array if non are found. :param regex: (str) Regular expression to use is the key search ...
386,642
def namedb_get_name_DID_info(cur, name, block_height): sql = "SELECT name_records.name,history.creator_address,history.block_id,history.vtxindex FROM name_records JOIN history ON name_records.name = history.history_id " + \ "WHERE name = ? AND creator_address IS NOT NULL AND history.block_id <= ...
Given a name and a DB cursor, find out its DID info at the given block. Returns {'name_type': ..., 'address': ..., 'index': ...} on success Return None if there is no such name
386,643
def try_lock(lock): was_locked = lock.acquire(False) try: yield was_locked finally: if was_locked: lock.release()
Attempts to acquire a lock, and auto releases if acquired (on exit).
386,644
def queue_actions(self, source, actions, event_args=None): source.event_args = event_args ret = self.trigger_actions(source, actions) source.event_args = None return ret
Queue a list of \a actions for processing from \a source. Triggers an aura refresh afterwards.
386,645
def save(self, filename=None): if filename: if ".db" in filename: filename = filename.split(".")[0] self.properties.db_name = filename else: self.properties.db_name = "{}".format(self.properties.name) if os.path.isfile("{}.db...
Save the point histories to sqlite3 database. Save the device object properties to a pickle file so the device can be reloaded.
386,646
def summarize_provenance(self): provenance_per_cache = self.summarize_provenance_per_cache() summary_provenance = None num_discrepant = 0 for cache in provenance_per_cache: if not(summary_provenance): summary_provenance = provenance_p...
Utility function to summarize provenance files for cached items used by a Cohort. At the moment, most PROVENANCE files contain details about packages used to generate files. However, this function is generic & so it summarizes the contents of those files irrespective of their contents. ...
386,647
def source_list(source, source_hash, saltenv): *{hash_type: , : <md5sum>} contextkey = .format(source, source_hash, saltenv) if contextkey in __context__: return __context__[contextkey] if isinstance(source, list): mfiles = [(f, saltenv) for f in __salt__[](saltenv)] mdirs ...
Check the source list and return the source to use CLI Example: .. code-block:: bash salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base
386,648
def relabel(self, qubits: Qubits) -> : gate = copy(self) gate.vec = gate.vec.relabel(qubits) return gate
Return a copy of this Gate with new qubits
386,649
def get(self, sid): return OriginationUrlContext(self._version, trunk_sid=self._solution[], sid=sid, )
Constructs a OriginationUrlContext :param sid: The unique string that identifies the resource :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext
386,650
def new_job(self, task, inputdata, callback, launcher_name="Unknown", debug=False, ssh_callback=None): job_id = str(uuid.uuid4()) if debug == "ssh" and ssh_callback is None: self._logger.error("SSH callback not set in %s/%s", task.get_course_id(), task.get_id()) callbac...
Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback: a function that will be called asynchronously in the client's process, with the results. it's signatur...
386,651
def load_items(self, items): loaded_items = {} requests = collections.deque(create_batch_get_chunks(items)) while requests: request = requests.pop() try: response = self.dynamodb_client.batch_get_item(RequestItems=request) except botoc...
Loads any number of items in chunks, handling continuation tokens. :param items: Unpacked in chunks into "RequestItems" for :func:`boto3.DynamoDB.Client.batch_get_item`.
386,652
def v_type_extension(ctx, stmt): (modulename, identifier) = stmt.keyword revision = stmt.i_extension_revision module = modulename_to_module(stmt.i_module, modulename, revision) if module is None: return if identifier not in module.i_extensions: if module.i_modulename == stmt.i_o...
verify that the extension matches the extension definition
386,653
def _init_records(self, record_types): for record_type in record_types: if str(record_type) not in self._my_map[]: record_initialized = self._init_record(str(record_type)) if record_initialized: self._my_map[].append(str(recor...
Initalize all records for this form.
386,654
def _push_processor(self, proc, index=None): if index is None: self._procstack.append(proc) else: self._procstack.insert(index, proc)
Pushes a processor onto the processor stack. Processors are objects with proc_request(), proc_response(), and/or proc_exception() methods, which can intercept requests, responses, and exceptions. When a method invokes the send() method on a request, the proc_request() method on each ...
386,655
def log(self, n=None, **kwargs): kwargs[] = kwargs.pop(, self.template) cmd = [, ] if n: cmd.append( % n) cmd.extend( (( % (k, v)) for (k, v) in iteritems(kwargs))) try: output = self.sh(cmd, shell=False) if "f...
Run the repository log command Returns: str: output of log command (``git log -n <n> <--kwarg=value>``)
386,656
async def create(self, token): token = encode_token(token) response = await self._api.put("/v1/acl/create", data=token) return response.body
Creates a new token with a given policy Parameters: token (Object): Token specification Returns: Object: token ID The create endpoint is used to make a new token. A token has a name, a type, and a set of ACL rules. The request body may take the form:: ...
386,657
def get_short_reads(vals): (args,txome,seed,chunk) = vals txe = TranscriptomeEmitter(txome,TranscriptomeEmitter.Options(seed=seed)) if args.weights: weights = {} if args.weights[-3:]==: inf = gzip.open(args.weights) else: inf = open(args.weights) for line in inf: f = li...
Emit the short reads first
386,658
def parse_lines(lines: [str], units: Units, use_na: bool = True) -> [dict]: parsed_lines = [] prob = while lines: raw_line = lines[0].strip() line = core.sanitize_line(raw_line) if line.startswith(): if len(line) == 6: prob = ...
Returns a list of parsed line dictionaries
386,659
def apply_modification(self): self.__changing_model = True if self.adding_model: self.model.add(self.adding_model) elif self.editing_model and self.editing_iter: path = self.model.get_path(self.editing_iter) self.model.row_changed(path, self.editing...
Modifications on the right side need to be committed
386,660
def title_line(text): columns = shutil.get_terminal_size()[0] start = columns // 2 - len(text) // 2 output = *columns + + \ * start + str(text) + "\n\n" + \ *columns + return output
Returns a string that represents the text as a title blurb
386,661
def density_contour(self, *args, **kwargs): lon, lat, totals, kwargs = self._contour_helper(args, kwargs) return self.contour(lon, lat, totals, **kwargs)
Estimates point density of the given linear orientation measurements (Interpreted as poles, lines, rakes, or "raw" longitudes and latitudes based on the `measurement` keyword argument.) and plots contour lines of the resulting density distribution. Parameters ---------- ...
386,662
def invert_index(source_dir, index_url=INDEX_URL, init=False): raw_index = defaultdict(list) for base, dir_list, fn_list in os.walk(source_dir): for fn in fn_list: fp = os.path.join(base, fn) code = fn with open(fp) as f: tokens = f.read().strip()...
Build the invert index from give source_dir Output a Shove object built on the store_path Input: source_dir: a directory on the filesystem index_url: the store_path for the Shove object init: clear the old index and rebuild from scratch Output: index: a Shove object
386,663
def trapz2(f, x=None, y=None, dx=1.0, dy=1.0): return numpy.trapz(numpy.trapz(f, x=y, dx=dy), x=x, dx=dx)
Double integrate.
386,664
def get_vector(self, max_choice=3): vec = {} for dim in [, , ]: if self.meta[dim] is None: continue dim_vec = map(lambda x: (x, max_choice), self.meta[dim]) vec[dim] = dict(dim_vec) return vec
Return pseudo-choice vectors.
386,665
def column_keymap(self): keystates = set() shortcuts = self.cp.items() keymap_dict = dict(shortcuts) for combo, action in shortcuts: combo_as_list = re.split(, combo)[1::2] if len(combo_as_list) > 1: keystates |= set(accumul...
Returns keymap and keystates used in column mode
386,666
def _get_magnitude_term(self, C, mag): lny = C[] + (C[] * ((8.5 - mag) ** 2.)) if mag > 6.3: return lny + (-C[] * C[]) * (mag - 6.3) else: return lny + C[] * (mag - 6.3)
Returns the magnitude scaling term.
386,667
def SETPE(cpu, dest): dest.write(Operators.ITEBV(dest.size, cpu.PF, 1, 0))
Sets byte if parity even. :param cpu: current CPU. :param dest: destination operand.
386,668
def assign(self, expr): name = self.variable() self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr)) return ast.Name(name, ast.Load())
Give *expr* a name.
386,669
def _sort_converters(cls, app_ready=False):
Sorts the converter functions
386,670
def _register_server_authenticator(klass, name): SERVER_MECHANISMS_D[name] = klass items = sorted(SERVER_MECHANISMS_D.items(), key = _key_func, reverse = True) SERVER_MECHANISMS[:] = [k for (k, v) in items ] SECURE_SERVER_MECHANISMS[:] = [k for (k, v) in items ...
Add a client authenticator class to `SERVER_MECHANISMS_D`, `SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`
386,671
def create_contact(self, *args, **kwargs): url = data = { : False, : } data.update(kwargs) return Contact(**self._api._post(url, data=json.dumps(data)))
Creates a contact
386,672
async def _retrieve_messages_around_strategy(self, retrieve): if self.around: around = self.around.id if self.around else None data = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return []
Retrieve messages using around parameter.
386,673
def append(self, element): from refract.refraction import refract self.content.append(refract(element))
Append an element onto the array. >>> array = Array() >>> array.append('test')
386,674
def _get_ptext_to_endchars(value, endchars): _3to2list = list(_wsp_splitter(value, 1)) fragment, remainder, = _3to2list[:1] + [_3to2list[1:]] vchars = [] escape = False had_qp = False for pos in range(len(fragment)): if fragment[pos] == : if escape: escap...
Scan printables/quoted-pairs until endchars and return unquoted ptext. This function turns a run of qcontent, ccontent-without-comments, or dtext-with-quoted-printables into a single string by unquoting any quoted printables. It returns the string, the remaining value, and a flag that is True iff ther...
386,675
def _build_request(self, type, commands): request = {} headers = { : , } if self.nxargs[]: user = self.nxargs[] headers[] = + user + request[] = self.NXAPI_UDS_URI_PATH else: request[] = .format( ...
Build NX-API JSON request.
386,676
def variants(self, case_id, skip=0, count=1000, filters=None): filters = filters or {} case_obj = self.case(case_id=case_id) limit = count + skip genes = set() if filters.get(): genes = set([gene_id.strip() for gene_id in filters[]]) frequency = No...
Return all variants in the VCF. This function will apply the given filter and return the 'count' first variants. If skip the first 'skip' variants will not be regarded. Args: case_id (str): Path to a vcf file (for this adapter) skip (int): Skip first variant...
386,677
def tag_manifest_into_registry(self, session, worker_digest): self.log.info("%s: Tagging manifest", session.registry) digest = worker_digest[] source_repo = worker_digest[] image_manifest, _, media_type, _ = self.get_manifest(session, source_repo, digest) if media_type...
Tags the manifest identified by worker_digest into session.registry with all the configured tags found in workflow.tag_conf.
386,678
def push(self, repository=None, tag=None): image = self if repository or tag: image = self.tag_image(repository, tag) for json_e in self.d.push(repository=image.name, tag=image.tag, stream=True, decode=True): logger.debug(json_e) status = graceful_...
Push image to registry. Raise exception when push fail. :param repository: str, see constructor :param tag: str, see constructor :return: None
386,679
def _to_addr(worksheet, row, col, row_fixed=False, col_fixed=False): addr = "" A = ord() col += 1 while col > 0: addr = chr(A + ((col - 1) % 26)) + addr col = (col - 1) // 26 prefix = ("!" % worksheet) if worksheet else "" col_modifier = "$" if col_fixed else "" row_mod...
converts a (0,0) based coordinate to an excel address
386,680
def connect_async(self, connection_id, connection_string, callback): topics = MQTTTopicValidator(self.prefix + .format(connection_string)) key = self._generate_key() name = self.name conn_message = {: , : , : key, : name} context = {: key, : connection_string, : topics...
Connect to a device by its connection_string This function looks for the device on AWS IOT using the preconfigured topic prefix and looking for: <prefix>/devices/connection_string It then attempts to lock that device for exclusive access and returns a callback if successful. ...
386,681
def event_update( self, event_id, name=None, season=None, start_time=None, event_group_id=None, status=None, account=None, **kwargs ): assert isinstance(season, list) assert isinstance( start_time, datetime ...
Update an event. This needs to be **proposed**. :param str event_id: Id of the event to update :param list name: Internationalized names, e.g. ``[['de', 'Foo'], ['en', 'bar']]`` :param list season: Internationalized season, e.g. ``[['de', 'Foo'], ['en...
386,682
def convert_snapshot(self, shift, instruction): command_dict = { : , : shift+instruction.start_time, : instruction.name, : instruction.type } return self._qobj_model(**command_dict)
Return converted `Snapshot`. Args: shift(int): Offset time. instruction (Snapshot): snapshot instruction. Returns: dict: Dictionary of required parameters.
386,683
def build_stop_times(pfeed, routes, shapes, stops, trips, buffer=cs.BUFFER): routes = ( routes .filter([, ]) .merge(pfeed.frequencies.drop([], axis=1)) ) trips = ( trips .assign(service_window_id=lambda x: x.trip_id.map( lambda y: y.split(cs.SEP)[2...
Given a ProtoFeed and its corresponding routes (DataFrame), shapes (DataFrame), stops (DataFrame), trips (DataFrame), return DataFrame representing ``stop_times.txt``. Includes the optional ``shape_dist_traveled`` column. Don't make stop times for trips with no nearby stops.
386,684
def expect_constructor(target): if not isinstance(target, ClassDouble): raise ConstructorDoubleError( .format(target), ) return expect(target)._doubles__new__
Set an expectation on a ``ClassDouble`` constructor :param ClassDouble target: The ClassDouble to set the expectation on. :return: an ``Expectation`` for the __new__ method. :raise: ``ConstructorDoubleError`` if target is not a ClassDouble.
386,685
def speech_speaker(self): if self.speaker: return self.speaker elif self.parent: return self.parent.speech_speaker() else: return None
Retrieves the speaker of the audio or video file associated with the element. The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly. Returns: str or None if not found
386,686
def execute_script(code_block, example_globals, image_path, fig_count, src_file, gallery_conf): time_elapsed = 0 stdout = print( % src_file) plt.close() cwd = os.getcwd() orig_stdout = sys.stdout try: os.chdir(os.path.dirname(sr...
Executes the code block of the example file
386,687
def police_priority_map_exceed_map_pri3_exceed(self, **kwargs): config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map, "name") name_key.text = kw...
Auto Generated Code
386,688
def get_diff_idxs(array, rtol, atol): C, N, L = array.shape diff_idxs = set() for c in range(1, C): for n in range(N): if not numpy.allclose(array[c, n], array[0, n], rtol, atol): diff_idxs.add(n) return numpy.fromiter(diff_idxs, int)
Given an array with (C, N, L) values, being the first the reference value, compute the relative differences and discard the one below the tolerance. :returns: indices where there are sensible differences.
386,689
def _dens(self,R,z,phi=0.,t=0.): x,y,z= bovy_coords.cyl_to_rect(R,phi,z) if self._aligned: xp, yp, zp= x, y, z else: xyzp= numpy.dot(self._rot,numpy.array([x,y,z])) xp, yp, zp= xyzp[0], xyzp[1], xyzp[2] m= numpy.sqrt(xp**2.+yp**2./self._b2+zp*...
NAME: _dens PURPOSE: evaluate the density for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the density HISTORY: 2018-08-06 - Written -...
386,690
def tatoeba(language, word, minlength = 10, maxlength = 100): word, sentences = unicode(word), [] page = requests.get( % (word, lltk.locale.iso639_1to3(language))) tree = html.fromstring(page.text) for sentence in tree.xpath(): sentence = sentence.strip(u).replace(u, u).replace(, u) if word in sentence and l...
Returns a list of suitable textsamples for a given word using Tatoeba.org.
386,691
def get_map(self, url, auth_map=None): response_code, content = self.get(url, auth_map) return response_code, content
Envia uma requisição GET. :param url: URL para enviar a requisição HTTP. :param auth_map: Dicionário com as informações para autenticação na networkAPI. :return: Retorna uma tupla contendo: (< código de resposta http >, < corpo da resposta >). :raise ConnectionError: Falha...
386,692
def robots(request): resp = request.response resp.status = resp.content_type = resp.body = return resp
Return a simple "don't index me" robots.txt file.
386,693
def get_email(self, token): resp = requests.get(self.emails_url, params={: token.token}) emails = resp.json().get(, []) email = try: email = emails[0].get() primary_emails = [e for e in emails if e.get(, False)] em...
Fetches email address from email API endpoint
386,694
def _create_function(name, doc=""): def _(col): sc = SparkContext._active_spark_context jc = getattr(sc._jvm.functions, name)(col._jc if isinstance(col, Column) else col) return Column(jc) _.__name__ = name _.__doc__ = doc return _
Create a PySpark function by its name
386,695
def _create_menu(self, items): menu = Gtk.Menu() self._create_menu_items(menu, items) return menu
Create a menu from the given node. :param list items: list of menu items :returns: a new Gtk.Menu object holding all items of the node
386,696
def file_md5(file_name): md5 = hashlib.md5() with open(file_name, ) as f: for chunk in iter(lambda: f.read(128 * md5.block_size), b): md5.update(chunk) return md5.hexdigest()
Generate an MD5 hash of the specified file. @file_name - The file to hash. Returns an MD5 hex digest string.
386,697
def get_force(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.plate_count): component_position, plate = QRTPacket._get_exact( RTForcePlate, data, component_pos...
Get force data.
386,698
def list(self, filter_name=None, filter_ids=None, filter_labels=None, page=None): label_param = if filter_labels: label_param = .join([.format(label, value) for label, value in filter_labels.items()]) filters = [ .format(filter_name) if filter_name else None, ...
This API endpoint returns a paginated list of the Servers associated with your New Relic account. Servers can be filtered by their name or by a list of server IDs. :type filter_name: str :param filter_name: Filter by server name :type filter_ids: list of ints :param fil...
386,699
def DetermineRunner(bbdir): tacfile = os.path.join(bbdir, ) if not os.path.exists(tacfile): import buildbot.scripts.runner return buildbot.scripts.runner.run with open(tacfile, ) as f: contents = f.read() try: if in contents: import buildbot_w...
Checks if the given directory is a worker or a master and returns the appropriate run function.