code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def prng(s):
return tf_np.asarray(s, dtype=_RNG_KEY_DTYPE) | Creates RNG state from seed.
Args:
s: the seed, an integer.
Returns:
An RNG state, as a scalar array of dtype `np.int64`. | github-repos |
def WriteStatEntries(stat_entries, client_id, mutation_pool, token=None):
for stat_response in stat_entries:
if stat_response.pathspec.last.stream_name:
stat_response.st_mode &= ~stat_type_mask
stat_response.st_mode |= stat.S_IFREG
if data_store.AFF4Enabled():
fo... | Persists information about stat entries.
Args:
stat_entries: A list of `StatEntry` instances.
client_id: An id of a client the stat entries come from.
mutation_pool: A mutation pool used for writing into the AFF4 data store.
token: A token used for writing into the AFF4 data store. | juraj-google-style |
def __init__(self, filename=None):
self._alphabet = set()
self.filename = filename
if filename is not None:
self._load_from_file(filename)
super(SubwordTextEncoder, self).__init__() | Initialize and read from a file, if provided.
Args:
filename: filename from which to read vocab. If None, do not load a
vocab | juraj-google-style |
def get_grappler_config(optimizers_list):
config = _config_pb2.ConfigProto()
rewrite_options = config.graph_options.rewrite_options
for optimizer in optimizers_list:
rewrite_options.optimizers.append(optimizer)
return config | Creates a tf.compat.v1.ConfigProto for configuring Grappler.
Args:
optimizers_list: List of strings that represents the list of optimizers.
Returns:
tf.ConfigProto. | github-repos |
def authenticate(self, username, password, service='login', encoding='utf-8', resetcreds=True):
@conv_func
def my_conv(n_messages, messages, p_response, app_data):
'Simple conversation function that responds to any\n prompt where the echo is off with the supplied password'
addr = ... | username and password authentication for the given service.
Returns True for success, or False for failure.
self.code (integer) and self.reason (string) are always stored and may
be referenced for the reason why authentication failed. 0/'Success' will
be stored for success.
Python3 expects bytes() for ctypes inputs.... | codesearchnet |
def run_query(self, view: views.View, limit: Optional[int]=None) -> bigquery.QueryJob:
return self._client.query(self.to_sql(view, limit=limit)) | Runs query for the view and returns the corresponding BigQuery job.
Args:
view: the view that defines the query to run.
limit: optional limit of the number of items to return.
Returns:
bigquery.QueryJob: the job for the running query. | github-repos |
def __init__(
self, file_object, member_start_offset, uncompressed_data_offset):
self.comment = None
self.modification_time = None
self.operating_system = None
self.original_filename = None
self._cache_start_offset = None
self._cache_end_offset = None
self._ca... | Initializes a gzip member.
Args:
file_object (FileIO): file-like object, containing the gzip member.
member_start_offset (int): offset to the beginning of the gzip member
in the containing file.
uncompressed_data_offset (int): current offset into the uncompressed data
in the containing file. | juraj-google-style |
def union(self, other):
union = Rect()
lib.SDL_UnionRect(self._ptr, other._ptr, union._ptr)
return union | Calculate the union of this rectangle and another rectangle.
Args:
other (Rect): The other rectangle.
Returns:
Rect: The union of this rectangle and the given other rectangle. | juraj-google-style |
def set_hyperparameters(self, hyperparameters):
for (block_name, block_hyperparams) in hyperparameters.items():
self.blocks[block_name].set_hyperparameters(block_hyperparams) | Set new hyperparameter values for some blocks.
Args:
hyperparameters (dict): A dictionary containing the block names as
keys and the new hyperparameters dictionary
as values. | codesearchnet |
def notify_batch_pending(self, batch):
txn_ids = {t.header_signature for t in batch.transactions}
with self._lock:
self._pending.add(batch.header_signature)
self._batch_info[batch.header_signature] = txn_ids
self._update_observers(batch.header_signature,
... | Adds a Batch id to the pending cache, with its transaction ids.
Args:
batch (str): The id of the pending batch | juraj-google-style |
def __init__(self, min_bundle_size=0, desired_bundle_size=DEFAULT_DESIRED_BUNDLE_SIZE, use_fastavro=True, with_filename=False, label='ReadAllFiles'):
source_from_file = partial(_FastAvroSource, min_bundle_size=min_bundle_size)
self._read_all_files = filebasedsource.ReadAllFiles(True, CompressionTypes.AUTO, desi... | Initializes ``ReadAllFromAvro``.
Args:
min_bundle_size: the minimum size in bytes, to be considered when
splitting the input into bundles.
desired_bundle_size: the desired size in bytes, to be considered when
splitting the input into bundles.
use_fastavro (bool): This flag is left for API backwards compatibility
and n... | github-repos |
def _export_debug_info(exported_graph: ops.Graph, export_dir: str):
debug_builder = tf_stack.GraphDebugInfoBuilder()
for fn_name in exported_graph._functions:
fn = exported_graph._get_function(fn_name)
if not isinstance(fn, defun.AtomicFunction):
continue
debug_builder.Append... | Exports debug information from graph to file.
Creates and writes GraphDebugInfo with traces for ops in all functions of the
exported_graph.
Args:
exported_graph: A Graph that has been created by tracing a saveable view.
export_dir: SavedModel directory in which to write the debug info. | github-repos |
def parse_command(command):
command = command.strip()
if not command:
return []
brackets_intervals = [f.span() for f in _BRACKETS_PATTERN.finditer(command)]
quotes_intervals = [f.span() for f in _QUOTES_PATTERN.finditer(command)]
whitespaces_intervals = [f.span() for f in _WHITESPACE_PATTERN... | Parse command string into a list of arguments.
- Disregards whitespace inside double quotes and brackets.
- Strips paired leading and trailing double quotes in arguments.
- Splits the command at whitespace.
Nested double quotes and brackets are not handled.
Args:
command: (str) Input command.
Returns:
(list of str)... | github-repos |
def _extract_nn_info(self, structure, nns):
if self.targets is None:
targets = structure.composition.elements
else:
targets = self.targets
siw = []
max_weight = max(nn[self.weight] for nn in nns.values())
for nstats in nns.valu... | Given Voronoi NNs, extract the NN info in the form needed by NearestNeighbors
Args:
structure (Structure): Structure being evaluated
nns ([dicts]): Nearest neighbor information for a structure
Returns:
(list of tuples (Site, array, float)): See nn_info | juraj-google-style |
def __init__(self,
nlp,
tokenizer,
extractor_name: str) -> None:
Extractor.__init__(self,
input_type=InputType.TEXT,
category="build_in_extractor",
name=extractor_name)
... | Initialize the extractor, storing the rule information and construct spacy rules
Args:
nlp:
tokenizer: Tokenizer
extractor_name: str
Returns: | juraj-google-style |
def parse_arguments(argv):
parser = argparse.ArgumentParser(description='online-clustering')
parser.add_argument('-m', '--mode', help='Mode to run pipeline in.', choices=['local', 'cloud'], default='local')
parser.add_argument('-p', '--project', help='GCP project to run pipeline on.', default=cfg.PROJECT_ID... | It parses the arguments passed to the command line and returns them as an object
Args:
argv: The arguments passed to the command line.
Returns:
The arguments that are being passed in. | github-repos |
def _init_from_proto(self, context_def, import_scope=None):
assert isinstance(context_def, control_flow_pb2.WhileContextDef)
g = ops.get_default_graph()
self._name = ops.prepend_name_scope(context_def.context_name, import_scope)
if context_def.maximum_iterations_name:
self._maximum_iterations = ... | Creates a new `WhileContext` from protocol buffer.
Args:
context_def: `WhileContextDef` protocol buffer.
import_scope: Optional `string`. Name scope to add. | github-repos |
def _xys(date):
(X, Y, s_xy2) = _xysxy2(date)
(dX, dY) = ((date.eop.dx / 1000.0), (date.eop.dy / 1000.0))
X = np.radians(((X + dX) / 3600.0))
Y = np.radians(((Y + dY) / 3600.0))
s = (np.radians((s_xy2 / 3600.0)) - ((X * Y) / 2))
return (X, Y, s) | Get The X, Y and s coordinates
Args:
date (Date):
Return:
3-tuple of float: Values of X, Y and s, in radians | codesearchnet |
def is_union(declaration):
if not is_class(declaration):
return False
decl = class_traits.get_declaration(declaration)
return decl.class_type == class_declaration.CLASS_TYPES.UNION | Returns True if declaration represents a C++ union
Args:
declaration (declaration_t): the declaration to be checked.
Returns:
bool: True if declaration represents a C++ union | juraj-google-style |
def reduce(self, initial_state, reduce_func): | Reduces this iterable object to a single element.
The transformation calls `reduce_func` successively on each element.
The `initial_state` argument is used for the initial state and the final
state is returned as the result.
Args:
initial_state: An element representing the initial state of the
reduction.
reduce_func:... | github-repos |
def _key_for_namespace(namespace, app):
if namespace:
return db.Key.from_path(metadata.Namespace.KIND_NAME,
namespace,
_app=app)
else:
return db.Key.from_path(metadata.Namespace.KIND_NAME,
metadata.Namespace.EMPTY_NAMESPA... | Return the __namespace__ key for a namespace.
Args:
namespace: The namespace whose key is requested.
app: The id of the application that the key belongs to.
Returns:
A db.Key representing the namespace. | juraj-google-style |
def state_view_for_block(block_wrapper, state_view_factory):
state_root_hash = (block_wrapper.state_root_hash if (block_wrapper is not None) else None)
return state_view_factory.create_view(state_root_hash) | Returns the state view for an arbitrary block.
Args:
block_wrapper (BlockWrapper): The block for which a state
view is to be returned
state_view_factory (StateViewFactory): The state view factory
used to create the StateView object
Returns:
StateView object associated with the block | codesearchnet |
def delete(self, domain, type_name, search_command):
return self._request(domain, type_name, search_command, 'DELETE', None) | Delete entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_command (string): Search command to pass to ES. | codesearchnet |
def upsert(self, insert_index, val, fn=None):
fn = fn or (lambda current, passed: passed)
self._magnitude = 0
position = self.position_for_index(insert_index)
if position < len(self.elements) and self.elements[position] == insert_index:
self.elements[position + 1] = ... | Inserts or updates an existing index within the vector.
Args:
- insert_index (int): The index at which the element should be
inserted.
- val (int|float): The value to be inserted into the vector.
- fn (callable, optional): An optional callable taking two
arguments, the current value and the passed value to generate
th... | juraj-google-style |
def __init__(self, c_list):
c_list = [NthOrderElasticTensor(c, check_rank=4+i*2)
for i, c in enumerate(c_list)]
super().__init__(c_list) | Initialization method for ElasticTensorExpansion
Args:
c_list (list or tuple): sequence of Tensor inputs
or tensors from which the elastic tensor
expansion is constructed. | juraj-google-style |
def _parameter_net(self, theta, kernel_shape=9):
with argscope(FullyConnected, nl=tf.nn.leaky_relu):
net = FullyConnected('fc1', theta, 64)
net = FullyConnected('fc2', net, 128)
pred_filter = FullyConnected('fc3', net, (kernel_shape ** 2), nl=tf.identity)
pred_filter = tf.reshape(pred_filter... | Estimate filters for convolution layers
Args:
theta: angle of filter
kernel_shape: size of each filter
Returns:
learned filter as [B, k, k, 1] | codesearchnet |
def create_subscription(self, *, customer_id, credit_card_token, plan_code, quantity=None, installments=None, trial_days=None, immediate_payment=None, extra1=None, extra2=None, delivery_address=None, notify_url=None, recurring_bill_items=None):
payload = {'quantity': quantity, 'installments': installments, 'trialDa... | Creating a new subscription of a client to a plan.
Args:
customer_id: Customer that will be associated to the subscription.
You can find more information in the "Customer" section of this page.
credit_card_token: Customer's credit card that is selected to make the payment.
You can find more information in the "Credit... | codesearchnet |
def _send_request(self, url, method='get', data=None, extra_headers=None):
headers = {'Content-type': 'application/json'}
if isinstance(extra_headers, dict):
headers.update(extra_headers)
if ((not data) or ('password' not in data)):
logger.debug('Sending {method} request to {url} with data {... | Performs a given request and returns a json object
Args:
url (str): URL of the request
method (str): Any of "get", "post", "delete"
data (any): Possible extra data to send with the request
extra_headers (dict): Possible extra headers to send along in the request
Returns:
dict | codesearchnet |
def activate(self, experiment_key, user_id, attributes=None):
if not self.is_valid:
self.logger.error(enums.Errors.INVALID_DATAFILE.format('activate'))
return None
if not validator.is_non_empty_string(experiment_key):
self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('experiment... | Buckets visitor and sends impression event to Optimizely.
Args:
experiment_key: Experiment which needs to be activated.
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
Variation key representing the variation the user will be bucketed in.
None if user... | juraj-google-style |
def create_graph_from_data(self, data, **kwargs):
self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test]
self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.method_indep]
self.arguments['{DIRECTED}'] = 'TRUE'
self.arguments['{ALPHA}'] = str(self.alpha)
... | Run the PC algorithm.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by PC on the given data. | juraj-google-style |
def write_all_sequences_file(self, outname, outdir=None):
if not outdir:
outdir = self.sequence_dir
if not outdir:
raise ValueError('Output directory must be specified')
outfile = op.join(outdir, outname + '.faa')
SeqIO.write(self.sequences, out... | Write all the stored sequences as a single FASTA file. By default, sets IDs to model gene IDs.
Args:
outname (str): Name of the output FASTA file without the extension
outdir (str): Path to output directory for the file, default is the sequences directory | juraj-google-style |
def iter_packages(self, name, range_=None, paths=None):
for package in iter_packages(name, range_, paths):
if not self.excludes(package):
yield package | Same as iter_packages in packages.py, but also applies this filter.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
... | juraj-google-style |
def receive(self, length):
slipDriver = sliplib.Driver()
ret = self._serialPort.read(length)
temp = slipDriver.receive(ret)
return iter(temp) | Reads in data from a serial port (length bytes), decodes SLIP packets
A function which reads from the serial port and then uses the SlipLib
module to decode the SLIP protocol packets. Each message received
is added to a receive buffer in SlipLib which is then returned.
Args:
length (int): Length to receive with seria... | juraj-google-style |
def parse(ifp, pb_cls, **kwargs):
mode = 'rb'
if isinstance(ifp, str):
istream = open(ifp, mode=mode, **kwargs)
else:
istream = open(fileobj=ifp, mode=mode, **kwargs)
with istream:
for data in istream:
pb_obj = pb_cls()
pb_obj.ParseFromString(data)
... | Parse a stream.
Args:
ifp (string or file-like object): input stream.
pb_cls (protobuf.message.Message.__class__): The class object of
the protobuf message type encoded in the stream. | juraj-google-style |
def make_list_of_t(ts, check_graph=True, allow_graph=True, ignore_ops=False):
if isinstance(ts, ops.Graph):
if allow_graph:
return get_tensors(ts)
else:
raise TypeError('allow_graph is False: cannot convert a tf.Graph.')
else:
if not is_iterable(ts):
t... | Convert ts to a list of `tf.Tensor`.
Args:
ts: can be an iterable of `tf.Tensor`, a `tf.Graph` or a single tensor.
check_graph: if `True` check if all the tensors belong to the same graph.
allow_graph: if `False` a `tf.Graph` cannot be converted.
ignore_ops: if `True`, silently ignore `tf.Operation`.
Returns:
A newly ... | github-repos |
def set_defaults(self, defaults):
def defaults_recurse(current, defaults):
"Walk the current context tree in recursive inner function.\n\n On 1st iteration, current = self (i.e root of context)\n On subsequent recursive iterations, current is wherever you're at\n in the nes... | Set defaults in context if keys do not exist already.
Adds the input dict (defaults) into the context, only where keys in
defaults do not already exist in context. Supports nested hierarchies.
Example:
Given a context like this:
key1: value1
key2:
key2.1: value2.1
key3: None
And defaults input like this:
key1: 'upda... | codesearchnet |
def __init__(self, credential=None):
self.credential = credential | Initializes FormatToQido.
Args:
credential: # type: Google credential object, if it is specified, the
Http client will use it instead of the default one. | github-repos |
def GetMessages(self, soft_size_limit=None):
with self._lock:
ret = rdf_flows.MessageList()
ret_size = 0
for message in self._Generate():
self._total_size -= len(message)
ret.job.append(rdf_flows.GrrMessage.FromSerializedString(message))
ret_size += len(me... | Retrieves and removes the messages from the queue.
Args:
soft_size_limit: int If there is more data in the queue than
soft_size_limit bytes, the returned list of messages will be
approximately this large. If None (default), returns all messages
currently on the queue.
Returns:
rdf_flows.MessageList A list of messages... | codesearchnet |
def softsign(x):
if any_symbolic_tensors((x,)):
return Softsign().symbolic_call(x)
return backend.nn.softsign(x) | Softsign activation function.
It is defined as `f(x) = x / (abs(x) + 1)`.
Args:
x: Input tensor.
Returns:
A tensor with the same shape as `x`.
Example:
>>> x = keras.ops.convert_to_tensor([-0.100, -10.0, 1.0, 0.0, 100.0])
>>> keras.ops.softsign(x)
Array([-0.09090909, -0.90909094, 0.5, 0.0, 0.990099], dtype=float32... | github-repos |
def WritePathHashHistory(self, client_path, hash_entries):
client_path_history = ClientPathHistory()
for (timestamp, hash_entry) in iteritems(hash_entries):
client_path_history.AddHashEntry(timestamp, hash_entry)
self.MultiWritePathHistory({client_path: client_path_history}) | Writes a collection of `Hash` observed for particular path.
Args:
client_path: A `ClientPath` instance.
hash_entries: A dictionary with timestamps as keys and `Hash` instances as
values. | codesearchnet |
def recommendations(self, **kwargs):
path = self._get_id_path('recommendations')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get a list of recommended movies for a movie.
Args:
language: (optional) ISO 639-1 code.
page: (optional) Minimum value of 1. Expected value is an integer.
Returns:
A dict representation of the JSON returned from the API. | codesearchnet |
def _ReadStructureDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):
if is_member:
error_message = 'data type not supported as member'
raise errors.DefinitionReaderError(definition_name, error_message)
return self._ReadDataTypeDefinitionWithMembe... | 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 type definition is a member
data type d... | codesearchnet |
def _remove_hdxobject(self, objlist, obj, matchon='id', delete=False):
if objlist is None:
return False
if isinstance(obj, six.string_types):
obj_id = obj
elif isinstance(obj, dict) or isinstance(obj, HDXObject):
obj_id = obj.get(matchon)
... | Remove an HDX object from a list within the parent HDX object
Args:
objlist (List[Union[T <= HDXObject,Dict]]): list of HDX objects
obj (Union[T <= HDXObject,Dict,str]): Either an id or hdx object metadata either from an HDX object or a dictionary
matchon (str): Field to match on. Defaults to id.
delete (bool): Whethe... | juraj-google-style |
def print_math(math_expression_lst, name='math.html', out='html', formatter=(lambda x: x)):
try:
shutil.rmtree('viz')
except:
pass
pth = (get_cur_path() + print_math_template_path)
shutil.copytree(pth, 'viz')
html_loc = None
if (out == 'html'):
html_loc = (pth + 'standalo... | Converts LaTeX math expressions into an html layout.
Creates a html file in the directory where print_math is called
by default. Displays math to jupyter notebook if "notebook" argument
is specified.
Args:
math_expression_lst (list): A list of LaTeX math (string) to be rendered by KaTeX
out (string): {"html"|"noteboo... | codesearchnet |
def dot(matrix, vector, matrix_ty, vector_ty):
weld_obj = WeldObject(encoder_, decoder_)
matrix_var = weld_obj.update(matrix)
if isinstance(matrix, WeldObject):
matrix_var = matrix.obj_id
weld_obj.dependencies[matrix_var] = matrix
vector_var = weld_obj.update(vector)
loopsize_annotat... | Computes the dot product between a matrix and a vector.
Args:
matrix (WeldObject / Numpy.ndarray): 2-d input matrix
vector (WeldObject / Numpy.ndarray): 1-d input vector
ty (WeldType): Type of each element in the input matrix and vector
Returns:
A WeldObject representing this computation | codesearchnet |
def get_enterprise_customer_for_user(auth_user):
EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser')
try:
return EnterpriseCustomerUser.objects.get(user_id=auth_user.id).enterprise_customer
except EnterpriseCustomerUser.DoesNotExist:
return None | Return enterprise customer instance for given user.
Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model,
1. if given user is associated with any enterprise customer, return enterprise customer.
2. otherwise return `None`.
Arguments:
auth_user (contrib.auth.User): Django User
Retu... | codesearchnet |
def boxify(message, border_color=None):
lines = message.split('\n')
max_width = max((_visual_width(line) for line in lines))
padding_horizontal = 5
padding_vertical = 1
box_size_horizontal = (max_width + (padding_horizontal * 2))
chars = {'corner': '+', 'horizontal': '-', 'vertical': '|', 'empty... | Put a message inside a box.
Args:
message (unicode): message to decorate.
border_color (unicode): name of the color to outline the box with. | codesearchnet |
def get_osdp(self, id_or_uri):
uri = self._client.build_subresource_uri(resource_id_or_uri=id_or_uri, subresource_path='osdp')
return self._client.get(uri) | Retrieves facts about Server Profiles and Server Profile Templates that are using Deployment Plan based on the ID or URI provided.
Args:
id_or_uri: ID or URI of the Deployment Plan.
Returns:
dict: Server Profiles and Server Profile Templates | codesearchnet |
def on_predict_end(self, logs=None): | Called at the end of prediction.
Subclasses should override for any actions to run.
Args:
logs: Dict. Currently no data is passed to this argument for this method
but that may change in the future. | github-repos |
def add_headers(vcf_obj, nr_cases=None, sv=False):
vcf_obj.add_info_to_header({'ID': 'Obs', 'Number': '1', 'Type': 'Integer', 'Description': 'The number of observations for the variant'})
if (not sv):
vcf_obj.add_info_to_header({'ID': 'Hom', 'Number': '1', 'Type': 'Integer', 'Description': 'The number o... | Add loqus specific information to a VCF header
Args:
vcf_obj(cyvcf2.VCF) | codesearchnet |
def _ParseCshVariables(self, lines):
paths = {}
for line in lines:
if (len(line) < 2):
continue
action = line[0]
if (action == 'setenv'):
target = line[1]
path_vals = []
if line[2:]:
path_vals = line[2].split(':')
... | Extract env_var and path values from csh derivative shells.
Path attributes can be set several ways:
- setenv takes the form "setenv PATH_NAME COLON:SEPARATED:LIST"
- set takes the form "set path_name=(space separated list)" and is
automatically exported for several types of files.
The first entry in each stanza is u... | codesearchnet |
def find_all(self, collection):
obj = getattr(self.db, collection)
result = obj.find()
return result | Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection. | codesearchnet |
def pre(fqdn, parent, stackdepth, *argl, **argd):
global _atdepth_call, _cstack_call
pcres = _pre_call(_atdepth_call, parent, fqdn, (stackdepth + 1), *argl, **argd)
(entry, _atdepth_call, reduced, bound, ekey) = pcres
_cstack_call.append(fqdn)
return (entry, bound, ekey) | Adds logging for a call to the specified function that is being handled
by an external module.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
parent: *object* that the function belongs to.
stackdepth (int): maximum stack depth before entries are ignored.
argl (list): positional arguments p... | codesearchnet |
def tail(self, n):
if (n < 0):
n = max(0, (len(self.index) + n))
if self._is_transposed:
result = self.__constructor__(self.data.transpose().take(1, (- n)).transpose(), self.index[(- n):], self.columns, self._dtype_cache)
result._is_transposed = True
else:
result = self.__con... | Returns the last n rows.
Args:
n: Integer containing the number of rows to return.
Returns:
DataManager containing the last n rows of the original DataManager. | codesearchnet |
def __init__(self, api_key: str, config: interfaces.Config | None=None):
self._config = config or interfaces.Config()
self._p_genai_model = genai_model.GenaiModel(api_key=api_key, model_name=self._config.topic_generator_model_name, generate_content_config={'response_mime_type': 'application/json', 'response_sch... | Initializes the TopicGenerator.
Args:
api_key: The API key to use for the GenAI API.
config: The agent configuration. | github-repos |
def get_critical_compositions(self, comp1, comp2):
n1 = comp1.num_atoms
n2 = comp2.num_atoms
pd_els = self.elements
c1 = self.pd_coords(comp1)
c2 = self.pd_coords(comp2)
if np.all(c1 == c2):
return [comp1.copy(),... | Get the critical compositions along the tieline between two
compositions. I.e. where the decomposition products change.
The endpoints are also returned.
Args:
comp1, comp2 (Composition): compositions that define the tieline
Returns:
[(Composition)]: list of critical compositions. All are of
the form x * comp1 + (1-x) *... | juraj-google-style |
def __init__(self, channel: 'EFBChannel', new_chats: Iterable[str] = tuple(),
removed_chats: Iterable[str] = tuple(), modified_chats: Iterable[str] = tuple()):
self.channel: 'EFBChannel' = channel
self.new_chats: Iterable[str] = new_chats
self.removed_chats: Iterable[st... | __init__(channel: EFBChannel, new_chats: Iterable[str]=tuple(), removed_chats: Iterable[str]=tuple(), modified_chats: Iterable[str]=tuple())
Args:
channel (:obj:`.EFBChannel`): Slave channel that issues the update
new_chats (Optional[Iterable[str]]): Unique ID of new chats
removed_chats (Optional[Iterable[str]]): Uniq... | juraj-google-style |
def GetHashData(hashable):
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
hashable.SerializeUnsigned(writer)
ms.flush()
retVal = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retVal | Get the data used for hashing.
Args:
hashable (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin
Returns:
bytes: | juraj-google-style |
def __init__(self, auth_key, auth_secret):
self._auth_key = auth_key
self._auth_secret = auth_secret | Create an authentication handler for HouseCanary API V1 requests
Args:
auth_key (string) - The HouseCanary API auth key
auth_secret (string) - The HouseCanary API secret | juraj-google-style |
def getPaddingNum(chars):
match = PRINTF_SYNTAX_PADDING_RE.match(chars)
if match:
return int(match.group(1))
try:
return sum([PAD_MAP[char] for char in chars])
except KeyError:
msg = 'Detected an unsupported padding character: "{}".'
msg += ' Supported padding characters:... | Given a supported group of padding characters, return the amount of padding.
Args:
chars (str): a supported group of padding characters
Returns:
int:
Raises:
ValueError: if unsupported padding character is detected | codesearchnet |
def insecure_channel(target, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False):
return Channel(_grpc.insecure_channel(target, options), loop, executor, standalone_pool_for_streaming) | Creates an insecure Channel to a server.
Args:
target: The server address
options: An optional list of key-value pairs (channel args in gRPC runtime)
to configure the channel.
Returns:
A Channel object. | codesearchnet |
def read_uint64(self, little_endian=True):
if little_endian:
endian = '<'
else:
endian = '>'
return self.unpack(('%sQ' % endian), 8) | Read 8 bytes as an unsigned integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: | codesearchnet |
def add_device(self, device, container):
if (self.findtext('is_smart') == 'false'):
self.add_object_to_path(device, container)
else:
raise ValueError('Devices may not be added to smart groups.') | Add a device to a group. Wraps JSSObject.add_object_to_path.
Args:
device: A JSSObject to add (as list data), to this object.
location: Element or a string path argument to find() | codesearchnet |
def get_by_name(self, name):
result = self.get_by("name", name)
if result:
data = result[0]
new_resource = self.new(self._connection, data)
else:
new_resource = None
return new_resource | Retrieves a resource by its name.
Args:
name: Resource name.
Returns:
Resource object or None if resource does not exist. | juraj-google-style |
def drop_if_default(self, default):
self._default = default
self._drop_if_default = True
return self | The item should be dropped if its value is equal to its default.
Returns:
Returns self. | github-repos |
def really_unicode(in_string):
if isinstance(in_string, StringType):
for args in (('utf-8',), ('latin-1',), ('ascii', 'replace')):
try:
in_string = in_string.decode(*args)
break
except UnicodeDecodeError:
continue
... | Make a string unicode. Really.
Ensure ``in_string`` is returned as unicode through a series of
progressively relaxed decodings.
Args:
in_string (str): The string to convert.
Returns:
str: Unicode.
Raises:
ValueError | juraj-google-style |
def make_lines_texture(num_lines=10, resolution=50):
x, y = np.meshgrid(
np.hstack([np.linspace(0, 1, resolution), np.nan]),
np.linspace(0, 1, num_lines),
)
y[np.isnan(x)] = np.nan
return x.flatten(), y.flatten() | Makes a texture consisting of a given number of horizontal lines.
Args:
num_lines (int): the number of lines to draw
resolution (int): the number of midpoints on each line
Returns:
A texture. | juraj-google-style |
def is_constant_jacobian(self):
return self._is_constant_jacobian | Returns true iff the Jacobian matrix is not a function of x.
Note: Jacobian matrix is either constant for both forward and inverse or
neither.
Returns:
is_constant_jacobian: Python `bool`. | github-repos |
def get_local_config_filepath(config_filepath, force_local=False):
local_config_name = (path.basename(config_filepath).split('.')[0] + '_local.cfg')
local_config_filepath = path.join(path.split(config_filepath)[0], local_config_name)
real_config_filepath = ''
if (path.isfile(local_config_filepath) or fo... | helper for finding local filepath for config
Args:
config_filepath (str): path to local config abspath > relpath
force_local (bool): force return of _local.cfg version
Returns:
str: Path to local config, or global if path DNE | codesearchnet |
def as_bool(self) -> bool:
if len(self._messages) != 1:
raise ValueError('FHIRPath did not evaluate to a single boolean.')
return proto_utils.get_value_at_field(self._messages[0], 'value') | Returns the result as a boolean.
Raises:
ValueError if the `EvaluationResult` is not a single boolean. | github-repos |
def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep + token_ids_1 + sep... | Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns... | github-repos |
def create_mutation_file(self, list_of_tuples):
self.mutation_infile = op.join(self.foldx_dir, 'individual_list.txt')
idx = 1
with open(self.mutation_infile, 'w') as f:
for mutant_group in list_of_tuples:
mutstring = ''.join(list(map(lambd... | Create the FoldX file 'individual_list.txt' to run BuildModel upon.
Args:
list_of_tuples (list): A list of tuples indicating mutation groups to carry out BuildModel upon. Example::
[
(('N', 'A', 308, 'S'), ('S', 'A', 320, 'T'), ('S', 'A', 321, 'H')), # Mutation group 1
(('S', 'A', 321, 'R'), ('T', 'A', 345, 'S')) #... | juraj-google-style |
def emit(self, name, *args, **kwargs):
e = self.__property_events.get(name)
if e is None:
e = self.__events[name]
return e(*args, **kwargs) | Dispatches an event to any subscribed listeners
Note:
If a listener returns :obj:`False`, the event will stop dispatching to
other listeners. Any other return value is ignored.
Args:
name (str): The name of the :class:`Event` to dispatch
*args (Optional): Positional arguments to be sent to listeners
**kwargs (Optiona... | juraj-google-style |
def items(self):
all_items = [(k.decode('utf-8'), v.decode('utf-8')) for (k, v) in self.rdb.hgetall(self.session_hash).items()]
return all_items | Return a list of all the key, value pair tuples in the dictionary.
Returns:
list of tuples: [(key1,value1),(key2,value2),...,(keyN,valueN)] | codesearchnet |
def __init__(self, logger):
self.logger = logger
self.oslogin_installed = True
self.update_time = 0 | Constructor.
Args:
logger: logger object, used to write to SysLog and serial port. | juraj-google-style |
def _parse_dtype(self, space):
if isinstance(space, gym.spaces.Discrete):
return tf.int32
if isinstance(space, gym.spaces.Box):
return tf.float32
raise NotImplementedError() | Get a tensor dtype from a OpenAI Gym space.
Args:
space: Gym space.
Raises:
NotImplementedError: For spaces other than Box and Discrete.
Returns:
TensorFlow data type. | juraj-google-style |
def next_power_of_2(x):
power_of_2 = 1 if x == 0 else 2 ** np.ceil(np.log2(x))
return power_of_2 | Finds the next power of 2 value
Args:
x: Input value
Returns:
power_of_2: Next power of 2 value | juraj-google-style |
def get_developer_package(path, format=None):
from rez.developer_package import DeveloperPackage
return DeveloperPackage.from_path(path, format=format) | Create a developer package.
Args:
path (str): Path to dir containing package definition file.
format (str): Package definition file format, detected if None.
Returns:
`DeveloperPackage`. | codesearchnet |
def argmax(x, axis=None, keepdims=False):
if any_symbolic_tensors((x,)):
return Argmax(axis=axis, keepdims=keepdims).symbolic_call(x)
return backend.numpy.argmax(x, axis=axis, keepdims=keepdims) | Returns the indices of the maximum values along an axis.
Args:
x: Input tensor.
axis: By default, the index is into the flattened tensor, otherwise
along the specified axis.
keepdims: If this is set to `True`, the axes which are reduced are left
in the result as dimensions with size one. Defaults to `False`.
Returns:... | github-repos |
def send_invitation(self, invitation, **kwargs):
return self.email_message(
invitation.invitee_identifier,
self.invitation_subject,
self.invitation_body,
invitation.invited_by,
**kwargs
).send() | Sends an invitation message for a specific invitation.
This could be overridden to do other things, such as sending a confirmation
email to the sender.
Args:
invitation:
Returns: | juraj-google-style |
def valid(self, value, level=[]):
self.validation_failures = []
if value is None and self._optional:
return True
if not isinstance(value, dict):
self.validation_failures.append(('.'.join(level), str(value)))
return False
bRet = True
for k,v in iteritems(value):
lLevel =... | Valid
Checks if a value is valid based on the instance's values
Arguments:
value {mixed} -- The value to validate
Returns:
bool | juraj-google-style |
def _add_sink_state(self, states):
cleared = []
for i in range(0, 128):
cleared.append(-1)
states.append(cleared) | This function adds a sing state in the total states
Args:
states (list): The current states
Returns:
None | juraj-google-style |
class TokenSpan(NamedTuple):
start: int
end: int | Token span in an encoded string (list of tokens).
Args:
start (`int`): Index of the first token in the span.
end (`int`): Index of the token following the last token in the span. | github-repos |
def diffuse_horizontal_illuminance(self, value=999999.0):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
'value {} need to be of type float '
'for field `diffuse_horizon... | Corresponds to IDD Field `diffuse_horizontal_illuminance`
will be missing if >= 999900
Args:
value (float): value for IDD Field `diffuse_horizontal_illuminance`
Unit: lux
value >= 0.0
Missing value: 999999.0
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raise... | juraj-google-style |
async def count(self, text, opts=None):
i = 0
async for _ in self.cell.eval(text, opts=opts, user=self.user):
i += 1
return i | Count the number of nodes which result from a storm query.
Args:
text (str): Storm query text.
opts (dict): Storm query options.
Returns:
(int): The number of nodes resulting from the query. | juraj-google-style |
def _tag_and_add_meta_graph(self, meta_graph_def, tags, signature_def_map):
for tag in tags:
meta_graph_def.meta_info_def.tags.append(tag)
if signature_def_map is not None:
for key in signature_def_map:
meta_graph_def.signature_def[key].CopyFrom(signature_def_map[key])
proto_meta... | Tags the meta graph def and adds it to the SavedModel.
Tags the meta graph def with the supplied tags, adds signature defs to it if
provided and appends the meta graph def to the SavedModel proto.
Args:
meta_graph_def: The meta graph def to add to the SavedModel.
tags: The set of tags to annotate the meta graph def w... | github-repos |
def fetcher_with_object(cls, parent_object, relationship="child"):
fetcher = cls()
fetcher.parent_object = parent_object
fetcher.relationship = relationship
rest_name = cls.managed_object_rest_name()
parent_object.register_fetcher(fetcher, rest_name)
return fe... | Register the fetcher for a served object.
This method will fill the fetcher with `managed_class` instances
Args:
parent_object: the instance of the parent object to serve
Returns:
It returns the fetcher instance. | juraj-google-style |
def base_http_parser():
base_parser = ArgumentParser(add_help=False)
base_parser.add_argument('--url', type=str, help="identify the URL of the validator's REST API (default: http:
base_parser.add_argument('-u', '--user', type=str, metavar='USERNAME[:PASSWORD]', help='specify the user to authorize request')
... | Creates a parser with arguments specific to sending an HTTP request
to the REST API.
Returns:
{ArgumentParser}: Base parser with default HTTP args | codesearchnet |
def sasl_plain(self, name, password, identity=None):
if identity is None:
identity = name
self.sasl('plain', name, password, identity) | Authenticate to a server using SASL plain, or does so on connection.
Args:
name (str): Name to auth with.
password (str): Password to auth with.
identity (str): Identity to auth with (defaults to name). | juraj-google-style |
def set_colour(self, r, g, b):
if not 0 <= r <= 255:
raise ValueError("The value for red needs to be between 0 and 255.")
if not 0 <= g <= 255:
raise ValueError("The value for green needs to be between 0 and 255.")
if not 0 <= b <= 255:
raise ValueErr... | Set colour of an rgb bulb.
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255. | juraj-google-style |
def __sendCommand(self, cmd):
logging.info('%s: sendCommand[%s]', self.port, cmd)
if self.logThreadStatus == self.logStatus['running']:
self.logThreadStatus = self.logStatus['pauseReq']
while self.logThreadStatus != self.logStatus['paused'] and self.logThreadStatus != se... | send specific command to reference unit over serial port
Args:
cmd: OpenThread_WpanCtl command string
Returns:
Fail: Failed to send the command to reference unit and parse it
Value: successfully retrieve the desired value from reference unit
Error: some errors occur, indicates by the followed specific error number | juraj-google-style |
def date_to_integer(date):
if pd and isinstance(date, pd.Timestamp):
try:
date = date.to_datetime64()
except:
date = date.to_datetime()
if isinstance(date, np.datetime64):
return date.astype('datetime64[ms]').astype(float)
elif isinstance(date, cftime_ty... | Converts support date types to milliseconds since epoch
Attempts highest precision conversion of different datetime
formats to milliseconds since the epoch (1970-01-01 00:00:00).
If datetime is a cftime with a non-standard calendar the
caveats described in hv.core.util.cftime_to_timestamp apply.
Args:
date: Date- or ... | juraj-google-style |
def index_worker_output(self, worker_name, md5, index_name, subfield):
if subfield:
data = self.work_request(worker_name, md5)[worker_name][subfield]
else:
data = self.work_request(worker_name, md5)[worker_name]
self.indexer.index_data(data, i... | Index worker output with the Indexer.
Args:
worker_name: 'strings', 'pe_features', whatever
md5: the md5 of the sample
index_name: the name of the index
subfield: index just this subfield (None for all)
Returns:
Nothing | juraj-google-style |
def download_from_s3(context):
target_file = context.solid_config['target_file']
return context.resources.download_manager.download_file_contents(context, target_file) | Download an object from s3.
Args:
info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource.
Returns:
str:
The path to the downloaded object. | codesearchnet |
def __init__(self, offset, size, extent_type=EXTENT_TYPE_DATA):
super(VolumeExtent, self).__init__()
self.offset = offset
self.size = size
self.extent_type = extent_type | Initializes a volume extent.
Args:
offset (int): start offset of the extent, in bytes.
size (int): size of the extent, in bytes.
extent_type (Optional[str]): type of extent. | juraj-google-style |
def sample(self, hashes):
api_name = 'opendns-sample'
fmt_url_path = u'sample/{0}'
return self._multi_get(api_name, fmt_url_path, hashes) | Get the information about a sample based on its hash.
Args:
hashes: an enumerable of strings as hashes
Returns:
An enumerable of arrays which contains the information
about the original samples | juraj-google-style |
def scrape_info(self, request, response, link_type=None):
info = {}
for scraper in self._document_scrapers:
scrape_result = scraper.scrape(request, response, link_type)
info[scraper] = scrape_result
return info | Iterate the scrapers and return a dict of results.
Returns:
dict: A dict where the keys are the scrapers instances and the
values are the results. That is, a mapping from
:class:`BaseDocumentScraper` to :class:`ScrapeResult`. | codesearchnet |
def _Insert(cursor, table, values):
precondition.AssertIterableType(values, dict)
if (not values):
return
column_names = list(sorted(values[0]))
for value_dict in values:
if (set(column_names) != set(value_dict)):
raise ValueError('Given value dictionaries must have identical... | Inserts one or multiple rows into the given table.
Args:
cursor: The MySQL cursor to perform the insertion.
table: The table name, where rows should be inserted.
values: A list of dicts, associating column names to values. | codesearchnet |
def _zip_files(files, root):
zip_data = StringIO()
with ZipFile(zip_data, 'w', ZIP_DEFLATED) as zip_file:
for fname in files:
zip_file.write(os.path.join(root, fname), fname)
for zip_entry in zip_file.filelist:
perms = ((zip_entry.external_attr & ZIP_PERMS_MASK) >> 16)
... | Generates a ZIP file in-memory from a list of files.
Files will be stored in the archive with relative names, and have their
UNIX permissions forced to 755 or 644 (depending on whether they are
user-executable in the source filesystem).
Args:
files (list[str]): file names to add to the archive, relative to
``root``.
... | codesearchnet |
def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False):
oslogin_configured = self._GetStatus(two_factor=False)
if (oslogin_configured is None):
return None
two_factor_configured = self._GetStatus(two_factor=True)
two_factor_desired = (two_factor_desired and oslogin_desired)
if os... | Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
int, the return code from updating OS Login, or None if not present. | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.