Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
346,200
def split_in_pairs(arg: Iterable) -> Iterable[Tuple]: iterator = iter(arg) return zip_longest(iterator, iterator)
Split given iterable in pairs [a, b, c, d, e] -> [(a, b), (c, d), (e, None)]
346,201
def _handle_posix_error(exc, cwd, cmd): if getattr(exc, , None) == cwd: _handle_posix_cwd_error(exc, cwd, cmd) else: _handle_posix_cmd_error(exc, cwd, cmd)
OSError handling for posix systems. Some things that could happen to trigger an OSError: - cwd could not exist - exc.errno == ENOENT - exc.filename == cwd - cwd could have permissions that prevent the current user moving to it - exc.errno == EACCES - ...
346,202
def dump_pytorch_graph(graph): f = "{:25} {:40} {} -> {}" print(f.format("kind", "scopeName", "inputs", "outputs")) for node in graph.nodes(): print(f.format(node.kind(), node.scopeName(), [i.unique() for i in node.inputs()], [i.unique() for i in ...
List all the nodes in a PyTorch graph.
346,203
def runnable(args): w = fapi.get_workspace(args.project, args.workspace) fapi._check_response_code(w, 200) workspace_d = w.json() if args.config and args.namespace and not args.entity: r = fapi.validate_config(args.project, args.workspace, args.namespace, ...
Show me what can be run in a given workspace
346,204
def generate_totp(secret, period=30, timestamp=None): if timestamp is None: timestamp = time.time() counter = int(timestamp) // period return generate_hotp(secret, counter)
Generate a TOTP code. A TOTP code is an extension of HOTP algorithm. :param secret: A secret token for the authentication. :param period: A period that a TOTP code is valid in seconds :param timestamp: Current time stamp.
346,205
def write(self, output=, flush=True, position=0): if self.enabled: term = self.term stream = self.stream try: term.move_to(0, term.height - position) if NEEDS_UNICODE_HELP: encoding = stream.en...
Args: output(str: Output string flush(bool): Flush the output stream after writing position(int): Position relative to the bottom of the screen to write output Write to stream at a given position
346,206
def parse_digest_challenge(authentication_header): WWW-Authenticate if not is_digest_challenge(authentication_header): return None parts = parse_parts(authentication_header[7:], defaults={: , : }) if not _check_required_parts(parts, _...
Parses the value of a 'WWW-Authenticate' header. Returns an object with properties corresponding to each of the recognized parameters in the header.
346,207
def x10_housecode(self): housecode = None if self.is_x10: housecode = insteonplm.utils.byte_to_housecode(self.addr[1]) return housecode
Emit the X10 house code.
346,208
def _write_to_hdx(self, action, data, id_field_name, file_to_upload=None): file = None try: if file_to_upload: file = open(file_to_upload, ) files = [(, file)] else: files = None return self.configurati...
Creates or updates an HDX object in HDX and return HDX object metadata dict Args: action (str): Action to perform eg. 'create', 'update' data (Dict): Data to write to HDX id_field_name (str): Name of field containing HDX object identifier or None file_to_upload (...
346,209
def FormattedTable(self, width=80, force_display=False, ml_delimiter=True, color=True, display_header=True, columns=None): def _FilteredCols(): if not columns: return self._Header().values return [col for col in self._Header().values if col in columns] ...
Returns whole table, with whitespace padding and row delimiters. Args: width: An int, the max width we want the table to fit in. force_display: A bool, if set to True will display table when the table can't be made to fit to the width. ml_delimiter: A bool, if set to False will not disp...
346,210
def list_upgrades(jid, style=, outputter=, ext_source=None): mminion = salt.minion.MasterMinion(__opts__) returner = _get_returner(( __opts__[], ext_source, __opts__[] )) data = mminion.returners[.format(returner)](jid) ...
Show list of available pkg upgrades using a specified format style CLI Example: .. code-block:: bash salt-run pkg.list_upgrades jid=20141120114114417719 style=group
346,211
def move_config(name, xpath=None, where=None, dst=None, commit=False): vsys1rule1vsys1rule1 ret = _default_ret(name) if not xpath: return ret if not where: return ret if where == : result, msg = _move_after(xpath, dst) elif where == : result, msg = _move_before...
Moves a XPATH value to a new location. Use the xpath parameter to specify the location of the object to be moved, the where parameter to specify type of move, and dst parameter to specify the destination path. name: The name of the module function to execute. xpath(str): The XPATH of the configuratio...
346,212
def is_numerical(tg_type, inc_array=False): global _scalar_numerical_types, _array_numerical_types if tg_type in _scalar_numerical_types: return True if not inc_array: return False return tg_type in _array_numerical_types
Tells if the given tango type is numerical :param tg_type: tango type :type tg_type: :class:`tango.CmdArgType` :param inc_array: (optional, default is False) determines if include array in the list of checked types :type inc_array: :py:obj:`bool` :return: True if the given ta...
346,213
def make_unpublished(self, request, queryset): rows_updated = queryset.update(is_published=False) self.message_user(request, ungettext(, , rows_updated) % {: rows_updated})
Marks selected news items as unpublished
346,214
def moveTo(x=None, y=None, duration=0.0, tween=linear, pause=None, _pause=True): _failSafeCheck() x, y = _unpackXY(x, y) _mouseMoveDrag(, x, y, 0, 0, duration, tween) _autoPause(pause, _pause)
Moves the mouse cursor to a point on the screen. The x and y parameters detail where the mouse event happens. If None, the current mouse position is used. If a float value, it is rounded down. If outside the boundaries of the screen, the event happens at edge of the screen. Args: x (int, flo...
346,215
def read(source, channels, start=None, end=None, scaled=None, type=None, series_class=TimeSeries): source = file_list(source) ctype = channel_dict_kwarg(type, channels, (str,)) out = series_class.DictClass() for i, file_ in enumerate(source): if i == 1: ...
Read a dict of series from one or more GWF files Parameters ---------- source : `str`, `list` Source of data, any of the following: - `str` path of single data file, - `str` path of cache file, - `list` of paths. channels : `~gwpy.detector.ChannelList`, `list` ...
346,216
def _decode_filename(base_filename, problem_name, decode_hp): if decode_hp.shards > 1: base_filename = _add_shard_to_filename(base_filename, decode_hp) if ("beam{beam}.alpha{alpha}.decodes".format( beam=str(decode_hp.beam_size), alpha=str(decode_hp.alpha)) in base_filename): return base_filen...
Generates decode filename. Args: base_filename: A string, base of the decode filename. problem_name: A string, name of the problem. decode_hp: HParams for decoding. Returns: A string, produced decode filename.
346,217
def get_items(self): ils = get_item_lookup_session(runtime=self._runtime, proxy=self._proxy) ils.use_federated_bank_view() items = [] if self.has_items(): for idstr in self._my_map[]: items.append(ils.get_item(Id(idstr))) return ItemList(items...
This is out of spec, but required for adaptive assessment parts?
346,218
def send_contact(chat_id, phone_number, first_name, last_name=None, reply_to_message_id=None, reply_markup=None, disable_notification=False, **kwargs): params = dict( chat_id=chat_id, phone_number=phone_number, first_name=first_name, ) ...
Use this method to send phone contacts. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param phone_number: Contact's phone number. :param first_name: Contact's first name. :param last_name: Contact's last name. :param reply...
346,219
def isAboveHorizon(ra, decl, mcRA, lat): dArc, _ = dnarcs(decl, lat) dist = abs(angle.closestdistance(mcRA, ra)) return dist <= dArc/2.0 + 0.0003
Returns if an object's 'ra' and 'decl' is above the horizon at a specific latitude, given the MC's right ascension.
346,220
def interruptRead(self, endpoint, size, timeout = 100): r return self.dev.read(endpoint, size, timeout)
r"""Performs a interrupt read request to the endpoint specified. Arguments: endpoint: endpoint number. size: number of bytes to read. timeout: operation timeout in milliseconds. (default: 100) Returns a tuple with the data read.
346,221
def generate(module_name, code): try: ast_tree = ast.parse(code) except Exception: raise RuntimeError() visitor = SearchSpaceGenerator(module_name) try: visitor.visit(ast_tree) except AssertionError as exc: raise RuntimeError( % (visitor.last_line, exc.args[0]))...
Generate search space. Return a serializable search space object. module_name: name of the module (str) code: user code (str)
346,222
def remove(self, repo): rem_repo = False with open(self.custom_repo_file, "w") as repos: for line in self.custom_repositories_list.splitlines(): repo_name = line.split()[0] if repo_name != repo: repos.write(line + "\n") ...
Remove custom repository
346,223
def namedItem(self, name: str) -> Optional[Node]: for n in self: if n.getAttribute() == name: return n for n in self: if n.getAttribute() == name: return n return None
TODO.
346,224
def process_item(self, item): group, value = item[], item[] if group in self._groups: cur_val = self._groups[group] self._groups[group] = max(cur_val, value) else: self._src.tracking = False new_max...
Calculate new maximum value for each group, for "new" items only.
346,225
def gen_key(self, key): b_key = self._hash_digest(key) return self._hash_val(b_key, lambda x: x)
Given a string key it returns a long value, this long value represents a place on the hash ring. md5 is currently used because it mixes well.
346,226
def generate_jobs(args, job_list, argument_string): mvtest_path = args.mvpath template = "".join(args.template.readlines()) logpath = os.path.abspath(args.logpath) respath = os.path.abspath(args.res_path) scriptpath = os.path.abspath(args.script_path) pwd = os.path.abspath(os.getcwd()) ...
Generate actual scripts to be submitted to the cluster :param args: argparse argument collection :param job_list: dictionary containing each each job to be submitted :param argument_string: string containing general arguments to be used by mvtest.py during execution :return: None
346,227
def interpolate_data(self, data, limit, method): data = data.interpolate(how="index", limit=limit, method=method) return data
Interpolate dataframe. Parameters ---------- data : pd.DataFrame() Dataframe to interpolate limit : int Interpolation limit. method : str Interpolation method. Returns ------- pd.DataFrame() Dataframe...
346,228
def exit(exit_code=0): r core.processExitHooks() if state.isExitHooked and not hasattr(sys, ): sys.stderr.flush() sys.stdout.flush() os._exit(exit_code) sys.exit(exit_code)
r"""A function to support exiting from exit hooks. Could also be used to exit from the calling scripts in a thread safe manner.
346,229
def bip32(self, s): s = parseable_str(s) return self.bip32_prv(s) or self.bip32_pub(s)
Parse a bip32 public key from a text string, either a seed, a prv or a pub. Return a :class:`BIP32 <pycoin.key.BIP32Node.BIP32Node>` or None.
346,230
def get_namespace_hash(self, hash_fn=hashlib.md5) -> str: m = hash_fn() if self.has_names: items = self._get_namespace_name_to_encoding(desc=).items() else: items = self._get_namespace_identifier_to_encoding(desc=).items() for name, encoding in items: ...
Get the namespace hash. Defaults to MD5.
346,231
def digest(self, data, mecha=MechanismSHA1): digest = ckbytelist() m = mecha.to_native() data1 = ckbytelist(data) rv = self.lib.C_DigestInit(self.session, m) if rv != CKR_OK: raise PyKCS11Error(rv) rv = self.lib.C_Digest(self.session, data1, ...
C_DigestInit/C_Digest :param data: the data to be digested :type data: (binary) sring or list/tuple of bytes :param mecha: the digesting mechanism to be used (use `MechanismSHA1` for `CKM_SHA_1`) :type mecha: :class:`Mechanism` :return: the computed digest :rt...
346,232
def a_standby_console(ctx): ctx.device.is_console = True ctx.ctrl.disconnect() raise ConnectionError("Standby console", ctx.ctrl.hostname)
Raise ConnectionError exception when connected to standby console.
346,233
def repl(): try: import IPython except: print("ERROR: IPython is not installed. Please install it to use the repl.", file=sys.stderr) raise IPython.embed(user_ns=dict( settings=oz.settings, actions=oz._actions, uimodules=oz._uimodules, routes=oz...
Runs an IPython repl with some context
346,234
def parse(self): self.parse_fields() records = [] for line in self.t[].split(): if EMPTY_ROW.match(line): continue row = [self.autoconvert(line[start_field:end_field+1]) for start_field, end_field in self.fields] re...
Parse the table data string into records.
346,235
def convert_value_to_code(M_c, cidx, value): if M_c[][cidx][] == : return float(value) else: return M_c[][cidx][][str(value)]
For a column with categorical data, this function takes the raw value (e.g. 'Joe' or 234.23409), which is always encoded as a string, and returns the 'code': the integer used to represent that value in the underlying representation. Note that the underlying store 'code_to_value' is unfortunately named back...
346,236
def run_HTM_false_positive_experiment_synapses(num_neurons = 1, a = 512, dim = 16000, num_samples = 1000, num_dendrites = 500, test_dendrite_lengths = range(2, 32, 2), nu...
Run an experiment to test the false positive rate based on number of synapses per dendrite, dimension and sparsity. Uses a single neuron, with a threshold nonlinearity of theta = s/2. Based on figure 5B in the original SDR paper. The parameters used in generating the figure for this experiment are: 1. a =...
346,237
def read_http(self, length): _plen = self._read_binary(3) _type = self._read_unpack(1) _flag = self._read_binary(1) _stid = self._read_binary(4)
Read Hypertext Transfer Protocol version 2. Structure of HTTP/2 packet [RFC 7230]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+---------------+ | Type (8) | Flags (8) ...
346,238
def _load_plugins(self): try: __import__() except ImportError as exc: raise errors.PluginImport(unicode(exc)) try: user_plugin_dir = os.path.join(self._data_dir, ) _import_modules(user_plugin_dir) ...
Attempts to load plugin modules according to the order of available plugin directories.
346,239
def score(self, features, class_labels, scoring_function=None, **scoring_function_kwargs): if self.feature_map is None: raise ValueError() new_feature = self.predict(features) if scoring_function is None: return accuracy_score(class_labels, new_feature) ...
Estimates the accuracy of the predictions from the constructed feature. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to predict from class_labels: array-like {n_samples} List of true class labels Returns -----...
346,240
def get_sha1_signature(token, timestamp, nonce, encrypt): try: sortlist = [token, timestamp, nonce, to_binary(encrypt)] sortlist.sort() sha = hashlib.sha1() sha.update(to_binary("").join(sortlist)) return sha.hexdigest() except Exception as e: raise CryptoCo...
用 SHA1 算法生成安全签名 @param token: 票据 @param timestamp: 时间戳 @param encrypt: 密文 @param nonce: 随机字符串 @return: 安全签名
346,241
def get_bucket(config, bucket_name=None): if not bucket_name: if not in config: raise ConfigurationError( ) bucket_name = config[] aws_access_key_id_path = config.get() aws_secret_access_key_path = config.get() params = () if aws_access_k...
This function is mostly about managing configuration, and then finally returns a boto.Bucket object. AWS credentials come first from config keys aws_access_key_id_path, aws_secret_access_key_path (paths to one line files); secondly from environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY...
346,242
def _format_repo_args(comment=None, component=None, distribution=None, uploaders_file=None, saltenv=): ret = list() cached_uploaders_path = None settings = {: comment, : component, : distribution} if uploaders_file: cached_uploaders_path = __salt__[](u...
Format the common arguments for creating or editing a repository. :param str comment: The description of the repository. :param str component: The default component to use when publishing. :param str distribution: The default distribution to use when publishing. :param str uploaders_file: The repositor...
346,243
def matthewscc(self, use_global=False): if use_global: if not self.global_total_examples: return 0. true_pos = float(self.global_true_positives) false_pos = float(self.global_false_positives) false_neg = float(self.global_false_negatives)...
Calculate the Matthew's Correlation Coefficent
346,244
def init_console_logging(conf): console = find_console_handler(logging.getLogger()) if not console: console = logging.StreamHandler() logging_level = log_level(conf) console.setLevel(logging_level) formatter = _get_debug_formatter(conf) console.setFormatter(formatter...
Log to console.
346,245
def _list(self, foldername="INBOX", reverse=False, since=None): folder = self.folder \ if foldername == "INBOX" \ else self._getfolder(foldername) def sortcmp(d): try: return d[1].date except: return -1 ls...
Do structured list output. Sorts the list by date, possibly reversed, filtered from 'since'. The returned list is: foldername, message key, message object
346,246
def max(self, array, role = None): return self.reduce(array, reducer = np.maximum, neutral_element = - np.infty, role = role)
Return the maximum value of ``array`` for the entity members. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into account. Example: >>> salaries = household.mem...
346,247
def _discover_sensitivity(self, seen) -> None: assert self._sensitivity is None, self ctx = self._sensitivity = SensitivityCtx() casual_sensitivity = set() self.switchOn._walk_sensitivity(casual_sensitivity, seen, ctx) if ctx.contains_ev_dependency: raise Hw...
Doc on parent class :meth:`HdlStatement._discover_sensitivity`
346,248
def update_kwargs(kwargs, **keyvalues): for key, value in keyvalues.items(): if key not in kwargs: kwargs[key] = value
Update dict with keys and values if keys do not already exist. >>> kwargs = {'one': 1, } >>> update_kwargs(kwargs, one=None, two=2) >>> kwargs == {'one': 1, 'two': 2} True
346,249
def agent_color(self, val): if val == : colour = elif val == : colour = elif val == : colour = elif val == : colour = elif val == : colour = elif val == : colour = elif val == ...
gets a colour for agent 0 - 9
346,250
def predict(self, df_data, threshold=0.05, **kwargs): nb_jobs = kwargs.get("nb_jobs", SETTINGS.NB_JOBS) list_nodes = list(df_data.columns.values) if nb_jobs != 1: result_feature_selection = Parallel(n_jobs=nb_jobs)(delayed(self.run_feature_selection) ...
Predict the skeleton of the graph from raw data. Returns iteratively the feature selection algorithm on each node. Args: df_data (pandas.DataFrame): data to construct a graph from threshold (float): cutoff value for feature selection scores kwargs (dict): additional...
346,251
def dispatk(keyer): calls = {} def _dispatk(main): def register(*keys): def _register(spec): for key in keys: if key in calls: raise ValueError( "function already registered for %r" ...
This is the decorator for the generic function and it accepts only one argument *keyer*, it'll be called with the same arguments of the function call and it must return an hashable object (int, tuple, etc.). Rhe generic function has a *register* method used to decorate the function for some specifi...
346,252
def _is_used_deprecated(self): func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, ) or self._globals[].split()[-1], f_name=self._orig_f_name) return func_path in self._globals.get().get( self.CFG_USE_DEPRECATED, list()) or fun...
Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return:
346,253
def from_path(cls, path: pathlib.Path) -> : if not path.is_file(): raise ValueError() return File(path.name, path.stat().st_size, cls._md5(path))
Create a file entity from a file path. :param path: The path of the file. :return: A file entity instance representing the file. :raises ValueError: If the path does not point to a file.
346,254
def qteDisconnectHook(self, hookName: str, slot: (types.FunctionType, types.MethodType)): reg = self._qteRegistryHooks if hookName not in reg: msg = self.qteLogger.info(msg.format(hookName)) return False ...
Disconnect ``slot`` from ``hookName``. If ``hookName`` does not exist, or ``slot`` is not connected to ``hookName`` then return **False**, otherwise disassociate ``slot`` with ``hookName`` and return **True**. |Args| * ``hookName`` (**str**): name of the hook. * ``slot...
346,255
def deserialize_transaction(tx_hex): tx = bitcoin.deserialize(str(tx_hex)) inputs = tx["ins"] outputs = tx["outs"] ret_inputs = [] ret_outputs = [] for inp in inputs: ret_inp = { "transaction_hash": inp["outpoint"]["hash"], "output_index": int(inp["outpoi...
Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig: string Each output will have: * value: int ...
346,256
def _add_rhoa(df, spacing): df[] = redaK.compute_K_analytical(df, spacing=spacing) df[] = df[] * df[] if in df.columns: df[] = df[] * df[] return df
a simple wrapper to compute K factors and add rhoa
346,257
def getmembers(object, predicate=None): results = [] for key in dir(object): value = getattr(object, key) if not predicate or predicate(value): results.append((key, value)) results.sort() return results
Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.
346,258
def on_config(self, config): "Fetch the variables and functions" self._variables = config.get(YAML_SUBSET) module_reader.load_variables(self._variables, config) print("Variables:", self.variables)
Fetch the variables and functions
346,259
def _volume(shape): prod = 1 for start, stop in shape: prod *= stop - start return prod
Return the volume of a shape.
346,260
def computeAccuracyEnding(predictions, truths, iterations, resets=None, randoms=None, num=None, sequenceCounter=None): accuracy = [] numIteration = [] numSequences = [] for i in xrange(len(predictions) - 1): if num is not None and i > num: continue if t...
Compute accuracy on the sequence ending
346,261
def all_api_methods(cls): return [ fn for fn in itervalues(vars(cls)) if getattr(fn, , False) ]
Return a list of all the TradingAlgorithm API methods.
346,262
def get_application_instance(): instance = QApplication.instance() if not instance: instance = QApplication(sys.argv) return instance
Returns the current `QApplication <http://doc.qt.nokia.com/qapplication.html>`_ instance or create one if it doesn't exists. :return: Application instance. :rtype: QApplication
346,263
def _get_regex_search(input_string, regex, metadata={}, match_index=None, ignore=, flags=0): generator = re.compile(regex, flags=flags).finditer(input_string) matches = [] for obj in generator: try: span_a = obj.span(1) group_a = obj.group(1) ...
Using this so that all results from the functions return similar results :param input_string: str, input string to be checked :param regex: str, input regex to be compiled and searched with :param match_index: (int, None), whether to get a specific match, if None returns all matches as list ...
346,264
def _calcEnergyBendStretchTwist(self, diff, es, which): r if which not in self.enGlobalTypes: raise ValueError(.format( which, self.enGlobalTypes)) energy = None if which == : temp = np.matrix(diff) energy = 0.5 * ((temp * es) * temp...
r"""Calculate energy for ``esType='BST'`` using a difference vector. It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame. Parameters ---------- diff : numpy.ndarray Array of difference between minimum and current parameter values. ...
346,265
def error_message(self, message, fh=None, prefix="[error]:", suffix="..."): msg = prefix + message + suffix fh = fh or sys.stderr if fh is sys.stderr: termcolor.cprint(msg, color="red") else: fh.write(msg) pass
print error type message if file handle is `sys.stderr`, print color message :param str message: message to print :param file fh: file handle, default is `sys.stdout` :param str prefix: message prefix,default is `[error]` :param str suffix: message suffix ,default is '...' ...
346,266
def from_dynacRepr(cls, pynacRepr): L = float(pynacRepr[1][0][0]) B = float(pynacRepr[1][0][1]) aperRadius = float(pynacRepr[1][0][2]) return cls(L, B, aperRadius)
Construct a ``Quad`` instance from the Pynac lattice element
346,267
def linkcode_resolve(domain, info): if domain != : return None modname = info[] fullname = info[] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split(): try: obj = getattr(obj, part) exce...
Determine the URL corresponding to Python object This code is stolen with thanks from the scipy team.
346,268
def rmspe(actual, predicted): actual = np.array(actual) predicted = np.array(predicted) zeros = actual == 0 actual = actual[~zeros] predicted = predicted[~zeros] return np.sqrt(np.sum(np.power((actual - predicted) / actual, 2)) / len(actual))
Computes the root mean square percentage error between two lists of numbers. Ignores elements where actual[n] == 0. Parameters ---------- actual : list of numbers, numpy array The ground truth value predicted : same type as actual The predicted value Returns ...
346,269
def jobInsertUnique(self, client, cmdLine, jobHash, clientInfo=, clientKey=, params=, minimumWorkers=0, maximumWorkers=0, jobType=, priority=DEFAULT_JOB_PRIORITY): assert cmdLine, "Unexpected empty or None command-line: " + repr(cmdLine) @...
Add an entry to the jobs table for a new job request, but only if the same job, by the same client is not already running. If the job is already running, or queued up to run, this call does nothing. If the job does not exist in the jobs table or has completed, it will be inserted and/or started up again...
346,270
def cube_open_hires_old(script, size=1.0, x_segments=1, y_segments=1, z_segments=1, center=False, color=None): size = util.make_list(size, 3) grid(script, [size[0], size[2]], x_segments=x_segments, y_segments=z_segments) transform.rotate(script, , 90) ...
Creates a square open tube, e.g. a box with no top or bottom. Useful if you want to wrap it around and join the open ends together, forming a torus.
346,271
def _check_for_more_pages(self): self._has_more = len(self._items) > self.per_page self._items = self._items[0 : self.per_page]
Check for more pages. The last item will be sliced off.
346,272
def filtered_archs(self): result = [] for arch in self.ctx.archs: if not self.archs or (arch.arch in self.archs): result.append(arch) return result
Return archs of self.ctx that are valid build archs for the Recipe.
346,273
def startElement(self, name, attrs): self.stack.append((self.current, self.chardata)) self.current = {} self.chardata = []
Initialize new node and store current node into stack.
346,274
def new_term(self, term, value, **kwargs): tc = self.doc.get_term_class(term.lower()) t = tc(term, value, doc=self.doc, parent=None, section=self).new_children(**kwargs) self.doc.add_term(t) return t
Create a new root-level term in this section
346,275
def label(self, name): json = None if name: url = self._build_url(, name, base_url=self._api) json = self._json(self._get(url), 200) return Label(json, self) if json else None
Get the label specified by ``name`` :param str name: (required), name of the label :returns: :class:`Label <github3.issues.label.Label>` if successful, else None
346,276
def get_relation_count_query(self, query, parent): if parent.get_query().from__ == query.get_query().from__: return self.get_relation_count_query_for_self_join(query, parent) self._set_join(query) return super(BelongsToMany, self).get_relation_count_query(query, parent)
Add the constraints for a relationship count query. :type query: orator.orm.Builder :type parent: orator.orm.Builder :rtype: orator.orm.Builder
346,277
def update(self, emailAddress=None, ttl=None, comment=None): return self.manager.update_domain(self, emailAddress=emailAddress, ttl=ttl, comment=comment)
Provides a way to modify the following attributes of a domain entry: - email address - ttl setting - comment
346,278
def add_cpds(self, *cpds): for cpd in cpds: if not isinstance(cpd, LinearGaussianCPD): raise ValueError() if set(cpd.variables) - set(cpd.variables).intersection( set(self.nodes())): raise ValueError(, cpd) for pr...
Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with the model Examples -------- >>> from pgmpy.mo...
346,279
def confirm_email_token_status(token): expired, invalid, user, token_data = \ get_token_status(token, , , return_data=True) if not invalid and user: user_id, token_email_hash = token_data invalid = not verify_hash(token_email_hash, user.email) return expired, invalid, user
Returns the expired status, invalid status, and user of a confirmation token. For example:: expired, invalid, user = confirm_email_token_status('...') :param token: The confirmation token
346,280
def file_upload(user_session, method, request): logger.debug(, vars(request)) http_command = getattr(user_session.session, method.lower()) try: response = http_command( request.href, params=request.params, files=request.files) except AttributeError: ...
Perform a file upload PUT/POST to SMC. Request should have the files attribute set which will be an open handle to the file that will be binary transfer. :param Session user_session: session object :param str method: method to use, could be put or post :param SMCRequest request: request object ...
346,281
def rename_workspace_config(namespace, workspace, cnamespace, config, new_namespace, new_name): body = { "namespace" : new_namespace, "name" : new_name, "workspaceName" : { "namespace" : namespace, "name"...
Rename a method configuration in a workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name mnamespace (str): Config namespace config (str): Config name new_namespace (str): Updated config namespace new_name (str): Updated ...
346,282
def fail_hosts(self, hosts_to_fail, activated_count=None): if not hosts_to_fail: return activated_count = activated_count or len(self.activated_hosts) logger.debug(.format(.join( (host.name for host in hosts_to_fail), ))) self.active_...
Flag a ``set`` of hosts as failed, error for ``config.FAIL_PERCENT``.
346,283
def insert(self, tname, record=None, columns=None, astype=None): tname = self._check_tname(tname) record = PandasDatabase._check_dict_type(str, str, record, cast=self.auto_cast) columns = PandasDatabase._check_type_iter(str, columns) record[self._id_colname] = str(uuid.uuid4()) ...
Inserts record into the provided table from the database. Returns inserted record as list, str or series depending on the value of `astype`. Parameters ---------- tname : str Table to insert records into. where : dict or None (default `None`) Dictionary o...
346,284
def _new_device_id(self, key): device_id = Id.SERVER + 1 if key in self._key2deviceId: return self._key2deviceId[key] while device_id in self._clients: device_id += 1 return device_id
Generate a new device id or return existing device id for key :param key: Key for device :type key: unicode :return: The device id :rtype: int
346,285
def check_prior_probs(self, statements): sources = set() for stmt in statements: sources |= set([ev.source_api for ev in stmt.evidence]) for err_type in (, ): for source in sources: if source not in self.prior_probs[err_type]: ...
Throw Exception if BeliefEngine parameter is missing. Make sure the scorer has all the information needed to compute belief scores of each statement in the provided list, and raises an exception otherwise. Parameters ---------- statements : list[indra.statements.Stateme...
346,286
def momentum(data, period): catch_errors.check_for_period_error(data, period) momentum = [data[idx] - data[idx+1-period] for idx in range(period-1, len(data))] momentum = fill_for_noncomputable_vals(data, momentum) return momentum
Momentum. Formula: DATA[i] - DATA[i - period]
346,287
def RowWith(self, column, value): for row in self._table[1:]: if row[column] == value: return row return None
Retrieves the first non header row with the column of the given value. Args: column: str, the name of the column to check. value: str, The value of the column to check. Returns: A Row() of the first row found, None otherwise. Raises: IndexError: The specified column does not exist...
346,288
def datagram_received(self, data, addr): response = unpack_lifx_message(data) response.ip_addr = addr[0] mac_addr = response.target_addr if mac_addr == BROADCAST_MAC: return if type(response) == StateService and response.service == 1: ...
Method run when data is received from the devices This method will unpack the data according to the LIFX protocol. If a new device is found, the Light device will be created and started aa a DatagramProtocol and will be registered with the parent. :param data: raw data ...
346,289
def filenameToModname(self, filename): for ext in reversed(self._exts): if filename.endswith(ext): filename = filename[:-len(ext)] break else: self.warn(filename, , filename) filename = os.path.abspath(filename) elements = ...
Convert a filename to a module name.
346,290
def bytes2str(bs): if isinstance(bs, type(b)) and PY_MAJOR_VERSION > 2: return bs.decode() else: return bs
For cross compatibility between Python 2 and Python 3 strings.
346,291
def monitored(name, **params): ret = {: name, : {}, : None, : } if __salt__[](name=name): ret[] = True ret[] = .format(name) ret[] = {} return ret if not __opts__[]: url_monitored = __salt__[](name, **params) if url_monitored: ret[] = True ...
Makes sure an URL is monitored by uptime. Checks if URL is already monitored, and if not, adds it.
346,292
def run(self): q = self._queue delayfunc = self.delayfunc timefunc = self.timefunc pop = heapq.heappop while q: checked_event = q[0] time, priority, action, argument = checked_event.get_fields() now = tim...
Execute events until the queue is empty. When there is a positive delay until the first event, the delay function is called and the event is left in the queue; otherwise, the event is removed from the queue and executed (its action function is called, passing it the argument). If ...
346,293
def _github_create_ssh_key(cls): try: login = cls._user.login pkey_path = .format( home=os.path.expanduser(), keyname=settings.GITHUB_SSH_KEYNAME.format(login=login)) -N \"\" -C \"DevAssistant\"ssh...
Creates a local ssh key, if it doesn't exist already, and uploads it to Github.
346,294
def handle_invalid_value(self, message, exc_info, context): raise NotImplementedError( .format(cls=type(self).__name__), )
Handles an invalid value. :param message: Error message. :param exc_info: Whether to include output from :py:func:``sys.exc_info``. :param context: Additional context values for the error.
346,295
def vinet_k(p, v0, k0, k0p, numerical=False): f_u = uct.wrap(cal_k_vinet) return f_u(p, [v0, k0, k0p])
calculate bulk modulus, wrapper for cal_k_vinet cannot handle uncertainties :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: bulk modulus at high...
346,296
def do_block(parser, token): name, args, kwargs = get_signature(token, contextable=True) kwargs[] = parser.parse(( % name,)) parser.delete_first_token() return BlockNode(parser, name, *args, **kwargs)
Process several nodes inside a single block Block functions take ``context``, ``nodelist`` as first arguments If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is. Syntax:: {% [block] [var args...] [name=value kwargs...] ...
346,297
def get_option_float(self, name, section=None, vars=None, expect=None): val = self.get_option(name, section, vars, expect) if val: return float(val)
Just like ``get_option`` but parse as a float.
346,298
def get_canonical_key(self, key_type, key_id): canonical_key_id = self.get_canonical_key_id(key_id) return self.get_key(key_type, canonical_key_id)
get_canonical_key returns the canonical form of a key given a key id. For example, '12345' maps to shard 6. The canonical key at index 6 (say '12') is the canonical key id given the key id of '12345'. This is useful for sets that need to exist on all shards. See compute_canonical_key_ids...
346,299
def rolling(self, dim: Optional[Mapping[Hashable, int]] = None, min_periods: Optional[int] = None, center: bool = False, **dim_kwargs: int): dim = either_dict_or_kwargs(dim, dim_kwargs, ) return self._rolling_cls(self, dim, min_periods=min_periods, ...
Rolling window object. Parameters ---------- dim: dict, optional Mapping from the dimension name to create the rolling iterator along (e.g. `time`) to its moving window size. min_periods : int, default None Minimum number of observations in window req...