Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
337,500
def get_updates(offset=None, limit=None, timeout=None, allowed_updates=None, **kwargs): params = _clean_params( offset=offset, limit=limit, timeout=timeout, allowed_updates=allowed_updates, ) return TelegramBotRPCRequest(, params=params, on_result=U...
Use this method to receive incoming updates using long polling. .. note:: 1. This method will not work if an outgoing webhook is set up. 2. In order to avoid getting duplicate updates, recalculate offset after each server response. :param allowed_updates: List the types of updates you want yo...
337,501
def docker_installed_rpms(broker): ctx = broker[DockerImageContext] root = ctx.root fmt = DefaultSpecs.rpm_format cmd = "/usr/bin/rpm -qa --root %s --qf " % (root, fmt) result = ctx.shell_out(cmd) return CommandOutputProvider(cmd, ctx, content=result)
Command: /usr/bin/rpm -qa --root `%s` --qf `%s`
337,502
def clear_published(self): metadata = Metadata(**settings.METADATA[]) if metadata.is_read_only() or metadata.is_required(): raise NoAccess() self._my_map[] = False
Removes the published status. :raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
337,503
def make_clusters(span_tree, cut_value): iv0, iv1 = span_tree.nonzero() match_dict = {} for i0, i1 in zip(iv0, iv1): d = span_tree[i0, i1] if d > cut_value: continue imin = int(min(i0, i1)) imax = int(max(i0, i1)) if imin in match_dic...
Find clusters from the spanning tree Parameters ---------- span_tree : a sparse nsrcs x nsrcs array Filled with zeros except for the active edges, which are filled with the edge measures (either distances or sigmas cut_value : float Value used to cluster group. All links with mea...
337,504
def Parse(self, raw_data): self.results = set() if not self.filters: self.results.update(raw_data) else: for f in self.filters: self.results.update(f.Parse(raw_data)) return list(self.results)
Take the data and yield results that passed through the filters. The output of each filter is added to a result set. So long as the filter selects, but does not modify, raw data, the result count will remain accurate. Args: raw_data: An iterable series of rdf values. Returns: A list o...
337,505
def move(fname, folder, options): if os.path.isfile(fname): shutil.move(fname, folder) else: if options.silent is False: print(.format(fname))
Move file to dir if existing
337,506
def shutdown(self): for item in self.clients: client, address = item client.close() self.clients.remove(item)
Shutdown the whole server
337,507
def send(self, packet, mac_addr=broadcast_addr): if self.keep_listening: if mac_addr == self.broadcast_addr: for addr, recv_queue in self.inq.items(): recv_queue.put(packet) else: self.inq[mac_addr].put(packet) ...
place sent packets directly into the reciever's queues (as if they are connected by wire)
337,508
def reset_option(self, key, subkey): if not self.open: return key, subkey = _lower_keys(key, subkey) _entry_must_exist(self.gc, key, subkey) df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)] if df["locked"].values[0]: raise ValueE...
Resets a single option to the default values. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. :raise: :NotRegisteredError: If ``key`` or ``subkey`` do not define any option. :ValueError: If the targeted...
337,509
def list_stacks(stack_ref: List[str], all: bool, remote: str, region: str, watch: int, output: str): lizzy = setup_lizzy_client(remote) stack_references = parse_stack_refs(stack_ref) while True: rows = [] for stack in lizzy.get_stacks(stack_references, region=region): ...
List Lizzy stacks
337,510
def transform(self, X): for col in range(X.shape[1]): X[:, col] = self._transform_col(X[:, col], col) return X
Normalize numerical columns. Args: X (numpy.array) : numerical columns to normalize Returns: X (numpy.array): normalized numerical columns
337,511
def dehydrate(self, iterator): for line in iterator: try: yield json.loads(line)[] except Exception as e: log.error("uhoh: %s\n" % e)
Pass in an iterator of tweets' JSON and get back an iterator of the IDs of each tweet.
337,512
def http(self, *args, **kwargs): kwargs[] = self.api return http(*args, **kwargs)
Starts the process of building a new HTTP route linked to this API instance
337,513
def __find_child_classes(self, file): child_classes = [] folder, name = os.path.split(file) name = os.path.splitext(name)[0] import imp module = imp.load_source(name, file) def filter_classes(m): if inspect.isclass(m): if inspect.ge...
Return a list of all <__base_class> based classes found in <file>
337,514
def handle_args(): default_database_name = os.environ.get( , dbconfig.testdb_corpus_url.database) default_logfile_path = os.path.expanduser("~/voeventdb_packet_ingest.log") parser = argparse.ArgumentParser( prog=os.path.basename(__file__), formatter_class=argparse.Argu...
Default values are defined here.
337,515
def point_rotate(pt, ax, theta): import numpy as np pt = make_nd_vec(pt, nd=3, t=np.float64, norm=False) rot_pt = np.dot(mtx_rot(ax, theta, reps=1), pt) return rot_pt
Rotate a 3-D point around a 3-D axis through the origin. Handedness is a counter-clockwise rotation when viewing the rotation axis as pointing at the observer. Thus, in a right-handed x-y-z frame, a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point at (0,1,0). .. todo:: Complete ...
337,516
def subtags(self): data = self.data subtags = [] if in data and self.data[][] == : return subtags codes = data[].split() for i, code in enumerate(codes): if len(code) == 1: break ...
Get the :class:`language_tags.Subtag.Subtag` objects of the tag. :return: list of :class:`language_tags.Subtag.Subtag` objects that are part of the tag. The return list can be empty.
337,517
def red_home(request, message=None): t have access to a page to the home page. Parameters: request - the request in the calling function message - a message from the caller function homepage'))
Convenience function for redirecting users who don't have access to a page to the home page. Parameters: request - the request in the calling function message - a message from the caller function
337,518
def get(self, key): try: try: obj = self.bucket.get(key) except: raise return dict(obj or {}) except: raise
Retrieve object indexed by <key>
337,519
def _buildExecutor(self): info = addict.Dict() info.name = "toil" info.command.value = resolveEntryPoint() info.executor_id.value = "toil-%i" % os.getpid() info.source = pwd.getpwuid(os.getuid()).pw_name return info
Creates and returns an ExecutorInfo-shaped object representing our executor implementation.
337,520
def _delete_sbo_tar_gz(self): if not self.auto and os.path.isfile(self.meta.build_path + self.script): os.remove(self.meta.build_path + self.script)
Delete slackbuild tar.gz file after untar
337,521
def port_profile_allow_nonprofiledmacs(self, **kwargs): config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, "name") name_key.text = kwargs.pop() allow...
Auto Generated Code
337,522
def get_installed_power(self): r for wind_farm in self.wind_farms: wind_farm.installed_power = wind_farm.get_installed_power() return sum(wind_farm.installed_power for wind_farm in self.wind_farms)
r""" Calculates the installed power of a wind turbine cluster. Returns ------- float Installed power of the wind turbine cluster.
337,523
def count_params(self): n_params = 0 for _i, p in enumerate(self.all_params): n = 1 for s in p.get_shape(): try: s = int(s) except Exception: s = 1 if s: ...
Returns the number of parameters in the network.
337,524
def from_array(array): if array is None or not array: return None assert_type_or_raise(array, dict, parameter_name="array") data = {} data[] = u(array.get()) data[] = bool(array.get()) data[] = int(array.get()) data[] = int(array.get...
Deserialize a new WebhookInfo from a given dictionary. :return: new WebhookInfo instance. :rtype: WebhookInfo
337,525
def _make_size_legend(self): areas = self._get_cluster_sizes() radii = np.sqrt(areas / np.pi) scaled = np.interp(radii, (radii.min(), radii.max()), (.1, 1)) indices = np.array([ percentile_index(self.scores_, p) for p in (25, 50, ...
Draw a legend that shows relative sizes of the clusters at the 25th, 50th, and 75th percentile based on the current scoring metric.
337,526
def _resolve_reference_sample(self, reference_samples=None, service_uids=None): if not reference_samples: return None, list() if not service_uids: sample = reference_samples[0] spec_uids = sample.ge...
Returns the reference sample from reference_samples passed in that fits better with the service uid requirements. This is, the reference sample that covers most (or all) of the service uids passed in and has less number of remaining service_uids. If no reference_samples are set, returns...
337,527
def send(self, anyway=False, prefetch=False): if self.config.get(): self.config.get().write( % ( datetime.now().isoformat(), self.method, self.url )) url = self.full_url if (content_type) and (not in self.headers): ...
Sends the request. Returns True of successful, false if not. If there was an HTTPError during transmission, self.response.status_code will contain the HTTPError code. Once a request is successfully sent, `sent` will equal True. :param anyway: If True, request will be sent, even if it h...
337,528
def alter_table_with_environment_context(self, dbname, tbl_name, new_tbl, environment_context): self.send_alter_table_with_environment_context(dbname, tbl_name, new_tbl, environment_context) self.recv_alter_table_with_environment_context()
Parameters: - dbname - tbl_name - new_tbl - environment_context
337,529
def port_ranges(): try: return _linux_ranges() except (OSError, IOError): try: ranges = _bsd_ranges() if ranges: return ranges except (OSError, IOError): pass return [DEFAULT_EPHEMERAL_PORT_RANGE]
Returns a list of ephemeral port ranges for current machine.
337,530
def htotdev(data, rate=1.0, data_type="phase", taus=None): if data_type == "phase": phase = data freq = phase2frequency(phase, rate) elif data_type == "freq": phase = frequency2phase(data, rate) freq = data else: raise Exception("unknown data_type: " + data_type)...
PRELIMINARY - REQUIRES FURTHER TESTING. Hadamard Total deviation. Better confidence at long averages for Hadamard deviation FIXME: bias corrections from http://www.wriley.com/CI2.pdf W FM 0.995 alpha= 0 F FM 0.851 alpha=-1 RW FM 0.771 alpha=-2 ...
337,531
def url(self, var, default=NOTSET): return self.get_value(var, cast=urlparse, default=default, parse_default=True)
:rtype: urlparse.ParseResult
337,532
def json_normalize(data, record_path=None, meta=None, meta_prefix=None, record_prefix=None, errors=, sep=): def _pull_field(js, spec): result = js if isinstance(spec, list): for field in spec: ...
Normalize semi-structured JSON data into a flat table. Parameters ---------- data : dict or list of dicts Unserialized JSON objects record_path : string or list of strings, default None Path in each object to list of records. If not passed, data will be assumed to be an array of...
337,533
def _new_import(self, import_name): import_name = "%s.%s" % (root_namespace, import_name) import_file_name = "%s.tx" % os.path.join(self.root_path, *import_name.split(".")) if import_name not in self.namespaces: ...
Starts a new import. Args: import_name(str): A relative import in the dot syntax (e.g. "first.second.expressions")
337,534
def start_all(self): for alias, service in self._service_objects.items(): if not service.is_alive: with expects.expect_no_raises( % alias): service.start()
Starts all inactive service instances.
337,535
def tag_check_function(tags): suffixes = [.format(t) for t in tags] def _check_image(image): repo_tags = image[] if not repo_tags: return False return any(r_tag.endswith(s) for s in suffixes for r_tag in repo_tags) return _check_image
Generates a function that checks whether the given image has any of the listed tags. :param tags: Tags to check for. :type tags: list[unicode | str] | set[unicode | str] :return: Function that returns ``True`` if any of the given tags apply to the image, ``False`` otherwise. :rtype: (unicode | str) -> ...
337,536
def get(key, profile=None): if not profile: return False redis_kwargs = profile.copy() redis_kwargs.pop() redis_conn = redis.StrictRedis(**redis_kwargs) return redis_conn.get(key)
Get a value from the Redis SDB.
337,537
def initialize_switch_endpoints(self): self._switches = {} self._port_group_info = {} self._validate_config() for s in cfg.CONF.ml2_arista.switch_info: switch_ip, switch_user, switch_pass = s.split(":") if switch_pass == "": switch_pass = ...
Initialize endpoints for switch communication
337,538
def read_dataset_metadata(self): if self.dataset_meta: return shell_call([, , + self.storage_client.bucket_name + + + self.dataset_name + , LOCAL_DATASET_METADATA_FILE]) with open(LOCAL_DATASET_METADATA_FILE, ) as f: self.dataset_meta = eva...
Read `dataset_meta` field from bucket
337,539
def recognise(self): result = "" for side in "LFRB": for square in self.cube.get_face(side)[0]: for _side in "LFRB": if square.colour == self.cube[_side].colour: result += _side break return ...
Recognise the PLL case of Cube.
337,540
def Seq(self, *sequence, **kwargs): fs = [ _parse(elem)._f for elem in sequence ] def g(x, state): return functools.reduce(lambda args, f: f(*args), fs, (x, state)) return self.__then__(g, **kwargs)
`Seq` is used to express function composition. The expression Seq(f, g) be equivalent to lambda x: g(f(x)) As you see, its a little different from the mathematical definition. Excecution order flow from left to right, this makes reading and reasoning about code way more easy. This bahaviour is based upon th...
337,541
def _cint(col, _map={base26(i): i - 1 for i in range(1, 257)}): try: return _map[col.upper()] except KeyError: raise ValueError(col)
Return zero-based column index from bijective base26 string. >>> Coordinates._cint('Ab') 27 >>> Coordinates._cint('spam') Traceback (most recent call last): ... ValueError: spam
337,542
def _stopThread(self, exception, raiseEvery=2.0): if self.isAlive() is False: return True self._stderr = open(os.devnull, ) joinThread = JoinThread(self, exception, repeatEvery=raiseEvery) joinThread._stderr = self._stderr joinTh...
_stopThread - @see StoppableThread.stop
337,543
def _sub_patterns(patterns, text): for pattern, repl in patterns: text = re.sub(pattern, repl, text) return text
Apply re.sub to bunch of (pattern, repl)
337,544
def nth_value(expr, nth, skip_nulls=False, sort=None, ascending=True): return _cumulative_op(expr, NthValue, data_type=expr._data_type, sort=sort, ascending=ascending, _nth=nth, _skip_nulls=skip_nulls)
Get nth value of a grouped and sorted expression. :param expr: expression for calculation :param nth: integer position :param skip_nulls: whether to skip null values, False by default :param sort: name of the sort column :param ascending: whether to sort in ascending order :return: calculated c...
337,545
def start(ctx, **kwargs): update_context(ctx, kwargs) daemon = mk_daemon(ctx) if ctx.debug or kwargs[]: daemon.run() else: daemon.start()
start a vaping process
337,546
def from_pkcs12(cls, key, email, scopes, subject=None, passphrase=PKCS12_PASSPHRASE): key = OpenSSL.crypto.load_pkcs12(key, passphrase).get_privatekey() return cls(key=key, email=email, scopes=scopes, subject=subject)
Alternate constructor intended for using .p12 files. Args: key (dict) - Parsed JSON with service account credentials. email (str) - Service account email. scopes (Union[str, collections.Iterable[str]]) - List of permissions that the application requests. ...
337,547
def initinletoutlet(idf, idfobject, thisnode, force=False): def blankfield(fieldvalue): try: if fieldvalue.strip() == : return True else: return False except AttributeError: return False def trimfields(fields, th...
initialze values for all the inlet outlet nodes for the object. if force == False, it willl init only if field = ''
337,548
def probe_dtz(self, board: chess.Board) -> int: v = self.probe_dtz_no_ep(board) if not board.ep_square or self.variant.captures_compulsory: return v v1 = -3 for move in board.generate_legal_ep(): board.push(move) try: ...
Probes DTZ tables for distance to zero information. Both DTZ and WDL tables are required in order to probe for DTZ. Returns a positive value if the side to move is winning, ``0`` if the position is a draw and a negative value if the side to move is losing. More precisely: +---...
337,549
def __select_text_under_cursor_blocks(self, cursor): start_block = self.document().findBlock(cursor.selectionStart()).firstLineNumber() end_block = self.document().findBlock(cursor.selectionEnd()).firstLineNumber() cursor.setPosition(self.document().findBlockByLineNumber(start_block).p...
Selects the document text under cursor blocks. :param cursor: Cursor. :type cursor: QTextCursor
337,550
def __calculate_changes(self, updated_centers): changes = numpy.sum(numpy.square(self.__centers - updated_centers), axis=1).T return numpy.max(changes)
! @brief Calculate changes between centers. @return (float) Maximum change between centers.
337,551
def get_BAIDUID(): url = .join([ const.PASSPORT_URL, , , util.timestamp(), , ]) req = net.urlopen(url, headers={: }) if req: return req.headers.get_all() else: return None
获取一个cookie - BAIDUID. 这里, 我们访问百度首页, 返回的response header里面有我们需要的cookie
337,552
def cleanup_a_alpha_and_derivatives(self): r del(self.a, self.Tc, self.S1, self.S2)
r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by `GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for every component
337,553
def __send_message(self, proto, payload): try: if not isinstance(payload, bytes): payload = payload.encode("utf-8") if not proto.connected: raise IOError("not connected") proto.sendMessage(payload) logger.debug("s...
Sends a message
337,554
def trace(self, name, chain=-1): if isinstance(name, str): return self.db.trace(name, chain) elif isinstance(name, Variable): return self.db.trace(name.__name__, chain) else: raise ValueError( % name)
Return the trace of a tallyable object stored in the database. :Parameters: name : string The name of the tallyable object. chain : int The trace index. Setting `chain=i` will return the trace created by the ith call to `sample`.
337,555
def _ReadStructureDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): if is_member: error_message = raise errors.DefinitionReaderError(definition_name, error_message) return self._ReadDataTypeDefinitionWithMembers( definiti...
Reads a structure data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data t...
337,556
def _merge_intervals(self, min_depth): def add_interval(ret, start, stop): if min_depth is not None: shift = 2 * (29 - min_depth) mask = (int(1) << shift) - 1 if stop - start < mask: ret.append((start, stop)) ...
Merge overlapping intervals. This method is called only once in the constructor.
337,557
def delete_async(self, url, name, callback=None, params=None, headers=None): if not name: name = params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, name) self._authenticate(params, headers) process_pool.apply_async(make_delete...
Asynchronous DELETE request with the process pool.
337,558
def set_flagged(self, *, start_date=None, due_date=None): self.__status = Flag.Flagged start_date = start_date or dt.datetime.now() due_date = due_date or dt.datetime.now() if start_date.tzinfo is None: start_date = self.protocol.timezone.localize(start_date) ...
Sets this message as flagged :param start_date: the start datetime of the followUp :param due_date: the due datetime of the followUp
337,559
def EI(inc): poly_tk03 = [3.15976125e-06, -3.52459817e-04, - 1.46641090e-02, 2.89538539e+00] return poly_tk03[0] * inc**3 + poly_tk03[1] * inc**2 + poly_tk03[2] * inc + poly_tk03[3]
Given a mean inclination value of a distribution of directions, this function calculates the expected elongation of this distribution using a best-fit polynomial of the TK03 GAD secular variation model (Tauxe and Kent, 2004). Parameters ---------- inc : inclination in degrees (int or float) ...
337,560
def isiterable(obj, reject_string=True): iterable = hasattr(obj, ) if reject_string: iterable = iterable and not isinstance(obj, str) return iterable
convenience tool to detect if something is iterable. in python3, strings count as iterables to we have the option to exclude them Parameters: ----------- obj : object to analyse reject_string : bool, whether to ignore strings Returns: -------- bool, if the object is itereable.
337,561
def count_lines(self, code): return sum(bool(line.strip()) for line in code.splitlines())
Count lines of code (by default ignores empty lines, but child could override to do more).
337,562
def create_rsa_signature(private_key, data, scheme=): securesystemslib.formats.PEMRSA_SCHEMA.check_match(private_key) securesystemslib.formats.DATA_SCHEMA.check_match(data) securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme) signature = None if len(private_key): ...
<Purpose> Generate a 'scheme' signature. The signature, and the signature scheme used, is returned as a (signature, scheme) tuple. The signing process will use 'private_key' to generate the signature of 'data'. RFC3447 - RSASSA-PSS http://www.ietf.org/rfc/rfc3447.txt >>> public, private ...
337,563
def __to_text(self, number, indice = 0, sing=False): number = int(number) exp = self.exponentes[indice] indice += 1 divisor = 10 ** exp if exp == 3: func = self.__numero_tres_cifras else: func = self.__to_text if divisor...
Convierte un numero a texto, recursivamente
337,564
def full_pixels(space, data, gap_pixels=1): available = space - (len(data) - 1) * gap_pixels res = [] for i, val in enumerate(data): data_sum = sum(data[i:]) norm = val * 1.0 / data_sum w = max(int(round(available * norm)), 1) res.append(w) available...
returns the given data distributed in the space ensuring it's full pixels and with the given gap. this will result in minor sub-pixel inaccuracies. XXX - figure out where to place these guys as they are quite useful
337,565
def calc_mse(q1, q2): dq = q2 - q1 return np.sqrt(np.mean(dq*dq))/au2m
Compare the results of two simulations
337,566
def find_chunk (phrase, np): for i in iter(range(0, len(phrase))): parsed_np = find_chunk_sub(phrase, np, i) if parsed_np: return parsed_np
leverage noun phrase chunking
337,567
def rs_find_errors(err_loc, nmess, generator=2): s search (but less efficient, Chien errs = len(err_loc) - 1 err_pos = [] for i in xrange(nmess): if gf_poly_eval(err_loc, gf_pow(generator, i)) == 0: err_pos.append(nmess - 1 - i) if len(err_pos) != errs: ...
Find the roots (ie, where evaluation = zero) of error polynomial by bruteforce trial, this is a sort of Chien's search (but less efficient, Chien's search is a way to evaluate the polynomial such that each evaluation only takes constant time).
337,568
def search(self, account_name): accounts = self.list() for a in accounts: if a[] == account_name: return a[]
Get a list of all the Accounts for the current user and return the ID of the one with the specified name.
337,569
def onExit(self): def try_call(fn): try: fn() except (pika.exceptions.ChannelClosed, AttributeError, pika.exceptions.ConnectionClosed): return if hasattr(self, "channel"): try_call(self.channel.cancel) ...
Called when daemon is stopped. Basically just AMQP's ``.close()`` functions to ensure clean exit. You can override this, but don't forget to call it thru ``super()``, or the AMQP communication won't be closed properly!
337,570
def make_app(global_conf, full_stack=True, **app_conf): app = make_base_app(global_conf, full_stack=True, **app_conf) app = raptorizemw.make_middleware(app) return app
Set tg2-raptorized up with the settings found in the PasteDeploy configuration file used. :param global_conf: The global settings for tg2-raptorized (those defined under the ``[DEFAULT]`` section). :type global_conf: dict :param full_stack: Should the whole TG2 stack be set up? :type fu...
337,571
def execute(self): rprocess = OrderedDict() commands = OrderedDict([ (self.file, [, self.file] + self.cmd), ]) for cmd_name, cmd in commands.items(): rprocess[cmd_name] = self.run_command_under_r_root(cmd) return self.decode_cmd_out(compl...
Execute R script
337,572
def dir_visitor(dirname, visitor): visitor(dirname) for obj in os.listdir(dirname): obj_path = os.path.join(dirname, obj) if os.path.isdir(obj_path): dir_visitor(obj_path, visitor)
_dir_visitor_ walk through all files in dirname, find directories and call the callable on them. :param dirname: Name of directory to start visiting, all subdirs will be visited :param visitor: Callable invoked on each dir visited
337,573
def _to_rest(model, includes=None): includes = includes or [] sparse = goldman.sess.req.fields.get(model.rtype, []) if sparse: sparse += [model.rid_field, model.rtype_field] sparse += includes props = model.to_primitive( load_rels=includes, sparse_fields=sparse, ...
Convert the model into a dict for serialization Notify schematics of the sparse fields requested while also forcing the resource id & resource type fields to always be present no matter the request. Additionally, any includes are implicitly added as well & automatically loaded. Then normalize the ...
337,574
def write(self, msg): self._current_stream.write(msg) for log in self._logs.values(): log.append(msg)
Writes msg to the current output stream (either standard out or dev/null). If a log has been registered, append msg to the log. PARAMTERS: msg -- str
337,575
def replace_namespaced_replica_set(self, name, namespace, body, **kwargs): kwargs[] = True if kwargs.get(): return self.replace_namespaced_replica_set_with_http_info(name, namespace, body, **kwargs) else: (data) = self.replace_namespaced_replica_set_with_http_inf...
replace the specified ReplicaSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_replica_set(name, namespace, body, async_req=True) >>> result = thread.get() :param asyn...
337,576
def _get_esxi_proxy_details(): s proxy details esxi.get_detailshostvcentervcenteresxi_hostesxi_hostusernamepasswordprotocolportmechanismprincipaldomain'), esxi_hosts
Returns the running esxi's proxy details
337,577
def run_ops(state, serial=False, no_wait=False): state.deploying = True if serial: _run_serial_ops(state) elif no_wait: _run_no_wait_ops(state) for op_hash in state.get_op_order(): _run_single_op(state, op_hash)
Runs all operations across all servers in a configurable manner. Args: state (``pyinfra.api.State`` obj): the deploy state to execute serial (boolean): whether to run operations host by host no_wait (boolean): whether to wait for all hosts between operations
337,578
def _delta_t_supconj_perpass(period, ecc, per0): ups_sc = np.pi/2-per0 E_sc = 2*np.arctan( np.sqrt((1-ecc)/(1+ecc)) * np.tan(ups_sc/2) ) M_sc = E_sc - ecc*np.sin(E_sc) return period*(M_sc/2./np.pi)
time shift between superior conjuction and periastron passage
337,579
def emit_tep(self, tep, typ="all", **context): e = self.get_all_tep.get(tep) or dict(HTMLFile=[], HTMLString=[]) if self.stpl is True: e["HTMLFile"] = map(lambda tpl: tpl.split()[-1], sorted(e[], key=lambda x: x.split()[0], reverse=self.stpl_reverse)) e["HTMLStr...
Emit a event(with tep) and gets the template extension point data(html code). Please use this function in the template. The extension point needs to be defined by itself. Suppose you have an extension point named `tep`, only need to enable custom extension points in the template, for examples:: ...
337,580
def size(self): complexity num_enabled_connections = sum([1 for cg in self.connections.values() if cg.enabled is True]) return len(self.nodes), num_enabled_connections
Returns genome 'complexity', taken to be (number of nodes, number of enabled connections)
337,581
def bonus_damage(self): if self._weapons: for weapon in self._weapons: if weapon.damage_bonus: b = weapon.damage_bonus[0] return b.bonus, b.attribute
Returns a tuple of form 'bonus damage, armor type' if unit does bonus damage against armor type Light = 1; Armored = 2; Biological = 3; Mechanical = 4; Robotic = 5; Psionic = 6; Massive = 7; Structure = 8; Hover = 9; Heroic = 10; Summoned = 11
337,582
def from_histogram(cls, histogram, bin_edges, axis_names=None): bin_edges = np.array(bin_edges) self = cls(bins=bin_edges, axis_names=axis_names) self.histogram = histogram return self
Make a HistdD from numpy histogram + bin edges :param histogram: Initial histogram :param bin_edges: x bin edges of histogram, y bin edges, ... :return: Histnd instance
337,583
def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource=True, **attrs): if isinstance(obj, str): name, rest = obj.strip().split(, 1) signature = rest[:-1] func = None else: name = None sig...
Create a function from the strings name, signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added, if any.
337,584
def move_to(self, x=0, y=0): self._driver.move_to(self, x, y)
Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead. Move the mouse by an offset of the specificed element. Support: Android Args: x(float): X offset to move to, relative to the top-left corner of the element. y(...
337,585
def _set_get_mac_address_table(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=get_mac_address_table.get_mac_address_table, is_leaf=True, yang_name="get-mac-address-table", rest_name="get-mac-address-table", parent=self, path_helper=self._path_helper,...
Setter method for get_mac_address_table, mapped from YANG variable /brocade_mac_address_table_rpc/get_mac_address_table (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_mac_address_table is considered as a private method. Backends looking to populate this variable s...
337,586
def escape(arg): "escape shell special characters" slash = special = arg = arg.replace(slash, slash+slash) for c in special: arg = arg.replace(c, slash+c) return + arg +
escape shell special characters
337,587
def setup_recent_files_menu(self): self.recent_files_manager = widgets.RecentFilesManager( , ) self.menu_recents = widgets.MenuRecentFiles( self.menuFile, title=, recent_files_manager=self.recent_files_manager) self.menu_recents.open_requested.connect...
Setup the recent files menu and manager
337,588
def remove_vcf_info(keyword, variant_line=None, variant_dict=None): logger.debug("Removing variant information {0}".format(keyword)) fixed_variant = None def get_new_info_string(info_string, keyword): new_info_list = [] splitted_info_string = info_string.split() ...
Remove the information of a info field of a vcf variant line or a variant dict. Arguments: variant_line (str): A vcf formatted variant line variant_dict (dict): A variant dictionary keyword (str): The info field key Returns: variant_line (str): A annotated vari...
337,589
def deliver(self, timeout=None): self.event.wait(timeout) if self.error: raise self.error elif not self.event.is_set(): raise OperationTimedOut() else: return self.responses
If fail_on_error was set to False, a list of (success, response) tuples will be returned. If success is False, response will be an Exception. Otherwise, response will be the normal query response. If fail_on_error was left as True and one of the requests failed, the corresponding Exce...
337,590
def period_array( data: Sequence[Optional[Period]], freq: Optional[Tick] = None, copy: bool = False, ) -> PeriodArray: if is_datetime64_dtype(data): return PeriodArray._from_datetime64(data, freq) if isinstance(data, (ABCPeriodIndex, ABCSeries, PeriodArray)): return ...
Construct a new PeriodArray from a sequence of Period scalars. Parameters ---------- data : Sequence of Period objects A sequence of Period objects. These are required to all have the same ``freq.`` Missing values can be indicated by ``None`` or ``pandas.NaT``. freq : str, Tick,...
337,591
def _sqlalchemy_on_finish(self): if hasattr(self, "_db_conns"): try: if self.get_status() >= 200 and self.get_status() <= 399: for db_conn in self._db_conns.values(): db_conn.commit() else: for ...
Closes the sqlalchemy transaction. Rolls back if an error occurred.
337,592
def team_pitching(start_season, end_season=None, league=, ind=1): if start_season is None: raise ValueError("You need to provide at least one season to collect data for. Try team_pitching(season) or team_pitching(start_season, end_season).") if end_season is None: end_season = start_season ...
Get season-level pitching data aggregated by team. ARGUMENTS: start_season : int : first season you want data for (or the only season if you do not specify an end_season) end_season : int : final season you want data for league : "all", "nl", or "al" ind : int : =1 if you want individual season l...
337,593
def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir): exe = if in url else with dest_ctx() as repo_dir: cmd = [exe, , url, repo_dir] if branch: cmd.extend([, branch]) devnull = open(os.path.devnull, ) stdout = devnull if quiet else None subprocess.check_call(cmd, stdout=stdout) yield ...
Check out the repo indicated by url. If dest_ctx is supplied, it should be a context manager to yield the target directory for the check out.
337,594
def mapping_delete(index, doc_type, hosts=None, profile=None): es = _get_instance(hosts, profile) try: result = es.indices.delete_mapping(index=index, doc_type=doc_type) return result.get(, False) except elasticsearch.exceptions.NotFoundError: return True except elasticsear...
Delete a mapping (type) along with its data. As of Elasticsearch 5.0 this is no longer available. index Index for the mapping doc_type Name of the document type CLI example:: salt myminion elasticsearch.mapping_delete testindex user
337,595
def correct(datasets_full, genes_list, return_dimred=False, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, return_dense=False, hvg=None, union=False, geosketch=False, geosketch_max=20000): d...
Integrate and batch correct a list of data sets. Parameters ---------- datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray` Data sets to integrate and correct. genes_list: `list` of `list` of `string` List of genes for each data set. return_dimred: `bool`, optio...
337,596
def usages(self): row, col = self.editor.cursor() self.log.debug() self.call_options[self.call_id] = { "word_under_cursor": self.editor.current_word(), "false_resp_msg": "Not a valid symbol under the cursor"} self.send_at_point("UsesOfSymbol", row...
Request usages of whatever at cursor.
337,597
def data_vectors(self): return {field: self.record[field] for field in self.record.dtype.names if field != }
The per-sample data in a vector. Returns: dict: A dict where the keys are the fields in the record and the values are the corresponding arrays. Examples: >>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN, ...
337,598
def install_from_repo(pkgname, plugin_type, install_path, register_func): rsession = requests.Session() rsession.mount("https://", HTTPAdapter(max_retries=3)) logger.debug("trying to install %s from online repo", pkgname) pkgurl = "{}/{}s/{}.zip".format(defs.GITHUB_RAW, plugin_type, pkgname) t...
Install plugin from online repo.
337,599
def gen_binary_files_from_urls( urls: Iterable[str], on_disk: bool = False, show_info: bool = True) -> Generator[BinaryIO, None, None]: for url in urls: if on_disk: with tempfile.TemporaryDirectory() as tmpdir: filename = os.path.join(tmp...
Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that are on disk (permitting random access); if ``False``, yields in-memory files (which will not permit random access) show_info: show progress...