code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def get_ignored_files(self):
return [os.path.join(self.path, p) for p in self.run('ls-files', '--ignored', '--exclude-standard', '--others').strip().split()] | Returns the list of files being ignored in this repository.
Note that file names, not directories, are returned.
So, we will get the following:
a/b.txt
a/c.txt
instead of just:
a/
Returns:
List[str] - list of ignored files. The paths are absolute. | codesearchnet |
def MakeZip(self, xar_file, output_file):
logging.info('Generating zip template file at %s', output_file)
with zipfile.ZipFile(output_file, mode='a') as zf:
build_yaml = io.BytesIO()
self.WriteBuildYaml(build_yaml)
build_yaml.seek(0)
zf.writestr('build.yaml', build_yaml.read()) | Add a zip to the end of the .xar containing build.yaml.
The build.yaml is already inside the .xar file, but we can't easily open
this on linux. To make repacking easier we add a zip to the end of the .xar
and add in the build.yaml. The repack step will then look at the build.yaml
and insert the config.yaml. We end up ... | codesearchnet |
def IsDecltype(clean_lines, linenum, column):
(text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
if start_col < 0:
return False
if Search(r'\bdecltype\s*$', text[0:start_col]):
return True
return False | Check if the token ending on (linenum, column) is decltype().
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is decltype() expression, False otherwise. | juraj-google-style |
def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP:
return Bsp(x, y, w, h) | Create a new BSP instance with the given rectangle.
Args:
x (int): Rectangle left coordinate.
y (int): Rectangle top coordinate.
w (int): Rectangle width.
h (int): Rectangle height.
Returns:
BSP: A new BSP instance.
.. deprecated:: 2.0
Call the :any:`BSP` class instead. | codesearchnet |
def addColumn(self, columnName, dtype, defaultValue):
model = self.tableView.model()
if model is not None:
model.addDataFrameColumn(columnName, dtype, defaultValue)
self.addColumnButton.setChecked(False) | Adds a column with the given parameters to the underlying model
This method is also a slot.
If no model is set, nothing happens.
Args:
columnName (str): The name of the new column.
dtype (numpy.dtype): The datatype of the new column.
defaultValue (object): Fill the column with this value. | juraj-google-style |
def send_put(self, mri, attribute_name, value):
path = attribute_name + ".value"
typ, value = convert_to_type_tuple_value(serialize_object(value))
if isinstance(typ, tuple):
_, typeid, fields = typ
value = Value(Type(fields, typeid), value)
t... | Abstract method to dispatch a Put to the server
Args:
mri (str): The mri of the Block
attribute_name (str): The name of the Attribute within the Block
value: The value to put | juraj-google-style |
def route(self, method, pattern):
def decorator(callback):
self._router.add(method, pattern, callback)
return callback
return decorator | Decorator to add route for a request with any HTTP method.
Arguments:
method (str): HTTP method name, e.g. GET, POST, etc.
pattern (str): Routing pattern the path must match.
Returns:
function: Decorator function to add route. | codesearchnet |
def get_service_state_object_id(subsystem: str, name: str, version: str) -> str:
return '{}:{}:{}'.format(subsystem, name, version) | Return service state data object key.
Args:
subsystem (str): Subsystem the service belongs to
name (str): Name of the Service
version (str): Version of the Service
Returns:
str, Key used to store the service state data object | codesearchnet |
def integer_key_convert(dictin, dropfailedkeys=False):
return key_value_convert(dictin, keyfn=int, dropfailedkeys=dropfailedkeys) | Convert keys of dictionary to integers
Args:
dictin (DictUpperBound): Input dictionary
dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False.
Returns:
Dict: Dictionary with keys converted to integers | codesearchnet |
def ParseCode(unformatted_source, filename='<unknown>'):
if not unformatted_source.endswith(os.linesep):
unformatted_source += os.linesep
try:
ast_tree = ast.parse(unformatted_source, filename)
ast.fix_missing_locations(ast_tree)
readline = StringIO(unformatted_source).readline
... | Parse a string of Python code into logical lines.
This provides an alternative entry point to YAPF.
Arguments:
unformatted_source: (unicode) The code to format.
filename: (unicode) The name of the file being reformatted.
Returns:
A list of LogicalLines.
Raises:
An exception is raised if there's an error during AST ... | github-repos |
def get_resources(minify=False):
all_resources = dict()
subclasses = (resource_base.ResourceBase.__subclasses__() + resource_definitions.ResourceAngular.__subclasses__())
for resource in subclasses:
obj = resource(minify)
all_resources[resource.RESOURCE_NAME] = dict(css=tuple(obj.resources_c... | Find all resources which subclass ResourceBase.
Keyword arguments:
minify -- select minified resources if available.
Returns:
Dictionary of available resources. Keys are resource names (part of the config variable names), values are dicts
with css and js keys, and tuples of resources as values. | codesearchnet |
def db_dict(c):
db_d = {}
c.execute('SELECT * FROM library_spectra')
db_d['library_spectra'] = [list(row) for row in c]
c.execute('SELECT * FROM library_spectra_meta')
db_d['library_spectra_meta'] = [list(row) for row in c]
c.execute('SELECT * FROM library_spectra_annotation')
db_d['library_... | Get a dictionary of the library spectra from a database
Example:
>>> from msp2db.db import get_connection
>>> conn = get_connection('sqlite', 'library.db')
>>> test_db_d = db_dict(conn.cursor())
If using a large database the resulting dictionary will be very large!
Args:
c (cursor): SQL database connection cursor
R... | codesearchnet |
def show(self, view: View, request: Request):
return view.render('welcome', {
'app': request.app().make('Application')
}) | Show the welcome page.
Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.
Returns:
masonite.view.View -- The Masonite view class. | juraj-google-style |
def _convert_values_and_partition(cls, values, row_partition, name):
if not isinstance(row_partition, RowPartition):
raise TypeError(f'Argument `row_partition` must be a RowPartition. Received {row_partition}.')
if isinstance(values, RaggedTensor):
if values._row_partition.dtype != row_partition... | Converts `values` and `partition` to Tensors.
If `values` is a `RaggedTensor`, then converts `values` and `partition`
to have compatible row-partitioning dtypes. In particular, if any of the
row partitioning tensors are `int64`, then all of the other row
partitioning tensors will be cast to `int64` (if auto_cast_part... | github-repos |
def wait_for_transform_job(self, job, poll=5):
desc = _wait_until((lambda : _transform_job_status(self.sagemaker_client, job)), poll)
self._check_job_status(job, desc, 'TransformJobStatus')
return desc | Wait for an Amazon SageMaker transform job to complete.
Args:
job (str): Name of the transform job to wait for.
poll (int): Polling interval in seconds (default: 5).
Returns:
(dict): Return value from the ``DescribeTransformJob`` API.
Raises:
ValueError: If the transform job fails. | codesearchnet |
def color(self, color):
self._data['color'] = color
request = self._base_request
request['color'] = color
return self._tc_requests.update(request, owner=self.owner) | Updates the security labels color.
Args:
color: | juraj-google-style |
def url(self, url):
if (url and url.endswith('/')):
url = url[:(- 1)]
self._url = url | Set API URL endpoint
Args:
url: the url of the API endpoint | codesearchnet |
def generate_version(max_major: int = 1, max_minor: int = 7,
max_patch: int = 15) -> str:
major = randint(0, max_major)
minor = randint(0, max_minor)
patch = randint(0, max_patch)
return '{:d}.{:d}.{:d}'.format(major, minor, patch) | Select a random version.
Args:
max_major (int, optional) maximum major version
max_minor (int, optional) maximum minor version
max_patch (int, optional) maximum patch version
Returns:
str, Version String | juraj-google-style |
def EnqueueBreakpointUpdate(self, breakpoint):
with self._transmission_thread_startup_lock:
if (self._transmission_thread is None):
self._transmission_thread = threading.Thread(target=self._TransmissionThreadProc)
self._transmission_thread.name = 'Cloud Debugger transmission thread'
... | Asynchronously updates the specified breakpoint on the backend.
This function returns immediately. The worker thread is actually doing
all the work. The worker thread is responsible to retry the transmission
in case of transient errors.
Args:
breakpoint: breakpoint in either final or non-final state. | codesearchnet |
def cmd_ssh(options):
import os
import subprocess
from os.path import expanduser
options.inst_state = "running"
(i_info, param_str) = gather_data(options)
(tar_inst, tar_idx) = determine_inst(i_info, param_str, options.command)
home_dir = expanduser("~")
if options.user is None:
... | Connect to the specified instance via ssh.
Finds instances that match the user specified args that are also
in the 'running' state. The target instance is determined, the
required connection information is retreived (IP, key and ssh
user-name), then an 'ssh' connection is made to the instance.
Args:
options (object)... | juraj-google-style |
def GetUserById(self, local_id):
user = self.rpc_helper.GetAccountInfoById(local_id)
return GitkitUser.FromApiResponse(user) | Gets user info by id.
Args:
local_id: string, the user id at Gitkit server.
Returns:
GitkitUser, containing the user info. | juraj-google-style |
def create_constructor_args(cls, proto_list: List[american_option_pb2.AmericanEquityOption], config: AmericanOptionConfig=None) -> Dict[str, Any]:
am_option_data = proto_utils.from_protos(proto_list, config)
res = {}
for key in am_option_data:
tensor_repr = proto_utils.tensor_repr(am_option_data[key... | Creates a dictionary to initialize AmericanEquityOption.
The output dictionary is such that the instruments can be initialized
as follows:
```
initializer = create_constructor_args(proto_list, config)
american_options = [AmericanEquityOption(**data)
for data in initializer.values()]
```
The keys of the output diction... | github-repos |
def is_initialised(self):
if (not self.lattice):
raise AttributeError('Running a simulation needs the lattice to be initialised')
if (not self.atoms):
raise AttributeError('Running a simulation needs the atoms to be initialised')
if ((not self.number_of_jumps) and (not self.for_time)):
... | Check whether the simulation has been initialised.
Args:
None
Returns:
None | codesearchnet |
def _set_all_lims(self, which, lim, d, scale, fontsize=None):
setattr(self.general, (which + 'lims'), lim)
setattr(self.general, ('d' + which), d)
setattr(self.general, (which + 'scale'), scale)
if (fontsize is not None):
setattr(self.general, (which + '_tick_label_fontsize'), fontsize)
retu... | Set limits and ticks for an axis for whole figure.
This will set axis limits and tick marks for the entire figure.
It can be overridden in the SinglePlot class.
Args:
which (str): The indicator of which part of the plots
to adjust. This currently handles `x` and `y`.
lim (len-2 list of floats): The limits for the axi... | codesearchnet |
def vflip(img):
if (not _is_pil_image(img)):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.transpose(Image.FLIP_TOP_BOTTOM) | Vertically flip the given PIL Image.
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Vertically flipped image. | codesearchnet |
def _resolve_credential(self, credential):
if self._credentials_found_in_instance:
return
elif self._credentials_found_in_envars():
return os.getenv(('PAN_' + credential.upper()))
else:
return self.storage.fetch_credential(credential=credential, profile=self.profile) | Resolve credential from envars or credentials store.
Args:
credential (str): Credential to resolve.
Returns:
str or None: Resolved credential or ``None``. | codesearchnet |
def _get_data_by_field(self, field_number):
if not self.is_data_loaded:
self._import_data()
if not 0 <= field_number < self._num_of_fields:
raise ValueError("Field number should be between 0-%d" % self._num_of_fields)
return self._data[field_number] | Return a data field by field number.
This is a useful method to get the values for fields that Ladybug
currently doesn't import by default. You can find list of fields by typing
EPWFields.fields
Args:
field_number: a value between 0 to 34 for different available epw fields.
Returns:
An annual Ladybug list | juraj-google-style |
def add_cohp_dict(self, cohp_dict, key_sort_func=None):
if key_sort_func:
keys = sorted(cohp_dict.keys(), key=key_sort_func)
else:
keys = cohp_dict.keys()
for label in keys:
self.add_cohp(label, cohp_dict[label]) | Adds a dictionary of COHPs with an optional sorting function
for the keys.
Args:
cohp_dict: dict of the form {label: Cohp}
key_sort_func: function used to sort the cohp_dict keys. | juraj-google-style |
def get_files_in_branch(profile, branch_sha):
tree_sha = get_commit_tree(profile, branch_sha)
files = get_files_in_tree(profile, tree_sha)
tree = [prepare(x) for x in files]
return tree | Get all files in a branch's tree.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
branch_sha
The SHA a branch's HEAD points to.
Returns:
A list of dicts containing info about each b... | juraj-google-style |
def __init__(self, url, conn=None, user=None, password=None, verify=True,
proxies=None):
if conn and (user or password):
raise InvalidArgumentsError("A connection and user/password may"
" not both be provided.")
elif conn:
... | Create a TAXII endpoint.
Args:
user (str): username for authentication (optional)
password (str): password for authentication (optional)
verify (bool): validate the entity credentials (default: True)
conn (_HTTPConnection): A connection to reuse (optional)
proxies (dict): key/value pair for http/https proxy settings.
... | juraj-google-style |
def DeserializeUnsignedWithoutType(self, reader):
self.Version = reader.ReadByte()
self.DeserializeExclusiveData(reader)
self.Attributes = reader.ReadSerializableArray('neo.Core.TX.TransactionAttribute.TransactionAttribute',
max=sel... | Deserialize object without reading transaction type data.
Args:
reader (neo.IO.BinaryReader): | juraj-google-style |
async def get_data(self, url):
logger.debug('making request to %r', url)
with aiohttp.ClientSession() as session:
async with session.get(url, headers=self.headers) as response:
body = json.loads((await response.read()).decode('utf-8'))
if response.sta... | Get data from the TMDb API via :py:func:`aiohttp.get`.
Notes:
Updates configuration (if required) on successful requests.
Arguments:
url (:py:class:`str`): The endpoint URL and params.
Returns:
:py:class:`dict`: The parsed JSON result. | juraj-google-style |
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:
r... | 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 | juraj-google-style |
def gen_permutations(self, index=0, args=None):
if args is None:
args = []
try:
name = self.layout_json_names[index]
display = self.layout_json_params.get(name, {}).get('display')
input_type = self.install_json_params().get(name, {}).get('type')
... | Iterate recursively over layout.json parameter names.
TODO: Add indicator values.
Args:
index (int, optional): The current index position in the layout names list.
args (list, optional): Defaults to None. The current list of args. | juraj-google-style |
def save_metadata(self, file_path):
data = self.metadata
with open(file_path, 'w') as out_file:
json.dump(data, out_file) | Saves a json file of the search result metadata.
Saves a json file of the search result metadata from :class:`api.results`.metadata.
Args:
file_path (str):
Path to the json file to save metadata to. | juraj-google-style |
def zero_add(previous_value, x, name=None, reuse=None):
with tf.variable_scope(name, default_name='zero_add', reuse=reuse):
gamma = tf.get_variable('gamma', (), initializer=tf.zeros_initializer())
return (previous_value + (gamma * x)) | Resnet connection with zero initialization.
Another type of resnet connection which returns previous_value + gamma * x.
gamma is a trainable scalar and initialized with zero. It is useful when a
module is plugged into a trained model and we want to make sure it matches the
original model's performance.
Args:
previous... | codesearchnet |
def window_partition(hidden_states, window_size):
batch_size, height, width, num_channels = hidden_states.shape
hidden_states = hidden_states.view(batch_size, height
windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
return windows | Returns the resized hidden states. The output shape should be `(batch_size * num_windows, window_size, window_size,
num_channels)`
Args:
hidden_states (`torch.FloatTensor` of shape `(batch_size, height, width, num_channels)`):
Input hidden states
window_size (`int`):
Window size | github-repos |
def get_random_url(ltd="com"):
url = [
"https:
RandomInputHelper.get_random_value(8, [string.ascii_lowercase]),
".",
ltd
]
return "".join(url) | Get a random url with the given ltd.
Args:
ltd (str): The ltd to use (e.g. com).
Returns:
str: The random url. | juraj-google-style |
def run_cell(self, cell):
globals = self.ipy_shell.user_global_ns
locals = self.ipy_shell.user_ns
globals.update({
"__ipy_scope__": None,
})
try:
with redirect_stdout(self.stdout):
self.run(cell, globals, locals)
except:
... | Run the Cell code using the IPython globals and locals
Args:
cell (str): Python code to be executed | juraj-google-style |
def _get_iam_rest_api_url_from_creds(rest_client, credentials):
res = rest_client.make_request(credentials[_IAMConstants.V2_REST_URL])
base = res['streams_self']
end = base.find('/instances')
return base[:end] + '/resources' | Retrieves the Streams REST API URL from the provided credentials using iam authentication.
Args:
rest_client (:py:class:`rest_primitives._IAMStreamsRestClient`): A client for making REST calls using IAM authentication
credentials (dict): A dict representation of the credentials.
Returns:
str: The remote Streams REST A... | juraj-google-style |
def union(self, second_iterable, selector=identity):
if self.closed():
raise ValueError('Attempt to call union() on a closed Queryable.')
if (not is_iterable(second_iterable)):
raise TypeError('Cannot compute union() with second_iterable of non-iterable {0}'.format(str(type(second_iterable))[7:(... | Returns those elements which are either in the source sequence or in
the second_iterable, or in both.
Note: This method uses deferred execution.
Args:
second_iterable: Elements from this sequence are returns if they
are not also in the source sequence.
selector: An optional single argument function which is used to
... | codesearchnet |
def guess_content_type_and_encoding(path):
for ext, content_type in _EXTENSION_TO_MIME_TYPE.items():
if path.endswith(ext):
return content_type
content_type, encoding = mimetypes.guess_type(path)
content_type = content_type or "application/binary"
return content_type, encoding | Guess the content type of a path, using ``mimetypes``.
Falls back to "application/binary" if no content type is found.
Args:
path (str): the path to guess the mimetype of
Returns:
str: the content type of the file | juraj-google-style |
def calibrate(self, fetch_names, num_runs, feed_dict_fn=None, input_map_fn=None):
assert self._converted
assert self._need_calibration
assert not self._calibration_data_collected
if feed_dict_fn and input_map_fn or (not feed_dict_fn and (not input_map_fn)):
raise ValueError('Should specify one a... | Run the calibration and return the calibrated GraphDef.
Args:
fetch_names: a list of output tensor name to fetch during calibration.
num_runs: number of runs of the graph during calibration.
feed_dict_fn: a function that returns a dictionary mapping input names (as
strings) in the GraphDef to be calibrated to values (... | github-repos |
def copy_table(self, src, dst):
self.create_table_from(dst, src)
self.execute("INSERT INTO {dst} SELECT * FROM {src}"
.format(dst=dst, src=src))
self.commit() | Create a carbon copy of the source table.
Arguments:
src (str): The name of the table to copy.
dst (str): The name of the target duplicate table.
Raises:
sql.OperationalError: If source table does not exist. | juraj-google-style |
def schema(self) -> Schema:
return self._schema | Schema of the EventSetNode.
The schema defines the name and dtype of the features and the index.
Returns:
Schema of the EventSetNode. | github-repos |
def uid(uid):
if uid is None:
raise ValueError('UID cannot be None.')
def decorate(test_func):
@functools.wraps(test_func)
def wrapper(*args, **kwargs):
return test_func(*args, **kwargs)
setattr(wrapper, 'uid', uid)
return wrapper
return decorate | Decorator specifying the unique identifier (UID) of a test case.
The UID will be recorded in the test's record when executed by Mobly.
If you use any other decorator for the test method, you may want to use
this as the outer-most one.
Note a common UID system is the Universal Unitque Identifier (UUID), but
we are no... | github-repos |
def create_scheduler(self, num_training_steps: int, optimizer: torch.optim.Optimizer=None):
if self.lr_scheduler is None:
self.lr_scheduler = get_scheduler(self.args.lr_scheduler_type, optimizer=self.optimizer if optimizer is None else optimizer, num_warmup_steps=self.args.get_warmup_steps(num_training_step... | Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or
passed as an argument.
Args:
num_training_steps (int): The number of training steps to do. | github-repos |
def get(self, name):
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
return self._properties[name] | Get a device model property.
Args:
name (str): The name of the property to get | juraj-google-style |
def log_cdf(self, value, name='log_cdf'):
return self._call_log_cdf(value, name) | Log cumulative distribution function.
Given random variable `X`, the cumulative distribution function `cdf` is:
```none
log_cdf(x) := Log[ P[X <= x] ]
```
Often, a numerical approximation can be used for `log_cdf(x)` that yields
a more accurate answer than simply taking the logarithm of the `cdf` when
`x << -1`.
Ar... | github-repos |
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
with open(json_file_path, 'w', encoding='utf-8') as writer:
writer.write(self.to_json_string()) | Save this instance to a JSON file.
Args:
json_file_path (`str` or `os.PathLike`):
Path to the JSON file in which this feature_extractor instance's parameters will be saved. | github-repos |
def onTagAdd(self, name, func):
if '*' in name:
self.ontagaddglobs.add(name, func)
else:
self.ontagadds[name].append(func) | Register a callback for tag addition.
Args:
name (str): The name of the tag or tag glob.
func (function): The callback func(node, tagname, tagval). | juraj-google-style |
def get_clinvar_submission(store, institute_id, case_name, variant_id, submission_id):
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
pinned = [store.variant(variant_id) or variant_id for variant_id in
case_obj.get('suspects', [])]
variant_obj = store.va... | Collects all variants from the clinvar submission collection with a specific submission_id
Args:
store(scout.adapter.MongoAdapter)
institute_id(str): Institute ID
case_name(str): case ID
variant_id(str): variant._id
submission_id(str): clinvar submission id, i.e. SUB76578
Returns:
A dictionary with all the data to di... | juraj-google-style |
def _get_name_and_module(full_name):
name_segments = full_name.split('.')
return ('.'.join(name_segments[:-1]), name_segments[-1]) | Split full_name into module and short name.
Args:
full_name: Full name of symbol that includes module.
Returns:
Full module name and short symbol name. | github-repos |
def list(cls, session, mailbox):
endpoint = '/mailboxes/%d/conversations.json' % mailbox.id
return super(Conversations, cls).list(session, endpoint) | Return conversations in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox to list.
Returns:
RequestPaginator(output_type=helpscout.models.Conversation):
Conversations iterator. | juraj-google-style |
def put(self, filename, encoding=None):
from . import LocalFile
if os.path.isdir(filename) and self.source is None:
raise ValueError("Cannot write this object to "
"directory %s without an explicit filename." % filename)
target = get_target_pat... | Write the file to the given path
Args:
filename (str): path to write this file to
encoding (str): file encoding (default: system default)
Returns:
LocalFile: reference to the copy of the file stored at ``filename`` | juraj-google-style |
def print_colored_columns(printer, rows, padding=2):
rows_ = [x[:-1] for x in rows]
colors = [x[-1] for x in rows]
for col, line in zip(colors, columnise(rows_, padding=padding)):
printer(line, col) | Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring. | juraj-google-style |
def bit_to_int(x_bit, num_bits, base=2):
x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits])))
x_labels = [
x_l[:, i] * tf.to_int32(base)**tf.to_int32(i) for i in range(num_bits)]
res = sum(x_labels)
return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1])) | Turn x_bit representing numbers bitwise (lower-endian) to int tensor.
Args:
x_bit: Tensor containing numbers in a particular base to be converted to
int.
num_bits: Number of bits in the representation.
base: Base of the representation.
Returns:
Integer representation of this number. | juraj-google-style |
def merge(self, obj):
if obj.id in self.cache:
self.cache[obj.id].merge(obj)
else:
self.cache[obj.id] = obj
return self.cache[obj.id] | Add a given object to the cache, or update an existing entry to include more fields.
Args:
obj (SkypeObj): object to add to the cache | juraj-google-style |
def GetFileEntryByPathSpec(self, path_spec):
tsk_file = None
inode = getattr(path_spec, 'inode', None)
location = getattr(path_spec, 'location', None)
root_inode = self.GetRootInode()
if (location == self.LOCATION_ROOT or
(inode is not None and root_inode is not None and inode == ... | Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
TSKFileEntry: a file entry or None if not available. | juraj-google-style |
def supply(self, issuer):
issuer_uri_config = self._issuer_uri_configs.get(issuer)
if not issuer_uri_config:
return
jwks_uri = issuer_uri_config.jwks_uri
if jwks_uri:
return jwks_uri
open_id_valid = i... | Supplies the `jwks_uri` for the given issuer.
Args:
issuer: the issuer.
Returns:
The `jwks_uri` that is either statically configured or retrieved via
OpenId discovery. None is returned when the issuer is unknown or the
OpenId discovery fails. | juraj-google-style |
def cancelTickByTickData(self, contract: Contract, tickType: str):
ticker = self.ticker(contract)
reqId = self.wrapper.endTicker(ticker, tickType)
if reqId:
self.client.cancelTickByTickData(reqId)
else:
self._logger.error(
f'cancelMktData:... | Unsubscribe from tick-by-tick data
Args:
contract: The exact contract object that was used to
subscribe with. | juraj-google-style |
def convertData(self, contents, def_buf, kwh_scale=ScaleKWH.EmptyScale):
log_str = ""
count = 0
if kwh_scale == ScaleKWH.EmptyScale:
scale_offset = int(def_buf.keys().index(Field.kWh_Scale))
self.m_kwh_precision = kwh_scale = i... | Move data from raw tuple into scaled and conveted values.
Args:
contents (tuple): Breakout of passed block from unpackStruct().
def_buf (): Read buffer destination.
kwh_scale (int): :class:`~ekmmeters.ScaleKWH` as int, from Field.kWhScale`
Returns:
bool: True on completion. | juraj-google-style |
def _setup_mock_socket_file(mock_socket_create_conn, resp):
fake_file = mock.Mock()
fake_file.readline.side_effect = resp
fake_conn = mock.Mock()
fake_conn.makefile.return_value = fake_file
mock_socket_create_conn.return_value = fake_conn
return fake_file | Sets up a mock socket file from the mock connection.
Args:
mock_socket_create_conn: The mock method for creating a socket connection.
resp: iterable, the side effect of the `readline` function of the mock
socket file.
Returns:
The mock socket file that will be injected into the code. | github-repos |
def get_paginated_catalog_courses(self, catalog_id, querystring=None):
return self._load_data(self.CATALOGS_COURSES_ENDPOINT.format(catalog_id), default=[], querystring=querystring, traverse_pagination=False, many=False) | Return paginated response for all catalog courses.
Returns:
dict: API response with links to next and previous pages. | codesearchnet |
def price(
self,
instrument,
**kwargs
):
request = Request(
'GET',
'/v3/instruments/{instrument}/price'
)
request.set_path_param(
'instrument',
instrument
)
request.set_param(
'tim... | Fetch a price for an instrument. Accounts are not associated in any way
with this endpoint.
Args:
instrument:
Name of the Instrument
time:
The time at which the desired price is in effect. The current
price is returned if no time is provided.
Returns:
v20.response.Response containing the results from submitting the
r... | juraj-google-style |
def peek(self, iroute: 'InstanceRoute') -> Optional[Value]:
val = self.value
sn = self.schema_node
for sel in iroute:
(val, sn) = sel.peek_step(val, sn)
if (val is None):
return None
return val | Return a value within the receiver's subtree.
Args:
iroute: Instance route (relative to the receiver). | codesearchnet |
def add_payload(self, key, val, append=True):
if append:
self._params.setdefault(key, []).append(val)
else:
self._params[key] = val | Add a key value pair to payload for this request.
.. Note:: For ``_search`` you can pass a search argument. (e.g. _search?summary=1.1.1.1).
Args:
key (string): The payload key
val (string): The payload value
append (bool): Indicates whether the value should be appended or overwritten. | juraj-google-style |
def segments(seg_type=None):
for index in xrange(idaapi.get_segm_qty()):
seg = Segment(index=index)
if (seg_type is None) or (seg.type == seg_type):
yield Segment(index=index) | Iterate segments based on type
Args:
seg_type: type of segment e.g. SEG_CODE
Returns:
iterator of `Segment` objects. if seg_type is None , returns all segments
otherwise returns only the relevant ones | juraj-google-style |
def _placement_points_generator(self, skyline, width):
skyline_r = skyline[-1].right
skyline_l = skyline[0].left
ppointsl = (s.left for s in skyline if s.left+width <= skyline_r)
ppointsr = (s.right-width for s in skyline if s.right-width >= skyline_l)
... | Returns a generator for the x coordinates of all the placement
points on the skyline for a given rectangle.
WARNING: In some cases could be duplicated points, but it is faster
to compute them twice than to remove them.
Arguments:
skyline (list): Skyline HSegment list
width (int, float): Rectangle width
Returns:
gene... | juraj-google-style |
def getTraitCovar(self, term_i=None):
assert term_i < self.n_randEffs, 'VarianceDecomposition:: specied term out of range'
if term_i is None:
RV = sp.zeros((self.P,self.P))
for term_i in range(self.n_randEffs):
RV += self.getTraitCovarFun().K()
e... | Return the estimated trait covariance matrix for term_i (or the total if term_i is None)
To retrieve the matrix of correlation coefficient use \see getTraitCorrCoef
Args:
term_i: index of the random effect term we want to retrieve the covariance matrix
Returns:
estimated trait covariance | juraj-google-style |
def get_repo_config(self, repo='default'):
for repo_config in self.repositories:
if repo_config.name == repo or repo_config.url in RepositoryURL(repo):
return repo_config
return None | Retrieve configuration for a given repository.
Args:
repo (str): a repository "realm" (alias) or its URL
Returns:
RepositoryConfig: if there is configuration for that repository
None: otherwise | juraj-google-style |
def to_dict(ramons, flatten=False):
if type(ramons) is not list:
ramons = [ramons]
out_ramons = {}
for r in ramons:
out_ramons[r.id] = {
"id": r.id,
"type": _reverse_ramon_types[type(r)],
"metadata": vars(r)
}
return out_ramons | Converts a RAMON object list to a JSON-style dictionary. Useful for going
from an array of RAMONs to a dictionary, indexed by ID.
Arguments:
ramons (RAMON[]): A list of RAMON objects
flatten (boolean: False): Not implemented
Returns:
dict: A python dictionary of RAMON objects. | juraj-google-style |
def add(self, predicted, target):
predicted = predicted.cpu().numpy()
target = target.cpu().numpy()
assert (predicted.shape[0] == target.shape[0]), 'number of targets and predicted outputs do not match'
if (np.ndim(predicted) != 1):
assert (predicted.shape[1] == self.k), 'number of predictions d... | Computes the confusion matrix of K x K size where K is no of classes
Args:
predicted (tensor): Can be an N x K tensor of predicted scores obtained from
the model for N examples and K classes or an N-tensor of
integer values between 0 and K-1.
target (tensor): Can be a N-tensor of integer values assumed to be integer
v... | codesearchnet |
def get_attribute(self, main_type, sub_type, unique_id, attribute_id, owner=None, params=None):
return self.attribute(
main_type, sub_type, unique_id, attribute_id, action='GET', owner=owner, params=params
) | Args:
owner:
main_type:
sub_type:
unique_id:
attribute_id:
params:
Return: | juraj-google-style |
def update_panel(store, panel_name, csv_lines, option):
new_genes = []
panel_obj = store.gene_panel(panel_name)
if (panel_obj is None):
return None
try:
new_genes = parse_genes(csv_lines)
except SyntaxError as error:
flash(error.args[0], 'danger')
return None
if (... | Update an existing gene panel with genes.
Args:
store(scout.adapter.MongoAdapter)
panel_name(str)
csv_lines(iterable(str)): Stream with genes
option(str): 'add' or 'replace'
Returns:
panel_obj(dict) | codesearchnet |
def add_group_member(self, grp_name, user):
self.project_service.set_auth(self._token_project)
self.project_service.add_group_member(grp_name, user) | Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user_name (string): User to add to group.
Raises:
requests.HTTPError on failure. | juraj-google-style |
def execute(self, command, data={}):
(method, uri) = command
try:
path = self._formatter.format_map(uri, data)
body = self._formatter.get_unused_kwargs()
url = '{0}{1}'.format(self._url, path)
return self._request(method, url, body)
except KeyError as err:
LOGGER.debu... | Format the endpoint url by data and then request the remote server.
Args:
command(Command): WebDriver command to be executed.
data(dict): Data fulfill the uri template and json body.
Returns:
A dict represent the json body from server response.
Raises:
KeyError: Data cannot fulfill the variable which command needed.... | codesearchnet |
def __contains__(self, item):
if self is item:
return True
elif self.package is item and self.name == '__init__':
return True
return False | Whether given item is contained inside this module.
Args:
item (Package/Module): a package or module.
Returns:
bool:
True if self is item or item is self's package and
self if an ``__init__`` module. | juraj-google-style |
def reduce_and_verify(self, inputs, expect, options):
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = options.prefer_unique_instance_key
collective, devices, pid = self.make_collective(options.num_processes, options.gpus_per_process)
def reduce_fn():
v... | Reduce the given `inputs` and verify the output matches `expect`.
Args:
inputs: a list of `Tensor` or `IndexedSlices`, where i-th value will be
fed to i-th replica.
expect: a `Tensor` or `IndexedSlices`. This should be the expected value
for one replica.
options: a `RunOpotions` instance. | github-repos |
def shift(self, time: int) -> 'Interval':
return Interval((self._begin + time), (self._end + time)) | Return a new interval shifted by `time` from self
Args:
time: time to be shifted
Returns:
Interval: interval shifted by `time` | codesearchnet |
def _create_grad_func(ys, xs, grads, cond_graph, body_graph, name, while_op, maximum_iterations):
assert len(ys) == len(grads)
total_iters = while_op.outputs[0]
counter = constant_op.constant(0, dtype=total_iters.dtype, name='grad_counter')
body_graph_inputs = object_identity.ObjectIdentitySet(body_grap... | Builds and returns the gradient FuncGraph of `func_graph` and its args.
The returned grad_func_graph must be called with the returned
args + grad_func_graph.captures.
Args:
ys: A `Tensor` or list of tensors to be differentiated.
xs: A `Tensor` or list of tensors to be used for differentiation.
grads: The incoming gra... | github-repos |
def update(self, data):
if data.state['Name'] == 'terminated':
self.delete(auto_commit=False)
return True
updated = self.set_property('launch_date', to_utc_date(data.launch_time).isoformat())
updated |= self.set_property('state', data.state['Name'])
... | Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(instance)` on the object.
Args:
data (:obj:): AWS API Resource object fetched from AWS API
Returns... | juraj-google-style |
def create_seq(character, action_metadata, direction, length=8, start=0):
sprite_start = ((action_metadata[0] + direction) * FRAME_SIZE)
sprite_end = (((action_metadata[0] + direction) + 1) * FRAME_SIZE)
sprite_line = character[(sprite_start:sprite_end, ...)]
frames = tf.stack(tf.split(sprite_line, 13, ... | Creates a sequence.
Args:
character: A character sprite tensor.
action_metadata: An action metadata tuple.
direction: An integer representing the direction, i.e., the row
offset within each action group corresponding to a particular
direction.
length: Desired length of the sequence. If this is longer than
the number o... | codesearchnet |
def from_filename(filename, require=None):
with io.open(filename, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
return (data, from_dict(data, require=require)) | Reads a Google service account JSON file and returns its parsed info.
Args:
filename (str): The path to the service account .json file.
require (Sequence[str]): List of keys required to be present in the
info.
Returns:
Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified
info and a signer instance. | codesearchnet |
def get_nowait(self, name, default=_MISSING, autoremove=False):
self._ensure_declared(name)
try:
future = self._data[name]
if future.done():
return future.result()
if (default is _MISSING):
raise KeyError('Key {} has not been assigned a value and no default given'... | Get the value of a key if it is already set.
This method allows you to check if a key has already been set
without blocking. If the key has not been set you will get the
default value you pass in or KeyError() if no default is passed.
When this method returns the key is automatically removed unless
you pass ``autore... | codesearchnet |
def __init__(self, env):
self._env = env
self._observation_space = self._env.observation_space
self._action_space = self._env.action_space | Cache observation and action space to not recompute them repeatedly.
Args:
env: OpenAI Gym environment. | juraj-google-style |
def __init__(self, prefs, g, divPressureValues, kappa=2.0, omega=0.5,
beta=1.0, mu=1.0,omega2=0.0,
freeparams=['kappa', 'omega', 'beta', 'mu', 'omega2']):
_checkParam('omega2',omega2, self.PARAMLIMITS, self.PARAMTYPES)
self.omega2 = omega2
self.deltar = scipy.arr... | Initialize an `ExpCM_empirical_phi_divpressure` object.
Args:
`prefs`, `kappa`, `omega`, `beta`, `mu`, `g`, `freeparams`
Same meaning as for an `ExpCM_empirical_phi`
`divPressureValues`, `omega2`
Meaning described in the main class doc string. | juraj-google-style |
def unwrap(data_type):
unwrapped_nullable = False
unwrapped_alias = False
while is_alias(data_type) or is_nullable_type(data_type):
if is_nullable_type(data_type):
unwrapped_nullable = True
if is_alias(data_type):
unwrapped_alias = True
data_type = data_t... | Convenience method to unwrap all Aliases and Nullables from around a
DataType. This checks for nullable wrapping aliases, as well as aliases
wrapping nullables.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool, bool]: The underlying data type; a bool that is
set if a nullable was present... | juraj-google-style |
def add(self, command, *args):
cmd = Command(command, args)
self.commands.append(cmd) | Add a command to this command file.
Args:
command (str): The command to add
*args (str): The parameters to call the command with | codesearchnet |
def create(self, ip_dest, next_hop, **kwargs):
return self._set_route(ip_dest, next_hop, **kwargs) | Create a static route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
**kwargs['distance'] (string): Administrative distance for this
route
**kwargs... | codesearchnet |
def spawn(self, function, *args, **kwargs):
assert self.state != STOPPED, "Can't spawn when process stopped"
spawned = Spawned(function, args, kwargs)
self._spawned.append(spawned)
self._spawn_count += 1
if self._spawn_count > SPAWN_CLEAR_COUNT:
... | Runs the function in a worker thread, returning a Result object
Args:
function: Function to run
args: Positional arguments to run the function with
kwargs: Keyword arguments to run the function with
Returns:
Spawned: Something you can call wait(timeout) on to see when it's
finished executing | juraj-google-style |
def GetSizeHint(self, context=None, **unused_kwargs):
context_state = getattr(context, 'state', {})
elements_data_size = self.GetByteSize()
if elements_data_size:
return elements_data_size
try:
elements_data_size = self._CalculateElementsDataSize(context)
except errors.MappingErro... | Retrieves a hint about the size.
Args:
context (Optional[DataTypeMapContext]): data type map context, used to
determine the size hint.
Returns:
int: hint of the number of bytes needed from the byte stream or None. | juraj-google-style |
def course_blocks(self, course_id, username):
resp = self.requester.get(urljoin(self.base_url, '/api/courses/v1/blocks/'), params={'depth': 'all', 'username': username, 'course_id': course_id, 'requested_fields': 'children,display_name,id,type,visible_to_staff_only'})
resp.raise_for_status()
return Structur... | Fetches course blocks.
Args:
course_id (str): An edx course id.
username (str): username of the user to query for (can reveal hidden
modules)
Returns:
Structure | codesearchnet |
def tuplesorted(items, *keys):
tuple_keys = [Key(func=(lambda t, i=index, k=key: k.func(t[i])), reverse=key.reverse) for (index, key) in enumerate(keys)]
return multisorted(items, *tuple_keys) | Sort by tuples with a different key for each item.
Args:
items: An iterable series of sequences (typically tuples)
*keys: Key objects which transform individual elements of
each tuple into sort keys. The zeroth object
transforms the zeroth element of each tuple, the first
key object transforms the first element of ea... | codesearchnet |
def GetKeyByPath(self, key_path):
key_path_upper = key_path.upper()
if key_path_upper.startswith(self._key_path_prefix_upper):
relative_key_path = key_path[self._key_path_prefix_length:]
elif key_path.startswith(definitions.KEY_PATH_SEPARATOR):
relative_key_path = key_path
key_path = ... | Retrieves the key for a specific path.
Args:
key_path (str): Windows Registry key path.
Returns:
WinRegistryKey: Windows Registry key or None if not available. | juraj-google-style |
def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):
try:
return msg_types[msg_type.lower()](*args, **kwargs)
except (UnknownProfileError, InvalidMessageInputError) as e:
err_exit("Unable to send message: ", e)
except KeyError:
raise UnsupportedMessageTypeErr... | Factory function to return the specified message instance.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:msg_types: (str, list, or set) the supported message types
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.E... | juraj-google-style |
def getPixmap(page, matrix = None, colorspace = csRGB, clip = None,
alpha = True):
CheckParent(page)
cs = colorspace
if type(colorspace) is str:
if colorspace.upper() == "GRAY":
cs = csGRAY
elif colorspace.upper() == "CMYK":
cs = csCMYK
... | Create pixmap of page.
Args:
matrix: Matrix for transformation (default: Identity).
colorspace: (str/Colorspace) rgb, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) include alpha channel | juraj-google-style |
def _log_effective_mass_data(data, is_spin_polarized, mass_type='m_e'):
s = (' ({})'.format(data['spin'].name) if is_spin_polarized else '')
band_str = 'band {}{}'.format((data['band_id'] + 1), s)
start_kpoint = data['start_kpoint']
end_kpoint = data['end_kpoint']
eff_mass = data['effective_mass']
... | Log data about the effective masses and their directions.
Args:
data (dict): The effective mass data. Formatted as a :obj:`dict` with
the keys:
'effective_mass' (:obj:`float`)
The effective mass in units of electron rest mass, :math:`m_0`.
'energies' (:obj:`numpy.ndarray`)
Band eigenvalues in eV.
'band_id' (:obj:`i... | codesearchnet |
def stations(self, station, limit=10):
query = {
'start': 1,
'S': station + '?',
'REQ0JourneyStopsB': limit
}
rsp = requests.get('http:
return parse_stations(rsp.text) | Find stations for given queries
Args:
station (str): search query
limit (int): limit number of results | juraj-google-style |
def generate_srt_from_sjson(sjson_subs):
output = ''
equal_len = len(sjson_subs['start']) == len(sjson_subs['end']) == len(sjson_subs['text'])
if not equal_len:
return output
for i in range(len(sjson_subs['start'])):
item = SubRipItem(
... | Generate transcripts from sjson to SubRip (*.srt).
Arguments:
sjson_subs (dict): `sjson` subs.
Returns:
Subtitles in SRT format. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.