Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
349,700
def validate_nexson(obj, warning_codes_to_skip=None, retain_deprecated=True, **kwargs): if warning_codes_to_skip: v = FilteringLogger(codes_to_skip=list(warning_codes_to_skip), store_messages=True) else: v = ValidationLogger(store_messages=True) v.retain_deprecated = retain_deprecated ...
Takes an `obj` that is a NexSON object. `warning_codes_to_skip` is None or an iterable collection of integers that correspond to facets of NexsonWarningCodes. Warnings associated with any code in the list will be suppressed. `retain_deprecated` if False, then `obj` may be modified to replace ...
349,701
def detect_mountpoint(self): if self.info.get(): return self.info.get() if not self.mountpoint: return None result = None paths = os.listdir(self.mountpoint) if in paths: result = elif in paths and in paths and in paths:...
Attempts to detect the previous mountpoint if this was not done through :func:`load_fsstat_data`. This detection does some heuristic method on the mounted volume.
349,702
def load_utf_text_file(file_, default_encoding=, use_utf8_strings=True): if isinstance(file_, my_basestring): with open(file_, ) as f: buf = f.read() else: buf = file_.read() return decode_utf_text_buffer(buf, default_encoding, use_utf8_strings)
Loads the specified text file and tries to decode it using one of the UTF encodings. :param file_: The path to the loadable text file or a file-like object with a read() method. :param default_encoding: The encoding to be used if the file doesn't have a BOM prefix. :param use_utf8_strings: Ignored in case o...
349,703
def collection_composition(collection, raw=False): tc = ThriftClient() body = {"query": {"filtered": {}}} fltr = {} query = { "query": { "bool": { "must": [ { "match": { "collection": col...
This method retrieve the total of documents, articles (citable documents), issues and bibliografic references of a journal arguments collection: SciELO 3 letters Acronym issn: Journal ISSN return for journal context { "citable": 12140, "non_citable": 20, "docs": 12160, ...
349,704
def save(self, model_file, save_dir, verbose=True): if not os.path.exists(save_dir): os.makedirs(save_dir) params = { "model": self.state_dict(), "cardinality": self.cardinality, "name": self.name, "config": self.settings, ...
Save current model. :param model_file: Saved model file name. :type model_file: str :param save_dir: Saved model directory. :type save_dir: str :param verbose: Print log or not :type verbose: bool
349,705
def dispatch(self, event, ev_msg): logger.debug( + event + + repr(ev_msg)) eo = self.events.get(event, None) if eo: eo.dispatch(ev_msg)
Dispatch an event. event: name of the event (str) ev_msg: non-optional arguments dictionary. Side effects: If an EventObject is not already registered with the EventManager, a new EventObject will be created and registered.
349,706
def run_multiple_commands_redirect_stdout( multiple_args_dict, print_commands=True, process_limit=-1, polling_freq=0.5, **kwargs): assert len(multiple_args_dict) > 0 assert all(len(args) > 0 for args in multiple_args_dict.values()) assert all(hasattr(f, ) for f i...
Run multiple shell commands in parallel, write each of their stdout output to files associated with each command. Parameters ---------- multiple_args_dict : dict A dictionary whose keys are files and values are args list. Run each args list as a subprocess and write stdout to the ...
349,707
def walk(self, top, topdown=True, onerror=None, followlinks=False): return walk(self.filesystem, top, topdown, onerror, followlinks)
Perform a walk operation over the fake filesystem. Args: top: The root directory from which to begin walk. topdown: Determines whether to return the tuples with the root as the first entry (`True`) or as the last, after all the child directory tuples (`Fa...
349,708
def is_name_valid(fqn): if not isinstance(fqn, (str,unicode)): return False if fqn.count( "." ) != 1: return False name, namespace_id = fqn.split(".") if len(name) == 0 or len(namespace_id) == 0: return False if not is_b40( name ) or "+" in name or "." in name: ...
Is a fully-qualified name acceptable? Return True if so Return False if not >>> is_name_valid('abcd') False >>> is_name_valid('abcd.') False >>> is_name_valid('.abcd') False >>> is_name_valid('Abcd.abcd') False >>> is_name_valid('abcd.abc.d') False >>> is_name_valid(...
349,709
def _make_fileobj(self): bio = BytesIO() f = gzip.GzipFile(mode=, fileobj=bio) if self.use_gzip else bio exporter = JsonLinesItemExporter(f) exporter.start_exporting() for item in self.items: exporter.export_item(item) exporter.finish_expor...
Build file object from items.
349,710
def insertElementTable(self, token): element = self.createElement(token) if self.openElements[-1].name not in tableInsertModeElements: return self.insertElementNormal(token) else: parent, insertBefore = self.getTableMisnestedNodePosition...
Create an element and insert it into the tree
349,711
def measure(self, v, rf, off=None): if off is None: off = {} keys = ["m0", "m1", "m2"] for key in keys: if key in v: if dq.is_quantity(v[key]): v[key] = v[key].to_dict() return _measures.measure(self, v, rf, off)
Create/convert a measure using the frame state set on the measures server instance (via :meth:`do_frame`) :param v: The measure to convert :param rf: The frame reference to convert to :param off: The optional offset for the measure
349,712
def delete(uid): q_u1 = TabPostHist.delete().where(TabPostHist.post_id == uid) q_u1.execute() q_u2 = TabRel.delete().where(TabRel.post_f_id == uid or TabRel.post_t_id == uid) q_u2.execute() q_u3 = TabCollect.delete().where(TabCollect.post_id == uid) q_u3.execute...
Delete by uid
349,713
def forward_word_extend_selection(self, e): u self.l_buffer.forward_word_extend_selection(self.argument_reset) self.finalize()
u"""Move forward to the end of the next word. Words are composed of letters and digits.
349,714
def remove_genes(cobra_model, gene_list, remove_reactions=True): gene_set = {cobra_model.genes.get_by_id(str(i)) for i in gene_list} gene_id_set = {i.id for i in gene_set} remover = _GeneRemover(gene_id_set) ast_rules = get_compiled_gene_reaction_rules(cobra_model) target_reactions = [] for...
remove genes entirely from the model This will also simplify all gene_reaction_rules with this gene inactivated.
349,715
def filter(self, twig=None, check_visible=True, check_default=True, **kwargs): kwargs[] = check_visible kwargs[] = check_default kwargs[] = True return self.filter_or_get(twig=twig, **kwargs)
Filter the ParameterSet based on the meta-tags of the Parameters and return another ParameterSet. Because another ParameterSet is returned, these filter calls are chainable. >>> b.filter(context='component').filter(component='starA') :parameter str twig: (optional) the search ...
349,716
def lexrank(sentences, continuous=False, sim_threshold=0.1, alpha=0.9, use_divrank=False, divrank_alpha=0.25): こんにちは.私の名前は飯沼です.s not the damping factor, see divrank.py) Returns: tuple ( { 0: 0.003, 1: 0.002, ... }, similarity_ma...
compute centrality score of sentences. Args: sentences: [u'こんにちは.', u'私の名前は飯沼です.', ... ] continuous: if True, apply continuous LexRank. (see reference) sim_threshold: if continuous is False and smilarity is greater or equal to sim_threshold, link the sentences. alpha: the damping fa...
349,717
def to_python(self, value): value = if value in validators.EMPTY_VALUES else smart_text(value) if value == self.empty_value or value in validators.EMPTY_VALUES: return self.empty_value try: value = self.coerce(value) except (ValueError, TypeError, Valida...
Validates that the value is in self.choices and can be coerced to the right type.
349,718
def get_all_hits(self): if not self.connect_to_turk(): return False try: hits = [] paginator = self.mtc.get_paginator() for page in paginator.paginate(): hits.extend(page[]) except Exception as e: print e ...
Get all HITs
349,719
def run_getmy(filename, **kwargs): assume_yes = kwargs.get("yes_to_all") user = getenv("GETGIST_USER") getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes) getgist.get()
Shortcut for run_getgist() reading username from env var
349,720
def nLLevalAllY(ldelta, UY, UX, S): return _core.nLLevalAllY(ldelta, UY, UX, S)
nLLevalAllY(double ldelta, MatrixXd const & UY, MatrixXd const & UX, VectorXd const & S) Parameters ---------- ldelta: double UY: MatrixXd const & UX: MatrixXd const & S: VectorXd const &
349,721
def _to_choi(rep, data, input_dim, output_dim): if rep == : return data if rep == : return _from_operator(, data, input_dim, output_dim) if rep == : return _superop_to_choi(data, input_dim, output_dim) if rep == : return _kraus_to_choi(data, input_dim, output_dim) ...
Transform a QuantumChannel to the Choi representation.
349,722
def setup(self, app): super().setup(app) self.handlers = OrderedDict() app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, )) @app.ps.jinja2.filter def admtest(value, a, b=None): return a if value else b @app.ps.jinja2.filter ...
Initialize the application.
349,723
def add_spec(self, *specs): for spec in specs: if not isinstance(spec, HeronComponentSpec): raise TypeError("Argument to add_spec needs to be HeronComponentSpec, given: %s" % str(spec)) if spec.name is None: raise ValueError("TopologyBuilder cannot take a spe...
Add specs to the topology :type specs: HeronComponentSpec :param specs: specs to add to the topology
349,724
def pointInGrid(A_point, a_gridSize, *args): b_wrapGridEdges = False if len(args): b_wrapGridEdges = args[0] if b_wrapGridEdges: W = where(A_point < 0) A_point[W] += a_gridSize[W[1]] Wbool = A_point >= 0 W = Wbool.prod(axis=1) A_point = A_point[where(W > 0)] ...
SYNOPSIS [A_point] = pointInGrid(A_point, a_gridSize [, ab_wrapGridEdges]) ARGS INPUT A_point array of N-D points points in grid space a_gridSize array the size (rows, cols) of + the grid space ...
349,725
def create_todo_item(self, list_id, content, party_id=None, notify=False): path = % list_id req = ET.Element() ET.SubElement(req, ).text = str(content) if party_id is not None: ET.SubElement(req, ).text = str(party_id) ET.SubElement(req, ).text = str(boo...
This call lets you add an item to an existing list. The item is added to the bottom of the list. If a person is responsible for the item, give their id as the party_id value. If a company is responsible, prefix their company id with a 'c' and use that as the party_id value. If the item h...
349,726
def getSampleTypes(self, active_only=True): catalog = api.get_tool("bika_setup_catalog") query = { "portal_type": "SampleType", "sort_on": "title", "sort_order": "ascending" } results = catalog(query) ...
Return all sampletypes
349,727
def set_preshared_key(self, new_key): if self.data.get(): self.update(preshared_key=new_key)
Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None
349,728
def _parse_parameter_list(parameter_list, normalized_parameter_values=_DEF_PARAM_VALUE, normalize_parameter_names=False, normalize_parameter_values=True): if normalized_parameter_values is not _DEF_PARAM_VALUE: warnings.war...
Parse a named parameter list in the "common" format. :param parameter_list: sequence of string values to parse :keyword bool normalize_parameter_names: if specified and *truthy* then parameter names will be case-folded to lower case :keyword bool normalize_parameter_values: if omitted or specified ...
349,729
def auto_init(autofile, force_init=False): if os.path.exists(autofile) and not force_init: try: autooptions = json.loads(open(autofile).read()) return autooptions except: print("Error in dgit.json configuration file") traceback.print_exc() ...
Initialize a repo-specific configuration file to execute dgit Parameters ---------- autofile: Repo-specific configuration file (dgit.json) force_init: Flag to force to re-initialization of the configuration file
349,730
def is_defined(self, objtxt, force_import=False): if self._reading: return wait_loop = QEventLoop() self.sig_got_reply.connect(wait_loop.quit) self.silent_exec_method( "get_ipython().kernel.is_defined(, force_import=%s)" % (objtxt, force_impor...
Return True if object is defined
349,731
def Bidirectional(l2r, r2l): nO = l2r.nO def birnn_fwd(Xs, drop=0.0): l2r_Zs, bp_l2r_Zs = l2r.begin_update(Xs, drop=drop) r2l_Zs, bp_r2l_Zs = r2l.begin_update( [l2r.ops.xp.ascontiguousarray(X[::-1]) for X in Xs] ) def birnn_bwd(dZs, sgd=None): d_l2r...
Stitch two RNN models into a bidirectional layer.
349,732
def interact(title, description, prompt, binary, options): args = [binary] p = subprocess.Popen(args=args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=os.environ) p.args = args expect(p, [b]) title = util.assua...
Use GPG pinentry program to interact with the user.
349,733
def string_to_file(path, input): mkdir_p(os.path.dirname(path)) with codecs.open(path, "w+", "UTF-8") as file: file.write(input)
Write a file from a given string.
349,734
def all(self): items = list() if not self._filters_cmd: items = self.store.get(self.query_class) else: for item in self.store.get(self.query_class): tmp_flag = True for filter_cmd in self._filters_cmd: if not fi...
SQLA like 'all' method, will populate all rows and apply all filters and orders to it.
349,735
def _run_nonblocking(self, args, input=None): if self._process: self.close() self._process = subprocess.Popen(args, stdout=subprocess.PIPE)
Internal API: run a non-blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process...
349,736
def _exact_fuzzy_match(response, match, insensitive): if insensitive: response = response.lower() match = match.lower() r_words = response.split() m_words = match.split() for word in r_words: if word in m_words: r_words.remove(word) m_words.remov...
Return True if the response matches fuzzily exactly. Insensitivity is taken into account.
349,737
def path_encloses_pt(pt, opt, path): assert path.isclosed() intersections = Path(Line(pt, opt)).intersect(path) if len(intersections) % 2: return True else: return False
returns true if pt is a point enclosed by path (which must be a Path object satisfying path.isclosed==True). opt is a point you know is NOT enclosed by path.
349,738
def peak_to_peak_period(t, f, amplitude_threshold=1E-2): if hasattr(t, ): t_unit = t.unit t = t.value else: t_unit = u.dimensionless_unscaled max_ix = argrelmax(f, mode=)[0] max_ix = max_ix[(max_ix != 0) & (max_ix != (len(f)-1))] min_ix = argrelmin(f, mode=)[...
Estimate the period of the input time series by measuring the average peak-to-peak time. Parameters ---------- t : array_like Time grid aligned with the input time series. f : array_like A periodic time series. amplitude_threshold : numeric (optional) A tolerance paramet...
349,739
def disable_dao_fork(chain_class: Type[BaseChain]) -> Type[BaseChain]: homstead_vms_found = any( _is_homestead(vm_class) for _, vm_class in chain_class.vm_configuration ) if not homstead_vms_found: raise ValidationError("No HomesteadVM found in vm_configuration.") vm_configuration ...
Set the ``support_dao_fork`` flag to ``False`` on the :class:`~eth.vm.forks.homestead.HomesteadVM`. Requires that presence of the :class:`~eth.vm.forks.homestead.HomesteadVM` in the ``vm_configuration``
349,740
def add(self, obj, metadata=None, update=False): if (obj not in self) or update: self[obj.id] = Object.fromdict( obj.id, dict( metadata=obj.metadata.read() if metadata is None else metadata, bitstreams=[bs._properties f...
Add an existing CDSTAR object to the catalog. :param obj: A pycdstar.resource.Object instance
349,741
def ssh(container, cmd=, user=, password=): rootroot ip = get_ip(container) ssh_cmd = %s\%s\ % (password, user, ip) local( % ( env.key_filename, env.user, env.host, ssh_cmd, cmd))
SSH into a running container, using the host as a jump host. This requires the container to have a running sshd process. Args: * container: Container name or ID * cmd='': Command to run in the container * user='root': SSH username * password='root': SSH password
349,742
def _groups_of_size(iterable, n, fillvalue=None): args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args)
Collect data into fixed-length chunks or blocks.
349,743
def add_upsert(self, value, criteria): value = value.strip() v = value.lower() self.lower_val_to_val[v] = value criteria_array = self.upserts.get(v) if criteria_array is None: criteria_array = [] self.upserts_size[v] = 31 + len(value...
Add a tag or populator to the batch by value and criteria
349,744
def percentAt(self, value): if value is None: return 0.0 values = self.values() try: return float(values.index(value)) / (len(values) - 1) except ValueError: return 0.0 except ZeroDivisionError: ...
Returns the percentage where the given value lies between this rulers minimum and maximum values. If the value equals the minimum, then the percent is 0, if it equals the maximum, then the percent is 1 - any value between will be a floating point. If the ruler is a custom type, the...
349,745
def argpack(args): if isinstance(args[0], (tuple, list, ndarray)): return tupleize(args[0]) elif isinstance(args[0], Iterable) and not isinstance(args[0], str): return tupleize(list(args[0])) else: return tuple(args)
Coerce a list of arguments to a tuple. Parameters ---------- args : tuple or nested tuple Pack arguments into a tuple, converting ((,...),) or (,) -> (,)
349,746
def get_node(self, ID): for node in self.nodes: if node.ID == str(ID): return node return None
Returns the node with the given ID or None.
349,747
def nextSolarEclipse(date): eclipse = swe.solarEclipseGlobal(date.jd, backward=False) return Datetime.fromJD(eclipse[], date.utcoffset)
Returns the Datetime of the maximum phase of the next global solar eclipse.
349,748
def get_interpolated_value(self, energy): f = {} for spin in self.densities.keys(): f[spin] = get_linear_interpolated_value(self.energies, self.densities[spin], energy) re...
Returns interpolated density for a particular energy. Args: energy: Energy to return the density for.
349,749
def set_measurements(test): test.measurements.level_none = 0 time.sleep(1) test.measurements.level_some = 8 time.sleep(1) test.measurements.level_all = 9 time.sleep(1) level_all = test.get_measurement() assert level_all.value == 9
Test phase that sets a measurement.
349,750
def get_parameter(self, var): parameter = [] for parameter_tag in var.findall(): parameter_type = if parameter_tag.get() is not None: parameter_type = parameter_tag.get() if parameter_type == : parameter = self.get_parameter_...
This method supports the functional tags by providing the actual values in the function as list of dict in case of table type parameter or as nested dict in case of decision diagram
349,751
def type(self, mpath): try: return self.stat(mpath)["type"] except errors.MantaResourceNotFoundError: return None except errors.MantaAPIError: _, ex, _ = sys.exc_info() if ex.code in (, ): return None else: ...
Return the manta type for the given manta path. @param mpath {str} The manta path for which to get the type. @returns {str|None} The manta type, e.g. "object" or "directory", or None if the path doesn't exist.
349,752
def load_yaml(filename): with open(filename) as myfile: content = myfile.read() if "win" in sys.platform: content = content.replace("\\", "/") return yaml.safe_load(content)
Return object in yaml file.
349,753
def convert_data_element_to_data_and_metadata_1(data_element) -> DataAndMetadata.DataAndMetadata: data = data_element["data"] dimensional_shape = Image.dimensional_shape_from_data(data) is_sequence = data_element.get("is_sequence", False) dimension_count = len(Image.dimensional_shape_from_data...
Convert a data element to xdata. No data copying occurs. The data element can have the following keys: data (required) is_sequence, collection_dimension_count, datum_dimension_count (optional description of the data) spatial_calibrations (optional list of spatial calibration dicts, scale, o...
349,754
def append(self, offset, timestamp, key, value, headers, encode_varint=encode_varint, size_of_varint=size_of_varint, get_type=type, type_int=int, time_time=time.time, byte_like=(bytes, bytearray, memoryview), bytearray_type=bytearray, len_func=...
Write message to messageset buffer with MsgVersion 2
349,755
def strippen(function): "Decorator. Strip excess whitespace from return value." def wrapper(*args, **kwargs): return strip_strings(function(*args, **kwargs)) return wrapper
Decorator. Strip excess whitespace from return value.
349,756
def _cleanRecursive(self, subSelf): for key, item in list(subSelf.items()): if self.isNestedDict(item): if not item: subSelf.pop(key) else: self._cleanRecursive(item)
Delete all NestedOrderedDict that haven't any entries.
349,757
def model_from_path(model_path, fuzziness=False): app_name = .join(model_path.split()[:-1]) model_name = model_path.split()[-1] if not app_name: return None module = importlib.import_module(app_name) try: model = getattr(module, model_name) except AttributeError: t...
Find the model class for a given model path like 'project.app.model' Args: path (str): dot-delimited model path, like 'project.app.model' Returns: Django Model-based class
349,758
def close(self): if self._closing: return self._closing = True for stream in self.streams: stream.close() self.streams.clear() if hasattr(self.sock, ): self.sock.close()
Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks.
349,759
def _check_for_pi(element): frac = Fraction(element / np.pi).limit_denominator(8) num, den = frac.numerator, frac.denominator sign = "-" if num < 0 else "" if num / float(den) == element / np.pi: if num == 0: return "0" elif abs(num) == 1 and den == 1: return...
Check to see if there exists a rational number r = p/q in reduced form for which the difference between element/np.pi and r is small and q <= 8. :param element: float :return element: pretty print string if true, else standard representation.
349,760
def run(self): import parmap from prospector.formatters.pylint import PylintFormatter cwd = os.getcwd() files = self._get_files_to_lint([os.path.join(cwd, "test")]) if not files: sys_exit(0) return use_multiprocessing = (not os.getenv...
Run linters.
349,761
def get_injuries(self, season, week): result = self._method_call("Injuries/{season}/{week}", "stats", season=season, week=week) return result
Injuries by week
349,762
def process_download_path(self): if os.path.exists(self.download_path): if not os.access(self.download_path, os.W_OK): raise DirectoryAccessError elif os.access(os.path.dirname(self.download_path), os.W_OK): os.makedirs(self.download_path) else: ...
Processes the download path. It checks if the path exists and the scraper has write permissions.
349,763
def form(self, usr=None, **kwargs): if self.usr: usr = self.usr if self.find("form", kwargs): return HTTPForm(usr, self.url, self.find("form", kwargs))
Returns an HTTPForm that matches the given criteria Searches for an HTML form in the page's content matching the criteria specified in kwargs. If a form is found, returns an HTTPForm instance that represents the form. Parameters: usr (User) -- User to asso...
349,764
def retrieve(self, node): if not self.is_enabled(): return False env = node.get_build_env() if cache_show: if CacheRetrieveSilent(node, [], env, execute=1) == 0: node.build(presub=0, execute=0) return True else: ...
This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Note that there's a special trick here with the execute flag (one that's not normally done for other actions). Basically if the user requested ...
349,765
def write_port(self, port, value): if port == : self.GPIOA = value elif port == : self.GPIOB = value else: raise AttributeError(.format(port)) self.sync()
Use a whole port as a bus and write a byte to it. :param port: Name of the port ('A' or 'B') :param value: Value to write (0-255)
349,766
def median_low(name, num, minimum=0, maximum=0, ref=None): return calc( name=name, num=num, oper=, minimum=minimum, maximum=maximum, ref=ref )
Calculates the low mean of the ``num`` most recent values. Requires a list. USAGE: .. code-block:: yaml foo: calc.median_low: - name: myregentry - num: 5
349,767
def check(self): if len(self.status_datasets) == 0: return False if all(self.status_datasets): return True return False
Returns False if no datasets exists or if one or more of the datasets are empty
349,768
def bind_to(self, argspec, dispatcher): self.bound_to[argspec.key].add((argspec, dispatcher)) dispatcher.bind(self.f, argspec)
Add our function to dispatcher
349,769
def channels_twitter_ticket_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/twitter_channel api_path = "/api/v2/channels/twitter/tickets.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/twitter_channel#create-ticket-from-tweet
349,770
def terminate(self): logger.info(.format(self.name)) if hasattr(self, ) and self.remote_client is not None: self.terminate_sent = True self.remote_client.close() return if not self.process: raise DagobahError() self.terminate_sent ...
Send SIGTERM to the task's process.
349,771
def _monomers(self): for stmt in self.statements: if _is_whitelisted(stmt): self._dispatch(stmt, , self.agent_set)
Calls the appropriate monomers method based on policies.
349,772
def generate_api(version): def get_partial_api(key, token=None): return TrelloAPI(ENDPOINTS[version], version, key, token=token) get_partial_api.__doc__ = \ .format(version) return get_partial_api
Generates a factory function to instantiate the API with the given version.
349,773
def targets_for_class(self, target, classname): targets_with_class = set() for target in target.closure(): for one_class in self._target_classes(target): if classname in one_class: targets_with_class.add(target) break return targets_with_class
Search which targets from `target`'s transitive dependencies contain `classname`.
349,774
def export_mv_grid(self, session, mv_grid_districts): if not all(isinstance(_, int) for _ in mv_grid_districts): raise TypeError() srid = str(int(cfg_ding0.get(, ))) session.query(db_int.sqla_mv_grid_viz).dele...
Exports MV grids to database for visualization purposes Parameters ---------- session : sqlalchemy.orm.session.Session Database session mv_grid_districts : List of MV grid_districts (instances of MVGridDistrictDing0 class) whose MV grids are exported. Re...
349,775
def post_process(self, layer): LOGGER.info() purpose = layer.keywords[] if purpose != layer_purpose_aggregation_summary[]: layer_title(layer) for post_processor in post_processors: run, run_message = should_run(layer.keywords, post...
More process after getting the impact layer with data. :param layer: The vector layer to use for post processing. :type layer: QgsVectorLayer
349,776
def get_graph(graph, conn, **kwargs): sparql = render_without_request("sparqlGraphDataTemplate.rq", prefix=NSM.prefix(), graph=graph) return conn.query(sparql, **kwargs)
Returns all the triples for a specific are graph args: graph: the URI of the graph to retreive conn: the rdfframework triplestore connection
349,777
def indented_script(self) -> bool: leading = INDENTED.match(self._script) return 0 if leading is None else len(leading.group(2))
check self._script and see if it is indented
349,778
def match(self, root, ns): tns = root.get() if len(self.tns): matched = ( tns in self.tns ) else: matched = 1 itself = ( ns == tns ) return ( matched and not itself )
Match by I{targetNamespace} excluding those that are equal to the specified namespace to prevent adding an import to itself. @param root: A schema root. @type root: L{Element}
349,779
def process_post_tags(self, bulk_mode, api_post, post_tags): post_tags[api_post["ID"]] = [] for api_tag in six.itervalues(api_post["tags"]): tag = self.process_post_tag(bulk_mode, api_tag) if tag: post_tags[api_post["ID"]].append(tag)
Create or update Tags related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_post: the API data for the post :param post_tags: a mapping of Tags keyed by post ID :return: None
349,780
def cached_func(fname=None, cache_dir=, appname=, key_argx=None, key_kwds=None, use_cache=None, verbose=None): r if verbose is None: verbose = VERBOSE_CACHE def cached_closure(func): from utool import util_decor import utool as ut fname_ = util_inspect.get_fun...
r""" Wraps a function with a Cacher object uses a hash of arguments as input Args: fname (str): file name (defaults to function name) cache_dir (unicode): (default = u'default') appname (unicode): (default = u'utool') key_argx (None): (default = None) key_kwds (Non...
349,781
def get_bytes(self, bridge): if not bridge.is_ready: raise Exception() wb1 = bridge.wb1 wb2 = bridge.wb2 sn = bridge.sn preamble = [0x80, 0x00, 0x00, 0x00, 0x11, wb1, wb2, 0x00, sn, 0x00] cmd = [0x31, self.PASSWORD_BYTE1, self.PASSWORD_BYTE2, ...
Gets the full command as bytes. :param bridge: The bridge, to which the command should be sent.
349,782
def _remove_duplicate(old_events, dat): diff_events = diff(old_events, axis=0) dupl = where((diff_events[:, 0] == 0) & (diff_events[:, 2] == 0))[0] dupl += 1 n_nondupl_events = old_events.shape[0] - len(dupl) new_events = zeros((n_nondupl_events, old_events.shape[1]), dtype=) if len(dupl...
Remove duplicates from the events. Parameters ---------- old_events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the data after detection-transformation (to compute peak) Returns ------- ndarray (dtype='int') ...
349,783
def _add_field(self, field_type, name, value): try: self.__getattribute__(field_type).update({name: value}) except: raise ValueError( %field_type) self.__setattr__(name, value)
Adds a new field to a specified dictionary. The field is also added as a process attribute. field_type can be 'input', 'diagnostics'
349,784
def no_moves(position): return position.no_moves(color.white) \ or position.no_moves(color.black)
Finds if the game is over. :type: position: Board :rtype: bool
349,785
def _column_type(strings, has_invisible=True): types = [_type(s, has_invisible) for s in strings ] return reduce(_more_generic, types, int)
The least generic type all column values are convertible to. >>> _column_type(["1", "2"]) is _int_type True >>> _column_type(["1", "2.3"]) is _float_type True >>> _column_type(["1", "2.3", "four"]) is _text_type True >>> _column_type(["four", '\u043f\u044f\u0442\u044c']) is _text_type T...
349,786
def cdn_url(request): cdn_url, ssl_url = _get_container_urls(CumulusStorage()) static_url = settings.STATIC_URL return { "CDN_URL": cdn_url + static_url, "CDN_SSL_URL": ssl_url + static_url, }
A context processor that exposes the full CDN URL in templates.
349,787
def unpunctuate(s, *, char_blacklist=string.punctuation): s = "".join(c for c in s if c not in char_blacklist) return " ".join(filter(None, s.split(" ")))
Remove punctuation from string s.
349,788
def trim(self, *conditions): conditions = list(conditions) for n in range(len(conditions)): if type(conditions[n]) is str: conditions[n] = self.execute_script(conditions[n]) new_databox = databox(delimiter=self.delimiter) new_datab...
Removes data points not satisfying the supplied conditions. Conditions can be truth arrays (having the same length as the columns!) or scripted strings. Example Workflow ---------------- d1 = spinmob.data.load() d2 = d1.trim( (2<d1[0]) & (d1[0]<10) | (d1[3]==22), 'sin(d[...
349,789
def _strip_tag(tree, tag): for el in tree.iter(): if el.tag == tag: el.getparent().remove(el)
Remove all tags that have the tag name ``tag``
349,790
def create_gzip (archive, compression, cmd, verbosity, interactive, filenames): if len(filenames) > 1: raise util.PatoolError() try: with gzip.GzipFile(archive, ) as gzipfile: filename = filenames[0] with open(filename, ) as srcfile: data = srcfile.re...
Create a GZIP archive with the gzip Python module.
349,791
def appendInputWithSimilarValues(inputs): numInputs = len(inputs) for i in xrange(numInputs): input = inputs[i] for j in xrange(len(input)-1): if input[j] == 1 and input[j+1] == 0: newInput = copy.deepcopy(input) newInput[j] = 0 newInput[j+1] = 1 inputs.append(newInp...
Creates an 'one-off' record for each record in the inputs. Appends new records to the same inputs list.
349,792
def make_tarball(tarball_fname,directory,cwd=None): "create a tarball from a directory" if tarball_fname.endswith(): opts = else: opts = args = [,opts,tarball_fname,directory] process_command(args, cwd=cwd)
create a tarball from a directory
349,793
def markdown(self,md,base_url=): print("\nProcessing documentation comments...") ford.sourceform.set_base_url(base_url) if self.settings[].lower() == : print() for src in self.allfiles: src.markdown(md, self)
Process the documentation with Markdown to produce HTML.
349,794
def load_psat(cls, fd): from pylon.io.psat import PSATReader return PSATReader().read(fd)
Returns a case object from the given PSAT data file.
349,795
def bind_keys(self, objects): for object in objects: if object.keys != None: for key in object.keys: if key != None: self.bind_key_name(key, object.name)
Configure name map: My goal here is to associate a named object with a specific function
349,796
def register_shipping_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs): filters_set = self.filters_factory.resolve(self.shipping_query_handlers, *custom_filters, ...
Register handler for shipping query Example: .. code-block:: python3 dp.register_shipping_query_handler(some_shipping_query_handler, lambda shipping_query: True) :param callback: :param state: :param custom_filters: :param run_task: run callback in task (n...
349,797
def count_below_mean(x): m = np.mean(x) return np.where(x < m)[0].size
Returns the number of values in x that are lower than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
349,798
def collect_observations_in_state(self, observations, state_index): if not self.hidden_state_trajectories: raise RuntimeError() dtype = observations[0].dtype collected_observations = np.array([], dtype=dtype) for (s_t, o_t) in zip(self.hidden_state_trajecto...
Collect a vector of all observations belonging to a specified hidden state. Parameters ---------- observations : list of numpy.array List of observed trajectories. state_index : int The index of the hidden state for which corresponding observations are to be retr...
349,799
def bootstrap(v): if type(v)==list: vboot=[] n=v[0].size iran=scipy.random.randint(0,n,n) for x in v: vboot.append(x[iran]) else: n=v.size iran=scipy.random.randint(0,n,n) vboot=v[iran] return vboot
Constructs Monte Carlo simulated data set using the Bootstrap algorithm. Usage: >>> bootstrap(x) where x is either an array or a list of arrays. If it is a list, the code returns the corresponding list of bootstrapped arrays assuming...