code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def sign(check_request): if (not isinstance(check_request, sc_messages.CheckRequest)): raise ValueError(u'Invalid request') op = check_request.operation if ((op is None) or (op.operationName is None) or (op.consumerId is None)): logging.error(u'Bad %s: not initialized => not signed', check_r...
Obtains a signature for an operation in a `CheckRequest` Args: op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an operation used in a `CheckRequest` Returns: string: a secure hash generated from the operation
codesearchnet
def LineWrap(text, omit_sgr=False): def _SplitWithSgr(text_line): token_list = sgr_re.split(text_line) text_line_list = [] line_length = 0 for (index, token) in enumerate(token_list): if token is '': continue if sgr_re.match(token): text_line_list....
Break line to fit screen width, factoring in ANSI/SGR escape sequences. Args: text: String to line wrap. omit_sgr: Bool, to omit counting ANSI/SGR sequences in the length. Returns: Text with additional line wraps inserted for lines grater than the width.
juraj-google-style
async def _on_state_update(self, state_update): notification_type = state_update.WhichOneof('state_update') if state_update.HasField('conversation'): try: await self._handle_conversation_delta( state_update.con...
Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance
juraj-google-style
def cmd_ssh_user(tar_aminame, inst_name): if tar_aminame == "Unknown": tar_aminame = inst_name userlu = {"ubunt": "ubuntu", "debia": "admin", "fedor": "root", "cento": "centos", "openb": "root"} usertemp = ['name'] + [value for key, value in list(userlu.items()) ...
Calculate instance login-username based on image-name. Args: tar_aminame (str): name of the image instance created with. inst_name (str): name of the instance. Returns: username (str): name for ssh based on AMI-name.
juraj-google-style
def get_users(self, capacity=None): users = list() usersdicts = self.data.get('users') if (usersdicts is not None): for userdata in usersdicts: if ((capacity is not None) and (userdata['capacity'] != capacity)): continue id = userdata.get('id') if ...
Returns the organization's users. Args: capacity (Optional[str]): Filter by capacity eg. member, admin. Defaults to None. Returns: List[User]: Organization's users.
codesearchnet
def to_text_diagram( self, *, use_unicode_characters: bool = True, transpose: bool = False, precision: Optional[int] = 3, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT) -> str: diagram = self.to_text_diagram_drawer( ...
Returns text containing a diagram describing the circuit. Args: use_unicode_characters: Determines if unicode characters are allowed (as opposed to ascii-only diagrams). transpose: Arranges qubit wires vertically instead of horizontally. precision: Number of digits to display in text diagram qubit_order: Determines ho...
juraj-google-style
def _PrintStorageInformationAsText(self, storage_reader): table_view = views.ViewsFactory.GetTableView(self._views_format_type, title='Plaso Storage Information') table_view.AddRow(['Filename', os.path.basename(self._storage_file_path)]) table_view.AddRow(['Format version', storage_reader.format_version]) ...
Prints information about the store as human-readable text. Args: storage_reader (StorageReader): storage reader.
codesearchnet
def PyParseIntCast(string, location, tokens): for (index, token) in enumerate(tokens): try: tokens[index] = int(token) except ValueError: logger.error('Unable to cast [{0:s}] to an int, setting to 0'.format(token)) tokens[index] = 0 for key in tokens.keys(): ...
Return an integer from a string. This is a pyparsing callback method that converts the matched string into an integer. The method modifies the content of the tokens list and converts them all to an integer value. Args: string (str): original string. location (int): location in the string where the match was made. to...
codesearchnet
def create_header(cls, request_id=None): header = {'msgid': bkserial.make_id(), 'msgtype': cls.msgtype} if (request_id is not None): header['reqid'] = request_id return header
Return a message header fragment dict. Args: request_id (str or None) : Message ID of the message this message replies to Returns: dict : a message header
codesearchnet
def recipe_bigquery_storage(config, auth_read, bucket, auth_write, path, dataset, table, schema): bigquery(config, {'auth': auth_read, 'from': {'bucket': bucket, 'path': path}, 'to': {'auth': auth_write, 'dataset': dataset, 'table': table}, 'schema': schema})
Move using bucket and path prefix. Args: auth_read (authentication) - Credentials used for reading data. bucket (string) - Google cloud bucket. auth_write (authentication) - Credentials used for writing data. path (string) - Path prefix to read from, no * required. dataset (string) - Existing BigQuery dataset. table (...
github-repos
def MeshViewers( shape=(1, 1), titlebar="Mesh Viewers", keepalive=False, window_width=1280, window_height=960 ): if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=shape, titlebar=titlebar, uid=None, keepalive=keepalive, window_width=window_width, w...
Allows subplot-style inspection of primitives in multiple subwindows. Args: shape: a tuple indicating the number of vertical and horizontal windows requested Returns: a list of lists of MeshViewer objects: one per window requested.
juraj-google-style
def standard_to_absl(level): if (not isinstance(level, int)): raise TypeError('Expect an int level, found {}'.format(type(level))) if (level < 0): level = 0 if (level < STANDARD_DEBUG): return ((STANDARD_DEBUG - level) + 1) elif (level < STANDARD_INFO): return ABSL_DEBUG ...
Converts an integer level from the standard value to the absl value. Args: level: int, a Python standard logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in absl logging.
codesearchnet
def get_help_datapacks(module_name, server_prefix): _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) module_dir = '{}/../{}'.format(_dir, module_name, '_help.json') if os.path.isdir(module_dir): module_help_path = '{}/{}'.format(module_dir, '_help.json') if os.pa...
Get the help datapacks for a module Args: module_name (str): The module to get help data for server_prefix (str): The command prefix for this server Returns: datapacks (list): The help datapacks for the module
codesearchnet
def export(self, filename, offset=0, length=None): self.__validate_offset(filename=filename, offset=offset, length=length) with open(filename, 'w') as f: if length is None: length = len(self.data) - offset if offset > 0: output = self.da...
Exports byte array to specified destination Args: filename (str): destination to output file offset (int): byte offset (default: 0)
juraj-google-style
def _compute_diff(left: pg.DNA, right: pg.DNA) -> Tuple[int, int, int]: if left.value == right.value: assert len(left.children) == len(right.children) n = 0 if left.value is None else 1 w = 0 d = 0 for c1, c2 in zip(left.children, right.children): cn, cw, cd = _co...
Compute different positions in two DNAs. Args: left: the first DNA to compare. right: the right DNA to compare. Returns: A tuple of (N, W, D). 'N' is the total number of components in the larger DNA, 'W' is the number of matching genes with different values, and 'D' is the number of disjoint genes. PyGlove DNAs have ...
github-repos
def vgg11_bn(pretrained=False, **kwargs): if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn'])) return model
VGG 11-layer model (configuration "A") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
juraj-google-style
def refresh(self, refresh_binary=True): updated_self = self.repo.get_resource(self.uri) if not isinstance(self, type(updated_self)): raise Exception('Instantiated %s, but repository reports this resource is %s' % (type(updated_self), type(self)) ) if updated_self: self.status_code = updated_s...
Performs GET request and refreshes RDF information for resource. Args: None Returns: None
juraj-google-style
def get_data_node(self, path: DataPath) -> Optional[DataNode]: addr = self.schema_data.path2route(path) node = self.schema for p in addr: node = node.get_data_child(*p) if (node is None): return None return node
Return the data node addressed by a data path. Args: path: Data path. Returns: Data node if found in the schema, or ``None``. Raises: InvalidSchemaPath: If the schema path is invalid.
codesearchnet
def convert_to_numpy(x): if any_symbolic_tensors((x,)): return np.array(x) return backend.convert_to_numpy(x)
Convert a tensor to a NumPy array. Args: x: A tensor. Returns: A NumPy array.
github-repos
def _process_arguments(arguments): if (arguments is None): return '' result = '' for (key, value) in arguments.items(): if (not key.startswith('bokeh-')): result += '&{}={}'.format(quote_plus(str(key)), quote_plus(str(value))) return result
Return user-supplied HTML arguments to add to a Bokeh server URL. Args: arguments (dict[str, object]) : Key/value pairs to add to the URL Returns: str
codesearchnet
def serialize_many_sparse_v2(sp_input, out_type=dtypes.string, name=None): sp_input = _convert_to_sparse_tensor(sp_input) return gen_sparse_ops.serialize_many_sparse(sp_input.indices, sp_input.values, sp_input.dense_shape, name=name, out_type=out_type)
Serialize `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor`. The `SparseTensor` must have rank `R` greater than 1, and the first dimension is treated as the minibatch dimension. Elements of the `SparseTensor` must be sorted in increasing order of this first dimension. The serialized `SparseTensor` objects going...
github-repos
def __frontend_limit_rules_descriptor(self, api_info): if (not api_info.frontend_limits.rules): return None rules = [] for rule in api_info.frontend_limits.rules: descriptor = {} for (propname, descname) in (('match', 'match'), ('qps', 'qps'), ('user_qps', 'userQps'), ('daily', 'dail...
Builds a frontend limit rules descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A list of dictionaries with frontend limit rules information.
codesearchnet
def __init__(self, loc, scale, validate_args=False, allow_nan_stats=True, name='Laplace'): parameters = dict(locals()) with ops.name_scope(name, values=[loc, scale]) as name: with ops.control_dependencies([check_ops.assert_positive(scale)] if validate_args else []): self._loc = array_ops.ide...
Construct Laplace distribution with parameters `loc` and `scale`. The parameters `loc` and `scale` must be shaped in a way that supports broadcasting (e.g., `loc / scale` is a valid operation). Args: loc: Floating point tensor which characterizes the location (center) of the distribution. scale: Positive floating poi...
github-repos
def get_filetypes_info(editor_quote='`', flag_leaf=True): NONE_REPL = '' import f311 data = [] for attr in f311.classes_file(flag_leaf): description = a99.get_obj_doc0(attr) def_ = (NONE_REPL if (attr.default_filename is None) else attr.default_filename) ee = attr.editors ...
Reports available data types Args: editor_quote: character to enclose the name of the editor script between. flag_leaf: see tabulate_filetypes_rest() Returns: list: list of FileTypeInfo
codesearchnet
def cancel_id(cls, id): conn = Qubole.agent() data = {"status": "kill"} return conn.put(cls.element_path(id), data)
Cancels command denoted by this id Args: `id`: command id
juraj-google-style
def _Open(self, path_spec, mode='rb'): if not path_spec.HasParent(): raise errors.PathSpecError( 'Unsupported path specification without parent.') file_object = resolver.Resolver.OpenFileObject( path_spec.parent, resolver_context=self._resolver_context) cpio_archive_file = cpi...
Opens the file system defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was denied. IOError: if the file system could not be opened. PathSpecE...
juraj-google-style
def find_resistance(record): for feature in record.features: labels = set(feature.qualifiers.get("label", [])) cassettes = labels.intersection(_ANTIBIOTICS) if len(cassettes) > 1: raise RuntimeError("multiple resistance cassettes detected") elif len(cassettes) == 1: ...
Infer the antibiotics resistance of the given record. Arguments: record (`~Bio.SeqRecord.SeqRecord`): an annotated sequence. Raises: RuntimeError: when there's not exactly one resistance cassette.
juraj-google-style
def read_from_bigquery(*, table: Optional[str]=None, query: Optional[str]=None, row_restriction: Optional[str]=None, fields: Optional[Iterable[str]]=None): if query is None: assert table is not None else: assert table is None and row_restriction is None and (fields is None) return ReadFromBi...
Reads data from BigQuery. Exactly one of table or query must be set. If query is set, neither row_restriction nor fields should be set. Args: table (str): The table to read from, specified as `DATASET.TABLE` or `PROJECT:DATASET.TABLE`. query (str): A query to be used instead of the table argument. row_restriction (st...
github-repos
def ParseFileObject(self, parser_mediator, file_object): display_name = parser_mediator.GetDisplayName() self.ParseFileLNKFile(parser_mediator, file_object, display_name)
Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
juraj-google-style
def add(self, *value): flattenedValueList = list(flatten(value)) return self._add(flattenedValueList, self.value)
convert value and add to self.value Subclass must overwrite this method. Subclass are responsible of creating whatever single instance it need from its ``add(*value)`` and call ``_add()`` to add them to ``self.value`` Args: *value: the value to be added
codesearchnet
def _UploadChunk(self, chunk): blob = _CompressedDataBlob(chunk) self._action.ChargeBytesToSession(len(chunk.data)) self._action.SendReply(blob, session_id=self._TRANSFER_STORE_SESSION_ID) return rdf_client_fs.BlobImageChunkDescriptor( digest=hashlib.sha256(chunk.data).digest(), o...
Uploads a single chunk to the transfer store flow. Args: chunk: A chunk to upload. Returns: A `BlobImageChunkDescriptor` object.
juraj-google-style
def set_syslog_server(server=None, type="primary"): if not server: raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.") if type == "primary": dn = "sys/svc-ext/syslog/client-primary" inconfig = .format(server) elif type == "secondary": dn...
Set the SYSLOG server on the host. Args: server(str): The hostname or IP address of the SYSLOG server. type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary. CLI Example: .. code-block:: bash salt '*' cimc.set_syslog_server foo.bar.com salt '*' cimc.set_syslog_server fo...
juraj-google-style
def _build_http_client(cls, session: AppSession): stream_factory = functools.partial(HTTPStream, ignore_length=session.args.ignore_length, keep_alive=session.args.http_keep_alive) return session.factory.new('HTTPClient', connection_pool=session.factory['ConnectionPool'], stream_factory=stream_factory)
Create the HTTP client. Returns: Client: An instance of :class:`.http.Client`.
codesearchnet
def counter(urn: str, labels: Optional[Dict[str, str]]=None, process_wide: bool=False) -> UserMetrics.DelegatingCounter: return UserMetrics.DelegatingCounter(MetricName(namespace=None, name=None, urn=urn, labels=labels), process_wide=process_wide)
Obtains or creates a Counter metric. Args: namespace: A class or string that gives the namespace to a metric name: A string that gives a unique name to a metric urn: URN to populate on a MonitoringInfo, when sending to RunnerHarness. labels: Labels to populate on a MonitoringInfo process_wide: Whether or not the metri...
github-repos
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = hidden_states.view(self.num_experts, -1, self.hidden_size) gate_up = torch.bmm(hidden_states, self.gate_up_proj) gate, up = gate_up.chunk(2, dim=-1) next_states = torch.bmm(up * self.act_fn(gate), self.down_proj) next_st...
This should really not be run on a single machine, as we are reaching compute bound: - the inputs are expected to be "sorted" per expert already. - the weights are viewed with another dim, to match num_expert, 1, shape * num_tokens, shape Args: hidden_states (torch.Tensor): (batch_size * token_num, hidden_size) select...
github-repos
def _sym_inferred(self, key: str, **kwargs): if key not in self._sym_attributes: raise AttributeError(key) v = pg_utils.contextual.get_scoped_value(self._contextual_overrides, key) if v is not None: return v.value override = pg_utils.contextual.get_contextual_override(key) if overrid...
Override to allow attribute to access scoped value. Args: key: attribute name. **kwargs: Optional keyword arguments for value inference. Returns: The value of the symbolic attribute. If not available, returns the default value. Raises: AttributeError: If the attribute does not exist or contextual attribute is not re...
github-repos
def list_container_services(access_token, subscription_id, resource_group): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerService/ContainerServ...
List the container services in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON model.
juraj-google-style
def load_manual_sequence(self, seq, ident=None, write_fasta_file=False, outdir=None, set_as_representative=False, force_rewrite=False): if write_fasta_file: if (not outdir): outdir = self.sequence_dir if (not outdir): raise ValueError('Output directory must be specifi...
Load a manual sequence given as a string and optionally set it as the representative sequence. Also store it in the sequences attribute. Args: seq (str, Seq, SeqRecord): Sequence string, Biopython Seq or SeqRecord object ident (str): Optional identifier for the sequence, required if seq is a string. Also will override...
codesearchnet
def is_finite(val_1, val_2=None): val_1_finite = (tf.math.is_finite(val_1.f) & tf.math.is_finite(val_1.df)) if (val_2 is not None): return ((val_1_finite & tf.math.is_finite(val_2.f)) & tf.math.is_finite(val_2.df)) return val_1_finite
Checks if the supplied values are finite. Args: val_1: A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations. val_2: (Optional) A namedtuple instance with the function value and derivative, as returned e.g. by value_and_gradients_function evaluations...
codesearchnet
def load_variable(ckpt_dir_or_file, name): if name.endswith(':0'): name = name[:-2] reader = load_checkpoint(ckpt_dir_or_file) return reader.get_tensor(name)
Returns the tensor value of the given variable in the checkpoint. When the variable name is unknown, you can use `tf.train.list_variables` to inspect all the variable names. Example usage: ```python import tensorflow as tf a = tf.Variable(1.0) b = tf.Variable(2.0) ckpt = tf.train.Checkpoint(var_list={'a': a, 'b': b}...
github-repos
def send(self, data_to_send): request_payload = json.dumps([ a.write() for a in data_to_send ]) request = HTTPClient.Request(self._service_endpoint_uri, bytearray(request_payload, 'utf-8'), { 'Accept': 'application/json', 'Content-Type' : 'application/json; charset=utf-8' }) try: ...
Immediately sends the data passed in to :func:`service_endpoint_uri`. If the service request fails, the passed in items are pushed back to the :func:`queue`. Args: data_to_send (Array): an array of :class:`contracts.Envelope` objects to send to the service.
juraj-google-style
def get_text_config(self, decoder=False) -> 'PretrainedConfig': decoder_possible_text_config_names = ('decoder', 'generator', 'text_config') encoder_possible_text_config_names = ('text_encoder',) if decoder: possible_text_config_names = decoder_possible_text_config_names else: possible_t...
Returns the config that is meant to be used with text IO. On most models, it is the original config instance itself. On specific composite models, it is under a set of valid names. Args: decoder (`Optional[bool]`, *optional*, defaults to `False`): If set to `True`, then only search for decoder config names.
github-repos
def create_list(self, list_json): return trolly.list.List(trello_client=self, list_id=list_json['id'], name=list_json['name'], data=list_json)
Create List object from JSON object Returns: List: The list from the given `list_json`.
codesearchnet
def view_edit(name=None): response.set_header('Cache-control', 'no-cache') response.set_header('Pragma', 'no-cache') if (name is None): return template('edit', type='edit', name=name, extended_name=None, is_repo=check_repo(), history=[], gitref=None, today=datetime.datetime.now().strftime('%Y%m%d'),...
Edit or creates a new page. .. note:: this is a bottle view if no page name is given, creates a new page. Keyword Arguments: :name: (str) -- name of the page (OPTIONAL) Returns: bottle response object
codesearchnet
def normalize_expression(self, expression_parts): expression_parts[3] = expression_parts[3].replace("?", "*") expression_parts[5] = expression_parts[5].replace("?", "*") if expression_parts[0].startswith("0/"): expression_parts[0] = expression_parts[ ...
Converts cron expression components into consistent, predictable formats. Args: expression_parts: A 7 part string array, one part for each component of the cron expression Returns: None
juraj-google-style
def execute(command, cwd=os.path.curdir, **options): process = subprocess.Popen(shlex.split(command), cwd=cwd, **options) stdout, stderr = process.communicate() return process, stdout, stderr
Run the system command with optional options. Args: * command: system command. * cwd: current working directory. * verbose: direct options for :func:`subprocess.Popen`. Returns: Opened process, standard output & error.
juraj-google-style
async def upload_artifacts(context, files): def to_upload_future(target_path): path = os.path.join(context.config['artifact_dir'], target_path) (content_type, content_encoding) = compress_artifact_if_supported(path) return asyncio.ensure_future(retry_create_artifact(context, path, target_pa...
Compress and upload the requested files from ``artifact_dir``, preserving relative paths. Compression only occurs with files known to be supported. This function expects the directory structure in ``artifact_dir`` to remain the same. So if we want the files in ``public/...``, create an ``artifact_dir/public`` and pu...
codesearchnet
def add_vtep(self, name, vtep, vlan=None): if not vlan: cmd = 'vxlan flood vtep add {}'.format(vtep) else: cmd = 'vxlan vlan {} flood vtep add {}'.format(vlan, vtep) return self.configure_interface(name, cmd)
Adds a new VTEP endpoint to the global or local flood list EosVersion: 4.13.7M Args: name (str): The name of the interface to configure vtep (str): The IP address of the remote VTEP endpoint to add vlan (str): The VLAN ID associated with this VTEP. If the VLAN keyword is used, then the VTEP is configured as a local ...
juraj-google-style
def _document_path(self): if (self._document_path_internal is None): if (self._client is None): raise ValueError('A document reference requires a `client`.') self._document_path_internal = _get_document_path(self._client, self._path) return self._document_path_internal
Create and cache the full path for this document. Of the form: ``projects/{project_id}/databases/{database_id}/... documents/{document_path}`` Returns: str: The full document path. Raises: ValueError: If the current document reference has no ``client``.
codesearchnet
def get(self, resource): return self.service.get( resource, self.url_prefix, self.auth, self.session, self.session_send_opts)
Get attributes of the data model object named by the given resource. Args: resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed. Returns: (intern.resource.boss.BossResource): Returns resource of type requested on success. Raises: requests.HTTPError on failu...
juraj-google-style
def make_tables(grammar, precedence): ACTION = {} GOTO = {} labels = {} def get_label(closure): if (closure not in labels): labels[closure] = len(labels) return labels[closure] def resolve_shift_reduce(lookahead, s_action, r_action): (s_assoc, s_level) = precede...
Generates the ACTION and GOTO tables for the grammar. Returns: action - dict[state][lookahead] = (action, ...) goto - dict[state][just_reduced] = new_state
codesearchnet
def VerifyStructure(self, parser_mediator, line): try: structure = self._LOG_LINE.parseString(line) except pyparsing.ParseException: logger.debug('Not a Sophos Anti-Virus log file') return False if ' ' not in (line[8], line[15]): logger.debug('Not a Sophos Anti-Virus log f...
Verify that this file is a Sophos Anti-Virus log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. line (str): line from a text file. Returns: bool: True if the line is in the expected format, False if not.
juraj-google-style
def from_concrete_function(concrete_fn, specialized_flat_specs: Optional[List[tensor_spec.TensorSpec]]=None): context.ensure_initialized() fn_name = concrete_fn.name filtered_flat_specs = specialized_flat_specs or list(nest.flatten(concrete_fn.structured_input_signature)) if not all((s.shape.is_fully_de...
Generate the Compiler Ir from tf concrete function with TensorSpec. Args: concrete_fn: returned by using get_concrete_function. specialized_flat_specs: specialized flat tf.TensorSpecs for function args. Returns: Function callable that generate the HLO text. Raises: ValueError: if concrete_fn is not "compilable" with...
github-repos
def artifact(self, counter, stage, job, stage_counter=1): return Artifact(self.server, self.name, counter, stage, job, stage_counter)
Helper to instantiate an :class:`gocd.api.artifact.Artifact` object Args: counter (int): The pipeline counter to get the artifact for stage: Stage name job: Job name stage_counter: Defaults to 1 Returns: Artifact: :class:`gocd.api.artifact.Artifact` object
juraj-google-style
def _GetUnifiedDiff(before, after, filename='code'): before = before.splitlines() after = after.splitlines() return '\n'.join(difflib.unified_diff(before, after, filename, filename, '(original)', '(reformatted)', lineterm='')) + '\n'
Get a unified diff of the changes. Arguments: before: (unicode) The original source code. after: (unicode) The reformatted source code. filename: (unicode) The code's filename. Returns: The unified diff text.
github-repos
def flatten(array: _ArrayT, pattern: str) -> tuple[_ArrayT, _Shape]: array, (batch_shape,) = einops.pack([array], pattern.replace('...', '*')) return (array, tuple(batch_shape))
Flatten an array along custom dimensions. Uses `einops` syntax. ```python flat_x, batch_shape = enp.flatten(x, '... h w c') y = enp.unflatten(y, batch_shape, '... h w c') ``` * `x.shape == (h, w, c)` -> `flat_x.shape == (1, h, w, c)` * `x.shape == (b, h, w, c)` -> `flat_x.shape == (b, h, w, c)` * `x.shape =...
github-repos
def _update_flags(compiler_flags, remove_flags=()): for flag in GFORTRAN_SHARED_FLAGS: if flag not in compiler_flags: compiler_flags.append(flag) if DEBUG_ENV in os.environ: to_add = GFORTRAN_DEBUG_FLAGS to_remove = GFORTRAN_OPTIMIZE_FLAGS else: to_add = GFOR...
Update a given set of compiler flags. Args: compiler_flags (List[str]): Existing flags associated with a compiler. remove_flags (Optional[Container[str]]): A container of flags to remove that will override any of the defaults. Returns: List[str]: The modified list (i.e. some flags added and some removed).
juraj-google-style
def target_code_to_name(code): TARGET_NAMES = {v: k for k, v in TARGET_CODES.items()} return TARGET_NAMES[code]
Converts an int target code to a target name Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup to get the more readable name. Args: code: Value from self.TARGET_CODES Returns: String target name corresponding to the given code.
juraj-google-style
def delete_customer(self, customer_id): return self.client._delete((self.url + 'customers/{}'.format(customer_id)), headers=self.get_headers())
Removes a user from the system. Args: customer_id: Identifier of the client to be deleted. Returns:
codesearchnet
def _convert_schemas(mapping, schemas): schemas = deepcopy(schemas) for schema in schemas: for fk in schema.get('foreignKeys', []): resource = fk['reference']['resource'] if (resource != 'self'): if (resource not in mapping): message = 'Not res...
Convert schemas to be compatible with storage schemas. Foreign keys related operations. Args: mapping (dict): mapping between resource name and table name schemas (list): schemas Raises: ValueError: if there is no resource for some foreign key in given mapping Returns: list: converted schemas
codesearchnet
def subscribe(self, subject, callback, queue=''): s = Subscription( sid=self._next_sid, subject=subject, queue=queue, callback=callback, connetion=self ) self._subscriptions[s.sid] = s self._send('SUB %s %s %d' % (s.su...
Subscribe will express interest in the given subject. The subject can have wildcards (partial:*, full:>). Messages will be delivered to the associated callback. Args: subject (string): a string with the subject callback (function): callback to be called
juraj-google-style
def to_dict(cls): return dict(((item.name, item.number) for item in iter(cls)))
Make dictionary version of enumerated class. Dictionary created this way can be used with def_num. Returns: A dict (name) -> number
codesearchnet
def __call__(self, *args: Union[str, 'Image.Image', List['Image.Image'], List[str]], **kwargs: Any) -> List[Any]: return super().__call__(*args, **kwargs)
Extract the features of the input(s). Args: images (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`): The pipeline handles three types of images: - A string containing a http link pointing to an image - A string containing a local path to an image - An image loaded in PIL directly The pipeline accepts either a ...
github-repos
def remove(path, dir_fd=None): system = get_instance(path) if (system.is_locator(path) or (path[(- 1)] == '/')): raise is_a_directory_error(("Is a directory: '%s'" % path)) system.remove(path)
Remove a file. Equivalent to "os.remove" and "os.unlink". Args: path (path-like object): Path or URL. dir_fd: directory descriptors; see the os.remove() description for how it is interpreted. Not supported on cloud storage objects.
codesearchnet
def pop(self, name, defval=None): valu = self.info.pop(name, defval) lkey = self.pref + name.encode('utf8') self.slab.pop(lkey, db=self.db) return valu
Pop a name from the SlabDict. Args: name (str): The name to remove. defval (obj): The default value to return if the name is not present. Returns: object: The object stored in the SlabDict, or defval if the object was not present.
juraj-google-style
def validate_session(self, token, remote='127.0.0.1', proxy=None): params = {'validationFactors': [{'name': 'remote_address', 'value': remote}]} if proxy: params['validation-factors']['validationFactors'].append({'name': 'X-Forwarded-For', 'value': proxy}) url = (self.rest_url + ('/session/%s' % tok...
Validate a session token. Validate a previously acquired session token against the Crowd server. This may be a token provided by a user from a http cookie or by some other means. Args: token: The session token. remote: The remote address of the user. proxy: Value of X-Forwarded-For server header Returns: dict: A d...
codesearchnet
def parse_relations( belstr: str, char_locs: CharLocs, parsed: Parsed, errors: Errors ) -> Tuple[Parsed, Errors]: quotes = char_locs["quotes"] quoted_range = set([i for start, end in quotes.items() for i in range(start, end)]) for match in relations_pattern_middle.finditer(belstr): (start,...
Parse relations from BEL string Args: belstr: BEL string as one single string (not list of chars) char_locs: paren, comma and quote char locations parsed: data structure for parsed functions, relations, nested errors: error messages Returns: (parsed, errors):
juraj-google-style
def as_session(name_or_func): if callable(name_or_func): func = name_or_func name = func.__name__ name = "".join([(' ' + x) if x.isupper() else x for x in name]) name = name.replace('_', ' ') return as_session(name)(func) else: name = name_or_func ...
print start/title/end info before and after the function call Args: title: title will show after the start, if has any
juraj-google-style
def _read_git_tags(default_version=DEFAULT_VERSION, git_command=('git', 'tag')): try: current_tags = check_output(git_command).splitlines() except Exception: raise if (not current_tags[0]): warnings.warn('Unable to resolve current version', exceptions.ProsperDefaultVersionWarning) ...
tries to find current git tag Notes: git_command exposed for testing null case Args: default_version (str): what version to make git_command (:obj:`list`): subprocess command Retruns: str: latest version found, or default Warns: exceptions.ProsperDefaultVersionWarning: git version not found
codesearchnet
def save_pkl(filename=None, times=None): if times is None: if not f.root.stopped: times = collapse.collapse_times() else: times = f.root.times else: if isinstance(times, (list, tuple)): for t in times: if not isinstance(t, Times): ...
Serialize and / or save a Times data object using pickle (cPickle). Args: filename (None, optional): Filename to dump to. If not provided, returns serialized object. times (None, optional): object to dump. If non provided, uses current root. Returns: pkl: Pickled Times data object, only if no filename provided. Rai...
juraj-google-style
async def receive(self, timeout: float = None) -> Union[Message, None]: if timeout: coro = self.queue.get() try: msg = await asyncio.wait_for(coro, timeout=timeout) except asyncio.TimeoutError: msg = None else: try:...
Receives a message for this behaviour. If timeout is not None it returns the message or "None" after timeout is done. Args: timeout (float): number of seconds until return Returns: spade.message.Message: a Message or None
juraj-google-style
def transform(self, program: moderngl.Program, buffer: moderngl.Buffer, mode=None, vertices=(- 1), first=0, instances=1): vao = self.instance(program) if (mode is None): mode = self.mode vao.transform(buffer, mode=mode, vertices=vertices, first=first, instances=instances)
Transform vertices. Stores the output in a single buffer. Args: program: The ``moderngl.Program`` buffer: The ``moderngl.buffer`` to store the output Keyword Args: mode: Draw mode (for example ``moderngl.POINTS``) vertices (int): The number of vertices to transform first (int): The index of the first vertex to start ...
codesearchnet
def resolve_lookups(variable, context, provider): resolved_lookups = {} for lookup in variable.lookups: try: handler = LOOKUP_HANDLERS[lookup.type] except KeyError: raise UnknownLookupType(lookup) try: resolved_lookups[lookup] = handler( ...
Resolve a set of lookups. Args: variable (:class:`stacker.variables.Variable`): The variable resolving it's lookups. context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider Returns: dict: dict of Lookup -> resolved value
juraj-google-style
def reduce_by(self, package_request): self.solver.reduction_broad_tests_count += 1 if self.package_request.conflict: return (self, []) (new_slice, reductions) = self.variant_slice.reduce_by(package_request) if (new_slice is None): self.solver.reductions_count += 1 if self.pr: ...
Reduce this scope wrt a package request. Returns: A (_PackageScope, [Reduction]) tuple, where the scope is a new scope copy with reductions applied, or self if there were no reductions, or None if the scope was completely reduced.
codesearchnet
def infer_graph(inputs: Optional[Set[EventSetNode]], outputs: Set[EventSetNode]) -> Graph: graph = Graph() graph.outputs.update(outputs) pending_nodes: Set[EventSetNode] = outputs.copy() done_nodes: Set[EventSetNode] = set() missing_nodes: Set[EventSetNode] = set() while pending_nodes: n...
Extracts the nodes in between the output and input nodes. If inputs is set, fails if outputs cannot be computed from `inputs`. If inputs is not set, infers the required set of inputs. Args: inputs: Set of available input nodes. If None, inputs are inferred. outputs: Set of expected output nodes. Returns: The inferre...
github-repos
def CreateAdGroup(client, campaign_id): ad_group_service = client.GetService('AdGroupService', 'v201809') adgroup = { 'adGroupType': 'SHOPPING_SHOWCASE_ADS', 'campaignId': campaign_id, 'name': 'AdGroup 'biddingStrategyConfiguration': { 'biddingStrategy...
Creates an AdGroup for the given shopping campaign ID. Args: client: an AdWordsClient instance. campaign_id: the str ID of a shopping campaign. Returns: The created AdGroup as a sudsobject.
juraj-google-style
def handle_or_else(self, orelse, test): if isinstance(orelse[0], ast.If): control_flow_node = self.visit(orelse[0]) control_flow_node.test.label = 'el' + control_flow_node.test.label test.connect(control_flow_node.test) return control_flow_n...
Handle the orelse part of an if or try node. Args: orelse(list[Node]) test(Node) Returns: The last nodes of the orelse branch.
juraj-google-style
def _save_model(self, epoch, batch, logs): filepath = self._get_file_path(epoch, batch, logs) try: if self._should_save_model(epoch, batch, logs, filepath): dirname = os.path.dirname(filepath) if dirname and (not file_utils.exists(dirname)): file_utils.makedirs(di...
Saves the model. Args: epoch: the epoch this iteration is in. batch: the batch this iteration is in. `None` if the `save_freq` is set to `"epoch"`. logs: the `logs` dict passed in to `on_batch_end` or `on_epoch_end`.
github-repos
def delete(self): cmd = self.command_builder('ntp source', disable=True) return self.configure(cmd)
Delete the NTP source entry from the node. Returns: True if the operation succeeds, otherwise False.
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. The special tokens depend on calling set_lang. An MBART sequence has the following format, where `X` represents the sequence: - `input_ids` (for encoder) `X [eos, src_lang_code]` - `d...
github-repos
def interconnects(self): if (not self.__interconnects): self.__interconnects = Interconnects(self.__connection) return self.__interconnects
Gets the Interconnects API client. Returns: Interconnects:
codesearchnet
def __init__(self, rate, validate_args=False, allow_nan_stats=True, name='Exponential'): parameters = dict(locals()) with ops.name_scope(name, values=[rate]) as name: self._rate = ops.convert_to_tensor(rate, name='rate') super(Exponential, self).__init__(concentration=array_ops.ones([], dtype=self._...
Construct Exponential distribution with parameter `rate`. Args: rate: Floating point tensor, equivalent to `1 / mean`. Must contain only positive values. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `Fal...
github-repos
def max_neighbor(self, in_lon, in_lat, radius=0.05): out_data = np.zeros((self.data.shape[0], in_lon.shape[0], in_lon.shape[1])) in_tree = cKDTree(np.vstack((in_lat.ravel(), in_lon.ravel())).T) out_indices = np.indices(out_data.shape[1:]) out_rows = out_indices[0].ravel() out_cols = out_indices[1].r...
Finds the largest value within a given radius of a point on the interpolated grid. Args: in_lon: 2D array of longitude values in_lat: 2D array of latitude values radius: radius of influence for largest neighbor search in degrees Returns: Array of interpolated data
codesearchnet
def FileEntryExistsByPathSpec(self, path_spec): store_index = vshadow.VShadowPathSpecGetStoreIndex(path_spec) if store_index is None: location = getattr(path_spec, 'location', None) return location is not None and location == self.LOCATION_ROOT return 0 <= store_index < self._vs...
Determines if a file entry for a path specification exists. Args: path_spec (PathSpec): path specification. Returns: bool: True if the file entry exists.
juraj-google-style
def _create_L_ind(self, L): if issparse(L): L = L.todense() L_ind = np.zeros((self.n, (self.m * self.k))) for y in range(1, (self.k + 1)): L_ind[(:, (y - 1)::self.k)] = np.where((L == y), 1, 0) return L_ind
Convert a label matrix with labels in 0...k to a one-hot format Args: L: An [n,m] scipy.sparse label matrix with values in {0,1,...,k} Returns: L_ind: An [n,m*k] dense np.ndarray with values in {0,1} Note that no column is required for 0 (abstain) labels.
codesearchnet
def __init__(self, context): self.multiplexer = context.multiplexer self.logdir = context.logdir self._handlers = None self.readers = {} self.run_paths = None self._configs = {} self.old_num_run_paths = None self.config_fpaths = None self.tensor_cache = LRUCache(_TENSOR_CACHE_CA...
Instantiates ProjectorPlugin via TensorBoard core. Args: context: A base_plugin.TBContext instance.
juraj-google-style
def _get(self, rec_id=None, upstream=None): if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug('GET {} record with ID {}: {}'.format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify...
Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found.
codesearchnet
def batch(self, timelimit=None): from .launcher import BatchLauncher prev_dir = os.path.join(*self.workdir.split(os.path.sep)[:-1]) prev_dir = os.path.join(os.path.sep, prev_dir) workdir = os.path.join(prev_dir, os.path.basename(self.workdir) + "_batch") return...
Run the flow in batch mode, return exit status of the job script. Requires a manager.yml file and a batch_adapter adapter. Args: timelimit: Time limit (int with seconds or string with time given with the slurm convention: "days-hours:minutes:seconds"). If timelimit is None, the default value specified in the `batch_ad...
juraj-google-style
def UpdateTaskAsPendingMerge(self, task): with self._lock: is_abandoned = (task.identifier in self._tasks_abandoned) is_processing = (task.identifier in self._tasks_processing) is_queued = (task.identifier in self._tasks_queued) if ((not is_queued) and (not is_processing) and (not is...
Updates the task manager to reflect the task is ready to be merged. Args: task (Task): task. Raises: KeyError: if the task was not queued, processing or abandoned, or the task was abandoned and has a retry task.
codesearchnet
def assertDTypeEqual(self, target, expected_dtype): target = self._GetNdArray(target) if not isinstance(target, list): arrays = [target] for arr in arrays: self.assertEqual(arr.dtype, expected_dtype)
Assert ndarray data type is equal to expected. Args: target: The numpy `ndarray`, or anything that can be converted into a numpy `ndarray` (including Tensor). expected_dtype: Expected data type.
github-repos
def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False): if (labels is not None): labels = [(i.id if isinstance(i, _node.Label) else i) for i in labels] return (node for node in self.all() if (((query is None) or ((isinstance(query, six.string_types) an...
Find Notes based on the specified criteria. Args: query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the title and text. func (Union[callable, None]): A filter function. labels (Union[List[str], None]): A list of label ids or objects to match. An empty list matches notes with no l...
codesearchnet
def Collect(self, knowledge_base, artifact_definition, searcher, file_system): for source in artifact_definition.sources: if (source.type_indicator not in (artifact_definitions.TYPE_INDICATOR_FILE, artifact_definitions.TYPE_INDICATOR_PATH)): continue for path in source.paths: ...
Collects values using a file artifact definition. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. artifact_definition (artifacts.ArtifactDefinition): artifact definition. searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess the file system. file_system (dfvfs.FileSystem...
codesearchnet
def belspec_yaml2json(yaml_fn: str, json_fn: str) -> str: try: spec_dict = yaml.load(open(yaml_fn, "r").read(), Loader=yaml.SafeLoader) spec_dict["admin"] = {} spec_dict["admin"]["version_underscored"] = spec_dict["version"].replace(".", "_") spec_dict["admin"]["parse...
Enhance BEL specification and save as JSON file Load all BEL Specification YAML files and convert to JSON files after enhancing them. Also create a bel_versions.json file with all available BEL versions for fast loading. Args: yaml_fn: original YAML version of BEL Spec json_fn: enhanced JSON version of BEL Spec Retu...
juraj-google-style
def map(self, op: Callable[[T], U]) -> 'Union[Result[U, E], Result[T, E]]': return self._type.Ok(op(cast(T, self._val))) if self._is_ok else self
Applies a function to the contained :meth:`Result.Ok` value. Args: op: The function to apply to the :meth:`Result.Ok` value. Returns: A :class:`Result` with its success value as the function result if `self` is an :meth:`Result.Ok` value, otherwise returns `self`. Examples: >>> Ok(1).map(lambda x: x * 2) Ok(2) >>> E...
juraj-google-style
def _sparse_or_dense_matmul_onehot(sparse_or_dense_matrix, col_index): if isinstance(sparse_or_dense_matrix, (tf.SparseTensor, tf.compat.v1.SparseTensorValue)): num_rows = _get_shape(sparse_or_dense_matrix)[-2] batch_shape = _get_shape(sparse_or_dense_matrix)[:-2] slice_start ...
Returns a (dense) column of a Tensor or SparseTensor. Args: sparse_or_dense_matrix: matrix-shaped, `float` `Tensor` or `SparseTensor`. col_index: scalar, `int` `Tensor` representing the index of the desired column. Returns: column: vector-shaped, `float` `Tensor` with the same dtype as `sparse_or_dense_matrix`, repre...
juraj-google-style
def filter_with_theta(image, theta, sigma=1.0, filter_size=9): x = np.arange((((- filter_size) g = np.array([np.exp(((- (x ** 2)) / (2 * (sigma ** 2))))]) gp = np.array([((- (x / sigma)) * np.exp(((- (x ** 2)) / (2 * (sigma ** 2)))))]) ix = convolve2d(image, (- gp), mode='same', boundary='fill', fillva...
Implements a steerable Gaussian filter. This function can be used to evaluate the first directional derivative of an image, using the method outlined in W. T. Freeman and E. H. Adelson, "The Design and Use of Steerable Filters", IEEE PAMI, 1991. It evaluates the directional derivative of the input image I, oriented ...
codesearchnet
def random_line_data(chars_per_line=80): return ''.join(__random.choice(__string.ascii_letters) for x in range(chars_per_line))
Function to create a line of a random string Args: chars_per_line: An integer that says how many characters to return Returns: A String
juraj-google-style
def resolve_image_exif(self, image_url): files = self.mets.find_files(url=image_url) if files: image_filename = self.download_file(files[0]).local_filename else: image_filename = self.download_url(image_url) if image_url not in self.image_cache['exif']: ...
Get the EXIF metadata about an image URL as :class:`OcrdExif` Args: image_url (string) : URL of image Return :class:`OcrdExif`
juraj-google-style
def _convert_tf2_model(flags): if flags.saved_model_dir: converter = lite.TFLiteConverterV2.from_saved_model(flags.saved_model_dir, signature_keys=_parse_array(flags.saved_model_signature_key), tags=_parse_set(flags.saved_model_tag_set)) elif flags.keras_model_file: model = keras_deps.get_load_m...
Calls function to convert the TensorFlow 2.0 model into a TFLite model. Args: flags: argparse.Namespace object. Raises: ValueError: Unsupported file format.
github-repos
def parse_response(service, response, search_type): _LOG.debug('Parse response "%s" from service "%s" of type "%s"', response, service, search_type) items = [] if 'searchResult' in response: response = response['searchResult'] elif 'getMetadataResult' in response: ...
Parse the response to a music service query and return a SearchResult Args: service (MusicService): The music service that produced the response response (OrderedDict): The response from the soap client call search_type (str): A string that indicates the search type that the response is from Returns: SearchResult: A ...
juraj-google-style