code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def add_tree(self, tree, parent=None):
if tree.path in self.path_db:
self.remove_tree_by_path(tree.path)
for index in tree.indexes:
if not getattr(tree, index):
continue
self._add_to(
getattr(self, index + "_db"),
... | Add `tree` into database.
Args:
tree (obj): :class:`.Tree` instance.
parent (ref, default None): Reference to parent tree. This is used
for all sub-trees in recursive call. | juraj-google-style |
def _offset(value):
o = int(value)
if (o == 0):
return 0
a = abs(o)
s = ((a * 36) + ((a % 100) * 24))
return ((o | Parse timezone to offset in seconds.
Args:
value: A timezone in the '+0000' format. An integer would also work.
Returns:
The timezone offset from GMT in seconds as an integer. | codesearchnet |
def _BuildStations(self, stoplist):
stations = []
dists = self._EuclidianDistances(stoplist)
stations = self._CalculateYLines(dists)
return stations | Dispatches the best algorithm for calculating station line position.
Args:
# Class Stop is defined in transitfeed.py
stoplist: [Stop, Stop, ...]
# Class Trip is defined in transitfeed.py
triplist: [Trip, Trip, ...]
Returns:
# One integer y-coordinate for each station normalized between
# 0 and X, where X is the heigh... | codesearchnet |
def _FloatingPointEncoder(wire_type, format):
value_size = struct.calcsize(format)
if (value_size == 4):
def EncodeNonFiniteOrRaise(write, value):
if (value == _POS_INF):
write(b'\x00\x00\x80\x7f')
elif (value == _NEG_INF):
write(b'\x00\x00\x80\xf... | Return a constructor for an encoder for float fields.
This is like StructPackEncoder, but catches errors that may be due to
passing non-finite floating-point values to struct.pack, and makes a
second attempt to encode those values.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string... | codesearchnet |
def triggered(self, manual=False):
if (self.walker is None):
raise InternalError('You can only check if a streamer is triggered if you create it with a SensorLog')
if ((not self.automatic) and (not manual)):
return False
return self.has_data() | Check if this streamer should generate a report.
Streamers can be triggered automatically whenever they have data
or they can be triggered manually. This method returns True if the
streamer is currented triggered.
A streamer is triggered if it:
- (has data AND is automatic) OR
- (has data AND is manually triggered)
... | codesearchnet |
def mme_matches(case_obj, institute_obj, mme_base_url, mme_token):
data = {
'institute' : institute_obj,
'case' : case_obj,
'server_errors' : []
}
matches = {}
if not case_obj.get('mme_submission'):
return None
for patient in case_obj['mme_submission']['pat... | Show Matchmaker submission data for a sample and eventual matches.
Args:
case_obj(dict): a scout case object
institute_obj(dict): an institute object
mme_base_url(str) base url of the MME server
mme_token(str) auth token of the MME server
Returns:
data(dict): data to display in the html template | juraj-google-style |
def from_bytes_list(cls, function_descriptor_list):
assert isinstance(function_descriptor_list, list)
if (len(function_descriptor_list) == 0):
return FunctionDescriptor.for_driver_task()
elif ((len(function_descriptor_list) == 3) or (len(function_descriptor_list) == 4)):
module_name = ensure... | Create a FunctionDescriptor instance from list of bytes.
This function is used to create the function descriptor from
backend data.
Args:
cls: Current class which is required argument for classmethod.
function_descriptor_list: list of bytes to represent the
function descriptor.
Returns:
The FunctionDescriptor instan... | codesearchnet |
def _create_extractors(col_params):
result = []
for col_param in col_params:
result.append(_create_extractor(col_param))
return result | Creates extractors to extract properties corresponding to 'col_params'.
Args:
col_params: List of ListSessionGroupsRequest.ColParam protobufs.
Returns:
A list of extractor functions. The ith element in the
returned list extracts the column corresponding to the ith element of
_request.col_params | codesearchnet |
def console(discord_token, discord_client_id):
state, response = datatools.get_compare_version()
logger.info("Starting Modis in console")
logger.info(response)
import threading
import asyncio
logger.debug("Loading packages")
from modis.discord_modis import main as discord_modis_cons... | Start Modis in console format.
Args:
discord_token (str): The bot token for your Discord application
discord_client_id: The bot's client ID | juraj-google-style |
def any_soco():
cls = config.SOCO_CLASS
try:
device = next((d for d in cls._instances[cls._class_group].values() if d.is_visible))
except (KeyError, StopIteration):
devices = discover()
return (None if (devices is None) else devices.pop())
return device | Return any visible soco device, for when it doesn't matter which.
Try to obtain an existing instance, or use `discover` if necessary.
Note that this assumes that the existing instance has not left
the network.
Returns:
SoCo: A `SoCo` instance (or subclass if `config.SOCO_CLASS` is set,
or `None` if no instances are f... | codesearchnet |
def detect(self, text):
t = text.encode("utf-8")
reliable, index, top_3_choices = cld2.detect(t, bestEffort=False)
if not reliable:
self.reliable = False
reliable, index, top_3_choices = cld2.detect(t, bestEffort=True)
if not self.quiet:
if not reliable:
rais... | Decide which language is used to write the text.
The method tries first to detect the language with high reliability. If
that is not possible, the method switches to best effort strategy.
Args:
text (string): A snippet of text, the longer it is the more reliable we
can detect the language used to write the text. | juraj-google-style |
def reach_max_num(self):
if self.signal.get('reach_max_num'):
return True
if ((self.max_num > 0) and (self.fetched_num >= self.max_num)):
return True
else:
return False | Check if downloaded images reached max num.
Returns:
bool: if downloaded images reached max num. | codesearchnet |
def file_exists(file_path, credentials=None):
if file_path.startswith('gs:
return _file_exists_in_gcs(file_path, credentials)
else:
return os.path.isfile(file_path) | Check whether the file exists, on local disk or GCS.
Args:
file_path: The target file path; should have the 'gs://' prefix if in gcs.
credentials: Optional credential to be used to load the file from gcs.
Returns:
True if the file's there. | juraj-google-style |
def get_file(self, filename, scope='all'):
filename = os.path.abspath(os.path.join(self.root, filename))
layouts = self._get_layouts_in_scope(scope)
for ly in layouts:
if filename in ly.files:
return ly.files[filename]
return None | Returns the BIDSFile object with the specified path.
Args:
filename (str): The path of the file to retrieve. Must be either
an absolute path, or relative to the root of this BIDSLayout.
scope (str, list): Scope of the search space. If passed, only
BIDSLayouts that match the specified scope will be
searched. See BIDSLa... | juraj-google-style |
def _StartMonitoringProcess(self, process):
if process is None:
raise ValueError('Missing process.')
pid = process.pid
if pid in self._process_information_per_pid:
raise KeyError(
'Already monitoring process (PID: {0:d}).'.format(pid))
if pid in self._rpc_clients_per_pid:
... | Starts monitoring a process.
Args:
process (MultiProcessBaseProcess): process.
Raises:
IOError: if the RPC client cannot connect to the server.
KeyError: if the process is not registered with the engine or
if the process is already being monitored.
OSError: if the RPC client cannot connect to the server.
ValueError: ... | juraj-google-style |
def get_fastq_dxfile_objects(self,barcode=None):
fq_ext_glob = "*{}".format(self.FQEXT)
name = fq_ext_glob
if barcode:
name = "*_{barcode}_*{FQEXT}".format(barcode=barcode, FQEXT=self.FQEXT)
fastqs= dxpy.find_data_objects(project=self.dx_project_id,folder=self.DX_FAS... | Retrieves all the FASTQ files in project self.dx_project_name as DXFile objects.
Args:
barcode: `str`. If set, then only FASTQ file properties for FASTQ files having the specified barcode are returned.
Returns:
`list` of DXFile objects representing FASTQ files.
Raises:
`dnanexus_utils.FastqNotFound`: No FASTQ files ... | juraj-google-style |
def sanity_check_tensor_sync(tensor: torch.Tensor, mesh: DeviceMesh, rtol: float=0.0001, atol: float=0.0001, not_sync: bool=False) -> None:
if not dist.is_initialized() or mesh.size() == 1:
return
pg = mesh.get_group()
if hasattr(tensor, 'to_local'):
local_tensor = tensor.to_local()
else... | Verify that a tensor is synchronized (or not synchronized) across all processes in the mesh's process group.
Handles both regular tensors and DTensors.
Args:
tensor (torch.Tensor): The tensor to check for synchronization (can be DTensor)
mesh (DeviceMesh): The device mesh containing the process group
rtol (float): Rel... | github-repos |
def plot(self, data):
import IPython
if (((sys.version_info.major > 2) and isinstance(data, str)) or ((sys.version_info.major <= 2) and isinstance(data, basestring))):
data = bq.Query(data)
if isinstance(data, bq.Query):
df = data.execute().result().to_dataframe()
data = self._get_la... | Plots a featire slice view on given data.
Args:
data: Can be one of:
A string of sql query.
A sql query module defined by "%%sql --module module_name".
A pandas DataFrame.
Regardless of data type, it must include the following columns:
"feature": identifies a slice of features. For example: "petal_length:4.0-4.2".
"co... | codesearchnet |
def repay_funding(self, amount, currency):
params = {
'amount': amount,
'currency': currency
}
return self._send_message('post', '/funding/repay',
data=json.dumps(params)) | Repay funding. Repays the older funding records first.
Args:
amount (int): Amount of currency to repay
currency (str): The currency, example USD
Returns:
Not specified by cbpro. | juraj-google-style |
def get_by_addr(self, address):
addr = address
if isinstance(address, str) and len(address) == 34:
addr = Helper.AddrStrToScriptHash(address)
if not isinstance(addr, UInt160):
raise Exception("Incorrect address format")
addrlist_snapshot = self.db.prefi... | Lookup a set of notifications by address
Args:
address (UInt160 or str): hash of address for notifications
Returns:
list: a list of notifications | juraj-google-style |
def sparse_grid(func, order, dim=None, skew=None):
if not isinstance(order, int):
orders = numpy.array(order).flatten()
dim = orders.size
m_order = int(numpy.min(orders))
skew = [order-m_order for order in orders]
return sparse_grid(func, m_order, dim, skew)
absciss... | Smolyak sparse grid constructor.
Args:
func (:py:data:typing.Callable):
Function that takes a single argument ``order`` of type
``numpy.ndarray`` and with ``order.shape = (dim,)``
order (int, numpy.ndarray):
The order of the grid. If ``numpy.ndarray``, it overrides both
``dim`` and ``skew``.
dim (int):
Number of dimen... | juraj-google-style |
def drift(data, n=3, **kwargs):
yi = data[(- n)]
yf = data[(- 1)]
slope = ((yf - yi) / (n - 1))
forecast = (yf + slope)
return forecast | The drift forecast for the next point is a linear extrapolation from the previous ``n``
points in the series.
Args:
data (np.array): Observed data, presumed to be ordered in time.
n (int): period over which to calculate linear model for extrapolation
Returns:
float: a single-valued forecast for the next value in the ... | codesearchnet |
def inspect(self, **kwargs):
what = kwargs.pop('what', 'hist')
if (what == 'hist'):
with self.open_hist() as hist:
return (hist.plot(**kwargs) if hist else None)
elif (what == 'scf'):
relaxation = abiinspect.Relaxation.from_file(self.output_file.path)
if ('title' not in k... | Plot the evolution of the structural relaxation with matplotlib.
Args:
what: Either "hist" or "scf". The first option (default) extracts data
from the HIST file and plot the evolution of the structural
parameters, forces, pressures and energies.
The second option, extracts data from the main output file and
plot the e... | codesearchnet |
def equal(x, y):
if PY_3:
return test_case().assertEqual(x, y) or True
assert x == y | Shortcut function for ``unittest.TestCase.assertEqual()``.
Arguments:
x (mixed)
y (mixed)
Raises:
AssertionError: in case of assertion error.
Returns:
bool | juraj-google-style |
def _SetValues(self, values):
def _ToStr(value):
'Convert individul list entries to string.'
if isinstance(value, (list, tuple)):
result = []
for val in value:
result.append(str(val))
return result
else:
return str(value)
i... | Set values from supplied dictionary or list.
Args:
values: A Row, dict indexed by column name, or list.
Raises:
TypeError: Argument is not a list or dict, or list is not equal row
length or dictionary keys don't match. | codesearchnet |
def set_ipv4_routing(self, vrf_name, default=False, disable=False):
cmd = ('ip routing vrf %s' % vrf_name)
if default:
cmd = ('default %s' % cmd)
elif disable:
cmd = ('no %s' % cmd)
cmd = make_iterable(cmd)
return self.configure(cmd) | Configures ipv4 routing for the vrf
Args:
vrf_name (str): The VRF name to configure
default (bool): Configures ipv4 routing for the vrf value to
default if this value is true
disable (bool): Negates the ipv4 routing for the vrf if set to true
Returns:
True if the operation was successful otherwise False | codesearchnet |
def get_raw(tree):
if isinstance(tree, Tree):
words = []
for child in tree:
words.append(get_raw(child))
return ' '.join(words)
else:
return tree | Get the exact words in lowercase in the tree object.
Args:
tree (Tree): Parsed tree structure
Returns:
Resulting string of tree ``(Ex: "The red car")`` | juraj-google-style |
def _GetMountpointBlacklist(xdev):
if xdev == rdf_file_finder.FileFinderArgs.XDev.NEVER:
return _GetMountpoints(only_physical=False)
if xdev == rdf_file_finder.FileFinderArgs.XDev.LOCAL:
physical = _GetMountpoints(only_physical=True)
return _GetMountpoints(only_physical=False) - physical
... | Builds a list of mountpoints to ignore during recursive searches.
Args:
xdev: A `XDev` value that determines policy for crossing device boundaries.
Returns:
A set of mountpoints to ignore.
Raises:
ValueError: If `xdev` value is invalid. | juraj-google-style |
def compile_state_action_constraints(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor]) -> List[TensorFluent]:
scope = self.transition_scope(state, action)
constraints = []
with self.graph.as_default():
with tf.name_scope('state_action_con... | Compiles the state-action constraints given current `state` and `action` fluents.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
action (Sequence[tf.Tensor]): The action fluents.
Returns:
A list of :obj:`rddl2tf.fluent.TensorFluent`. | juraj-google-style |
def cache_connect(database=None):
if (database is None):
database = cache_file()
if os.path.isfile(database):
conn = sqlite3.connect(database)
else:
conn = sqlite3.connect(database)
conn.executescript(schema)
with conn as cur:
cur.execute('PRAGMA foreign_keys = ON... | Returns a connection object to a sqlite database.
Args:
database (str, optional): The path to the database the user wishes
to connect to. If not specified, a default is chosen using
:func:`.cache_file`. If the special database name ':memory:'
is given, then a temporary database is created in memory.
Returns:
:class:`... | codesearchnet |
def videos(self, **kwargs):
path = self._get_id_path('videos')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the videos (trailers, teasers, clips, etc...) for a
specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API. | juraj-google-style |
def as_objective(obj):
if isinstance(obj, Objective):
return obj
elif callable(obj):
return obj
elif isinstance(obj, str):
(layer, n) = obj.split(':')
(layer, n) = (layer.strip(), int(n))
return channel(layer, n) | Convert obj into Objective class.
Strings of the form "layer:n" become the Objective channel(layer, n).
Objectives are returned unchanged.
Args:
obj: string or Objective.
Returns:
Objective | codesearchnet |
def get_max_size(pool, num_option, item_length):
max_items = (POOL_SIZE / item_length)
existing = ((POOL_OPTION_MIN_SIZE * num_option) + sum([max(0, (len(pool.get(i, {})) - 5)) for i in xrange(num_option)]))
return int((max_items - existing)) | Calculate the max number of item that an option can stored in the pool at give time.
This is to limit the pool size to POOL_SIZE
Args:
option_index (int): the index of the option to calculate the size for
pool (dict): answer pool
num_option (int): total number of options available for the question
item_length (int): ... | codesearchnet |
def similar_movies(self, **kwargs):
path = self._get_id_path('similar_movies')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the similar movies for a specific movie id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API. | juraj-google-style |
def _CreateFeedItems(client, feed_details, label_name):
feed_item_service = client.GetService('FeedItemService', version='v201809')
urls = ('http:
'http:
'http:
operations = [{
'operand': {
'feedId': feed_details.feed_id,
'attributeValues': [
... | Creates the page URLs in the DSA page feed.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
label_name: a str containing the page feed URL label. | juraj-google-style |
def init_properties(env='dev', app='unnecessary', **_):
aws_env = boto3.session.Session(profile_name=env)
s3client = aws_env.resource('s3')
generated = get_details(app=app, env=env)
archaius = generated.archaius()
archaius_file = '{path}/application.properties'.format(path=archaius['path'])
try:... | Make sure _application.properties_ file exists in S3.
For Applications with Archaius support, there needs to be a file where the
cloud environment variable points to.
Args:
env (str): Deployment environment/account, i.e. dev, stage, prod.
app (str): GitLab Project name.
Returns:
True when application.properties was ... | codesearchnet |
def make_sgf(
move_history,
result_string,
ruleset="Chinese",
komi=7.5,
white_name=PROGRAM_IDENTIFIER,
black_name=PROGRAM_IDENTIFIER,
comments=[]
):
boardsize = go.N
game_moves = ''.join(translate_sgf_move(*z)
for z in itertools.zip_longest(move_history,... | Turn a game into SGF.
Doesn't handle handicap games or positions with incomplete history.
Args:
move_history: iterable of PlayerMoves
result_string: "B+R", "W+0.5", etc.
comments: iterable of string/None. Will be zipped with move_history. | juraj-google-style |
def _encode_reference_type_constraints(self, builder: expressions.Builder, elem: message.Message) -> List[validation_pb2.SqlRequirement]:
field_name = _last_path_token(builder)
constraint_key = f'{field_name}-resource-type-exclusivity'
if constraint_key in self._options.skip_keys:
return []
elem... | Generates constraints for reference types.
Ensures that a reference type only has a value for one of the resourceId
columns across each of the possible resources the reference can link.
Args:
builder: The builder to the reference type for which to encode
constraints.
elem: Element definition of the builder.
Returns:... | github-repos |
def _value_set_from_url(self, url: str) -> Optional[value_set_pb2.ValueSet]:
url, version = url_utils.parse_url_version(url)
value_set = self._package_manager.get_resource(url)
if value_set is None:
logging.info('Unable to find value set for url: %s in given resolver packages.', url)
return ... | Retrieves the value set for the given URL.
The value set is assumed to be a member of one of the packages contained in
self._package_manager. This function will not attempt to look up resources
over the network in other locations.
Args:
url: The url of the value set to retrieve.
Returns:
The value set for the given ... | github-repos |
def translate_sites(self, indices, vector, frac_coords=True,
to_unit_cell=True):
if not isinstance(indices, collections.abc.Iterable):
indices = [indices]
for i in indices:
site = self._sites[i]
if frac_coords:
fcoords... | Translate specific sites by some vector, keeping the sites within the
unit cell.
Args:
indices: Integer or List of site indices on which to perform the
translation.
vector: Translation vector for sites.
frac_coords (bool): Whether the vector corresponds to fractional or
cartesian coordinates.
to_unit_cell (bool): Whet... | juraj-google-style |
def stft_magnitude(signal, fft_length, hop_length=None, window_length=None):
frames = frame(signal, window_length, hop_length)
window = periodic_hann(window_length)
windowed_frames = (frames * window)
return np.abs(np.fft.rfft(windowed_frames, int(fft_length))) | Calculate the short-time Fourier transform magnitude.
Args:
signal: 1D np.array of the input time-domain signal.
fft_length: Size of the FFT to apply.
hop_length: Advance (in samples) between each frame passed to FFT.
window_length: Length of each block of samples to pass to FFT.
Returns:
2D np.array where each row c... | codesearchnet |
def __init__(self, plist_filename):
self.filename = plist_filename
with open(self.filename, 'r') as plist_file:
self.soup = BeautifulSoup(plist_file, 'lxml-xml')
self.properties = self.soup.findChild(name='dict')
if self.properties is None:
... | Initialize a property list representation from an existing file.
Args:
plist_filename: A string containing the full path to a
Doxygen-generated property list file.
Raises:
OSError / FileNotFoundError: Input file cannot be read
RuntimeError: The property list file is not of the expected format | juraj-google-style |
def check_cell_type(cell, cell_type):
if ((cell_type == None) or (cell_type == type(None))):
return ((cell == None) or (isinstance(cell, basestring) and (not cell)))
else:
return isinstance(cell, cell_type) | Checks the cell type to see if it represents the cell_type passed in.
Args:
cell_type: The type id for a cell match or None for empty match. | codesearchnet |
def profile_settings_args_layout_json(self, required):
profile_args = {}
self.db_create_table(self.input_table, self.install_json_params().keys())
self.db_insert_record(self.input_table, self.install_json_params().keys())
self.gen_permutations()
try:
for pn ... | Return args based on layout.json and conditional rendering.
Args:
required (bool): If True only required args will be returned.
Returns:
dict: Dictionary of required or optional App args. | juraj-google-style |
def _bash_comp_command(self, cmd, add_help=True):
out = (['-h', '--help'] if add_help else [])
cmd_dict = (self._opt_cmds[cmd] if cmd else self._opt_bare)
for (opt, sct) in cmd_dict:
out.extend(_names(self._conf[sct], opt))
return out | Build a list of all options for a given command.
Args:
cmd (str): command name, set to None or '' for bare command.
add_help (bool): add an help option.
Returns:
list of str: list of CLI options strings. | codesearchnet |
def body(self, body):
if isinstance(body, bytes):
body = body.decode('utf-8')
self._body = body | Defines response body data.
Arguments:
body (str|bytes): response body to use.
Returns:
self: ``pook.Response`` current instance. | juraj-google-style |
def _time_delta_from_info(info):
delta_seconds = int(time.time()) - info.start_time
return str(datetime.timedelta(seconds=delta_seconds)) | Format the elapsed time for the given TensorBoardInfo.
Args:
info: A TensorBoardInfo value.
Returns:
A human-readable string describing the time since the server
described by `info` started: e.g., "2 days, 0:48:58". | juraj-google-style |
def get_unrecognized_field_info(self, key, value_default=None,
variant_default=None):
value, variant = self.__unrecognized_fields.get(key, (value_default,
variant_default))
return value, variant | Get the value and variant of an unknown field in this message.
Args:
key: The name or number of the field to retrieve.
value_default: Value to be returned if the key isn't found.
variant_default: Value to be returned as variant if the key isn't
found.
Returns:
(value, variant), where value and variant are whatever wa... | juraj-google-style |
def measure_topology(fbasename=None, log=None, ml_version=ml_version):
ml_script1_file = 'TEMP3D_measure_topology.mlx'
ml_script1 = mlx.FilterScript(file_in=fbasename, ml_version=ml_version)
compute.measure_topology(ml_script1)
ml_script1.save_to_file(ml_script1_file)
ml_script1.run_script(log=log, ... | Measures mesh topology
Args:
fbasename (str): input filename.
log (str): filename to log output
Returns:
dict: dictionary with the following keys:
vert_num (int): number of vertices
edge_num (int): number of edges
face_num (int): number of faces
unref_vert_num (int): number or unreferenced vertices
boundry_edge_num (... | codesearchnet |
def get_table(bq_legacy_client: BigQueryLegacyClient, table_metadata: TableMetadata) -> Table | None:
table: Table | None
try:
table = bq_legacy_client.get_table(table_metadata.full_table_id)
except NotFound:
table = None
return table | Get a table if it exists in BigQuery given the ID.
Args:
* bq_legacy_client: BigQuery Legacy API client
* table_metadata: TableMetadata object
Returns:
* Table object if it exists, else None | github-repos |
def __init__(self, encoding='utf-8'):
super(StdoutOutputWriter, self).__init__(sys.stdout, encoding=encoding) | Initializes a stdout output writer.
Args:
encoding (Optional[str]): output encoding. | juraj-google-style |
def add_tasks_r(addon_module, package_module, package_name):
module_dict = package_module.__dict__
for attr_name, attr_val in module_dict.items():
if isinstance(attr_val, fabric.tasks.WrappedCallableTask):
addon_module.__dict__[attr_name] = attr_val
elif attr_name != package_n... | Recursively iterate through 'package_module' and add every fabric task
to the 'addon_module' keeping the task hierarchy.
Args:
addon_module(types.ModuleType)
package_module(types.ModuleType)
package_name(str): Required, to avoid redundant addition of tasks
Return: None | juraj-google-style |
def _MergeSameAgency(self, a_agency_id, b_agency_id):
a_agency_id = (a_agency_id or
self.feed_merger.a_schedule.GetDefaultAgency().agency_id)
b_agency_id = (b_agency_id or
self.feed_merger.b_schedule.GetDefaultAgency().agency_id)
a_agency = self.feed_merger.a_sched... | Merge agency ids to the corresponding agency id in the merged schedule.
Args:
a_agency_id: an agency id from the old schedule
b_agency_id: an agency id from the new schedule
Returns:
The agency id of the corresponding merged agency.
Raises:
MergeError: If a_agency_id and b_agency_id do not correspond to the same
mer... | juraj-google-style |
def __closely_associated_score(self, normalized_sentences, top_n_words):
scores_list = []
sentence_idx = -1
for sentence in normalized_sentences:
self.tokenize(sentence)
sentence = self.token
sentence_idx += 1
word_idx = []
... | Scoring the sentence with closely associations.
Args:
normalized_sentences: The list of sentences.
top_n_words: Important sentences.
Returns:
The list of scores. | juraj-google-style |
def _maybe_repeat(self, x):
if isinstance(x, list):
assert (len(x) == self.n)
return x
else:
return ([x] * self.n) | Utility function for processing arguments that are singletons or lists.
Args:
x: either a list of self.n elements, or not a list.
Returns:
a list of self.n elements. | codesearchnet |
def _compute_fans(shape):
if (len(shape) < 1):
fan_in = fan_out = 1
elif (len(shape) == 1):
fan_in = fan_out = shape[0]
elif (len(shape) == 2):
fan_in = shape[0]
fan_out = shape[1]
else:
receptive_field_size = 1.0
for dim in shape[:(- 2)]:
rece... | Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out). | codesearchnet |
def check_compatibility(self):
usr_keys = list(self.usr_config.keys())
for k in self.usr_config.keys():
if k not in usr_keys:
err_msg = '[Error] Required config not found in user config.'
err_msg += '(required = %s, ' % str(k)
err_msg += 'user configs = %s)' % str(usr... | Checks version and dependency compatibility for a given configuration.
`check_compatibility` immediately returns with `False` (or failure status)
if any child process or checks fail. For error and warning messages, either
print `self.(error_msg|warning_msg)` or call `_print` function.
Returns:
Boolean that is a statu... | github-repos |
def destroy(ads):
for ad in ads:
try:
ad.services.stop_all()
except Exception:
ad.log.exception('Failed to clean up properly.') | Cleans up AndroidDevice objects.
Args:
ads: A list of AndroidDevice objects. | github-repos |
def from_str(self, in_str):
parts = in_str.split(';')
for part in parts:
(var_name, value) = part.split(':')
if (var_name == 'Obs_Threshold'):
self.obs_threshold = float(value)
elif (var_name == 'Thresholds'):
self.thresholds = np.array(value.split(), dtype=float)... | Read the DistributedROC string and parse the contingency table values from it.
Args:
in_str (str): The string output from the __str__ method | codesearchnet |
def devectorize(vectorized_mat, method='col'):
vectorized_mat = np.array(vectorized_mat)
dimension = int(np.sqrt(vectorized_mat.size))
if (len(vectorized_mat) != (dimension * dimension)):
raise Exception('Input is not a vectorized square matrix')
if (method == 'col'):
return vectorized_m... | Devectorize a vectorized square matrix.
Args:
vectorized_mat (ndarray): a vectorized density matrix.
method (str): the method of devectorization. Allowed values are
- 'col' (default): flattens to column-major vector.
- 'row': flattens to row-major vector.
- 'pauli': flattens in the n-qubit Pauli basis.
- 'pauli-weight... | codesearchnet |
def clone(self, callable=None, **overrides):
old = {k: v for k, v in self.get_param_values()
if k not in ['callable', 'name']}
params = dict(old, **overrides)
callable = self.callable if callable is None else callable
return self.__class__(callable, **params) | Clones the Callable optionally with new settings
Args:
callable: New callable function to wrap
**overrides: Parameter overrides to apply
Returns:
Cloned Callable object | juraj-google-style |
def write_config(params, config_path=None):
if config_path is None:
config_path = tempfile.mktemp(prefix="mongo-")
cfg = params.copy()
if 'setParameter' in cfg:
set_parameters = cfg.pop('setParameter')
try:
for key, value in set_parameters.items():
c... | write mongo*'s config file
Args:
params - options wich file contains
config_path - path to the config_file, will create if None
Return config_path
where config_path - path to mongo*'s options file | juraj-google-style |
def _assert_sparse_indices_are_ragged_right(indices):
index_prefix = indices[:, :-1]
index_suffix = indices[:, -1]
index_prefix_changed = math_ops.reduce_any(math_ops.not_equal(index_prefix[1:], index_prefix[:-1]), axis=1)
index_ok = array_ops.where(index_prefix_changed, math_ops.equal(index_suffix[1:],... | Checks that the given SparseTensor.indices tensor is ragged-right.
Example: `indices = [[0, 0], [0, 1], [2, 0], [3, 1]]` is not ragged right
because the entry `[3, 1]` skips a cell.
Args:
indices: The SparseTensor indices to check.
Returns:
A list of control dependency op tensors. | github-repos |
def kill_plasma_store(self, check_alive=True):
self._kill_process_type(
ray_constants.PROCESS_TYPE_PLASMA_STORE, check_alive=check_alive) | Kill the plasma store.
Args:
check_alive (bool): Raise an exception if the process was already
dead. | juraj-google-style |
def agg_dims(arr, stat):
axis = None
if arr.ndim > 2:
axis = 1
arr = arr.reshape(arr.shape[0], -1)
module = np.ma if hasattr(arr, 'mask') else np
return getattr(module, stat)(arr, axis) | Returns a 1D array with higher dimensions aggregated using stat fn.
Arguments:
arr -- ndarray
stat -- numpy or numpy.ma function as str to call | juraj-google-style |
def double(self, count: float=0) -> float:
return 2 * count | Returns the input multiplied by 2.
Args:
count: Input number that you want to double.
Returns:
A number that is the double of count. | github-repos |
def inspect_service(self, service, insert_defaults=None):
url = self._url('/services/{0}', service)
params = {}
if (insert_defaults is not None):
if utils.version_lt(self._version, '1.29'):
raise errors.InvalidVersion('insert_defaults is not supported in API version < 1.29')
para... | Return information about a service.
Args:
service (str): Service name or ID.
insert_defaults (boolean): If true, default values will be merged
into the service inspect output.
Returns:
(dict): A dictionary of the server-side representation of the
service, including all relevant properties.
Raises:
:py:class:`docker.... | codesearchnet |
def ParseFileEntryMetadata(self, parser_mediator, file_entry):
if self._filestat_parser:
self._ParseFileEntryWithParser(
parser_mediator, self._filestat_parser, file_entry) | Parses the file entry metadata e.g. file system data.
Args:
parser_mediator (ParserMediator): parser mediator.
file_entry (dfvfs.FileEntry): file entry. | juraj-google-style |
def IsSimpleGroup(component):
assert isinstance(component, dict)
for unused_key, value in component.items():
if not IsValue(value) and (not isinstance(value, (list, dict))):
return False
return True | If a group is simple enough, then we treat it as a value in PrintResult.
Only if a group contains all value types do we consider it simple enough to
print as a value.
Args:
component: The group to check for value-group status.
Returns:
A boolean indicating if the group should be treated as a value for printing
purpos... | github-repos |
def _CreateReadAccessHelper(self):
h = CheckAccessHelper('read')
h.Allow('aff4:/')
h.Allow('aff4:/users')
h.Allow('aff4:/users/*', self._IsHomeDir)
h.Allow('aff4:/foreman', self._UserHasAdminLabel)
h.Allow('aff4:/blobs')
h.Allow('aff4:/blobs/*')
h.Allow('aff4:/FP')
h.Allow('aff4:/FP/... | Creates a CheckAccessHelper for controlling read access.
This function and _CreateQueryAccessHelper essentially define GRR's ACL
policy. Please refer to these 2 functions to either review or modify
GRR's ACLs.
Read access gives you the ability to open and read aff4 objects for which
you already have the URN.
Returns... | codesearchnet |
def _manage_location(attr):
return property((lambda self: getattr(self, ('_%s' % attr))), (lambda self, value: self._set_location(attr, value))) | Build managed property interface.
Args:
attr (str): Property's name
Returns:
property: Managed property interface | codesearchnet |
def getslice_slot(self, node: cfg.CFGNode, start_var: cfg.Variable, end_var: cfg.Variable) -> tuple[cfg.CFGNode, cfg.Variable]:
node, ret = self.call_pytd(node, '__getslice__', start_var, end_var)
results = []
unresolved = False
if self.is_concrete:
for start_val, end_val in cfg_utils.variable_p... | Implements __getslice__ for List.
Arguments:
node: The current CFG node.
start_var: A Variable containing the i in lst[i:j].
end_var: A Variable containing the j in lst[i:j].
Returns:
Tuple of (node, return_variable). node may be the same as the argument.
return_variable is a Variable with bindings of the possible re... | github-repos |
def get_inheritance(obj_name, obj_type='file'):
obj_dacl = dacl(obj_name=obj_name, obj_type=obj_type)
inherited = win32security.INHERITED_ACE
for i in range(0, obj_dacl.dacl.GetAceCount()):
ace = obj_dacl.dacl.GetAce(i)
if ((ace[0][1] & inherited) == inherited):
return True
r... | Get an object's inheritance.
Args:
obj_name (str):
The name of the object
obj_type (Optional[str]):
The type of object. Only three object types allow inheritance. Valid
objects are:
- file (default): This is a file or directory
- registry
- registry32 (for WOW64)
The following should return False as there is no in... | codesearchnet |
def to_concat_skip_model(self, start_id, end_id):
self.operation_history.append(("to_concat_skip_model", start_id, end_id))
filters_end = self.layer_list[end_id].output.shape[-1]
filters_start = self.layer_list[start_id].output.shape[-1]
start_node_id = self.layer_id_to_output_n... | Add a weighted add concatenate connection from after start node to end node.
Args:
start_id: The convolutional layer ID, after which to start the skip-connection.
end_id: The convolutional layer ID, after which to end the skip-connection. | juraj-google-style |
def pack_x_y_sample_weight(x, y=None, sample_weight=None):
if y is None:
if not isinstance(x, (tuple, list)):
return x
else:
return (x,)
elif sample_weight is None:
return (x, y)
else:
return (x, y, sample_weight) | Packs user-provided data into a tuple.
This is a convenience utility for packing data into the tuple formats
that `Model.fit()` uses.
Example:
>>> x = ops.ones((10, 1))
>>> data = pack_x_y_sample_weight(x)
>>> isinstance(data, ops.Tensor)
True
>>> y = ops.ones((10, 1))
>>> data = pack_x_y_sample_weight(x, y)
>>> isi... | github-repos |
def create_effect(self, label: str, name: str, *args, **kwargs) -> Effect:
effect_cls = effects.find_effect_class(name)
effect = effect_cls(*args, **kwargs)
effect._label = label
if label in self._effects:
raise ValueError("An effect with label '{}' already exists".... | Create an effect instance adding it to the internal effects dictionary using the label as key.
Args:
label (str): The unique label for the effect instance
name (str): Name or full python path to the effect class we want to instantiate
args: Positional arguments to the effect initializer
kwargs: Keyword arguments to th... | juraj-google-style |
def get_index(uid, i):
return _SHARED_SEQUENCES[uid][i] | Get the value from the PyDataset `uid` at index `i`.
To allow multiple PyDatasets to be used at the same time, we use `uid` to
get a specific one. A single PyDataset would cause the validation to
overwrite the training PyDataset.
This methods is called from worker threads.
Args:
uid: int, PyDataset identifier
i: ind... | github-repos |
def WriteFileEntry(self, path):
string = '{0:s}\n'.format(path)
encoded_string = self._EncodeString(string)
self._file_object.write(encoded_string) | Writes the file path to file.
Args:
path (str): path of the file. | codesearchnet |
def _duplicate_example(self, request):
index = int(request.args.get('index'))
if (index >= len(self.examples)):
return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400)
new_example = self.example_class()
new_example.CopyFrom(self.examples[index])
s... | Duplicates the specified example.
Args:
request: A request that should contain 'index'.
Returns:
An empty response. | codesearchnet |
def set_metadata(self, key: str, value: str):
if ((not isinstance(key, str)) or (not isinstance(value, str))):
raise TypeError("'key' and 'value' of metadata MUST be strings")
self.metadata[key] = value | Add a new metadata to the message
Args:
key (str): name of the metadata
value (str): value of the metadata | codesearchnet |
def image(array, domain=None, width=None, format='png', **kwargs):
image_data = serialize_array(array, fmt=format, domain=domain)
image = IPython.display.Image(data=image_data, format=format, width=width)
IPython.display.display(image) | Display an image.
Args:
array: NumPy array representing the image
fmt: Image format e.g. png, jpeg
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nearest neighbor interpolation.
size unchanged if None | codesearchnet |
def make_multiscale(image, resolutions,
resize_method=tf.image.ResizeMethod.BICUBIC,
num_channels=3):
scaled_images = []
for height in resolutions:
scaled_image = tf.image.resize_images(
image,
size=[height, height],
method=resize_method)
... | Returns list of scaled images, one for each resolution.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's height is resized to.
resize_method: tf.image.ResizeMethod.
num_channels: Number of channels in image.
Returns:
List of Tensors, one for each resolution with s... | juraj-google-style |
def call(self, inputs):
del inputs
with tf.compat.v1.name_scope(self._name):
return tfd.MultivariateNormalDiag(self.loc, self.scale_diag) | Runs the model to generate multivariate normal distribution.
Args:
inputs: Unused.
Returns:
A MultivariateNormalDiag distribution with event shape
[dimensions], batch shape [], and sample shape [sample_shape,
dimensions]. | codesearchnet |
def remove_tree_by_path(self, path):
with transaction.manager:
trees = self.path_db.get(path, None)
if not trees:
return
for tree in trees:
return self._remove_tree(tree) | Remove the tree from database by given `path`.
Args:
path (str): Path of the tree. | juraj-google-style |
def _unable_to_call_layer_due_to_serialization_issue(layer, *unused_args, **unused_kwargs):
raise ValueError('Cannot call custom layer {} of type {}, because the call function was not serialized to the SavedModel.Please try one of the following methods to fix this issue:\n\n(1) Implement `get_config` and `from_conf... | Replaces the `layer.call` if the layer was not fully serialized.
Keras Model/Layer serialization is relatively relaxed because SavedModels
are not always loaded back as keras models. Thus, when there is an issue
tracing a non-signature function, a warning is logged instead of raising an
error. This results in a SavedM... | github-repos |
def add_signature(key, inputs, outputs):
_check_dict_maps_to_tensors_or_sparse_tensors(inputs)
_check_dict_maps_to_tensors_or_sparse_tensors(outputs)
input_info = {input_name: tf_v1.saved_model.utils.build_tensor_info(tensor) for (input_name, tensor) in inputs.items()}
output_info = {output_name: tf_v1.... | Adds a signature to current graph.
Args:
key: Signature key as a string.
inputs: Signature inputs as a map from string to Tensor or SparseTensor.
outputs: Signature outputs as a map from string to Tensor or SparseTensor.
(Recall that a Variable is not a Tensor, but Variable.value() is.)
Raises:
TypeError: if the argu... | codesearchnet |
def get_segment(neuron, section_id, segment_id):
sec = neuron.sections[section_id]
return sec.points[segment_id:(segment_id + 2)][(:, COLS.XYZR)] | Get a segment given a section and segment id
Returns:
array of two [x, y, z, r] points defining segment | codesearchnet |
def __init__(self, channel):
self.CreateCluster = channel.unary_unary(
"/google.cloud.dataproc.v1beta2.ClusterController/CreateCluster",
request_serializer=google_dot_cloud_dot_dataproc__v1beta2_dot_proto_dot_clusters__pb2.CreateClusterRequest.SerializeToString,
resp... | Constructor.
Args:
channel: A grpc.Channel. | juraj-google-style |
def query(self, attributes=None, filters=None, only_unique=True, use_attr_names=False, dtypes=None):
root = ElementTree.Element('Query')
root.set('virtualSchemaName', self._virtual_schema)
root.set('formatter', 'TSV')
root.set('header', '1')
root.set('uniqueRows', native_str(int(only_unique)))
r... | Queries the dataset to retrieve the contained data.
Args:
attributes (list[str]): Names of attributes to fetch in query.
Attribute names must correspond to valid attributes. See
the attributes property for a list of valid attributes.
filters (dict[str,any]): Dictionary of filters --> values
to filter the dataset by. F... | codesearchnet |
def apply(
self,
func,
num_splits=None,
other_axis_partition=None,
maintain_partitioning=True,
**kwargs
):
import dask
if num_splits is None:
num_splits = len(self.list_of_blocks)
if other_axis_partition is not None:
... | Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
num_splits: The number of times to split the result object.
other_axis_partition: Another `DaskFrameAxisPartition` object to apply to
func with this one.
Returns:
A list of `DaskFramePartition` objects. | juraj-google-style |
def create(self, interface, vrid, **kwargs):
if ('enable' not in kwargs):
kwargs['enable'] = False
return self._vrrp_set(interface, vrid, **kwargs) | Creates a vrrp instance from an interface
Note:
This method will attempt to create a vrrp in the node's
operational config. If the vrrp already exists on the
interface, then this method will set the properties of
the existing vrrp to those that have been passed in, if
possible.
Args:
interface (string): The interface... | codesearchnet |
def addBorrowers(self, *borrowers):
self._borrowers.extend(borrowers)
((debug.logger & debug.flagCompiler) and debug.logger(('current MIB borrower(s): %s' % ', '.join([str(x) for x in self._borrowers]))))
return self | Add more transformed MIBs repositories to borrow MIBs from.
Whenever MibCompiler.compile encounters MIB module which neither of
the *searchers* can find or fetched ASN.1 MIB module can not be
parsed (due to syntax errors), these *borrowers* objects will be
invoked in order of their addition asking each if already tran... | codesearchnet |
def get_csv_row_count(filename: str) -> int:
row_count = 0
with open(filename, 'r') as f:
for _ in f:
row_count += 1
if row_count != 0:
row_count -= 1
return row_count | Quickly count number of rows in the given csv file.
Args:
* filename: Path to CSV file
Returns:
* number of rows, minus header | github-repos |
def save(self, checkpoint_dir=None):
checkpoint_dir = os.path.join(checkpoint_dir or self.logdir,
"checkpoint_{}".format(self._iteration))
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
checkpoint = self._save(checkp... | Saves the current model state to a checkpoint.
Subclasses should override ``_save()`` instead to save state.
This method dumps additional metadata alongside the saved path.
Args:
checkpoint_dir (str): Optional dir to place the checkpoint.
Returns:
Checkpoint path that may be passed to restore(). | juraj-google-style |
def _open_config_files(self, command_line_args):
config_files = [open(f) for files in map(glob.glob, map(os.path.expanduser, self._default_config_files))
for f in files]
user_config_file_arg_actions = [
a for a in self._actions if ... | Tries to parse config file path(s) from within command_line_args.
Returns a list of opened config files, including files specified on the
commandline as well as any default_config_files specified in the
constructor that are present on disk.
Args:
command_line_args: List of all args (already split on spaces) | juraj-google-style |
def get_interpolated_value(self, energy):
f = {}
for spin in self.densities.keys():
f[spin] = get_linear_interpolated_value(self.energies,
self.densities[spin],
energy)
re... | Returns interpolated density for a particular energy.
Args:
energy: Energy to return the density for. | juraj-google-style |
def LoadFromStorage(cls, path=None):
if path is None:
path = os.path.join(os.path.expanduser('~'), 'googleads.yaml')
return cls(**googleads.common.LoadFromStorage(
path, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES,
cls._OPTIONAL_INIT_VALUES)) | Creates an AdWordsClient with information stored in a yaml file.
Args:
[optional]
path: The path string to the file containing cached AdWords data.
Returns:
An AdWordsClient initialized with the values cached in the file.
Raises:
A GoogleAdsValueError if the given yaml file does not contain the
information necessary... | juraj-google-style |
def bessel_k1e(x, name=None):
with ops.name_scope(name, 'bessel_k1e', [x]):
return gen_special_math_ops.bessel_k1e(x) | Computes the Bessel k1e function of `x` element-wise.
Modified Bessel function of order 1.
>>> tf.math.special.bessel_k1e([0.5, 1., 2., 4.]).numpy()
array([2.73100971, 1.63615349, 1.03347685, 0.68157595], dtype=float32)
Args:
x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`,
`float32`, `fl... | github-repos |
def _GetTextInside(text, start_pattern):
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set(itervalues(matching_punctuation))
match = re.search(start_pattern, text, re.M)
if (not match):
return None
start_position = match.end(0)
assert (start_position > 0), '... | r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the pun... | codesearchnet |
def establish_ssh_connection(ip, ssh_private_key_file, ssh_user, port, attempts=5, timeout=None):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
while attempts:
try:
client.connect(ip, port=port, username=ssh_user, key_filename=ssh_private_key_... | Establish ssh connection and return paramiko client.
Raises:
IpaSSHException: If connection cannot be established
in given number of attempts. | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.