code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def create_contentkey_authorization_policy_options(access_token, key_delivery_type="2", \ name="HLS Open Authorization Policy", key_restriction_type="0"): path = endpoint = .join([ams_rest_endpoint, path]) body = + key_delivery_type + + name + + key_restriction_type + return do_ams_post(endpoi...
Create Media Service Content Key Authorization Policy Options. Args: access_token (str): A valid Azure authentication token. key_delivery_type (str): A Media Service Content Key Authorization Policy Delivery Type. name (str): A Media Service Contenty Key Authorization Policy Name. k...
def getChild(self, name, ns=None, default=None): if self.__root is None: return default if ns is None: prefix, name = splitPrefix(name) if prefix is None: ns = None else: ns = self.__root.resolvePrefix(prefix) ...
Get a child by (optional) name and/or (optional) namespace. @param name: The name of a child element (may contain prefix). @type name: basestring @param ns: An optional namespace used to match the child. @type ns: (I{prefix}, I{name}) @param default: Returned when child not-found...
def children_and_parameters(m:nn.Module): "Return the children of `m` and its direct parameters not registered in modules." children = list(m.children()) children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[]) for p in m.parameters(): if id(p) not in children_p: children.app...
Return the children of `m` and its direct parameters not registered in modules.
def get_metadata(feature_name, etextno): metadata_values = MetadataExtractor.get(feature_name).get_metadata(etextno) return frozenset(metadata_values)
Looks up the value of a meta-data feature for a given text. Arguments: feature_name (str): The name of the meta-data to look up. etextno (int): The identifier of the Gutenberg text for which to look up the meta-data. Returns: frozenset: The values of the meta-data for the t...
def intersection(self, *others): r result = self.__copy__() _elements = result._elements _total = result._total for other in map(self._as_mapping, others): for element, multiplicity in list(_elements.items()): new_multiplicity = other.get(element, 0) ...
r"""Return a new multiset with elements common to the multiset and all others. >>> ms = Multiset('aab') >>> sorted(ms.intersection('abc')) ['a', 'b'] You can also use the ``&`` operator for the same effect. However, the operator version will only accept a set as other operator,...
def _condition_as_text(lambda_inspection: icontract._represent.ConditionLambdaInspection) -> str: lambda_ast_node = lambda_inspection.node assert isinstance(lambda_ast_node, ast.Lambda) body_node = lambda_ast_node.body text = None if isinstance(body_node, ast.BoolOp) and isinstance(body_nod...
Format condition lambda function as reST.
async def send_cluster_commands(self, stack, raise_on_error=True, allow_redirections=True): attempt = sorted(stack, key=lambda x: x.position) nodes = {} for c in attempt: slot = self._determine_slot(*c....
Send a bunch of cluster commands to the redis cluster. `allow_redirections` If the pipeline should follow `ASK` & `MOVED` responses automatically. If set to false it will raise RedisClusterException.
def build_channel(namespace, name, user_ids): ids = .join(map(str, user_ids)) return "{0}:{1}
Creates complete channel information as described here https://fzambia.gitbooks.io/centrifugal/content/server/channels.html.
def pack(self, grads): for i, g in enumerate(grads): assert g.shape == self._shapes[i] with cached_name_scope("GradientPacker", top_level=False): concat_grads = tf.concat([tf.reshape(g, [-1]) for g in grads], 0, name=) grad_packs = tf.split(conc...
Args: grads (list): list of gradient tensors Returns: packed list of gradient tensors to be aggregated.
def page_guiref(arg_s=None): from IPython.core import page page.page(gui_reference, auto_html=True)
Show a basic reference about the GUI Console.
def crypto_hash_sha256(message): digest = ffi.new("unsigned char[]", crypto_hash_sha256_BYTES) rc = lib.crypto_hash_sha256(digest, message, len(message)) ensure(rc == 0, , raising=exc.RuntimeError) return ffi.buffer(digest, crypto_hash_sha256_BYTES)[:]
Hashes and returns the message ``message``. :param message: bytes :rtype: bytes
def read(self, obj): path, frag = [], obj for part in self.parts: path.append(part) if isinstance(frag, dict): try: frag = frag[part] except KeyError as error: raise NotFound(.join(path)) from error ...
Returns object: fragment
def _real_time_thread(self): while self.ws_client.connected(): if self.die: break if self.pause: sleep(5) continue message = self.ws_client.receive() if message is None: break message_type = message[] if message_type == : c...
Handles real-time updates to the order book.
def _handle_array(toks): if len(toks) == 5 and toks[1] == and toks[4] == : subtree = toks[2:4] signature = .join(s for (_, s) in subtree) [key_func, value_func] = [f for (f, _) in subtree] def the_dict_func(a_dict, variant=0): ...
Generate the correct function for an array signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str
def set_write_buffer_limits(self, high=None, low=None): if high is None: high = self.write_buffer_size if low is None: low = high // 2 if low > high: low = high self._write_buffer_high = high self._write_buffer_low = low
Set the low and high watermark for the write buffer.
def check_encoding(proof_req: dict, proof: dict) -> bool: LOGGER.debug(, proof_req, proof) cd_id2proof_id = {} p_preds = {} for idx in range(len(proof[])): cd_id = proof[][idx][] cd_id2proof_id[cd_id] = idx p_preds[cd_id] = { ...
Return whether the proof's raw values correspond to their encodings as cross-referenced against proof request. :param proof request: proof request :param proof: corresponding proof to check :return: True if OK, False for encoding mismatch
def _GetRecordValue(self, record, value_entry): column_type = record.get_column_type(value_entry) long_value = None if record.is_long_value(value_entry): long_value = record.get_value_data_as_long_value(value_entry) if record.is_multi_value(value_entry): raise ValueError() ...
Retrieves a specific value from the record. Args: record (pyesedb.record): ESE record. value_entry (int): value entry. Returns: object: value. Raises: ValueError: if the value is not supported.
def securitygroupid(vm_): securitygroupid_set = set() securitygroupid_list = config.get_cloud_config_value( , vm_, __opts__, search_global=False ) if securitygroupid_list: securitygroupid_set = securitygroupid_set.union(set(securitygroupid...
Returns the SecurityGroupId
def observe(M, C, obs_mesh, obs_vals, obs_V=0, lintrans=None, cross_validate=True): obs_mesh = regularize_array(obs_mesh) obs_V = resize(obs_V, obs_mesh.shape[0]) obs_vals = resize(obs_vals, obs_mesh.shape[0]) relevant_slice, obs_mesh_new = C.observe(obs_mesh, obs_V, output_t...
(M, C, obs_mesh, obs_vals[, obs_V = 0, lintrans = None, cross_validate = True]) Imposes observation of the value of obs_vals on M and C, where obs_vals ~ N(lintrans * f(obs_mesh), V) f ~ GP(M,C) :Arguments: - `M`: The mean function - `C`: The covariance function - `...
def list_all_geo_zones(cls, **kwargs): kwargs[] = True if kwargs.get(): return cls._list_all_geo_zones_with_http_info(**kwargs) else: (data) = cls._list_all_geo_zones_with_http_info(**kwargs) return data
List GeoZones Return a list of GeoZones This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_geo_zones(async=True) >>> result = thread.get() :param async bool :param int p...
def getBool(t): b = c_int() if PL_get_long(t, byref(b)): return bool(b.value) else: raise InvalidTypeError("bool")
If t is of type bool, return it, otherwise raise InvalidTypeError.
def make_decoder(num_topics, num_words): topics_words_logits = tf.compat.v1.get_variable( "topics_words_logits", shape=[num_topics, num_words], initializer=tf.compat.v1.glorot_normal_initializer()) topics_words = tf.nn.softmax(topics_words_logits, axis=-1) def decoder(topics): word_probs...
Create the decoder function. Args: num_topics: The number of topics. num_words: The number of words. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distribution` instance over words.
def _import_next_layer(self, proto, length): if length == 0: from pcapkit.protocols.null import NoPayload as Protocol elif self._sigterm: from pcapkit.protocols.raw import Raw as Protocol elif proto == 0x0806: from pcapkit.protocols.link.arp import AR...
Import next layer extractor. Positional arguments: * proto -- str, next layer protocol name * length -- int, valid (not padding) length Returns: * bool -- flag if extraction of next layer succeeded * Info -- info of next layer * ProtoChain --...
def minimum_sys(cls, inherit_path): site_libs = set(cls.site_libs()) for site_lib in site_libs: TRACER.log( % site_lib) for extras_path in cls._extras_paths(): TRACER.log( % extras_path) site_libs.add(extras_path) site_libs = set(os.path.normpath(path) for path in site_libs) ...
Return the minimum sys necessary to run this interpreter, a la python -S. :returns: (sys.path, sys.path_importer_cache, sys.modules) tuple of a bare python installation.
def force_horizontal_padding_after( self, index: int, padding: Union[int, float]) -> None: self.horizontal_padding[index] = padding
Change the padding after the given column.
def timeseries(self, dataframe=False): self.query.get_cardinality("author_uuid").by_period() return super().timeseries(dataframe)
Get the date histogram aggregations. :param dataframe: if true, return a pandas.DataFrame object
def check(self, batch_size): self.increment(batch_size) return self.unit_count >= self.config["log_train_every"]
Returns True if the logging frequency has been met.
def _threaded(self, *args, **kwargs): for target in self.targets: result = target(*args, **kwargs) self.queue.put(result)
Call the target and put the result in the Queue.
def register_view(self, view): super(TopToolBarController, self).register_view(view) view[].connect(, self.on_maximize_button_clicked) self.update_maximize_button()
Called when the View was registered
def check(dependency=None, timeout=60): hello.c exists\hello.c compiles\prints "Hello, world!\\\\n\ def decorator(check): _check_names.append(check.__name__) check._check_dependency = dependency @functools.wraps(check) def wrapper(checks_root, dependency_state...
Mark function as a check. :param dependency: the check that this check depends on :type dependency: function :param timeout: maximum number of seconds the check can run :type timeout: int When a check depends on another, the former will only run if the latter passes. Additionally, the dependen...
def read(self): if self.default_file: self.read_default_config() return self.read_config_files(self.all_config_files())
Read the default, additional, system, and user config files. :raises DefaultConfigValidationError: There was a validation error with the *default* file.
def index(index, length): if index < 0: index += length if 0 <= index < length: return index raise IndexError()
Generates an index. :param index: The index, can be positive or negative. :param length: The length of the sequence to index. :raises: IndexError Negative indices are typically used to index a sequence in reverse order. But to use them, the indexed object must convert them to the correct, pos...
def type_list(signature, doc, header): lines = [] docced = set() lines.append(header) try: for names, types, description in doc: names, types = _get_names(names, types) unannotated = [] for name in names: docced.add(name) ...
Construct a list of types, preferring type annotations to docstrings if they are available. Parameters ---------- signature : Signature Signature of thing doc : list of tuple Numpydoc's type list section Returns ------- list of str Markdown formatted type list
def _execute_single_level_task(self): self.log(u"Executing single level task...") try: self._step_begin(u"extract MFCC real wave") real_wave_mfcc = self._extract_mfcc( file_path=self.task.audio_file_path_absolute, file_format=...
Execute a single-level task
def update_alias(FunctionName, Name, FunctionVersion=None, Description=None, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) args = {} if FunctionVersion: args[] = FunctionVersion...
Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_alias my_lambda my_alias $LATEST
def get_events(conn, stackname): next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(eve...
Get the events in batches and return in chronological order
def nsx_controller_connection_addr_method(self, **kwargs): config = ET.Element("config") nsx_controller = ET.SubElement(config, "nsx-controller", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(nsx_controller, "name") name_key.text = kwargs.pop() c...
Auto Generated Code
def valid_token(token): is_scale = False try: Scale(token) is_scale = True except ScaleFormatError: pass if any([token.isdigit(), token in SEPARATOR_TOKENS, is_scale]): return True return False
Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string
def find_node(self, node, path): for hash_value in path: if isinstance(node, LeafStatisticsNode): break for stats in node.get_child_keys(): if hash(stats) == hash_value: node = node.get_child_node(stats) bre...
Finds a node by the given path from the given node.
def make_shift_function(alphabet): def shift_case_sensitive(shift, symbol): case = [case for case in alphabet if symbol in case] if not case: return symbol case = case[0] index = case.index(symbol) return case[(index - shift) % len(case)] return shift_c...
Construct a shift function from an alphabet. Examples: Shift cases independently >>> make_shift_function([string.ascii_uppercase, string.ascii_lowercase]) <function make_shift_function.<locals>.shift_case_sensitive> Additionally shift punctuation characters >>> make_shift...
def execute_command_with_connection(self, context, command, *args): logger = self.context_based_logger_factory.create_logger_for_context( logger_name=, context=context) if not command: logger.error(COMMAND_CANNOT_BE_NONE) raise Exception(COMMAND...
Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command :param command: :param context: instance of ResourceCommandContext or AutoLoadCommandContext :type context: cloudshell.shell.core.context.ResourceCommandContext :param args:
def wait_for_servers(session, servers): nclient = nova.Client(NOVA_VERSION, session=session, region_name=os.environ[]) while True: deployed = [] undeployed = [] for server in servers: c = nclient.servers.get(server.id) if c.addresses...
Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH connection to be ready.
def get_group_dict(user=None, include_default=True): staffsudo if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) r...
Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27}
def add(self, node): self.sons.append(node) node.parent = self
Add one node as descendant
def nan_empty(self, col: str): try: self.df[col] = self.df[col].replace(, nan) self.ok("Filled empty values with nan in column " + col) except Exception as e: self.err(e, "Can not fill empty values with nan")
Fill empty values with NaN values :param col: name of the colum :type col: str :example: ``ds.nan_empty("mycol")``
def widget_from_single_value(o): if isinstance(o, string_types): return Text(value=unicode_type(o)) elif isinstance(o, bool): return Checkbox(value=o) elif isinstance(o, Integral): min, max, value = _get_min_max_value(None, None, o) return...
Make widgets from single values, which can be used as parameter defaults.
def nfa_union(nfa_1: dict, nfa_2: dict) -> dict: union = { : nfa_1[].union(nfa_2[]), : nfa_1[].union(nfa_2[]), : nfa_1[].union(nfa_2[]), : nfa_1[].union(nfa_2[]), : nfa_1[].copy()} for trans in nfa_2[]: for elem in nfa_2[][trans]: ...
Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_2` and runs it on the input word. It is defined as: :math:`A...
def with_run_kwargs(self, **kwargs: Dict[str, Any]) -> : self._run_kwargs = kwargs return self
Replace Tensorflow session run kwargs. Check Tensorflow session run [documentation](https://www.tensorflow.org/api_docs/python/tf/Session). :param kwargs: Dictionary of tensors as keys and numpy arrays or primitive python types as values. :return: Optimization instance s...
def plot_pc_scatter(self, pc1, pc2, v=True, subset=None, ax=None, color=None, s=None, marker=None, color_name=None, s_name=None, marker_name=None): import matplotlib.pyplot as plt if v: df = self.v else: df = self.u...
Make a scatter plot of two principal components. You can create differently colored, sized, or marked scatter points. Parameters ---------- pc1 : str String of form PCX where X is the number of the principal component you want to plot on the x-axis. ...
def heappush(heap, item): heap.append(item) _siftdown(heap, 0, len(heap)-1)
Push item onto heap, maintaining the heap invariant.
def add_update_callback(self, group=None, name=None, cb=None): if not group and not name: self.all_update_callback.add_callback(cb) elif not name: if group not in self.group_update_callbacks: self.group_update_callbacks[group] = Caller() self....
Add a callback for a specific parameter name. This callback will be executed when a new value is read from the Crazyflie.
def make_sentence(self, init_state=None, **kwargs): tries = kwargs.get(, DEFAULT_TRIES) mor = kwargs.get(, DEFAULT_MAX_OVERLAP_RATIO) mot = kwargs.get(, DEFAULT_MAX_OVERLAP_TOTAL) test_output = kwargs.get(, True) max_words = kwargs.get(, None) if init_state != N...
Attempts `tries` (default: 10) times to generate a valid sentence, based on the model and `test_sentence_output`. Passes `max_overlap_ratio` and `max_overlap_total` to `test_sentence_output`. If successful, returns the sentence as a string. If not, returns None. If `init_state` (a tupl...
def __load_parcov(self): if not self.parcov_arg: if self.pst_arg: self.parcov_arg = self.pst_arg else: raise Exception("linear_analysis.__load_parcov(): " + "parcov_arg is None") if isinsta...
private method to set the parcov attribute from: a pest control file (parameter bounds) a pst object a matrix object an uncert file an ascii matrix file
def write_ioc_to_file(self, output_dir=None, force=False): return write_ioc(self.root, output_dir, force=force)
Serialize the IOC to a .ioc file. :param output_dir: Directory to write the ioc out to. default is the current working directory. :param force: If specified, will not validate the root node of the IOC is 'OpenIOC'. :return:
def get_dates_file(path): with open(path) as f: dates = f.readlines() return [(convert_time_string(date_string.split(" ")[0]), float(date_string.split(" ")[1])) for date_string in dates]
parse dates file of dates and probability of choosing
def set_tag(self, tag): if self._world: if self._world.get_entity_by_tag(tag): raise NonUniqueTagError(tag) self._tag = tag
Sets the tag. If the Entity belongs to the world it will check for tag conflicts.
def is_restricted(self, assets, dt): if isinstance(assets, Asset): return assets in self._restricted_set return pd.Series( index=pd.Index(assets), data=vectorized_is_element(assets, self._restricted_set) )
An asset is restricted for all dts if it is in the static list.
def inverse(self, z): z = np.asarray(z) t = np.exp(-z) return 1. / (1. + t)
Inverse of the logit transform Parameters ---------- z : array-like The value of the logit transform at `p` Returns ------- p : array Probabilities Notes ----- g^(-1)(z) = exp(z)/(1+exp(z))
def _spill(self): global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(path) used_memory = get_used_memory() if not self.pdata: ...
dump already partitioned data into disks.
def key_to_int(key, base=BASE62): base_length = len(base) value = 0 for c in reversed(key): value = (value * base_length) + base.index(c) return value
Convert the following key to an integer. @param key: a key. @param base: a sequence of characters that was used to encode the integer value. @return: the integer value corresponding to the given key. @raise ValueError: if one character of the specified key doesn't match any char...
def indent(txt, spacing=4): return prefix(str(txt), .join([ for _ in range(spacing)]))
Indent given text using custom spacing, default is set to 4.
def create_build_context(image, inputs, wdir): assert os.path.isabs(wdir) dockerlines = ["FROM %s" % image, "RUN mkdir -p %s" % wdir] build_context = {} if inputs: dockerlines.append() for ifile, (path, obj) in enumerate(inputs.items()): i...
Creates a tar archive with a dockerfile and a directory called "inputs" The Dockerfile will copy the "inputs" directory to the chosen working directory
def pick_enclosure_link(post, parameter=): t be updated.hreftype')): continue return dict(link=href)
Override URL of the Post to point to url of the first enclosure with href attribute non-empty and type matching specified regexp parameter (empty=any). Missing "type" attribute for enclosure will be matched as an empty string. If none of the enclosures match, link won't be updated.
def get_settings(): settings = {} for config_file in config_files(): config_contents = load_config(config_file) if config_contents is not None: settings = deep_merge(settings, config_contents) return settings
Get all currently loaded settings.
def is_default_port(self): if self.port is None: return False default = DEFAULT_PORTS.get(self.scheme) if default is None: return False return self.port == default
A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise.
def bytes(self): addrbyte = b if self.addr is not None: addrbyte = self.addr return addrbyte
Emit the address in bytes format.
def envs(self): load = {: } return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
Return a list of available environments
def rm_subtitles(path): sub_exts = [, , ] count = 0 for root, dirs, files in os.walk(path): for f in files: _, ext = os.path.splitext(f) ext = ext[1:] if ext in sub_exts: p = os.path.join(root, f) count += 1 pri...
delete all subtitles in path recursively
def apply(self, name, foci): if name in self.transformations: return transform(foci, self.transformations[name]) else: logger.info( "No transformation named found; coordinates left " "untransformed." % name) return foci
Apply a named transformation to a set of foci. If the named transformation doesn't exist, return foci untransformed.
def gps_inject_data_send(self, target_system, target_component, len, data, force_mavlink1=False): return self.send(self.gps_inject_data_encode(target_system, target_component, len, data), force_mavlink1=force_mavlink1)
data for injecting into the onboard GPS (used for DGPS) target_system : System ID (uint8_t) target_component : Component ID (uint8_t) len : data length (uint8_t) data : raw data (110 is enoug...
def basic_auth_user(self, realm, user_name, password, environ): user = self._get_realm_entry(realm, user_name) if user is not None and password == user.get("password"): environ["wsgidav.auth.roles"] = user.get("roles", []) return True return False
Returns True if this user_name/password pair is valid for the realm, False otherwise. Used for basic authentication.
def rangecalc(x, y=None, pad=0.05): mn = np.nanmin([np.nanmin(x), np.nanmin(y)]) mx = np.nanmax([np.nanmax(x), np.nanmax(y)]) rn = mx - mn return (mn - pad * rn, mx + pad * rn)
Calculate padded range limits for axes.
def validate_protocol(protocol): if not re.match(PROTOCOL_REGEX, protocol): raise ValueError(f) return protocol.lower()
Validate a protocol, a string, and return it.
def make_bucket(self, bucket_name, location=): is_valid_bucket_name(bucket_name) region = if self._region: region = self._region if self._region != location: raise InvalidArgumentError("Configured region {0}, requested" ...
Make a new bucket on the server. Optionally include Location. ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-west-1', 'eu-west-2', 'ca-central-1', 'eu-central-1', 'sa-east-1', 'cn-north-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northe...
def save_list(lst, path): with open(path, ) as out: lines = [] for item in lst: if isinstance(item, (six.text_type, six.binary_type)): lines.append(make_str(item)) else: lines.append(make_str(json.dumps(item))) out.write(b.join(li...
Save items from list to the file.
def is_multipart(header_dict): return ( {k.lower(): v for k, v in header_dict.items()} .get(, ) .startswith() )
Args: header_dict : CaseInsensitiveDict Returns: bool: ``True`` if ``header_dict`` has a Content-Type key (case insensitive) with value that begins with 'multipart'.
def nd_sort_samples(samples): assert len(samples.shape) == 2 tree = cKDTree(samples) d, i = tree.query(samples[0], k=len(samples)) return i
Sort an N-dimensional list of samples using a KDTree. :param samples: ``(nsamples, ndim)`` The list of samples. This must be a two-dimensional array. :returns i: ``(nsamples,)`` The list of indices into the original array that return the correctly sorted version.
def cbpdnmd_ustep(k): mp_Z_U0[k] += mp_DX[k] - mp_Z_Y0[k] - mp_S[k] mp_Z_U1[k] += mp_Z_X[k] - mp_Z_Y1[k]
Do the U step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
def set_ground_width(self, ground_width): state = self.state state.ground_width = ground_width state.panel.re_center(state.width/2, state.height/2, state.lat, state.lon)
set ground width of view
def evaluate(self, sequence, transformations): result = sequence parallel = partial( parallelize, processes=self.processes, partition_size=self.partition_size) staged = [] for transform in transformations: strategies = transform.execution_strategies or {}...
Execute the sequence of transformations in parallel :param sequence: Sequence to evaluation :param transformations: Transformations to apply :return: Resulting sequence or value
def _get_autoscaling_min_max(template, parameters, asg_name): params = {e[]: e[] for e in parameters} asg = template.get(, {}).get(asg_name, None) if asg: assert asg[] == min = asg.get(, {}).get(, None) max = asg.get(, {}).get(, None) if in min: min = param...
Helper to extract the configured MinSize, MaxSize attributes from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param asg_name: logical resource name of the autoscaling group :return: MinSize, MaxSize
def decode(self, encoded_packet): ep = encoded_packet try: self.packet_type = int(ep[0:1]) except TypeError: self.packet_type = ep ep = self.namespace = None self.data = None ep = ep[1:] dash = ep.find() attach...
Decode a transmitted package. The return value indicates how many binary attachment packets are necessary to fully decode the packet.
def predict(self, X): kernel_mat = self._get_kernel(X, self.fit_X_) val = numpy.dot(kernel_mat, self.coef_) if hasattr(self, "intercept_"): val += self.intercept_ if self.rank_ratio == 1: val *= -1 else: val = n...
Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape = (n_samples,) ...
def parse_stations(html): html = html.replace(, ).replace(, ) html = json.loads(html) return html[]
Strips JS code, loads JSON
def get_stations(self): status, data = self.http_client.get_json( STATIONS_URI, params={: self.API_key}, headers={: }) return [self.stations_parser.parse_dict(item) for item in data]
Retrieves all of the user's stations registered on the Stations API. :returns: list of *pyowm.stationsapi30.station.Station* objects
def parse(self, limit=None): if limit is not None: LOG.info("Only parsing first %s rows fo each file", str(limit)) LOG.info("Parsing files...") if self.test_only: self.test_mode = True self._process_diseases(limit) self._process_genes(limit) ...
:param limit: :return:
def InvalidLineEnd(self, bad_line_end, context=None, type=TYPE_WARNING): e = InvalidLineEnd(bad_line_end=bad_line_end, context=context, context2=self._context, type=type) self.AddToAccumulator(e)
bad_line_end is a human readable string.
def find_egg(self, egg_dist): site_packages = self.libdir[1] search_filename = "{0}.egg-link".format(egg_dist.project_name) try: user_site = site.getusersitepackages() except AttributeError: user_site = site.USER_SITE search_locations = [site_pack...
Find an egg by name in the given environment
def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None): mem_value = encoder_outputs decoder_states = [mem_value] mem_length = mem_value.shape[1] if encoder_valid_length is not None: dtype = encoder_valid_length.dtype ctx = encoder_v...
Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list The decoder states, includes: - mem_value : NDArray - me...
def comparable(self): string_parts = [] if self.cipher_mode: string_parts.append(.format(self.cipher_mode)) if self.encryption_method: string_parts.append(.format( self.encryption_method)) if self.initialization_vector: initialization_vector = codecs.encode(self.initi...
str: comparable representation of the path specification.
def get_config(config_file): def load(fp): try: return yaml.safe_load(fp) except yaml.YAMLError as e: sys.stderr.write(text_type(e)) sys.exit(1) if config_file == : return load(sys.stdin) if not os.path.exists(config_file): sys.stde...
Get configuration from a file.
def to_table(components, topo_info): inputs, outputs = defaultdict(list), defaultdict(list) for ctype, component in components.items(): if ctype == : for component_name, component_info in component.items(): for input_stream in component_info[]: input_name = input_stream[] in...
normalize raw logical plan info to table
def logpdf_link(self, link_f, y, Y_metadata=None): return -link_f + y*np.log(link_f) - special.gammaln(y+1)
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = -\\lambda(f_{i}) + y_{i}\\log \\lambda(f_{i}) - \\log y_{i}! :param link_f: latent variables (link(f)) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata:...
def _load_profile(self, profile_name): default_profile = self._profile_list[0] for profile in self._profile_list: if profile.get(, False): default_profile = profile if profile[] == profile_name: break el...
Load a profile by name Called by load_user_options
def language_match(self, cpeset, cpel_dom=None): TAG_ROOT = TAG_PLATSPEC = TAG_PLATFORM = TAG_LOGITEST = TAG_CPE = TAG_CHECK_CPE = ATT_NAME = ATT_OP = ATT_NEGATE = ATT_OP_AN...
Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applicability Language, represented as the XML infoset for the ...
def fake2db_logger(): username = getpass.getuser() FORMAT = logging.basicConfig(format=FORMAT) extra_information = {: username} logger = logging.getLogger() return logger, extra_information
creates a logger obj
def index(self, axes): return None if axes is self._colormap_axes else self._axes.index(axes)
:param axes: The Axes instance to find the index of. :type axes: Axes :rtype: int
def yesterday(date=None): if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1)
yesterday once more
def RootNode(self): tree = self.loader.get_root( self.viewType ) adapter = self.loader.get_adapter( self.viewType ) rows = self.loader.get_rows( self.viewType ) adapter.SetPercentage(self.percentageView, adapter.value( tree )) return adapter, tree, rows
Return our current root node and appropriate adapter for it
def next_run_in(self, utc_now=None): if utc_now is None: utc_now = datetime.utcnow() if self.is_alive(): next_run = timedelta(seconds=self.interval_current) + self.activation_dt return next_run - utc_now else: return None
:param utc_now: optional parameter to be used by Unit Tests as a definition of "now" :return: timedelta instance presenting amount of time before the trigger is triggered next time or None if the RepeatTimer instance is not running