code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
input_length = input_ids.size(1)
if self.max_length == input_length + 1:
return (input_ids, None)
chosen_ids = None
match_found = False
for ngram_size in range(min(self.max_matching... | Fetches the candidates to be tried for the current input.
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
Return:
`torch.LongTensor` of shape `(num_candidates, candidate_length)`: The candid... | github-repos |
def _BuildEventData(self, record):
event_data = FseventsdEventData()
event_data.path = record.path
event_data.flags = record.event_flags
event_data.event_identifier = record.event_identifier
event_data.node_identifier = getattr(record, 'node_identifier', None)
return event_data | Builds an FseventsdData object from a parsed structure.
Args:
record (dls_record_v1|dls_record_v2): parsed record structure.
Returns:
FseventsdEventData: event data attribute container. | codesearchnet |
def delete_note(self, note_id):
note, status = self.trash_note(note_id)
if (status == -1):
return note, status
params = '/i/%s' % (str(note_id))
request = Request(url=DATA_URL+params, method='DELETE')
request.add_header(self.header, self.get_token()... | Method to permanently delete a note
Arguments:
- note_id (string): key of the note to trash
Returns:
A tuple `(note, status)`
- note (dict): an empty dict or an error message
- status (int): 0 on success and -1 otherwise | juraj-google-style |
def __init__(self, name):
self.name = name
self.edges_in = set()
self.edges_out = set() | Initialization method.
Args:
name (str): name of the vertex. | juraj-google-style |
def RegisterCredentials(cls, credentials):
if (credentials.type_indicator in cls._credentials):
raise KeyError('Credentials object already set for type indicator: {0:s}.'.format(credentials.type_indicator))
cls._credentials[credentials.type_indicator] = credentials | Registers a path specification credentials.
Args:
credentials (Credentials): credentials.
Raises:
KeyError: if credentials object is already set for the corresponding
type indicator. | codesearchnet |
def _get_value(self, scalar_data_blob, dtype_enum):
tensorflow_dtype = tf.DType(dtype_enum)
buf = np.frombuffer(scalar_data_blob, dtype=tensorflow_dtype.as_numpy_dtype)
return np.asscalar(buf) | Obtains value for scalar event given blob and dtype enum.
Args:
scalar_data_blob: The blob obtained from the database.
dtype_enum: The enum representing the dtype.
Returns:
The scalar value. | codesearchnet |
def _remove_subsequent_result_because_of_batch_failure(self, sig):
batch = self._batches_by_txn_id[sig]
seen = []
for txn in batch.transactions:
txn_id = txn.header_signature
for poss_successor in self._scheduled.copy():
if (not self.is_transaction_in_schedule(poss_successor)):
... | Remove transactions from scheduled and txn_results for
successors of txns in a failed batch. These transactions will now,
or in the future be rescheduled in next_transaction; giving a
replay ability.
Args:
sig (str): Transaction header signature | codesearchnet |
def repeat(sequence):
N = len(sequence)
def f(i):
return sequence[(i % N)]
return partial(force, sequence=_advance(f)) | Return a driver function that can advance a repeated of values.
.. code-block:: none
seq = [0, 1, 2, 3]
# repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...]
Args:
sequence (seq) : a sequence of values for the driver to bounce | codesearchnet |
def unflatten(guide, falttened_input):
return [unflatten(sub_list, falttened_input) if isinstance(sub_list, list)
else next(falttened_input) for sub_list in guide] | Unflatten a falttened generator.
Args:
guide: A guide list to follow the structure
falttened_input: A flattened iterator object
Usage:
guide = [["a"], ["b","c","d"], [["e"]], ["f"]]
input_list = [0, 1, 2, 3, 4, 5, 6, 7]
unflatten(guide, iter(input_list))
>> [[0], [1, 2, 3], [[4]], [5]] | juraj-google-style |
def _get_access_token():
access_token = os.environ.get(ACCESS_TOKEN_ENVIRONMENT_VARIABLE)
if access_token:
return access_token
else:
for access_token_variable in LEGACY_ACCESS_TOKEN_ENVIRONMENT_VARIABLES:
access_token = os.environ.get(access_token_variable)
if access_... | Attempt to get the access token from the environment.
Try using the current and legacy environment variables. If the access token
is found in a legacy environment variable, raise a deprecation warning.
Returns:
The access token found in the environment (str), or None. | codesearchnet |
def SetModifyTimestamp(self, value):
if value is None or isinstance(value, int):
self._last_modification_timestamp = value
else:
raise TypeError('timestamp can only be int or None, not %r' % value) | Set the last modify timestamp of this map.
Args:
value: An integer containing the number of seconds since epoch, or None.
Raises:
TypeError: The argument is not an int or None. | github-repos |
def _dropout(x, rate, noise_shape, uniform_sampler, dummy_rng_step, name, default_name):
with ops.name_scope(name, default_name, [x]) as name:
is_rate_number = isinstance(rate, numbers.Real)
if is_rate_number and (rate < 0 or rate >= 1):
raise ValueError(f'`rate` must be a scalar tensor ... | Shared implementation of the various dropout functions.
Args:
x: same as the namesake in `dropout_v2`.
rate: same as the namesake in `dropout_v2`.
noise_shape: same as the namesake in `dropout_v2`.
uniform_sampler: a callable of signature `(shape, dtype) ->
Tensor`, used to generate a tensor of uniformly-distributed
r... | github-repos |
def encode_boxes(self, text: Union[TextInput, PreTokenizedInput, EncodedInput], text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]]=None, boxes: Optional[List[List[int]]]=None, word_labels: Optional[List[List[int]]]=None, add_special_tokens: bool=True, padding: Union[bool, str, PaddingStrategy]=False... | Args:
Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary. Same as doing
`self.convert_tokens_to_ids(self.tokenize(text))`.
text (`str`, `List[str]` or `List[int]`):
The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
`tokenize` method) ... | github-repos |
def noisy_moment(self, moment: 'cirq.Moment',
system_qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
if not hasattr(self.noisy_moments, '_not_overridden'):
return self.noisy_moments([moment], system_qubits)
if not hasattr(self.noisy_operation, '_not_overridden... | Adds noise to the operations from a moment.
Args:
moment: The moment to add noise to.
system_qubits: A list of all qubits in the system.
Returns:
An OP_TREE corresponding to the noisy operations for the moment. | juraj-google-style |
def __create_and_save_state(cls, job_config, mapreduce_spec):
state = model.MapreduceState.create_new(job_config.job_id)
state.mapreduce_spec = mapreduce_spec
state.active = True
state.active_shards = 0
state.app_id = job_config._app
config = datastore_rpc.Configuration(force_writes=job_con... | Save map job state to datastore.
Save state to datastore so that UI can see it immediately.
Args:
job_config: map_job.JobConfig.
mapreduce_spec: model.MapreduceSpec.
Returns:
model.MapreduceState for this job. | juraj-google-style |
def __init__(self, shape, scope='distribution', summary_labels=None):
self.shape = shape
self.scope = scope
self.summary_labels = set(summary_labels or ())
self.variables = dict()
self.all_variables = dict()
def custom_getter(getter, name, registered=False, **... | Distribution.
Args:
shape: Action shape. | juraj-google-style |
def set_xml(self, diagram, force=False):
no_of_running = WFInstance.objects.filter(wf=self, finished=False, started=True).count()
if no_of_running and not force:
raise RunningInstancesExist(
"Can't update WF diagram! Running %s WF instances exists for %s" % (
... | updates xml link if there aren't any running instances of this wf
Args:
diagram: XMLDiagram object | juraj-google-style |
def __init__(self, sbn):
isbn = '0' + sbn
super(Sbn, self).__init__(isbn) | Initialise a new ``Sbn`` object.
Args:
sbn (str): SBN string | juraj-google-style |
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
if token_ids_1:
output += token_ids_1 + [self.sep_token_id]
return output | Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A BERT sequence has the following format:
- single sequence: `[CLS] X [SEP]`
- pair of sequences: `[CLS] A [SEP] B [SEP]`
Args:
token_ids_0 (`List[int]`):
List of IDs to which the spe... | github-repos |
def plot_state_histogram(result: trial_result.TrialResult) -> np.ndarray:
import matplotlib.pyplot as plt
num_qubits = len(result.measurements.keys())
states = 2**num_qubits
values = np.zeros(states)
measurement_by_result = np.array([
v.transpo... | Plot the state histogram from a single result with repetitions.
States is a bitstring representation of all the qubit states in a single
result.
Currently this function assumes each measurement gate applies to only
a single qubit.
Args:
result: The trial results to plot.
Returns:
The histogram. A list of values plot... | juraj-google-style |
def get_enterprise_customer_user(user_id, enterprise_uuid):
EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser')
try:
return EnterpriseCustomerUser.objects.get(
enterprise_customer__uuid=enterprise_uuid,
user_id=user_id
)
except Ent... | Return the object for EnterpriseCustomerUser.
Arguments:
user_id (str): user identifier
enterprise_uuid (UUID): Universally unique identifier for the enterprise customer.
Returns:
(EnterpriseCustomerUser): enterprise customer user record | juraj-google-style |
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('public_key', type=parameters.valid_ed25519, required=True)
parser.add_argument('spent', type=parameters.valid_bool)
args = parser.parse_args(strict=True)
pool = current_app.config['bigchain_pool']
with pool() as bigchain:
... | API endpoint to retrieve a list of links to transaction
outputs.
Returns:
A :obj:`list` of :cls:`str` of links to outputs. | codesearchnet |
def path_is_empty(p: tcod.path.AStar) -> bool:
return bool(lib.TCOD_path_is_empty(p._path_c)) | Return True if a path is empty.
Args:
p (AStar): An AStar instance.
Returns:
bool: True if a path is empty. Otherwise False. | codesearchnet |
def ToParameter(item: StackItem):
if (isinstance(item, Array) or isinstance(item, Struct)):
items = item.GetArray()
output = [ContractParameter.ToParameter(subitem) for subitem in items]
return ContractParameter(type=ContractParameterType.Array, value=output)
elif isinstance(item, Boolea... | Convert a StackItem to a ContractParameter object
Args:
item (neo.VM.InteropService.StackItem) The item to convert to a ContractParameter object
Returns:
ContractParameter | codesearchnet |
def mixins(self, name):
m = self._smixins(name)
if m:
return m
return self._smixins(name.replace('?>?', ' ')) | Search mixins for name.
Allow '>' to be ignored. '.a .b()' == '.a > .b()'
Args:
name (string): Search term
Returns:
Mixin object list OR False | juraj-google-style |
def _wrap_result(self, response):
if isinstance(response, int):
response = self._wrap_response(response)
return HandlerResult(status=HandlerStatus.RETURN, message_out=self._response_proto(**response), message_type=self._response_type) | Wraps child's response in a HandlerResult to be sent back to client.
Args:
response (enum or dict): Either an integer status enum, or a dict
of attributes to be added to the protobuf response. | codesearchnet |
def output_reference(self, name):
if name not in self.output_names:
raise ValueError('Invalid output "{}"'.format(name))
return Reference(step_name=self.name_in_workflow, output_name=name) | Return a reference to the given output for use in an input
of a next Step.
For a Step named `echo` that has an output called `echoed`, the
reference `echo/echoed` is returned.
Args:
name (str): the name of the Step output
Raises:
ValueError: The name provided is not a valid output name for this
Step. | juraj-google-style |
def register_many(self, *args):
params = []
for name in args:
params.append(self.register(name))
return params | Register many configuration names.
Arguments:
*args: Config names as strings.
Returns:
list: List of registered configs. | codesearchnet |
def call(self, inputs):
image_shape = tf.shape(input=inputs)[(- 3):]
collapsed_shape = tf.concat(([(- 1)], image_shape), axis=0)
out = tf.reshape(inputs, collapsed_shape)
out = self.conv1(out)
out = self.conv2(out)
out = self.conv3(out)
out = self.conv4(out)
expanded_shape = tf.concat((t... | Runs the model to generate an intermediate representation of x_t.
Args:
inputs: A batch of image sequences `x_{1:T}` of shape
`[sample_shape, batch_size, timesteps, height, width,
channels]`.
Returns:
A batch of intermediate representations of shape [sample_shape,
batch_size, timesteps, hidden_size]. | codesearchnet |
def prepare_namespace(self, func):
if self.is_imethod:
to_run = getattr(self.obj, self.imethod_name)
else:
to_run = func
for (varname, modulename) in self.global_modules.items():
to_run.__globals__[varname] = __import__(modulename)
if self.global_closure:
to_run.__globals... | Prepares the function to be run after deserializing it.
Re-associates any previously bound variables and modules from the closure
Returns:
callable: ready-to-call function | codesearchnet |
def rot90(array, k=1, axes=(0, 1)):
if any_symbolic_tensors((array,)):
return Rot90(k=k, axes=axes).symbolic_call(array)
return backend.numpy.rot90(array, k=k, axes=axes) | Rotate an array by 90 degrees in the plane specified by axes.
This function rotates an array counterclockwise
by 90 degrees `k` times in the plane specified by `axes`.
Supports arrays of two or more dimensions.
Args:
array: Input array to rotate.
k: Number of times the array is rotated by 90 degrees.
axes: A tuple of... | github-repos |
def unravel_staff(staff_data):
staff_list = []
for (role, staff_members) in staff_data['data'].items():
for member in staff_members:
member['role'] = role
staff_list.append(member)
return staff_list | Unravels staff role dictionary into flat list of staff
members with ``role`` set as an attribute.
Args:
staff_data(dict): Data return from py:method::get_staff
Returns:
list: Flat list of staff members with ``role`` set to
role type (i.e. course_admin, instructor, TA, etc) | codesearchnet |
def forecast(self, throughputs, backlog_size, num_simulations=10000, max_periods=10000, seed=None):
self._check_throughputs(throughputs)
results = []
if seed is not None:
random.seed(seed)
for i in range(0, num_simulations):
simulated_backlog = backlog_... | Forecasts how long a backlog will take to complete given the historical values provided.
Arguments:
throughputs(List[int]): Number of units completed per unit of time (stories per week, story points per month, etc.)
backlog_size(int): Units in the backlog (stories, points, etc.)
Returns:
results
Exceptions:
ValueError:... | juraj-google-style |
def _predictResponseSize(mode, functioncode, payloadToSlave):
MIN_PAYLOAD_LENGTH = 4
BYTERANGE_FOR_GIVEN_SIZE = slice(2, 4)
NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION = 4
NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD = 1
RTU_TO_ASCII_PAYLOAD_FACTOR = 2
NUMBER_OF_RTU_RESPONSE_STARTBYTES = 2
N... | Calculate the number of bytes that should be received from the slave.
Args:
* mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
* functioncode (int): Modbus function code.
* payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string)
Returns:
The preducted number of bytes... | codesearchnet |
def create_detector(self, detector):
resp = self._post(self._u(self._DETECTOR_ENDPOINT_SUFFIX), data=detector)
resp.raise_for_status()
return resp.json() | Creates a new detector.
Args:
detector (object): the detector model object. Will be serialized as
JSON.
Returns:
dictionary of the response (created detector model). | codesearchnet |
def get_application_configurations(self, name=None):
if hasattr(self, 'applicationConfigurations'):
return self._get_elements(self.applicationConfigurations, 'applicationConfigurations', ApplicationConfiguration, None, name) | Retrieves application configurations for this instance.
Args:
name (str, optional): Only return application configurations containing property **name** that matches `name`. `name` can be a
regular expression. If `name` is not supplied, then all application configurations are returned.
Returns:
list(ApplicationConfigu... | juraj-google-style |
def apply_cut(self, cut):
return MacroSubsystem(self.network, self.network_state, self.micro_node_indices, cut=cut, time_scale=self.time_scale, blackbox=self.blackbox, coarse_grain=self.coarse_grain) | Return a cut version of this |MacroSubsystem|.
Args:
cut (Cut): The cut to apply to this |MacroSubsystem|.
Returns:
MacroSubsystem: The cut version of this |MacroSubsystem|. | codesearchnet |
def parse_user_data(variables, raw_user_data, blueprint_name):
variable_values = {}
for (key, value) in variables.items():
if (type(value) is CFNParameter):
variable_values[key] = value.to_parameter_value()
else:
variable_values[key] = value
template = string.Template... | Parse the given user data and renders it as a template
It supports referencing template variables to create userdata
that's supplemented with information from the stack, as commonly
required when creating EC2 userdata files.
For example:
Given a raw_user_data string: 'open file ${file}'
And a variables dictionary wit... | codesearchnet |
def _genBgTerm_fromXX(self,vTot,vCommon,XX,a=None,c=None):
vSpecific = vTot-vCommon
SP.random.seed(0)
if c==None: c = SP.randn(self.P)
XX += 1e-3 * SP.eye(XX.shape[0])
L = LA.cholesky(XX,lower=True)
R = self.genWeights(self.N,self.P)
A = self.g... | generate background term from SNPs
Args:
vTot: variance of Yc+Yi
vCommon: variance of Yc
XX: kinship matrix
a: common scales, it can be set for debugging purposes
c: indipendent scales, it can be set for debugging purposes | juraj-google-style |
def EncodeEnv(env, encoding=None):
encoding = encoding or _GetEncoding()
return {Encode(k, encoding=encoding): Encode(v, encoding=encoding) for k, v in env.items()} | Encodes all the key value pairs in env in preparation for subprocess.
Args:
env: {str: str}, The environment you are going to pass to subprocess.
encoding: str, The encoding to use or None to use the default.
Returns:
{bytes: bytes}, The environment to pass to subprocess. | github-repos |
def _keyDown(key):
if key not in keyboardMapping or keyboardMapping[key] is None:
return
if type(key) == int:
fake_input(_display, X.KeyPress, key)
_display.sync()
return
needsShift = pyautogui.isShiftCharacter(key)
if needsShift:
fake_input(_display, X.Key... | Performs a keyboard key press without the release. This will put that
key in a held down state.
NOTE: For some reason, this does not seem to cause key repeats like would
happen if a keyboard key was held down on a text field.
Args:
key (str): The key to be pressed down. The valid names are listed in
pyautogui.KEY_NAM... | juraj-google-style |
def __init__(self, learning_rate, initial_accumulator_value=0.1, use_locking=False, name='Adagrad'):
if initial_accumulator_value <= 0.0:
raise ValueError('initial_accumulator_value must be positive: %s' % initial_accumulator_value)
super(AdagradOptimizer, self).__init__(use_locking, name)
self._lea... | Construct a new Adagrad optimizer.
Args:
learning_rate: A `Tensor` or a floating point value. The learning rate.
initial_accumulator_value: A floating point value.
Starting value for the accumulators, must be positive.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operatio... | github-repos |
def symbol_top(body_output, targets, model_hparams, vocab_size):
del targets
if model_hparams.shared_embedding_and_softmax_weights:
scope_name = 'shared'
reuse = tf.AUTO_REUSE
else:
scope_name = 'softmax'
reuse = False
with tf.variable_scope(scope_name, reuse=reuse):
... | Generate logits.
Args:
body_output: A Tensor with shape
[batch, p0, p1, model_hparams.hidden_size].
targets: Unused.
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
Returns:
logits: A Tensor with shape [batch, p0, p1, ?, vocab_size]. | codesearchnet |
def concurrence(state):
rho = np.array(state)
if (rho.ndim == 1):
rho = outer(state)
if (len(state) != 4):
raise Exception('Concurrence is only defined for more than two qubits')
YY = np.fliplr(np.diag([(- 1), 1, 1, (- 1)]))
A = rho.dot(YY).dot(rho.conj()).dot(YY)
w = la.eigh(A, ... | Calculate the concurrence.
Args:
state (np.array): a quantum state (1x4 array) or a density matrix (4x4
array)
Returns:
float: concurrence.
Raises:
Exception: if attempted on more than two qubits. | codesearchnet |
def create_course_completion(self, user_id, payload):
return self._post(urljoin(self.enterprise_configuration.degreed_base_url, self.global_degreed_config.completion_status_api_path), payload, self.COMPLETION_PROVIDER_SCOPE) | Send a completion status payload to the Degreed Completion Status endpoint
Args:
user_id: Unused.
payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)
containing completion status fields per Degreed documentation.
Returns:
A tuple containing the status code and the body of the response.
... | codesearchnet |
def add_nodes(self, nodes):
if (not isinstance(nodes, list)):
add_list = [nodes]
else:
add_list = nodes
self.node_list.extend(add_list) | Add a given node or list of nodes to self.node_list.
Args:
node (Node or list[Node]): the node or list of nodes to add
to the graph
Returns: None
Examples:
Adding one node: ::
>>> from blur.markov.node import Node
>>> graph = Graph()
>>> node_1 = Node('One')
>>> graph.add_nodes(node_1)
>>> print([node.value for no... | codesearchnet |
def initialize(self, map_arr, start_point_label="S", end_point_label="G", wall_label="
np.set_printoptions(threshold=np.inf)
self.__agent_label = agent_label
self.__map_arr = map_arr
self.__start_point_label = start_point_label
start_arr_tuple = np.where(self.__map_arr ... | Initialize map of maze and setup reward value.
Args:
map_arr: Map. the 2d- `np.ndarray`.
start_point_label: Label of start point.
end_point_label: Label of end point.
wall_label: Label of wall.
agent_label: Label of agent. | juraj-google-style |
def expand_value_set_url_using_service(self, value_set_url: str, terminology_service_url: str) -> value_set_pb2.ValueSet:
value_set_url, value_set_version = url_utils.parse_url_version(value_set_url)
auth = self.auth_per_terminology_server.get(terminology_service_url)
return self._expand_value_set_url_using... | Expands the value set using the requested terminology service.
Requests an expansion of the value set from the terminology
server at `terminology_service_url` for the given URL and version if present
on the URL.
If the terminology service requires credentials to access,
`terminology_service_url` must have an entry in... | github-repos |
async def teardown_client(self, client_id):
client_info = self._client_info(client_id)
self.adapter.remove_monitor(client_info['monitor'])
conns = client_info['connections']
for (conn_string, conn_id) in conns.items():
try:
self._logger.debug('Disconnecting client %s from conn %s at ... | Release all resources held by a client.
This method must be called and awaited whenever a client is
disconnected. It ensures that all of the client's resources are
properly released and any devices they have connected to are
disconnected cleanly.
Args:
client_id (str): The client that we should tear down.
Raises:
A... | codesearchnet |
def CreateAd(client, opener, ad_group_id):
ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809')
media_service = client.GetService('MediaService', 'v201809')
marketing_image_id = _CreateImage(media_service, opener, 'https:
logo_image_id = _CreateImage(media_service, opener, 'https:
... | Creates a ResponsiveDisplayAd.
Args:
client: an AdWordsClient instance.
opener: an OpenerDirector instance.
ad_group_id: an int ad group ID.
Returns:
The ad group ad that was successfully created. | codesearchnet |
def build_aspect_ratio_mask(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray:
batch_size = len(aspect_ratios)
max_num_images = max([len(row) for row in aspect_ratios])
aspect_ratio_mask = np.zeros((batch_size, max_num_images, max_image_tiles), dtype=np.int64)
aspect_ratio_... | Builds a mask for the aspect ratios of the images.
Args:
aspect_ratios (`List[List[Tuple[int, int]]]`):
A list of lists containing aspect ratios for each image in the batch.
Each aspect ratio is represented as a tuple of (width, height) in terms of number of tiles.
max_image_tiles (`int`):
The maximum number of tiles ... | github-repos |
def simplify_countryname(cls, country):
countryupper = country.upper()
words = get_words_in_sentence(countryupper)
index = countryupper.find(',')
if (index != (- 1)):
countryupper = countryupper[:index]
index = countryupper.find(':')
if (index != (- 1)):
countryupper = countryupp... | Simplifies country name by removing descriptive text eg. DEMOCRATIC, REPUBLIC OF etc.
Args:
country (str): Country name to simplify
Returns:
Tuple[str, List[str]]: Uppercase simplified country name and list of removed words | codesearchnet |
def parse_verilog_file(fname):
with open(fname, 'rt') as fh:
text = fh.read()
return parse_verilog(text) | Parse a named Verilog file
Args:
fname (str): File to parse.
Returns:
List of parsed objects. | juraj-google-style |
def load_readers(filenames=None, reader=None, reader_kwargs=None, ppp_config_dir=None):
reader_instances = {}
reader_kwargs = (reader_kwargs or {})
reader_kwargs_without_filter = reader_kwargs.copy()
reader_kwargs_without_filter.pop('filter_parameters', None)
if (ppp_config_dir is None):
ppp... | Create specified readers and assign files to them.
Args:
filenames (iterable or dict): A sequence of files that will be used to load data from. A ``dict`` object
should map reader names to a list of filenames for that reader.
reader (str or list): The name of the reader to use for loading the data or a list of names.
... | codesearchnet |
def _find_root_dir(path, spor_dir):
start_path = pathlib.Path((os.getcwd() if (path is None) else path))
paths = ([start_path] + list(start_path.parents))
for path in paths:
data_dir = (path / spor_dir)
if (data_dir.exists() and data_dir.is_dir()):
return path
raise ValueErro... | Search for a spor repo containing `path`.
This searches for `spor_dir` in directories dominating `path`. If a
directory containing `spor_dir` is found, then that directory is returned
as a `pathlib.Path`.
Returns: The dominating directory containing `spor_dir` as a
`pathlib.Path`.
Raises:
ValueError: No repository i... | codesearchnet |
def last_updated(path):
filesystem = FileSystems.get_filesystem(path)
return filesystem.last_updated(path) | Get UNIX Epoch time in seconds on the FileSystem.
Args:
path: string path of file.
Returns: float UNIX Epoch time
Raises:
``BeamIOError``: if path doesn't exist. | github-repos |
def log_histogram(self, name, value, step=None):
if isinstance(value, six.string_types):
raise TypeError('"value" should be a number, got {}'.format(type(value)))
self._check_step(step)
tf_name = self._ensure_tf_name(name)
summary = self._histogram_summary(tf_name, value, step=step)
self._lo... | Log a histogram for given name on given step.
Args:
name (str): name of the variable (it will be converted to a valid
tensorflow summary name).
value (tuple or list): either list of numbers
to be summarized as a histogram, or a tuple of bin_edges and
bincounts that directly define a histogram.
step (int): non-negative... | codesearchnet |
def map_to_pdf(map_source, zoom, x, y, width, height):
map_source = app.config["mapsources"][map_source]
pdf_file = print_map(map_source, x=float(x), y=float(y),
zoom=int(zoom), width=float(width), height=float(height), format='pdf')
return send_file(pdf_file,
... | Generate a PDF at the given position.
Args:
map_source (str): id of the map source to print.
zoom (int): zoom-level to print
x (float): Center of the Map in mercator projection (EPSG:4326), x-coordinate
y (float): Center of the Map in mercator projection (EPSG:4326), y-coordinate
width (float): width of the pdf in mm
... | juraj-google-style |
def maybe(cls, val: Optional[T]) -> 'Option[T]':
return cast('Option[T]', NONE) if val is None else cls.Some(val) | Shortcut method to return ``Some`` or :py:data:`NONE` based on ``val``.
Args:
val: Some value.
Returns:
``Some(val)`` if the ``val`` is not None, otherwise :py:data:`NONE`.
Examples:
>>> Option.maybe(0)
Some(0)
>>> Option.maybe(None)
NONE | juraj-google-style |
def compress_encoder_2d(x, hparams, name=None):
return compress_encoder(
x,
hparams,
strides=(2, 2),
kernel_size=(hparams.kernel_size, hparams.kernel_size),
name=name) | Encoder that compresses 2-D inputs by 2**num_compress_steps.
Args:
x: Tensor of shape [batch, height, width, channels].
hparams: HParams.
name: string, variable scope.
Returns:
Tensor of shape [batch, latent_length, hparams.hidden_size], where
latent_length is
hparams.num_latents * (height*width) / 2**(hparams.num_co... | juraj-google-style |
def write_to_hdf5(self, filename_out, *args, **kwargs):
t0 = time.time()
self.__update_header()
if self.container.isheavy():
self.__write_to_hdf5_heavy(filename_out)
else:
self.__write_to_hdf5_light(filename_out)
t1 = time.ti... | Write data to HDF5 file.
It check the file size then decides how to write the file.
Args:
filename_out (str): Name of output file | juraj-google-style |
def keep_doc_examples_only(content: str) -> str:
splits = content.split('```')
content = '```' + '```'.join(splits[1::2]) + '```'
lines_to_keep = []
for line in content.split('\n'):
line = re.sub('
if len(line) != 0 and (not line.isspace()):
lines_to_keep.append(line)
ret... | Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc
tests or not).
Args:
content (`str`): The code to clean
Returns:
`str`: The cleaned code. | github-repos |
def subscriber(address,topics,callback,message_type):
return Subscriber(address,topics,callback,message_type) | Creates a subscriber binding to the given address and
subscribe the given topics.
The callback is invoked for every message received.
Args:
- address: the address to bind the PUB socket to.
- topics: the topics to subscribe
- callback: the callback to invoke for every message. Must accept 2 variables - topic and messa... | juraj-google-style |
def set_dataset_year_range(self, dataset_year, dataset_end_year=None):
if isinstance(dataset_year, int):
dataset_date = '01/01/%d' % dataset_year
elif isinstance(dataset_year, str):
dataset_date = '01/01/%s' % dataset_year
else:
raise hdx.dat... | Set dataset date as a range from year or start and end year.
Args:
dataset_year (Union[str, int]): Dataset year given as string or int
dataset_end_year (Optional[Union[str, int]]): Dataset end year given as string or int
Returns:
None | juraj-google-style |
def dot(matrix, vector):
matrix_weld_type = None
vector_weld_type = None
if isinstance(matrix, LazyOpResult):
matrix_weld_type = matrix.weld_type
matrix = matrix.expr
elif isinstance(matrix, np.ndarray):
matrix_weld_type = numpy_weld_impl.numpy_to_weld_type_mapping[
... | Computes the dot product between a matrix and a vector.
TODO: Make this more generic
Args:
matrix (TYPE): Description
vector (TYPE): Description | juraj-google-style |
def trailing_stop_loss(self, accountID, **kwargs):
return self.create(
accountID,
order=TrailingStopLossOrderRequest(**kwargs)
) | Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request | juraj-google-style |
def CrowdsaleRegister(self, wallet, register_addresses, from_addr=None):
invoke_args = [self.ScriptHash.ToString(), 'crowdsale_register', [PromptUtils.parse_param(p, wallet) for p in register_addresses]]
(tx, fee, results, num_ops, engine_success) = TestInvokeContract(wallet, invoke_args, None, True, from_addr)... | Register for a crowd sale.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
register_addresses (list): list of public addresses to register for the sale.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results. | codesearchnet |
def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
if token_ids_1 is None:
return self.prefix_tokens + token_ids_0 + self.suffix_tokens
return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens | Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. An NLLB sequence has the following format, where `X` represents the sequence:
- `input_ids` (for encoder) `X [eos, src_lang_code]`
- `decoder_input_ids`: (for decoder) `X [eos, tgt_lan... | github-repos |
def decode(self, ids, strip_extraneous=False):
if strip_extraneous:
ids = strip_ids(ids, list(range((self._num_reserved_ids or 0))))
return ' '.join(self.decode_list(ids)) | Transform a sequence of int ids into a human-readable string.
EOS is not expected in ids.
Args:
ids: list of integers to be converted.
strip_extraneous: bool, whether to strip off extraneous tokens
(EOS and PAD).
Returns:
s: human-readable string. | codesearchnet |
def from_dict(event_dict):
return CallbackEvent(callback_id=event_dict['callbackId'], name=event_dict['name'], creation_time=event_dict['time'], data=event_dict['data']) | Creates a CallbackEvent object from a dictionary.
Args:
event_dict: dict, a dictionary representing an event.
Returns:
A CallbackEvent object. | github-repos |
def entry_dict_from_list(all_slab_entries):
entry_dict = {}
for entry in all_slab_entries:
hkl = tuple(entry.miller_index)
if (hkl not in entry_dict.keys()):
entry_dict[hkl] = {}
if entry.clean_entry:
clean = entry.clean_entry
else:
clean = ent... | Converts a list of SlabEntry to an appropriate dictionary. It is
assumed that if there is no adsorbate, then it is a clean SlabEntry
and that adsorbed SlabEntry has the clean_entry parameter set.
Args:
all_slab_entries (list): List of SlabEntry objects
Returns:
(dict): Dictionary of SlabEntry with the Miller index as... | codesearchnet |
def _build_key_wrapping_specification(self, value):
if value is None:
return None
if not isinstance(value, dict):
raise TypeError("Key wrapping specification must be a dictionary.")
encryption_key_info = self._build_encryption_key_information(
value.... | Build a KeyWrappingSpecification struct from a dictionary.
Args:
value (dict): A dictionary containing the key/value pairs for a
KeyWrappingSpecification struct.
Returns:
KeyWrappingSpecification: a KeyWrappingSpecification struct
Raises:
TypeError: if the input argument is invalid | juraj-google-style |
def _DiscoverElementTypeFromLocalname(self, type_localname):
elem_type = None
last_exception = None
for ns_prefix in self.zeep_client.wsdl.types.prefix_map.values():
try:
elem_type = self.zeep_client.get_type(('{%s}%s' % (ns_prefix, type_localname)))
except zeep.exceptions.Lookup... | Searches all namespaces for a type by name.
Args:
type_localname: The name of the type.
Returns:
A fully qualified SOAP type with the specified name.
Raises:
A zeep.exceptions.LookupError if the type cannot be found in any
namespace. | codesearchnet |
def decorate(self, record):
color = 'gray'
if record.levelno == logging.WARNING:
color = 'yellow'
if record.levelno == logging.INFO:
color = 'green'
if record.levelno == logging.DEBUG:
color = 'gray'
if record.levelno >= logging.ERROR:... | Build up HipChat specific values for log record
Args:
record (:obj:`logging.record`): log message object
Returns:
dict: params for POST request | juraj-google-style |
def call(self, inputs, states):
raise NotImplementedError('Abstract method') | The function that contains the logic for one RNN step calculation.
Args:
inputs: the input tensor, which is a slide from the overall RNN input by
the time dimension (usually the second dimension).
states: the state tensor from previous step, which has the same shape
as `(batch, state_size)`. In the case of timestep 0,... | github-repos |
def factor_hatch(field_name, patterns, factors, start=0, end=None):
return field(field_name, CategoricalPatternMapper(patterns=patterns, factors=factors, start=start, end=end)) | Create a ``DataSpec`` dict that applies a client-side
``CategoricalPatternMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
patterns (seq[string]) : a list of hatch patterns to use to map to
factors (seq) : a sequences of categorical factor... | codesearchnet |
def check_schema_transforms_match(schema, inverted_features):
num_target_transforms = 0
for col_schema in schema:
col_name = col_schema['name']
col_type = col_schema['type'].lower()
if col_name in inverted_features:
for transform in inverted_features[col_name]:
transform_name = t... | Checks that the transform and schema do not conflict.
Args:
schema: schema list
inverted_features: inverted_features dict
Raises:
ValueError if transform cannot be applied given schema type. | juraj-google-style |
def get_appliance_by_name(self, appliance_name):
appliances = self.get_appliances()
if appliances:
for appliance in appliances:
if (appliance['name'] == appliance_name):
return appliance
return None | Gets the particular Image Streamer resource based on its name.
Args:
appliance_name:
The Image Streamer resource name.
Returns:
dict: Image Streamer resource. | codesearchnet |
def register_frame_to_skip(method: Union[Callable[..., Any], List[Callable[..., Any]]]) -> bool:
register_fn = getattr(_DEFAULT_LOGGER.__class__, 'register_frame_to_skip', None)
if register_fn is None:
return False
methods = [method] if not isinstance(method, list) else method
for m in methods:
... | Skips the source of the given method when logging.
Args:
method: The method to skip. Can be a single method or a list of methods.
Returns:
True if the method is registered to skip.
Raises:
TypeError: The source file of the method cannot be inspected. | github-repos |
def CmdRegister(self, challenge_param, app_param):
self.logger.debug('CmdRegister')
if ((len(challenge_param) != 32) or (len(app_param) != 32)):
raise errors.InvalidRequestError()
body = bytearray((challenge_param + app_param))
response = self.InternalSendApdu(apdu.CommandApdu(0, apdu.CMD_REGIST... | Register security key.
Ask the security key to register with a particular origin & client.
Args:
challenge_param: Arbitrary 32 byte challenge string.
app_param: Arbitrary 32 byte applciation parameter.
Returns:
A binary structure containing the key handle, attestation, and a
signature over that by the attestation ke... | codesearchnet |
def __init__(self, location, field_type):
super(GlobalContextField, self).__init__(location, field_type)
self.location = location
self.field_type = field_type
self.validate() | Construct a new GlobalContextField object that references a field at a given location.
Args:
location: Location, specifying where the field was declared.
Returns:
new GlobalContextField object | juraj-google-style |
def _Check3DImage(image, require_static=True):
try:
image_shape = image.get_shape().with_rank(3)
except ValueError:
raise ValueError("'image' (shape %s) must be three-dimensional." % image.shape)
if require_static and (not image_shape.is_fully_defined()):
raise ValueError("'image' (s... | Assert that we are working with a properly shaped image.
Args:
image: 3-D Tensor of shape [height, width, channels]
require_static: If `True`, requires that all dimensions of `image` are known
and non-zero.
Raises:
ValueError: if `image.shape` is not a 3-vector.
Returns:
An empty list, if `image` has fully defined d... | github-repos |
def on_moved(self, event):
if (not self._event_error):
pathtools_options = {'included_patterns': self.patterns, 'excluded_patterns': self.ignore_patterns, 'case_sensitive': self.case_sensitive}
if match_path(event.dest_path, **pathtools_options):
self.logger.info(u'Change detected from a... | Called when a file or a directory is moved or renamed.
Many editors don't directly change a file, instead they make a
transitional file like ``*.part`` then move it to the final filename.
Args:
event: Watchdog event, either ``watchdog.events.DirMovedEvent`` or
``watchdog.events.FileModifiedEvent``. | codesearchnet |
def add_tensor_filter(self, filter_name, tensor_filter):
self._tensor_filters[filter_name] = tensor_filter | Add a tensor filter.
Args:
filter_name: (`str`) name of the filter.
tensor_filter: (`callable`) the filter callable. See the doc string of
`DebugDumpDir.find()` for more details about its signature. | github-repos |
def generate_key(action, path_or_id, settings=None, default=" (default)"):
settings = " {}".format(str(sorted(settings.items()))) if settings else default
return "{}: {}{}".format(action.upper(), path_or_id, settings) | generate_key: generate key used for caching
Args:
action (str): how video is being processed (e.g. COMPRESSED or DOWNLOADED)
path_or_id (str): path to video or youtube_id
settings (dict): settings for compression or downloading passed in by user
default (str): if settings are None, default to this extension (avoid over... | juraj-google-style |
def predict_proba(self, a, b, nb_runs=6, nb_jobs=None, gpu=None, idx=0, verbose=None, ttest_threshold=0.01, nb_max_runs=16, train_epochs=1000, test_epochs=1000):
(Nb_jobs, verbose, gpu) = SETTINGS.get_default(('nb_jobs', nb_jobs), ('verbose', verbose), ('gpu', gpu))
x = np.stack([a.ravel(), b.ravel()], 1)
t... | Run multiple times GNN to estimate the causal direction.
Args:
a (np.ndarray): Variable 1
b (np.ndarray): Variable 2
nb_runs (int): number of runs to execute per batch (before testing for significance with t-test).
nb_jobs (int): number of runs to execute in parallel. (Initialized with ``cdt.SETTINGS.NB_JOBS``)
gpu (b... | codesearchnet |
def compute_sub_structure(self, sub_structure, tol=0.001):
total_energy_matrix = self.total_energy_matrix.copy()
def find_match(site):
for test_site in sub_structure:
frac_diff = (abs((np.array(site.frac_coords) - np.array(test_site.frac_coords))) % 1)
frac_diff = [((abs(a) < to... | Gives total ewald energy for an sub structure in the same
lattice. The sub_structure must be a subset of the original
structure, with possible different charges.
Args:
substructure (Structure): Substructure to compute Ewald sum for.
tol (float): Tolerance for site matching in fractional coordinates.
Returns:
Ewald su... | codesearchnet |
def from_conv_part_data(conv_part_data, self_user_id):
user_id = UserID(chat_id=conv_part_data.id.chat_id,
gaia_id=conv_part_data.id.gaia_id)
return User(user_id, conv_part_data.fallback_name, None, None, [],
(self_user_id == user_id) or (self_user_i... | Construct user from ``ConversationParticipantData`` message.
Args:
conv_part_id: ``ConversationParticipantData`` message.
self_user_id (~hangups.user.UserID or None): The ID of the current
user. If ``None``, assume ``conv_part_id`` is the current user.
Returns:
:class:`~hangups.user.User` object. | juraj-google-style |
def record_value(self, value, count=1):
if value < 0:
return False
counts_index = self._counts_index_for(value)
if (counts_index < 0) or (self.counts_len <= counts_index):
return False
self.counts[counts_index] += count
self.total_count += count
... | Record a new value into the histogram
Args:
value: the value to record (must be in the valid range)
count: incremental count (defaults to 1) | juraj-google-style |
def serialize_dtype(o):
if len(o) == 0:
return dict(
_type='np.dtype',
descr=str(o))
return dict(
_type='np.dtype',
descr=o.descr) | Serializes a :obj:`numpy.dtype`.
Args:
o (:obj:`numpy.dtype`): :obj:`dtype` to be serialized.
Returns:
A dictionary that can be passed to :obj:`json.dumps`. | juraj-google-style |
def post(self, path, body, headers=None):
response = requests.post(self._url_for(path), data=json.dumps(body), headers=self._headers(headers))
self._handle_errors(response)
return response | Perform a POST request, providing a body, which will be JSON-encoded.
Args:
path (str): A path that gets appended to ``base_url``.
body (dict): Dictionary that will be JSON-encoded and sent as the body.
Example:
api_client.post('/users', body={'name': 'Billy Jean'})
Returns:
A requests ``Response`` object. | codesearchnet |
def process_node(layer, node_data):
args, kwargs = deserialize_node(node_data, created_layers)
layer(*args, **kwargs) | Reconstruct node by linking to inbound layers
Args:
layer: Layer to process
node_data: List of layer configs | github-repos |
def with_rank_at_most(self, rank):
if self.rank is not None and self.rank > rank:
raise ValueError('Shape %s must have rank at most %d' % (self, rank))
else:
return self | Returns a shape based on `self` with at most the given rank.
Args:
rank: An integer.
Returns:
A shape that is at least as specific as `self` with at most the given
rank.
Raises:
ValueError: If `self` does not represent a shape with at most the given
`rank`. | github-repos |
def calculate_oobatake_dG(seq, temp):
dH = calculate_oobatake_dH(seq, temp)
dS = calculate_oobatake_dS(seq, temp)
dG = dH - (temp + 273.15) * dS
return dG - 563.552 | Get free energy of unfolding (dG) using Oobatake method in units cal/mol.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
temp (float): Temperature in degrees C
Returns:
float: Free energy of unfolding dG (J/mol) | juraj-google-style |
def dump_stats(filename):
res = _dump_impl()
f = open(filename, 'w')
json.dump(res, f, indent=4)
f.close() | Write collected information to file.
Args:
filename: absolute filename | juraj-google-style |
def __init__(self, zoom):
self.zoom = zoom
super().__init__('Zoom angle should be in [0,360] (received {})'
.format(zoom)) | Initialization of instances:
Args:
zoom (int): the invalid zoom level.
Attributes:
zoom (int): the invalid zoom level. | juraj-google-style |
def featurize_row(self, x, y):
x = x.ravel()
y = y.ravel()
b = np.ones(x.shape)
dx = np.cos(np.dot(self.W2, np.vstack((x, b)))).mean(1)
dy = np.cos(np.dot(self.W2, np.vstack((y, b)))).mean(1)
if (sum(dx) > sum(dy)):
return np.hstack((dx, dy, np.cos(np.dot(self.W, np.vstack((x, y, b)))).m... | Projects the causal pair to the RKHS using the sampled kernel approximation.
Args:
x (np.ndarray): Variable 1
y (np.ndarray): Variable 2
Returns:
np.ndarray: projected empirical distributions into a single fixed-size vector. | codesearchnet |
def write_genotypes(self, genotypes):
if self._mode != "w":
raise UnsupportedOperation("not available in 'r' mode")
if self._nb_values is None:
self._nb_values = len(genotypes)
if self._nb_values != len(genotypes):
raise ValueError... | Write genotypes to binary file.
Args:
genotypes (numpy.ndarray): The genotypes to write in the BED file. | juraj-google-style |
def brake_on(self):
data = []
data.append(10)
data.append(self.servoid)
data.append(RAM_WRITE_REQ)
data.append(TORQUE_CONTROL_RAM)
data.append(1)
data.append(64)
send_data(data) | Set the Brakes of Herkulex
In braked mode, position control and velocity control
will not work, enable torque before that
Args:
none | codesearchnet |
def from_json(cls, data):
assert 'header' in data, 'Required keyword "header" is missing!'
assert 'values' in data, 'Required keyword "values" is missing!'
return cls(Header.from_json(data['header']), data['values']) | Create a Data Collection from a dictionary.
Args:
{
"header": A Ladybug Header,
"values": An array of values,
} | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.