Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
3,500
def obj_res(data, fail_on=[, , ]): errors = [] if not data.get(, None) and in fail_on: errors += [] obj = None obj_type = None for fd in ACTOR_FIELDS: if data.get(fd, False): if not obj: obj = data[fd...
Given some CLI input data, Returns the following and their types: obj - the role grantee res - the resource that the role applies to
3,501
def _sentence_context(match, language=, case_insensitive=True): language_punct = {: r, : r} assert language in language_punct.keys(), \ .format(language_punct.keys()) start = match.start() end = match.end() window = 1000 snippet_left = match.string[start - w...
Take one incoming regex match object and return the sentence in which the match occurs. :rtype : str :param match: regex.match :param language: str
3,502
def _graphite_url(self, query, raw_data=False, graphite_url=None): query = escape.url_escape(query) graphite_url = graphite_url or self.reactor.options.get() url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}".format( base=graphite_url, query=query, ...
Build Graphite URL.
3,503
def create_graph_rules(address_mapper): @rule(AddressMapper, []) def address_mapper_singleton(): return address_mapper return [ address_mapper_singleton, hydrate_struct, parse_address_family, addresses_from_address_families, RootRule(Address), RootRule(BuildFil...
Creates tasks used to parse Structs from BUILD files. :param address_mapper_key: The subject key for an AddressMapper instance. :param symbol_table: A SymbolTable instance to provide symbols for Address lookups.
3,504
def _repack_options(options): return dict( [ (six.text_type(x), _normalize(y)) for x, y in six.iteritems(salt.utils.data.repack_dictlist(options)) ] )
Repack the options data
3,505
def calculate_leapdays(init_date, final_date): leap_days = (final_date.year - 1) // 4 - (init_date.year - 1) // 4 leap_days -= (final_date.year - 1) // 100 - (init_date.year - 1) // 100 leap_days += (final_date.year - 1) // 400 - (init_date.year - 1) // 400 return datetime.timedelta(days=le...
Currently unsupported, it only works for differences in years.
3,506
def get_auth_header(self, user_payload): auth_token = self.get_auth_token(user_payload) return .format( auth_header_prefix=self.auth_header_prefix, auth_token=auth_token )
Returns the value for authorization header Args: user_payload(dict, required): A `dict` containing required information to create authentication token
3,507
def to_cloudformation(self): rest_api = self._construct_rest_api() deployment = self._construct_deployment(rest_api) swagger = None if rest_api.Body is not None: swagger = rest_api.Body elif rest_api.BodyS3Location is not None: swagger = rest_ap...
Generates CloudFormation resources from a SAM API resource :returns: a tuple containing the RestApi, Deployment, and Stage for an empty Api. :rtype: tuple
3,508
def filterMapNames(regexText, records=getIndex(), excludeRegex=False, closestMatch=True): bestScr = 99999 regex = re.compile(regexText, flags=re.IGNORECASE) ret = [] if excludeRegex: if regexText and closestMatch: for m in list(records): if re.search(regex, m...
matches each record against regexText according to parameters NOTE: the code could be written more simply, but this is loop-optimized to scale better with a large number of map records
3,509
def parse(cls, fptr, offset, length): nbytes = offset + length - fptr.tell() fptr.read(nbytes) return cls(length=length, offset=offset)
Parse JPX free box. Parameters ---------- f : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns ------- FreeBox Instance of the current fre...
3,510
def config(config, fork_name="", origin_name=""): state = read(config.configfile) any_set = False if fork_name: update(config.configfile, {"FORK_NAME": fork_name}) success_out("fork-name set to: {}".format(fork_name)) any_set = True if origin_name: update(config.conf...
Setting various configuration options
3,511
def cmd(command, *args, **kwargs): *show ver**$5$lkjsdfoi$blahblahblah proxy_prefix = __opts__[][] proxy_cmd = .join([proxy_prefix, command]) if proxy_cmd not in __proxy__: return False for k in list(kwargs): if k.startswith(): kwargs.pop(k) return __proxy__[proxy_cmd...
run commands from __proxy__ :mod:`salt.proxy.onyx<salt.proxy.onyx>` command function from `salt.proxy.onyx` to run args positional args to pass to `command` function kwargs key word arguments to pass to `command` function .. code-block:: bash salt '*' onyx.cmd se...
3,512
def _read_set(ctx: ReaderContext) -> lset.Set: start = ctx.reader.advance() assert start == "{" def set_if_valid(s: Collection) -> lset.Set: if len(s) != len(set(s)): raise SyntaxError("Duplicated values in set") return lset.set(s) return _read_coll(ctx, set_if_valid, ...
Return a set from the input stream.
3,513
def mkstemp(suffix="", prefix=template, dir=None, text=False): if dir is None: dir = gettempdir() if text: flags = _text_openflags else: flags = _bin_openflags return _mkstemp_inner(dir, prefix, suffix, flags)
User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename. If 'suffix' is specified, the file name will end with that suffix, otherwise there will be no suffix. If 'prefi...
3,514
def username_user_password(self, **kwargs): config = ET.Element("config") username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa") name_key = ET.SubElement(username, "name") name_key.text = kwargs.pop() user_password = ET.SubElement(username...
Auto Generated Code
3,515
def get_properties(self, feature): if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.Feature) result = [] for p in self.all_: if p.feature == feature: ...
Returns all contained properties associated with 'feature
3,516
def hflip(img): if not _is_pil_image(img): raise TypeError(.format(type(img))) return img.transpose(Image.FLIP_LEFT_RIGHT)
Horizontally flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Horizontall flipped image.
3,517
def table_add(tab, data, col): x = [] for i in range(len(data)): if col not in data[i]: temp = else: temp = data[i][col] if temp is None: temp = x.append(temp) print(.format(col)) tab.add_column(Column(x, name=col))
Function to parse dictionary list **data** and add the data to table **tab** for column **col** Parameters ---------- tab: Table class Table to store values data: list Dictionary list from the SQL query col: str Column name (ie, dictionary key) for the column to add
3,518
def lintersects(self, span): if isinstance(span, list): return [sp for sp in span if self._lintersects(sp)] return self._lintersects(span)
If this span intersects the left (starting) side of the given span.
3,519
def reordi(iorder, ndim, array): iorder = stypes.toIntVector(iorder) ndim = ctypes.c_int(ndim) array = stypes.toIntVector(array) libspice.reordi_c(iorder, ndim, array) return stypes.cVectorToPython(array)
Re-order the elements of an integer array according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordi_c.html :param iorder: Order vector to be used to re-order array. :type iorder: Array of ints :param ndim: Dimension of array. :type ndim: int :param a...
3,520
def unpublish(scm, published_branch, verbose, fake): scm.fake = fake scm.verbose = fake or verbose scm.repo_check(require_remote=True) branch = scm.fuzzy_match_branch(published_branch) if not branch: scm.display_available_branches() raise click.BadArgumentUsage() branch_n...
Removes a published branch from the remote repository.
3,521
def share(track_id=None, url=None, users=None): client = get_client() if url: track_id = client.get(, url=url).id if not users: return client.get( % track_id) permissions = {: []} for username in users: user = settings.users.get(username, None) if u...
Returns list of users track has been shared with. Either track or url need to be provided.
3,522
def delete_host(zone, name, nameserver=, timeout=5, port=53, **kwargs): fqdn = .format(name, zone) request = dns.message.make_query(fqdn, ) answer = dns.query.udp(request, nameserver, timeout, port) try: ips = [i.address for i in answer.answer[0].items] except IndexError...
Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1
3,523
def add_multiifo_input_list_opt(self, opt, inputs): self.add_raw_arg(opt) self.add_raw_arg() for infile in inputs: self.add_raw_arg(infile.ifo) self.add_raw_arg() self.add_raw_arg(infile.name) self.add_raw_arg() ...
Add an option that determines a list of inputs from multiple detectors. Files will be supplied as --opt ifo1:input1 ifo2:input2 .....
3,524
def watch_from_file(connection, file_name): with open(file_name, ) as filehandle: for line in filehandle.xreadlines(): volume, interval, retention = line.rstrip().split() watch( connection, get_volume_id(connection, volume), interv...
Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None
3,525
def plot_precision_recall_curve(y_true, y_probas, title=, curves=(, ), ax=None, figsize=None, cmap=, title_fontsize="large", text_fontsize="medium"): y...
Generates the Precision Recall Curve from labels and probabilities Args: y_true (array-like, shape (n_samples)): Ground truth (correct) target values. y_probas (array-like, shape (n_samples, n_classes)): Prediction probabilities for each class returned by a classifier. ...
3,526
def assign(self, value, termenc): if self._termenc != termenc: self._decoder = codecs.getincrementaldecoder(termenc)(errors=) self._termenc = termenc self._data = self._decoder.decode(value)
>>> scanner = DefaultScanner() >>> scanner.assign("01234", "ascii") >>> scanner._data u'01234'
3,527
def active_tcp(): * if __grains__[] == : return salt.utils.network.active_tcp() elif __grains__[] == : ret = {} for connection in _netstat_sunos(): if not connection[].startswith(): continue if connection[] != : continu...
Return a dict containing information on all of the running TCP connections (currently linux and solaris only) .. versionchanged:: 2015.8.4 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.active_tcp
3,528
def to_bool(s): if isinstance(s, bool): return s elif s.lower() in [, ]: return True elif s.lower() in [, ]: return False else: raise ValueError("Can%s' to bool" % (s))
Convert string `s` into a boolean. `s` can be 'true', 'True', 1, 'false', 'False', 0. Examples: >>> to_bool("true") True >>> to_bool("0") False >>> to_bool(True) True
3,529
def _update(self, layer=None): meta = getattr(self, ModelBase._meta_attr) if not layer: layers = self.layers else: layers = _listify(layer) for layer in layers: path = os.path.abspath(os.path.join(meta.modelpath, laye...
Update layers in model.
3,530
def cmd_set(context): if context.value in EFConfig.SPECIAL_VERSIONS and context.env_short not in EFConfig.SPECIAL_VERSION_ENVS: fail("special version: {} not allowed in env: {}".format(context.value, context.env_short)) if context.value in EFConfig.SPECIAL_VERSIONS and context.stable: fail("special...
Set the new "current" value for a key. If the existing current version and the new version have identical /value/ and /status, then nothing is written, to avoid stacking up redundant entreis in the version table. Args: context: a populated EFVersionContext object
3,531
def get_offset_range(self, row_offset, column_offset): return self._get_range(, rowOffset=row_offset, columnOffset=column_offset)
Gets an object which represents a range that's offset from the specified range. The dimension of the returned range will match this range. If the resulting range is forced outside the bounds of the worksheet grid, an exception will be thrown. :param int row_offset: The number of rows...
3,532
def Async(f, n=None, timeout=None): return threads(n=n, timeout=timeout)(f)
Concise usage for pool.submit. Basic Usage Asnyc & threads :: from torequests.main import Async, threads import time def use_submit(i): time.sleep(i) result = 'use_submit: %s' % i print(result) return result @threads() def...
3,533
def bus_inspector(self, bus, message): if message.get_interface() != self.screensaver_uri: return True member = message.get_member() if member in ("SessionIdleChanged", "ActiveChanged"): logger.debug("%s -> %s" % (member, message.get...
Inspect the bus for screensaver messages of interest
3,534
def _session(self): if self._http_session is None: self._http_session = requests.Session() self._http_session.headers.update(self._get_headers()) self._http_session.verify = self._verify_https_request() if all(self._credentials): username...
The current session used by the client. The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3's connection pooling. So if you're making several requests to the same h...
3,535
def tag_remove(self, *tags): return View({**self.spec, : list(set(self.tags) - set(tags))})
Return a view with the specified tags removed
3,536
def google_poem(self, message, topic): r = requests.get("http://www.google.com/complete/search?output=toolbar&q=" + topic + "%20") xmldoc = minidom.parseString(r.text) item_list = xmldoc.getElementsByTagName("suggestion") context = {"topic": topic, "lines": [x.attributes["data"]...
make a poem about __: show a google poem about __
3,537
def find_module(self, fullname, path=None): if fullname.startswith() and hasattr( maps, fullname.split()[2]): return self return None
Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module.
3,538
def savefig(writekey, dpi=None, ext=None): if dpi is None: if not isinstance(rcParams[], str) and rcParams[] < 150: if settings._low_resolution_warning: logg.warn( savefig.dpi\) settings._...
Save current figure to file. The `filename` is generated as follows: filename = settings.figdir + writekey + settings.plot_suffix + '.' + settings.file_format_figs
3,539
def set_mode(self, mode): keys = if mode == : pass elif mode == : keys += elif mode == : keys += elif mode == : keys += elif mode == : keys += else: raise ValueError(.format(mode...
Set *Vim* mode to ``mode``. Supported modes: * ``normal`` * ``insert`` * ``command`` * ``visual`` * ``visual-block`` This method behave as setter-only property. Example: >>> import headlessvim >>> with headlessvim.open() as vim: ...
3,540
def insert(self, tag, identifier, parent, data): if self.global_plate_definitions.contains(identifier): raise KeyError("Identifier {} already exists in tree".format(identifier)) self.global_plate_definitions.create_node(tag=tag, identifier=identifier, parent=parent, data=d...
Insert the given meta data into the database :param tag: The tag (equates to meta_data_id) :param identifier: The identifier (a combination of the meta_data_id and the plate value) :param parent: The parent plate identifier :param data: The data (plate value) :return: None
3,541
def _get_args_for_reloading(): rv = [sys.executable] py_script = sys.argv[0] if os.name == and not os.path.exists(py_script) and \ os.path.exists(py_script + ): py_script += rv.append(py_script) rv.extend(sys.argv[1:]) return rv
Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading.
3,542
def _validate_row_label(dataset, label=None, default_label=): if not label: if not dataset[label].dtype in (str, int): raise TypeError("Row labels must be integers or strings.") return dataset, label
Validate a row label column. If the row label is not specified, a column is created with row numbers, named with the string in the `default_label` parameter. Parameters ---------- dataset : SFrame Input dataset. label : str, optional Name of the column containing row labels. ...
3,543
def get_view_attr(view, key, default=None, cls_name=None): ns = view_namespace(view, cls_name) if ns: if ns not in _views_attr: return default return _views_attr[ns].get(key, default) return default
Get the attributes that was saved for the view :param view: object (class or instance method) :param key: string - the key :param default: mixed - the default value :param cls_name: str - To pass the class name associated to the view in the case of decorators that may not give the real class...
3,544
def add_columns(self, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], col_attrs: Dict[str, np.ndarray], *, row_attrs: Dict[str, np.ndarray] = None, fill_values: Dict[str, np.ndarray] = None) -> None: if self._file.mode != "r+": raise IOError("Cannot add columns when connected in read-only...
Add columns of data and attribute values to the dataset. Args: layers (dict or numpy.ndarray or LayerManager): Either: 1) A N-by-M matrix of float32s (N rows, M columns) in this case columns are added at the default layer 2) A dict {layer_name : matrix} specified so that the matrix (N, M) will be adde...
3,545
def unload(module): * ret = {} fmadm = _check_fmadm() cmd = .format( cmd=fmadm, module=module ) res = __salt__[](cmd) retcode = res[] result = {} if retcode != 0: result[] = res[] else: result = True return result
Unload specified fault manager module module: string module to unload CLI Example: .. code-block:: bash salt '*' fmadm.unload software-response
3,546
def _already_resized_on_flickr(self,fn,pid,_megapixels): logger.debug("%s - resize requested"%(fn)) width_flickr,height_flickr=self._getphoto_originalsize(pid) new_width,new_height=pusher_utils.resize_compute_width_height(\ fn,_megapixels) if wi...
Checks if image file (fn) with photo_id (pid) has already been resized on flickr. If so, returns True
3,547
def from_pubsec_file(cls: Type[SigningKeyType], path: str) -> SigningKeyType: with open(path, ) as fh: pubsec_content = fh.read() regex_pubkey = compile("pub: ([1-9A-HJ-NP-Za-km-z]{43,44})", MULTILINE) regex_signkey = compile("sec: ([1-9A-HJ-NP-Za-km-z]{88,90})", M...
Return SigningKey instance from Duniter WIF file :param path: Path to WIF file
3,548
def lml(self): reml = (self._logdetXX() - self._logdetH()) / 2 if self._optimal["scale"]: lml = self._lml_optimal_scale() else: lml = self._lml_arbitrary_scale() return lml + reml
Log of the marginal likelihood. Returns ------- lml : float Log of the marginal likelihood. Notes ----- The log of the marginal likelihood is given by :: 2⋅log(p(𝐲)) = -n⋅log(2π) - n⋅log(s) - log|D| - (Qᵀ𝐲)ᵀs⁻¹D⁻¹(Qᵀ𝐲) ...
3,549
def _send_request(self, enforce_json, method, raise_for_status, url, **kwargs): r = self.session.request(method, url, **kwargs) if raise_for_status: r.raise_for_status() if enforce_json: if in self.session.headers.get( , ...
Send HTTP request. Args: enforce_json (bool): Require properly-formatted JSON or raise :exc:`~pancloud.exceptions.PanCloudError`. Defaults to ``False``. method (str): HTTP method. raise_for_status (bool): If ``True``, raises :exc:`~pancloud.exceptions.HTTPError` if status...
3,550
def __set_private_key(self, pk): self.__private_key = pk self.__public_key = pk.public_key()
Internal method that sets the specified private key :param pk: private key to set :return: None
3,551
def setActiveState(self, active): st = DISABLED if active: st = NORMAL self.entry.configure(state=st) self.inputLabel.configure(state=st) self.promptLabel.configure(state=st)
Use this to enable or disable (grey out) a parameter.
3,552
def read_local_conf(local_conf): log = logging.getLogger(__name__) log.info(, local_conf) try: config = read_config(os.path.dirname(local_conf), ) except HandledError: log.warning() return dict() return {k[4:]: v for k, v in config.items() if k.startswith() a...
Search for conf.py in any rel_source directory in CWD and if found read it and return. :param str local_conf: Path to conf.py to read. :return: Loaded conf.py. :rtype: dict
3,553
def get_element_types(obj, **kwargs): max_iterable_length = kwargs.get(, 10000) consume_generator = kwargs.get(, False) if not isiterable(obj): return None if isgenerator(obj) and not consume_generator: return None t = get_types(obj, **kwargs) if not t[]: if t[]...
Get element types as a set.
3,554
def disconnect(self, forced=False): reversed_postorder = reversed(self.postorder()) self.log.debug( % \ (repr(self), repr(reversed_postorder))) for piper in reversed_postorder: if piper.connected:
Given the pipeline topology disconnects ``Pipers`` in the order output -> input. This also disconnects inputs. See ``Dagger.connect``, ``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True`` ``NuMap`` instances will be emptied. Arguments: - forced...
3,555
def data(self, **query): objects = self.cache[] data = self.api.data.get(**query)[] data_objects = [] for d in data: _id = d[] if _id in objects: objects[_id].update(d) else: o...
Query for Data object annotation.
3,556
def sshpull(host, maildir, localmaildir, noop=False, verbose=False, filterfile=None): store = _SSHStore(host, maildir) _pull(store, localmaildir, noop, verbose, filterfile)
Pull a remote maildir to the local one.
3,557
def add_zoom_buttons(viewer, canvas=None, color=): def zoom(box, canvas, event, pt, viewer, n): zl = viewer.get_zoom() zl += n if zl == 0.0: zl += n viewer.zoom_to(zl + n) def add_buttons(viewer, canvas, tag): objs = [] wd, ht = viewer.get_window...
Add zoom buttons to a canvas. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. canvas : a DrawingCanvas instance The canvas to which the buttons should be added. If not supplied defaults to the private canvas...
3,558
def to_json(obj): try: return json.dumps(obj, default=lambda obj: {k.lower(): v for k, v in obj.__dict__.items()}, sort_keys=False, separators=(, )).encode() except Exception as e: logger.info("to_json: ", e, obj)
Convert obj to json. Used mostly to convert the classes in json_span.py until we switch to nested dicts (or something better) :param obj: the object to serialize to json :return: json string
3,559
def simple_attention(memory, att_size, mask, keep_prob=1.0, scope="simple_attention"): with tf.variable_scope(scope): BS, ML, MH = tf.unstack(tf.shape(memory)) memory_do = tf.nn.dropout(memory, keep_prob=keep_prob, noise_shape=[BS, 1, MH]) logits = tf.layers.dense(tf.layers.dense(memory...
Simple attention without any conditions. Computes weighted sum of memory elements.
3,560
def default_styles(): styles = {} def _add_style(name, **kwargs): styles[name] = _create_style(name, **kwargs) _add_style(, family=, fontsize=, fontweight=, ) _add_style(, family=, fontsize=, ...
Generate default ODF styles.
3,561
def build_parser(self, context): context.parser, context.max_level = self._create_parser(context)
Create the final argument parser. This method creates the non-early (full) argparse argument parser. Unlike the early counterpart it is expected to have knowledge of the full command tree. This method relies on ``context.cmd_tree`` and produces ``context.parser``. Other ingredi...
3,562
def resolve_response_data(head_key, data_key, data): new_data = [] if isinstance(data, list): for data_row in data: if head_key in data_row and data_key in data_row[head_key]: if isinstance(data_row[head_key][data_key], list): ...
Resolves the responses you get from billomat If you have done a get_one_element request then you will get a dictionary If you have done a get_all_elements request then you will get a list with all elements in it :param head_key: the head key e.g: CLIENTS :param data_key: the data key e....
3,563
def uncomment_or_update_or_append_line(filename, prefix, new_line, comment=, keep_backup=True, update_or_append_line=update_or_append_line): uncommented = update_or_append_line(filename, prefix=comment+prefix, ...
Remove the comment of an commented out line and make the line "active". If such an commented out line not exists it would be appended.
3,564
def autocorrect(query, possibilities, delta=0.75): possibilities = [possibility.lower() for possibility in possibilities] return matches[0]
Attempts to figure out what possibility the query is This autocorrect function is rather simple right now with plans for later improvement. Right now, it just attempts to finish spelling a word as much as possible, and then determines which possibility is closest to said word. Args: query (un...
3,565
def _filter_by_moys_slow(self, moys): _filt_values = [] _filt_datetimes = [] for i, d in enumerate(self.datetimes): if d.moy in moys: _filt_datetimes.append(d) _filt_values.append(self._values[i]) return _filt_values, _filt_datetimes
Filter the Data Collection with a slow method that always works.
3,566
def run_linters(files): data = {} for file_type, file_list in list(files.items()): linter = LintFactory.get_linter(file_type) if linter is not None: data[file_type] = linter.run(file_list) return data
Run through file list, and try to find a linter that matches the given file type. If it finds a linter, it will run it, and store the resulting data in a dictionary (keyed to file_type). :param files: :return: {file_extension: lint_data}
3,567
def query_relations(self, environment_id, collection_id, entities=None, context=None, sort=None, filter=None, count=None, eviden...
Knowledge Graph relationship query. See the [Knowledge Graph documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-kg#kg) for more details. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :...
3,568
def patch(self, *args, **kwargs): return super(Deposit, self).patch(*args, **kwargs)
Patch only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved.
3,569
def _CheckCollation(cursor): cur_collation_connection = _ReadVariable("collation_connection", cursor) if cur_collation_connection != COLLATION: logging.warning("Require MySQL collation_connection of %s, got %s.", COLLATION, cur_collation_connection) cur_collation_datab...
Checks MySQL collation and warns if misconfigured.
3,570
def built_datetime(self): from datetime import datetime try: return datetime.fromtimestamp(self.state.build_done) except TypeError: return None
Return the built time as a datetime object
3,571
def add_minutes(self, datetimestr, n): a_datetime = self.parse_datetime(datetimestr) return a_datetime + timedelta(seconds=60 * n)
Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。
3,572
def merge_ids(self, token, channel, ids, delete=False): url = self.url() + "/merge/{}/".format(.join([str(i) for i in ids])) req = self.remote_utils.get_url(url) if req.status_code is not 200: raise RemoteDataUploadError(.format( .join...
Call the restful endpoint to merge two RAMON objects into one. Arguments: token (str): The token to inspect channel (str): The channel to inspect ids (int[]): the list of the IDs to merge delete (bool : False): Whether to delete after merging. Returns: ...
3,573
def get_ttext(value): m = _non_token_end_matcher(value) if not m: raise errors.HeaderParseError( "expected ttext but found ".format(value)) ttext = m.group() value = value[len(ttext):] ttext = ValueTerminal(ttext, ) _validate_xtext(ttext) return ttext, value
ttext = <matches _ttext_matcher> We allow any non-TOKEN_ENDS in ttext, but add defects to the token's defects list if we find non-ttext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322.
3,574
def _add_secondary_if_exists(secondary, out, get_retriever): secondary = [_file_local_or_remote(y, get_retriever) for y in secondary] secondary = [z for z in secondary if z] if secondary: out["secondaryFiles"] = [{"class": "File", "path": f} for f in secondary] return out
Add secondary files only if present locally or remotely.
3,575
def Chen_Friedel(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0, L=1): r v_lo = m/rhol/(pi/4*D**2) Re_lo = Reynolds(V=v_lo, rho=rhol, mu=mul, D=D) fd_lo = friction_factor(Re=Re_lo, eD=roughness/D) dP_lo = fd_lo*L/D*(0.5*rhol*v_lo**2) v_go = m/rhog/(pi/4*D**2) Re_go = Reynolds(V...
r'''Calculates two-phase pressure drop with the Chen modification of the Friedel correlation, as given in [1]_ and also shown in [2]_ and [3]_. .. math:: \Delta P = \Delta P_{Friedel}\Omega For Bo < 2.5: .. math:: \Omega = \frac{0.0333Re_{lo}^{0.45}}{Re_g^{0.09}(1 + 0.4\exp(-Bo))} ...
3,576
def verify_files(files, user): if salt.utils.platform.is_windows(): return True import pwd try: pwnam = pwd.getpwnam(user) uid = pwnam[2] except KeyError: err = ( ).format(user) sys.stderr.write(err) sys.exit(salt.defaults.exitcodes.E...
Verify that the named files exist and are owned by the named user
3,577
def session(self): if not self.__session: self.__session = dal.get_default_session() return self.__session
Returns the current db session
3,578
def contains_remove(self, item): try: self._lens_contains_remove except AttributeError: message = t know how to remove an item from {}' raise NotImplementedError(message.format(type(self))) else: return self._lens_contains_remove(item)
Takes a collection and an item and returns a new collection of the same type with that item removed. The notion of "contains" is defined by the object itself; the following must be ``True``: .. code-block:: python item not in contains_remove(obj, item) This function is used by some lenses (pa...
3,579
def load_instackenv(self): self.add_environment_file(user=, filename=) self.run(, user=) ironic_node_nbr = 0 count_cmd = for f in [, ]: try: ironic_node_nbr = int( self.run(count_cmd.format(filter=f), user=)[0]) ...
Load the instackenv.json file and wait till the ironic nodes are ready. TODO(Gonéri): should be splitted, write_instackenv() to generate the instackenv.json and instackenv_import() for the rest.
3,580
def get_dataset(self, key, info): if self._polarization != key.polarization: return logger.debug(, key.name) if key.name in [, ]: logger.debug() if self.lons is None or self.lats is None: self.lons, self.lats, self.alts = self.get_l...
Load a dataset.
3,581
def get_summary(self): return (self.contract.name, self.full_name, self.visibility, [str(x) for x in self.modifiers], [str(x) for x in self.state_variables_read + self.solidity_variables_read], [str(x) for x in self.state_variables_written], ...
Return the function summary Returns: (str, str, str, list(str), list(str), listr(str), list(str), list(str); contract_name, name, visibility, modifiers, vars read, vars written, internal_calls, external_calls_as_expressions
3,582
def branches(self): local_branches = self.repo.branches data = [[x.name, True] for x in list(local_branches)] remote_branches = self.repo.git.branch(all=True).split() if sys.version_info.major == 2: remote_branches = set([x.split()[-1] for x in re...
Returns a data frame of all branches in origin. The DataFrame will have the columns: * repository * branch * local :returns: DataFrame
3,583
def return_values_ssa(self): from slither.core.cfg.node import NodeType from slither.slithir.operations import Return from slither.slithir.variables import Constant if self._return_values_ssa is None: return_values_ssa = list() returns = [n for n in self...
list(Return Values in SSA form): List of the return values in ssa form
3,584
def compute_geometric_median(X, eps=1e-5): y = np.mean(X, 0) while True: D = scipy.spatial.distance.cdist(X, [y]) nonzeros = (D != 0)[:, 0] Dinv = 1 / D[nonzeros] Dinvs = np.sum(Dinv) W = Dinv / Dinvs T = np.sum(W * X[nonzeros], 0) num_zeros = len(...
Estimate the geometric median of points in 2D. Code from https://stackoverflow.com/a/30305181 Parameters ---------- X : (N,2) ndarray Points in 2D. Second axis must be given in xy-form. eps : float, optional Distance threshold when to return the median. Returns ------- ...
3,585
def normalizeGroupValue(value): if not isinstance(value, (tuple, list)): raise TypeError("Group value must be a list, not %s." % type(value).__name__) value = [normalizeGlyphName(v) for v in value] return tuple([unicode(v) for v in value])
Normalizes group value. * **value** must be a ``list``. * **value** items must normalize as glyph names with :func:`normalizeGlyphName`. * Returned value will be a ``tuple`` of unencoded ``unicode`` strings.
3,586
def recommendations(self, **kwargs): path = self._get_id_path() response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get a list of recommended movies for a movie. Args: language: (optional) ISO 639-1 code. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict representation of the JSON returned from the API.
3,587
def emit(self, record): if record.name.startswith(): return data, header = self._prepPayload(record) try: self.session.post(self._getEndpoint(), data=data, headers={: header}) except E...
Override emit() method in handler parent for sending log to RESTful API
3,588
def _nested_cwl_record(xs, want_attrs, input_files): if isinstance(xs, (list, tuple)): return [_nested_cwl_record(x, want_attrs, input_files) for x in xs] else: assert isinstance(xs, dict), pprint.pformat(xs) return _collapse_to_cwl_record_single(xs, want_attrs, input_files)
Convert arbitrarily nested samples into a nested list of dictionaries. nests only at the record level, rather than within records. For batching a top level list is all of the batches and sub-lists are samples within the batch.
3,589
def parse(self, response): content_raw = response.body.decode() self.logger.debug(.format(content_raw)) content = json.loads(content_raw, encoding=) self.logger.debug(content) date = datetime.datetime.strptime(content[], ) strftime = date.strftime("%Y-...
根据对 ``start_urls`` 中提供链接的请求响应包内容,解析生成具体文章链接请求 :param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象
3,590
def __set_window_title(self): if self.has_editor_tab(): windowTitle = "{0} - {1}".format(self.__default_window_title, self.get_current_editor().file) else: windowTitle = "{0}".format(self.__default_window_title) LOGGER.debug("> Setting window title to .".forma...
Sets the Component window title.
3,591
def from_scf_task(cls, scf_task, ddk_tolerance=None, ph_tolerance=None, manager=None): new = cls(manager=manager) new.add_becs_from_scf_task(scf_task, ddk_tolerance, ph_tolerance) return new
Build tasks for the computation of Born effective charges from a ground-state task. Args: scf_task: ScfTask object. ddk_tolerance: tolerance used in the DDK run if with_becs. None to use AbiPy default. ph_tolerance: dict {"varname": value} with the tolerance used in the phon...
3,592
def estimate_clock_model(params): if assure_tree(params, tmp_dir=): return 1 dates = utils.parse_dates(params.dates) if len(dates)==0: return 1 outdir = get_outdir(params, ) aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else...
implementing treetime clock
3,593
def approx(x, y, xout, method=, rule=1, f=0, yleft=None, yright=None, ties=): if method not in VALID_APPROX: raise ValueError( % VALID_APPROX) xout = c(xout).astype(np.float64) method_key = method method = get_callable(method_key, VALID_APPROX) x, y ...
Linearly interpolate points. Return a list of points which (linearly) interpolate given data points, or a function performing the linear (or constant) interpolation. Parameters ---------- x : array-like, shape=(n_samples,) Numeric vector giving the coordinates of the points to be i...
3,594
def add_peer(self, peer_addr): "Build a connection to the Hub at a given ``(host, port)`` address" peer = connection.Peer( self._ident, self._dispatcher, peer_addr, backend.Socket()) peer.start() self._started_peers[peer_addr] = peer
Build a connection to the Hub at a given ``(host, port)`` address
3,595
def main(): org = Organization(name=).create() pprint(org.get_values()) org.delete()
Create an organization, print out its attributes and delete it.
3,596
def subscribe_to_address_webhook(callback_url, subscription_address, event=, confirmations=0, confidence=0.00, coin_symbol=, api_key=None): assert is_valid_coin_symbol(coin_symbol) assert is_valid_address_for_coinsymbol(subscription_address, coin_symbol) assert api_key, url = make_url(coin_symbol...
Subscribe to transaction webhooks on a given address. Webhooks for transaction broadcast and each confirmation (up to 6). Returns the blockcypher ID of the subscription
3,597
def logs(ctx, services, num, follow): logger.debug("running command %s (%s)", ctx.command.name, ctx.params, extra={"command": ctx.command.name, "params": ctx.params}) home = ctx.obj["HOME"] services_path = os.path.join(home, SERVICES) tail_threads = [] for service in services...
Show logs of daemonized service.
3,598
def purge(self): try: self._device.setblocking(0) while(self._device.recv(1)): pass except socket.error as err: pass finally: self._device.setblocking(1)
Purges read/write buffers.
3,599
def update_type_lookups(self): self.type_to_typestring = dict(zip(self.types, self.python_type_strings)) self.typestring_to_type = dict(zip(self.python_type_strings, self.types))
Update type and typestring lookup dicts. Must be called once the ``types`` and ``python_type_strings`` attributes are set so that ``type_to_typestring`` and ``typestring_to_type`` are constructed. .. versionadded:: 0.2 Notes ----- Subclasses need to call this f...