code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def create_index(self, model, waiting_models): bucket_name = model._get_bucket_name() bucket_type = client.bucket_type(settings.DEFAULT_BUCKET_TYPE) index_name = "%s_%s" % (settings.DEFAULT_BUCKET_TYPE, bucket_name) bucket = bucket_type.bucket(bucket_name) try: client.get_search_index(index_name) if not (bucket.get_property('search_index') == index_name): bucket.set_property('search_index', index_name) print("+ %s (%s) search index is created." % (model.__name__, index_name)) except RiakError: try: client.create_search_index(index_name, index_name, self.n_val) bucket.set_property('search_index', index_name) print("+ %s (%s) search index is created." % (model.__name__, index_name)) except RiakError: print("+ %s (%s) search index checking operation is taken to queue." % ( model.__name__, index_name)) waiting_models.append(model)
Creates search indexes. Args: model: model to execute waiting_models: if riak can't return response immediately, model is taken to queue. After first execution session, method is executed with waiting models and controlled. And be ensured that all given models are executed properly. Returns:
juraj-google-style
def getConfig(self, section = None): data = {} if section is None: for s in self.config.sections(): if '/' in s: parent, _s = s.split('/') data[parent][_s] = dict(self.config.items(s)) else: data[s] = dict(self.config.items(s)) else: data = dict(self.config.items(section)) return data
Returns a dictionary which contains the current config. If a section is setted, only will returns the section config Args: section (str): (Optional) Section name. Returns: dict: Representation of current config
juraj-google-style
def _parse_state(self, config): value = STATE_RE.search(config).group('value') return dict(state=value)
_parse_state scans the provided configuration block and extracts the vlan state value. The config block is expected to always return the vlan state config. The return dict is inteded to be merged into the response dict. Args: config (str): The vlan configuration block from the nodes running configuration Returns: dict: resource dict attribute
juraj-google-style
def _validate_namespace(self, namespace): if (self._namespace_regex.fullmatch(namespace) is None): LOGGER.debug('Invalid namespace: %s', namespace) raise _ResponseFailed(self._status.INVALID_ADDRESS)
Validates a namespace, raising a ResponseFailed error if invalid. Args: state_root (str): The state_root to validate Raises: ResponseFailed: The state_root was invalid, and a status of INVALID_ROOT will be sent with the response.
codesearchnet
def subtract_business_days(self, date_tensor, num_days, roll_convention=constants.BusinessDayConvention.NONE): pass
Adds given number of business days to given dates. Note that this is different from calling `subtract_period_and_roll` with PeriodType.DAY. For example, subtracting 5 business days from Friday gives the previous Friday (unless there are holidays on this week or previous Friday). Subtracting 5 days and rolling means landing on Sunday and then rolling either to Monday or to Friday, depending on the roll convention. If any of the dates in `date_tensor` are not business days, they will be rolled to business days before doing the subtraction. If `roll_convention` is `NONE`, and any dates are not business days, an exception is raised. Args: date_tensor: DateTensor of dates to advance from. num_days: Tensor of int32 type broadcastable to `date_tensor`. roll_convention: BusinessDayConvention. Determines how to roll a date that falls on a holiday. Returns: The resulting DateTensor.
github-repos
def _find_bad_transition(self, mma, w_string): conj_out = mma.consume_input(w_string) targ_out = self._membership_query(w_string) length = min(len(conj_out), len(targ_out)) diff = [i for i in range(length) if conj_out[i] != targ_out[i]] if len(diff) == 0: diff_index = len(targ_out) else: diff_index = diff[0] low = 0 high = len(w_string) while True: i = (low + high) / 2 length = len(self._membership_query(w_string[:i])) if length == diff_index + 1: return w_string[:i] elif length < diff_index + 1: low = i + 1 else: high = i - 1
Checks for bad DFA transitions using the examined string Args: mma (DFA): The hypothesis automaton w_string (str): The examined string to be consumed Returns: str: The prefix of the examined string that matches
juraj-google-style
def get_pk_attrnames(obj) -> List[str]: return [attrname for attrname, column in gen_columns(obj) if column.primary_key]
Asks an SQLAlchemy ORM object: "what are your primary key(s)?" Args: obj: SQLAlchemy ORM object Returns: list of attribute names of primary-key columns
juraj-google-style
def _get_edges(self): if (self._edges is None): self._edges = self._compute_edges() return self._edges
Get the edges for the current surface. If they haven't been computed yet, first compute and store them. This is provided as a means for internal calls to get the edges without copying (since :attr:`.edges` copies before giving to a user to keep the stored data immutable). Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface.
codesearchnet
def _eval_once(saver, summary_writer, top_1_op, top_5_op, summary_op): with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: print("ckpt.model_checkpoint_path: {0}".format(ckpt.model_checkpoint_path)) saver.restore(sess, ckpt.model_checkpoint_path) global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] print('Successfully loaded model from %s at step=%s.' % (ckpt.model_checkpoint_path, global_step)) else: print('No checkpoint file found') return coord = tf.train.Coordinator() try: threads = [] for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS): threads.extend(qr.create_threads(sess, coord=coord, daemon=True, start=True)) num_iter = int(math.ceil(FLAGS.num_examples / FLAGS.batch_size)) count_top_1 = 0.0 count_top_5 = 0.0 total_sample_count = num_iter * FLAGS.batch_size step = 0 print('%s: starting evaluation on (%s).' % (datetime.now(), FLAGS.subset)) start_time = time.time() while step < num_iter and not coord.should_stop(): top_1, top_5 = sess.run([top_1_op, top_5_op]) count_top_1 += np.sum(top_1) count_top_5 += np.sum(top_5) step += 1 if step % 20 == 0: duration = time.time() - start_time sec_per_batch = duration / 20.0 examples_per_sec = FLAGS.batch_size / sec_per_batch print('%s: [%d batches out of %d] (%.1f examples/sec; %.3f' 'sec/batch)' % (datetime.now(), step, num_iter, examples_per_sec, sec_per_batch)) start_time = time.time() precision_at_1 = count_top_1 / total_sample_count recall_at_5 = count_top_5 / total_sample_count print('%s: precision @ 1 = %.4f recall @ 5 = %.4f [%d examples]' % (datetime.now(), precision_at_1, recall_at_5, total_sample_count)) summary = tf.Summary() summary.ParseFromString(sess.run(summary_op)) summary.value.add(tag='Precision @ 1', simple_value=precision_at_1) summary.value.add(tag='Recall @ 5', simple_value=recall_at_5) summary_writer.add_summary(summary, global_step) except Exception as e: coord.request_stop(e) coord.request_stop() coord.join(threads, stop_grace_period_secs=10)
Runs Eval once. Args: saver: Saver. summary_writer: Summary writer. top_1_op: Top 1 op. top_5_op: Top 5 op. summary_op: Summary op.
juraj-google-style
def _next_dna(self, dna: Optional[DNA]=None) -> Optional[DNA]: if self.next_dna_fn is None: cls_name = self.hyper_type or self.__class__.__name__ raise NotImplementedError(f'`next_dna` is not supported on {cls_name!r}.') return self.next_dna_fn(dna)
Returns the next DNA in the space represented by this spec. Args: dna: The DNA whose next will be returned. If None, `next_dna` will return the first DNA. Returns: The next DNA or None if there is no next DNA.
github-repos
def reshape(self, shape: tf.TensorShape) -> 'TensorFluent': t = tf.reshape(self.tensor, shape) scope = self.scope.as_list() batch = self.batch return TensorFluent(t, scope, batch=batch)
Returns a TensorFluent for the reshape operation with given `shape`. Args: shape: The output's shape. Returns: A TensorFluent wrapping the reshape operation.
juraj-google-style
def devno_alloc(self): devno_int = self._devno_pool.alloc() devno = '{:04X}'.format(devno_int) return devno
Allocates a device number unique to this partition, in the range of 0x8000 to 0xFFFF. Returns: string: The device number as four hexadecimal digits in upper case. Raises: ValueError: No more device numbers available in that range.
codesearchnet
def set_default(self, name, value): fl = self._flags() if (name not in fl): self._set_unknown_flag(name, value) return fl[name]._set_default(value) self._assert_validators(fl[name].validators)
Changes the default value of the named flag object. The flag's current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value. Args: name: str, the name of the flag to modify. value: The new default value. Raises: UnrecognizedFlagError: Raised when there is no registered flag named name. IllegalFlagValueError: Raised when value is not valid.
codesearchnet
def get_content_of_file(self, name, full_path=False): if self.handle: for member in self.handle.getmembers(): if ((full_path and (member.name == name)) or ((not full_path) and (os.path.basename(member.name) == name))): extracted = self.handle.extractfile(member) return extracted.read().decode(locale.getpreferredencoding()) return None
Returns content of file from archive. If full_path is set to False and two files with given name exist, content of one is returned (it is not specified which one that is). If set to True, returns content of exactly that file. Args: name: name of the file to get content of Returns: Content of the file with given name or None, if no such.
codesearchnet
def _pre_action(self, action): assert (len(action) == self.dof), 'environment got invalid action dimension' (low, high) = self.action_spec action = np.clip(action, low, high) if self.has_gripper: arm_action = action[:self.mujoco_robot.dof] gripper_action_in = action[self.mujoco_robot.dof:(self.mujoco_robot.dof + self.gripper.dof)] gripper_action_actual = self.gripper.format_action(gripper_action_in) action = np.concatenate([arm_action, gripper_action_actual]) ctrl_range = self.sim.model.actuator_ctrlrange bias = (0.5 * (ctrl_range[(:, 1)] + ctrl_range[(:, 0)])) weight = (0.5 * (ctrl_range[(:, 1)] - ctrl_range[(:, 0)])) applied_action = (bias + (weight * action)) self.sim.data.ctrl[:] = applied_action self.sim.data.qfrc_applied[self._ref_joint_vel_indexes] = self.sim.data.qfrc_bias[self._ref_joint_vel_indexes] if self.use_indicator_object: self.sim.data.qfrc_applied[self._ref_indicator_vel_low:self._ref_indicator_vel_high] = self.sim.data.qfrc_bias[self._ref_indicator_vel_low:self._ref_indicator_vel_high]
Overrides the superclass method to actuate the robot with the passed joint velocities and gripper control. Args: action (numpy array): The control to apply to the robot. The first @self.mujoco_robot.dof dimensions should be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof dimensions should be actuation controls for the gripper.
codesearchnet
def resolve(self, method, path): if method in self._literal and path in self._literal[method]: return self._literal[method][path], [], {} else: return self._resolve_non_literal_route(method, path)
Resolve a request to a route handler. Arguments: method (str): HTTP method, e.g. GET, POST, etc. (type: str) path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) 2. Positional arguments (list) 3. Keyword arguments (dict) ``None`` if no route matches the request.
juraj-google-style
def find_in_matrix_2d(val, matrix): dim = len(matrix[0]) item_index = 0 for row in matrix: for i in row: if (i == val): break item_index += 1 if (i == val): break loc = (int((item_index / dim)), (item_index % dim)) return loc
Returns a tuple representing the index of an item in a 2D matrix. Arguments: - val (str) Value to look for - matrix (list) 2D matrix to search for val in Returns: - (tuple) Ordered pair representing location of val
codesearchnet
def bulk_insert_extras(dialect_name: str, fileobj: TextIO, start: bool) -> None: lines = [] if dialect_name == SqlaDialectName.MYSQL: if start: lines = [ "SET autocommit=0;", "SET unique_checks=0;", "SET foreign_key_checks=0;", ] else: lines = [ "SET foreign_key_checks=1;", "SET unique_checks=1;", "COMMIT;", ] writelines_nl(fileobj, lines)
Writes bulk ``INSERT`` preamble (start=True) or end (start=False). For MySQL, this temporarily switches off autocommit behaviour and index/FK checks, for speed, then re-enables them at the end and commits. Args: dialect_name: SQLAlchemy dialect name (see :class:`SqlaDialectName`) fileobj: file-like object to write to start: if ``True``, write preamble; if ``False``, write end
juraj-google-style
def stop_ec2_instance(client, resource): instance = EC2Instance.get(resource.id) if instance.state in ('stopped', 'terminated'): return ActionStatus.IGNORED, {} client.stop_instances(InstanceIds=[resource.id]) return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}
Stop an EC2 Instance This function will attempt to stop a running instance. Args: client (:obj:`boto3.session.Session.client`): A boto3 client object resource (:obj:`Resource`): The resource object to stop Returns: `ActionStatus`
juraj-google-style
def _trychar(char, fallback, asciimode=None): if asciimode is True: return fallback if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: try: char.encode(sys.stdout.encoding) except Exception: pass else: return char return fallback
Logic from IPython timeit to handle terminals that cant show mu Args: char (str): character, typically unicode, to try to use fallback (str): ascii character to use if stdout cannot encode char asciimode (bool): if True, always use fallback Example: >>> char = _trychar('µs', 'us') >>> print('char = {}'.format(char)) >>> assert _trychar('µs', 'us', asciimode=True) == 'us'
juraj-google-style
def _model_to_dict(model, ignore): return {attr: value for (attr, value) in model.__dict__.items() if ((not attr.startswith('_')) and (attr not in ignore))}
Convert OSS model to dict. Args: model (oss2.models.RequestResult): Model. ignore (tuple of str): Keys to not insert to dict. Returns: dict: Model dict version.
codesearchnet
def verify_link_ed25519_cot_signature(chain, link, unsigned_path, signature_path): if chain.context.config['verify_cot_signature']: log.debug('Verifying the {} {} {} ed25519 chain of trust signature'.format(link.name, link.task_id, link.worker_impl)) signature = read_from_file(signature_path, file_type='binary', exception=CoTError) binary_contents = read_from_file(unsigned_path, file_type='binary', exception=CoTError) errors = [] verify_key_seeds = chain.context.config['ed25519_public_keys'].get(link.worker_impl, []) for seed in verify_key_seeds: try: verify_key = ed25519_public_key_from_string(seed) verify_ed25519_signature(verify_key, binary_contents, signature, "{} {}: {} ed25519 cot signature doesn't verify against {}: %(exc)s".format(link.name, link.task_id, link.worker_impl, seed)) log.debug('{} {}: ed25519 cot signature verified.'.format(link.name, link.task_id)) break except ScriptWorkerEd25519Error as exc: errors.append(str(exc)) else: errors = (errors or ['{} {}: Unknown error verifying ed25519 cot signature. worker_impl {} verify_keys {}'.format(link.name, link.task_id, link.worker_impl, verify_key_seeds)]) message = '\n'.join(errors) raise CoTError(message) link.cot = load_json_or_yaml(unsigned_path, is_path=True, exception=CoTError, message='{} {}: Invalid unsigned cot json body! %(exc)s'.format(link.name, link.task_id))
Verify the ed25519 signatures of the chain of trust artifacts populated in ``download_cot``. Populate each link.cot with the chain of trust json body. Args: chain (ChainOfTrust): the chain of trust to add to. Raises: (CoTError, ScriptWorkerEd25519Error): on signature verification failure.
codesearchnet
def unpack_archive(*components, **kwargs) -> str: path = fs.abspath(*components) compression = kwargs.get('compression', 'bz2') dir = kwargs.get('dir', fs.dirname(path)) fs.cd(dir) tar = tarfile.open(path, ('r:' + compression)) tar.extractall() tar.close() fs.cdpop() return dir
Unpack a compressed archive. Arguments: *components (str[]): Absolute path. **kwargs (dict, optional): Set "compression" to compression type. Default: bz2. Set "dir" to destination directory. Defaults to the directory of the archive. Returns: str: Path to directory.
codesearchnet
def __frontend_limit_descriptor(self, api_info): if (api_info.frontend_limits is None): return None descriptor = {} for (propname, descname) in (('unregistered_user_qps', 'unregisteredUserQps'), ('unregistered_qps', 'unregisteredQps'), ('unregistered_daily', 'unregisteredDaily')): if (getattr(api_info.frontend_limits, propname) is not None): descriptor[descname] = getattr(api_info.frontend_limits, propname) rules = self.__frontend_limit_rules_descriptor(api_info) if rules: descriptor['rules'] = rules return descriptor
Builds a frontend limit descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A dictionary with frontend limit information.
codesearchnet
def Deserialize(self, reader): self.PrevHash = reader.ReadUInt256() self.PrevIndex = reader.ReadUInt16()
Deserialize full object. Args: reader (neo.IO.BinaryReader):
juraj-google-style
def _guess_format_from_extension(ext): ext = ext.strip('.') formats = [] for fmt in FILE_FORMATS: if ext in FILE_FORMATS[fmt]: formats.append(fmt) if formats == [] or len(formats) > 1: return False return formats[0]
Guess the appropriate data type from file extension. Arguments: ext: The file extension (period optional) Returns: String. The format (without leading period), or False if none was found or couldn't be guessed
juraj-google-style
def handle_upnp_error(self, xml_error): xml_error = xml_error.encode('utf-8') error = XML.fromstring(xml_error) log.debug('Error %s', xml_error) error_code = error.findtext('. if (error_code is not None): description = self.UPNP_ERRORS.get(int(error_code), '') raise SoCoUPnPException(message='UPnP Error {} received: {} from {}'.format(error_code, description, self.soco.ip_address), error_code=error_code, error_description=description, error_xml=xml_error) else: log.error('Unknown error received from %s', self.soco.ip_address) raise UnknownSoCoException(xml_error)
Disect a UPnP error, and raise an appropriate exception. Args: xml_error (str): a unicode string containing the body of the UPnP/SOAP Fault response. Raises an exception containing the error code.
codesearchnet
def get_signature_def(meta_graph, signature_key): signature_def_map = meta_graph.signature_def signature_def_keys = set(signature_def_map.keys()) logging.info('The given SavedModel MetaGraphDef contains SignatureDefs with the following keys: %s', signature_def_keys) if signature_key not in signature_def_keys: raise ValueError("No '{}' in the SavedModel's SignatureDefs. Possible values are '{}'.".format(signature_key, ','.join(signature_def_keys))) return signature_def_map[signature_key]
Get the signature def from meta_graph with given signature_key. Args: meta_graph: meta_graph_def. signature_key: signature_def in the meta_graph_def. Returns: The signature_def used for tflite conversion. Raises: ValueError: Given signature_key is not valid for this meta_graph.
github-repos
def get_m49_from_iso3(cls, iso3, use_live=True, exception=None): countriesdata = cls.countriesdata(use_live=use_live) m49 = countriesdata['m49iso3'].get(iso3) if (m49 is not None): return m49 if (exception is not None): raise exception return None
Get M49 from ISO3 code Args: iso3 (str): ISO3 code for which to get M49 code use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None. Returns: Optional[int]: M49 code
codesearchnet
def agent_version(self, value): if value == self._defaults['ai.internal.agentVersion'] and 'ai.internal.agentVersion' in self._values: del self._values['ai.internal.agentVersion'] else: self._values['ai.internal.agentVersion'] = value
The agent_version property. Args: value (string). the property value.
juraj-google-style
def byte_str(nBytes, unit='bytes', precision=2): if unit.lower().startswith('b'): nUnit = nBytes elif unit.lower().startswith('k'): nUnit = (nBytes / (2.0 ** 10)) elif unit.lower().startswith('m'): nUnit = (nBytes / (2.0 ** 20)) elif unit.lower().startswith('g'): nUnit = (nBytes / (2.0 ** 30)) elif unit.lower().startswith('t'): nUnit = (nBytes / (2.0 ** 40)) else: raise NotImplementedError(('unknown nBytes=%r unit=%r' % (nBytes, unit))) return ((repr2(nUnit, precision=precision) + ' ') + unit)
representing the number of bytes with the chosen unit Returns: str
codesearchnet
def report_error(self, read_tuple_name, error_name, wrong="", message="", warning=False): if (not self.report_only_first) or (error_name not in self.reported_errors): print("\t".join(["error" if warning == False else "warning", read_tuple_name, error_name, wrong, message])) self.reported_errors.add(error_name) if warning: self.warning_has_been_reported = True else: self.error_has_been_reported = True
Report an error. Args: read_tuple_name (): Name of the read tuple. error_name (): Name of the error. wrong (str): What is wrong. message (str): Additional msessage to be printed. warning (bool): Warning (not an error).
juraj-google-style
def activate_absence_with_duration(self, duration: int): data = {"duration": duration} return self._restCall( "home/heating/activateAbsenceWithDuration", json.dumps(data) )
activates the absence mode for a given time Args: duration(int): the absence duration in minutes
juraj-google-style
def wb004(self, value=None): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `wb004`'.format(value)) self._wb004 = value
Corresponds to IDD Field `wb004` Wet-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `wb004` Unit: C if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
codesearchnet
async def download_cot(chain): artifact_tasks = [] for link in chain.links: task_id = link.task_id parent_dir = link.cot_dir urls = [] unsigned_url = get_artifact_url(chain.context, task_id, 'public/chain-of-trust.json') urls.append(unsigned_url) if chain.context.config['verify_cot_signature']: urls.append( get_artifact_url(chain.context, task_id, 'public/chain-of-trust.json.sig') ) artifact_tasks.append( asyncio.ensure_future( download_artifacts( chain.context, urls, parent_dir=parent_dir, valid_artifact_task_ids=[task_id] ) ) ) artifacts_paths = await raise_future_exceptions(artifact_tasks) for path in artifacts_paths: sha = get_hash(path[0]) log.debug("{} downloaded; hash is {}".format(path[0], sha))
Download the signed chain of trust artifacts. Args: chain (ChainOfTrust): the chain of trust to add to. Raises: BaseDownloadError: on failure.
juraj-google-style
def rtm(self, url: Optional[str]=None, bot_id: Optional[str]=None) -> Iterator[events.Event]: while True: bot_id = (bot_id or self._find_bot_id()) url = (url or self._find_rtm_url()) for event in self._incoming_from_rtm(url, bot_id): (yield event) url = None
Iterate over event from the RTM API Args: url: Websocket connection url bot_id: Connecting bot ID Returns: :class:`slack.events.Event` or :class:`slack.events.Message`
codesearchnet
class InputExample: guid: str text_a: str text_b: Optional[str] = None label: Optional[str] = None def to_json_string(self): return json.dumps(dataclasses.asdict(self), indent=2) + '\n'
A single training/test example for simple sequence classification. Args: guid: Unique id for the example. text_a: string. The untokenized text of the first sequence. For single sequence tasks, only this sequence must be specified. text_b: (Optional) string. The untokenized text of the second sequence. Only must be specified for sequence pair tasks. label: (Optional) string. The label of the example. This should be specified for train and dev examples, but not for test examples.
github-repos
def _use_gl(objs): from ..models.plots import Plot return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl")
Whether a collection of Bokeh objects contains a plot requesting WebGL Args: objs (seq[Model or Document]) : Returns: bool
juraj-google-style
def _encode_slice_definition(self, root_builder: expressions.Builder, slice_: _fhir_path_data_types.Slice) -> List[validation_pb2.SqlRequirement]: if slice_.relative_path: slice_builder = self._get_new_child_builder(root_builder, slice_.relative_path) else: slice_builder = root_builder if slice_builder is None: return [] element_constraints = [] for rule_path, rule_def in slice_.slice_rules: if not rule_def.HasField('fixed') and (not rule_def.HasField('pattern')): continue slice_element_builder = root_builder for path_component in rule_path.split('.'): slice_element_builder = slice_element_builder.__getattr__(path_component) if slice_element_builder.return_type.returns_polymorphic(): type_codes = _utils.element_type_codes(slice_element_builder.return_type.root_element_definition) if len(type_codes) > 1: self._error_reporter.report_fhir_path_error(cast(Any, rule_def).path.value, str(slice_element_builder), f'Element `{slice_element_builder}` in slice `{cast(Any, slice_.slice_def).id.value}` is a choice type with more than one choice which is not currently supported.') return [] slice_element_builder = slice_element_builder.ofType(type_codes[0]) fixed_constraint = self._constraint_for_fixed_slice_element(slice_element_builder, rule_def) if fixed_constraint is not None: element_constraints.append(fixed_constraint) pattern_constraint = self._constraint_for_pattern_slice_element(slice_element_builder, rule_def) if pattern_constraint is not None: element_constraints.append(pattern_constraint) if not element_constraints: return [] element_predicate = functools.reduce(operator.and_, element_constraints) elements_in_slice = slice_builder.where(element_predicate) slice_constraints = [] min_size: int = cast(Any, slice_.slice_def).min.value max_size: str = cast(Any, slice_.slice_def).max.value if str(min_size) == max_size: slice_constraints.append(elements_in_slice.count() == min_size) else: if min_size == 1: slice_constraints.append(elements_in_slice.exists()) elif min_size > 1: slice_constraints.append(elements_in_slice.count() >= min_size) if max_size.isdigit(): slice_constraints.append(elements_in_slice.count() <= int(max_size)) if not slice_constraints: return [] slice_constraint = functools.reduce(operator.and_, slice_constraints) constraint_sql = self._encode_fhir_path_builder_constraint(slice_constraint, None) if constraint_sql is None: return [] slice_id = cast(Any, slice_.slice_def).id.value slice_path = self._abs_path_invocation(root_builder) slice_name = cast(Any, slice_.slice_def).slice_name.value column_name = f'{_path_to_sql_column_name(slice_path)}_{_path_to_sql_column_name(slice_id)}_slice_cardinality' description = f'Slice {slice_id} requires at least {min_size} and at most {max_size} elements in {slice_builder} to conform to slice {slice_name}.' return [validation_pb2.SqlRequirement(column_name=column_name, sql_expression=constraint_sql.sql, fhir_path_sql_expression=constraint_sql.fhir_path_sql, severity=validation_pb2.ValidationSeverity.SEVERITY_ERROR, type=validation_pb2.ValidationType.VALIDATION_TYPE_CARDINALITY, element_path=root_builder.node.get_root_node().to_fhir_path(), description=description, fhir_path_key=column_name.replace('_', '-'), fhir_path_expression=constraint_sql.builder.fhir_path, fields_referenced_by_expression=sorted(constraint_sql.builder.node.find_paths_referenced()))]
Encodes constraints for slices. Args: root_builder: The builder representing a path to the structure definition defining the slice. slice_: A slice defined by the structure definition at `root_builder`. Returns: A constraint enforcing the cardinality of `slice_` if `slice_` imposes a non-zero or non-* min or max cardinality. Otherwise, an empty list.
github-repos
def Convert(self, metadata, stat_entry, token=None): if stat_entry.pathspec.pathtype != rdf_paths.PathSpec.PathType.REGISTRY: return [] result = ExportedRegistryKey( metadata=metadata, urn=stat_entry.AFF4Path(metadata.client_urn), last_modified=stat_entry.st_mtime) if (stat_entry.HasField("registry_type") and stat_entry.HasField("registry_data")): result.type = stat_entry.registry_type data = stat_entry.registry_data.GetValue() if isinstance(data, bytes): result.data = data else: result.data = str(data).encode("utf-8") return [result]
Converts StatEntry to ExportedRegistryKey. Does nothing if StatEntry corresponds to a file and not a registry entry. Args: metadata: ExportedMetadata to be used for conversion. stat_entry: StatEntry to be converted. token: Security token. Returns: List or generator with resulting RDFValues. Empty list if StatEntry corresponds to a file and not to a registry entry.
juraj-google-style
def __init__(self, on_exception=Exception, limit=5, interval=None, validator=None): self.attempts = 0 self._on_exception = on_exception self._setup_limit(limit) self._setup_interval(interval) self._setup_validator(validator)
Configure how a function should be retried. Args: on_exception (BaseException): The exception to catch. Use this to set which exception and it's subclasses to catch. limit ()
juraj-google-style
def _handle_agg_function(gb, agg_func, agg_name, *args, **kwargs): if _is_associative(agg_func): return _liftable_agg(agg_func)(gb, *args, **kwargs) elif _is_liftable_with_sum(agg_func): return _liftable_agg(agg_func, postagg_meth='sum')(gb, *args, **kwargs) elif _is_unliftable(agg_func): return _unliftable_agg(agg_func)(gb, *args, **kwargs) elif callable(agg_func): return DeferredDataFrame(expressions.ComputedExpression(agg_name, lambda gb_val: gb_val.agg(agg_func, *args, **kwargs), [gb._expr], requires_partition_by=partitionings.Index(), preserves_partition_by=partitionings.Singleton())) else: raise NotImplementedError(f'GroupBy.agg(func={agg_func!r})')
Handles the aggregation logic based on the function type passed. Args: gb: The groupby instance (DeferredGroupBy). agg_name: The name/label of the aggregation function. fn: The aggregation function to apply. *args: Additional arguments to pass to the aggregation function. **kwargs: Keyword arguments to pass to the aggregation function. Returns: A DeferredDataFrame or the result of the aggregation function. Raises: NotImplementedError: If the aggregation function type is unsupported.
github-repos
def register_ops_if_needed(graph_ops): missing_ops = (graph_ops - set(op_def_registry.get_registered_ops().keys())) if (not missing_ops): return p_buffer = c_api.TF_GetAllOpList() cpp_op_list = op_def_pb2.OpList() cpp_op_list.ParseFromString(c_api.TF_GetBuffer(p_buffer)) cpp_registry_ops = {op.name: op for op in cpp_op_list.op} missing_op_list = op_def_pb2.OpList() for missing_op in missing_ops: if (missing_op not in cpp_registry_ops): logging.info('Op %s is missing from both the python and C++ registry.', missing_op) else: missing_op_list.op.extend([cpp_registry_ops[missing_op]]) logging.info('Adding op %s from c++ registry to python registry.', missing_op) op_def_registry.register_op_list(missing_op_list) if (not (missing_ops <= set(cpp_registry_ops.keys()))): raise RuntimeError(('Graph ops missing from the python registry (%s) are also absent from the c++ registry.' % missing_ops.difference(set(cpp_registry_ops.keys()))))
Register graph ops absent in op_def_registry, if present in c++ registry. Args: graph_ops: set with graph op names to register. Raises: RuntimeError: if `graph_ops` contains ops that are not in either python or c++ registry.
codesearchnet
async def dist(self, mesg): if self.isfini: return () ret = [] for func in self._syn_funcs.get(mesg[0], ()): try: ret.append(await s_coro.ornot(func, mesg)) except asyncio.CancelledError: raise except Exception: logger.exception('base %s error with mesg %s', self, mesg) for func in self._syn_links: try: ret.append(await func(mesg)) except asyncio.CancelledError: raise except Exception: logger.exception('base %s error with mesg %s', self, mesg) return ret
Distribute an existing event tuple. Args: mesg ((str,dict)): An event tuple. Example: await base.dist( ('foo',{'bar':'baz'}) )
juraj-google-style
def extract_tree_with(self, labels, suppress_unifurcations=True): return self.extract_tree(labels, False, suppress_unifurcations)
Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels`` Args: ``leaves`` (``set``): Set of leaf labels to include. ``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False`` Returns: Tree: Copy of this Tree, including only the leaves labeled by the strings in ``labels``
codesearchnet
def _clone_layers_and_model_config(model, input_layers, layer_fn): created_layers = {} def _copy_layer(layer): if layer in input_layers: created_layers[layer.name] = input_layers[layer] elif layer in model._input_layers: created_layers[layer.name] = InputLayer(**layer.get_config()) else: created_layers[layer.name] = layer_fn(layer) return {} config = functional.get_network_config(model, serialize_layer_fn=_copy_layer) return (config, created_layers)
Clones all layers, and returns the model config without serializing layers. This function ensures that only the node graph is retrieved when getting the model config. The `layer_fn` used to clone layers might not rely on `layer.get_config()`, so some custom layers do not define `get_config`. Trying to retrieve the config results in errors. Args: model: A Functional model. input_layers: Dictionary mapping input layers in `model` to new input layers layer_fn: Function used to clone all non-input layers. Returns: Model config object, and a dictionary of newly created layers.
github-repos
def _convert_validators_to_mapping(validators): validators_mapping = {} for validator in validators: if (not isinstance(validator['check'], collections.Hashable)): check = json.dumps(validator['check']) else: check = validator['check'] key = (check, validator['comparator']) validators_mapping[key] = validator return validators_mapping
convert validators list to mapping. Args: validators (list): validators in list Returns: dict: validators mapping, use (check, comparator) as key. Examples: >>> validators = [ {"check": "v1", "expect": 201, "comparator": "eq"}, {"check": {"b": 1}, "expect": 200, "comparator": "eq"} ] >>> _convert_validators_to_mapping(validators) { ("v1", "eq"): {"check": "v1", "expect": 201, "comparator": "eq"}, ('{"b": 1}', "eq"): {"check": {"b": 1}, "expect": 200, "comparator": "eq"} }
codesearchnet
def get(self, secret_id): return self.prepare_model(self.client.api.inspect_secret(secret_id))
Get a secret. Args: secret_id (str): Secret ID. Returns: (:py:class:`Secret`): The secret. Raises: :py:class:`docker.errors.NotFound` If the secret does not exist. :py:class:`docker.errors.APIError` If the server returns an error.
codesearchnet
def filing_history(self, num, transaction=None, **kwargs): baseuri = self._BASE_URI + "company/{}/filing-history".format(num) if transaction is not None: baseuri += "/{}".format(transaction) res = self.session.get(baseuri, params=kwargs) self.handle_http_error(res) return res
Search for a company's filling history by company number. Args: num (str): Company number to search on. transaction (Optional[str]): Filing record number. kwargs (dict): additional keywords passed into requests.session.get params keyword.
juraj-google-style
def binary_arguments_to_tensors(x1, x2): if not isinstance(x1, Tensor) and not isinstance(x2, Tensor): raise ValueError("at least one of x1 and x2 must be an mtf Tensor") elif isinstance(x1, Tensor) and isinstance(x2, Tensor): return x1, x2 elif isinstance(x1, Tensor): return x1, import_tf_tensor( x1.mesh, tf.convert_to_tensor(x2, dtype=x1.dtype), Shape([])) else: return import_tf_tensor(x2.mesh, tf.convert_to_tensor(x1, dtype=x2.dtype), Shape([])), x2
Convert argument of a binary operation to Tensors. Args: x1: a Tensor or something convertible to a tf Scalar x2: a Tensor or something convertible to a tf Scalar Returns: new_x1: a Tensor new_x2: a Tensor Raises: ValueError: on failure
juraj-google-style
def _stride(stride_spec): if stride_spec is None: return [1, 1, 1, 1] elif isinstance(stride_spec, tf.compat.integral_types): return [1, stride_spec, stride_spec, 1] elif len(stride_spec) == 1: return [1, stride_spec[0], stride_spec[0], 1] elif len(stride_spec) == 2: return [1, stride_spec[0], stride_spec[1], 1] else: assert len(stride_spec) == 4 return stride_spec
Expands the stride spec into a length 4 list. Args: stride_spec: If length 0, 1 or 2 then assign the inner dimensions, otherwise return stride_spec if it is length 4. Returns: A length 4 list.
juraj-google-style
def to_str(self, separator=''): if self.closed(): raise ValueError('Attempt to call to_str() on a closed Queryable.') return str(separator).join(self.select(str))
Build a string from the source sequence. The elements of the query result will each coerced to a string and then the resulting strings concatenated to return a single string. This allows the natural processing of character sequences as strings. An optional separator which will be inserted between each item may be specified. Note: this method uses immediate execution. Args: separator: An optional separator which will be coerced to a string and inserted between each source item in the resulting string. Returns: A single string which is the result of stringifying each element and concatenating the results into a single string. Raises: TypeError: If any element cannot be coerced to a string. TypeError: If the separator cannot be coerced to a string. ValueError: If the Queryable is closed.
codesearchnet
def properties(self, value): if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properties'] = value
The properties property. Args: value (hash). the property value.
juraj-google-style
def report_line(zipfilename: str, contentsfilename: str, line: str, show_inner_file: bool) -> None: if show_inner_file: print("{} [{}]: {}".format(zipfilename, contentsfilename, line)) else: print("{}: {}".format(zipfilename, line))
Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file line: the line from the inner file show_inner_file: if ``True``, show both filenames; if ``False``, show just the ``.zip`` filename
juraj-google-style
def _send(self, **req_kwargs): auth_token = self._auth.getAuthToken() if auth_token is None: raise exception.LoginException('Not logged in') req_kwargs.setdefault('headers', { 'Authorization': 'OAuth ' + auth_token }) return self._session.request(**req_kwargs)
Send an authenticated request to a Google API. Args: **req_kwargs: Arbitrary keyword arguments to pass to Requests. Return: requests.Response: The raw response. Raises: LoginException: If :py:meth:`login` has not been called.
juraj-google-style
def _CheckGrayscaleImage(image, require_static=True): try: if image.get_shape().ndims is None: image_shape = image.get_shape().with_rank(2) else: image_shape = image.get_shape().with_rank_at_least(2) except ValueError: raise ValueError('A grayscale image (shape %s) must be at least two-dimensional.' % image.shape) if require_static and (not image_shape.is_fully_defined()): raise ValueError("'image' must be fully defined.") if image_shape.is_fully_defined(): if image_shape[-1] != 1: raise ValueError('Last dimension of a grayscale image should be size 1.') if not image_shape.is_fully_defined(): return [check_ops.assert_equal(array_ops.shape(image)[-1], 1, message='Last dimension of a grayscale image should be size 1.'), check_ops.assert_greater_equal(array_ops.rank(image), 3, message='A grayscale image must be at least two-dimensional.')] else: return []
Assert that we are working with properly shaped grayscale image. Args: image: >= 2-D Tensor of size [*, 1] require_static: Boolean, whether static shape is required. Raises: ValueError: if image.shape is not a [>= 2] vector or if last dimension is not size 1. Returns: An empty list, if `image` has fully defined dimensions. Otherwise, a list containing an assert op is returned.
github-repos
def post_process_video_grounding(self, logits, video_durations): start, end = (round(logits.tolist()[0][0] * video_durations, 1), round(logits.tolist()[0][1] * video_durations, 1)) return (start, end)
Compute the time of the video. Args: logits (`torch.Tensor`): The logits output of TvpForVideoGrounding. video_durations (`float`): The video's duration. Returns: start (`float`): The start time of the video. end (`float`): The end time of the video.
github-repos
def get_commit_tree(profile, sha): data = commits.get_commit(profile, sha) tree = data.get("tree") sha = tree.get("sha") return sha
Get the SHA of a commit's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. sha The SHA of a commit. Returns: The SHA of the commit's tree.
juraj-google-style
def diffusion_mds(means, weights, d, diffusion_rounds=10): for i in range(diffusion_rounds): weights = (weights * weights) weights = (weights / weights.sum(0)) X = dim_reduce(means, weights, d) if (X.shape[0] == 2): return X.dot(weights) else: return X.T.dot(weights)
Dimensionality reduction using MDS, while running diffusion on W. Args: means (array): genes x clusters weights (array): clusters x cells d (int): desired dimensionality Returns: W_reduced (array): array of shape (d, cells)
codesearchnet
def WaitUntilDone(self, timeout=None): utils.Poll( generator=self.GetState, condition=lambda s: s != self.__class__.STATE_RUNNING, timeout=timeout) self.target_file = self.target_file.Get() return self
Wait until the operation is done. Args: timeout: timeout in seconds. None means default timeout (1 hour). 0 means no timeout (wait forever). Returns: Operation object with refreshed target_file. Raises: PollTimeoutError: if timeout is reached.
juraj-google-style
def _compile_arithmetic_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> TensorFluent: etype = expr.etype args = expr.args if len(args) == 1: etype2op = { '+': lambda x: x, '-': lambda x: -x } if etype[1] not in etype2op: raise ValueError('Invalid binary arithmetic expression:\n{}'.format(expr)) op = etype2op[etype[1]] x = self._compile_expression(args[0], scope, batch_size, noise) fluent = op(x) else: etype2op = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y, } if etype[1] not in etype2op: raise ValueError('Invalid binary arithmetic expression:\n{}'.format(expr)) op = etype2op[etype[1]] x = self._compile_expression(args[0], scope, batch_size, noise) y = self._compile_expression(args[1], scope, batch_size, noise) fluent = op(x, y) return fluent
Compile an arithmetic expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL arithmetic expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optional[size]): The batch size. Returns: :obj:`rddl2tf.fluent.TensorFluent`: The compiled expression as a TensorFluent.
juraj-google-style
def _check_etag(self, etag): if (etag is None): return elif (self._etag is None): self._etag = etag elif (self._etag != etag): raise ValueError('File on GCS has changed while reading.')
Check if etag is the same across requests to GCS. If self._etag is None, set it. If etag is set, check that the new etag equals the old one. In the __init__ method, we fire one HEAD and one GET request using ndb tasklet. One of them would return first and set the first value. Args: etag: etag from a GCS HTTP response. None if etag is not part of the response header. It could be None for example in the case of GCS composite file. Raises: ValueError: if two etags are not equal.
codesearchnet
def stop_site(name): ps_cmd = ['Stop-WebSite', "'{0}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return (cmd_ret['retcode'] == 0)
Stop a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to stop. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.stop_site name='My Test Site'
codesearchnet
def assignSchedule(self, schedule, period, hour, minute, tariff): if ((schedule not in range(Extents.Schedules)) or (period not in range(Extents.Tariffs)) or (hour < 0) or (hour > 23) or (minute < 0) or (minute > 59) or (tariff < 0)): ekm_log(('Out of bounds in Schedule_' + str((schedule + 1)))) return False period += 1 idx_min = ('Min_' + str(period)) idx_hour = ('Hour_' + str(period)) idx_rate = ('Tariff_' + str(period)) if (idx_min not in self.m_schedule_params): ekm_log(('Incorrect index: ' + idx_min)) return False if (idx_hour not in self.m_schedule_params): ekm_log(('Incorrect index: ' + idx_hour)) return False if (idx_rate not in self.m_schedule_params): ekm_log(('Incorrect index: ' + idx_rate)) return False self.m_schedule_params[idx_rate] = tariff self.m_schedule_params[idx_hour] = hour self.m_schedule_params[idx_min] = minute self.m_schedule_params['Schedule'] = schedule return True
Assign one schedule tariff period to meter bufffer. Args: schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extents.Schedules). tariff (int): :class:`~ekmmeters.Tariffs` value or in range(Extents.Tariffs). hour (int): Hour from 0-23. minute (int): Minute from 0-59. tariff (int): Rate value. Returns: bool: True on completed assignment.
codesearchnet
def disease_term(self, disease_identifier): query = {} try: disease_identifier = int(disease_identifier) query['disease_nr'] = disease_identifier except ValueError: query['_id'] = disease_identifier return self.disease_term_collection.find_one(query)
Return a disease term Checks if the identifier is a disease number or a id Args: disease_identifier(str) Returns: disease_obj(dict)
codesearchnet
def get_pool_context(self): context = {self.current.lane_id: self.current.role, 'self': self.current.role} for (lane_id, role_id) in self.current.pool.items(): if role_id: context[lane_id] = lazy_object_proxy.Proxy((lambda : self.role_model(super_context).objects.get(role_id))) return context
Builds context for the WF pool. Returns: Context dict.
codesearchnet
def semantic_eq(node1, node2): if 'barrier' == node1.name == node2.name: return set(node1.qargs) == set(node2.qargs) return node1.data_dict == node2.data_dict
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic. Args: node1 (DAGNode): A node to compare. node2 (DAGNode): The other node to compare. Return: Bool: If node1 == node2
juraj-google-style
def match(self, name): if self.method == Ex.Method.PREFIX: return name.startswith(self.value) elif self.method == Ex.Method.SUFFIX: return name.endswith(self.value) elif self.method == Ex.Method.CONTAINS: return self.value in name elif self.method == Ex.Method.EXACT: return self.value == name elif self.method == Ex.Method.REGEX: return re.search(self.value, name) return False
Check if given name matches. Args: name (str): name to check. Returns: bool: matches name.
juraj-google-style
class Rescaling(TFDataLayer): def __init__(self, scale, offset=0.0, **kwargs): super().__init__(**kwargs) self.scale = scale self.offset = offset self.supports_masking = True def call(self, inputs): dtype = self.compute_dtype scale = self.backend.cast(self.scale, dtype) offset = self.backend.cast(self.offset, dtype) scale_shape = self.backend.core.shape(scale) if len(scale_shape) > 0 and backend.image_data_format() == 'channels_first': scale = self.backend.numpy.reshape(scale, scale_shape + (1,) * (3 - len(scale_shape))) return self.backend.cast(inputs, dtype) * scale + offset def compute_output_shape(self, input_shape): return input_shape def get_config(self): config = super().get_config() config.update({'scale': serialization_lib.serialize_keras_object(self.scale), 'offset': serialization_lib.serialize_keras_object(self.offset)}) return config @classmethod def from_config(cls, config, custom_objects=None): config = config.copy() config['scale'] = serialization_lib.deserialize_keras_object(config['scale'], custom_objects=custom_objects) config['offset'] = serialization_lib.deserialize_keras_object(config['offset'], custom_objects=custom_objects) return cls(**config)
A preprocessing layer which rescales input values to a new range. This layer rescales every value of an input (often an image) by multiplying by `scale` and adding `offset`. For instance: 1. To rescale an input in the `[0, 255]` range to be in the `[0, 1]` range, you would pass `scale=1./255`. 2. To rescale an input in the `[0, 255]` range to be in the `[-1, 1]` range, you would pass `scale=1./127.5, offset=-1`. The rescaling is applied both during training and inference. Inputs can be of integer or floating point dtype, and by default the layer will output floats. **Note:** This layer is safe to use inside a `tf.data` pipeline (independently of which backend you're using). Args: scale: Float, the scale to apply to the inputs. offset: Float, the offset to apply to the inputs. **kwargs: Base layer keyword arguments, such as `name` and `dtype`.
github-repos
def render(self, container, descender, state, space_below=0, first_line_only=False): indent_first = (float(self.get_style('indent_first', container)) if state.initial else 0) line_width = float(container.width) line_spacing = self.get_style('line_spacing', container) text_align = self.get_style('text_align', container) tab_stops = self.get_style('tab_stops', container) if (not tab_stops): tab_width = (2 * self.get_style('font_size', container)) tab_stops = DefaultTabStops(tab_width) saved_state = copy(state) prev_state = copy(state) max_line_width = 0 def typeset_line(line, last_line=False): "Typeset `line` and, if no exception is raised, update the\n paragraph's internal rendering state." nonlocal state, saved_state, max_line_width, descender, space_below max_line_width = max(max_line_width, line.cursor) advance = (line.ascender(container) if (descender is None) else line_spacing.advance(line, descender, container)) descender = line.descender(container) line.advance = advance total_advance = ((advance + (space_below if last_line else 0)) - descender) if (container.remaining_height < total_advance): raise EndOfContainer(saved_state) assert container.advance2(advance) line.typeset(container, text_align, last_line) assert container.advance2((- descender)) state.initial = False saved_state = copy(state) return Line(tab_stops, line_width, container, significant_whitespace=self.significant_whitespace) first_line = line = Line(tab_stops, line_width, container, indent_first, self.significant_whitespace) while True: try: word = state.next_word() except StopIteration: break try: if (not line.append_word(word)): for (first, second) in word.hyphenate(container): if line.append_word(first): state.prepend_word(second) break else: state = prev_state line = typeset_line(line) if first_line_only: break continue except NewLineException: line.append(word.glyphs_span) line = typeset_line(line, last_line=True) if first_line_only: break prev_state = copy(state) if line: typeset_line(line, last_line=True) if (self._width(container) == FlowableWidth.AUTO): if (text_align == TextAlign.CENTER): container.left -= (float((container.width - max_line_width)) / 2) if (text_align == TextAlign.RIGHT): container.left -= float((container.width - max_line_width)) return (max_line_width, first_line.advance, descender)
Typeset the paragraph The paragraph is typeset in the given container starting below the current cursor position of the container. When the end of the container is reached, the rendering state is preserved to continue setting the rest of the paragraph when this method is called with a new container. Args: container (Container): the container to render to descender (float or None): descender height of the preceeding line state (ParagraphState): the state where rendering will continue first_line_only (bool): typeset only the first line
codesearchnet
def __init__(self, sender, persistence_path=''): if persistence_path and PersistQueue is None: raise ValueError('persistence_path argument requires persist-queue dependency to be installed') elif persistence_path: self._queue = PersistQueue(persistence_path) else: self._queue = Queue() self._persistence_path = persistence_path self._max_queue_length = 500 self._sender = sender if sender: self._sender.queue = self
Initializes a new instance of the class. Args: sender (:class:`SenderBase`) the sender object that will be used in conjunction with this queue. persistence_path (str) if set, persist the queue on disk into the provided directory.
juraj-google-style
def __init__(self, output_path, open_function=open): self._output_path = output_path self._open_function = open_function self._old_enabled = None
Initialize. Args: output_path: The path for the metrics data. If empty, no metrics are collected. open_function: A custom file opening function.
github-repos
def get_credentials(self): return ReadOnlyCredentials(self.access_token, self.client_id, self.client_secret, self.refresh_token)
Get read-only credentials. Returns: class: Read-only credentials.
codesearchnet
def set(self, option, value=None): option = self._container.optionxform(option) if option in self.options(): self.__getitem__(option).value = value else: self.__setitem__(option, value) return self
Set an option for chaining. Args: option (str): option name value (str): value, default None
juraj-google-style
def measures(*measurements, **kwargs): def _maybe_make(meas): 'Turn strings into Measurement objects if necessary.' if isinstance(meas, Measurement): return meas elif isinstance(meas, six.string_types): return Measurement(meas, **kwargs) raise InvalidMeasurementType('Expected Measurement or string', meas) if (kwargs and (len(measurements) != 1)): raise InvalidMeasurementType('If @measures kwargs are provided, a single measurement name must be provided as a positional arg first.') if ('outcome' in kwargs): raise ValueError('Cannot specify outcome in measurement declaration!') measurements = [_maybe_make(meas) for meas in measurements] def decorate(wrapped_phase): 'Phase decorator to be returned.' phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(wrapped_phase) duplicate_names = (set((m.name for m in measurements)) & set((m.name for m in phase.measurements))) if duplicate_names: raise DuplicateNameError('Measurement names duplicated', duplicate_names) phase.measurements.extend(measurements) return phase return decorate
Decorator-maker used to declare measurements for phases. See the measurements module docstring for examples of usage. Args: measurements: Measurement objects to declare, or a string name from which to create a Measurement. kwargs: Keyword arguments to pass to Measurement constructor if we're constructing one. Note that if kwargs are provided, the length of measurements must be 1, and that value must be a string containing the measurement name. For valid kwargs, see the definition of the Measurement class. Returns: A decorator that declares the measurement(s) for the decorated phase.
codesearchnet
def _parse_request_arguments(self, request): inference_addresses = request.args.get('inference_address').split(',') model_names = request.args.get('model_name').split(',') model_versions = request.args.get('model_version').split(',') model_signatures = request.args.get('model_signature').split(',') if (len(model_names) != len(inference_addresses)): raise common_utils.InvalidUserInputError(('Every model should have a ' + 'name and address.')) return (inference_addresses, model_names, model_versions, model_signatures)
Parses comma separated request arguments Args: request: A request that should contain 'inference_address', 'model_name', 'model_version', 'model_signature'. Returns: A tuple of lists for model parameters
codesearchnet
def get_terminal_size(): try: from IPython import get_ipython ipython = get_ipython() from ipykernel import zmqshell if isinstance(ipython, zmqshell.ZMQInteractiveShell): return (79, 24) except Exception: pass try: import shutil (w, h) = shutil.get_terminal_size() if (w and h): return ((w - 1), h) except Exception: pass try: w = int(os.environ.get('COLUMNS')) h = int(os.environ.get('LINES')) if (w and h): return (w, h) except Exception: pass try: import blessings terminal = blessings.Terminal() w = terminal.width h = terminal.height if (w and h): return (w, h) except Exception: pass try: (w, h) = _get_terminal_size_linux() if (w and h): return (w, h) except Exception: pass try: (w, h) = _get_terminal_size_windows() if (w and h): return (w, h) except Exception: pass try: (w, h) = _get_terminal_size_tput() if (w and h): return (w, h) except Exception: pass return (79, 24)
Get the current size of your terminal Multiple returns are not always a good idea, but in this case it greatly simplifies the code so I believe it's justified. It's not the prettiest function but that's never really possible with cross-platform code. Returns: width, height: Two integers containing width and height
codesearchnet
def find_mip(self, direction, mechanism, purview, allow_neg=False): alpha_min = float('inf') probability = self.probability(direction, mechanism, purview) for partition in mip_partitions(mechanism, purview, self.node_labels): partitioned_probability = self.partitioned_probability(direction, partition) alpha = log2((probability / partitioned_probability)) if (utils.eq(alpha, 0) or ((alpha < 0) and (not allow_neg))): return AcRepertoireIrreducibilityAnalysis(state=self.mechanism_state(direction), direction=direction, mechanism=mechanism, purview=purview, partition=partition, probability=probability, partitioned_probability=partitioned_probability, node_labels=self.node_labels, alpha=0.0) if ((abs(alpha_min) - abs(alpha)) > constants.EPSILON): alpha_min = alpha acria = AcRepertoireIrreducibilityAnalysis(state=self.mechanism_state(direction), direction=direction, mechanism=mechanism, purview=purview, partition=partition, probability=probability, partitioned_probability=partitioned_probability, node_labels=self.node_labels, alpha=alpha_min) return acria
Find the ratio minimum information partition for a mechanism over a purview. Args: direction (str): |CAUSE| or |EFFECT| mechanism (tuple[int]): A mechanism. purview (tuple[int]): A purview. Keyword Args: allow_neg (boolean): If true, ``alpha`` is allowed to be negative. Otherwise, negative values of ``alpha`` will be treated as if they were 0. Returns: AcRepertoireIrreducibilityAnalysis: The irreducibility analysis for the mechanism.
codesearchnet
def del_hparam(self, name): if hasattr(self, name): delattr(self, name) del self._hparam_types[name]
Removes the hyperparameter with key 'name'. Does nothing if it isn't present. Args: name: Name of the hyperparameter.
codesearchnet
def __squid_to_guid(self, squid): if not squid: return '' squid_match = self.__squid_pattern.match(squid) guid = '' if squid_match is not None: guid = '{' +\ squid_match.group(1)[::-1]+'-' +\ squid_match.group(2)[::-1]+'-' +\ squid_match.group(3)[::-1]+'-' +\ squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-' for index in range(6, 12): guid += squid_match.group(index)[::-1] guid += '}' return guid
Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided.
juraj-google-style
def persist_experiment(experiment): from benchbuild.utils.schema import Experiment, Session session = Session() cfg_exp = experiment.id LOG.debug("Using experiment ID stored in config: %s", cfg_exp) exps = session.query(Experiment).filter(Experiment.id == cfg_exp) desc = str(CFG["experiment_description"]) name = experiment.name if exps.count() == 0: newe = Experiment() newe.id = cfg_exp newe.name = name newe.description = desc session.add(newe) ret = newe else: exps.update({'name': name, 'description': desc}) ret = exps.first() try: session.commit() except IntegrityError: session.rollback() persist_experiment(experiment) return (ret, session)
Persist this experiment in the benchbuild database. Args: experiment: The experiment we want to persist.
juraj-google-style
def __init__(self): super(JLinkSpeedInfo, self).__init__() self.SizeOfStruct = ctypes.sizeof(self)
Initializes the ``JLinkSpeedInfo`` instance. Sets the size of the structure. Args: self (JLinkSpeedInfo): the ``JLinkSpeedInfo`` instance Returns: ``None``
juraj-google-style
def connect_sync(self, connection_id, connection_string): calldone = threading.Event() results = {} def connect_done(callback_connid, callback_adapterid, callback_success, failure_reason): results['success'] = callback_success results['failure_reason'] = failure_reason calldone.set() self.connect_async(connection_id, connection_string, connect_done) calldone.wait() return results
Synchronously connect to a device Args: connection_id (int): A unique identifier that will refer to this connection connection_string (string): A DeviceAdapter specific string that can be used to connect to a device using this DeviceAdapter. Returns: dict: A dictionary with two elements 'success': a bool with the result of the connection attempt 'failure_reason': a string with the reason for the failure if we failed
codesearchnet
def _get_programs_dict(): global __programs_dict if (__programs_dict is not None): return __programs_dict d = __programs_dict = OrderedDict() for pkgname in COLLABORATORS_S: try: package = importlib.import_module(pkgname) except ImportError: continue path_ = os.path.join(os.path.split(package.__file__)[0], 'scripts') bulk = a99.get_exe_info(path_, flag_protected=True) d[pkgname] = {'description': a99.get_obj_doc0(package), 'exeinfo': bulk} return __programs_dict
Builds and returns programs dictionary This will have to import the packages in COLLABORATORS_S in order to get their absolute path. Returns: dictionary: {"packagename": [ExeInfo0, ...], ...} "packagename" examples: "f311.explorer", "numpy"
codesearchnet
def add_comment(self, line): if (not isinstance(self.last_item, Comment)): comment = Comment(self._structure) self._structure.append(comment) self.last_item.add_line(line) return self
Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the comment
codesearchnet
def from_dim_sizes(dim_sizes): with ops.name_scope(None, 'RaggedTensorDynamicShapeFromDimensionSizes', [dim_sizes]): dim_sizes = tuple((ops.convert_to_tensor(size, preferred_dtype=dtypes.int64, name='dim_sizes') for size in dim_sizes)) inner_split = 0 for dim, dim_size in enumerate(dim_sizes): if dim_size.shape.ndims == 1: inner_split = dim + 1 elif dim_size.shape.ndims != 0: raise ValueError('Each dim_size must be a scalar or a vector') return RaggedTensorDynamicShape(dim_sizes[:inner_split], dim_sizes[inner_split:])
Constructs a ragged shape from a list of dimension sizes. This list contains a single tensor for each dimension, where the tensor is a scalar if the dimension is uniform, or a vector if the dimension is ragged. Args: dim_sizes: List of int32 or int64 scalars or vectors. Returns: A RaggedTensorDynamicShape.
github-repos
def basis(sample_paths, time_index): sample_paths = tf.convert_to_tensor(sample_paths, name='sample_paths') if sample_paths.shape.rank == 3: sample_paths = tf.expand_dims(sample_paths, axis=0) shape = tf.shape(sample_paths) num_samples = shape[1] batch_size = shape[0] dim = sample_paths.shape[-1] slice_samples = tf.slice(sample_paths, [0, 0, time_index, 0], [batch_size, num_samples, 1, dim]) samples_centered = slice_samples - tf.math.reduce_mean(slice_samples, axis=1, keepdims=True) grid = tf.range(degree + 1, dtype=samples_centered.dtype) grid = tf.meshgrid(*dim * [grid]) grid = tf.reshape(tf.stack(grid, -1), [-1, dim]) basis_expansion = tf.reduce_prod(samples_centered ** grid, axis=-1) return tf.transpose(basis_expansion, [0, 2, 1])
Computes polynomial basis expansion at the given sample points. Args: sample_paths: A `Tensor` of either `flaot32` or `float64` dtype and of either shape `[num_samples, num_times, dim]` or `[batch_size, num_samples, num_times, dim]`. time_index: An integer scalar `Tensor` that corresponds to the time coordinate at which the basis function is computed. Returns: A `Tensor`s of shape `[batch_size, (degree + 1)**dim, num_samples]`.
github-repos
def TotalFees(self): amount = Fixed8.Zero() for tx in self.Transactions: amount += tx.SystemFee() return amount
Get the total transaction fees in the block. Returns: Fixed8:
codesearchnet
def parse_table_data(lines): data = '\n'.join([i.rstrip() for i in lines if ((not i.startswith(('^', '!', ' if data: return read_csv(StringIO(data), index_col=None, sep='\t') else: return DataFrame()
Parse list of lines from SOFT file into DataFrame. Args: lines (:obj:`Iterable`): Iterator over the lines. Returns: :obj:`pandas.DataFrame`: Table data.
codesearchnet
def depth_soil_density(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `depth_soil_density`'.format(value)) self._depth_soil_density = value
Corresponds to IDD Field `depth_soil_density` Args: value (float): value for IDD Field `depth_soil_density` Unit: kg/m3 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
juraj-google-style
def _remove_files(files): logger.debug("Request for file removal (_remove_files()).") for fn in files: if os.path.exists(fn): logger.debug("Removing '%s'." % fn) os.remove(fn)
Remove all given files. Args: files (list): List of filenames, which will be removed.
juraj-google-style
def set_seed(seed: int, deterministic: bool=False): random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) if deterministic: torch.use_deterministic_algorithms(True) if is_torch_mlu_available(): torch.mlu.manual_seed_all(seed) if is_torch_musa_available(): torch.musa.manual_seed_all(seed) if is_torch_npu_available(): torch.npu.manual_seed_all(seed) if is_torch_hpu_available(): torch.hpu.manual_seed_all(seed) if is_torch_xpu_available(): torch.xpu.manual_seed_all(seed) if is_tf_available(): import tensorflow as tf tf.random.set_seed(seed) if deterministic: tf.config.experimental.enable_op_determinism()
Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch` and/or `tf` (if installed). Args: seed (`int`): The seed to set. deterministic (`bool`, *optional*, defaults to `False`): Whether to use deterministic algorithms where available. Can slow down training.
github-repos
def validate(self, graph): if not nx.is_directed_acyclic_graph(graph): raise DirectedAcyclicGraphInvalid(graph_name=self._name)
Validate the graph by checking whether it is a directed acyclic graph. Args: graph (DiGraph): Reference to a DiGraph object from NetworkX. Raises: DirectedAcyclicGraphInvalid: If the graph is not a valid dag.
juraj-google-style
def get_structure(atoms, cls=None): symbols = atoms.get_chemical_symbols() positions = atoms.get_positions() lattice = atoms.get_cell() cls = Structure if cls is None else cls return cls(lattice, symbols, positions, coords_are_cartesian=True)
Returns pymatgen structure from ASE Atoms. Args: atoms: ASE Atoms object cls: The Structure class to instantiate (defaults to pymatgen structure) Returns: Equivalent pymatgen.core.structure.Structure
juraj-google-style
def Verify(self): return getattr(self, self._KEY) is not None
We can properly index this instance into a Map. Returns: True if the value in the attribute named by self._KEY for this class is not None. False otherwise.
github-repos
def set_epsilon(value): global _EPSILON _EPSILON = value
Sets the value of the fuzz factor used in numeric expressions. Args: value: float. New value of epsilon. Example: >>> tf.keras.backend.epsilon() 1e-07 >>> tf.keras.backend.set_epsilon(1e-5) >>> tf.keras.backend.epsilon() 1e-05 >>> tf.keras.backend.set_epsilon(1e-7)
github-repos
def __init__(self, state_handler: sdk_worker.CachingStateHandler, transform_id: str, key_coder: coders.Coder, window_coder: coders.Coder) -> None: self._state_handler = state_handler self._transform_id = transform_id self._key_coder = key_coder self._window_coder = window_coder self._timers_info: Dict[str, TimerInfo] = {} self._all_states: Dict[tuple, FnApiUserRuntimeStateTypes] = {}
Initialize a ``FnApiUserStateContext``. Args: state_handler: A StateServicer object. transform_id: The name of the PTransform that this context is associated. key_coder: Coder for the key type. window_coder: Coder for the window type.
github-repos
def __le__(self, other: 'TensorFluent') -> 'TensorFluent': return self._binary_op(self, other, tf.less_equal, tf.float32)
Returns a TensorFluent for the less-than-or-equal relational operator. Args: self: The first operand. other: The second operand.
juraj-google-style
def _handle_emailauth(maildomain='', message=''): print('SteamGuard requires email authentication...') emailauth = input(('Please enter the code sent to your mail address at "%s": ' % maildomain)) emailauth.upper() return emailauth
Called when SteamGuard requires authentication via e-mail. Asks the user to enter the code. Args: maildomain: Optional. The mail domain of the e-mail address the SteamGuard code is send to. message: Optional. A message from Steam service. Returns: A string containing the code.
codesearchnet
def load_transcripts(adapter, transcripts_lines=None, build='37', ensembl_genes=None): ensembl_genes = ensembl_genes or adapter.ensembl_genes(build) if transcripts_lines is None: transcripts_lines = fetch_ensembl_transcripts(build=build) transcripts_dict = parse_transcripts(transcripts_lines) for ens_tx_id in list(transcripts_dict): parsed_tx = transcripts_dict[ens_tx_id] ens_gene_id = parsed_tx['ensembl_gene_id'] gene_obj = ensembl_genes.get(ens_gene_id) if not gene_obj: transcripts_dict.pop(ens_tx_id) LOG.debug("Gene %s does not exist in build %s", ens_gene_id, build) continue parsed_tx['hgnc_id'] = gene_obj['hgnc_id'] parsed_tx['primary_transcripts'] = set(gene_obj.get('primary_transcripts', [])) ref_seq_transcripts = 0 nr_primary_transcripts = 0 nr_transcripts = len(transcripts_dict) transcript_objs = [] with progressbar(transcripts_dict.values(), label="Building transcripts", length=nr_transcripts) as bar: for tx_data in bar: tx_data['is_primary'] = False primary_transcripts = tx_data['primary_transcripts'] refseq_identifier = None refseq_identifiers = [] for category in TRANSCRIPT_CATEGORIES: identifiers = tx_data[category] if not identifiers: continue for refseq_id in identifiers: refseq_identifiers.append(refseq_id) ref_seq_transcripts += 1 if refseq_id in primary_transcripts: refseq_identifier = refseq_id tx_data['is_primary'] = True nr_primary_transcripts += 1 if not refseq_identifier: refseq_identifier = refseq_id if refseq_identifier: tx_data['refseq_id'] = refseq_identifier if refseq_identifiers: tx_data['refseq_identifiers'] = refseq_identifiers tx_obj = build_transcript(tx_data, build) transcript_objs.append(tx_obj) LOG.info("Loading transcripts...") if len(transcript_objs) > 0: adapter.load_transcript_bulk(transcript_objs) LOG.info('Number of transcripts in build %s: %s', build, nr_transcripts) LOG.info('Number of transcripts with refseq identifier: %s', ref_seq_transcripts) LOG.info('Number of primary transcripts: %s', nr_primary_transcripts) return transcript_objs
Load all the transcripts Transcript information is from ensembl. Args: adapter(MongoAdapter) transcripts_lines(iterable): iterable with ensembl transcript lines build(str) ensembl_genes(dict): Map from ensembl_id -> HgncGene Returns: transcript_objs(list): A list with all transcript objects
juraj-google-style