code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def validate(cls, mapper_spec): if mapper_spec.input_reader_class() != cls: raise BadReaderParamsError("Input reader class mismatch") params = _get_params(mapper_spec) if cls.ENTITY_KIND_PARAM not in params: raise BadReaderParamsError("Missing mapper parameter 'entity_kind'") if cls.BAT...
Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.
juraj-google-style
def flip_channel_order(self, image: np.ndarray, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray: return flip_channel_order(image, data_format=data_format, input_data_format=input_data_format)
Flip the color channels from RGB to BGR or vice versa. Args: image (`np.ndarray`): The image, represented as a numpy array. data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. input_data_format (`ChannelDimension` or...
github-repos
def infer(self, ob): self._add_to_stack(ob) (logits, vf) = self.infer_from_frame_stack(self._frame_stack) return (logits, vf)
Add new observation to frame stack and infer policy. Args: ob: array of shape (height, width, channels) Returns: logits and vf.
codesearchnet
def get_selected_subassistant_path(self, **kwargs): path = [self] previous_subas_list = None currently_searching = self.get_subassistant_tree()[1] while settings.SUBASSISTANT_N_STRING.format(len(path) - 1) in kwargs and \ kwargs[settings.SUBASSISTANT_N_...
Recursively searches self._tree - has format of (Assistant: [list_of_subassistants]) - for specific path from first to last selected subassistants. Args: kwargs: arguments containing names of the given assistants in form of subassistant_0 = 'name', subassistant_1 = 'another_name', ... Returns: list of subassistants ob...
juraj-google-style
def __rfloordiv__(self, other): other = as_dimension(other) if self._value is None or other.value is None: return Dimension(None) else: return Dimension(other.value
Returns the quotient of `other` and `self` rounded down. Args: other: Another Dimension, or a value accepted by `as_dimension`. Returns: A `Dimension` whose value is the integer quotient of `self` and `other`.
github-repos
def func(self, w, *args): x0 = args[0] x1 = args[1] n0 = x0.shape[0] n1 = x1.shape[0] n = (max(n0, n1) * 10) idx0 = np.random.choice(range(n0), size=n) idx1 = np.random.choice(range(n1), size=n) b0 = np.ones((n0, 1)) b1 = np.ones((n1, 1)) i1 = (self.i + 1) h = self.h h1 =...
Return the costs of the neural network for predictions. Args: w (array of float): weight vectors such that: w[:-h1] -- weights between the input and h layers w[-h1:] -- weights between the h and output layers args: features (args[0]) and target (args[1]) Returns: combined cost of RMSE, L1, and L2 regularization
codesearchnet
def normal_meanvar(data): data = np.hstack(([0.0], np.array(data))) cumm = np.cumsum(data) cumm_sq = np.cumsum([(val ** 2) for val in data]) def cost(s, t): ' Cost function for normal distribution with variable variance\n\n Args:\n start (int): start index\n end (in...
Creates a segment cost function for a time series with a Normal distribution with changing mean and variance Args: data (:obj:`list` of float): 1D time series data Returns: function: Function with signature (int, int) -> float where the first arg is the starting index, and the second is the last arg. Returns the cost ...
codesearchnet
def for_each(self, func): aliases = list(self._service_objects.keys()) for alias in aliases: with expects.expect_no_raises('Failed to execute "%s" for service "%s".' % (func.__name__, alias)): func(self._service_objects[alias])
Executes a function with all registered services. Args: func: function, the function to execute. This function should take a service object as args.
github-repos
def _inject(self, value, settings): assert isinstance(value, string_types), 'Expected str; got {0.__class__}'.format(value) (begin, end) = ('{{', '}}') if (begin not in value): return (value, False) new_value = value (begin_pos, end_pos) = (0, None) (len_begin, len_end) = (len(begin), le...
Inject ``settings`` into ``value``. Go through ``value`` looking for ``{{NAME}}`` groups and replace each group with the value of the named item from ``settings``. Args: value (str): The value to inject settings into settings: An object that provides the dotted access interface Returns: (str, bool): The new value an...
codesearchnet
def interpolate_jagged(xyz,nseg): (r,theta,phi) = sequential_spherical(xyz) rcum = np.append(0,np.cumsum(r)) breakpoints = np.linspace(0,rcum[-1],nseg+1) np.delete(breakpoints,0) seg_paths = [] for a in range(nseg): path = [] ...
Interpolates along a jagged path in 3D Args: xyz = section path specified in cartesian coordinates nseg = number of segment paths in section path Returns: interp_xyz = interpolated path
juraj-google-style
def idxmax(self, **kwargs): if self._is_transposed: kwargs['axis'] = (kwargs.get('axis', 0) ^ 1) return self.transpose().idxmax(**kwargs) axis = kwargs.get('axis', 0) index = (self.index if (axis == 0) else self.columns) def idxmax_builder(df, **kwargs): if (axis == 0): ...
Returns the first occurrence of the maximum over requested axis. Returns: A new QueryCompiler object containing the maximum of each column or axis.
codesearchnet
def contains_vasp_input(dir_name): for f in ["INCAR", "POSCAR", "POTCAR", "KPOINTS"]: if not os.path.exists(os.path.join(dir_name, f)) and \ not os.path.exists(os.path.join(dir_name, f + ".orig")): return False return True
Checks if a directory contains valid VASP input. Args: dir_name: Directory name to check. Returns: True if directory contains all four VASP input files (INCAR, POSCAR, KPOINTS and POTCAR).
juraj-google-style
def tf(): try: from tensorboard.compat import notf except ImportError: try: import tensorflow return tensorflow except ImportError: pass from tensorboard.compat import tensorflow_stub return tensorflow_stub
Provide the root module of a TF-like API for use within TensorBoard. By default this is equivalent to `import tensorflow as tf`, but it can be used in combination with //tensorboard/compat:tensorflow (to fall back to a stub TF API implementation if the real one is not available) or with //tensorboard/compat:no_tensorf...
codesearchnet
def tables_list(self, dataset_name, max_results=0, page_token=None): url = Api._ENDPOINT +\ (Api._TABLES_PATH % (dataset_name.project_id, dataset_name.dataset_id, '', '')) args = {} if max_results != 0: args['maxResults'] = max_results if page_token is not None: args['pageToken...
Issues a request to retrieve a list of tables. Args: dataset_name: the name of the dataset to enumerate. max_results: an optional maximum number of tables to retrieve. page_token: an optional token to continue the retrieval. Returns: A parsed result object. Raises: Exception if there is an error performing the operati...
juraj-google-style
def normal_meanvar(data): data = np.hstack(([0.0], np.array(data))) cumm = np.cumsum(data) cumm_sq = np.cumsum([val**2 for val in data]) def cost(s, t): ts_i = 1.0 / (t-s) mu = (cumm[t] - cumm[s]) * ts_i sig = (cumm_sq[t] - cumm_sq[s]) * ts_i - mu**2 sig_i...
Creates a segment cost function for a time series with a Normal distribution with changing mean and variance Args: data (:obj:`list` of float): 1D time series data Returns: function: Function with signature (int, int) -> float where the first arg is the starting index, and the second is the last arg. Returns the cost ...
juraj-google-style
def timezone(self, timezone=0): tz_dt = timedelta(hours=timezone) for segment in self.segments: for point in segment.points: point.time = (point.time + tz_dt) return self
Sets the timezone of the entire track Args: timezone (int): Timezone hour delta
codesearchnet
def extract(self, url=None, raw_html=None): crawl_candidate = CrawlCandidate(self.config, url, raw_html) return self.__crawl(crawl_candidate)
Extract the most likely article content from the html page Args: url (str): URL to pull and parse raw_html (str): String representation of the HTML page Returns: Article: Representation of the article contents \ including other parsed and extracted metadata
juraj-google-style
def _eligible_features_from_example_handler(self, request): features_list = inference_utils.get_eligible_features( self.examples[0: NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS) return http_util.Respond(request, features_list, 'application/json')
Returns a list of JSON objects for each feature in the example. Args: request: A request for features. Returns: A list with a JSON object for each feature. Numeric features are represented as {name: observedMin: observedMax:}. Categorical features are repesented as {name: samples:[]}.
juraj-google-style
def help(self, print_output=True): help_text = self._rpc('help') if print_output: print(help_text) else: return help_text
Calls the help RPC, which returns the list of RPC calls available. This RPC should normally be used in an interactive console environment where the output should be printed instead of returned. Otherwise, newlines will be escaped, which will make the output difficult to read. Args: print_output: bool, for whether the...
github-repos
def __getitem__(self, key): if key in self._policy_map: return self._policy_map[key] matching_keys = [] for k in self._policy_map: if re.search(k, key): matching_keys.append(k) if len(matching_keys) > 1: raise ValueError(f"Path '{key}' matches multiple dtype policy sp...
Retrieves the corresponding `DTypePolicy` by the string key. When there isn't an exact match, all the existing keys in the map will be treated as a regex and map against the input key again. When there are multiple matches for the regex, an `ValueError` will be raised. Returns `self.default_policy` if there isn't any ...
github-repos
def frequency_to_probability(frequency_map, decorator=lambda f: f): total = sum(frequency_map.values()) return {k: decorator(v / total) for k, v in frequency_map.items()}
Transform a ``frequency_map`` into a map of probability using the sum of all frequencies as the total. Example: >>> frequency_to_probability({'a': 2, 'b': 2}) {'a': 0.5, 'b': 0.5} Args: frequency_map (dict): The dictionary to transform decorator (function): A function to manipulate the probability Returns: Dictionar...
juraj-google-style
def start_new_feature(**cc_kwargs): project = Project.from_path(pathlib.Path.cwd().resolve()) contrib_dir = project.get('contrib', 'module_path') with tempfile.TemporaryDirectory() as tempdir: output_dir = tempdir cc_kwargs['output_dir'] = output_dir rendered_dir = render_feature_tem...
Start a new feature within a ballet project Renders the feature template into a temporary directory, then copies the feature files into the proper path within the contrib directory. Args: **cc_kwargs: options for the cookiecutter template Raises: ballet.exc.BalletError: the new feature has the same name as an existi...
codesearchnet
def set_cc_opt_flags(environ_cp): if is_ppc64le(): default_cc_opt_flags = '-mcpu=native' elif is_windows(): default_cc_opt_flags = '/arch:AVX' else: default_cc_opt_flags = '-Wno-sign-compare' question = 'Please specify optimization flags to use during compilation when bazel optio...
Set up architecture-dependent optimization flags. Also append CC optimization flags to bazel.rc.. Args: environ_cp: copy of the os.environ.
github-repos
def get_actual_replica(self, service_id: str) -> str: if not self._manager: raise RuntimeError('Only the Swarm manager node can retrieve ' 'replication level of the service') service_details = self.get_service_details(service_id) actu...
Get the actual replica level of a service. Args: service_id (str): docker swarm service id Returns: str, replicated level of the service
juraj-google-style
def get_model_class_for_feature(feature: str, framework: str='pt') -> Type: task = FeaturesManager.feature_to_task(feature) FeaturesManager._validate_framework_choice(framework) if framework == 'pt': task_to_automodel = FeaturesManager._TASKS_TO_AUTOMODELS else: task_to_automodel = Featu...
Attempts to retrieve an AutoModel class from a feature name. Args: feature (`str`): The feature required. framework (`str`, *optional*, defaults to `"pt"`): The framework to use for the export. Returns: The AutoModel class corresponding to the feature.
github-repos
def GetOutputDir(self, base_dir, config_filename): return os.path.join(base_dir, os.path.basename(config_filename.replace('.yaml', '')))
Add the repack config filename onto the base output directory. This allows us to repack lots of different configs to the same installer name and still be able to distinguish them. Args: base_dir: output directory string config_filename: the secondary config filename string Returns: String to be used as output direct...
codesearchnet
def SignBuffer(self, in_buffer): precondition.AssertType(in_buffer, bytes) with tempfile.NamedTemporaryFile() as temp_in: temp_in.write(in_buffer) temp_in.seek(0) outfile = self.SignFile(temp_in.name) with io.open(outfile, "rb") as filedesc: return filedesc.read()
Sign a buffer via temp files. Our signing tool can't sign a buffer, so we work around it using temporary files. Args: in_buffer: data to sign Returns: signed data
juraj-google-style
def FlagCxx11Features(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] include = Match(r'\s* if include and include.group(1) in ('cfenv', 'condition_variable', 'fenv.h', ...
Flag those c++11 features that we only allow in certain places. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
juraj-google-style
def _parse_name(self, config): value = NAME_RE.search(config).group('value') return dict(name=value)
_parse_name scans the provided configuration block and extracts the vlan name. The config block is expected to always return the vlan name. The return dict is intended to be merged into the response dict. Args: config (str): The vlan configuration block from the nodes running configuration Returns: dict: resource d...
codesearchnet
def read_probes(self, key): assert key in list(self._PROBES.keys()) import random if key == 'value1': value = random.random() elif key == 'value2': value = self.settings['output probe2'] elif key == 'internal': value = self._internal_...
requestes value from the instrument and returns it Args: key: name of requested value Returns: reads values from instrument
juraj-google-style
def handle_api_explorer_request(self, request, start_response): redirect_url = self._get_explorer_redirect_url( request.server, request.port, request.base_path) return util.send_wsgi_redirect_response(redirect_url, start_response)
Handler for requests to {base_path}/explorer. This calls start_response and returns the response body. Args: request: An ApiRequest, the request from the user. start_response: A function with semantics defined in PEP-333. Returns: A string containing the response body (which is empty, in this case).
juraj-google-style
def list_live_services(self): aliases = [] self.for_each(lambda service: aliases.append(service.alias) if service.is_alive else None) return aliases
Lists the aliases of all the services that are alive. Order of this list is determined by the order the services are registered in. Returns: list of strings, the aliases of the services that are running.
github-repos
def resize_bilinear_nd(t, target_shape): shape = t.get_shape().as_list() target_shape = list(target_shape) assert len(shape) == len(target_shape) d = 0 while d < len(shape): if shape[d] == target_shape[d]: d += 1 continue new_shape = shape[:] new_shape[d : d+2] ...
Bilinear resizes a tensor t to have shape target_shape. This function bilinearly resizes a n-dimensional tensor by iteratively applying tf.image.resize_bilinear (which can only resize 2 dimensions). For bilinear interpolation, the order in which it is applied does not matter. Args: t: tensor to be resized target_shap...
juraj-google-style
def from_backbone_configs(cls, backbone_config: PretrainedConfig, **kwargs): return cls(backbone_config=backbone_config, **kwargs)
Instantiate a [`RTDetrV2Config`] (or a derived class) from a pre-trained backbone model configuration and DETR model configuration. Args: backbone_config ([`PretrainedConfig`]): The backbone configuration. Returns: [`RTDetrV2Config`]: An instance of a configuration object
github-repos
def add_session_log(self, session_log, global_step=None): event = event_pb2.Event(session_log=session_log) self._add_event(event, global_step)
Adds a `SessionLog` protocol buffer to the event file. This method wraps the provided session in an `Event` protocol buffer and adds it to the event file. Args: session_log: A `SessionLog` protocol buffer. global_step: Number. Optional global step value to record with the summary.
github-repos
def post_warning(self, name, message): self.post_command(OPERATIONS.CMD_POST_MESSAGE, _create_message(name, states.WARNING_LEVEL, message))
Asynchronously post a user facing warning message about a service. Args: name (string): The name of the service message (string): The user facing warning message that will be stored for the service and can be queried later.
juraj-google-style
def _readline(sock, buf): chunks = [] last_char = b'' while True: if ((last_char == b'\r') and (buf[0:1] == b'\n')): chunks[(- 1)] = chunks[(- 1)][:(- 1)] return (buf[1:], b''.join(chunks)) elif (buf.find(b'\r\n') != (- 1)): (before, sep, after) = buf.part...
Read line of text from the socket. Read a line of text (delimited by "\r\n") from the socket, and return that line along with any trailing characters read from the socket. Args: sock: Socket object, should be connected. buf: String, zero or more characters, returned from an earlier call to _readline or _readvalue (pa...
codesearchnet
def update_sub(x, decrement): return state_ops.assign_sub(x, decrement)
Update the value of `x` by subtracting `decrement`. Args: x: A Variable. decrement: A tensor of same shape as `x`. Returns: The variable `x` updated.
github-repos
class HungarianMatcher(nn.Module): def __init__(self, class_cost: float=1, bbox_cost: float=1, giou_cost: float=1): super().__init__() requires_backends(self, ['scipy']) self.class_cost = class_cost self.bbox_cost = bbox_cost self.giou_cost = giou_cost if class_cost ...
This class computes an assignment between the targets and the predictions of the network. For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are un-matched...
github-repos
def ParsePageVisitRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) was_http_non_get = self._GetRowValue(query_hash, row, 'http_non_get') event_data = SafariHistoryPageVisitedEventData() event_data.offset = self._GetRowValue(query_hash, row, 'id') event_data.que...
Parses a visited row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row.
juraj-google-style
def get_shape(self) -> tensor_shape.TensorShape: return self.shape
The statically known shape of this ragged tensor. Returns: A `TensorShape` containing the statically known shape of this ragged tensor. Ragged dimensions have a size of `None`. Alias for `shape` property. Examples: >>> tf.ragged.constant([[0], [1, 2]]).get_shape() TensorShape([2, None]) >>> tf.ragged.constant( .....
github-repos
def get_file_path(self, digest): relPath = Fsdb.generate_tree_path(digest, self._conf['depth']) return os.path.join(self.fsdbRoot, relPath)
Retrieve the absolute path to the file with the given digest Args: digest -- digest of the file Returns: String rapresenting the absolute path of the file
juraj-google-style
def __init__(self, thunk): self._thunk = thunk self._master_tensor = thunk()
Initializes a _LazyEvalTensor object. Args: thunk: A callable. A thunk which computes the value of the tensor.
github-repos
def take_while(predicate): def _apply_fn(dataset): return dataset.take_while(predicate=predicate) return _apply_fn
A transformation that stops dataset iteration based on a `predicate`. Args: predicate: A function that maps a nested structure of tensors (having shapes and types defined by `self.output_shapes` and `self.output_types`) to a scalar `tf.bool` tensor. Returns: A `Dataset` transformation function, which can be passed to...
github-repos
def bandit(self, choice_rewards): return max(choice_rewards, key=(lambda a: np.mean(choice_rewards[a])))
Return the choice to take next using multi-armed bandit Multi-armed bandit method. Accepts a mapping of choices to rewards which indicate their historical performance, and returns the choice that we should make next in order to maximize expected reward in the long term. The default implementation is to return the arm...
codesearchnet
def color_val(color): if is_str(color): return Color[color].value elif isinstance(color, Color): return color.value elif isinstance(color, tuple): assert (len(color) == 3) for channel in color: assert ((channel >= 0) and (channel <= 255)) return color ...
Convert various input to color tuples. Args: color (:obj:`Color`/str/tuple/int/ndarray): Color inputs Returns: tuple[int]: A tuple of 3 integers indicating BGR channels.
codesearchnet
def time_travel(self, datetime=None, timedelta=None, seconds=0, minutes=0, hours=0, days=0): if (datetime is not None): self.timedelta = (datetime - python_datetime.now()) if (timedelta is not None): self.timedelta = (self.timedelta + timedelta) self.timedelta = (self.timedelta + python_time...
Mock moving forward or backward in time by shifting the system clock fed to the services tested. Note that all of these arguments can be used together, individually or not at all. The time traveled to will be the sum of all specified time deltas from datetime. If no datetime is specified, the deltas will be added to t...
codesearchnet
def __init__(self, pid_filename): self.stdin_path = '/dev/null' self.stdout_path = '/dev/null' self.stderr_path = '/dev/null' self.pidfile_path = '/tmp/' + pid_filename + '.pid' self.pidfile_timeout = 5 self.daemon_runner = runner.DaemonRunner(self) ...
Generic daemon class, which allows you to daemonize your script and react to events in simple callbacks. Args: pid_filename (str): name of daemon's PID file, which is stored in ``/tmp``. Class automatically adds ``.pid`` suffix.
juraj-google-style
def __init__(self, file_pattern, action_function): super(GeneratorAction, self).__init__() self.__file_pattern = file_pattern self.__action_function = action_function
Container to store an "action". Every file(s) generation is considered as an action. Args: file_pattern: fnmatch pattern. action_function: Callback without argument. See documentation.
juraj-google-style
def validate_resource(resource: message.Message, primitive_handler_: primitive_handler.PrimitiveHandler) -> None: _validate_fhir_constraints(resource, resource.DESCRIPTOR.name, primitive_handler_)
Performs basic FHIR constraint validation on the provided resource. This API works for all supported versions of FHIR, but requires a primitive handler to be passed as an argument. If the FHIR version being used is known ahead of time, version-specific APIs such as `google.fhir.r4 resource_validation` should be used i...
github-repos
def load_hgnc_genes(adapter, genes=None, ensembl_lines=None, hgnc_lines=None, exac_lines=None, mim2gene_lines=None, genemap_lines=None, hpo_lines=None, build='37', omim_api_key=''): gene_objects = list() if (not genes): if (ensembl_lines is None): ensembl_lines = fetch_ensembl_genes(build=bu...
Load genes into the database link_genes will collect information from all the different sources and merge it into a dictionary with hgnc_id as key and gene information as values. Args: adapter(scout.adapter.MongoAdapter) genes(dict): If genes are already parsed ensembl_lines(iterable(str)): Lines formated with ensemb...
codesearchnet
def login_with_password_no_sync(self, username, password): warn("login_with_password_no_sync is deprecated. Use login with sync=False.", DeprecationWarning) return self.login(username, password, sync=False)
Deprecated. Use ``login`` with ``sync=False``. Login to the homeserver. Args: username (str): Account username password (str): Account password Returns: str: Access token Raises: MatrixRequestError
juraj-google-style
def render_diagram(out_base): import codecs import subprocess import sadisplay desc = sadisplay.describe(list(model_registry.values()), show_methods=False, show_properties=True, show_indexes=True) with codecs.open((out_base + '.dot'), 'w', encoding='utf-8') as f: f.write(sadisplay.dot(desc))...
Render a data model diagram Included in the diagram are all classes from the model registry. For your project, write a small script that imports all models that you would like to have included and then calls this function. .. note:: This function requires the 'dot' executable from the GraphViz package to be installed...
codesearchnet
def uses_keras_history(tensors): checked_tensors = set() tensors_to_check = nest.flatten(tensors) while tensors_to_check: new_tensors_to_check = [] for tensor in tensors_to_check: if id(tensor) in checked_tensors: continue checked_tensors.add(id(tensor...
Check if at least one Tensor originates from a `keras.Input`. This is `True` if at least one Tensor has its origin in a `keras.Input`. Any Tensor that originates from a `keras.Input` will have a dependency Tensor with a `_keras_history` attribute attached. Tensors that have already been checked to not originate from a...
github-repos
def get_version(tool_name, tool_command): result = {} for line in Bash(ShellConfig(script=tool_command, internal=True)).process(): if line.find("command not found") >= 0: VersionsCheck.LOGGER.error("Required tool '%s' not found (stopping pipeline)!", tool_name) ...
Get name and version of a tool defined by given command. Args: tool_name (str): name of the tool. tool_command (str): Bash one line command to get the version of the tool. Returns: dict: tool name and version or empty when no line has been found
juraj-google-style
def get(self, request): code = request.GET.get('code') if (not code): return render(request, 'django_auth_adfs/login_failed.html', {'error_message': 'No authorization code was provided.'}, status=400) redirect_to = request.GET.get('state') user = authenticate(request=request, authorization_code=...
Handles the redirect from ADFS to our site. We try to process the passed authorization code and login the user. Args: request (django.http.request.HttpRequest): A Django Request object
codesearchnet
def get_transaction_id(transaction, read_operation=True): if (transaction is None): return None else: if (not transaction.in_progress): raise ValueError(INACTIVE_TXN) if (read_operation and (len(transaction._write_pbs) > 0)): raise ReadAfterWriteError(READ_AFTER_W...
Get the transaction ID from a ``Transaction`` object. Args: transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that this query will run in. read_operation (Optional[bool]): Indicates if the transaction ID will be used in a read operation. Defaults to :data:`True`. Returns: ...
codesearchnet
def run(argv=None, save_main_session=True, test_pipeline=None) -> PipelineResult: known_args, pipeline_args = parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = save_main_session model_loader = KeyedModelHandler(TFModelHand...
Args: argv: Command line arguments defined for this example. save_main_session: Used for internal testing. test_pipeline: Used for internal testing.
github-repos
def get_ip_reports(self, ips): api_name = 'virustotal-ip-address-reports' (all_responses, ips) = self._bulk_cache_lookup(api_name, ips) responses = self._request_reports("ip", ips, 'ip-address/report') for ip, response in zip(ips, responses): if self._cache: ...
Retrieves the most recent VT info for a set of ips. Args: ips: list of IPs. Returns: A dict with the IP as key and the VT report as value.
juraj-google-style
def bridge_list(): cmd = 'ovs-vsctl list-br' result = __salt__['cmd.run_all'](cmd) retcode = result['retcode'] stdout = result['stdout'] return _stdout_list_split(retcode, stdout)
Lists all existing real and fake bridges. Returns: List of bridges (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_list
codesearchnet
def request(self, send_terminator = False): self.m_a_crc = False start_context = self.getContext() self.setContext("request[v3A]") try: self.m_serial_port.write("2f3f".decode("hex") + self.m_meter_address + ...
Required request() override for v3 and standard method to read meter. Args: send_terminator (bool): Send termination string at end of read. Returns: bool: CRC request flag result from most recent read
juraj-google-style
def download_structure_file(self, outdir, file_type=None, load_header_metadata=True, force_rerun=False): ssbio.utils.double_check_attribute(object=self, setter=file_type, backup_attribute='file_type', custom_error_text='Please set file type to be downloaded from the PDB: pdb, mmCif, xml, or mmtf') p = PDBList()...
Download a structure file from the PDB, specifying an output directory and a file type. Optionally download the mmCIF header file and parse data from it to store within this object. Args: outdir (str): Path to output directory file_type (str): ``pdb``, ``mmCif``, ``xml``, ``mmtf`` - file type for files downloaded from...
codesearchnet
class UperNetPyramidPoolingModule(nn.Module): def __init__(self, pool_scales: Tuple[int, ...], in_channels: int, channels: int, align_corners: bool) -> None: super().__init__() self.pool_scales = pool_scales self.align_corners = align_corners self.in_channels = in_channels s...
Pyramid Pooling Module (PPM) used in PSPNet. Args: pool_scales (`Tuple[int]`): Pooling scales used in Pooling Pyramid Module. in_channels (`int`): Input channels. channels (`int`): Channels after modules, before conv_seg. align_corners (`bool`): align_corners argument of F.interpolate.
github-repos
def execute_phase(self, phase): repeat_count = 1 repeat_limit = phase.options.repeat_limit or sys.maxsize while not self._stopping.is_set(): is_last_repeat = repeat_count >= repeat_limit phase_execution_outcome = self._execute_phase_once(phase, is_last_repeat) if phase_execution_outc...
Executes a phase or skips it, yielding PhaseExecutionOutcome instances. Args: phase: Phase to execute. Returns: The final PhaseExecutionOutcome that wraps the phase return value (or exception) of the final phase run. All intermediary results, if any, are REPEAT and handled internally. Returning REPEAT here means the ...
juraj-google-style
def _git_fetch_for_comparison(remote: str, actual_branch: str, compare_branch: str, verbose: bool) -> prepared_env.PreparedEnv: actual_id = '' base_id = '' for depth in [10, 100, 1000, None]: depth_str = ('' if (depth is None) else '--depth={}'.format(depth)) shell_tools.run_cmd('git', 'fetc...
Fetches two branches including their common ancestor. Limits the depth of the fetch to avoid unnecessary work. Scales up the depth exponentially and tries again when the initial guess is not deep enough. Args: remote: The location of the remote repository, in a format that the git command will understand. actual_bran...
codesearchnet
def get(self, webfont_name, webfont_settings): try: webfont_settings = extend_webfont_settings(webfont_settings) except IcomoonSettingsError as e: msg = "Invalid webfont settings for '{}': {}" self.errors[webfont_name] = msg.format(webfont_name, e.value) ...
Get a manifest file, parse and store it. Args: webfont_name (string): Webfont key name. Used to store manifest and potentially its parser error. webfont_settings (dict): Webfont settings (an item value from ``settings.ICOMOON_WEBFONTS``).
juraj-google-style
def __init__(self, features, location_id=None, metadata=None, timeout=120): super().__init__(features=features, location_id=location_id, metadata=metadata, timeout=timeout)
Args: features: (List[``videointelligence_v1.Feature``]) Required. the Video Intelligence API features to detect location_id: (str) Optional. Cloud region where annotation should take place. If no region is specified, a region will be determined based on video file location. metadata: (Sequence[Tuple[str, str]]) Option...
github-repos
def set_colors(self, fg=None, bg=None): if fg is not None: self._fg = _format_color(fg, self._fg) if bg is not None: self._bg = _format_color(bg, self._bg)
Sets the colors to be used with the L{print_str} and draw_* methods. Values of None will only leave the current values unchanged. Args: fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) .. seealso:: :any:`move`, :any:`print_str`
juraj-google-style
def __init__(self, filename, temporary_directory=None): self._database = None self._filename = filename self._is_open = False self._temp_db_file_path = '' self._temporary_directory = temporary_directory self._temp_wal_file_path = '' self.schema = {}
Initializes the database object. Args: filename (str): name of the file entry. temporary_directory (Optional[str]): path of the directory for temporary files.
juraj-google-style
def and_terms(*args): args = [arg if not isinstance(arg, list) else ' '.join(arg) for arg in args] return '({0})'.format(' '.join(args))
Connect given term strings or list(s) of term strings with an AND operator for querying. Args: An arbitrary number of either strings or lists of strings representing query terms. Returns A query string consisting of argument terms and'ed together.
juraj-google-style
def Proxy(self, status, headers, exc_info=None): self.call_context['status'] = status self.call_context['headers'] = headers self.call_context['exc_info'] = exc_info return self.body_buffer.write
Save args, defer start_response until response body is parsed. Create output buffer for body to be written into. Note: this is not quite WSGI compliant: The body should come back as an iterator returned from calling service_app() but instead, StartResponse returns a writer that will be later called to output the body....
codesearchnet
def readlink(self, path): if path is None: raise TypeError try: link_obj = self.lresolve(path) except IOError as exc: self.raise_os_error(exc.errno, path) if S_IFMT(link_obj.st_mode) != S_IFLNK: self.raise_os_error(errno.EINVAL, pa...
Read the target of a symlink. Args: path: symlink to read the target of. Returns: the string representing the path to which the symbolic link points. Raises: TypeError: if path is None OSError: (with errno=ENOENT) if path is not a valid path, or (with errno=EINVAL) if path is valid, but is not a symlink, or if the ...
juraj-google-style
def write_dftbp(filename, atoms): scale_pos = dftbpToBohr lines = '' natoms = atoms.get_number_of_atoms() lines += str(natoms) lines += ' S \n' expaned_symbols = atoms.get_chemical_symbols() symbols = get_reduced_symbols(expaned_symbols) lines += (' '.join(symbols) + '\n') atom_numbe...
Writes DFTB+ readable, gen-formatted structure files Args: filename: name of the gen-file to be written atoms: object containing information about structure
codesearchnet
def get_max_position(self, chrom): res = self.db.variant.find({'chrom':chrom}, {'_id':0, 'end':1}).sort([('end', DESCENDING)]).limit(1) end = 0 for variant in res: end = variant['end'] return end
Get the last position observed on a chromosome in the database Args: chrom(str) Returns: end(int): The largest end position found
juraj-google-style
def banner(text, border='=', width=80): text_padding = '{0:^%d}' % (width) LOG.info(border * width) LOG.info(text_padding.format(text)) LOG.info(border * width)
Center _text_ in a banner _width_ wide with _border_ characters. Args: text (str): What to write in the banner border (str): Border character width (int): How long the border should be
juraj-google-style
def load_hpo_terms(adapter, hpo_lines=None, hpo_gene_lines=None, alias_genes=None): hpo_terms = {} if not hpo_lines: hpo_lines = fetch_hpo_terms() if not hpo_gene_lines: hpo_gene_lines = fetch_hpo_to_genes() LOG.info("Parsing hpo terms") ...
Load the hpo terms into the database Parse the hpo lines, build the objects and add them to the database Args: adapter(MongoAdapter) hpo_lines(iterable(str)) hpo_gene_lines(iterable(str))
juraj-google-style
def form_out(self, _form=None): _form = _form or self.object_form self.output['forms'] = _form.serialize() self._add_meta_props(_form) self.output['forms']['grouping'] = _form.Meta.grouping self.output['forms']['constraints'] = _form.Meta.constraints self._patch_...
Renders form. Applies form modifiers, then writes result to response payload. If supplied, given form object instance will be used instead of view's default ObjectForm. Args: _form (:py:attr:`~zengine.forms.json_form.JsonForm`): Form object to override `self.object_form`
juraj-google-style
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((...
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].
juraj-google-style
def minutes(start, end=None): return iterate.between(start, datetime.timedelta(minutes=1), end)
Iterate over the minutes between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a minute apart.
juraj-google-style
def copy_and_move_messages(from_channel, to_channel): with BlockSave(Message, query_dict={'channel_id': to_channel.key}): for message in Message.objects.filter(channel=from_channel, typ=15): message.key = '' message.channel = to_channel messag...
While splitting channel and moving chosen subscribers to new channel, old channel's messages are copied and moved to new channel. Args: from_channel (Channel object): move messages from channel to_channel (Channel object): move messages to channel
juraj-google-style
def forward(self, hidden_states: Optional[torch.FloatTensor], attention_mask: Optional[torch.FloatTensor]=None, position_ids: Optional[torch.LongTensor]=None, past_key_value: Optional[Cache]=None, use_cache: Optional[bool]=False, output_attentions: Optional[bool]=False, cache_position: Optional[torch.LongTensor]=None) ...
Forward pass of the JetMoeAttention module. Args: hidden_states (Optional[torch.FloatTensor]): Input hidden states. attention_mask (Optional[torch.FloatTensor]): Attention mask. layer_past (Optional[Tuple[torch.Tensor]]): Past layer state. use_cache (Optional[bool]): Whether to use cached states. output_attentions (Op...
github-repos
def Read(f): try: yaml_data = yaml.load(f) except yaml.YAMLError as e: raise ParseError(('%s' % e)) except IOError as e: raise YAMLLoadError(('%s' % e)) _CheckData(yaml_data) try: return Config(yaml_data.get('blacklist', ()), yaml_data.get('whitelist', '*')) excep...
Reads and returns Config data from a yaml file. Args: f: Yaml file to parse. Returns: Config object as defined in this file. Raises: Error (some subclass): If there is a problem loading or parsing the file.
codesearchnet
def verify(self, obj): if obj is not None: raise ValidationError("Object is not None", reason='%s is not None' % str(obj), object=obj) return obj
Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reason key set indicating the reason for the lack of validation.
juraj-google-style
def collect_per_output_metric_info(metrics, output_names, output_shapes, loss_fns, from_serialized=False, is_weighted=False): if not metrics: return [{} for _ in output_names] if isinstance(metrics, list): any_sub_list = any((isinstance(m, list) for m in metrics)) if any_sub_list: ...
Maps metric names and functions to model outputs. Args: metrics: a list or a list of lists or a dict of metric functions. output_names: a list of the names (strings) of model outputs. output_shapes: a list of the shapes (strings) of model outputs. loss_fns: a list of the loss functions corresponding to the model outpu...
github-repos
def experimental_design(self) -> Any: if (not self.samples): raise ValueError('No samples in sample sheet') markdown = tabulate([[getattr(s, h, '') for h in DESIGN_HEADER] for s in self.samples], headers=DESIGN_HEADER, tablefmt='pipe') return maybe_render_markdown(markdown)
Return a markdown summary of the samples on this sample sheet. This property supports displaying rendered markdown only when running within an IPython interpreter. If we are not running in an IPython interpreter, then print out a nicely formatted ASCII table. Returns: Markdown, str: A visual table of IDs and names fo...
codesearchnet
def GenerateModelReport(metagraph, assume_valid_feeds=True, debug=False): return tf_wrap.GenerateModelReport(metagraph.SerializeToString(), assume_valid_feeds, debug)
Report what's known statically about each node in the provided metagraph. Args: metagraph: A TensorFlow MetaGraphDef. assume_valid_feeds: If True, assume that the shape of the fed nodes is valid debug: Add some information useful for debugging. Returns: A string containing the report.
github-repos
def Parse(self, stat, file_object, knowledge_base): (_, _) = (stat, knowledge_base) lines = [l.strip() for l in utils.ReadFileBytesAsUnicode(file_object).splitlines()] return self.ParseLines(lines)
Parse the netgroup file and return User objects. Lines are of the form: group1 (-,user1,) (-,user2,) (-,user3,) Groups are ignored, we return users in lines that match the filter regexes, or all users in the file if no filters are specified. We assume usernames are in the default regex format specified in the adduse...
codesearchnet
def __delitem__(self, name: str) -> None: if base.treats_as_sealed(self): raise base.WritePermissionError('Cannot del item from a sealed Dict.') if not base.writtable_via_accessors(self): raise base.WritePermissionError(self._error_message("Cannot del Dict field by attribute or key while accesso...
Delete a key from the Dict. This is used to delete a key which resolves to a pg.typing.NonConstKey. Args: name: Key to delete. Raises: WritePermissionError: When Dict is sealed. KeyError: When key is not a NonConstKey.
github-repos
def make_simulated_env_fn(**env_kwargs): def env_fn(in_graph): class_ = (SimulatedBatchEnv if in_graph else SimulatedBatchGymEnv) return class_(**env_kwargs) return env_fn
Returns a function creating a simulated env, in or out of graph. Args: **env_kwargs: kwargs to pass to the simulated env constructor. Returns: Function in_graph -> env.
codesearchnet
def segment_sum(data, segment_ids, num_segments=None, sorted=False): _segment_reduce_validation(data, segment_ids) if any_symbolic_tensors((data,)): return SegmentSum(num_segments, sorted).symbolic_call(data, segment_ids) return backend.math.segment_sum(data, segment_ids, num_segments=num_segments, ...
Computes the sum of segments in a tensor. Args: data: Input tensor. segment_ids: A N-D tensor containing segment indices for each element in `data`. Num dims for segment ids should be strictly smaller or equal to number of dims in data. num_segments: An integer representing the total number of segments. If not specifi...
github-repos
def to_representation(self, instance): request = self.context['request'] enterprise_customer = instance.enterprise_customer representation = super(EnterpriseCustomerCatalogDetailSerializer, self).to_representation(instance) paginated_content = instance.get_paginated_c...
Serialize the EnterpriseCustomerCatalog object. Arguments: instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize. Returns: dict: The EnterpriseCustomerCatalog converted to a dict.
juraj-google-style
def pandas(self): (names, prior, posterior) = ([], [], []) for (iname, name) in enumerate(self.posterior_parameter.row_names): names.append(name) posterior.append(np.sqrt(float(self.posterior_parameter[(iname, iname)].x))) iprior = self.parcov.row_names.index(name) prior.append(n...
get a pandas dataframe of prior and posterior for all predictions Returns: pandas.DataFrame : pandas.DataFrame a dataframe with prior and posterior uncertainty estimates for all forecasts (predictions)
codesearchnet
def to_array(data): try: numpy_data = blosc.unpack_array(data) except Exception as e: raise ValueError('Could not load numpy data. {}'.format(e)) return numpy_data
Import a blosc array into a numpy array. Arguments: data: A blosc packed numpy array Returns: A numpy array with data from a blosc compressed array
codesearchnet
def __init__(self, x, offset, dim, wrap, name=None): super(ShiftOperation, self).__init__([x], name=name or "shift") self._dim = dim self._axis = x.shape.dims.index(dim) self._offset = offset self._wrap = wrap self._outputs = [Tensor(self, x.shape, x.dtype)]
Create a shift operation. Shift x right by +offset in dimension dim. If offset is negative, shift left. If wrap is true then wrap-around. Else, pad with zeros. Args: x: a Tensor offset: an integer dim: a Dimension of x wrap: a boolean - whether to wrap or pad. name: an optional string
juraj-google-style
def fastcc_is_consistent(model, epsilon, solver): for reaction in fastcc(model, epsilon, solver): return False return True
Quickly check whether model is consistent Return true if the model is consistent. If it is only necessary to know whether a model is consistent, this function is fast as it will return the result as soon as it finds a single inconsistent reaction. Args: model: :class:`MetabolicModel` to solve. epsilon: Flux threshold...
juraj-google-style
def _compute_router_probabilities(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: self.input_dtype = hidden_states.dtype hidden_states = hidden_states.to(self.dtype) if self.training and self.jitter_noise > 0: hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - s...
Computes router probabilities from input hidden states. Args: hidden_states (`torch.Tensor`): (batch_size, sequence_length, hidden_dim) from which router probabilities are computed. Returns: router_probabilities (`torch.Tensor`): Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabili...
github-repos
def cancel_job(self, job_id=None, job_name=None): payload = {} if job_name is not None: payload['job_name'] = job_name if job_id is not None: payload['job_id'] = job_id jobs_url = self._get_url('jobs_path') res = self.rest_client.session.delete(j...
Cancel a running job. Args: job_id (str, optional): Identifier of job to be canceled. job_name (str, optional): Name of job to be canceled. Returns: dict: JSON response for the job cancel operation.
juraj-google-style
def __init__(self, primitive_handler_: primitive_handler.PrimitiveHandler, default_timezone: str) -> None: self.primitive_handler = primitive_handler_ self.default_timezone = default_timezone self._resource_type_mapping = {field.message_type.name: field for field in primitive_handler_.contained_resource_cls...
Initializes an instance of the FHIR JSON parser. Note that this is for *internal-use* only. External clients should leverage one of the available class constructors, such as: `JsonParser.json_parser_with_default_timezone(...)`. Args: primitive_handler_: Responsible for returning PrimitiveWrappers. default_timezone: T...
github-repos
def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) -> FrozenSet[Flag]: if (self == FlagOp.ADD): return frozenset((flag_set | operand)) elif (self == FlagOp.DELETE): return frozenset((flag_set - operand)) else: return frozenset(operand)
Apply the flag operation on the two sets, returning the result. Args: flag_set: The flag set being operated on. operand: The flags to use as the operand.
codesearchnet
def DumpMany(objs): precondition.AssertIterableType(objs, object) text = yaml.safe_dump_all(objs, default_flow_style=False, allow_unicode=True) if compatibility.PY2: text = text.decode('utf-8') return text
Stringifies a sequence of Python objects to a multi-document YAML. Args: objs: An iterable of Python objects to convert to YAML. Returns: A multi-document YAML representation of the given objects.
codesearchnet