Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
356,300
def get_sequence_rules_for_assessment_part(self, assessment_part_id): collection = JSONClientValidated(, collection=, runtime=self._runtime) result = collection.find( dict({:...
Gets a ``SequenceRuleList`` for the given source assessment part. arg: assessment_part_id (osid.id.Id): an assessment part ``Id`` return: (osid.assessment.authoring.SequenceRuleList) - the returned ``SequenceRule`` list raise: NullArgument - ``assessment_part...
356,301
def with_name(cls, name, id_user=0, **extra_data): return cls(name=name, id_user=0, **extra_data)
Instantiate a WorkflowEngine given a name or UUID. :param name: name of workflow to run. :type name: str :param id_user: id of user to associate with workflow :type id_user: int :param module_name: label used to query groups of workflows. :type module_name: str
356,302
def _call(self, method, url, params): request_params = {} if method == : request_params[] = params elif method == : request_params[] = params response = requests.request(method, url, **request_params) return response
Return response from Clef API call.
356,303
def places_within_radius( self, place=None, latitude=None, longitude=None, radius=0, **kwargs ): kwargs[] = True kwargs[] = True kwargs[] = False kwargs.setdefault(, ) unit = kwargs.setdefault(, ) if place is not None: response =...
Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. The center of the circle can be specified by the identifier of another place in the collection with the *place* keyword arg...
356,304
def make_request(method, url, params): empty = [] for key, value in six.iteritems(params): if value is None: empty.append(key) for key in empty: del params[key] allow_redirects = params.get(, True) kwargs = { : allow_redirects, ...
Make an HTTP request, formatting params as required.
356,305
def get_excitation_spectrum(self, width=0.1, npoints=2000): roots = self.parse_tddft() data = roots["singlet"] en = np.array([d["energy"] for d in data]) osc = np.array([d["osc_strength"] for d in data]) epad = 20.0 * width emin = en[0] - epad emax = en[...
Generate an excitation spectra from the singlet roots of TDDFT calculations. Args: width (float): Width for Gaussian smearing. npoints (int): Number of energy points. More points => smoother curve. Returns: (ExcitationSpectrum) which can be p...
356,306
def delete_empty_dir(directory): if os.path.exists(directory): if os.path.isdir(directory): for d in os.listdir(directory): path = os.path.join(directory, d) if os.path.isdir(path): delete_empty_dir(path) if not os.listdir(directo...
删除空目录 :param directory: 目录路径
356,307
def encode(self, value): if value is None and self._default is not None: value = self._default for encoder in self._encoders: try: return encoder(value) except ValueError as ex: pass raise ValueError({}\ ...
The encoder for this schema. Tries each encoder in order of the types specified for this schema.
356,308
def make_xml_name(self, source_name, galkey, fullpath): format_dict = self.__dict__.copy() format_dict[] = self._name_factory.galprop_sourcekey(source_name=source_name, galpropkey=galkey) format_dict[] = fullpath ...
Make the name of an xml file for a model definition for a set of merged rings Parameters ---------- source_name : str The galprop component, used to define path to gasmap files galkey : str A short key identifying the galprop parameters fullpath : bool ...
356,309
def get_path_contents(self, project, provider_name, service_endpoint_id=None, repository=None, commit_or_branch=None, path=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if provider_name is not None: route_value...
GetPathContents. [Preview API] Gets the contents of a directory in the given source code repository. :param str project: Project ID or project name :param str provider_name: The name of the source provider. :param str service_endpoint_id: If specified, the ID of the service endpoint to q...
356,310
def get_request_id(self): try: return self.request_ids.popleft() except IndexError: new_request_id = self.highest_request_id + 1 assert new_request_id <= self.max_request_id self.highest_request_id = new_request_id return ...
This must be called while self.lock is held.
356,311
def run(self, root_allowed=False): self.root_allowed = root_allowed scan_devices(self.on_push, lambda d: d.src.lower() in self.devices, self.settings.get())
Start daemon mode :param bool root_allowed: Only used for ExecuteCmd :return: loop
356,312
def download_items(self, items, file_path, file_format=): download_url = download_url += + urlencode(((, file_format),)) item_data = {: list(items)} data = self.api_request(download_url, method=, data=json.dumps(item_data), raw=True) with open(file_path, ) as f: ...
Retrieve a file from the server containing the metadata and documents for the speficied items :type items: List or ItemGroup :param items: List of the the URLs of the items to download, or an ItemGroup object :type file_path: String :param file_path: the path to whic...
356,313
def short_relative_path_to(self, destination): relative = self.relpathto(destination) absolute = self.__class__(destination).abspath() if len(relative) < len(absolute): return relative return absolute
The shorter of either the absolute path of the destination, or the relative path to it >>> print(DotPath('/home/guido/bin').short_relative_path_to( ... '/home/guido/build/python.tar')) ../build/python.tar >>> print(DotPath('/home/guido/bin').short_relative_path_to( ...
356,314
def name2marc(self, key, value): result = self.get(, {}) result[] = value.get() result[] = value.get() result[] = value.get() result[] = value.get() if in value: self[] = [{: el} for el in value[]] if in value: self[] = [{: el} for el in value[]] if in value: ...
Populates the ``100`` field. Also populates the ``400``, ``880``, and ``667`` fields through side effects.
356,315
def _read_file_and_pos(self): try: with open(self.pos_storage_filename, ) as f: _pos = f.read() _logger.debug( % (_pos, self.pos_storage_filename)) if not _pos: return log_file,...
Read last position from file, store as current position
356,316
def binPack(self, jobShapes): logger.debug(, self.nodeShapes, len(jobShapes)) jobShapes.sort() jobShapes.reverse() assert len(jobShapes) == 0 or jobShapes[0] >= jobShapes[-1] for jS in jobShapes: self.addJobShap...
Pack a list of jobShapes into the fewest nodes reasonable. Can be run multiple times.
356,317
def as_boxes(self, solid=False): if solid: filled = self.sparse_solid else: filled = self.sparse_surface centers = indices_to_points(indices=filled, pitch=self.pitch, origin=self.ori...
A rough Trimesh representation of the voxels with a box for each filled voxel. Parameters ----------- solid: bool, if True return boxes for sparse_solid Returns --------- mesh: Trimesh object made up of one box per filled cell.
356,318
def get(*dataset, **kwargs): **** flags = [] opts = {} if kwargs.get(, False): opts[] = kwargs.get() elif kwargs.get(, False): flags.append() fields = kwargs.get(, ).split() if in fields: fields.remove() if in fields: fields.remov...
Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list childr...
356,319
def remove_file(self, name): self.check_write(name) path = os.path.join(self.cur_dir, name) os.remove(path)
Remove cur_dir/name.
356,320
def ask_for_board_id(self): board_id = raw_input("paste in board id or url: ").strip() m = re.search(r"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)", board_id) if m: board_id = m.group(1) return board_id
Factored out in case interface isn't keyboard
356,321
def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]): grammar_dictionary["select_result"] = [, , ] grammar_dictionary["single_source"] = [, ] del grammar_dictionary["source_subq"] del grammar_dictionary["source_table"] grammar_dictionary["expr"...
SQL is a predominately variable free language in terms of simple usage, in the sense that most queries do not create references to variables which are not already static tables in a dataset. However, it is possible to do this via derived tables. If we don't require this functionality, we can tighten the ...
356,322
def _list_vlans_by_name(self, name): results = self.list_vlans(name=name, mask=) return [result[] for result in results]
Returns a list of IDs of VLANs which match the given VLAN name. :param string name: a VLAN name :returns: List of matching IDs
356,323
def strip_docstrings(tokens): stack = [] state = for t in tokens: typ = t[0] if state == : if typ in (tokenize.NL, tokenize.COMMENT): yield t elif typ in (tokenize.DEDENT, tokenize.INDENT, tokenize.STRING): stack.append(t) ...
Replace docstring tokens with NL tokens in a `tokenize` stream. Any STRING token not part of an expression is deemed a docstring. Indented docstrings are not yet recognised.
356,324
def run(self, image, command=None, create_kwargs=None, start_kwargs=None, volume_bindings=None, privileged=None): logger.info("creating container from image and running it", image) create_kwargs = create_kwargs or {} if not in create_kwargs: conf = {} ...
create container from provided image and start it for more info, see documentation of REST API calls: * containers/{}/start * container/create :param image: ImageName or string, name or id of the image :param command: str :param create_kwargs: dict, kwargs for docker....
356,325
def _submit(self): user_prompt_issueI want to do the thing.user_prompt_repovsoch/hello-worlduser_prompt_titleError with this thingrecord_asciinema/tmp/helpme.93o__nt5.jsonrecord_environment body = self.data[] title = self.data[] repo = self.data[] envars = self.data.g...
submit the issue to github. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'user_prompt_repo': 'vsoch/hello-world', 'user_prompt_title': 'Error with this thing', 'record_asciinema': '/tmp/helpme.93o__nt5.json', '...
356,326
def reshape_text(buffer, from_row, to_row): lines = buffer.text.splitlines(True) lines_before = lines[:from_row] lines_after = lines[to_row + 1:] lines_to_reformat = lines[from_row:to_row + 1] if lines_to_reformat: length = re.search(r, lines_to_reformat[0]).end() inde...
Reformat text, taking the width into account. `to_row` is included. (Vi 'gq' operator.)
356,327
def run(self): self.tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp) | ...
Creates a listener and loops while waiting for an event. Intended to run as a background thread.
356,328
def xSectionChunk(lines): KEYWORDS = (, , , , , , , , , , , ) result = {: None, : None, : None, ...
Parse XSEC Method
356,329
def _parse_complex_list(self, prop): xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop)
Default parsing operation for lists of complex structs
356,330
def CreateAllStaticECMWFFiles(in_catchment, catchment_river_id, rapid_output_folder, rapid_connect_file, file_geodatabase=None ): lsm_grid_folder = \ os....
This creates all of the ECMWF grid weight tables using an area weighted method based on Esri's RAPID_Toolbox. Parameters ---------- in_catchment: str Path to the Catchment shapefile. catchment_river_id: str The name of the field with the river ID (Ex. 'DrainLnID' or 'LINKNO'). r...
356,331
def save(path, json_data): try: loop = asyncio.get_event_loop() if loop.is_running(): asyncio.run_coroutine_threadsafe(Persistence._save(path, json_data), loop) else: loop.run_until_complete(Persistence._save(path, json_data)) ...
Saves json_data in path :param Path path: Path that json_data will be persisted :param json_data: Data that will be persisted
356,332
def constructTx(self): ops = list() for op in self.ops: if isinstance(op, ProposalBuilder): proposal = op.get_raw() if proposal: ops.append(proposal) elif isinstance(op, self.operation_...
Construct the actual transaction and store it in the class's dict store
356,333
def start_timer(self, name): op_stat = self.get_op_statistic(name) op_stat.start_timer() return op_stat
This method is called by pywbem to start the timer for a particular operation execution. It returns the corresponding :class:`~pywbem.OperationStatistic` object, creating one if needed. The timer is subsequently stopped by pywbem by calling the :meth:`~pywbem.OperationStatistic.stop_tim...
356,334
def C_Reader_Harris_Gallagher(D, Do, rho, mu, m, taps=): r - 0.8M_2 = \frac{2L_2 = 0 If the orifice has D and D/2 taps: .. math:: L_1 = 1 .. math:: L_2 = \frac{0.0254}{D} Parameters ---------- D : float Upstream internal pipe diamet...
r'''Calculates the coefficient of discharge of the orifice based on the geometry of the plate, measured pressures of the orifice, mass flow rate through the orifice, and the density and viscosity of the fluid. .. math:: C = 0.5961 + 0.0261\beta^2 - 0.216\beta^8 + 0.000521\left(\frac{ 1...
356,335
def array2qimage(array, normalize = False): if _np.ndim(array) == 2: array = array[...,None] elif _np.ndim(array) != 3: raise ValueError("array2qimage can only convert 2D or 3D arrays (got %d dimensions)" % _np.ndim(array)) if array.shape[2] not in (1, 2, 3, 4): raise ValueError...
Convert a 2D or 3D numpy array into a 32-bit QImage_. The first dimension represents the vertical image axis; the optional third dimension is supposed to contain 1-4 channels: ========= =================== #channels interpretation ========= =================== 1 scalar/gray ...
356,336
def subtask(*args, **kwargs): depth = kwargs.get(, 2) prefix = kwargs.get(, + * depth + ) tail = kwargs.get(, ) doc1 = kwargs.get(, False) color = kwargs.get(, cyan) def real_decorator(func): if doc1: return print_full_name(color=color, prefix=prefix, ...
Decorator which prints out the name of the decorated function on execution.
356,337
def sfs_folded(ac, n=None): ac, n = _check_ac_n(ac, n) mac = np.amin(ac, axis=1) mac = mac.astype(int, copy=False) x = n//2 + 1 s = np.bincount(mac, minlength=x) return s
Compute the folded site frequency spectrum given reference and alternate allele counts at a set of biallelic variants. Parameters ---------- ac : array_like, int, shape (n_variants, 2) Allele counts array. n : int, optional The total number of chromosomes called. Returns --...
356,338
def pkcs_emsa_pss_verify(M, EM, emBits, h, mgf, sLen): hLen = _hashFuncParams[h][0] hFunc = _hashFuncParams[h][1] mHash = hFunc(M) emLen = int(math.ceil(emBits/8.)) if emLen < hLen + sLen + 2: return False if EM[-1] != :...
Implements EMSA-PSS-VERIFY() function described in Sect. 9.1.2 of RFC 3447 Input: M : message to be encoded, an octet string EM : encoded message, an octet string of length emLen = ceil(emBits/8) emBits: maximal bit length of the integer resulting of pkcs_os2ip(EM) h : hash f...
356,339
def execution_history_focus(self, model, prop_name, info): if state_machine_execution_engine.status.execution_mode in \ [StateMachineExecutionStatus.STARTED, StateMachineExecutionStatus.STOPPED, StateMachineExecutionStatus.FINISHED]: if self.parent is not No...
Arranges to put execution-history widget page to become top page in notebook when execution starts and stops and resets the boolean of modification_history_was_focused to False each time this notification are observed.
356,340
def __str_cleanup(line): if in line: line = line.replace(" line = line.strip() if in line: line = return line
Remove the unnecessary characters in the line that we don't want :param str line: :return str:
356,341
def read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None): pandas_sql = pandasSQL_builder(con) if isinstance(pandas_sql, SQLiteDatabase): return pandas_sql.read_query( sql, index_col=index_col, params=params, ...
Read SQL query or database table into a DataFrame. This function is a convenience wrapper around ``read_sql_table`` and ``read_sql_query`` (for backward compatibility). It will delegate to the specific function depending on the provided input. A SQL query will be routed to ``read_sql_query``, while a d...
356,342
def html_format(data, out=, opts=None, **kwargs): *keyvalue if not opts: opts = __opts__ return salt.output.html_format(data, out, opts=opts, **kwargs)
Return the formatted string as HTML. data The JSON serializable object. out: ``nested`` The name of the output to use to transform the data. Default: ``nested``. opts Dictionary of configuration options. Default: ``__opts__``. kwargs Arguments to sent to the outputter...
356,343
def _transform_should_cast(self, func_nm): return (self.size().fillna(0) > 0).any() and ( func_nm not in base.cython_cast_blacklist)
Parameters: ----------- func_nm: str The name of the aggregation function being performed Returns: -------- bool Whether transform should attempt to cast the result of aggregation
356,344
def add_node(self, name_base, attrs=None): if name_base not in self.counters: node_id = name_base else: node_id = % (name_base, self.counters[name_base]) node = {: node_id} if attrs: node[] = attrs self.nodes.append(node) self...
Add a node with a given base name to the Nugget and return ID.
356,345
def image_to_url(image, colormap=None, origin=): if isinstance(image, str) and not _is_url(image): fileformat = os.path.splitext(image)[-1][1:] with io.open(image, ) as f: img = f.read() b64encoded = base64.b64encode(img).decode() url = .format(fileformat, b64encoded...
Infers the type of an image argument and transforms it into a URL. Parameters ---------- image: string, file or array-like object * If string, it will be written directly in the output file. * If file, it's content will be converted as embedded in the output file. * If arr...
356,346
def get_sdb_secret_version_paths(self, sdb_id): sdb_resp = get_with_retry(str.join(, [self.cerberus_url, , sdb_id]), headers=self.HEADERS) throw_if_bad_response(sdb_resp) return sdb_resp.json()
Get SDB secret version paths. This function takes the sdb_id
356,347
def _generate_injection_cmd(self, meta_data): cmd = [] self._validate_templates(meta_data) for i, config_data in enumerate(meta_data): container_path = os.path.join(config_data[], config_data[]) cmd.append("mkdir") cmd.append("-p") cmd.ap...
example injector response: [ { "config_path":"/configs/cli_config.py", "path":"/opt/cia-cli/cia_sdk/config", "user":"injector", "status_code":201, "chmod":755, "checksum":"a4bcf3939dd3a6aa4e04ee9f92131df4", ...
356,348
def layers(self): layermap = dict() for operator in self.ops: if hasattr(operator, ): layermap.update(operator.layers()) return layermap
Construct Keras input layers for all feature transformers in the pump. Returns ------- layers : {field: keras.layers.Input} A dictionary of keras input layers, keyed by the corresponding fields.
356,349
def execute(self): parser = NewOptionParser(prog=self.prog_name, usage=self.usage_info, formatter = NewFormatter(), add_help_option = False, option_list=self.o...
Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it.
356,350
def setInterimValue(self, keyword, value): val = str( if not value and value != 0 else value).strip() interims = self.getInterimFields() for interim in interims: if interim[] == keyword: interim[] = val self.setInterimFields(interims)...
Sets a value to an interim of this analysis :param keyword: the keyword of the interim :param value: the value for the interim
356,351
def remove_handler(self, handler): super(Session, self).remove_handler(handler) self.promote() self.stop_heartbeat()
Detach active handler from the session `handler` Handler to remove
356,352
def compute_from_counts(self,countmat,beta=0): self.counts = countmat self.width = len(countmat) self.bgscale = 0 maxcount = 0 for col in countmat: tot = 0 for v in col.values(): tot = tot + v if tot > maxc...
m.compute_from_counts(,countmat,beta=0) -- Utility function to build a motif object from a matrix of letter counts.
356,353
def getattribute(value, arg): if callable(getattr(value, arg)): return str(getattr(value, arg)()) elif hasattr(value, str(arg)): return getattr(value, arg) elif hasattr(value, ) and value.has_key(arg): return value[arg] elif numeric_test.match(str(arg)) and len(value) >...
Gets an attribute of an object dynamically from a string name
356,354
def match_path_against(pathname, patterns, case_sensitive=True): if case_sensitive: match_func = fnmatchcase pattern_transform_func = (lambda w: w) else: match_func = fnmatch pathname = pathname.lower() pattern_transform_func = _string_lower for pattern in set(pa...
Determines whether the pathname matches any of the given wildcard patterns, optionally ignoring the case of the pathname and patterns. :param pathname: A path name that will be matched against a wildcard pattern. :param patterns: A list of wildcard patterns to match_path the filename agains...
356,355
def add_conversation_tab(self, conv_id, switch=False): conv_widget = self.get_conv_widget(conv_id) self._tabbed_window.set_tab(conv_widget, switch=switch, title=conv_widget.title)
Add conversation tab if not present, and optionally switch to it.
356,356
def read_sql(self, code: str) -> pandas.DataFrame: if self.kind != SessionKind.SQL: raise ValueError("not a SQL session") output = self._execute(code) output.raise_for_status() if output.json is None: raise RuntimeError("statement had no JSON output") ...
Evaluate a Spark SQL satatement and retrieve the result. :param code: The Spark SQL statement to evaluate.
356,357
def template_update(call=None, kwargs=None): CPU="1.0" DISK=[IMAGE="Ubuntu-14.04"] GRAPHICS=[LISTEN="0.0.0.0",TYPE="vnc"] \\ MEMORY="1024" NETWORK="yes" NIC=[NETWORK="192net",NETWORK_UNAME="oneadmin"] \\ OS=[ARCH="x86_64"] SUNSTONE_CAPACITY_SELECT="YES" SUNSTONE_NETWORK_SELECT="YES" \\ ...
Replaces the template contents. .. versionadded:: 2016.3.0 template_id The ID of the template to update. Can be used instead of ``template_name``. template_name The name of the template to update. Can be used instead of ``template_id``. path The path to a file containing the ...
356,358
def fast_approximate_personalized_pagerank(s, r, w_i, a_i, out_degree, in_degree, ...
Calculates the approximate personalized PageRank starting from a seed node without self-loops.
356,359
def get_so_far(self): position = self.packet.tell() self.rewind() return self.packet.read(position)
Returns the `str` bytes of this message that have been parsed and returned. The string passed into a message's constructor can be regenerated by concatenating ``get_so_far`` and `get_remainder`.
356,360
def match_pattern(self, path): for pattern in self.__pattern: if len(fnmatch.filter([path], pattern)) > 0: return True return False
Return if given path match the pattern(s). :param path: path to check. :return: True if match, False otherwise.
356,361
def list(self, path): try: payload = { : True } return self._adapter.get(.format(path), params=payload).json() except exceptions.InvalidPath: return None
GET /<path>?list=true :param path: :type path: :return: :rtype:
356,362
def get_date_format_string(period):
For a given period (e.g. 'month', 'day', or some numeric interval such as 3600 (in secs)), return the format string that can be used with strftime to format that time to specify the times across that interval, but no more detailed. For example, >>> get_date_format_string('month') '%Y-%m' >>> get_date_format_str...
356,363
def attach(self, handle, filters=None, resolution=None): params = self._get_params(filters=filters, resolution=resolution) c = computation.Computation( lambda since: self._transport.attach(handle, params)) self._computations.add(c) return c
Attach to an existing SignalFlow computation.
356,364
def send_confirmation(self, message, success=True): message = message.strip() if not self.confirmation: return try: self.confirmation.send(message, success) except Exception as e: logger.warning(.format(self.name, e))
Send success or error message to configured confirmation :param str message: Body message to send :param bool success: Device executed successfully to personalize message :return: None
356,365
def get_all_resource_ids_in_datastore(configuration=None): resource = Resource(configuration=configuration) success, result = resource._read_from_hdx(, , , Resource.actions()[], limit=10000) resource_ids = list() if not ...
Get list of resources that have a datastore returning their ids. Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: List[str]: List of resource ids that are in the datastore
356,366
def unbind(self, exchange, source, routing_key=, nowait=True, arguments={}, ticket=None, cb=None): nowait = nowait and self.allow_nowait() and not cb args = Writer() args.write_short(ticket or self.default_ticket).\ write_shortstr(exchange).\ writ...
Unbind an exchange from another.
356,367
def _color_button_clicked(self, n,top): self._button_save.setEnabled(True) if top: self._color_dialogs_top[n].open() else: self._color_dialogs_bottom[n].open()
Opens the dialog.
356,368
def get_all_conditions(self): for condition_set in sorted(self.get_condition_sets(), key=lambda x: x.get_group_label()): group = unicode(condition_set.get_group_label()) for field in condition_set.fields.itervalues(): yield condition_set.get_id(), group, field
Returns a generator which yields groups of lists of conditions. >>> for set_id, label, field in gargoyle.get_all_conditions(): #doctest: +SKIP >>> print "%(label)s: %(field)s" % (label, field.label) #doctest: +SKIP
356,369
def shorten_type(typ): offset = 0 for prefix in SHORTEN_TYPE_PREFIXES: if typ.startswith(prefix): if len(prefix) > offset: offset = len(prefix) return typ[offset:]
Shorten a type. E.g. drops 'System.'
356,370
def segment_into_chars(utterance: str) -> str: if not isinstance(utterance, str): raise TypeError("Input type must be a string. Got {}.".format(type(utterance))) utterance.strip() utterance = utterance.replace(" ", "") return " ".join(utterance)
Segments an utterance into space delimited characters.
356,371
def add_rds_instance(self, instance, region): if not self.all_rds_instances and instance.status != : return dest = instance.endpoint[0] if not dest: return self.index[dest] = [region, instance.id] ...
Adds an RDS instance to the inventory and index, as long as it is addressable
356,372
def __write(self, containers, initialize=True): path = self._state_file self._assure_dir() try: flags = os.O_WRONLY | os.O_CREAT if initialize: flags |= os.O_EXCL with os.fdopen(os.open(path, flags), "w") as f: yaml.saf...
Write the given state information into a file
356,373
def make_view(robot): assert isinstance(robot, BaseRoBot),\ "RoBot should be an BaseRoBot instance." @csrf_exempt def werobot_view(request): timestamp = request.GET.get("timestamp", "") nonce = request.GET.get("nonce", "") signature = request.GET.get("signature", "") ...
为一个 BaseRoBot 生成 Django view。 :param robot: 一个 BaseRoBot 实例。 :return: 一个标准的 Django view
356,374
def option(*args, **kwargs): def decorate(f): if not hasattr(f, "optparser"): f.optparser = SubCmdOptionParser() f.optparser.add_option(*args, **kwargs) return f return decorate
Decorator to add an option to the optparser argument of a Cmdln subcommand. Example: class MyShell(cmdln.Cmdln): @cmdln.option("-f", "--force", help="force removal") def do_remove(self, subcmd, opts, *args): #...
356,375
def get_contents(self, path, ref=github.GithubObject.NotSet): return self.get_file_contents(path, ref)
:calls: `GET /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents>`_ :param path: string :param ref: string :rtype: :class:`github.ContentFile.ContentFile`
356,376
def _PrintExtractionStatusUpdateLinear(self, processing_status): for worker_status in processing_status.workers_status: status_line = ( ).format( worker_status.identifier, worker_status.pid, worker_status.number_of_produced_events, worker_sta...
Prints an extraction status update in linear mode. Args: processing_status (ProcessingStatus): processing status.
356,377
def future(self, request_iterator, timeout=None, metadata=None, credentials=None): return _utils.wrap_future_call( self._inner.future( _utils.WrappedAsyncIterator(request_iterator, self._loop), ...
Asynchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: An optional duration of time in seconds to allow for the RPC. If None, the timeout is considered infinite. metadata: Optional :term:`m...
356,378
def update_count(self): node_rating_count = self.node.rating_count node_rating_count.comment_count = self.node.comment_set.count() node_rating_count.save()
updates comment count
356,379
def sorted(self, by, **kwargs): sort_idc = np.argsort(self[by], **kwargs) return self.__class__( self[sort_idc], h5loc=self.h5loc, split_h5=self.split_h5, name=self.name )
Sort array by a column. Parameters ========== by: str Name of the columns to sort by(e.g. 'time').
356,380
def delete(self, key, *keys): fut = self.execute(b, key, *keys) return wait_convert(fut, int)
Delete a key.
356,381
def key_deploy(self, host, ret): t auth ssh_key_deploypasswdssh_passwdstderrPermission deniedPermission denied for host {0}, do you want to deploy the salt-ssh key? (password required):[Y/n] nNpasswdPassword for {0}@{1}: user'], host) ) return self._key_deploy_run(host, targe...
Deploy the SSH key if the minions don't auth
356,382
def import_object_with_scope(name): parts = name.split() current_name = parts[0] obj = import_module(current_name) scope = None for part in parts[1:]: current_name += + part try: if hasattr(obj, ): sub_obj = obj.__dict__[part] else: sub_obj = getattr(obj...
Imports a Python object by an absolute identifier. # Arguments name (str): The name of the Python object to import. # Returns (any, Module): The object and the module that contains it. Note that for plain modules loaded with this function, both elements of the tuple may be the same object.
356,383
def gitignore_template(self, language): url = self._build_url(, , language) json = self._json(self._get(url), 200) if not json: return return json.get(, )
Returns the template for language. :returns: str
356,384
def loadIcon(self, fileName, color=None): if not fileName: return None key = (fileName, color) if key not in self._icons: try: with open(fileName, ) as input: svg = input.read() self._icons[key] = self.createI...
Reads SVG from a file name and creates an QIcon from it. Optionally replaces the color. Caches the created icons. :param fileName: absolute path to an icon file. If False/empty/None, None returned, which yields no icon. :param color: '#RRGGBB' string (e.g. '#FF0000'...
356,385
def batchnorm_2d(nf:int, norm_type:NormType=NormType.Batch): "A batchnorm2d layer with `nf` features initialized depending on `norm_type`." bn = nn.BatchNorm2d(nf) with torch.no_grad(): bn.bias.fill_(1e-3) bn.weight.fill_(0. if norm_type==NormType.BatchZero else 1.) return bn
A batchnorm2d layer with `nf` features initialized depending on `norm_type`.
356,386
def load_hdf(cls, filename, path=): stars = pd.read_hdf(filename,path+) constraint_df = pd.read_hdf(filename,path+) with pd.HDFStore(filename) as store: has_orbpop = .format(path) in store has_triple_orbpop = .format(path) in store attrs = store.get_...
Loads StarPopulation from .h5 file Correct properties should be restored to object, and object will be original type that was saved. Complement to :func:`StarPopulation.save_hdf`. Example usage:: >>> from vespa.stars import Raghavan_BinaryPopulation, StarPopulation ...
356,387
def _extractFeatureClasses(lookupIndex, subtableIndex, classDefs, coverage=None): classDict = {} for glyphName, classIndex in classDefs.items(): if classIndex not in classDict: classDict[classIndex] = set() classDict[classIndex].add(glyphName) revisedClass0 = set()...
Extract classes for a specific lookup in a specific subtable. This is relatively straightforward, except for class 0 interpretation. Some fonts don't have class 0. Some fonts have a list of class members that are clearly not all to be used in kerning pairs. In the case of a missing class 0, the coverage...
356,388
def delete(self, uri, logon_required=True): if logon_required: self.logon() url = self.base_url + uri self._log_http_request(, url, headers=self.headers) stats = self.time_stats_keeper.get_stats( + uri) stats.begin() req = self._session or requests ...
Perform the HTTP DELETE method against the resource identified by a URI. A set of standard HTTP headers is automatically part of the request. If the HMC session token is expired, this method re-logs on and retries the operation. Parameters: uri (:term:`string`): ...
356,389
def pointColors(self, scalars, cmap="jet", alpha=1, bands=None, vmin=None, vmax=None): poly = self.polydata(False) if isinstance(scalars, str): scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) n = len(scalars) useAlpha = False if n != poly.Ge...
Set individual point colors by providing a list of scalar values and a color map. `scalars` can be a string name of the ``vtkArray``. :param cmap: color map scheme to transform a real number into a color. :type cmap: str, list, vtkLookupTable, matplotlib.colors.LinearSegmentedColormap :...
356,390
def describe(i): d=i.get(,{}) a=d.get(,{}) ck.out() ck.out() ck.out() r=ck.inp({:}) x=r[] if x!=: a[]=x r=ck.inp({:}) x=r[] if x!=: a[]=x r=ck.inp({:}) x=r[] if x!=: a[]=x r=ck.inp({:}) x=r[] if x!=: a[]=x r=ck.inp({:}) x=r[] i...
Input: { (dict) - dict with current repo description } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 (dict) - updated dict with current ...
356,391
def loaded_instruments(self) -> Dict[str, Optional[]]: return {mount.name.lower(): instr for mount, instr in self._instruments.items()}
Get the instruments that have been loaded into the protocol. :returns: A dict mapping mount names in lowercase to the instrument in that mount, or `None` if no instrument is present.
356,392
def filter_input(self, forced=False, context=None): content = [] for hunk in self.hunks(forced, context=context): content.append(hunk) return content
Passes each hunk (file or code) to the 'input' methods of the compressor filters.
356,393
def process_input_data(filename, imager, grid_data, grid_norm, grid_weights): ms = oskar.MeasurementSet.open(filename) block_start = 0 num_rows = ms.num_rows num_baselines = ms.num_stations * (ms.num_stations - 1) // 2 while block_start < num_rows: block_size = num_rows - blo...
Reads visibility data from a Measurement Set. The visibility grid or weights grid is updated accordingly. Visibility data are read from disk in blocks of size num_baselines. Args: filename (str): Name of Measurement Set to open. imager (oskar.Imager): Handle...
356,394
def search(obj, glob, yielded=False, separator="/", afilter=None, dirs = True): def _search_view(obj, glob, separator, afilter, dirs): view = {} globlist = __safe_path__(glob, separator) for path in _inner_search(obj, globlist, separator, dirs=dirs): try: va...
Given a path glob, return a dictionary containing all keys that matched the given glob. If 'yielded' is true, then a dictionary will not be returned. Instead tuples will be yielded in the form of (path, value) for every element in the document that matched the glob.
356,395
def process_npdu(self, npdu): if _debug: RouterToRouterService._debug("process_npdu %r", npdu) pdu = PDU() npdu.encode(pdu) if _debug: RouterToRouterService._debug(" - pdu: %r", pdu) if pdu.pduDestination.addrType == Address.localBroadcastAddr: ...
encode NPDUs from the service access point and send them downstream.
356,396
def fill_categorical_na(df, nan_cat=): for col in df.columns[df.isna().any()].tolist(): if df[col].dtype.name != : df[col] = df[col].fillna() else: try: df[col].cat.add_categories([nan_cat], inplace=True) except Val...
Fill categoricals with 'NA', possibly creating a new category, and fill other NaNa with blanks
356,397
def _output(self, s): if s.lower().startswith(b): self._buffer.insert(1, s) else: self._buffer.append(s)
Host header should always be first
356,398
def check_alert(self, text): try: alert = Alert(world.browser) if alert.text != text: raise AssertionError( "Alert text expected to be {!r}, got {!r}.".format( text, alert.text)) except WebDriverException: pass
Assert an alert is showing with the given text.
356,399
def delete_group_category(self, group_category_id): path = {} data = {} params = {} path["group_category_id"] = group_category_id self.logger.debug("DELETE /api/v1/group_categories/{group_category_id} with query params: {params} and form data...
Delete a Group Category. Deletes a group category and all groups under it. Protected group categories can not be deleted, i.e. "communities" and "student_organized".