Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
21,400
def PluginTagToContent(self, plugin_name): if plugin_name not in self._plugin_to_tag_to_content: raise KeyError( % plugin_name) return self._plugin_to_tag_to_content[plugin_name]
Returns a dict mapping tags to content specific to that plugin. Args: plugin_name: The name of the plugin for which to fetch plugin-specific content. Raises: KeyError: if the plugin name is not found. Returns: A dict mapping tags to plugin-specific content (which are always stri...
21,401
def ask_backend(self): response = self._ask_boolean( "Do you have a local docker daemon (on Linux), do you use docker-machine via a local machine, or do you use " "Docker for macOS?", True) if (response): self._display_info("If you use docker-machine on macOS...
Ask the user to choose the backend
21,402
def begin_write(self, content_type=None): assert not self.is_collection self._check_write_access() mode = "wb" return open(self.absFilePath, mode, BUFFER_SIZE)
Open content as a stream for writing. See DAVResource.begin_write()
21,403
def suggest_move(self, position): start = time.time() if self.timed_match: while time.time() - start < self.seconds_per_move: self.tree_search() else: current_readouts = self.root.N while self.root.N < current_readouts + self.num_read...
Used for playing a single game. For parallel play, use initialize_move, select_leaf, incorporate_results, and pick_move
21,404
def to_internal_value(self, data): if html.is_html_input(data): data = html.parse_html_list(data) if not isinstance(data, list): message = self.error_messages[].format( input_type=type(data).__name__ ) raise ValidationError({ ...
List of dicts of native values <- List of dicts of primitive datatypes.
21,405
def _flush_tile_queue_blits(self, surface): tw, th = self.data.tile_size ltw = self._tile_view.left * tw tth = self._tile_view.top * th self.data.prepare_tiles(self._tile_view) blit_list = [(image, (x * tw - ltw, y * th - tth)) for x, y, l, image in self._tile_queue] ...
Blit the queued tiles and block until the tile queue is empty for pygame 1.9.4 +
21,406
def _make_load_template(self): loader = self._make_loader() def load_template(template_name): return loader.load_name(template_name) return load_template
Return a function that loads a template by name.
21,407
def wants(cls, *service_names): def _decorator(cls_): for service_name in service_names: cls_._services_requested[service_name] = "want" return cls_ return _decorator
A class decorator to indicate that an XBlock class wants particular services.
21,408
def multiifo_noise_coinc_rate(rates, slop): ifos = numpy.array(sorted(rates.keys())) rates_raw = list(rates[ifo] for ifo in ifos) expected_coinc_rates = {} allowed_area = multiifo_noise_coincident_area(ifos, slop) rateprod = [numpy.prod(rs) for rs in zip(*rates_raw)] ifostring = ...
Calculate the expected rate of noise coincidences for multiple detectors Parameters ---------- rates: dict Dictionary keyed on ifo string Value is a sequence of single-detector trigger rates, units assumed to be Hz slop: float time added to maximum time-of-flight between...
21,409
def set_env(self, key, value): os.environ[make_env_key(self.appname, key)] = str(value) self._registered_env_keys.add(key) self._clear_memoization()
Sets environment variables by prepending the app_name to `key`. Also registers the environment variable with the instance object preventing an otherwise-required call to `reload()`.
21,410
def _to_dict(self): _dict = {} if hasattr(self, ) and self.entity is not None: _dict[] = self.entity if hasattr(self, ) and self.location is not None: _dict[] = self.location if hasattr(self, ) and self.value is not None: _dict[] = self.value ...
Return a json dictionary representing this model.
21,411
def stop_execution(self): if not (self._stopping or self._stopped): for actor in self.owner.actors: actor.stop_execution() self._stopping = True
Triggers the stopping of the object.
21,412
def explain_weights_dfs(estimator, **kwargs): kwargs = _set_defaults(kwargs) return format_as_dataframes( eli5.explain_weights(estimator, **kwargs))
Explain weights and export them to a dict with ``pandas.DataFrame`` values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does). All keyword arguments are passed to :func:`eli5.explain_weights`. Weights of all features are exported by default.
21,413
def sync_local_to_remote(force="no"): _check_requirements() if force != "yes": message = "This will replace the remote database with your "\ "local , are you sure [y/n]" % (env.psql_db, env.local_psql_db) answer = prompt(message, "y") if answer != "y": lo...
Sync your local postgres database with remote Example: fabrik prod sync_local_to_remote:force=yes
21,414
def _serialize_object(self, response_data, request): if self._is_doc_request(request): return response_data else: return super(DocumentedResource, self)._serialize_object( response_data, request)
Override to not serialize doc responses.
21,415
def count_never_executed(self): lineno = self.firstlineno counter = 0 for line in self.source: if self.sourcelines.get(lineno) == 0: if not self.blank_rx.match(line): counter += 1 lineno += 1 return counter
Count statements that were never executed.
21,416
def _agl_compliant_name(glyph_name): MAX_GLYPH_NAME_LENGTH = 63 clean_name = re.sub("[^0-9a-zA-Z_.]", "", glyph_name) if len(clean_name) > MAX_GLYPH_NAME_LENGTH: return None return clean_name
Return an AGL-compliant name string or None if we can't make one.
21,417
def is_form_get(attr, attrs): res = False if attr == "action": method = attrs.get_true(, u).lower() res = method != return res
Check if this is a GET form action URL.
21,418
def print_input(i): o=i.get(,) rx=dumps_json({:i, :}) if rx[]>0: return rx h=rx[] if o==: out(h) return {:0, :h}
Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 html - input as JSON }
21,419
async def set_gs(self, mgr_addr, gs): remote_manager = await self.env.connect(mgr_addr) await remote_manager.set_gs(gs)
Set grid size for :py:class:`GridEnvironment` which manager is in given address. :param str mgr_addr: Address of the manager agent :param gs: New grid size of the grid environment, iterable with length 2.
21,420
def _parse_query(self, source): if self.OBJECTFILTER_WORDS.search(source): syntax_ = "objectfilter" else: syntax_ = None return query.Query(source, syntax=syntax_)
Parse one of the rules as either objectfilter or dottysql. Example: _parse_query("5 + 5") # Returns Sum(Literal(5), Literal(5)) Arguments: source: A rule in either objectfilter or dottysql syntax. Returns: The AST to represent the rule.
21,421
def to_python(self, value): if isinstance(value, GroupDescriptor): value = value._value result = {} for name, field in self.fields.items(): result[name] = field.to_python(value.get(name, None)) return GroupDescriptor(result)
Convert value if needed.
21,422
def parse_table_definition_file(file): logging.info("Reading table definition from ...", file) if not os.path.isfile(file): logging.error("File does not exist.", file) exit(1) try: tableGenFile = ElementTree.ElementTree().parse(file) except IOError as e: logging.er...
Read an parse the XML of a table-definition file. @return: an ElementTree object for the table definition
21,423
def get_if_raw_addr(ifname): try: fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname)) except OSError as msg: warning("Failed to execute ifconfig: (%s)", msg) return b"\0\0\0\0" addresses = [l for l in fd if l.find("inet ") >= 0] if not addresses: warn...
Returns the IPv4 address configured on 'ifname', packed with inet_pton.
21,424
def _parse(self, threshold): match = re.search(r, threshold) if not match: raise ValueError(.format(threshold)) if match.group(1) == : self._inclusive = True if match.group(3) == : self._min = float() elif match.group(3): ...
internal threshold string parser arguments: threshold: string describing the threshold
21,425
def merge(root, head, update, head_source=None): configuration = get_configuration(head, update, head_source) conflicts = [] root, head, update = filter_records(root, head, update, filters=configuration.pre_filters) merger = Merger( root=root, head=head, update=update, default_dict...
This function instantiate a ``Merger`` object using a configuration in according to the ``source`` value of head and update params. Then it run the merger on the three files provided in input. Params root(dict): the last common parent json of head and update head(dict): the last version of ...
21,426
def set_control_scheme(self, index): self._current_control_scheme = index % self._num_control_schemes self._control_scheme_buffer[0] = self._current_control_scheme
Sets the control scheme for the agent. See :obj:`ControlSchemes`. Args: index (int): The control scheme to use. Should be set with an enum from :obj:`ControlSchemes`.
21,427
def fill_model(self, model=None): normalized_dct = self.normalize() if model: if not isinstance(model, self._model_class): raise ModelFormSecurityError( % (model, self._model_class.__name__)) model.populate(**normalized_dct) return model ...
Populates a model with normalized properties. If no model is provided (None) a new one will be created. :param model: model to be populade :return: populated model
21,428
def compute_sims(inputs: mx.nd.NDArray, normalize: bool) -> mx.nd.NDArray: if normalize: logger.info("Normalizing embeddings to unit length") inputs = mx.nd.L2Normalization(inputs, mode=) sims = mx.nd.dot(inputs, inputs, transpose_b=True) sims_np = sims.asnumpy() np.fill_diagonal(si...
Returns a matrix with pair-wise similarity scores between inputs. Similarity score is (normalized) Euclidean distance. 'Similarity with self' is masked to large negative value. :param inputs: NDArray of inputs. :param normalize: Whether to normalize to unit-length. :return: NDArray with pairwise si...
21,429
def bounding_box(alpha, threshold=0.1): assert alpha.ndim == 2 supp_axs = [alpha.max(axis=1-i) for i in range(2)] bb = [np.where(supp_axs[i] > threshold)[0][[0, -1]] for i in range(2)] return (bb[0][0], bb[1][0], bb[0][1], bb[1][1])
Returns a bounding box of the support. Parameters ---------- alpha : ndarray, ndim=2 Any one-channel image where the background has zero or low intensity. threshold : float The threshold that divides background from foreground. Returns ------- bounding_box : (top, left, bot...
21,430
def _pack(self, msg_type, payload): pb = payload.encode() s = struct.pack(, len(pb), msg_type.value) return self.MAGIC.encode() + s + pb
Packs the given message type and payload. Turns the resulting message into a byte string.
21,431
def phonenumber_validation(data): from phonenumber_field.phonenumber import to_python phone_number = to_python(data) if not phone_number: return data elif not phone_number.country_code: raise serializers.ValidationError(_("Phone number needs to include valid country code (E.g +37255...
Validates phonenumber Similar to phonenumber_field.validators.validate_international_phonenumber() but uses a different message if the country prefix is absent.
21,432
def mkdir_chown(paths, user_group=None, permissions=, create_parent=True, check_if_exists=False, recursive=False): def _generate_str(path): mkdir_str = mkdir(path, create_parent, check_if_exists) chown_str = chown(user_group, path, recursive) if user_group else None chmod_str = chmod(p...
Generates a unix command line for creating a directory and assigning permissions to it. Shortcut to a combination of :func:`~mkdir`, :func:`~chown`, and :func:`~chmod`. Note that if `check_if_exists` has been set to ``True``, and the directory is found, `mkdir` is not called, but `user_group` and `permissi...
21,433
def generate_image_commands(): class ImageClient(object): group = "image" from spython.main.base.logger import println from spython.main.base.command import ( init_command, run_command ) from .utils import ( compress, decompress ) from .create import create from .importcmd import ...
The Image client holds the Singularity image command group, mainly deprecated commands (image.import) and additional command helpers that are commonly use but not provided by Singularity The levels of verbosity (debug and quiet) are passed from the main client via the environment variab...
21,434
def sort_dict(d, desc=True): sort = sorted(d.items(), key=lambda x: x[1], reverse=desc) return OrderedDict(sort)
Sort an ordered dictionary by value, descending. Args: d (OrderedDict): An ordered dictionary. desc (bool): If true, sort desc. Returns: OrderedDict: The sorted dictionary.
21,435
def find_xenon_grpc_jar(): prefix = Path(sys.prefix) locations = [ prefix / , prefix / / ] for location in locations: jar_file = location / .format( xenon_grpc_version) if not jar_file.exists(): continue else: retu...
Find the Xenon-GRPC jar-file, windows version.
21,436
def asyncStarCmap(asyncCallable, iterable): results = [] yield coopStar(asyncCallable, results.append, iterable) returnValue(results)
itertools.starmap for deferred callables using cooperative multitasking
21,437
def add_acquisition_source( self, method, submission_number=None, internal_uid=None, email=None, orcid=None, source=None, datetime=None, ): acquisition_source = self._sourced_dict(source) acquisition_source[] = str(submission_...
Add acquisition source. :type submission_number: integer :type email: integer :type source: string :param method: method of acquisition for the suggested document :type method: string :param orcid: orcid of the user that is creating the record :type orcid: st...
21,438
def get_labels(data, centroids,K): distances = np.sqrt(((data - centroids[:, np.newaxis])**2).sum(axis=2)) return np.argmin(distances, axis=0)
Returns a label for each piece of data in the dataset Parameters ------------ data: array-like, shape= (m_samples,n_samples) K: integer number of K clusters centroids: array-like, shape=(K, n_samples) returns ------------- labels: array-like, shape (1,n_samples)
21,439
def _deserialize_data(self, json_data): my_dict = json.loads(json_data.decode().replace(""UTF-8%Y-%m-%d%H:%M:%S%Y-%m-%d%H:%M:%S%Y-%m-%d%H:%M:%S%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.WHITELIST: my_dict[item] = self._str_to_bool(my_dict[item]) e...
Deserialize a JSON into a dictionary
21,440
def _process_download_descriptor(self, dd): self._update_progress_bar() offsets, resume_bytes = dd.next_offsets() if resume_bytes is not None: with self._disk_operation_lock: self._download_bytes_sofar += resume_bytes ...
Process download descriptor :param Downloader self: this :param blobxfer.models.download.Descriptor dd: download descriptor
21,441
def _construct_message(self): self.message = {"token": self._auth, "channel": self.channel} super()._construct_message()
Set the message token/channel, then call the bas class constructor.
21,442
def _resolve_datacenter(dc, pillarenv): s a dict then sort it in descending order by key length and try to use keys as RegEx patterns to match against ``pillarenv``. The value for matched pattern should be a string (that can use ``str.format`` syntax togetehr with captured variables from pattern) po...
If ``dc`` is a string - return it as is. If it's a dict then sort it in descending order by key length and try to use keys as RegEx patterns to match against ``pillarenv``. The value for matched pattern should be a string (that can use ``str.format`` syntax togetehr with captured variables from pattern...
21,443
def enqueue_mod(self, dn, mod): if dn not in self.__pending_mod_dn__: self.__pending_mod_dn__.append(dn) self.__mod_queue__[dn] = [] self.__mod_queue__[dn].append(mod)
Enqueue a LDAP modification. Arguments: dn -- the distinguished name of the object to modify mod -- an ldap modfication entry to enqueue
21,444
def create_custom_gradebook_column(self, course_id, column_title, column_hidden=None, column_position=None, column_teacher_notes=None): path = {} data = {} params = {} path["course_id"] = course_id data["column[title]"] = c...
Create a custom gradebook column. Create a custom gradebook column
21,445
def get_number_of_atoms(self): strc = self.get_output_structure() if not strc: return None return Property(scalars=[Scalar(value=len(strc))], units="/unit cell")
Get the number of atoms in the calculated structure. Returns: Property, where number of atoms is a scalar.
21,446
def get_preparation_cmd(user, permissions, path): r_user = resolve_value(user) r_permissions = resolve_value(permissions) if user: yield chown(r_user, path) if permissions: yield chmod(r_permissions, path)
Generates the command lines for adjusting a volume's ownership and permission flags. Returns an empty list if there is nothing to adjust. :param user: User to set ownership for on the path via ``chown``. :type user: unicode | str | int | dockermap.functional.AbstractLazyObject :param permissions: Permi...
21,447
def get_config(self): if in self.config: self.rmq_port = int(self.config[]) if in self.config: self.rmq_user = self.config[] if in self.config: self.rmq_password = self.config[] if in self.config: self.rmq_vhost = self.confi...
Get and set config options from config file
21,448
def setValue(self, p_float): p_float = p_float * 100 super(PercentageSpinBox, self).setValue(p_float)
Override method to set a value to show it as 0 to 100. :param p_float: The float number that want to be set. :type p_float: float
21,449
def admin_url(obj): if hasattr(obj, ): return mark_safe(obj.get_admin_url()) return mark_safe(admin_url_fn(obj))
Returns the admin URL of the object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_url }} renders as:: /admin/foo/123 :param obj: A Django model instance. :return: the admin URL of the o...
21,450
def title(label, style=None): fig = current_figure() fig.title = label if style is not None: fig.title_style = style
Sets the title for the current figure. Parameters ---------- label : str The new title for the current figure. style: dict The CSS style to be applied to the figure title
21,451
def expect_column_kl_divergence_to_be_less_than(self, column, partition_object=None, threshold=None, tail_weight...
Expect the Kulback-Leibler (KL) divergence (relative entropy) of the specified column with respect to the \ partition object to be lower than the provided threshold. KL divergence compares two distributions. The higher the divergence value (relative entropy), the larger the \ difference between...
21,452
def compile_pythrancode(module_name, pythrancode, specs=None, opts=None, cpponly=False, pyonly=False, output_file=None, module_dir=None, **kwargs): if pyonly: content = generate_py(module_name, pythrancode, opts, module_dir) if output_fi...
Pythran code (string) -> c++ code -> native module if `cpponly` is set to true, return the generated C++ filename if `pyonly` is set to true, prints the generated Python filename, unless `output_file` is set otherwise, return the generated native library filename
21,453
def write(self, buf): underflow = self._audio_stream.write(buf) if underflow: logging.warning(, len(buf)) return len(buf)
Write bytes to the stream.
21,454
def plot_fermi_surface(data, structure, cbm, energy_levels=[], multiple_figure=True, mlab_figure=None, kpoints_dict={}, color=(0, 0, 1), transparency_factor=[], labels_scale_factor=0.05, points_scale_factor=0.02, interative=True...
Plot the Fermi surface at specific energy value. Args: data: energy values in a 3D grid from a CUBE file via read_cube_file function, or from a BoltztrapAnalyzer.fermi_surface_data structure: structure object of the material energy_levels: list of energy value ...
21,455
def feature_importances(data, top_n=None, feature_names=None, ax=None): if data is None: raise ValueError( ) res = compute.feature_importances(data, top_n, feature_names) n_feats = len(res) if ax is None: ax = plt.gca() ...
Get and order feature importances from a scikit-learn model or from an array-like structure. If data is a scikit-learn model with sub-estimators (e.g. RandomForest, AdaBoost) the function will compute the standard deviation of each feature. Parameters ---------- data : sklearn model or array-li...
21,456
def need_latex_rerun(self): for pattern in LATEX_RERUN_PATTERNS: if pattern.search(self.out): return True return False
Test for all rerun patterns if they match the output.
21,457
def save_model(self, directory=None, append_timestep=True): return self.model.save(directory=directory, append_timestep=append_timestep)
Save TensorFlow model. If no checkpoint directory is given, the model's default saver directory is used. Optionally appends current timestep to prevent overwriting previous checkpoint files. Turn off to be able to load model from the same given path argument as given here. Args: ...
21,458
def get_division(self, obj): if self.context.get("division"): return DivisionSerializer(self.context.get("division")).data else: if obj.slug == "senate": return DivisionSerializer(obj.jurisdiction.division).data else: us = Divi...
Division.
21,459
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable=): if not self.runner.sudo or not sudoable: if executable: local_cmd = [executable, , cmd] else: local_cmd = cmd else: local_cmd, prompt = utils.make_...
run a command on the local host
21,460
def _cho_solve_AATI(A, rho, b, c, lwr, check_finite=True): N, M = A.shape if N >= M: x = (b - _cho_solve((c, lwr), b.dot(A).T, check_finite=check_finite).T.dot(A.T)) / rho else: x = _cho_solve((c, lwr), b.T, check_finite=check_finite).T return x
Patched version of :func:`sporco.linalg.cho_solve_AATI`.
21,461
def txid_to_block_data(txid, bitcoind_proxy, proxy=None): proxy = get_default_proxy() if proxy is None else proxy timeout = 1.0 while True: try: untrusted_tx_data = bitcoind_proxy.getrawtransaction(txid, 1) untrusted_block_hash = untrusted_tx_data[] untrust...
Given a txid, get its block's data. Use SPV to verify the information we receive from the (untrusted) bitcoind host. @bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session) Return the (block hash, block data, txdata) on success Return (None, None, None) on error
21,462
async def validate(state, holdout_glob): if not glob.glob(holdout_glob): print(t match any files, skipping validationpython3validate.py--flagfile={}validate.flags--work_dir={}'.format(fsdb.working_dir()))
Validate the trained model against holdout games. Args: state: the RL loop State instance. holdout_glob: a glob that matches holdout games.
21,463
def _required_child(parent, tag): if _child(parent, tag) is None: parent.append(_Element(tag))
Add child element with *tag* to *parent* if it doesn't already exist.
21,464
def get(cls, uuid): if not uuid: raise ValueError("get must have a value passed as an argument") uuid = quote(str(uuid)) url = recurly.base_uri() + (cls.member_path % (uuid,)) _resp, elem = cls.element_for_url(url) return cls.from_element(elem)
Return a `Resource` instance of this class identified by the given code or UUID. Only `Resource` classes with specified `member_path` attributes can be directly requested with this method.
21,465
def generate_checker(value): @property @wraps(can_be_) def checker(self): return self.can_be_(value) return checker
Generate state checker for given value.
21,466
def get_metric_values(self): group_names = self.properties.get(, None) if not group_names: group_names = self.manager.get_metric_values_group_names() ret = [] for group_name in group_names: try: mo_val = self.manager.get_metric_values(grou...
Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object. Returns: iterable of tuple (group_name, iterable of values): The faked metrics, in the order they had been added, where: group_name (s...
21,467
def evaluate(self, x): if not hasattr(self, ): c = self.G.igft(self._kernels.evaluate(self.G.e).squeeze()) c = np.sqrt(self.G.n_vertices) * self.G.U * c[:, np.newaxis] self._coefficients = self.G.gft(c) shape = x.shape x = x.flatten() ...
TODO: will become _evaluate once polynomial filtering is merged.
21,468
def _detach_received(self, error): if error: condition = error.condition description = error.description info = error.info else: condition = b"amqp:unknown-error" description = None info = None self._error ...
Callback called when a link DETACH frame is received. This callback will process the received DETACH error to determine if the link is recoverable or whether it should be shutdown. :param error: The error information from the detach frame. :type error: ~uamqp.errors.ErrorRespon...
21,469
def check_auth(self, username, password): return username == self.queryname and password == self.querypw
This function is called to check if a username password combination is valid.
21,470
def enable(self): nquad = self.nquad.value() for label, xsll, xsul, xslr, xsur, ys, nx, ny in \ zip(self.label[:nquad], self.xsll[:nquad], self.xsul[:nquad], self.xslr[:nquad], self.xsur[:nquad], self.ys[:nquad], self.nx[:nquad], self.ny[:...
Enables WinQuad setting
21,471
def complete_vhwa_command(self, command): if not isinstance(command, basestring): raise TypeError("command can only be an instance of type basestring") self._call("completeVHWACommand", in_p=[command])
Signals that the Video HW Acceleration command has completed. in command of type str Pointer to VBOXVHWACMD containing the completed command.
21,472
def _run_program(self, bin, fastafile, params=None): params = self._parse_params(params) cmd = "%s -f %s -b %s -m %s -w %s -n %s -o %s -s %s" % ( bin, fastafile, params["background_model"], params["pwmfile"], ...
Run MotifSampler and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, optional Optional parameters. For some of the tools req...
21,473
def iter_org_events(self, org, number=-1, etag=None): url = if org: url = self._build_url(, , org, base_url=self._api) return self._iter(int(number), url, Event, etag=etag)
Iterate over events as they appear on the user's organization dashboard. You must be authenticated to view this. :param str org: (required), name of the organization :param int number: (optional), number of events to return. Default: -1 returns all available events :param st...
21,474
def get_objects_dex(self): for digest, d in self.analyzed_dex.items(): yield digest, d, self.analyzed_vms[digest]
Yields all dex objects inclduing their Analysis objects :returns: tuple of (sha256, DalvikVMFormat, Analysis)
21,475
def from_string(cls, s): if not (s.startswith() and s.endswith()): raise ValueError( ) s_ = s[1:] stack = [] deriv = None try: matches = cls.udf_re.finditer(s_) for match in matches: if ma...
Instantiate a `Derivation` from a UDF or UDX string representation. The UDF/UDX representations are as output by a processor like the `LKB <http://moin.delph-in.net/LkbTop>`_ or `ACE <http://sweaglesw.org/linguistics/ace/>`_, or from the :meth:`UdfNode.to_udf` or :meth:`UdfNode.to_udx` ...
21,476
def solar_position_loop(unixtime, loc_args, out): lat = loc_args[0] lon = loc_args[1] elev = loc_args[2] pressure = loc_args[3] temp = loc_args[4] delta_t = loc_args[5] atmos_refract = loc_args[6] sst = loc_args[7] esd = loc_args[8] for i in range(unixtime.shape[0]): ...
Loop through the time array and calculate the solar position
21,477
def _check_input(self, X, R): if not isinstance(X, list): raise TypeError("Input data should be a list") if not isinstance(R, list): raise TypeError("Coordinates should be a list") if len(X) < 1: raise ValueError("Need at leat one ...
Check whether input data and coordinates in right type Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. R : list of 2D arrays, element i has shape=[n_voxel, n_dim] ...
21,478
def qteStartRecordingHook(self, msgObj): if self.qteRecording: self.qteMain.qteStatus() return self.qteRecording = True self.qteMain.qteStatus() self.recorded_keysequence = QtmacsKeysequence() self.qteMain.qtesigKeypa...
Commence macro recording. Macros are recorded by connecting to the 'keypressed' signal it emits. If the recording has already commenced, or if this method was called during a macro replay, then return immediately.
21,479
def set_continous_wave(self, enabled): pk = CRTPPacket() pk.set_header(CRTPPort.PLATFORM, PLATFORM_COMMAND) pk.data = (0, enabled) self._cf.send_packet(pk)
Enable/disable the client side X-mode. When enabled this recalculates the setpoints before sending them to the Crazyflie.
21,480
def pick_auth(endpoint_context, areq, all=False): acrs = [] try: if len(endpoint_context.authn_broker) == 1: return endpoint_context.authn_broker.default() if "acr_values" in areq: if not isinstance(areq["acr_values"], list): areq["acr_values"] = [a...
Pick authentication method :param areq: AuthorizationRequest instance :return: A dictionary with the authentication method and its authn class ref
21,481
def _get_unicode(data, force=False): if isinstance(data, binary_type): return data.decode() elif data is None: return elif force: if PY2: return unicode(data) else: return str(data) else: return data
Try to return a text aka unicode object from the given data.
21,482
def InteractiveShell(self, cmd=None, strip_cmd=True, delim=None, strip_delim=True): conn = self._get_service_connection(b) return self.protocol_handler.InteractiveShellCommand( conn, cmd=cmd, strip_cmd=strip_cmd, delim=delim, strip_delim=strip_delim)
Get stdout from the currently open interactive shell and optionally run a command on the device, returning all output. Args: cmd: Optional. Command to run on the target. strip_cmd: Optional (default True). Strip command name from stdout. delim: Optional. Delimiter to l...
21,483
def take_action(self, production_rule: str) -> : left_side, right_side = production_rule.split() assert self._nonterminal_stack[-1] == left_side, (f"Tried to expand {self._nonterminal_stack[-1]}" f"but got rule {left_side} -> {right_side...
Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack. Updating the non-terminal stack involves popping the non-terminal that was ...
21,484
def init_flatpak(): tessdata_files = glob.glob("/app/share/locale/*/*.traineddata") if len(tessdata_files) <= 0: return os.path.exists("/app") localdir = os.path.expanduser("~/.local") base_data_dir = os.getenv( "XDG_DATA_HOME", os.path.join(localdir, "share") ) tes...
If we are in Flatpak, we must build a tessdata/ directory using the .traineddata files from each locale directory
21,485
def drop_prefix_and_return_type(function): DELIMITERS = { : , : , : , : , : "re building current = [] for i, char in enumerate(function): if char in OPEN: levels.append(char) current.append(char) elif char in CLOSE: ...
Takes the function value from a frame and drops prefix and return type For example:: static void * Allocator<MozJemallocBase>::malloc(unsigned __int64) ^ ^^^^^^ return type prefix This gets changes to this:: Allocator<MozJemallocBase>::malloc(unsigned __int64) This ...
21,486
def load(self): droplets = self.get_data("droplets/%s" % self.id) droplet = droplets[] for attr in droplet.keys(): setattr(self, attr, droplet[attr]) for net in self.networks[]: if net[] == : self.private_ip_address = net[] i...
Fetch data about droplet - use this instead of get_data()
21,487
def _CollectHistory_(lookupType, fromVal, toVal, using={}, pattern=): histObj = {} if fromVal != toVal: histObj[lookupType] = {"from": fromVal, "to": toVal} if lookupType in [, , , , ] and using!=: histObj[lookupType]["using"] = using if lookupType in [, , , ] and pat...
Return a dictionary detailing what, if any, change was made to a record field :param string lookupType: what cleaning rule made the change; one of: genericLookup, genericRegex, fieldSpecificLookup, fieldSpecificRegex, normLookup, normRegex, normIncludes, deriveValue, copyValue, deriveRegex :param string fromVa...
21,488
def get_direct_queue(self): return Queue(self.id, self.inbox_direct, routing_key=self.routing_key, auto_delete=True)
Returns a :class: `kombu.Queue` instance to be used to listen for messages send to this specific Actor instance
21,489
def plot(self, columns=None, loc=None, iloc=None, **kwargs): from matplotlib import pyplot as plt assert loc is None or iloc is None, "Cannot set both loc and iloc in call to .plot" def shaded_plot(ax, x, y, y_upper, y_lower, **kwargs): base_line, = ax.plot(x, y, drawstyle...
A wrapper around plotting. Matplotlib plot arguments can be passed in, plus: Parameters ----------- columns: string or list-like, optional If not empty, plot a subset of columns from the ``cumulative_hazards_``. Default all. loc: iloc: slice, optional specif...
21,490
def LightcurveHDU(model): cards = model._mission.HDUCards(model.meta, hdu=1) cards.append((, )) cards.append((, )) cards.append((, )) cards.append((, model.mission, )) cards.append((, EVEREST_MAJOR_MINOR, )) cards.append((, EVEREST_VERSION, )) cards.append((, strftime(),...
Construct the data HDU file containing the arrays and the observing info.
21,491
def unpack(self, buff, offset=0): begin = offset hexas = [] while begin < offset + 8: number = struct.unpack("!B", buff[begin:begin+1])[0] hexas.append("%.2x" % number) begin += 1 self._value = .join(hexas)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
21,492
def _build_http(http=None): if not http: http = httplib2.Http( timeout=HTTP_REQUEST_TIMEOUT, ca_certs=HTTPLIB_CA_BUNDLE) user_agent = .format( httplib2.__version__, , ) return set_user_agent(http, user_agent)
Construct an http client suitable for googleapiclient usage w/ user agent.
21,493
def kill(self) -> None: self._proc.kill() self._loop.run_in_executor(None, self._proc.communicate)
Kill ffmpeg job.
21,494
def generate_signed_url_v2( credentials, resource, expiration, api_access_endpoint="", method="GET", content_md5=None, content_type=None, response_type=None, response_disposition=None, generation=None, headers=None, query_parameters=None, ): expiration_stamp = ge...
Generate a V2 signed URL to provide query-string auth'n to a resource. .. note:: Assumes ``credentials`` implements the :class:`google.auth.credentials.Signing` interface. Also assumes ``credentials`` has a ``service_account_email`` property which identifies the credentials. ....
21,495
def render_field(self, obj, field_name, **options): try: field = obj._meta.get_field(field_name) except FieldDoesNotExist: return getattr(obj, field_name, ) if hasattr(field, ) and getattr(field, ): return getattr(obj, .format(field_name))() ...
Render field
21,496
def add_dependency(self, p_from_todo, p_to_todo): def find_next_id(): def id_exists(p_id): for todo in self._todos: number = str(p_id) if todo.has_tag(, number) or todo.has_tag(, number): ...
Adds a dependency from task 1 to task 2.
21,497
def unpack_kinesis_event(kinesis_event, deserializer=None, unpacker=None, embed_timestamp=False): records = kinesis_event["Records"] events = [] shard_ids = set() for rec in records: data = rec["kinesis"]["data"] try: payload = b64decode(data) ...
Extracts events (a list of dicts) from a Kinesis event.
21,498
def getstate(self): state = "RUNNING" exit_code = -1 exitcode_file = os.path.join(self.workdir, "exit_code") pid_file = os.path.join(self.workdir, "pid") if os.path.exists(exitcode_file): with open(exitcode_file) as f: exit_code = int(f.read...
Returns RUNNING, -1 COMPLETE, 0 or EXECUTOR_ERROR, 255
21,499
def find_sample_min_std(self, Intensities): Best_array = [] best_array_std_perc = inf Best_array_tmp = [] Best_interpretations = {} Best_interpretations_tmp = {} for this_specimen in list(Intensities.keys()): for value in Intensities[this_specimen]: ...
find the best interpretation with the minimum stratard deviation (in units of percent % !)