Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
364,500
def _set_link_oam(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=link_oam.link_oam, is_container=, presence=True, yang_name="link-oam", rest_name="link-oam", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True...
Setter method for link_oam, mapped from YANG variable /protocol/link_oam (container) If this variable is read-only (config: false) in the source YANG file, then _set_link_oam is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_link_oam() di...
364,501
def counts(args): p = OptionParser(counts.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) vcffile, = args vcf_reader = vcf.Reader(open(vcffile)) for r in vcf_reader: v = CPRA(r) if not v.is_valid: continue ...
%prog counts vcffile Collect allele counts from RO and AO fields.
364,502
def parseHolidays(holidaysStr, holidayMap=None): if holidayMap is None: holidayMap = _HOLIDAY_MAP retval = holidays.HolidayBase() retval.country = None holidaysStr = holidaysStr.strip() for (country, subdivisions) in HolsRe.findall(holidaysStr): cls = holidayMap.get(country) ...
Takes a string like NZ[WTL,Nelson],AU[*],Northern Ireland and builds a HolidaySum from it
364,503
def decode_param(data): logger.debug(, data) header_len = struct.calcsize() partype, parlen = struct.unpack(, data[:header_len]) pardata = data[header_len:parlen] logger.debug(, pardata) ret = { : partype, } if partype == 1023: vsfmt = vendor, subtype = s...
Decode any parameter to a byte sequence. :param data: byte sequence representing an LLRP parameter. :returns dict, bytes: where dict is {'Type': <decoded type>, 'Data': <decoded data>} and bytes is the remaining bytes trailing the bytes we could decode.
364,504
def varintSize(value): if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return 4 if value <= 0x7ffffffff: return 5 if value <= 0x3ffffffffff: return 6 if value <= 0x1ffffffffffff: return 7 if value <= 0xffffffffffffff: return 8 if value <...
Compute the size of a varint value.
364,505
def dbmax50years(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) self._dbmax50years = value
Corresponds to IDD Field `dbmax50years` 50-year return period values for maximum extreme dry-bulb temperature Args: value (float): value for IDD Field `dbmax50years` Unit: C if `value` is None it will not be checked against the specification a...
364,506
async def stop(self): if self.__container: for track, context in self.__tracks.items(): if context.task is not None: context.task.cancel() context.task = None for packet in context.stream.encode(None): ...
Stop recording.
364,507
def serve(self, host=, port=5000): from meinheld import server, middleware server.listen((host, port)) server.run(middleware.WebSocketMiddleware(self.app))
Serve predictions as an API endpoint.
364,508
def p_bexpr_func(p): args = make_arg_list(make_argument(p[2], p.lineno(2))) p[0] = make_call(p[1], p.lineno(1), args) if p[0] is None: return if p[0].token in (, , ): entry = SYMBOL_TABLE.access_call(p[1], p.lineno(1)) entry.accessed = True return ...
bexpr : ID bexpr
364,509
def list_user_logins_users(self, user_id): path = {} data = {} params = {} path["user_id"] = user_id self.logger.debug("GET /api/v1/users/{user_id}/logins with query params: {params} and form data: {data}".format(params=params, data=data, **p...
List user logins. Given a user ID, return that user's logins for the given account.
364,510
def single(self, predicate=None): if self.closed(): raise ValueError("Attempt to call single() on a closed Queryable.") return self._single() if predicate is None else self._single_predicate(predicate)
The only element (which satisfies a condition). If the predicate is omitted or is None this query returns the only element in the sequence; otherwise, it returns the only element in the sequence for which the predicate evaluates to True. Exceptions are raised if there is either no such ...
364,511
def _embedding_classical_mds(matrix, dimensions=3, additive_correct=False): if additive_correct: dbc = double_centre(_additive_correct(matrix)) else: dbc = double_centre(matrix) decomp = eigen(dbc) lambda_ = np.diag(np.sqrt(np.abs(decomp.vals[:dimensions]))) evecs = decomp.vecs[...
Private method to calculate CMDS embedding :param dimensions: (int) :return: coordinate matrix (np.array)
364,512
def create_or_update_tags(self, tags): params = {} for i, tag in enumerate(tags): tag.build_params(params, i+1) return self.get_status(, params, verb=)
Creates new tags or updates existing tags for an Auto Scaling group. :type tags: List of :class:`boto.ec2.autoscale.tag.Tag` :param tags: The new or updated tags.
364,513
def GetLinkedFileEntry(self): link = self._GetLink() if not link: return None link_identifier = None parent_path_spec = getattr(self.path_spec, , None) path_spec = apfs_path_spec.APFSPathSpec( location=link, parent=parent_path_spec) is_root = bool( link == self...
Retrieves the linked file entry, e.g. for a symbolic link. Returns: APFSFileEntry: linked file entry or None if not available.
364,514
def group(self): split_count = self._url.lower().find("/content/") len_count = len() gURL = self._url[:self._url.lower().find("/content/")] + \ "/community/" + self._url[split_count+ len_count:] return CommunityGroup(url=gURL, securityH...
returns the community.Group class for the current group
364,515
def _handle_force_timeout(self) -> None: while True: try: ret, num_handles = self._multi.socket_all() except pycurl.error as e: ret = e.args[0] if ret != pycurl.E_CALL_MULTI_PERFORM: break self._finish_pending_r...
Called by IOLoop periodically to ask libcurl to process any events it may have forgotten about.
364,516
def add_new(self, command): self.queue[self.next_key] = command self.queue[self.next_key][] = self.queue[self.next_key][] = self.queue[self.next_key][] = self.queue[self.next_key][] = self.queue[self.next_key][] = self.queue[self.next_key][] = ...
Add a new entry to the queue.
364,517
def calc_requiredrelease_v2(self): con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess flu.requiredrelease = con.neardischargeminimumthreshold[ der.toy[self.idx_sim]]
Calculate the water release (immediately downstream) required for reducing drought events. Required control parameter: |NearDischargeMinimumThreshold| Required derived parameter: |dam_derived.TOY| Calculated flux sequence: |RequiredRelease| Basic equation: :math:`Required...
364,518
def register_options(cls, register): super(JvmResolverBase, cls).register_options(register) register(, type=bool, default=False, help= )
Register an option to make capturing snapshots optional. This class is intended to be extended by Jvm resolvers (coursier and ivy), and the option name should reflect that.
364,519
def remove_link_type_vlan(enode, name, shell=None): assert name if name not in enode.ports: raise ValueError(t existsip link del link dev {name}Cannot remove virtual link {name}'.format(name=name) del enode.ports[name]
Delete a virtual link. Deletes a vlan device with the name {name}. Will raise an expection if the port is not already present. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str name: specifies the name of the new virtual device. :param...
364,520
def aggregate_cap_val(self, conn, **kwargs): pv_pwrwind_pwr region = kwargs[] [pv_df, wind_df, cap] = self.get_timeseries( conn, geometry=region.geom, **kwargs) if kwargs.get(, False): self.store_full_df(pv_df, wind_df, **kwargs) ...
Returns the normalised feedin profile and installed capacity for a given region. Parameters ---------- region : Region instance region.geom : shapely.geometry object Geo-spatial data with information for location/region-shape. The geometry can be a polygo...
364,521
def add_child(self, node, as_last=True): if not isinstance(node, Tree): self.log_exc(u"node is not an instance of Tree", None, True, TypeError) if as_last: self.__children.append(node) else: self.__children = [node] + self.__children node.__pa...
Add the given child to the current list of children. The new child is appended as the last child if ``as_last`` is ``True``, or as the first child if ``as_last`` is ``False``. This call updates the ``__parent`` and ``__level`` fields of ``node``. :param node: the child node to be adde...
364,522
def create_data_and_metadata_io_handler(self, io_handler_delegate): class DelegateIOHandler(ImportExportManager.ImportExportHandler): def __init__(self): super().__init__(io_handler_delegate.io_handler_id, io_handler_delegate.io_handler_name, io_handler_delegate.io_handler_e...
Create an I/O handler that reads and writes a single data_and_metadata. :param io_handler_delegate: A delegate object :py:class:`DataAndMetadataIOHandlerInterface` .. versionadded:: 1.0 Scriptable: No
364,523
def process_refs_for_node(cls, manifest, current_project, node): target_model = None target_model_name = None target_model_package = None for ref in node.refs: if len(ref) == 1: target_model_name = ref[0] elif len(ref) == 2: ...
Given a manifest and a node in that manifest, process its refs
364,524
def neg_loglik(self,beta): mu, Y = self._model(beta) if self.use_ols_covariance is False: cm = self.custom_covariance(beta) else: cm = self.ols_covariance() diff = Y.T - mu.T ll1 = -(mu.T.shape[0]*mu.T.shape[1]/2.0)*np.log(2.0*np.pi) - (m...
Creates the negative log-likelihood of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- The negative logliklihood of the model
364,525
def mkFilter(parts): if parts is None: parts = [BasicServiceEndpoint] try: parts = list(parts) except TypeError: return mkCompoundFilter([parts]) else: return mkCompoundFilter(parts)
Convert a filter-convertable thing into a filter @param parts: a filter, an endpoint, a callable, or a list of any of these.
364,526
def forward(self, observations): input_data = self.input_block(observations) advantage_features, value_features = self.backbone(input_data) log_histogram = self.q_head(advantage_features, value_features) return log_histogram
Model forward pass
364,527
def unsign(self, signed_value): signed_value = want_bytes(signed_value) sep = want_bytes(self.sep) if sep not in signed_value: raise BadSignature( % self.sep) value, sig = signed_value.rsplit(sep, 1) if self.verify_signature(value, sig): return va...
Unsigns the given string.
364,528
def chain(request): bars = foobar_models.Bar.objects.all() bazs = foobar_models.Baz.objects.all() qsc = XmlQuerySetChain(bars, bazs) return HttpResponse(tree.xml(qsc), mimetype=)
shows how the XmlQuerySetChain can be used instead of @toxml decorator
364,529
def _is_known_signed_by_dtype(dt): return { tf.float16: True, tf.float32: True, tf.float64: True, tf.int8: True, tf.int16: True, tf.int32: True, tf.int64: True, }.get(dt.base_dtype, False)
Helper returning True if dtype is known to be signed.
364,530
def start_output (self): if self.logparts is None: parts = Fields.keys() else: parts = self.logparts values = (self.part(x) for x in parts) self.max_indent = max(len(x) for x in values)+1 for key in parts: numspaces =...
Start log output.
364,531
def reverse_cyk_transforms(root): root = InverseContextFree.transform_from_chomsky_normal_form(root) root = InverseContextFree.unit_rules_restore(root) root = InverseContextFree.epsilon_rules_restore(root) return root
Reverse transformation made to grammar before CYK. Performs following steps: - transform from chomsky normal form - restore unit rules - restore epsilon rules :param root: Root node of the parsed tree. :return: Restored parsed tree.
364,532
def filter_users_by_email(email): from .models import EmailAddress User = get_user_model() mails = EmailAddress.objects.filter(email__iexact=email) users = [e.user for e in mails.prefetch_related()] if app_settings.USER_MODEL_EMAIL_FIELD: q_dict = {app_settings.USER_MODEL_EMAIL_FIELD + ...
Return list of users by email address Typically one, at most just a few in length. First we look through EmailAddress table, than customisable User model table. Add results together avoiding SQL joins and deduplicate.
364,533
def make_example_scripts_docs(spth, npth, rpth): mkdir(rpth) for fp in glob(os.path.join(spth, )) + \ glob(os.path.join(spth, , )): b = os.path.basename(fp) dn = os.path.dirname(fp) sd = os.path.split(dn) if dn ==...
Generate rst docs from example scripts. Arguments `spth`, `npth`, and `rpth` are the top-level scripts directory, the top-level notebooks directory, and the top-level output directory within the docs respectively.
364,534
def copy(self, name=None): if name is None: return Attribute( javabridge.call(self.jobject, "copy", "()Ljava/lang/Object;")) else: return Attribute( javabridge.call(self.jobject, "copy", "(Ljava/lang/String;)Lweka/core/Attribute;", name))
Creates a copy of this attribute. :param name: the new name, uses the old one if None :type name: str :return: the copy of the attribute :rtype: Attribute
364,535
def generate_gallery_rst(app): try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) gallery_conf.update(app.config.sphinx_gallery_conf) gallery_conf.update(plot_gallery=plot_gallery) gallery_conf.update...
Generate the Main examples gallery reStructuredText Start the sphinx-gallery configuration and recursively scan the examples directories in order to populate the examples gallery
364,536
def _normalize_tags_type(self, tags, device_name=None, metric_name=None): normalized_tags = [] if device_name: self._log_deprecation("device_name") device_tag = self._to_bytes("device:{}".format(device_name)) if device_tag is None: self.log.w...
Normalize tags contents and type: - append `device_name` as `device:` tag - normalize tags type - doesn't mutate the passed list, returns a new list
364,537
def qsub(command, queue=None, cwd=True, name=None, deps=[], stdout=, stderr=, env=[], array=None, context=, hostname=None, memfree=None, hvmem=None, gpumem=None, pe_opt=None, io_big=False): scmd = [] import six if isinstance(queue, six.string_types) and queue not in (, ): scmd += [, queue] if ...
Submits a shell job to a given grid queue Keyword parameters: command The command to be submitted to the grid queue A valid queue name or None, to use the default queue cwd If the job should change to the current working directory before starting name An optional name to set for the job. ...
364,538
def instance_cache(cls, func): @functools.wraps(func) def func_wrapper(*args, **kwargs): if not args: raise ValueError() else: the_self = args[0] func_key = cls.get_key(func) val_cache = cls.get_self_cache(the_self...
Save the cache to `self` This decorator take it for granted that the decorated function is a method. The first argument of the function is `self`. :param func: function to decorate :return: the decorator
364,539
def __draw_leaf_density(self): leafs = self.__directory.get_leafs() density_scale = leafs[-1].get_density() if density_scale == 0.0: density_scale = 1.0 for block in leafs: alpha = 0.8 * block.get_density() / density_scale self.__draw_block(blo...
! @brief Display densities by filling blocks by appropriate colors.
364,540
def smooth(y, radius, mode=, valid_only=False): twosidedcausal assert mode in (, ) if len(y) < 2*radius+1: return np.ones_like(y) * y.mean() elif mode == : convkernel = np.ones(2 * radius+1) out = np.convolve(y, convkernel,mode=) / np.convolve(np.ones_like(y), convkernel, mode=) ...
Smooth signal y, where radius is determines the size of the window mode='twosided': average over the window [max(index - radius, 0), min(index + radius, len(y)-1)] mode='causal': average over the window [max(index - radius, 0), index] valid_only: put nan in entries where the full-sized win...
364,541
def _to_dict(self): _dict = {} if hasattr(self, ) and self.expansions is not None: _dict[] = [x._to_dict() for x in self.expansions] return _dict
Return a json dictionary representing this model.
364,542
def url_as_file(url, ext=None): if ext: ext = + ext.strip() url_hint = .format(urlparse(url).hostname or ) if url.startswith(): url = os.path.abspath(url[len():]) if os.path.isabs(url): with open(url, ) as handle: content = handle.read() else: con...
Context manager that GETs a given `url` and provides it as a local file. The file is in a closed state upon entering the context, and removed when leaving it, if still there. To give the file name a specific extension, use `ext`; the extension can optionally include a separating dot, ...
364,543
def add_style(self, name, fg=None, bg=None, options=None): style = Style(name) if fg is not None: style.fg(fg) if bg is not None: style.bg(bg) if options is not None: if "bold" in options: style.bold() if "underl...
Adds a new style
364,544
def get_series(self, key): url = make_series_url(key) resp = self.session.get(url) return resp
Get a series object from TempoDB given its key. :param string key: a string name for the series :rtype: :class:`tempodb.response.Response` with a :class:`tempodb.protocol.objects.Series` data payload
364,545
def filter_nremoved(self, filt=True, quiet=False): rminfo = {} for n in self.subsets[]: s = self.data[n] rminfo[n] = s.filt_nremoved(filt) if not quiet: maxL = max([len(s) for s in rminfo.keys()]) print(.format(string=, number=maxL + 3) + ...
Report how many data are removed by the active filters.
364,546
def get_vertices(self, indexed=None): if indexed is None: if (self._vertices is None and self._vertices_indexed_by_faces is not None): self._compute_unindexed_vertices() return self._vertices elif indexed == : if (self._ver...
Get the vertices Parameters ---------- indexed : str | None If Note, return an array (N,3) of the positions of vertices in the mesh. By default, each unique vertex appears only once. If indexed is 'faces', then the array will instead contain three ...
364,547
def parse_ACCT(chunk, encryption_key): io = BytesIO(chunk.payload) id = read_item(io) name = decode_aes256_plain_auto(read_item(io), encryption_key) group = decode_aes256_plain_auto(read_item(io), encryption_key) url = decode_hex(read_item(io)) notes = decode_aes256_plain_auto(read_it...
Parses an account chunk, decrypts and creates an Account object. May return nil when the chunk does not represent an account. All secure notes are ACCTs but not all of them strore account information.
364,548
def p_localparamdecl_integer(self, p): paramlist = [Localparam(rname, rvalue, lineno=p.lineno(3)) for rname, rvalue in p[3]] p[0] = Decl(tuple(paramlist), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
localparamdecl : LOCALPARAM INTEGER param_substitution_list SEMICOLON
364,549
def _lexsorted_specs(self, order): specs = self.specs[:] if not all(el[0] in [, ] for el in order): raise Exception("Please specify the keys for sorting, use" " prefix for ascending," " for descending.)") sort_cycles =...
A lexsort is specified using normal key string prefixed by '+' (for ascending) or '-' for (for descending). Note that in Python 2, if a key is missing, None is returned (smallest Python value). In Python 3, an Exception will be raised regarding comparison of heterogenous types.
364,550
def human_or_01(X, y, model_generator, method_name): return _human_or(X, model_generator, method_name, False, True)
OR (false/true) This tests how well a feature attribution method agrees with human intuition for an OR operation combined with linear effects. This metric deals specifically with the question of credit allocation for the following function when all three inputs are true: if fever: +2 points if ...
364,551
def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq, membship, num_dissim, cat_dissim, gamma, random_state): moves = 0 for ipoint in range(Xnum.shape[0]): clust = np.argmin( num_dissim(centroids[0], Xnum[ipoint]) + gamm...
Single iteration of the k-prototypes algorithm
364,552
def load_files(filenames,multiproc=False,**kwargs): filenames = np.atleast_1d(filenames) logger.debug("Loading %s files..."%len(filenames)) kwargs = [dict(filename=f,**kwargs) for f in filenames] if multiproc: from multiprocessing import Pool processes = multiproc if multiproc > 0...
Load a set of FITS files with kwargs.
364,553
def _image_data(self, normalize=False, min_depth=MIN_DEPTH, max_depth=MAX_DEPTH, twobyte=False): max_val = BINARY_IM_MAX_VAL if twobyte: max_val = np.iinfo(np.uint16).max if normalize: min_depth...
Returns the data in image format, with scaling and conversion to uint8 types. Parameters ---------- normalize : bool whether or not to normalize by the min and max depth of the image min_depth : float minimum depth value for the normalization max_depth : ...
364,554
def validate(node, source): lf = LanguageFence(source, strict=False) lf.visit(node) return node
Call this function to validate an AST.
364,555
def create_new_version( self, name, subject, text=, template_id=None, html=None, locale=None, timeout=None ): if(html): payload = { : name, : subject, : html, ...
API call to create a new version of a template
364,556
def get_options_from_file(self, file_path): with open(file_path) as options_file: options_dict = json.load(options_file) options = [] for opt_name in options_dict: options.append(opt_name) options.append(options_dict[opt_name]) return...
Return the options parsed from a JSON file.
364,557
def main(*kw): parser = create_parser() args = parser.parse_args(kw if kw else None) if args.help: parser.print_help() elif args.usage: print() elif args.version: print("formic", get_version()) elif args.license: print(resource_string(__name__, "LICENSE.txt"...
Command line entry point; arguments must match those defined in in :meth:`create_parser()`; returns 0 for success, else 1. Example:: command.main("-i", "**/*.py", "--no-default-excludes") Runs formic printing out all .py files in the current working directory and its children to ``sys.stdout``....
364,558
def canonicalize_half_turns( half_turns: Union[sympy.Basic, float] ) -> Union[sympy.Basic, float]: if isinstance(half_turns, sympy.Basic): return half_turns half_turns %= 2 if half_turns > 1: half_turns -= 2 return half_turns
Wraps the input into the range (-1, +1].
364,559
def _compute_acq(self,x): means, stds = self.model.predict(x) f_acqu = 0 for m,s in zip(means, stds): f_acqu += -m + self.exploration_weight * s return f_acqu/(len(means))
Integrated GP-Lower Confidence Bound
364,560
def plot_sources(topo, mixmaps, unmixmaps, global_scale=None, fig=None): urange, mrange = None, None m = len(mixmaps) if global_scale: tmp = np.asarray(unmixmaps) tmp = tmp[np.logical_not(np.isnan(tmp))] umax = np.percentile(np.abs(tmp), global_scale) umin = -umax ...
Plot all scalp projections of mixing- and unmixing-maps. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- topo : :class:`~eegtopo.topoplot.Topoplot` This object draws the topo plot mixmaps : array, shape = [...
364,561
def gb(args): from Bio.Alphabet import generic_dna try: from BCBio import GFF except ImportError: print("You need to install dep first: $ easy_install bcbio-gff", file=sys.stderr) p = OptionParser(gb.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.e...
%prog gb gffile fastafile Convert GFF3 to Genbank format. Recipe taken from: <http://www.biostars.org/p/2492/>
364,562
def to_string(self): fmt = first = struct.pack( fmt, self._mode, self._cr_timeout, self._auto_eject_time ) return first
Return the current DEVICE_CONFIG as a string (always 4 bytes).
364,563
def pip_uninstall(package, **options): command = ["uninstall", "-q", "-y"] available_options = (, , ) for option in parse_options(options, available_options): command.append(option) if isinstance(package, list): command.extend(package) else: command.append(package) ...
Uninstall a python package
364,564
def update_system(version=, ruby=None, runas=None, gem_bin=None): * return _gem([, , version], ruby, gem_bin=gem_bin, runas=runas)
Update rubygems. :param version: string : (newest) The version of rubygems to install. :param gem_bin: string : None Full path to ``gem`` binary to use. :param ruby: string : None If RVM or rbenv are installed, the ruby version and gemset to use. Ignored if ``gem_bin`` is sp...
364,565
def inq_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, num_bits=4, inq_iterations=(), selection_algorithm=, seed=-1, w_init=None, i_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, ...
Incremental Network Quantization Convolution Layer During training, the weights are sequentially quantized to power-of-two values, which allows the training of a multiplierless network. Using `inq_iterations`, one can specify after how many forward passes half of the learnable weights are fixed and qu...
364,566
def blog_authors(*args): blog_posts = BlogPost.objects.published() authors = User.objects.filter(blogposts__in=blog_posts) return list(authors.annotate(post_count=Count("blogposts")))
Put a list of authors (users) for blog posts into the template context.
364,567
def remove(ctx, client, sources): from renku.api._git import _expand_directories def fmt_path(path): return str(Path(path).absolute().relative_to(client.path)) files = { fmt_path(source): fmt_path(file_or_dir) for file_or_dir in sources for source in _expand_d...
Remove files and check repository for potential problems.
364,568
def imshow(self, *args, show_crosshair=True, show_mask=True, show_qscale=True, axes=None, invalid_color=, mask_opacity=0.8, show_colorbar=True, **kwargs): if not in kwargs: kwargs[] = if not in kwargs: kwargs[] = if not in kwarg...
Plot the matrix (imshow) Keyword arguments [and their default values]: show_crosshair [True]: if a cross-hair marking the beam position is to be plotted. show_mask [True]: if the mask is to be plotted. show_qscale [True]: if the horizontal and vertical axes are to be ...
364,569
def set_global_defaults(**kwargs): valid_options = [ , , , , , , , , , , , , , , , , , , , , , , , , , , ] for kw in kwargs: if kw in valid_options: _default_options[kw] = kwargs[kw] else: erro...
Set global defaults for the options passed to the icon painter.
364,570
def _parse_udevadm_info(udev_info): devices = [] dev = {} for line in (line.strip() for line in udev_info.splitlines()): if line: line = line.split(, 1) if len(line) != 2: continue query, data = line if query == : ...
Parse the info returned by udevadm command.
364,571
def info_hash(self): info = self._struct.get() if not info: return None return sha1(Bencode.encode(info)).hexdigest()
Hash of torrent file info section. Also known as torrent hash.
364,572
def parse_cluster(self, global_params, region, cluster): vpc_id = cluster.pop() if in cluster else ec2_classic manage_dictionary(self.vpcs, vpc_id, VPCConfig(self.vpc_resource_types)) name = cluster.pop() cluster[] = name self.vpcs[vpc_id].clusters[name] = cluster
Parse a single Redshift cluster :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param cluster: Cluster
364,573
def clean_csvs(dialogpath=None): dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath) for filename in filenames: filepath = os.path.join(dialogdir, filename) ...
Translate non-ASCII characters to spaces or equivalent ASCII characters
364,574
def group_files_by_size(fileslist, multi): flord = OrderedDict(sorted(fileslist.items(), key=lambda x: x[1], reverse=True)) if multi <= 1: fgrouped = {} i = 0 for x in flord.keys(): i += 1 fgrouped[i] = [[x]] return fgrouped fgrouped = {} i...
Cluster files into the specified number of groups, where each groups total size is as close as possible to each other. Pseudo-code (O(n^g) time complexity): Input: number of groups G per cluster, list of files F with respective sizes - Order F by descending size - Until F is empty: - Create a c...
364,575
def construct_from(cls, group_info): group = cls(group_info[]) group._info_cache = group_info return group
Constructs ``FileGroup`` instance from group information.
364,576
def setup_Jupyter(): sns.set(context = "paper", font = "monospace") warnings.filterwarnings("ignore") pd.set_option("display.max_rows", 500) pd.set_option("display.max_columns", 500) plt.rcParams["figure.figsize"] = (17, 10)
Set up a Jupyter notebook with a few defaults.
364,577
def pprint_out(dct: Dict): for name, val in dct.items(): print(name + ) pprint(val, indent=4)
Utility methods to pretty-print a dictionary that is typically outputted by parsyfiles (an ordered dict) :param dct: :return:
364,578
def save(self, *args, **kwargs): custom_checks = kwargs.pop(, True) super(Device, self).save(*args, **kwargs) if custom_checks is False: return changed = False if not self.location: self.location = self.node.point changed = True ...
Custom save method does the following: * automatically inherit node coordinates and elevation * save shortcuts if HSTORE is enabled
364,579
def raw_corpus_rouge2(hypotheses: Iterable[str], references: Iterable[str]) -> float: return rouge.rouge_2(hypotheses, references)
Simple wrapper around ROUGE-2 implementation. :param hypotheses: Hypotheses stream. :param references: Reference stream. :return: ROUGE-2 score as float between 0 and 1.
364,580
def delta(self, mapping, prefix): previous = self.getrange(prefix, strip=True) if not previous: pk = set() else: pk = set(previous.keys()) ck = set(mapping.keys()) delta = DeltaSet() for k in ck.difference(pk): delta[...
return a delta containing values that have changed.
364,581
def visit_subscript(self, node): try: for inferred in node.value.infer(): if not isinstance(inferred, astroid.Instance): continue if utils.inherit_from_std_ex(inferred): self.add_message("indexing-exception", node=node)...
Look for indexing exceptions.
364,582
def store_initial_arguments(request, initial_arguments=None): if initial_arguments is None: return None cache_id = "dpd-initial-args-%s" % str(uuid.uuid4()).replace(, ) if initial_argument_location(): cache.set(cache_id, initial_arguments, cache_timeout_initial_arguments())...
Store initial arguments, if any, and return a cache identifier
364,583
def fcoe_get_interface_input_fcoe_intf_name(self, **kwargs): config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface input = ET.SubElement(fcoe_get_interface, "input") fcoe_intf_name = ET.SubElement(input, "fcoe-int...
Auto Generated Code
364,584
def circ_permutation(items): permutations = [] for i in range(len(items)): permutations.append(items[i:] + items[:i]) return permutations
Calculate the circular permutation for a given list of items.
364,585
def list_all_orders(cls, **kwargs): kwargs[] = True if kwargs.get(): return cls._list_all_orders_with_http_info(**kwargs) else: (data) = cls._list_all_orders_with_http_info(**kwargs) return data
List Orders Return a list of Orders This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_orders(async=True) >>> result = thread.get() :param async bool :param int page: pa...
364,586
def data(): from keras.datasets import mnist from keras.utils import np_utils (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype() x_test = x_test.astype() x_train /= 255 x_t...
Data providing function: Make sure to have every relevant import statement included here and return data as used in model function below. This function is separated from model() so that hyperopt won't reload data for each evaluation run.
364,587
def __expand_subfeatures_aux (property_, dont_validate = False): from . import property assert isinstance(property_, property.Property) assert isinstance(dont_validate, int) f = property_.feature v = property_.value if not dont_validate: validate_value_string(f, v) compone...
Helper for expand_subfeatures. Given a feature and value, or just a value corresponding to an implicit feature, returns a property set consisting of all component subfeatures and their values. For example: expand_subfeatures <toolset>gcc-2.95.2-linux-x86 -> <toolset>gcc ...
364,588
def menu(items, heading): heading = "\n"*5 + heading while True: keydict = {} clear_screen() print(heading) for item in items: menustring = " " + item["key"] + " " + item["text"] keydict[item["key"]] = item["function"] print(men...
Takes list of dictionaries and prints a menu. items parameter should be in the form of a list, containing dictionaries with the keys: {"key", "text", "function"}. Typing the key for a menuitem, followed by return, will run "function".
364,589
def _get_read_query(self, table_columns, limit=None): query_columns = [column.name for column in table_columns] query_columns.remove() query = .format( table_name=self.table_name, schema=self.schema, columns=.join(query_columns)) if limit is...
Create the read (COPY TO) query
364,590
def syzygyJD(jd): sun = swe.sweObjectLon(const.SUN, jd) moon = swe.sweObjectLon(const.MOON, jd) dist = angle.distance(sun, moon) offset = 180 if (dist >= 180) else 0 while abs(dist) > MAX_ERROR: jd = jd - dist / 13.1833 sun = swe.sweObjectLon(const.SUN, jd) ...
Finds the latest new or full moon and returns the julian date of that event.
364,591
def screenshot(self, save_path, element=None, delay=0): if save_path is None: logger.error("save_path cannot be None") return None save_location = cutil.norm_path(save_path) cutil.create_path(save_location) logger.info("Taking screenshot: {filename}".for...
This can be used no matter what driver that is being used * ^ Soon requests support will be added Save screenshot to local dir with uuid as filename then move the file to `filename` (path must be part of the file name) Return the filepath of the image
364,592
def drop_table(self, table): job_id = self.submit("DROP TABLE %s"%table, context="MYDB") status = self.monitor(job_id) if status[0] != 5: raise Exception("Couldn't drop table %s"%table)
Drop a table from the MyDB context. ## Arguments * `table` (str): The name of the table to drop.
364,593
def change_settings(self, bio=None, public_images=None, messaging_enabled=None, album_privacy=None, accepted_gallery_terms=None): url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name) resp = self._img...
Update the settings for the user. :param bio: A basic description filled out by the user, is displayed in the gallery profile page. :param public_images: Set the default privacy setting of the users images. If True images are public, if False private. :param messaging_en...
364,594
def get_contents(self): childsigs = [n.get_csig() for n in self.children()] return .join(childsigs)
The contents of an alias is the concatenation of the content signatures of all its sources.
364,595
def handle_read(self): with self.lock: logger.debug("handle_read()") if self._eof or self._socket is None: return if self._state == "tls-handshake": while True: logger.debug("tls handshake read...") ...
Handle the 'channel readable' state. E.g. read from a socket.
364,596
def gmdaArray(arry, dtype, mask=None, numGhosts=1): a = numpy.array(arry, dtype) res = GhostedMaskedDistArray(a.shape, a.dtype) res.mask = mask res.setNumberOfGhosts(numGhosts) res[:] = a return res
ghosted distributed array constructor @param arry numpy-like array @param numGhosts the number of ghosts (>= 0)
364,597
def _get_features(self, eopatch=None): for feature_type, feature_dict in self.feature_collection.items(): if feature_type is None and self.default_feature_type is not None: feature_type = self.default_feature_type if feature_type is None: ...
A generator of parsed features. :param eopatch: A given EOPatch :type eopatch: EOPatch or None :return: One by one feature :rtype: tuple(FeatureType, str) or tuple(FeatureType, str, str)
364,598
def format_in_original_format(numobj, region_calling_from): if (numobj.raw_input is not None and not _has_formatting_pattern_for_number(numobj)): return numobj.raw_input if numobj.country_code_source is CountryCodeSource.UNSPECIFIED: return format_number(numobj, PhoneNumbe...
Format a number using the original format that the number was parsed from. The original format is embedded in the country_code_source field of the PhoneNumber object passed in. If such information is missing, the number will be formatted into the NATIONAL format by default. When we don't have a forma...
364,599
def parse_list(cls, data): results = ResultSet() data = data or [] for obj in data: if obj: results.append(cls.parse(obj)) return results
Parse a list of JSON objects into a result set of model instances.