Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
3,700
def simple_db_engine(reader=None, srnos=None): if reader is None: reader = dbreader.Reader() logger.debug("No reader provided. Creating one myself.") info_dict = dict() info_dict["filenames"] = [reader.get_cell_name(srno) for srno in srnos] info_dict["masses"] = [reader.get_mass(s...
engine that gets values from the simple excel 'db
3,701
def djfrontend_jquery_formset(version=None): if version is None: version = getattr(settings, , DJFRONTEND_JQUERY_FORMSET_DEFAULT) if getattr(settings, , False): template = else: template = ( <script src="{static}djfrontend/js/jquery/jquery.formset/{v}/...
Returns the jQuery Dynamic Formset plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file.
3,702
def get_project_totals(entries, date_headers, hour_type=None, overtime=False, total_column=False, by=): totals = [0 for date in date_headers] rows = [] for thing, thing_entries in groupby(entries, lambda x: x[by]): name, thing_id, date_dict = date_totals(thing_entries, by...
Yield hour totals grouped by user and date. Optionally including overtime.
3,703
def _create_storage_profile(self): if self.image_publisher: storage_profile = { : { : self.image_publisher, : self.image_offer, : self.image_sku, : self.image_version }, ...
Create the storage profile for the instance. Image reference can be a custom image name or a published urn.
3,704
def inv_n(x): assert x.ndim == 3 assert x.shape[1] == x.shape[2] c = np.array([ [cofactor_n(x, j, i) * (1 - ((i+j) % 2)*2) for j in range(x.shape[1])] for i in range(x.shape[1])]).transpose(2,0,1) return c / det_n(x...
given N matrices, return N inverses
3,705
def preprocess(self, x): if (six.PY2 and isinstance(x, six.string_types) and not isinstance(x, six.text_type)): x = Pipeline(lambda s: six.text_type(s, encoding=))(x) if self.sequential and isinstance(x, six.text_type): x = self.tokenize(x.rstrip()) ...
Load a single example using this field, tokenizing if necessary. If the input is a Python 2 `str`, it will be converted to Unicode first. If `sequential=True`, it will be tokenized. Then the input will be optionally lowercased and passed to the user-provided `preprocessing` Pipeline.
3,706
def check_xml(code): try: xml.etree.ElementTree.fromstring(code) except xml.etree.ElementTree.ParseError as exception: message = .format(exception) line_number = 0 found = re.search(r, message) if found: line_number = int(found.group(1)) yield (...
Yield errors.
3,707
def upcoming( cls, api_key=djstripe_settings.STRIPE_SECRET_KEY, customer=None, coupon=None, subscription=None, subscription_plan=None, subscription_prorate=None, subscription_proration_date=None, subscription_quantity=None, subscription_trial_end=None, **kwargs ): if customer is not None...
Gets the upcoming preview invoice (singular) for a customer. At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, including subscription renewal charges, invoice item charges, etc. It will also show you any discount that is applicable to the c...
3,708
def convert_all(self): for url_record in self._url_table.get_all(): if url_record.status != Status.done: continue self.convert_by_record(url_record)
Convert all links in URL table.
3,709
def upsert_event(self, calendar_id, event): event[] = format_event_time(event[]) event[] = format_event_time(event[]) self.request_handler.post( endpoint= % calendar_id, data=event)
Inserts or updates an event for the specified calendar. :param string calendar_id: ID of calendar to insert/update event into. :param dict event: Dictionary of event data to send to cronofy.
3,710
def generate_passphrase(size=12): chars = string.ascii_lowercase + string.ascii_uppercase + string.digits return str(.join(random.choice(chars) for _ in range(size)))
Return a generate string `size` long based on lowercase, uppercase, and digit chars
3,711
def bound(self, p1, p2=None): r = Rect(p1, p2) return Point(min(max(self.x, r.l), r.r), min(max(self.y, r.t), r.b))
Bound this point within the rect defined by (`p1`, `p2`).
3,712
def s_demand(self, bus): Svl = array([complex(g.p, g.q) for g in self.generators if (g.bus == bus) and g.is_load], dtype=complex64) Sd = complex(bus.p_demand, bus.q_demand) return -sum(Svl) + Sd
Returns the total complex power demand.
3,713
def add_alt(self, entry): entry = entry[7:-1] info = entry.split() if len(info) < 2: return False for v in info: key, value = v.split(, 1) if key == : self.alt[value] = {} id_ = value elif key == : ...
Parse and store the alternative allele field
3,714
def _equal_values(self, val1, val2): if self._is_supported_matrix(val1): if self._is_supported_matrix(val2): _, _, hash_tuple_1 = self._serialize_matrix(val1) _, _, hash_tuple_2 = self._serialize_matrix(val2) return hash(hash_tuple_1) == has...
Matrices are equal if they hash to the same value.
3,715
def simxPackFloats(floatList): if sys.version_info[0] == 3: s=bytes() for i in range(len(floatList)): s=s+struct.pack(,floatList[i]) s=bytearray(s) else: s= for i in range(len(floatList)): s+=struct.pack(,floatList[i]) return s
Please have a look at the function description/documentation in the V-REP user manual
3,716
def open_zip(cls, dbname, zipped, encoding=None, fieldnames_lower=True, case_sensitive=True): with ZipFile(zipped, ) as zip_: if not case_sensitive: dbname = pick_name(dbname, zip_.namelist()) with zip_.open(dbname) as f: yield cls(f, encoding=e...
Context manager. Allows opening a .dbf file from zip archive. .. code-block:: with Dbf.open_zip('some.dbf', 'myarch.zip') as dbf: ... :param str|unicode dbname: .dbf file name :param str|unicode|file zipped: .zip file path or a file-like object. :param st...
3,717
def union(cls): assert isinstance(cls, type) return type(cls.__name__, (cls,), { : True, })
A class decorator which other classes can specify that they can resolve to with `UnionRule`. Annotating a class with @union allows other classes to use a UnionRule() instance to indicate that they can be resolved to this base union class. This class will never be instantiated, and should have no members -- it is...
3,718
def do_find(self, arg): if not arg: raise CmdError("missing parameter: string") process = self.get_process_from_prefix() self.find_in_memory(arg, process)
[~process] f <string> - find the string in the process memory [~process] find <string> - find the string in the process memory
3,719
def write(self, bytes_): string = bytes_.decode(self._encoding) self._file.write(string)
Write bytes to the file.
3,720
def create_stack_user(self): self.run(, success_status=(0, 9)) self.create_file(, ) self.run() self.run() self.run() self.run() self.run() self.ssh_pool.build_ssh_client(self.hostname, , self._key_filename, ...
Create the stack user on the machine.
3,721
def __set_transaction_detail(self, *args, **kwargs): customer_transaction_id = kwargs.get(, None) if customer_transaction_id: transaction_detail = self.client.factory.create() transaction_detail.CustomerTransactionId = customer_transaction_id self.logger.deb...
Checks kwargs for 'customer_transaction_id' and sets it if present.
3,722
def shift_or_mirror_into_invertible_domain(self, solution_genotype, copy=False): assert solution_genotype is not None if copy: y = [val for val in solution_genotype] else: y = solution_genotype if isinstance(...
Details: input ``solution_genotype`` is changed. The domain is [lb - al, ub + au] and in [lb - 2*al - (ub - lb) / 2, lb - al] mirroring is applied.
3,723
def d_step(self, true_frames, gen_frames): hparam_to_disc_loss = { "least_squares": gan_losses.least_squares_discriminator_loss, "cross_entropy": gan_losses.modified_discriminator_loss, "wasserstein": gan_losses.wasserstein_discriminator_loss} _, batch_size, _, _, _ = common_l...
Performs the discriminator step in computing the GAN loss. Applies stop-gradient to the generated frames while computing the discriminator loss to make sure that the gradients are not back-propagated to the generator. This makes sure that only the discriminator is updated. Args: true_frames: Tru...
3,724
def list_documents(self, page_size=None): parent, _ = self._parent_info() iterator = self._client._firestore_api.list_documents( parent, self.id, page_size=page_size, show_missing=True, metadata=self._client._rpc_metadata, ) ...
List all subdocuments of the current collection. Args: page_size (Optional[int]]): The maximum number of documents in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. Returns: Sequence[...
3,725
def clear(self): self.services.clear() self._future_value.clear() self.services = None self._lock = None self._ipopo_instance = None self._context = None self.requirement = None self._key = None self._allow_none = None self._futur...
Cleans up the manager. The manager can't be used after this method has been called
3,726
def is_readable(value, **kwargs): try: validators.readable(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is a readable file. .. caution:: **Use of this validator is an anti-pattern and should be used with caution.** Validating the readability of a file *before* attempting to read it exposes your code to a bug called `TOCTOU <https://en.wikipedia.org/wiki/Time_of_ch...
3,727
def process_action(self, request, queryset): count = 0 try: with transaction.commit_on_success(): for obj in queryset: self.log_action(obj, CMSLog.DELETE) count += 1 obj.delete() msg = "%s object...
Deletes the object(s). Successful deletes are logged. Returns a 'render redirect' to the result of the `get_done_url` method. If a ProtectedError is raised, the `render` method is called with message explaining the error added to the context as `protected`.
3,728
def __set_bp(self, aProcess): lpAddress = self.get_address() dwSize = self.get_size() flNewProtect = aProcess.mquery(lpAddress).Protect flNewProtect = flNewProtect | win32.PAGE_GUARD aProcess.mprotect(lpAddress, dwSize, flNewProtect)
Sets the target pages as guard pages. @type aProcess: L{Process} @param aProcess: Process object.
3,729
def _create_row_labels(self): labels = {} for c in self._columns: labels[c] = c if self._alt_labels: for k in self._alt_labels.keys(): labels[k] = self._alt_labels[k] if self._label_...
Take the original labels for rows. Rename if alternative labels are provided. Append label suffix if label_suffix is True. Returns ---------- labels : dictionary Dictionary, keys are original column name, values are final label.
3,730
def validate_object(obj, field_validators=None, non_field_validators=None, schema=None, context=None): if schema is None: schema = {} if context is None: context = {} if field_validators is None: field_validators = ValidationDict() if non_field_validators...
Takes a mapping and applies a mapping of validator functions to it collecting and reraising any validation errors that occur.
3,731
def _parse_mtllibs(self): for mtllib in self.meta.mtllibs: try: materials = self.material_parser_cls( os.path.join(self.path, mtllib), encoding=self.encoding, strict=self.strict).materials except IOError...
Load mtl files
3,732
def dump(self, filename): try: with open(filename, ) as fp: cPickle.dump(self.counters, fp) except Exception as e: logging.warning("can't dump counter to file %s: %s", filename, e) return False return True
Dump counters to file
3,733
def imresize(self, data, new_wd, new_ht, method=): old_ht, old_wd = data.shape[:2] start_time = time.time() if have_pilutil: means = zoom_x = float(new_wd) / float(old_wd) zoom_y = float(new_ht) / float(old_ht) if (old_wd >= new_wd) or (...
Scale an image in numpy array _data_ to the specified width and height. A smooth scaling is preferred.
3,734
def _landsat_get_mtl(sceneid): scene_params = _landsat_parse_scene_id(sceneid) meta_file = "http://landsat-pds.s3.amazonaws.com/{}_MTL.txt".format( scene_params["key"] ) metadata = str(urlopen(meta_file).read().decode()) return toa_utils._parse_mtl_txt(metadata)
Get Landsat-8 MTL metadata. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. Returns ------- out : dict returns a JSON like object with the metadata.
3,735
def hamming_emd(d1, d2): N = d1.squeeze().ndim d1, d2 = flatten(d1), flatten(d2) return emd(d1, d2, _hamming_matrix(N))
Return the Earth Mover's Distance between two distributions (indexed by state, one dimension per node) using the Hamming distance between states as the transportation cost function. Singleton dimensions are sqeezed out.
3,736
def _on_library_path_changed(self, renderer, path, new_library_path): library_name = self.library_list_store[int(path)][self.KEY_STORAGE_ID] library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True, ...
Callback handling a change of a library path :param Gtk.CellRenderer renderer: Cell renderer showing the library path :param path: Path of library within the list store :param str new_library_path: New library path
3,737
def get_message_actions(current): current.output = {: , : 200, : Message.objects.get( current.input[]).get_actions_for(current.user)}
Returns applicable actions for current user for given message key .. code-block:: python # request: { 'view':'_zops_get_message_actions', 'key': key, } # response: { 'actions':[('name_string', 'cmd_string'),] 'status': str...
3,738
def _get_optimizer(self): optim = tf.train.AdagradOptimizer(self.learning_rate) gradients = optim.compute_gradients(self.cost) if self.log_dir: for name, (g, v) in zip([, , , ], gradients): tf.summary.histogram("{}_grad".format(name), g) tf.su...
Uses Adagrad to optimize the GloVe/Mittens objective, as specified in the GloVe paper.
3,739
def ssn(self): def _checksum(digits): evensum = sum(digits[:-1:2]) oddsum = sum(digits[1::2]) return (10 - ((evensum + oddsum * 3) % 10)) % 10 digits = [7, 5, 6] digits += self.generator.random.sample(range(10), 9) digits.ap...
Returns a 13 digits Swiss SSN named AHV (German) or AVS (French and Italian) See: http://www.bsv.admin.ch/themen/ahv/00011/02185/
3,740
def _validate_sample_rates(input_filepath_list, combine_type): sample_rates = [ file_info.sample_rate(f) for f in input_filepath_list ] if not core.all_equal(sample_rates): raise IOError( "Input files do not have the same sample rate. The {} combine " "type requi...
Check if files in input file list have the same sample rate
3,741
def pca_plot(pca, dt, xlabs=None, mode=, lognorm=True): nc = pca.n_components f = np.arange(pca.n_features_) cs = list(itertools.combinations(range(nc), 2)) ind = ~np.apply_along_axis(any, 1, np.isnan(dt)) cylim = (pca.components_.min(), pca.components_.max()) yd = cylim[1] - cyl...
Plot a fitted PCA, and all components.
3,742
def spill(self, src, dest): if exists(dest) and not isdir(dest): raise Exception("Not a directory: %s" % dest) if isdir(dest): workspace_name = re.sub(r, , basename(src)) new_dest = join(dest, workspace_name) if exists(new_dest...
Spill a workspace, i.e. unpack it and turn it into a workspace. See https://ocr-d.github.com/ocrd_zip#unpacking-ocrd-zip-to-a-workspace Arguments: src (string): Path to OCRD-ZIP dest (string): Path to directory to unpack data folder to
3,743
def create_jinja_env(): template_dir = os.path.join(os.path.dirname(__file__), ) env = jinja2.Environment( loader=jinja2.FileSystemLoader(template_dir), autoescape=jinja2.select_autoescape([]) ) env.filters[] = filter_simple_date env.filters[] = filter_paragraphify return en...
Create a Jinja2 `~jinja2.Environment`. Returns ------- env : `jinja2.Environment` Jinja2 template rendering environment, configured to use templates in ``templates/``.
3,744
def print(self, tag=None, name=None): _name = name if _name is None: _name = fn = streamsx.topology.functions.print_flush if tag is not None: tag = str(tag) + fn = lambda v : streamsx.topology.functions.print_flush(tag + str(v)) sp =...
Prints each tuple to stdout flushing after each tuple. If `tag` is not `None` then each tuple has "tag: " prepended to it before printing. Args: tag: A tag to prepend to each tuple. name(str): Name of the resulting stream. When `None` defaults to a gener...
3,745
def get_tops(self): tops = DefaultOrderedDict(list) include = DefaultOrderedDict(list) done = DefaultOrderedDict(list) found = 0 merging_strategy = self.opts[] if merging_strategy == and not self.opts[]: if not self.opts[]: ...
Gather the top files
3,746
def pretty_dumps(data): try: return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False) except: return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=True)
Return json string in pretty format. **中文文档** 将字典转化成格式化后的字符串。
3,747
def calc_nested_probs(nest_coefs, index_coefs, design, rows_to_obs, rows_to_nests, chosen_row_to_obs=None, return_type="long_probs", *args, **kw...
Parameters ---------- nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of nesting coefficients being used to predict the probabilities ...
3,748
def find_usage(self): logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim in self.limits.values(): lim._reset_usage() try: self._find_delivery_streams() except EndpointConnectionError as ex: logger.w...
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
3,749
def read(self, length): data = bytearray() while len(data) != length: data += self.sock.recv((length - len(data))) if not data: raise ConnectionError() return data
Read as many bytes from socket as specified in length. Loop as long as every byte is read unless exception is raised.
3,750
def get_index(self, index, type, alias=None, typed=None, read_only=True, kwargs=None): if kwargs.tjson != None: Log.error("used `typed` parameter, not `tjson`") if read_only: aliases = wrap(self.get_aliases()) if index in aliases.index: ...
TESTS THAT THE INDEX EXISTS BEFORE RETURNING A HANDLE
3,751
def check(self): for tool in (, , , , , , , ): if not self.pathfinder.exists(tool): raise RuntimeError("Dependency {} is missing".format(tool))
Check if data and third party tools are available :raises: RuntimeError
3,752
def predictor(self, (i, j, A, alpha, Bb)): "Add to chart any rules for B that could help extend this edge." B = Bb[0] if B in self.grammar.rules: for rhs in self.grammar.rewrites_for(B): self.add_edge([j, j, B, [], rhs])
Add to chart any rules for B that could help extend this edge.
3,753
def find(self, path, all=False): matches = [] for prefix, root in self.locations: if root not in searched_locations: searched_locations.append(root) matched_path = self.find_location(root, path, prefix) if matched_path: if not ...
Looks for files in the extra locations as defined in ``MEDIA_FIXTURES_FILES_DIRS``.
3,754
def make_tempfile (self, want=, resolution=, suffix=, **kwargs): if want not in (, ): raise ValueError ( % (want,)) if resolution not in (, , , ): raise ValueError ( % (resolution,)) return Path._PathTempfileContextManager (self, want, resolution, suffix, kwargs)
Get a context manager that creates and cleans up a uniquely-named temporary file with a name similar to this path. This function returns a context manager that creates a secure temporary file with a path similar to *self*. In particular, if ``str(self)`` is something like ``foo/bar``, t...
3,755
def prepare(self): self.scope = 0 self.mapping = deque([0]) self._handler = [i() for i in sorted(self.handlers, key=lambda handler: handler.priority)]
Prepare the ordered list of transformers and reset context state to initial.
3,756
def numpy_to_data_array(ary, *, var_name="data", coords=None, dims=None): default_dims = ["chain", "draw"] ary = np.atleast_2d(ary) n_chains, n_samples, *shape = ary.shape if n_chains > n_samples: warnings.warn( "More chains ({n_chains}) than draws ({n_samples}). " ...
Convert a numpy array to an xarray.DataArray. The first two dimensions will be (chain, draw), and any remaining dimensions will be "shape". If the numpy array is 1d, this dimension is interpreted as draw If the numpy array is 2d, it is interpreted as (chain, draw) If the numpy array is 3 or more di...
3,757
def venv_pth(self, dirs): text = StringIO.StringIO() text.write(" for path in dirs: text.write(.format(path)) put(text, os.path.join(self.site_packages_dir(), ), mode=0664)
Add the directories in `dirs` to the `sys.path`. A venv.pth file will be written in the site-packages dir of this virtualenv to add dirs to sys.path. dirs: a list of directories.
3,758
def command_upgrade(self): if len(self.args) == 1 and self.args[0] == "upgrade": Initialization(False).upgrade(only="") elif (len(self.args) == 2 and self.args[0] == "upgrade" and self.args[1].startswith("--only=")): repos = self.args[1].split("=")[-1].sp...
Recreate repositories package lists
3,759
def def_links(mobj): fdict = json_load(os.path.join("data", "requirements.json")) sdeps = sorted(fdict.keys()) olines = [] for item in sdeps: olines.append( ".. _{name}: {url}\n".format( name=fdict[item]["name"], url=fdict[item]["url"] ) ) ...
Define Sphinx requirements links.
3,760
def export(self, name, columns, points): WHITELIST = + string.ascii_letters + string.digits SUBSTITUTE = def whitelisted(s, whitelist=WHITELIST, substitute=SUBSTITUTE): return .join(c if c in whitelist else substitute for c...
Write the points in MQTT.
3,761
def get_minimum_size(self, data): size = self.element.get_minimum_size(data) if self.angle in (RotateLM.NORMAL, RotateLM.UPSIDE_DOWN): return size else: return datatypes.Point(size.y, size.x)
Returns the rotated minimum size.
3,762
def current(cls): name = socket.getfqdn() ip = socket.gethostbyname(name) return cls(name, ip)
Helper method for getting the current peer of whichever host we're running on.
3,763
def _auth_session(self, username, password): api = self.api[self.account][] endpoint = api.get(, self.api[self.account][]) session = requests.Session() session_retries = Retry(total=10, backoff_factor=0.5) session_adapter = requests.adapters.HTTPAdapter(max_retries=sessi...
Creates session to Hetzner account, authenticates with given credentials and returns the session, if authentication was successful. Otherwise raises error.
3,764
def get_representative_cases(self): return (self.get_declined(decl_utils.Case.nominative, decl_utils.Number.singular), self.get_declined(decl_utils.Case.genitive, decl_utils.Number.singular), self.get_declined(decl_utils.Case.nominative, decl_utils.Number.plural))
>>> armr = OldNorseNoun("armr", decl_utils.Gender.masculine) >>> armr.set_representative_cases("armr", "arms", "armar") >>> armr.get_representative_cases() ('armr', 'arms', 'armar') :return: nominative singular, genetive singular, nominative plural
3,765
def list_config(root_package = ): pkg = __import__(root_package, fromlist=[]) return_dict = OrderedDict() for imp, module, _ in walk_packages(pkg.__path__, root_package + ): m = __import__(module, fromlist = []) for name, v in vars(m).items(): if v is not None and isinstance...
Walk through all the sub modules, find subclasses of vlcp.config.Configurable, list their available configurations through _default_ prefix
3,766
def _apply_role_tree(self, perm_tree, role): role_permissions = role.get_permissions() for perm in role_permissions: self._traverse_tree(perm_tree, perm)[] = True return perm_tree
In permission tree, sets `'checked': True` for the permissions that the role has.
3,767
def smove(self, src, dst, value): src_set = self._get_set(src, ) dst_set = self._get_set(dst, ) value = self._encode(value) if value not in src_set: return False src_set.discard(value) dst_set.add(value) self.redis[self._encode(src)], self.r...
Emulate smove.
3,768
def _check_for_api_errors(geocoding_results): status_result = geocoding_results.get("STATUS", {}) if "NO_RESULTS" in status_result.get("status", ""): return api_call_success = status_result.get("status", "") == "SUCCESS" if not api_call_success: access_er...
Raise any exceptions if there were problems reported in the api response.
3,769
def check_list_type(objects, allowed_type, name, allow_none=True): if objects is None: if not allow_none: raise TypeError( % name) return objects if not isinstance(objects, (tuple, list)): raise TypeError( % name) if not all(isinstance(i, allowed_type) for i in objects): type_list = sorte...
Verify that objects in list are of the allowed type or raise TypeError. Args: objects: The list of objects to check. allowed_type: The allowed type of items in 'settings'. name: Name of the list of objects, added to the exception. allow_none: If set, None is also allowed. Raises: TypeError: if...
3,770
def register(cls): registry_entry = RegistryEntry(category = cls.category, namespace = cls.namespace, name = cls.name, cls=cls) if registry_entry not in registry and not exists_in_registry(cls.category, cls.namespace, cls.name): registry.append(registry_entry) else: log.warn("Class {0} ...
Register a given model in the registry
3,771
def addAsn1MibSource(self, *asn1Sources, **kwargs): if self._asn1SourcesToAdd is None: self._asn1SourcesToAdd = asn1Sources else: self._asn1SourcesToAdd += asn1Sources if self._asn1SourcesOptions: self._asn1SourcesOptions.update(kwargs) els...
Adds path to a repository to search ASN.1 MIB files. Parameters ---------- *asn1Sources : one or more URL in form of :py:obj:`str` identifying local or remote ASN.1 MIB repositories. Path must include the *@mib@* component which will be replaced with MIB modu...
3,772
def load(self): cl_tmp = self.api.list(self.objName, limit=self.searchLimit).values() cl = [] for i in cl_tmp: cl.extend(i) return {x[self.index]: ItemPuppetClass(self.api, x[], self.objName, self.payloadObj, ...
Function load Get the list of all objects @return RETURN: A ForemanItem list
3,773
def _generate_request_handler_proxy(handler_class, handler_args, name): @scope.inject def request_handler_wrapper(app, handler, **kwargs): handler = handler_class(app, handler.request, **handler_args) handler._execute([], **kwargs) request_handler_wrapper.__name__ = name request_ha...
When a tornado.web.RequestHandler gets mounted we create a launcher function
3,774
def _prepare_sets(self, sets): if self.stored_key and not self.stored_key_exists(): raise DoesNotExist( ) conn = self.cls.get_connection() all_sets = set() tmp_keys = set() lists = [] def add_key(key, key_type=None, ...
The original "_prepare_sets" method simple return the list of sets in _lazy_collection, know to be all keys of redis sets. As the new "intersect" method can accept different types of "set", we have to handle them because we must return only keys of redis sets.
3,775
def _lcs(x, y): n, m = len(x), len(y) table = {} for i in range(n + 1): for j in range(m + 1): if i == 0 or j == 0: table[i, j] = 0 elif x[i - 1] == y[j - 1]: table[i, j] = table[i - 1, j - 1] + 1 else: table[i, j] = max(table[i - 1, j], table[i, j - 1]) return t...
Computes the length of the LCS between two seqs. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of words Returns: ...
3,776
def values(self, with_defaults=True): return dict(((k, str(v)) for k, v in self._inputs.items() if not v.is_empty(with_defaults)))
Return the values dictionary, defaulting to default values
3,777
def _generate(self, pset, min_, max_, condition, type_=None): if type_ is None: type_ = pset.ret expr = [] height = np.random.randint(min_, max_) stack = [(0, type_)] while len(stack) != 0: depth, type_ = stack.pop() ...
Generate a Tree as a list of lists. The tree is build from the root to the leaves, and it stop growing when the condition is fulfilled. Parameters ---------- pset: PrimitiveSetTyped Primitive set from which primitives are selected. min_: int Mini...
3,778
def magnitude(self): return math.sqrt( self.x * self.x + self.y * self.y )
Return the magnitude when treating the point as a vector.
3,779
def search_end_date(self, search_end_date): assert isinstance(search_end_date, Time) self._search_end_date = search_end_date.replicate(format=) self._search_end_date.out_subfmt =
:type search_end_date: astropy.io.Time :param search_end_date: search for frames take after the given date.
3,780
def parse_enum_value_definition(lexer: Lexer) -> EnumValueDefinitionNode: start = lexer.token description = parse_description(lexer) name = parse_name(lexer) directives = parse_directives(lexer, True) return EnumValueDefinitionNode( description=description, name=name, directives=directi...
EnumValueDefinition: Description? EnumValue Directives[Const]?
3,781
def calculate_size(name, thread_id): data_size = 0 data_size += calculate_size_str(name) data_size += LONG_SIZE_IN_BYTES return data_size
Calculates the request payload size
3,782
def filter_files_extensions(files, extension_lists): log.debug(.format(files)) result = [[] for _ in extension_lists] for file in files: ext = file.suffix[1:].lower() for ext_i, ext_list in enumerate(extension_lists): if ext in ext_list: result[ext_i].append(...
Put the files in buckets according to extension_lists files=[movie.avi, movie.srt], extension_lists=[[avi],[srt]] ==> [[movie.avi],[movie.srt]] :param files: A list of files :param extension_lists: A list of list of extensions :return: The files filtered and sorted according to extension_lists
3,783
def woodbury_vector(self): if self._woodbury_vector is None: self._woodbury_vector, _ = dpotrs(self.K_chol, self.mean - self._prior_mean) return self._woodbury_vector
Woodbury vector in the gaussian likelihood case only is defined as $$ (K_{xx} + \Sigma)^{-1}Y \Sigma := \texttt{Likelihood.variance / Approximate likelihood covariance} $$
3,784
def create_table(self, table, fields): table = table.get_soap_object(self.client) return self.call(, table, fields)
Responsys.createTable call Accepts: InteractObject table list fields Returns True on success
3,785
def _reducedProtToPeps(protToPeps, proteins): return {k: v for k, v in viewitems(protToPeps) if k not in proteins}
Returns a new, reduced "protToPeps" dictionary that does not contain entries present in "proteins". :param protToPeps: dict, for each protein (=key) contains a set of associated peptides (=value). For Example {protein: {peptide, ...}, ...} :param proteins: a list of proteinSet :returns: dict, p...
3,786
def emit(self, record): if getattr(this, , {}).get(LOGS_NAME, False): self.format(record) this.send({ : ADDED, : LOGS_NAME, : meteor_random_id( % LOGS_NAME), : { attr: { ...
Emit a formatted log record via DDP.
3,787
def weighted_round_robin(iterable): cyclable_list = [] assigned_weight = 0 still_to_process = [ (item, weight) for item, weight in sorted(iterable, key=lambda tup: tup[1], reverse=True)] while still_to_process: for i, (item, weight) in enumerate(still_to_process): ...
Takes an iterable of tuples of <item>, <weight> and cycles around them, returning heavier (integer) weighted items more frequently.
3,788
def standings(self, league_table, league): headers = [, , , , , , ] result = [headers] result.extend([team[], team[][], team[], team[], team[], team[], ...
Store output of league standings to a CSV file
3,789
def run_initial(self, events): self_name = type(self).__name__ for i, batch in enumerate(grouper(events, self.INITIAL_BATCH_SIZE, skip_missing=True), 1): self.logger.debug(, self_name, i) for j, processed_batch in enumerate(grouper( batch, self.BATCH...
Runs the initial batch upload :param events: an iterable containing events
3,790
def set_pdb_trace(pm=False): import sys import pdb for attr in ("stdin", "stdout", "stderr"): setattr(sys, attr, getattr(sys, "__%s__" % attr)) if pm: pdb.post_mortem() else: pdb.set_trace()
Start the Python debugger when robotframework is running. This makes sure that pdb can use stdin/stdout even though robotframework has redirected I/O.
3,791
def combineReads(filename, sequences, readClass=DNARead, upperCase=False, idPrefix=): if filename: reads = FastaReads(filename, readClass=readClass, upperCase=upperCase) else: reads = Reads() if sequences: for count, sequence in enumerate(sequences, s...
Combine FASTA reads from a file and/or sequence strings. @param filename: A C{str} file name containing FASTA reads. @param sequences: A C{list} of C{str} sequences. If a sequence contains spaces, the last field (after splitting on spaces) will be used as the sequence and the first fields will ...
3,792
async def _play(self, ctx, *, query: str): player = self.bot.lavalink.players.get(ctx.guild.id) query = query.strip() if not url_rx.match(query): query = f tracks = await self.bot.lavalink.get_tracks(query) if not tracks: return aw...
Searches and plays a song from a given query.
3,793
def list_of_vars(arg_plot): lovs = [[[var for var in svars.split() if var] for svars in pvars.split() if svars] for pvars in arg_plot.split() if pvars] lovs = [[slov for slov in lov if slov] for lov in lovs if lov] return [lov for lov in lovs if lov]
Construct list of variables per plot. Args: arg_plot (str): string with variable names separated with ``_`` (figures), ``.`` (subplots) and ``,`` (same subplot). Returns: three nested lists of str - variables on the same subplot; - subplots on the same figure; ...
3,794
def generate_markdown(cls): lines = [] if cls.__doc__: lines.extend([.format(cls.__doc__), ]) for k, v in cls._values.items(): lines.append(.format(k)) if v.required: lines[-1] = lines[-1] + if v.help: line...
Documents values in markdown
3,795
def is_auto_partition_required(self, brain_or_object): obj = api.get_object(brain_or_object) if not IAnalysisRequest.providedBy(obj): return False template = obj.getTemplate() return template and template.getAutoPartition()
Returns whether the passed in object needs to be partitioned
3,796
def AddWeight(self, path_segment_index, weight): if path_segment_index not in self._weight_per_index: raise ValueError() self._weight_per_index[path_segment_index] += weight if weight not in self._indexes_per_weight: self._indexes_per_weight[weight] = [] self._indexes_per_weight[weig...
Adds a weight for a specific path segment index. Args: path_segment_index: an integer containing the path segment index. weight: an integer containing the weight. Raises: ValueError: if the path segment weights do not contain the path segment index.
3,797
def snapshot_created(name, ami_name, instance_name, wait_until_available=True, wait_timeout_seconds=300, **kwargs): ret = {: name, : True, : , : {} } if not __salt__[](ami_name=ami_name, instance_name=instance_name, **kwargs): ret[] = .format(ami_name=am...
Create a snapshot from the given instance .. versionadded:: 2016.3.0
3,798
def get_arg_parser(cls, settings = None, option_prefix = u, add_help = False): parser = argparse.ArgumentParser(add_help = add_help, prefix_chars = option_prefix[0]) if settings is N...
Make a command-line option parser. The returned parser may be used as a parent parser for application argument parser. :Parameters: - `settings`: list of PyXMPP2 settings to consider. By default all 'basic' settings are provided. - `option_prefix`: custom ...
3,799
def recall_score(y_true, y_pred, average=, suffix=False): true_entities = set(get_entities(y_true, suffix)) pred_entities = set(get_entities(y_pred, suffix)) nb_correct = len(true_entities & pred_entities) nb_true = len(true_entities) score = nb_correct / nb_true if nb_true > 0 else 0 re...
Compute the recall. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The best value is 1 and the worst value is 0. Args: ...