code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def __init__(self, issues = None):
self._issues = []
self._config = {}
self._project = None
self.issues = issues | Class constructor.
Args:
issues (list): List of `Issue` instances | juraj-google-style |
def compute_delta(deps: List[str], imports: List[str], rule_dir: str, source_to_rules: SourceToRule, rule_name: str) -> Optional[DepsDelta]:
issues = []
adds = set()
subs = set()
expanded_deps = set([expand_dep(dep, rule_dir) for dep in deps])
used_deps = set()
for imp in imports:
imp_it... | Computes the operation on the deps to support all the imports.
Args:
deps: Dependencies of the rule.
imports: Imports of the rule.
rule_dir: Path of the rule relative to the repo root.
source_to_rules: Mapping from all available source files to rules. | github-repos |
def add(name, **kwargs):
if not info(name):
comp_obj = _get_computer_object()
try:
new_group = comp_obj.Create('group', name)
new_group.SetInfo()
log.info('Successfully created group %s', name)
except pywintypes.com_error as exc:
msg = 'Fa... | Add the specified group
Args:
name (str):
The name of the group to add
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' group.add foo | juraj-google-style |
def get_class_attributes(cls):
for (name, value) in cls.__dict__.items():
if GenericStruct._is_pyof_attribute(value):
(yield (name, value)) | Return a generator for class attributes' names and value.
This method strict relies on the PEP 520 (Preserving Class Attribute
Definition Order), implemented on Python 3.6. So, if this behaviour
changes this whole lib can loose its functionality (since the
attributes order are a strong requirement.) For the same reaso... | codesearchnet |
def inference(self, observed_arr):
if observed_arr.ndim < 4:
observed_arr = np.expand_dims(observed_arr, axis=1)
self.__add_channel_flag = True
else:
self.__add_channel_flag = False
return super().inference(observed_arr) | Draws samples from the `true` distribution.
Args:
observed_arr: `np.ndarray` of observed data points.
Returns:
`np.ndarray` of inferenced. | juraj-google-style |
def stop_dag(self, name=None):
return self._client.send(Request(action='stop_dag', payload={'name': (name if (name is not None) else self._dag_name)})).success | Send a stop signal to the specified dag or the dag that hosts this task.
Args:
name str: The name of the dag that should be stopped. If no name is given the
dag that hosts this task is stopped.
Upon receiving the stop signal, the dag will not queue any new tasks and wait
for running tasks to terminate.
Returns:
bool... | codesearchnet |
def PrintResponse(batch_job_helper, response_xml):
response = batch_job_helper.ParseResponse(response_xml)
if 'rval' in response['mutateResponse']:
for data in response['mutateResponse']['rval']:
if 'errorList' in data:
print 'Operation %s - FAILURE:' % data['index']
print '\terrorType... | Prints the BatchJobService response.
Args:
batch_job_helper: a BatchJobHelper instance.
response_xml: a string containing a response from the BatchJobService. | juraj-google-style |
def compute_match(mapping, weight_dict):
if veryVerbose:
print("Computing match for mapping", file=DEBUG_LOG)
print(mapping, file=DEBUG_LOG)
if tuple(mapping) in match_triple_dict:
if veryVerbose:
print("saved value", match_triple_dict[tuple(mapping)], file=DEBUG_LO... | Given a node mapping, compute match number based on weight_dict.
Args:
mappings: a list of node index in AMR 2. The ith element (value j) means node i in AMR 1 maps to node j in AMR 2.
Returns:
matching triple number
Complexity: O(m*n) , m is the node number of AMR 1, n is the node number of AMR 2 | juraj-google-style |
def get_attributes(self, uid=None, attribute_names=None):
if (uid is not None):
if (not isinstance(uid, six.string_types)):
raise TypeError('uid must be a string')
if (attribute_names is not None):
if (not isinstance(attribute_names, list)):
raise TypeError('attribute_nam... | Get the attributes associated with a managed object.
If the uid is not specified, the appliance will use the ID placeholder
by default.
If the attribute_names list is not specified, the appliance will
return all viable attributes for the managed object.
Args:
uid (string): The unique ID of the managed object with wh... | codesearchnet |
def _truncate(self, processed_features: Union[dict[str, np.ndarray], BatchFeature], max_length: Optional[int]=None, pad_to_multiple_of: Optional[int]=None, truncation: Optional[bool]=None):
if not truncation:
return processed_features
elif truncation and max_length is None:
raise ValueError('Whe... | Truncate inputs to predefined length or max length in the batch
Args:
processed_features(`Union[Dict[str, np.ndarray], BatchFeature]`):
Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch
of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]... | github-repos |
def decode_base64(data):
data = bytes(data, encoding="ascii")
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=' * (4 - missing_padding)
return base64.b64decode(data) | Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes | juraj-google-style |
def formatted(self, func):
other = EscapedString.__new__(EscapedString)
other.strings = []
for is_literal, value in self.strings:
if not is_literal:
value = func(value)
other.strings.append((is_literal, value))
return other | Return the string with non-literal parts formatted.
Args:
func (callable): Callable that translates a string into a
formatted string.
Returns:
`EscapedString` object. | juraj-google-style |
def get_idx_types(rng_def, ranges):
idx_types = rng_def.get('kds_esIndexType', []).copy()
if not idx_types:
nested = False
for rng in ranges:
if range_is_obj(rng, __MODULE__.rdfclass):
nested = True
if nested:
idx_types.append('es_Nested')
... | Returns the elasticsearch index types for the obj
args:
rng_def: the range defintion dictionay
ranges: rdfproperty ranges | juraj-google-style |
def __generate_reference__(self, triple_map, **kwargs):
raw_value = self.source.get(str(triple_map.reference))
if raw_value is None or len(raw_value) < 1:
return
if hasattr(triple_map, "datatype"):
if triple_map.datatype == NS_MGR.xsd.anyURI.rdflib:
... | Generates a RDF entity based on triple map
Args:
triple_map(SimpleNamespace): Triple Map | juraj-google-style |
def check_tx(self, raw_transaction):
self.abort_if_abci_chain_is_not_synced()
logger.debug('check_tx: %s', raw_transaction)
transaction = decode_transaction(raw_transaction)
if self.bigchaindb.is_valid_transaction(transaction):
logger.debug('check_tx: VALID')
return ResponseCheckTx(code=... | Validate the transaction before entry into
the mempool.
Args:
raw_tx: a raw string (in bytes) transaction. | codesearchnet |
def spliceext(filepath, s):
root, ext = os.path.splitext(safepath(filepath))
return root + s + ext | Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str | juraj-google-style |
def create_unit(self, name, unit):
self._single_request('Units.Set', unitName=name, body={'desiredState': unit.desiredState, 'options': unit.options})
return self.get_unit(name) | Create a new Unit in the cluster
Create and modify Unit entities to communicate to fleet the desired state of the cluster.
This simply declares what should be happening; the backend system still has to react to
the changes in this desired state. The actual state of the system is communicated with
UnitState entities.
... | codesearchnet |
def remove(self, future):
if self._loop.get_debug():
logger.debug('Removing %s from the linked list.', future)
if (future.prev is None):
assert (future is self.head)
self.head = future.next
if (self.head is None):
self.tail = None
if (not self.cancelled())... | Remove an object from the linked list.
Args:
future (PlasmaObjectFuture): A PlasmaObjectFuture instance. | codesearchnet |
def UnlockScanNode(self, path_spec):
if (not self.HasScanNode(path_spec)):
raise KeyError('Scan node does not exist.')
if (path_spec not in self._locked_scan_nodes):
raise KeyError('Scan node is not locked.')
del self._locked_scan_nodes[path_spec]
self._scan_nodes[path_spec].scanned = Fa... | Marks a scan node as unlocked.
Args:
path_spec (PathSpec): path specification.
Raises:
KeyError: if the scan node does not exists or is not locked. | codesearchnet |
def user_avatar_url(username, size=64, default="retro"):
openid = "http:
return libravatar_url(openid=openid, size=size, default=default) | Get the avatar URL of the provided Fedora username.
The URL is returned from the Libravatar service.
Args:
username (str): The username to get the avatar of.
size (int): Size of the avatar in pixels (it's a square).
default (str): Default avatar to return if not found.
Returns:
str: The URL to the avatar image. | juraj-google-style |
def __lt__(self, other):
other = as_dimension(other)
if self._value is None or other.value is None:
return None
else:
return self._value < other.value | Returns True if `self` is known to be less than `other`.
Dimensions are compared as follows:
```python
(tf.compat.v1.Dimension(m) < tf.compat.v1.Dimension(n)) == (m < n)
(tf.compat.v1.Dimension(m) < tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) < tf.compat.v1.Dimension(n)) == None
(t... | github-repos |
class LabelSmoother:
epsilon: float = 0.1
ignore_index: int = -100
def __call__(self, model_output, labels, shift_labels=False):
logits = model_output['logits'] if isinstance(model_output, dict) else model_output[0]
if shift_labels:
logits = logits[..., :-1, :].contiguous()
... | Adds label-smoothing on a pre-computed output from a Transformers model.
Args:
epsilon (`float`, *optional*, defaults to 0.1):
The label smoothing factor.
ignore_index (`int`, *optional*, defaults to -100):
The index in the labels to ignore when computing the loss. | github-repos |
def url(self, suffix=""):
return super(neuroRemote,
self).url('{}/'.format(self._ext) + suffix) | Return a constructed URL, appending an optional suffix (uri path).
Arguments:
suffix (str : ""): The suffix to append to the end of the URL
Returns:
str: The complete URL | juraj-google-style |
def shape(self):
return self._shape | The statically known shape of the RaggedTensor.
Examples:
>>> rt = tf.ragged.constant([[0], [1, 2]])
>>> tf.type_spec_from_value(rt).shape
TensorShape([2, None])
>>> rt = tf.ragged.constant([[[0, 1]], [[1, 2], [3, 4]]], ragged_rank=1)
>>> tf.type_spec_from_value(rt).shape
TensorShape([2, None, 2])
Returns:
A `tf.Te... | github-repos |
def disconnect_container_from_network(self, container, net_id,
force=False):
data = {"Container": container}
if force:
if version_lt(self._version, '1.22'):
raise InvalidVersion(
'Forced disconnect was int... | Disconnect a container from a network.
Args:
container (str): container ID or name to be disconnected from the
network
net_id (str): network ID
force (bool): Force the container to disconnect from a network.
Default: ``False`` | juraj-google-style |
def py_hash(key, num_buckets):
b, j = -1, 0
if num_buckets < 1:
raise ValueError('num_buckets must be a positive number')
while j < num_buckets:
b = int(j)
key = ((key * long(2862933555777941757)) + 1) & 0xffffffffffffffff
j = float(b + 1) * (float(1 << 31) / float((ke... | Generate a number in the range [0, num_buckets).
Args:
key (int): The key to hash.
num_buckets (int): Number of buckets to use.
Returns:
The bucket number `key` computes to.
Raises:
ValueError: If `num_buckets` is not a positive number. | juraj-google-style |
def ParseLeakFilesTable(
self, parser_mediator, database=None, table=None, **unused_kwargs):
if database is None:
raise ValueError('Missing database value.')
if table is None:
raise ValueError('Missing table value.')
for esedb_record in table.records:
if parser_mediator.abort:... | Parses the LeakFiles table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
database (Optional[pyesedb.file]): ESE database.
table (Optional[pyesedb.table]): table.
Raises:
ValueError: if the database or table value is missing. | juraj-google-style |
def print_headers(head, outfile=None, silent=False):
for header_line in head.print_header():
if outfile:
outfile.write(header_line+'\n')
else:
if not silent:
print(header_line)
return | Print the vcf headers.
If a result file is provided headers will be printed here, otherwise
they are printed to stdout.
Args:
head (HeaderParser): A vcf header object
outfile (FileHandle): A file handle
silent (Bool): If nothing should be printed. | juraj-google-style |
def entityLabel(rdfGraph, anEntity, language=DEFAULT_LANGUAGE, getall=True):
if getall:
temp = []
for o in rdfGraph.objects(anEntity, RDFS.label):
temp += [o]
return temp
else:
for o in rdfGraph.objects(anEntity, RDFS.label):
if getattr(o, 'language'... | Returns the rdfs.label value of an entity (class or property), if existing.
Defaults to DEFAULT_LANGUAGE. Returns the RDF.Literal resource
Args:
language: 'en', 'it' etc..
getall: returns a list of all labels rather than a string | juraj-google-style |
def update(self, node_spec):
return self.client.api.update_node(self.id, self.version, node_spec) | Update the node's configuration.
Args:
node_spec (dict): Configuration settings to update. Any values
not provided will be removed. Default: ``None``
Returns:
`True` if the request went through.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
>>> node_spec = {'Availability': 'ac... | codesearchnet |
def get_tz(tz) -> str:
from xbbg.const import exch_info
if tz is None: return DEFAULT_TZ
to_tz = tz
if isinstance(tz, str):
if hasattr(TimeZone, tz):
to_tz = getattr(TimeZone, tz)
else:
exch = exch_info(ticker=tz)
if 'tz' in exch.index:
... | Convert tz from ticker / shorthands to timezone
Args:
tz: ticker or timezone shorthands
Returns:
str: Python timzone
Examples:
>>> get_tz('NY')
'America/New_York'
>>> get_tz(TimeZone.NY)
'America/New_York'
>>> get_tz('BHP AU Equity')
'Australia/Sydney' | juraj-google-style |
def normalize_list_like_lines(generation):
lines = generation.split('\n')
output_lines = []
for line_no, line in enumerate(lines):
match = re.search('. ([-*]) ', line)
if not match or line[0] not in ('-', '*'):
output_lines.append(line)
continue
delim = match.... | Normalize lines in the given text that resemble list items. The function looks for lines that start optionally with
'-' or '*', possibly followed by Roman numerals or digits indicating nesting levels. The function reformats such
lines to make them more structured.
Args:
generation (str): The input text containing line... | github-repos |
def find_bind_module(name, verbose=False):
bindnames = get_bind_modules(verbose=verbose)
bindfile = bindnames.get(name)
if bindfile:
return bindfile
if not verbose:
return None
fuzzy_matches = get_close_pkgs(name, bindnames.keys())
if fuzzy_matches:
rows = [... | Find the bind module matching the given name.
Args:
name (str): Name of package to find bind module for.
verbose (bool): If True, print extra output.
Returns:
str: Filepath to bind module .py file, or None if not found. | juraj-google-style |
def forward(self, hidden: torch.Tensor):
if self.mode == 'mix_channel':
hidden = self.channel_feature_mixer(hidden)
hidden = self.patch_mixer(hidden)
hidden = self.feature_mixer(hidden)
return hidden | Args:
hidden (`torch.Tensor` of shape `(batch_size, num_patches, d_model)`):
Input tensor to the layer.
Returns:
`torch.Tensor`: Transformed tensor. | github-repos |
def connected_emulators(self, host=enums.JLinkHost.USB):
res = self._dll.JLINKARM_EMU_GetList(host, 0, 0)
if (res < 0):
raise errors.JLinkException(res)
num_devices = res
info = (structs.JLinkConnectInfo * num_devices)()
num_found = self._dll.JLINKARM_EMU_GetList(host, info, num_devices)
... | Returns a list of all the connected emulators.
Args:
self (JLink): the ``JLink`` instance
host (int): host type to search (default: ``JLinkHost.USB``)
Returns:
List of ``JLinkConnectInfo`` specifying the connected emulators.
Raises:
JLinkException: if fails to enumerate devices. | codesearchnet |
def get_config_parameter_boolean(config: ConfigParser, section: str, param: str, default: bool) -> bool:
try:
value = config.getboolean(section, param)
except (TypeError, ValueError, NoOptionError):
log.warning('Configuration variable {} not found or improper in section [{}]; using default of {!... | Get Boolean parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
default: default value
Returns:
parameter value, or default | codesearchnet |
def create_transformation(self, rotation=None, translation=None):
mat = None
if (rotation is not None):
mat = Matrix44.from_eulers(Vector3(rotation))
if (translation is not None):
trans = matrix44.create_from_translation(Vector3(translation))
if (mat is None):
mat = trans... | Creates a transformation matrix woth rotations and translation.
Args:
rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`
translation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3`
Returns:
A 4x4 matrix as a :py:class:`numpy.array` | codesearchnet |
def get_name(cls):
global _registry_loaded
if (not _registry_loaded):
load_message_classes()
try:
return _class_to_schema_name[cls]
except KeyError:
raise TypeError('The class {} is not in the message registry, which indicates it is not in the current list of entry points for "fe... | Retrieve the schema name associated with a message class.
Returns:
str: The schema name.
Raises:
TypeError: If the message class isn't registered. Check your entry point
for correctness. | codesearchnet |
def GetNotificationsForAllShards(self, queue):
notifications_by_session_id = {}
for queue_shard in self.GetAllNotificationShards(queue):
self._GetUnsortedNotifications(
queue_shard, notifications_by_session_id=notifications_by_session_id)
return notifications_by_session_id.values() | Returns notifications for all shards of a queue at once.
Used by worker_test_lib.MockWorker to cover all shards with a single worker.
Args:
queue: usually rdfvalue.RDFURN("aff4:/W")
Returns:
List of rdf_flows.GrrNotification objects | juraj-google-style |
def get_image_features(self, pixel_values: torch.FloatTensor, vision_feature_layers: Optional[Union[int, List[int]]]=None):
vision_feature_layers = vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers
image_outputs = self.vision_tower(pixel_values, output_hidden_stat... | Obtains image last hidden states from the vision tower and apply multimodal projection.
Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
The tensors corresponding to the input images.
vision_feature_layers (`Union[int, List[int]]`):
The vision feature layer, or the list of ind... | github-repos |
def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0):
hostname = None
try:
address = dns.reversename.from_address(ip_address)
hostname = query_dns(address, 'PTR', cache=cache, nameservers=nameservers, timeout=timeout)[0]
except dns.exception.DNSException:
pass
... | Resolves an IP address to a hostname using a reverse DNS query
Args:
ip_address (str): The IP address to resolve
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
timeout (float): Sets the DNS query timeout in seconds
Return... | codesearchnet |
def _aggregation_op(cls, op: Callable[([tf.Tensor, Optional[Sequence[int]]], tf.Tensor)], x: 'TensorFluent', vars_list: List[str]) -> 'TensorFluent':
axis = cls._varslist2axis(x, vars_list)
t = op(x.tensor, axis)
scope = []
for var in x.scope.as_list():
if (var not in vars_list):
sco... | Returns a TensorFluent for the aggregation `op` applied to fluent `x`.
Args:
op: The aggregation operation.
x: The input fluent.
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the aggregation operator's output. | codesearchnet |
def longest_existing_path(_path):
existing_path = _path
while True:
_path_new = os.path.dirname(existing_path)
if exists(_path_new):
existing_path = _path_new
break
if (_path_new == existing_path):
print('!!! [utool] This is a very illformated path ind... | r"""
Returns the longest root of _path that exists
Args:
_path (str): path string
Returns:
str: _path - path string
CommandLine:
python -m utool.util_path --exec-longest_existing_path
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut
>>> target = dirname(ut.__file__)
>... | codesearchnet |
def from_bulk_and_miller(cls, structure, miller_index, min_slab_size=8.0, min_vacuum_size=10.0, max_normal_search=None, center_slab=True, selective_dynamics=False, undercoord_threshold=0.09):
vnn_bulk = VoronoiNN(tol=0.05)
bulk_coords = [len(vnn_bulk.get_nn(structure, n)) for n in range(len(structure))]
str... | This method constructs the adsorbate site finder from a bulk
structure and a miller index, which allows the surface sites
to be determined from the difference in bulk and slab coordination,
as opposed to the height threshold.
Args:
structure (Structure): structure from which slab
input to the ASF is constructed
miller... | codesearchnet |
def byte_swap_tensor_content(tensor, from_endiness, to_endiness):
if tensor.dtype in byte_swappable:
tshape = tensor.tensor_shape.dim
tensor_bytes = tensor.tensor_content
if tensor_bytes:
tensor_size = 1
for sz in tshape:
if sz.size != 0:
... | Byte swaps.
Args:
tensor: Target tensor to change endiness.
from_endiness: The original endianness format. "big" or "little"
to_endiness: The target endianness format. "big" or "little" | github-repos |
def slice(filename, number_tiles=None, col=None, row=None, save=True):
im = Image.open(filename)
im_w, im_h = im.size
columns = 0
rows = 0
if not number_tiles is None:
validate_image(im, number_tiles)
columns, rows = calc_columns_rows(number_tiles)
extras = (columns * r... | Split an image into a specified number of tiles.
Args:
filename (str): The filename of the image to split.
number_tiles (int): The number of tiles required.
Kwargs:
save (bool): Whether or not to save tiles to disk.
Returns:
Tuple of :class:`Tile` instances. | juraj-google-style |
def inflate_plugins(self, plugins_definition, inflate_method):
if isinstance(plugins_definition, list):
return self.inflate_plugin_list(plugins_definition, inflate_method)
elif isinstance(plugins_definition, dict):
return self.inflate_plugin_dict(plugins_definition, infl... | Inflate multiple plugins based on a list/dict definition.
Args:
plugins_definition (list/dict): the plugins definitions.
inflate_method (method): the method to indlate each plugin.
Returns:
list: a list of plugin instances.
Raises:
ValueError: when the definition type is not list or dict. | juraj-google-style |
def read(cls, data):
if isinstance(data, pd.DataFrame):
output = OrderedDict({})
output['version'] = '2.0'
output['class'] = 'dimension'
[label] = [x for x in list(data.columns.values) if
x not in ['id', 'index']]
output... | Reads data from URL, Dataframe, JSON string, JSON file
or OrderedDict.
Args:
data: can be a Pandas Dataframe, a JSON string, a JSON file,
an OrderedDict or a URL pointing to a JSONstat file.
Returns:
An object of class Dimension populated with data. | juraj-google-style |
def _get_new_finished_state(self, state, new_seq, new_log_probs):
i = state[_StateKeys.CUR_INDEX]
finished_seq = state[_StateKeys.FINISHED_SEQ]
finished_scores = state[_StateKeys.FINISHED_SCORES]
finished_flags = state[_StateKeys.FINISHED_FLAGS]
finished_seq = tf.concat([finished_seq, tf.zeros([self... | Combine new and old finished sequences, and gather the top k sequences.
Args:
state: A dictionary with the current loop state.
new_seq: New sequences generated by growing the current alive sequences
int32 tensor with shape [batch_size, beam_size, i + 1]
new_log_probs: Log probabilities of new sequences
float32 tensor ... | codesearchnet |
def load_and_use(path):
example_cond, example_a, example_b = _get_example_tensors()
restored = tf.saved_model.load(path)
return restored.use_multiplex(example_cond, example_a, example_b) | Load and used a model that was previously created by `save()`.
Args:
path: Directory to load model from, typically the same directory that was
used by save().
Returns:
A tensor that is the result of using the multiplex op that is
tf.constant([1, 20, 3, 40, 5], dtype=tf.int64). | github-repos |
def rename_document(self, did, name):
payload = {'name': name}
return self._api.request('post', ('/api/documents/' + did), body=payload) | Renames the specified document.
Args:
- did (str): Document ID
- name (str): New document name
Returns:
- requests.Response: Onshape response data | codesearchnet |
def is_link(path):
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
try:
return salt.utils.path.islink(path)
except Exception as exc:
raise CommandExecutionError(exc) | Check if the path is a symlink
This is only supported on Windows Vista or later.
Inline with Unix behavior, this function will raise an error if the path
is not a symlink, however, the error raised will be a SaltInvocationError,
not an OSError.
Args:
path (str): The path to a file or directory
Returns:
bool: True i... | juraj-google-style |
def _identify_eds_ing(first, second):
A = set([first.L, first.R])
A.update(first.D)
B = set([second.L, second.R])
B.update(second.D)
depend_set = A & B
left, right = sorted(list(A ^ B))
return left, right, depend_set | Find nodes connecting adjacent edges.
Args:
first(Edge): Edge object representing the first edge.
second(Edge): Edge object representing the second edge.
Returns:
tuple[int, int, set[int]]: The first two values represent left and right node
indicies of the new edge. The third value is the new dependence set. | juraj-google-style |
def wait_for_js(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
if (len(args) < 1):
return function(*args, **kwargs)
else:
self = args[0]
if hasattr(self, 'wait_for_js'):
self.wait_for_js()
return function(*args... | Method decorator that waits for JavaScript dependencies before executing `function`.
If the function is not a method, the decorator has no effect.
Args:
function (callable): Method to decorate.
Returns:
Decorated method | codesearchnet |
def _calc_block_mean_variance(image, mask, blocksize):
I = image.copy()
I_f = (I.astype(np.float32) / 255.0)
result = np.zeros(((image.shape[0] / blocksize), (image.shape[1] / blocksize)), dtype=np.float32)
for i in xrange(0, (image.shape[0] - blocksize), blocksize):
for j in xrange(0, (image.sh... | Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image of same size as input with foreground inpainted with background. | codesearchnet |
def train(self, debug=True, force=False, single_thread=False, timeout=20):
if ((not self.must_train) and (not force)):
return
self.padaos.compile()
self.train_thread = Thread(target=self._train, kwargs=dict(debug=debug, single_thread=single_thread, timeout=timeout), daemon=True)
self.train_threa... | Trains all the loaded intents that need to be updated
If a cache file exists with the same hash as the intent file,
the intent will not be trained and just loaded from file
Args:
debug (bool): Whether to print a message to stdout each time a new intent is trained
force (bool): Whether to force training if already fini... | codesearchnet |
def model_fn(features, labels, mode, params, config):
del labels, config
if params["analytic_kl"] and params["mixture_components"] != 1:
raise NotImplementedError(
"Using `analytic_kl` is only supported when `mixture_components = 1` "
"since there's no closed form otherwise.")
encoder = m... | Builds the model function for use in an estimator.
Arguments:
features: The input features for the estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionary.
config: The RunConfig, unused here.
Returns:
EstimatorSpec: A tf.estimato... | juraj-google-style |
def num_connected_components(self, unitary_only=False):
reg_offset = 0
reg_map = {}
if unitary_only:
regs = self.qregs
else:
regs = self.qregs+self.cregs
for reg in regs:
reg_map[reg.name] = reg_offset
reg_offset... | How many non-entangled subcircuits can the circuit be factored to.
Args:
unitary_only (bool): Compute only unitary part of graph.
Returns:
int: Number of connected components in circuit. | juraj-google-style |
def __init__(self, event_type: str):
if not isinstance(event_type, str) or event_type == "":
raise TypeError("Invalid event type: {}".format(event_type))
self._event_type: str = event_type
self._target: EventDispatcherBase = None | Constructor.
Args:
event_type (str): The type - string identifier - of the event.
Must not be `None` or empty string. | juraj-google-style |
def init_c_overturn(step):
(rbot, rtop) = misc.get_rbounds(step)
xieut = step.sdat.par['tracersin']['fe_eut']
k_fe = step.sdat.par['tracersin']['k_fe']
xi0l = step.sdat.par['tracersin']['fe_cont']
xi0s = (k_fe * xi0l)
xired = (xi0l / xieut)
rsup = (((rtop ** 3) - ((xired ** (1 / (1 - k_fe)))... | Initial concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial position
at which it is evaluated. | codesearchnet |
def get_first_content(el_list, alt=None, strip=True):
if not el_list:
return alt
content = el_list[0].getContent()
if strip:
content = content.strip()
if not content:
return alt
return content | Return content of the first element in `el_list` or `alt`. Also return `alt`
if the content string of first element is blank.
Args:
el_list (list): List of HTMLElement objects.
alt (default None): Value returner when list or content is blank.
strip (bool, default True): Call .strip() to content.
Returns:
str or alt: ... | juraj-google-style |
def forward(self, hidden_states):
hidden_states = hidden_states.transpose(-1, 1)
hidden_states = self.conv1(hidden_states)
hidden_states = torch.relu(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.conv2(hidden_states)
hidden_states = hidden_states.transpose(-1, 1... | Calculate forward propagation.
Args:
hidden_states (torch.Tensor): Batch of input tensors (batch_size, time, input_channels).
Returns:
torch.Tensor: Batch of output tensors (batch_size, time, hidden_channels). | github-repos |
def parse_data_types_and_routes_from_doc_ref(api, doc, namespace_context, ignore_missing_entries=False):
assert (doc is not None)
data_types = set()
routes = defaultdict(set)
for match in doc_ref_re.finditer(doc):
try:
tag = match.group('tag')
val = match.group('val')
... | Given a documentation string, parse it and return all references to other
data types and routes.
Args:
- api: The API containing this doc ref.
- doc: The documentation string to parse.
- namespace_context: The namespace name relative to this documentation.
- ignore_missing_entries: If set, this will skip references to... | codesearchnet |
def get_or_create(self, defaults=None, **kwargs):
try:
return (self.get(**kwargs), False)
except ObjectDoesNotExist:
pass
data = (defaults or {})
data.update(kwargs)
return (self._model_class(**data).blocking_save(), True) | Looks up an object with the given kwargs, creating a new one if necessary.
Args:
defaults (dict): Used when we create a new object. Must map to fields
of the model.
\*\*kwargs: Used both for filtering and new object creation.
Returns:
A tuple of (object, created), where created is a boolean variable
specifies whether... | codesearchnet |
def __init__(self, retriever):
self._page_token = None
self._first_page = True
self._retriever = retriever
self._count = 0 | Initializes an instance of an Iterator.
Args:
retriever: a function that can retrieve the next page of items. | juraj-google-style |
def impad_to_multiple(img, divisor, pad_val=0):
pad_h = int(np.ceil(img.shape[0] / divisor)) * divisor
pad_w = int(np.ceil(img.shape[1] / divisor)) * divisor
return impad(img, (pad_h, pad_w), pad_val) | Pad an image to ensure each edge to be multiple to some number.
Args:
img (ndarray): Image to be padded.
divisor (int): Padded image edges will be multiple to divisor.
pad_val (number or sequence): Same as :func:`impad`.
Returns:
ndarray: The padded image. | juraj-google-style |
def getShareInfo(item):
key = f'_syn_sharinfo_{item.__class__.__module__}_{item.__class__.__qualname__}'
info = getattr(item, key, None)
if (info is not None):
return info
meths = {}
info = {'meths': meths}
for name in dir(item):
if name.startswith('_'):
continue
... | Get a dictionary of special annotations for a Telepath Proxy.
Args:
item: Item to inspect.
Notes:
This will set the ``_syn_telemeth`` attribute on the item
and the items class, so this data is only computed once.
Returns:
dict: A dictionary of methods requiring special handling by the proxy. | codesearchnet |
class XGBoostModelHandlerDatatable(XGBoostModelHandler[datatable.Frame, PredictionResult, Union[xgboost.Booster, xgboost.XGBModel]]):
def run_inference(self, batch: Sequence[datatable.Frame], model: Union[xgboost.Booster, xgboost.XGBModel], inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionResul... | Implementation of the ModelHandler interface for XGBoost
using datatable dataframes as input.
Example Usage::
pcoll | RunInference(
XGBoostModelHandlerDatatable(
model_class="XGBoost Model Class",
model_state="my_model_state.json")))
Args:
model_class: class of the XGBoost model that defines the model
structure.
mod... | github-repos |
def update(self, friendly_name=None, description=None, query=None):
self._table._load_info()
if (query is not None):
if isinstance(query, _query.Query):
query = query.sql
self._table._info['view'] = {'query': query}
self._table.update(friendly_name=friendly_name, description=desc... | Selectively updates View information.
Any parameters that are None (the default) are not applied in the update.
Args:
friendly_name: if not None, the new friendly name.
description: if not None, the new description.
query: if not None, a new query string for the View. | codesearchnet |
def default_peek(python_type, exposes):
with_args = False
make = python_type
try:
make()
except (SystemExit, KeyboardInterrupt):
raise
except:
make = lambda: python_type.__new__(python_type)
try:
make()
except (SystemExit, KeyboardInterrupt):
... | Autoserializer factory.
Works best in Python 3.
Arguments:
python_type (type): type constructor.
exposes (iterable): sequence of attributes.
Returns:
callable: deserializer (`peek` routine). | juraj-google-style |
def _unify_call_signature(i, dist_fn):
if distribution_util.is_distribution_instance(dist_fn):
return ((lambda *_: dist_fn), None)
if (not callable(dist_fn)):
raise TypeError('{} must be either `tfd.Distribution`-like or `callable`.'.format(dist_fn))
args = _get_required_args(dist_fn)
if... | Creates `dist_fn_wrapped` which calls `dist_fn` with all prev nodes.
Args:
i: Python `int` corresponding to position in topologically sorted DAG.
dist_fn: Python `callable` which takes a subset of previously constructed
distributions (in reverse order) and produces a new distribution instance.
Returns:
dist_fn_wrappe... | codesearchnet |
class Permute(Layer):
def __init__(self, dims, **kwargs):
super(Permute, self).__init__(**kwargs)
self.dims = tuple(dims)
if sorted(dims) != list(range(1, len(dims) + 1)):
raise ValueError('Invalid permutation `dims` for Permute Layer: %s. The set of indices in `dims` must be co... | Permutes the dimensions of the input according to a given pattern.
Useful e.g. connecting RNNs and convnets.
Example:
```python
model = Sequential()
model.add(Permute((2, 1), input_shape=(10, 64)))
# now: model.output_shape == (None, 64, 10)
# note: `None` is the batch dimension
```
Args:
dims: Tuple of integers. P... | github-repos |
def to_representation(self, value):
if not value:
return None
image = get_thumbnail(value, self.geometry_string, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except:
... | Perform the actual serialization.
Args:
value: the image to transform
Returns:
a url pointing at a scaled and cached image | juraj-google-style |
def highlight(text: str, color_code: int, bold: bool=False) -> str:
return '{}\x1b[{}m{}\x1b[0m'.format(('\x1b[1m' if bold else ''), color_code, text) | Wraps the given string with terminal color codes.
Args:
text: The content to highlight.
color_code: The color to highlight with, e.g. 'shelltools.RED'.
bold: Whether to bold the content in addition to coloring.
Returns:
The highlighted string. | codesearchnet |
def List(self, request, global_params=None):
config = self.GetMethodConfig('List')
return self._RunMethod(config, request, global_params=global_params) | List all GitHubEnterpriseConfigs for a given project.
Args:
request: (CloudbuildProjectsGithubEnterpriseConfigsListRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(ListGithubEnterpriseConfigsResponse) The response message. | github-repos |
def _EnforceProcessMemoryLimit(self, memory_limit):
if resource:
if (memory_limit is None):
memory_limit = (((4 * 1024) * 1024) * 1024)
elif (memory_limit == 0):
memory_limit = resource.RLIM_INFINITY
resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit... | Enforces a process memory limit.
Args:
memory_limit (int): maximum number of bytes the process is allowed
to allocate, where 0 represents no limit and None a default of
4 GiB. | codesearchnet |
def run(self, dag):
self.layout = self.layout or self.property_set['layout']
if self.layout is None:
raise TranspilerError("EnlargeWithAncilla requires property_set[\"layout\"] or"
" \"layout\" parameter to run")
layout_virtual_qubits = se... | Extends dag with virtual qubits that are in layout but not in the circuit yet.
Args:
dag (DAGCircuit): DAG to extend.
Returns:
DAGCircuit: An extended DAG.
Raises:
TranspilerError: If there is not layout in the property set or not set at init time. | juraj-google-style |
def disable_control_flow_v2(unused_msg: str) -> Callable[[_F], _F]:
def wrapper(func: _F) -> _F:
func._disable_control_flow_v2 = True
return func
return wrapper | Decorator for a function in a with_control_flow_v2 enabled test class.
Blocks the function from being run with v2 control flow ops.
Args:
unused_msg: Reason for disabling.
Returns:
The wrapped function with _disable_control_flow_v2 attr set to True. | github-repos |
def xml(self):
self.pendingvalidation()
E = ElementMaker(namespace='http:
attribs = {}
attribs['{http:
attribs['version'] = FOLIAVERSION
attribs['generator'] = ('pynlpl.formats.folia-v' + LIBVERSION)
metadataattribs = {}
metadataattribs[(('{' + NSFOLIA) + '}type')] = self.metadatatype
... | Serialise the document to XML.
Returns:
lxml.etree.Element
See also:
:meth:`Document.xmlstring` | codesearchnet |
def traverse_nodes(self, node_set, depth=0):
tab = ' '
result = list()
for n in node_set:
repr = (n if (self.nodes[n]['type'] == 'variable') else f"{n}{inspect.signature(self.nodes[n]['lambda_fn'])}")
result.append(f'{(tab * depth)}{repr}')
result.extend(self.traverse_nodes(self.suc... | BFS traversal of nodes that returns name traversal as large string.
Args:
node_set: Set of input nodes to begin traversal.
depth: Current traversal depth for child node viewing.
Returns:
type: String containing tabbed traversal view. | codesearchnet |
def CheckTaskToMerge(self, task):
with self._lock:
is_abandoned = task.identifier in self._tasks_abandoned
is_processing = task.identifier in self._tasks_processing
is_queued = task.identifier in self._tasks_queued
if not is_queued and not is_processing and not is_abandoned:
ra... | Checks if the task should be merged.
Args:
task (Task): task.
Returns:
bool: True if the task should be merged.
Raises:
KeyError: if the task was not queued, processing or abandoned. | juraj-google-style |
def put_many(self, type: Type[T], items: Iterable[T]) -> None:
LOGGER.info("Getting SinkHandlers for \"{type}\"".format(type=type.__name__))
try:
handlers = self._put_types[type]
except KeyError:
try:
LOGGER.info("Building new SinkHandlers for \"{... | Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
items: An iterable (e.g. list) of objects to be inserted into the data pipeline. | juraj-google-style |
def CreateAdsWithCustomizations(client, adgroup_ids, feed_name):
adgroup_ad_service = client.GetService('AdGroupAdService', 'v201809')
expanded_text_ad = {'xsi_type': 'ExpandedTextAd', 'headlinePart1': ('Luxury Cruise to {=%s.Name}' % feed_name), 'headlinePart2': ('Only {=%s.Price}' % feed_name), 'description':... | Creates ExpandedTextAds that use ad customizations for specified AdGroups.
Args:
client: an AdWordsClient instance.
adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to.
feed_name: the name of the feed used to apply customizations.
Raises:
GoogleAdsError: if no ExpandedTextAds were added. | codesearchnet |
def structure_np_to_list(data):
if isinstance(data, np.ndarray):
return data.tolist()
if isinstance(data, dict):
return {key: structure_np_to_list(value) for key, value in data.items()}
if isinstance(data, list):
return [structure_np_to_list(item) for item in data]
if isinstance(... | Apply a function to a recursive structure of dict and list.
Args:
data: The data to apply the function to.
Returns:
The data with the function applied. | github-repos |
def _AddHeader(self, fp):
text = textwrap.wrap(textwrap.dedent(self.config_header), break_on_hyphens=False)
fp.write('\n'.join([('
fp.write('\n\n') | Create a file header in the config.
Args:
fp: int, a file pointer for writing the header. | codesearchnet |
def rot90(array, k=1, axes=(0, 1)):
array = convert_to_tensor(array)
if array.ndim < 2:
raise ValueError(f'Input array must have at least 2 dimensions. Received: array.ndim={array.ndim}')
if len(axes) != 2 or axes[0] == axes[1]:
raise ValueError(f'Invalid axes: {axes}. Axes must be a tuple o... | Rotate an array by 90 degrees in the specified plane using PyTorch.
Args:
array: Input tensor
k: Number of 90-degree rotations (default=1)
axes: Tuple of two axes that define the
plane of rotation (defaults to `(0, 1)`).
Returns:
Rotated tensor | github-repos |
def heightmap_clamp(hm: np.ndarray, mi: float, ma: float) -> None:
hm.clip(mi, ma) | Clamp all values on this heightmap between ``mi`` and ``ma``
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
mi (float): The lower bound to clamp to.
ma (float): The upper bound to clamp to.
.. deprecated:: 2.0
Do ``hm.clip(mi, ma)`` instead. | codesearchnet |
def dprintx(passeditem, special=False):
if DEBUGALL:
if special:
from pprint import pprint
pprint(passeditem)
else:
print(('%s%s%s' % (C_TI, passeditem, C_NORM))) | Print Text if DEBUGALL set, optionally with PrettyPrint.
Args:
passeditem (str): item to print
special (bool): determines if item prints with PrettyPrint
or regular print. | codesearchnet |
def get_parameters(params=None, path='', grad_only=True):
global current_scope
if (params is None):
params = OrderedDict()
for (k, v) in iteritems(current_scope):
if isinstance(v, dict):
with parameter_scope(k):
params = get_parameters(params, ('/'.join([path, k])... | Get parameter Variables under the current parameter scope.
Args:
params (dict): Internal use. User doesn't set it manually.
path (str): Internal use. User doesn't set it manually.
grad_only (bool): Retrieve all parameters under the current scope if
False, while only parameters with need_grad=True are retrieved
if Tru... | codesearchnet |
def depth_april_average_ground_temperature(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 `depth_april... | Corresponds to IDD Field `depth_april_average_ground_temperature`
Args:
value (float): value for IDD Field `depth_april_average_ground_temperature`
Unit: C
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | juraj-google-style |
def __init__(self, component=None, action=None, target=None, args=None, filename=None, lineno=None, error=None, capacity=None):
self.component = component
self._action = action
self._target = target
self.args = args
self._filename = filename
self._lineno = lineno
self._error = error
self... | Instantiates a FireTraceElement.
Args:
component: The result of this element of the trace.
action: The type of action (e.g. instantiating a class) taking place.
target: (string) The name of the component being acted upon.
args: The args consumed by the represented action.
filename: The file in which the action is defi... | github-repos |
def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None, dtype=tf.float32):
mlperf_log.resnet_print(key=mlperf_log.INPUT_ORDER)
filenames = get_filenames(is_training, data_dir)
dataset = tf.data.Dataset.from_tensor_slices(filenames)
if is_training:
dataset = dataset.shuffle(b... | Input function which provides batches for train or eval.
Args:
is_training: A boolean denoting whether the input is for training.
data_dir: The directory containing the input data.
batch_size: The number of samples per batch.
num_epochs: The number of epochs to repeat the dataset.
num_gpus: The number of gpus used for... | codesearchnet |
def is_chief(cluster_spec=None, task_type=None, task_id=None):
if has_worker_context():
return dc_context.get_current_worker_context().is_chief
_validate_cluster_spec(cluster_spec, task_type, task_id)
cluster_spec = normalize_cluster_spec(cluster_spec).as_dict()
if task_type == 'chief' or task_t... | Returns whether the given task is chief in the cluster.
Since there is at most one evaluator and the evaluator itself should be
independent of the training cluster, the evaluator job is also a chief job on
its own.
If this is currently running under a `_WorkerContext` of distribute
coordinator, the arguments can be o... | github-repos |
def ToScriptHash(self, address):
if len(address) == 34:
if address[0] == 'A':
data = b58decode(address)
if data[0] != self.AddressVersion:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(da... | Retrieve the script_hash based from an address.
Args:
address (str): a base58 encoded address.
Raises:
ValuesError: if an invalid address is supplied or the coin version is incorrect
Exception: if the address string does not start with 'A' or the checksum fails
Returns:
UInt160: script hash. | juraj-google-style |
def set_metadata(self, entity_type, entity_id, metadata):
if (not is_valid_uuid(entity_id)):
raise StorageArgumentException('Invalid UUID for entity_id: {0}'.format(entity_id))
if (not isinstance(metadata, dict)):
raise StorageArgumentException('The metadata was not provided as a dictionary')
... | Set metadata for an entity.
Args:
entity_type (str): Type of the entity. Admitted values: ['project',
'folder', 'file'].
entity_id (str): The UUID of the entity to be modified.
metadata (dict): A dictionary of key/value pairs to be written as
metadata.
Warning:
It will replace all existing metadata with the provided ... | codesearchnet |
def get_file_list(self):
if os.path.isdir(self.root_path):
return [os.path.join(self.root_path, f) for f in os.listdir(self.root_path) if os.path.isfile(os.path.join(self.root_path, f))]
else:
return [self.root_path] | Retrieve the list of absolute paths to all the files in this data source.
Returns:
List[str] List of absolute paths. | codesearchnet |
def allzeros(msg):
d = hex2bin(data(msg))
if bin2int(d) > 0:
return False
else:
return True | check if the data bits are all zeros
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | juraj-google-style |
def run_census(flags_obj, ctx):
train_file = os.path.join(flags_obj.data_dir, census_dataset.TRAINING_FILE)
test_file = os.path.join(flags_obj.data_dir, census_dataset.EVAL_FILE)
def train_input_fn():
return census_dataset.input_fn(
train_file, flags_obj.epochs_between_evals, True, flags_obj.ba... | Construct all necessary functions and call run_loop.
Args:
flags_obj: Object containing user specified flags. | juraj-google-style |
def check_file(self, fs, info):
if ((self.exclude is not None) and fs.match(self.exclude, info.name)):
return False
return fs.match(self.filter, info.name) | Check if a filename should be included.
Override to exclude files from the walk.
Arguments:
fs (FS): A filesystem instance.
info (Info): A resource info object.
Returns:
bool: `True` if the file should be included. | codesearchnet |
def expo(base=2, factor=1, max_value=None):
n = 0
while True:
a = (factor * (base ** n))
if ((max_value is None) or (a < max_value)):
(yield a)
n += 1
else:
(yield max_value) | Generator for exponential decay.
Args:
base: The mathematical base of the exponentiation operation
factor: Factor to multiply the exponentation by.
max_value: The maximum value to yield. Once the value in the
true exponential sequence exceeds this, the value
of max_value will forever after be yielded. | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.