code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def _ParseTriggerEndTime(self, parser_mediator, trigger):
time_elements_tuple = (trigger.end_date.year, trigger.end_date.month, trigger.end_date.day_of_month, 0, 0, 0)
date_time = None
if (time_elements_tuple != (0, 0, 0, 0, 0, 0)):
try:
date_time = dfdatetime_time_elements.TimeElements(... | Parses the end time from a trigger.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
trigger (job_trigger): a trigger.
Returns:
dfdatetime.DateTimeValues: last run date and time or None if not
available. | codesearchnet |
def parse_variant(store, institute_obj, case_obj, variant_obj, update=False, genome_build='37', get_compounds=True):
has_changed = False
compounds = variant_obj.get('compounds', [])
if (compounds and get_compounds):
if ('not_loaded' not in compounds[0]):
new_compounds = store.update_vari... | Parse information about variants.
- Adds information about compounds
- Updates the information about compounds if necessary and 'update=True'
Args:
store(scout.adapter.MongoAdapter)
institute_obj(scout.models.Institute)
case_obj(scout.models.Case)
variant_obj(scout.models.Variant)
update(bool): If variant should be u... | codesearchnet |
def _call_method(self, method, req, resp_class):
payload = req.SerializeToString()
headers = {
'Content-Type': 'application/x-protobuf',
'Content-Length': str(len(payload)),
'X-Goog-Api-Format-Version': '2'
}
response, content = self._http.request(
'%s:%s' % (sel... | _call_method call the given RPC method over HTTP.
It uses the given protobuf message request as the payload and
returns the deserialized protobuf message response.
Args:
method: RPC method name to be called.
req: protobuf message for the RPC request.
resp_class: protobuf message class for the RPC response.
Returns:
... | juraj-google-style |
def call_boxes(self, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]], text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]]=None, boxes: Optional[Union[List[List[int]], List[List[List[int]]]]]=None, word_labels: Optional[Union[List[int], List[List[int]]]]=None, add_s... | Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
sequences with word-level normalized bounding boxes and optional labels.
Args:
text (`str`, `List[str]`, `List[List[str]]`):
The sequence or batch of sequences to be encoded. Each sequence can be a string, a list ... | github-repos |
def getVersionListCount(self, orgresource):
url = nurls['getVersionListCount']
data = {'userid': self.user_id,
'useridx': self.useridx,
'orgresource': orgresource,
}
r = self.session.post(url = url, data = data)
j = json.loads(r... | GetVersionListCount
Args:
orgresource: File path
Returns:
Integer number: # of version list
False: Failed to get property | juraj-google-style |
def _URange(s):
a = s.split("..")
if len(a) == 1:
return [_UInt(a[0])]
if len(a) == 2:
lo = _UInt(a[0])
hi = _UInt(a[1])
if lo < hi:
return range(lo, hi + 1)
raise InputError("invalid Unicode range %s" % (s,)) | Converts string to Unicode range.
'0001..0003' => [1, 2, 3].
'0001' => [1].
Args:
s: string to convert
Returns:
Unicode range
Raises:
InputError: the string is not a valid Unicode range. | juraj-google-style |
def text(cls, text, *, resize=None, single_use=None, selective=None):
return cls(types.KeyboardButton(text), resize=resize, single_use=single_use, selective=selective) | Creates a new button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.
single_use (`bool`):
If present, the entire keyboard will be reconfigured to
be usable only once before it hides itself.
selective (`bool`)... | codesearchnet |
def _get_table(name):
item = google.datalab.utils.commands.get_notebook_item(name)
if isinstance(item, bigquery.Table):
return item
try:
return _existing_table_cache[name]
except KeyError:
table = bigquery.Table(name)
if table.exists():
_existing_table_cache[name] = table
re... | Given a variable or table name, get a Table if it exists.
Args:
name: the name of the Table or a variable referencing the Table.
Returns:
The Table, if found. | juraj-google-style |
def persist_upstream_diagram(self, filepath):
assert isinstance(filepath, str), 'Step {} error, filepath must be str. Got {} instead'.format(self.name, type(filepath))
persist_as_png(self.upstream_structure, filepath) | Creates upstream steps diagram and persists it to disk as png file.
Pydot graph is created and persisted to disk as png file under the filepath directory.
Args:
filepath (str): filepath to which the png with steps visualization should
be persisted | codesearchnet |
def markdown_cell(markdown):
r
import utool as ut
markdown_header = ut.codeblock(
)
markdown_footer = ut.codeblock(
)
return (markdown_header + '\n' +
ut.indent(repr_single_for_md(markdown), ' ' * 2) +
'\n' + markdown_footer) | r"""
Args:
markdown (str):
Returns:
str: json formatted ipython notebook markdown cell
CommandLine:
python -m ibeis.templates.generate_notebook --exec-markdown_cell
Example:
>>> # DISABLE_DOCTEST
>>> from ibeis.templates.generate_notebook import * # NOQA
>>> markdown = '# Title'
>>> result = markdown_cell(markdown)... | juraj-google-style |
def _get_short_description(self):
if (self.description is None):
return None
lines = [x for x in self.description.split('\n')]
if (len(lines) == 1):
return lines[0]
elif ((len(lines) >= 3) and (lines[1] == '')):
return lines[0]
return None | Return the first line of a multiline description
Returns:
string: The short description, otherwise None | codesearchnet |
def sign(allocate_quota_request):
if (not isinstance(allocate_quota_request, sc_messages.AllocateQuotaRequest)):
raise ValueError(u'Invalid request')
op = allocate_quota_request.allocateOperation
if ((op is None) or (op.methodName is None) or (op.consumerId is None)):
logging.error(u'Bad %s:... | Obtains a signature for an operation in a `AllocateQuotaRequest`
Args:
op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an
operation used in a `AllocateQuotaRequest`
Returns:
string: a secure hash generated from the operation | codesearchnet |
def define_grid(self, matrix):
self.style['grid-template-areas'] = ''.join("'%s'"%(' '.join(x)) for x in matrix) | Populates the Table with a list of tuples of strings.
Args:
matrix (list): list of iterables of strings (lists or something else).
Items in the matrix have to correspond to a key for the children. | juraj-google-style |
def WinChmod(filename, acl_list, user=None):
if (user is None):
user = win32api.GetUserName()
if (not os.path.exists(filename)):
raise RuntimeError(('filename %s does not exist' % filename))
acl_bitmask = 0
for acl in acl_list:
acl_bitmask |= getattr(ntsecuritycon, acl)
dacl ... | Provide chmod-like functionality for windows.
Doco links:
goo.gl/n7YR1
goo.gl/rDv81
goo.gl/hDobb
Args:
filename: target filename for acl
acl_list: list of ntsecuritycon acl strings to be applied with bitwise OR.
e.g. ["FILE_GENERIC_READ", "FILE_GENERIC_WRITE"]
user: username string. If not specified we use the user... | codesearchnet |
def __init__(self, channel):
self.GetStepNames = channel.unary_unary(
'/gauge.messages.lspService/GetStepNames',
request_serializer=messages__pb2.StepNamesRequest.SerializeToString,
response_deserializer=messages__pb2.StepNamesResponse.FromString,
)
self.CacheFile = channel.... | Constructor.
Args:
channel: A grpc.Channel. | juraj-google-style |
def _get_genes(self, variant):
transcripts = variant['transcripts']
ensembl_ids = [transcript['ensembl_id'] for transcript in
transcripts if transcript['ensembl_id']]
hgnc_symbols = [transcript['hgnc_symbol'] for transcript in
transcripts i... | Add the genes for a variant
Get the hgnc symbols from all transcripts and add them
to the variant.
Args:
variant (dict): A variant dictionary
Returns:
genes (list): A list of Genes | juraj-google-style |
def cummax(self, axis=None, skipna=True, *args, **kwargs):
axis = self._get_axis_number(axis) if axis is not None else 0
if axis:
self._validate_dtypes()
return self.__constructor__(
query_compiler=self._query_compiler.cummax(
axis=axis, skipna=sk... | Perform a cumulative maximum across the DataFrame.
Args:
axis (int): The axis to take maximum on.
skipna (bool): True to skip NA values, false otherwise.
Returns:
The cumulative maximum of the DataFrame. | juraj-google-style |
def delete_variants(self, case_id, variant_type, category=None):
category = category or ''
LOG.info("Deleting old {0} {1} variants for case {2}".format(
variant_type, category, case_id))
query = {'case_id': case_id, 'variant_type': variant_type}
if category:
... | Delete variants of one type for a case
This is used when a case is reanalyzed
Args:
case_id(str): The case id
variant_type(str): 'research' or 'clinical'
category(str): 'snv', 'sv' or 'cancer' | juraj-google-style |
def unstack(x, num=None, axis=0):
if any_symbolic_tensors((x,)):
return Unstack(num, axis).symbolic_call(x)
return backend.core.unstack(x, num=num, axis=axis) | Unpacks the given dimension of a rank-R tensor into rank-(R-1) tensors.
Args:
x: The input tensor.
num: The length of the dimension axis. Automatically inferred
if `None`.
axis: The axis along which to unpack.
Returns:
A list of tensors unpacked along the given axis.
Example:
>>> x = keras.ops.array([[1, 2], [3, 4]... | github-repos |
def tmpdir(suffix='', prefix='tmp', dir=None):
tmp = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
(yield tmp)
shutil.rmtree(tmp) | Create a temporary directory with a context manager. The file is deleted when the context exits.
The prefix, suffix, and dir arguments are the same as for mkstemp().
Args:
suffix (str): If suffix is specified, the file name will end with that suffix, otherwise there will be no
suffix.
prefix (str): If prefix is spe... | codesearchnet |
def _get_next_partition(self) -> tuple[int, float]:
rank = self._working_tensor_shape.rank
if rank is None or rank == 0:
return (0, math.inf)
num_elems = self._working_tensor_shape.num_elements()
def num_partitions(axis: int) -> float:
axis_len = self._working_tensor_shape.dims[axis].va... | Gets tensor partition with size closest to shard_size_remaining.
Returns:
A tuple containing the axis and size of the next partition. | github-repos |
def trajectory(self):
traj = np.zeros((2, self.times.size))
for (t, time) in enumerate(self.times):
traj[(:, t)] = self.center_of_mass(time)
return traj | Calculates the center of mass for each time step and outputs an array
Returns: | codesearchnet |
def infer_element_type(elements):
element_type = typehints.Union[[trivial_inference.instance_to_type(e) for e in elements]]
return element_type | For internal use only; no backwards-compatibility guarantees.
Infer a Beam type for a list of elements.
Args:
elements (List[Any]): A list of elements for which the type should be
inferred.
Returns:
A Beam type encompassing all elements. | github-repos |
def apply_grad_zmat_tensor(grad_C, construction_table, cart_dist):
if (construction_table.index != cart_dist.index).any():
message = 'construction_table and cart_dist must use the same index'
raise ValueError(message)
X_dist = cart_dist.loc[(:, ['x', 'y', 'z'])].values.T
C_dist = np.tensordo... | Apply the gradient for transformation to Zmatrix space onto cart_dist.
Args:
grad_C (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array.
The mathematical details of the index layout is explained in
:meth:`~chemcoord.Cartesian.get_grad_zmat()`.
construction_table (pandas.DataFrame): Explained in
:meth:`~chemcoord.Cartes... | codesearchnet |
def diff_is_docstring_only(repo: Repo, branching_point: str, filename: str) -> bool:
folder = Path(repo.working_dir)
with checkout_commit(repo, branching_point):
with open(folder / filename, 'r', encoding='utf-8') as f:
old_content = f.read()
with open(folder / filename, 'r', encoding='u... | Check if the diff is only in docstrings (or comments and whitespace) in a filename.
Args:
repo (`git.Repo`): A git repository (for instance the Transformers repo).
branching_point (`str`): The commit reference of where to compare for the diff.
filename (`str`): The filename where we want to know if the diff isonly in ... | github-repos |
def load_region(adapter, case_id, hgnc_id=None, chrom=None, start=None, end=None):
if hgnc_id:
gene_obj = adapter.hgnc_gene(hgnc_id)
if (not gene_obj):
ValueError('Gene {} does not exist in database'.format(hgnc_id))
chrom = gene_obj['chromosome']
start = gene_obj['start'... | Load all variants in a region defined by a HGNC id
Args:
adapter (MongoAdapter)
case_id (str): Case id
hgnc_id (int): If all variants from a gene should be uploaded
chrom (str): If variants from coordinates should be uploaded
start (int): Start position for region
end (int): Stop position for region | codesearchnet |
def _create_conversion_trie(strict):
t = pygtrie.CharTrie()
for beta, uni in _map.BETACODE_MAP.items():
if strict:
t[beta] = uni
else:
diacritics = beta[1:]
perms = itertools.permutations(diacritics)
... | Create the trie for betacode conversion.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The trie for conversion. | juraj-google-style |
def _create_checkable_action(self, text, conf_name, editorstack_method):
def toogle(checked):
self.switch_to_plugin()
self._toggle_checkable_action(checked, editorstack_method,
conf_name)
action = create_action(self, text, toggle... | Helper function to create a checkable action.
Args:
text (str): Text to be displayed in the action.
conf_name (str): configuration setting associated with the action
editorstack_method (str): name of EditorStack class that will be
used to update the changes in each editorstack. | juraj-google-style |
def auto_docstring(obj=None, *, custom_intro=None, custom_args=None, checkpoint=None):
def auto_docstring_decorator(obj):
if len(obj.__qualname__.split('.')) > 1:
return auto_method_docstring(obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint)
else:
... | Automatically generates docstrings for classes and methods in the Transformers library.
This decorator can be used in the following forms:
@auto_docstring
def my_function(...):
...
or
@auto_docstring()
def my_function(...):
...
or
@auto_docstring(custom_intro="Custom intro", ...)
def my_function(...):
...
Args:
custo... | github-repos |
def get_conversion_factor(self, new_unit):
uo_base, ofactor = self.as_base_units
un_base, nfactor = Unit(new_unit).as_base_units
units_new = sorted(un_base.items(),
key=lambda d: _UNAME2UTYPE[d[0]])
units_old = sorted(uo_base.items(),
... | Returns a conversion factor between this unit and a new unit.
Compound units are supported, but must have the same powers in each
unit type.
Args:
new_unit: The new unit. | juraj-google-style |
def adversary(self, name, owner=None, **kwargs):
return Adversary(self.tcex, name, owner=owner, **kwargs) | Create the Adversary TI object.
Args:
owner:
name:
**kwargs:
Return: | codesearchnet |
def get_recipe(self, recipe_name):
if recipe_name.endswith('.yaml'):
recipe = self._recipes.get(RecipeObject.FromFile(recipe_name, self._recipe_actions, self._recipe_resources).name)
else:
recipe = self._recipes.get(recipe_name)
if recipe is None:
rai... | Get a recipe by name.
Args:
recipe_name (str): The name of the recipe to fetch. Can be either the
yaml file name or the name of the recipe. | juraj-google-style |
def __init__(self, temperature=1.0, max_fine_history_length=512, max_fine_input_length=1024, n_fine_codebooks=8, **kwargs):
super().__init__(temperature=temperature)
self.max_fine_history_length = max_fine_history_length
self.max_fine_input_length = max_fine_input_length
self.n_fine_codebooks = n_fine_c... | Class that holds a generation configuration for [`BarkFineModel`].
[`BarkFineModel`] is an autoencoder model, so should not usually be used for generation. However, under the
hood, it uses `temperature` when used by [`BarkModel`]
This configuration inherit from [`GenerationConfig`] and can be used to control the mode... | github-repos |
def handle_app_update(self, task_id, future, memo_cbk=False):
if (not self.tasks[task_id]['app_fu'].done()):
logger.error('Internal consistency error: app_fu is not done for task {}'.format(task_id))
if (not (self.tasks[task_id]['app_fu'] == future)):
logger.error('Internal consistency error: ca... | This function is called as a callback when an AppFuture
is in its final state.
It will trigger post-app processing such as checkpointing
and stageout.
Args:
task_id (string) : Task id
future (Future) : The relevant app future (which should be
consistent with the task structure 'app_fu' entry
KWargs:
memo_cbk(Bool) :... | codesearchnet |
def handle(self, message, connection):
handler = self._handlers.get((message.msgtype, message.revision))
if handler is None:
handler = self._handlers.get(message.msgtype)
if handler is None:
raise ProtocolError("%s not expected on server" % message)
t... | Delegate a received message to the appropriate handler.
Args:
message (Message) :
The message that was receive that needs to be handled
connection (ServerConnection) :
The connection that received this message
Raises:
ProtocolError | juraj-google-style |
def _set_typeahead(cls, el, value):
PlaceholderHandler.reset_placeholder_dropdown(el)
if ((not value) and (not el.value)):
DropdownHandler.set_dropdown_glyph(el.id, 'glyphicon-alert')
return
if (len(value) == 1):
source = value[0]['source'].strip()
dropdown_el = DropdownHandl... | Convert given `el` to typeahead input and set it to `value`.
This method also sets the dropdown icons and descriptors.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
value (list): List of dicts with two keys: ``source`` and ``val``. | codesearchnet |
def describe_file(module):
descriptor = FileDescriptor()
descriptor.package = util.get_package_for_module(module)
if (not descriptor.package):
descriptor.package = None
message_descriptors = []
enum_descriptors = []
for name in sorted(dir(module)):
value = getattr(module, name)
... | Build a file from a specified Python module.
Args:
module: Python module to describe.
Returns:
Initialized FileDescriptor instance describing the module. | codesearchnet |
def _translate_name(name):
underscored = inflection.underscore(name)
dasherized = inflection.dasherize(underscored)
words = dasherized.split('-')
last_word = words.pop()
words.append(inflection.pluralize(last_word))
return '-'.join(words) | Translate the class name to the API endpoint.
For example, Car would become cars, FastCar would become fast-cars.
Args:
name (string): Camel case name (singular)
Returns:
string: A pluraised, dasherized string. | juraj-google-style |
def intrusion_sets(self, name, owner=None, **kwargs):
return IntrusionSet(self.tcex, name, owner=owner, **kwargs) | Create the Intrustion Set TI object.
Args:
owner:
name:
**kwargs:
Return: | codesearchnet |
def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep + sep + token_ids_1... | Create a mask from the two sequences passed to be used in a sequence-pair classification task. MVP does not
make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`... | github-repos |
def _ReadSupportedOS(self, definition_values, definition_object, name):
supported_os = definition_values.get('supported_os', [])
if (not isinstance(supported_os, list)):
raise errors.FormatError('Invalid supported_os type: {0!s}'.format(type(supported_os)))
undefined_supported_os = set(supported_os)... | Reads the optional artifact or source type supported OS.
Args:
definition_values (dict[str, object]): artifact definition values.
definition_object (ArtifactDefinition|SourceType): the definition object.
name (str): name of the artifact definition.
Raises:
FormatError: if there are undefined supported operating syste... | codesearchnet |
def ddot(L, R, left=None, out=None):
r
L = asarray(L, float)
R = asarray(R, float)
if left is None:
ok = min(L.ndim, R.ndim) == 1 and max(L.ndim, R.ndim) == 2
if not ok:
msg = "Wrong array layout. One array should have"
msg += " ndim=1 and the other one ndim=2."
... | r"""Dot product of a matrix and a diagonal one.
Args:
L (array_like): Left matrix.
R (array_like): Right matrix.
out (:class:`numpy.ndarray`, optional): copy result to.
Returns:
:class:`numpy.ndarray`: Resulting matrix. | juraj-google-style |
def load_module_functions(module):
module_functions = {}
for (name, item) in vars(module).items():
if validator.is_function(item):
module_functions[name] = item
return module_functions | load python module functions.
Args:
module: python module
Returns:
dict: functions mapping for specified python module
{
"func1_name": func1,
"func2_name": func2
} | codesearchnet |
def ExpandGlobs(path, opts = None):
precondition.AssertType(path, Text)
if not path:
raise ValueError("Path is empty")
if not _IsAbsolutePath(path, opts):
raise ValueError("Path '%s' is not absolute" % path)
if opts is not None and opts.pathtype == rdf_paths.PathSpec.PathType.REGISTRY:
roo... | Performs glob expansion on a given path.
Path can contain regular glob elements (such as `**`, `*`, `?`, `[a-z]`). For
example, having files `foo`, `bar`, `baz` glob expansion of `ba?` will yield
`bar` and `baz`.
Args:
path: A path to expand.
opts: A `PathOpts` object.
Returns:
Generator over all possible glob expan... | juraj-google-style |
def create_sys_dsn(driver: str, **kw) -> bool:
attributes = []
for attr in kw.keys():
attributes.append("%s=%s" % (attr, kw[attr]))
return bool(
ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_SYS_DSN,
driver,
... | (Windows only.)
Create a system ODBC data source name (DSN).
Args:
driver: ODBC driver name
kw: Driver attributes
Returns:
bool: was the DSN created? | juraj-google-style |
def __call__(self, artist, genres, lyrics='', return_tensors='pt') -> BatchEncoding:
input_ids = [0, 0, 0]
artist = [artist] * len(self.version)
genres = [genres] * len(self.version)
artists_tokens, genres_tokens, lyrics_tokens = self.tokenize(artist, genres, lyrics)
artists_id, genres_ids, full_tok... | Convert the raw string to a list of token ids
Args:
artist (`str`):
Name of the artist.
genres (`str`):
List of genres that will be mixed to condition the audio
lyrics (`str`, *optional*, defaults to `""`):
Lyrics used to condition the generation | github-repos |
def get_license_from_url(url):
if (not url):
return
split_url = urlsplit(url, scheme='http')
if (split_url.netloc.lower() == 'creativecommons.org'):
if ('publicdomain' in split_url.path):
match = _RE_PUBLIC_DOMAIN_URL.match(split_url.path)
if (match is None):
... | Get the license abbreviation from an URL.
Args:
url(str): canonical url of the license.
Returns:
str: the corresponding license abbreviation.
Raises:
ValueError: when the url is not recognized | codesearchnet |
def load_default_traditional_chinese_parser() -> Parser:
with open(os.path.join(MODEL_DIR, 'zh-hant.json'), encoding='utf-8') as f:
model = json.load(f)
return Parser(model) | Loads a parser equipped with the default Traditional Chinese model.
Returns:
A parser (:obj:`budoux.Parser`). | github-repos |
def filter_segs(self, segs):
def whole_seg(seg):
m = self.seg_regex.match(seg)
if m and m.group(0) == seg:
return True
else:
return False
return list(filter(whole_seg, segs)) | Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definititions of bases and diacritics/modifiers known to the
object | juraj-google-style |
def snake_to_camel(name):
ret = ''.join((x.title() for x in name.split('_')))
ret = (ret[0].lower() + ret[1:])
return ret | Takes a snake_field_name and returns a camelCaseFieldName
Args:
name (str): E.g. snake_field_name or SNAKE_FIELD_NAME
Returns:
str: camelCase converted name. E.g. capsFieldName | codesearchnet |
def get_referenced_object_as_list(prev_obj, obj, dot_separated_name, desired_type=None):
res = get_referenced_object(prev_obj, obj, dot_separated_name, desired_type)
if (res is None):
return []
elif (type(res) is list):
return res
else:
return [res] | Same as get_referenced_object, but always returns a list.
Args:
prev_obj: see get_referenced_object
obj: see get_referenced_object
dot_separated_name: see get_referenced_object
desired_type: see get_referenced_object
Returns:
same as get_referenced_object, but always returns a list | codesearchnet |
def market_if_touched_replace(self, accountID, orderID, **kwargs):
return self.replace(
accountID,
orderID,
order=MarketIfTouchedOrderRequest(**kwargs)
) | Shortcut to replace a pending MarketIfTouched Order in an Account
Args:
accountID : The ID of the Account
orderID : The ID of the MarketIfTouched Order to replace
kwargs : The arguments to create a MarketIfTouchedOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request | juraj-google-style |
def split_instance_route(self, route: 'InstanceRoute') -> Optional[Tuple[('InstanceRoute', 'InstanceRoute')]]:
sroute = []
sn = self
while sn:
sroute.append(sn.iname())
sn = sn.data_parent()
i = 0
while True:
if (not sroute):
break
inst = sroute.pop()
... | Split `route` into the part up to receiver and the rest.
Args:
route: Absolute instance route (the receiver should correspond to an
instance node on this route).
Returns:
A tuple consisting of
- the part of `route` from the root up to and including the
instance whose schema node is the receiver, and
- the rest of `ro... | codesearchnet |
def build_frontend(self, frontend_node):
proxy_name = frontend_node.frontend_header.proxy_name.text
service_address_node = frontend_node.frontend_header.service_address
config_block_lines = self.__build_config_block(
frontend_node.config_block)
ho... | parse `frontend` sections, and return a config.Frontend
Args:
frontend_node (TreeNode): Description
Raises:
Exception: Description
Returns:
config.Frontend: an object | juraj-google-style |
def query(self, s):
s1 = np.sort([self.order[token] for token in s if token in self.order])
logging.debug("{} original tokens and {} tokens after applying "
"frequency order.".format(len(s), len(s1)))
prefix = self._get_prefix(s1)
candidates = set([i for p1, token in... | Query the search index for sets similar to the query set.
Args:
s (Iterable): the query set.
Returns (list): a list of tuples `(index, similarity)` where the index
is the index of the matching sets in the original list of sets. | juraj-google-style |
def __init__(self,
coupling_map,
initial_layout=None,
trials=20,
seed=None):
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.trials = trials
self.seed = seed... | Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
trials (int): the number of attempts the randomized algorithm makes.
seed (int): initial seed. | juraj-google-style |
def typecheck(fn):
is_compiled = False
if hasattr(fn, '__wrapped__'):
signature_fn = fn.__wrapped__
if hasattr(signature_fn, 'is_tp_compiled'):
is_compiled = getattr(signature_fn, 'is_tp_compiled')
else:
signature_fn = fn
signature = inspect.signature(signature_fn)
... | Annotation that check the arguments and outputs of a function at runtime.
@typecheck checks, at runtime, that the type hints of the arguments and output
of a function are satisfied.
Usage example:
```python
@typecheck
def f(a, b: int, c: str = "aze") -> List[str]:
return ["hello", "world"]
f(1, 2, "a") # Ok
f(1, 2, ... | github-repos |
def __call__(self, func):
if not hasattr(func, "parser"):
_LOG.debug("Creating parser for '%s'%s", func.__name__,
"/%s" % self._name if self._name else "")
(func_args, _, _, defaults) = getargspec(func)
self._types, func_args = _check_types(fun... | Add an argument parser attribute `parser` to the decorated function.
Args:
func: the function for which we want to create an argument parser | juraj-google-style |
def call(self, inputs, state):
_check_rnn_cell_input_dtypes([inputs, state])
sigmoid = math_ops.sigmoid
one = constant_op.constant(1, dtype=dtypes.int32)
if self._state_is_tuple:
c, h = state
else:
c, h = array_ops.split(value=state, num_or_size_splits=2, axis=one)
gate_inputs = ... | Long short-term memory cell (LSTM).
Args:
inputs: `2-D` tensor with shape `[batch_size, input_size]`.
state: An `LSTMStateTuple` of state tensors, each shaped `[batch_size,
num_units]`, if `state_is_tuple` has been set to `True`. Otherwise, a
`Tensor` shaped `[batch_size, 2 * num_units]`.
Returns:
A pair containing ... | github-repos |
def _num_image_tokens(image_size: Tuple[int, int], patch_size: Tuple[int, int]) -> int:
height, width = image_size
patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size)
num_width_tokens = (width - 1)
num_height_tokens = (height - 1)
return (n... | Calculate the number of image tokens given the image size and patch size.
Args:
image_size (`Tuple[int, int]`):
The size of the image as `(height, width)`.
patch_size (`Tuple[int, int]`):
The patch size as `(height, width)`.
Returns:
`int`: The number of image tokens. | github-repos |
def get_events_for_blocks(self, blocks, subscriptions):
events = []
for blkw in blocks:
events.extend(self.get_events_for_block(blkw, subscriptions))
return events | Get a list of events associated with all the blocks.
Args:
blocks (list of BlockWrapper): The blocks to search for events that
match each subscription.
subscriptions (list of EventSubscriptions): EventFilter and
event type to filter events.
Returns (list of Events): The Events associated which each block id.
Raises:... | juraj-google-style |
def _retrieve_endpoint(self, endpoint_id: str, location: str, is_private: bool) -> aiplatform.Endpoint:
if is_private:
endpoint: aiplatform.Endpoint = aiplatform.PrivateEndpoint(endpoint_name=endpoint_id, location=location)
LOGGER.debug('Treating endpoint %s as private', endpoint_id)
else:
... | Retrieves an AI Platform endpoint and queries it for liveness/deployed
models.
Args:
endpoint_id: the numerical ID of the Vertex AI endpoint to retrieve.
is_private: a boolean indicating if the Vertex AI endpoint is a private
endpoint
Returns:
An aiplatform.Endpoint object
Raises:
ValueError: if endpoint is inactive o... | github-repos |
def build_request_relationship(type, ids):
if (ids is None):
return {'data': None}
elif isinstance(ids, str):
return {'data': {'id': ids, 'type': type}}
else:
return {'data': [{'id': id, 'type': type} for id in ids]} | Build a relationship list.
A relationship list is used to update relationships between two
resources. Setting sensors on a label, for example, uses this
function to construct the list of sensor ids to pass to the Helium
API.
Args:
type(string): The resource type for the ids in the relationship
ids([uuid] or uuid): J... | codesearchnet |
def unbind(self, devices_to_unbind):
if self.entity_api_key == "":
return {'status': 'failure', 'response': 'No API key found in request'}
url = self.base_url + "api/0.1.0/subscribe/unbind"
headers = {"apikey": self.entity_api_key}
data = {
"exchange": "a... | This function allows an entity to unbound devices that are already bound.
Args:
devices_to_unbind (list): an array of devices that are to be unbound ( stop listening)
Example unbind(["test10","testDemo105"]) | juraj-google-style |
def _add_new_tf_operations(self, compute_devices=True) -> list['Operation']:
self._check_not_finalized()
new_ops = [self._create_op_from_tf_operation(c_op, compute_device=compute_devices) for c_op in self.new_operations()]
for op in new_ops:
new_control_inputs = self._control_dependencies_for_inputs... | Creates `Operations` in this graph for any new TF_Operations.
This is useful for when TF_Operations are indirectly created by the C API
outside of the Operation constructor (e.g. by TF_ImportGraphDef,
TF_FinishWhile). This ensures there are corresponding Operations for all
TF_Operations in the underlying TF_Graph.
Ar... | github-repos |
def get_coordinate_offset(self, other_reading):
my_x, my_y = self.reference_source_point
other_x, other_y = other_reading.reference_source_point
return my_x - other_x, my_y - other_y | Calculates the offsets between readings' coordinate systems.
Args:
other_reading: ossos.astrom.SourceReading
The reading to compare coordinate systems with.
Returns:
(offset_x, offset_y):
The x and y offsets between this reading and the other reading's
coordinate systems. | juraj-google-style |
def sparse_slice(sp_input, start, size, name=None):
sp_input = _convert_to_sparse_tensor(sp_input)
start = ops.convert_to_tensor(start, dtypes.int64)
size = ops.convert_to_tensor(size, dtypes.int64)
with ops.name_scope(name, 'SparseSlice', [sp_input]) as name:
output_indices, output_values, outp... | Slice a `SparseTensor` based on the `start` and `size`.
For example, if the input is
input_tensor = shape = [2, 7]
[ a d e ]
[b c ]
Graphically the output tensors are:
sparse.slice([0, 0], [2, 4]) = shape = [2, 4]
[ a ]
[b c ]
sparse.slice([0, 4], [2, 3]) = shape = [2, 3]
[ d e ]
[ ]
A... | github-repos |
def tan(x):
if any_symbolic_tensors((x,)):
return Tan().symbolic_call(x)
return backend.numpy.tan(x) | Compute tangent, element-wise.
Args:
x: Input tensor.
Returns:
Output tensor of same shape as `x`. | github-repos |
def get_msd_plot(self, plt=None, mode="specie"):
from pymatgen.util.plotting import pretty_plot
plt = pretty_plot(12, 8, plt=plt)
if np.max(self.dt) > 100000:
plot_dt = self.dt / 1000
unit = 'ps'
else:
plot_dt = self.dt
unit = 'fs'... | Get the plot of the smoothed msd vs time graph. Useful for
checking convergence. This can be written to an image file.
Args:
plt: A plot object. Defaults to None, which means one will be
generated.
mode (str): Determines type of msd plot. By "species", "sites",
or direction (default). If mode = "mscd", the smoothed ms... | juraj-google-style |
def mark_streamer(self, index):
self._logger.debug('Marking streamer %d manually', index)
if (index >= len(self.streamers)):
raise ArgumentError('Invalid streamer index', index=index, num_streamers=len(self.streamers))
self._manually_triggered_streamers.add(index) | Manually mark a streamer that should trigger.
The next time check_streamers is called, the given streamer will be
manually marked that it should trigger, which will cause it to trigger
unless it has no data.
Args:
index (int): The index of the streamer that we should mark as
manually triggered.
Raises:
ArgumentError... | codesearchnet |
def __init__(self, lower=True, num_norm=True,
use_char=True, initial_vocab=None):
self._num_norm = num_norm
self._use_char = use_char
self._word_vocab = Vocabulary(lower=lower)
self._char_vocab = Vocabulary(lower=False)
self._label_vocab = Vocabulary(low... | Create a preprocessor object.
Args:
lower: boolean. Whether to convert the texts to lowercase.
use_char: boolean. Whether to use char feature.
num_norm: boolean. Whether to normalize text.
initial_vocab: Iterable. Initial vocabulary for expanding word_vocab. | juraj-google-style |
def get_correct_answer(question, default=None, required=False,
answer=None, is_answer_correct=None):
u
while 1:
if default is None:
msg = u' - No Default Available'
else:
msg = (u'\n[DEFAULT] -> {}\nPress Enter To '
u'Use Default'... | u"""Ask user a question and confirm answer
Args:
question (str): Question to ask user
default (str): Default answer if no input from user
required (str): Require user to input answer
answer (str): Used for testing
is_answer_correct (str): Used for testing | juraj-google-style |
def _check_required_fields(self, object_type, ignore_fields):
for field in self.configuration[object_type]['required_fields']:
if field not in self.data and field not in ignore_fields:
raise HDXError('Field %s is missing in %s!' % (field, object_type)) | Helper method to check that metadata for HDX object is complete
Args:
ignore_fields (List[str]): Any fields to ignore in the check
Returns:
None | juraj-google-style |
def as_check_request(self, timer=datetime.utcnow):
if (not self.service_name):
raise ValueError(u'the service name must be set')
if (not self.operation_id):
raise ValueError(u'the operation id must be set')
if (not self.operation_name):
raise ValueError(u'the operation name must be s... | Makes a `ServicecontrolServicesCheckRequest` from this instance
Returns:
a ``ServicecontrolServicesCheckRequest``
Raises:
ValueError: if the fields in this instance are insufficient to
to create a valid ``ServicecontrolServicesCheckRequest`` | codesearchnet |
def GetBalance(self, wallet, address, as_string=False):
addr = PromptUtils.parse_param(address, wallet)
if isinstance(addr, UInt160):
addr = addr.Data
sb = ScriptBuilder()
sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr])
(tx, fee, results, num_ops, engine_success) = t... | Get the token balance.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
address (str): public address of the account to get the token balance of.
as_string (bool): whether the return value should be a string. Default is False, returning an integer.
Returns:
int/str: token balance value as int (default), token ba... | codesearchnet |
def save_project_id(project_id):
try:
subprocess.call(['gcloud', 'config', 'set', 'project', project_id])
except:
config_file = os.path.join(get_config_dir(), 'config.json')
config = {}
if os.path.exists(config_file):
with open(config_file) as f:
confi... | Save project id to config file.
Args:
project_id: the project_id to save. | codesearchnet |
def maybe_get_common_dtype(arg_list):
if all(((a is None) for a in arg_list)):
return None
return dtype_util.common_dtype(arg_list, tf.float32) | Return common dtype of arg_list, or None.
Args:
arg_list: an iterable of items which are either `None` or have a `dtype`
property.
Returns:
dtype: The common dtype of items in `arg_list`, or `None` if the list is
empty or all items are `None`. | codesearchnet |
def log_every_n(level, msg, n, *args):
count = _get_next_log_count_per_token(get_absl_logger().findCaller())
log_if(level, msg, (not (count % n)), *args) | Logs 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: int, the absl logging level at which to log.
msg: str, the message to be logged.
n: int, the number of times this should be called before it is logged.
*args: The args to be substi... | codesearchnet |
def create_host_call(model_dir):
graph = tf.get_default_graph()
summaries = graph.get_collection(tf.GraphKeys.SUMMARIES)
gs_t = tf.reshape(tf.to_int32(tf.train.get_global_step()), [1])
summary_kwargs = collections.OrderedDict()
for t in summaries:
if (t.op.type not in ['ScalarSummary']):
... | Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call. | codesearchnet |
def get_default_assets_zip_provider():
path = os.path.join(os.path.dirname(inspect.getfile(sys._getframe(1))), 'webfiles.zip')
if (not os.path.exists(path)):
logger.warning('webfiles.zip static assets not found: %s', path)
return None
return (lambda : open(path, 'rb')) | Opens stock TensorBoard web assets collection.
Returns:
Returns function that returns a newly opened file handle to zip file
containing static assets for stock TensorBoard, or None if webfiles.zip
could not be found. The value the callback returns must be closed. The
paths inside the zip file are considered absolute p... | codesearchnet |
def _get_newsfeeds(self, uri, detail_level = None):
if detail_level:
if detail_level not in ['ALL', 'CONDENSED']:
return requests.codes.bad_request, {'success' : 'False',
'error': 'detailLevel needs to be provided and field_type needs to be \'ALL\' or \'CONDENSED\''}
uri += self.detail_leve... | General purpose function to get newsfeeds
Args:
uri uri for the feed base
detail_level arguments for req str ['ALL', 'CONDENSED']
return list of feed dicts parse at your convenience | juraj-google-style |
def xarrayfunc(func):
@wraps(func)
def wrapper(*args, **kwargs):
if any(isinstance(arg, xr.DataArray) for arg in args):
newargs = []
for arg in args:
if isinstance(arg, xr.DataArray):
newargs.append(arg.values)
else:
... | Make a function compatible with xarray.DataArray.
This function is intended to be used as a decorator like::
>>> @dc.xarrayfunc
>>> def func(array):
... # do something
... return newarray
>>>
>>> result = func(array)
Args:
func (function): Function to be wrapped. The first argument
of the function must be an... | juraj-google-style |
def save(self, output_saved_model_dir, save_gpu_specific_engines=True, options=None):
assert self._converted
if trt_utils.is_experimental_feature_activated('remove_native_segments'):
logging.info("'remove_native_segments' experimental feature is enabled during saving of converted SavedModel.")
s... | Save the converted SavedModel.
Args:
output_saved_model_dir: directory to saved the converted SavedModel.
save_gpu_specific_engines: whether to save TRT engines that have been
built. When True, all engines are saved and when False, the engines
are not saved and will be rebuilt at inference time. By using
save_gpu_spec... | github-repos |
def _sendline(self, line):
logging.info('%s: sending line', self.port)
self._lines = []
try:
self._read()
except socket.error:
logging.debug('%s: Nothing cleared', self.port)
print 'sending [%s]' % line
self._write(line + '\r\n')... | Send exactly one line to the device
Args:
line str: data send to device | juraj-google-style |
def average(self, var):
return self._averages.get(var.ref(), None) | Returns the `Variable` holding the average of `var`.
Args:
var: A `Variable` object.
Returns:
A `Variable` object or `None` if the moving average of `var`
is not maintained. | github-repos |
def get_vasp_input(self, vasp_input_set=MPRelaxSet, **kwargs):
d = vasp_input_set(self.final_structure, **kwargs).get_vasp_input()
d["transformations.json"] = json.dumps(self.as_dict())
return d | Returns VASP input as a dict of vasp objects.
Args:
vasp_input_set (pymatgen.io.vaspio_set.VaspInputSet): input set
to create vasp input files from structures | juraj-google-style |
def _project_single_observable(self, **kwargs: Dict[(str, Any)]) -> Hist:
assert isinstance(self.output_attribute_name, str)
(output_hist, projection_name, projection_name_args) = self._project_observable(input_key='single_observable', input_observable=self.observable_to_project_from, **kwargs)
output_hist_... | Driver function for projecting and storing a single observable.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histogram. The histogram is also stored in the output specified by ``output_observable``. | codesearchnet |
def _new_convolution(self, use_bias):
def clean_dict(input_dict):
if input_dict and not use_bias:
cleaned_dict = input_dict.copy()
cleaned_dict.pop("b", None)
return cleaned_dict
return input_dict
return self._conv_class(
output_channels=4*self._output_channels,
... | Returns new convolution.
Args:
use_bias: Use bias in convolutions. If False, clean_dict removes bias
entries from initializers, partitioners and regularizers passed to
the constructor of the convolution. | juraj-google-style |
class BasicRNNCell(LayerRNNCell):
def __init__(self, num_units, activation=None, reuse=None, name=None, dtype=None, **kwargs):
warnings.warn('`tf.nn.rnn_cell.BasicRNNCell` is deprecated and will be removed in a future version. This class is equivalent as `tf.keras.layers.SimpleRNNCell`, and will be replace... | The most basic RNN cell.
Note that this cell is not optimized for performance. Please use
`tf.contrib.cudnn_rnn.CudnnRNNTanh` for better performance on GPU.
Args:
num_units: int, The number of units in the RNN cell.
activation: Nonlinearity to use. Default: `tanh`. It could also be string
that is within Keras activa... | github-repos |
def restore_captures(concrete_function, inputs):
bound_inputs = [get_tensor_from_node(obj) for obj in inputs]
bound_variables = [obj for obj in inputs if isinstance(obj, (variables_lib.Variable, resource_variable_ops.BaseResourceVariable))]
captured_inputs_list = []
concrete_function.set_variables(bound... | Restore captures for the concrete function.
Used at deserialization time. For functions that are being deserialized,
saved model restores objects that tensors were captured from, but functions
only know about their tensors -- object information is destroyed by tracing.
This additional logic extracts the tensors which... | github-repos |
def builder_from_source(source, filename, system_includes, nonsystem_includes, quiet=False):
return ASTBuilder(tokenize.get_tokens(source), filename, system_includes, nonsystem_includes, quiet=quiet) | Utility method that returns an ASTBuilder from source code.
Args:
source: 'C++ source code'
filename: 'file1'
Returns:
ASTBuilder | codesearchnet |
def __init__(self, on_ui_exit=None, config=None):
self._on_ui_exit = on_ui_exit
self._command_handler_registry = debugger_cli_common.CommandHandlerRegistry()
self._tab_completion_registry = debugger_cli_common.TabCompletionRegistry()
self._tab_completion_registry.register_tab_comp_context([''], self.CLI... | Constructor of the base class.
Args:
on_ui_exit: (`Callable`) the callback to be called when the UI exits.
config: An instance of `cli_config.CLIConfig()` carrying user-facing
configurations. | github-repos |
def random_set_distribution(
rnd: Optional[tcod.random.Random], dist: int
) -> None:
lib.TCOD_random_set_distribution(rnd.random_c if rnd else ffi.NULL, dist) | Change the distribution mode of a random number generator.
Args:
rnd (Optional[Random]): A Random instance, or None to use the default.
dist (int): The distribution mode to use. Should be DISTRIBUTION_*. | juraj-google-style |
def set_circular(self, circular: bool, chain: List[Table] = None) -> None:
self.circular = circular
self.circular_chain = chain or [] | Mark this table as circular (or not).
Args:
circular: is it circular?
chain: if it's circular, this should be the list of tables
participating in the circular chain | juraj-google-style |
def time_estimate(self, duration, **kwargs):
path = '%s/%s/time_estimate' % (self.manager.path, self.get_id())
data = {'duration': duration}
return self.manager.gitlab.http_post(path, post_data=data, **kwargs) | Set an estimated time of work for the object.
Args:
duration (str): Duration in human format (e.g. 3h30)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done | juraj-google-style |
def __init__(
self,
size,
weights=None,
bias=True,
l2_regularization=0.0,
l1_regularization=0.0,
trainable=True,
named_tensors=None,
scope='linear',
summary_labels=()
):
self.size = size
self.weights_init = weig... | Linear layer.
Args:
size: Layer size.
weights: Weight initialization, random if None.
bias: Bias initialization, random if True, no bias added if False.
l2_regularization: L2 regularization weight.
l1_regularization: L1 regularization weight. | juraj-google-style |
def get_typecast_value(self, value, type):
if (type == entities.Variable.Type.BOOLEAN):
return (value == 'true')
elif (type == entities.Variable.Type.INTEGER):
return int(value)
elif (type == entities.Variable.Type.DOUBLE):
return float(value)
else:
return value | Helper method to determine actual value based on type of feature variable.
Args:
value: Value in string form as it was parsed from datafile.
type: Type denoting the feature flag type.
Return:
Value type-casted based on type of feature variable. | codesearchnet |
def batch_shape(self):
return tensor_shape.as_shape(self._batch_shape()) | Shape of a single sample from a single event index as a `TensorShape`.
May be partially defined or unknown.
The batch dimensions are indexes into independent, non-identical
parameterizations of this distribution.
Returns:
batch_shape: `TensorShape`, possibly unknown. | github-repos |
def _build_ragged_tensor_from_value_ranges(starts, limits, step, values):
if step is None:
step = 1
step = ops.convert_to_tensor(step, name='step')
if step.dtype.is_integer:
step = math_ops.cast(step, starts.dtype)
else:
raise TypeError('slice strides must be integers or None')
... | Returns a `RaggedTensor` containing the specified sequences of values.
Returns a RaggedTensor `output` where:
```python
output.shape[0] = starts.shape[0]
output[i] = values[starts[i]:limits[i]:step]
```
Requires that `starts.shape == limits.shape` and
`0 <= starts[i] <= limits[i] <= values.shape[0]`.
Args:
starts: ... | github-repos |
async def getProvStack(self, iden: str):
return self.cell.provstor.getProvStack(s_common.uhex(iden)) | Return the providence stack associated with the given iden.
Args:
iden (str): the iden from splice
Note: the iden appears on each splice entry as the 'prov' property | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.