Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
369,300
def insert(self, i, tag1, tag2, cmd="prevtag", x=None, y=None): if " < " in tag1 and not x and not y: tag1, x = tag1.split(" < "); cmd="prevtag" if " > " in tag1 and not x and not y: x, tag1 = tag1.split(" > "); cmd="nexttag" lazylist.insert(self, i, [tag1, tag2,...
Inserts a new rule that updates words with tag1 to tag2, given constraints x and y, e.g., Context.append("TO < NN", "VB")
369,301
def loadPage(self, number=0): if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") val = _fitz.Document_loadPage(self, number) if val: val.thisown = True val.parent = weakref.proxy(self) ...
loadPage(self, number=0) -> Page
369,302
def start(self, hash, name=None, service=): params = {: hash} if name: params[] = name return self.request.post(service + , params)
Start a recording for the provided hash :param hash: The hash to start recording with :type hash: str :param name: The name of the recording :type name: str :param service: The service for this API call (facebook, etc) :type service: str ...
369,303
def create_double(self, value: float) -> Double: self.append((6, value)) self.append(None) return self.get(self.raw_count - 2)
Creates a new :class:`ConstantDouble`, adding it to the pool and returning it. :param value: The value of the new Double.
369,304
def loads(self, param): if isinstance(param, ProxyRef): try: return self.lookup_url(param.url, param.klass, param.module) except HostError: print "Can't lookup for the actor received with the call. \ It does not exist or the ur...
Checks the return parameters generating new proxy instances to avoid query concurrences from shared proxies and creating proxies for actors from another host.
369,305
def concat_variant_files(orig_files, out_file, regions, ref_file, config): if not utils.file_exists(out_file): input_file_list = _get_file_list(orig_files, out_file, regions, ref_file, config) try: out_file = _run_concat_variant_files_gatk4(input_file_list, out_file, config) ...
Concatenate multiple variant files from regions into a single output file. Uses GATK4's GatherVcfs, falling back to bcftools concat --naive if it fails. These both only combine samples and avoid parsing, allowing scaling to large file sizes.
369,306
def math_func(f): @wraps(f) def wrapper(*args, **kwargs): if len(args) > 0: return_type = type(args[0]) if kwargs.has_key(): return_type = kwargs[] kwargs.pop() return return_type(f(*args, **kwargs)) args = list((setify(x) for x in arg...
Statics the methods. wut.
369,307
def setText(self, label, default=, description=, format=): obj = self.load(label) if obj == None: obj=default self.save(obj, label) textw = Text(value=obj, description=description) hndl = interact(self.save, obj=textw, label=fixed(label), format=fixed...
Set text in a notebook pipeline (via interaction or with nbconvert)
369,308
def dump(self, fields=None, exclude=None): exclude = exclude or [] d = {} if fields and self._primary_field not in fields: fields = list(fields) fields.append(self._primary_field) for k, v in self.properties.items(): if ((not fields) or (k in ...
Dump current object to dict, but the value is string for manytomany fields will not automatically be dumpped, only when they are given in fields parameter
369,309
def NameImport(package, as_name=None, prefix=None): if prefix is None: prefix = u"" children = [Name(u"import", prefix=prefix), package] if as_name is not None: children.extend([Name(u"as", prefix=u" "), Name(as_name, prefix=u" ")]) return Node(syms.import_n...
Accepts a package (Name node), name to import it as (string), and optional prefix and returns a node: import <package> [as <as_name>]
369,310
def convert2hdf5(ClassIn, platform_name, bandnames, scale=1e-06): import h5py instr = ClassIn(bandnames[0], platform_name) instr_name = instr.instrument.replace(, ) filename = os.path.join(instr.output_dir, "rsr_{0}_{1}.h5".format(instr_name, ...
Retrieve original RSR data and convert to internal hdf5 format. *scale* is the number which has to be multiplied to the wavelength data in order to get it in the SI unit meter
369,311
def eth_getCode(self, address, block=BLOCK_TAG_LATEST): block = validate_block(block) return (yield from self.rpc_call(, [address, block]))
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode :param address: Address of contract :type address: str :param block: Block tag or number (optional) :type block: int or BLOCK_TAGS :return: code :rtype: str
369,312
def save_fig_with_metadata(fig, filename, fig_kwds=None, **kwds): if fig_kwds is None: fig_kwds = {} try: extension = os.path.splitext(filename)[1] kwds[] = pycbc.version.git_verbose_msg _metadata_saver[extension](fig, filename, fig_kwds, kwds) except KeyError: r...
Save plot to file with metadata included. Kewords translate to metadata that is stored directly in the plot file. Limited format types available. Parameters ---------- fig: matplotlib figure The matplotlib figure to save to the file filename: str Name of file to store the plot.
369,313
def roc(self): return plot.roc(self.y_true, self.y_score, ax=_gen_ax())
ROC plot
369,314
def parse_package_for_version(name): from utool import util_regex init_fpath = join(name, ) version_errmsg = textwrap.dedent( s __init__.py file. Try something like: __version__ = version[0-9a-zA-Z.]+__version__ *= *[\ + val_regex def parse_version(line): l...
Searches for a variable named __version__ in name's __init__.py file and returns the value. This function parses the source text. It does not load the module.
369,315
def dump_json(token_dict, dump_path): if sys.version > : with open(dump_path, , encoding=) as output_file: json.dump(token_dict, output_file, indent=4) else: with open(dump_path, ) as output_file: json.dump(token_dict, output_file, indent=4)
write json data to file
369,316
def execute_download_request(request): if request.save_response and request.data_folder is None: raise ValueError( ) if not request.will_download: return None try_num = SHConfig().max_download_attempts response = None while try_num > 0: try: ...
Executes download request. :param request: DownloadRequest to be executed :type request: DownloadRequest :return: downloaded data or None :rtype: numpy array, other possible data type or None :raises: DownloadFailedException
369,317
def submit_job(self, bundle, job_config=None): return self._delegator._submit_job(bundle=bundle, job_config=job_config)
Submit a Streams Application Bundle (sab file) to this Streaming Analytics service. Args: bundle(str): path to a Streams application bundle (sab file) containing the application to be submitted job_config(JobConfig): a job configuration overlay ...
369,318
def raw_clean(self, datas): datas = strip_tags(datas) datas = STOP_WORDS.rebase(datas, ) datas = PUNCTUATION.sub(, datas) datas = datas.lower() return [d for d in datas.split() if len(d) > 1]
Apply a cleaning on raw datas.
369,319
def get_view(self): d = self.declaration if d.cached and self.widget: return self.widget if d.defer_loading: self.widget = FrameLayout(self.get_context()) app = self.get_context() app.deferred_call( lambda: self.widget....
Get the page to display. If a view has already been created and is cached, use that otherwise initialize the view and proxy. If defer loading is used, wrap the view in a FrameLayout and defer add view until later.
369,320
def purge_archives(self): klass = self.get_version_class() qs = klass.normal.filter(object_id=self.object_id, state=self.ARCHIVED).order_by()[self.NUM_KEEP_ARCHIVED:] for obj in qs: obj._delete_reverses() klass.normal.filter(vid...
Delete older archived items. Use the class attribute NUM_KEEP_ARCHIVED to control how many items are kept.
369,321
def migratable_vc_domains(self): if not self.__migratable_vc_domains: self.__migratable_vc_domains = MigratableVcDomains(self.__connection) return self.__migratable_vc_domains
Gets the VC Migration Manager API client. Returns: MigratableVcDomains:
369,322
def deserialize(self, obj): if obj[]: return obj[] else: guid = obj[] if not guid in object_registry: instance = JSObject(self, guid) object_registry[guid] = instance return object_registry[guid]
Deserialize an object from the front-end.
369,323
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): self.fileExtension = extension with open(path, ) as nwsrfsFile: for line in nwsrfsFile: sline = line.strip().split() ...
NWSRFS Read from File Method
369,324
def changeLogType(self): logType = self.selectedType() programs = self.logList.get(logType)[0] default = self.logList.get(logType)[1] if logType in self.logList: self.programName.clear() self.programName.addItems(programs) self.programName.set...
Populate log program list to correspond with log type selection.
369,325
def get_monolayer(self): unit_a = self.get_unit_primitive_area Nsurfs = self.Nsurfs_ads_in_slab Nads = self.Nads_in_slab return Nads / (unit_a * Nsurfs)
Returns the primitive unit surface area density of the adsorbate.
369,326
def use(self, *middleware: MiddlewareType) -> None: for m in middleware: if is_middleware(m): self.middleware.append(m)
Register Middleware :param middleware: The Middleware Function
369,327
def to_simplex(y): r n = y.shape[-1] z = expit(y - np.log(n - np.arange(1, n+1))) x = np.empty(y.shape) x[..., 0] = z[..., 0] x[..., 1:] = z[..., 1:] * (1 - z[..., :-1]).cumprod(axis=-1) return x
r""" Interprets the last index of ``y`` as stick breaking fractions in logit space and returns a non-negative array of the same shape where the last dimension always sums to unity. A unit simplex is a list of non-negative numbers :math:`(x_1,...,x_K)` that sum to one, :math:`\sum_{k=1}^K x_k=...
369,328
def survival_rate(work_db): kills = sum(r.is_killed for _, r in work_db.results) num_results = work_db.num_results if not num_results: return 0 return (1 - kills / num_results) * 100
Calcuate the survival rate for the results in a WorkDB.
369,329
def _temporal_distance_cdf(self): distance_split_points = set() for block in self._profile_blocks: if block.distance_start != float(): distance_split_points.add(block.distance_end) distance_split_points.add(block.distance_start) distance_spli...
Temporal distance cumulative density function. Returns ------- x_values: numpy.array values for the x-axis cdf: numpy.array cdf values
369,330
def d3logpdf_dlink3(self, link_f, y, Y_metadata=None): c = np.zeros_like(y) if Y_metadata is not None and in Y_metadata.keys(): c = Y_metadata[] uncensored = (1-c)*(-2/link_f**3+ 6*y**self.r/link_f**4) censored = c*6*y**self.r/link_f**4 ...
Third order derivative log-likelihood function at y given link(f) w.r.t link(f) .. math:: \\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables link(...
369,331
async def start(self): await self.server.start() self.port = self.server.port
Start the supervisor server.
369,332
def reject_source(ident, comment): source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_REFUSED if current_user.is_authenticated: source.validation.by = current_user._get_current_object() source.sav...
Reject a source for automatic harvesting
369,333
def Histograms(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.Histograms(tag)
Retrieve the histogram events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not available for the given run. ...
369,334
def resize_image_with_crop_or_pad(image, target_height, target_width, dynamic_shape=False): image = ops.convert_to_tensor(image, name=) _Check3DImage(image, require_static=(not dynamic_shape)) original_height, original_width, _ = _ImageDimensions(image, dynamic_shape=dynam...
Crops and/or pads an image to a target width and height. Resizes an image to a target width and height by either centrally cropping the image or padding it evenly with zeros. If `width` or `height` is greater than the specified `target_width` or `target_height` respectively, this op centrally crops along that...
369,335
def _submit(primitive, port_index, tuple_): args = (_get_opc(primitive), port_index, tuple_) _ec._submit(args)
Internal method to submit a tuple
369,336
def notify_about_new_variables(callback): def _tracking_creator(getter, **kwargs): v = getter(**kwargs) callback(v) return v with tf.variable_creator_scope(_tracking_creator): yield
Calls `callback(var)` for all newly created variables. Callback should not modify the variable passed in. Use cases that require variables to be modified should use `variable_creator_scope` directly and sit within the variable creator stack. >>> variables = [] >>> with notify_about_variables(variables.appen...
369,337
def scalars_impl(self, run, tag_regex_string): if not tag_regex_string: return { _REGEX_VALID_PROPERTY: False, _TAG_TO_EVENTS_PROPERTY: {}, } try: regex = re.compile(tag_regex_string) except re.error: return { _REGEX_VALID_PROPERTY: Fal...
Given a tag regex and single run, return ScalarEvents. Args: run: A run string. tag_regex_string: A regular expression that captures portions of tags. Raises: ValueError: if the scalars plugin is not registered. Returns: A dictionary that is the JSON-able response.
369,338
def _build_full_partition( optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation ) -> List[Sequence[Expression]]: i = 0 var_index = 0 opt_index = 0 result = [] for operand in op_iter(operation): wrap_associative = False ...
Distribute subject operands among pattern operands. Given a partitoning for the variable part of the operands (i.e. a list of how many extra operands each sequence variable gets assigned).
369,339
def sig_cmp(sig1, sig2): types1 = sig1.required types2 = sig2.required if len(types1) != len(types2): return False dup_pos = [] dup_kw = {} for t1, t2 in zip(types1, types2): match = type_cmp(t1, t2) if match: dup_pos.append(match) else: ...
Compares two normalized type signatures for validation purposes.
369,340
def get_node_by_id(self, node_id): tmp_nodes = self.diagram_graph.nodes(data=True) for node in tmp_nodes: if node[0] == node_id: return node
Gets a node with requested ID. Returns a tuple, where first value is node ID, second - a dictionary of all node attributes. :param node_id: string with ID of node.
369,341
def _process_if(self, node): creg_name = node.children[0].name creg = self.dag.cregs[creg_name] cval = node.children[1].value self.condition = (creg, cval) self._process_node(node.children[2]) self.condition = None
Process an if node.
369,342
def postSolve(self): self.solution[0].mNrm_list.insert(0,0.0) self.solution[0].cNrm_list.insert(0,0.0) self.solution[0].MPC_list.insert(0,self.MPCmax) self.solution[0].cFunc = CubicInterp(self.solution[0].mNrm_list,self.solution[0].cNrm_list,self.solution[0].M...
This method adds consumption at m=0 to the list of stable arm points, then constructs the consumption function as a cubic interpolation over those points. Should be run after the backshooting routine is complete. Parameters ---------- none Returns ------- ...
369,343
def fit(self, X): self.n_samples_fit = X.shape[0] if self.metric_kwds is None: metric_kwds = {} else: metric_kwds = self.metric_kwds self.pynndescent_ = NNDescent( X, self.metric, metric_kwds, self.n_neigh...
Fit the PyNNDescent transformer to build KNN graphs with neighbors given by the dataset X. Parameters ---------- X : array-like, shape (n_samples, n_features) Sample data Returns ------- transformer : PyNNDescentTransformer The trained tr...
369,344
def prune(self, cutoff: int = 2): for node_pair in tqdm(list(permutations(self.nodes(), 2))): paths = [ list(pairwise(path)) for path in nx.all_simple_paths(self, *node_pair, cutoff) ] if len(paths) > 1: for p...
Prunes the CAG by removing redundant paths. If there are multiple (directed) paths between two nodes, this function removes all but the longest paths. Subsequently, it restricts the graph to the largest connected component. Args: cutoff: The maximum path length to consider f...
369,345
def convert_notebook(self, name): exporter = nbconvert.exporters.python.PythonExporter() relative_path = self.convert_path(name) file_path = self.get_path("%s.ipynb"%relative_path) code = exporter.from_filename(file_path)[0] self.write_code(name, code)...
Converts a notebook into a python file.
369,346
def is_repository(self, path): if path.strip() in (,): path = os.getcwd() repoPath = os.path.realpath( os.path.expanduser(path) ) if os.path.isfile( os.path.join(repoPath,self.__repoFile) ): return True else: try: from .OldRepo...
Check if there is a Repository in path. :Parameters: #. path (string): The real path of the directory where to check if there is a repository. :Returns: #. result (boolean): Whether it's a repository or not.
369,347
def clear_weights(self): self.weighted = False for layer in self.layer_list: layer.weights = None
clear weights of the graph
369,348
def get_processed_data(self, *args, **kwargs): return self.process_data(self.get_data(*args, **kwargs), **kwargs)
Get and process forecast data. Parameters ---------- *args: positional arguments Passed to get_data **kwargs: keyword arguments Passed to get_data and process_data Returns ------- data: DataFrame Processed forecast data
369,349
def process(self, batch, device=None): padded = self.pad(batch) tensor = self.numericalize(padded, device=device) return tensor
Process a list of examples to create a torch.Tensor. Pad, numericalize, and postprocess a batch and create a tensor. Args: batch (list(object)): A list of object from a batch of examples. Returns: torch.autograd.Variable: Processed object given the input and...
369,350
def validate(self, auth_rest): try: auth_salt, auth_hash = auth_rest.split() except ValueError: raise ValueError("Missing in %s" % auth_rest) if len(auth_salt) == 0: raise ValueError("Salt must have non-zero length!") if len(auth_hash) != 40...
Validate user credentials whether format is right for Sha1 :param auth_rest: User credentials' part without auth_type :return: Dict with a hash and a salt part of user credentials :raises ValueError: If credentials' part doesn't contain delimiter between a salt and a...
369,351
def add_color_stop_rgb(self, offset, red, green, blue): cairo.cairo_pattern_add_color_stop_rgb( self._pointer, offset, red, green, blue) self._check_status()
Same as :meth:`add_color_stop_rgba` with ``alpha=1``. Kept for compatibility with pycairo.
369,352
def is_initialised( self ): if not self.lattice: raise AttributeError() if not self.atoms: raise AttributeError() if not self.number_of_jumps and not self.for_time: raise AttributeError()
Check whether the simulation has been initialised. Args: None Returns: None
369,353
def save_figures(image_path, fig_count, gallery_conf): figure_list = [] fig_managers = matplotlib._pylab_helpers.Gcf.get_all_fig_managers() for fig_mngr in fig_managers: fig = plt.figure(fig_mngr.num) kwargs = {} to_rgba = matplotlib.colors.colorConverter.to_rgba ...
Save all open matplotlib figures of the example code-block Parameters ---------- image_path : str Path where plots are saved (format string which accepts figure number) fig_count : int Previous figure number count. Figure number add from this number Returns ------- list of ...
369,354
def coerce(from_, to, **to_kwargs): def preprocessor(func, argname, arg): if isinstance(arg, from_): return to(arg, **to_kwargs) return arg return preprocessor
A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. **to_kwargs Additional keywords to fo...
369,355
def verify_quote(self, quote_id, extra): container = self.generate_order_template(quote_id, extra) clean_container = {} for key in container.keys(): if container.get(key) != : clean_container[key] = container[key] return s...
Verifies that a quote order is valid. :: extras = { 'hardware': {'hostname': 'test', 'domain': 'testing.com'}, 'quantity': 2 } manager = ordering.OrderingManager(env.client) result = manager.verify_quote(12345, extras) :...
369,356
def oauthgetm(method, param_dict, socket_timeout=None): try: import oauth2 except ImportError: raise Exception("You must install the python-oauth2 library to use this method.") def build_request(url): params = { : "1.0", : oauth2.generate_nonce(), ...
Call the api! With Oauth! Param_dict is a *regular* *python* *dictionary* so if you want to have multi-valued params put them in a list. ** note, if we require 2.6, we can get rid of this timeout munging.
369,357
def get_cur_batch(items): batches = [] for data in items: batch = tz.get_in(["metadata", "batch"], data, []) batches.append(set(batch) if isinstance(batch, (list, tuple)) else set([batch])) combo_batches = reduce(lambda b1, b2: b1.intersection(b2), batches) if len(combo_batches) == ...
Retrieve name of the batch shared between all items in a group.
369,358
def on_rabbitmq_close(self, reply_code, reply_text): global rabbitmq_connection LOGGER.warning(, reply_code, reply_text) rabbitmq_connection = None self._set_rabbitmq_channel(None) self._connect_to_rabbitmq()
Called when RabbitMQ has been connected to. :param int reply_code: The code for the disconnect :param str reply_text: The disconnect reason
369,359
def run_parallel(pipeline, input_gen, options={}, ncpu=4, chunksize=200): t0 = time() logger = logging.getLogger("reliure.run_parallel") jobs = [] results = [] Qdata = mp.JoinableQueue(ncpu*2) Qresult = mp.Queue() if hasattr(input_gen, "__len__"): ...
Run a pipeline in parallel over a input generator cutting it into small chunks. >>> # if we have a simple component >>> from reliure.pipeline import Composable >>> # that we want to run over a given input: >>> input = "abcde" >>> import string >>> pipeline = Composable(lambda letters: (l.up...
369,360
def append_md5_if_too_long(component, size): if len(component) > size: if size > 32: component_size = size - 32 - 1 return "%s_%s" % (component[:component_size], hashlib.md5(component.encode()).hexdigest()) else:...
Trims the component if it is longer than size and appends the component's md5. Total must be of length size. :param str component: component to work on :param int size: component's size limit :return str: component and appended md5 trimmed to be of length size
369,361
def before_insert(mapper, conn, target): if target.sequence_id is None: from ambry.orm.exc import DatabaseError raise DatabaseError() assert (target.name == ) == (target.sequence_id == 1), (target.name, target.sequence_id) Column.be...
event.listen method for Sqlalchemy to set the seqience_id for this object and create an ObjectNumber value for the id_
369,362
def _check_dedup(data): if dd.get_analysis(data).lower() in ["rna-seq", "smallrna-seq"] or not dd.get_aligner(data): dup_param = utils.get_in(data, ("config", "algorithm", "mark_duplicates"), False) else: dup_param = utils.get_in(data, ("config", "algorithm", "mark_duplicates"), True) i...
Check configuration for de-duplication. Defaults to no de-duplication for RNA-seq and small RNA, the back compatible default. Allow overwriting with explicit `mark_duplicates: true` setting. Also defaults to false for no alignment inputs.
369,363
def instance_absent(name, instance_name=None, instance_id=None, release_eip=False, region=None, key=None, keyid=None, profile=None, filters=None): ret = {: name, : True, : , : {} } running_states = (, , , , ) ...
Ensure an EC2 instance does not exist (is stopped and removed). .. versionchanged:: 2016.11.0 name (string) - The name of the state definition. instance_name (string) - The name of the instance. instance_id (string) - The ID of the instance. release_eip (bool) - R...
369,364
def interpolation_points(self, N): if N == 1: return np.array([0.]) return np.cos(np.arange(N)*np.pi/(N-1))
N Chebyshev points in [-1, 1], boundaries included
369,365
def _GetAttributes(self): if self._attributes is None: self._attributes = [] for fsntfs_attribute in self._fsntfs_file_entry.attributes: attribute_class = self._ATTRIBUTE_TYPE_CLASS_MAPPINGS.get( fsntfs_attribute.attribute_type, NTFSAttribute) attribute_object = attribu...
Retrieves the attributes. Returns: list[NTFSAttribute]: attributes.
369,366
def sorted_stats(self): key = self.get_key() return sorted(self.stats, key=lambda stat: tuple(map( lambda part: int(part) if part.isdigit() else part.lower(), re.split(r"(\d+|\D+)", self.has_alias(stat[key]) or stat[key]) )))
Get the stats sorted by an alias (if present) or key.
369,367
def _aggr_mean(inList): aggrSum = 0 nonNone = 0 for elem in inList: if elem != SENTINEL_VALUE_FOR_MISSING_DATA: aggrSum += elem nonNone += 1 if nonNone != 0: return aggrSum / nonNone else: return None
Returns mean of non-None elements of the list
369,368
def get_go2color_inst(self, hdrgo): go2color = self.go2color.copy() go2color[hdrgo] = self.hdrgo_dflt_color return go2color
Get a copy of go2color with GO group header colored.
369,369
def parse_header(header): triples = [] fields = [] for col_str in header: col = col_str.strip().split() n = len(col) if n == 1: col = [col[0], , ] elif n == 2: if castable_to_int(col[1]): col = [col[0], , col[1]] el...
Convert a list of the form `['fieldname:fieldtype:fieldsize',...]` into a numpy composite dtype. The parser understands headers generated by :func:`openquake.commonlib.writers.build_header`. Here is an example: >>> parse_header(['PGA:float32', 'PGV', 'avg:float32:2']) (['PGA', 'PGV', 'avg'], dtype(...
369,370
def run_from_argv(self, prog, subcommand, global_options, argv): self.prog_name = prog parser = self.create_parser(prog, subcommand) options, args = parser.parse_args(argv) self.global_options = global_options self.options = options self.args = args self....
Set up any environment changes requested, then run this command.
369,371
def from_chars(chars): paulis = [pauli_from_char(c, n) for n, c in enumerate(chars) if c != "I"] if not paulis: return 1.0 * I if len(paulis) == 1: return 1.0 * paulis[0] return reduce(lambda a, b: a * b, paulis)
Make Pauli's Term from chars which is written by "X", "Y", "Z" or "I". e.g. "XZIY" => X(0) * Z(1) * Y(3) Args: chars (str): Written in "X", "Y", "Z" or "I". Returns: Term: A `Term` object. Raises: ValueError: When chars conteins the character which ...
369,372
def log_cert_info(logger, msg_str, cert_obj): list( map( logger, ["{}:".format(msg_str)] + [ " {}".format(v) for v in [ "Subject: {}".format( _get_val_str(cert_obj, ["subject", "value"], rev...
Dump basic certificate values to the log. Args: logger: Logger Logger to which to write the certificate values. msg_str: str A message to write to the log before the certificate values. cert_obj: cryptography.Certificate Certificate containing values to log. Returns...
369,373
def wait_for_element_to_disappear(self, locator, params=None, timeout=None): exp_cond = eec.invisibility_of if isinstance(locator, WebElement) else ec.invisibility_of_element_located try: self._get(locator, exp_cond, params, timeout, error_msg="Element never disappeared") ex...
Waits until the element is not visible (hidden) or no longer attached to the DOM. Raises TimeoutException if element does not become invisible. :param locator: locator tuple or WebElement instance :param params: (optional) locator params :param timeout: (optional) time to wait for elem...
369,374
def request(self, method, path, query=None, content=None): if not path.startswith("/"): raise ClientError("Implementation error: Called with bad path %s" % path) body = None if content is not None: data = self._json_encoder.encode...
Sends an HTTP request. This constructs a full URL, encodes and decodes HTTP bodies, and handles invalid responses in a pythonic way. @type method: string @param method: HTTP method to use @type path: string @param path: HTTP URL path @type query: list of two-tup...
369,375
async def provStacks(self, offs, size): count = 0 for iden, stack in self.cell.provstor.provStacks(offs, size): count += 1 if not count % 1000: await asyncio.sleep(0) yield s_common.ehex(iden), stack
Return stream of (iden, provenance stack) tuples at the given offset.
369,376
def process_pkcs7(self, data, name): from cryptography.hazmat.backends.openssl.backend import backend from cryptography.hazmat.backends.openssl.x509 import _Certificate is_pem = startswith(data, ) if self.re_match(r, data): is_pem = True try: ...
Process PKCS7 signature with certificate in it. :param data: :param name: :return:
369,377
def pexpire(self, key, milliseconds): return self._expire(self._encode(key), timedelta(milliseconds=milliseconds))
Emulate pexpire
369,378
def count_duplicate_starts(bam_file, sample_size=10000000): count = Counter() with bam.open_samfile(bam_file) as samfile: filtered = ifilter(lambda x: not x.is_unmapped, samfile) def read_parser(read): return ":".join([str(read.tid), str(read.pos)]) samples = ut...
Return a set of x, y points where x is the number of reads sequenced and y is the number of unique start sites identified If sample size < total reads in a file the file will be downsampled.
369,379
def setParent(self, other): if self._parent == other: return False if self._parent and self in self._parent._children: self._parent._children.remove(self) self._parent = other if self._parent and not self in se...
Sets the parent for this layer to the inputed layer. :param other | <XNodeLayer> || None :return <bool> changed
369,380
def register(): signals.initialized.connect(initialized) try: signals.content_object_init.connect(detect_content) signals.all_generators_finalized.connect(detect_images_and_galleries) signals.article_writer_finalized.connect(resize_photos) except Exception as e: logger.e...
Uses the new style of registration based on GitHub Pelican issue #314.
369,381
def get_current_temperature(self, refresh=False): if refresh: self.refresh() try: return float(self.get_value()) except (TypeError, ValueError): return None
Get current temperature
369,382
def neg_loglik(self,beta): _, _, _, F, v = self._model(self.data,beta) loglik = 0.0 for i in range(0,self.data.shape[0]): loglik += np.linalg.slogdet(F[:,:,i])[1] + np.dot(v[i],np.dot(np.linalg.pinv(F[:,:,i]),v[i])) return -(-((self.data.shape[0]/2)*np.log(2...
Creates the negative log likelihood of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- The negative log logliklihood of the model
369,383
def display(self): size = list(range(len(self.layers))) size.reverse() for i in size: layer = self.layers[i] if layer.active: print( % (layer.name, layer.size)) tlabel, olabel = , if (layer.type == ): ...
Displays the network to the screen.
369,384
def reload(self): text = self._read(self.location) cursor_position = min(self.buffer.cursor_position, len(text)) self.buffer.document = Document(text, cursor_position) self._file_content = text
Reload file again from storage.
369,385
def handleOneNodeMsg(self, wrappedMsg): try: vmsg = self.validateNodeMsg(wrappedMsg) if vmsg: logger.trace("{} msg validated {}".format(self, wrappedMsg), extra={"tags": ["node-msg-validation"]}) self.unpackNodeMsg(*vm...
Validate and process one message from a node. :param wrappedMsg: Tuple of message and the name of the node that sent the message
369,386
def uint(nstr, schema): if isinstance(nstr, basestring): if not nstr.isdigit(): return False nstr = long(nstr) elif not isinstance(nstr, (int, long)): return False return nstr > 0
!~~uint
369,387
def request_frame(self): self.session_id = get_new_session_id() return FrameCommandSendRequest(node_ids=[self.node_id], parameter=self.parameter, session_id=self.session_id)
Construct initiating frame.
369,388
def on_subscript(self, node): val = self.run(node.value) nslice = self.run(node.slice) ctx = node.ctx.__class__ if ctx in (ast.Load, ast.Store): if isinstance(node.slice, (ast.Index, ast.Slice, ast.Ellipsis)): return val.__getitem__(nslice) ...
Subscript handling -- one of the tricky parts.
369,389
def ask_pascal_16(self, next_rva_ptr): length = self.__get_pascal_16_length() if length == (next_rva_ptr - (self.rva_ptr+2)) / 2: self.length = length return True return False
The next RVA is taken to be the one immediately following this one. Such RVA could indicate the natural end of the string and will be checked with the possible length contained in the first word.
369,390
def update_warning(self): widget = self._button_warning if not self.is_valid(): tip = _() widget.setIcon(ima.icon()) widget.setToolTip(tip) QToolTip.showText(self._widget.mapToGlobal(QPoint(0, 5)), tip) else: self._but...
Updates the icon and tip based on the validity of the array content.
369,391
def remove_namespace(doc, namespace): ns = u % namespace nsl = len(ns) for elem in doc.getiterator(): if elem.tag.startswith(ns): elem.tag = elem.tag[nsl:] elem.attrib[] = namespace
Remove namespace in the passed document in place.
369,392
def _process_output(output, parse_json=True): output = output.strip() _LOGGER.debug(, output) if not output: return None elif in output: raise RequestError( ) elif output.startswith(CLIENT_ERROR_PREFIX): raise ClientError(output)...
Process output.
369,393
def batch_delete_jobs( self, parent, filter_, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if "batch_delete_jobs" not in self._inner_api_calls: self._inner_api_c...
Deletes a list of ``Job``\ s by filter. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.JobServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `filte...
369,394
def get_environment_requirements_list(): requirement_list = [] requirements = check_output([sys.executable, , , ]) for requirement in requirements.split(): requirement_list.append(requirement.decode("utf-8")) return requirement_list
Take the requirements list from the current running environment :return: string
369,395
def create(host, port): wrapper = WrapperServer({ : None }) d = { : port, : wrapper } if host: d[] = host ses = MeasureServer(d) wrapper.server = ses return [wrapper], cmd_line
Prepare server to execute :return: Modules to execute, cmd line function :rtype: list[WrapperServer], callable | None
369,396
def typed_subtopic_data(fc, subid):
Returns typed subtopic data from an FC.
369,397
def filter(self, *args): def wraps(f): self.add_filter(func=f, rules=list(args)) return f return wraps
为文本 ``(text)`` 消息添加 handler 的简便方法。 使用 ``@filter("xxx")``, ``@filter(re.compile("xxx"))`` 或 ``@filter("xxx", "xxx2")`` 的形式为特定内容添加 handler。
369,398
def __insert_frond_LF(d_w, d_u, dfs_data): dfs_data[].append( (d_w, d_u) ) dfs_data[][] += 1 dfs_data[] =
Encapsulates the process of inserting a frond uw into the left side frond group.
369,399
def upload_file_to(self, addressinfo, timeout): self.hostname, self.port = addressinfo self.timeout = timeout filename = self.fw_file firmware = open(filename, ).read() boundary = b( + str(random.randint(100000, 1000000)) + ) while...
Uploads the raw firmware file to iLO Uploads the raw firmware file (already set as attribute in FirmwareImageControllerBase constructor) to iLO, whose address information is passed to this method. :param addressinfo: tuple of hostname and port of the iLO :param timeout: timeout ...