Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
343,500
def Container(*args): if len(args) == 1: iterable = args[0] else: iterable = args if isinstance(iterable, ContainerBase): return iterable for container_class, containing_classes in ContainerRegistry: if any([isinstance(iterable, containing_class) f...
C = Container(iterable) C = Container(module) C = Container(object) C = Container(obj_1, obj_2, obj_3, ...) Wraps an iterable object (currently a list, set, tuple, dictionary or ndarray), or a module or other object, or just a sequence of objects, in a subclass of ContainerBase and returns it. ...
343,501
def tag_value(func): def inner(self): tag, attrib, attrib_type = func(self) tag_obj = self.et.find(tag) if tag_obj is not None: try: return attrib_type(self.et.find(tag).attrib[attrib]) except KeyError: raise AttributeError r...
Decorator used to declare that the property is attribute of embedded tag
343,502
def bind(self, model, template="{}"): self._bound_model = model self._uri_template = template self._set_uri_from_bound_model()
Bind the ``model`` to the reference. This uses the model's ``id`` attribute and the given ``template`` to dynamically produce a uri when accessed.
343,503
def value_to_single_key_strokes(value): result = [] if isinstance(value, Integral): value = str(value) for v in value: if isinstance(v, Keys): result.append(v.value) elif isinstance(v, Integral): result.append(str(v)) else: result.app...
Convert value to a list of key strokes >>> value_to_single_key_strokes(123) ['1', '2', '3'] >>> value_to_single_key_strokes('123') ['1', '2', '3'] >>> value_to_single_key_strokes([1, 2, 3]) ['1', '2', '3'] >>> value_to_single_key_strokes(['1', '2', '3']) ['1', '2', '3'] Args: ...
343,504
def render(self): if not self.validate(): raise ValidationError self.process_request() self.clean() return self.response
Validate, process, clean and return the result of the call.
343,505
def _detect_xgettext(env): if in env: return env[] xgettext = env.Detect(); if xgettext: return xgettext raise SCons.Errors.StopError(XgettextNotFound, "Could not detect xgettext") return None
Detects *xgettext(1)* binary
343,506
def deepupdate(original, update): for key, value in original.items(): if key not in update: update[key] = value elif isinstance(value, dict): deepupdate(value, update[key]) return update
Recursively update a dict. Subdict's won't be overwritten but also updated.
343,507
def from_object(cls: Type["Config"], instance: Union[object, str]) -> "Config": if isinstance(instance, str): try: path, config = instance.rsplit(".", 1) except ValueError: path = instance instance = importlib.import_module(instanc...
Create a configuration from a Python object. This can be used to reference modules or objects within modules for example, .. code-block:: python Config.from_object('module') Config.from_object('module.instance') from module import instance Confi...
343,508
def deserialize(cls, value, trusted=False, strict=False, assert_valid=False, **kwargs): if not isinstance(value, dict): raise ValueError() identifier = value.pop(, value.get()) if identifier is None: raise ValueError() if identifier in...
Create a Singleton instance from a serialized dictionary. This behaves identically to HasProperties.deserialize, except if the singleton is already found in the singleton registry the existing value is used. .. note:: If property values differ from the existing singleton a...
343,509
def parse_args(self, args): parser = argparse.ArgumentParser( description=) root = parser.add_mutually_exclusive_group(required=True) root.add_argument(, , help=) root.add_argument(, help=) root.add_argument(, action=, ...
Parse arguments and return an arguments object >>> from margaritashotgun.cli import Cli >>> cli = CLi() >>> cli.parse_args(sys.argv[1:]) :type args: list :param args: list of arguments
343,510
def creatauth(name, homedir): uid, gid = [None, None] command = "id %s" % (name) data = commands.getstatusoutput(command) if data[0] > 0: command = "useradd -g %s %s" % (sett.APACHEIIS_GROUP, name) data = commands.getstatusoutput(command) if data[0] ...
Function create user in linux for group and set homedir. Function return gid and uid.
343,511
def rotate(self, angle, axis): self.matrix = np.dot(self.matrix, transforms.rotate(angle, axis))
Rotate the matrix by some angle about a given axis. The rotation is applied *after* the transformations already present in the matrix. Parameters ---------- angle : float The angle of rotation, in degrees. axis : array-like The x, y and z coordin...
343,512
def unprotect(self, **kwargs): id = self.get_id().replace(, ) path = % (self.manager.path, id) self.manager.gitlab.http_put(path, **kwargs) self._attrs[] = False
Unprotect the branch. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabProtectError: If the branch could not be unprotected
343,513
def batch_map_concat(self, func, batch_size, progress_iter_func=None, n_batches=None, prepend_args=None, **kwargs): if n_batches is None: n = self.num_samples(**kwargs) if n == np.inf: raise ValueError( ...
A batch oriented implementation of `map`. Applies a function to all the samples in this data source by breaking the data into mini-batches and applying the function to each mini-batch. Returns the per-sample results. This method is a wrapper around the :func:`batch_map` function...
343,514
def print_bin_sizes(): for i, offset in enumerate(OFFSETS): binstart = offset try: binstop = OFFSETS[i + 1] except IndexError: binstop = binstart bin_size = 2 ** (FIRST_SHIFT + (i * NEXT_SHIFT)) actual_size = bin_size bin_size, ...
Useful for debugging: how large is each bin, and what are the bin IDs?
343,515
def init_run_context(self, raw=False): self.raw = raw self._set_context(self)
Sets the log context.
343,516
def update_settings(self): self.display() self.display_markers() if self.parent.notes.annot is not None: self.parent.notes.display_notes()
After changing the settings, we need to recreate the whole image.
343,517
def id_by_name(self, hostname): addr = self._gethostbyname(hostname) return self.id_by_addr(addr)
Returns the database ID for specified hostname. The id might be useful as array index. 0 is unknown. :arg hostname: Hostname to get ID from.
343,518
def sync_projects(self): p = self.keystone_event._service.projects.list() for proj in p: if proj.name in not_create_project_name: continue LOG.info("Syncing project %s" % proj.name) self.project_create_func(proj.id, proj=proj)
Sync projects. This function will retrieve project from keystone and populate them dfa database and dcnm
343,519
def _parse_soil_profile(block, units, curves, **kwargs): wt_layer, length, _, name = parse_fixed_width( 3 * [(5, int)] + [(55, to_str)], block) layers = [] soil_types = [] for i in range(length): index, soil_idx, thickness, shear_mod, damping, unit_wt, shear_vel = \ par...
Parse soil profile block.
343,520
def transformer_tall(): hparams = transformer_base() hparams.batch_size = 2048 hparams.hidden_size = 768 hparams.filter_size = 3072 hparams.num_hidden_layers = 12 hparams.num_heads = 12 hparams.label_smoothing = 0.0 hparams.max_length = 1024 hparams.eval_drop_long_sequences = True hparams.multipr...
Hparams for transformer on LM for pretraining/finetuning/mixing.
343,521
def _find_agent(self, location): for a in self._auth_info.agents:
Finds an appropriate agent entry for the given location. :return Agent
343,522
def start(self, timeout=300): if self.is_alive: return True try: dbpath = self.cfg.get() if dbpath and self._is_locked: logger.info("Performing repair on locked dbpath %s", dbpath) process.repair_mongo(self.nam...
start server return True of False
343,523
def GET_parameteritemvalues(self) -> None: for item in state.parameteritems: self._outputs[item.name] = item.value
Get the values of all |ChangeItem| objects handling |Parameter| objects.
343,524
def restoreDataSet( settings, key, dataSet ): for datakey in dataSet.keys(): vtype = unwrapVariant(settings.value( % (key, datakey))) value = unwrapVariant(settings.value( % (key, datakey))) if ( vtype is None ): continue vtype = nativestring(vtype)...
Restores the dataset settings to the inputed data set for the given key. :param settings | <QSettings> key | <str> dataSet | <projex.dataset.DataSet>
343,525
def is_location_command(self, cmd): mav_cmd = mavutil.mavlink.enums[] if not cmd in mav_cmd: return False if not mav_cmd[cmd].param.get(5,).startswith(): return False if not mav_cmd[cmd].param.get(6,).startswith(): return False return ...
see if cmd is a MAV_CMD with a latitide/longitude. We check if it has Latitude and Longitude params in the right indexes
343,526
def do_get_content(parser, token): bits = token.split_contents() if not 5 <= len(bits) <= 6: raise TemplateSyntaxError( % bits[0]) if bits[-2] != : raise TemplateSyntaxError( % bits[0]) page = parser.compile_filter(bits[1]) content_type = parser.compile_filter(bits[...
Retrieve a Content object and insert it into the template's context. Example:: {% get_content page_object "title" as content %} You can also use the slug of a page:: {% get_content "my-page-slug" "title" as content %} Syntax:: {% get_content page type [lang] as name %} :pa...
343,527
def atexit_rmglob(path, glob=glob.glob, isdir=os.path.isdir, isfile=os.path.isfile, remove=os.remove, rmtree=shutil.rmtree): for p in glob(path): if isfile(p): remove(p) elif isdir(p): ...
Ensure removal of multiple files at interpreter exit.
343,528
def recompile(self, nick=None, new_nick=None, **kw): if self.bot.nick == nick.nick: self.bot.config[] = new_nick self.bot.recompile()
recompile regexp on new nick
343,529
def deserializeEc(x, compress=True): return _deserialize(x, ec1Element, compress, librelic.ec_read_bin_abi)
Deserialize binary string @x into an EC element.
343,530
def ordering(self, type): result = [] for child, ancestry in type.resolve(): name = child.name if child.name is None: continue if child.isattr(): name = % child.name result.append(name) return result
Get the attribute ordering defined in the specified XSD type information. @param type: An XSD type object. @type type: SchemaObject @return: An ordered list of attribute names. @rtype: list
343,531
def clear(self): with self.__svc_lock: self.__svc_registry.clear() self.__svc_factories.clear() self.__svc_specs.clear() self.__bundle_svc.clear() self.__bundle_imports.clear() self.__factory_usage.clear() self.__pendin...
Clears the registry
343,532
def get_prep_value(self, value): if isinstance(value, Seconds): return value.seconds elif value: return self.parse_seconds(value).seconds else: return None
Prepare value for database storage.
343,533
def parse_subject(content, reference_id=None, clean=True): def to_unicodechar(match): return unichr(int(match.group(1))) m = _SUBJECT_MAX_PATTERN.search(content) max_idx = m.start() if m else _MAX_HEADER_IDX m = _SUBJECT_PATTERN.search(content, 0, max_idx) if not m: return u ...
\ Parses and returns the subject of a cable. If the cable has no subject, an empty string is returned. `content` The cable's content. `reference_id` The (optional) reference id of the cable. Used for error msgs `clean` Indicates if classification prefixes like ``(S)`` sh...
343,534
def add_single_feature_methods(cls): if not hasattr(cls, "enums"): return cls for feature in cls.enums.Feature.Type: if feature.name == "TYPE_UNSPECIFIED": continue detect = _create_single_feature_method(feature) ...
Custom decorator intended for :class:`~vision.helpers.VisionHelpers`. This metaclass adds a `{feature}` method for every feature defined on the Feature enum.
343,535
def get_smeared_densities(self, sigma): from scipy.ndimage.filters import gaussian_filter1d diff = [self.frequencies[i + 1] - self.frequencies[i] for i in range(len(self.frequencies) - 1)] avgdiff = sum(diff) / len(diff) smeared_dens = gaussian_filter1d(self.de...
Returns the densities, but with a Gaussian smearing of std dev sigma applied. Args: sigma: Std dev of Gaussian smearing function. Returns: Gaussian-smeared densities.
343,536
def count_het(self, allele=None, axis=None): b = self.is_het(allele=allele) return np.sum(b, axis=axis)
Count heterozygous genotypes. Parameters ---------- allele : int, optional Allele index. axis : int, optional Axis over which to count, or None to perform overall count.
343,537
def configuration_remove(self, environment_id, configuration_id): data = dict() data["configuration_id"] = configuration_id data["environment_id"] = environment_id url = ( "environment/configuration/remove/%(environment_id)s/%(configuration_id)s/" % da...
Remove Prefix Configuration :return: None :raise InvalidValueError: Invalid Id for Environment or IpConfig. :raise IPConfigNotFoundError: Ipconfig not resgistred. :raise AmbienteNotFoundError: Environment not registered. :raise DataBaseError: Failed into networkapi access data ...
343,538
def setup_datafind_runtime_cache_multi_calls_perifo(cp, scienceSegs, outputDir, tags=None): if tags is None: tags = [] logging.info("Setting up connection to datafind server.") connection = setup_datafind_server_connection(cp, tags=...
This function uses the glue.datafind library to obtain the location of all the frame files that will be needed to cover the analysis of the data given in scienceSegs. This function will not check if the returned frames cover the whole time requested, such sanity checks are done in the pycbc.workflow.set...
343,539
def ignore_blanks(self) -> bool: self._stream.save_context() if not self.read_eof() and self._stream.peek_char in " \t\v\f\r\n": while (not self.read_eof() and self._stream.peek_char in " \t\v\f\r\n"): self._stream.incpos() return self....
Consume whitespace characters.
343,540
def poll(self, timeout=0.0): if self.sock_map is None: Log.warning("Socket map is not registered to Gateway Looper") readable_lst = [] writable_lst = [] error_lst = [] if self.sock_map is not None: for fd, obj in self.sock_map.items(): is_r = obj.readable() is_w = o...
Modified version of poll() from asyncore module
343,541
def queue_declare(self, queue=, passive=False, durable=False, exclusive=False, auto_delete=True, nowait=False, arguments=None): arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_short...
Declare queue, create if needed This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue. RULE: The server MUST crea...
343,542
def iter_repos(self, type=None, sort=None, direction=None, number=-1, etag=None): url = self._build_url(, ) params = {} if type in (, , , , ): params.update(type=type) if sort in (, , , ): params.update(sort=sort) if direction ...
List public repositories for the authenticated user. .. versionchanged:: 0.6 Removed the login parameter for correctness. Use iter_user_repos instead :param str type: (optional), accepted values: ('all', 'owner', 'public', 'private', 'member') API default:...
343,543
def service_executions(self, *args, **kwargs): return self._client.service_executions(*args, scope=self.id, **kwargs)
Retrieve services belonging to this scope. See :class:`pykechain.Client.service_executions` for available parameters. .. versionadded:: 1.13
343,544
def write_config(self): with open(self.config_file, "w") as config_file: self.cfg.write(config_file)
Writes `self.cfg` to `self.config_file`.
343,545
def _parse_from_import_names(self, is_future_import): if self.current.value == "(": self.consume(tk.OP) expected_end_kinds = (tk.OP,) else: expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER) while self.current.kind not in expected_end_kinds and not ( ...
Parse the 'y' part in a 'from x import y' statement.
343,546
def get_patched_request(self, package_requests=None, package_subtractions=None, strict=False, rank=0): if strict: request = [] for variant in self.resolved_packages: req = PackageRequest(variant.qualified_package_name) ...
Get a 'patched' request. A patched request is a copy of this context's request, but with some changes applied. This can then be used to create a new, 'patched' context. New package requests override original requests based on the type - normal, conflict or weak. So 'foo-2' over...
343,547
def disconnect_from(callback, signals): if not isinstance(signals, (list, tuple)): signals = [signals] for signal in signals: if responds_to(callback, signal): receivers[signal].remove(callback)
Removes a callback from specified signal registries and prevents it from responding to any emitted signal. :param callback: A callable registered with smokesignal :param signals: A single signal or list/tuple of signals
343,548
def find_element_by_link_text(self, link_text): return self.find_element(by=By.LINK_TEXT, value=link_text)
Finds an element by link text. :Args: - link_text: The text of the element to be found. :Returns: - WebElement - the element if it was found :Raises: - NoSuchElementException - if the element wasn't found :Usage: :: element = dr...
343,549
def get_form(self, form, name): kwargs = self.get_kwargs(form, name) form_class = self.get_form_class(form, name) composite_form = form_class( data=form.data if form.is_bound else None, files=form.files if form.is_bound else None, **kwargs) re...
Get an instance of the form.
343,550
def export(self, version, export_dir): atts = [ (PROV[], self.type), (PROV[], self.label), ] if version[] == "1.0.0": atts += [ (NIDM_USER_SPECIFIED_THRESHOLD_TYPE, self.user_threshold_type), (PROV[], self.stat_thresh...
Create prov entities and activities.
343,551
def nvmlDeviceGetRetiredPagesPendingStatus(device): r c_pending = _nvmlEnableState_t() fn = _nvmlGetFunctionPointer("nvmlDeviceGetRetiredPagesPendingStatus") ret = fn(device, byref(c_pending)) _nvmlCheckReturn(ret) return int(c_pending.value)
r""" /** * Check if any pages are pending retirement and need a reboot to fully retire. * * For Kepler &tm; or newer fully supported devices. * * @param device The identifier of the target device * @param isPending Reference in which t...
343,552
def verify_create(self, recipient, params=None): if params is None: params = {} params.update({: recipient}) return Verify().load(self.request(, , params))
Create a new verification.
343,553
def _updateTargetFromNode(self): font = self.data if self.familyCti.configValue: font.setFamily(self.familyCti.configValue) else: font.setFamily(QtGui.QFont().family()) font.setPointSize(self.pointSizeCti.configValue) font.setWeight(self.weightCt...
Applies the font config settings to the target widget's font. That is the targetWidget.setFont() is called with a font create from the config values.
343,554
def activate_status_input_rbridge_id(self, **kwargs): config = ET.Element("config") activate_status = ET.Element("activate_status") config = activate_status input = ET.SubElement(activate_status, "input") rbridge_id = ET.SubElement(input, "rbridge-id") rbridge_id...
Auto Generated Code
343,555
def getEarliness(self): maxtime = self.getMaxTimeAllowed() if not maxtime: return 0 return api.to_minutes(**maxtime) - self.getDuration()
The remaining time in minutes for this analysis to be completed. Returns zero if the analysis is neither 'ready to process' nor a turnaround time is set. earliness = duration - max_turnaround_time The analysis is late if the earliness is negative :return: the remaining time i...
343,556
def connect_output(self, node): if len(self.outputs) == self.max_outputs: raise TooManyOutputsError("Attempted to connect too many nodes to the output of a node", max_outputs=self.max_outputs, stream=self.stream) self.outputs.append(node)
Connect another node to our output. This downstream node will automatically be triggered when we update our output. Args: node (SGNode): The node that should receive our output
343,557
def download(self, url, path, name_audio): if path is not None: with open(str(path+name_audio), ) as handle: response = requests.get(url, stream = True) if not response.ok: raise Exception("Error in audio download.") for bl...
Params: ::url = Comprises the url used to download the audio. ::path = Comprises the location where the file should be saved. ::name_audio = Is the name of the desired audio. Definition: Basically, we do a get with the requests modu...
343,558
def html2data(html_string): spans = extract_spans(html_string) column_count = get_html_column_count(html_string) row_count = get_html_row_count(spans) count = 0 while count < len(spans): if len(spans[count]) == 1: spans.pop(count) else: count += 1 ...
Convert an html table to a data table and spans. Parameters ---------- html_string : str The string containing the html table Returns ------- table : list of lists of str spans : list of lists of lists of int A span is a list of [row, column] pairs that define what cells ...
343,559
def logout(request, config_loader_path=None): state = StateCache(request.session) conf = get_config(config_loader_path, request) client = Saml2Client(conf, state_cache=state, identity_cache=IdentityCache(request.session)) subject_id = _get_subject_id(request.session) i...
SAML Logout Request initiator This view initiates the SAML2 Logout request using the pysaml2 library to create the LogoutRequest.
343,560
def wait_lock(lk_fn, dest, wait_timeout=0): if not os.path.exists(lk_fn): return False if not os.path.exists(dest): time.sleep(1) if not os.path.isfile(dest): _unlock_cache(lk_fn) return False timeout = None if wait_timeout: ...
If the write lock is there, check to see if the file is actually being written. If there is no change in the file size after a short sleep, remove the lock and move forward.
343,561
def merged(self, other): if self.name_ != other.name_: return None def _r(r_): r = Requirement(None) r.name_ = r_.name_ r.negate_ = r_.negate_ r.conflict_ = r_.conflict_ r.sep_ = r_.sep_ return r if ...
Returns the merged result of two requirements. Two requirements can be in conflict and if so, this function returns None. For example, requests for "foo-4" and "foo-6" are in conflict, since both cannot be satisfied with a single version of foo. Some example successful requirements mer...
343,562
def calc_noise(volume, mask, template, noise_dict=None, ): if template.max() > 1.1: raise ValueError() if mask is None: raise ValueError() if noise_dict is None: noise_dict = {: [1.0, 1.0, 1.0]} el...
Calculates the noise properties of the volume supplied. This estimates what noise properties the volume has. For instance it determines the spatial smoothness, the autoregressive noise, system noise etc. Read the doc string for generate_noise to understand how these different types of noise interact. ...
343,563
def _warn_if_string(iterable): if isinstance(iterable, string_types): from warnings import warn warn(Warning( ), stacklevel=2)
Helper for the response objects to check if the iterable returned to the WSGI server is not a string.
343,564
def expr2dimacscnf(ex): litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
Convert an expression into an equivalent DIMACS CNF.
343,565
def item(*args): ** ret = {} for arg in args: try: ret[arg] = __pillar__[arg] except KeyError: pass return ret
.. versionadded:: 0.16.2 Return one or more pillar entries CLI Examples: .. code-block:: bash salt '*' pillar.item foo salt '*' pillar.item foo bar baz
343,566
def export_as_csv(admin_model, request, queryset): if getattr(settings, , None): admin_opts = admin_model.opts codename = % (, admin_opts.object_name.lower()) has_csv_permission = request.user.has_perm("%s.%s" % (admin_opts.app_label, codename)) else: has_csv_permissio...
Generic csv export admin action. based on http://djangosnippets.org/snippets/1697/
343,567
def getSignedNS(self, ns_uri): msg_args = self.message.getArgs(ns_uri) for key in msg_args.iterkeys(): if not self.isSigned(ns_uri, key): logging.info("SuccessResponse.getSignedNS: (%s, %s) not signed." % (ns_uri, key)) re...
Get signed arguments from the response message. Return a dict of all arguments in the specified namespace. If any of the arguments are not signed, return None.
343,568
def run_study(self, study, **kws): if not study: return [] methods = Methods(kws[]) if in kws else self.methods alpha = kws[] if in kws else self.alpha log = kws[] if in kws else self.log results = self.get_pval_uncorr(study, log) ...
Run Gene Ontology Enrichment Study (GOEA) on study ids.
343,569
def _auth_base(self, password_text): dk = hashlib.pbkdf2_hmac( config.PASSWORD_HASH_FUNC_NAME, password_text.encode(), get_bytes_from_blob(self.salt), config.PASSWORD_HASH_ITERATIONS ) if self.password == dk: return self
已获取了用户对象,进行密码校验 :param password_text: :return:
343,570
def open_file(self, store=current_store, use_seek=False): if not isinstance(store, Store): raise TypeError( + repr(store)) if Session.object_session(self) is None: try: file = self.file ...
Opens the file-like object which is a context manager (that means it can used for :keyword:`with` statement). If ``use_seek`` is :const:`True` (though :const:`False` by default) it guarentees the returned file-like object is also seekable (provides :meth:`~file.seek()` method). ...
343,571
def copy(self, deep=False): if deep: return deepcopy(self) return super(DataQualityDict, self).copy()
Build a copy of this dictionary. Parameters ---------- deep : `bool`, optional, default: `False` perform a deep copy of the original dictionary with a fresh memory address Returns ------- flag2 : `DataQualityFlag` a copy of the origin...
343,572
def feed(self, text=None, source=None): if text is not None: words = re.split(r, text) wlen = len(words) for i in range(wlen - 2): self._insert(words[i:i+3]) if source is not None: with open(source, ) as f: self.fe...
Feed some text to the database, either from a string (``text``) or a file (``source``). >>> db = TrigramsDB() >>> db.feed("This is my text") >>> db.feed(source="some/file.txt")
343,573
def update_value(self, block_id, field, value): block_name = self._db.get_block(block_id) for name in block_name: self._db.set_value(name, field, value)
Update the value of the given block id and field
343,574
def handle_addVersion(repo, **kwargs): log.info( %(repo, kwargs)) try: v = repo.addVersion(**kwargs) return v.serialize() except RepoError, e: raise
:return: repo.addSubmodule()
343,575
def get_requirements(self, arguments, max_retries=None, use_wheels=False): arguments = self.decorate_arguments(arguments) with DownloadLogFilter(): with SetupRequiresPatch(self.config, self.eggs_links): self.create_build_directory()...
Use pip to download and unpack the requested source distribution archives. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param max_retries: The maximum number of times that pip will be asked to download di...
343,576
def reduce_in_chunks(fn, iterable, initializer, chunk_size=0): if len(iterable) == 0: return initializer if chunk_size == 0: chunk_size = len(iterable) return reduce(fn, chunks(iterable, chunk_size), initializer)
Reduce the given list of items by splitting it into chunks of the given size and passing each chunk through the reducer
343,577
def _genBgTerm_fromXX(self,vTot,vCommon,XX,a=None,c=None): vSpecific = vTot-vCommon SP.random.seed(0) if c==None: c = SP.randn(self.P) XX += 1e-3 * SP.eye(XX.shape[0]) L = LA.cholesky(XX,lower=True) R = self.genWeights(self.N,self.P) A = self.g...
generate background term from SNPs Args: vTot: variance of Yc+Yi vCommon: variance of Yc XX: kinship matrix a: common scales, it can be set for debugging purposes c: indipendent scales, it can be set for debugging purposes
343,578
def set_bpp(self, bpp): self.bpp = bpp self.maxc = 2 ** self.bpp - 1 self._set_dtype() self.calc_cmap() self.recalc(callback=False)
Set the bit depth (per band) for the output. A typical "32-bit RGBA" image would be 8; a 48-bit image would be 16, etc.
343,579
def equal(data, num_breaks): step = (numpy.amax(data) - numpy.amin(data)) / num_breaks return numpy.linspace(numpy.amin(data) + step, numpy.amax(data), num_breaks)
Calculate equal interval breaks. Arguments: data -- Array of values to classify. num_breaks -- Number of breaks to perform.
343,580
def make_open_functions(): if hasattr(str, ): def isidentifier(x): return x.isidentifier() else: IDENTIFIER_REGEX = re.compile(r) isidentifier = IDENTIFIER_REGEX.match for plugin_name, plugin in registry.items(): func_name = + plugin_name if not...
From the current state of ``registry``, create open_* functions
343,581
def registrations(self): if self._registrations is None: self._registrations = AuthTypeRegistrationsList( self._version, account_sid=self._solution[], domain_sid=self._solution[], ) return self._registrations
Access the registrations :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.AuthTypeRegistrationsList
343,582
def push_to_gateway( gateway, job, registry, grouping_key=None, timeout=30, handler=default_handler): _use_gateway(, gateway, job, registry, grouping_key, timeout, handler)
Push metrics to the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defaults to 'http' if none is provided `job` is the job label to be attached to all pushed metrics `registry` is an insta...
343,583
def clear_dag_task_instances(): session = settings.Session() TI = TaskInstance tis = ( session .query(TI) .filter(TI.dag_id.in_(DAG_IDS)) .all() ) for ti in tis: logging.info(.format(ti)) session.delete(ti) session.commit()
Remove any existing task instances for the perf test DAGs.
343,584
def add_string(self, data): lines = [] while data: match = self._line_end_re.search(data) if match is None: chunk = data else: chunk = data[:match.end()] data = data[len(chunk):] if self._buf and self....
Process some data splitting it into complete lines and buffering the rest Args: data: A `str` in Python 2 or `bytes` in Python 3 Returns: list of complete lines ending with a carriage return (eg. a progress bar) or a newline.
343,585
def rename_columns(cr, column_spec): for table in column_spec.keys(): for (old, new) in column_spec[table]: if new is None: new = get_legacy_name(old) logger.info("table %s, column %s: renaming to %s", table, old, new) cr.execu...
Rename table columns. Typically called in the pre script. :param column_spec: a hash with table keys, with lists of tuples as \ values. Tuples consist of (old_name, new_name). Use None for new_name \ to trigger a conversion of old_name using get_legacy_name()
343,586
def from_local_repository(repository_path, refspec=None): context = GitContext() if refspec is None: commit_parents = parents.split(" ") commit_is_merge_commit = len(commit_parents) > 1 changed_files = _git(...
Retrieves the git context from a local git repository. :param repository_path: Path to the git repository to retrieve the context from :param refspec: The commit(s) to retrieve
343,587
def get_feincms_inlines(self, model, request): model._needs_content_types() inlines = [] for content_type in model._feincms_content_types: if not self.can_add_content(request, content_type): continue attrs = { : model.__module__,...
Generate genuine django inlines for registered content types.
343,588
def _handle_response(self, response): status = response.status_code if status == 400: msg = u"bad request" raise exceptions.BadRequest(status, msg) elif status == 401: msg = u"authorization failed user:%s" % (self.sk_user) raise exceptions.Unautho...
internal method to throw the correct exception if something went wrong
343,589
def set_robot_joint_positions(self, positions): self.env.set_robot_joint_positions(positions) self.controller.sync_state()
Overrides the function to set the joint positions directly, since we need to notify the IK controller of the change.
343,590
def gen_experiment_ref(experiment_tag, n=10): experiment_id = gen_experiment_id(n=n) return .format(experiment_tag, experiment_id)
Generate a random string for naming. Parameters ---------- experiment_tag : :obj:`str` tag to prefix name with n : int number of random chars to use Returns ------- :obj:`str` string experiment ref
343,591
def many(func): def _many(result): if _isSequenceTypeNotText(result): return map(func, result) return [] return maybe(_many, default=[])
Create a callable that applies ``func`` to every value in a sequence. If the value is not a sequence then an empty list is returned. :type func: `callable` :param func: Callable to be applied to the first result.
343,592
def parse_cnf(s, varname=): lexer = iter(CNFLexer(s)) try: ast = _cnf(lexer, varname) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, text: {0.text})") raise Error(fstr.format(exc)) _expect_token(lexer, {EndTo...
Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults to 'x'. Returns ------- An as...
343,593
def get_subgraph_by_annotation_value(graph, annotation, values): if isinstance(values, str): values = {values} return get_subgraph_by_annotations(graph, {annotation: values})
Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type values: str or iter[str] :return: A subgraph of the original BEL graph ...
343,594
def pytype_to_deps_hpp(t): if isinstance(t, List): return {}.union(pytype_to_deps_hpp(t.__args__[0])) elif isinstance(t, Set): return {}.union(pytype_to_deps_hpp(t.__args__[0])) elif isinstance(t, Dict): tkey, tvalue = t.__args__ return {}.union(pytype_to_deps_hpp(tkey),...
python -> pythonic type hpp filename.
343,595
def upper_bound(fm, nr_subs = None, scale_factor = 1): nr_subs_total = len(np.unique(fm.SUBJECTINDEX)) if not nr_subs: nr_subs = nr_subs_total - 1 assert (nr_subs < nr_subs_total) intersub_scores = [] for measure in range(len(measures.scores)): res_dict = {} re...
compute the inter-subject consistency upper bound for a fixmat. Input: fm : a fixmat instance nr_subs : the number of subjects used for the prediction. Defaults to the total number of subjects in the fixmat minus 1 scale_factor : the scale factor of the FDMs. Default is 1....
343,596
def describe_additive(self): resp = random.choice(additives) if random.random() < .2: resp = random.choice(foodqualities) + + resp if random.random() < .01: resp = self.articleize(resp) return resp
vinegar. spicy vinegar. a spicy vinegar.
343,597
def _find_matcher(self, alias): matcher = lookup(alias) if not matcher: msg = % alias similar = suggest(alias, max=3, cutoff=0.5) if len(similar) > 1: last = similar.pop() msg += % (.join(similar), last) ...
Finds a matcher based on the given alias or raises an error if no matcher could be found.
343,598
def delete(self, key=None): if key is None: for key in self.all(): key.delete() return self._boto_bucket.delete() k = self.key(key) return k.delete()
Deletes the given key, or the whole bucket.
343,599
def unsubscribe(self, topic): topic_list = None if topic is None: raise ValueError() if isinstance(topic, str): if len(topic) == 0: raise ValueError() topic_list = [topic.encode()] elif isinstance(topic, list): topi...
Unsubscribe the client from one or more topics. topic: A single string, or list of strings that are the subscription topics to unsubscribe from. Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not ...