code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def _process_celeba_config_file(self, file_path):
with tf.io.gfile.GFile(file_path) as f:
data_raw = f.read()
lines = data_raw.split('\n')
keys = lines[1].strip().split()
values = {}
for line in lines[2:(- 1)]:
row_values = line.strip().split()
values[row_values[0]] = [int(v)... | Unpack the celeba config file.
The file starts with the number of lines, and a header.
Afterwards, there is a configuration for each file: one per line.
Args:
file_path: Path to the file with the configuration.
Returns:
keys: names of the attributes
values: map from the file name to the list of attribute values for
... | codesearchnet |
def validate_level_indexes(num_levels, v_level_indexes, h_level_indexes):
if (num_levels < 1):
raise ValueError('num_levels {} is less than one'.format(num_levels))
all_levels = SortedFrozenSet(range(num_levels))
if ((h_level_indexes is None) and (v_level_indexes is None)):
v_level_indexes =... | Ensure that v_level_indexes and h_level_indexes are consistent.
Args:
num_levels: The number of levels of keys in the data structure being tabulated.
v_level_indexes: A sequence of level indexes between zero and num_levels for
the vertical axis, or None.
h_level_indexes: A sequence of level indexes between zero and nu... | codesearchnet |
def gradient_summaries(grad_vars, groups=None, scope='gradients'):
groups = groups or {r'all': r'.*'}
grouped = collections.defaultdict(list)
for grad, var in grad_vars:
if grad is None:
continue
for name, pattern in groups.items():
if re.match(pattern, var.name):
name = re.sub(patt... | Create histogram summaries of the gradient.
Summaries can be grouped via regexes matching variables names.
Args:
grad_vars: List of (gradient, variable) tuples as returned by optimizers.
groups: Mapping of name to regex for grouping summaries.
scope: Name scope for this operation.
Returns:
Summary tensor. | juraj-google-style |
def parse_hgnc_line(line, header):
hgnc_gene = {}
line = line.rstrip().split('\t')
raw_info = dict(zip(header, line))
if 'Withdrawn' in raw_info['status']:
return hgnc_gene
hgnc_symbol = raw_info['symbol']
hgnc_gene['hgnc_symbol'] = hgnc_symbol
hgnc_gene['hgnc_id'] = i... | Parse an hgnc formated line
Args:
line(list): A list with hgnc gene info
header(list): A list with the header info
Returns:
hgnc_info(dict): A dictionary with the relevant info | juraj-google-style |
def recompute_grad(fn):
@functools.wraps(fn)
def wrapped(*args):
return _recompute_grad(fn, args)
return wrapped | Decorator that recomputes the function on the backwards pass.
Args:
fn: a function that takes Tensors (all as positional arguments) and returns
a tuple of Tensors.
Returns:
A wrapped fn that is identical to fn when called, but its activations will
be discarded and recomputed on the backwards pass (i.e. on a call to
t... | codesearchnet |
def make_qs(n, m=None):
try:
import sympy
except ImportError:
raise ImportError("This function requires sympy. Please install it.")
if m is None:
syms = sympy.symbols(" ".join(f"q{i}" for i in range(n)))
if isinstance(syms, tuple):
return syms
else:
... | Make sympy symbols q0, q1, ...
Args:
n(int), m(int, optional):
If specified both n and m, returns [qn, q(n+1), ..., qm],
Only n is specified, returns[q0, q1, ..., qn].
Return:
tuple(Symbol): Tuple of sympy symbols. | juraj-google-style |
def CheckFile(self, filename):
result = True
artifact_reader = reader.YamlArtifactsReader()
try:
for artifact_definition in artifact_reader.ReadFile(filename):
try:
self._artifact_registry.RegisterDefinition(artifact_definition)
except KeyError:
logging.warnin... | Validates the artifacts definition in a specific file.
Args:
filename (str): name of the artifacts definition file.
Returns:
bool: True if the file contains valid artifacts definitions. | juraj-google-style |
def _AddAttribute(self, attribute):
if (attribute.identifier in self._attributes):
raise KeyError('Volume attribute object already set for volume attribute identifier: {0:s}.'.format(attribute.identifier))
self._attributes[attribute.identifier] = attribute | Adds an attribute.
Args:
attribute (VolumeAttribute): a volume attribute.
Raises:
KeyError: if volume attribute is already set for the corresponding volume
attribute identifier. | codesearchnet |
def set_colourtemp(self, colourtemp):
if (not (0 <= colourtemp <= 255)):
raise ValueError('The colour temperature needs to be between 0 and 255.')
payload = self.generate_payload(SET, {self.DPS_INDEX_COLOURTEMP: colourtemp})
data = self._send_receive(payload)
return data | Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255). | codesearchnet |
def _remove_one_redundant_stack_unstack(in_graph_def):
name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary(in_graph_def)
del name_to_seq_num
do_generic_pack_unpack = True
out = _graph_pb2.GraphDef()
out.library.CopyFrom(in_graph_def.library)
out.versions.CopyFrom(in_graph_... | Removes a stack->unstack pattern from in_graph_def in a returned graph.
Args:
in_graph_def: Graph def to use as input.
Returns:
Simplified tuple (graph_def, changed_something) where changed_something
is true if anything was done. | github-repos |
def __init__(self, value_type, value):
self.value_type = value_type
self.value = value_type(value) | Args:
value_type: Type of the static value
value: Static value | github-repos |
def scatter(indices, values, shape):
if any_symbolic_tensors((indices, values)):
return Scatter(shape=shape).symbolic_call(indices, values)
return backend.core.scatter(indices, values, shape) | Returns a tensor of shape `shape` where `indices` are set to `values`.
At a high level, this operation does `zeros[indices] = updates` and
returns the output. It is equivalent to:
```python
zeros = keras.ops.zeros(shape)
output = keras.ops.scatter_update(zeros, indices, values)
```
Args:
indices: A tensor or list/tu... | github-repos |
def __init__(
self, processing_configuration, enable_sigsegv_handler=False, **kwargs):
super(MultiProcessBaseProcess, self).__init__(**kwargs)
self._debug_output = False
self._enable_sigsegv_handler = enable_sigsegv_handler
self._guppy_memory_profiler = None
self._log_filename = None
... | Initializes a process.
Args:
processing_configuration (ProcessingConfiguration): processing
configuration.
enable_sigsegv_handler (Optional[bool]): True if the SIGSEGV handler
should be enabled.
kwargs (dict[str,object]): keyword arguments to pass to
multiprocessing.Process. | juraj-google-style |
def learn(self, state_arr, limit=1000):
while self.t <= limit:
next_action_arr = self.extract_possible_actions(state_arr)
predicted_q_arr = self.__function_approximator.inference_q(next_action_arr)
reward_value_arr = np.empty((n... | Learning and searching the optimal solution.
Args:
state_arr: `np.ndarray` of initial state.
limit: The maximum number of iterative updates based on value iteration algorithms. | juraj-google-style |
def __init__(self, group_key_start=1):
self._group_key = group_key_start
self._instance_key_table = {}
self._lock = threading.Lock()
self._known_groups = {} | Initializes the object.
Args:
group_key_start: the starting integer of group key. | github-repos |
def _serialize_tensor_like_io(value, debug_path: Optional[str]=None, use_repr: bool=True, path_to_value: Optional[str]=None):
torch.set_printoptions(sci_mode=True)
if use_repr:
value_out = _repr_to_list(value)
elif path_to_value:
if not path_to_value.endswith('.safetensors'):
pat... | Converts Tensors and DTensors to a JSON-serializable dictionary representation.
Args:
value: Any Python object, often including torch Tensors, lists, dicts, etc.
debug_path (`str`, *optional*, defaults to `None`): Directory to dump debug JSON and SafeTensors files.
use_repr (bool, *optional*, defaults to `True`): Whet... | github-repos |
def _QueryHash(self, nsrl_socket, digest):
try:
query = 'QUERY {0:s}\n'.format(digest).encode('ascii')
except UnicodeDecodeError:
logger.error('Unable to encode digest: {0!s} to ASCII.'.format(digest))
return False
response = None
try:
nsrl_socket.sendall(query)
resp... | Queries nsrlsvr for a specific hash.
Args:
nsrl_socket (socket._socketobject): socket of connection to nsrlsvr.
digest (str): hash to look up.
Returns:
bool: True if the hash was found, False if not or None on error. | juraj-google-style |
def __init__(self, *args, **kwargs):
super(JLinkDeviceInfo, self).__init__(*args, **kwargs)
self.SizeofStruct = ctypes.sizeof(self) | Initializes the instance.
Populates the ``.SizeofStruct`` parameter to the size of the instance.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
args: list of arguments
kwargs: key-word arguments dictionary
Returns:
``None`` | juraj-google-style |
def open_channel_url(channel, staging=False):
return OPEN_CHANNEL_URL.format(domain=DOMAIN, channel_id=channel, access='staging' if staging or STAGE else 'edit') | open_channel_url: returns url to uploaded channel
Args:
channel (str): channel id of uploaded channel
Returns: string url to open channel | juraj-google-style |
def condition_details_has_owner(condition_details, owner):
if 'subconditions' in condition_details:
result = condition_details_has_owner(condition_details['subconditions'], owner)
if result:
return True
elif isinstance(condition_details, list):
for subcondition in condi... | Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True if the public key is found in the condition details, False otherwise | juraj-google-style |
def random( self ):
j = np.searchsorted( self.cumulative_probabilities(), random.random() )
return self.jumps[ j ] | Select a jump at random with appropriate relative probabilities.
Args:
None
Returns:
(Jump): The randomly selected Jump. | juraj-google-style |
def get_functions_overridden_by(self, function):
candidates = [c.functions_not_inherited for c in self.inheritance]
candidates = [candidate for sublist in candidates for candidate in sublist]
return [f for f in candidates if f.full_name == function.full_name] | Return the list of functions overriden by the function
Args:
(core.Function)
Returns:
list(core.Function) | juraj-google-style |
def pipe(engine, format, data, renderer=None, formatter=None, quiet=False):
(cmd, _) = command(engine, format, None, renderer, formatter)
(out, _) = run(cmd, input=data, capture_output=True, check=True, quiet=quiet)
return out | Return ``data`` piped through Graphviz ``engine`` into ``format``.
Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (``'pdf'``, ``'png'``, ...).
data: The binary (encoded) DOT source string to render.
renderer: The output renderer used for... | codesearchnet |
def create_position_ids_from_input_ids(input_ids, padding_idx):
mask = input_ids.ne(padding_idx).int()
incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask
return incremental_indices.long() + padding_idx | Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
are ignored. This is modified from fairseq's `utils.make_positions`.
Args:
x: torch.Tensor x:
Returns: torch.Tensor | github-repos |
def get_layer_vis_square(data,
allow_heatmap=True,
normalize=True,
min_img_dim=100,
max_width=1200,
channel_order='RGB',
colormap='jet',
):
... | Returns a vis_square for the given layer data
Arguments:
data -- a np.ndarray
Keyword arguments:
allow_heatmap -- if True, convert single channel images to heatmaps
normalize -- whether to normalize the data when visualizing
max_width -- maximum width for the vis_square | juraj-google-style |
def MakeHistFromList(t, name=''):
hist = Hist(name=name)
[hist.Incr(x) for x in t]
return hist | Makes a histogram from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this histogram
Returns:
Hist object | codesearchnet |
async def get_ticket(self, request):
session = await get_session(request)
return session.get(self.cookie_name) | Called to return the ticket for a request.
Args:
request: aiohttp Request object.
Returns:
A ticket (string like) object, or None if no ticket is available
for the passed request. | juraj-google-style |
def system_repertoire_distance(r1, r2):
if (config.MEASURE in measures.asymmetric()):
raise ValueError('{} is asymmetric and cannot be used as a system-level irreducibility measure.'.format(config.MEASURE))
return measures[config.MEASURE](r1, r2) | Compute the distance between two repertoires of a system.
Args:
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``r1`` and ``r2``. | codesearchnet |
def VerifyStructure(self, parser_mediator, line):
return max([parser.matches(line) for (_, parser) in self.LINE_STRUCTURES]) | Verifies that this is an apache access log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
line (str): line from the text file.
Returns:
bool: True if this is the correct parser, False otherwise. | codesearchnet |
def __init__(self, napp_path, tpl_path):
self._napp_path = napp_path
self._template = tpl_path / 'openapi.yml.template'
self._api_file = napp_path / 'openapi.yml'
metadata = napp_path / 'kytos.json'
self._napp = NApp.create_from_json(metadata)
self._su... | Instantiate an OpenAPI object.
Args:
napp_path (string): Napp directory
tlp_path (string): File name from template | juraj-google-style |
def build(self, text, matrix, skim_depth=10, d_weights=False):
for anchor in bar(matrix.keys):
n1 = text.unstem(anchor)
pairs = matrix.anchored_pairs(anchor).items()
for term, weight in list(pairs)[:skim_depth]:
... | 1. For each term in the passed matrix, score its KDE similarity with
all other indexed terms.
2. With the ordered stack of similarities in hand, skim off the top X
pairs and add them as edges.
Args:
text (Text): The source text instance.
matrix (Matrix): An indexed term matrix.
skim_depth (int): The number of sibling... | juraj-google-style |
def __response_message_descriptor(self, message_type, method_id):
descriptor = {'200': {'description': 'A successful response'}}
if message_type != message_types.VoidMessage():
self.__parser.add_message(message_type.__class__)
self.__response_schema[method_id] = self.__parser.ref_for_mes... | Describes the response.
Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
Returns:
Dictionary describing the response. | juraj-google-style |
def MakeSuiteFromList(t, name=''):
hist = MakeHistFromList(t)
d = hist.GetDict()
return MakeSuiteFromDict(d) | Makes a suite from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this suite
Returns:
Suite object | juraj-google-style |
def get_course_duration(self, obj):
duration = obj.end - obj.start if obj.start and obj.end else None
if duration:
return strfdelta(duration, '{W} weeks {D} days.')
return '' | Get course's duration as a timedelta.
Arguments:
obj (CourseOverview): CourseOverview object
Returns:
(timedelta): Duration of a course. | juraj-google-style |
def next_trials(self):
trials = []
for trial in self._trial_generator:
if (trial is None):
return trials
trials += [trial]
self._finished = True
return trials | Provides a batch of Trial objects to be queued into the TrialRunner.
A batch ends when self._trial_generator returns None.
Returns:
trials (list): Returns a list of trials. | codesearchnet |
def remove(self, *l):
for a in flatten(l):
self._remove([self.Inner(a)], self.l) | remove inner from outer
Args:
*l element that is passes into Inner init | juraj-google-style |
def random_data(line_count=1, chars_per_line=80):
divide_lines = chars_per_line * line_count
return '\n'.join(random_line_data(chars_per_line) for x in range(int(divide_lines / chars_per_line))) | Function to creates lines of random string data
Args:
line_count: An integer that says how many lines to return
chars_per_line: An integer that says how many characters per line to return
Returns:
A String | juraj-google-style |
def get_response(response: Dict[str, Any]) -> JSONRPCResponse:
if "error" in response:
return ErrorResponse(**response)
return SuccessResponse(**response) | Converts a deserialized response into a JSONRPCResponse object.
The dictionary be either an error or success response, never a notification.
Args:
response: Deserialized response dictionary. We can assume the response is valid
JSON-RPC here, since it passed the jsonschema validation. | juraj-google-style |
def check_list_type(objects, allowed_type, name, allow_none=True):
if objects is None:
if not allow_none:
raise TypeError('%s is None, which is not allowed.' % name)
return objects
if not isinstance(objects, (tuple, list)):
raise TypeError('%s is not a list.' % name)
if not all(isinstance(i, ... | Verify that objects in list are of the allowed type or raise TypeError.
Args:
objects: The list of objects to check.
allowed_type: The allowed type of items in 'settings'.
name: Name of the list of objects, added to the exception.
allow_none: If set, None is also allowed.
Raises:
TypeError: if object is not of the al... | juraj-google-style |
def __ne__(self, other):
if isinstance(other, DocumentReference):
return self._client != other._client or self._path != other._path
else:
return NotImplemented | Inequality check against another instance.
Args:
other (Any): A value to compare against.
Returns:
Union[bool, NotImplementedType]: Indicating if the values are
not equal. | juraj-google-style |
def _g(self, z):
return (np.exp(np.multiply((- self.theta), z)) - 1) | Helper function to solve Frank copula.
This functions encapsulates :math:`g_z = e^{-\\theta z} - 1` used on Frank copulas.
Argument:
z: np.ndarray
Returns:
np.ndarray | codesearchnet |
def plots_html_page(query_module):
template = jenv.get_template('analysis.html')
context = dict(extended=config.EXTENDED)
cl = client.get_client()
session = cl.create_session()
seaborn.set_style('whitegrid')
decade_df = query_module.decade_query()
pix_size = pixels_to_inches((600, 400))
... | Generate analysis output as html page
Args:
query_module (module): module to use for querying data for the
desired model/pipeline variant, e.g. leonardo.standard.queries | codesearchnet |
def as_objective(obj):
if isinstance(obj, Objective):
return obj
elif callable(obj):
return obj
elif isinstance(obj, str):
layer, n = obj.split(":")
layer, n = layer.strip(), int(n)
return channel(layer, n) | Convert obj into Objective class.
Strings of the form "layer:n" become the Objective channel(layer, n).
Objectives are returned unchanged.
Args:
obj: string or Objective.
Returns:
Objective | juraj-google-style |
def add_token(self, token):
token = self.process_token(token)
self._token_count.update([token]) | Add token to vocabulary.
Args:
token (str): token to add. | juraj-google-style |
def _parse_services(self, service_config: dict, service_name: str, service_list: dict) -> dict:
for (key, value) in service_list['services'][service_name].items():
service_config[key] = value
if ('command' in key):
key = 'args'
service_config['args'] = value
servi... | Parse the docker compose file.
Args:
service_config (dict): Service configurations from the compose file
service_name (string): Name of the services
service_list (dict): Service configuration list
Returns:
dict, service specifications extracted from the compose file | codesearchnet |
def track_storms(storm_objects, times, distance_components, distance_maxima, distance_weights, tracked_objects=None):
obj_matcher = ObjectMatcher(distance_components, distance_weights, distance_maxima)
if (tracked_objects is None):
tracked_objects = []
for (t, time) in enumerate(times):
past... | Given the output of extract_storm_objects, this method tracks storms through time and merges individual
STObjects into a set of tracks.
Args:
storm_objects: list of list of STObjects that have not been tracked.
times: List of times associated with each set of STObjects
distance_components: list of function objects tha... | codesearchnet |
def select_action(self, next_action_arr, next_q_arr):
key_arr = self.select_action_key(next_action_arr, next_q_arr)
return next_action_arr[key_arr], next_q_arr[key_arr] | Select action by Q(state, action).
Args:
next_action_arr: `np.ndarray` of actions.
next_q_arr: `np.ndarray` of Q-Values.
Retruns:
Tuple(`np.ndarray` of action., Q-Value) | juraj-google-style |
def template_string(task: Task, template: str, jinja_filters: FiltersDict=None, **kwargs: Any) -> Result:
jinja_filters = (jinja_filters or {} or task.nornir.config.jinja2.filters)
text = jinja_helper.render_from_string(template=template, host=task.host, jinja_filters=jinja_filters, **kwargs)
return Result(... | Renders a string with jinja2. All the host data is available in the template
Arguments:
template (string): template string
jinja_filters (dict): jinja filters to enable. Defaults to nornir.config.jinja2.filters
**kwargs: additional data to pass to the template
Returns:
Result object with the following attributes set:... | codesearchnet |
def locate_module(module_id: str, module_type: str = None):
entry_point = None
if module_type:
entry_point = 'ehforwarderbot.%s' % module_type
module_id = module_id.split('
if entry_point:
for i in pkg_resources.iter_entry_points(entry_point):
if i.name == module_id:... | Locate module by module ID
Args:
module_id: Module ID
module_type: Type of module, one of ``'master'``, ``'slave'`` and ``'middleware'`` | juraj-google-style |
def verify_account(self, email_address):
request = self._get_request()
resp = request.post(self.ACCOUNT_VERIFY_URL, {
'email_address': email_address
})
return ('account' in resp) | Verify whether a HelloSign Account exists
Args:
email_address (str): Email address for the account to verify
Returns:
True or False | juraj-google-style |
def install_package(self, name, index=None, force=False, update=False):
cmd = 'install'
if force:
cmd = '{0} {1}'.format(cmd, '--force-reinstall')
if update:
cmd = '{0} {1}'.format(cmd, '--update')
if index:
cmd = '{0} {1}'.format(cmd, '-... | Install a given package.
Args:
name (str): The package name to install. This can be any valid
pip package specification.
index (str): The URL for a pypi index to use.
force (bool): For the reinstall of packages during updates.
update (bool): Update the package if it is out of date. | juraj-google-style |
def receive(self, event_type, signature, data_str):
if (not self.validate_signature(signature, data_str)):
raise HelpScoutSecurityException('The signature provided by this request was invalid.')
return HelpScoutWebHookEvent(event_type=event_type, record=json.loads(data_str)) | Receive a web hook for the event and signature.
Args:
event_type (str): Name of the event that was received (from the
request ``X-HelpScout-Event`` header).
signature (str): The signature that was received, which serves as
authentication (from the request ``X-HelpScout-Signature``
header).
data_str (str): The raw data... | codesearchnet |
def get_energy_relax_structure_buckingham(structure, gulp_cmd='gulp', keywords=('optimise', 'conp'), valence_dict=None):
gio = GulpIO()
gc = GulpCaller(gulp_cmd)
gin = gio.buckingham_input(structure, keywords, valence_dict=valence_dict)
gout = gc.run(gin)
energy = gio.get_energy(gout)
relax_stru... | Relax a structure and compute the energy using Buckingham potential.
Args:
structure: pymatgen.core.structure.Structure
gulp_cmd: GULP command if not in standard place
keywords: GULP first line keywords
valence_dict: {El: valence}. Needed if the structure is not charge
neutral. | codesearchnet |
def read(self, length, timeout=None):
data = b''
while True:
if (timeout is not None):
(rlist, _, _) = select.select([self._fd], [], [], timeout)
if (self._fd not in rlist):
break
try:
data += os.read(self._fd, (length - len(data)))
exc... | Read up to `length` number of bytes from the serial port with an
optional timeout.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking read, or negative or None for a blocking read that will
block until `length` number of bytes are read. Default is a blocking
read.
For a non-blocking or timeout-b... | codesearchnet |
def CreateTaskStorage(self, task):
if self._storage_type != definitions.STORAGE_TYPE_SESSION:
raise IOError('Unsupported storage type.')
storage_file_path = self._GetTaskStorageFilePath(task)
return self._CreateTaskStorageWriter(storage_file_path, task) | Creates a task storage.
The task storage is used to store attributes created by the task.
Args:
task(Task): task.
Returns:
StorageWriter: storage writer.
Raises:
IOError: if the storage type is not supported.
OSError: if the storage type is not supported. | juraj-google-style |
def __init__(self, host: str, port: int, time_to_live: Union[int, timedelta], *, request_coder: Optional[coders.Coder], response_coder: Optional[coders.Coder], kwargs: Optional[Dict[str, Any]]=None, source_caller: Optional[Caller]=None, mode: _RedisMode):
self.host, self.port = (host, port)
self.time_to_live = ... | Args:
host (str): The hostname or IP address of the Redis server.
port (int): The port number of the Redis server.
time_to_live: `(Union[int, timedelta])` The time-to-live (TTL) for
records stored in Redis. Provide an integer (in seconds) or a
`datetime.timedelta` object.
request_coder: (Optional[`coders.Coder`]) coder... | github-repos |
def get_section_by_name(self, section_name):
sections = self.unravel_sections(self.get_sections())
for section in sections:
if (section['name'] == section_name):
return (section['groupId'], section)
return (None, None) | Get a section by its name.
Get a list of sections for a given gradebook,
specified by a gradebookid.
Args:
section_name (str): The section's name.
Raises:
requests.RequestException: Exception connection error
ValueError: Unable to decode response content
Returns:
tuple: tuple of group id, and section dictionary
An... | codesearchnet |
def generate_message_doc(message_descriptor, locations, path, name_prefix=''):
prefixed_name = name_prefix + message_descriptor.name
print(make_subsection(prefixed_name))
location = locations[path]
if location.HasField('leading_comments'):
print(textwrap.dedent(location.leading_comment... | Generate docs for message and nested messages and enums.
Args:
message_descriptor: descriptor_pb2.DescriptorProto instance for message
to generate docs for.
locations: Dictionary of location paths tuples to
descriptor_pb2.SourceCodeInfo.Location instances.
path: Path tuple to the message definition.
name_prefix: Optio... | juraj-google-style |
def cancel(self, job_ids):
statuses = []
for job_id in job_ids:
try:
self.delete_instance(job_id)
statuses.append(True)
self.provisioned_blocks -= 1
except Exception:
statuses.append(False)
return statuses | Cancels the resources identified by the job_ids provided by the user.
Args:
- job_ids (list): A list of job identifiers
Returns:
- A list of status from cancelling the job which can be True, False
Raises:
- ExecutionProviderException or its subclasses | codesearchnet |
def get_losses_for(self, inputs):
warnings.warn('`layer.get_losses_for` is deprecated and will be removed in a future version. Please use `layer.losses` instead.')
return self.losses | Deprecated, do NOT use!
Retrieves losses relevant to a specific set of inputs.
Args:
inputs: Input tensor or list/tuple of input tensors.
Returns:
List of loss tensors of the layer that depend on `inputs`. | github-repos |
def _verify_output(self, submission_type):
result = True
if (submission_type == 'defense'):
try:
image_classification = load_defense_output(os.path.join(self._sample_output_dir, 'result.csv'))
expected_keys = [IMAGE_NAME_PATTERN.format(i) for i in range(BATCH_SIZE)]
i... | Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid | codesearchnet |
def dumpfile(item, path):
with io.open(path, 'wb') as fd:
fd.write(en(item)) | Dump an object to a file by path.
Args:
item (object): The object to serialize.
path (str): The file path to save.
Returns:
None | juraj-google-style |
def squared_hinge(y_true, y_pred):
y_pred = ops.convert_to_tensor(y_pred)
y_true = ops.cast(y_true, y_pred.dtype)
y_true = convert_binary_labels_to_hinge(y_true)
return ops.mean(ops.square(ops.maximum(1.0 - y_true * y_pred, 0.0)), axis=-1) | Computes the squared hinge loss between `y_true` & `y_pred`.
Formula:
```python
loss = mean(square(maximum(1 - y_true * y_pred, 0)), axis=-1)
```
Args:
y_true: The ground truth values. `y_true` values are expected to be -1
or 1. If binary (0 or 1) labels are provided we will convert them
to -1 or 1 with shape = `[ba... | github-repos |
def install(name, dst, capture_error=False):
if dst not in sys.path:
sys.path.insert(0, dst)
entrypoint_type = _entry_point_type.get(dst, name)
if entrypoint_type is _entry_point_type.PYTHON_PACKAGE:
_modules.install(dst, capture_error)
if entrypoint_type is _entry_point_type.COMMA... | Install the user provided entry point to be executed as follow:
- add the path to sys path
- if the user entry point is a command, gives exec permissions to the script
Args:
name (str): name of the script or module.
dst (str): path to directory with the script or module.
capture_error (bool): Default false. If True, t... | juraj-google-style |
def _confirm_overwrite(filename):
message = '{}Would you like to overwrite the contents of {} (y/[n])? '.format(c.Fore.MAGENTA, filename)
response = raw_input(message)
response = response.lower()
if (response in ['y', 'yes']):
return True
return False | Confirm overwrite of template files.
Make sure the user would like to continue downloading a file which will overwrite a file
in the current directory.
Args:
filename (str): The name of the file to overwrite.
Returns:
bool: True if the user specifies a "yes" response. | codesearchnet |
def log_error(self, msg):
if self.__logger:
self.__logger.error(msg)
raise RuntimeError(msg) | Log an error and raise an exception.
Args:
msg: Error message to log.
Raises:
RuntimeError: With the message. | codesearchnet |
def Process(self, parser_mediator, root_item=None, **kwargs):
super(DefaultOLECFPlugin, self).Process(parser_mediator, **kwargs)
if not root_item:
raise ValueError('Root item not set.')
if not self._ParseItem(parser_mediator, root_item):
event_data = OLECFItemEventData()
event_... | Parses an OLECF file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
root_item (Optional[pyolecf.item]): root item of the OLECF file.
Raises:
ValueError: If the root item is not set. | juraj-google-style |
def sample_from_discretized_mix_logistic(pred, seed=None):
logits, locs, log_scales, coeffs = split_to_discretized_mix_logistic_params(
pred)
num_mixtures = shape_list(logits)[-1]
gumbel_noise = -tf.log(-tf.log(
tf.random_uniform(
tf.shape(logits), minval=1e-5, maxval=1. - 1e-5, seed... | Sampling from a discretized mixture of logistics.
Args:
pred: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one per channel), three standard deviations (one per channel),
and three coefficients which linearly parameterize dependence across
cha... | juraj-google-style |
def _read_protocol_line(self):
while True:
line = self._proc.stdout.readline().decode('utf-8')
if (not line):
raise jsonrpc_client_base.AppStartError(self._ad, 'Unexpected EOF waiting for app to start')
line = line.strip()
if (line.startswith('INSTRUMENTATION_RESULT:') or... | Reads the next line of instrumentation output relevant to snippets.
This method will skip over lines that don't start with 'SNIPPET' or
'INSTRUMENTATION_RESULT'.
Returns:
(str) Next line of snippet-related instrumentation output, stripped.
Raises:
jsonrpc_client_base.AppStartError: If EOF is reached without any
prot... | codesearchnet |
def profile(self, profile):
self._staging_data = None
lang = profile.get('install_json', {}).get('programLanguage', 'PYTHON')
profile_args = ArgBuilder(lang, self.profile_args(profile.get('args')))
self._profile = profile
self... | Set the current profile.
Args:
profile (dict): The profile data. | juraj-google-style |
def sg_int(tensor, opt):
r
return tf.cast(tensor, tf.sg_intx, name=opt.name) | r"""Casts a tensor to intx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A `Tensor` or `SparseTensor` with same shape as `tensor`. | juraj-google-style |
def __init__(self, _max_size, _random=None, always_keep_last=True):
if _max_size < 0 or _max_size != round(_max_size):
raise ValueError('_max_size must be nonnegative int, was %s' % _max_size)
self.items = []
self._mutex = threading.Lock()
self._max_size = _max_size
self._num_it... | Create the _ReservoirBucket.
Args:
_max_size: The maximum size the reservoir bucket may grow to. If size is
zero, the bucket has unbounded size.
_random: The random number generator to use. If not specified, defaults to
random.Random(0).
always_keep_last: Whether the latest seen item should always be included
in the e... | juraj-google-style |
def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT):
DEFAULT_REQUEST_CACHE.set(key, value)
django_cache.set(key, value, django_cache_timeout) | Caches the value for the provided key in both the request cache and the
django cache.
Args:
key (string)
value (object)
django_cache_timeout (int): (Optional) Timeout used to determine
if and for how long to cache in the django cache. A timeout of
0 will skip the django cache. If timeout is provided, use that
timeout ... | juraj-google-style |
def random_uniform(mesh, shape, **kwargs):
shape = convert_to_shape(shape)
return RandomOperation(mesh, shape, tf.random.uniform, **kwargs).outputs[0] | Random uniform.
Args:
mesh: a Mesh
shape: a Shape
**kwargs: keyword args for tf.random.uniform, except seed
Returns:
a Tensor | juraj-google-style |
def unicode(self, b, encoding=None):
if (encoding is None):
encoding = self.string_encoding
return unicode(b, encoding, self.decode_errors) | Convert a byte string to unicode, using string_encoding and decode_errors.
Arguments:
b: a byte string.
encoding: the name of an encoding. Defaults to the string_encoding
attribute for this instance.
Raises:
TypeError: Because this method calls Python's built-in unicode()
function, this method raises the followin... | codesearchnet |
def run(self, *args, **kwargs):
accounts = list(AWSAccount.get_all(include_disabled=False).values())
self.manage_policies(accounts) | Iterate through all AWS accounts and apply roles and policies from Github
Args:
*args: Optional list of arguments
**kwargs: Optional list of keyword arguments
Returns:
`None` | codesearchnet |
def convert_elementwise_div(
params, w_name, scope_name, inputs, layers, weights, names
):
print('Converting elementwise_div ...')
if names == 'short':
tf_name = 'D' + random_string(7)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
... | Convert elementwise multiplication.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | juraj-google-style |
def box_predictor(self, image_feats: torch.FloatTensor, feature_map: torch.FloatTensor, interpolate_pos_encoding: bool=False) -> torch.FloatTensor:
pred_boxes = self.box_head(image_feats)
if interpolate_pos_encoding:
_, num_patches_height, num_patches_width, _ = feature_map.shape
box_bias = self... | Args:
image_feats:
Features extracted from the image, returned by the `image_text_embedder` method.
feature_map:
A spatial re-arrangement of image_features, also returned by the `image_text_embedder` method.
interpolate_pos_encoding:
Whether to interpolate the pre-trained position encodings.
Returns:
pred_boxes:
List o... | github-repos |
def make_class(node, props, ctx):
name = abstract_utils.get_atomic_python_constant(props.name_var)
log.info('Declaring class %s', name)
try:
class_dict = abstract_utils.get_atomic_value(props.class_dict_var)
except abstract_utils.ConversionError:
log.error('Error initializing class %r', ... | Create a class with the name, bases and methods given.
Args:
node: The current CFG node.
props: class_mixin.ClassBuilderProperties required to build the class
ctx: The current context.
Returns:
A node and an instance of class_type. | github-repos |
def _AbortJoin(self, timeout=None):
for pid, process in iter(self._processes_per_pid.items()):
logger.debug('Waiting for process: {0:s} (PID: {1:d}).'.format(
process.name, pid))
process.join(timeout=timeout)
if not process.is_alive():
logger.debug('Process {0:s} (PID: {1:d}... | Aborts all registered processes by joining with the parent process.
Args:
timeout (int): number of seconds to wait for processes to join, where
None represents no timeout. | juraj-google-style |
def handle_error(err, halt=True):
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err))
if halt:
sys.exit(1) | Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit. | juraj-google-style |
def _decode_helper(obj, deserialize=False, module_objects=None, custom_objects=None):
if isinstance(obj, dict) and 'class_name' in obj:
if tf.available:
if obj['class_name'] == 'TensorShape':
return tf.TensorShape(obj['items'])
elif obj['class_name'] == 'TypeSpec':
... | A decoding helper that is TF-object aware.
Args:
obj: A decoded dictionary that may represent an object.
deserialize: Boolean. When True, deserializes any Keras
objects found in `obj`. Defaults to `False`.
module_objects: A dictionary of built-in objects to look the name up in.
Generally, `module_objects` is provided ... | github-repos |
def get_vnet(access_token, subscription_id, resource_group, vnet_name):
endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/virtualNetworks/', vnet_name, '?api-version=', NETWORK_API])
return do_get(endpoint, access_token) | Get details about the named virtual network.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vnet_name (str): Name of the VNet.
Returns:
HTTP response. VNet JSON body. | codesearchnet |
def register_rpc(self, address, rpc_id, func):
if ((rpc_id < 0) or (rpc_id > 65535)):
raise RPCInvalidIDError('Invalid RPC ID: {}'.format(rpc_id))
if (address not in self._rpc_overlays):
self._rpc_overlays[address] = RPCDispatcher()
self._rpc_overlays[address].add_rpc(rpc_id, func) | Register a single RPC handler with the given info.
This function can be used to directly register individual RPCs,
rather than delegating all RPCs at a given address to a virtual
Tile.
If calls to this function are mixed with calls to add_tile for
the same address, these RPCs will take precedence over what is
defined... | codesearchnet |
def image_section(image, title):
img = yield marv.pull(image)
if img is None:
return
widget = {'title': image.title, 'image': {'src': img.relpath}}
section = {'title': title, 'widgets': [widget]}
yield marv.push(section) | Create detail section with one image.
Args:
title (str): Title to be displayed for detail section.
image: marv image file.
Returns
One detail section. | juraj-google-style |
def _minimize_peak_memory_list(graph):
schedule = []
bytes_freed = {}
users_of = collections.defaultdict(set)
in_degree = collections.defaultdict(int)
operation_id = {}
priority_queue = []
for i, operation_name in enumerate(graph.get_all_operation_names()):
operation_id[operatio... | Computes schedule according to the greedy list heuristic.
Greedy list heuristic: schedule the operation which results in the most bytes
of memory being (immediately) freed.
TODO(joshuawang): Experiment with tiebreaking by preferring more successors.
Args:
graph: an mtf.auto_mtf.graph_interface.GraphInterface.
Return... | juraj-google-style |
def deepcopy(original_obj):
if isinstance(original_obj, list):
return list(deepcopy(item) for item in original_obj)
elif isinstance(original_obj, dict):
return dict((key, deepcopy(val)) for key, val in original_obj.items())
else:
return original_obj | Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the object | juraj-google-style |
def db990(self, value=None):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError('value {} need to be of type float '
'for field `db990`'.format(value))
self._db990 = value | Corresponds to IDD Field `db990`
Dry-bulb temperature corresponding to 90.0% annual cumulative
frequency of occurrence (cold conditions)
Args:
value (float): value for IDD Field `db990`
Unit: C
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError:... | juraj-google-style |
def add_mutually_exclusive_groups(self, groups):
all_params = set.union(*groups)
for group in groups:
mutually_exclusive = all_params - group
for name in group:
self._mutually_exclusive[name].update(mutually_exclusive) | Adds groups of mutually exclusive type parameters.
For example, [{"T1", "T2"}, {"T3", "T4"}] would mean that the following
pairs are mutually exclusive: (T1, T3), (T1, T4), (T2, T3), (T2, T4).
Args:
groups: The mutually exclusive groups. | github-repos |
def listdir(self, target_directory):
target_directory = self.resolve_path(target_directory, allow_fd=True)
directory = self.confirmdir(target_directory)
directory_contents = directory.contents
return list(directory_contents.keys()) | Return a list of file names in target_directory.
Args:
target_directory: Path to the target directory within the
fake filesystem.
Returns:
A list of file names within the target directory in arbitrary
order.
Raises:
OSError: if the target is not a directory. | codesearchnet |
def add_history(self, filename, color_scheme, font, wrap):
filename = encoding.to_unicode_from_fs(filename)
if (filename in self.filenames):
return
editor = codeeditor.CodeEditor(self)
if (osp.splitext(filename)[1] == '.py'):
language = 'py'
else:
language = 'bat'
editor.... | Add new history tab.
Args:
filename (str): file to be loaded in a new tab. | codesearchnet |
def resolve(self, context, provider):
resolve_variables(self.variables, context, provider)
self.blueprint.resolve_variables(self.variables) | Resolve the Stack variables.
This resolves the Stack variables and then prepares the Blueprint for
rendering by passing the resolved variables to the Blueprint.
Args:
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of
the base provider | codesearchnet |
def layer_norm(x, dim, epsilon=1e-6, name="layer_prepostprocess"):
with tf.variable_scope(name + "/layer_norm"):
scale = mtf.get_variable(
x.mesh,
"layer_norm_scale",
mtf.Shape([dim]),
initializer=tf.ones_initializer(),
activation_dtype=x.dtype)
bias = mtf.get_variab... | Layer normalization over dimension dim.
Args:
x: a mtf.Tensor whose shape contains dim.
dim: a mtf.Dimension
epsilon: a floating point number
name: a string. variable scope.
Returns:
a mtf.Tensor with same shape as x. | juraj-google-style |
def __init__(self, key: Key, exclude_from_indexes: Iterable[str]=()):
self.key = key
self.exclude_from_indexes = set(exclude_from_indexes)
self.properties = {} | Represents a Datastore entity.
Does not support the property value "meaning" field.
Args:
key: (Key) A complete Key representing this Entity.
exclude_from_indexes: (iterable of str) List of property keys whose values
should not be indexed for this entity. | github-repos |
def stop_threadsafe(self):
if self.stopped:
return
try:
self._loop.run_coroutine(self.stop())
except asyncio.TimeoutError:
raise TimeoutExpiredError('Timeout stopping task {} with {} subtasks'.format(self.name, len(self.subtasks))) | Stop this task from another thread and wait for it to finish.
This method must not be called from within the BackgroundEventLoop but
will inject self.stop() into the event loop and block until it
returns.
Raises:
TimeoutExpiredError: If the task does not stop in the given
timeout specified in __init__() | codesearchnet |
def lu_solve(LU, b):
from scipy.linalg import lu_solve as sp_lu_solve
LU = (asarray(LU[0], float), asarray(LU[1], float))
b = asarray(b, float)
return sp_lu_solve(LU, b, check_finite=False) | r"""Solve for LU decomposition.
Solve the linear equations :math:`\mathrm A \mathbf x = \mathbf b`,
given the LU factorization of :math:`\mathrm A`.
Args:
LU (array_like): LU decomposition.
b (array_like): Right-hand side.
Returns:
:class:`numpy.ndarray`: The solution to the system
:math:`\mathrm A \mathbf x = \math... | codesearchnet |
def set_site_energies(self, energies):
self.site_energies = energies
for site_label in energies:
for site in self.sites:
if (site.label == site_label):
site.energy = energies[site_label] | Set the energies for every site in the lattice according to the site labels.
Args:
energies (Dict(Str:Float): Dictionary of energies for each site label, e.g.::
{ 'A' : 1.0, 'B', 0.0 }
Returns:
None | codesearchnet |
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0):
if (kmip_version < enums.KMIPVersion.KMIP_2_0):
raise exceptions.VersionNotSupported('KMIP {} does not support the ObjectDefaults object.'.format(kmip_version.value))
local_buffer = BytearrayStream()
if self._object_type:
... | Write the ObjectDefaults structure encoding to the data stream.
Args:
output_buffer (stream): A data stream in which to encode
Attributes structure data, supporting a write method.
kmip_version (enum): A KMIPVersion enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP... | codesearchnet |
def subCell2DSlices(arr, shape, d01=None, p01=None):
if p01 is not None:
yinit, xinit = p01
else:
xinit, yinit = 0, 0
x, y = xinit, yinit
g0, g1 = shape
s0, s1 = arr.shape[:2]
if d01 is not None:
d0, d1 = d01
else:
d0, d1 = s0 / g0, s1 / g1
y1 = d0... | Generator to access evenly sized sub-cells in a 2d array
Args:
shape (tuple): number of sub-cells in y,x e.g. (10,15)
d01 (tuple, optional): cell size in y and x
p01 (tuple, optional): position of top left edge
Returns:
int: 1st index
int: 2nd index
slice: first dimension
slice: 1st dimension | juraj-google-style |
def create_secret(self, name, data, labels=None, driver=None):
if (not isinstance(data, bytes)):
data = data.encode('utf-8')
data = base64.b64encode(data)
if six.PY3:
data = data.decode('ascii')
body = {'Data': data, 'Name': name, 'Labels': labels}
if (driver is not None):
if... | Create a secret
Args:
name (string): Name of the secret
data (bytes): Secret data to be stored
labels (dict): A mapping of labels to assign to the secret
driver (DriverConfig): A custom driver configuration. If
unspecified, the default ``internal`` driver will be used
Returns (dict): ID of the newly created secret | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.