diff --git "a/test.jsonl" "b/test.jsonl" new file mode 100644--- /dev/null +++ "b/test.jsonl" @@ -0,0 +1,4909 @@ +{"code": "def _CalculateElementsDataSize(self, context):\n elements_data_size = None\n if self._HasElementsDataSize():\n elements_data_size = self._EvaluateElementsDataSize(context)\n elif self._HasNumberOfElements():\n element_byte_size = self._element_data_type_definition.GetByteSize()\n if (element_byte_size is not None):\n number_of_elements = self._EvaluateNumberOfElements(context)\n elements_data_size = (number_of_elements * element_byte_size)\n return elements_data_size", "docstring": "Calculates the elements data size.\n\nArgs:\n context (Optional[DataTypeMapContext]): data type map context, used to\n determine the size hint.\n\nReturns:\n int: the elements data size or None if not available.", "source": "codesearchnet_filtered"} +{"code": "def unlock_kinetis_identified(identity, flags):\n if (flags.version_code != identity.version_code):\n return False\n if (flags.part_no != identity.part_no):\n return False\n return flags.valid", "docstring": "Checks whether the given flags are a valid identity.\n\nArgs:\n identity (Identity): the identity to validate against\n flags (register.IDCodeRegisterFlags): the set idcode flags\n\nReturns:\n ``True`` if the given ``flags`` correctly identify the the debug\n interface, otherwise ``False``.", "source": "codesearchnet_filtered"} +{"code": "def install_json_params(self, ij=None):\n if ((self._install_json_params is None) or (ij is not None)):\n self._install_json_params = {}\n if (ij is None):\n ij = self.install_json\n for p in (ij.get('params') or []):\n self._install_json_params.setdefault(p.get('name'), p)\n return self._install_json_params", "docstring": "Return install.json params in a dict with name param as key.\n\nArgs:\n ij (dict, optional): Defaults to None. The install.json contents.\n\nReturns:\n dict: A dictionary containing the install.json input params with name as key.", "source": "codesearchnet_filtered"} +{"code": "def extract(self, html_text: str, strategy: Strategy=Strategy.ALL_TEXT) -> List[Extraction]:\n if html_text:\n if (strategy == Strategy.ALL_TEXT):\n soup = BeautifulSoup(html_text, 'html.parser')\n texts = soup.findAll(text=True)\n visible_texts = filter(self._tag_visible, texts)\n all_text = u' '.join((t.strip() for t in visible_texts))\n return [Extraction(all_text, self.name)]\n else:\n relax = (strategy == Strategy.MAIN_CONTENT_RELAXED)\n readable = Document(html_text, recallPriority=relax).summary(html_partial=False)\n clean_text = BeautifulSoup(readable.encode('utf-8'), 'lxml').strings\n readability_text = ' '.join(clean_text)\n return [Extraction(readability_text, self.name)]\n else:\n return []", "docstring": "Extracts text from an HTML page using a variety of strategies\n\nArgs:\n html_text (str): html page in string\n strategy (enum[Strategy.ALL_TEXT, Strategy.MAIN_CONTENT_RELAXED, Strategy.MAIN_CONTENT_STRICT]): one of\n Strategy.ALL_TEXT, Strategy.MAIN_CONTENT_STRICT and Strategy.MAIN_CONTENT_RELAXED\n\nReturns:\n List[Extraction]: typically a singleton list with the extracted text", "source": "codesearchnet_filtered"} +{"code": "def mkdir(path):\n try:\n os.makedirs(path)\n if (not os.path.isdir(path)):\n raise IOError('path is not a directory')\n except OSError as e:\n if ((e.errno == 17) and os.path.isdir(path)):\n return\n raise", "docstring": "Make a directory and its parents.\n\nArgs:\n path (str): path to create\n\nReturns:\n None\n\nRaises:\n OSError if the directory cannot be created.", "source": "codesearchnet_filtered"} +{"code": "def kde_partition_data(data, estimate_tails=True):\n kde = stats.kde.gaussian_kde(data)\n evaluation_bins = np.linspace(start=(np.min(data) - (kde.covariance_factor() / 2)), stop=(np.max(data) + (kde.covariance_factor() / 2)), num=np.floor((((np.max(data) - np.min(data)) / kde.covariance_factor()) + 1)).astype(int))\n cdf_vals = [kde.integrate_box_1d((- np.inf), x) for x in evaluation_bins]\n evaluation_weights = np.diff(cdf_vals)\n if estimate_tails:\n bins = np.concatenate(([(np.min(data) - (1.5 * kde.covariance_factor()))], evaluation_bins, [(np.max(data) + (1.5 * kde.covariance_factor()))]))\n else:\n bins = np.concatenate(([(- np.inf)], evaluation_bins, [np.inf]))\n weights = np.concatenate(([cdf_vals[0]], evaluation_weights, [(1 - cdf_vals[(- 1)])]))\n return {'bins': bins, 'weights': weights}", "docstring": "Convenience method for building a partition and weights using a gaussian Kernel Density Estimate and default bandwidth.\n\nArgs:\n data (list-like): The data from which to construct the estimate\n estimate_tails (bool): Whether to estimate the tails of the distribution to keep the partition object finite\n\nReturns:\n A new partition_object::\n\n {\n \"partition\": (list) The endpoints of the partial partition of reals,\n \"weights\": (list) The densities of the bins implied by the partition.\n }", "source": "codesearchnet_filtered"} +{"code": "def iter_compress(item_iter, flag_iter):\n true_items = (item for (item, flag) in zip(item_iter, flag_iter) if flag)\n return true_items", "docstring": "iter_compress - like numpy compress\n\nArgs:\n item_iter (list):\n flag_iter (list): of bools\n\nReturns:\n list: true_items\n\nExample:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_iter import * # NOQA\n >>> item_iter = [1, 2, 3, 4, 5]\n >>> flag_iter = [False, True, True, False, True]\n >>> true_items = iter_compress(item_iter, flag_iter)\n >>> result = list(true_items)\n >>> print(result)\n [2, 3, 5]", "source": "codesearchnet_filtered"} +{"code": "def load(config):\n if config.sys_path:\n logger.debug('Appending %s to sys.path.', config.sys_path)\n sys.path.append(config.sys_path)\n logger.debug('sys.path is now %s', sys.path)\n if config.lookups:\n for (key, handler) in config.lookups.items():\n register_lookup_handler(key, handler)\n return config", "docstring": "Loads a stacker configuration by modifying sys paths, loading lookups,\n etc.\n\nArgs:\n config (:class:`Config`): the stacker config to load.\n\nReturns:\n :class:`Config`: the stacker config provided above.", "source": "codesearchnet_filtered"} +{"code": "def predict_proba(self, a, b, idx=0, **kwargs):\n return self.predict_dataset(DataFrame([[a, b]], columns=['A', 'B']))", "docstring": "Use Jarfo to predict the causal direction of a pair of vars.\n\nArgs:\n a (numpy.ndarray): Variable 1\n b (numpy.ndarray): Variable 2\n idx (int): (optional) index number for printing purposes\n\nReturns:\n float: Causation score (Value : 1 if a->b and -1 if b->a)", "source": "codesearchnet_filtered"} +{"code": "def iter_cast(inputs, dst_type, return_type=None):\n if (not isinstance(inputs, collections_abc.Iterable)):\n raise TypeError('inputs must be an iterable object')\n if (not isinstance(dst_type, type)):\n raise TypeError('\"dst_type\" must be a valid type')\n out_iterable = six.moves.map(dst_type, inputs)\n if (return_type is None):\n return out_iterable\n else:\n return return_type(out_iterable)", "docstring": "Cast elements of an iterable object into some type.\n\nArgs:\n inputs (Iterable): The input object.\n dst_type (type): Destination type.\n return_type (type, optional): If specified, the output object will be\n converted to this type, otherwise an iterator.\n\nReturns:\n iterator or specified type: The converted object.", "source": "codesearchnet_filtered"} +{"code": "def get_airport_metars_hist(self, iata):\n url = (AIRPORT_BASE.format(iata) + '/weather')\n return self._fr24.get_airport_metars_hist(url)", "docstring": "Retrieve the metar data for past 72 hours. The data will not be parsed to readable format.\n\n Given the IATA code of an airport, this method returns the metar information for last 72 hours.\n\nArgs:\n iata (str): The IATA code for an airport, e.g. HYD\n\nReturns:\n The metar data for the airport\n\n Example::\n\n from pyflightdata import FlightData\n f=FlightData()\n #optional login\n f.login(myemail,mypassword)\n f.get_airport_metars_hist('HYD')", "source": "codesearchnet_filtered"} +{"code": "def expand(tmpl, *args, **kwargs):\n replacer = functools.partial(_expand_variable_match, list(args), kwargs)\n return _VARIABLE_RE.sub(replacer, tmpl)", "docstring": "Expand a path template with the given variables.\n\n ..code-block:: python\n\n >>> expand('users/*/messages/*', 'me', '123')\n users/me/messages/123\n >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3')\n /v1/shelves/1/books/3\n\nArgs:\n tmpl (str): The path template.\n args: The positional variables for the path.\n kwargs: The named variables for the path.\n\nReturns:\n str: The expanded path\n\nRaises:\n ValueError: If a positional or named variable is required by the\n template but not specified or if an unexpected template expression\n is encountered.", "source": "codesearchnet_filtered"} +{"code": "def FromFile(cls, in_path):\n with open(in_path, 'rb') as infile:\n in_data = json.load(infile)\n if (not (('trace', 'selectors') in in_data)):\n raise ArgumentError('Invalid trace file format', keys=in_data.keys(), expected=('trace', 'selectors'))\n selectors = [DataStreamSelector.FromString(x) for x in in_data['selectors']]\n readings = [IOTileReading(x['time'], DataStream.FromString(x['stream']).encode(), x['value'], reading_id=x['reading_id']) for x in in_data['trace']]\n return SimulationTrace(readings, selectors=selectors)", "docstring": "Load a previously saved ascii representation of this simulation trace.\n\nArgs:\n in_path (str): The path of the input file that we should load.\n\nReturns:\n SimulationTrace: The loaded trace object.", "source": "codesearchnet_filtered"} +{"code": "def nb_cluster(data, k, P_init=None, R_init=None, assignments=None, means=None, max_iters=10):\n (genes, cells) = data.shape\n if (P_init is None):\n P_init = np.random.random((genes, k))\n if (R_init is None):\n R_init = np.random.randint(1, data.max(), (genes, k))\n R_init = R_init.astype(float)\n if (assignments is None):\n (_, assignments) = kmeans_pp(data, k, means)\n means = np.zeros((genes, k))\n old_assignments = np.copy(assignments)\n for i in range(max_iters):\n nb_gene_indices = fit_cluster(data, assignments, k, P_init, R_init, means)\n lls = nb_ll(data[(nb_gene_indices, :)], P_init[(nb_gene_indices, :)], R_init[(nb_gene_indices, :)])\n lls += pois_ll.poisson_ll(data[((~ nb_gene_indices), :)], means[((~ nb_gene_indices), :)])\n P_init[((~ nb_gene_indices), :)] = 0\n R_init[((~ nb_gene_indices), :)] = np.inf\n for c in range(cells):\n assignments[c] = np.argmax(lls[(c, :)])\n if np.equal(assignments, old_assignments).all():\n break\n old_assignments = np.copy(assignments)\n return (assignments, P_init, R_init)", "docstring": "Performs negative binomial clustering on the given data. If some genes have mean > variance, then these genes are fitted to a Poisson distribution.\n\nArgs:\n data (array): genes x cells\n k (int): number of clusters\n P_init (array): NB success prob param - genes x k. Default: random\n R_init (array): NB stopping param - genes x k. Default: random\n assignments (array): cells x 1 array of integers 0...k-1. Default: kmeans-pp (poisson)\n means (array): initial cluster means (for use with kmeans-pp to create initial assignments). Default: None\n max_iters (int): default: 100\n\nReturns:\n assignments (array): 1d array of length cells, containing integers 0...k-1\n P (array): genes x k - value is 0 for genes with mean > var\n R (array): genes x k - value is inf for genes with mean > var", "source": "codesearchnet_filtered"} +{"code": "def write_int16(self, value, little_endian=True):\n if little_endian:\n endian = '<'\n else:\n endian = '>'\n return self.pack(('%sh' % endian), value)", "docstring": "Pack the value as a signed integer and write 2 bytes to the stream.\n\nArgs:\n value:\n little_endian (bool): specify the endianness. (Default) Little endian.\n\nReturns:\n int: the number of bytes written.", "source": "codesearchnet_filtered"} +{"code": "def get_unique_families(hkls):\n\n def is_perm(hkl1, hkl2):\n h1 = np.abs(hkl1)\n h2 = np.abs(hkl2)\n return all([(i == j) for (i, j) in zip(sorted(h1), sorted(h2))])\n unique = collections.defaultdict(list)\n for hkl1 in hkls:\n found = False\n for hkl2 in unique.keys():\n if is_perm(hkl1, hkl2):\n found = True\n unique[hkl2].append(hkl1)\n break\n if (not found):\n unique[hkl1].append(hkl1)\n pretty_unique = {}\n for (k, v) in unique.items():\n pretty_unique[sorted(v)[(- 1)]] = len(v)\n return pretty_unique", "docstring": "Returns unique families of Miller indices. Families must be permutations\n of each other.\n\nArgs:\n hkls ([h, k, l]): List of Miller indices.\n\nReturns:\n {hkl: multiplicity}: A dict with unique hkl and multiplicity.", "source": "codesearchnet_filtered"} +{"code": "def _index_idiom(el_name, index, alt=None):\n el_index = ('%s[%d]' % (el_name, index))\n if (index == 0):\n cond = ('%s' % el_name)\n else:\n cond = ('len(%s) - 1 >= %d' % (el_name, index))\n output = (IND + '# pick element from list\\n')\n return ((output + IND) + ('%s = %s if %s else %s\\n\\n' % (el_name, el_index, cond, repr(alt))))", "docstring": "Generate string where `el_name` is indexed by `index` if there are enough\n items or `alt` is returned.\n\nArgs:\n el_name (str): Name of the `container` which is indexed.\n index (int): Index of the item you want to obtain from container.\n alt (whatever, default None): Alternative value.\n\nReturns:\n str: Python code.\n\n Live example::\n >>> import generator as g\n >>> print g._index_idiom(\"xex\", 0)\n # pick element from list\n xex = xex[0] if xex else None\n >>> print g._index_idiom(\"xex\", 1, \"something\")\n # pick element from list\n xex = xex[1] if len(xex) - 1 >= 1 else 'something'", "source": "codesearchnet_filtered"} +{"code": "def _CheckCompositeMap(self, data_type_definition):\n if (not data_type_definition):\n raise errors.FormatError('Missing data type definition')\n members = getattr(data_type_definition, 'members', None)\n if (not members):\n raise errors.FormatError('Invalid data type definition missing members')\n is_composite_map = False\n last_member_byte_order = data_type_definition.byte_order\n for member_definition in members:\n if member_definition.IsComposite():\n is_composite_map = True\n break\n if ((last_member_byte_order != definitions.BYTE_ORDER_NATIVE) and (member_definition.byte_order != definitions.BYTE_ORDER_NATIVE) and (last_member_byte_order != member_definition.byte_order)):\n is_composite_map = True\n break\n last_member_byte_order = member_definition.byte_order\n return is_composite_map", "docstring": "Determines if the data type definition needs a composite map.\n\nArgs:\n data_type_definition (DataTypeDefinition): structure data type definition.\n\nReturns:\n bool: True if a composite map is needed, False otherwise.\n\nRaises:\n FormatError: if a composite map is needed cannot be determined from the\n data type definition.", "source": "codesearchnet_filtered"} +{"code": "def prepare_create_transaction(*, signers, recipients=None, asset=None, metadata=None):\n if (not isinstance(signers, (list, tuple))):\n signers = [signers]\n elif isinstance(signers, tuple):\n signers = list(signers)\n if (not recipients):\n recipients = [(signers, 1)]\n elif (not isinstance(recipients, (list, tuple))):\n recipients = [([recipients], 1)]\n elif isinstance(recipients, tuple):\n recipients = [(list(recipients), 1)]\n transaction = Transaction.create(signers, recipients, metadata=metadata, asset=(asset['data'] if asset else None))\n return transaction.to_dict()", "docstring": "Prepares a ``\"CREATE\"`` transaction payload, ready to be\n fulfilled.\n\nArgs:\n signers (:obj:`list` | :obj:`tuple` | :obj:`str`): One\n or more public keys representing the issuer(s) of the asset\n being created.\n recipients (:obj:`list` | :obj:`tuple` | :obj:`str`, optional):\n One or more public keys representing the new recipients(s)\n of the asset being created. Defaults to ``None``.\n asset (:obj:`dict`, optional): The asset to be created.\n Defaults to ``None``.\n metadata (:obj:`dict`, optional): Metadata associated with the\n transaction. Defaults to ``None``.\n\nReturns:\n dict: The prepared ``\"CREATE\"`` transaction.\n\n .. important::\n\n * If ``asset`` is set, it MUST be in the form of::\n\n {\n 'data': {\n ...\n }\n }\n\n * If ``recipients`` is not given, or evaluates to\n ``False``, it will be set equal to ``signers``::\n\n if not recipients:\n recipients = signers", "source": "codesearchnet_filtered"} +{"code": "def write_merged_bioassembly(inpath, outdir, outname, force_rerun=False):\n outpath = outfile = op.join(outdir, (outname + '.pdb'))\n if ssbio.utils.force_rerun(flag=force_rerun, outfile=op.join(outdir, (outname + '.pdb'))):\n s = StructProp('Model merging', structure_path=inpath, file_type='pdb')\n ss = s.parse_structure()\n merge_all_models_into_first_model(ss.structure)\n outpath = ss.write_pdb(custom_name=outname, out_dir=outdir, force_rerun=force_rerun)\n else:\n return outpath", "docstring": "Utility to take as input a bioassembly file and merge all its models into multiple chains in a single model.\n\nArgs:\n infile (str): Path to input PDB file with multiple models that represent an oligomeric form of a structure.\n outdir (str): Path to output directory\n outname (str): New filename of structure file\n force_rerun (bool): If a new PDB should be written if the file exists\n\nReturns:\n str: Path to newly written PDB file.", "source": "codesearchnet_filtered"} +{"code": "def _ParseLNKFile(self, parser_mediator, file_entry, file_offset, remaining_file_size):\n path_spec = path_spec_factory.Factory.NewPathSpec(definitions.TYPE_INDICATOR_DATA_RANGE, range_offset=file_offset, range_size=remaining_file_size, parent=file_entry.path_spec)\n display_name = '{0:s} # 0x{1:08x}'.format(file_entry.name, file_offset)\n try:\n lnk_file_object = resolver.Resolver.OpenFileObject(path_spec)\n except (dfvfs_errors.BackEndError, RuntimeError) as exception:\n message = 'unable to open LNK file: {0:s} with error: {1!s}'.format(display_name, exception)\n parser_mediator.ProduceExtractionWarning(message)\n return 0\n parser_mediator.AppendToParserChain(self._WINLNK_PARSER)\n try:\n lnk_file_object.seek(0, os.SEEK_SET)\n self._WINLNK_PARSER.ParseFileLNKFile(parser_mediator, lnk_file_object, display_name)\n finally:\n parser_mediator.PopFromParserChain()\n lnk_file_size = lnk_file_object.get_offset()\n lnk_file_object.close()\n return lnk_file_size", "docstring": "Parses a LNK file stored within the .customDestinations-ms file.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n file_entry (dfvfs.FileEntry): a file entry.\n file_offset (int): offset to the LNK file, relative to the start of the\n .customDestinations-ms file.\n remaining_file_size (int): size of the data remaining in the\n .customDestinations-ms file.\n\nReturns:\n int: size of the LNK file data or 0 if the LNK file could not be read.", "source": "codesearchnet_filtered"} +{"code": "def get(cls, ns, key):\n return getattr(db, cls.__name__).find_one((ConfigItem.namespace_prefix == ns), (ConfigItem.key == key))", "docstring": "Fetch an item by namespace and key\n\nArgs:\n ns (str): Namespace prefix\n key (str): Item key\n\nReturns:\n :obj:`Configitem`: Returns config item object if found, else `None`", "source": "codesearchnet_filtered"} +{"code": "def list_load_balancers(access_token, subscription_id):\n endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Network/', '/loadBalancers?api-version=', NETWORK_API])\n return do_get(endpoint, access_token)", "docstring": "List the load balancers in a subscription.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n\nReturns:\n HTTP response. JSON body of load balancer list with properties.", "source": "codesearchnet_filtered"} +{"code": "def _parse_metadata(self, message):\n metadata = Metadata(source=self.actor_urn).__dict__\n metadata['thread_ts'] = message.get('thread_ts')\n if ('presence' in message):\n metadata['presence'] = message['presence']\n if ('text' in message):\n metadata['text'] = message['text']\n elif ('previous_message' in message):\n if ('text' in message['previous_message']):\n metadata['text'] = message['previous_message']['text']\n else:\n metadata['text'] = None\n else:\n metadata['text'] = None\n if ('user' in message):\n metadata['source_user'] = message['user']\n elif ('bot_id' in message):\n metadata['source_user'] = self.get_userid_from_botid(message['bot_id'])\n elif (('message' in message) and ('user' in message['message'])):\n metadata['source_user'] = message['message']['user']\n else:\n metadata['source_user'] = None\n metadata['user_id'] = metadata['source_user']\n metadata['display_name'] = self.get_username(metadata['source_user'])\n if ('channel' in message):\n metadata['source_channel'] = message['channel']\n if message['channel'].startswith('D'):\n metadata['is_private_message'] = True\n else:\n metadata['is_private_message'] = False\n metadata['source_connector'] = 'slack'\n return metadata", "docstring": "Parse incoming messages to build metadata dict\n Lots of 'if' statements. It sucks, I know.\n\nArgs:\n message (dict): JSON dump of message sent from Slack\n\nReturns:\n Legobot.Metadata", "source": "codesearchnet_filtered"} +{"code": "def delete_folder(self, folder):\n if (not is_valid_uuid(folder)):\n raise StorageArgumentException('Invalid UUID for folder: {0}'.format(folder))\n self._authenticated_request.to_endpoint('folder/{}/'.format(folder)).delete()", "docstring": "Delete a folder. It will recursively delete all the content.\n\nArgs:\n folder_id (str): The UUID of the folder to be deleted.\n\nReturns:\n None\n\nRaises:\n StorageArgumentException: Invalid arguments\n StorageForbiddenException: 403\n StorageNotFoundException: 404\n HTTPError: other non-20x error codes", "source": "codesearchnet_filtered"} +{"code": "def camel_to_snake(name):\n s1 = re.sub('(.)([A-Z][a-z]+)', '\\\\1_\\\\2', name)\n return re.sub('([a-z0-9])([A-Z])', '\\\\1_\\\\2', s1).lower()", "docstring": "Converts CamelCase to snake_case.\n\nArgs:\n name (string): The name to convert from CamelCase to snake_case.\n\nReturns:\n string: Converted string.", "source": "codesearchnet_filtered"} +{"code": "def update_query(url, params, remove=None):\n if (remove is None):\n remove = []\n parts = urllib.parse.urlparse(url)\n query_params = urllib.parse.parse_qs(parts.query)\n query_params.update(params)\n query_params = {key: value for (key, value) in six.iteritems(query_params) if (key not in remove)}\n new_query = urllib.parse.urlencode(query_params, doseq=True)\n new_parts = parts._replace(query=new_query)\n return urllib.parse.urlunparse(new_parts)", "docstring": "Updates a URL's query parameters.\n\n Replaces any current values if they are already present in the URL.\n\nArgs:\n url (str): The URL to update.\n params (Mapping[str, str]): A mapping of query parameter\n keys to values.\n remove (Sequence[str]): Parameters to remove from the query string.\n\nReturns:\n str: The URL with updated query parameters.\n\nExample:\n >>> url = 'http://example.com?a=1'\n >>> update_query(url, {'a': '2'})\n http://example.com?a=2\n >>> update_query(url, {'b': '3'})\n http://example.com?a=1&b=3\n >> update_query(url, {'b': '3'}, remove=['a'])\n http://example.com?b=3", "source": "codesearchnet_filtered"} +{"code": "def _send_offset_commit_request(self, offsets):\n assert (self.config['api_version'] >= (0, 8, 1)), 'Unsupported Broker API'\n assert all(map((lambda k: isinstance(k, TopicPartition)), offsets))\n assert all(map((lambda v: isinstance(v, OffsetAndMetadata)), offsets.values()))\n if (not offsets):\n log.debug('No offsets to commit')\n return Future().success(None)\n node_id = self.coordinator()\n if (node_id is None):\n return Future().failure(Errors.GroupCoordinatorNotAvailableError)\n offset_data = collections.defaultdict(dict)\n for (tp, offset) in six.iteritems(offsets):\n offset_data[tp.topic][tp.partition] = offset\n if self._subscription.partitions_auto_assigned():\n generation = self.generation()\n else:\n generation = Generation.NO_GENERATION\n if ((self.config['api_version'] >= (0, 9)) and (generation is None)):\n return Future().failure(Errors.CommitFailedError())\n if (self.config['api_version'] >= (0, 9)):\n request = OffsetCommitRequest[2](self.group_id, generation.generation_id, generation.member_id, OffsetCommitRequest[2].DEFAULT_RETENTION_TIME, [(topic, [(partition, offset.offset, offset.metadata) for (partition, offset) in six.iteritems(partitions)]) for (topic, partitions) in six.iteritems(offset_data)])\n elif (self.config['api_version'] >= (0, 8, 2)):\n request = OffsetCommitRequest[1](self.group_id, (- 1), '', [(topic, [(partition, offset.offset, (- 1), offset.metadata) for (partition, offset) in six.iteritems(partitions)]) for (topic, partitions) in six.iteritems(offset_data)])\n elif (self.config['api_version'] >= (0, 8, 1)):\n request = OffsetCommitRequest[0](self.group_id, [(topic, [(partition, offset.offset, offset.metadata) for (partition, offset) in six.iteritems(partitions)]) for (topic, partitions) in six.iteritems(offset_data)])\n log.debug('Sending offset-commit request with %s for group %s to %s', offsets, self.group_id, node_id)\n future = Future()\n _f = self._client.send(node_id, request)\n _f.add_callback(self._handle_offset_commit_response, offsets, future, time.time())\n _f.add_errback(self._failed_request, node_id, request, future)\n return future", "docstring": "Commit offsets for the specified list of topics and partitions.\n\n This is a non-blocking call which returns a request future that can be\n polled in the case of a synchronous commit or ignored in the\n asynchronous case.\n\nArgs:\n offsets (dict of {TopicPartition: OffsetAndMetadata}): what should\n be committed\n\nReturns:\n Future: indicating whether the commit was successful or not", "source": "codesearchnet_filtered"} +{"code": "def get_texture(self, label: str) -> Union[(moderngl.Texture, moderngl.TextureArray, moderngl.Texture3D, moderngl.TextureCube)]:\n return self._project.get_texture(label)", "docstring": "Get a texture by its label\n\nArgs:\n label (str): The Label for the texture\n\nReturns:\n The py:class:`moderngl.Texture` instance", "source": "codesearchnet_filtered"} +{"code": "def get_region_vcf(self, case_obj, chrom=None, start=None, end=None, gene_obj=None, variant_type='clinical', category='snv', rank_threshold=None):\n rank_threshold = (rank_threshold or (- 100))\n variant_file = None\n if (variant_type == 'clinical'):\n if (category == 'snv'):\n variant_file = case_obj['vcf_files'].get('vcf_snv')\n elif (category == 'sv'):\n variant_file = case_obj['vcf_files'].get('vcf_sv')\n elif (category == 'str'):\n variant_file = case_obj['vcf_files'].get('vcf_str')\n elif (variant_type == 'research'):\n if (category == 'snv'):\n variant_file = case_obj['vcf_files'].get('vcf_snv_research')\n elif (category == 'sv'):\n variant_file = case_obj['vcf_files'].get('vcf_sv_research')\n if (not variant_file):\n raise SyntaxError('Vcf file does not seem to exist')\n vcf_obj = VCF(variant_file)\n region = ''\n if gene_obj:\n chrom = gene_obj['chromosome']\n start = gene_obj['start']\n end = gene_obj['end']\n if chrom:\n if (start and end):\n region = '{0}:{1}-{2}'.format(chrom, start, end)\n else:\n region = '{0}'.format(chrom)\n else:\n rank_threshold = (rank_threshold or 5)\n with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:\n file_name = str(pathlib.Path(temp.name))\n for header_line in vcf_obj.raw_header.split('\\n'):\n if (len(header_line) > 3):\n temp.write((header_line + '\\n'))\n for variant in vcf_obj(region):\n temp.write(str(variant))\n return file_name", "docstring": "Produce a reduced vcf with variants from the specified coordinates\n This is used for the alignment viewer.\n\nArgs:\n case_obj(dict): A case from the scout database\n variant_type(str): 'clinical' or 'research'. Default: 'clinical'\n category(str): 'snv' or 'sv'. Default: 'snv'\n rank_threshold(float): Only load variants above this score. Default: 5\n chrom(str): Load variants from a certain chromosome\n start(int): Specify the start position\n end(int): Specify the end position\n gene_obj(dict): A gene object from the database\n\nReturns:\n file_name(str): Path to the temporary file", "source": "codesearchnet_filtered"} +{"code": "def multi_rouge_n(sequences, scores_ids, n=2):\n ngrams = [_get_word_ngrams(n, sequence) for sequence in sequences]\n counts = [len(ngram) for ngram in ngrams]\n scores = []\n for (hyp_id, ref_id) in scores_ids:\n evaluated_ngrams = ngrams[hyp_id]\n evaluated_count = counts[hyp_id]\n reference_ngrams = ngrams[ref_id]\n reference_count = counts[ref_id]\n overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams)\n overlapping_count = len(overlapping_ngrams)\n scores += [f_r_p_rouge_n(evaluated_count, reference_count, overlapping_count)]\n return scores", "docstring": "Efficient way to compute highly repetitive scoring\n i.e. sequences are involved multiple time\n\nArgs:\n sequences(list[str]): list of sequences (either hyp or ref)\n scores_ids(list[tuple(int)]): list of pairs (hyp_id, ref_id)\n ie. scores[i] = rouge_n(scores_ids[i][0],\n scores_ids[i][1])\n\nReturns:\n scores: list of length `len(scores_ids)` containing rouge `n`\n scores as a dict with 'f', 'r', 'p'\n\nRaises:\n KeyError: if there's a value of i in scores_ids that is not in\n [0, len(sequences)[", "source": "codesearchnet_filtered"} +{"code": "def decrypt_report(self, device_id, root, data, **kwargs):\n report_key = self._verify_derive_key(device_id, root, **kwargs)\n try:\n from Crypto.Cipher import AES\n import Crypto.Util.Counter\n except ImportError:\n raise NotFoundError\n ctr = Crypto.Util.Counter.new(128)\n encryptor = AES.new(bytes(report_key[:16]), AES.MODE_CTR, counter=ctr)\n decrypted = encryptor.decrypt(bytes(data))\n return {'data': decrypted}", "docstring": "Decrypt a buffer of report data on behalf of a device.\n\nArgs:\n device_id (int): The id of the device that we should encrypt for\n root (int): The root key type that should be used to generate the report\n data (bytearray): The data that we should decrypt\n **kwargs: There are additional specific keyword args that are required\n depending on the root key used. Typically, you must specify\n - report_id (int): The report id\n - sent_timestamp (int): The sent timestamp of the report\n\n These two bits of information are used to construct the per report\n signing and encryption key from the specific root key type.\n\nReturns:\n dict: The decrypted data and any associated metadata about the data.\n The data itself must always be a bytearray stored under the 'data'\n key, however additional keys may be present depending on the encryption method\n used.\n\nRaises:\n NotFoundError: If the auth provider is not able to decrypt the data.", "source": "codesearchnet_filtered"} +{"code": "def get_authorization_url(self, client_id=None, instance_id=None, redirect_uri=None, region=None, scope=None, state=None):\n client_id = (client_id or self.client_id)\n instance_id = (instance_id or self.instance_id)\n redirect_uri = (redirect_uri or self.redirect_uri)\n region = (region or self.region)\n scope = (scope or self.scope)\n state = (state or str(uuid.uuid4()))\n self.state = state\n return (Request('GET', self.auth_base_url, params={'client_id': client_id, 'instance_id': instance_id, 'redirect_uri': redirect_uri, 'region': region, 'response_type': 'code', 'scope': scope, 'state': state}).prepare().url, state)", "docstring": "Generate authorization URL.\n\nArgs:\n client_id (str): OAuth2 client ID. Defaults to ``None``.\n instance_id (str): App Instance ID. Defaults to ``None``.\n redirect_uri (str): Redirect URI. Defaults to ``None``.\n region (str): App Region. Defaults to ``None``.\n scope (str): Permissions. Defaults to ``None``.\n state (str): UUID to detect CSRF. Defaults to ``None``.\n\nReturns:\n str, str: Auth URL, state", "source": "codesearchnet_filtered"} +{"code": "def compatible_firmware_version(self):\n identifier = self.firmware_version.split('compiled')[0]\n buf_size = self.MAX_BUF_SIZE\n buf = (ctypes.c_char * buf_size)()\n res = self._dll.JLINKARM_GetEmbeddedFWString(identifier.encode(), buf, buf_size)\n if (res < 0):\n raise errors.JLinkException(res)\n return ctypes.string_at(buf).decode()", "docstring": "Returns the DLL's compatible J-Link firmware version.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n The firmware version of the J-Link that the DLL is compatible\n with.\n\nRaises:\n JLinkException: on error.", "source": "codesearchnet_filtered"} +{"code": "def generate(self, information, timeout=(- 1)):\n return self._client.create(information, timeout=timeout)", "docstring": "Generates a self signed certificate or an internal CA signed certificate for RabbitMQ clients.\n\nArgs:\n information (dict): Information to generate the certificate for RabbitMQ clients.\n timeout:\n Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n in OneView; it just stops waiting for its completion.\n\nReturns:\n dict: RabbitMQ certificate generated", "source": "codesearchnet_filtered"} +{"code": "def parse_view(query):\n try:\n idx = query.lower().index('where')\n query = query[:idx]\n except ValueError:\n pass\n if (not query.endswith(';')):\n query = query.strip()\n query += ';'\n result = _view_stmt.parseString(query)\n return View(result)", "docstring": "Parses asql query to view object.\n\nArgs:\n query (str): asql query\n\nReturns:\n View instance: parsed view.", "source": "codesearchnet_filtered"} +{"code": "def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN):\n min_x = min((np.nanmin(x) for (x, y) in layers))\n max_x = max((np.nanmax(x) for (x, y) in layers))\n min_y = min((np.nanmin(y) for (x, y) in layers))\n max_y = max((np.nanmax(y) for (x, y) in layers))\n height = (max_y - min_y)\n width = (max_x - min_x)\n if (height > (width * aspect_ratio)):\n adj_height = (height * (1.0 + margin))\n adj_width = (adj_height / aspect_ratio)\n else:\n adj_width = (width * (1.0 + margin))\n adj_height = (adj_width * aspect_ratio)\n width_buffer = ((adj_width - width) / 2.0)\n height_buffer = ((adj_height - height) / 2.0)\n return ((min_x - width_buffer), (min_y - height_buffer), adj_width, adj_height)", "docstring": "Calculates the size of the SVG viewBox to use.\n\nArgs:\n layers (list): the layers in the image\n aspect_ratio (float): the height of the output divided by the width\n margin (float): minimum amount of buffer to add around the image, relative\n to the total dimensions\n\nReturns:\n tuple: a 4-tuple of floats representing the viewBox according to SVG\n specifications ``(x, y, width, height)``.", "source": "codesearchnet_filtered"} +{"code": "def ebalance(sdat, tstart=None, tend=None):\n tseries = sdat.tseries_between(tstart, tend)\n (rbot, rtop) = misc.get_rbounds(sdat.steps.last)\n if (rbot != 0):\n coefsurf = ((rtop / rbot) ** 2)\n volume = ((rbot * (((rtop / rbot) ** 3) - 1)) / 3)\n else:\n coefsurf = 1.0\n volume = 1.0\n (dtdt, time) = dt_dt(sdat, tstart, tend)\n ftop = (tseries['ftop'].values * coefsurf)\n fbot = tseries['fbot'].values\n radio = tseries['H_int'].values\n ebal = ((ftop[1:] - fbot[1:]) + (volume * (dtdt - radio[1:])))\n return (ebal, time)", "docstring": "Energy balance.\n\n Compute Nu_t - Nu_b + V*dT/dt as a function of time using an explicit\n Euler scheme. This should be zero if energy is conserved.\n\nArgs:\n sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.\n tstart (float): time at which the computation should start. Use the\n beginning of the time series data if set to None.\n tend (float): time at which the computation should end. Use the\n end of the time series data if set to None.\n\nReturns:\n tuple of :class:`numpy.array`: energy balance and time arrays.", "source": "codesearchnet_filtered"} +{"code": "def iter(self, keyed=False, extended=False):\n if self.closed:\n message = 'Stream is closed. Please call \"stream.open()\" first.'\n raise exceptions.TabulatorException(message)\n iterator = chain(self.__sample_extended_rows, self.__parser.extended_rows)\n iterator = self.__apply_processors(iterator)\n for (row_number, headers, row) in iterator:\n if (row_number > self.__row_number):\n self.__row_number = row_number\n if extended:\n (yield (row_number, headers, row))\n elif keyed:\n (yield dict(zip(headers, row)))\n else:\n (yield row)", "docstring": "Iterate over the rows.\n\n Each row is returned in a format that depends on the arguments `keyed`\n and `extended`. By default, each row is returned as list of their\n values.\n\nArgs:\n keyed (bool, optional): When True, each returned row will be a\n `dict` mapping the header name to its value in the current row.\n For example, `[{'name': 'J Smith', 'value': '10'}]`. Ignored if\n ``extended`` is True. Defaults to False.\n extended (bool, optional): When True, returns each row as a tuple\n with row number (starts at 1), list of headers, and list of row\n values. For example, `(1, ['name', 'value'], ['J Smith', '10'])`.\n Defaults to False.\n\nReturns:\n Iterator[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]:\n The row itself. The format depends on the values of `keyed` and\n `extended` arguments.\n\nRaises:\n exceptions.TabulatorException: If the stream is closed.", "source": "codesearchnet_filtered"} +{"code": "def run(self):\n target = getattr(self, '_Thread__target', getattr(self, '_target', None))\n args = getattr(self, '_Thread__args', getattr(self, '_args', None))\n kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None))\n if (target is not None):\n self._return = target(*args, **kwargs)\n return None", "docstring": "Runs the thread.\n\nArgs:\n self (ThreadReturn): the ``ThreadReturn`` instance\n\nReturns:\n ``None``", "source": "codesearchnet_filtered"} +{"code": "def make_datetime(dt, date_parser=parse_date):\n if (isinstance(dt, (datetime.datetime, datetime.date, datetime.time, pd.Timestamp, np.datetime64)) or (dt in (float('nan'), float('inf'), float('-inf'), None, ''))):\n return dt\n if isinstance(dt, (float, int)):\n return datetime_from_ordinal_float(dt)\n if isinstance(dt, datetime.date):\n return datetime.datetime(dt.year, dt.month, dt.day)\n if isinstance(dt, datetime.time):\n return datetime.datetime(1, 1, 1, dt.hour, dt.minute, dt.second, dt.microsecond)\n if (not dt):\n return datetime.datetime(1970, 1, 1)\n if isinstance(dt, basestring):\n try:\n return date_parser(dt)\n except ValueError:\n print('Unable to make_datetime({})'.format(dt))\n raise\n try:\n return datetime.datetime(*dt.timetuple()[:7])\n except AttributeError:\n try:\n dt = list(dt)\n if (0 < len(dt) < 7):\n try:\n return datetime.datetime(*dt[:7])\n except (TypeError, IndexError, ValueError):\n pass\n except (TypeError, IndexError, ValueError, AttributeError):\n return dt\n return [make_datetime(val, date_parser=date_parser) for val in dt]", "docstring": "Coerce a datetime or string into datetime.datetime object\n\nArgs:\n dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date\n to be coerced into a `datetime.date` object\n\nReturns:\n datetime.time: Time of day portion of a `datetime` string or object\n\n >>> make_date('')\n datetime.date(1970, 1, 1)\n >>> make_date(None)\n datetime.date(1970, 1, 1)\n >>> make_date(\"11:59 PM\") == datetime.date.today()\n True\n >>> make_date(datetime.datetime(1999, 12, 31, 23, 59, 59))\n datetime.date(1999, 12, 31)\n >>> make_datetime(['1970-10-31', '1970-12-25']) # doctest: +NORMALIZE_WHITESPACE\n [datetime.datetime(1970, 10, 31, 0, 0), datetime.datetime(1970, 12, 25, 0, 0)]", "source": "codesearchnet_filtered"} +{"code": "def get_engine(self, filepath, kind=None):\n if (not kind):\n extension = os.path.splitext(filepath)[1]\n if (not extension):\n msg = 'Unable to discover settings format from an empty file extension: {}'\n raise SettingsDiscoveryError(msg.format(filepath))\n elif (extension[1:] not in self.extensions):\n msg = 'Settings file extension is unknowed from available backends: {}'\n raise SettingsDiscoveryError(msg.format(filepath))\n kind = self.extensions[extension[1:]]\n elif (kind not in self.engines):\n msg = 'Given settings format is unknow: {}'\n raise SettingsDiscoveryError(msg.format(kind))\n return self.engines[kind]", "docstring": "From given filepath try to discover which backend format to use.\n\n Discovering is pretty naive as it find format from file extension.\n\nArgs:\n filepath (str): Settings filepath or filename.\n\n Keyword Arguments:\n kind (str): A format name to enforce a specific backend. Can be any\n value from attribute ``_kind_name`` of available backend\n engines.\n\nRaises:\n boussole.exceptions.SettingsDiscoveryError: If extension is\n unknowed or if given format name is unknowed.\n\nReturns:\n object: Backend engine class.", "source": "codesearchnet_filtered"} +{"code": "def get(self, blob):\n return self._send(url=((((self._base_url + blob.parent.server_id) + '/') + blob.server_id) + '?s=0'), method='GET', allow_redirects=False).headers.get('Location')", "docstring": "Get the canonical link to a media blob.\n\nArgs:\n blob (gkeepapi.node.Blob): The blob.\n\nReturns:\n str: A link to the media.", "source": "codesearchnet_filtered"} +{"code": "def most_uncertain_by_mask(self, mask, y):\n idxs = np.where(mask)[0]\n return idxs[np.argsort(np.abs((self.probs[(idxs, y)] - (1 / self.num_classes))))[:4]]", "docstring": "Extracts the first 4 most uncertain indexes from the ordered list of probabilities\n\nArgs:\n mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else\n y (int): the selected class\n\nReturns:\n idxs (ndarray): An array of indexes of length 4", "source": "codesearchnet_filtered"} +{"code": "def method_not_allowed(cls, errors=None):\n if cls.expose_status:\n cls.response.content_type = 'application/json'\n cls.response._status_line = '405 Method Not Allowed'\n return cls(405, None, errors).to_json", "docstring": "Shortcut API for HTTP 405 `Method not allowed` response.\n\nArgs:\n errors (list): Response key/value data.\n\nReturns:\n WSResponse Instance.", "source": "codesearchnet_filtered"} +{"code": "def import_project(self, file, path, namespace=None, overwrite=False, override_params=None, **kwargs):\n files = {'file': ('file.tar.gz', file)}\n data = {'path': path, 'overwrite': overwrite}\n if override_params:\n for (k, v) in override_params.items():\n data[('override_params[%s]' % k)] = v\n if namespace:\n data['namespace'] = namespace\n return self.gitlab.http_post('/projects/import', post_data=data, files=files, **kwargs)", "docstring": "Import a project from an archive file.\n\nArgs:\n file: Data or file object containing the project\n path (str): Name and path for the new project\n namespace (str): The ID or path of the namespace that the project\n will be imported to\n overwrite (bool): If True overwrite an existing project with the\n same path\n override_params (dict): Set the specific settings for the project\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabListError: If the server failed to perform the request\n\nReturns:\n dict: A representation of the import status.", "source": "codesearchnet_filtered"} +{"code": "def write_payload(payload=None, objectInput=None):\n temp = tempfile.mkstemp()[1]\n log.debug('Write payload in temp file {!r}'.format(temp))\n with open(temp, 'wb') as f:\n if payload:\n payload = base64.b64decode(payload)\n elif objectInput:\n if six.PY3:\n payload = objectInput.buffer.read()\n elif six.PY2:\n payload = objectInput.read()\n f.write(payload)\n return temp", "docstring": "This function writes a base64 payload or file object on disk.\n\nArgs:\n payload (string): payload in base64\n objectInput (object): file object/standard input to analyze\n\nReturns:\n Path of file", "source": "codesearchnet_filtered"} +{"code": "def get_dispatcher_event(self, name):\n e = self.__property_events.get(name)\n if (e is None):\n e = self.__events[name]\n return e", "docstring": "Retrieves an Event object by name\n\nArgs:\n name (str): The name of the :class:`Event` or\n :class:`~pydispatch.properties.Property` object to retrieve\n\nReturns:\n The :class:`Event` instance for the event or property definition\n\n .. versionadded:: 0.1.0", "source": "codesearchnet_filtered"} +{"code": "def _makedirs(name, user=None, group=None, dir_mode=None, win_owner=None, win_perms=None, win_deny_perms=None, win_inheritance=None):\n if salt.utils.platform.is_windows():\n (drive, path) = os.path.splitdrive(name)\n if (not os.path.isdir(drive)):\n raise CommandExecutionError(drive)\n win_owner = (win_owner if win_owner else user)\n return __salt__['file.makedirs'](path=name, owner=win_owner, grant_perms=win_perms, deny_perms=win_deny_perms, inheritance=win_inheritance)\n else:\n return __salt__['file.makedirs'](path=name, user=user, group=group, mode=dir_mode)", "docstring": "Helper function for creating directories when the ``makedirs`` option is set\n to ``True``. Handles Unix and Windows based systems\n\n .. versionadded:: 2017.7.8\n\nArgs:\n name (str): The directory path to create\n user (str): The linux user to own the directory\n group (str): The linux group to own the directory\n dir_mode (str): The linux mode to apply to the directory\n win_owner (str): The Windows user to own the directory\n win_perms (dict): A dictionary of grant permissions for Windows\n win_deny_perms (dict): A dictionary of deny permissions for Windows\n win_inheritance (bool): True to inherit permissions on Windows\n\nReturns:\n bool: True if successful, otherwise False on Windows\n str: Error messages on failure on Linux\n None: On successful creation on Linux\n\nRaises:\n CommandExecutionError: If the drive is not mounted on Windows", "source": "codesearchnet_filtered"} +{"code": "def asn(self, as_number, **kwargs):\n indicator_obj = ASN(as_number, **kwargs)\n return self._indicator(indicator_obj)", "docstring": "Add ASN data to Batch object.\n\nArgs:\n as_number (str): The value for this Indicator.\n confidence (str, kwargs): The threat confidence for this Indicator.\n date_added (str, kwargs): The date timestamp the Indicator was created.\n last_modified (str, kwargs): The date timestamp the Indicator was last modified.\n rating (str, kwargs): The threat rating for this Indicator.\n xid (str, kwargs): The external id for this Indicator.\n\nReturns:\n obj: An instance of ASN.", "source": "codesearchnet_filtered"} +{"code": "def receiveds_not_parsed(receiveds):\n log.debug('Receiveds for this email are not parsed')\n output = []\n counter = Counter()\n for i in receiveds[::(- 1)]:\n j = {'raw': i.strip()}\n j['hop'] = (counter['hop'] + 1)\n counter['hop'] += 1\n output.append(j)\n else:\n return output", "docstring": "If receiveds are not parsed, makes a new structure with raw\n field. It's useful to have the same structure of receiveds\n parsed.\n\nArgs:\n receiveds (list): list of raw receiveds headers\n\nReturns:\n a list of not parsed receiveds headers with first hop in first position", "source": "codesearchnet_filtered"} +{"code": "def add_cidr_rules(self, rules):\n session = boto3.session.Session(profile_name=self.env, region_name=self.region)\n client = session.client('ec2')\n group_id = get_security_group_id(self.app_name, self.env, self.region)\n for rule in rules:\n data = {'DryRun': False, 'GroupId': group_id, 'IpPermissions': [{'IpProtocol': rule['protocol'], 'FromPort': rule['start_port'], 'ToPort': rule['end_port'], 'IpRanges': [{'CidrIp': rule['app']}]}]}\n self.log.debug('Security Group rule: %s', data)\n try:\n client.authorize_security_group_ingress(**data)\n except botocore.exceptions.ClientError as error:\n if ('InvalidPermission.Duplicate' in str(error)):\n self.log.debug('Duplicate rule exist, that is OK.')\n else:\n msg = 'Unable to add cidr rules to {}'.format(rule.get('app'))\n self.log.error(msg)\n raise SpinnakerSecurityGroupError(msg)\n return True", "docstring": "Add cidr rules to security group via boto.\n\nArgs:\n rules (list): Allowed Security Group ports and protocols.\n\nReturns:\n True: Upon successful completion.\n\nRaises:\n SpinnakerSecurityGroupError: boto3 call failed to add CIDR block to\n Security Group.", "source": "codesearchnet_filtered"} +{"code": "def _source_is_newer(src_fs, src_path, dst_fs, dst_path):\n try:\n if dst_fs.exists(dst_path):\n namespace = ('details', 'modified')\n src_modified = src_fs.getinfo(src_path, namespace).modified\n if (src_modified is not None):\n dst_modified = dst_fs.getinfo(dst_path, namespace).modified\n return ((dst_modified is None) or (src_modified > dst_modified))\n return True\n except FSError:\n return True", "docstring": "Determine if source file is newer than destination file.\n\nArgs:\n src_fs (FS): Source filesystem (instance or URL).\n src_path (str): Path to a file on the source filesystem.\n dst_fs (FS): Destination filesystem (instance or URL).\n dst_path (str): Path to a file on the destination filesystem.\n\nReturns:\n bool: `True` if the source file is newer than the destination\n file or file modification time cannot be determined, `False`\n otherwise.", "source": "codesearchnet_filtered"} +{"code": "def wait(self, **kwargs):\n return self.client.api.wait(self.id, **kwargs)", "docstring": "Block until the container stops, then return its exit code. Similar to\n the ``docker wait`` command.\n\nArgs:\n timeout (int): Request timeout\n condition (str): Wait until a container state reaches the given\n condition, either ``not-running`` (default), ``next-exit``,\n or ``removed``\n\nReturns:\n (dict): The API's response as a Python dictionary, including\n the container's exit code under the ``StatusCode`` attribute.\n\nRaises:\n :py:class:`requests.exceptions.ReadTimeout`\n If the timeout is exceeded.\n :py:class:`docker.errors.APIError`\n If the server returns an error.", "source": "codesearchnet_filtered"} +{"code": "def load_api_folder(api_folder_path):\n api_definition_mapping = {}\n api_items_mapping = load_folder_content(api_folder_path)\n for (api_file_path, api_items) in api_items_mapping.items():\n if isinstance(api_items, list):\n for api_item in api_items:\n (key, api_dict) = api_item.popitem()\n api_id = (api_dict.get('id') or api_dict.get('def') or api_dict.get('name'))\n if ((key != 'api') or (not api_id)):\n raise exceptions.ParamsError('Invalid API defined in {}'.format(api_file_path))\n if (api_id in api_definition_mapping):\n raise exceptions.ParamsError('Duplicated API ({}) defined in {}'.format(api_id, api_file_path))\n else:\n api_definition_mapping[api_id] = api_dict\n elif isinstance(api_items, dict):\n if (api_file_path in api_definition_mapping):\n raise exceptions.ParamsError('Duplicated API defined: {}'.format(api_file_path))\n else:\n api_definition_mapping[api_file_path] = api_items\n return api_definition_mapping", "docstring": "load api definitions from api folder.\n\nArgs:\n api_folder_path (str): api files folder.\n\n api file should be in the following format:\n [\n {\n \"api\": {\n \"def\": \"api_login\",\n \"request\": {},\n \"validate\": []\n }\n },\n {\n \"api\": {\n \"def\": \"api_logout\",\n \"request\": {},\n \"validate\": []\n }\n }\n ]\n\nReturns:\n dict: api definition mapping.\n\n {\n \"api_login\": {\n \"function_meta\": {\"func_name\": \"api_login\", \"args\": [], \"kwargs\": {}}\n \"request\": {}\n },\n \"api_logout\": {\n \"function_meta\": {\"func_name\": \"api_logout\", \"args\": [], \"kwargs\": {}}\n \"request\": {}\n }\n }", "source": "codesearchnet_filtered"} +{"code": "def random_subset_by_duration(self, relative_duration, balance_labels=False, label_list_ids=None):\n total_duration = self.corpus.total_duration\n subset_duration = (relative_duration * total_duration)\n utterance_durations = {utt_idx: utt.duration for (utt_idx, utt) in self.corpus.utterances.items()}\n if balance_labels:\n all_label_values = self.corpus.all_label_values(label_list_ids=label_list_ids)\n label_durations = {}\n for (utt_idx, utt) in self.corpus.utterances.items():\n label_durations[utt_idx] = utt.label_total_duration(label_list_ids)\n subset_utterance_ids = utils.select_balanced_subset(label_durations, subset_duration, list(all_label_values), select_count_values=utterance_durations, seed=self.rand.random())\n else:\n dummy_weights = {utt_idx: {'w': 1} for utt_idx in self.corpus.utterances.keys()}\n subset_utterance_ids = utils.select_balanced_subset(dummy_weights, subset_duration, ['w'], select_count_values=utterance_durations, seed=self.rand.random())\n filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=set(subset_utterance_ids))\n return subview.Subview(self.corpus, filter_criteria=[filter])", "docstring": "Create a subview of random utterances with a approximate duration relative to the full corpus.\n Random utterances are selected so that the sum of all utterance durations\n equals to the relative duration of the full corpus.\n\nArgs:\n relative_duration (float): A value between 0 and 1. (e.g. 0.5 will create a subset with approximately\n 50% of the full corpus duration)\n balance_labels (bool): If True, the labels of the selected utterances are balanced as far as possible.\n So the count/duration of every label within the subset is equal.\n label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered\n for balancing. Otherwise only the ones that are in the list are considered.\n\nReturns:\n Subview: The subview representing the subset.", "source": "codesearchnet_filtered"} +{"code": "def add(self, payload=None):\n try:\n db = self._client[self.database]\n col = db[WORKFLOW_DATA_COLLECTION_NAME]\n return str(col.insert_one({DataStoreDocumentSection.Meta: (payload if isinstance(payload, dict) else {}), DataStoreDocumentSection.Data: {}}).inserted_id)\n except ConnectionFailure:\n raise DataStoreNotConnected()", "docstring": "Adds a new document to the data store and returns its id.\n\nArgs:\n payload (dict): Dictionary of initial data that should be stored\n in the new document in the meta section.\n\nRaises:\n DataStoreNotConnected: If the data store is not connected to the server.\n\nReturns:\n str: The id of the newly created document.", "source": "codesearchnet_filtered"} +{"code": "def field_to_markdown(field):\n if ('title' in field):\n field_title = '**{}**'.format(field['title'])\n else:\n raise Exception('Es necesario un `title` para describir un campo.')\n field_type = (' ({})'.format(field['type']) if ('type' in field) else '')\n field_desc = (': {}'.format(field['description']) if ('description' in field) else '')\n text_template = '{title}{type}{description}'\n text = text_template.format(title=field_title, type=field_type, description=field_desc)\n return text", "docstring": "Genera texto en markdown a partir de los metadatos de un `field`.\n\nArgs:\n field (dict): Diccionario con metadatos de un `field`.\n\nReturns:\n str: Texto que describe un `field`.", "source": "codesearchnet_filtered"} +{"code": "def _generate_security_groups(config_key):\n raw_default_groups = validate_key_values(CONFIG, 'base', config_key, default='')\n default_groups = _convert_string_to_native(raw_default_groups)\n LOG.debug('Default security group for %s is %s', config_key, default_groups)\n entries = {}\n for env in ENVS:\n entries[env] = []\n if isinstance(default_groups, list):\n groups = _remove_empty_entries(default_groups)\n for env in entries:\n entries[env] = groups\n elif isinstance(default_groups, dict):\n entries.update(default_groups)\n LOG.debug('Generated security group: %s', entries)\n return entries", "docstring": "Read config file and generate security group dict by environment.\n\nArgs:\n config_key (str): Configuration file key\n\nReturns:\n dict: of environments in {'env1': ['group1', 'group2']} format", "source": "codesearchnet_filtered"} +{"code": "def hotkey(*args, **kwargs):\n interval = float(kwargs.get('interval', 0.0))\n _failSafeCheck()\n for c in args:\n if (len(c) > 1):\n c = c.lower()\n platformModule._keyDown(c)\n time.sleep(interval)\n for c in reversed(args):\n if (len(c) > 1):\n c = c.lower()\n platformModule._keyUp(c)\n time.sleep(interval)\n _autoPause(kwargs.get('pause', None), kwargs.get('_pause', True))", "docstring": "Performs key down presses on the arguments passed in order, then performs\n key releases in reverse order.\n\n The effect is that calling hotkey('ctrl', 'shift', 'c') would perform a\n \"Ctrl-Shift-C\" hotkey/keyboard shortcut press.\n\nArgs:\n key(s) (str): The series of keys to press, in order. This can also be a\n list of key strings to press.\n interval (float, optional): The number of seconds in between each press.\n 0.0 by default, for no pause in between presses.\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def get(self, key, default=None):\n retval = self.__getitem__(key)\n if (not retval):\n retval = default\n return retval", "docstring": "Get a value from the dictionary.\n\nArgs:\n key (str): The dictionary key.\n default (any): The default to return if the key is not in the\n dictionary. Defaults to None.\n\nReturns:\n str or any: The dictionary value or the default if the key is not\n in the dictionary.", "source": "codesearchnet_filtered"} +{"code": "def create_channel(target, credentials=None, scopes=None, ssl_credentials=None, **kwargs):\n if (credentials is None):\n (credentials, _) = google.auth.default(scopes=scopes)\n else:\n credentials = google.auth.credentials.with_scopes_if_required(credentials, scopes)\n request = google.auth.transport.requests.Request()\n metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin(credentials, request)\n google_auth_credentials = grpc.metadata_call_credentials(metadata_plugin)\n if (ssl_credentials is None):\n ssl_credentials = grpc.ssl_channel_credentials()\n composite_credentials = grpc.composite_channel_credentials(ssl_credentials, google_auth_credentials)\n if HAS_GRPC_GCP:\n return grpc_gcp.secure_channel(target, composite_credentials, **kwargs)\n else:\n return grpc.secure_channel(target, composite_credentials, **kwargs)", "docstring": "Create a secure channel with credentials.\n\nArgs:\n target (str): The target service address in the format 'hostname:port'.\n credentials (google.auth.credentials.Credentials): The credentials. If\n not specified, then this function will attempt to ascertain the\n credentials from the environment using :func:`google.auth.default`.\n scopes (Sequence[str]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n ssl_credentials (grpc.ChannelCredentials): Optional SSL channel\n credentials. This can be used to specify different certificates.\n kwargs: Additional key-word args passed to\n :func:`grpc_gcp.secure_channel` or :func:`grpc.secure_channel`.\n\nReturns:\n grpc.Channel: The created channel.", "source": "codesearchnet_filtered"} +{"code": "def predict_proba(self, a, b, **kwargs):\n return (self.cds_score(b, a) - self.cds_score(a, b))", "docstring": "Infer causal relationships between 2 variables using the CDS statistic\n\nArgs:\n a (numpy.ndarray): Variable 1\n b (numpy.ndarray): Variable 2\n\nReturns:\n float: Causation score (Value : 1 if a->b and -1 if b->a)", "source": "codesearchnet_filtered"} +{"code": "def _FormatPackedIPv6Address(self, packed_ip_address):\n octet_pairs = zip(packed_ip_address[0::2], packed_ip_address[1::2])\n octet_pairs = [((octet1 << 8) | octet2) for (octet1, octet2) in octet_pairs]\n return ':'.join(['{0:04x}'.format(octet_pair) for octet_pair in octet_pairs])", "docstring": "Formats a packed IPv6 address as a human readable string.\n\nArgs:\n packed_ip_address (list[int]): packed IPv6 address.\n\nReturns:\n str: human readable IPv6 address.", "source": "codesearchnet_filtered"} +{"code": "def _color(str_, fore_color=None, back_color=None, styles=None):\n if ((not config.get('color_enabled', False)) or (platform_.name == 'windows')):\n return str_\n _init_colorama()\n colored = ''\n if (not styles):\n styles = []\n if fore_color:\n colored += getattr(colorama.Fore, fore_color.upper(), '')\n if back_color:\n colored += getattr(colorama.Back, back_color.upper(), '')\n for style in styles:\n colored += getattr(colorama.Style, style.upper(), '')\n return ((colored + str_) + colorama.Style.RESET_ALL)", "docstring": "Return the string wrapped with the appropriate styling escape sequences.\n\nArgs:\n str_ (str): The string to be wrapped.\n fore_color (str, optional): Any foreground color supported by the\n `Colorama`_ module.\n back_color (str, optional): Any background color supported by the\n `Colorama`_ module.\n styles (list of str, optional): Any styles supported by the `Colorama`_\n module.\n\nReturns:\n str: The string styled with the appropriate escape sequences.\n\n .. _Colorama:\n https://pypi.python.org/pypi/colorama", "source": "codesearchnet_filtered"} +{"code": "def ask_stories(self, raw=False, limit=None):\n ask_stories = self._get_stories('askstories', limit)\n if raw:\n ask_stories = [story.raw for story in ask_stories]\n return ask_stories", "docstring": "Returns list of item ids of latest Ask HN stories\n\nArgs:\n limit (int): specifies the number of stories to be returned.\n raw (bool): Flag to indicate whether to transform all\n objects into raw json.\n\nReturns:\n `list` object containing ids of Ask HN stories.", "source": "codesearchnet_filtered"} +{"code": "def _register_preallocated_ips(self, conf):\n for (dom_name, dom_spec) in conf.get('domains', {}).items():\n for (idx, nic) in enumerate(dom_spec.get('nics', [])):\n if ('ip' not in nic):\n continue\n net = conf['nets'][nic['net']]\n if self._subnet_store.is_leasable_subnet(net['gw']):\n nic['ip'] = _create_ip(net['gw'], int(nic['ip'].split('.')[(- 1)]))\n dom_name = dom_spec['name']\n if (not _ip_in_subnet(net['gw'], nic['ip'])):\n raise RuntimeError((\"%s:nic%d's IP [%s] is outside the subnet [%s]\" % (dom_name, dom_spec['nics'].index(nic), nic['ip'], net['gw'])))\n if (nic['ip'] in net['mapping'].values()):\n conflict_list = [name for (name, ip) in net['mapping'].items() if (ip == net['ip'])]\n raise RuntimeError(('IP %s was to several domains: %s %s' % (nic['ip'], dom_name, ' '.join(conflict_list))))\n self._add_nic_to_mapping(net, dom_spec, nic)", "docstring": "Parse all the domains in the given conf and preallocate all their ips\n into the networks mappings, raising exception on duplicated ips or ips\n out of the allowed ranges\n\n See Also:\n :mod:`lago.subnet_lease`\n\nArgs:\n conf (dict): Configuration spec to parse\n\nReturns:\n None\n\nRaises:\n RuntimeError: if there are any duplicated ips or any ip out of the\n allowed range", "source": "codesearchnet_filtered"} +{"code": "def query_gal(self, l, b, d=None, **kwargs):\n if (not isinstance(l, units.Quantity)):\n l = (l * units.deg)\n if (not isinstance(b, units.Quantity)):\n b = (b * units.deg)\n if (d is None):\n coords = coordinates.SkyCoord(l, b, frame='galactic')\n else:\n if (not isinstance(d, units.Quantity)):\n d = (d * units.kpc)\n coords = coordinates.SkyCoord(l, b, distance=d, frame='galactic')\n return self.query(coords, **kwargs)", "docstring": "Query using Galactic coordinates.\n\nArgs:\n l (:obj:`float`, scalar or array-like): Galactic longitude, in degrees,\n or as an :obj:`astropy.unit.Quantity`.\n b (:obj:`float`, scalar or array-like): Galactic latitude, in degrees,\n or as an :obj:`astropy.unit.Quantity`.\n d (Optional[:obj:`float`, scalar or array-like]): Distance from the Solar\n System, in kpc, or as an :obj:`astropy.unit.Quantity`. Defaults to\n ``None``, meaning no distance is specified.\n **kwargs: Any additional keyword arguments accepted by derived\n classes.\n\nReturns:\n The results of the query, which must be implemented by derived\n classes.", "source": "codesearchnet_filtered"} +{"code": "def build_request_relationship(type, ids):\n if (ids is None):\n return {'data': None}\n elif isinstance(ids, str):\n return {'data': {'id': ids, 'type': type}}\n else:\n return {'data': [{'id': id, 'type': type} for id in ids]}", "docstring": "Build a relationship list.\n\n A relationship list is used to update relationships between two\n resources. Setting sensors on a label, for example, uses this\n function to construct the list of sensor ids to pass to the Helium\n API.\n\nArgs:\n type(string): The resource type for the ids in the relationship\n ids([uuid] or uuid): Just one or a list of resource uuids to use\n in the relationship\n\nReturns:\n A ready to use relationship JSON object.", "source": "codesearchnet_filtered"} +{"code": "def resized_crop(img, i, j, h, w, size, interpolation=Image.BILINEAR):\n assert _is_pil_image(img), 'img should be PIL Image'\n img = crop(img, i, j, h, w)\n img = resize(img, size, interpolation)\n return img", "docstring": "Crop the given PIL Image and resize it to desired size.\n\n Notably used in :class:`~torchvision.transforms.RandomResizedCrop`.\n\nArgs:\n img (PIL Image): Image to be cropped.\n i (int): i in (i,j) i.e coordinates of the upper left corner\n j (int): j in (i,j) i.e coordinates of the upper left corner\n h (int): Height of the cropped image.\n w (int): Width of the cropped image.\n size (sequence or int): Desired output size. Same semantics as ``resize``.\n interpolation (int, optional): Desired interpolation. Default is\n ``PIL.Image.BILINEAR``.\n\nReturns:\n PIL Image: Cropped image.", "source": "codesearchnet_filtered"} +{"code": "def connect_to(name):\n kwargs = config_for(name)\n if (not kwargs):\n raise AttributeError('connection profile not found in config')\n node = connect(return_node=True, **kwargs)\n return node", "docstring": "Creates a node instance based on an entry from the config\n\n This function will retrieve the settings for the specified connection\n from the config and return a Node instance. The configuration must\n be loaded prior to calling this function.\n\nArgs:\n name (str): The name of the connection to load from the config. The\n name argument should be the connection name (everything right of\n the colon from the INI file)\n\nReturns:\n This function will return an instance of Node with the settings\n from the config instance.\n\nRaises:\n AttributeError: raised if the specified configuration name is not\n found in the loaded configuration", "source": "codesearchnet_filtered"} +{"code": "def send_offset_commit_request(self, group, payloads=None, fail_on_error=True, callback=None, group_generation_id=(- 1), consumer_id=''):\n group = _coerce_consumer_group(group)\n encoder = partial(KafkaCodec.encode_offset_commit_request, group=group, group_generation_id=group_generation_id, consumer_id=consumer_id)\n decoder = KafkaCodec.decode_offset_commit_response\n resps = (yield self._send_broker_aware_request(payloads, encoder, decoder, consumer_group=group))\n returnValue(self._handle_responses(resps, fail_on_error, callback, group))", "docstring": "Send a list of OffsetCommitRequests to the Kafka broker for the\n given consumer group.\n\nArgs:\n group (str): The consumer group to which to commit the offsets\n payloads ([OffsetCommitRequest]): List of topic, partition, offsets\n to commit.\n fail_on_error (bool): Whether to raise an exception if a response\n from the Kafka broker indicates an error\n callback (callable): a function to call with each of the responses\n before returning the returned value to the caller.\n group_generation_id (int): Must currently always be -1\n consumer_id (str): Must currently always be empty string\n\nReturns:\n [OffsetCommitResponse]: List of OffsetCommitResponse objects.\n Will raise KafkaError for failed requests if fail_on_error is True", "source": "codesearchnet_filtered"} +{"code": "def with_organisation(self, organisation):\n if (organisation is None):\n organisation = ''\n organisation = slugify(organisation)\n self._validate_organisation(organisation)\n self.organisation = organisation\n return self", "docstring": "Add an organisation segment.\n\nArgs:\n organisation (str): Official name of an administrative body\n holding an election.\n\nReturns:\n IdBuilder\n\nRaises:\n ValueError", "source": "codesearchnet_filtered"} +{"code": "def GetUsernameByIdentifier(self, user_identifier, session_identifier=CURRENT_SESSION):\n user_accounts = self._user_accounts.get(session_identifier, {})\n user_account = user_accounts.get(user_identifier, None)\n if (not user_account):\n return ''\n return (user_account.username or '')", "docstring": "Retrieves the username based on an user identifier.\n\nArgs:\n user_identifier (str): user identifier, either a UID or SID.\n session_identifier (Optional[str])): session identifier, where\n CURRENT_SESSION represents the active session.\n\nReturns:\n str: username.", "source": "codesearchnet_filtered"} +{"code": "def FromJson(json):\n type = ContractParameterType.FromString(json['type'])\n value = json['value']\n param = ContractParameter(type=type, value=None)\n if ((type == ContractParameterType.Signature) or (type == ContractParameterType.ByteArray)):\n param.Value = bytearray.fromhex(value)\n elif (type == ContractParameterType.Boolean):\n param.Value = bool(value)\n elif (type == ContractParameterType.Integer):\n param.Value = int(value)\n elif (type == ContractParameterType.Hash160):\n param.Value = UInt160.ParseString(value)\n elif (type == ContractParameterType.Hash256):\n param.Value = UInt256.ParseString(value)\n elif (type == ContractParameterType.PublicKey):\n param.Value = ECDSA.decode_secp256r1(value).G\n elif (type == ContractParameterType.String):\n param.Value = str(value)\n elif (type == ContractParameterType.Array):\n val = [ContractParameter.FromJson(item) for item in value]\n param.Value = val\n return param", "docstring": "Convert a json object to a ContractParameter object\n\nArgs:\n item (dict): The item to convert to a ContractParameter object\n\nReturns:\n ContractParameter", "source": "codesearchnet_filtered"} +{"code": "def create_raw(self, key, value):\n data = None\n if ((key is not None) and (value is not None)):\n data = self.db.create(key.strip(), value)\n else:\n self.tcex.log.warning(u'The key or value field was None.')\n return data", "docstring": "Create method of CRUD operation for raw data.\n\nArgs:\n key (string): The variable to write to the DB.\n value (any): The data to write to the DB.\n\nReturns:\n (string): Result of DB write.", "source": "codesearchnet_filtered"} +{"code": "def GetDataByPath(self, path):\n (_, path_data) = self._paths.get(path, (None, None))\n return path_data", "docstring": "Retrieves the data associated to a path.\n\nArgs:\n path (str): path of the file entry.\n\nReturns:\n bytes: data or None if not available.", "source": "codesearchnet_filtered"} +{"code": "def get_country_name(self, callsign, timestamp=timestamp_now):\n return self.get_all(callsign, timestamp)[const.COUNTRY]", "docstring": "Returns the country name where the callsign is located\n\nArgs:\n callsign (str): Amateur Radio callsign\n timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\nReturns:\n str: name of the Country\n\nRaises:\n KeyError: No Country found for callsign\n\nNote:\n Don't rely on the country name when working with several instances of\n py:class:`Callinfo`. Clublog and Country-files.org use slightly different names\n for countries. Example:\n\n - Country-files.com: \"Fed. Rep. of Germany\"\n - Clublog: \"FEDERAL REPUBLIC OF GERMANY\"", "source": "codesearchnet_filtered"} +{"code": "def with_mfa(self, mfa_token):\n if hasattr(mfa_token, '__call__'):\n self.context.mfa_token = mfa_token.__call__()\n else:\n self.context.mfa_token = mfa_token\n return self", "docstring": "Set the MFA token for the next request.\n `mfa_token`s are only good for one request. Use this method to chain into\n the protected action you want to perform.\n\n Note: Only useful for Application authentication.\n Usage:\n account.with_mfa(application.totp.now()).pay(...)\n\nArgs:\n mfa_token (str/function, optional): TOTP token for the Application\n OR a callable/function which will generate such a token when called.\n\nReturns:\n self", "source": "codesearchnet_filtered"} +{"code": "def merge_dictionaries(dicts, merge_lists=False):\n dict1 = dicts[0]\n for other_dict in dicts[1:]:\n merge_two_dictionaries(dict1, other_dict, merge_lists=merge_lists)\n return dict1", "docstring": "Merges all dictionaries in dicts into a single dictionary and returns result\n\nArgs:\n dicts (List[DictUpperBound]): Dictionaries to merge into the first one in the list\n merge_lists (bool): Whether to merge lists (True) or replace lists (False). Default is False.\n\nReturns:\n DictUpperBound: Merged dictionary", "source": "codesearchnet_filtered"} +{"code": "def deploy_template_uri(access_token, subscription_id, resource_group, deployment_name, template_uri, parameters):\n endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.Resources/deployments/', deployment_name, '?api-version=', DEPLOYMENTS_API])\n properties = {'templateLink': {'uri': template_uri}}\n properties['mode'] = 'Incremental'\n properties['parameters'] = parameters\n template_body = {'properties': properties}\n body = json.dumps(template_body)\n return do_put(endpoint, body, access_token)", "docstring": "Deploy a template referenced by a URI, with parameters as a JSON string.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n resource_group (str): Azure resource group name.\n deployment_name (str): A name you give to the deployment.\n template_uri (str): URI which points to a JSON template (e.g. github raw location).\n parameters (str): String representation of a JSON template parameters body.\n\nReturns:\n HTTP response.", "source": "codesearchnet_filtered"} +{"code": "def _representative_structure_setter(self, structprop, keep_chain, clean=True, keep_chemicals=None, out_suffix='_clean', outdir=None, force_rerun=False):\n if (not outdir):\n outdir = self.structure_dir\n if (not outdir):\n raise ValueError('Output directory must be specified')\n new_id = 'REP-{}'.format(structprop.id)\n if self.structures.has_id(new_id):\n if force_rerun:\n existing = self.structures.get_by_id(new_id)\n self.structures.remove(existing)\n if clean:\n final_pdb = structprop.clean_structure(outdir=outdir, out_suffix=out_suffix, keep_chemicals=keep_chemicals, keep_chains=keep_chain, force_rerun=force_rerun)\n log.debug('{}: cleaned structure and saved new file at {}'.format(structprop.id, final_pdb))\n else:\n final_pdb = structprop.structure_path\n self.representative_structure = StructProp(ident=new_id, chains=keep_chain, mapped_chains=keep_chain, structure_path=final_pdb, file_type='pdb')\n self.representative_chain = keep_chain\n self.representative_structure.update(structprop.get_dict_with_chain(chain=keep_chain), only_keys=self.__representative_structure_attributes, overwrite=True)\n self.representative_structure.original_structure_id = structprop.id\n self.representative_structure.parse_structure()\n self.structures.append(self.representative_structure)", "docstring": "Set the representative structure by 1) cleaning it and 2) copying over attributes of the original structure.\n\n The structure is copied because the chains stored may change, and cleaning it makes a new PDB file.\n\nArgs:\n structprop (StructProp): StructProp object to set as representative\n keep_chain (str): Chain ID to keep\n clean (bool): If the PDB file should be cleaned (see ssbio.structure.utils.cleanpdb)\n keep_chemicals (str, list): Keep specified chemical names\n out_suffix (str): Suffix to append to clean PDB file\n outdir (str): Path to output directory\n\nReturns:\n StructProp: representative structure", "source": "codesearchnet_filtered"} +{"code": "def run(self, data):\n result_type = namedtuple('Result', 'code messages')\n if (self.passes is True):\n result = result_type(Checker.Code.PASSED, '')\n elif (self.passes is False):\n if self.allow_failure:\n result = result_type(Checker.Code.IGNORED, '')\n else:\n result = result_type(Checker.Code.FAILED, '')\n else:\n try:\n result = self.check(data, **self.arguments)\n messages = ''\n if isinstance(result, tuple):\n (result, messages) = result\n if (result not in Checker.Code):\n result = (Checker.Code.PASSED if bool(result) else Checker.Code.FAILED)\n if ((result == Checker.Code.FAILED) and self.allow_failure):\n result = Checker.Code.IGNORED\n result = result_type(result, messages)\n except NotImplementedError:\n result = result_type(Checker.Code.NOT_IMPLEMENTED, '')\n self.result = result", "docstring": "Run the check method and format the result for analysis.\n\nArgs:\n data (DSM/DMM/MDM): DSM/DMM/MDM instance to check.\n\nReturns:\n tuple (int, str): status constant from Checker class and messages.", "source": "codesearchnet_filtered"} +{"code": "def create_batch(cls, size, **kwargs):\n return [cls.create(**kwargs) for _ in range(size)]", "docstring": "Create a batch of instances of the given class, with overriden attrs.\n\nArgs:\n size (int): the number of instances to create\n\nReturns:\n object list: the created instances", "source": "codesearchnet_filtered"} +{"code": "def pause(self, device):\n resp = self.post('pause', params={'device': device}, return_response=True)\n error = resp.text\n if (not error):\n error = None\n return {'success': (resp.status_code == requests.codes.ok), 'error': error}", "docstring": "Pause the given device.\n\nArgs:\n device (str): Device ID.\n\nReturns:\n dict: with keys ``success`` and ``error``.", "source": "codesearchnet_filtered"} +{"code": "def _ReadConstantDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):\n if is_member:\n error_message = 'data type not supported as member'\n raise errors.DefinitionReaderError(definition_name, error_message)\n value = definition_values.get('value', None)\n if (value is None):\n error_message = 'missing value'\n raise errors.DefinitionReaderError(definition_name, error_message)\n definition_object = self._ReadSemanticDataTypeDefinition(definitions_registry, definition_values, data_types.ConstantDefinition, definition_name, self._SUPPORTED_DEFINITION_VALUES_CONSTANT)\n definition_object.value = value\n return definition_object", "docstring": "Reads a constant data type definition.\n\nArgs:\n definitions_registry (DataTypeDefinitionsRegistry): data type definitions\n registry.\n definition_values (dict[str, object]): definition values.\n definition_name (str): name of the definition.\n is_member (Optional[bool]): True if the data type definition is a member\n data type definition.\n\nReturns:\n ConstantDataTypeDefinition: constant data type definition.\n\nRaises:\n DefinitionReaderError: if the definitions values are missing or if\n the format is incorrect.", "source": "codesearchnet_filtered"} +{"code": "def point_line_distance(point, start, end):\n if (start == end):\n return distance(point, start)\n else:\n un_dist = abs((((end.lat - start.lat) * (start.lon - point.lon)) - ((start.lat - point.lat) * (end.lon - start.lon))))\n n_dist = sqrt((((end.lat - start.lat) ** 2) + ((end.lon - start.lon) ** 2)))\n if (n_dist == 0):\n return 0\n else:\n return (un_dist / n_dist)", "docstring": "Distance from a point to a line, formed by two points\n\nArgs:\n point (:obj:`Point`)\n start (:obj:`Point`): line point\n end (:obj:`Point`): line point\n\nReturns:\n float: distance to line, in degrees", "source": "codesearchnet_filtered"} +{"code": "def match_name(self, in_string, fuzzy=False):\n in_string = _normalize(in_string)\n if (in_string in self._hex_by_color):\n return MatchResult(self._hex_by_color[in_string], 100)\n if (not fuzzy):\n raise ValueError(('No match for %r found.' % in_string))\n color_names = self._hex_by_color.keys()\n set_match = dict(fuzzywuzzy.process.extract(in_string, color_names, scorer=fuzzywuzzy.fuzz.token_set_ratio))\n standard_match = dict(fuzzywuzzy.process.extract(in_string, color_names))\n key_union = (set(set_match) | set(standard_match))\n counter = ((n, (set_match.get(n, 0) + standard_match.get(n, 0))) for n in key_union)\n (color_name, score) = sorted(counter, key=operator.itemgetter(1))[(- 1)]\n return MatchResult(self._hex_by_color[color_name], (score / 2))", "docstring": "Match a color to a sRGB value.\n\n The matching will be based purely on the input string and the color names in the\n registry. If there's no direct hit, a fuzzy matching algorithm is applied. This method\n will never fail to return a sRGB value, but depending on the score, it might or might\n not be a sensible result – as a rule of thumb, any score less then 90 indicates that\n there's a lot of guessing going on. It's the callers responsibility to judge if the return\n value should be trusted.\n\n In normalization terms, this method implements \"normalize an arbitrary color name\n to a sRGB value\".\n\nArgs:\n in_string (string): The input string containing something resembling\n a color name.\n fuzzy (bool, optional): Try fuzzy matching if no exact match was found.\n Defaults to ``False``.\n\nReturns:\n A named tuple with the members `hex_code` and `score`.\n\nRaises:\n ValueError: If ``fuzzy`` is ``False`` and no match is found\n\nExample:\n >>> tint_registry = TintRegistry()\n >>> tint_registry.match_name(\"rather white\", fuzzy=True)\n MatchResult(hex_code=u'ffffff', score=95)", "source": "codesearchnet_filtered"} +{"code": "def list_container_services(access_token, subscription_id, resource_group):\n endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerService/ContainerServices', '?api-version=', ACS_API])\n return do_get(endpoint, access_token)", "docstring": "List the container services in a resource group.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n resource_group (str): Azure resource group name.\n\nReturns:\n HTTP response. JSON model.", "source": "codesearchnet_filtered"} +{"code": "def post_task(task_data, task_uri='/tasks'):\n url = '{}/{}'.format(API_URL, task_uri.lstrip('/'))\n if isinstance(task_data, str):\n task_json = task_data\n else:\n task_json = json.dumps(task_data)\n resp = requests.post(url, data=task_json, headers=HEADERS, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)\n resp_json = resp.json()\n LOG.debug(resp_json)\n assert resp.ok, 'Spinnaker communication error: {0}'.format(resp.text)\n return resp_json['ref']", "docstring": "Create Spinnaker Task.\n\nArgs:\n task_data (str): Task JSON definition.\n\nReturns:\n str: Spinnaker Task ID.\n\nRaises:\n AssertionError: Error response from Spinnaker.", "source": "codesearchnet_filtered"} +{"code": "def _get_mpr_view(self, connection, table):\n logger.debug('Looking for view of the table.\\n table: {}'.format(table.vid))\n view = self.get_view_name(table)\n view_exists = self._relation_exists(connection, view)\n if view_exists:\n logger.debug('View of the table exists.\\n table: {}, view: {}'.format(table.vid, view))\n return view\n raise MissingViewError('sqlite database does not have view for {} table.'.format(table.vid))", "docstring": "Finds and returns view name in the sqlite db represented by given connection.\n\nArgs:\n connection: connection to sqlite db where to look for partition table.\n table (orm.Table):\n\nRaises:\n MissingViewError: if database does not have partition table.\n\nReturns:\n str: database table storing partition data.", "source": "codesearchnet_filtered"} +{"code": "def _gen_condition(cls, initial, new_public_keys):\n try:\n threshold = len(new_public_keys)\n except TypeError:\n threshold = None\n if (isinstance(new_public_keys, list) and (len(new_public_keys) > 1)):\n ffill = ThresholdSha256(threshold=threshold)\n reduce(cls._gen_condition, new_public_keys, ffill)\n elif (isinstance(new_public_keys, list) and (len(new_public_keys) <= 1)):\n raise ValueError('Sublist cannot contain single owner')\n else:\n try:\n new_public_keys = new_public_keys.pop()\n except AttributeError:\n pass\n if isinstance(new_public_keys, Fulfillment):\n ffill = new_public_keys\n else:\n ffill = Ed25519Sha256(public_key=base58.b58decode(new_public_keys))\n initial.add_subfulfillment(ffill)\n return initial", "docstring": "Generates ThresholdSha256 conditions from a list of new owners.\n\nNote:\n This method is intended only to be used with a reduce function.\n For a description on how to use this method, see\n :meth:`~.Output.generate`.\n\nArgs:\n initial (:class:`cryptoconditions.ThresholdSha256`):\n A Condition representing the overall root.\n new_public_keys (:obj:`list` of :obj:`str`|str): A list of new\n owners or a single new owner.\n\nReturns:\n :class:`cryptoconditions.ThresholdSha256`:", "source": "codesearchnet_filtered"} +{"code": "def validate_pipeline(url, pipeline_id, auth, verify_ssl):\n validate_result = requests.get((((url + '/') + pipeline_id) + '/validate'), headers=X_REQ_BY, auth=auth, verify=verify_ssl)\n validate_result.raise_for_status()\n previewer_id = validate_result.json()['previewerId']\n poll_validation_status(url, pipeline_id, previewer_id, auth, verify_ssl)\n preview_result = requests.get(((((url + '/') + pipeline_id) + '/preview/') + validate_result.json()['previewerId']), headers=X_REQ_BY, auth=auth, verify=verify_ssl)\n logging.debug('result content: {}'.format(preview_result.content))\n return preview_result.json()", "docstring": "Validate a pipeline and show issues.\n\nArgs:\n url (str): the host url in the form 'http://host:port/'.\n pipeline_id (str): the ID of of the exported pipeline.\n auth (tuple): a tuple of username, and password.\n verify_ssl (bool): whether to verify ssl certificates\n\nReturns:\n dict: the response json", "source": "codesearchnet_filtered"} +{"code": "def description(self, value):\n try:\n value = np.dtype(value)\n except TypeError as e:\n return None\n for (dtype, string) in self._all:\n if (dtype == value):\n return string\n return None", "docstring": "Fetches the translated description for the given datatype.\n\n The given value will be converted to a `numpy.dtype` object, matched\n against the supported datatypes and the description will be translated\n into the preferred language. (Usually a settings dialog should be\n available to change the language).\n\n If the conversion fails or no match can be found, `None` will be returned.\n\nArgs:\n value (type|numpy.dtype): Any object or type.\n\nReturns:\n str: The translated description of the datatype\n None: If no match could be found or an error occured during convertion.", "source": "codesearchnet_filtered"} +{"code": "def as_matrix(self, depth=0):\n if (depth in self._matrix_cache):\n return self._matrix_cache[depth]\n self._matrix_cache[depth] = matrix = Matrix(self, depth=depth)\n return matrix", "docstring": "Create a matrix with self as node, cache it, return it.\n\nArgs:\n depth (int): depth of the matrix.\n\nReturns:\n Matrix: an instance of Matrix.", "source": "codesearchnet_filtered"} +{"code": "def opensearch(self, query, results=10, redirect=True):\n self._check_query(query, 'Query must be specified')\n query_params = {'action': 'opensearch', 'search': query, 'limit': (100 if (results > 100) else results), 'redirects': ('resolve' if redirect else 'return'), 'warningsaserror': True, 'namespace': ''}\n results = self.wiki_request(query_params)\n self._check_error_response(results, query)\n res = list()\n for (i, item) in enumerate(results[1]):\n res.append((item, results[2][i], results[3][i]))\n return res", "docstring": "Execute a MediaWiki opensearch request, similar to search box\n suggestions and conforming to the OpenSearch specification\n\nArgs:\n query (str): Title to search for\n results (int): Number of pages within the radius to return\n redirect (bool): If **False** return the redirect itself, \\\n otherwise resolve redirects\n\nReturns:\n List: List of results that are stored in a tuple \\\n (Title, Summary, URL)", "source": "codesearchnet_filtered"} +{"code": "def detail_parking(self, **kwargs):\n date = util.datetime_string(kwargs.get('day', 1), kwargs.get('month', 1), kwargs.get('year', 1970), kwargs.get('hour', 0), kwargs.get('minute', 0))\n params = {'language': util.language_code(kwargs.get('lang')), 'publicData': True, 'date': date, 'id': kwargs.get('parking'), 'family': kwargs.get('family')}\n result = self.make_request('detail_parking', {}, **params)\n if (not util.check_result(result)):\n return (False, result.get('message', 'UNKNOWN ERROR'))\n values = util.response_list(result, 'Data')\n return (True, [emtype.ParkingDetails(**a) for a in values])", "docstring": "Obtain detailed info of a given parking.\n\nArgs:\n lang (str): Language code (*es* or *en*).\n day (int): Day of the month in format DD.\n The number is automatically padded if it only has one digit.\n month (int): Month number in format MM.\n The number is automatically padded if it only has one digit.\n year (int): Year number in format YYYY.\n hour (int): Hour of the day in format hh.\n The number is automatically padded if it only has one digit.\n minute (int): Minute of the hour in format mm.\n The number is automatically padded if it only has one digit.\n parking (int): ID of the parking to query.\n family (str): Family code of the parking (3 chars).\n\nReturns:\n Status boolean and parsed response (list[ParkingDetails]), or message\n string in case of error.", "source": "codesearchnet_filtered"} +{"code": "def register_views(self, app):\n self.add_resource(LoginRedirectView, '/auth/login')\n self.add_resource(LogoutRedirectView, '/auth/logout')\n for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.auth']['plugins']:\n cls = entry_point.load()\n app.available_auth_systems[cls.name] = cls\n if app.register_auth_system(cls):\n for vcls in cls.views:\n self.add_resource(vcls, *vcls.URLS)\n logger.debug('Registered auth system view {} for paths: {}'.format(cls.__name__, ', '.join(vcls.URLS)))\n if (not app.active_auth_system):\n logger.error('No auth systems active, please enable an auth system and then start the system again')\n sys.exit((- 1))\n for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.views']['plugins']:\n view = entry_point.load()\n self.add_resource(view, *view.URLS)\n app.register_menu_item(view.MENU_ITEMS)\n logger.debug('Registered view {} for paths: {}'.format(view.__name__, ', '.join(view.URLS)))", "docstring": "Iterates all entry points for views and auth systems and dynamically load and register the routes with Flask\n\nArgs:\n app (`CINQFlask`): CINQFlask object to register views for\n\nReturns:\n `None`", "source": "codesearchnet_filtered"} +{"code": "def with_random_weights(cls, options):\n return cls([(value, random.randint(1, len(options))) for value in options])", "docstring": "Initialize from a list of options with random weights.\n\n The weights assigned to each object are uniformally random\n integers between ``1`` and ``len(options)``\n\nArgs:\n options (list): The list of options of any type this object\n can return with the ``get()`` method.\n\nReturns:\n SoftOptions: A newly constructed instance", "source": "codesearchnet_filtered"} +{"code": "def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'):\n total_pages = int(math.ceil((record_count / limit)))\n next_cond = ((limit + offset) <= record_count)\n prev_cond = (offset >= limit)\n next_page = ((base_uri + page_nav_tpl.format(limit, (offset + limit))) if next_cond else None)\n prev_page = ((base_uri + page_nav_tpl.format(limit, (offset - limit))) if prev_cond else None)\n return OrderedDict([('total_count', record_count), ('total_pages', total_pages), ('next_page', next_page), ('prev_page', prev_page)])", "docstring": "Compute pagination info for collection filtering.\n\nArgs:\n limit (int): Collection filter limit.\n offset (int): Collection filter offset.\n record_count (int): Collection filter total record count.\n base_uri (str): Collection filter base uri (without limit, offset)\n page_nav_tpl (str): Pagination template.\n\nReturns:\n A mapping of pagination info.", "source": "codesearchnet_filtered"} +{"code": "def setLCDCmd(self, display_list, password='00000000'):\n result = False\n try:\n self.initLcd()\n item_cnt = len(display_list)\n if ((item_cnt > 45) or (item_cnt <= 0)):\n ekm_log('LCD item list must have between 1 and 40 items')\n return False\n for display_item in display_list:\n self.addLcdItem(int(display_item))\n result = self.setLCD(password)\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n return result", "docstring": "Single call wrapper for LCD set.\"\n\n Wraps :func:`~ekmmeters.V4Meter.setLcd` and associated init and add methods.\n\nArgs:\n display_list (list): List composed of :class:`~ekmmeters.LCDItems`\n password (str): Optional password.\n\nReturns:\n bool: Passthrough from :func:`~ekmmeters.V4Meter.setLcd`", "source": "codesearchnet_filtered"} +{"code": "def check(self, check_req):\n self.start()\n res = self._check_aggregator.check(check_req)\n if res:\n _logger.debug(u'using cached check response for %s: %s', check_request, res)\n return res\n try:\n transport = self._create_transport()\n resp = transport.services.Check(check_req)\n self._check_aggregator.add_response(check_req, resp)\n return resp\n except exceptions.Error:\n _logger.error(u'direct send of check request failed %s', check_request, exc_info=True)\n return None", "docstring": "Process a check_request.\n\n The req is first passed to the check_aggregator. If there is a valid\n cached response, that is returned, otherwise a response is obtained from\n the transport.\n\nArgs:\n check_req (``ServicecontrolServicesCheckRequest``): to be sent to\n the service control service\n\nReturns:\n ``CheckResponse``: either the cached response if one is applicable\n or a response from making a transport request, or None if\n if the request to the transport fails", "source": "codesearchnet_filtered"} +{"code": "def table_info(self, table):\n\n def _row2dict(row):\n return {'name': row[1], 'type': row[2].lower(), 'notnull': (row[3] == 1), 'default_value': row[4], 'primary_key': (row[5] == 1)}\n if (table not in self.tables):\n raise sql.OperationalError(\"Cannot retrieve information about missing table '{0}'\".format(table))\n query = self.execute('PRAGMA table_info({table})'.format(table=table))\n return [_row2dict(row) for row in query]", "docstring": "Returns information about the named table.\n\n See: https://www.sqlite.org/pragma.html#pragma_table_info\n\nExample:\n >>> db.table_info(\"foo\")\n [{\"name\": \"id\", \"type\": \"integer\", \"primary key\": True,\n \"notnull\": False, \"default_value\": None}]\n\nArgs:\n name (str): The name of the table to lookup.\n\nReturns:\n list of dicts: One dict per column. Each dict contains the\n keys: \"name\", \"type\", \"primary key\", \"notnull\", and\n \"default_value\".\n\nRaises:\n sql.OperationalError: If table does not exist.", "source": "codesearchnet_filtered"} +{"code": "def get_current_round(self, tournament=1):\n query = '\\n query($tournament: Int!) {\\n rounds(tournament: $tournament\\n number: 0) {\\n number\\n }\\n }\\n '\n arguments = {'tournament': tournament}\n data = self.raw_query(query, arguments)['data']['rounds'][0]\n if (data is None):\n return None\n round_num = data['number']\n return round_num", "docstring": "Get number of the current active round.\n\nArgs:\n tournament (int): ID of the tournament (optional, defaults to 1)\n\nReturns:\n int: number of the current active round\n\nExample:\n >>> NumerAPI().get_current_round()\n 104", "source": "codesearchnet_filtered"} +{"code": "def patch(self, id, name=None, description=None, whitelisted_container_task_types=None, whitelisted_executable_task_types=None):\n request_url = (self._client.base_api_url + self.detail_url.format(id=id))\n data_to_patch = {}\n if (name is not None):\n data_to_patch['name'] = name\n if (description is not None):\n data_to_patch['description'] = description\n if (whitelisted_container_task_types is not None):\n data_to_patch['whitelisted_container_task_types'] = whitelisted_container_task_types\n if (whitelisted_executable_task_types is not None):\n data_to_patch['whitelisted_executable_task_types'] = whitelisted_executable_task_types\n response = self._client.session.patch(request_url, data=data_to_patch)\n self.validate_request_success(response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_200_OK)\n return self.response_data_to_model_instance(response.json())", "docstring": "Partially updates a task whitelist on the saltant server.\n\nArgs:\n id (int): The ID of the task whitelist.\n name (str, optional): The name of the task whitelist.\n description (str, optional): A description of the task whitelist.\n whitelisted_container_task_types (list, optional): A list of\n whitelisted container task type IDs.\n whitelisted_executable_task_types (list, optional): A list\n of whitelisted executable task type IDs.\n\nReturns:\n :class:`saltant.models.task_whitelist.TaskWhitelist`:\n A task whitelist model instance representing the task\n whitelist just updated.", "source": "codesearchnet_filtered"} +{"code": "def _get_css_files(cls, extra_files):\n packager = Packager()\n css_packages = getattr(cls, 'css_packages', {})\n return dict(((media_target, cls._get_media_files(packager=packager, media_packages=media_packages, media_type='css', extra_files=extra_files.get(media_target, []))) for (media_target, media_packages) in six.iteritems(css_packages)))", "docstring": "Return all CSS files from the Media class.\n\nArgs:\n extra_files (dict):\n The contents of the Media class's original :py:attr:`css`\n attribute, if one was provided.\n\nReturns:\n dict:\n The CSS media types and files to return for the :py:attr:`css`\n attribute.", "source": "codesearchnet_filtered"} +{"code": "def GetRelativePath(self, path_spec):\n location = getattr(path_spec, 'location', None)\n if (location is None):\n raise errors.PathSpecError('Path specification missing location.')\n if path_spec_factory.Factory.IsSystemLevelTypeIndicator(self._file_system.type_indicator):\n if (not location.startswith(self._mount_point.location)):\n raise errors.PathSpecError('Path specification does not contain mount point.')\n else:\n if (not hasattr(path_spec, 'parent')):\n raise errors.PathSpecError('Path specification missing parent.')\n if (path_spec.parent != self._mount_point):\n raise errors.PathSpecError('Path specification does not contain mount point.')\n path_segments = self._file_system.SplitPath(location)\n if path_spec_factory.Factory.IsSystemLevelTypeIndicator(self._file_system.type_indicator):\n mount_point_path_segments = self._file_system.SplitPath(self._mount_point.location)\n path_segments = path_segments[len(mount_point_path_segments):]\n return '{0:s}{1:s}'.format(self._file_system.PATH_SEPARATOR, self._file_system.PATH_SEPARATOR.join(path_segments))", "docstring": "Returns the relative path based on a resolved path specification.\n\n The relative path is the location of the upper most path specification.\n The the location of the mount point is stripped off if relevant.\n\nArgs:\n path_spec (PathSpec): path specification.\n\nReturns:\n str: corresponding relative path or None if the relative path could not\n be determined.\n\nRaises:\n PathSpecError: if the path specification is incorrect.", "source": "codesearchnet_filtered"} +{"code": "def get_sketch(self, sketch_id):\n resource_url = '{0:s}/sketches/{1:d}/'.format(self.api_base_url, sketch_id)\n response = self.session.get(resource_url)\n response_dict = response.json()\n try:\n response_dict['objects']\n except KeyError:\n raise ValueError('Sketch does not exist or you have no access')\n return response_dict", "docstring": "Get information on the specified sketch.\n\nArgs:\n sketch_id (int): ID of sketch\n\nReturns:\n dict: Dictionary of sketch information\n\nRaises:\n ValueError: Sketch is inaccessible", "source": "codesearchnet_filtered"} +{"code": "def get_history_by_tail_number(self, tail_number, page=1, limit=100):\n url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)\n return self._fr24.get_data(url, True)", "docstring": "Fetch the history of a particular aircraft by its tail number.\n\n This method can be used to get the history of a particular aircraft by its tail number.\n It checks the user authentication and returns the data accordingly.\n\nArgs:\n tail_number (str): The tail number, e.g. VT-ANL\n page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data\n limit (int): Optional limit on number of records returned\n\nReturns:\n A list of dicts with the data; one dict for each row of data from flightradar24\n\n Example::\n\n from pyflightdata import FlightData\n f=FlightData()\n #optional login\n f.login(myemail,mypassword)\n f.get_history_by_flight_number('VT-ANL')\n f.get_history_by_flight_number('VT-ANL',page=1,limit=10)", "source": "codesearchnet_filtered"} +{"code": "def _parse_vrf(self, config):\n match = re.search('^router ospf \\\\d+ vrf (\\\\w+)', config)\n if match:\n return dict(vrf=match.group(1))\n return dict(vrf='default')", "docstring": "Parses config file for the OSPF vrf name\n\nArgs:\n config(str): Running configuration\n\nReturns:\n dict: key: ospf_vrf (str)", "source": "codesearchnet_filtered"} +{"code": "def version(self):\n version = int(self._dll.JLINKARM_GetDLLVersion())\n major = (version / 10000)\n minor = ((version / 100) % 100)\n rev = (version % 100)\n rev = ('' if (rev == 0) else chr(((rev + ord('a')) - 1)))\n return ('%d.%02d%s' % (major, minor, rev))", "docstring": "Returns the device's version.\n\n The device's version is returned as a string of the format: M.mr where\n ``M`` is major number, ``m`` is minor number, and ``r`` is revision\n character.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n Device version string.", "source": "codesearchnet_filtered"} +{"code": "def _validate_write(self, address):\n if (not any((address.startswith(ns) for ns in self._write_list))):\n raise AuthorizationException(address=address)", "docstring": "Raises an exception if the address is not allowed to be set\n in this context, based on txn outputs.\n\nNote:\n Checks that the address is either listed fully as one of the\n outputs, or some portion of the address is listed as a namespace\n in the outputs of the txn.\n\nArgs:\n address (str): The address to be validated. The context manager\n validates the address correctness (70 hex characters).\n\nReturns:\n None\n\nRaises:\n AuthorizationException", "source": "codesearchnet_filtered"} +{"code": "def get_params(img, output_size):\n (w, h) = img.size\n (th, tw) = output_size\n if ((w == tw) and (h == th)):\n return (0, 0, h, w)\n i = random.randint(0, (h - th))\n j = random.randint(0, (w - tw))\n return (i, j, th, tw)", "docstring": "Get parameters for ``crop`` for a random crop.\n\nArgs:\n img (PIL Image): Image to be cropped.\n output_size (tuple): Expected output size of the crop.\n\nReturns:\n tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.", "source": "codesearchnet_filtered"} +{"code": "def smart_device_selection(preferred_device_type=None):\n cl_environments = CLEnvironmentFactory.all_devices(cl_device_type=preferred_device_type)\n platform_names = [env.platform.name for env in cl_environments]\n has_amd_pro_platform = any((('AMD Accelerated Parallel Processing' in name) for name in platform_names))\n if has_amd_pro_platform:\n return list(filter((lambda env: ('Clover' not in env.platform.name)), cl_environments))\n if ((preferred_device_type is not None) and (not len(cl_environments))):\n return CLEnvironmentFactory.all_devices()\n return cl_environments", "docstring": "Get a list of device environments that is suitable for use in MOT.\n\n Basically this gets the total list of devices using all_devices() and applies a filter on it.\n\n This filter does the following:\n 1) if the 'AMD Accelerated Parallel Processing' is available remove all environments using the 'Clover'\n platform.\n\n More things may be implemented in the future.\n\nArgs:\n preferred_device_type (str): the preferred device type, one of 'CPU', 'GPU' or 'APU'.\n If no devices of this type can be found, we will use any other device available.\n\nReturns:\n list of CLEnvironment: List with the CL device environments.", "source": "codesearchnet_filtered"} +{"code": "def remove_showcase(self, showcase):\n dataset_showcase = self._get_dataset_showcase_dict(showcase)\n showcase = hdx.data.showcase.Showcase({'id': dataset_showcase['showcase_id']}, configuration=self.configuration)\n showcase._write_to_hdx('disassociate', dataset_showcase, 'package_id')", "docstring": "Remove dataset from showcase\n\nArgs:\n showcase (Union[Showcase,Dict,str]): Either a showcase id string or showcase metadata from a Showcase object or dictionary\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def parse_clnsig(acc, sig, revstat, transcripts):\n clnsig_accsessions = []\n if acc:\n try:\n acc = int(acc)\n except ValueError:\n pass\n if isinstance(acc, int):\n revstat_groups = []\n if revstat:\n revstat_groups = [rev.lstrip('_') for rev in revstat.split(',')]\n sig_groups = []\n if sig:\n for significance in sig.split('/'):\n splitted_word = significance.split('_')\n sig_groups.append(' '.join(splitted_word[:2]))\n for sign_term in sig_groups:\n clnsig_accsessions.append({'value': sign_term, 'accession': int(acc), 'revstat': ', '.join(revstat_groups)})\n else:\n acc_groups = acc.split('|')\n sig_groups = sig.split('|')\n revstat_groups = revstat.split('|')\n for (acc_group, sig_group, revstat_group) in zip(acc_groups, sig_groups, revstat_groups):\n accessions = acc_group.split(',')\n significances = sig_group.split(',')\n revstats = revstat_group.split(',')\n for (accession, significance, revstat) in zip(accessions, significances, revstats):\n clnsig_accsessions.append({'value': int(significance), 'accession': accession, 'revstat': revstat})\n elif transcripts:\n clnsig = set()\n for transcript in transcripts:\n for annotation in transcript.get('clinsig', []):\n clnsig.add(annotation)\n for annotation in clnsig:\n clnsig_accsessions.append({'value': annotation})\n return clnsig_accsessions", "docstring": "Get the clnsig information\n\nArgs:\n acc(str): The clnsig accession number, raw from vcf\n sig(str): The clnsig significance score, raw from vcf\n revstat(str): The clnsig revstat, raw from vcf\n transcripts(iterable(dict))\n\nReturns:\n clnsig_accsessions(list): A list with clnsig accessions", "source": "codesearchnet_filtered"} +{"code": "def grid_reload_from_ids(oargrid_jobids):\n gk = get_api_client()\n jobs = []\n for (site, job_id) in oargrid_jobids:\n jobs.append(gk.sites[site].jobs[job_id])\n return jobs", "docstring": "Reload all running or pending jobs of Grid'5000 from their ids\n\nArgs:\n oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the\n jobs on each site\n\nReturns:\n The list of python-grid5000 jobs retrieved", "source": "codesearchnet_filtered"} +{"code": "def map_uniprot_resnum_to_pdb(uniprot_resnum, chain_id, sifts_file):\n parser = etree.XMLParser(ns_clean=True)\n tree = etree.parse(sifts_file, parser)\n root = tree.getroot()\n my_pdb_resnum = None\n my_pdb_annotation = False\n ent = './/{http://www.ebi.ac.uk/pdbe/docs/sifts/eFamily.xsd}entity'\n for chain in root.findall(ent):\n if (chain.attrib['entityId'] == chain_id):\n ures = ('.//{http://www.ebi.ac.uk/pdbe/docs/sifts/eFamily.xsd}crossRefDb[@dbSource=\"UniProt\"][@dbResNum=\"%s\"]' % uniprot_resnum)\n my_uniprot_residue = chain.findall(ures)\n if (len(my_uniprot_residue) == 1):\n parent = my_uniprot_residue[0].getparent()\n pres = './/{http://www.ebi.ac.uk/pdbe/docs/sifts/eFamily.xsd}crossRefDb[@dbSource=\"PDB\"]'\n my_pdb_residue = parent.findall(pres)\n my_pdb_resnum = int(my_pdb_residue[0].attrib['dbResNum'])\n anno = './/{http://www.ebi.ac.uk/pdbe/docs/sifts/eFamily.xsd}residueDetail[@dbSource=\"PDBe\"][@property=\"Annotation\"]'\n my_pdb_annotation = parent.findall(anno)\n if (len(my_pdb_annotation) == 1):\n my_pdb_annotation = my_pdb_annotation[0].text\n if (my_pdb_annotation == 'Not_Observed'):\n my_pdb_annotation = False\n else:\n my_pdb_annotation = True\n else:\n return (None, False)\n return (my_pdb_resnum, my_pdb_annotation)", "docstring": "Map a UniProt residue number to its corresponding PDB residue number.\n\n This function requires that the SIFTS file be downloaded,\n and also a chain ID (as different chains may have different mappings).\n\nArgs:\n uniprot_resnum (int): integer of the residue number you'd like to map\n chain_id (str): string of the PDB chain to map to\n sifts_file (str): Path to the SIFTS XML file\n\nReturns:\n (tuple): tuple containing:\n\n mapped_resnum (int): Mapped residue number\n is_observed (bool): Indicates if the 3D structure actually shows the residue", "source": "codesearchnet_filtered"} +{"code": "def _ReadAttributeValueString(self, attribute_values_data, record_offset, attribute_values_data_offset, attribute_value_offset):\n if (attribute_value_offset == 0):\n return None\n data_type_map = self._GetDataTypeMap('keychain_string')\n file_offset = ((record_offset + attribute_values_data_offset) + attribute_value_offset)\n attribute_value_offset -= (attribute_values_data_offset + 1)\n attribute_value_data = attribute_values_data[attribute_value_offset:]\n try:\n string_attribute_value = self._ReadStructureFromByteStream(attribute_value_data, file_offset, data_type_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError('Unable to map string attribute value data at offset: 0x{0:08x} with error: {1!s}'.format(file_offset, exception))\n return string_attribute_value.string", "docstring": "Reads a string attribute value.\n\nArgs:\n attribute_values_data (bytes): attribute values data.\n record_offset (int): offset of the record relative to the start of\n the file.\n attribute_values_data_offset (int): offset of the attribute values data\n relative to the start of the record.\n attribute_value_offset (int): offset of the attribute relative to\n the start of the record.\n\nReturns:\n str: string value or None if attribute value offset is not set.\n\nRaises:\n ParseError: if the attribute value cannot be read.", "source": "codesearchnet_filtered"} +{"code": "def consume(self, source):\n manifest = OrderedDict()\n rules = parse_stylesheet(source, skip_comments=True, skip_whitespace=True)\n for rule in rules:\n name = self.digest_prelude(rule)\n if (not name.startswith(RULE_BASE_PREFIX)):\n continue\n properties = self.digest_content(rule)\n manifest[name] = properties\n return manifest", "docstring": "Parse source and consume tokens from tinycss2.\n\nArgs:\n source (string): Source content to parse.\n\nReturns:\n dict: Retrieved rules.", "source": "codesearchnet_filtered"} +{"code": "def copy(source, destination, ignore=None, adapter=None, fatal=True, logger=LOG.debug):\n return _file_op(source, destination, _copy, adapter, fatal, logger, ignore=ignore)", "docstring": "Copy source -> destination\n\nArgs:\n source (str | None): Source file or folder\n destination (str | None): Destination file or folder\n ignore (callable | list | str | None): Names to be ignored\n adapter (callable | None): Optional function to call on 'source' before copy\n fatal (bool | None): Abort execution on failure if True\n logger (callable | None): Logger to use\n\nReturns:\n (int): 1 if effectively done, 0 if no-op, -1 on failure", "source": "codesearchnet_filtered"} +{"code": "def get_mapping_variable(variable_name, variables_mapping):\n try:\n return variables_mapping[variable_name]\n except KeyError:\n raise exceptions.VariableNotFound('{} is not found.'.format(variable_name))", "docstring": "get variable from variables_mapping.\n\nArgs:\n variable_name (str): variable name\n variables_mapping (dict): variables mapping\n\nReturns:\n mapping variable value.\n\nRaises:\n exceptions.VariableNotFound: variable is not found.", "source": "codesearchnet_filtered"} +{"code": "def build_sanitiser_node_dict(cfg, sinks_in_file):\n sanitisers = list()\n for sink in sinks_in_file:\n sanitisers.extend(sink.sanitisers)\n sanitisers_in_file = list()\n for sanitiser in sanitisers:\n for cfg_node in cfg.nodes:\n if (sanitiser in cfg_node.label):\n sanitisers_in_file.append(Sanitiser(sanitiser, cfg_node))\n sanitiser_node_dict = dict()\n for sanitiser in sanitisers:\n sanitiser_node_dict[sanitiser] = list(find_sanitiser_nodes(sanitiser, sanitisers_in_file))\n return sanitiser_node_dict", "docstring": "Build a dict of string -> TriggerNode pairs, where the string\n is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser.\n\nArgs:\n cfg(CFG): cfg to traverse.\n sinks_in_file(list[TriggerNode]): list of TriggerNodes containing\n the sinks in the file.\n\nReturns:\n A string -> TriggerNode dict.", "source": "codesearchnet_filtered"} +{"code": "def _get_sample_generator(samples):\n if isinstance(samples, Mapping):\n\n def samples_generator():\n for ind in range(samples[list(samples.keys())[0]].shape[0]):\n (yield np.array([samples[s][(ind, :)] for s in sorted(samples)]))\n elif isinstance(samples, np.ndarray):\n\n def samples_generator():\n for ind in range(samples.shape[0]):\n (yield samples[ind])\n else:\n samples_generator = samples\n return samples_generator", "docstring": "Get a sample generator from the given polymorphic input.\n\nArgs:\n samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and\n n samples, or a dictionary with for every parameter a matrix with shape (d, n) or, finally,\n a generator function that yields sample arrays of shape (p, n).\n\nReturns:\n generator: a generator that yields a matrix of size (p, n) for every problem in the input.", "source": "codesearchnet_filtered"} +{"code": "def get_overlaps(self, offset, length):\n if (''.join([chunk.word for chunk in self])[offset] == ' '):\n offset += 1\n index = 0\n result = ChunkList()\n for chunk in self:\n if ((offset < (index + len(chunk.word))) and (index < (offset + length))):\n result.append(chunk)\n index += len(chunk.word)\n return result", "docstring": "Returns chunks overlapped with the given range.\n\nArgs:\n offset (int): Begin offset of the range.\n length (int): Length of the range.\n\nReturns:\n Overlapped chunks. (:obj:`budou.chunk.ChunkList`)", "source": "codesearchnet_filtered"} +{"code": "def create_package(name, data, package_cls=None):\n from rez.package_maker__ import PackageMaker\n maker = PackageMaker(name, data, package_cls=package_cls)\n return maker.get_package()", "docstring": "Create a package given package data.\n\nArgs:\n name (str): Package name.\n data (dict): Package data. Must conform to `package_maker.package_schema`.\n\nReturns:\n `Package` object.", "source": "codesearchnet_filtered"} +{"code": "def fwd(self, x_data):\n x_data = numpy.asfarray(x_data)\n shape = x_data.shape\n x_data = x_data.reshape(len(self), (- 1))\n (lower, upper) = evaluation.evaluate_bound(self, x_data)\n q_data = numpy.zeros(x_data.shape)\n indices = (x_data > upper)\n q_data[indices] = 1\n indices = ((~ indices) & (x_data >= lower))\n q_data[indices] = numpy.clip(evaluation.evaluate_forward(self, x_data), a_min=0, a_max=1)[indices]\n q_data = q_data.reshape(shape)\n return q_data", "docstring": "Forward Rosenblatt transformation.\n\nArgs:\n x_data (numpy.ndarray):\n Location for the distribution function. ``x_data.shape`` must\n be compatible with distribution shape.\n\nReturns:\n (numpy.ndarray):\n Evaluated distribution function values, where\n ``out.shape==x_data.shape``.", "source": "codesearchnet_filtered"} +{"code": "def find_all(self, selector, **kwargs):\n self.debug_log(('Finding elements with selector: %s' % selector))\n raise_exception = kwargs.get('raise_exception', BROME_CONFIG['proxy_driver']['raise_exception'])\n self.debug_log(('effective raise_exception: %s' % raise_exception))\n wait_until_present = kwargs.get('wait_until_present', BROME_CONFIG['proxy_driver']['wait_until_present_before_find'])\n self.debug_log(('effective wait_until_present: %s' % wait_until_present))\n wait_until_visible = kwargs.get('wait_until_visible', BROME_CONFIG['proxy_driver']['wait_until_visible_before_find'])\n self.debug_log(('effective wait_until_visible: %s' % wait_until_visible))\n _selector = Selector(self, selector)\n found = False\n if wait_until_visible:\n found = self.wait_until_visible(selector, raise_exception=False)\n if (wait_until_present and (not found)):\n found = self.wait_until_present(selector, raise_exception=raise_exception)\n if (not found):\n self.debug_log(('find_all (%s): No element found' % _selector))\n return []\n try:\n elements = getattr(self._driver, _selector.find_function)(_selector.get_selector())\n except exceptions.NoSuchElementException:\n self.debug_log(('find_all (%s): No element found' % _selector))\n self.print_javascript_error()\n if raise_exception:\n raise exceptions.NoSuchElementException(_selector)\n else:\n return []\n if (type(elements) == list):\n if len(elements):\n self.debug_log(('find_all (%s): Element found' % _selector))\n return ProxyElementList(elements, _selector, self)\n else:\n msg = ('find_all (%s): No element found' % _selector)\n self.debug_log(msg)\n self.print_javascript_error()\n if raise_exception:\n raise exceptions.NoSuchElementException(msg)\n else:\n return []\n else:\n self.debug_log(('find_all (%s): Element found' % _selector))\n return [ProxyElement(elements, _selector, self)]", "docstring": "Return all the elements found with a selector\n\nArgs:\n selector (str): the selector used to find the element\n\n Kwargs:\n wait_until_present (bool) default configurable via\n proxy_driver:wait_until_present_before_find\n wait_until_visible (bool) default configurable via\n proxy_driver:wait_until_visible_before_find\n raise_exception (bool) default configurable via\n proxy_driver:raise_exception\n\nReturns:\n empty list if no element was found\n proxy_element_list when element are found\n\nRaises:\n this function might raise an exception depending on the\n raise_exception kwargs\n or\n the config proxy_driver:raise_exception", "source": "codesearchnet_filtered"} +{"code": "def _get_initial_step(parameters, lower_bounds, upper_bounds, max_step_sizes):\n nmr_params = parameters.shape[1]\n initial_step = np.zeros_like(parameters)\n if (max_step_sizes is None):\n max_step_sizes = 0.1\n if isinstance(max_step_sizes, Number):\n max_step_sizes = ([max_step_sizes] * nmr_params)\n max_step_sizes = np.array(max_step_sizes)\n for ind in range(parameters.shape[1]):\n minimum_allowed_step = np.minimum(np.abs((parameters[(:, ind)] - lower_bounds[ind])), np.abs((upper_bounds[ind] - parameters[(:, ind)])))\n initial_step[(:, ind)] = np.minimum(minimum_allowed_step, max_step_sizes[ind])\n return (initial_step / 2.0)", "docstring": "Get an initial step size to use for every parameter.\n\n This chooses the step sizes based on the maximum step size and the lower and upper bounds.\n\nArgs:\n parameters (ndarray): The parameters at which to evaluate the gradient. A (d, p) matrix with d problems,\n p parameters and n samples.\n lower_bounds (list): lower bounds\n upper_bounds (list): upper bounds\n max_step_sizes (list or None): the maximum step size, or the maximum step size per parameter. Defaults to 0.1\n\nReturns:\n ndarray: for every problem instance the vector with the initial step size for each parameter.", "source": "codesearchnet_filtered"} +{"code": "def _GetSerializedAttributeContainerByIndex(self, container_type, index):\n container_list = self._GetSerializedAttributeContainerList(container_type)\n return container_list.GetAttributeContainerByIndex(index)", "docstring": "Retrieves a specific serialized attribute container.\n\nArgs:\n container_type (str): attribute container type.\n index (int): attribute container index.\n\nReturns:\n bytes: serialized attribute container data or None if not available.", "source": "codesearchnet_filtered"} +{"code": "def make_full_document(text, title=None, preamp_decl={}, preamb_extra=None):\n import utool as ut\n doc_preamb = ut.codeblock('\\n %\\\\documentclass{article}\\n \\\\documentclass[10pt,twocolumn,letterpaper]{article}\\n % \\\\usepackage[utf8]{inputenc}\\n \\\\usepackage[T1]{fontenc}\\n\\n \\\\usepackage{times}\\n \\\\usepackage{epsfig}\\n \\\\usepackage{graphicx}\\n \\\\usepackage{amsmath,amsthm,amssymb}\\n \\\\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}\\n \\\\usepackage{multirow}\\n \\\\usepackage{subcaption}\\n \\\\usepackage{booktabs}\\n\\n %\\\\pagenumbering{gobble}\\n ')\n if (preamb_extra is not None):\n if isinstance(preamb_extra, (list, tuple)):\n preamb_extra = '\\n'.join(preamb_extra)\n doc_preamb += (('\\n' + preamb_extra) + '\\n')\n if (title is not None):\n preamp_decl['title'] = title\n decl_lines = ['\\\\{key}{{{val}}}'.format(key=key, val=val) for (key, val) in preamp_decl.items()]\n doc_decllines = '\\n'.join(decl_lines)\n doc_header = ut.codeblock('\\n \\\\begin{document}\\n ')\n if (preamp_decl.get('title') is not None):\n doc_header += '\\\\maketitle'\n doc_footer = ut.codeblock('\\n \\\\end{document}\\n ')\n text_ = '\\n'.join((doc_preamb, doc_decllines, doc_header, text, doc_footer))\n return text_", "docstring": "r\"\"\"\n dummy preamble and document to wrap around latex fragment\n\nArgs:\n text (str):\n title (str):\n\nReturns:\n str: text_\n\n CommandLine:\n python -m utool.util_latex --test-make_full_document\n\nExample:\n >>> # DISABLE_DOCTEST\n >>> from utool.util_latex import * # NOQA\n >>> text = 'foo'\n >>> title = 'title'\n >>> preamp_decl = {}\n >>> text_ = make_full_document(text, title)\n >>> result = str(text_)\n >>> print(result)", "source": "codesearchnet_filtered"} +{"code": "def add_server(self, hostname, port, use_ssl, tls_ctx=None):\n if ((not use_ssl) and tls_ctx):\n raise ValueError('Cannot specify a TLS context and not use SSL!')\n server = ldap3.Server(hostname, port=port, use_ssl=use_ssl, tls=tls_ctx)\n self._server_pool.add(server)\n return server", "docstring": "Add an additional server to the server pool and return the\n freshly created server.\n\nArgs:\n hostname (str): Hostname of the server\n port (int): Port of the server\n use_ssl (bool): True if SSL is to be used when connecting.\n tls_ctx (ldap3.Tls): An optional TLS context object to use\n when connecting.\n\nReturns:\n ldap3.Server: The freshly created server object.", "source": "codesearchnet_filtered"} +{"code": "def extract_build_info(exe_path, elf_section=ELF_SECTION):\n build_info = {}\n with mkdtemp() as tempd, pushd(tempd):\n proc = subprocess.Popen([OBJCOPY, DUMP_SECTION, '{secn}={ofile}'.format(secn=elf_section, ofile=BUILDINFO_FILE), exe_path], stderr=subprocess.PIPE)\n proc.wait()\n errno = proc.returncode\n stderr = proc.stderr.read()\n if (errno or len(stderr)):\n LOGGER.warning('objcopy failed with errno %s.', errno)\n if len(stderr):\n LOGGER.warning('objcopy failed with following msg:\\n%s', stderr)\n return build_info\n with open(BUILDINFO_FILE) as build_info_f:\n try:\n build_info = json.load(build_info_f, object_hook=byteify)\n except JSONDcdError as jsde:\n LOGGER.warning('benchmark executable build is not valid json:')\n LOGGER.warning(jsde.msg)\n LOGGER.warning('build info section content:')\n LOGGER.warning(jsde.doc)\n return build_info", "docstring": "Extracts the build information from a given executable.\n\n The build information is expected to be in json format, which is parsed\n and returned as a dictionary.\n If no build information is found an empty dictionary is returned.\n\n This assumes binutils 2.25 to work.\n\nArgs:\n exe_path (str): The full path to the executable to be examined\n\nReturns:\n dict: A dictionary of the extracted information.", "source": "codesearchnet_filtered"} +{"code": "def _DictToListOfStrings(self, data_dict):\n ret_list = []\n for (key, value) in iter(data_dict.items()):\n if (key in ('body', 'datetime', 'type', 'room', 'rooms', 'id')):\n continue\n ret_list.append('{0:s} = {1!s}'.format(key, value))\n return ret_list", "docstring": "Converts a dictionary into a list of strings.\n\nArgs:\n data_dict (dict[str, object]): dictionary to convert.\n\nReturns:\n list[str]: list of strings.", "source": "codesearchnet_filtered"} +{"code": "def validate_layout_display(self, table, display_condition):\n display = False\n if (display_condition is None):\n display = True\n else:\n display_query = 'select count(*) from {} where {}'.format(table, display_condition)\n try:\n cur = self.db_conn.cursor()\n cur.execute(display_query.replace('\"', ''))\n rows = cur.fetchall()\n if (rows[0][0] > 0):\n display = True\n except sqlite3.Error as e:\n print('\"{}\" query returned an error: ({}).'.format(display_query, e))\n sys.exit(1)\n return display", "docstring": "Check to see if the display condition passes.\n\nArgs:\n table (str): The name of the DB table which hold the App data.\n display_condition (str): The \"where\" clause of the DB SQL statement.\n\nReturns:\n bool: True if the row count is greater than 0.", "source": "codesearchnet_filtered"} +{"code": "def compile_initial_state(self, batch_size: Optional[int]=None) -> Sequence[tf.Tensor]:\n with self.graph.as_default():\n with tf.name_scope('initial_state'):\n self._initialize_initial_state_fluents()\n if (batch_size is None):\n return self.initial_state_fluents\n return self._compile_batch_fluents(self.initial_state_fluents, batch_size)", "docstring": "Returns a tuple of tensors representing the initial state fluents.\n\nArgs:\n batch_size (Optional[int]): The batch size.\n\nReturns:\n Sequence[tf.Tensor]: A tuple of tensors.", "source": "codesearchnet_filtered"} +{"code": "def encrypt(self, message, public_key):\n max_str_len = (rsa.common.byte_size(public_key.n) - 11)\n if (len(message) > max_str_len):\n message = textwrap.wrap(message, width=max_str_len)\n else:\n message = [message]\n enc_msg = []\n for line in message:\n enc_line = rsa.encrypt(line, public_key)\n enc_line_converted = binascii.b2a_base64(enc_line)\n enc_msg.append(enc_line_converted)\n enc_msg = json.dumps(enc_msg)\n return enc_msg", "docstring": "Encrypts a string using a given rsa.PublicKey object. If the message\n is larger than the key, it will split it up into a list and encrypt\n each line in the list.\n\nArgs:\n message (string): The string to encrypt.\n public_key (rsa.PublicKey): The key object used to encrypt the\n message. Only the paired private key can decrypt it.\n\nReturns:\n A json string of the list of encrypted lines of the message.", "source": "codesearchnet_filtered"} +{"code": "def create(self, secret_type, value=None):\n if (secret_type is ObjectType.CERTIFICATE):\n return self._create_certificate(value)\n elif (secret_type is ObjectType.SYMMETRIC_KEY):\n return self._create_symmetric_key(value)\n elif (secret_type is ObjectType.PUBLIC_KEY):\n return self._create_public_key(value)\n elif (secret_type is ObjectType.PRIVATE_KEY):\n return self._create_private_key(value)\n elif (secret_type is ObjectType.SPLIT_KEY):\n return self._create_split_key(value)\n elif (secret_type is ObjectType.TEMPLATE):\n return self._create_template(value)\n elif (secret_type is ObjectType.SECRET_DATA):\n return self._create_secret_data(value)\n elif (secret_type is ObjectType.OPAQUE_DATA):\n return self._create_opaque_data(value)\n else:\n raise TypeError('Unrecognized secret type: {0}'.format(secret_type))", "docstring": "Create a secret object of the specified type with the given value.\n\nArgs:\n secret_type (ObjectType): An ObjectType enumeration specifying the\n type of secret to create.\n value (dict): A dictionary containing secret data. Optional,\n defaults to None.\n\nReturns:\n secret: The newly constructed secret object.\n\nRaises:\n TypeError: If the provided secret type is unrecognized.\n\nExample:\n >>> factory.create(ObjectType.SYMMETRIC_KEY)\n SymmetricKey(...)", "source": "codesearchnet_filtered"} +{"code": "def _clamp_value(value, minimum, maximum):\n if (maximum < minimum):\n raise ValueError\n if (value < minimum):\n return minimum\n elif (value > maximum):\n return maximum\n else:\n return value", "docstring": "Clamp a value to fit between a minimum and a maximum.\n\n * If ``value`` is between ``minimum`` and ``maximum``, return ``value``\n * If ``value`` is below ``minimum``, return ``minimum``\n * If ``value is above ``maximum``, return ``maximum``\n\nArgs:\n value (float or int): The number to clamp\n minimum (float or int): The lowest allowed return value\n maximum (float or int): The highest allowed return value\n\nReturns:\n float or int: the clamped value\n\nRaises:\n ValueError: if maximum < minimum\n\nExample:\n >>> _clamp_value(3, 5, 10)\n 5\n >>> _clamp_value(11, 5, 10)\n 10\n >>> _clamp_value(8, 5, 10)\n 8", "source": "codesearchnet_filtered"} +{"code": "def _code_search(query, github_user=None):\n github_client = temple.utils.GithubClient()\n headers = {'Accept': 'application/vnd.github.v3.text-match+json'}\n resp = github_client.get('/search/code', params={'q': query, 'per_page': 100}, headers=headers)\n if ((resp.status_code == requests.codes.unprocessable_entity) and github_user):\n raise temple.exceptions.InvalidGithubUserError('Invalid Github user or org - \"{}\"'.format(github_user))\n resp.raise_for_status()\n resp_data = resp.json()\n repositories = collections.defaultdict(dict)\n while True:\n repositories.update({'git@github.com:{}.git'.format(repo['repository']['full_name']): repo['repository'] for repo in resp_data['items']})\n next_url = _parse_link_header(resp.headers).get('next')\n if next_url:\n resp = requests.get(next_url, headers=headers)\n resp.raise_for_status()\n resp_data = resp.json()\n else:\n break\n return repositories", "docstring": "Performs a Github API code search\n\nArgs:\n query (str): The query sent to Github's code search\n github_user (str, optional): The Github user being searched in the query string\n\nReturns:\n dict: A dictionary of repository information keyed on the git SSH url\n\nRaises:\n `InvalidGithubUserError`: When ``github_user`` is invalid", "source": "codesearchnet_filtered"} +{"code": "def from_celery(cls, name, worker_dict, queues):\n return WorkerStats(name=name, broker=BrokerStats.from_celery(worker_dict['broker']), pid=worker_dict['pid'], process_pids=worker_dict['pool']['processes'], concurrency=worker_dict['pool']['max-concurrency'], job_count=worker_dict['pool']['writes']['total'], queues=queues)", "docstring": "Create a WorkerStats object from the dictionary returned by celery.\n\nArgs:\n name (str): The name of the worker.\n worker_dict (dict): The dictionary as returned by celery.\n queues (list): A list of QueueStats objects that represent the queues this\n worker is listening on.\n\nReturns:\n WorkerStats: A fully initialized WorkerStats object.", "source": "codesearchnet_filtered"} +{"code": "def write_uint16(self, value, little_endian=True):\n if little_endian:\n endian = '<'\n else:\n endian = '>'\n return self.pack(('%sH' % endian), value)", "docstring": "Pack the value as an unsigned integer and write 2 bytes to the stream.\n\nArgs:\n value:\n little_endian (bool): specify the endianness. (Default) Little endian.\n\nReturns:\n int: the number of bytes written.", "source": "codesearchnet_filtered"} +{"code": "def doc2id(self, doc):\n doc = map(self.process_token, doc)\n return [self.token_to_id(token) for token in doc]", "docstring": "Get the list of token_id given doc.\n\nArgs:\n doc (list): document.\n\nReturns:\n list: int id of doc.", "source": "codesearchnet_filtered"} +{"code": "def resize(x, mode, factor=4):\n assert (mode in ['bilinear', 'nearest']), mode\n shp = (tf.shape(x)[2:] * factor)\n x = tf.transpose(x, [0, 2, 3, 1])\n if (mode == 'bilinear'):\n x = tf.image.resize_bilinear(x, shp, align_corners=True)\n else:\n x = tf.image.resize_nearest_neighbor(x, shp, align_corners=False)\n return tf.transpose(x, [0, 3, 1, 2])", "docstring": "Resize input tensor with unkown input-shape by a factor\n\nArgs:\n x (tf.Tensor): tensor NCHW\n factor (int, optional): resize factor for H, W\n\nNote:\n Differences here against Caffe have huge impacts on the\n quality of the predictions.\n\nReturns:\n tf.Tensor: resized tensor NCHW", "source": "codesearchnet_filtered"} +{"code": "def parse_isoformat(timestamp):\n if (len(timestamp) == 20):\n zone = TzOffset('+00:00')\n timestamp = timestamp[:(- 1)]\n elif (len(timestamp) == 24):\n zone = TzOffset(('%s:%s' % (timestamp[(- 5):(- 2)], timestamp[(- 2):])))\n timestamp = timestamp[:(- 5)]\n elif (len(timestamp) == 25):\n zone = TzOffset(timestamp[(- 6):])\n timestamp = timestamp[:(- 6)]\n timestamp = Timestamp.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')\n timestamp = timestamp.replace(tzinfo=zone)\n return timestamp", "docstring": "Parse an ISO 8601 formatted time stamp.\n\nArgs:\n timestamp (str): Timestamp to parse\n\nReturns:\n Timestamp: Parsed timestamp", "source": "codesearchnet_filtered"} +{"code": "def resolve_widget(self, field):\n if hasattr(field, 'field'):\n widget = field.field.widget\n else:\n widget = field.widget\n return widget", "docstring": "Given a Field or BoundField, return widget instance.\n\n Todo:\n Raise an exception if given field object does not have a\n widget.\n\nArgs:\n field (Field or BoundField): A field instance.\n\nReturns:\n django.forms.widgets.Widget: Retrieved widget from given field.", "source": "codesearchnet_filtered"} +{"code": "def add_to_queue(self, queueable_item, position=0, as_next=False):\n metadata = to_didl_string(queueable_item)\n response = self.avTransport.AddURIToQueue([('InstanceID', 0), ('EnqueuedURI', queueable_item.resources[0].uri), ('EnqueuedURIMetaData', metadata), ('DesiredFirstTrackNumberEnqueued', position), ('EnqueueAsNext', int(as_next))])\n qnumber = response['FirstTrackNumberEnqueued']\n return int(qnumber)", "docstring": "Add a queueable item to the queue.\n\nArgs:\n queueable_item (DidlObject or MusicServiceItem): The item to be\n added to the queue\n position (int): The index (1-based) at which the URI should be\n added. Default is 0 (add URI at the end of the queue).\n as_next (bool): Whether this URI should be played as the next\n track in shuffle mode. This only works if `play_mode=SHUFFLE`.\n\nReturns:\n int: The index of the new item in the queue.", "source": "codesearchnet_filtered"} +{"code": "def readMonthTariffs(self, months_type):\n self.setContext('readMonthTariffs')\n try:\n req_type = binascii.hexlify(str(months_type).zfill(1))\n req_str = (('01523102303031' + req_type) + '282903')\n work_table = self.m_mons\n if (months_type == ReadMonths.kWhReverse):\n work_table = self.m_rev_mons\n self.request(False)\n req_crc = self.calc_crc16(req_str[2:].decode('hex'))\n req_str += req_crc\n self.m_serial_port.write(req_str.decode('hex'))\n raw_ret = self.m_serial_port.getResponse(self.getContext())\n self.serialPostEnd()\n unpacked_read = self.unpackStruct(raw_ret, work_table)\n self.convertData(unpacked_read, work_table, self.m_kwh_precision)\n return_crc = self.calc_crc16(raw_ret[1:(- 2)])\n if (str(return_crc) == str(work_table['crc16'][MeterData.StringValue])):\n ekm_log(('Months CRC success, type = ' + str(req_type)))\n self.setContext('')\n return True\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n self.setContext('')\n return False", "docstring": "Serial call to read month tariffs block into meter object buffer.\n\nArgs:\n months_type (int): A :class:`~ekmmeters.ReadMonths` value.\n\nReturns:\n bool: True on completion.", "source": "codesearchnet_filtered"} +{"code": "def codemirror_field_js_bundle(field):\n manifesto = CodemirrorAssetTagRender()\n manifesto.register_from_fields(field)\n try:\n bundle_name = manifesto.js_bundle_names()[0]\n except IndexError:\n msg = \"Given field with configuration name '{}' does not have a Javascript bundle name\"\n raise CodeMirrorFieldBundleError(msg.format(field.config_name))\n return bundle_name", "docstring": "Filter to get CodeMirror Javascript bundle name needed for a single field.\n\nExample:\n ::\n\n {% load djangocodemirror_tags %}\n {{ form.myfield|codemirror_field_js_bundle }}\n\nArgs:\n field (django.forms.fields.Field): A form field that contains a widget\n :class:`djangocodemirror.widget.CodeMirrorWidget`.\n\nRaises:\n CodeMirrorFieldBundleError: If Codemirror configuration form field\n does not have a bundle name.\n\nReturns:\n string: Bundle name to load with webassets.", "source": "codesearchnet_filtered"} +{"code": "def transform_table(self, table, table_meta, missing=None):\n if (missing is None):\n missing = self.missing\n else:\n self.missing = missing\n warnings.warn(DEPRECATION_MESSAGE.format('transform_table'), DeprecationWarning)\n content = {}\n columns = []\n table_name = table_meta['name']\n for field in table_meta['fields']:\n column_name = field['name']\n if (missing and table[column_name].isnull().any()):\n null_transformer = transformers.NullTransformer(field)\n clean_column = null_transformer.fit_transform(table[column_name])\n null_name = ('?' + column_name)\n columns.append(null_name)\n content[null_name] = clean_column[null_name].values\n column = clean_column[column_name]\n else:\n column = table[column_name].to_frame()\n transformer = self.transformers[(table_name, column_name)]\n content[column_name] = transformer.transform(column)[column_name].values\n columns.append(column_name)\n return pd.DataFrame(content, columns=columns)", "docstring": "Apply the stored transformers to `table`.\n\nArgs:\n table(pandas.DataFrame): Contents of the table to be transformed.\n\n table_meta(dict): Metadata for the given table.\n\n missing(bool): Wheter or not use NullTransformer to handle missing values.\n\nReturns:\n pandas.DataFrame: Transformed table.", "source": "codesearchnet_filtered"} +{"code": "def read_int32(self, little_endian=True):\n if little_endian:\n endian = '<'\n else:\n endian = '>'\n return self.unpack(('%si' % endian), 4)", "docstring": "Read 4 bytes as a signed integer value from the stream.\n\nArgs:\n little_endian (bool): specify the endianness. (Default) Little endian.\n\nReturns:\n int:", "source": "codesearchnet_filtered"} +{"code": "def get_models(self, uniprot_acc):\n if (uniprot_acc in self.all_models):\n return self.all_models[uniprot_acc]\n else:\n log.error('{}: no SWISS-MODELs available'.format(uniprot_acc))\n return None", "docstring": "Return all available models for a UniProt accession number.\n\nArgs:\n uniprot_acc (str): UniProt ACC/ID\n\nReturns:\n dict: All available models in SWISS-MODEL for this UniProt entry", "source": "codesearchnet_filtered"} +{"code": "def split(s, posix=True):\n if isinstance(s, six.binary_type):\n s = s.decode('utf-8')\n return shlex.split(s, posix=posix)", "docstring": "Split the string s using shell-like syntax.\n\nArgs:\n s (str): String to split\n posix (bool): Use posix split\n\nReturns:\n list of str: List of string parts", "source": "codesearchnet_filtered"} +{"code": "def get_exception_handlers(node: astroid.node_classes.NodeNG, exception=Exception) -> List[astroid.ExceptHandler]:\n context = find_try_except_wrapper_node(node)\n if isinstance(context, astroid.TryExcept):\n return [handler for handler in context.handlers if error_of_type(handler, exception)]\n return None", "docstring": "Return the collections of handlers handling the exception in arguments.\n\nArgs:\n node (astroid.NodeNG): A node that is potentially wrapped in a try except.\n exception (builtin.Exception or str): exception or name of the exception.\n\nReturns:\n list: the collection of handlers that are handling the exception or None.", "source": "codesearchnet_filtered"} +{"code": "def isemptyfile(filepath):\n exists = os.path.exists(safepath(filepath))\n if exists:\n filesize = os.path.getsize(safepath(filepath))\n return (filesize == 0)\n else:\n return False", "docstring": "Determine if the file both exists and isempty\n\nArgs:\n filepath (str, path): file path\n\nReturns:\n bool", "source": "codesearchnet_filtered"} +{"code": "def cgmlst_subspecies_call(df_relatives):\n closest_distance = df_relatives['distance'].min()\n if (closest_distance > CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD):\n logging.warning('Min cgMLST distance (%s) above subspeciation distance threshold (%s)', closest_distance, CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD)\n return None\n else:\n df_relatives = df_relatives.loc[((df_relatives.distance <= CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD), :)]\n df_relatives = df_relatives.sort_values('distance', ascending=True)\n logging.debug('df_relatives by cgmlst %s', df_relatives.head())\n genome_spp = genomes_to_subspecies()\n subspecies_below_threshold = [(genome_spp[member_genome] if (member_genome in genome_spp) else None) for member_genome in df_relatives.index]\n subspecies_below_threshold = filter(None, subspecies_below_threshold)\n subspecies_counter = Counter(subspecies_below_threshold)\n logging.debug('Subspecies counter: %s', subspecies_counter)\n return (subspecies_counter.most_common(1)[0][0], closest_distance, dict(subspecies_counter))", "docstring": "Call Salmonella subspecies based on cgMLST results\n\n This method attempts to find the majority subspecies type within curated\n public genomes above a cgMLST allelic profile distance threshold.\n\nNote:\n ``CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD`` is the cgMLST distance\n threshold used to determine the subspecies by cgMLST. It is set at a\n distance of 0.9 which translates to a cgMLST allelic similarity of 10%.\n A threshold of 0.9 is generous and reasonable given the congruence\n between subspecies designations and 10% cgMLST clusters by Adjusted\n Rand (~0.850) and Adjusted Wallace metrics (~0.850 both ways).\n\nArgs:\n df_relatives (pandas.DataFrame): Table of genomes related by cgMLST to input genome\n\nReturns:\n None: if no curated public genomes found to have a cgMLST profile similarity of 10% or greater\n (string, float, dict): most common subspecies, closest related public genome distance, subspecies frequencies", "source": "codesearchnet_filtered"} +{"code": "def _translate(pattern, case_sensitive=True):\n if (not case_sensitive):\n pattern = pattern.lower()\n (i, n) = (0, len(pattern))\n res = ''\n while (i < n):\n c = pattern[i]\n i = (i + 1)\n if (c == '*'):\n res = (res + '[^/]*')\n elif (c == '?'):\n res = (res + '.')\n elif (c == '['):\n j = i\n if ((j < n) and (pattern[j] == '!')):\n j = (j + 1)\n if ((j < n) and (pattern[j] == ']')):\n j = (j + 1)\n while ((j < n) and (pattern[j] != ']')):\n j = (j + 1)\n if (j >= n):\n res = (res + '\\\\[')\n else:\n stuff = pattern[i:j].replace('\\\\', '\\\\\\\\')\n i = (j + 1)\n if (stuff[0] == '!'):\n stuff = ('^' + stuff[1:])\n elif (stuff[0] == '^'):\n stuff = ('\\\\' + stuff)\n res = ('%s[%s]' % (res, stuff))\n else:\n res = (res + re.escape(c))\n return res", "docstring": "Translate a wildcard pattern to a regular expression.\n\n There is no way to quote meta-characters.\n\nArgs:\n pattern (str): A wildcard pattern.\n case_sensitive (bool): Set to `False` to use a case\n insensitive regex (default `True`).\n\nReturns:\n str: A regex equivalent to the given pattern.", "source": "codesearchnet_filtered"} +{"code": "def run(self, args):\n jlink = self.create_jlink(args)\n if args.downgrade:\n if (not jlink.firmware_newer()):\n print('DLL firmware is not older than J-Link firmware.')\n else:\n jlink.invalidate_firmware()\n try:\n jlink.update_firmware()\n except pylink.JLinkException as e:\n jlink = self.create_jlink(args)\n print(('Firmware Downgraded: %s' % jlink.firmware_version))\n elif args.upgrade:\n if (not jlink.firmware_outdated()):\n print('DLL firmware is not newer than J-Link firmware.')\n else:\n try:\n jlink.update_firmware()\n except pylink.JLinkException as e:\n jlink = self.create_jlink(args)\n print(('Firmware Updated: %s' % jlink.firmware_version))\n return None", "docstring": "Runs the firmware command.\n\nArgs:\n self (FirmwareCommand): the ``FirmwareCommand`` instance\n args (Namespace): arguments to parse\n\nReturns:\n ``None``", "source": "codesearchnet_filtered"} +{"code": "def _ip_unnumbered_name(self, **kwargs):\n method_name = ('interface_%s_ip_ip_config_unnumbered_ip_donor_interface_name' % kwargs['int_type'])\n ip_unnumbered_name = getattr(self._interface, method_name)\n config = ip_unnumbered_name(**kwargs)\n if kwargs['delete']:\n tag = 'ip-donor-interface-name'\n config.find(('.//*%s' % tag)).set('operation', 'delete')\n return config", "docstring": "Return the `ip unnumbered` donor name XML.\n\n You should not use this method.\n You probably want `Interface.ip_unnumbered`.\n\nArgs:\n int_type (str): Type of interface. (gigabitethernet,\n tengigabitethernet etc).\n delete (bool): Remove the configuration if ``True``.\n ip_donor_interface_name (str): The donor interface name (1, 2, etc)\n\nReturns:\n XML to be passed to the switch.\n\nRaises:\n None", "source": "codesearchnet_filtered"} +{"code": "def to_dd(degrees, minutes, seconds=0):\n sign = ((- 1) if any(((i < 0) for i in (degrees, minutes, seconds))) else 1)\n return (sign * ((abs(degrees) + (abs(minutes) / 60)) + (abs(seconds) / 3600)))", "docstring": "Convert degrees, minutes and optionally seconds to decimal angle.\n\nArgs:\n degrees (float): Number of degrees\n minutes (float): Number of minutes\n seconds (float): Number of seconds\n\nReturns:\n float: Angle converted to decimal degrees", "source": "codesearchnet_filtered"} +{"code": "def start_new(cls, tuner, inputs):\n config = _Job._load_config(inputs, tuner.estimator)\n warm_start_config_req = None\n if tuner.warm_start_config:\n warm_start_config_req = tuner.warm_start_config.to_input_req()\n tuner_args = config.copy()\n tuner_args['job_name'] = tuner._current_job_name\n tuner_args['strategy'] = tuner.strategy\n tuner_args['objective_type'] = tuner.objective_type\n tuner_args['objective_metric_name'] = tuner.objective_metric_name\n tuner_args['max_jobs'] = tuner.max_jobs\n tuner_args['max_parallel_jobs'] = tuner.max_parallel_jobs\n tuner_args['parameter_ranges'] = tuner.hyperparameter_ranges()\n tuner_args['static_hyperparameters'] = tuner.static_hyperparameters\n tuner_args['input_mode'] = tuner.estimator.input_mode\n tuner_args['metric_definitions'] = tuner.metric_definitions\n tuner_args['tags'] = tuner.tags\n tuner_args['warm_start_config'] = warm_start_config_req\n tuner_args['early_stopping_type'] = tuner.early_stopping_type\n if isinstance(tuner.estimator, sagemaker.algorithm.AlgorithmEstimator):\n tuner_args['algorithm_arn'] = tuner.estimator.algorithm_arn\n else:\n tuner_args['image'] = tuner.estimator.train_image()\n tuner_args['enable_network_isolation'] = tuner.estimator.enable_network_isolation()\n tuner_args['encrypt_inter_container_traffic'] = tuner.estimator.encrypt_inter_container_traffic\n tuner.estimator.sagemaker_session.tune(**tuner_args)\n return cls(tuner.sagemaker_session, tuner._current_job_name)", "docstring": "Create a new Amazon SageMaker hyperparameter tuning job from the HyperparameterTuner.\n\nArgs:\n tuner (sagemaker.tuner.HyperparameterTuner): HyperparameterTuner object created by the user.\n inputs (str): Parameters used when called :meth:`~sagemaker.estimator.EstimatorBase.fit`.\n\nReturns:\n sagemaker.tuner._TuningJob: Constructed object that captures all information about the started job.", "source": "codesearchnet_filtered"} +{"code": "def swo_stop(self):\n res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.STOP, 0)\n if (res < 0):\n raise errors.JLinkException(res)\n return None", "docstring": "Stops collecting SWO data.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n ``None``\n\nRaises:\n JLinkException: on error", "source": "codesearchnet_filtered"} +{"code": "def delete(self, query_id=None, **kwargs):\n path = '/logging-service/v1/queries/{}'.format(query_id)\n r = self._httpclient.request(method='DELETE', url=self.url, path=path, **kwargs)\n return r", "docstring": "Delete a query job.\n\n Uses the DELETE HTTP method to delete a query job. After calling\n this endpoint, it is an error to poll for query results using\n the queryId specified here.\n\nArgs:\n query_id (str): Specifies the ID of the query job.\n **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters.\n\nReturns:\n requests.Response: Requests Response() object.\n\nExample:\n Refer to ``logging_query.py`` example.", "source": "codesearchnet_filtered"} +{"code": "def load_table_from_config(input_dir, config):\n path = pathlib.Path(input_dir).joinpath(config['path'])\n kwargs = config['pd_read_kwargs']\n return pd.read_csv(path, **kwargs)", "docstring": "Load table from table config dict\n\nArgs:\n input_dir (path-like): directory containing input files\n config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.\n\nReturns:\n pd.DataFrame", "source": "codesearchnet_filtered"} +{"code": "def get_archive(self, container, path, chunk_size=DEFAULT_DATA_CHUNK_SIZE):\n params = {'path': path}\n url = self._url('/containers/{0}/archive', container)\n res = self._get(url, params=params, stream=True)\n self._raise_for_status(res)\n encoded_stat = res.headers.get('x-docker-container-path-stat')\n return (self._stream_raw_result(res, chunk_size, False), (utils.decode_json_header(encoded_stat) if encoded_stat else None))", "docstring": "Retrieve a file or folder from a container in the form of a tar\n archive.\n\nArgs:\n container (str): The container where the file is located\n path (str): Path to the file or folder to retrieve\n chunk_size (int): The number of bytes returned by each iteration\n of the generator. If ``None``, data will be streamed as it is\n received. Default: 2 MB\n\nReturns:\n (tuple): First element is a raw tar data stream. Second element is\n a dict containing ``stat`` information on the specified ``path``.\n\nRaises:\n :py:class:`docker.errors.APIError`\n If the server returns an error.\n\nExample:\n >>> c = docker.APIClient()\n >>> f = open('./sh_bin.tar', 'wb')\n >>> bits, stat = c.get_archive(container, '/bin/sh')\n >>> print(stat)\n {'name': 'sh', 'size': 1075464, 'mode': 493,\n 'mtime': '2018-10-01T15:37:48-07:00', 'linkTarget': ''}\n >>> for chunk in bits:\n ... f.write(chunk)\n >>> f.close()", "source": "codesearchnet_filtered"} +{"code": "def get_user_groups(self, dn, group_search_dn=None, _connection=None):\n connection = _connection\n if (not connection):\n connection = self._make_connection(bind_user=self.config.get('LDAP_BIND_USER_DN'), bind_password=self.config.get('LDAP_BIND_USER_PASSWORD'))\n connection.bind()\n safe_dn = ldap3.utils.conv.escape_filter_chars(dn)\n search_filter = '(&{group_filter}({members_attr}={user_dn}))'.format(group_filter=self.config.get('LDAP_GROUP_OBJECT_FILTER'), members_attr=self.config.get('LDAP_GROUP_MEMBERS_ATTR'), user_dn=safe_dn)\n log.debug(\"Searching for groups for specific user with filter '{0}' , base '{1}' and scope '{2}'\".format(search_filter, (group_search_dn or self.full_group_search_dn), self.config.get('LDAP_GROUP_SEARCH_SCOPE')))\n connection.search(search_base=(group_search_dn or self.full_group_search_dn), search_filter=search_filter, attributes=self.config.get('LDAP_GET_GROUP_ATTRIBUTES'), search_scope=getattr(ldap3, self.config.get('LDAP_GROUP_SEARCH_SCOPE')))\n results = []\n for item in connection.response:\n if (('type' not in item) or (item.get('type') != 'searchResEntry')):\n continue\n group_data = item['attributes']\n group_data['dn'] = item['dn']\n results.append(group_data)\n if (not _connection):\n self.destroy_connection(connection)\n return results", "docstring": "Gets a list of groups a user at dn is a member of\n\nArgs:\n dn (str): The dn of the user to find memberships for.\n _connection (ldap3.Connection): A connection object to use when\n searching. If not given, a temporary connection will be\n created, and destroyed after use.\n group_search_dn (str): The search dn for groups. Defaults to\n ``'{LDAP_GROUP_DN},{LDAP_BASE_DN}'``.\n\nReturns:\n list: A list of LDAP groups the user is a member of.", "source": "codesearchnet_filtered"} +{"code": "def connect_direct(self, device, calibration=True):\n if (not isinstance(device, ScanResult)):\n if isinstance(device, str):\n device = ScanResult(device, fmt_addr_raw(device))\n elif isinstance(device, unicode):\n device = device.encode('ascii')\n device = ScanResult(device, fmt_addr_raw(device))\n else:\n logger.warn('Expected ScanResult, found type {} instead!'.format(type(device)))\n return (False, None)\n logger.debug('Connecting directly to device address'.format(device.addr))\n self._set_state(self._STATE_CONNECTING)\n self.api.ble_cmd_gap_connect_direct(device.raw_addr, 0, 6, 14, 100, 50)\n self._wait_for_state(self._STATE_CONNECTING, 5)\n if (self.state != self._STATE_CONNECTED):\n logger.warn('Connection failed!')\n self._set_state(self._STATE_GAP_END)\n self.api.ble_cmd_gap_end_procedure()\n self._wait_for_state(self._STATE_GAP_END)\n return (False, None)\n conn_handle = self.conn_handles[(- 1)]\n logger.info('Connection OK, handle is 0x{:02X}'.format(conn_handle))\n sk8 = SK8(self, conn_handle, device, calibration)\n self._add_device(sk8)\n sk8._discover_services()\n return (True, sk8)", "docstring": "Establish a connection to a single SK8.\n\nArgs:\n device: either a :class:`ScanResult` or a plain hardware address string\n in xx:xx:xx:xx:xx:xx format.\n calibration (bool): True to attempt to load calibration data for this\n device after connection, False otherwise. See :meth:`SK8.load_calibration`.\n\nReturns:\n tuple (`result`, `device`), where `result` is a bool indicating if a\n connection was created successfully. If `result` is True, `device` will\n be set to a new :class:`SK8` instance. Otherwise it will be None.", "source": "codesearchnet_filtered"} +{"code": "def get_textdiff(text1, text2, num_context_lines=0, ignore_whitespace=False):\n import difflib\n text1 = ensure_unicode(text1)\n text2 = ensure_unicode(text2)\n text1_lines = text1.splitlines()\n text2_lines = text2.splitlines()\n if ignore_whitespace:\n text1_lines = [t.rstrip() for t in text1_lines]\n text2_lines = [t.rstrip() for t in text2_lines]\n ndiff_kw = dict(linejunk=difflib.IS_LINE_JUNK, charjunk=difflib.IS_CHARACTER_JUNK)\n else:\n ndiff_kw = {}\n all_diff_lines = list(difflib.ndiff(text1_lines, text2_lines, **ndiff_kw))\n if (num_context_lines is None):\n diff_lines = all_diff_lines\n else:\n from utool import util_list\n ismarked_list = [((len(line) > 0) and (line[0] in '+-?')) for line in all_diff_lines]\n isvalid_list = ismarked_list[:]\n for i in range(1, (num_context_lines + 1)):\n isvalid_list[:(- i)] = util_list.or_lists(isvalid_list[:(- i)], ismarked_list[i:])\n isvalid_list[i:] = util_list.or_lists(isvalid_list[i:], ismarked_list[:(- i)])\n USE_BREAK_LINE = True\n if USE_BREAK_LINE:\n diff_lines = []\n prev = False\n visual_break = '\\n <... FILTERED CONTEXT ...> \\n'\n for (line, valid) in zip(all_diff_lines, isvalid_list):\n if valid:\n diff_lines.append(line)\n elif prev:\n if False:\n diff_lines.append(visual_break)\n prev = valid\n else:\n diff_lines = util_list.compress(all_diff_lines, isvalid_list)\n return '\\n'.join(diff_lines)", "docstring": "r\"\"\"\n Uses difflib to return a difference string between two similar texts\n\nArgs:\n text1 (str):\n text2 (str):\n\nReturns:\n str: formatted difference text message\n\n SeeAlso:\n ut.color_diff_text\n\n References:\n http://www.java2s.com/Code/Python/Utility/IntelligentdiffbetweentextfilesTimPeters.htm\n\n CommandLine:\n python -m utool.util_str --test-get_textdiff:1\n python -m utool.util_str --test-get_textdiff:0\n\nExample:\n >>> # DISABLE_DOCTEST\n >>> from utool.util_str import * # NOQA\n >>> # build test data\n >>> text1 = 'one\\ntwo\\nthree'\n >>> text2 = 'one\\ntwo\\nfive'\n >>> # execute function\n >>> result = get_textdiff(text1, text2)\n >>> # verify results\n >>> print(result)\n - three\n + five\n\n Example2:\n >>> # DISABLE_DOCTEST\n >>> from utool.util_str import * # NOQA\n >>> # build test data\n >>> text1 = 'one\\ntwo\\nthree\\n3.1\\n3.14\\n3.1415\\npi\\n3.4\\n3.5\\n4'\n >>> text2 = 'one\\ntwo\\nfive\\n3.1\\n3.14\\n3.1415\\npi\\n3.4\\n4'\n >>> # execute function\n >>> num_context_lines = 1\n >>> result = get_textdiff(text1, text2, num_context_lines)\n >>> # verify results\n >>> print(result)", "source": "codesearchnet_filtered"} +{"code": "def _addupdate_hdxobject(self, hdxobjects, id_field, new_hdxobject):\n for hdxobject in hdxobjects:\n if (hdxobject[id_field] == new_hdxobject[id_field]):\n merge_two_dictionaries(hdxobject, new_hdxobject)\n return hdxobject\n hdxobjects.append(new_hdxobject)\n return new_hdxobject", "docstring": "Helper function to add a new HDX object to a supplied list of HDX objects or update existing metadata if the object\n already exists in the list\n\nArgs:\n hdxobjects (List[T <= HDXObject]): list of HDX objects to which to add new objects or update existing ones\n id_field (str): Field on which to match to determine if object already exists in list\n new_hdxobject (T <= HDXObject): The HDX object to be added/updated\n\nReturns:\n T <= HDXObject: The HDX object which was added or updated", "source": "codesearchnet_filtered"} +{"code": "def create_repository(cls, repository_data):\n location = ('memory{%s}' % hex(id(repository_data)))\n resource_pool = ResourcePool(cache_size=None)\n repo = MemoryPackageRepository(location, resource_pool)\n repo.data = repository_data\n return repo", "docstring": "Create a standalone, in-memory repository.\n\n Using this function bypasses the `package_repository_manager` singleton.\n This is usually desired however, since in-memory repositories are for\n temporarily storing programmatically created packages, which we do not\n want to cache and that do not persist.\n\nArgs:\n repository_data (dict): Repository data, see class docstring.\n\nReturns:\n `MemoryPackageRepository` object.", "source": "codesearchnet_filtered"} +{"code": "def decode(cls, command_str):\n (name, _, arg) = command_str.partition(' ')\n args = []\n if (len(arg) > 0):\n if ((arg[0] != '{') or (arg[(- 1)] != '}')):\n raise DataError('Invalid command, argument is not contained in { and }', arg=arg, cmd=name)\n arg = arg[1:(- 1)]\n args = arg.split(',')\n proc = []\n for arg in args:\n if arg.startswith('hex:'):\n arg = unhexlify(arg[4:]).decode('utf-8')\n proc.append(arg)\n return Command(name, proc)", "docstring": "Decode a string encoded command back into a Command object.\n\nArgs:\n command_str (str): The encoded command string output from a\n previous call to encode.\n\nReturns:\n Command: The decoded Command object.", "source": "codesearchnet_filtered"} +{"code": "def predict_dataset(self, df):\n if (len(list(df.columns)) == 2):\n df.columns = ['A', 'B']\n if (self.model is None):\n raise AssertionError('Model has not been trained before predictions')\n df2 = DataFrame()\n for (idx, row) in df.iterrows():\n df2 = df2.append(row, ignore_index=True)\n df2 = df2.append({'A': row['B'], 'B': row['A']}, ignore_index=True)\n return predict.predict(deepcopy(df2), deepcopy(self.model))[::2]", "docstring": "Runs Jarfo independently on all pairs.\n\nArgs:\n x (pandas.DataFrame): a CEPC format Dataframe.\n kwargs (dict): additional arguments for the algorithms\n\nReturns:\n pandas.DataFrame: a Dataframe with the predictions.", "source": "codesearchnet_filtered"} +{"code": "def lu_slogdet(LU):\n LU = (asarray(LU[0], float), asarray(LU[1], float))\n adet = _sum(log(_abs(LU[0].diagonal())))\n s = prod(sign(LU[0].diagonal()))\n nrows_exchange = (LU[1].size - _sum((LU[1] == arange(LU[1].size, dtype='int32'))))\n odd = ((nrows_exchange % 2) == 1)\n if odd:\n s *= (- 1.0)\n return (s, adet)", "docstring": "r\"\"\"Natural logarithm of a LU decomposition.\n\nArgs:\n LU (tuple): LU decomposition.\n\nReturns:\n tuple: sign and log-determinant.", "source": "codesearchnet_filtered"} +{"code": "def get_pipeline_id(app='', name=''):\n return_id = None\n pipelines = get_all_pipelines(app=app)\n for pipeline in pipelines:\n LOG.debug('ID of %(name)s: %(id)s', pipeline)\n if (pipeline['name'] == name):\n return_id = pipeline['id']\n LOG.info('Pipeline %s found, ID: %s', name, return_id)\n break\n return return_id", "docstring": "Get the ID for Pipeline _name_.\n\nArgs:\n app (str): Name of Spinnaker Application to search.\n name (str): Name of Pipeline to get ID for.\n\nReturns:\n str: ID of specified Pipeline.\n None: Pipeline or Spinnaker Appliation not found.", "source": "codesearchnet_filtered"} +{"code": "def agent_heartbeat(self, agent_id, metrics, run_states):\n mutation = gql('\\n mutation Heartbeat(\\n $id: ID!,\\n $metrics: JSONString,\\n $runState: JSONString\\n ) {\\n agentHeartbeat(input: {\\n id: $id,\\n metrics: $metrics,\\n runState: $runState\\n }) {\\n agent {\\n id\\n }\\n commands\\n }\\n }\\n ')\n try:\n response = self.gql(mutation, variable_values={'id': agent_id, 'metrics': json.dumps(metrics), 'runState': json.dumps(run_states)})\n except Exception as e:\n message = ast.literal_eval(e.args[0])['message']\n logger.error('Error communicating with W&B: %s', message)\n return []\n else:\n return json.loads(response['agentHeartbeat']['commands'])", "docstring": "Notify server about agent state, receive commands.\n\nArgs:\n agent_id (str): agent_id\n metrics (dict): system metrics\n run_states (dict): run_id: state mapping\n\nReturns:\n List of commands to execute.", "source": "codesearchnet_filtered"} +{"code": "def get_value(self, field, quick):\n if callable(field.default):\n default = field.default(self)\n else:\n default = field.default\n if (quick and (default is not None)):\n return default\n shell.cprint('<90>{}', field.help)\n while True:\n try:\n answer = click.prompt(field.pretty_prompt, default=default)\n return field.type(answer)\n except ValueError:\n shell.cprint('<31>Unsupported value')", "docstring": "Ask user the question represented by this instance.\n\nArgs:\n field (Field):\n The field we're asking the user to provide the value for.\n quick (bool):\n Enable quick mode. In quick mode, the form will reduce the\n number of question asked by using defaults wherever possible.\n This can greatly reduce the number of interactions required on\n the user part, but will obviously limit the user choices. This\n should probably be enabled only by a specific user action\n (like passing a ``--quick`` flag etc.).\n\nReturns:\n The user response converted to a python type using the\n :py:attr:`cliform.core.Field.type` converter.", "source": "codesearchnet_filtered"} +{"code": "def is60(msg):\n if allzeros(msg):\n return False\n d = hex2bin(data(msg))\n if wrongstatus(d, 1, 2, 12):\n return False\n if wrongstatus(d, 13, 14, 23):\n return False\n if wrongstatus(d, 24, 25, 34):\n return False\n if wrongstatus(d, 35, 36, 45):\n return False\n if wrongstatus(d, 46, 47, 56):\n return False\n ias = ias60(msg)\n if ((ias is not None) and (ias > 500)):\n return False\n mach = mach60(msg)\n if ((mach is not None) and (mach > 1)):\n return False\n vr_baro = vr60baro(msg)\n if ((vr_baro is not None) and (abs(vr_baro) > 6000)):\n return False\n vr_ins = vr60ins(msg)\n if ((vr_ins is not None) and (abs(vr_ins) > 6000)):\n return False\n return True", "docstring": "Check if a message is likely to be BDS code 6,0\n\nArgs:\n msg (String): 28 bytes hexadecimal message string\n\nReturns:\n bool: True or False", "source": "codesearchnet_filtered"} +{"code": "def add_authorization_policy(access_token, ck_id, oid):\n path = '/ContentKeys'\n body = (('{\"AuthorizationPolicyId\":\"' + oid) + '\"}')\n return helper_add(access_token, ck_id, path, body)", "docstring": "Add Media Service Authorization Policy.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n ck_id (str): A Media Service Asset Content Key ID.\n options_id (str): A Media Service OID.\n\nReturns:\n HTTP response. JSON body.", "source": "codesearchnet_filtered"} +{"code": "def pack_and_batch(dataset, batch_size, length, pack=True):\n if pack:\n dataset = pack_dataset(dataset, length=length)\n dataset = dataset.map(functools.partial(trim_and_pad_all_features, length=length), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n dataset = dataset.batch(batch_size, drop_remainder=False)\n dataset = dataset.map(functools.partial(trim_and_pad_all_features, length=batch_size), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n dataset = dataset.map((lambda x: {k: tf.reshape(v, (batch_size, length)) for (k, v) in x.items()}), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n dataset = dataset.prefetch(100)\n return dataset", "docstring": "Create a tf.data.Dataset which emits training batches.\n\n The input dataset emits feature-dictionaries where each feature is a vector\n of integers ending in EOS=1\n\n The tensors in the returned tf.data.Dataset have shape\n [batch_size, length]. Zeros indicate padding.\n\n length indicates the length of the emitted examples. Examples with\n inputs/targets longer than length get truncated.\n\n TODO(noam): for text2self problems, we should just chop too-long\n sequences into multiple parts and train on all of them.\n\n If pack=False, then each emitted example will contain one\n example emitted by load_internal().\n\n If pack=True, then multiple examples emitted by load_internal() are\n concatenated to form one combined example with the given length.\n See comments in the function pack_dataset().\n\n batch_size indicates the number of (combined) examples per batch,\n across all cores.\n\nArgs:\n dataset: a tf.data.Dataset\n batch_size: an integer\n length: an integer\n pack: a boolean\n\nReturns:\n a tf.data.Dataset where all features have fixed shape [batch, length].", "source": "codesearchnet_filtered"} +{"code": "def check_for_empty_defaults(status):\n dirs_to_check = ('./vars', './handlers', './defaults', './tasks')\n for (dirpath, dirname, filename) in os.walk('.'):\n if ((dirpath == './files') or (dirpath == './templates')):\n if (not any([dirname, filename])):\n status.append('There are no files in the {0} directory. please remove directory'.format(dirpath))\n if (dirpath in dirs_to_check):\n try:\n joined_filename = os.path.join(dirpath, 'main.yml')\n with open(joined_filename, 'r') as f:\n if re.match('^---\\\\n# \\\\S+ file for \\\\S+\\\\n$', f.read()):\n status.append('Empty file, please remove file and directory: {0}'.format(joined_filename))\n except IOError:\n pass\n return status", "docstring": "Method to check for empty roles structure.\n\n When a role is created using ansible-galaxy it creates a default\n scaffolding structure. Best practice dictates that if any of these are not\n used then they should be removed. For example a bare main.yml with the\n following string is created for a 'defaults' for a role called 'myrole':\n\n ---\n defaults file for myrole\n\n This should be removed.\n\nArgs:\n status (list): list of pre-receive check failures to eventually print\n to the user\n\nReturns:\n status list of current pre-redeive check failures. Might be an empty\n list.", "source": "codesearchnet_filtered"} +{"code": "def build_twisted_request(self, method, url, extra_headers={}, body_producer=None, full_url=False):\n uri = (url if full_url else self._url(url))\n raw_headers = self.get_headers()\n if extra_headers:\n raw_headers.update(extra_headers)\n headers = http_headers.Headers()\n for header in raw_headers:\n headers.addRawHeader(header, raw_headers[header])\n agent = client.Agent(reactor)\n request = agent.request(method, uri, headers, body_producer)\n return (reactor, request)", "docstring": "Build a request for twisted\n\nArgs:\n method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None\n url (str): Destination URL (full, or relative)\n\n Kwargs:\n extra_headers (dict): Headers (override default connection headers, if any)\n body_producer (:class:`twisted.web.iweb.IBodyProducer`): Object producing request body\n full_url (bool): If False, URL is relative\n\nReturns:\n tuple. Tuple with two elements: reactor, and request", "source": "codesearchnet_filtered"} +{"code": "def calculate_sleep_time(attempt, delay_factor=5.0, randomization_factor=0.5, max_delay=120):\n if (attempt <= 0):\n return 0\n delay = (float((2 ** (attempt - 1))) * float(delay_factor))\n delay = (delay * ((randomization_factor * random.random()) + 1))\n return min(delay, max_delay)", "docstring": "Calculate the sleep time between retries, in seconds.\n\n Based off of `taskcluster.utils.calculateSleepTime`, but with kwargs instead\n of constant `delay_factor`/`randomization_factor`/`max_delay`. The taskcluster\n function generally slept for less than a second, which didn't always get\n past server issues.\n\nArgs:\n attempt (int): the retry attempt number\n delay_factor (float, optional): a multiplier for the delay time. Defaults to 5.\n randomization_factor (float, optional): a randomization multiplier for the\n delay time. Defaults to .5.\n max_delay (float, optional): the max delay to sleep. Defaults to 120 (seconds).\n\nReturns:\n float: the time to sleep, in seconds.", "source": "codesearchnet_filtered"} +{"code": "def parse_hausdorff(ml_log, log=None, print_output=False):\n hausdorff_distance = {'min_distance': 0.0, 'max_distance': 0.0, 'mean_distance': 0.0, 'rms_distance': 0.0, 'number_points': 0}\n with open(ml_log) as fread:\n result = fread.readlines()\n data = ''\n for (idx, line) in enumerate(result):\n m = re.match('\\\\s*Sampled (\\\\d+) pts.*', line)\n if (m is not None):\n hausdorff_distance['number_points'] = int(m.group(1))\n if ('Hausdorff Distance computed' in line):\n data = result[(idx + 2)]\n m = re.match('\\\\D+(\\\\d+\\\\.*\\\\d*)\\\\D+(\\\\d+\\\\.*\\\\d*)\\\\D+(\\\\d+\\\\.*\\\\d*)\\\\D+(\\\\d+\\\\.*\\\\d*)', data)\n hausdorff_distance['min_distance'] = float(m.group(1))\n hausdorff_distance['max_distance'] = float(m.group(2))\n hausdorff_distance['mean_distance'] = float(m.group(3))\n hausdorff_distance['rms_distance'] = float(m.group(4))\n for (key, value) in hausdorff_distance.items():\n if (log is not None):\n log_file = open(log, 'a')\n log_file.write('{:16} = {}\\n'.format(key, value))\n log_file.close()\n elif print_output:\n print('{:16} = {}'.format(key, value))\n return hausdorff_distance", "docstring": "Parse the ml_log file generated by the hausdorff_distance function.\n\nArgs:\n ml_log (str): MeshLab log file to parse\n log (str): filename to log output\n\nReturns:\n dict: dictionary with the following keys:\n number_points (int): number of points in mesh\n min_distance (float): minimum hausdorff distance\n max_distance (float): maximum hausdorff distance\n mean_distance (float): mean hausdorff distance\n rms_distance (float): root mean square distance", "source": "codesearchnet_filtered"} +{"code": "def helper_delete(access_token, oid, path):\n full_path = ''.join([path, \"('\", oid, \"')\"])\n full_path_encoded = urllib.parse.quote(full_path, safe='')\n endpoint = ''.join([ams_rest_endpoint, full_path_encoded])\n return do_ams_delete(endpoint, full_path_encoded, access_token)", "docstring": "Helper Function to delete a Object at a URL path.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n oid (str): An OID.\n path (str): A URL Path.\n\nReturns:\n HTTP response. JSON body.", "source": "codesearchnet_filtered"} +{"code": "def datastore(self, domain, data_type, mapping=None):\n from .tcex_datastore import TcExDataStore\n return TcExDataStore(self, domain, data_type, mapping)", "docstring": "Get instance of the DataStore module.\n\nArgs:\n domain (str): The domain can be either \"system\", \"organization\", or \"local\". When using\n \"organization\" the data store can be accessed by any Application in the entire org,\n while \"local\" access is restricted to the App writing the data. The \"system\" option\n should not be used in almost all cases.\n data_type (str): The data type descriptor (e.g., tc:whois:cache).\n\nReturns:\n object: An instance of the DataStore Class.", "source": "codesearchnet_filtered"} +{"code": "def flash_write(self, addr, data, nbits=None, flags=0):\n self._dll.JLINKARM_BeginDownload(flags)\n self.memory_write(addr, data, nbits=nbits)\n bytes_flashed = self._dll.JLINKARM_EndDownload()\n if (bytes_flashed < 0):\n raise errors.JLinkFlashException(bytes_flashed)\n return bytes_flashed", "docstring": "Writes data to the flash region of a device.\n\n The given number of bits, if provided, must be either ``8``, ``16``, or\n ``32``.\n\nArgs:\n self (JLink): the ``JLink`` instance\n addr (int): starting flash address to write to\n data (list): list of data units to write\n nbits (int): number of bits to use for each unit\n\nReturns:\n Number of bytes written to flash.", "source": "codesearchnet_filtered"} +{"code": "def roll50(msg):\n d = hex2bin(data(msg))\n if (d[0] == '0'):\n return None\n sign = int(d[1])\n value = bin2int(d[2:11])\n if sign:\n value = (value - 512)\n angle = ((value * 45.0) / 256.0)\n return round(angle, 1)", "docstring": "Roll angle, BDS 5,0 message\n\nArgs:\n msg (String): 28 bytes hexadecimal message (BDS50) string\n\nReturns:\n float: angle in degrees,\n negative->left wing down, positive->right wing down", "source": "codesearchnet_filtered"} +{"code": "def _inquire(self, **kwargs):\n if (rname_rfc6680 is None):\n raise NotImplementedError('Your GSSAPI implementation does not support RFC 6680 (the GSSAPI naming extensions)')\n if (not kwargs):\n default_val = True\n else:\n default_val = False\n attrs = kwargs.get('attrs', default_val)\n mech_name = kwargs.get('mech_name', default_val)\n return rname_rfc6680.inquire_name(self, mech_name=mech_name, attrs=attrs)", "docstring": "Inspect this name for information.\n\n This method inspects the name for information.\n\n If no keyword arguments are passed, all available information\n is returned. Otherwise, only the keyword arguments that\n are passed and set to `True` are returned.\n\nArgs:\n mech_name (bool): get whether this is a mechanism name,\n and, if so, the associated mechanism\n attrs (bool): get the attributes names for this name\n\nReturns:\n InquireNameResult: the results of the inquiry, with unused\n fields set to None\n\nRaises:\n GSSError", "source": "codesearchnet_filtered"} +{"code": "def _read_group_h5(filename, groupname):\n with h5py.File(filename, 'r') as h5f:\n data = h5f[groupname][()]\n return data", "docstring": "Return group content.\n\nArgs:\n filename (:class:`pathlib.Path`): path of hdf5 file.\n groupname (str): name of group to read.\n\nReturns:\n :class:`numpy.array`: content of group.", "source": "codesearchnet_filtered"} +{"code": "def FromReadings(cls, uuid, readings, events, report_id=IOTileReading.InvalidReadingID, selector=65535, streamer=256, sent_timestamp=0, received_time=None):\n lowest_id = IOTileReading.InvalidReadingID\n highest_id = IOTileReading.InvalidReadingID\n for item in itertools.chain(iter(readings), iter(events)):\n if (item.reading_id == IOTileReading.InvalidReadingID):\n continue\n if ((lowest_id == IOTileReading.InvalidReadingID) or (item.reading_id < lowest_id)):\n lowest_id = item.reading_id\n if ((highest_id == IOTileReading.InvalidReadingID) or (item.reading_id > highest_id)):\n highest_id = item.reading_id\n reading_list = [x.asdict() for x in readings]\n event_list = [x.asdict() for x in events]\n report_dict = {'format': cls.FORMAT_TAG, 'device': uuid, 'streamer_index': streamer, 'streamer_selector': selector, 'incremental_id': report_id, 'lowest_id': lowest_id, 'highest_id': highest_id, 'device_sent_timestamp': sent_timestamp, 'events': event_list, 'data': reading_list}\n encoded = msgpack.packb(report_dict, default=_encode_datetime, use_bin_type=True)\n return FlexibleDictionaryReport(encoded, signed=False, encrypted=False, received_time=received_time)", "docstring": "Create a flexible dictionary report from a list of readings and events.\n\nArgs:\n uuid (int): The uuid of the device that this report came from\n readings (list of IOTileReading): A list of IOTileReading objects containing the data in the report\n events (list of IOTileEvent): A list of the events contained in the report.\n report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.\n Note that you can specify anything you want for the report id but for actual IOTile devices\n the report id will always be greater than the id of all of the readings contained in the report\n since devices generate ids sequentially.\n selector (int): The streamer selector of this report. This can be anything but if the report came from\n a device, it would correspond with the query the device used to pick readings to go into the report.\n streamer (int): The streamer id that this reading was sent from.\n sent_timestamp (int): The device's uptime that sent this report.\n received_time(datetime): The UTC time when this report was received from an IOTile device. If it is being\n created now, received_time defaults to datetime.utcnow().\n\nReturns:\n FlexibleDictionaryReport: A report containing the readings and events passed in.", "source": "codesearchnet_filtered"} +{"code": "def _ReadEncryptedData(self, read_size):\n encrypted_data = self._file_object.read(read_size)\n read_count = len(encrypted_data)\n self._encrypted_data = b''.join([self._encrypted_data, encrypted_data])\n (self._decrypted_data, self._encrypted_data) = self._decrypter.Decrypt(self._encrypted_data)\n self._decrypted_data_size = len(self._decrypted_data)\n return read_count", "docstring": "Reads encrypted data from the file-like object.\n\nArgs:\n read_size (int): number of bytes of encrypted data to read.\n\nReturns:\n int: number of bytes of encrypted data read.", "source": "codesearchnet_filtered"} +{"code": "def OpenAndRead(relative_path='debugger-blacklist.yaml'):\n try:\n with open(os.path.join(sys.path[0], relative_path), 'r') as f:\n return Read(f)\n except IOError:\n return None", "docstring": "Attempts to find the yaml configuration file, then read it.\n\nArgs:\n relative_path: Optional relative path override.\n\nReturns:\n A Config object if the open and read were successful, None if the file\n does not exist (which is not considered an error).\n\nRaises:\n Error (some subclass): As thrown by the called Read() function.", "source": "codesearchnet_filtered"} +{"code": "def generate_nodes(tpm, cm, network_state, indices, node_labels=None):\n if (node_labels is None):\n node_labels = NodeLabels(None, indices)\n node_state = utils.state_of(indices, network_state)\n return tuple((Node(tpm, cm, index, state, node_labels) for (index, state) in zip(indices, node_state)))", "docstring": "Generate |Node| objects for a subsystem.\n\nArgs:\n tpm (np.ndarray): The system's TPM\n cm (np.ndarray): The corresponding CM.\n network_state (tuple): The state of the network.\n indices (tuple[int]): Indices to generate nodes for.\n\n Keyword Args:\n node_labels (|NodeLabels|): Textual labels for each node.\n\nReturns:\n tuple[Node]: The nodes of the system.", "source": "codesearchnet_filtered"} +{"code": "def GetDisplayNameForPathSpec(self, path_spec):\n return path_helper.PathHelper.GetDisplayNameForPathSpec(path_spec, mount_path=self._mount_path, text_prepend=self._text_prepend)", "docstring": "Retrieves the display name for a path specification.\n\nArgs:\n path_spec (dfvfs.PathSpec): path specification.\n\nReturns:\n str: human readable version of the path specification.", "source": "codesearchnet_filtered"} +{"code": "def _parse_line(cls, line):\n try:\n (pkg, rest) = line.split(None, 1)\n except ValueError:\n rpm = cls._parse_package(line.strip())\n return rpm\n rpm = cls._parse_package(pkg)\n rest = rest.split('\\t')\n for (i, value) in enumerate(rest):\n rpm[cls.SOSREPORT_KEYS[i]] = value\n return rpm", "docstring": "Helper method for parsing package line with or without SOS report information.\n\nArgs:\n line (str): package line with or without SOS report information\n\nReturns:\n dict: dictionary containing 'name', 'version', 'release' and 'arch' keys plus\n additionally 'installtime', 'buildtime', 'vendor', 'buildserver', 'pgpsig',\n 'pgpsig_short' if these are present.", "source": "codesearchnet_filtered"} +{"code": "def import_locations(self, marker_file):\n self._marker_file = marker_file\n field_names = ('tag', 'identity', 'latitude', 'longitude', 'altitude', 'name')\n pos_parse = (lambda x, s: (float(s[1:]) if (s[0] == x) else (0 - float(s[1:]))))\n latitude_parse = partial(pos_parse, 'N')\n longitude_parse = partial(pos_parse, 'E')\n altitude_parse = (lambda s: (None if (s.strip() == '8888.0') else float(s)))\n field_parsers = (str, int, latitude_parse, longitude_parse, altitude_parse, str)\n data = utils.prepare_csv_read(marker_file, field_names)\n for row in (x for x in data if (x['tag'] == 'W')):\n for (name, parser) in zip(field_names, field_parsers):\n row[name] = parser(row[name])\n del row['tag']\n try:\n self[row['identity']] = Trigpoint(**row)\n except TypeError:\n del row[None]\n self[row['identity']] = Trigpoint(**row)", "docstring": "Import trigpoint database files.\n\n ``import_locations()`` returns a dictionary with keys containing the\n trigpoint identifier, and values that are :class:`Trigpoint` objects.\n\n It expects trigpoint marker files in the format provided at\n alltrigs-wgs84.txt_, which is the following format::\n\n H SOFTWARE NAME & VERSION\n I GPSU 4.04,\n S SymbolSet=0\n ...\n W,500936,N52.066035,W000.281449, 37.0,Broom Farm\n W,501097,N52.010585,W000.173443, 97.0,Bygrave\n W,505392,N51.910886,W000.186462, 136.0,Sish Lane\n\n Any line not consisting of 6 comma separated fields will be ignored.\n The reader uses the :mod:`csv` module, so alternative whitespace\n formatting should have no effect. The above file processed by\n ``import_locations()`` will return the following ``dict`` object::\n\n {500936: point.Point(52.066035, -0.281449, 37.0, \"Broom Farm\"),\n 501097: point.Point(52.010585, -0.173443, 97.0, \"Bygrave\"),\n 505392: point.Point(51.910886, -0.186462, 136.0, \"Sish Lane\")}\n\nArgs:\n marker_file (iter): Trigpoint marker data to read\n\nReturns:\n dict: Named locations with :class:`Trigpoint` objects\n\nRaises:\n ValueError: Invalid value for ``marker_file``\n\n .. _alltrigs-wgs84.txt: http://www.haroldstreet.org.uk/trigpoints/", "source": "codesearchnet_filtered"} +{"code": "def issorted(list_, op=operator.le):\n return all((op(list_[ix], list_[(ix + 1)]) for ix in range((len(list_) - 1))))", "docstring": "Determines if a list is sorted\n\nArgs:\n list_ (list):\n op (func): sorted operation (default=operator.le)\n\nReturns:\n bool : True if the list is sorted", "source": "codesearchnet_filtered"} +{"code": "def save_yaml(dictionary, path, pretty=False, sortkeys=False):\n if sortkeys:\n dictionary = dict(dictionary)\n with open(path, 'w') as f:\n if pretty:\n pyaml.dump(dictionary, f)\n else:\n yaml.dump(dictionary, f, default_flow_style=None, Dumper=yamlloader.ordereddict.CDumper)", "docstring": "Save dictionary to YAML file preserving order if it is an OrderedDict\n\nArgs:\n dictionary (Dict): Python dictionary to save\n path (str): Path to YAML file\n pretty (bool): Whether to pretty print. Defaults to False.\n sortkeys (bool): Whether to sort dictionary keys. Defaults to False.\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def memoizedmethod(method):\n method_name = method.__name__\n\n @wraps(method)\n def patched(self, *args, **kwargs):\n 'Patched method'\n try:\n return self._cache[method_name]\n except KeyError:\n result = self._cache[method_name] = method(self, *args, **kwargs)\n return result\n return patched", "docstring": "Decorator that caches method result.\n\nArgs:\n method (function): Method\n\nReturns:\n function: Memoized method.\n\nNote:\n Target method class needs as \"_cache\" attribute (dict).\n\n It is the case of \"ObjectIOBase\" and all its subclasses.", "source": "codesearchnet_filtered"} +{"code": "def locator_to_latlong(locator):\n locator = locator.upper()\n if ((len(locator) == 5) or (len(locator) < 4)):\n raise ValueError\n if ((ord(locator[0]) > ord('R')) or (ord(locator[0]) < ord('A'))):\n raise ValueError\n if ((ord(locator[1]) > ord('R')) or (ord(locator[1]) < ord('A'))):\n raise ValueError\n if ((ord(locator[2]) > ord('9')) or (ord(locator[2]) < ord('0'))):\n raise ValueError\n if ((ord(locator[3]) > ord('9')) or (ord(locator[3]) < ord('0'))):\n raise ValueError\n if (len(locator) == 6):\n if ((ord(locator[4]) > ord('X')) or (ord(locator[4]) < ord('A'))):\n raise ValueError\n if ((ord(locator[5]) > ord('X')) or (ord(locator[5]) < ord('A'))):\n raise ValueError\n longitude = (((ord(locator[0]) - ord('A')) * 20) - 180)\n latitude = (((ord(locator[1]) - ord('A')) * 10) - 90)\n longitude += ((ord(locator[2]) - ord('0')) * 2)\n latitude += (ord(locator[3]) - ord('0'))\n if (len(locator) == 6):\n longitude += ((ord(locator[4]) - ord('A')) * (2 / 24))\n latitude += ((ord(locator[5]) - ord('A')) * (1 / 24))\n longitude += (1 / 24)\n latitude += (0.5 / 24)\n else:\n longitude += 1\n latitude += 0.5\n return (latitude, longitude)", "docstring": "converts Maidenhead locator in the corresponding WGS84 coordinates\n\nArgs:\n locator (string): Locator, either 4 or 6 characters\n\nReturns:\n tuple (float, float): Latitude, Longitude\n\nRaises:\n ValueError: When called with wrong or invalid input arg\n TypeError: When arg is not a string\n\nExample:\n The following example converts a Maidenhead locator into Latitude and Longitude\n\n >>> from pyhamtools.locator import locator_to_latlong\n >>> latitude, longitude = locator_to_latlong(\"JN48QM\")\n >>> print latitude, longitude\n 48.5208333333 9.375\n\nNote:\n Latitude (negative = West, positive = East)\n Longitude (negative = South, positive = North)", "source": "codesearchnet_filtered"} +{"code": "def _allocate_subnets(self, conf):\n allocated_subnets = []\n try:\n for net_spec in conf.get('nets', {}).itervalues():\n if (net_spec['type'] != 'nat'):\n continue\n gateway = net_spec.get('gw')\n if gateway:\n allocated_subnet = self._subnet_store.acquire(self.paths.uuid(), gateway)\n else:\n allocated_subnet = self._subnet_store.acquire(self.paths.uuid())\n net_spec['gw'] = str(allocated_subnet.iter_hosts().next())\n allocated_subnets.append(allocated_subnet)\n except:\n self._subnet_store.release(allocated_subnets)\n raise\n return (allocated_subnets, conf)", "docstring": "Allocate all the subnets needed by the given configuration spec\n\nArgs:\n conf (dict): Configuration spec where to get the nets definitions\n from\n\nReturns:\n tuple(list, dict): allocated subnets and modified conf", "source": "codesearchnet_filtered"} +{"code": "def get_lang_tags(index_page):\n dom = dhtmlparser.parseString(index_page)\n lang_tags = [get_html_lang_tags(dom), get_dc_lang_tags(dom), [detect_language(dom)], get_html_tag_lang_params(dom)]\n return list(sorted(set((SourceString(normalize(lang), source=lang.source) for lang in sum(lang_tags, [])))))", "docstring": "Collect informations about language of the page from HTML and Dublin core\n tags and langdetect guesses.\n\nArgs:\n index_page (str): HTML content of the page you wish to analyze.\n\nReturns:\n list: List of :class:`.SourceString` objects.", "source": "codesearchnet_filtered"} +{"code": "def compare(self, value, expectation, regex_expr=False):\n return compare(value, expectation, regex_expr=regex_expr)", "docstring": "Compares two values with regular expression matching support.\n\nArgs:\n value (mixed): value to compare.\n expectation (mixed): value to match.\n regex_expr (bool, optional): enables string based regex matching.\n\nReturns:\n bool", "source": "codesearchnet_filtered"} +{"code": "def get_intermediate_dirs(fs, dir_path):\n intermediates = []\n with fs.lock():\n for path in recursepath(abspath(dir_path), reverse=True):\n try:\n resource = fs.getinfo(path)\n except ResourceNotFound:\n intermediates.append(abspath(path))\n else:\n if resource.is_dir:\n break\n raise errors.DirectoryExpected(dir_path)\n return intermediates[::(- 1)][:(- 1)]", "docstring": "Get a list of non-existing intermediate directories.\n\nArgs:\n fs (FS): A filesystem instance.\n dir_path (str): A path to a new directory on the filesystem.\n\nReturns:\n list: A list of non-existing paths.\n\nRaises:\n ~fs.errors.DirectoryExpected: If a path component\n references a file and not a directory.", "source": "codesearchnet_filtered"} +{"code": "def load_image(buf, request_components=0):\n x = ffi.new('int*')\n y = ffi.new('int*')\n n = ffi.new('int*')\n cbuf = ffi.from_buffer(buf)\n bitmap = lib.stbi_load_from_memory(ffi.cast('unsigned char*', cbuf), len(buf), x, y, n, request_components)\n pybuffer = ffi.buffer(bitmap, ((x[0] * y[0]) * n[0]))\n return (pybuffer, x[0], y[0], n[0])", "docstring": "Load a png or jpeg image into a bitmap buffer.\n\nArgs:\n buf (Buffer): Buffer to load\n request_components (int): If you want to force number of components\n\nReturns:\n A tuple containing:\n\n - Bitmap buffer\n - width of bitmap\n - height of bitmap\n - number of components", "source": "codesearchnet_filtered"} +{"code": "def _redistribute_builder(self, afi='ipv4', source=None):\n if (source == 'connected'):\n return getattr(self._rbridge, 'rbridge_id_router_router_bgp_address_family_{0}_{0}_unicast_default_vrf_af_{0}_uc_and_vrf_cmds_call_point_holder_redistribute_connected_redistribute_connected'.format(afi))\n else:\n raise AttributeError('Invalid source.')", "docstring": "Build BGP redistribute method.\n\n Do not use this method directly. You probably want ``redistribute``.\n\nArgs:\n source (str): Source for redistributing. (connected)\n afi (str): Address family to configure. (ipv4, ipv6)\n\nReturns:\n Method to redistribute desired source.\n\nRaises:\n KeyError: if `source` is not specified.\n\nExample:\n >>> import pynos.device\n >>> conn = ('10.24.39.203', '22')\n >>> auth = ('admin', 'password')\n >>> with pynos.device.Device(conn=conn, auth=auth) as dev:\n ... output = dev.bgp._redistribute_builder(source='connected',\n ... afi='ipv4')\n ... dev.bgp._redistribute_builder(source='hodor',\n ... afi='ipv4') # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n AttributeError", "source": "codesearchnet_filtered"} +{"code": "def file(self, path):\n with open(path, 'r') as f:\n self.body(str(f.read()))", "docstring": "Reads the body to match from a disk file.\n\nArgs:\n path (str): relative or absolute path to file to read from.\n\nReturns:\n self: current Mock instance.", "source": "codesearchnet_filtered"} +{"code": "def get_data(self, file_path=sys.stdin, delimiter=',', categories_delimiter=None):\n if (file_path == sys.stdin):\n logger.info('Read data from standard input')\n lines = [line.replace('\\n', '') for line in file_path]\n else:\n logger.info(('Read data from file ' + file_path))\n with open(file_path) as file:\n lines = list(file)\n columns = lines[0].rstrip('\\n').split(delimiter)[1:]\n categories = None\n if categories_delimiter:\n (columns, categories) = zip(*[c.split(categories_delimiter, 1) for c in columns])\n size = len(columns)\n data = [list(map(int, l.split(delimiter)[1:])) for l in lines[1:(size + 1)]]\n return DesignStructureMatrix(data, columns, categories)", "docstring": "Implement get_dsm method from Provider class.\n\n Parse CSV to return an instance of DSM.\n\nArgs:\n file_path (str/fd): path or file descriptor.\n delimiter (str): character(s) used as delimiter for columns.\n categories_delimiter (str):\n character(s) used as delimiter for categories and keys\n (first column).\n\nReturns:\n DSM: instance of DSM.", "source": "codesearchnet_filtered"} +{"code": "def new_stories(self, raw=False, limit=None):\n new_stories = self._get_stories('newstories', limit)\n if raw:\n new_stories = [story.raw for story in new_stories]\n return new_stories", "docstring": "Returns list of item ids of current new stories\n\nArgs:\n limit (int): specifies the number of stories to be returned.\n raw (bool): Flag to indicate whether to transform all\n objects into raw json.\n\nReturns:\n `list` object containing ids of new stories.", "source": "codesearchnet_filtered"} +{"code": "def connect_sync(self, connection_id, connection_string):\n calldone = threading.Event()\n results = {}\n\n def connect_done(callback_connid, callback_adapterid, callback_success, failure_reason):\n results['success'] = callback_success\n results['failure_reason'] = failure_reason\n calldone.set()\n self.connect_async(connection_id, connection_string, connect_done)\n calldone.wait()\n return results", "docstring": "Synchronously connect to a device\n\nArgs:\n connection_id (int): A unique identifier that will refer to this connection\n connection_string (string): A DeviceAdapter specific string that can be used to connect to\n a device using this DeviceAdapter.\n\nReturns:\n dict: A dictionary with two elements\n 'success': a bool with the result of the connection attempt\n 'failure_reason': a string with the reason for the failure if we failed", "source": "codesearchnet_filtered"} +{"code": "def apply(self, window_length, samples=True, func1d=None):\n window_length /= (1 if samples else self.step)\n if (func1d is None):\n func1d = np.mean\n params = self.__dict__.copy()\n out = self._rolling_window(int(window_length), func1d)\n return Curve(out, params=params)", "docstring": "Runs any kind of function over a window.\n\nArgs:\n window_length (int): the window length. Required.\n samples (bool): window length is in samples. Use False for a window\n length given in metres.\n func1d (function): a function that takes a 1D array and returns a\n scalar. Default: ``np.mean()``.\n\nReturns:\n Curve.", "source": "codesearchnet_filtered"} +{"code": "def _ConvertRowToUnicode(self, parser_mediator, row):\n for (key, value) in iter(row.items()):\n if isinstance(value, py2to3.UNICODE_TYPE):\n continue\n try:\n row[key] = value.decode(self._encoding)\n except UnicodeDecodeError:\n replaced_value = value.decode(self._encoding, errors='replace')\n parser_mediator.ProduceExtractionWarning('error decoding DSV value: {0:s} as {1:s}, characters have been replaced in {2:s}'.format(key, self._encoding, replaced_value))\n row[key] = replaced_value\n return row", "docstring": "Converts all strings in a DSV row dict to Unicode.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n row (dict[str, bytes]): a row from a DSV file, where the dictionary\n key contains the column name and the value a binary string.\n\nReturns:\n dict[str, str]: a row from the DSV file, where the dictionary key\n contains the column name and the value a Unicode string.", "source": "codesearchnet_filtered"} +{"code": "def get_model(self, model, model_id):\n return self._store.find_record(self._get_model_class(model), int(model_id))", "docstring": "Get a single model from the server.\n\nArgs:\n model (string): The class as a string.\n model_id (string): The integer ID as a string.\n\nReturns:\n :class:`cinder_data.model.CinderModel`: A instance of the model.", "source": "codesearchnet_filtered"} +{"code": "def get_contact(self, response=None, nir=None, handle=None, retry_count=3, dt_format=None):\n if (response or (nir == 'krnic')):\n contact_response = response\n else:\n contact_response = self._net.get_http_raw(url=str(NIR_WHOIS[nir]['url']).format(handle), retry_count=retry_count, headers=NIR_WHOIS[nir]['request_headers'], request_type=NIR_WHOIS[nir]['request_type'])\n return self.parse_fields(response=contact_response, fields_dict=NIR_WHOIS[nir]['contact_fields'], dt_format=dt_format, hourdelta=int(NIR_WHOIS[nir]['dt_hourdelta']), is_contact=True)", "docstring": "The function for retrieving and parsing NIR whois data based on\n NIR_WHOIS contact_fields.\n\nArgs:\n response (:obj:`str`): Optional response object, this bypasses the\n lookup.\n nir (:obj:`str`): The NIR to query ('jpnic' or 'krnic'). Required\n if response is None.\n handle (:obj:`str`): For NIRs that have separate contact queries\n (JPNIC), this is the contact handle to use in the query.\n Defaults to None.\n retry_count (:obj:`int`): The number of times to retry in case\n socket errors, timeouts, connection resets, etc. are\n encountered. Defaults to 3.\n dt_format (:obj:`str`): The format of datetime fields if known.\n Defaults to None.\n\nReturns:\n dict: Mapping of the fields provided in contact_fields, to their\n parsed results.", "source": "codesearchnet_filtered"} +{"code": "def list(self, teamId, max=None, **request_parameters):\n check_type(teamId, basestring, may_be_none=False)\n check_type(max, int)\n params = dict_from_items_with_values(request_parameters, teamId=teamId, max=max)\n items = self._session.get_items(API_ENDPOINT, params=params)\n for item in items:\n (yield self._object_factory(OBJECT_TYPE, item))", "docstring": "List team memberships for a team, by ID.\n\n This method supports Webex Teams's implementation of RFC5988 Web\n Linking to provide pagination support. It returns a generator\n container that incrementally yields all team memberships returned by\n the query. The generator will automatically request additional 'pages'\n of responses from Webex as needed until all responses have been\n returned. The container makes the generator safe for reuse. A new API\n call will be made, using the same parameters that were specified when\n the generator was created, every time a new iterator is requested from\n the container.\n\nArgs:\n teamId(basestring): List team memberships for a team, by ID.\n max(int): Limit the maximum number of items returned from the Webex\n Teams service per request.\n **request_parameters: Additional request parameters (provides\n support for parameters that may be added in the future).\n\nReturns:\n GeneratorContainer: A GeneratorContainer which, when iterated,\n yields the team memberships returned by the Webex Teams query.\n\nRaises:\n TypeError: If the parameter types are incorrect.\n ApiError: If the Webex Teams cloud returns an error.", "source": "codesearchnet_filtered"} +{"code": "def set_flowcontrol_receive(self, name, value=None, default=False, disable=False):\n return self.set_flowcontrol(name, 'receive', value, default, disable)", "docstring": "Configures the interface flowcontrol receive value\n\nArgs:\n name (string): The interface identifier. It must be a full\n interface name (ie Ethernet, not Et)\n\n value (boolean): True if the interface should enable receiving\n flow control packets, otherwise False\n\n default (boolean): Specifies to default the interface flow\n control receive value\n\n disable (boolean): Specifies to disable the interface flow\n control receive value\n\nReturns:\n True if the operation succeeds otherwise False is returned", "source": "codesearchnet_filtered"} +{"code": "def set_tick(self, index, interval):\n name = self.tick_name(index)\n if (name is None):\n return pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY)\n self.ticks[name] = interval\n return Error.NO_ERROR", "docstring": "Update the a tick's interval.\n\nArgs:\n index (int): The index of the tick that you want to fetch.\n interval (int): The number of seconds between ticks.\n Setting this to 0 will disable the tick.\n\nReturns:\n int: An error code.", "source": "codesearchnet_filtered"} +{"code": "def receive_data(socket):\n answer = b''\n while True:\n packet = socket.recv(4096)\n if (not packet):\n break\n answer += packet\n response = pickle.loads(answer)\n socket.close()\n return response", "docstring": "Receive an answer from the daemon and return the response.\n\nArgs:\n socket (socket.socket): A socket that is connected to the daemon.\n\nReturns:\n dir or string: The unpickled answer.", "source": "codesearchnet_filtered"} +{"code": "def as_money(self, number, **options):\n if isinstance(number, list):\n return map((lambda val: self.as_money(val, **options)))\n decimal = options.get('decimal')\n number = self.parse(number, decimal)\n if check_type(options, 'dict'):\n options = self.settings['currency'].update(options)\n formats = self._check_currency_format(options['format'])\n use_format = (lambda num: (formats['pos'] if (num > 0) else (formats['neg'] if (num < 0) else formats['zero'])))(number)\n precision = self._change_precision(number, options['precision'])\n thousands = options['thousand']\n decimal = options['decimal']\n formater = self.format(abs(number), precision, thousands, decimal)\n amount = use_format.replace('%s', options['symbol']).replace('%v', formater)\n return amount", "docstring": "Format a number into currency.\n\n Usage: accounting.formatMoney(number, symbol, precision, thousandsSep,\n decimalSep, format)\n defaults: (0, \"$\", 2, \",\", \".\", \"%s%v\")\n Localise by overriding the symbol, precision,\n thousand / decimal separators and format\n Second param can be an object matching `settings.currency`\n which is the easiest way.\n\nArgs:\n number (TYPE): Description\n precision (TYPE): Description\n thousand (TYPE): Description\n decimal (TYPE): Description\n\nReturns:\n name (TYPE): Description", "source": "codesearchnet_filtered"} +{"code": "def _rectify_countdown_or_bool(count_or_bool):\n if ((count_or_bool is True) or (count_or_bool is False)):\n count_or_bool_ = count_or_bool\n elif isinstance(count_or_bool, int):\n if (count_or_bool == 0):\n return 0\n elif (count_or_bool > 0):\n count_or_bool_ = (count_or_bool - 1)\n else:\n count_or_bool_ = count_or_bool\n else:\n count_or_bool_ = False\n return count_or_bool_", "docstring": "used by recursive functions to specify which level to turn a bool on in\n counting down yields True, True, ..., False\n counting up yields False, False, False, ... True\n\nArgs:\n count_or_bool (bool or int): if positive and an integer, it will count\n down, otherwise it will remain the same.\n\nReturns:\n int or bool: count_or_bool_\n\n CommandLine:\n python -m utool.util_str --test-_rectify_countdown_or_bool\n\nExample:\n >>> from ubelt.util_format import _rectify_countdown_or_bool # NOQA\n >>> count_or_bool = True\n >>> a1 = (_rectify_countdown_or_bool(2))\n >>> a2 = (_rectify_countdown_or_bool(1))\n >>> a3 = (_rectify_countdown_or_bool(0))\n >>> a4 = (_rectify_countdown_or_bool(-1))\n >>> a5 = (_rectify_countdown_or_bool(-2))\n >>> a6 = (_rectify_countdown_or_bool(True))\n >>> a7 = (_rectify_countdown_or_bool(False))\n >>> a8 = (_rectify_countdown_or_bool(None))\n >>> result = [a1, a2, a3, a4, a5, a6, a7, a8]\n >>> print(result)\n [1, 0, 0, -1, -2, True, False, False]", "source": "codesearchnet_filtered"} +{"code": "def entanglement_of_formation(state, d0, d1=None):\n state = np.array(state)\n if (d1 is None):\n d1 = int((len(state) / d0))\n if ((state.ndim == 2) and (len(state) == 4) and (d0 == 2) and (d1 == 2)):\n return __eof_qubit(state)\n elif (state.ndim == 1):\n if (d0 < d1):\n tr = [1]\n else:\n tr = [0]\n state = partial_trace(state, tr, dimensions=[d0, d1])\n return entropy(state)\n else:\n print('Input must be a state-vector or 2-qubit density matrix.')\n return None", "docstring": "Compute the entanglement of formation of quantum state.\n\n The input quantum state must be either a bipartite state vector, or a\n 2-qubit density matrix.\n\nArgs:\n state (array_like): (N) array_like or (4,4) array_like, a\n bipartite quantum state.\n d0 (int): the dimension of the first subsystem.\n d1 (int or None): the dimension of the second subsystem.\n\nReturns:\n float: The entanglement of formation.", "source": "codesearchnet_filtered"} +{"code": "def _ExtractYandexSearchQuery(self, url):\n if ('text=' not in url):\n return None\n (_, _, line) = url.partition('text=')\n (before_and, _, _) = line.partition('&')\n if (not before_and):\n return None\n yandex_search_url = before_and.split()[0]\n return yandex_search_url.replace('+', ' ')", "docstring": "Extracts a search query from a Yandex search URL.\n\n Yandex: https://www.yandex.com/search/?text=query\n\nArgs:\n url (str): URL.\n\nReturns:\n str: search query or None if no query was found.", "source": "codesearchnet_filtered"} +{"code": "def post_create_app(cls, app, **settings):\n super(MarshmallowAwareApp, cls).post_create_app(app, **settings)\n marsh.init_app(app)\n return app", "docstring": "Automatically register and init the Flask Marshmallow extension.\n\nArgs:\n app (flask.Flask): The application instance in which to initialize\n Flask Marshmallow upon.\n\n Kwargs:\n settings (dict): The settings passed to this method from the\n parent app.\n\nReturns:\n flask.Flask: The Flask application that was passed in.", "source": "codesearchnet_filtered"} +{"code": "def _dataset_merge_filestore_newresource(self, new_resource, ignore_fields, filestore_resources):\n new_resource.check_required_fields(ignore_fields=ignore_fields)\n self.resources.append(new_resource)\n if new_resource.get_file_to_upload():\n filestore_resources.append(new_resource)\n new_resource['url'] = Dataset.temporary_url", "docstring": "Helper method to add new resource from dataset including filestore.\n\nArgs:\n new_resource (hdx.data.Resource): New resource from dataset\n ignore_fields (List[str]): List of fields to ignore when checking resource\n filestore_resources (List[hdx.data.Resource]): List of resources that use filestore (to be appended to)\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def omit_wells(self, uwis=None):\n if (uwis is None):\n raise ValueError('Must specify at least one uwi')\n return Project([w for w in self if (w.uwi not in uwis)])", "docstring": "Returns a new project where wells with specified uwis have been omitted\n\nArgs:\n uwis (list): list or tuple of UWI strings.\n\nReturns:\n project", "source": "codesearchnet_filtered"} +{"code": "def download_url(self, url, **kwargs):\n if (self.baseurl and ('://' not in url)):\n url = join(self.baseurl, url)\n return self.resolver.download_to_directory(self.directory, url, **kwargs)", "docstring": "Download a URL to the workspace.\n\nArgs:\n url (string): URL to download to directory\n **kwargs : See :py:mod:`ocrd.resolver.Resolver`\n\nReturns:\n The local filename of the downloaded file", "source": "codesearchnet_filtered"} +{"code": "def _CheckIsFile(self, file_entry):\n if (definitions.FILE_ENTRY_TYPE_FILE not in self._file_entry_types):\n return False\n return file_entry.IsFile()", "docstring": "Checks the is_file find specification.\n\nArgs:\n file_entry (FileEntry): file entry.\n\nReturns:\n bool: True if the file entry matches the find specification, False if not.", "source": "codesearchnet_filtered"} +{"code": "def unique_flags(items, key=None):\n len_ = len(items)\n if (key is None):\n item_to_index = dict(zip(reversed(items), reversed(range(len_))))\n indices = item_to_index.values()\n else:\n indices = argunique(items, key=key)\n flags = boolmask(indices, len_)\n return flags", "docstring": "Returns a list of booleans corresponding to the first instance of each\n unique item.\n\nArgs:\n items (Sequence): indexable collection of items\n\n key (Callable, optional): custom normalization function.\n If specified returns items where `key(item)` is unique.\n\nReturns:\n List[bool] : flags the items that are unique\n\nExample:\n >>> import ubelt as ub\n >>> items = [0, 2, 1, 1, 0, 9, 2]\n >>> flags = unique_flags(items)\n >>> assert flags == [True, True, True, False, False, True, False]\n >>> flags = unique_flags(items, key=lambda x: x % 2 == 0)\n >>> assert flags == [True, False, True, False, False, False, False]", "source": "codesearchnet_filtered"} +{"code": "def compile_state_cpfs(self, scope: Dict[(str, TensorFluent)], batch_size: Optional[int]=None, noise: Optional[Noise]=None) -> List[CPFPair]:\n next_state_fluents = []\n with self.graph.as_default():\n with tf.name_scope('state_cpfs'):\n for cpf in self.rddl.domain.state_cpfs:\n cpf_noise = (noise.get(cpf.name, None) if (noise is not None) else None)\n name_scope = utils.identifier(cpf.name)\n with tf.name_scope(name_scope):\n t = self._compile_expression(cpf.expr, scope, batch_size, cpf_noise)\n next_state_fluents.append((cpf.name, t))\n key = (lambda f: self.rddl.domain.next_state_fluent_ordering.index(f[0]))\n next_state_fluents = sorted(next_state_fluents, key=key)\n return next_state_fluents", "docstring": "Compiles the next state fluent CPFs given the current `state` and `action` scope.\n\nArgs:\n scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation.\n batch_size (Optional[int]): The batch size.\n\nReturns:\n A list of state fluent CPFs compiled to :obj:`rddl2tf.fluent.TensorFluent`.", "source": "codesearchnet_filtered"} +{"code": "def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True):\n traj = {}\n trajsize = len(rollout[SampleBatch.ACTIONS])\n for key in rollout:\n traj[key] = np.stack(rollout[key])\n if use_gae:\n assert (SampleBatch.VF_PREDS in rollout), 'Values not found!'\n vpred_t = np.concatenate([rollout[SampleBatch.VF_PREDS], np.array([last_r])])\n delta_t = ((traj[SampleBatch.REWARDS] + (gamma * vpred_t[1:])) - vpred_t[:(- 1)])\n traj[Postprocessing.ADVANTAGES] = discount(delta_t, (gamma * lambda_))\n traj[Postprocessing.VALUE_TARGETS] = (traj[Postprocessing.ADVANTAGES] + traj[SampleBatch.VF_PREDS]).copy().astype(np.float32)\n else:\n rewards_plus_v = np.concatenate([rollout[SampleBatch.REWARDS], np.array([last_r])])\n traj[Postprocessing.ADVANTAGES] = discount(rewards_plus_v, gamma)[:(- 1)]\n traj[Postprocessing.VALUE_TARGETS] = np.zeros_like(traj[Postprocessing.ADVANTAGES])\n traj[Postprocessing.ADVANTAGES] = traj[Postprocessing.ADVANTAGES].copy().astype(np.float32)\n assert all(((val.shape[0] == trajsize) for val in traj.values())), 'Rollout stacked incorrectly!'\n return SampleBatch(traj)", "docstring": "Given a rollout, compute its value targets and the advantage.\n\nArgs:\n rollout (SampleBatch): SampleBatch of a single trajectory\n last_r (float): Value estimation for last observation\n gamma (float): Discount factor.\n lambda_ (float): Parameter for GAE\n use_gae (bool): Using Generalized Advantage Estamation\n\nReturns:\n SampleBatch (SampleBatch): Object with experience from rollout and\n processed rewards.", "source": "codesearchnet_filtered"} +{"code": "def db_dict(c):\n db_d = {}\n c.execute('SELECT * FROM library_spectra')\n db_d['library_spectra'] = [list(row) for row in c]\n c.execute('SELECT * FROM library_spectra_meta')\n db_d['library_spectra_meta'] = [list(row) for row in c]\n c.execute('SELECT * FROM library_spectra_annotation')\n db_d['library_spectra_annotations'] = [list(row) for row in c]\n c.execute('SELECT * FROM library_spectra_source')\n db_d['library_spectra_source'] = [list(row) for row in c]\n c.execute('SELECT * FROM metab_compound')\n db_d['metab_compound'] = [list(row) for row in c]\n return db_d", "docstring": "Get a dictionary of the library spectra from a database\n\nExample:\n >>> from msp2db.db import get_connection\n >>> conn = get_connection('sqlite', 'library.db')\n >>> test_db_d = db_dict(conn.cursor())\n\n If using a large database the resulting dictionary will be very large!\n\nArgs:\n c (cursor): SQL database connection cursor\n\nReturns:\n A dictionary with the following keys 'library_spectra', 'library_spectra_meta', 'library_spectra_annotations',\n 'library_spectra_source' and 'metab_compound'. Where corresponding values for each key are list of list containing\n all the rows in the database.", "source": "codesearchnet_filtered"} +{"code": "def parse_response(service, response, search_type):\n _LOG.debug('Parse response \"%s\" from service \"%s\" of type \"%s\"', response, service, search_type)\n items = []\n if ('searchResult' in response):\n response = response['searchResult']\n elif ('getMetadataResult' in response):\n response = response['getMetadataResult']\n else:\n raise ValueError('\"response\" should contain either the key \"searchResult\" or \"getMetadataResult\"')\n search_metadata = {'number_returned': response['count'], 'total_matches': None, 'search_type': search_type, 'update_id': None}\n for result_type in ('mediaCollection', 'mediaMetadata'):\n result_type_proper = (result_type[0].upper() + result_type[1:])\n raw_items = response.get(result_type, [])\n if isinstance(raw_items, OrderedDict):\n raw_items = [raw_items]\n for raw_item in raw_items:\n class_key = (result_type_proper + raw_item['itemType'].title())\n cls = get_class(class_key)\n items.append(cls.from_music_service(service, raw_item))\n return SearchResult(items, **search_metadata)", "docstring": "Parse the response to a music service query and return a SearchResult\n\nArgs:\n service (MusicService): The music service that produced the response\n response (OrderedDict): The response from the soap client call\n search_type (str): A string that indicates the search type that the\n response is from\n\nReturns:\n SearchResult: A SearchResult object", "source": "codesearchnet_filtered"} +{"code": "def clean(self, settings):\n return {k: v for (k, v) in settings.items() if (k in DEFAULT_SETTINGS)}", "docstring": "Filter given settings to keep only key names available in\n ``DEFAULT_SETTINGS``.\n\nArgs:\n settings (dict): Loaded settings.\n\nReturns:\n dict: Settings object filtered.", "source": "codesearchnet_filtered"} +{"code": "def imrescale(img, scale, return_scale=False, interpolation='bilinear'):\n (h, w) = img.shape[:2]\n if isinstance(scale, (float, int)):\n if (scale <= 0):\n raise ValueError('Invalid scale {}, must be positive.'.format(scale))\n scale_factor = scale\n elif isinstance(scale, tuple):\n max_long_edge = max(scale)\n max_short_edge = min(scale)\n scale_factor = min((max_long_edge / max(h, w)), (max_short_edge / min(h, w)))\n else:\n raise TypeError('Scale must be a number or tuple of int, but got {}'.format(type(scale)))\n new_size = _scale_size((w, h), scale_factor)\n rescaled_img = imresize(img, new_size, interpolation=interpolation)\n if return_scale:\n return (rescaled_img, scale_factor)\n else:\n return rescaled_img", "docstring": "Resize image while keeping the aspect ratio.\n\nArgs:\n img (ndarray): The input image.\n scale (float or tuple[int]): The scaling factor or maximum size.\n If it is a float number, then the image will be rescaled by this\n factor, else if it is a tuple of 2 integers, then the image will\n be rescaled as large as possible within the scale.\n return_scale (bool): Whether to return the scaling factor besides the\n rescaled image.\n interpolation (str): Same as :func:`resize`.\n\nReturns:\n ndarray: The rescaled image.", "source": "codesearchnet_filtered"} +{"code": "def get_clinvar_submission(store, institute_id, case_name, variant_id, submission_id):\n (institute_obj, case_obj) = institute_and_case(store, institute_id, case_name)\n pinned = [(store.variant(variant_id) or variant_id) for variant_id in case_obj.get('suspects', [])]\n variant_obj = store.variant(variant_id)\n clinvar_submission_objs = store.clinvars(submission_id=submission_id)\n return dict(today=str(date.today()), institute=institute_obj, case=case_obj, variant=variant_obj, pinned_vars=pinned, clinvars=clinvar_submission_objs)", "docstring": "Collects all variants from the clinvar submission collection with a specific submission_id\n\nArgs:\n store(scout.adapter.MongoAdapter)\n institute_id(str): Institute ID\n case_name(str): case ID\n variant_id(str): variant._id\n submission_id(str): clinvar submission id, i.e. SUB76578\n\nReturns:\n A dictionary with all the data to display the clinvar_update.html template page", "source": "codesearchnet_filtered"} +{"code": "def get_thread(self, thread_id, update_if_cached=True, raise_404=False):\n cached_thread = self._thread_cache.get(thread_id)\n if cached_thread:\n if update_if_cached:\n cached_thread.update()\n return cached_thread\n res = self._requests_session.get(self._url.thread_api_url(thread_id=thread_id))\n if raise_404:\n res.raise_for_status()\n elif (not res.ok):\n return None\n thread = Thread._from_request(self, res, thread_id)\n self._thread_cache[thread_id] = thread\n return thread", "docstring": "Get a thread from 4chan via 4chan API.\n\nArgs:\n thread_id (int): Thread ID\n update_if_cached (bool): Whether the thread should be updated if it's already in our cache\n raise_404 (bool): Raise an Exception if thread has 404'd\n\nReturns:\n :class:`basc_py4chan.Thread`: Thread object", "source": "codesearchnet_filtered"} +{"code": "def cancel(self, workflow_id):\n self.logger.debug(('Canceling workflow: ' + workflow_id))\n url = ('%(wf_url)s/%(wf_id)s/cancel' % {'wf_url': self.workflows_url, 'wf_id': workflow_id})\n r = self.gbdx_connection.post(url, data='')\n r.raise_for_status()", "docstring": "Cancels a running workflow.\n\nArgs:\n workflow_id (str): Workflow id.\n\nReturns:\n Nothing", "source": "codesearchnet_filtered"} +{"code": "def system_repertoire_distance(r1, r2):\n if (config.MEASURE in measures.asymmetric()):\n raise ValueError('{} is asymmetric and cannot be used as a system-level irreducibility measure.'.format(config.MEASURE))\n return measures[config.MEASURE](r1, r2)", "docstring": "Compute the distance between two repertoires of a system.\n\nArgs:\n r1 (np.ndarray): The first repertoire.\n r2 (np.ndarray): The second repertoire.\n\nReturns:\n float: The distance between ``r1`` and ``r2``.", "source": "codesearchnet_filtered"} +{"code": "def local_expert_attention(x, k, loss_coef, attention_num_experts, train=True, batch_coordinate=None, **kwargs):\n if (batch_coordinate is None):\n batch_coordinate = tf.expand_dims(coordinate_tensor(common_layers.shape_list(x)[:(- 1)], axis=0), axis=(- 1))\n with tf.variable_scope('local_expert_attention'):\n additional_dispatch_params = {'batch_coordinate': batch_coordinate}\n return expert_utils.local_moe(x, train, functools.partial(self_attention_expert, **kwargs), attention_num_experts, k=k, loss_coef=loss_coef, pass_x=True, pass_gates=False, additional_dispatch_params=additional_dispatch_params)", "docstring": "Attention using a mixture of experts.\n\n Positions sent to the same expert can attend to each other.\n The mixture of experts is \"local\" in that it is replicated on each\n datashard.\n\n local_moe flatten all batches so to avoid problems with padding (ex: all\n padding going to the same expert, self attention attending to non null\n padding tokens,...), the padding should be removed before.\n\nArgs:\n x: a Tensor with shape [batch, length, depth] or [1, batch*length, depth]\n k: The number of experts to dispatch each example to\n loss_coef: a scalar. A multiplier for the expert loss\n attention_num_experts: The number of experts to use\n train: a boolean for the current mode\n batch_coordinate (tf.Tensor): int32 tensor of shape [1, batch*length, 1]\n containing the batch ids. If None, deduced from first dim of x.\n **kwargs: Arguments to forward to self_attention_expert\n\nReturns:\n y: a Tensor with shape [batch, length, depth]\n loss: a Scalar", "source": "codesearchnet_filtered"} +{"code": "def get_cases(variant_source, case_lines=None, case_type='ped', variant_type='snv', variant_mode='vcf'):\n individuals = get_individuals(variant_source=variant_source, case_lines=case_lines, case_type=case_type, variant_mode=variant_mode)\n case_objs = []\n case_ids = set()\n compressed = False\n tabix_index = False\n if variant_source.endswith('.gz'):\n logger.debug('Found compressed variant source')\n compressed = True\n tabix_file = '.'.join([variant_source, 'tbi'])\n if os.path.exists(tabix_file):\n logger.debug('Found index file')\n tabix_index = True\n if (len(individuals) > 0):\n for individual in individuals:\n case_ids.add(individual.case_id)\n else:\n case_ids = [os.path.basename(variant_source)]\n for case_id in case_ids:\n logger.info('Found case {0}'.format(case_id))\n case = Case(case_id=case_id, name=case_id, variant_source=variant_source, variant_type=variant_type, variant_mode=variant_mode, compressed=compressed, tabix_index=tabix_index)\n for individual in individuals:\n if (individual.case_id == case_id):\n logger.info('Adding ind {0} to case {1}'.format(individual.name, individual.case_id))\n case.add_individual(individual)\n case_objs.append(case)\n return case_objs", "docstring": "Create a cases and populate it with individuals\n\nArgs:\n variant_source (str): Path to vcf files\n case_lines (Iterable): Ped like lines\n case_type (str): Format of case lines\n\nReturns:\n case_objs (list(puzzle.models.Case))", "source": "codesearchnet_filtered"} +{"code": "def apply_pending(self, panel_obj, version):\n updates = {}\n new_panel = deepcopy(panel_obj)\n new_panel['pending'] = []\n new_panel['date'] = dt.datetime.now()\n info_fields = ['disease_associated_transcripts', 'inheritance_models', 'reduced_penetrance', 'mosaicism', 'database_entry_version', 'comment']\n new_genes = []\n for update in panel_obj.get('pending', []):\n hgnc_id = update['hgnc_id']\n if (update['action'] != 'add'):\n updates[hgnc_id] = update\n continue\n info = update.get('info', {})\n gene_obj = {'hgnc_id': hgnc_id, 'symbol': update['symbol']}\n for field in info_fields:\n if (field in info):\n gene_obj[field] = info[field]\n new_genes.append(gene_obj)\n for gene in panel_obj['genes']:\n hgnc_id = gene['hgnc_id']\n if (hgnc_id not in updates):\n new_genes.append(gene)\n continue\n current_update = updates[hgnc_id]\n action = current_update['action']\n info = current_update['info']\n if (action == 'delete'):\n continue\n elif (action == 'edit'):\n for field in info_fields:\n if (field in info):\n gene[field] = info[field]\n new_genes.append(gene)\n new_panel['genes'] = new_genes\n new_panel['version'] = float(version)\n inserted_id = None\n if (new_panel['version'] == panel_obj['version']):\n result = self.panel_collection.find_one_and_replace({'_id': panel_obj['_id']}, new_panel, return_document=pymongo.ReturnDocument.AFTER)\n inserted_id = result['_id']\n else:\n new_panel.pop('_id')\n panel_obj['is_archived'] = True\n self.update_panel(panel_obj=panel_obj, date_obj=panel_obj['date'])\n inserted_id = self.panel_collection.insert_one(new_panel).inserted_id\n return inserted_id", "docstring": "Apply the pending changes to an existing gene panel or create a new version of the same panel.\n\nArgs:\n panel_obj(dict): panel in database to update\n version(double): panel version to update\n\nReturns:\n inserted_id(str): id of updated panel or the new one", "source": "codesearchnet_filtered"} +{"code": "def get_path_from_query_string(req):\n if (req.args.get('path') is None):\n raise exceptions.UserError('Path not found in query string')\n return req.args.get('path')", "docstring": "Gets path from query string\n\nArgs:\n req (flask.request): Request object from Flask\n\nReturns:\n path (str): Value of \"path\" parameter from query string\n\nRaises:\n exceptions.UserError: If \"path\" is not found in query string", "source": "codesearchnet_filtered"} +{"code": "def getmtime(self, path=None, client_kwargs=None, header=None):\n return self._getmtime_from_header(self.head(path, client_kwargs, header))", "docstring": "Return the time of last access of path.\n\nArgs:\n path (str): File path or URL.\n client_kwargs (dict): Client arguments.\n header (dict): Object header.\n\nReturns:\n float: The number of seconds since the epoch\n (see the time module).", "source": "codesearchnet_filtered"} +{"code": "def modname_to_modpath(modname, hide_init=True, hide_main=False, sys_path=None):\n modpath = _syspath_modname_to_modpath(modname, sys_path)\n if (modpath is None):\n return None\n modpath = normalize_modpath(modpath, hide_init=hide_init, hide_main=hide_main)\n return modpath", "docstring": "Finds the path to a python module from its name.\n\n Determines the path to a python module without directly import it\n\n Converts the name of a module (__name__) to the path (__file__) where it is\n located without importing the module. Returns None if the module does not\n exist.\n\nArgs:\n modname (str): module filepath\n hide_init (bool): if False, __init__.py will be returned for packages\n hide_main (bool): if False, and hide_init is True, __main__.py will be\n returned for packages, if it exists.\n sys_path (list): if specified overrides `sys.path` (default None)\n\nReturns:\n str: modpath - path to the module, or None if it doesn't exist\n\n CommandLine:\n python -m xdoctest.static_analysis modname_to_modpath:0\n pytest /home/joncrall/code/xdoctest/xdoctest/static_analysis.py::modname_to_modpath:0\n\nExample:\n >>> modname = 'xdoctest.__main__'\n >>> modpath = modname_to_modpath(modname, hide_main=False)\n >>> assert modpath.endswith('__main__.py')\n >>> modname = 'xdoctest'\n >>> modpath = modname_to_modpath(modname, hide_init=False)\n >>> assert modpath.endswith('__init__.py')\n >>> modpath = basename(modname_to_modpath('_ctypes'))\n >>> assert 'ctypes' in modpath", "source": "codesearchnet_filtered"} +{"code": "def fit(self, struct1, struct2):\n (struct1, struct2) = self._process_species([struct1, struct2])\n if ((not self._subset) and (self._comparator.get_hash(struct1.composition) != self._comparator.get_hash(struct2.composition))):\n return None\n (struct1, struct2, fu, s1_supercell) = self._preprocess(struct1, struct2)\n match = self._match(struct1, struct2, fu, s1_supercell, break_on_match=True)\n if (match is None):\n return False\n else:\n return (match[0] <= self.stol)", "docstring": "Fit two structures.\n\nArgs:\n struct1 (Structure): 1st structure\n struct2 (Structure): 2nd structure\n\nReturns:\n True or False.", "source": "codesearchnet_filtered"} +{"code": "def _compile_arithmetic_expression(self, expr: Expression, scope: Dict[(str, TensorFluent)], batch_size: Optional[int]=None, noise: Optional[List[tf.Tensor]]=None) -> TensorFluent:\n etype = expr.etype\n args = expr.args\n if (len(args) == 1):\n etype2op = {'+': (lambda x: x), '-': (lambda x: (- x))}\n if (etype[1] not in etype2op):\n raise ValueError('Invalid binary arithmetic expression:\\n{}'.format(expr))\n op = etype2op[etype[1]]\n x = self._compile_expression(args[0], scope, batch_size, noise)\n fluent = op(x)\n else:\n etype2op = {'+': (lambda x, y: (x + y)), '-': (lambda x, y: (x - y)), '*': (lambda x, y: (x * y)), '/': (lambda x, y: (x / y))}\n if (etype[1] not in etype2op):\n raise ValueError('Invalid binary arithmetic expression:\\n{}'.format(expr))\n op = etype2op[etype[1]]\n x = self._compile_expression(args[0], scope, batch_size, noise)\n y = self._compile_expression(args[1], scope, batch_size, noise)\n fluent = op(x, y)\n return fluent", "docstring": "Compile an arithmetic expression `expr` into a TensorFluent\n in the given `scope` with optional batch size.\n\nArgs:\n expr (:obj:`rddl2tf.expr.Expression`): A RDDL arithmetic expression.\n scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.\n batch_size (Optional[size]): The batch size.\n\nReturns:\n :obj:`rddl2tf.fluent.TensorFluent`: The compiled expression as a TensorFluent.", "source": "codesearchnet_filtered"} +{"code": "def self_attention_expert(x, batch_coordinate, mask_right=True, split_batch=False, attention_num_head=1, attention_kq_size=None, attention_v_size=None):\n depth = x.get_shape().as_list()[(- 1)]\n length = common_layers.shape_list(batch_coordinate)[0]\n global _expert_count\n _expert_count += 1\n length = tf.cond(tf.equal(length, 0), (lambda : tf.Print(length, [length], 'Expert {} empty: '.format(_expert_count))), (lambda : length))\n tf.summary.scalar('batch_size', length, family='experts_stats_batch_size')\n attention_kq_size = (attention_kq_size or depth)\n attention_v_size = (attention_v_size or depth)\n\n def length_not_null(x, batch_coordinate):\n \"Branch of the graph only evaluated when length isn't null.\"\n bias_batch = attention_bias_coordinates(batch_coordinate)\n\n def add_or_set_if(prev_bias, new_bias, condition):\n 'Add the bias together while considering the None case.'\n if (not condition):\n return prev_bias\n if (prev_bias is None):\n return new_bias\n return (prev_bias + new_bias)\n\n def mask_and_call_attention(x):\n 'Function applied once for each sequence of the batch.'\n length = common_layers.shape_list(x)[1]\n bias_past = tf.reshape(attention_bias_lower_triangle(length), [length, length])\n bias = None\n bias = add_or_set_if(bias, bias_past, mask_right)\n bias = add_or_set_if(bias, bias_batch, (not split_batch))\n bias = tf.reshape(bias, [1, 1, length, length])\n return multihead_attention(x, None, bias, total_key_depth=attention_kq_size, total_value_depth=attention_v_size, output_depth=depth, num_heads=attention_num_head, dropout_rate=0.0)\n if split_batch:\n out = expert_utils.map_ids(x, batch_coordinate, mask_and_call_attention)\n else:\n x = tf.reshape(x, [1, length, depth])\n out = mask_and_call_attention(x)\n out = tf.squeeze(out, 0)\n return out\n out = tf.cond(tf.equal(length, 0), (lambda : tf.zeros(shape=[0, depth], dtype=tf.float32, name='empty_out')), (lambda : length_not_null(x, batch_coordinate)))\n return out", "docstring": "Implementing attention that runs inside each expert.\n\nArgs:\n x: A tensor of shape[batch, depth]. Contains representations from\n different positions, which are lexicographically ordered.\n batch_coordinate: A tensor of shape [batch, 1] containing the batch\n coordinate of each element in x. This is needed to make sure that\n positions from different sequences don't attend to each other.\n mask_right: A bool. If true, we will not attend to positions on the right,\n just as decoder self attention.\n split_batch (bool): If True, each sequence of the batch is processed\n individually on a loop. If False, the sequences are processed all at\n once and a mask is applied to isolate the sequences from each others\n attention_num_head (int): number of attention heads\n attention_kq_size (int): dimension used for the attention key, and query\n attention_v_size (int): dimension used for the attention value\n\nReturns:\n out: A tensor of shape [batch, depth].\n example use:\n expert_utils.local_moe(\n ...\n expert_fn=functools.partial(self_attention_expert, mask_right=)\n )", "source": "codesearchnet_filtered"} +{"code": "def get_airport_weather(self, iata, page=1, limit=100):\n url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)\n weather = self._fr24.get_airport_weather(url)\n mi = weather['sky']['visibility']['mi']\n if ((mi is not None) and (mi != 'None')):\n mi = float(mi)\n km = (mi * 1.6094)\n weather['sky']['visibility']['km'] = km\n return weather", "docstring": "Retrieve the weather at an airport\n\n Given the IATA code of an airport, this method returns the weather information.\n\nArgs:\n iata (str): The IATA code for an airport, e.g. HYD\n page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher page numbers to get more data\n limit (int): Optional limit on number of records returned\n\nReturns:\n A list of dicts with the data; one dict for each row of data from flightradar24\n\n Example::\n\n from pyflightdata import FlightData\n f=FlightData()\n #optional login\n f.login(myemail,mypassword)\n f.get_airport_weather('HYD')\n f.get_airport_weather('HYD',page=1,limit=10)", "source": "codesearchnet_filtered"} +{"code": "def getattr_sdk(attr, name):\n if inspect.isroutine(attr):\n if hasattr(attr, '_sdkmeta'):\n return attr\n raise AttributeError(name)", "docstring": "Filter SDK attributes\n\nArgs:\n attr(attribute): Attribute as returned by :func:`getattr`.\n name(str): Attribute name.\n\nReturns:\n `attr` if passed.", "source": "codesearchnet_filtered"} +{"code": "def simple_spool_transaction(self, from_address, to, op_return, min_confirmations=6):\n ntokens = len(to)\n nfees = old_div(self._t.estimate_fee(ntokens, 2), self.fee)\n inputs = self.select_inputs(from_address, nfees, ntokens, min_confirmations=min_confirmations)\n outputs = [{'address': to_address, 'value': self.token} for to_address in to]\n outputs += [{'script': self._t._op_return_hex(op_return), 'value': 0}]\n unsigned_tx = self._t.build_transaction(inputs, outputs)\n return unsigned_tx", "docstring": "Utililty function to create the spool transactions. Selects the inputs,\n encodes the op_return and constructs the transaction.\n\nArgs:\n from_address (str): Address originating the transaction\n to (str): list of addresses to receive tokens (file_hash, file_hash_metadata, ...)\n op_return (str): String representation of the spoolverb, as returned by the properties of Spoolverb\n min_confirmations (int): Number of confirmations when chosing the inputs of the transaction. Defaults to 6\n\nReturns:\n str: unsigned transaction", "source": "codesearchnet_filtered"} +{"code": "def tokeninfo(self, jwt):\n warnings.warn('/tokeninfo will be deprecated in future releases', DeprecationWarning)\n return self.post(url='https://{}/tokeninfo'.format(self.domain), data={'id_token': jwt}, headers={'Content-Type': 'application/json'})", "docstring": "Returns user profile based on the user's jwt\n\n Validates a JSON Web Token (signature and expiration) and returns the\n user information associated with the user id (sub property) of\n the token.\n\nArgs:\n jwt (str): User's jwt\n\nReturns:\n The user profile.", "source": "codesearchnet_filtered"} +{"code": "def _validate_netconfig(self, conf):\n nets = conf.get('nets', {})\n if (len(nets) == 0):\n raise LagoInitException('No networks configured.')\n no_mgmt_dns = [name for (name, net) in nets.iteritems() if ((net.get('management', None) is None) and (net.get('main_dns') or net.get('dns_domain_name')))]\n if ((len(no_mgmt_dns) > 0) and (len(nets.keys()) > 1)):\n raise LagoInitException('Networks: {0}, misconfigured, they are not marked as management, but have DNS attributes. DNS is supported only in management networks.'.format(','.join(no_mgmt_dns)))\n for (dom_name, dom_spec) in conf['domains'].items():\n mgmts = []\n for nic in dom_spec['nics']:\n net = self._get_net(conf, dom_name, nic)\n if (net.get('management', False) is True):\n mgmts.append(nic['net'])\n if (len(mgmts) == 0):\n raise LagoInitException('VM {0} has no management network, please connect it to one.'.format(dom_name))\n if (len(mgmts) > 1):\n raise LagoInitException('VM {0} has more than one management network: {1}. It should have exactly one.'.format(dom_name, ','.join(mgmts)))", "docstring": "Validate network configuration\n\nArgs:\n conf(dict): spec\n\nReturns:\n None\n\nRaises:\n :exc:`~lago.utils.LagoInitException`: If a VM has more than\n one management network configured, or a network which is not\n management has DNS attributes, or a VM is configured with a\n none-existence NIC, or a VM has no management network.", "source": "codesearchnet_filtered"} +{"code": "def prepare_all_data(data_dir, block_pct_tokens_thresh=0.1):\n gs_blocks_dir = os.path.join(data_dir, GOLD_STANDARD_BLOCKS_DIRNAME)\n gs_blocks_filenames = get_filenames(gs_blocks_dir, full_path=False, match_regex=re.escape(GOLD_STANDARD_BLOCKS_EXT))\n gs_blocks_fileroots = (re.search(('(.+)' + re.escape(GOLD_STANDARD_BLOCKS_EXT)), gs_blocks_filename).group(1) for gs_blocks_filename in gs_blocks_filenames)\n return [prepare_data(data_dir, fileroot, block_pct_tokens_thresh) for fileroot in gs_blocks_fileroots]", "docstring": "Prepare data for all HTML + gold standard blocks examples in ``data_dir``.\n\nArgs:\n data_dir (str)\n block_pct_tokens_thresh (float): must be in [0.0, 1.0]\n\nReturns:\n List[Tuple[str, List[float, int, List[str]], List[float, int, List[str]]]]\n\n See Also:\n :func:`prepare_data`", "source": "codesearchnet_filtered"} +{"code": "def interval(coro, interval=1, times=None, loop=None):\n assert_corofunction(coro=coro)\n times = (int((times or 0)) or float('inf'))\n\n @asyncio.coroutine\n def schedule(times, *args, **kw):\n while (times > 0):\n times -= 1\n (yield from coro(*args, **kw))\n (yield from asyncio.sleep(interval))\n\n def wrapper(*args, **kw):\n return ensure_future(schedule(times, *args, **kw), loop=loop)\n return wrapper", "docstring": "Schedules the execution of a coroutine function every `x` amount of\n seconds.\n\n The function returns an `asyncio.Task`, which implements also an\n `asyncio.Future` interface, allowing the user to cancel the execution\n cycle.\n\n This function can be used as decorator.\n\nArgs:\n coro (coroutinefunction): coroutine function to defer.\n interval (int/float): number of seconds to repeat the coroutine\n execution.\n times (int): optional maximum time of executions. Infinite by default.\n loop (asyncio.BaseEventLoop, optional): loop to run.\n Defaults to asyncio.get_event_loop().\n\nRaises:\n TypeError: if coro argument is not a coroutine function.\n\nReturns:\n future (asyncio.Task): coroutine wrapped as task future.\n Useful for cancellation and state checking.\n\n Usage::\n\n # Usage as function\n future = paco.interval(coro, 1)\n\n # Cancel it after a while...\n await asyncio.sleep(5)\n future.cancel()\n\n # Usage as decorator\n @paco.interval(10)\n async def metrics():\n await send_metrics()\n\n future = await metrics()", "source": "codesearchnet_filtered"} +{"code": "def get_uuid_string(low=None, high=None, **x):\n if ((low is None) or (high is None)):\n return None\n x = ''.join([parse_part(low), parse_part(high)])\n return '-'.join([x[:8], x[8:12], x[12:16], x[16:20], x[20:32]])", "docstring": "This method parses a UUID protobuf message type from its component\n 'high' and 'low' longs into a standard formatted UUID string\n\nArgs:\n x (dict): containing keys, 'low' and 'high' corresponding to the UUID\n protobuf message type\n\nReturns:\n str: UUID formatted string", "source": "codesearchnet_filtered"} +{"code": "def wait_for_element(self, using, value, timeout=10000, interval=1000, asserter=is_displayed):\n if (not callable(asserter)):\n raise TypeError('Asserter must be callable.')\n\n @retry(retry_on_exception=(lambda ex: isinstance(ex, WebDriverException)), stop_max_delay=timeout, wait_fixed=interval)\n def _wait_for_element(ctx, using, value):\n el = ctx.element(using, value)\n asserter(el)\n return el\n return _wait_for_element(self, using, value)", "docstring": "Wait for element till satisfy the given condition\n\n Support:\n Android iOS Web(WebView)\n\nArgs:\n using(str): The element location strategy.\n value(str): The value of the location strategy.\n timeout(int): How long we should be retrying stuff.\n interval(int): How long between retries.\n asserter(callable): The asserter func to determine the result.\n\nReturns:\n Return the Element.\n\nRaises:\n WebDriverException.", "source": "codesearchnet_filtered"} +{"code": "def bulkDetails(self, packageNames):\n params = {'au': '1'}\n req = googleplay_pb2.BulkDetailsRequest()\n req.docid.extend(packageNames)\n data = req.SerializeToString()\n message = self.executeRequestApi2(BULK_URL, post_data=data.decode('utf-8'), content_type=CONTENT_TYPE_PROTO, params=params)\n response = message.payload.bulkDetailsResponse\n return [(None if (not utils.hasDoc(entry)) else utils.parseProtobufObj(entry.doc)) for entry in response.entry]", "docstring": "Get several apps details from a list of package names.\n\n This is much more efficient than calling N times details() since it\n requires only one request. If an item is not found it returns an empty object\n instead of throwing a RequestError('Item not found') like the details() function\n\nArgs:\n packageNames (list): a list of app IDs (usually starting with 'com.').\n\nReturns:\n a list of dictionaries containing docv2 data, or None\n if the app doesn't exist", "source": "codesearchnet_filtered"} +{"code": "def _EncodeString(self, string):\n try:\n encoded_string = string.encode(self._encoding, errors=self._errors)\n except UnicodeEncodeError:\n if (self._errors == 'strict'):\n logging.error('Unable to properly write output due to encoding error. Switching to error tolerant encoding which can result in non Basic Latin (C0) characters to be replaced with \"?\" or \"\\\\ufffd\".')\n self._errors = 'replace'\n encoded_string = string.encode(self._encoding, errors=self._errors)\n return encoded_string", "docstring": "Encodes the string.\n\nArgs:\n string (str): string to encode.\n\nReturns:\n bytes: encoded string.", "source": "codesearchnet_filtered"} +{"code": "def get_minimum_indentation(text):\n lines = text.split('\\n')\n indentations = [get_indentation(line_) for line_ in lines if (len(line_.strip()) > 0)]\n if (len(indentations) == 0):\n return 0\n return min(indentations)", "docstring": "r\"\"\"\n returns the number of preceding spaces\n\nArgs:\n text (str): unicode text\n\nReturns:\n int: indentation\n\n CommandLine:\n python -m utool.util_str --exec-get_minimum_indentation --show\n\nExample:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_str import * # NOQA\n >>> import utool as ut\n >>> text = ' foo\\n bar'\n >>> result = get_minimum_indentation(text)\n >>> print(result)\n 3", "source": "codesearchnet_filtered"} +{"code": "def decrypt(self, message):\n message = json.loads(message)\n unencrypted_msg = []\n for line in message:\n enc_line = binascii.a2b_base64(line)\n unencrypted_line = rsa.decrypt(enc_line, self.private_key)\n unencrypted_msg.append(unencrypted_line)\n unencrypted_msg = ''.join(unencrypted_msg)\n return unencrypted_msg", "docstring": "Decrypts a string using our own private key object.\n\nArgs:\n message (string): The string of the message to decrypt.\n\nReturns:\n The unencrypted string.", "source": "codesearchnet_filtered"} +{"code": "def parseConfig(cls, value):\n if ('enabled' in value):\n value['enabled'] = bool(value['enabled'])\n if ('exclude_paths' in value):\n value['exclude_paths'] = [n.strip() for n in ast.literal_eval(value['exclude_paths'])]\n return value", "docstring": "Parse the config values\n\nArgs:\n value (dict): Dictionary which contains the checker config\n\nReturns:\n dict: The checker config with parsed values", "source": "codesearchnet_filtered"} +{"code": "def write(gmt, out_path):\n with open(out_path, 'w') as f:\n for (_, each_dict) in enumerate(gmt):\n f.write((each_dict[SET_IDENTIFIER_FIELD] + '\\t'))\n f.write((each_dict[SET_DESC_FIELD] + '\\t'))\n f.write('\\t'.join([str(entry) for entry in each_dict[SET_MEMBERS_FIELD]]))\n f.write('\\n')", "docstring": "Write a GMT to a text file.\n\nArgs:\n gmt (GMT object): list of dicts\n out_path (string): output path\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def auto_docstr(modname, funcname, verbose=True, moddir=None, modpath=None, **kwargs):\n (func, module, error_str) = load_func_from_module(modname, funcname, verbose=verbose, moddir=moddir, modpath=modpath)\n if (error_str is None):\n try:\n docstr = make_default_docstr(func, **kwargs)\n except Exception as ex:\n import utool as ut\n error_str = ut.formatex(ex, 'Caught Error in parsing docstr', tb=True)\n error_str += '\\n\\nReplicateCommand:\\n python -m utool --tf auto_docstr --modname={modname} --funcname={funcname} --moddir={moddir}'.format(modname=modname, funcname=funcname, moddir=moddir)\n error_str += ('\\n kwargs=' + ut.repr4(kwargs))\n return error_str\n else:\n docstr = error_str\n return docstr", "docstring": "r\"\"\"\n called from vim. Uses strings of filename and modnames to build docstr\n\nArgs:\n modname (str): name of a python module\n funcname (str): name of a function in the module\n\nReturns:\n str: docstr\n\n CommandLine:\n python -m utool.util_autogen auto_docstr\n python -m utool --tf auto_docstr\n\nExample:\n >>> # DISABLE_DOCTEST\n >>> import utool as ut\n >>> from utool.util_autogen import * # NOQA\n >>> ut.util_autogen.rrr(verbose=False)\n >>> #docstr = ut.auto_docstr('ibeis.algo.hots.smk.smk_index', 'compute_negentropy_names')\n >>> modname = ut.get_argval('--modname', default='utool.util_autogen')\n >>> funcname = ut.get_argval('--funcname', default='auto_docstr')\n >>> moddir = ut.get_argval('--moddir', type_=str, default=None)\n >>> docstr = ut.util_autogen.auto_docstr(modname, funcname)\n >>> print(docstr)", "source": "codesearchnet_filtered"} +{"code": "def bad_request(cls, errors=None):\n if cls.expose_status:\n cls.response.content_type = 'application/json'\n cls.response._status_line = '400 Bad Request'\n return cls(400, errors=errors).to_json", "docstring": "Shortcut API for HTTP 400 `Bad Request` response.\n\nArgs:\n errors (list): Response key/value data.\n\nReturns:\n WSResponse Instance.", "source": "codesearchnet_filtered"} +{"code": "def hill_climb(nsteps, start_node, get_next_node):\n outputs = []\n best_score = (- float('inf'))\n for step in range(nsteps):\n (next_node, score, output) = get_next_node(copy.deepcopy(start_node))\n if (score > best_score):\n start_node = copy.deepcopy(next_node)\n best_score = score\n outputs.append(output)\n return (start_node, best_score, outputs)", "docstring": "Modular hill climbing algorithm.\n\nExample:\n >>> def get_next_node(node):\n ... a, b = random.sample(range(len(node)), 2)\n ... node[a], node[b] = node[b], node[a]\n ... plaintext = decrypt(node, ciphertext)\n ... score = lantern.score(plaintext, *fitness_functions)\n ... return node, score, Decryption(plaintext, ''.join(node), score)\n >>> final_node, best_score, outputs = hill_climb(10, \"ABC\", get_next_node)\n\nArgs:\n nsteps (int): The number of neighbours to visit\n start_node: The starting node\n get_next_node (function): Function to return the next node\n the score of the current node and any optional output from the current node\n\nReturns:\n The highest node found, the score of this node and the outputs from the best nodes along the way", "source": "codesearchnet_filtered"} +{"code": "def deepgetattr(obj, name, default=_UNSPECIFIED):\n try:\n if ('.' in name):\n (attr, subname) = name.split('.', 1)\n return deepgetattr(getattr(obj, attr), subname, default)\n else:\n return getattr(obj, name)\n except AttributeError:\n if (default is _UNSPECIFIED):\n raise\n else:\n return default", "docstring": "Try to retrieve the given attribute of an object, digging on '.'.\n\n This is an extended getattr, digging deeper if '.' is found.\n\nArgs:\n obj (object): the object of which an attribute should be read\n name (str): the name of an attribute to look up.\n default (object): the default value to use if the attribute wasn't found\n\nReturns:\n the attribute pointed to by 'name', splitting on '.'.\n\nRaises:\n AttributeError: if obj has no 'name' attribute.", "source": "codesearchnet_filtered"} +{"code": "def swo_speed_info(self):\n info = structs.JLinkSWOSpeedInfo()\n res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_SPEED_INFO, ctypes.byref(info))\n if (res < 0):\n raise errors.JLinkException(res)\n return info", "docstring": "Retrieves information about the supported SWO speeds.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n A ``JLinkSWOSpeedInfo`` instance describing the target's supported\n SWO speeds.\n\nRaises:\n JLinkException: on error", "source": "codesearchnet_filtered"} +{"code": "def create_chapter_from_string(self, html_string, url=None, title=None):\n clean_html_string = self.clean_function(html_string)\n clean_xhtml_string = clean.html_to_xhtml(clean_html_string)\n if title:\n pass\n else:\n try:\n root = BeautifulSoup(html_string, 'html.parser')\n title_node = root.title\n if (title_node is not None):\n title = unicode(title_node.string)\n else:\n raise ValueError\n except (IndexError, ValueError):\n title = 'Ebook Chapter'\n return Chapter(clean_xhtml_string, title, url)", "docstring": "Creates a Chapter object from a string. Sanitizes the\n string using the clean_function method, and saves\n it as the content of the created chapter.\n\nArgs:\n html_string (string): The html or xhtml content of the created\n Chapter\n url (Option[string]): A url to infer the title of the chapter from\n title (Option[string]): The title of the created Chapter. By\n default, this is None, in which case the title will try to be\n inferred from the webpage at the url.\n\nReturns:\n Chapter: A chapter object whose content is the given string\n and whose title is that provided or inferred from the url", "source": "codesearchnet_filtered"} +{"code": "def _validate_input_state(quantum_state):\n rho = np.asarray(quantum_state)\n if (rho.ndim == 1):\n rho = np.outer(rho, np.conj(rho))\n shape = np.shape(rho)\n if ((len(shape) != 2) or (shape[0] != shape[1])):\n raise VisualizationError('Input is not a valid quantum state.')\n num = int(np.log2(rho.shape[0]))\n if ((2 ** num) != rho.shape[0]):\n raise VisualizationError('Input is not a multi-qubit quantum state.')\n return rho", "docstring": "Validates the input to state visualization functions.\n\nArgs:\n quantum_state (ndarray): Input state / density matrix.\n\nReturns:\n rho: A 2d numpy array for the density matrix.\n\nRaises:\n VisualizationError: Invalid input.", "source": "codesearchnet_filtered"} +{"code": "def un(byts):\n return msgpack.loads(byts, use_list=False, raw=False, unicode_errors='surrogatepass')", "docstring": "Use msgpack to de-serialize a python object.\n\nArgs:\n byts (bytes): The bytes to de-serialize\n\nNote:\n String objects are decoded using utf8 encoding. In order to handle\n potentially malformed input, ``unicode_errors='surrogatepass'`` is set\n to allow decoding bad input strings.\n\nReturns:\n obj: The de-serialized object", "source": "codesearchnet_filtered"} +{"code": "def collection(self, collection_id):\n child_path = (self._path + (collection_id,))\n return self._client.collection(*child_path)", "docstring": "Create a sub-collection underneath the current document.\n\nArgs:\n collection_id (str): The sub-collection identifier (sometimes\n referred to as the \"kind\").\n\nReturns:\n ~.firestore_v1beta1.collection.CollectionReference: The\n child collection.", "source": "codesearchnet_filtered"} +{"code": "def get_cookiecutter_config(template, default_config=None, version=None):\n default_config = (default_config or {})\n config_dict = cc_config.get_user_config()\n (repo_dir, _) = cc_repository.determine_repo_dir(template=template, abbreviations=config_dict['abbreviations'], clone_to_dir=config_dict['cookiecutters_dir'], checkout=version, no_input=True)\n context_file = os.path.join(repo_dir, 'cookiecutter.json')\n context = cc_generate.generate_context(context_file=context_file, default_context={**config_dict['default_context'], **default_config})\n return (repo_dir, cc_prompt.prompt_for_config(context))", "docstring": "Obtains the configuration used for cookiecutter templating\n\nArgs:\n template: Path to the template\n default_config (dict, optional): The default configuration\n version (str, optional): The git SHA or branch to use when\n checking out template. Defaults to latest version\n\nReturns:\n tuple: The cookiecutter repo directory and the config dict", "source": "codesearchnet_filtered"} +{"code": "def BalanceFor(self, assetId):\n for (key, fixed8) in self.Balances.items():\n if (key == assetId):\n return fixed8\n return Fixed8(0)", "docstring": "Get the balance for a given asset id.\n\nArgs:\n assetId (UInt256):\n\nReturns:\n Fixed8: balance value.", "source": "codesearchnet_filtered"} +{"code": "def request(path):\n headers = {'Accept': 'application/json'}\n try:\n requested_object = requests.get(path, headers=headers)\n requested_object.raise_for_status()\n except requests.exceptions.HTTPError as exception:\n LOGGER.error(((((((inspect.stack()[0][3] + ': HTTPError = ') + str(exception.response.status_code)) + ' ') + str(exception.response.reason)) + ' ') + str(path)))\n raise\n except requests.exceptions.InvalidURL as exception:\n LOGGER.error(((('URLError = ' + str(exception.reason)) + ' ') + str(path)))\n raise\n except Exception:\n import traceback\n LOGGER.error(('Generic exception: ' + traceback.format_exc()))\n raise\n else:\n response = requested_object.json()\n return response", "docstring": "Send a request to a given URL accepting JSON format and return a \\\n deserialized Python object.\n\nArgs:\n path (str): The URI to be requested.\n\nReturns:\n response: Deserialized JSON Python object.\n\nRaises:\n HTTPError: the HTTP error returned by the requested server.\n InvalidURL: an invalid URL has been requested.\n Exception: generic exception.", "source": "codesearchnet_filtered"} +{"code": "def _get_resource_view(self, resource_view):\n if isinstance(resource_view, dict):\n resource_view = ResourceView(resource_view, configuration=self.configuration)\n if isinstance(resource_view, ResourceView):\n return resource_view\n raise HDXError(('Type %s is not a valid resource view!' % type(resource_view).__name__))", "docstring": "Get resource view id\n\nArgs:\n resource_view (Union[ResourceView,Dict]): ResourceView metadata from a ResourceView object or dictionary\n\nReturns:\n ResourceView: ResourceView object", "source": "codesearchnet_filtered"} +{"code": "def import_module(name):\n parts = name.split('.')\n path = None\n module_name = ''\n fhandle = None\n for (index, part) in enumerate(parts):\n module_name = (part if (index == 0) else ('%s.%s' % (module_name, part)))\n path = ([path] if (path is not None) else path)\n try:\n (fhandle, path, descr) = imp.find_module(part, path)\n if (module_name in sys.modules):\n mod = sys.modules[module_name]\n else:\n mod = imp.load_module(module_name, fhandle, path, descr)\n finally:\n if fhandle:\n fhandle.close()\n return mod", "docstring": "Imports a module into the current runtime environment\n\n This function emulates the Python import system that allows for\n importing full path modules. It will break down the module and\n import each part (or skip if it is already loaded in cache).\n\nArgs:\n name (str): The name of the module to import. This should be\n the full path of the module\n\nReturns:\n The module that was imported", "source": "codesearchnet_filtered"} +{"code": "def generate_output_list(self, source, key, val, line='2', hr=True, show_name=False, colorize=True):\n output = generate_output(line=line, short=(HR_RDAP[source][key]['_short'] if hr else key), name=(HR_RDAP[source][key]['_name'] if (hr and show_name) else None), is_parent=(False if ((val is None) or (len(val) == 0)) else True), value=('None' if ((val is None) or (len(val) == 0)) else None), colorize=colorize)\n if (val is not None):\n for item in val:\n output += generate_output(line=str((int(line) + 1)), value=item, colorize=colorize)\n return output", "docstring": "The function for generating CLI output RDAP list results.\n\nArgs:\n source (:obj:`str`): The parent key 'network' or 'objects'\n (required).\n key (:obj:`str`): The event key 'events' or 'events_actor'\n (required).\n val (:obj:`dict`): The event dictionary (required).\n line (:obj:`str`): The line number (0-4). Determines indentation.\n Defaults to '0'.\n hr (:obj:`bool`): Enable human readable key translations. Defaults\n to True.\n show_name (:obj:`bool`): Show human readable name (default is to\n only show short). Defaults to False.\n colorize (:obj:`bool`): Colorize the console output with ANSI\n colors. Defaults to True.\n\nReturns:\n str: The generated output.", "source": "codesearchnet_filtered"} +{"code": "def read(cls, five9, external_id):\n results = cls.search(five9, {cls.__uid_field__: external_id})\n if (not results):\n return None\n return results[0]", "docstring": "Return a record singleton for the ID.\n\nArgs:\n five9 (five9.Five9): The authenticated Five9 remote.\n external_id (mixed): The identified on Five9. This should be the\n value that is in the ``__uid_field__`` field on the record.\n\nReturns:\n BaseModel: The record, if found. Otherwise ``None``", "source": "codesearchnet_filtered"} +{"code": "def LoadFromFile(cls, script_path):\n (_name, dev) = ComponentRegistry().load_extension(script_path, class_filter=VirtualTile, unique=True)\n return dev", "docstring": "Import a virtual tile from a file rather than an installed module\n\n script_path must point to a python file ending in .py that contains exactly one\n VirtualTile class definition. That class is loaded and executed as if it\n were installed.\n\n To facilitate development, if there is a proxy object defined in the same\n file, it is also added to the HardwareManager proxy registry so that it\n can be found and used with the device.\n\nArgs:\n script_path (string): The path to the script to load\n\nReturns:\n VirtualTile: A subclass of VirtualTile that was loaded from script_path", "source": "codesearchnet_filtered"} +{"code": "def set_number_of_atoms(self, n, selected_sites=None):\n self.number_of_atoms = n\n self.atoms = species.Species(self.lattice.populate_sites(self.number_of_atoms, selected_sites=selected_sites))", "docstring": "Set the number of atoms for the simulation, and populate the simulation lattice.\n\nArgs:\n n (Int): Number of atoms for this simulation.\n selected_sites (:obj:(List|Set|String), optional): Selects a subset of site types to be populated with atoms. Defaults to None.\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def _get_required_fn(fn, root_path):\n if (not fn.startswith(root_path)):\n raise ValueError('Both paths have to be absolute or local!')\n replacer = ('/' if root_path.endswith('/') else '')\n return fn.replace(root_path, replacer, 1)", "docstring": "Definition of the MD5 file requires, that all paths will be absolute\n for the package directory, not for the filesystem.\n\n This function converts filesystem-absolute paths to package-absolute paths.\n\nArgs:\n fn (str): Local/absolute path to the file.\n root_path (str): Local/absolute path to the package directory.\n\nReturns:\n str: Package-absolute path to the file.\n\nRaises:\n ValueError: When `fn` is absolute and `root_path` relative or \\\n conversely.", "source": "codesearchnet_filtered"} +{"code": "def DistFitDataset(Dat):\n (r, c) = Dat.shape\n Poiss = np.zeros(r)\n Norm = np.zeros(r)\n LogNorm = np.zeros(r)\n for i in range(r):\n temp = GetDistFitError(Dat[i])\n Poiss[i] = temp['poiss']\n Norm[i] = temp['norm']\n LogNorm[i] = temp['lognorm']\n d = {}\n d['poiss'] = Poiss\n d['norm'] = Norm\n d['lognorm'] = LogNorm\n return d", "docstring": "Given a data matrix, this returns the per-gene fit error for the\n Poisson, Normal, and Log-Normal distributions.\n\nArgs:\n Dat (array): numpy array with shape (genes, cells)\n\nReturns:\n d (dict): 'poiss', 'norm', 'lognorm' give the fit error for each distribution.", "source": "codesearchnet_filtered"} +{"code": "def assignSeasonSchedule(self, season, month, day, schedule):\n season += 1\n schedule += 1\n if ((season < 1) or (season > Extents.Seasons) or (schedule < 1) or (schedule > Extents.Schedules) or (month > 12) or (month < 0) or (day < 0) or (day > 31)):\n ekm_log(((((((('Out of bounds: month ' + str(month)) + ' day ') + str(day)) + ' schedule ') + str(schedule)) + ' season ') + str(season)))\n return False\n idx_mon = (('Season_' + str(season)) + '_Start_Day')\n idx_day = (('Season_' + str(season)) + '_Start_Month')\n idx_schedule = (('Season_' + str(season)) + '_Schedule')\n if (idx_mon not in self.m_seasons_sched_params):\n ekm_log(('Incorrect index: ' + idx_mon))\n return False\n if (idx_day not in self.m_seasons_sched_params):\n ekm_log(('Incorrect index: ' + idx_day))\n return False\n if (idx_schedule not in self.m_seasons_sched_params):\n ekm_log(('Incorrect index: ' + idx_schedule))\n return False\n self.m_seasons_sched_params[idx_mon] = month\n self.m_seasons_sched_params[idx_day] = day\n self.m_seasons_sched_params[idx_schedule] = schedule\n return True", "docstring": "Define a single season and assign a schedule\n\nArgs:\n season (int): A :class:`~ekmmeters.Seasons` value or in range(Extent.Seasons).\n month (int): Month 1-12.\n day (int): Day 1-31.\n schedule (int): A :class:`~ekmmeters.LCDItems` value or in range(Extent.Schedules).\n\nReturns:\n bool: True on completion and ACK.", "source": "codesearchnet_filtered"} +{"code": "def prepare_read(data, method='readlines', mode='r'):\n if hasattr(data, 'readlines'):\n data = getattr(data, method)()\n elif isinstance(data, list):\n if (method == 'read'):\n return ''.join(data)\n elif isinstance(data, basestring):\n data = getattr(open(data, mode), method)()\n else:\n raise TypeError(('Unable to handle data of type %r' % type(data)))\n return data", "docstring": "Prepare various input types for parsing.\n\nArgs:\n data (iter): Data to read\n method (str): Method to process data with\n mode (str): Custom mode to process with, if data is a file\n\nReturns:\n list: List suitable for parsing\n\nRaises:\n TypeError: Invalid value for data", "source": "codesearchnet_filtered"} +{"code": "def get_filtered_vts_list(self, vts, vt_filter):\n if (not vt_filter):\n raise RequiredArgument('vt_filter: A valid filter is required.')\n filters = self.parse_filters(vt_filter)\n if (not filters):\n return None\n _vts_aux = vts.copy()\n for (_element, _oper, _filter_val) in filters:\n for vt_id in _vts_aux.copy():\n if (not _vts_aux[vt_id].get(_element)):\n _vts_aux.pop(vt_id)\n continue\n _elem_val = _vts_aux[vt_id].get(_element)\n _val = self.format_filter_value(_element, _elem_val)\n if self.filter_operator[_oper](_val, _filter_val):\n continue\n else:\n _vts_aux.pop(vt_id)\n return _vts_aux", "docstring": "Gets a collection of vulnerability test from the vts dictionary,\n which match the filter.\n\nArgs:\n vt_filter (string): Filter to apply to the vts collection.\n vts (dictionary): The complete vts collection.\n\nReturns:\n Dictionary with filtered vulnerability tests.", "source": "codesearchnet_filtered"} +{"code": "def get_student_current_grades(self, username, course_ids=None):\n if (course_ids is None):\n enrollments_client = CourseEnrollments(self.requester, self.base_url)\n enrollments = enrollments_client.get_student_enrollments()\n course_ids = list(enrollments.get_enrolled_course_ids())\n all_current_grades = []\n for course_id in course_ids:\n try:\n all_current_grades.append(self.get_student_current_grade(username, course_id))\n except HTTPError as error:\n if (error.response.status_code >= 500):\n raise\n return CurrentGradesByUser(all_current_grades)", "docstring": "Returns a CurrentGradesByUser object with the user current grades.\n\nArgs:\n username (str): an edx user's username\n course_ids (list): a list of edX course ids.\n\nReturns:\n CurrentGradesByUser: object representing the student current grades", "source": "codesearchnet_filtered"} +{"code": "def get_all_anonymous_mappings(self, struct1, struct2, niggli=True, include_dist=False):\n (struct1, struct2) = self._process_species([struct1, struct2])\n (struct1, struct2, fu, s1_supercell) = self._preprocess(struct1, struct2, niggli)\n matches = self._anonymous_match(struct1, struct2, fu, s1_supercell, break_on_match=(not include_dist))\n if matches:\n if include_dist:\n return [(m[0], m[1][0]) for m in matches]\n else:\n return [m[0] for m in matches]", "docstring": "Performs an anonymous fitting, which allows distinct species in one\n structure to map to another. Returns a dictionary of species\n substitutions that are within tolerance\n\nArgs:\n struct1 (Structure): 1st structure\n struct2 (Structure): 2nd structure\n niggli (bool): Find niggli cell in preprocessing\n include_dist (bool): Return the maximin distance with each mapping\n\nReturns:\n list of species mappings that map struct1 to struct2.", "source": "codesearchnet_filtered"} +{"code": "def split_identifiers(identifiers=[], proportions={}):\n abs_proportions = absolute_proportions(proportions, len(identifiers))\n parts = {}\n start_index = 0\n for (idx, proportion) in abs_proportions.items():\n parts[idx] = identifiers[start_index:(start_index + proportion)]\n start_index += proportion\n return parts", "docstring": "Split the given identifiers by the given proportions.\n\nArgs:\n identifiers (list): List of identifiers (str).\n proportions (dict): A dictionary containing the proportions with the identifier from the\n input as key.\n\nReturns:\n dict: Dictionary containing a list of identifiers per part with the same key as the\n proportions dict.\n\n Example::\n\n >>> split_identifiers(\n >>> identifiers=['a', 'b', 'c', 'd'],\n >>> proportions={'melvin' : 0.5, 'timmy' : 0.5}\n >>> )\n {'melvin' : ['a', 'c'], 'timmy' : ['b', 'd']}", "source": "codesearchnet_filtered"} +{"code": "def set_peer_address(self, value=None, default=False, disable=False):\n return self._configure_mlag('peer-address', value, default, disable)", "docstring": "Configures the mlag peer-address value\n\nArgs:\n value (str): The value to configure the peer-address\n default (bool): Configures the peer-address using the\n default keyword\n disable (bool): Negates the peer-address using the no keyword\n\nReturns:\n bool: Returns True if the commands complete successfully", "source": "codesearchnet_filtered"} +{"code": "def get_signed_url(self, file_id):\n if (not is_valid_uuid(file_id)):\n raise StorageArgumentException('Invalid UUID for file_id: {0}'.format(file_id))\n return self._authenticated_request.to_endpoint('file/{}/content/secure_link/'.format(file_id)).return_body().get()['signed_url']", "docstring": "Get a signed unauthenticated URL.\n\n It can be used to download the file content without the need for a\n token. The signed URL expires after 5 seconds.\n\nArgs:\n file_id (str): The UUID of the file to get the link for.\n\nReturns:\n The signed url as a string\n\nRaises:\n StorageArgumentException: Invalid arguments\n StorageForbiddenException: Server response code 403\n StorageNotFoundException: Server response code 404\n StorageException: other 400-600 error codes", "source": "codesearchnet_filtered"} +{"code": "def gridsearch_timer(func_list, args_list, niters=None, **searchkw):\n import utool as ut\n timings = ut.ddict(list)\n if (niters is None):\n niters = len(args_list)\n if ut.is_funclike(args_list):\n get_args = args_list\n else:\n get_args = args_list.__getitem__\n func_labels = searchkw.get('func_labels', [ut.get_funcname(func) for func in func_list])\n use_cache = searchkw.get('use_cache', (not ut.get_argflag(('--nocache', '--nocache-time'))))\n assert_eq = searchkw.get('assert_eq', True)\n count_list = list(range(niters))\n xlabel_list = []\n cache = ut.ShelfCacher('timeings.shelf', enabled=use_cache)\n for count in ut.ProgressIter(count_list, lbl='Testing Timeings'):\n args_ = get_args(count)\n xlabel_list.append(args_)\n if True:\n if (not isinstance(args_, tuple)):\n args_ = (args_,)\n assert isinstance(args_, tuple), 'args_ should be a tuple so it can be unpacked'\n ret_list = []\n for func_ in func_list:\n try:\n kwargs_ = {}\n func_cachekey = ut.get_func_result_cachekey(func_, args_, kwargs_)\n ellapsed = cache.load(func_cachekey)\n except ut.CacheMissException:\n with ut.Timer(verbose=False) as t:\n ret = func_(*args_)\n ret_list.append(ret)\n ellapsed = t.ellapsed\n cache.save(func_cachekey, ellapsed)\n timings[func_].append(ellapsed)\n if assert_eq:\n ut.assert_all_eq(list(map(ut.cachestr_repr, ret_list)))\n cache.close()\n count_to_xtick = searchkw.get('count_to_xtick', (lambda x, y: x))\n xtick_list = [count_to_xtick(count, get_args(count)) for count in count_list]\n\n def plot_timings():\n import plottool as pt\n ydata_list = ut.dict_take(timings, func_list)\n xdata = xtick_list\n ylabel = 'seconds'\n xlabel = 'input size'\n pt.multi_plot(xdata, ydata_list, label_list=func_labels, ylabel=ylabel, xlabel=xlabel, **searchkw)\n time_result = {'plot_timings': plot_timings, 'timings': timings}\n return time_result", "docstring": "Times a series of functions on a series of inputs\n\n args_list is a list should vary the input sizes\n can also be a func that take a count param\n\n items in args_list list or returned by the func should be a tuple so it can be\n unpacked\n\n CommandLine:\n python -m ibeis.annotmatch_funcs --exec-get_annotmatch_rowids_from_aid2 --show\n python -m ibeis.annotmatch_funcs --exec-get_annotmatch_rowids_from_aid:1 --show\n\nArgs:\n func_list (list):\n args_list (list):\n niters (None): (default = None)\n\nReturns:\n dict: time_result\n\n CommandLine:\n python -m utool.util_gridsearch --exec-gridsearch_timer --show\n\nExample:\n >>> # DISABLE_DOCTEST\n >>> from utool.util_gridsearch import * # NOQA\n >>> import utool as ut\n >>> func_list = [ut.fibonacci_recursive, ut.fibonacci_iterative]\n >>> args_list = list(range(1, 35))\n >>> niters = None\n >>> searchkw = {}\n >>> time_result = gridsearch_timer(func_list, args_list, niters, **searchkw)\n >>> result = ('time_result = %s' % (six.text_type(time_result),))\n >>> print(result)\n >>> time_result['plot_timings']()\n >>> ut.show_if_requested()", "source": "codesearchnet_filtered"} +{"code": "def VerifyStructure(self, parser_mediator, line):\n try:\n structure = self._DPKG_LOG_LINE.parseString(line)\n except pyparsing.ParseException as exception:\n logger.debug('Unable to parse Debian dpkg.log file with error: {0!s}'.format(exception))\n return False\n return (('date_time' in structure) and ('body' in structure))", "docstring": "Verifies if a line from a text file is in the expected format.\n\nArgs:\n parser_mediator (ParserMediator): parser mediator.\n line (str): line from a text file.\n\nReturns:\n bool: True if the line is in the expected format, False if not.", "source": "codesearchnet_filtered"} +{"code": "def do_youtube_dl(worker, site, page):\n with tempfile.TemporaryDirectory(prefix='brzl-ydl-') as tempdir:\n ydl = _build_youtube_dl(worker, tempdir, site)\n ie_result = _try_youtube_dl(worker, ydl, site, page)\n outlinks = set()\n if (ie_result and (ie_result.get('extractor') == 'youtube:playlist')):\n outlinks = {('https://www.youtube.com/watch?v=%s' % e['id']) for e in ie_result.get('entries_no_dl', [])}\n return (ydl.fetch_spy.fetches, outlinks)", "docstring": "Runs youtube-dl configured for `worker` and `site` to download videos from\n `page`.\n\nArgs:\n worker (brozzler.BrozzlerWorker): the calling brozzler worker\n site (brozzler.Site): the site we are brozzling\n page (brozzler.Page): the page we are brozzling\n\nReturns:\n tuple with two entries:\n `list` of `dict`: with info about urls fetched:\n [{\n 'url': ...,\n 'method': ...,\n 'response_code': ...,\n 'response_headers': ...,\n }, ...]\n `list` of `str`: outlink urls", "source": "codesearchnet_filtered"} +{"code": "def compile(self, target_instance_family, input_shape, output_path, role, tags=None, job_name=None, compile_max_run=(5 * 60), framework=None, framework_version=None):\n framework = (self._framework() or framework)\n if (framework is None):\n raise ValueError('You must specify framework, allowed values {}'.format(NEO_ALLOWED_FRAMEWORKS))\n if (framework not in NEO_ALLOWED_FRAMEWORKS):\n raise ValueError('You must provide valid framework, allowed values {}'.format(NEO_ALLOWED_FRAMEWORKS))\n if (job_name is None):\n raise ValueError('You must provide a compilation job name')\n framework = framework.upper()\n framework_version = (self._get_framework_version() or framework_version)\n config = self._compilation_job_config(target_instance_family, input_shape, output_path, role, compile_max_run, job_name, framework, tags)\n self.sagemaker_session.compile_model(**config)\n job_status = self.sagemaker_session.wait_for_compilation_job(job_name)\n self.model_data = job_status['ModelArtifacts']['S3ModelArtifacts']\n if target_instance_family.startswith('ml_'):\n self.image = self._neo_image(self.sagemaker_session.boto_region_name, target_instance_family, framework, framework_version)\n self._is_compiled_model = True\n else:\n LOGGER.warning('The intance type {} is not supported to deploy via SageMaker,please deploy the model on the device by yourself.'.format(target_instance_family))\n return self", "docstring": "Compile this ``Model`` with SageMaker Neo.\n\nArgs:\n target_instance_family (str): Identifies the device that you want to run your model after compilation, for\n example: ml_c5. Allowed strings are: ml_c5, ml_m5, ml_c4, ml_m4, jetsontx1, jetsontx2, ml_p2, ml_p3,\n deeplens, rasp3b\n input_shape (dict): Specifies the name and shape of the expected inputs for your trained model in json\n dictionary form, for example: {'data':[1,3,1024,1024]}, or {'var1': [1,1,28,28], 'var2':[1,1,28,28]}\n output_path (str): Specifies where to store the compiled model\n role (str): Execution role\n tags (list[dict]): List of tags for labeling a compilation job. For more, see\n https://docs.aws.amazon.com/sagemaker/latest/dg/API_Tag.html.\n job_name (str): The name of the compilation job\n compile_max_run (int): Timeout in seconds for compilation (default: 3 * 60).\n After this amount of time Amazon SageMaker Neo terminates the compilation job regardless of its\n current status.\n framework (str): The framework that is used to train the original model. Allowed values: 'mxnet',\n 'tensorflow', 'pytorch', 'onnx', 'xgboost'\n framework_version (str)\n\nReturns:\n sagemaker.model.Model: A SageMaker ``Model`` object. See :func:`~sagemaker.model.Model` for full details.", "source": "codesearchnet_filtered"} +{"code": "def shannon_entropy(pvec, base=2):\n if (base == 2):\n\n def logfn(x):\n return ((- x) * np.log2(x))\n elif (base == np.e):\n\n def logfn(x):\n return ((- x) * np.log(x))\n else:\n\n def logfn(x):\n return (((- x) * np.log(x)) / np.log(base))\n h = 0.0\n for x in pvec:\n if (0 < x < 1):\n h += logfn(x)\n return h", "docstring": "Compute the Shannon entropy of a probability vector.\n\n The shannon entropy of a probability vector pv is defined as\n $H(pv) = - \\\\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$.\n\nArgs:\n pvec (array_like): a probability vector.\n base (int): the base of the logarith\n\nReturns:\n float: The Shannon entropy H(pvec).", "source": "codesearchnet_filtered"} +{"code": "def create_folder(self, name, parent):\n if (not is_valid_uuid(parent)):\n raise StorageArgumentException('Invalid UUID for parent: {0}'.format(parent))\n return self._authenticated_request.to_endpoint('folder/').with_json_body(self._prep_params(locals())).return_body().post()", "docstring": "Create a new folder.\n\nArgs:\n name (srt): The name of the folder.\n parent (str): The UUID of the parent entity. The parent must be a\n project or a folder.\n\nReturns:\n A dictionary of details of the created folder::\n\n {\n u'created_by': u'303447',\n u'created_on': u'2017-03-21T14:06:32.293902Z',\n u'description': u'',\n u'entity_type': u'folder',\n u'modified_by': u'303447',\n u'modified_on': u'2017-03-21T14:06:32.293967Z',\n u'name': u'myfolder',\n u'parent': u'3abd8742-d069-44cf-a66b-2370df74a682',\n u'uuid': u'2516442e-1e26-4de1-8ed8-94523224cc40'\n }\n\nRaises:\n StorageArgumentException: Invalid arguments\n StorageForbiddenException: Server response code 403\n StorageNotFoundException: Server response code 404\n StorageException: other 400-600 error codes", "source": "codesearchnet_filtered"} +{"code": "def has_request(self, request):\n queue_item = QueueItem(request, Response(request.url))\n key = queue_item.get_hash()\n for status in QueueItem.STATUSES:\n if (key in self.__get_var(('items_' + status)).keys()):\n return True\n return False", "docstring": "Check if the given request already exists in the queue.\n\nArgs:\n request (:class:`nyawc.http.Request`): The request to check.\n\nReturns:\n bool: True if already exists, False otherwise.", "source": "codesearchnet_filtered"} +{"code": "def convert(isbn, code='978'):\n isbn = _isbn_cleanse(isbn)\n if (len(isbn) == 10):\n isbn = (code + isbn[:(- 1)])\n return (isbn + calculate_checksum(isbn))\n elif isbn.startswith('978'):\n return (isbn[3:(- 1)] + calculate_checksum(isbn[3:(- 1)]))\n else:\n raise IsbnError('Only ISBN-13s with 978 Bookland code can be converted to ISBN-10.')", "docstring": "Convert ISBNs between ISBN-10 and ISBN-13.\n\nNote:\n No attempt to hyphenate converted ISBNs is made, because the\n specification requires that *any* hyphenation must be correct but\n allows ISBNs without hyphenation.\n\nArgs:\n isbn (str): SBN, ISBN-10 or ISBN-13\n code (str): EAN Bookland code\n\nReturns:\n ``str``: Converted ISBN-10 or ISBN-13\n\nRaises:\n IsbnError: When ISBN-13 isn't convertible to an ISBN-10", "source": "codesearchnet_filtered"} +{"code": "def get_region(b):\n remap = {None: 'us-east-1', 'EU': 'eu-west-1'}\n region = b.get('Location', {}).get('LocationConstraint')\n return remap.get(region, region)", "docstring": "Tries to get the bucket region from Location.LocationConstraint\n\n Special cases:\n LocationConstraint EU defaults to eu-west-1\n LocationConstraint null defaults to us-east-1\n\nArgs:\n b (object): A bucket object\n\nReturns:\n string: an aws region string", "source": "codesearchnet_filtered"} +{"code": "def pipeline_status(url, pipeline_id, auth, verify_ssl):\n status_result = requests.get((((url + '/') + pipeline_id) + '/status'), headers=X_REQ_BY, auth=auth, verify=verify_ssl)\n status_result.raise_for_status()\n logging.debug((('Status request: ' + url) + '/status'))\n logging.debug(status_result.json())\n return status_result.json()", "docstring": "Retrieve the current status for a pipeline.\n\nArgs:\n url (str): the host url in the form 'http://host:port/'.\n pipeline_id (str): the ID of of the exported pipeline.\n auth (tuple): a tuple of username, and password.\n verify_ssl (bool): whether to verify ssl certificates\n\nReturns:\n dict: the response json", "source": "codesearchnet_filtered"} +{"code": "def exception(self, timeout=None):\n if (not self._completed.wait(timeout=timeout)):\n raise exceptions.TimeoutError('Timed out waiting for result.')\n if (self._result != self._SENTINEL):\n return None\n return self._exception", "docstring": "Return the exception raised by the call, if any.\n\n This blocks until the message has successfully been published, and\n returns the exception. If the call succeeded, return None.\n\nArgs:\n timeout (Union[int, float]): The number of seconds before this call\n times out and raises TimeoutError.\n\nRaises:\n TimeoutError: If the request times out.\n\nReturns:\n Exception: The exception raised by the call, if any.", "source": "codesearchnet_filtered"} +{"code": "def create(self, resource, timeout=(- 1)):\n return self._client.create(resource, timeout=timeout, default_values=self.DEFAULT_VALUES)", "docstring": "Creates a scope.\n\nArgs:\n resource (dict): Object to create.\n timeout:\n Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n in OneView, just stop waiting for its completion.\n\nReturns:\n dict: Created scope.", "source": "codesearchnet_filtered"} +{"code": "def apply_func_to_find_bin(func: Union[(None, Callable[(..., Union[(float, int, Any)])])], values: Optional[float]=None) -> Callable[([Any], Union[(float, int)])]:\n\n def return_func(axis) -> Any:\n ' Apply the stored function and value to a given axis.\\n\\n Args:\\n axis (TAxis or similar): Axis to which the function should be applied.\\n Returns:\\n any: The value returned by the function. Often a float or int, but not necessarily.\\n '\n if func:\n if (values is not None):\n return func(axis, values)\n else:\n return func(axis)\n else:\n return values\n return return_func", "docstring": "Closure to determine the bin associated with a value on an axis.\n\n It can apply a function to an axis if necessary to determine the proper bin. Otherwise,\n it can just return a stored value.\n\nNote:\n To properly determine the value, carefully note the information below. In many cases,\n such as when we want values [2, 5), the values need to be shifted by a small epsilon\n to retrieve the proper bin. This is done automatically in ``SetRangeUser()``.\n\n >>> hist = ROOT.TH1D(\"test\", \"test\", 10, 0, 10)\n >>> x = 2, y = 5\n >>> hist.FindBin(x)\n 2\n >>> hist.FindBin(x+epsilon)\n 2\n >>> hist.FindBin(y)\n 6\n >>> hist.FindBin(y-epsilon)\n 5\n\n Note that the bin + epsilon on the lower bin is not strictly necessary, but it is\n used for consistency with the upper bound.\n\nArgs:\n func (Callable): Function to apply to the histogram axis. If it is None, the value\n will be returned.\n values (int or float): Value to pass to the function. Default: None (in which case,\n it won't be passed).\n\nReturns:\n Function to be called with an axis to determine the desired bin on that axis.", "source": "codesearchnet_filtered"} +{"code": "def load_and_run_pipeline(pipeline_name, pipeline_context_input=None, working_dir=None, context=None, parse_input=True, loader=None):\n logger.debug(f'you asked to run pipeline: {pipeline_name}')\n if loader:\n logger.debug(f'you set the pype loader to: {loader}')\n else:\n loader = 'pypyr.pypeloaders.fileloader'\n logger.debug(f'use default pype loader: {loader}')\n logger.debug(f'you set the initial context to: {pipeline_context_input}')\n if (context is None):\n context = pypyr.context.Context()\n context.working_dir = working_dir\n else:\n working_dir = context.working_dir\n loader_module = pypyr.moduleloader.get_module(loader)\n try:\n get_pipeline_definition = getattr(loader_module, 'get_pipeline_definition')\n except AttributeError:\n logger.error(f\"The pipeline loader {loader_module} doesn't have a get_pipeline_definition(pipeline_name, working_dir) function.\")\n raise\n logger.debug(f'loading the pipeline definition with {loader_module}')\n pipeline_definition = get_pipeline_definition(pipeline_name=pipeline_name, working_dir=working_dir)\n logger.debug(f'{loader_module} done')\n run_pipeline(pipeline=pipeline_definition, pipeline_context_input=pipeline_context_input, context=context, parse_input=parse_input)", "docstring": "Load and run the specified pypyr pipeline.\n\n This function runs the actual pipeline by name. If you are running another\n pipeline from within a pipeline, call this, not main(). Do call main()\n instead for your 1st pipeline if there are pipelines calling pipelines.\n\n By default pypyr uses file loader. This means that pipeline_name.yaml\n should be in the working_dir/pipelines/ directory.\n\nArgs:\n pipeline_name (str): Name of pipeline, sans .yaml at end.\n pipeline_context_input (str): Initialize the pypyr context with this\n string.\n working_dir (path): Look for pipelines and modules in this directory.\n If context arg passed, will use context.working_dir and\n ignore this argument. If context is None, working_dir\n must be specified.\n context (pypyr.context.Context): Use if you already have a\n Context object, such as if you are running a pipeline from\n within a pipeline and you want to re-use the same context\n object for the child pipeline. Any mutations of the context by\n the pipeline will be against this instance of it.\n parse_input (bool): run context_parser in pipeline.\n loader (str): str. optional. Absolute name of pipeline loader module.\n If not specified will use pypyr.pypeloaders.fileloader.\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def transform_absolute_coords(self, width, height):\n if (self.type != EventType.POINTER_MOTION_ABSOLUTE):\n raise AttributeError(_wrong_meth.format(self.type))\n abs_x = self._libinput.libinput_event_pointer_get_absolute_x_transformed(self._handle, width)\n abs_y = self._libinput.libinput_event_pointer_get_absolute_y_transformed(self._handle, height)\n return (abs_x, abs_y)", "docstring": "Return the current absolute coordinates of the pointer event,\n transformed to screen coordinates.\n\n For pointer events that are not of type\n :attr:`~libinput.constant.EventType.POINTER_MOTION_ABSOLUTE`,\n this method raises :exc:`AttributeError`.\n\nArgs:\n width (int): The current output screen width.\n height (int): The current output screen height.\n\nReturns:\n (float, float): The current absolute (x, y) coordinates transformed\n to a screen coordinates.\n\nRaises:\n AttributeError", "source": "codesearchnet_filtered"} +{"code": "def _get_elements(self, url, key, eclass, id=None, name=None):\n if ((id is not None) and (name is not None)):\n raise ValueError('id and name cannot specified together')\n json_elements = self.rest_client.make_request(url)[key]\n return [eclass(element, self.rest_client) for element in json_elements if (_exact_resource(element, id) and _matching_resource(element, name))]", "docstring": "Get elements matching `id` or `name`\n\nArgs:\n url(str): url of children.\n key(str): key in the returned JSON.\n eclass(subclass type of :py:class:`_ResourceElement`): element class to create instances of.\n id(str, optional): only return resources whose `id` property matches the given `id`\n name(str, optional): only return resources whose `name` property matches the given `name`\n\nReturns:\n list(_ResourceElement): List of `eclass` instances\n\nRaises:\n ValueError: both `id` and `name` are specified together", "source": "codesearchnet_filtered"} +{"code": "def icon_description(self, **kwargs):\n params = {'language': util.language_code(kwargs.get('lang'))}\n result = self.make_request('icon_description', {}, **params)\n if (not util.check_result(result)):\n return (False, result.get('message', 'UNKNOWN ERROR'))\n values = util.response_list(result, 'Data')\n return (True, [emtype.IconDescription(**a) for a in values])", "docstring": "Obtain a list of elements that have an associated icon.\n\nArgs:\n lang (str): Language code (*es* or *en*).\n\nReturns:\n Status boolean and parsed response (list[IconDescription]), or\n message string in case of error.", "source": "codesearchnet_filtered"} +{"code": "def convert_idx_to_name(self, y, lens):\n y = [[self.id2label[idx] for idx in row[:l]] for (row, l) in zip(y, lens)]\n return y", "docstring": "Convert label index to name.\n\nArgs:\n y (list): label index list.\n lens (list): true length of y.\n\nReturns:\n y: label name list.\n\nExample:\n >>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'}\n >>> y = [[1, 0, 0], [1, 2, 0], [1, 1, 1]]\n >>> lens = [1, 2, 3]\n >>> self.convert_idx_to_name(y, lens)\n [['B-LOC'], ['B-LOC', 'I-LOC'], ['B-LOC', 'B-LOC', 'B-LOC']]", "source": "codesearchnet_filtered"} +{"code": "def extract_changelog_items(text, tags):\n patterns = {x['header']: tag_re(x['tag']) for x in tags}\n items = {x['header']: [] for x in tags}\n curr_tag = None\n curr_text = ''\n for line in text.splitlines():\n if (not line.strip()):\n if (curr_tag is not None):\n items[curr_tag].append(curr_text)\n curr_text = ''\n curr_tag = None\n for tag in tags:\n m = patterns[tag['header']].match(line)\n if m:\n if (curr_tag is not None):\n items[curr_tag].append(curr_text)\n curr_text = ''\n curr_tag = tag['header']\n line = m.group('text')\n break\n if (curr_tag is not None):\n curr_text = '{} {}'.format(curr_text.strip(), line.strip()).strip()\n if (curr_tag is not None):\n items[curr_tag].append(curr_text)\n return items", "docstring": "Extract all tagged items from text.\n\nArgs:\n text (str):\n Text to extract the tagged items from. Each tagged item is a\n paragraph that starts with a tag. It can also be a text list item.\n\nReturns:\n tuple[list[str], list[str], list[str]]:\n A tuple of `(features, changes, fixes)` extracted from the given\n text.\n\n The tagged items are usually features/changes/fixes but it can be configured\n through `pelconf.yaml`.", "source": "codesearchnet_filtered"} +{"code": "def extract_paths(disk_path, disk_root, paths, ignore_nopath):\n with guestfs_conn_mount_ro(disk_path, disk_root) as conn:\n for (guest_path, host_path) in paths:\n msg = 'Extracting guestfs://{0} to {1}'.format(guest_path, host_path)\n LOGGER.debug(msg)\n try:\n _copy_path(conn, guest_path, host_path)\n except ExtractPathNoPathError as err:\n if ignore_nopath:\n LOGGER.debug('%s - ignoring', err)\n else:\n raise", "docstring": "Extract paths from a disk using guestfs\n\nArgs:\n disk_path(str): path to the disk\n disk_root(str): root partition\n paths(list of tuples): files to extract in\n `[(src1, dst1), (src2, dst2)...]` format, if ``srcN`` is a\n directory in the guest, and ``dstN`` does not exist on the host,\n it will be created. If ``srcN`` is a file on the guest, it will be\n copied exactly to ``dstN``\n ignore_nopath(bool): If set to True, ignore paths in the guest that\n do not exit\n\nReturns:\n None\n\nRaises:\n :exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing\n path was found on the guest, and `ignore_nopath` is False.\n :exc:`~lago.plugins.vm.ExtractPathError`: on all other failures.", "source": "codesearchnet_filtered"} +{"code": "def get_link_or_none(pattern_name, request, view_kwargs=None):\n from is_core.patterns import reverse_pattern\n pattern = reverse_pattern(pattern_name)\n assert (pattern is not None), 'Invalid pattern name {}'.format(pattern_name)\n if pattern.has_permission('get', request, view_kwargs=view_kwargs):\n return pattern.get_url_string(request, view_kwargs=view_kwargs)\n else:\n return None", "docstring": "Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.\n If not None is returned.\n\nArgs:\n pattern_name (str): slug which is used for view registratin to pattern\n request (django.http.request.HttpRequest): Django request object\n view_kwargs (dict): list of kwargs necessary for URL generator\n\n Returns:", "source": "codesearchnet_filtered"} +{"code": "def to_url(self, site='amazon', country='us'):\n try:\n try:\n (url, tlds) = URL_MAP[site]\n except ValueError:\n tlds = None\n url = URL_MAP[site]\n except KeyError:\n raise SiteError(site)\n inject = {'isbn': self._isbn}\n if tlds:\n if (country not in tlds):\n raise CountryError(country)\n tld = tlds[country]\n if (not tld):\n tld = country\n inject['tld'] = tld\n return (url % inject)", "docstring": "Generate a link to an online book site.\n\nArgs:\n site (str): Site to create link to\n country (str): Country specific version of ``site``\n\nReturns:\n ``str``: URL on ``site`` for book\n\nRaises:\n SiteError: Unknown site value\n CountryError: Unknown country value", "source": "codesearchnet_filtered"} +{"code": "def set(self, context_id, address_value_list):\n if (context_id not in self._contexts):\n LOGGER.warning('Context_id not in contexts, %s', context_id)\n return False\n context = self._contexts.get(context_id)\n add_value_dict = {}\n for d in address_value_list:\n for (add, val) in d.items():\n if (not self.address_is_valid(address=add)):\n raise AuthorizationException(address=add)\n add_value_dict[add] = val\n context.set_direct(add_value_dict)\n return True", "docstring": "Within a context, sets addresses to a value.\n\nArgs:\n context_id (str): the context id returned by create_context\n address_value_list (list): list of {address: value} dicts\n\nReturns:\n (bool): True if the operation is successful, False if\n the context_id doesn't reference a known context.\n\nRaises:\n AuthorizationException if an address is given in the\n address_value_list that was not in the original\n transaction's outputs, or was under a namespace but the\n characters after the namespace are not valid address\n characters.", "source": "codesearchnet_filtered"} +{"code": "def GetPluginObjectByName(cls, plugin_name):\n plugin_class = cls._plugin_classes.get(plugin_name, None)\n if plugin_class:\n return plugin_class()\n return None", "docstring": "Retrieves a specific plugin object by its name.\n\nArgs:\n plugin_name (str): name of the plugin.\n\nReturns:\n BasePlugin: a plugin object or None if not available.", "source": "codesearchnet_filtered"} +{"code": "def _GetRecordValue(self, record, value_entry):\n column_type = record.get_column_type(value_entry)\n long_value = None\n if record.is_long_value(value_entry):\n long_value = record.get_value_data_as_long_value(value_entry)\n if record.is_multi_value(value_entry):\n raise ValueError('Multi value support not implemented yet.')\n if (column_type == pyesedb.column_types.NULL):\n return None\n if (column_type == pyesedb.column_types.BOOLEAN):\n raise ValueError('Boolean value support not implemented yet.')\n if (column_type in self.INTEGER_COLUMN_TYPES):\n if long_value:\n raise ValueError('Long integer value not supported.')\n return record.get_value_data_as_integer(value_entry)\n if (column_type in self.FLOATING_POINT_COLUMN_TYPES):\n if long_value:\n raise ValueError('Long floating point value not supported.')\n return record.get_value_data_as_floating_point(value_entry)\n if (column_type in self.STRING_COLUMN_TYPES):\n if long_value:\n return long_value.get_data_as_string()\n return record.get_value_data_as_string(value_entry)\n if (column_type == pyesedb.column_types.GUID):\n raise ValueError('GUID value support not implemented yet.')\n if long_value:\n return long_value.get_data()\n return record.get_value_data(value_entry)", "docstring": "Retrieves a specific value from the record.\n\nArgs:\n record (pyesedb.record): ESE record.\n value_entry (int): value entry.\n\nReturns:\n object: value.\n\nRaises:\n ValueError: if the value is not supported.", "source": "codesearchnet_filtered"} +{"code": "def _read_metrics(repo, metrics, branch):\n res = {}\n for (out, typ, xpath) in metrics:\n assert (out.scheme == 'local')\n if (not typ):\n typ = os.path.splitext(out.path.lower())[1].replace('.', '')\n if out.use_cache:\n open_fun = open\n path = repo.cache.local.get(out.checksum)\n else:\n open_fun = repo.tree.open\n path = out.path\n try:\n with open_fun(path) as fd:\n metric = _read_metric(fd, typ=typ, xpath=xpath, rel_path=out.rel_path, branch=branch)\n except IOError as e:\n if (e.errno == errno.ENOENT):\n logger.warning(NO_METRICS_FILE_AT_REFERENCE_WARNING.format(out.rel_path, branch))\n metric = None\n else:\n raise\n if (not metric):\n continue\n res[out.rel_path] = metric\n return res", "docstring": "Read the content of each metric file and format it.\n\nArgs:\n metrics (list): List of metric touples\n branch (str): Branch to look up for metrics.\n\nReturns:\n A dict mapping keys with metrics path name and content.\n For example:\n\n {'metric.csv': (\"value_mse deviation_mse data_set\\n\"\n \"0.421601 0.173461 train\\n\"\n \"0.67528 0.289545 testing\\n\"\n \"0.671502 0.297848 validation\\n\")}", "source": "codesearchnet_filtered"} +{"code": "def list_keyvaults_sub(access_token, subscription_id):\n endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.KeyVault/vaults', '?api-version=', KEYVAULT_API])\n return do_get_next(endpoint, access_token)", "docstring": "Lists key vaults belonging to this subscription.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n\nReturns:\n HTTP response. 200 OK.", "source": "codesearchnet_filtered"} +{"code": "def compare_name(given_name, family_name, question_name):\n given_name = given_name.lower()\n family_name = family_name.lower()\n question_name = question_name.lower()\n if (',' in question_name):\n name_split = question_name.split(',')\n name_split.reverse()\n question_name = ' '.join(name_split).strip()\n question_name = question_name.replace('.', '')\n given_name = given_name.replace('.', '')\n family_name = family_name.replace('.', '')\n given_name = list(filter(None, re.split('[, \\\\-.]+', given_name)))\n num_family_names = len(list(filter(None, re.split('[, .]+', family_name))))\n name_split = list(filter(None, re.split('[, \\\\-.]+', question_name)))\n first_name = [name_split[0]]\n if (len(name_split) > 2):\n first_name += [n for n in name_split[1:(- num_family_names)]]\n if ((len(first_name) > 1) and (len(given_name) == len(first_name))):\n for i in range(1, len(first_name)):\n first_name[i] = first_name[i][0]\n given_name[i] = given_name[i][0]\n elif (len(given_name) != len(first_name)):\n min_names = min(len(given_name), len(first_name))\n first_name = first_name[:min_names]\n given_name = given_name[:min_names]\n if ((len(first_name[0]) == 1) or (len(given_name[0]) == 1)):\n given_name[0] = given_name[0][0]\n first_name[0] = first_name[0][0]\n if ((len(first_name[0]) > 1) or (len(given_name[0]) > 1)):\n given_name[0] = given_name[0][0]\n first_name[0] = name_split[0][0]\n if ((num_family_names == 1) and ('-' in family_name)):\n num_hyphen = family_name.count('-')\n family_name_compare = '-'.join(name_split[(- (num_hyphen + 1)):])\n else:\n family_name_compare = ' '.join(name_split[(- num_family_names):])\n return ((given_name == first_name) and (family_name == family_name_compare))", "docstring": "Compares a name in question to a specified name separated into given and family.\n\n The name in question ``question_name`` can be of varying format, including\n \"Kyle E. Niemeyer\", \"Kyle Niemeyer\", \"K. E. Niemeyer\", \"KE Niemeyer\", and\n \"K Niemeyer\". Other possibilities include names with hyphens such as\n \"Chih-Jen Sung\", \"C. J. Sung\", \"C-J Sung\".\n\nExample:\n >>> compare_name('Kyle', 'Niemeyer', 'Kyle E Niemeyer')\n True\n >>> compare_name('Chih-Jen', 'Sung', 'C-J Sung')\n True\n\nArgs:\n given_name (`str`): Given (or first) name to be checked against.\n family_name (`str`): Family (or last) name to be checked against.\n question_name (`str`): The whole name in question.\n\nReturns:\n `bool`: The return value. True for successful comparison, False otherwise.", "source": "codesearchnet_filtered"} +{"code": "def get(self, node_id):\n return (self._nodes[_node.Root.ID].get(node_id) or self._nodes[_node.Root.ID].get(self._sid_map.get(node_id)))", "docstring": "Get a note with the given ID.\n\nArgs:\n node_id (str): The note ID.\n\nReturns:\n gkeepapi.node.TopLevelNode: The Note or None if not found.", "source": "codesearchnet_filtered"} +{"code": "def isregex(value):\n if (not value):\n return False\n return any((isregex_expr(value), isinstance(value, retype)))", "docstring": "Returns ``True`` if the input argument object is a native\n regular expression object, otherwise ``False``.\n\nArgs:\n value (mixed): input value to test.\n\nReturns:\n bool", "source": "codesearchnet_filtered"} +{"code": "def _ParseEntryObjectOffsets(self, file_object, file_offset):\n entry_array_object = self._ParseEntryArrayObject(file_object, file_offset)\n entry_object_offsets = list(entry_array_object.entry_object_offsets)\n while (entry_array_object.next_entry_array_offset != 0):\n entry_array_object = self._ParseEntryArrayObject(file_object, entry_array_object.next_entry_array_offset)\n entry_object_offsets.extend(entry_array_object.entry_object_offsets)\n return entry_object_offsets", "docstring": "Parses entry array objects for the offset of the entry objects.\n\nArgs:\n file_object (dfvfs.FileIO): a file-like object.\n file_offset (int): offset of the first entry array object relative to\n the start of the file-like object.\n\nReturns:\n list[int]: offsets of the entry objects.", "source": "codesearchnet_filtered"} +{"code": "def GetPresetsForOperatingSystem(cls, operating_system, operating_system_product, operating_system_version):\n operating_system = artifacts.OperatingSystemArtifact(family=operating_system, product=operating_system_product, version=operating_system_version)\n return cls._presets.GetPresetsByOperatingSystem(operating_system)", "docstring": "Determines the presets for a specific operating system.\n\nArgs:\n operating_system (str): operating system for example \"Windows\". This\n should be one of the values in definitions.OPERATING_SYSTEM_FAMILIES.\n operating_system_product (str): operating system product for\n example \"Windows XP\" as determined by preprocessing.\n operating_system_version (str): operating system version for\n example \"5.1\" as determined by preprocessing.\n\nReturns:\n list[PresetDefinition]: preset definitions, where an empty list\n represents all parsers and parser plugins (no preset).", "source": "codesearchnet_filtered"} +{"code": "def zip_cluster(data, k, init=None, max_iters=100):\n (genes, cells) = data.shape\n (init, new_assignments) = kmeans_pp((data + eps), k, centers=init)\n centers = np.copy(init)\n M = np.zeros(centers.shape)\n assignments = new_assignments\n for c in range(k):\n (centers[(:, c)], M[(:, c)]) = zip_fit_params_mle(data[(:, (assignments == c))])\n for it in range(max_iters):\n lls = zip_ll(data, centers, M)\n new_assignments = np.argmax(lls, 1)\n if np.equal(assignments, new_assignments).all():\n return (assignments, centers, M)\n for c in range(k):\n (centers[(:, c)], M[(:, c)]) = zip_fit_params_mle(data[(:, (assignments == c))])\n assignments = new_assignments\n return (assignments, centers, M)", "docstring": "Performs hard EM clustering using the zero-inflated Poisson distribution.\n\nArgs:\n data (array): A 2d array- genes x cells\n k (int): Number of clusters\n init (array, optional): Initial centers - genes x k array. Default: None, use kmeans++\n max_iters (int, optional): Maximum number of iterations. Default: 100\n\nReturns:\n assignments (array): integer assignments of cells to clusters (length cells)\n L (array): Poisson parameter (genes x k)\n M (array): zero-inflation parameter (genes x k)", "source": "codesearchnet_filtered"} +{"code": "def _CreateOutputModule(self, options):\n formatter_mediator = formatters_mediator.FormatterMediator(data_location=self._data_location)\n try:\n formatter_mediator.SetPreferredLanguageIdentifier(self._preferred_language)\n except (KeyError, TypeError) as exception:\n raise RuntimeError(exception)\n mediator = output_mediator.OutputMediator(self._knowledge_base, formatter_mediator, preferred_encoding=self.preferred_encoding)\n mediator.SetTimezone(self._preferred_time_zone)\n try:\n output_module = output_manager.OutputManager.NewOutputModule(self._output_format, mediator)\n except (KeyError, ValueError) as exception:\n raise RuntimeError('Unable to create output module with error: {0!s}'.format(exception))\n if output_manager.OutputManager.IsLinearOutputModule(self._output_format):\n output_file_object = open(self._output_filename, 'wb')\n output_writer = tools.FileObjectOutputWriter(output_file_object)\n output_module.SetOutputWriter(output_writer)\n helpers_manager.ArgumentHelperManager.ParseOptions(options, output_module)\n missing_parameters = output_module.GetMissingArguments()\n while missing_parameters:\n for parameter in missing_parameters:\n value = self._PromptUserForInput('Missing parameter {0:s} for output module'.format(parameter))\n if (value is None):\n logger.warning('Unable to set the missing parameter for: {0:s}'.format(parameter))\n continue\n setattr(options, parameter, value)\n helpers_manager.ArgumentHelperManager.ParseOptions(options, output_module)\n missing_parameters = output_module.GetMissingArguments()\n return output_module", "docstring": "Creates the output module.\n\nArgs:\n options (argparse.Namespace): command line arguments.\n\nReturns:\n OutputModule: output module.\n\nRaises:\n RuntimeError: if the output module cannot be created.", "source": "codesearchnet_filtered"} +{"code": "def siblings(self, as_resources=False):\n siblings = set()\n for parent in self.parents(as_resources=True):\n for sibling in parent.children(as_resources=as_resources):\n siblings.add(sibling)\n if as_resources:\n siblings.remove(self)\n if (not as_resources):\n siblings.remove(self.uri)\n return list(siblings)", "docstring": "method to return hierarchical siblings of this resource.\n\nArgs:\n as_resources (bool): if True, opens each as appropriate resource type instead of return URI only\n\nReturns:\n (list): list of resources", "source": "codesearchnet_filtered"} +{"code": "def distance_to_line(a, b, p):\n return distance(closest_point(a, b, p), p)", "docstring": "Closest distance between a line segment and a point\n\nArgs:\n a ([float, float]): x and y coordinates. Line start\n b ([float, float]): x and y coordinates. Line end\n p ([float, float]): x and y coordinates. Point to compute the distance\n\nReturns:\n float", "source": "codesearchnet_filtered"} +{"code": "def r_edges(step):\n (rbot, rtop) = misc.get_rbounds(step)\n centers = (step.rprof.loc[(:, 'r')].values + rbot)\n edges = ((centers[:(- 1)] + centers[1:]) / 2)\n edges = np.insert(edges, 0, rbot)\n edges = np.append(edges, rtop)\n return (edges, edges)", "docstring": "Cell border.\n\nArgs:\n step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData\n instance.\n\nReturns:\n tuple of :class:`numpy.array`: the position of the bottom and top walls\n of the cells. The two elements of the tuple are identical.", "source": "codesearchnet_filtered"} +{"code": "def _get_depencency_var_name(self, dependency):\n for (dep_path, var_name) in self.dependencies:\n if (dep_path == dependency):\n return var_name", "docstring": "Returns the variable name assigned to the given dependency or None if the dependency has\n not yet been registered.\n\nArgs:\n dependency (str): Thet dependency that needs to be imported.\n\nReturns:\n str or None", "source": "codesearchnet_filtered"} +{"code": "def convertData(self, contents, def_buf, kwh_scale=ScaleKWH.EmptyScale):\n log_str = ''\n count = 0\n if (kwh_scale == ScaleKWH.EmptyScale):\n scale_offset = int(def_buf.keys().index(Field.kWh_Scale))\n self.m_kwh_precision = kwh_scale = int(contents[scale_offset])\n for fld in def_buf:\n if def_buf[fld][MeterData.CalculatedFlag]:\n count += 1\n continue\n if (len(contents) == 0):\n count += 1\n continue\n try:\n raw_data = contents[count]\n fld_type = def_buf[fld][MeterData.TypeValue]\n fld_scale = def_buf[fld][MeterData.ScaleValue]\n if (fld_type == FieldType.Float):\n float_data = float(str(raw_data))\n divisor = 1\n if (fld_scale == ScaleType.KWH):\n divisor = 1\n if (kwh_scale == ScaleKWH.Scale10):\n divisor = 10\n elif (kwh_scale == ScaleKWH.Scale100):\n divisor = 100\n elif ((kwh_scale != ScaleKWH.NoScale) and (kwh_scale != ScaleKWH.EmptyScale)):\n ekm_log('Unrecognized kwh scale.')\n elif (fld_scale == ScaleType.Div10):\n divisor = 10\n elif (fld_scale == ScaleType.Div100):\n divisor = 100\n elif (fld_scale != ScaleType.No):\n ekm_log('Unrecognized float scale.')\n float_data /= divisor\n float_data_str = str(float_data)\n def_buf[fld][MeterData.StringValue] = float_data_str\n def_buf[fld][MeterData.NativeValue] = float_data\n elif (fld_type == FieldType.Hex):\n hex_data = raw_data.encode('hex')\n def_buf[fld][MeterData.StringValue] = hex_data\n def_buf[fld][MeterData.NativeValue] = hex_data\n elif (fld_type == FieldType.Int):\n integer_data = int(raw_data)\n integer_data_str = str(integer_data)\n if (len(integer_data_str) == 0):\n integer_data_str = str(0)\n def_buf[fld][MeterData.StringValue] = integer_data_str\n def_buf[fld][MeterData.NativeValue] = integer_data\n elif (fld_type == FieldType.String):\n string_data = str(raw_data)\n def_buf[fld][MeterData.StringValue] = string_data\n def_buf[fld][MeterData.NativeValue] = string_data\n elif (fld_type == FieldType.PowerFactor):\n def_buf[fld][MeterData.StringValue] = str(raw_data)\n def_buf[fld][MeterData.NativeValue] = str(raw_data)\n else:\n ekm_log('Unrecognized field type')\n log_str = (((((log_str + '\"') + fld) + '\": \"') + def_buf[fld][MeterData.StringValue]) + '\"\\n')\n except:\n ekm_log(('Exception on Field:' + str(fld)))\n ekm_log(traceback.format_exc(sys.exc_info()))\n self.writeCmdMsg(('Exception on Field:' + str(fld)))\n count += 1\n return True", "docstring": "Move data from raw tuple into scaled and conveted values.\n\nArgs:\n contents (tuple): Breakout of passed block from unpackStruct().\n def_buf (): Read buffer destination.\n kwh_scale (int): :class:`~ekmmeters.ScaleKWH` as int, from Field.kWhScale`\n\nReturns:\n bool: True on completion.", "source": "codesearchnet_filtered"} +{"code": "def GetRowCache(self, query):\n query_hash = hash(query)\n if (query_hash not in self._row_caches):\n self._row_caches[query_hash] = set()\n return self._row_caches[query_hash]", "docstring": "Retrieves the row cache for a specific query.\n\n The row cache is a set that contains hashes of values in a row. The row\n cache is used to find duplicate row when a database and a database with\n a WAL file is parsed.\n\nArgs:\n query (str): query.\n\nReturns:\n set: hashes of the rows that have been parsed.", "source": "codesearchnet_filtered"} +{"code": "def setCTRatio(self, new_ct, password='00000000'):\n ret = False\n self.setContext('setCTRatio')\n try:\n self.clearCmdMsg()\n if ((new_ct != CTRatio.Amps_100) and (new_ct != CTRatio.Amps_200) and (new_ct != CTRatio.Amps_400) and (new_ct != CTRatio.Amps_600) and (new_ct != CTRatio.Amps_800) and (new_ct != CTRatio.Amps_1000) and (new_ct != CTRatio.Amps_1200) and (new_ct != CTRatio.Amps_1500) and (new_ct != CTRatio.Amps_2000) and (new_ct != CTRatio.Amps_3000) and (new_ct != CTRatio.Amps_4000) and (new_ct != CTRatio.Amps_5000)):\n self.writeCmdMsg(('Legal CT Ratios: 100, 200, 400, 600, ' + '800, 1000, 1200, 1500, 2000, 3000, 4000 and 5000'))\n self.setContext('')\n return ret\n if (len(password) != 8):\n self.writeCmdMsg('Invalid password length.')\n self.setContext('')\n return ret\n if (not self.request(False)):\n self.writeCmdMsg('Bad read CRC on setting')\n elif (not self.serialCmdPwdAuth(password)):\n self.writeCmdMsg('Password failure')\n else:\n req_str = (('015731023030443028' + binascii.hexlify(str(new_ct).zfill(4))) + '2903')\n req_str += self.calc_crc16(req_str[2:].decode('hex'))\n self.m_serial_port.write(req_str.decode('hex'))\n if (self.m_serial_port.getResponse(self.getContext()).encode('hex') == '06'):\n self.writeCmdMsg('Success(setCTRatio): 06 returned.')\n ret = True\n self.serialPostEnd()\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n self.setContext('')\n return ret", "docstring": "Serial call to set CT ratio for attached inductive pickup.\n\nArgs:\n new_ct (int): A :class:`~ekmmeters.CTRatio` value, a legal amperage setting.\n password (str): Optional password.\n\nReturns:\n bool: True on completion with ACK.", "source": "codesearchnet_filtered"} +{"code": "def key_validation_check(tweet_keys_list, superset_keys, minset_keys):\n tweet_keys = set(tweet_keys_list)\n minset_overlap = (tweet_keys & minset_keys)\n if (minset_overlap != minset_keys):\n raise UnexpectedFormatError('keys ({}) missing from Tweet (Public API data is not supported)'.format((minset_keys - tweet_keys)))\n unexpected_keys = (tweet_keys - superset_keys)\n if (len(unexpected_keys) > 0):\n raise UnexpectedFormatError('Unexpected keys ({}) are in this Tweet'.format(unexpected_keys))\n return 0", "docstring": "Validates the keys present in a Tweet.\n\nArgs:\n tweet_keys_list (list): the keys present in a tweet\n superset_keys (set): the set of all possible keys for a tweet\n minset_keys (set): the set of minimal keys expected in a tweet.\n\nReturns:\n 0 if no errors\n\nRaises:\n UnexpectedFormatError on any mismatch of keys.", "source": "codesearchnet_filtered"} +{"code": "def path_get_origin(p: tcod.path.AStar) -> Tuple[(int, int)]:\n x = ffi.new('int *')\n y = ffi.new('int *')\n lib.TCOD_path_get_origin(p._path_c, x, y)\n return (x[0], y[0])", "docstring": "Get the current origin position.\n\n This point moves when :any:`path_walk` returns the next x,y step.\n\nArgs:\n p (AStar): An AStar instance.\n\nReturns:\n Tuple[int, int]: An (x, y) point.", "source": "codesearchnet_filtered"} +{"code": "def ip_geoloc(ip, hit_api=True):\n from ..logs.models import IPInfoCheck\n try:\n obj = IPInfoCheck.objects.get(ip_address=ip).ip_info\n except IPInfoCheck.DoesNotExist:\n if hit_api:\n try:\n obj = IPInfoCheck.check_ip(ip)\n except RateExceededError:\n return None\n else:\n return None\n return (obj.latitude, obj.longitude)", "docstring": "Get IP geolocation.\n\nArgs:\n ip (str): IP address to use if no data provided.\n hit_api (bool): whether to hit api if info not found.\n\nReturns:\n str: latitude and longitude, comma-separated.", "source": "codesearchnet_filtered"} +{"code": "def from_db(cls, bigchain, tx_dict_list):\n return_list = True\n if isinstance(tx_dict_list, dict):\n tx_dict_list = [tx_dict_list]\n return_list = False\n tx_map = {}\n tx_ids = []\n for tx in tx_dict_list:\n tx.update({'metadata': None})\n tx_map[tx['id']] = tx\n tx_ids.append(tx['id'])\n assets = list(bigchain.get_assets(tx_ids))\n for asset in assets:\n if (asset is not None):\n tx = tx_map[asset['id']]\n del asset['id']\n tx['asset'] = asset\n tx_ids = list(tx_map.keys())\n metadata_list = list(bigchain.get_metadata(tx_ids))\n for metadata in metadata_list:\n tx = tx_map[metadata['id']]\n tx.update({'metadata': metadata.get('metadata')})\n if return_list:\n tx_list = []\n for (tx_id, tx) in tx_map.items():\n tx_list.append(cls.from_dict(tx))\n return tx_list\n else:\n tx = list(tx_map.values())[0]\n return cls.from_dict(tx)", "docstring": "Helper method that reconstructs a transaction dict that was returned\n from the database. It checks what asset_id to retrieve, retrieves the\n asset from the asset table and reconstructs the transaction.\n\nArgs:\n bigchain (:class:`~bigchaindb.tendermint.BigchainDB`): An instance\n of BigchainDB used to perform database queries.\n tx_dict_list (:list:`dict` or :obj:`dict`): The transaction dict or\n list of transaction dict as returned from the database.\n\nReturns:\n :class:`~Transaction`", "source": "codesearchnet_filtered"} +{"code": "def _update_unenrolled_list(sailthru_client, email, course_url, unenroll):\n try:\n sailthru_response = sailthru_client.api_get('user', {'id': email, 'fields': {'vars': 1}})\n if (not sailthru_response.is_ok()):\n error = sailthru_response.get_error()\n logger.error('Error attempting to read user record from Sailthru: %s', error.get_message())\n return (not can_retry_sailthru_request(error))\n response_json = sailthru_response.json\n unenroll_list = []\n if (response_json and ('vars' in response_json) and response_json['vars'] and ('unenrolled' in response_json['vars'])):\n unenroll_list = response_json['vars']['unenrolled']\n changed = False\n if unenroll:\n if (course_url not in unenroll_list):\n unenroll_list.append(course_url)\n changed = True\n elif (course_url in unenroll_list):\n unenroll_list.remove(course_url)\n changed = True\n if changed:\n sailthru_response = sailthru_client.api_post('user', {'id': email, 'key': 'email', 'vars': {'unenrolled': unenroll_list}})\n if (not sailthru_response.is_ok()):\n error = sailthru_response.get_error()\n logger.error('Error attempting to update user record in Sailthru: %s', error.get_message())\n return (not can_retry_sailthru_request(error))\n return True\n except SailthruClientError as exc:\n logger.exception('Exception attempting to update user record for %s in Sailthru - %s', email, text_type(exc))\n return False", "docstring": "Maintain a list of courses the user has unenrolled from in the Sailthru user record\n\nArgs:\n sailthru_client (object): SailthruClient\n email (str): user's email address\n course_url (str): LMS url for course info page.\n unenroll (boolean): True if unenrolling, False if enrolling\n\nReturns:\n False if retryable error, else True", "source": "codesearchnet_filtered"} +{"code": "def add_data(self, data):\n if ((self.data_size - self.data_index) < len(data)):\n return Error.DESTINATION_BUFFER_TOO_SMALL\n if (self.in_progress is not None):\n self.in_progress.data += data\n return Error.NO_ERROR", "docstring": "Add data to the currently in progress entry.\n\nArgs:\n data (bytes): The data that we want to add.\n\nReturns:\n int: An error code", "source": "codesearchnet_filtered"} +{"code": "def prop(pode, prop):\n form = pode[0][0]\n if prop.startswith(form):\n prop = prop[len(form):]\n if (prop[0] == ':'):\n prop = prop[1:]\n return pode[1]['props'].get(prop)", "docstring": "Return the valu of a given property on the node.\n\nArgs:\n pode (tuple): A packed node.\n prop (str): Property to retrieve.\n\nNote:\n The prop argument may be the full property name (foo:bar:baz), relative property name (:baz) , or the unadorned\n property name (baz).\n\n Returns:", "source": "codesearchnet_filtered"} +{"code": "def noise_new(dim: int, h: float=NOISE_DEFAULT_HURST, l: float=NOISE_DEFAULT_LACUNARITY, random: Optional[tcod.random.Random]=None) -> tcod.noise.Noise:\n return tcod.noise.Noise(dim, hurst=h, lacunarity=l, seed=random)", "docstring": "Return a new Noise instance.\n\nArgs:\n dim (int): Number of dimensions. From 1 to 4.\n h (float): The hurst exponent. Should be in the 0.0-1.0 range.\n l (float): The noise lacunarity.\n random (Optional[Random]): A Random instance, or None.\n\nReturns:\n Noise: The new Noise instance.", "source": "codesearchnet_filtered"} +{"code": "def tetragonal(a: float, c: float):\n return Lattice.from_parameters(a, a, c, 90, 90, 90)", "docstring": "Convenience constructor for a tetragonal lattice.\n\nArgs:\n a (float): *a* lattice parameter of the tetragonal cell.\n c (float): *c* lattice parameter of the tetragonal cell.\n\nReturns:\n Tetragonal lattice of dimensions a x a x c.", "source": "codesearchnet_filtered"} +{"code": "def position(self, partition):\n if (not isinstance(partition, TopicPartition)):\n raise TypeError('partition must be a TopicPartition namedtuple')\n assert self._subscription.is_assigned(partition), 'Partition is not assigned'\n offset = self._subscription.assignment[partition].position\n if (offset is None):\n self._update_fetch_positions([partition])\n offset = self._subscription.assignment[partition].position\n return offset", "docstring": "Get the offset of the next record that will be fetched\n\nArgs:\n partition (TopicPartition): Partition to check\n\nReturns:\n int: Offset", "source": "codesearchnet_filtered"} +{"code": "def _ParseSystemTime(self, byte_stream):\n systemtime_map = self._GetDataTypeMap('systemtime')\n try:\n systemtime = self._ReadStructureFromByteStream(byte_stream, 0, systemtime_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError('Unable to parse SYSTEMTIME value with error: {0!s}'.format(exception))\n system_time_tuple = (systemtime.year, systemtime.month, systemtime.weekday, systemtime.day_of_month, systemtime.hours, systemtime.minutes, systemtime.seconds, systemtime.milliseconds)\n if (system_time_tuple == self._EMPTY_SYSTEM_TIME_TUPLE):\n return None\n try:\n return dfdatetime_systemtime.Systemtime(system_time_tuple=system_time_tuple)\n except ValueError:\n raise errors.ParseError('Invalid SYSTEMTIME value: {0!s}'.format(system_time_tuple))", "docstring": "Parses a SYSTEMTIME date and time value from a byte stream.\n\nArgs:\n byte_stream (bytes): byte stream.\n\nReturns:\n dfdatetime.Systemtime: SYSTEMTIME date and time value or None if no\n value is set.\n\nRaises:\n ParseError: if the SYSTEMTIME could not be parsed.", "source": "codesearchnet_filtered"} +{"code": "def parse_frequency(variant, info_key):\n raw_annotation = variant.INFO.get(info_key)\n raw_annotation = (None if (raw_annotation == '.') else raw_annotation)\n frequency = (float(raw_annotation) if raw_annotation else None)\n return frequency", "docstring": "Parse any frequency from the info dict\n\nArgs:\n variant(cyvcf2.Variant)\n info_key(str)\n\nReturns:\n frequency(float): or None if frequency does not exist", "source": "codesearchnet_filtered"} +{"code": "def get(self, key):\n lock.acquire()\n try:\n if (key not in self):\n return None\n current_time = time.time()\n if (self[key].expire > current_time):\n return self[key].value\n deletes = []\n for (k, val) in self.items():\n if (val.expire <= current_time):\n deletes.append(k)\n for k in deletes:\n del self[k]\n return None\n finally:\n lock.release()", "docstring": "Get an object from the cache\n\nArgs:\n key (str): Cache key\n\nReturns:\n Cached object", "source": "codesearchnet_filtered"} +{"code": "def datetime_string(day, month, year, hour, minute):\n if ((hour < 0) or (hour > 23)):\n hour = 0\n if ((minute < 0) or (minute > 60)):\n minute = 0\n return ('%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute))", "docstring": "Build a date string using the provided day, month, year numbers.\n\n Automatically adds a leading zero to ``day`` and ``month`` if they only have\n one digit.\n\nArgs:\n day (int): Day number.\n month(int): Month number.\n year(int): Year number.\n hour (int): Hour of the day in 24h format.\n minute (int): Minute of the hour.\n\nReturns:\n str: Date in the format *YYYY-MM-DDThh:mm:ss*.", "source": "codesearchnet_filtered"} +{"code": "def ReadAtOffset(self, offset, size=None):\n if ((size is not None) and (size < 0)):\n raise ValueError('Invalid size value {0!s}'.format(size))\n if (offset < 0):\n raise ValueError('Invalid offset value {0!s}'.format(offset))\n if ((size == 0) or (offset >= self.uncompressed_data_size)):\n return b''\n if (self._cache_start_offset is None):\n self._LoadDataIntoCache(self._file_object, offset)\n if ((offset > self._cache_end_offset) or (offset < self._cache_start_offset)):\n self.FlushCache()\n self._LoadDataIntoCache(self._file_object, offset)\n cache_offset = (offset - self._cache_start_offset)\n if (not size):\n return self._cache[cache_offset:]\n data_end_offset = (cache_offset + size)\n if (data_end_offset > self._cache_end_offset):\n return self._cache[cache_offset:]\n return self._cache[cache_offset:data_end_offset]", "docstring": "Reads a byte string from the gzip member at the specified offset.\n\n The function will read a byte string of the specified size or\n all of the remaining data if no size was specified.\n\nArgs:\n offset (int): offset within the uncompressed data in this member to\n read from.\n size (Optional[int]): maximum number of bytes to read, where None\n represents all remaining data, to a maximum of the uncompressed\n cache size.\n\nReturns:\n bytes: data read.\n\nRaises:\n IOError: if the read failed.\n ValueError: if a negative read size or offset is specified.", "source": "codesearchnet_filtered"} +{"code": "def format(self, exclude_class=False):\n if exclude_class:\n msg = self.msg\n else:\n msg = ('%s: %s' % (self.__class__.__name__, self.msg))\n if (len(self.params) != 0):\n paramstring = '\\n'.join([((str(key) + ': ') + str(val)) for (key, val) in self.params.items()])\n msg += ('\\nAdditional Information:\\n' + paramstring)\n return msg", "docstring": "Format this exception as a string including class name.\n\nArgs:\n exclude_class (bool): Whether to exclude the exception class\n name when formatting this exception\n\nReturns:\n string: a multiline string with the message, class name and\n key value parameters passed to create the exception.", "source": "codesearchnet_filtered"} +{"code": "def add_server(self, name, prefer=False):\n if ((not name) or re.match('^[\\\\s]+$', name)):\n raise ValueError('ntp server name must be specified')\n if prefer:\n name = ('%s prefer' % name)\n cmd = self.command_builder('ntp server', value=name)\n return self.configure(cmd)", "docstring": "Add or update an NTP server entry to the node config\n\nArgs:\n name (string): The IP address or FQDN of the NTP server.\n prefer (bool): Sets the NTP server entry as preferred if True.\n\nReturns:\n True if the operation succeeds, otherwise False.", "source": "codesearchnet_filtered"} +{"code": "def receiveds_parsing(receiveds):\n parsed = []\n receiveds = [re.sub(JUNK_PATTERN, ' ', i).strip() for i in receiveds]\n n = len(receiveds)\n log.debug('Nr. of receiveds. {}'.format(n))\n for (idx, received) in enumerate(receiveds):\n log.debug('Parsing received {}/{}'.format((idx + 1), n))\n log.debug('Try to parse {!r}'.format(received))\n try:\n values_by_clause = parse_received(received)\n except MailParserReceivedParsingError:\n parsed.append({'raw': received})\n else:\n parsed.append(values_by_clause)\n log.debug(('len(receiveds) %s, len(parsed) %s' % (len(receiveds), len(parsed))))\n if (len(receiveds) != len(parsed)):\n log.error(('len(receiveds): %s, len(parsed): %s, receiveds: %s, parsed: %s' % (len(receiveds), len(parsed), receiveds, parsed)))\n return receiveds_not_parsed(receiveds)\n else:\n return receiveds_format(parsed)", "docstring": "This function parses the receiveds headers.\n\nArgs:\n receiveds (list): list of raw receiveds headers\n\nReturns:\n a list of parsed receiveds headers with first hop in first position", "source": "codesearchnet_filtered"} +{"code": "def _CreateSanitizedDestination(self, source_file_entry, source_path_spec, source_data_stream_name, destination_path):\n file_system = source_file_entry.GetFileSystem()\n path = getattr(source_path_spec, 'location', None)\n path_segments = file_system.SplitPath(path)\n for (index, path_segment) in enumerate(path_segments):\n path_segments[index] = ''.join([(character if (character not in self._DIRTY_CHARACTERS) else '_') for character in path_segment])\n target_filename = path_segments.pop()\n parent_path_spec = getattr(source_file_entry.path_spec, 'parent', None)\n while parent_path_spec:\n if (parent_path_spec.type_indicator == dfvfs_definitions.TYPE_INDICATOR_TSK_PARTITION):\n path_segments.insert(0, parent_path_spec.location[1:])\n break\n elif (parent_path_spec.type_indicator == dfvfs_definitions.TYPE_INDICATOR_VSHADOW):\n path_segments.insert(0, parent_path_spec.location[1:])\n parent_path_spec = getattr(parent_path_spec, 'parent', None)\n target_directory = os.path.join(destination_path, *path_segments)\n if source_data_stream_name:\n target_filename = '{0:s}_{1:s}'.format(target_filename, source_data_stream_name)\n return (target_directory, target_filename)", "docstring": "Creates a sanitized path of both destination directory and filename.\n\n This function replaces non-printable and other characters defined in\n _DIRTY_CHARACTERS with an underscore \"_\".\n\nArgs:\n source_file_entry (dfvfs.FileEntry): file entry of the source file.\n source_path_spec (dfvfs.PathSpec): path specification of the source file.\n source_data_stream_name (str): name of the data stream of the source file\n entry.\n destination_path (str): path of the destination directory.\n\nReturns:\n tuple[str, str]: sanitized paths of both destination directory and\n filename.", "source": "codesearchnet_filtered"} +{"code": "def disambiguate_pdf(self, file, language=None, entities=None):\n body = {'customisation': 'generic'}\n if language:\n body['language'] = {'lang': language}\n if entities:\n body['entities'] = entities\n files = {'query': str(body), 'file': (file, open(file, 'rb'), 'application/pdf', {'Expires': '0'})}\n (res, status) = self.post(self.disambiguate_service, files=files, headers={'Accept': 'application/json'})\n if (status != 200):\n logger.debug(('Disambiguation failed with error ' + str(status)))\n return (self.decode(res), status)", "docstring": "Call the disambiguation service in order to process a pdf file .\n\nArgs:\n pdf (file): PDF file to be disambiguated.\n language (str): language of text (if known)\n\nReturns:\n dict, int: API response and API status.", "source": "codesearchnet_filtered"} +{"code": "def out_file_name(out_dir, fname, ext=None):\n if (ext is None):\n return os.path.join(out_dir, os.path.basename(fname))\n fname = remove_ext(fname)\n return os.path.join(out_dir, '{}.{}'.format(fname, ext))", "docstring": "Return path of output file, given a directory, file name and extension.\n\n If fname is a path, it is converted to its basename.\n\nArgs:\n out_dir (str): path to the directory where output should be written.\n fname (str): path to the input file.\n ext (str): file extension of the output file (defaults to None).\n\nReturns:\n str: out_dir + fname with extension replaced. If `ext` is `None`, the\n original extension is kept.", "source": "codesearchnet_filtered"} +{"code": "def generate_branches(scales=None, angles=None, shift_angle=0):\n branches = []\n for (pos, scale) in enumerate(scales):\n angle = ((((- sum(angles)) / 2) + sum(angles[:pos])) + shift_angle)\n branches.append([scale, angle])\n return branches", "docstring": "Generates branches with alternative system.\n\nArgs:\n scales (tuple/array): Indicating how the branch/es length/es develop/s from age to age.\n angles (tuple/array): Holding the branch and shift angle in radians.\n shift_angle (float): Holding the rotation angle for all branches.\n\nReturns:\n branches (2d-array): A array constits of arrays holding scale and angle for every branch.", "source": "codesearchnet_filtered"} +{"code": "def parse_mmtf_header(infile):\n infodict = {}\n mmtf_decoder = mmtf.parse(infile)\n infodict['date'] = mmtf_decoder.deposition_date\n infodict['release_date'] = mmtf_decoder.release_date\n try:\n infodict['experimental_method'] = [x.decode() for x in mmtf_decoder.experimental_methods]\n except AttributeError:\n infodict['experimental_method'] = [x for x in mmtf_decoder.experimental_methods]\n infodict['resolution'] = mmtf_decoder.resolution\n infodict['description'] = mmtf_decoder.title\n group_name_exclude = ['HOH']\n chem_comp_type_exclude = ['l-peptide linking', 'peptide linking']\n chemicals = list(set([mmtf_decoder.group_list[idx]['groupName'] for idx in mmtf_decoder.group_type_list if ((mmtf_decoder.group_list[idx]['chemCompType'].lower() not in chem_comp_type_exclude) and (mmtf_decoder.group_list[idx]['groupName'] not in group_name_exclude))]))\n infodict['chemicals'] = chemicals\n return infodict", "docstring": "Parse an MMTF file and return basic header-like information.\n\nArgs:\n infile (str): Path to MMTF file\n\nReturns:\n dict: Dictionary of parsed header\n\n Todo:\n - Can this be sped up by not parsing the 3D coordinate info somehow?\n - OR just store the sequences when this happens since it is already being parsed.", "source": "codesearchnet_filtered"} +{"code": "def service_info(self, short_name):\n if (short_name not in self.services):\n raise ArgumentError('Unknown service name', short_name=short_name)\n info = {}\n info['short_name'] = short_name\n info['long_name'] = self.services[short_name]['state'].long_name\n info['preregistered'] = self.services[short_name]['state'].preregistered\n return info", "docstring": "Get static information about a service.\n\nArgs:\n short_name (string): The short name of the service to query\n\nReturns:\n dict: A dictionary with the long_name and preregistered info\n on this service.", "source": "codesearchnet_filtered"} +{"code": "def insert(self, i, species, coords, validate_proximity=False, properties=None):\n new_site = Site(species, coords, properties=properties)\n if validate_proximity:\n for site in self:\n if (site.distance(new_site) < self.DISTANCE_TOLERANCE):\n raise ValueError('New site is too close to an existing site!')\n self._sites.insert(i, new_site)", "docstring": "Insert a site to the molecule.\n\nArgs:\n i (int): Index to insert site\n species: species of inserted site\n coords (3x1 array): coordinates of inserted site\n validate_proximity (bool): Whether to check if inserted site is\n too close to an existing site. Defaults to True.\n properties (dict): Dict of properties for the Site.\n\nReturns:\n New molecule with inserted site.", "source": "codesearchnet_filtered"} +{"code": "def fulfill_transaction(transaction, *, private_keys):\n if (not isinstance(private_keys, (list, tuple))):\n private_keys = [private_keys]\n if isinstance(private_keys, tuple):\n private_keys = list(private_keys)\n transaction_obj = Transaction.from_dict(transaction)\n try:\n signed_transaction = transaction_obj.sign(private_keys)\n except KeypairMismatchException as exc:\n raise MissingPrivateKeyError('A private key is missing!') from exc\n return signed_transaction.to_dict()", "docstring": "Fulfills the given transaction.\n\nArgs:\n transaction (dict): The transaction to be fulfilled.\n private_keys (:obj:`str` | :obj:`list` | :obj:`tuple`): One or\n more private keys to be used for fulfilling the\n transaction.\n\nReturns:\n dict: The fulfilled transaction payload, ready to be sent to a\n BigchainDB federation.\n\nRaises:\n :exc:`~.exceptions.MissingPrivateKeyError`: If a private\n key is missing.", "source": "codesearchnet_filtered"} +{"code": "def download_file(self, url, folder=None, filename=None, overwrite=False, post=False, parameters=None, timeout=None):\n self.setup(url, stream=True, post=post, parameters=parameters, timeout=timeout)\n return self.stream_file(url, folder, filename, overwrite)", "docstring": "Download file from url and store in provided folder or temporary folder if no folder supplied\n\nArgs:\n url (str): URL to download\n folder (Optional[str]): Folder to download it to. Defaults to None.\n filename (Optional[str]): Filename to use for downloaded file. Defaults to None (derive from the url).\n overwrite (bool): Whether to overwrite existing file. Defaults to False.\n post (bool): Whether to use POST instead of GET. Defaults to False.\n parameters (Optional[Dict]): Parameters to pass. Defaults to None.\n timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no timeout).\n\nReturns:\n str: Path of downloaded file", "source": "codesearchnet_filtered"} +{"code": "def VerifyStructure(self, parser_mediator, lines):\n try:\n structure = self._GDS_LINE.parseString(lines)\n except pyparsing.ParseException as exception:\n logger.debug('Not a Google Drive Sync log file: {0!s}'.format(exception))\n return False\n date_time = dfdatetime_time_elements.TimeElementsInMilliseconds()\n try:\n datetime_iso8601 = self._GetISO8601String(structure.date_time)\n date_time.CopyFromStringISO8601(datetime_iso8601)\n except ValueError as exception:\n logger.debug('Not a Google Drive Sync log file, invalid date/time: {0!s} with error: {1!s}'.format(structure.date_time, exception))\n return False\n return True", "docstring": "Verify that this file is a Google Drive Sync log file.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n lines (str): one or more lines from the text file.\n\nReturns:\n bool: True if this is the correct parser, False otherwise.", "source": "codesearchnet_filtered"} +{"code": "def clip_by_value(x, min, max):\n from .function_bases import maximum2 as maximum2_base\n from .function_bases import minimum2 as minimum2_base\n return minimum2_base(maximum2_base(x, min), max)", "docstring": "r\"\"\"Clip inputs by values.\n\n .. math::\n\n y = \\begin{cases}\n max & (x > max) \\\\\n x & (otherwise) \\\\\n min & (x < min)\n \\end{cases}.\n\nArgs:\n x (Variable): An input variable.\n min (Variable): A min variable by which `x` is clipped. Note that the shape of `min` must be the same as `x`'s.\n max (Variable): A max variable by which `x` is clipped. Note that the shape of `max` must be the same as `x`'s\n\nReturns:\n ~nnabla.Variable: N-D array.", "source": "codesearchnet_filtered"} +{"code": "def evaluate_bound(distribution, x_data, parameters=None, cache=None):\n assert (len(x_data) == len(distribution))\n assert (len(x_data.shape) == 2)\n cache = (cache if (cache is not None) else {})\n parameters = load_parameters(distribution, '_bnd', parameters=parameters, cache=cache)\n out = numpy.zeros(((2,) + x_data.shape))\n (lower, upper) = distribution._bnd(x_data.copy(), **parameters)\n out.T[(:, :, 0)] = numpy.asfarray(lower).T\n out.T[(:, :, 1)] = numpy.asfarray(upper).T\n cache[distribution] = out\n return out", "docstring": "Evaluate lower and upper bounds.\n\nArgs:\n distribution (Dist):\n Distribution to evaluate.\n x_data (numpy.ndarray):\n Locations for where evaluate bounds at. Relevant in the case of\n multivariate distributions where the bounds are affected by the\n output of other distributions.\n parameters (:py:data:typing.Any):\n Collection of parameters to override the default ones in the\n distribution.\n cache (:py:data:typing.Any):\n A collection of previous calculations in case the same distribution\n turns up on more than one occasion.\n\nReturns:\n The lower and upper bounds of ``distribution`` at location\n ``x_data`` using parameters ``parameters``.", "source": "codesearchnet_filtered"} +{"code": "def GetName(self, number):\n value = self._data_type_definition.values_per_number.get(number, None)\n if (not value):\n return None\n return value.name", "docstring": "Retrieves the name of an enumeration value by number.\n\nArgs:\n number (int): number.\n\nReturns:\n str: name of the enumeration value or None if no corresponding\n enumeration value was found.", "source": "codesearchnet_filtered"} +{"code": "def get_gradebook_id(self, gbuuid):\n gradebook = self.get('gradebook', params={'uuid': gbuuid})\n if ('data' not in gradebook):\n failure_messsage = 'Error in get_gradebook_id for {0} - no data'.format(gradebook)\n log.error(failure_messsage)\n raise PyLmodUnexpectedData(failure_messsage)\n return gradebook['data']['gradebookId']", "docstring": "Return gradebookid for a given gradebook uuid.\n\nArgs:\n gbuuid (str): gradebook uuid, i.e. ``STELLAR:/project/gbngtest``\n\nRaises:\n PyLmodUnexpectedData: No gradebook id returned\n requests.RequestException: Exception connection error\n ValueError: Unable to decode response content\n\nReturns:\n str: value of gradebook id", "source": "codesearchnet_filtered"} +{"code": "def update(self, jump):\n atom = jump.initial_site.atom\n dr = jump.dr(self.cell_lengths)\n jump.final_site.occupation = atom.number\n jump.final_site.atom = atom\n jump.final_site.is_occupied = True\n jump.initial_site.occupation = 0\n jump.initial_site.atom = None\n jump.initial_site.is_occupied = False\n atom.site = jump.final_site\n atom.number_of_hops += 1\n atom.dr += dr\n atom.summed_dr2 += np.dot(dr, dr)", "docstring": "Update the lattice state by accepting a specific jump\n\nArgs:\n jump (Jump): The jump that has been accepted.\n\nReturns:\n None.", "source": "codesearchnet_filtered"} +{"code": "def get_dm_channel(self, userid):\n dm_open = self.slack_client.api_call('im.open', user=userid)\n return dm_open['channel']['id']", "docstring": "Perform a lookup of users to resolve a userid to a DM channel\n\nArgs:\n userid (string): Slack userid to lookup.\n\nReturns:\n string: DM channel ID of user", "source": "codesearchnet_filtered"} +{"code": "def fib(n):\n assert (n > 0)\n (a, b) = (1, 1)\n for i in range((n - 1)):\n (a, b) = (b, (a + b))\n return a", "docstring": "Fibonacci example function\n\nArgs:\n n (int): integer\n\nReturns:\n int: n-th Fibonacci number", "source": "codesearchnet_filtered"} +{"code": "def prelu(inp, base_axis=1, shared=True, fix_parameters=False):\n shape = (tuple() if shared else (inp.shape[base_axis],))\n w = get_parameter_or_create('slope', shape, ConstantInitializer((- 1)), True, (not fix_parameters))\n return F.prelu(inp, w, base_axis)", "docstring": "Parametrized Rectified Linear Unit function defined as\n\n .. math::\n y_i = \\max(0, x_i) + w_i \\min(0, -x_i)\n\n where negative slope :math:`w` is learned and can vary across channels (an\n axis specified with base_axis). Weights are initialized with :math:`-1`.\n\nArgs:\n x(~nnabla.Variable): N-D array as input\n base_axis(int): Dimensions up to base_axis is treated as sample dimension.\n shared(bool): Use shared weight value or not\n fix_parameters (bool): When set to `True`, the negative slope values\n will not be updated.\n\nReturns:\n ~nnabla.Variable: N-D array.", "source": "codesearchnet_filtered"} +{"code": "def has_button(self, button):\n rc = self._libinput.libinput_device_pointer_has_button(self._handle, button)\n assert (rc >= 0), 'This device is not a pointer device'\n return bool(rc)", "docstring": "Check if this device has a given button.\n\nArgs:\n button (int): Button to check for, see ``input.h`` for button\n definitions.\n\nReturns:\n bool: :obj:`True` if the device has this button, :obj:`False` if\n it does not.\n\nRaises:\n AssertionError", "source": "codesearchnet_filtered"} +{"code": "def valid_config_exists(config_path=CONFIG_PATH):\n if os.path.isfile(config_path):\n try:\n config = read_config(config_path)\n check_config(config)\n except (ConfigurationError, IOError):\n return False\n else:\n return False\n return True", "docstring": "Verify that a valid config file exists.\n\nArgs:\n config_path (str): Path to the config file.\n\nReturns:\n boolean: True if there is a valid config file, false if not.", "source": "codesearchnet_filtered"} +{"code": "def track_progress(func, tasks, bar_width=50, **kwargs):\n if isinstance(tasks, tuple):\n assert (len(tasks) == 2)\n assert isinstance(tasks[0], collections_abc.Iterable)\n assert isinstance(tasks[1], int)\n task_num = tasks[1]\n tasks = tasks[0]\n elif isinstance(tasks, collections_abc.Iterable):\n task_num = len(tasks)\n else:\n raise TypeError('\"tasks\" must be an iterable object or a (iterator, int) tuple')\n prog_bar = ProgressBar(task_num, bar_width)\n results = []\n for task in tasks:\n results.append(func(task, **kwargs))\n prog_bar.update()\n sys.stdout.write('\\n')\n return results", "docstring": "Track the progress of tasks execution with a progress bar.\n\n Tasks are done with a simple for-loop.\n\nArgs:\n func (callable): The function to be applied to each task.\n tasks (list or tuple[Iterable, int]): A list of tasks or\n (tasks, total num).\n bar_width (int): Width of progress bar.\n\nReturns:\n list: The task results.", "source": "codesearchnet_filtered"} +{"code": "def setup(config_root=''):\n config = _load_config(root=config_root)\n logging_config = config.get('core', {}).get('logging', {})\n log_level = logging_config.get('level', 'INFO').upper()\n log_handlers = (logging_config.get('handlers') or ['syslog'])\n ulogger.setup_logging(progname='gordon-janitor', level=log_level, handlers=log_handlers)\n return config", "docstring": "Service configuration and logging setup.\n\n Configuration defined in ``gordon-janitor-user.toml`` will overwrite\n ``gordon-janitor.toml``.\n\nArgs:\n config_root (str): where configuration should load from,\n defaults to current working directory.\n\nReturns:\n A dict for Gordon service configuration", "source": "codesearchnet_filtered"} +{"code": "def require_representation(self, req):\n try:\n (type_, subtype, _) = parse_mime_type(req.content_type)\n content_type = '/'.join((type_, subtype))\n except:\n raise falcon.HTTPUnsupportedMediaType(description='Invalid Content-Type header: {}'.format(req.content_type))\n if (content_type == 'application/json'):\n body = req.stream.read()\n return json.loads(body.decode('utf-8'))\n else:\n raise falcon.HTTPUnsupportedMediaType(description='only JSON supported, got: {}'.format(content_type))", "docstring": "Require raw representation dictionary from falcon request object.\n\n This does not perform any field parsing or validation but only uses\n allowed content-encoding handler to decode content body.\n\nNote:\n Currently only JSON is allowed as content type.\n\nArgs:\n req (falcon.Request): request object\n\nReturns:\n dict: raw dictionary of representation supplied in request body", "source": "codesearchnet_filtered"} +{"code": "def disambiguate_query(self, query, language=None, entities=None):\n body = {'shortText': query, 'entities': [], 'onlyNER': 'false', 'customisation': 'generic'}\n if language:\n body['language'] = {'lang': language}\n if entities:\n body['entities'] = entities\n files = {'query': str(body)}\n logger.debug('About to submit the following query {}'.format(body))\n (res, status) = self.post(self.disambiguate_service, files=files, headers={'Accept': 'application/json'})\n if (status == 200):\n return (self.decode(res), status)\n else:\n logger.debug('Disambiguation failed.')\n return (None, status)", "docstring": "Call the disambiguation service in order to disambiguate a search query.\n\nArgs:\n text (str): Query to be disambiguated.\n language (str): language of text (if known)\n entities (list): list of entities or mentions to be supplied by\n the user.\n\nReturns:\n dict, int: API response and API status.", "source": "codesearchnet_filtered"} +{"code": "def bounds(self, thr=0, lower_index=0, upper_index=(- 1)):\n points = self.points[lower_index:upper_index]\n min_lat = float('inf')\n min_lon = float('inf')\n max_lat = (- float('inf'))\n max_lon = (- float('inf'))\n for point in points:\n min_lat = min(min_lat, point.lat)\n min_lon = min(min_lon, point.lon)\n max_lat = max(max_lat, point.lat)\n max_lon = max(max_lon, point.lon)\n return ((min_lat - thr), (min_lon - thr), (max_lat + thr), (max_lon + thr))", "docstring": "Computes the bounds of the segment, or part of it\n\nArgs:\n lower_index (int, optional): Start index. Defaults to 0\n upper_index (int, optional): End index. Defaults to 0\n\nReturns:\n :obj:`tuple` of :obj:`float`: Bounds of the (sub)segment, such that\n (min_lat, min_lon, max_lat, max_lon)", "source": "codesearchnet_filtered"} +{"code": "def random_subsets(self, relative_sizes, by_duration=False, balance_labels=False, label_list_ids=None):\n resulting_sets = {}\n next_bigger_subset = self.corpus\n for relative_size in reversed(relative_sizes):\n generator = SubsetGenerator(next_bigger_subset, random_seed=self.random_seed)\n if by_duration:\n sv = generator.random_subset_by_duration(relative_size, balance_labels=balance_labels, label_list_ids=label_list_ids)\n else:\n sv = generator.random_subset(relative_size, balance_labels=balance_labels, label_list_ids=label_list_ids)\n resulting_sets[relative_size] = sv\n return resulting_sets", "docstring": "Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus.\n Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times\n with different values. But this method makes sure that every subset contains only utterances,\n that are also contained in the next bigger subset.\n\nArgs:\n relative_sizes (list): A list of numbers between 0 and 1 indicating the sizes of the desired subsets,\n relative to the full corpus.\n by_duration (bool): If True the size measure is the duration of all utterances in a subset/corpus.\n balance_labels (bool): If True the labels contained in a subset are chosen to be balanced\n as far as possible.\n label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered\n for balancing. Otherwise only the ones that are in the list are considered.\n\nReturns:\n dict : A dictionary containing all subsets with the relative size as key.", "source": "codesearchnet_filtered"} +{"code": "def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None):\n if (ignore_index is not None):\n assert (tensor.size() == tensor_other.size())\n mask_arr = tensor.ne(ignore_index)\n tensor = tensor.masked_select(mask_arr)\n tensor_other = tensor_other.masked_select(mask_arr)\n return torch.equal(tensor, tensor_other)", "docstring": "Compute ``torch.equal`` with the optional mask parameter.\n\nArgs:\n ignore_index (int, optional): Specifies a ``tensor`` index that is ignored.\n\nReturns:\n (bool) Returns ``True`` if target and prediction are equal.", "source": "codesearchnet_filtered"} +{"code": "def break_bond(self, ind1, ind2, tol=0.2):\n sites = self._sites\n clusters = [[sites[ind1]], [sites[ind2]]]\n sites = [site for (i, site) in enumerate(sites) if (i not in (ind1, ind2))]\n\n def belongs_to_cluster(site, cluster):\n for test_site in cluster:\n if CovalentBond.is_bonded(site, test_site, tol=tol):\n return True\n return False\n while (len(sites) > 0):\n unmatched = []\n for site in sites:\n for cluster in clusters:\n if belongs_to_cluster(site, cluster):\n cluster.append(site)\n break\n else:\n unmatched.append(site)\n if (len(unmatched) == len(sites)):\n raise ValueError('Not all sites are matched!')\n sites = unmatched\n return (self.__class__.from_sites(cluster) for cluster in clusters)", "docstring": "Returns two molecules based on breaking the bond between atoms at index\n ind1 and ind2.\n\nArgs:\n ind1 (int): Index of first site.\n ind2 (int): Index of second site.\n tol (float): Relative tolerance to test. Basically, the code\n checks if the distance between the sites is less than (1 +\n tol) * typical bond distances. Defaults to 0.2, i.e.,\n 20% longer.\n\nReturns:\n Two Molecule objects representing the two clusters formed from\n breaking the bond.", "source": "codesearchnet_filtered"} +{"code": "def loads(serialized_messages):\n try:\n messages_dicts = json.loads(serialized_messages)\n except ValueError:\n _log.error('Loading serialized messages failed.')\n raise\n messages = []\n for message_dict in messages_dicts:\n try:\n headers = message_dict['headers']\n except KeyError:\n _log.error('Message saved without headers.')\n raise\n try:\n MessageClass = get_class(headers['fedora_messaging_schema'])\n except KeyError:\n _log.error('Message (headers=%r) saved without a schema header.', headers)\n raise\n try:\n body = message_dict['body']\n except KeyError:\n _log.error('Message saved without body.')\n raise\n try:\n id = message_dict['id']\n except KeyError:\n _log.error('Message saved without id.')\n raise\n try:\n queue = message_dict['queue']\n except KeyError:\n _log.warning('Message saved without queue.')\n queue = None\n try:\n topic = message_dict['topic']\n except KeyError:\n _log.error('Message saved without topic.')\n raise\n try:\n severity = headers['fedora_messaging_severity']\n except KeyError:\n _log.error('Message saved without a severity.')\n raise\n message = MessageClass(body=body, topic=topic, headers=headers, severity=severity)\n try:\n message.validate()\n _log.debug('Successfully validated message %r', message)\n except jsonschema.exceptions.ValidationError as e:\n _log.error('Message validation of %r failed: %r', message, e)\n raise ValidationError(e)\n message.queue = queue\n message.id = id\n messages.append(message)\n return messages", "docstring": "Deserialize messages from a JSON formatted str\n\nArgs:\n serialized_messages (JSON str):\n\nReturns:\n list: Deserialized message objects.\n\nRaises:\n ValidationError: If deserialized message validation failed.\n KeyError: If serialized_messages aren't properly serialized.\n ValueError: If serialized_messages is not valid JSON", "source": "codesearchnet_filtered"} +{"code": "def fts_match_all(self, fts, inv):\n return all([self.fts_match(fts, s) for s in inv])", "docstring": "Return `True` if all segments in `inv` matches the features in fts\n\nArgs:\n fts (list): a collection of (value, feature) tuples\n inv (list): a collection of IPA segments represented as Unicode\n strings\n\nReturns:\n bool: `True` if all segments in `inv` matches the features in `fts`", "source": "codesearchnet_filtered"} +{"code": "def time_series(timefile, colnames):\n if (not timefile.is_file()):\n return None\n data = pd.read_csv(timefile, delim_whitespace=True, dtype=str, header=None, skiprows=1, index_col=0, engine='c', memory_map=True, error_bad_lines=False, warn_bad_lines=False)\n data = data.apply(pd.to_numeric, raw=True, errors='coerce')\n rows_to_del = []\n irow = (len(data) - 1)\n while (irow > 0):\n iprev = (irow - 1)\n while ((iprev >= 0) and (data.index[irow] <= data.index[iprev])):\n rows_to_del.append(iprev)\n iprev -= 1\n irow = iprev\n if rows_to_del:\n rows_to_keep = (set(range(len(data))) - set(rows_to_del))\n data = data.take(list(rows_to_keep), convert=False)\n ncols = data.shape[1]\n _tidy_names(colnames, ncols)\n data.columns = colnames\n return data", "docstring": "Read temporal series text file.\n\n If :data:`colnames` is too long, it will be truncated. If it is too short,\n additional numeric column names from 0 to N-1 will be attributed to the N\n extra columns present in :data:`timefile`.\n\nArgs:\n timefile (:class:`pathlib.Path`): path of the time.dat file.\n colnames (list of names): names of the variables expected in\n :data:`timefile` (may be modified).\n\nReturns:\n :class:`pandas.DataFrame`:\n Time series, with the variables in columns and the time steps in\n rows.", "source": "codesearchnet_filtered"} +{"code": "def geosearch(self, latitude=None, longitude=None, radius=1000, title=None, auto_suggest=True, results=10):\n\n def test_lat_long(val):\n ' handle testing lat and long '\n if (not isinstance(val, Decimal)):\n error = 'Latitude and Longitude must be specified either as a Decimal or in formats that can be coerced into a Decimal.'\n try:\n return Decimal(val)\n except (DecimalException, TypeError):\n raise ValueError(error)\n return val\n params = {'list': 'geosearch', 'gsradius': radius, 'gslimit': results}\n if (title is not None):\n if auto_suggest:\n title = self.suggest(title)\n params['gspage'] = title\n else:\n lat = test_lat_long(latitude)\n lon = test_lat_long(longitude)\n params['gscoord'] = '{0}|{1}'.format(lat, lon)\n raw_results = self.wiki_request(params)\n self._check_error_response(raw_results, title)\n return [d['title'] for d in raw_results['query']['geosearch']]", "docstring": "Search for pages that relate to the provided geocoords or near\n the page\n\nArgs:\n latitude (Decimal or None): Latitude geocoord; must be \\\n coercable to decimal\n longitude (Decimal or None): Longitude geocoord; must be \\\n coercable to decimal\n radius (int): Radius around page or geocoords to pull back; \\\n in meters\n title (str): Page title to use as a geocoordinate; this has \\\n precedence over lat/long\n auto_suggest (bool): Auto-suggest the page title\n results (int): Number of pages within the radius to return\n\nReturns:\n list: A listing of page titles\n\nRaises:\n ValueError: If either the passed latitutde or longitude are \\\n not coercable to a Decimal", "source": "codesearchnet_filtered"} +{"code": "def get_subdomain(url):\n if (url not in URLHelper.__cache):\n URLHelper.__cache[url] = urlparse(url)\n return '.'.join(URLHelper.__cache[url].netloc.split('.')[:(- 2)])", "docstring": "Get the subdomain of the given URL.\n\nArgs:\n url (str): The URL to get the subdomain from.\n\nReturns:\n str: The subdomain(s)", "source": "codesearchnet_filtered"} +{"code": "def get_header(vcf_file_path):\n logger.info('Parsing header of file {0}'.format(vcf_file_path))\n head = HeaderParser()\n handle = get_vcf_handle(infile=vcf_file_path)\n for line in handle:\n line = line.rstrip()\n if line.startswith('#'):\n if line.startswith('##'):\n head.parse_meta_data(line)\n else:\n head.parse_header_line(line)\n else:\n break\n handle.close()\n return head", "docstring": "Parse the header and return a header object\n\nArgs:\n vcf_file_path(str): Path to vcf\n\nReturns:\n head: A HeaderParser object", "source": "codesearchnet_filtered"} +{"code": "def power(self, n):\n if (not isinstance(n, int)):\n raise QiskitError('Can only take integer powers of Operator.')\n if (self.input_dims() != self.output_dims()):\n raise QiskitError('Can only power with input_dims = output_dims.')\n return Operator(np.linalg.matrix_power(self.data, n), self.input_dims(), self.output_dims())", "docstring": "Return the matrix power of the operator.\n\nArgs:\n n (int): the power to raise the matrix to.\n\nReturns:\n BaseOperator: the n-times composed operator.\n\nRaises:\n QiskitError: if the input and output dimensions of the operator\n are not equal, or the power is not a positive integer.", "source": "codesearchnet_filtered"} +{"code": "def get_pattern_link_topattern(self, patternnumber):\n _checkPatternNumber(patternnumber)\n address = _calculateRegisterAddress('linkpattern', patternnumber)\n return self.read_register(address)", "docstring": "Get the 'linked pattern' value for a given pattern.\n\nArgs:\n patternnumber (integer): From 0-7\n\nReturns:\n The 'linked pattern' value (int).", "source": "codesearchnet_filtered"} +{"code": "def delete(self, vid):\n command = ('no vlan %s' % vid)\n return (self.configure(command) if isvlan(vid) else False)", "docstring": "Deletes a VLAN from the running configuration\n\nArgs:\n vid (str): The VLAN ID to delete\n\nReturns:\n True if the operation was successful otherwise False", "source": "codesearchnet_filtered"} +{"code": "def get_doc_id(document_pb, expected_prefix):\n (prefix, document_id) = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1)\n if (prefix != expected_prefix):\n raise ValueError('Unexpected document name', document_pb.name, 'Expected to begin with', expected_prefix)\n return document_id", "docstring": "Parse a document ID from a document protobuf.\n\nArgs:\n document_pb (google.cloud.proto.firestore.v1beta1.\\\n document_pb2.Document): A protobuf for a document that\n was created in a ``CreateDocument`` RPC.\n expected_prefix (str): The expected collection prefix for the\n fully-qualified document name.\n\nReturns:\n str: The document ID from the protobuf.\n\nRaises:\n ValueError: If the name does not begin with the prefix.", "source": "codesearchnet_filtered"} +{"code": "def gene_to_panels(self, case_obj):\n LOG.info('Building gene to panels')\n gene_dict = {}\n for panel_info in case_obj.get('panels', []):\n panel_name = panel_info['panel_name']\n panel_version = panel_info['version']\n panel_obj = self.gene_panel(panel_name, version=panel_version)\n if (not panel_obj):\n LOG.warning('Panel: {0}, version {1} does not exist in database'.format(panel_name, panel_version))\n for gene in panel_obj['genes']:\n hgnc_id = gene['hgnc_id']\n if (hgnc_id not in gene_dict):\n gene_dict[hgnc_id] = set([panel_name])\n continue\n gene_dict[hgnc_id].add(panel_name)\n LOG.info('Gene to panels done')\n return gene_dict", "docstring": "Fetch all gene panels and group them by gene\n\nArgs:\n case_obj(scout.models.Case)\n\nReturns:\n gene_dict(dict): A dictionary with gene as keys and a set of\n panel names as value", "source": "codesearchnet_filtered"} +{"code": "def _args2_fpath(dpath, fname, cfgstr, ext):\n if ((len(ext) > 0) and (ext[0] != '.')):\n raise ValueError('Please be explicit and use a dot in ext')\n max_len = 128\n cfgstr_hashlen = 16\n prefix = fname\n fname_cfgstr = consensed_cfgstr(prefix, cfgstr, max_len=max_len, cfgstr_hashlen=cfgstr_hashlen)\n fpath = join(dpath, (fname_cfgstr + ext))\n fpath = normpath(fpath)\n return fpath", "docstring": "r\"\"\"\n Ensures that the filename is not too long\n\n Internal util_cache helper function\n Windows MAX_PATH=260 characters\n Absolute length is limited to 32,000 characters\n Each filename component is limited to 255 characters\n\nArgs:\n dpath (str):\n fname (str):\n cfgstr (str):\n ext (str):\n\nReturns:\n str: fpath\n\n CommandLine:\n python -m utool.util_cache --test-_args2_fpath\n\nExample:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_cache import * # NOQA\n >>> from utool.util_cache import _args2_fpath\n >>> import utool as ut\n >>> dpath = 'F:\\\\data\\\\work\\\\PZ_MTEST\\\\_ibsdb\\\\_ibeis_cache'\n >>> fname = 'normalizer_'\n >>> cfgstr = u'PZ_MTEST_DSUUIDS((9)67j%dr%&bl%4oh4+)_QSUUIDS((9)67j%dr%&bl%4oh4+)zebra_plains_vsone_NN(single,K1+1,last,cks1024)_FILT(ratio<0.625;1.0,fg;1.0)_SV(0.01;2;1.57minIn=4,nRR=50,nsum,)_AGG(nsum)_FLANN(4_kdtrees)_FEATWEIGHT(ON,uselabel,rf)_FEAT(hesaff+sift_)_CHIP(sz450)'\n >>> ext = '.cPkl'\n >>> fpath = _args2_fpath(dpath, fname, cfgstr, ext)\n >>> result = str(ut.ensure_unixslash(fpath))\n >>> target = 'F:/data/work/PZ_MTEST/_ibsdb/_ibeis_cache/normalizer_xfylfboirymmcpfg.cPkl'\n >>> ut.assert_eq(result, target)", "source": "codesearchnet_filtered"} +{"code": "def find_nearest(a, value, index=False):\n i = np.abs((a - value)).argmin()\n if index:\n return i\n else:\n return a[i]", "docstring": "Find the array value, or index of the array value, closest to some given\n value.\n\nArgs:\n a (ndarray)\n value (float)\n index (bool): whether to return the index instead of the array value.\n\nReturns:\n float. The array value (or index, as int) nearest the specified value.", "source": "codesearchnet_filtered"} +{"code": "def validate_service_config_changed(self, sentry_unit, mtime, service, filename, pgrep_full=None, sleep_time=20, retry_count=30, retry_sleep_time=10):\n service_restart = self.service_restarted_since(sentry_unit, mtime, service, pgrep_full=pgrep_full, sleep_time=sleep_time, retry_count=retry_count, retry_sleep_time=retry_sleep_time)\n config_update = self.config_updated_since(sentry_unit, filename, mtime, sleep_time=sleep_time, retry_count=retry_count, retry_sleep_time=retry_sleep_time)\n return (service_restart and config_update)", "docstring": "Check service and file were updated after mtime\n\nArgs:\n sentry_unit (sentry): The sentry unit to check for the service on\n mtime (float): The epoch time to check against\n service (string): service name to look for in process table\n filename (string): The file to check mtime of\n pgrep_full: [Deprecated] Use full command line search mode with pgrep\n sleep_time (int): Initial sleep in seconds to pass to test helpers\n retry_count (int): If service is not found, how many times to retry\n retry_sleep_time (int): Time in seconds to wait between retries\n\n Typical Usage:\n u = OpenStackAmuletUtils(ERROR)\n ...\n mtime = u.get_sentry_time(self.cinder_sentry)\n self.d.configure('cinder', {'verbose': 'True', 'debug': 'True'})\n if not u.validate_service_config_changed(self.cinder_sentry,\n mtime,\n 'cinder-api',\n '/etc/cinder/cinder.conf')\n amulet.raise_status(amulet.FAIL, msg='update failed')\n\nReturns:\n bool: True if both service and file where updated/restarted after\n mtime, False if service is older than mtime or if service was\n not found or if filename was modified before mtime.", "source": "codesearchnet_filtered"} +{"code": "def get_student_current_grade(self, username, course_id):\n resp = self.requester.get(urljoin(self.base_url, '/api/grades/v1/courses/{course_key}/?username={username}'.format(username=username, course_key=course_id)))\n resp.raise_for_status()\n return CurrentGrade(resp.json()[0])", "docstring": "Returns an CurrentGrade object for the user in a course\n\nArgs:\n username (str): an edx user's username\n course_id (str): an edX course id.\n\nReturns:\n CurrentGrade: object representing the student current grade for a course", "source": "codesearchnet_filtered"} +{"code": "def licenses(self):\n buf_size = self.MAX_BUF_SIZE\n buf = (ctypes.c_char * buf_size)()\n res = self._dll.JLINK_GetAvailableLicense(buf, buf_size)\n if (res < 0):\n raise errors.JLinkException(res)\n return ctypes.string_at(buf).decode()", "docstring": "Returns a string of the built-in licenses the J-Link has.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n String of the contents of the built-in licenses the J-Link has.", "source": "codesearchnet_filtered"} +{"code": "def _log_submission(submission, student_item):\n logger.info(u'Created submission uuid={submission_uuid} for (course_id={course_id}, item_id={item_id}, anonymous_student_id={anonymous_student_id})'.format(submission_uuid=submission['uuid'], course_id=student_item['course_id'], item_id=student_item['item_id'], anonymous_student_id=student_item['student_id']))", "docstring": "Log the creation of a submission.\n\nArgs:\n submission (dict): The serialized submission model.\n student_item (dict): The serialized student item model.\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def to_voxels(array):\n if (type(array) is not numpy.ndarray):\n raise ValueError('array argument must be of type numpy.ndarray')\n return numpy.argwhere(array)", "docstring": "Converts an array to its voxel list.\n\nArgs:\n array (numpy.ndarray): A numpy nd array. This must be boolean!\n\nReturns:\n A list of n-tuples", "source": "codesearchnet_filtered"} +{"code": "def _update_seek(self, offset, whence):\n with self._seek_lock:\n if (whence == SEEK_SET):\n self._seek = offset\n elif (whence == SEEK_CUR):\n self._seek += offset\n elif (whence == SEEK_END):\n self._seek = (offset + self._size)\n else:\n raise ValueError(('whence value %s unsupported' % whence))\n return self._seek", "docstring": "Update seek value.\n\nArgs:\n offset (int): Offset.\n whence (int): Whence.\n\nReturns:\n int: Seek position.", "source": "codesearchnet_filtered"} +{"code": "def wait_for_transform_job(self, job, poll=5):\n desc = _wait_until((lambda : _transform_job_status(self.sagemaker_client, job)), poll)\n self._check_job_status(job, desc, 'TransformJobStatus')\n return desc", "docstring": "Wait for an Amazon SageMaker transform job to complete.\n\nArgs:\n job (str): Name of the transform job to wait for.\n poll (int): Polling interval in seconds (default: 5).\n\nReturns:\n (dict): Return value from the ``DescribeTransformJob`` API.\n\nRaises:\n ValueError: If the transform job fails.", "source": "codesearchnet_filtered"} +{"code": "def get_collections(self, unit, names=None, merge=False, sampling_rate=None, **entities):\n nodes = self.get_nodes(unit, entities)\n var_sets = []\n for n in nodes:\n var_set = list(n.variables.values())\n var_set = [v for v in var_set if v.matches_entities(entities)]\n if (names is not None):\n var_set = [v for v in var_set if (v.name in names)]\n if (unit != 'run'):\n var_set = [v.filter(entities) for v in var_set]\n var_sets.append(var_set)\n if merge:\n var_sets = [list(chain(*var_sets))]\n results = []\n for vs in var_sets:\n if (not vs):\n continue\n if (unit == 'run'):\n vs = clc.BIDSRunVariableCollection(vs, sampling_rate)\n else:\n vs = clc.BIDSVariableCollection(vs)\n results.append(vs)\n if merge:\n return (results[0] if results else None)\n return results", "docstring": "Retrieve variable data for a specified level in the Dataset.\n\nArgs:\n unit (str): The unit of analysis to return variables for. Must be\n one of 'run', 'session', 'subject', or 'dataset'.\n names (list): Optional list of variables names to return. If\n None, all available variables are returned.\n merge (bool): If True, variables are merged across all observations\n of the current unit. E.g., if unit='subject' and return_type=\n 'collection', variablesfrom all subjects will be merged into a\n single collection. If False, each observation is handled\n separately, and the result is returned as a list.\n sampling_rate (int, str): If unit='run', the sampling rate to\n pass onto the returned BIDSRunVariableCollection.\n entities: Optional constraints used to limit what gets returned.\n\n Returns:", "source": "codesearchnet_filtered"} +{"code": "def check_config(config, path):\n messages = []\n config_copy = get_frozen_copy(config)\n missing_keys = (set(DEFAULT_CONFIG.keys()) - set(config_copy.keys()))\n if missing_keys:\n messages.append('Missing config keys {}!'.format(missing_keys))\n for (key, value) in config_copy.items():\n if (key not in DEFAULT_CONFIG):\n messages.append('Unknown key {} in {}!'.format(key, path))\n continue\n if (value is None):\n messages.append(_VALUE_UNDEFINED_MESSAGE.format(path=path, key=key))\n else:\n value_type = type(value)\n if (isinstance(DEFAULT_CONFIG[key], Mapping) and ('by-cot-product' in DEFAULT_CONFIG[key])):\n default_type = type(DEFAULT_CONFIG[key]['by-cot-product'][config['cot_product']])\n else:\n default_type = type(DEFAULT_CONFIG[key])\n if (value_type is not default_type):\n messages.append('{} {}: type {} is not {}!'.format(path, key, value_type, default_type))\n if (value in ('...', b'...')):\n messages.append(_VALUE_UNDEFINED_MESSAGE.format(path=path, key=key))\n if ((key in ('provisioner_id', 'worker_group', 'worker_type', 'worker_id')) and (not _is_id_valid(value))):\n messages.append('{} doesn\\'t match \"{}\" (required by Taskcluster)'.format(key, _GENERIC_ID_REGEX.pattern))\n return messages", "docstring": "Validate the config against DEFAULT_CONFIG.\n\n Any unknown keys or wrong types will add error messages.\n\nArgs:\n config (dict): the running config.\n path (str): the path to the config file, used in error messages.\n\nReturns:\n list: the error messages found when validating the config.", "source": "codesearchnet_filtered"} +{"code": "def _parse_corporations(self, datafield, subfield, roles=['any']):\n if (len(datafield) != 3):\n raise ValueError('datafield parameter have to be exactly 3 chars long!')\n if (len(subfield) != 1):\n raise ValueError('Bad subfield specification - subield have to be 3 chars long!')\n parsed_corporations = []\n for corporation in self.get_subfields(datafield, subfield):\n other_subfields = corporation.other_subfields\n if (('4' in other_subfields) and (roles != ['any'])):\n corp_roles = other_subfields['4']\n relevant = any(map((lambda role: (role in roles)), corp_roles))\n if (not relevant):\n continue\n name = ''\n place = ''\n date = ''\n name = corporation\n if ('c' in other_subfields):\n place = ','.join(other_subfields['c'])\n if ('d' in other_subfields):\n date = ','.join(other_subfields['d'])\n parsed_corporations.append(Corporation(name, place, date))\n return parsed_corporations", "docstring": "Parse informations about corporations from given field identified\n by `datafield` parameter.\n\nArgs:\n datafield (str): MARC field ID (\"``110``\", \"``610``\", etc..)\n subfield (str): MARC subfield ID with name, which is typically\n stored in \"``a``\" subfield.\n roles (str): specify which roles you need. Set to ``[\"any\"]`` for\n any role, ``[\"dst\"]`` for distributors, etc.. For\n details, see\n http://www.loc.gov/marc/relators/relaterm.html\n\nReturns:\n list: :class:`Corporation` objects.", "source": "codesearchnet_filtered"} +{"code": "def get_signature_request(self, signature_request_id, ux_version=None):\n request = self._get_request()\n parameters = None\n if (ux_version is not None):\n parameters = {'ux_version': ux_version}\n return request.get((self.SIGNATURE_REQUEST_INFO_URL + signature_request_id), parameters=parameters)", "docstring": "Get a signature request by its ID\n\nArgs:\n signature_request_id (str): The id of the SignatureRequest to retrieve\n\n ux_version (int): UX version, either 1 (default) or 2.\n\nReturns:\n A SignatureRequest object", "source": "codesearchnet_filtered"} +{"code": "def create_or_update(cls, video, language_code, metadata, file_data=None):\n try:\n video_transcript = cls.objects.get(video=video, language_code=language_code)\n retrieved = True\n except cls.DoesNotExist:\n video_transcript = cls(video=video, language_code=language_code)\n retrieved = False\n for (prop, value) in six.iteritems(metadata):\n if (prop in ['language_code', 'file_format', 'provider']):\n setattr(video_transcript, prop, value)\n transcript_name = metadata.get('file_name')\n try:\n if transcript_name:\n video_transcript.transcript.name = transcript_name\n elif file_data:\n with closing(file_data) as transcript_file_data:\n file_name = '{uuid}.{ext}'.format(uuid=uuid4().hex, ext=video_transcript.file_format)\n video_transcript.transcript.save(file_name, transcript_file_data)\n video_transcript.save()\n except Exception:\n logger.exception('[VAL] Transcript save failed to storage for video_id \"%s\" language code \"%s\"', video.edx_video_id, language_code)\n raise\n return (video_transcript, (not retrieved))", "docstring": "Create or update Transcript object.\n\nArgs:\n video (Video): Video for which transcript is going to be saved.\n language_code (str): language code for (to be created/updated) transcript\n metadata (dict): A dict containing (to be overwritten) properties\n file_data (InMemoryUploadedFile): File data to be saved\n\nReturns:\n Returns a tuple of (video_transcript, created).", "source": "codesearchnet_filtered"} +{"code": "def set_enable(self, name, vrid, value=False, run=True):\n if (value is False):\n cmd = ('vrrp %d shutdown' % vrid)\n elif (value is True):\n cmd = ('no vrrp %d shutdown' % vrid)\n else:\n raise ValueError(\"vrrp property 'enable' must be True or False\")\n if run:\n result = self.configure_interface(name, cmd)\n if (result is False):\n return self.error\n return result\n return cmd", "docstring": "Set the enable property of the vrrp\n\nArgs:\n name (string): The interface to configure.\n vrid (integer): The vrid number for the vrrp to be managed.\n value (boolean): True to enable the vrrp, False to disable.\n run (boolean): True to execute the command, False to\n return a string with the formatted command.\n\nReturns:\n If run is True, returns True if the command executed successfully,\n error if failure\n\n If run is False, returns the formatted command string which can\n be passed to the node", "source": "codesearchnet_filtered"} +{"code": "def filter_sequences(self, seq_type):\n return DictList((x for x in self.sequences if isinstance(x, seq_type)))", "docstring": "Return a DictList of only specified types in the sequences attribute.\n\nArgs:\n seq_type (SeqProp): Object type\n\nReturns:\n DictList: A filtered DictList of specified object type only", "source": "codesearchnet_filtered"} +{"code": "def map_structprop_resnums_to_seqprop_resnums(self, resnums, structprop=None, chain_id=None, seqprop=None, use_representatives=False):\n resnums = ssbio.utils.force_list(resnums)\n if use_representatives:\n seqprop = self.representative_sequence\n structprop = self.representative_structure\n chain_id = self.representative_chain\n if (not structprop):\n raise ValueError('No representative structure set, please specify sequence, structure, and chain ID')\n elif ((not seqprop) or (not structprop) or (not chain_id)):\n raise ValueError('Please specify sequence, structure, and chain ID')\n if (structprop.id == self.representative_structure.id):\n full_structure_id = '{}-{}'.format(structprop.id, chain_id).replace('REP-', '')\n else:\n full_structure_id = '{}-{}'.format(structprop.id, chain_id)\n aln_id = '{}_{}'.format(seqprop.id, full_structure_id)\n access_key = '{}_chain_index'.format(aln_id)\n if (access_key not in seqprop.letter_annotations):\n raise KeyError('{}: structure mapping {} not available in sequence letter annotations. Was alignment parsed? Run ``align_seqprop_to_structprop`` with ``parse=True``.'.format(access_key, aln_id))\n chain = structprop.chains.get_by_id(chain_id)\n chain_structure_resnum_mapping = chain.seq_record.letter_annotations['structure_resnums']\n final_mapping = {}\n for resnum in resnums:\n resnum = int(resnum)\n resnum_index = chain_structure_resnum_mapping.index(resnum)\n struct_res_singleaa = structprop.chains.get_by_id(chain_id).seq_record[resnum_index]\n what = seqprop.letter_annotations[access_key].index((resnum_index + 1))\n seq_res_singleaa = seqprop[what]\n sp_resnum = (what + 1)\n final_mapping[resnum] = sp_resnum\n format_data = {'seqprop_id': seqprop.id, 'seqprop_resid': seq_res_singleaa, 'seqprop_resnum': sp_resnum, 'structprop_id': structprop.id, 'structprop_chid': chain_id, 'structprop_resid': struct_res_singleaa, 'structprop_resnum': resnum}\n if (struct_res_singleaa != seq_res_singleaa):\n log.warning('Sequence {seqprop_id} residue {seqprop_resid}{seqprop_resnum} does not match to structure {structprop_id}-{structprop_chid} residue {structprop_resid}{structprop_resnum}. NOTE: this may be due to structural differences'.format(**format_data))\n else:\n log.debug('Sequence {seqprop_id} residue {seqprop_resid}{seqprop_resnum} is mapped to structure {structprop_id}-{structprop_chid} residue {structprop_resid}{structprop_resnum}'.format(**format_data))\n return final_mapping", "docstring": "Map a residue number in any StructProp + chain ID to any SeqProp's residue number.\n\nArgs:\n resnums (int, list): Residue numbers in the structure\n structprop (StructProp): StructProp object\n chain_id (str): Chain ID to map from\n seqprop (SeqProp): SeqProp object\n use_representatives (bool): If the representative sequence and structure should be used. If True, seqprop,\n structprop, and chain_id do not need to be defined.\n\nReturns:\n dict: Mapping of structure residue numbers to sequence residue numbers", "source": "codesearchnet_filtered"} +{"code": "def rsolve(A, b, epsilon=_epsilon):\n A = asarray(A, float)\n b = asarray(b, float)\n if (A.shape[0] == 0):\n return zeros((A.shape[1],))\n if (A.shape[1] == 0):\n return zeros((0,))\n try:\n x = lstsq(A, b, rcond=epsilon)\n r = sum((x[3] > epsilon))\n if (r == 0):\n return zeros(A.shape[1])\n return x[0]\n except (ValueError, LinAlgError) as e:\n warnings.warn(str(e), RuntimeWarning)\n return solve(A, b)", "docstring": "r\"\"\"Robust solve for the linear equations.\n\nArgs:\n A (array_like): Coefficient matrix.\n b (array_like): Ordinate values.\n\nReturns:\n :class:`numpy.ndarray`: Solution ``x``.", "source": "codesearchnet_filtered"} +{"code": "def stop(name=None, backdate=None, unique=None, keep_subdivisions=None, quick_print=None, un=None, ks=None, qp=None):\n t = timer()\n if f.t.stopped:\n raise StoppedError('Timer already stopped.')\n if (backdate is None):\n t_stop = t\n else:\n if (f.t is f.root):\n raise BackdateError('Cannot backdate stop of root timer.')\n if (not isinstance(backdate, float)):\n raise TypeError('Backdate must be type float.')\n if (backdate > t):\n raise BackdateError('Cannot backdate to future time.')\n if (backdate < f.t.last_t):\n raise BackdateError('Cannot backdate to time earlier than last stamp.')\n t_stop = backdate\n unique = (SET['UN'] if ((unique is None) and (un is None)) else bool((unique or un)))\n keep_subdivisions = (SET['KS'] if ((keep_subdivisions is None) and (ks is None)) else bool((keep_subdivisions or ks)))\n quick_print = (SET['QP'] if ((quick_print is None) and (qp is None)) else bool((quick_print or qp)))\n if (name is not None):\n if f.t.paused:\n raise PausedError('Cannot stamp paused timer.')\n elapsed = (t_stop - f.t.last_t)\n _stamp(name, elapsed, unique, keep_subdivisions, quick_print)\n else:\n times_priv.assign_subdivisions(UNASGN, keep_subdivisions)\n for s in f.t.rgstr_stamps:\n if (s not in f.s.cum):\n f.s.cum[s] = 0.0\n f.s.order.append(s)\n if (not f.t.paused):\n f.t.tmp_total += (t_stop - f.t.start_t)\n f.t.tmp_total -= f.t.self_cut\n f.t.self_cut += (timer() - t)\n times_priv.dump_times()\n f.t.stopped = True\n if quick_print:\n print('({}) Total: {:.4f}'.format(f.t.name, f.r.total))\n return t", "docstring": "Mark the end of timing. Optionally performs a stamp, hence accepts the\n same arguments.\n\nNote:\n If keeping subdivisions and not calling a stamp, any awaiting subdivisions\n will be assigned to a special 'UNASSIGNED' position to indicate that they\n are not properly accounted for in the hierarchy (these can happen at\n different places and may be combined inadvertently).\n\n Backdating: For subdivisions only. Backdate time must be in the past\n but more recent than the latest stamp.\n\nArgs:\n name (any, optional): If used, passed to a call to stamp()\n backdate (float, optional): time to use for stop instead of current\n unique (bool, optional): see stamp()\n keep_subdivisions (bool, optional): keep awaiting subdivisions\n quick_print (bool, optional): boolean, print total time\n un (bool, optional): see stamp()\n ks (bool, optional): see stamp()\n qp (bool, optional): see stamp()\n\nReturns:\n float: The current time.\n\nRaises:\n BackdateError: If given backdate is out of range, or if used in root timer.\n PausedError: If attempting stamp in paused timer.\n StoppedError: If timer already stopped.\n TypeError: If given backdate value is not type float.", "source": "codesearchnet_filtered"} +{"code": "def get_course_current_grades(self, course_id):\n resp = self.requester.get(urljoin(self.base_url, '/api/grades/v1/courses/{course_key}/'.format(course_key=course_id)))\n resp.raise_for_status()\n resp_json = resp.json()\n if ('results' in resp_json):\n grade_entries = [CurrentGrade(entry) for entry in resp_json['results']]\n while (resp_json['next'] is not None):\n resp = self.requester.get(resp_json['next'])\n resp.raise_for_status()\n resp_json = resp.json()\n grade_entries.extend((CurrentGrade(entry) for entry in resp_json['results']))\n else:\n grade_entries = [CurrentGrade(entry) for entry in resp_json]\n return CurrentGradesByCourse(grade_entries)", "docstring": "Returns a CurrentGradesByCourse object for all users in the specified course.\n\nArgs:\n course_id (str): an edX course ids.\n\nReturns:\n CurrentGradesByCourse: object representing the student current grades\n\n Authorization:\n The authenticated user must have staff permissions to see grades for all users\n in a course.", "source": "codesearchnet_filtered"} +{"code": "def tas53(msg):\n d = hex2bin(data(msg))\n if (d[33] == '0'):\n return None\n tas = (bin2int(d[34:46]) * 0.5)\n return round(tas, 1)", "docstring": "Aircraft true airspeed, BDS 5,3 message\n\nArgs:\n msg (String): 28 bytes hexadecimal message\n\nReturns:\n float: true airspeed in knots", "source": "codesearchnet_filtered"} +{"code": "def delete(self, dry=False, meta=None, index_fields=None):\n from datetime import datetime\n if (not dry):\n self.pre_delete()\n (results, errors) = self._delete_relations(dry)\n if (not (dry or errors)):\n self.deleted = True\n self.deleted_at = datetime.now()\n self.save(internal=True, meta=meta, index_fields=index_fields)\n self.post_delete()\n if settings.ENABLE_CACHING:\n cache.delete(self.key)\n return (results, errors)", "docstring": "Sets the objects \"deleted\" field to True and,\n current time to \"deleted_at\" fields then saves it to DB.\n\nArgs:\n dry (bool): False. Do not execute the actual deletion.\n Just list what will be deleted as a result of relations.\n meta (dict): JSON serializable meta data for logging of save operation.\n {'lorem': 'ipsum', 'dolar': 5}\n index_fields (list): Tuple list for secondary indexing keys in riak (with 'bin' or 'int').\n bin is used for string fields, int is used for integer fields.\n [('lorem','bin'),('dolar','int')]\n\nReturns:\n Tuple. (results [], errors [])", "source": "codesearchnet_filtered"} +{"code": "def E(poly, dist=None, **kws):\n if (not isinstance(poly, (distributions.Dist, polynomials.Poly))):\n print(type(poly))\n print('Approximating expected value...')\n out = quadrature.quad(poly, dist, veceval=True, **kws)\n print('done')\n return out\n if isinstance(poly, distributions.Dist):\n (dist, poly) = (poly, polynomials.variable(len(poly)))\n if (not poly.keys):\n return numpy.zeros(poly.shape, dtype=int)\n if isinstance(poly, (list, tuple, numpy.ndarray)):\n return [E(_, dist, **kws) for _ in poly]\n if (poly.dim < len(dist)):\n poly = polynomials.setdim(poly, len(dist))\n shape = poly.shape\n poly = polynomials.flatten(poly)\n keys = poly.keys\n mom = dist.mom(numpy.array(keys).T, **kws)\n A = poly.A\n if (len(dist) == 1):\n mom = mom[0]\n out = numpy.zeros(poly.shape)\n for i in range(len(keys)):\n out += (A[keys[i]] * mom[i])\n out = numpy.reshape(out, shape)\n return out", "docstring": "Expected value operator.\n\n 1st order statistics of a probability distribution or polynomial on a given\n probability space.\n\nArgs:\n poly (Poly, Dist):\n Input to take expected value on.\n dist (Dist):\n Defines the space the expected value is taken on. It is ignored if\n ``poly`` is a distribution.\n\nReturns:\n (numpy.ndarray):\n The expected value of the polynomial or distribution, where\n ``expected.shape == poly.shape``.\n\nExample:\n >>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))\n >>> print(chaospy.E(dist))\n [1. 0.]\n >>> x, y = chaospy.variable(2)\n >>> poly = chaospy.Poly([1, x, y, 10*x*y])\n >>> print(chaospy.E(poly, dist))\n [1. 1. 0. 0.]", "source": "codesearchnet_filtered"} +{"code": "def td_sp(points, speed_threshold):\n if (len(points) <= 2):\n return points\n else:\n max_speed_threshold = 0\n found_index = 0\n for i in range(1, (len(points) - 1)):\n dt1 = time_dist(points[i], points[(i - 1)])\n if (dt1 == 0):\n dt1 = 1e-09\n vim = (loc_dist(points[i], points[(i - 1)]) / dt1)\n dt2 = time_dist(points[(i + 1)], points[i])\n if (dt2 == 0):\n dt2 = 1e-09\n vi_ = (loc_dist(points[(i + 1)], points[i]) / dt2)\n if (abs((vi_ - vim)) > max_speed_threshold):\n max_speed_threshold = abs((vi_ - vim))\n found_index = i\n if (max_speed_threshold > speed_threshold):\n one = td_sp(points[:found_index], speed_threshold)\n two = td_sp(points[found_index:], speed_threshold)\n one.extend(two)\n return one\n else:\n return [points[0], points[(- 1)]]", "docstring": "Top-Down Speed-Based Trajectory Compression Algorithm\n\n Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf\n\nArgs:\n points (:obj:`list` of :obj:`Point`): trajectory or part of it\n speed_threshold (float): max speed error, in km/h\n\nReturns:\n :obj:`list` of :obj:`Point`, compressed trajectory", "source": "codesearchnet_filtered"} +{"code": "def convert_positional_argument(self, index, arg_value):\n if self._has_self:\n if (index == 0):\n return arg_value\n index -= 1\n arg_name = self.arg_names[index]\n return self.convert_argument(arg_name, arg_value)", "docstring": "Convert and validate a positional argument.\n\nArgs:\n index (int): The positional index of the argument\n arg_value (object): The value to convert and validate\n\nReturns:\n object: The converted value.", "source": "codesearchnet_filtered"} +{"code": "def longest_existing_path(_path):\n existing_path = _path\n while True:\n _path_new = os.path.dirname(existing_path)\n if exists(_path_new):\n existing_path = _path_new\n break\n if (_path_new == existing_path):\n print('!!! [utool] This is a very illformated path indeed.')\n existing_path = ''\n break\n existing_path = _path_new\n return existing_path", "docstring": "r\"\"\"\n Returns the longest root of _path that exists\n\nArgs:\n _path (str): path string\n\nReturns:\n str: _path - path string\n\n CommandLine:\n python -m utool.util_path --exec-longest_existing_path\n\nExample:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_path import * # NOQA\n >>> import utool as ut\n >>> target = dirname(ut.__file__)\n >>> _path = join(target, 'nonexist/foobar')\n >>> existing_path = longest_existing_path(_path)\n >>> result = ('existing_path = %s' % (str(existing_path),))\n >>> print(result)\n >>> assert existing_path == target", "source": "codesearchnet_filtered"} +{"code": "def select(self, field_paths):\n field_paths = list(field_paths)\n for field_path in field_paths:\n field_path_module.split_field_path(field_path)\n new_projection = query_pb2.StructuredQuery.Projection(fields=[query_pb2.StructuredQuery.FieldReference(field_path=field_path) for field_path in field_paths])\n return self.__class__(self._parent, projection=new_projection, field_filters=self._field_filters, orders=self._orders, limit=self._limit, offset=self._offset, start_at=self._start_at, end_at=self._end_at)", "docstring": "Project documents matching query to a limited set of fields.\n\n See :meth:`~.firestore_v1beta1.client.Client.field_path` for\n more information on **field paths**.\n\n If the current query already has a projection set (i.e. has already\n called :meth:`~.firestore_v1beta1.query.Query.select`), this\n will overwrite it.\n\nArgs:\n field_paths (Iterable[str, ...]): An iterable of field paths\n (``.``-delimited list of field names) to use as a projection\n of document fields in the query results.\n\nReturns:\n ~.firestore_v1beta1.query.Query: A \"projected\" query. Acts as\n a copy of the current query, modified with the newly added\n projection.\n\nRaises:\n ValueError: If any ``field_path`` is invalid.", "source": "codesearchnet_filtered"} +{"code": "def dataset_exists(client, dataset_reference):\n from google.cloud.exceptions import NotFound\n try:\n client.get_dataset(dataset_reference)\n return True\n except NotFound:\n return False", "docstring": "Return if a dataset exists.\n\nArgs:\n client (google.cloud.bigquery.client.Client):\n A client to connect to the BigQuery API.\n dataset_reference (google.cloud.bigquery.dataset.DatasetReference):\n A reference to the dataset to look for.\n\nReturns:\n bool: ``True`` if the dataset exists, ``False`` otherwise.", "source": "codesearchnet_filtered"} +{"code": "def _remove_hidden_parts(projected_surface):\n surface = np.copy(projected_surface)\n surface[(~ _make_occlusion_mask(projected_surface))] = np.nan\n return surface", "docstring": "Removes parts of a projected surface that are not visible.\n\nArgs:\n projected_surface (surface): the surface to use\n\nReturns:\n surface: A projected surface.", "source": "codesearchnet_filtered"} +{"code": "def delete_case(self, case_id=None, institute_id=None, display_name=None):\n query = {}\n if case_id:\n query['_id'] = case_id\n LOG.info('Deleting case %s', case_id)\n else:\n if (not (institute_id and display_name)):\n raise ValueError('Have to provide both institute_id and display_name')\n LOG.info('Deleting case %s institute %s', display_name, institute_id)\n query['owner'] = institute_id\n query['display_name'] = display_name\n result = self.case_collection.delete_one(query)\n return result", "docstring": "Delete a single case from database\n\nArgs:\n institute_id(str)\n case_id(str)\n\nReturns:\n case_obj(dict): The case that was deleted", "source": "codesearchnet_filtered"} +{"code": "def Acf(poly, dist, N=None, **kws):\n if (N is None):\n N = ((len(poly) / 2) + 1)\n corr = Corr(poly, dist, **kws)\n out = numpy.empty(N)\n for n in range(N):\n out[n] = numpy.mean(corr.diagonal(n), 0)\n return out", "docstring": "Auto-correlation function.\n\nArgs:\n poly (Poly):\n Polynomial of interest. Must have ``len(poly) > N``.\n dist (Dist):\n Defines the space the correlation is taken on.\n N (int):\n The number of time steps appart included. If omited set to\n ``len(poly)/2+1``.\n\nReturns:\n (numpy.ndarray) :\n Auto-correlation of ``poly`` with shape ``(N,)``. Note that by\n definition ``Q[0]=1``.\n\nExample:\n >>> poly = chaospy.prange(10)[1:]\n >>> Z = chaospy.Uniform()\n >>> print(numpy.around(chaospy.Acf(poly, Z, 5), 4))\n [1. 0.9915 0.9722 0.9457 0.9127]", "source": "codesearchnet_filtered"} +{"code": "def sia(transition, direction=Direction.BIDIRECTIONAL):\n validate.direction(direction, allow_bi=True)\n log.info('Calculating big-alpha for %s...', transition)\n if (not transition):\n log.info('Transition %s is empty; returning null SIA immediately.', transition)\n return _null_ac_sia(transition, direction)\n if (not connectivity.is_weak(transition.network.cm, transition.node_indices)):\n log.info('%s is not strongly/weakly connected; returning null SIA immediately.', transition)\n return _null_ac_sia(transition, direction)\n log.debug('Finding unpartitioned account...')\n unpartitioned_account = account(transition, direction)\n log.debug('Found unpartitioned account.')\n if (not unpartitioned_account):\n log.info('Empty unpartitioned account; returning null AC SIA immediately.')\n return _null_ac_sia(transition, direction)\n cuts = _get_cuts(transition, direction)\n engine = ComputeACSystemIrreducibility(cuts, transition, direction, unpartitioned_account)\n result = engine.run_sequential()\n log.info('Finished calculating big-ac-phi data for %s.', transition)\n log.debug('RESULT: \\n%s', result)\n return result", "docstring": "Return the minimal information partition of a transition in a specific\n direction.\n\nArgs:\n transition (Transition): The candidate system.\n\nReturns:\n AcSystemIrreducibilityAnalysis: A nested structure containing all the\n data from the intermediate calculations. The top level contains the\n basic irreducibility information for the given subsystem.", "source": "codesearchnet_filtered"} +{"code": "def list(self, **kwargs):\n resp = self.client.api.secrets(**kwargs)\n return [self.prepare_model(obj) for obj in resp]", "docstring": "List secrets. Similar to the ``docker secret ls`` command.\n\nArgs:\n filters (dict): Server-side list filtering options.\n\nReturns:\n (list of :py:class:`Secret`): The secrets.\n\nRaises:\n :py:class:`docker.errors.APIError`\n If the server returns an error.", "source": "codesearchnet_filtered"} +{"code": "def create_ondemand_streaming_locator(access_token, encoded_asset_id, pid, starttime=None):\n path = '/Locators'\n endpoint = ''.join([ams_rest_endpoint, path])\n if (starttime is None):\n body = (((('{ \\t\\t\\t\"AccessPolicyId\":\"' + pid) + '\", \\t\\t\\t\"AssetId\":\"') + encoded_asset_id) + '\", \\t\\t\\t\"Type\": \"2\" }')\n else:\n body = (((((('{ \\t\\t\\t\"AccessPolicyId\":\"' + pid) + '\", \\t\\t\\t\"AssetId\":\"') + encoded_asset_id) + '\", \\t\\t\\t\"StartTime\":\"') + str(starttime)) + '\", \\t\\t\\t\"Type\": \"2\" \\t\\t}')\n return do_ams_post(endpoint, path, body, access_token, 'json_only')", "docstring": "Create Media Service OnDemand Streaming Locator.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n encoded_asset_id (str): A Media Service Encoded Asset ID.\n pid (str): A Media Service Encoded PID.\n starttime (str): A Media Service Starttime.\n\nReturns:\n HTTP response. JSON body.", "source": "codesearchnet_filtered"} +{"code": "def get_membership(self, uuid=None):\n group_id = self.get_group_id(uuid=uuid)\n uri = 'group/{group_id}/member'\n mbr_data = self.get(uri.format(group_id=group_id), params=None)\n return mbr_data", "docstring": "Get membership data based on uuid.\n\nArgs:\n uuid (str): optional uuid. defaults to self.cuuid\n\nRaises:\n PyLmodUnexpectedData: No data was returned.\n requests.RequestException: Exception connection error\n\nReturns:\n dict: membership json", "source": "codesearchnet_filtered"} +{"code": "def earliest_date(dates, full_date=False):\n min_date = min((PartialDate.loads(date) for date in dates))\n if ((not min_date.month) and full_date):\n min_date.month = 1\n if ((not min_date.day) and full_date):\n min_date.day = 1\n return min_date.dumps()", "docstring": "Return the earliest among the schema-compliant dates.\n\n This is a convenience wrapper around :ref:`PartialDate`, which should be\n used instead if more features are needed.\n\nArgs:\n dates(list): List of dates from which oldest/earliest one will be returned\n full_date(bool): Adds month and/or day as \"01\" if they are missing\n\nReturns:\n str: Earliest date from provided list", "source": "codesearchnet_filtered"} +{"code": "def create(options, timer=None, use_deque=True):\n if (options is None):\n return None\n if (not isinstance(options, (CheckOptions, QuotaOptions, ReportOptions))):\n _logger.error(u'make_cache(): bad options %s', options)\n raise ValueError(u'Invalid options')\n if (options.num_entries <= 0):\n _logger.debug(u'did not create cache, options was %s', options)\n return None\n _logger.debug(u'creating a cache from %s', options)\n if (options.flush_interval > ZERO_INTERVAL):\n ttl = getattr(options, u'expiration', options.flush_interval)\n cache_cls = (DequeOutTTLCache if use_deque else cachetools.TTLCache)\n return LockedObject(cache_cls(options.num_entries, ttl=ttl.total_seconds(), timer=to_cache_timer(timer)))\n cache_cls = (DequeOutLRUCache if use_deque else cachetools.LRUCache)\n return LockedObject(cache_cls(options.num_entries))", "docstring": "Create a cache specified by ``options``\n\n ``options`` is an instance of either\n :class:`endpoints_management.control.caches.CheckOptions` or\n :class:`endpoints_management.control.caches.ReportOptions`\n\n The returned cache is wrapped in a :class:`LockedObject`, requiring it to\n be accessed in a with statement that gives synchronized access\n\nExample:\n >>> options = CheckOptions()\n >>> synced_cache = make_cache(options)\n >>> with synced_cache as cache: # acquire the lock\n ... cache['a_key'] = 'a_value'\n\nArgs:\n options (object): an instance of either of the options classes\n\nReturns:\n :class:`cachetools.Cache`: the cache implementation specified by options\n or None: if options is ``None`` or if options.num_entries < 0\n\nRaises:\n ValueError: if options is not a support type", "source": "codesearchnet_filtered"} +{"code": "def _run(self, cmd):\n if isinstance(cmd, six.string_types):\n cmd = salt.utils.args.shlex_split(cmd)\n try:\n log.debug(cmd)\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n return p.communicate()\n except (OSError, IOError) as exc:\n log.debug('Command Failed: %s', ' '.join(cmd))\n log.debug('Error: %s', exc)\n raise CommandExecutionError(exc)", "docstring": "Internal function for running commands. Used by the uninstall function.\n\nArgs:\n cmd (str, list): The command to run\n\nReturns:\n str: The stdout of the command", "source": "codesearchnet_filtered"} +{"code": "def read_from(fpath, verbose=None, aslines=False, strict=True, n=None, errors='replace'):\n if (n is None):\n n = __READ_TAIL_N__\n verbose = _rectify_verb_read(verbose)\n if verbose:\n print(('[util_io] * Reading text file: %r ' % util_path.tail(fpath, n=n)))\n try:\n if (not util_path.checkpath(fpath, verbose=verbose, n=n)):\n raise IOError('[io] * FILE DOES NOT EXIST!')\n with open(fpath, 'rb') as file_:\n if aslines:\n if six.PY2:\n text = [line.decode('utf8', errors=errors) for line in file_.readlines()]\n else:\n text = [line.decode('utf8', errors=errors) for line in file_.readlines()]\n elif six.PY2:\n text = file_.read().decode('utf8', errors=errors)\n else:\n text = file_.read().decode('utf8', errors=errors)\n return text\n except IOError as ex:\n from utool import util_dbg\n if (verbose or strict):\n util_dbg.printex(ex, (' * Error reading fpath=%r' % util_path.tail(fpath, n=n)), '[io]')\n if strict:\n raise", "docstring": "r\"\"\" Reads text from a file. Automatically returns utf8.\n\nArgs:\n fpath (str): file path\n aslines (bool): if True returns list of lines\n verbose (bool): verbosity flag\n\nReturns:\n str: text from fpath (this is unicode)\n\n Ignore:\n x = b'''/whaleshark_003_fors\\xc3\\xb8g.wmv\" />\\r\\n'''\n ut.writeto('foo.txt', x)\n y = ut.readfrom('foo.txt')\n y.encode('utf8') == x", "source": "codesearchnet_filtered"} +{"code": "def get_cluster(self, label):\n for cluster in self._clusters:\n if (label == cluster['label']):\n return self._get_connection(cluster)\n raise AttributeError(('No such cluster %s.' % label))", "docstring": "Returns a connection to a mongo-clusters.\n\nArgs:\n label (string): the label of a cluster.\n\nReturns:\n A connection to the cluster labeld with label.\n\nRaises:\n AttributeError: there is no cluster with the given label in the\n config", "source": "codesearchnet_filtered"} +{"code": "def load_kegg(self, kegg_id, kegg_organism_code=None, kegg_seq_file=None, kegg_metadata_file=None, set_as_representative=False, download=False, outdir=None, force_rerun=False):\n if download:\n if (not outdir):\n outdir = self.sequence_dir\n if (not outdir):\n raise ValueError('Output directory must be specified')\n if kegg_organism_code:\n kegg_id = ((kegg_organism_code + ':') + kegg_id)\n if self.sequences.has_id(kegg_id):\n if force_rerun:\n existing = self.sequences.get_by_id(kegg_id)\n self.sequences.remove(existing)\n else:\n log.debug('{}: KEGG ID already present in list of sequences'.format(kegg_id))\n kegg_prop = self.sequences.get_by_id(kegg_id)\n if (not self.sequences.has_id(kegg_id)):\n kegg_prop = KEGGProp(id=kegg_id, seq=None, fasta_path=kegg_seq_file, txt_path=kegg_metadata_file)\n if download:\n kegg_prop.download_seq_file(outdir, force_rerun)\n kegg_prop.download_metadata_file(outdir, force_rerun)\n if self.representative_sequence:\n if (not self.representative_sequence.uniprot):\n if kegg_prop.equal_to(self.representative_sequence):\n self.representative_sequence.update(kegg_prop.get_dict(), only_keys=['sequence_path', 'metadata_path', 'kegg', 'description', 'taxonomy', 'id', 'pdbs', 'uniprot', 'seq_record', 'gene_name', 'refseq'])\n else:\n log.warning('{}: representative sequence does not match mapped KEGG sequence.'.format(self.id))\n self.sequences.append(kegg_prop)\n if set_as_representative:\n self.representative_sequence = kegg_prop\n return self.sequences.get_by_id(kegg_id)", "docstring": "Load a KEGG ID, sequence, and metadata files into the sequences attribute.\n\nArgs:\n kegg_id (str): KEGG ID\n kegg_organism_code (str): KEGG organism code to prepend to the kegg_id if not part of it already.\n Example: ``eco:b1244``, ``eco`` is the organism code\n kegg_seq_file (str): Path to KEGG FASTA file\n kegg_metadata_file (str): Path to KEGG metadata file (raw KEGG format)\n set_as_representative (bool): If this KEGG ID should be set as the representative sequence\n download (bool): If the KEGG sequence and metadata files should be downloaded if not provided\n outdir (str): Where the sequence and metadata files should be downloaded to\n force_rerun (bool): If ID should be reloaded and files redownloaded\n\nReturns:\n KEGGProp: object contained in the sequences attribute", "source": "codesearchnet_filtered"} +{"code": "def libravatar_url(email=None, openid=None, size=64, default='retro'):\n params = collections.OrderedDict([('s', size), ('d', default)])\n query = parse.urlencode(params)\n if email:\n value = email\n elif openid:\n value = openid\n else:\n raise ValueError('You must provide either the email or the openid.')\n idhash = sha256(value.encode('utf-8')).hexdigest()\n return ('https://seccdn.libravatar.org/avatar/%s?%s' % (idhash, query))", "docstring": "Get the URL to an avatar from libravatar.\n\n Either the user's email or openid must be provided.\n\n If you want to use Libravatar federation (through DNS), you should install\n and use the ``libravatar`` library instead. Check out the\n ``libravatar.libravatar_url()`` function.\n\nArgs:\n email (str): The user's email\n openid (str): The user's OpenID\n size (int): Size of the avatar in pixels (it's a square).\n default (str): Default avatar to return if not found.\n\nReturns:\n str: The URL to the avatar image.\n\nRaises:\n ValueError: If neither email nor openid are provided.", "source": "codesearchnet_filtered"} +{"code": "def product_name(self):\n buf = (ctypes.c_char * self.MAX_BUF_SIZE)()\n self._dll.JLINKARM_EMU_GetProductName(buf, self.MAX_BUF_SIZE)\n return ctypes.string_at(buf).decode()", "docstring": "Returns the product name of the connected J-Link.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n Product name.", "source": "codesearchnet_filtered"} +{"code": "def top(self, **kwargs):\n return self.client.api.top(self.id, **kwargs)", "docstring": "Display the running processes of the container.\n\nArgs:\n ps_args (str): An optional arguments passed to ps (e.g. ``aux``)\n\nReturns:\n (str): The output of the top\n\nRaises:\n :py:class:`docker.errors.APIError`\n If the server returns an error.", "source": "codesearchnet_filtered"} +{"code": "def _clone_and_score_clusterer(clf, X, n_clusters):\n start = time.time()\n clf = clone(clf)\n setattr(clf, 'n_clusters', n_clusters)\n return (clf.fit(X).score(X), (time.time() - start))", "docstring": "Clones and scores clusterer instance.\n\nArgs:\n clf: Clusterer instance that implements ``fit``,``fit_predict``, and\n ``score`` methods, and an ``n_clusters`` hyperparameter.\n e.g. :class:`sklearn.cluster.KMeans` instance\n\n X (array-like, shape (n_samples, n_features)):\n Data to cluster, where n_samples is the number of samples and\n n_features is the number of features.\n\n n_clusters (int): Number of clusters\n\nReturns:\n score: Score of clusters\n\n time: Number of seconds it took to fit cluster", "source": "codesearchnet_filtered"} +{"code": "def generate_nb_data(P, R, n_cells, assignments=None):\n (genes, clusters) = P.shape\n output = np.zeros((genes, n_cells))\n if (assignments is None):\n cluster_probs = (np.ones(clusters) / clusters)\n labels = []\n for i in range(n_cells):\n if (assignments is None):\n c = np.random.choice(range(clusters), p=cluster_probs)\n else:\n c = assignments[i]\n labels.append(c)\n output[(:, i)] = np.random.negative_binomial(R[(:, c)], (1.0 - P[(:, c)]))\n return (output, np.array(labels))", "docstring": "Generates negative binomial data\n\nArgs:\n P (array): genes x clusters\n R (array): genes x clusters\n n_cells (int): number of cells\n assignments (list): cluster assignment of each cell. Default:\n random uniform\n\nReturns:\n data array with shape genes x cells\n labels - array of cluster labels", "source": "codesearchnet_filtered"} +{"code": "def logs(self, **kwargs):\n return self.client.api.logs(self.id, **kwargs)", "docstring": "Get logs from this container. Similar to the ``docker logs`` command.\n\n The ``stream`` parameter makes the ``logs`` function return a blocking\n generator you can iterate over to retrieve log output as it happens.\n\nArgs:\n stdout (bool): Get ``STDOUT``. Default ``True``\n stderr (bool): Get ``STDERR``. Default ``True``\n stream (bool): Stream the response. Default ``False``\n timestamps (bool): Show timestamps. Default ``False``\n tail (str or int): Output specified number of lines at the end of\n logs. Either an integer of number of lines or the string\n ``all``. Default ``all``\n since (datetime or int): Show logs since a given datetime or\n integer epoch (in seconds)\n follow (bool): Follow log output. Default ``False``\n until (datetime or int): Show logs that occurred before the given\n datetime or integer epoch (in seconds)\n\nReturns:\n (generator or str): Logs from the container.\n\nRaises:\n :py:class:`docker.errors.APIError`\n If the server returns an error.", "source": "codesearchnet_filtered"} +{"code": "def Analyze(self, hashes):\n hash_analyses = []\n for digest in hashes:\n json_response = self._QueryHash(digest)\n hash_analysis = interface.HashAnalysis(digest, json_response)\n hash_analyses.append(hash_analysis)\n return hash_analyses", "docstring": "Looks up hashes in Viper using the Viper HTTP API.\n\nArgs:\n hashes (list[str]): hashes to look up.\n\nReturns:\n list[HashAnalysis]: hash analysis.\n\nRaises:\n RuntimeError: If no host has been set for Viper.", "source": "codesearchnet_filtered"} +{"code": "def _FormatHumanReadableSize(self, size):\n magnitude_1000 = 0\n size_1000 = float(size)\n while (size_1000 >= 1000):\n size_1000 /= 1000\n magnitude_1000 += 1\n magnitude_1024 = 0\n size_1024 = float(size)\n while (size_1024 >= 1024):\n size_1024 /= 1024\n magnitude_1024 += 1\n size_string_1000 = None\n if (0 < magnitude_1000 <= 7):\n size_string_1000 = '{0:.1f}{1:s}'.format(size_1000, self._UNITS_1000[magnitude_1000])\n size_string_1024 = None\n if (0 < magnitude_1024 <= 7):\n size_string_1024 = '{0:.1f}{1:s}'.format(size_1024, self._UNITS_1024[magnitude_1024])\n if ((not size_string_1000) or (not size_string_1024)):\n return '{0:d} B'.format(size)\n return '{0:s} / {1:s} ({2:d} B)'.format(size_string_1024, size_string_1000, size)", "docstring": "Represents a number of bytes as a human readable string.\n\nArgs:\n size (int): size in bytes.\n\nReturns:\n str: human readable string of the size.", "source": "codesearchnet_filtered"} +{"code": "def merge_and_average(self, platform, expression_column, group_by_column, force=False, merge_on_column=None, gsm_on=None, gpl_on=None):\n if isinstance(platform, str):\n gpl = self.gpls[platform]\n elif isinstance(platform, GPL):\n gpl = platform\n else:\n raise ValueError('Platform has to be of type GPL or string with key for platform in GSE')\n data = []\n for gsm in self.gsms.values():\n if (gpl.name == gsm.metadata['platform_id'][0]):\n data.append(gsm.annotate_and_average(gpl=gpl, merge_on_column=merge_on_column, expression_column=expression_column, group_by_column=group_by_column, force=force, gpl_on=gpl_on, gsm_on=gsm_on))\n if (len(data) == 0):\n logger.warning('No samples for the platform were found\\n')\n return None\n elif (len(data) == 1):\n return data[0]\n else:\n return data[0].join(data[1:])", "docstring": "Merge and average GSE samples.\n\n For given platform prepare the DataFrame with all the samples present in\n the GSE annotated with given column from platform and averaged over\n the column.\n\nArgs:\n platform (:obj:`str` or :obj:`GEOparse.GPL`): GPL platform to use.\n expression_column (:obj:`str`): Column name in which \"expressions\"\n are represented\n group_by_column (:obj:`str`): The data will be grouped and averaged\n over this column and only this column will be kept\n force (:obj:`bool`): If the name of the GPL does not match the\n platform name in GSM proceed anyway\n merge_on_column (:obj:`str`): Column to merge the data on - should\n be present in both GSM and GPL\n gsm_on (:obj:`str`): In the case columns to merge are different in\n GSM and GPL use this column in GSM\n gpl_on (:obj:`str`): In the case columns to merge are different in\n GSM and GPL use this column in GPL\n\nReturns:\n :obj:`pandas.DataFrame`: Merged and averaged table of results.", "source": "codesearchnet_filtered"} +{"code": "def get_oauth_access_token(url, client_id, client_secret, token_type='jwt', grant_type='client_credentials', refresh_token=None):\n now = datetime.datetime.utcnow()\n data = {'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'token_type': token_type}\n if refresh_token:\n data['refresh_token'] = refresh_token\n else:\n assert (grant_type != 'refresh_token'), 'refresh_token parameter required'\n response = requests.post(url, data=data, headers={'User-Agent': USER_AGENT})\n data = response.json()\n try:\n access_token = data['access_token']\n expires_in = data['expires_in']\n except KeyError:\n raise requests.RequestException(response=response)\n expires_at = (now + datetime.timedelta(seconds=expires_in))\n return (access_token, expires_at)", "docstring": "Retrieves OAuth 2.0 access token using the given grant type.\n\nArgs:\n url (str): Oauth2 access token endpoint\n client_id (str): client ID\n client_secret (str): client secret\n Kwargs:\n token_type (str): Type of token to return. Options include bearer and jwt.\n grant_type (str): One of 'client_credentials' or 'refresh_token'\n refresh_token (str): The previous access token (for grant_type=refresh_token)\n\nReturns:\n tuple: Tuple containing access token string and expiration datetime.", "source": "codesearchnet_filtered"} +{"code": "def update(self, resource, timeout=(- 1)):\n return self._client.update(resource, timeout=timeout, default_values=self.DEFAULT_VALUES, uri=self.URI)", "docstring": "Updates a User.\n\nArgs:\n resource (dict): Object to update.\n timeout:\n Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n in OneView, just stop waiting for its completion.\n\nReturns:\n dict: Updated resource.", "source": "codesearchnet_filtered"} +{"code": "def split_by_proportionally_distribute_labels(self, proportions={}, use_lengths=True):\n identifiers = {}\n for utterance in self.corpus.utterances.values():\n if use_lengths:\n identifiers[utterance.idx] = {l: int((d * 100)) for (l, d) in utterance.label_total_duration().items()}\n else:\n identifiers[utterance.idx] = utterance.label_count()\n splits = utils.get_identifiers_splitted_by_weights(identifiers, proportions)\n return self._subviews_from_utterance_splits(splits)", "docstring": "Split the corpus into subsets, so the occurrence of the labels is distributed amongst the\n subsets according to the given proportions.\n\nArgs:\n proportions (dict): A dictionary containing the relative size of the target subsets.\n The key is an identifier for the subset.\n use_lengths (bool): If True the lengths of the labels are considered for splitting proportionally,\n otherwise only the number of occurrences is taken into account.\n\nReturns:\n (dict): A dictionary containing the subsets with the identifier from the input as key.", "source": "codesearchnet_filtered"} +{"code": "def to(self, fmt=None, filename=None, **kwargs):\n filename = (filename or '')\n fmt = ('' if (fmt is None) else fmt.lower())\n fname = os.path.basename(filename)\n if ((fmt == 'cif') or fnmatch(fname.lower(), '*.cif*')):\n from pymatgen.io.cif import CifWriter\n writer = CifWriter(self, **kwargs)\n elif ((fmt == 'mcif') or fnmatch(fname.lower(), '*.mcif*')):\n from pymatgen.io.cif import CifWriter\n writer = CifWriter(self, write_magmoms=True, **kwargs)\n elif ((fmt == 'poscar') or fnmatch(fname, '*POSCAR*')):\n from pymatgen.io.vasp import Poscar\n writer = Poscar(self, **kwargs)\n elif ((fmt == 'cssr') or fnmatch(fname.lower(), '*.cssr*')):\n from pymatgen.io.cssr import Cssr\n writer = Cssr(self, **kwargs)\n elif ((fmt == 'json') or fnmatch(fname.lower(), '*.json')):\n s = json.dumps(self.as_dict())\n if filename:\n with zopen(filename, 'wt') as f:\n f.write(('%s' % s))\n return s\n elif ((fmt == 'xsf') or fnmatch(fname.lower(), '*.xsf*')):\n from pymatgen.io.xcrysden import XSF\n s = XSF(self).to_string()\n if filename:\n with zopen(fname, 'wt', encoding='utf8') as f:\n f.write(s)\n return s\n elif ((fmt == 'mcsqs') or fnmatch(fname, '*rndstr.in*') or fnmatch(fname, '*lat.in*') or fnmatch(fname, '*bestsqs*')):\n from pymatgen.io.atat import Mcsqs\n s = Mcsqs(self).to_string()\n if filename:\n with zopen(fname, 'wt', encoding='ascii') as f:\n f.write(s)\n return s\n else:\n import ruamel.yaml as yaml\n if filename:\n with zopen(filename, 'wt') as f:\n yaml.safe_dump(self.as_dict(), f)\n return\n else:\n return yaml.safe_dump(self.as_dict())\n if filename:\n writer.write_file(filename)\n else:\n return writer.__str__()", "docstring": "Outputs the structure to a file or string.\n\nArgs:\n fmt (str): Format to output to. Defaults to JSON unless filename\n is provided. If fmt is specifies, it overrides whatever the\n filename is. Options include \"cif\", \"poscar\", \"cssr\", \"json\".\n Non-case sensitive.\n filename (str): If provided, output will be written to a file. If\n fmt is not specified, the format is determined from the\n filename. Defaults is None, i.e. string output.\n \\\\*\\\\*kwargs: Kwargs passthru to relevant methods. E.g., This allows\n the passing of parameters like symprec to the\n CifWriter.__init__ method for generation of symmetric cifs.\n\nReturns:\n (str) if filename is None. None otherwise.", "source": "codesearchnet_filtered"} +{"code": "def get_path(name, *default):\n global g_config\n value = get(name, *default)\n if (value is None):\n return None\n return proj_path(value)", "docstring": "Get config value as path relative to the project directory.\n\n This allows easily defining the project configuration within the fabfile\n as always relative to that fabfile.\n\nArgs:\n name (str):\n The name of the config value containing the path.\n *default (Any):\n If given and the key doesn't not exist, this will be returned\n instead. If it's not given and the config value does not exist,\n AttributeError will be raised\n\nReturns:\n The requested config value. This is one of the global values defined\n in this file. If the value does not exist it will return `default` if\n give or raise `AttributeError`.\n\nRaises:\n AttributeError: If the value does not exist and `default` was not given.", "source": "codesearchnet_filtered"} +{"code": "def PauliX(local_space, states=None):\n (local_space, states) = _get_pauli_args(local_space, states)\n (g, e) = states\n return (LocalSigma.create(g, e, hs=local_space) + LocalSigma.create(e, g, hs=local_space))", "docstring": "r\"\"\"Pauli-type X-operator\n\n .. math::\n\n \\hat{\\sigma}_x = \\begin{pmatrix}\n 0 & 1 \\\\\n 1 & 0\n \\end{pmatrix}\n\n on an arbitrary two-level system.\n\nArgs:\n local_space (str or int or .LocalSpace): Associated Hilbert space.\n If :class:`str` or :class:`int`, a :class:`LocalSpace` with a\n matching label will be created.\n states (None or tuple[int or str]): The labels for the basis states\n for the two levels on which the operator acts. If None, the two\n lowest levels are used.\n\nReturns:\n Operator: Local X-operator as a linear combination of\n :class:`LocalSigma`", "source": "codesearchnet_filtered"} +{"code": "def region(self, start=0, end=None):\n if (end is None):\n end = len(self.sequence)\n return '>{}\\n{}'.format(self.id, self.sequence[start:end])", "docstring": "Returns a region of ``Sequence.sequence``, in FASTA format.\n\n If called without kwargs, the entire sequence will be returned.\n\nArgs:\n start (int): Start position of the region to be returned. Default\n is 0.\n\n end (int): End position of the region to be returned. Negative values\n will function as they do when slicing strings.\n\nReturns:\n str: A region of ``Sequence.sequence``, in FASTA format", "source": "codesearchnet_filtered"} +{"code": "def refs(self, type='all', **kwargs):\n path = ('%s/%s/refs' % (self.manager.path, self.get_id()))\n data = {'type': type}\n return self.manager.gitlab.http_get(path, query_data=data, **kwargs)", "docstring": "List the references the commit is pushed to.\n\nArgs:\n type (str): The scope of references ('branch', 'tag' or 'all')\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabGetError: If the references could not be retrieved\n\nReturns:\n list: The references the commit is pushed to.", "source": "codesearchnet_filtered"} +{"code": "def download_file(self, path, target_path):\n self.__validate_storage_path(path)\n entity = self.api_client.get_entity_by_query(path=path)\n if (entity['entity_type'] != 'file'):\n raise StorageArgumentException('Only file entities can be downloaded')\n signed_url = self.api_client.get_signed_url(entity['uuid'])\n response = self.api_client.download_signed_url(signed_url)\n with open(target_path, 'wb') as output:\n for chunk in response.iter_content(chunk_size=1024):\n output.write(chunk)", "docstring": "Download a file from storage service to local disk.\n\n Existing files on the target path will be overwritten.\n The download is not recursive, as it only works on files.\n\nArgs:\n path (str): The path of the entity to be downloaded. Must start with a '/'.\n\nReturns:\n None\n\nRaises:\n StorageArgumentException: Invalid arguments\n StorageForbiddenException: Server response code 403\n StorageNotFoundException: Server response code 404\n StorageException: other 400-600 error codes", "source": "codesearchnet_filtered"} +{"code": "def requirements(requirements_file):\n return [str(pkg.req) for pkg in parse_requirements(requirements_file, session=pip_download.PipSession()) if (pkg.req is not None)]", "docstring": "Return packages mentioned in the given file.\n\nArgs:\n requirements_file (str): path to the requirements file to be parsed.\n\nReturns:\n (list): 3rd-party package dependencies contained in the file.", "source": "codesearchnet_filtered"} +{"code": "def fprime(self, w, *args):\n x0 = args[0]\n x1 = args[1]\n n0 = x0.shape[0]\n n1 = x1.shape[0]\n n = (max(n0, n1) * 10)\n idx0 = np.random.choice(range(n0), size=n)\n idx1 = np.random.choice(range(n1), size=n)\n b = np.ones((n, 1))\n i1 = (self.i + 1)\n h = self.h\n h1 = (h + 1)\n w2 = w[(- h1):].reshape(h1, 1)\n w1 = w[:(- h1)].reshape(i1, h)\n if sparse.issparse(x0):\n x0 = x0.tocsr()[idx0]\n x1 = x1.tocsr()[idx1]\n xb0 = sparse.hstack((x0, b))\n xb1 = sparse.hstack((x1, b))\n else:\n x0 = x0[idx0]\n x1 = x1[idx1]\n xb0 = np.hstack((x0, b))\n xb1 = np.hstack((x1, b))\n z0 = np.hstack((sigm(xb0.dot(w1)), b))\n z1 = np.hstack((sigm(xb1.dot(w1)), b))\n y0 = z0.dot(w2)\n y1 = z1.dot(w2)\n e = (1 - (y1 - y0))\n dy = (e / n)\n dw1 = ((- (xb1.T.dot((dy.dot(w2[:(- 1)].reshape(1, h)) * dsigm(xb1.dot(w1)))) - xb0.T.dot((dy.dot(w2[:(- 1)].reshape(1, h)) * dsigm(xb0.dot(w1))))).reshape((i1 * h))) + ((self.l1 * w[:(- h1)]) / (i1 * h)))\n dw2 = ((- (z1 - z0).T.dot(dy).reshape(h1)) + ((self.l2 * w[(- h1):]) / h1))\n return np.append(dw1, dw2)", "docstring": "Return the derivatives of the cost function for predictions.\n\nArgs:\n w (array of float): weight vectors such that:\n w[:-h1] -- weights between the input and h layers\n w[-h1:] -- weights between the h and output layers\n args: features (args[0]) and target (args[1])\n\nReturns:\n gradients of the cost function for predictions", "source": "codesearchnet_filtered"} +{"code": "def _build_key_wrapping_specification(self, value):\n if (value is None):\n return None\n if (not isinstance(value, dict)):\n raise TypeError('Key wrapping specification must be a dictionary.')\n encryption_key_info = self._build_encryption_key_information(value.get('encryption_key_information'))\n mac_signature_key_info = self._build_mac_signature_key_information(value.get('mac_signature_key_information'))\n key_wrapping_specification = cobjects.KeyWrappingSpecification(wrapping_method=value.get('wrapping_method'), encryption_key_information=encryption_key_info, mac_signature_key_information=mac_signature_key_info, attribute_names=value.get('attribute_names'), encoding_option=value.get('encoding_option'))\n return key_wrapping_specification", "docstring": "Build a KeyWrappingSpecification struct from a dictionary.\n\nArgs:\n value (dict): A dictionary containing the key/value pairs for a\n KeyWrappingSpecification struct.\n\nReturns:\n KeyWrappingSpecification: a KeyWrappingSpecification struct\n\nRaises:\n TypeError: if the input argument is invalid", "source": "codesearchnet_filtered"} +{"code": "def renderJsonReadsSince(self, timestamp, meter):\n result = ''\n try:\n connection = sqlite3.connect(self.m_connection_string)\n connection.row_factory = self.dict_factory\n select_cursor = connection.cursor()\n select_cursor.execute((((((((('select * from Meter_Reads where ' + Field.Time_Stamp) + ' > ') + str(timestamp)) + ' and ') + Field.Meter_Address) + \"= '\") + meter) + \"';\"))\n reads = select_cursor.fetchall()\n result = json.dumps(reads, indent=4)\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n return result", "docstring": "Simple since Time_Stamp query returned as JSON records.\n\nArgs:\n timestamp (int): Epoch time in seconds.\n meter (str): 12 character meter address to query\n\nReturns:\n str: JSON rendered read records.", "source": "codesearchnet_filtered"} +{"code": "def update(self, car_id=None, wake_if_asleep=False, force=False):\n cur_time = time.time()\n with self.__lock:\n last_update = self._last_attempted_update_time\n if (force or ((cur_time - last_update) > self.update_interval)):\n cars = self.get_vehicles()\n for car in cars:\n self.car_online[car['id']] = (car['state'] == 'online')\n self._last_attempted_update_time = cur_time\n update_succeeded = False\n for (id_, value) in self.car_online.items():\n if ((car_id is not None) and (car_id != id_)):\n continue\n if (value and ((id_ in self.__update) and self.__update[id_]) and (force or (id_ not in self._last_update_time) or ((cur_time - self._last_update_time[id_]) > self.update_interval))):\n try:\n data = self.get(id_, 'data', wake_if_asleep)\n except TeslaException:\n data = None\n if (data and data['response']):\n response = data['response']\n self.__climate[car_id] = response['climate_state']\n self.__charging[car_id] = response['charge_state']\n self.__state[car_id] = response['vehicle_state']\n self.__driving[car_id] = response['drive_state']\n self.__gui[car_id] = response['gui_settings']\n self.car_online[car_id] = (response['state'] == 'online')\n self._last_update_time[car_id] = time.time()\n update_succeeded = True\n return update_succeeded", "docstring": "Update all vehicle attributes in the cache.\n\n This command will connect to the Tesla API and first update the list of\n online vehicles assuming no attempt for at least the [update_interval].\n It will then update all the cached values for cars that are awake\n assuming no update has occurred for at least the [update_interval].\n\nArgs:\n inst (Controller): The instance of a controller\n car_id (string): The vehicle to update. If None, all cars are updated.\n wake_if_asleep (bool): Keyword arg to force a vehicle awake. This is\n processed by the wake_up decorator.\n force (bool): Keyword arg to force a vehicle update regardless of the\n update_interval\n\nReturns:\n True if any update succeeded for any vehicle else false\n\n Throws:\n RetryLimitError", "source": "codesearchnet_filtered"} +{"code": "def get_language(self, text):\n files = {'text': text}\n (res, status_code) = self.post(self.language_service, files=files)\n if (status_code != 200):\n logger.debug('Language recognition failed.')\n return (self.decode(res), status_code)", "docstring": "Recognise the language of the text in input\n\nArgs:\n id (str): The text whose the language needs to be recognised\n\nReturns:\n dict, int: A dict containing the recognised language and the\n confidence score.", "source": "codesearchnet_filtered"} +{"code": "def generate_password(length=32):\n return ''.join((random.SystemRandom().choice((string.ascii_letters + '!@#$+.,')) for _ in range(length)))", "docstring": "Generate a cryptographically secure random string to use for passwords\n\nArgs:\n length (int): Length of password, defaults to 32 characters\n\nReturns:\n Randomly generated string", "source": "codesearchnet_filtered"} +{"code": "def add_region_location(self, region, locations=None, use_live=True):\n return self.add_country_locations(Country.get_countries_in_region(region, exception=HDXError, use_live=use_live), locations=locations)", "docstring": "Add all countries in a region. If a 3 digit UNStats M49 region code is not provided, value is parsed as a\n region name. If any country is already added, it is ignored.\n\nArgs:\n region (str): M49 region, intermediate region or subregion to add\n locations (Optional[List[str]]): Valid locations list. Defaults to list downloaded from HDX.\n use_live (bool): Try to get use latest country data from web rather than file in package. Defaults to True.\n\nReturns:\n bool: True if all countries in region added or False if any already present.", "source": "codesearchnet_filtered"} +{"code": "def exists(self, path):\n self.__validate_storage_path(path)\n try:\n metadata = self.api_client.get_entity_by_query(path=path)\n except StorageNotFoundException:\n return False\n return (metadata and ('uuid' in metadata))", "docstring": "Check if a certain path exists in the storage service.\n\nArgs:\n path (str): The path to be checked\n\nReturns:\n True if the path exists, False otherwise\n\nRaises:\n StorageArgumentException: Invalid arguments\n StorageForbiddenException: Server response code 403\n StorageNotFoundException: Server response code 404\n StorageException: other 400-600 error codes", "source": "codesearchnet_filtered"} +{"code": "def controller_factory(cls, passes, options, **partial_controller):\n if (None in partial_controller.values()):\n raise TranspilerError('The controller needs a condition.')\n if partial_controller:\n for registered_controller in cls.registered_controllers.keys():\n if (registered_controller in partial_controller):\n return cls.registered_controllers[registered_controller](passes, options, **partial_controller)\n raise TranspilerError(('The controllers for %s are not registered' % partial_controller))\n else:\n return FlowControllerLinear(passes, options)", "docstring": "Constructs a flow controller based on the partially evaluated controller arguments.\n\nArgs:\n passes (list[BasePass]): passes to add to the flow controller.\n options (dict): PassManager options.\n **partial_controller (dict): Partially evaluated controller arguments in the form\n `{name:partial}`\n\nRaises:\n TranspilerError: When partial_controller is not well-formed.\n\nReturns:\n FlowController: A FlowController instance.", "source": "codesearchnet_filtered"} +{"code": "def create(self, resource):\n return self.service.create(resource, self.url_prefix, self.auth, self.session, self.session_send_opts)", "docstring": "Create the given resource.\n\nArgs:\n resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.\n\nReturns:\n (intern.resource.boss.BossResource): Returns resource of type requested on success.\n\nRaises:\n requests.HTTPError on failure.", "source": "codesearchnet_filtered"} +{"code": "def _BuildFindSpecsFromRegistrySourceKey(self, key_path):\n find_specs = []\n for key_path_glob in path_helper.PathHelper.ExpandRecursiveGlobs(key_path, '\\\\'):\n logger.debug('building find spec from key path glob: {0:s}'.format(key_path_glob))\n key_path_glob_upper = key_path_glob.upper()\n if key_path_glob_upper.startswith('HKEY_USERS\\\\%%USERS.SID%%'):\n key_path_glob = 'HKEY_CURRENT_USER{0:s}'.format(key_path_glob[26:])\n find_spec = registry_searcher.FindSpec(key_path_glob=key_path_glob)\n find_specs.append(find_spec)\n return find_specs", "docstring": "Build find specifications from a Windows Registry source type.\n\nArgs:\n key_path (str): Windows Registry key path defined by the source.\n\nReturns:\n list[dfwinreg.FindSpec]: find specifications for the Windows Registry\n source type.", "source": "codesearchnet_filtered"} +{"code": "def xldate_as_datetime(xldate, datemode=0, option='to_datetime'):\n if (option == 'to_float'):\n d = ((xldate - 25589) * 86400.0)\n else:\n try:\n d = (datetime.datetime(1899, 12, 30) + datetime.timedelta(days=(xldate + (1462 * datemode))))\n if (option == 'to_string'):\n date_format = '%Y-%m-%d %H:%M:%S'\n d = d.strftime(date_format)\n except TypeError:\n logging.info(f'The date is not of correct type [{xldate}]')\n d = xldate\n return d", "docstring": "Converts a xls date stamp to a more sensible format.\n\nArgs:\n xldate (str): date stamp in Excel format.\n datemode (int): 0 for 1900-based, 1 for 1904-based.\n option (str): option in (\"to_datetime\", \"to_float\", \"to_string\"),\n return value\n\nReturns:\n datetime (datetime object, float, or string).", "source": "codesearchnet_filtered"} +{"code": "def _generate_legacy_type_checks(types=()):\n types = dict(types)\n\n def gen_type_check(pytypes):\n pytypes = _utils.flatten(pytypes)\n\n def type_check(checker, instance):\n if isinstance(instance, bool):\n if (bool not in pytypes):\n return False\n return isinstance(instance, pytypes)\n return type_check\n definitions = {}\n for (typename, pytypes) in iteritems(types):\n definitions[typename] = gen_type_check(pytypes)\n return definitions", "docstring": "Generate newer-style type checks out of JSON-type-name-to-type mappings.\n\nArgs:\n types (dict):\n\n A mapping of type names to their Python types\n\nReturns:\n A dictionary of definitions to pass to `TypeChecker`", "source": "codesearchnet_filtered"} +{"code": "def _BuildFindSpecsFromFileSourcePath(self, source_path, path_separator, environment_variables, user_accounts):\n find_specs = []\n for path_glob in path_helper.PathHelper.ExpandRecursiveGlobs(source_path, path_separator):\n logger.debug('building find spec from path glob: {0:s}'.format(path_glob))\n for path in path_helper.PathHelper.ExpandUsersVariablePath(path_glob, path_separator, user_accounts):\n logger.debug('building find spec from path: {0:s}'.format(path))\n if ('%' in path):\n path = path_helper.PathHelper.ExpandWindowsPath(path, environment_variables)\n logger.debug('building find spec from expanded path: {0:s}'.format(path))\n if (not path.startswith(path_separator)):\n logger.warning('The path filter must be defined as an absolute path: \"{0:s}\"'.format(path))\n continue\n path_segments = path.split(path_separator)\n path_segments.pop(0)\n if (not path_segments[(- 1)]):\n logger.warning('Empty last path segment in path filter: \"{0:s}\"'.format(path))\n path_segments.pop((- 1))\n try:\n find_spec = file_system_searcher.FindSpec(location_glob=path_segments, case_sensitive=False)\n except ValueError as exception:\n logger.error('Unable to build find specification for path: \"{0:s}\" with error: {1!s}'.format(path, exception))\n continue\n find_specs.append(find_spec)\n return find_specs", "docstring": "Builds find specifications from a file source type.\n\nArgs:\n source_path (str): file system path defined by the source.\n path_separator (str): file system path segment separator.\n environment_variables (list[str]): environment variable attributes used to\n dynamically populate environment variables in key.\n user_accounts (list[str]): identified user accounts stored in the\n knowledge base.\n\nReturns:\n list[dfvfs.FindSpec]: find specifications for the file source type.", "source": "codesearchnet_filtered"} +{"code": "def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None):\n if (method == 'Hilbert-Schmidt'):\n return __random_density_hs(length, rank, seed)\n elif (method == 'Bures'):\n return __random_density_bures(length, rank, seed)\n else:\n raise QiskitError('Error: unrecognized method {}'.format(method))", "docstring": "Generate a random density matrix rho.\n\nArgs:\n length (int): the length of the density matrix.\n rank (int or None): the rank of the density matrix. The default\n value is full-rank.\n method (string): the method to use.\n 'Hilbert-Schmidt': sample rho from the Hilbert-Schmidt metric.\n 'Bures': sample rho from the Bures metric.\n seed (int): Optional. To set a random seed.\n\nReturns:\n ndarray: rho (length, length) a density matrix.\n\nRaises:\n QiskitError: if the method is not valid.", "source": "codesearchnet_filtered"} +{"code": "def write_content(self, content, destination):\n directory = os.path.dirname(destination)\n if (directory and (not os.path.exists(directory))):\n os.makedirs(directory)\n with io.open(destination, 'w', encoding='utf-8') as f:\n f.write(content)\n return destination", "docstring": "Write given content to destination path.\n\n It will create needed directory structure first if it contain some\n directories that does not allready exists.\n\nArgs:\n content (str): Content to write to target file.\n destination (str): Destination path for target file.\n\nReturns:\n str: Path where target file has been written.", "source": "codesearchnet_filtered"} +{"code": "def has_no_title(self, title, **kwargs):\n try:\n self.assert_no_title(title, **kwargs)\n return True\n except ExpectationNotMet:\n return False", "docstring": "Checks if the page doesn't have the given title.\n\nArgs:\n title (str | RegexObject): The string that the title should include.\n **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.\n\nReturns:\n bool: Whether it doesn't match.", "source": "codesearchnet_filtered"} +{"code": "def sample(self, size=None):\n self._recompute()\n if (size is None):\n n = np.random.randn(len(self._t))\n else:\n n = np.random.randn(len(self._t), size)\n n = self.solver.dot_L(n)\n if (size is None):\n return (self.mean.get_value(self._t) + n[(:, 0)])\n return (self.mean.get_value(self._t)[(None, :)] + n.T)", "docstring": "Sample from the prior distribution over datasets\n\nArgs:\n size (Optional[int]): The number of samples to draw.\n\nReturns:\n array[n] or array[size, n]: The samples from the prior\n distribution over datasets.", "source": "codesearchnet_filtered"} +{"code": "def cartesian(shape):\n n = len(shape)\n idx = [slice(0, s) for s in shape]\n g = rollaxis(mgrid[idx], 0, (n + 1))\n return g.reshape((prod(shape), n))", "docstring": "r\"\"\"Cartesian indexing.\n\n Returns a sequence of n-tuples indexing each element of a hypothetical\n matrix of the given shape.\n\nArgs:\n shape (tuple): tuple of dimensions.\n\nReturns:\n array_like: indices.\n\n Example\n -------\n\n .. doctest::\n\n >>> from numpy_sugar import cartesian\n >>> print(cartesian((2, 3)))\n [[0 0]\n [0 1]\n [0 2]\n [1 0]\n [1 1]\n [1 2]]\n\n Reference:\n\n [1] http://stackoverflow.com/a/27286794", "source": "codesearchnet_filtered"} +{"code": "def get_parents_graph(self, item_ids, language=None):\n\n def _parents(item_ids):\n if (item_ids is None):\n items = Item.objects.filter(active=True).prefetch_related('parents')\n else:\n item_ids = [ii for iis in item_ids.values() for ii in iis]\n items = Item.objects.filter(id__in=item_ids, active=True).prefetch_related('parents')\n return {item.id: sorted([_item.id for _item in item.parents.all()]) for item in items}\n return self._reachable_graph(item_ids, _parents, language=language)\n if (item_ids is None):\n return self._reachable_graph(None, _parents, language=language)\n else:\n graph = self.get_parents_graph(None, language)\n return self._subset_graph(graph, item_ids)", "docstring": "Get a subgraph of items reachable from the given set of items through\n the 'parent' relation.\n\nArgs:\n item_ids (list): items which are taken as roots for the reachability\n language (str): if specified, filter out items which are not\n available in the given language\n\nReturns:\n dict: item id -> list of items (parent items), root items are\n referenced by None key", "source": "codesearchnet_filtered"} +{"code": "def _abort_workflow(pb: ProcessingBlock, workflow_stage_dict: dict, docker: DockerSwarmClient):\n _abort_flag = False\n if _abort_flag:\n for workflow_stage in pb.workflow_stages:\n for (service_id, _) in workflow_stage_dict[workflow_stage.id]['services'].items():\n docker.delete_service(service_id)\n LOG.info('Deleted Service Id %s', service_id)\n return True\n return False", "docstring": "Abort the workflow.\n\n TODO(BMo): This function currently does nothing as the abort flag\n is hardcoded to False!\n\n This function is used by `execute_processing_block`.\n\nArgs:\n pb (ProcessingBlock): Configuration database Processing block object.\n workflow_stage_dict (dict): Workflow stage metadata dictionary.\n docker (DockerClient): Docker Swarm Client object.\n\nReturns:\n bool, True if the stage is aborted, otherwise False.", "source": "codesearchnet_filtered"} +{"code": "def block_start(self, previous_block):\n previous_header_bytes = previous_block.header\n previous_header = BlockHeader()\n previous_header.ParseFromString(previous_header_bytes)\n block_info = BlockInfo(block_num=previous_header.block_num, previous_block_id=previous_header.previous_block_id, signer_public_key=previous_header.signer_public_key, header_signature=previous_block.header_signature, timestamp=int(time.time()))\n return [self.create_batch(block_info)]", "docstring": "Returns an ordered list of batches to inject at the beginning of the\n block. Can also return None if no batches should be injected.\n\nArgs:\n previous_block (Block): The previous block.\n\nReturns:\n A list of batches to inject.", "source": "codesearchnet_filtered"} +{"code": "def _get_kernel_data(self, nmr_samples, thinning, return_output):\n kernel_data = {'data': self._data, 'method_data': self._get_mcmc_method_kernel_data(), 'nmr_iterations': Scalar((nmr_samples * thinning), ctype='ulong'), 'iteration_offset': Scalar(self._sampling_index, ctype='ulong'), 'rng_state': Array(self._rng_state, 'uint', mode='rw', ensure_zero_copy=True), 'current_chain_position': Array(self._current_chain_position, 'mot_float_type', mode='rw', ensure_zero_copy=True), 'current_log_likelihood': Array(self._current_log_likelihood, 'mot_float_type', mode='rw', ensure_zero_copy=True), 'current_log_prior': Array(self._current_log_prior, 'mot_float_type', mode='rw', ensure_zero_copy=True)}\n if return_output:\n kernel_data.update({'samples': Zeros((self._nmr_problems, self._nmr_params, nmr_samples), ctype='mot_float_type'), 'log_likelihoods': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'), 'log_priors': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type')})\n return kernel_data", "docstring": "Get the kernel data we will input to the MCMC sampler.\n\n This sets the items:\n\n * data: the pointer to the user provided data\n * method_data: the data specific to the MCMC method\n * nmr_iterations: the number of iterations to sample\n * iteration_offset: the current sample index, that is, the offset to the given number of iterations\n * rng_state: the random number generator state\n * current_chain_position: the current position of the sampled chain\n * current_log_likelihood: the log likelihood of the current position on the chain\n * current_log_prior: the log prior of the current position on the chain\n\n Additionally, if ``return_output`` is True, we add to that the arrays:\n\n * samples: for the samples\n * log_likelihoods: for storing the log likelihoods\n * log_priors: for storing the priors\n\nArgs:\n nmr_samples (int): the number of samples we will draw\n thinning (int): the thinning factor we want to use\n return_output (boolean): if the kernel should return output\n\nReturns:\n dict[str: mot.lib.utils.KernelData]: the kernel input data", "source": "codesearchnet_filtered"} +{"code": "def most_exposes(python_type):\n _exposes = set()\n try:\n do_not_expose = set((python_type.__dir__(object) + ['__slots__', '__module__', '__weakref__']))\n empty = python_type.__new__(python_type)\n except AttributeError:\n try:\n _exposes = python_type.__slots__\n except AttributeError:\n pass\n except TypeError:\n for _workaround in storable_workarounds:\n try:\n _exposes = _workaround(python_type)\n except (SystemExit, KeyboardInterrupt):\n raise\n except:\n pass\n else:\n break\n else:\n all_members = empty.__dir__()\n for attr in all_members:\n if (attr in do_not_expose):\n continue\n try:\n getattr(empty, attr)\n except AttributeError as e:\n if e.args:\n msg = e.args[0]\n if ((msg == attr) or msg.endswith(\"' object has no attribute '{}'\".format(attr))):\n _exposes.add(attr)\n except (SystemExit, KeyboardInterrupt):\n raise\n except:\n pass\n for attr in ('__dict__',):\n if (attr in all_members):\n _exposes.add(attr)\n return list(_exposes)", "docstring": "Core engine for the automatic generation of storable instances.\n\n Finds the attributes exposed by the objects of a given type.\n\n Mostly Python3-only.\n Does not handle types which `__new__` method requires extra arguments either.\n\nArgs:\n python_type (type): object type.\n\nReturns:\n list: attributes exposed.", "source": "codesearchnet_filtered"} +{"code": "def request(self, path, data=None, headers=None, method=None):\n if isinstance(data, str):\n data = data.encode('utf-8')\n response = urlopen(self._request(path, data=data, headers=headers, method=method))\n self._set_session_cookie(response)\n return response", "docstring": "Performs a HTTP request to the Go server\n\nArgs:\n path (str): The full path on the Go server to request.\n This includes any query string attributes.\n data (str, dict, bool, optional): If any data is present this\n request will become a POST request.\n headers (dict, optional): Headers to set for this particular\n request\n\nRaises:\n HTTPError: when the HTTP request fails.\n\nReturns:\n file like object: The response from a\n :func:`urllib2.urlopen` call", "source": "codesearchnet_filtered"} +{"code": "def response_data_to_model_instance(self, response_data):\n response_data['datetime_created'] = dateutil.parser.parse(response_data['datetime_created'])\n if response_data['datetime_finished']:\n response_data['datetime_finished'] = dateutil.parser.parse(response_data['datetime_finished'])\n return super(BaseTaskInstanceManager, self).response_data_to_model_instance(response_data)", "docstring": "Convert response data to a task instance model.\n\nArgs:\n response_data (dict): The data from the request's response.\n\nReturns:\n :class:`saltant.models.base_task_instance.BaseTaskInstance`:\n A task instance model instance representing the task\n instance from the reponse data.", "source": "codesearchnet_filtered"} +{"code": "def read_var_bytes(self, max_size=sys.maxsize) -> bytes:\n length = self.read_var_int(max_size)\n return self.read_bytes(length)", "docstring": "Read a variable length of bytes from the stream.\n\nArgs:\n max_size (int): (Optional) maximum number of bytes to read.\n\nReturns:\n bytes:", "source": "codesearchnet_filtered"} +{"code": "def _init_index(root_dir, schema, index_name):\n index_dir = os.path.join(root_dir, index_name)\n try:\n if (not os.path.exists(index_dir)):\n os.makedirs(index_dir)\n return (create_in(index_dir, schema), index_dir)\n else:\n return (open_dir(index_dir), index_dir)\n except Exception as e:\n logger.error(\"Init error: failed to open search index at: '{}': {} \".format(index_dir, e))\n raise", "docstring": "Creates new index or opens existing.\n\nArgs:\n root_dir (str): root dir where to find or create index.\n schema (whoosh.fields.Schema): schema of the index to create or open.\n index_name (str): name of the index.\n\nReturns:\n tuple ((whoosh.index.FileIndex, str)): first element is index, second is index directory.", "source": "codesearchnet_filtered"} +{"code": "def execute(self, asm_instr):\n self.ir_emulator.registers[self.ip] = (asm_instr.address + asm_instr.size)\n if self.arch_info.instr_is_syscall(asm_instr):\n raise Syscall()\n return self.__execute(asm_instr)", "docstring": "Execute an assembler instruction.\n\nArgs:\n asm_instr (X86Instruction): A instruction to execute.\n\nReturns:\n A int. The address of the next instruction to execute.", "source": "codesearchnet_filtered"} +{"code": "def contains(self, rect):\n return ((rect.y >= self.y) and (rect.x >= self.x) and ((rect.y + rect.height) <= (self.y + self.height)) and ((rect.x + rect.width) <= (self.x + self.width)))", "docstring": "Tests if another rectangle is contained by this one\n\nArgs:\n rect (Rectangle): The other rectangle\n\nReturns:\n bool: True if it is container, False otherwise", "source": "codesearchnet_filtered"} +{"code": "def delete_folder(self, folder_id, recursive=True):\n return self.__request('DELETE', ('folders/%s' % (folder_id,)), querystring={'recursive': unicode(recursive).lower()})", "docstring": "Delete an existing folder\n\nArgs:\n folder_id (int): ID of the folder to delete.\n recursive (bool): Delete all subfolder if True.\n\nReturns:\n dict. Response from Box.\n\nRaises:\n BoxError: An error response is returned from Box (status_code >= 400).\n\n BoxHttpResponseError: Response from Box is malformed.\n\n requests.exceptions.*: Any connection related problem.", "source": "codesearchnet_filtered"} +{"code": "def sparse_segment(cords):\n cords = (np.array(cords) + 1)\n slices = []\n for cord in cords:\n slices.append(slice(1, ((2 ** cord) + 1), 2))\n grid = np.mgrid[slices]\n indices = grid.reshape(len(cords), np.prod(grid.shape[1:])).T\n sgrid = (indices * (2.0 ** (- cords)))\n return sgrid", "docstring": "r\"\"\"\n Create a segment of a sparse grid.\n\n Convert a ol-index to sparse grid coordinates on ``[0, 1]^N`` hyper-cube.\n A sparse grid of order ``D`` coencide with the set of sparse_segments where\n ``||cords||_1 <= D``.\n\n More specifically, a segment of:\n\n .. math::\n \\cup_{cords \\in C} sparse_segment(cords) == sparse_grid(M)\n\n where:\n\n .. math::\n C = {cords: M=sum(cords)}\n\nArgs:\n cords (numpy.ndarray):\n The segment to extract. ``cord`` must consist of non-negative\n integers.\n\nReturns:\n Q (numpy.ndarray):\n Sparse segment where ``Q.shape==(K, sum(M))`` and ``K`` is segment\n specific.\n\nExample:\n >>> print(cp.bertran.sparse_segment([0, 2]))\n [[0.5 0.125]\n [0.5 0.375]\n [0.5 0.625]\n [0.5 0.875]]\n >>> print(cp.bertran.sparse_segment([0, 1, 0, 0]))\n [[0.5 0.25 0.5 0.5 ]\n [0.5 0.75 0.5 0.5 ]]", "source": "codesearchnet_filtered"} +{"code": "def filter(self, limit=None, to=None, category=None):\n if (category and (not to)):\n msg_slice = itertools.islice((x for x in self.store if (x[2] == category)), limit)\n elif (to and (not category)):\n to = JID.fromstr(to)\n msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1])), limit)\n elif (to and category):\n to = JID.fromstr(to)\n msg_slice = itertools.islice((x for x in self.store if (_agent_in_msg(to, x[1]) and (x[2] == category))), limit)\n else:\n msg_slice = self.all(limit=limit)\n return msg_slice\n return list(msg_slice)[::(- 1)]", "docstring": "Returns the events that match the filters\n\nArgs:\n limit (int, optional): the max length of the events to return (Default value = None)\n to (str, optional): only events that have been sent or received by 'to' (Default value = None)\n category (str, optional): only events belonging to the category (Default value = None)\n\nReturns:\n list: a list of filtered events", "source": "codesearchnet_filtered"} +{"code": "def remove_redistribution(self, protocol):\n protocols = ['bgp', 'rip', 'static', 'connected']\n if (protocol not in protocols):\n raise ValueError('redistributed protocol must bebgp, connected, rip or static')\n cmd = 'no redistribute {}'.format(protocol)\n return self.configure_ospf(cmd)", "docstring": "Removes a protocol redistribution to OSPF\n\nArgs:\n protocol (str): protocol to redistribute\n route_map_name (str): route-map to be used to\n filter the protocols\n\nReturns:\n bool: True if the command completes successfully\n Exception:\n ValueError: This will be raised if the protocol pass is not one\n of the following: [rip, bgp, static, connected]", "source": "codesearchnet_filtered"} +{"code": "def _copy_delpoy_scripts(self, scripts):\n if (not os.path.exists(self.paths.scripts())):\n os.makedirs(self.paths.scripts())\n new_scripts = []\n for script in scripts:\n script = os.path.expandvars(script)\n if (not os.path.exists(script)):\n raise RuntimeError(('Script %s does not exist' % script))\n sanitized_name = script.replace('/', '_')\n new_script_cur_path = os.path.expandvars(self.paths.scripts(sanitized_name))\n shutil.copy(script, new_script_cur_path)\n new_script_init_path = os.path.join('$LAGO_PREFIX_PATH', os.path.basename(self.paths.scripts()), sanitized_name)\n new_scripts.append(new_script_init_path)\n return new_scripts", "docstring": "Copy the given deploy scripts to the scripts dir in the prefix\n\nArgs:\n scripts(list of str): list of paths of the scripts to copy to the\n prefix\n\nReturns:\n list of str: list with the paths to the copied scripts, with a\n prefixed with $LAGO_PREFIX_PATH so the full path is not\n hardcoded", "source": "codesearchnet_filtered"} +{"code": "def get_student_by_email(self, email, students=None):\n if (students is None):\n students = self.get_students()\n email = email.lower()\n for student in students:\n if (student['accountEmail'].lower() == email):\n return (student['studentId'], student)\n return (None, None)", "docstring": "Get a student based on an email address.\n\n Calls ``self.get_students()`` to get list of all students,\n if not passed as the ``students`` parameter.\n\nArgs:\n email (str): student email\n students (list): dictionary of students to search, default: None\n When ``students`` is unspecified, all students in gradebook\n are retrieved.\n\nRaises:\n requests.RequestException: Exception connection error\n ValueError: Unable to decode response content\n\nReturns:\n tuple: tuple of student id and student dictionary.", "source": "codesearchnet_filtered"} +{"code": "def get_vulnerability(source, sink, triggers, lattice, cfg, interactive, blackbox_mapping):\n nodes_in_constraint = [secondary for secondary in reversed(source.secondary_nodes) if lattice.in_constraint(secondary, sink.cfg_node)]\n nodes_in_constraint.append(source.cfg_node)\n if sink.trigger.all_arguments_propagate_taint:\n sink_args = get_sink_args(sink.cfg_node)\n else:\n sink_args = get_sink_args_which_propagate(sink, sink.cfg_node.ast_node)\n tainted_node_in_sink_arg = get_tainted_node_in_sink_args(sink_args, nodes_in_constraint)\n if tainted_node_in_sink_arg:\n vuln_deets = {'source': source.cfg_node, 'source_trigger_word': source.trigger_word, 'sink': sink.cfg_node, 'sink_trigger_word': sink.trigger_word}\n sanitiser_nodes = set()\n potential_sanitiser = None\n if sink.sanitisers:\n for sanitiser in sink.sanitisers:\n for cfg_node in triggers.sanitiser_dict[sanitiser]:\n if isinstance(cfg_node, AssignmentNode):\n sanitiser_nodes.add(cfg_node)\n elif isinstance(cfg_node, IfNode):\n potential_sanitiser = cfg_node\n def_use = build_def_use_chain(cfg.nodes, lattice)\n for chain in get_vulnerability_chains(source.cfg_node, sink.cfg_node, def_use):\n (vulnerability_type, interactive) = how_vulnerable(chain, blackbox_mapping, sanitiser_nodes, potential_sanitiser, cfg.blackbox_assignments, interactive, vuln_deets)\n if (vulnerability_type == VulnerabilityType.FALSE):\n continue\n vuln_deets['reassignment_nodes'] = chain\n return (vuln_factory(vulnerability_type)(**vuln_deets), interactive)\n return (None, interactive)", "docstring": "Get vulnerability between source and sink if it exists.\n\n Uses triggers to find sanitisers.\n\n Note: When a secondary node is in_constraint with the sink\n but not the source, the secondary is a save_N_LHS\n node made in process_function in expr_visitor.\n\nArgs:\n source(TriggerNode): TriggerNode of the source.\n sink(TriggerNode): TriggerNode of the sink.\n triggers(Triggers): Triggers of the CFG.\n lattice(Lattice): the lattice we're analysing.\n cfg(CFG): .blackbox_assignments used in is_unknown, .nodes used in build_def_use_chain\n interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.\n blackbox_mapping(dict): A map of blackbox functions containing whether or not they propagate taint.\n\nReturns:\n A Vulnerability if it exists, else None", "source": "codesearchnet_filtered"} +{"code": "def enable(self, information, id_or_uri, timeout=(- 1)):\n uri = self._client.build_uri(id_or_uri)\n return self._client.update(information, uri, timeout=timeout)", "docstring": "Enables or disables a range.\n\nArgs:\n information (dict): Information to update.\n id_or_uri: ID or URI of range.\n timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n in OneView; it just stops waiting for its completion.\n\nReturns:\n dict: Updated resource.", "source": "codesearchnet_filtered"} +{"code": "def get_lattice_type(number):\n f = (lambda i, j: (i <= number <= j))\n cs = {'triclinic': (1, 2), 'monoclinic': (3, 15), 'orthorhombic': (16, 74), 'tetragonal': (75, 142), 'trigonal': (143, 167), 'hexagonal': (168, 194), 'cubic': (195, 230)}\n crystal_system = None\n for (k, v) in cs.items():\n if f(*v):\n crystal_system = k\n break\n if (number in [146, 148, 155, 160, 161, 166, 167]):\n return 'rhombohedral'\n elif (crystal_system == 'trigonal'):\n return 'hexagonal'\n else:\n return crystal_system", "docstring": "Return the lattice crystal system.\n\n Hexagonal cells are differentiated into rhombohedral and hexagonal\n lattices.\n\nArgs:\n number (int): The international space group number.\n\nReturns:\n str: The lattice crystal system.", "source": "codesearchnet_filtered"} +{"code": "def set_matrix(self, matrix):\n matrix = (c_float * 6)(*matrix)\n return self._libinput.libinput_device_config_calibration_set_matrix(self._handle, matrix)", "docstring": "Apply the 3x3 transformation matrix to absolute device coordinates.\n\n This matrix has no effect on relative events.\n\n Given a 6-element array [a, b, c, d, e, f], the matrix is applied as\n ::\n\n [ a b c ] [ x ]\n [ d e f ] * [ y ]\n [ 0 0 1 ] [ 1 ]\n\n The translation component (c, f) is expected to be normalized to\n the device coordinate range. For example, the matrix\n ::\n\n [ 1 0 1 ]\n [ 0 1 -1 ]\n [ 0 0 1 ]\n\n moves all coordinates by 1 device-width to the right and\n 1 device-height up.\n\n The rotation matrix for rotation around the origin is defined as\n ::\n\n [ cos(a) -sin(a) 0 ]\n [ sin(a) cos(a) 0 ]\n [ 0 0 1 ]\n\n Note that any rotation requires an additional translation component\n to translate the rotated coordinates back into the original device\n space. The rotation matrixes for 90, 180 and 270 degrees clockwise are::\n\n 90 deg cw: 180 deg cw: 270 deg cw:\n [ 0 -1 1] [ -1 0 1] [ 0 1 0 ]\n [ 1 0 0] [ 0 -1 1] [ -1 0 1 ]\n [ 0 0 1] [ 0 0 1] [ 0 0 1 ]\n\nArgs:\n matrix (iterable): An array representing the first two rows of\n a 3x3 matrix as described above.\n\nReturns:\n ~libinput.constant.ConfigStatus: A config status code.", "source": "codesearchnet_filtered"} +{"code": "def longest_one_seg_prefix(self, word):\n match = self.seg_regex.match(word)\n if match:\n return match.group(0)\n else:\n return ''", "docstring": "Return longest IPA Unicode prefix of `word`\n\nArgs:\n word (unicode): word as IPA string\n\nReturns:\n unicode: longest single-segment prefix of `word`", "source": "codesearchnet_filtered"} +{"code": "def filterbanks(num_filter, coefficients, sampling_freq, low_freq=None, high_freq=None):\n high_freq = (high_freq or (sampling_freq / 2))\n low_freq = (low_freq or 300)\n s = 'High frequency cannot be greater than half of the sampling frequency!'\n assert (high_freq <= (sampling_freq / 2)), s\n assert (low_freq >= 0), 'low frequency cannot be less than zero!'\n mels = np.linspace(functions.frequency_to_mel(low_freq), functions.frequency_to_mel(high_freq), (num_filter + 2))\n hertz = functions.mel_to_frequency(mels)\n freq_index = np.floor((((coefficients + 1) * hertz) / sampling_freq)).astype(int)\n filterbank = np.zeros([num_filter, coefficients])\n for i in range(0, num_filter):\n left = int(freq_index[i])\n middle = int(freq_index[(i + 1)])\n right = int(freq_index[(i + 2)])\n z = np.linspace(left, right, num=((right - left) + 1))\n filterbank[(i, left:(right + 1))] = functions.triangle(z, left=left, middle=middle, right=right)\n return filterbank", "docstring": "Compute the Mel-filterbanks. Each filter will be stored in one rows.\n The columns correspond to fft bins.\n\nArgs:\n num_filter (int): the number of filters in the filterbank, default 20.\n coefficients (int): (fftpoints//2 + 1). Default is 257.\n sampling_freq (float): the samplerate of the signal we are working\n with. It affects mel spacing.\n low_freq (float): lowest band edge of mel filters, default 0 Hz\n high_freq (float): highest band edge of mel filters,\n default samplerate/2\n\nReturns:\n array: A numpy array of size num_filter x (fftpoints//2 + 1)\n which are filterbank", "source": "codesearchnet_filtered"} +{"code": "def _send_offset_fetch_request(self, partitions):\n assert (self.config['api_version'] >= (0, 8, 1)), 'Unsupported Broker API'\n assert all(map((lambda k: isinstance(k, TopicPartition)), partitions))\n if (not partitions):\n return Future().success({})\n node_id = self.coordinator()\n if (node_id is None):\n return Future().failure(Errors.GroupCoordinatorNotAvailableError)\n if (not self._client.ready(node_id)):\n log.debug('Node %s not ready -- failing offset fetch request', node_id)\n return Future().failure(Errors.NodeNotReadyError)\n log.debug('Group %s fetching committed offsets for partitions: %s', self.group_id, partitions)\n topic_partitions = collections.defaultdict(set)\n for tp in partitions:\n topic_partitions[tp.topic].add(tp.partition)\n if (self.config['api_version'] >= (0, 8, 2)):\n request = OffsetFetchRequest[1](self.group_id, list(topic_partitions.items()))\n else:\n request = OffsetFetchRequest[0](self.group_id, list(topic_partitions.items()))\n future = Future()\n _f = self._client.send(node_id, request)\n _f.add_callback(self._handle_offset_fetch_response, future)\n _f.add_errback(self._failed_request, node_id, request, future)\n return future", "docstring": "Fetch the committed offsets for a set of partitions.\n\n This is a non-blocking call. The returned future can be polled to get\n the actual offsets returned from the broker.\n\nArgs:\n partitions (list of TopicPartition): the partitions to fetch\n\nReturns:\n Future: resolves to dict of offsets: {TopicPartition: int}", "source": "codesearchnet_filtered"} +{"code": "def pkg_version_list(self, pkg_id):\n pkg_data = self.__reg_software.get(pkg_id, None)\n if (not pkg_data):\n return []\n if isinstance(pkg_data, list):\n return pkg_data\n installed_versions = list(pkg_data.get('version').keys())\n return sorted(installed_versions, key=cmp_to_key(self.__oldest_to_latest_version))", "docstring": "Returns information on a package.\n\nArgs:\n pkg_id (str): Package Id of the software/component.\n\nReturns:\n list: List of version numbers installed.", "source": "codesearchnet_filtered"} +{"code": "def get_bin_edges_from_axis(axis) -> np.ndarray:\n bins = range(1, (axis.GetNbins() + 1))\n bin_edges = np.empty((len(bins) + 1))\n bin_edges[:(- 1)] = [axis.GetBinLowEdge(i) for i in bins]\n bin_edges[(- 1)] = axis.GetBinUpEdge(axis.GetNbins())\n return bin_edges", "docstring": "Get bin edges from a ROOT hist axis.\n\nNote:\n Doesn't include over- or underflow bins!\n\nArgs:\n axis (ROOT.TAxis): Axis from which the bin edges should be extracted.\n\nReturns:\n Array containing the bin edges.", "source": "codesearchnet_filtered"} +{"code": "def inflate_plugin(self, identifier, definition=None, cls=None):\n cls = self.get_plugin(identifier, cls)\n return cls(**(definition or {}))", "docstring": "Inflate a plugin thanks to it's identifier, definition and class.\n\nArgs:\n identifier (str): the plugin identifier.\n definition (dict): the kwargs to instantiate the plugin with.\n cls (str): \"provider\", \"checker\", or None.\n\nReturns:\n Provider/Checker: instance of plugin.", "source": "codesearchnet_filtered"} +{"code": "def build_parameter(name, properties):\n p = Parameter(name, Type=properties.get('type'))\n for (name, attr) in PARAMETER_PROPERTIES.items():\n if (name in properties):\n setattr(p, attr, properties[name])\n return p", "docstring": "Builds a troposphere Parameter with the given properties.\n\nArgs:\n name (string): The name of the parameter.\n properties (dict): Contains the properties that will be applied to the\n parameter. See:\n http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html\n\nReturns:\n :class:`troposphere.Parameter`: The created parameter object.", "source": "codesearchnet_filtered"} +{"code": "def getHostCaPath(self, name):\n cert = self.getHostCert(name)\n if (cert is None):\n return None\n return self._getCaPath(cert)", "docstring": "Gets the path to the CA certificate that issued a given host keypair.\n\nArgs:\n name (str): The name of the host keypair.\n\nExample:\n Get the path to the CA cert which issue the cert for \"myhost\":\n\n mypath = cdir.getHostCaPath('myhost')\n\nReturns:\n str: The path if exists.", "source": "codesearchnet_filtered"} +{"code": "def polymorph_response(response, poly, bqm, penalty_strength=None, keep_penalty_variables=True, discard_unsatisfied=False):\n record = response.record\n penalty_vector = penalty_satisfaction(response, bqm)\n original_variables = bqm.variables\n if discard_unsatisfied:\n samples_to_keep = list(map(bool, list(penalty_vector)))\n penalty_vector = np.array(([True] * np.sum(samples_to_keep)))\n else:\n samples_to_keep = list(map(bool, ([1] * len(record.sample))))\n samples = record.sample[samples_to_keep]\n energy_vector = poly.energies((samples, response.variables))\n if (not keep_penalty_variables):\n original_variables = poly.variables\n idxs = [response.variables.index[v] for v in original_variables]\n samples = np.asarray(samples[(:, idxs)])\n (num_samples, num_variables) = np.shape(samples)\n datatypes = [('sample', np.dtype(np.int8), (num_variables,)), ('energy', energy_vector.dtype), ('penalty_satisfaction', penalty_vector.dtype)]\n datatypes.extend(((name, record[name].dtype, record[name].shape[1:]) for name in record.dtype.names if (name not in {'sample', 'energy'})))\n data = np.rec.array(np.empty(num_samples, dtype=datatypes))\n data.sample = samples\n data.energy = energy_vector\n for name in record.dtype.names:\n if (name not in {'sample', 'energy'}):\n data[name] = record[name][samples_to_keep]\n data['penalty_satisfaction'] = penalty_vector\n response.info['reduction'] = bqm.info['reduction']\n if (penalty_strength is not None):\n response.info['penalty_strength'] = penalty_strength\n return SampleSet(data, original_variables, response.info, response.vartype)", "docstring": "Transforms the sampleset for the higher order problem.\n\n Given a response of a penalized HUBO, this function creates a new sampleset\n object, taking into account penalty information and calculates the\n energies of samples for the higherorder problem.\n\nArgs:\n response (:obj:`.SampleSet`): response for a penalized hubo.\n\n poly (:obj:`.BinaryPolynomial`):\n A binary polynomial.\n\n bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model of the\n reduced problem.\n\n penalty_strength (float, optional): default is None, if provided,\n will be added to the info field of the returned sampleSet object.\n\n keep_penalty_variables (bool, optional): default is True. if False\n will remove the variables used for penalty from the samples\n\n discard_unsatisfied (bool, optional): default is False. If True\n will discard samples that do not satisfy the penalty conditions.\n\nReturns:\n (:obj:`.SampleSet'): A sampleSet object that has additional penalty\n information. The energies of samples are calculated for the HUBO\n ignoring the penalty variables.", "source": "codesearchnet_filtered"} +{"code": "def readSchedules(self, tableset):\n self.setContext('readSchedules')\n try:\n req_table = binascii.hexlify(str(tableset).zfill(1))\n req_str = (('01523102303037' + req_table) + '282903')\n self.request(False)\n req_crc = self.calc_crc16(req_str[2:].decode('hex'))\n req_str += req_crc\n self.m_serial_port.write(req_str.decode('hex'))\n raw_ret = self.m_serial_port.getResponse(self.getContext())\n self.serialPostEnd()\n return_crc = self.calc_crc16(raw_ret[1:(- 2)])\n if (tableset == ReadSchedules.Schedules_1_To_4):\n unpacked_read = self.unpackStruct(raw_ret, self.m_schd_1_to_4)\n self.convertData(unpacked_read, self.m_schd_1_to_4, self.m_kwh_precision)\n if (str(return_crc) == str(self.m_schd_1_to_4['crc16'][MeterData.StringValue])):\n ekm_log('Schedules 1 to 4 CRC success (06 return')\n self.setContext('')\n return True\n elif (tableset == ReadSchedules.Schedules_5_To_6):\n unpacked_read = self.unpackStruct(raw_ret, self.m_schd_5_to_6)\n self.convertData(unpacked_read, self.m_schd_5_to_6, self.m_kwh_precision)\n if (str(return_crc) == str(self.m_schd_5_to_6['crc16'][MeterData.StringValue])):\n ekm_log('Schedules 5 to 8 CRC success (06 return)')\n self.setContext('')\n return True\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n self.setContext('')\n return False", "docstring": "Serial call to read schedule tariffs buffer\n\nArgs:\n tableset (int): :class:`~ekmmeters.ReadSchedules` buffer to return.\n\nReturns:\n bool: True on completion and ACK.", "source": "codesearchnet_filtered"} +{"code": "def trace_format(self):\n cmd = enums.JLinkTraceCommand.GET_FORMAT\n data = ctypes.c_uint32(0)\n res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))\n if (res == 1):\n raise errors.JLinkException('Failed to get trace format.')\n return data.value", "docstring": "Retrieves the current format the trace buffer is using.\n\nArgs:\n self (JLink): the ``JLink`` instance.\n\nReturns:\n The current format the trace buffer is using. This is one of the\n attributes of ``JLinkTraceFormat``.", "source": "codesearchnet_filtered"} +{"code": "def to(self, fmt=None, filename=None):\n from pymatgen.io.xyz import XYZ\n from pymatgen.io.gaussian import GaussianInput\n from pymatgen.io.babel import BabelMolAdaptor\n fmt = ('' if (fmt is None) else fmt.lower())\n fname = os.path.basename((filename or ''))\n if ((fmt == 'xyz') or fnmatch(fname.lower(), '*.xyz*')):\n writer = XYZ(self)\n elif any([((fmt == r) or fnmatch(fname.lower(), '*.{}*'.format(r))) for r in ['gjf', 'g03', 'g09', 'com', 'inp']]):\n writer = GaussianInput(self)\n elif ((fmt == 'json') or fnmatch(fname, '*.json*') or fnmatch(fname, '*.mson*')):\n if filename:\n with zopen(filename, 'wt', encoding='utf8') as f:\n return json.dump(self.as_dict(), f)\n else:\n return json.dumps(self.as_dict())\n elif ((fmt == 'yaml') or fnmatch(fname, '*.yaml*')):\n import ruamel.yaml as yaml\n if filename:\n with zopen(fname, 'wt', encoding='utf8') as f:\n return yaml.safe_dump(self.as_dict(), f)\n else:\n return yaml.safe_dump(self.as_dict())\n else:\n m = re.search('\\\\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)', fname.lower())\n if ((not fmt) and m):\n fmt = m.group(1)\n writer = BabelMolAdaptor(self)\n return writer.write_file(filename, file_format=fmt)\n if filename:\n writer.write_file(filename)\n else:\n return str(writer)", "docstring": "Outputs the molecule to a file or string.\n\nArgs:\n fmt (str): Format to output to. Defaults to JSON unless filename\n is provided. If fmt is specifies, it overrides whatever the\n filename is. Options include \"xyz\", \"gjf\", \"g03\", \"json\". If\n you have OpenBabel installed, any of the formats supported by\n OpenBabel. Non-case sensitive.\n filename (str): If provided, output will be written to a file. If\n fmt is not specified, the format is determined from the\n filename. Defaults is None, i.e. string output.\n\nReturns:\n (str) if filename is None. None otherwise.", "source": "codesearchnet_filtered"} +{"code": "def cumprod(vari, axis=None):\n if isinstance(vari, Poly):\n if (np.prod(vari.shape) == 1):\n return vari.copy()\n if (axis is None):\n vari = chaospy.poly.shaping.flatten(vari)\n axis = 0\n vari = chaospy.poly.shaping.rollaxis(vari, axis)\n out = [vari[0]]\n for poly in vari[1:]:\n out.append((out[(- 1)] * poly))\n return Poly(out, vari.dim, vari.shape, vari.dtype)\n return np.cumprod(vari, axis)", "docstring": "Perform the cumulative product of a shapeable quantity over a given axis.\n\nArgs:\n vari (chaospy.poly.base.Poly, numpy.ndarray):\n Input data.\n axis (int):\n Axis over which the sum is taken. By default ``axis`` is None, and\n all elements are summed.\n\nReturns:\n (chaospy.poly.base.Poly):\n An array shaped as ``vari`` but with the specified axis removed.\n\nExample:\n >>> vari = cp.prange(4)\n >>> print(vari)\n [1, q0, q0^2, q0^3]\n >>> print(cp.cumprod(vari))\n [1, q0, q0^3, q0^6]", "source": "codesearchnet_filtered"} +{"code": "def generate_html(store):\n spline = {'version': VERSION, 'url': 'https://github.com/Nachtfeuer/pipeline', 'generated': datetime.now().strftime('%A, %d. %B %Y - %I:%M:%S %p')}\n html_template_file = os.path.join(os.path.dirname(__file__), 'templates/report.html.j2')\n with open(html_template_file) as handle:\n html_template = handle.read()\n return render(html_template, spline=spline, store=store)", "docstring": "Generating HTML report.\n\nArgs:\n store (Store): report data.\n\nReturns:\n str: rendered HTML template.", "source": "codesearchnet_filtered"} +{"code": "def status(self, order_id):\n self.logger.debug(('Get status of order ' + order_id))\n url = ('%(base_url)s/order/%(order_id)s' % {'base_url': self.base_url, 'order_id': order_id})\n r = self.gbdx_connection.get(url)\n r.raise_for_status()\n return r.json().get('acquisitions', {})", "docstring": "Checks imagery order status. There can be more than one image per\n order and this function returns the status of all images\n within the order.\n\nArgs:\n order_id (str): The id of the order placed.\n\nReturns:\n List of dictionaries, one per image. Each dictionary consists\n of the keys 'acquisition_id', 'location' and 'state'.", "source": "codesearchnet_filtered"} +{"code": "def _ParseCommon2003CachedEntry(self, value_data, cached_entry_offset):\n data_type_map = self._GetDataTypeMap('appcompatcache_cached_entry_2003_common')\n try:\n cached_entry = self._ReadStructureFromByteStream(value_data[cached_entry_offset:], cached_entry_offset, data_type_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError('Unable to parse cached entry value with error: {0!s}'.format(exception))\n if (cached_entry.path_size > cached_entry.maximum_path_size):\n raise errors.ParseError('Path size value out of bounds.')\n path_end_of_string_size = (cached_entry.maximum_path_size - cached_entry.path_size)\n if ((cached_entry.path_size == 0) or (path_end_of_string_size != 2)):\n raise errors.ParseError('Unsupported path size values.')\n return cached_entry", "docstring": "Parses the cached entry structure common for Windows 2003, Vista and 7.\n\nArgs:\n value_data (bytes): value data.\n cached_entry_offset (int): offset of the first cached entry data\n relative to the start of the value data.\n\nReturns:\n appcompatcache_cached_entry_2003_common: cached entry structure common\n for Windows 2003, Windows Vista and Windows 7.\n\nRaises:\n ParseError: if the value data could not be parsed.", "source": "codesearchnet_filtered"} +{"code": "def update(self, resource, id_or_uri):\n return self._client.update(resource=resource, uri=id_or_uri)", "docstring": "Updates a registered Device Manager.\n\nArgs:\n resource (dict): Object to update.\n id_or_uri: Can be either the Device manager ID or URI.\n\nReturns:\n dict: The device manager resource.", "source": "codesearchnet_filtered"} +{"code": "def to_insert(table, d):\n columns = []\n args = []\n for (key, val) in d.items():\n columns.append('\"{}\"'.format(key))\n args.append(val)\n stmt = 'insert into {table} ({columns}) values ({params})'.format(table=table, columns=', '.join(columns), params=', '.join((['?'] * len(columns))))\n return (stmt, args)", "docstring": "Generate an insert statement using the given table and dictionary.\n\nArgs:\n table (str): table name\n d (dict): dictionary with column names as keys and values as values.\n\nReturns:\n tuple of statement and arguments\n\n >>> to_insert('doc.foobar', {'name': 'Marvin'})\n ('insert into doc.foobar (\"name\") values (?)', ['Marvin'])", "source": "codesearchnet_filtered"} +{"code": "def delete(self, url, params=None, **kwargs):\n return self.call_api('DELETE', url, params=params, **kwargs)", "docstring": "Call the API with a DELETE request.\n\nArgs:\n url (str): Resource location relative to the base URL.\n params (dict or None): Query-string parameters.\n\nReturns:\n ResultParser or ErrorParser.", "source": "codesearchnet_filtered"} +{"code": "def update(self, properties=None, description=None):\n cv = ApplicationConfiguration._props(properties=properties, description=description)\n res = self.rest_client.session.patch(self.rest_self, headers={'Accept': 'application/json', 'Content-Type': 'application/json'}, json=cv)\n _handle_http_errors(res)\n self.json_rep = res.json()\n return self", "docstring": "Update this application configuration.\n\n To create or update a property provide its key-value\n pair in `properties`.\n\n To delete a property provide its key with the value ``None``\n in properties.\n\nArgs:\n properties (dict): Property values to be updated. If ``None`` the properties are unchanged.\n description (str): Description for the configuration. If ``None`` the description is unchanged.\n\nReturns:\n ApplicationConfiguration: self", "source": "codesearchnet_filtered"} +{"code": "def overlay_gateway_type(self, **kwargs):\n callback = kwargs.pop('callback', self._callback)\n get_config = kwargs.pop('get', False)\n if (not get_config):\n gw_name = kwargs.pop('gw_name')\n gw_type = kwargs.pop('gw_type')\n gw_args = dict(name=gw_name, gw_type=gw_type)\n overlay_gw = getattr(self._tunnels, 'overlay_gateway_gw_type')\n config = overlay_gw(**gw_args)\n if get_config:\n overlay_gw = getattr(self._tunnels, 'overlay_gateway_gw_type')\n config = overlay_gw(name='', gw_type='')\n output = callback(config, handler='get_config')\n if (output.data.find('.//{*}name') is not None):\n gwtype = output.data.find('.//{*}gw-type').text\n return gwtype\n else:\n return None\n return callback(config)", "docstring": "Configure Overlay Gateway Type on vdx switches\n\nArgs:\n gw_name: Name of Overlay Gateway\n gw_type: Type of Overlay Gateway(hardware-vtep/\n layer2-extension/nsx)\n get (bool): Get config instead of editing config. (True, False)\n delete (bool): True, delete the overlay gateway type.\n (True, False)\n callback (function): A function executed upon completion of the\n method. The only parameter passed to `callback` will be the\n ``ElementTree`` `config`.\n\nReturns:\n Return value of `callback`.\n\nRaises:\n KeyError: if `gw_name`, 'gw_type' is not passed.\n ValueError: if `gw_name`, 'gw_type' is invalid.\n\nExample:\n >>> import pynos.device\n >>> conn = ('10.24.39.211', '22')\n >>> auth = ('admin', 'password')\n >>> with pynos.device.Device(conn=conn, auth=auth) as dev:\n ... output = dev.interface.overlay_gateway_type(gw_name='Leaf',\n ... gw_type='layer2-extension')\n ... output = dev.interface.overlay_gateway_name(get=True)", "source": "codesearchnet_filtered"} +{"code": "def hardware_info(self, mask=4294967295):\n buf = (ctypes.c_uint32 * 32)()\n res = self._dll.JLINKARM_GetHWInfo(mask, ctypes.byref(buf))\n if (res != 0):\n raise errors.JLinkException(res)\n return list(buf)", "docstring": "Returns a list of 32 integer values corresponding to the bitfields\n specifying the power consumption of the target.\n\n The values returned by this function only have significance if the\n J-Link is powering the target.\n\n The words, indexed, have the following significance:\n 0. If ``1``, target is powered via J-Link.\n 1. Overcurrent bitfield:\n 0: No overcurrent.\n 1: Overcurrent happened. 2ms @ 3000mA\n 2: Overcurrent happened. 10ms @ 1000mA\n 3: Overcurrent happened. 40ms @ 400mA\n 2. Power consumption of target (mA).\n 3. Peak of target power consumption (mA).\n 4. Peak of target power consumption during J-Link operation (mA).\n\nArgs:\n self (JLink): the ``JLink`` instance\n mask (int): bit mask to decide which hardware information words are\n returned (defaults to all the words).\n\nReturns:\n List of bitfields specifying different states based on their index\n within the list and their value.\n\nRaises:\n JLinkException: on hardware error.", "source": "codesearchnet_filtered"} +{"code": "def candidates(self, word):\n if self.known([word]):\n return {word}\n res = [x for x in self.edit_distance_1(word)]\n tmp = self.known(res)\n if tmp:\n return tmp\n if (self._distance == 2):\n tmp = self.known([x for x in self.__edit_distance_alt(res)])\n if tmp:\n return tmp\n return {word}", "docstring": "Generate possible spelling corrections for the provided word up to\n an edit distance of two, if and only when needed\n\nArgs:\n word (str): The word for which to calculate candidate spellings\n\nReturns:\n set: The set of words that are possible candidates", "source": "codesearchnet_filtered"} +{"code": "def userhome(username=None):\n if (username is None):\n if ('HOME' in os.environ):\n userhome_dpath = os.environ['HOME']\n elif sys.platform.startswith('win32'):\n if ('USERPROFILE' in os.environ):\n userhome_dpath = os.environ['USERPROFILE']\n elif ('HOMEPATH' in os.environ):\n drive = os.environ.get('HOMEDRIVE', '')\n userhome_dpath = join(drive, os.environ['HOMEPATH'])\n else:\n raise OSError(\"Cannot determine the user's home directory\")\n else:\n import pwd\n userhome_dpath = pwd.getpwuid(os.getuid()).pw_dir\n elif sys.platform.startswith('win32'):\n c_users = dirname(userhome())\n userhome_dpath = join(c_users, username)\n if (not exists(userhome_dpath)):\n raise KeyError('Unknown user: {}'.format(username))\n else:\n import pwd\n try:\n pwent = pwd.getpwnam(username)\n except KeyError:\n raise KeyError('Unknown user: {}'.format(username))\n userhome_dpath = pwent.pw_dir\n return userhome_dpath", "docstring": "Returns the user's home directory.\n If `username` is None, this is the directory for the current user.\n\nArgs:\n username (str): name of a user on the system\n\nReturns:\n PathLike: userhome_dpath: path to the home directory\n\nExample:\n >>> import getpass\n >>> username = getpass.getuser()\n >>> assert userhome() == expanduser('~')\n >>> assert userhome(username) == expanduser('~')", "source": "codesearchnet_filtered"} +{"code": "def confinterval(array, conf=0.95, normal_threshold=30, error_only=False, array_mean=None):\n n = len(array)\n if (n < 1):\n (array_mean, c0, c1) = (0, 0, 0)\n elif (n == 1):\n (array_mean, c0, c1) = (array[0], array[0], array[0])\n else:\n scale = (stdev(array) / sqrt(n))\n values_all_same = all(((x == array[0]) for x in array[1:]))\n if values_all_same:\n (array_mean, c0, c1) = (array[0], array[0], array[0])\n else:\n if (array_mean is None):\n array_mean = mean(array)\n if (n < normal_threshold):\n (c0, c1) = stats.t.interval(conf, (n - 1), loc=array_mean, scale=scale)\n else:\n (c0, c1) = stats.norm.interval(conf, loc=array_mean, scale=scale)\n if error_only:\n return (c1 - array_mean)\n else:\n return (c0, c1)", "docstring": "Return the confidence interval of a list for a given confidence.\n\nArgs:\n array (list): Sequence of numbers.\n conf (float): Confidence interval, in range 0 <= ci <= 1\n normal_threshold (int): The number of elements in the array is\n < normal_threshold, use a T-distribution. If the number of\n elements in the array is >= normal_threshold, use a normal\n distribution.\n error_only (bool, optional): If true, return only the size of\n symmetrical confidence interval, equal to ci_upper - mean.\n array_mean (float, optional): Optimisation trick for if you\n already know the arithmetic mean of the array to prevent\n this function from re-calculating.\n\nReturns:\n (float, float): Lower and upper bounds on confidence interval,\n respectively.", "source": "codesearchnet_filtered"} +{"code": "def transfer(self, transfer_payload=None, *, from_user, to_user):\n if (self.persist_id is None):\n raise EntityNotYetPersistedError('Entities cannot be transferred until they have been persisted')\n return self.plugin.transfer(self.persist_id, transfer_payload, from_user=from_user, to_user=to_user)", "docstring": "Transfer this entity to another owner on the backing\n persistence layer\n\nArgs:\n transfer_payload (dict): Payload for the transfer\n from_user (any): A user based on the model specified by the\n persistence layer\n to_user (any): A user based on the model specified by the\n persistence layer\n\nReturns:\n str: Id of the resulting transfer action on the persistence\n layer\n\nRaises:\n :exc:`~.EntityNotYetPersistedError`: If the entity being\n transferred is not associated with an id on the\n persistence layer (:attr:`~Entity.persist_id`) yet\n :exc:`~.EntityNotFoundError`: If the entity could not be\n found on the persistence layer\n :exc:`~.EntityTransferError`: If the entity fails to be\n transferred on the persistence layer\n :exc:`~.PersistenceError`: If any other unhandled error\n in the plugin occurred", "source": "codesearchnet_filtered"} +{"code": "def convert_snapshot(self, shift, instruction):\n command_dict = {'name': 'snapshot', 't0': (shift + instruction.start_time), 'label': instruction.name, 'type': instruction.type}\n return self._qobj_model(**command_dict)", "docstring": "Return converted `Snapshot`.\n\nArgs:\n shift(int): Offset time.\n instruction (Snapshot): snapshot instruction.\n\nReturns:\n dict: Dictionary of required parameters.", "source": "codesearchnet_filtered"} +{"code": "def automatic_density_by_vol(structure, kppvol, force_gamma=False):\n vol = structure.lattice.reciprocal_lattice.volume\n kppa = ((kppvol * vol) * structure.num_sites)\n return Kpoints.automatic_density(structure, kppa, force_gamma=force_gamma)", "docstring": "Returns an automatic Kpoint object based on a structure and a kpoint\n density per inverse Angstrom^3 of reciprocal cell.\n\n Algorithm:\n Same as automatic_density()\n\nArgs:\n structure (Structure): Input structure\n kppvol (int): Grid density per Angstrom^(-3) of reciprocal cell\n force_gamma (bool): Force a gamma centered mesh\n\nReturns:\n Kpoints", "source": "codesearchnet_filtered"} +{"code": "def render(self, tmpl_name, request_env):\n return super(WebApplication, self).render(tmpl_name, request_env)", "docstring": "Render the specified template and return the output.\n\nArgs:\n tmpl_name (str): file name of the template\n request_env (dict): request environment\n\nReturns:\n str - the rendered template", "source": "codesearchnet_filtered"} +{"code": "def GetMessage(self, log_source, lcid, message_identifier):\n event_log_provider_key = self._GetEventLogProviderKey(log_source)\n if (not event_log_provider_key):\n return None\n generator = self._GetMessageFileKeys(event_log_provider_key)\n if (not generator):\n return None\n message_string = None\n for message_file_key in generator:\n message_string = self._GetMessage(message_file_key, lcid, message_identifier)\n if message_string:\n break\n if (self._string_format == 'wrc'):\n message_string = self._ReformatMessageString(message_string)\n return message_string", "docstring": "Retrieves a specific message for a specific Event Log source.\n\nArgs:\n log_source (str): Event Log source.\n lcid (int): language code identifier (LCID).\n message_identifier (int): message identifier.\n\nReturns:\n str: message string or None if not available.", "source": "codesearchnet_filtered"} +{"code": "def hflip(img):\n if (not _is_pil_image(img)):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n return img.transpose(Image.FLIP_LEFT_RIGHT)", "docstring": "Horizontally flip the given PIL Image.\n\nArgs:\n img (PIL Image): Image to be flipped.\n\nReturns:\n PIL Image: Horizontall flipped image.", "source": "codesearchnet_filtered"} +{"code": "def copydb(self, sourcedb, destslab, destdbname=None, progresscb=None):\n destdb = destslab.initdb(destdbname, sourcedb.dupsort)\n statdict = destslab.stat(db=destdb)\n if (statdict['entries'] > 0):\n raise s_exc.DataAlreadyExists()\n rowcount = 0\n for chunk in s_common.chunks(self.scanByFull(db=sourcedb), COPY_CHUNKSIZE):\n (ccount, acount) = destslab.putmulti(chunk, dupdata=True, append=True, db=destdb)\n if ((ccount != len(chunk)) or (acount != len(chunk))):\n raise s_exc.BadCoreStore(mesg='Unexpected number of values written')\n rowcount += len(chunk)\n if ((progresscb is not None) and (0 == (rowcount % PROGRESS_PERIOD))):\n progresscb(rowcount)\n return rowcount", "docstring": "Copy an entire database in this slab to a new database in potentially another slab.\n\nArgs:\n sourcedb (LmdbDatabase): which database in this slab to copy rows from\n destslab (LmdbSlab): which slab to copy rows to\n destdbname (str): the name of the database to copy rows to in destslab\n progresscb (Callable[int]): if not None, this function will be periodically called with the number of rows\n completed\n\nReturns:\n (int): the number of rows copied\n\nNote:\n If any rows already exist in the target database, this method returns an error. This means that one cannot\n use destdbname=None unless there are no explicit databases in the destination slab.", "source": "codesearchnet_filtered"} +{"code": "def infer_distribution_parameters(data, distribution, params=None):\n if (params is None):\n params = dict()\n elif (not isinstance(params, dict)):\n raise TypeError('params must be a dictionary object, see great_expectations documentation')\n if ('mean' not in params.keys()):\n params['mean'] = data.mean()\n if ('std_dev' not in params.keys()):\n params['std_dev'] = data.std()\n if (distribution == 'beta'):\n if ('alpha' not in params.keys()):\n params['alpha'] = ((params['mean'] ** 2) * (((1 - params['mean']) / (params['std_dev'] ** 2)) - (1 / params['mean'])))\n if ('beta' not in params.keys()):\n params['beta'] = (params['alpha'] * ((1 / params['mean']) - 1))\n elif (distribution == 'gamma'):\n if ('alpha' not in params.keys()):\n params['alpha'] = (params['mean'] / params.get('scale', 1))\n elif (distribution == 'uniform'):\n if ('min' not in params.keys()):\n if ('loc' in params.keys()):\n params['min'] = params['loc']\n else:\n params['min'] = min(data)\n if ('max' not in params.keys()):\n if ('scale' in params.keys()):\n params['max'] = params['scale']\n else:\n params['max'] = (max(data) - params['min'])\n elif (distribution == 'chi2'):\n if ('df' not in params.keys()):\n params['df'] = params['mean']\n elif (distribution is not 'norm'):\n raise AttributeError('Unsupported distribution type. Please refer to Great Expectations Documentation')\n params['loc'] = params.get('loc', 0)\n params['scale'] = params.get('scale', 1)\n return params", "docstring": "Convenience method for determining the shape parameters of a given distribution\n\nArgs:\n data (list-like): The data to build shape parameters from.\n distribution (string): Scipy distribution, determines which parameters to build.\n params (dict or None): The known parameters. Parameters given here will not be altered. \\\n Keep as None to infer all necessary parameters from the data data.\n\nReturns:\n A dictionary of named parameters::\n\n {\n \"mean\": (float),\n \"std_dev\": (float),\n \"loc\": (float),\n \"scale\": (float),\n \"alpha\": (float),\n \"beta\": (float),\n \"min\": (float),\n \"max\": (float),\n \"df\": (float)\n }\n\n See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html#scipy.stats.kstest", "source": "codesearchnet_filtered"} +{"code": "def create(self, ip_dest, next_hop, **kwargs):\n return self._set_route(ip_dest, next_hop, **kwargs)", "docstring": "Create a static route\n\nArgs:\n ip_dest (string): The ip address of the destination in the\n form of A.B.C.D/E\n next_hop (string): The next hop interface or ip address\n **kwargs['next_hop_ip'] (string): The next hop address on\n destination interface\n **kwargs['distance'] (string): Administrative distance for this\n route\n **kwargs['tag'] (string): Route tag\n **kwargs['route_name'] (string): Route name\n\nReturns:\n True if the operation succeeds, otherwise False.", "source": "codesearchnet_filtered"} +{"code": "def run_shell_command(state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs):\n command = make_command(command, **command_kwargs)\n logger.debug('--> Running command on localhost: {0}'.format(command))\n if print_output:\n print('{0}>>> {1}'.format(host.print_prefix, command))\n process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)\n stdout_reader = gevent.spawn(read_buffer, process.stdout, print_output=print_output, print_func=(lambda line: '{0}{1}'.format(host.print_prefix, line)))\n stderr_reader = gevent.spawn(read_buffer, process.stderr, print_output=print_output, print_func=(lambda line: '{0}{1}'.format(host.print_prefix, click.style(line, 'red'))))\n greenlets = gevent.wait((stdout_reader, stderr_reader), timeout=timeout)\n if (len(greenlets) != 2):\n stdout_reader.kill()\n stderr_reader.kill()\n raise timeout_error()\n stdout = stdout_reader.get()\n stderr = stderr_reader.get()\n logger.debug('--> Waiting for exit status...')\n process.wait()\n process.stdout.close()\n logger.debug('--> Command exit status: {0}'.format(process.returncode))\n return ((process.returncode == 0), stdout, stderr)", "docstring": "Execute a command on the local machine.\n\nArgs:\n state (``pyinfra.api.State`` obj): state object for this command\n hostname (string): hostname of the target\n command (string): actual command to execute\n sudo (boolean): whether to wrap the command with sudo\n sudo_user (string): user to sudo to\n get_pty (boolean): whether to get a PTY before executing the command\n env (dict): envrionment variables to set\n timeout (int): timeout for this command to complete before erroring\n\nReturns:\n tuple: (exit_code, stdout, stderr)\n stdout and stderr are both lists of strings from each buffer.", "source": "codesearchnet_filtered"} +{"code": "def issubset(self, other):\n other = self._cast_to_frameset(other)\n if (other is NotImplemented):\n return NotImplemented\n return (self.items <= other.items)", "docstring": "Check if the contents of `self` is a subset of the contents of\n `other.`\n\nArgs:\n other (:class:`FrameSet`):\n\nReturns:\n bool:\n :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`", "source": "codesearchnet_filtered"} +{"code": "def peek_native(make):\n\n def peek(service, container, _stack=None):\n return make(service.peekNative(container))\n return peek", "docstring": "Deserializer factory for types which state can be natively serialized.\n\nArgs:\n make (callable): type constructor.\n\nReturns:\n callable: deserializer (`peek` routine)", "source": "codesearchnet_filtered"} +{"code": "def enroll_user_in_course(self, username, course_id, mode, cohort=None):\n return self.client.enrollment.post({'user': username, 'course_details': {'course_id': course_id}, 'mode': mode, 'cohort': cohort})", "docstring": "Call the enrollment API to enroll the user in the course specified by course_id.\n\nArgs:\n username (str): The username by which the user goes on the OpenEdX platform\n course_id (str): The string value of the course's unique identifier\n mode (str): The enrollment mode which should be used for the enrollment\n cohort (str): Add the user to this named cohort\n\nReturns:\n dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.", "source": "codesearchnet_filtered"} +{"code": "def _decode_exp(self, access_token=None):\n c = self.get_credentials()\n jwt = (access_token or c.access_token)\n x = self.decode_jwt_payload(jwt)\n if ('exp' in x):\n try:\n exp = int(x['exp'])\n except ValueError:\n raise PanCloudError('Expiration time (exp) must be an integer')\n else:\n self.jwt_exp = exp\n return exp\n else:\n raise PanCloudError('No exp field found in payload')", "docstring": "Extract exp field from access token.\n\nArgs:\n access_token (str): Access token to decode. Defaults to ``None``.\n\nReturns:\n int: JWT expiration in epoch seconds.", "source": "codesearchnet_filtered"} +{"code": "def with_subject(self, subject):\n return self.__class__(self._signer, service_account_email=self._service_account_email, scopes=self._scopes, token_uri=self._token_uri, subject=subject, project_id=self._project_id, additional_claims=self._additional_claims.copy())", "docstring": "Create a copy of these credentials with the specified subject.\n\nArgs:\n subject (str): The subject claim.\n\nReturns:\n google.auth.service_account.Credentials: A new credentials\n instance.", "source": "codesearchnet_filtered"} +{"code": "def predict_undirected_graph(self, data):\n graph = Graph()\n for (idx_i, i) in enumerate(data.columns):\n for (idx_j, j) in enumerate(data.columns[(idx_i + 1):]):\n score = self.predict(data[i].values, data[j].values)\n if (abs(score) > 0.001):\n graph.add_edge(i, j, weight=score)\n return graph", "docstring": "Build a skeleton using a pairwise independence criterion.\n\nArgs:\n data (pandas.DataFrame): Raw data table\n\nReturns:\n networkx.Graph: Undirected graph representing the skeleton.", "source": "codesearchnet_filtered"} +{"code": "def compare_modules(file_, imports):\n modules = parse_requirements(file_)\n imports = [imports[i]['name'] for i in range(len(imports))]\n modules = [modules[i]['name'] for i in range(len(modules))]\n modules_not_imported = (set(modules) - set(imports))\n return modules_not_imported", "docstring": "Compare modules in a file to imported modules in a project.\n\nArgs:\n file_ (str): File to parse for modules to be compared.\n imports (tuple): Modules being imported in the project.\n\nReturns:\n tuple: The modules not imported in the project, but do exist in the\n specified file.", "source": "codesearchnet_filtered"} +{"code": "def create_ingress_rule(self, app, rule):\n if isinstance(rule, dict):\n start_port = rule.get('start_port')\n end_port = rule.get('end_port')\n protocol = rule.get('protocol', 'tcp')\n requested_cross_account = rule.get('env', self.env)\n if (self.env == requested_cross_account):\n cross_account_env = None\n cross_account_vpc_id = None\n else:\n cross_account_env = requested_cross_account\n cross_account_vpc_id = get_vpc_id(cross_account_env, self.region)\n else:\n start_port = rule\n end_port = rule\n protocol = 'tcp'\n cross_account_env = None\n cross_account_vpc_id = None\n created_rule = {'app': app, 'start_port': start_port, 'end_port': end_port, 'protocol': protocol, 'cross_account_env': cross_account_env, 'cross_account_vpc_id': cross_account_vpc_id}\n self.log.debug('Normalized ingress rule: %s', created_rule)\n return created_rule", "docstring": "Create a normalized ingress rule.\n\nArgs:\n app (str): Application name\n rule (dict or int): Allowed Security Group ports and protocols.\n\nReturns:\n dict: Contains app, start_port, end_port, protocol, cross_account_env and cross_account_vpc_id", "source": "codesearchnet_filtered"} +{"code": "def split_columns(text, n_columns):\n if ((n_columns <= 0) or (n_columns > len(text))):\n raise ValueError('n_columns must be within the bounds of 1 and text length')\n return [text[i::n_columns] for i in range(n_columns)]", "docstring": "Split ``text`` into ``n_columns`` many columns.\n\nExample:\n >>> split_columns(\"example\", 2)\n ['eape', 'xml']\n\nArgs:\n text (str): The text to split\n n_columns (int): The number of columns to create\n\nReturns:\n List of columns\n\nRaises:\n ValueError: If n_cols is <= 0 or >= len(text)", "source": "codesearchnet_filtered"} +{"code": "def get_contacts(self, issue):\n if (not issue.resource):\n return []\n account_contacts = issue.resource.account.contacts\n try:\n resource_owners = issue.resource.get_owner_emails()\n if (type(resource_owners) is list):\n for resource_owner in resource_owners:\n account_contacts.append({'type': 'email', 'value': resource_owner})\n except AttributeError:\n pass\n return account_contacts", "docstring": "Returns a list of contacts for an issue\n\nArgs:\n issue (:obj:`RequiredTagsIssue`): Issue record\n\nReturns:\n `list` of `dict`", "source": "codesearchnet_filtered"} +{"code": "def update(self, identity, params=None, headers=None):\n path = self._sub_url_params('/payments/:identity', {'identity': identity})\n if (params is not None):\n params = {self._envelope_key(): params}\n response = self._perform_request('PUT', path, params, headers, retry_failures=True)\n return self._resource_for(response)", "docstring": "Update a payment.\n\n Updates a payment object. This accepts only the metadata parameter.\n\nArgs:\n identity (string): Unique identifier, beginning with \"PM\".\n params (dict, optional): Request body.\n\nReturns:\n ListResponse of Payment instances", "source": "codesearchnet_filtered"} +{"code": "def inject(module_name=None, module_prefix='[???]', DEBUG=False, module=None, N=1):\n noinject(module_name, module_prefix, DEBUG, module, N=N)\n module = _get_module(module_name, module)\n rrr = make_module_reload_func(None, module_prefix, module)\n profile_ = make_module_profile_func(None, module_prefix, module)\n print_funcs = inject_print_functions(None, module_prefix, DEBUG, module)\n (print, print_, printDBG) = print_funcs\n return (print, print_, printDBG, rrr, profile_)", "docstring": "Injects your module with utool magic\n\n Utool magic is not actually magic. It just turns your ``print`` statments into\n logging statments, allows for your module to be used with the utool.Indent\n context manager and the and utool.indent_func decorator. ``printDBG`` will soon\n be deprecated as will ``print_``. The function rrr is a developer convinience for\n reloading the module dynamically durring runtime. The profile decorator is\n a no-op if not using kernprof.py, otherwise it is kernprof.py's profile\n decorator.\n\nArgs:\n module_name (str): the __name__ varaible in your module\n module_prefix (str): a user defined module prefix\n DEBUG (bool):\n module (None): the actual module (optional)\n\nReturns:\n tuple : (print, print_, printDBG, rrr, profile_)\n\nExample:\n >>> # DISABLE_DOCTEST\n >>> from utool.util_inject import * # NOQA\n >>> from __future__ import absolute_import, division, print_function, unicode_literals\n >>> from util.util_inject import inject\n >>> print, rrr, profile = inject2(__name__, '[mod]')", "source": "codesearchnet_filtered"} +{"code": "def sign(self, private_keys):\n if ((private_keys is None) or (not isinstance(private_keys, list))):\n raise TypeError('`private_keys` must be a list instance')\n\n def gen_public_key(private_key):\n public_key = private_key.get_verifying_key().encode()\n return public_key.decode()\n key_pairs = {gen_public_key(PrivateKey(private_key)): PrivateKey(private_key) for private_key in private_keys}\n tx_dict = self.to_dict()\n tx_dict = Transaction._remove_signatures(tx_dict)\n tx_serialized = Transaction._to_str(tx_dict)\n for (i, input_) in enumerate(self.inputs):\n self.inputs[i] = self._sign_input(input_, tx_serialized, key_pairs)\n self._hash()\n return self", "docstring": "Fulfills a previous Transaction's Output by signing Inputs.\n\nNote:\n This method works only for the following Cryptoconditions\n currently:\n - Ed25519Fulfillment\n - ThresholdSha256\n Furthermore, note that all keys required to fully sign the\n Transaction have to be passed to this method. A subset of all\n will cause this method to fail.\n\nArgs:\n private_keys (:obj:`list` of :obj:`str`): A complete list of\n all private keys needed to sign all Fulfillments of this\n Transaction.\n\nReturns:\n :class:`~bigchaindb.common.transaction.Transaction`", "source": "codesearchnet_filtered"} +{"code": "def _starts_with(field, filter_value):\n valid = False\n if field.startswith(filter_value):\n valid = True\n return valid", "docstring": "Validate field starts with provided value.\n\nArgs:\n filter_value (string): A string or list of values.\n\nReturns:\n (boolean): Results of validation", "source": "codesearchnet_filtered"} +{"code": "def frame(self, frame):\n try:\n zframe = str(int(frame)).zfill(self._zfill)\n except ValueError:\n zframe = frame\n if (self._zfill == 0):\n zframe = ''\n return ''.join((self._dir, self._base, zframe, self._ext))", "docstring": "Return a path go the given frame in the sequence. Integer or string\n digits are treated as a frame number and padding is applied, all other\n values are passed though.\n\nExample:\n >>> seq.frame(1)\n /foo/bar.0001.exr\n >>> seq.frame(\"#\")\n /foo/bar.#.exr\n\nArgs:\n frame (int or str): the desired frame number or a char to pass\n through (ie. #)\n\nReturns:\n str:", "source": "codesearchnet_filtered"} +{"code": "def get_structures(self, primitive=True):\n structures = []\n for d in self._cif.data.values():\n try:\n s = self._get_structure(d, primitive)\n if s:\n structures.append(s)\n except (KeyError, ValueError) as exc:\n self.errors.append(str(exc))\n warnings.warn(str(exc))\n if self.errors:\n warnings.warn('Issues encountered while parsing CIF:')\n for error in self.errors:\n warnings.warn(error)\n if (len(structures) == 0):\n raise ValueError('Invalid cif file with no structures!')\n return structures", "docstring": "Return list of structures in CIF file. primitive boolean sets whether a\n conventional cell structure or primitive cell structure is returned.\n\nArgs:\n primitive (bool): Set to False to return conventional unit cells.\n Defaults to True. With magnetic CIF files, will return primitive\n magnetic cell which may be larger than nuclear primitive cell.\n\nReturns:\n List of Structures.", "source": "codesearchnet_filtered"} +{"code": "def state_invariant_scope(self, state: Sequence[tf.Tensor]):\n scope = {}\n scope.update(self.non_fluents_scope())\n scope.update(self.state_scope(state))\n return scope", "docstring": "Returns the state invariant fluent scope for the current `state`.\n\nArgs:\n state (Sequence[tf.Tensor]): The current state fluents.\n\nReturns:\n A mapping from fluent names to :obj:`rddl2tf.fluent.TensorFluent`.", "source": "codesearchnet_filtered"} +{"code": "def createThread(parent, worker, deleteWorkerLater=False):\n thread = QtCore.QThread(parent)\n thread.started.connect(worker.doWork)\n worker.finished.connect(thread.quit)\n if deleteWorkerLater:\n thread.finished.connect(worker.deleteLater)\n worker.moveToThread(thread)\n worker.setParent(parent)\n return thread", "docstring": "Create a new thread for given worker.\n\nArgs:\n parent (QObject): parent of thread and worker.\n worker (ProgressWorker): worker to use in thread.\n deleteWorkerLater (bool, optional): delete the worker if thread finishes.\n\nReturns:\n QThread", "source": "codesearchnet_filtered"} +{"code": "def get_available_servers(self, **kwargs):\n uri = self._helper.build_uri_with_query_string(kwargs, '/available-servers')\n return self._helper.do_get(uri)", "docstring": "Retrieves the list of available servers.\n\nArgs:\n enclosureGroupUri (str): The URI of the enclosure group associated with the resource.\n serverHardwareTypeUri (str): The URI of the server hardware type associated with the resource.\n profileUri (str): The URI of the server profile resource.\n scopeUris (str): An expression to restrict the resources returned according to\n the scopes to which they are assigned.\n filter (list or str): A general filter/query string to narrow the list of items returned.\n The default is no filter, all resources are returned.\n\nReturns:\n list: Available servers.", "source": "codesearchnet_filtered"} +{"code": "def validate_with_tags(self, tags, confidence):\n result = {'intent_type': self.name}\n intent_confidence = 0.0\n local_tags = tags[:]\n used_tags = []\n for (require_type, attribute_name) in self.requires:\n (required_tag, canonical_form, confidence) = find_first_tag(local_tags, require_type)\n if (not required_tag):\n result['confidence'] = 0.0\n return (result, [])\n result[attribute_name] = canonical_form\n if (required_tag in local_tags):\n local_tags.remove(required_tag)\n used_tags.append(required_tag)\n intent_confidence += confidence\n if (len(self.at_least_one) > 0):\n best_resolution = resolve_one_of(tags, self.at_least_one)\n if (not best_resolution):\n result['confidence'] = 0.0\n return (result, [])\n else:\n for key in best_resolution:\n result[key] = best_resolution[key][0].get('key')\n intent_confidence += 1.0\n used_tags.append(best_resolution)\n if (best_resolution in local_tags):\n local_tags.remove(best_resolution)\n for (optional_type, attribute_name) in self.optional:\n (optional_tag, canonical_form, conf) = find_first_tag(local_tags, optional_type)\n if ((not optional_tag) or (attribute_name in result)):\n continue\n result[attribute_name] = canonical_form\n if (optional_tag in local_tags):\n local_tags.remove(optional_tag)\n used_tags.append(optional_tag)\n intent_confidence += 1.0\n total_confidence = ((intent_confidence / len(tags)) * confidence)\n (target_client, canonical_form, confidence) = find_first_tag(local_tags, CLIENT_ENTITY_NAME)\n result['target'] = (target_client.get('key') if target_client else None)\n result['confidence'] = total_confidence\n return (result, used_tags)", "docstring": "Validate weather tags has required entites for this intent to fire\n\nArgs:\n tags(list): Tags and Entities used for validation\n confidence(float): ?\n\nReturns:\n intent, tags: Returns intent and tags used by the intent on\n falure to meat required entities then returns intent with confidence\n of 0.0 and an empty list for tags.", "source": "codesearchnet_filtered"} +{"code": "def _scale_size(size, scale):\n (w, h) = size\n return (int(((w * float(scale)) + 0.5)), int(((h * float(scale)) + 0.5)))", "docstring": "Rescale a size by a ratio.\n\nArgs:\n size (tuple): w, h.\n scale (float): Scaling factor.\n\nReturns:\n tuple[int]: scaled size.", "source": "codesearchnet_filtered"} +{"code": "def load_dict(self, db_key: str, hierarchical: bool=False) -> dict:\n if (not hierarchical):\n db_values = self._db.hgetall(db_key)\n for (_key, _value) in db_values.items():\n if isinstance(_value, str):\n db_values[_key] = ast.literal_eval(_value)\n my_dict = db_values\n else:\n my_dict = self._load_dict_hierarchical(db_key)\n return my_dict", "docstring": "Load the dictionary at the specified key.\n\n Hierarchically stored dictionaries use a ':' separator to expand\n the dictionary into a set of Redis hashes.\n\nArgs:\n db_key (str): Key at which the dictionary is stored in the db.\n hierarchical (bool): If True, expect the dictionary to have been\n stored hierarchically. If False, expect the dictionary to have\n been stored flat.\n\nReturns:\n dict, the dictionary stored at key", "source": "codesearchnet_filtered"} +{"code": "def find_dependency_wheels(tile):\n return [os.path.join(x.folder, 'python', x.support_wheel) for x in _iter_dependencies(tile) if x.has_wheel]", "docstring": "Return a list of all python wheel objects created by dependencies of this tile\n\nArgs:\n tile (IOTile): Tile that we should scan for dependencies\n\nReturns:\n list: A list of paths to dependency wheels", "source": "codesearchnet_filtered"} +{"code": "def ctype_to_dtype(cl_type, mot_float_type='float'):\n if is_vector_ctype(cl_type):\n (raw_type, vector_length) = split_vector_ctype(cl_type)\n if (raw_type == 'mot_float_type'):\n if is_vector_ctype(mot_float_type):\n (raw_type, _) = split_vector_ctype(mot_float_type)\n else:\n raw_type = mot_float_type\n vector_type = (raw_type + str(vector_length))\n return getattr(cl_array.vec, vector_type)\n else:\n if (cl_type == 'mot_float_type'):\n cl_type = mot_float_type\n data_types = [('char', np.int8), ('uchar', np.uint8), ('short', np.int16), ('ushort', np.uint16), ('int', np.int32), ('uint', np.uint32), ('long', np.int64), ('ulong', np.uint64), ('float', np.float32), ('double', np.float64)]\n for (ctype, dtype) in data_types:\n if (ctype == cl_type):\n return dtype", "docstring": "Get the numpy dtype of the given cl_type string.\n\nArgs:\n cl_type (str): the CL data type to match, for example 'float' or 'float4'.\n mot_float_type (str): the C name of the ``mot_float_type``. The dtype will be looked up recursively.\n\nReturns:\n dtype: the numpy datatype", "source": "codesearchnet_filtered"} +{"code": "def prepare_capstone(syntax=AsmSyntax.att, target=None):\n if (not HAVE_CAPSTONE):\n raise NotImplementedError('pwnypack requires capstone to disassemble to AT&T and Intel syntax')\n if (target is None):\n target = pwnypack.target.target\n if (target.arch == pwnypack.target.Target.Arch.x86):\n if (target.bits is pwnypack.target.Target.Bits.bits_32):\n md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)\n else:\n md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)\n elif (target.arch == pwnypack.target.Target.Arch.arm):\n mode = 0\n if (target.bits is pwnypack.target.Target.Bits.bits_32):\n arch = capstone.CS_ARCH_ARM\n if (target.mode and pwnypack.target.Target.Mode.arm_thumb):\n mode = capstone.CS_MODE_THUMB\n else:\n mode = capstone.CS_MODE_ARM\n if (target.mode and pwnypack.target.Target.Mode.arm_m_class):\n mode |= capstone.CS_MODE_MCLASS\n if (target.mode and pwnypack.target.Target.Mode.arm_v8):\n mode |= capstone.CS_MODE_V8\n else:\n arch = capstone.CS_ARCH_ARM64\n if (target.endian is pwnypack.target.Target.Endian.little):\n mode |= capstone.CS_MODE_LITTLE_ENDIAN\n else:\n mode |= capstone.CS_MODE_BIG_ENDIAN\n md = capstone.Cs(arch, mode)\n else:\n raise NotImplementedError('Only x86 is currently supported.')\n md.skipdata = True\n if (syntax is AsmSyntax.att):\n md.syntax = capstone.CS_OPT_SYNTAX_ATT\n elif (syntax is AsmSyntax.intel):\n md.skipdata_setup(('db', None, None))\n else:\n raise NotImplementedError('capstone engine only implements AT&T and Intel syntax.')\n return md", "docstring": "Prepare a capstone disassembler instance for a given target and syntax.\n\nArgs:\n syntax(AsmSyntax): The assembler syntax (Intel or AT&T).\n target(~pwnypack.target.Target): The target to create a disassembler\n instance for. The global target is used if this argument is\n ``None``.\n\nReturns:\n An instance of the capstone disassembler.\n\nRaises:\n NotImplementedError: If the specified target isn't supported.", "source": "codesearchnet_filtered"} +{"code": "def create_window(size=None, samples=16, *, fullscreen=False, title=None, threaded=True) -> Window:\n if (size is None):\n (width, height) = (1280, 720)\n else:\n (width, height) = size\n if ((samples < 0) or ((samples & (samples - 1)) != 0)):\n raise Exception(('Invalid number of samples: %d' % samples))\n window = Window.__new__(Window)\n window.wnd = glwnd.create_window(width, height, samples, fullscreen, title, threaded)\n return window", "docstring": "Create the main window.\n\nArgs:\n size (tuple): The width and height of the window.\n samples (int): The number of samples.\n\n Keyword Args:\n fullscreen (bool): Fullscreen?\n title (bool): The title of the window.\n threaded (bool): Threaded?\n\nReturns:\n Window: The main window.", "source": "codesearchnet_filtered"} +{"code": "def numbafy(fn, args, compiler='jit', **nbkws):\n kwargs = {}\n if (not isinstance(args, (tuple, list))):\n args = (args,)\n if isinstance(compiler, six.string_types):\n compiler_ = getattr(nb, compiler, None)\n if (compiler is None):\n raise AttributeError('No numba function with name {}.'.format(compiler))\n compiler = compiler_\n if (compiler in (nb.jit, nb.njit, nb.autojit)):\n kwargs.update(jitkwargs)\n sig = nbkws.pop('signature', None)\n else:\n kwargs.update(veckwargs)\n sig = nbkws.pop('signatures', None)\n if (sig is None):\n warn(\"Vectorization without 'signatures' can lead to wrong results!\")\n kwargs.update(nbkws)\n if isinstance(fn, sy.Expr):\n fn = sy.expand_func(fn)\n func = sy.lambdify(args, fn, modules='numpy')\n if (sig is None):\n try:\n func = compiler(**kwargs)(func)\n except RuntimeError:\n kwargs['cache'] = False\n func = compiler(**kwargs)(func)\n else:\n try:\n func = compiler(sig, **kwargs)(func)\n except RuntimeError:\n kwargs['cache'] = False\n func = compiler(sig, **kwargs)(func)\n return func", "docstring": "Compile a string, sympy expression or symengine expression using numba.\n\n Not all functions are supported by Python's numerical package (numpy). For\n difficult cases, valid Python code (as string) may be more suitable than\n symbolic expressions coming from sympy, symengine, etc. When compiling\n vectorized functions, include valid signatures (see `numba`_ documentation).\n\nArgs:\n fn: Symbolic expression as sympy/symengine expression or string\n args (iterable): Symbolic arguments\n compiler: String name or callable numba compiler\n nbkws: Compiler keyword arguments (if none provided, smart defaults are used)\n\nReturns:\n func: Compiled function\n\n Warning:\n For vectorized functions, valid signatures are (almost always) required.", "source": "codesearchnet_filtered"} +{"code": "def subproc_call(cmd, timeout=None):\n try:\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout)\n return (output, 0)\n except subprocess.TimeoutExpired as e:\n logger.warn(\"Command '{}' timeout!\".format(cmd))\n logger.warn(e.output.decode('utf-8'))\n return (e.output, (- 1))\n except subprocess.CalledProcessError as e:\n logger.warn(\"Command '{}' failed, return code={}\".format(cmd, e.returncode))\n logger.warn(e.output.decode('utf-8'))\n return (e.output, e.returncode)\n except Exception:\n logger.warn(\"Command '{}' failed to run.\".format(cmd))\n return ('', (- 2))", "docstring": "Execute a command with timeout, and return STDOUT and STDERR\n\nArgs:\n cmd(str): the command to execute.\n timeout(float): timeout in seconds.\n\nReturns:\n output(bytes), retcode(int). If timeout, retcode is -1.", "source": "codesearchnet_filtered"} +{"code": "def get_hosted_zone_by_name(client, zone_name):\n p = client.get_paginator('list_hosted_zones')\n for i in p.paginate():\n for zone in i['HostedZones']:\n if (zone['Name'] == zone_name):\n return parse_zone_id(zone['Id'])\n return None", "docstring": "Get the zone id of an existing zone by name.\n\nArgs:\n client (:class:`botocore.client.Route53`): The connection used to\n interact with Route53's API.\n zone_name (string): The name of the DNS hosted zone to create.\n\nReturns:\n string: The Id of the Hosted Zone.", "source": "codesearchnet_filtered"} +{"code": "def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name):\n if (bai_field_variation not in (FieldVariations.search, FieldVariations.raw)):\n raise ValueError('Non supported field variation \"{}\".'.format(bai_field_variation))\n normalized_author_name = normalize_name(node_value).strip('.')\n if (ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and ElasticSearchVisitor.BAI_REGEX.match(node_value)):\n return [((ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.') + bai_field_variation)]\n elif ((not whitespace.search(normalized_author_name)) and query_bai_field_if_dots_in_name and ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and ('.' in normalized_author_name)):\n return ([((ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.') + bai_field_variation)] + force_list(ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author']))\n else:\n return None", "docstring": "Generates new fieldnames in case of BAI query.\n\nArgs:\n node_value (six.text_type): The node's value (i.e. author name).\n bai_field_variation (six.text_type): Which field variation to query ('search' or 'raw').\n query_bai_field_if_dots_in_name (bool): Whether to query BAI field (in addition to author's name field)\n if dots exist in the name and name contains no whitespace.\n\nReturns:\n list: Fieldnames to query on, in case of BAI query or None, otherwise.\n\nRaises:\n ValueError, if ``field_variation`` is not one of ('search', 'raw').", "source": "codesearchnet_filtered"} +{"code": "def set_shutter_level(self, level=0.0):\n data = {'channelIndex': 1, 'deviceId': self.id, 'shutterLevel': level}\n return self._restCall('device/control/setShutterLevel', body=json.dumps(data))", "docstring": "sets the shutter level\n\nArgs:\n level(float): the new level of the shutter. 0.0 = open, 1.0 = closed\n\nReturns:\n the result of the _restCall", "source": "codesearchnet_filtered"} +{"code": "def _parse_domain_id(self, config):\n match = re.search('domain-id (.+)$', config)\n value = (match.group(1) if match else None)\n return dict(domain_id=value)", "docstring": "Scans the config block and parses the domain-id value\n\nArgs:\n config (str): The config block to scan\n\nReturns:\n dict: A dict object that is intended to be merged into the\n resource dict", "source": "codesearchnet_filtered"} +{"code": "def from_file(cls, filename, *, strict=True):\n config = cls()\n config.load_from_file(filename, strict=strict)\n return config", "docstring": "Create a new Config object from a configuration file.\n\nArgs:\n filename (str): The location and name of the configuration file.\n strict (bool): If true raises a ConfigLoadError when the configuration\n cannot be found.\n\nReturns:\n An instance of the Config class.\n\nRaises:\n ConfigLoadError: If the configuration cannot be found.", "source": "codesearchnet_filtered"} +{"code": "def autorotate(image, orientation=None):\n orientation_value = (orientation if orientation else image._getexif().get(EXIF_KEYS.get('Orientation')))\n if (orientation_value is None):\n raise ImDirectException('No orientation available in Exif tag or given explicitly.')\n if (orientation_value in (1, 2)):\n i = image\n elif (orientation_value in (3, 4)):\n i = image.transpose(Image.ROTATE_180)\n elif (orientation_value in (5, 6)):\n i = image.transpose(Image.ROTATE_270)\n elif (orientation_value in (7, 8)):\n i = image.transpose(Image.ROTATE_90)\n else:\n i = image\n if (orientation_value in (2, 4, 5, 7)):\n i = i.transpose(Image.FLIP_LEFT_RIGHT)\n return i", "docstring": "Rotate and return an image according to its Exif information.\n\n ROTATION_NEEDED = {\n 1: 0,\n 2: 0 (Mirrored),\n 3: 180,\n 4: 180 (Mirrored),\n 5: -90 (Mirrored),\n 6: -90,\n 7: 90 (Mirrored),\n 8: 90,\n }\n\nArgs:\n image (PIL.Image.Image): PIL image to rotate\n orientation (): Optional orientation value in [1, 8]\n\nReturns:\n A :py:class:`~PIL.Image.Image` image.", "source": "codesearchnet_filtered"} +{"code": "def column(self, index_or_label):\n if (isinstance(index_or_label, str) and (index_or_label not in self.labels)):\n raise ValueError('The column \"{}\" is not in the table. The table contains these columns: {}'.format(index_or_label, ', '.join(self.labels)))\n if (isinstance(index_or_label, int) and (not (0 <= index_or_label < len(self.labels)))):\n raise ValueError('The index {} is not in the table. Only indices between 0 and {} are valid'.format(index_or_label, (len(self.labels) - 1)))\n return self._columns[self._as_label(index_or_label)]", "docstring": "Return the values of a column as an array.\n\n table.column(label) is equivalent to table[label].\n\n >>> tiles = Table().with_columns(\n ... 'letter', make_array('c', 'd'),\n ... 'count', make_array(2, 4),\n ... )\n\n >>> list(tiles.column('letter'))\n ['c', 'd']\n >>> tiles.column(1)\n array([2, 4])\n\nArgs:\n label (int or str): The index or label of a column\n\nReturns:\n An instance of ``numpy.array``.\n\nRaises:\n ``ValueError``: When the ``index_or_label`` is not in the table.", "source": "codesearchnet_filtered"} +{"code": "def events(config):\n celery_app = create_app(config)\n for event in event_stream(celery_app, filter_by_prefix='task'):\n try:\n (yield create_event_model(event))\n except JobEventTypeUnsupported:\n pass", "docstring": "Return a generator that yields workflow events.\n\n For every workflow event that is sent from celery this generator yields an event\n object.\n\nArgs:\n config (Config): Reference to the configuration object from which the\n settings are retrieved.\n\nReturns:\n generator: A generator that returns workflow events.", "source": "codesearchnet_filtered"} +{"code": "def bind_parameters(self, value_dict):\n new_circuit = self.copy()\n if (value_dict.keys() > self.parameters):\n raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format([str(p) for p in (value_dict.keys() - self.parameters)]))\n for (parameter, value) in value_dict.items():\n new_circuit._bind_parameter(parameter, value)\n for parameter in value_dict:\n del new_circuit._parameter_table[parameter]\n return new_circuit", "docstring": "Assign parameters to values yielding a new circuit.\n\nArgs:\n value_dict (dict): {parameter: value, ...}\n\nRaises:\n QiskitError: If value_dict contains parameters not present in the circuit\n\nReturns:\n QuantumCircuit: copy of self with assignment substitution.", "source": "codesearchnet_filtered"} +{"code": "def load_hdf5(path):\n with h5py.File(path, 'r') as f:\n is_sparse = f['issparse'][...]\n if is_sparse:\n shape = tuple(f['shape'][...])\n data = f['data'][...]\n indices = f['indices'][...]\n indptr = f['indptr'][...]\n X = sparse.csr_matrix((data, indices, indptr), shape=shape)\n else:\n X = f['data'][...]\n y = f['target'][...]\n return (X, y)", "docstring": "Load data from a HDF5 file.\n\nArgs:\n path (str): A path to the HDF5 format file containing data.\n dense (boolean): An optional variable indicating if the return matrix\n should be dense. By default, it is false.\n\nReturns:\n Data matrix X and target vector y", "source": "codesearchnet_filtered"} +{"code": "def get_mnemonic(self, mnemonic, alias=None):\n alias = (alias or {})\n aliases = alias.get(mnemonic, [mnemonic])\n for a in aliases:\n if (a in self.data):\n return a\n return None", "docstring": "Instead of picking curves by name directly from the data dict, you\n can pick them up with this method, which takes account of the alias\n dict you pass it. If you do not pass an alias dict, then you get the\n curve you asked for, if it exists, or None. NB Wells do not have alias\n dicts, but Projects do.\n\nArgs:\n mnemonic (str): the name of the curve you want.\n alias (dict): an alias dictionary, mapping mnemonics to lists of\n mnemonics.\n\nReturns:\n Curve.", "source": "codesearchnet_filtered"} +{"code": "def _getsize_from_header(self, header):\n for key in self._SIZE_KEYS:\n try:\n return int(header.pop(key))\n except KeyError:\n continue\n else:\n raise UnsupportedOperation('getsize')", "docstring": "Return the size from header\n\nArgs:\n header (dict): Object header.\n\nReturns:\n int: Size in bytes.", "source": "codesearchnet_filtered"} +{"code": "def dumpfile(item, path):\n with io.open(path, 'wb') as fd:\n fd.write(en(item))", "docstring": "Dump an object to a file by path.\n\nArgs:\n item (object): The object to serialize.\n path (str): The file path to save.\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def get(self, name):\n return self.prepare_model(self.client.api.inspect_plugin(name))", "docstring": "Gets a plugin.\n\nArgs:\n name (str): The name of the plugin.\n\nReturns:\n (:py:class:`Plugin`): The plugin.\n\nRaises:\n :py:class:`docker.errors.NotFound` If the plugin does not\n exist.\n :py:class:`docker.errors.APIError`\n If the server returns an error.", "source": "codesearchnet_filtered"} +{"code": "def _FormatMessageShort(self, event):\n (_, message_short) = self._output_mediator.GetFormattedMessages(event)\n if (message_short is None):\n data_type = getattr(event, 'data_type', 'UNKNOWN')\n raise errors.NoFormatterFound('Unable to find event formatter for: {0:s}.'.format(data_type))\n return message_short", "docstring": "Formats the short message.\n\nArgs:\n event (EventObject): event.\n\nReturns:\n str: short message field.\n\nRaises:\n NoFormatterFound: if no event formatter can be found to match the data\n type in the event.", "source": "codesearchnet_filtered"} +{"code": "def get_firmware_version(self, cached=True):\n if (cached and (self.firmware_version != 'unknown')):\n return self.firmware_version\n firmware_version = self.get_characteristic_handle_from_uuid(UUID_FIRMWARE_REVISION)\n if (firmware_version is None):\n logger.warn('Failed to find handle for firmware version')\n return None\n self.firmware_version = self.dongle._read_attribute(self.conn_handle, firmware_version)\n return self.firmware_version", "docstring": "Returns the SK8 device firmware version.\n\nArgs:\n cached (bool): if True, returns the locally cached copy of the firmware version.\n If this is set to False, or the version is not cached, it will read from\n the device instead.\n\nReturns:\n str. The current firmware version string. May be `None` if an error occurs.", "source": "codesearchnet_filtered"} +{"code": "def wc(filename, contents, parsed=None, is_jekyll=False):\n if is_jekyll:\n fmt = 'jekyll'\n else:\n fmt = 'md/txt'\n body = (parsed.strip() if parsed else contents.strip())\n words = re.sub('\\\\s+', ' ', body, re.MULTILINE)\n for punctuation in INTERSTITIAL_PUNCTUATION:\n words = re.sub(punctuation, ' ', words)\n punct = re.compile('[^\\\\w\\\\s]', re.U)\n words = punct.sub('', words)\n real_characters = re.sub('\\\\s', '', words)\n paragraphs = [(1 if (len(x) == 0) else 0) for x in contents.strip().splitlines()]\n for (index, paragraph) in enumerate(paragraphs):\n if ((paragraph == 1) and (paragraphs[(index + 1)] == 1)):\n paragraphs[index] = 0\n return {'counts': {'file': filename, 'type': fmt, 'paragraphs': (sum(paragraphs) + 1), 'words': len(re.split('\\\\s+', words)), 'characters_real': len(real_characters), 'characters_total': len(words)}}", "docstring": "Count the words, characters, and paragraphs in a string.\n\nArgs:\n contents: the original string to count\n filename (optional): the filename as provided to the CLI\n parsed (optional): a parsed string, expected to be plaintext only\n is_jekyll: whether the original contents were from a Jekyll file\n\nReturns:\n An object containing the various counts", "source": "codesearchnet_filtered"} +{"code": "def has_no_unchecked_field(self, locator, **kwargs):\n kwargs['checked'] = False\n return self.has_no_selector('field', locator, **kwargs)", "docstring": "Checks if the page or current node has no radio button or checkbox with the given label,\n value, or id, that is currently unchecked.\n\nArgs:\n locator (str): The label, name, or id of an unchecked field.\n **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.\n\nReturns:\n bool: Whether it doesn't exist.", "source": "codesearchnet_filtered"} +{"code": "def GetAttributeContainerByIndex(self, index):\n if (index < 0):\n raise IndexError('Unsupported negative index value: {0:d}.'.format(index))\n if (index < len(self._list)):\n return self._list[index]\n return None", "docstring": "Retrieves a specific serialized attribute container from the list.\n\nArgs:\n index (int): attribute container index.\n\nReturns:\n bytes: serialized attribute container data or None if not available.\n\nRaises:\n IndexError: if the index is less than zero.", "source": "codesearchnet_filtered"} +{"code": "def delete_resource_group(access_token, subscription_id, rgname):\n endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '?api-version=', RESOURCE_API])\n return do_delete(endpoint, access_token)", "docstring": "Delete the named resource group.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n rgname (str): Azure resource group name.\n\nReturns:\n HTTP response.", "source": "codesearchnet_filtered"} +{"code": "def check_missing(self, args):\n return [opt.name for opt in self if ((opt.name not in args) and (opt.default is None))]", "docstring": "Returns the names of all options that are required but were not specified.\n\n All options that don't have a default value are required in order to run the\n workflow.\n\nArgs:\n args (dict): A dictionary of the provided arguments that is checked for\n missing options.\n\nReturns:\n list: A list with the names of the options that are missing from the\n provided arguments.", "source": "codesearchnet_filtered"} +{"code": "def array_to_npy(array_like):\n buffer = BytesIO()\n np.save(buffer, array_like)\n return buffer.getvalue()", "docstring": "Convert an array like object to the NPY format.\n\n To understand better what an array like object is see:\n https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays\n\nArgs:\n array_like (np.array or Iterable or int or float): array like object to be converted to NPY.\n\nReturns:\n (obj): NPY array.", "source": "codesearchnet_filtered"} +{"code": "def prepare(self, variables):\n initializedsteps = []\n if (variables is None):\n variables = dict()\n for (step, params, _resources, _files) in self.steps:\n new_params = _complete_parameters(params, variables)\n initializedsteps.append(step(new_params))\n return initializedsteps", "docstring": "Initialize all steps in this recipe using their parameters.\n\nArgs:\n variables (dict): A dictionary of global variable definitions\n that may be used to replace or augment the parameters given\n to each step.\n\nReturns:\n list of RecipeActionObject like instances: The list of instantiated\n steps that can be used to execute this recipe.", "source": "codesearchnet_filtered"} +{"code": "def user_has_access(self, user):\n if (ROLE_ADMIN in user.roles):\n return True\n if self.enabled:\n if (not self.required_roles):\n return True\n for role in self.required_roles:\n if (role in user.roles):\n return True\n return False", "docstring": "Check if a user has access to view information for the account\n\nArgs:\n user (:obj:`User`): User object to check\n\nReturns:\n True if user has access to the account, else false", "source": "codesearchnet_filtered"} +{"code": "def FromDictionary(cls, msg_dict):\n level = msg_dict.get('level')\n msg = msg_dict.get('message')\n now = msg_dict.get('now_time')\n created = msg_dict.get('created_time')\n count = msg_dict.get('count', 1)\n msg_id = msg_dict.get('id', 0)\n new_msg = ServiceMessage(level, msg, msg_id, created, now)\n if (count > 1):\n new_msg.count = count\n return new_msg", "docstring": "Create from a dictionary with kv pairs.\n\nArgs:\n msg_dict (dict): A dictionary with information as created by to_dict()\n\nReturns:\n ServiceMessage: the converted message", "source": "codesearchnet_filtered"} +{"code": "def gmeta_pop(gmeta, info=False):\n if (type(gmeta) is GlobusHTTPResponse):\n gmeta = json.loads(gmeta.text)\n elif (type(gmeta) is str):\n gmeta = json.loads(gmeta)\n elif (type(gmeta) is not dict):\n raise TypeError('gmeta must be dict, GlobusHTTPResponse, or JSON string')\n results = []\n for res in gmeta['gmeta']:\n for con in res['content']:\n results.append(con)\n if info:\n fyi = {'total_query_matches': gmeta.get('total')}\n return (results, fyi)\n else:\n return results", "docstring": "Remove GMeta wrapping from a Globus Search result.\n This function can be called on the raw GlobusHTTPResponse that Search returns,\n or a string or dictionary representation of it.\n\nArgs:\n gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to unwrap.\n info (bool): If ``False``, will return a list of the results\n and discard the metadata. If ``True``, will return a tuple containing\n the results list, and other information about the query.\n **Default**: ``False``.\n\nReturns:\n list (if ``info=False``): The unwrapped results.\n tuple (if ``info=True``): The unwrapped results, and a dictionary of query information.", "source": "codesearchnet_filtered"} +{"code": "def get_detail(self, course_id):\n resp = self._requester.get(urljoin(self._base_url, '/api/courses/v1/courses/{course_key}/'.format(course_key=course_id)))\n resp.raise_for_status()\n return CourseDetail(resp.json())", "docstring": "Fetches course details.\n\nArgs:\n course_id (str): An edx course id.\n\nReturns:\n CourseDetail", "source": "codesearchnet_filtered"} +{"code": "def parse_matches(patient_id, match_objs):\n LOG.info('Parsing MatchMaker matches for patient {}'.format(patient_id))\n parsed_matches = []\n for match_obj in match_objs:\n milliseconds_date = match_obj['created']['$date']\n mdate = datetime.datetime.fromtimestamp((milliseconds_date / 1000.0))\n match_type = 'external'\n matching_patients = []\n parsed_match = {'match_oid': match_obj['_id']['$oid'], 'match_date': mdate}\n if (match_obj['data']['patient']['id'] == patient_id):\n match_results = match_obj['results']\n for node_result in match_results:\n if (match_obj['match_type'] == 'internal'):\n match_type = 'internal'\n for patient in node_result['patients']:\n match_patient = {'patient_id': patient['patient']['id'], 'score': patient['score'], 'patient': patient['patient'], 'node': node_result['node']}\n matching_patients.append(match_patient)\n else:\n m_patient = match_obj['data']['patient']\n contact_institution = m_patient['contact'].get('institution')\n if (contact_institution and ('Scout software user' in contact_institution)):\n match_type = 'internal'\n score = None\n for res in match_obj['results']:\n for patient in res['patients']:\n LOG.info('Looping in else, patient:{}'.format(patient['patient']['id']))\n if (patient['patient']['id'] == patient_id):\n score = patient['score']\n match_patient = {'patient_id': m_patient['id'], 'score': score, 'patient': m_patient, 'node': res['node']}\n matching_patients.append(match_patient)\n parsed_match['match_type'] = match_type\n parsed_match['patients'] = matching_patients\n parsed_matches.append(parsed_match)\n parsed_matches = sorted(parsed_matches, key=(lambda k: k['match_date']), reverse=True)\n return parsed_matches", "docstring": "Parse a list of matchmaker matches objects and returns\n a readable list of matches to display in matchmaker matches view.\n\nArgs:\n patient_id(str): id of a mme patient\n match_objs(list): list of match objs returned by MME server for the patient\n # match_objs looks like this:\n [\n {\n 'node' : { id : node_id , label: node_label},\n 'patients' : [\n { 'patient': {patient1_data} },\n { 'patient': {patient2_data} },\n ..\n ]\n },\n ..\n ]\n\nReturns:\n parsed_matches(list): a list of parsed match objects", "source": "codesearchnet_filtered"} +{"code": "def from_node(cls, node):\n if (not isinstance(node, aioxmpp.stanza.Message)):\n raise AttributeError('node must be a aioxmpp.stanza.Message instance')\n msg = cls()\n msg._to = node.to\n msg._sender = node.from_\n if (None in node.body):\n msg.body = node.body[None]\n else:\n for key in node.body.keys():\n msg.body = node.body[key]\n break\n for data in node.xep0004_data:\n if (data.title == SPADE_X_METADATA):\n for field in data.fields:\n if (field.var != '_thread_node'):\n msg.set_metadata(field.var, field.values[0])\n else:\n msg.thread = field.values[0]\n return msg", "docstring": "Creates a new spade.message.Message from an aixoxmpp.stanza.Message\n\nArgs:\n node (aioxmpp.stanza.Message): an aioxmpp Message\n\nReturns:\n spade.message.Message: a new spade Message", "source": "codesearchnet_filtered"} +{"code": "def download_hrrr_for_gssha(main_directory, forecast_start_date_string, forecast_start_hour_string, leftlon=(- 180), rightlon=180, toplat=90, bottomlat=(- 90)):\n out_directory = path.join(main_directory, forecast_start_date_string)\n try:\n mkdir(out_directory)\n except OSError:\n pass\n forecast_timestep_hour_string_array = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18']\n downloaded_file_list = []\n for forecast_timestep_hour_string in forecast_timestep_hour_string_array:\n file_name = 'hrrr.t{0}z.wrfsfcf{1}.grib2'.format(forecast_start_hour_string, forecast_timestep_hour_string)\n payload = {'file': file_name, 'lev_10_m_above_ground': 'on', 'lev_2_m_above_ground': 'on', 'lev_entire_atmosphere': 'on', 'lev_surface': 'on', 'var_DSWRF': 'on', 'var_PRATE': 'on', 'var_PRES': 'on', 'var_RH': 'on', 'var_TMP': 'on', 'var_UGRD': 'on', 'var_VGRD': 'on', 'var_TCDC': 'on', 'subregion': '', 'leftlon': str(leftlon), 'rightlon': str(rightlon), 'toplat': str(toplat), 'bottomlat': str(bottomlat), 'dir': '/hrrr.{0}'.format(forecast_start_date_string)}\n r = requests.get('http://nomads.ncep.noaa.gov/cgi-bin/filter_hrrr_2d.pl', params=payload, stream=True)\n if (r.status_code == requests.codes.ok):\n out_file = path.join(out_directory, file_name)\n downloaded_file_list.append(out_file)\n with open(out_file, 'wb') as fd:\n for chunk in r.iter_content(chunk_size=1024):\n fd.write(chunk)\n else:\n log.error('Problem downloading {0}'.format(file_name))\n for filename in downloaded_file_list:\n try:\n remove(filename)\n except OSError:\n pass\n downloaded_file_list = []\n break\n return downloaded_file_list", "docstring": "Function to download HRRR data for GSSHA\n\n URL:\n http://nomads.ncep.noaa.gov/cgi-bin/filter_hrrr_2d.pl\n\nArgs:\n main_directory(str): Location of the output for the forecast data.\n forecast_start_date_string(str): String for day of forecast. Ex. '20160913'\n forecast_start_hour_string(str): String for hour of forecast start. Ex. '02'\n leftlon(Optional[double,int]): Left bound for longitude. Default is -180.\n rightlon(Optional[double,int]): Right bound for longitude. Default is 180.\n toplat(Optional[double,int]): Top bound for latitude. Default is 90.\n bottomlat(Optional[double,int]): Bottom bound for latitude. Default is -90.\n\nReturns:\n downloaded_file_list(list): List of paths to downloaded files.\n\n Example::\n\n from gsshapy.grid.hrrr_to_gssha import download_hrrr_for_gssha\n\n hrrr_folder = '/HRRR'\n leftlon = -95\n rightlon = -75\n toplat = 35\n bottomlat = 30\n downloaded_file_list = download_hrrr_for_gssha(hrrr_folder,'20160914','01',\n leftlon,rightlon,toplat,bottomlat)", "source": "codesearchnet_filtered"} +{"code": "def reflection(normal, origin=(0, 0, 0)):\n n = (np.array(normal, dtype=float) / np.linalg.norm(normal))\n (u, v, w) = n\n translation = np.eye(4)\n translation[(0:3, 3)] = (- np.array(origin))\n xx = (1 - (2 * (u ** 2)))\n yy = (1 - (2 * (v ** 2)))\n zz = (1 - (2 * (w ** 2)))\n xy = (((- 2) * u) * v)\n xz = (((- 2) * u) * w)\n yz = (((- 2) * v) * w)\n mirror_mat = [[xx, xy, xz, 0], [xy, yy, yz, 0], [xz, yz, zz, 0], [0, 0, 0, 1]]\n if (np.linalg.norm(origin) > 1e-06):\n mirror_mat = np.dot(np.linalg.inv(translation), np.dot(mirror_mat, translation))\n return SymmOp(mirror_mat)", "docstring": "Returns reflection symmetry operation.\n\nArgs:\n normal (3x1 array): Vector of the normal to the plane of\n reflection.\n origin (3x1 array): A point in which the mirror plane passes\n through.\n\nReturns:\n SymmOp for the reflection about the plane", "source": "codesearchnet_filtered"} +{"code": "def token_to_id(self, token):\n token = self.process_token(token)\n return self._token2id.get(token, (len(self._token2id) - 1))", "docstring": "Get the token_id of given token.\n\nArgs:\n token (str): token from vocabulary.\n\nReturns:\n int: int id of token.", "source": "codesearchnet_filtered"} +{"code": "def load_configuration(config_file, config_dir, service_file):\n config_files = [config_file]\n config = configparser.ConfigParser()\n config.read_dict(DEFAULT_OPTIONS)\n if (not os.path.isfile(config_file)):\n raise ValueError(\"{f} configuration file either isn't readable or doesn't exist\".format(f=config_file))\n if (service_file is not None):\n if (not os.path.isfile(service_file)):\n raise ValueError(\"{f} configuration file for a service check doesn't exist\".format(f=service_file))\n else:\n config_files.append(service_file)\n elif (config_dir is not None):\n if (not os.path.isdir(config_dir)):\n raise ValueError(\"{d} directory with configuration files for service checks doesn't exist\".format(d=config_dir))\n else:\n config_files.extend(glob.glob(os.path.join(config_dir, '*.conf')))\n try:\n config.read(config_files)\n except configparser.Error as exc:\n raise ValueError(exc)\n configuration_check(config)\n bird_configuration = build_bird_configuration(config)\n create_bird_config_files(bird_configuration)\n return (config, bird_configuration)", "docstring": "Build configuration objects.\n\n If all sanity checks against daemon and service check settings are passed\n then it builds a ConfigParser object which holds all our configuration\n and a dictionary data structure which holds Bird configuration per IP\n protocol version.\n\nArgs:\n config_file (str): The file name which holds daemon settings\n config_dir (str): The directory name which has configuration files\n for each service check\n service_file (str): A file which contains configuration for a single\n service check\n\nReturns:\n A tuple with 1st element a ConfigParser object and 2nd element\n a dictionary.\n\nRaises:\n ValueError if a sanity check fails.", "source": "codesearchnet_filtered"} +{"code": "def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''):\n log.info('Get latest data for sensors. Stop with Ctrl+C.')\n log.info('Stops automatically in %ss', search_duratio_sec)\n log.info('MACs: %s', macs)\n datas = dict()\n for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device):\n datas[new_data[0]] = new_data[1]\n return datas", "docstring": "Get lates data for sensors in the MAC's list.\n\nArgs:\n macs (array): MAC addresses\n search_duratio_sec (int): Search duration in seconds. Default 5\n bt_device (string): Bluetooth device id\n\nReturns:\n dict: MAC and state of found sensors", "source": "codesearchnet_filtered"} +{"code": "def transform_to_mods_mono(marc_xml, uuid, url):\n marc_xml = _read_content_or_path(marc_xml)\n transformed = xslt_transformation(marc_xml, _absolute_template_path('MARC21slim2MODS3-4-NDK.xsl'))\n return _apply_postprocessing(marc_xml=marc_xml, xml=transformed, func=mods_postprocessor.postprocess_monograph, uuid=uuid, url=url)", "docstring": "Convert `marc_xml` to MODS data format.\n\nArgs:\n marc_xml (str): Filename or XML string. Don't use ``\\\\n`` in case of\n filename.\n uuid (str): UUID string giving the package ID.\n url (str): URL of the publication (public or not).\n\nReturns:\n list: Collection of transformed xml strings.", "source": "codesearchnet_filtered"} +{"code": "def write_int8(self, value, little_endian=True):\n if little_endian:\n endian = '<'\n else:\n endian = '>'\n return self.pack(('%sb' % endian), value)", "docstring": "Pack the value as a signed byte and write 1 byte to the stream.\n\nArgs:\n value:\n little_endian (bool): specify the endianness. (Default) Little endian.\n\nReturns:\n int: the number of bytes written.", "source": "codesearchnet_filtered"} +{"code": "def _ConvertValueBinaryDataToUBInt64(self, value):\n if (not value):\n return None\n integer_map = self._GetDataTypeMap('uint64be')\n try:\n return self._ReadStructureFromByteStream(value, 0, integer_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError('Unable to parse integer value with error: {0!s}'.format(exception))", "docstring": "Converts a binary data value into an integer.\n\nArgs:\n value (bytes): binary data value containing an unsigned 64-bit big-endian\n integer.\n\nReturns:\n int: integer representation of binary data value or None if value is\n not set.\n\nRaises:\n ParseError: if the integer value cannot be parsed.", "source": "codesearchnet_filtered"} +{"code": "def get_stream_action_type(stream_arn):\n stream_type_map = {'kinesis': awacs.kinesis.Action, 'dynamodb': awacs.dynamodb.Action}\n stream_type = stream_arn.split(':')[2]\n try:\n return stream_type_map[stream_type]\n except KeyError:\n raise ValueError((\"Invalid stream type '%s' in arn '%s'\" % (stream_type, stream_arn)))", "docstring": "Returns the awacs Action for a stream type given an arn\n\nArgs:\n stream_arn (str): The Arn of the stream.\n\nReturns:\n :class:`awacs.aws.Action`: The appropriate stream type awacs Action\n class\n\nRaises:\n ValueError: If the stream type doesn't match kinesis or dynamodb.", "source": "codesearchnet_filtered"} +{"code": "def GetEventFormatter(self, event):\n data_type = getattr(event, 'data_type', None)\n if (not data_type):\n return None\n return formatters_manager.FormattersManager.GetFormatterObject(event.data_type)", "docstring": "Retrieves the event formatter for a specific event type.\n\nArgs:\n event (EventObject): event.\n\nReturns:\n EventFormatter: event formatter or None.", "source": "codesearchnet_filtered"} +{"code": "def _GetComparable(self, sub_comparable_string=''):\n string_parts = []\n string_parts.append(getattr(self.parent, 'comparable', ''))\n string_parts.append('type: {0:s}'.format(self.type_indicator))\n if sub_comparable_string:\n string_parts.append(', {0:s}'.format(sub_comparable_string))\n string_parts.append('\\n')\n return ''.join(string_parts)", "docstring": "Retrieves the comparable representation.\n\n This is a convenience function for constructing comparables.\n\nArgs:\n sub_comparable_string (str): sub comparable string.\n\nReturns:\n str: comparable representation of the path specification.", "source": "codesearchnet_filtered"} +{"code": "def state_scope(self, state_fluents: Sequence[tf.Tensor]) -> Dict[(str, TensorFluent)]:\n return dict(zip(self.rddl.domain.state_fluent_ordering, state_fluents))", "docstring": "Returns a partial scope with current state-fluents.\n\nArgs:\n state_fluents (Sequence[tf.Tensor]): The current state fluents.\n\nReturns:\n A mapping from state fluent names to :obj:`rddl2tf.fluent.TensorFluent`.", "source": "codesearchnet_filtered"} +{"code": "def add_network(self, network, netmask, area=0):\n if ((network == '') or (netmask == '')):\n raise ValueError('network and mask values may not be empty')\n cmd = 'network {}/{} area {}'.format(network, netmask, area)\n return self.configure_ospf(cmd)", "docstring": "Adds a network to be advertised by OSPF\n\nArgs:\n network (str): The network to be advertised in dotted decimal\n notation\n netmask (str): The netmask to configure\n area (str): The area the network belongs to.\n By default this value is 0\n\nReturns:\n bool: True if the command completes successfully\n Exception:\n ValueError: This will get raised if network or netmask\n are not passed to the method", "source": "codesearchnet_filtered"} +{"code": "def CreateTask(self, session_identifier):\n task = tasks.Task(session_identifier)\n logger.debug('Created task: {0:s}.'.format(task.identifier))\n with self._lock:\n self._tasks_queued[task.identifier] = task\n self._total_number_of_tasks += 1\n self.SampleTaskStatus(task, 'created')\n return task", "docstring": "Creates a task.\n\nArgs:\n session_identifier (str): the identifier of the session the task is\n part of.\n\nReturns:\n Task: task attribute container.", "source": "codesearchnet_filtered"} +{"code": "def GetDecrypter(cls, encryption_method, **kwargs):\n encryption_method = encryption_method.lower()\n decrypter = cls._decrypters.get(encryption_method, None)\n if (not decrypter):\n return None\n return decrypter(**kwargs)", "docstring": "Retrieves the decrypter object for a specific encryption method.\n\nArgs:\n encryption_method (str): encryption method identifier.\n kwargs (dict): keyword arguments depending on the decrypter.\n\nReturns:\n Decrypter: decrypter or None if the encryption method does not exists.\n\nRaises:\n CredentialError: if the necessary credentials are missing.", "source": "codesearchnet_filtered"} +{"code": "def case(self, case):\n LOG.debug('Getting case {0} from database'.format(case.get('case_id')))\n case_id = case['case_id']\n return self.db.case.find_one({'case_id': case_id})", "docstring": "Get a case from the database\n\n Search the cases with the case id\n\nArgs:\n case (dict): A case dictionary\n\nReturns:\n mongo_case (dict): A mongo case dictionary", "source": "codesearchnet_filtered"} +{"code": "def _fetch(self, method, url=None, post_data=None, parse_data=True, key=None, parameters=None, listener=None, full_return=False):\n headers = self.get_headers()\n headers['Content-Type'] = 'application/json'\n handlers = []\n debuglevel = int(self._settings['debug'])\n handlers.append(urllib2.HTTPHandler(debuglevel=debuglevel))\n if hasattr(httplib, 'HTTPS'):\n handlers.append(urllib2.HTTPSHandler(debuglevel=debuglevel))\n handlers.append(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))\n password_url = self._get_password_url()\n if (password_url and ('Authorization' not in headers)):\n pwd_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()\n pwd_manager.add_password(None, password_url, self._settings['user'], self._settings['password'])\n handlers.append(HTTPBasicAuthHandler(pwd_manager))\n opener = urllib2.build_opener(*handlers)\n if (post_data is not None):\n post_data = json.dumps(post_data)\n uri = self._url(url, parameters)\n request = RESTRequest(uri, method=method, headers=headers)\n if (post_data is not None):\n request.add_data(post_data)\n response = None\n try:\n response = opener.open(request)\n body = response.read()\n if (password_url and (password_url not in self._settings['authorizations']) and request.has_header('Authorization')):\n self._settings['authorizations'][password_url] = request.get_header('Authorization')\n except urllib2.HTTPError as e:\n if (e.code == 401):\n raise AuthenticationError(('Access denied while trying to access %s' % uri))\n elif (e.code == 404):\n raise ConnectionError(('URL not found: %s' % uri))\n else:\n raise\n except urllib2.URLError as e:\n raise ConnectionError(('Error while fetching from %s: %s' % (uri, e)))\n finally:\n if response:\n response.close()\n opener.close()\n data = None\n if parse_data:\n if (not key):\n key = string.split(url, '/')[0]\n data = self.parse(body, key)\n if full_return:\n info = (response.info() if response else None)\n status = (int(string.split(info['status'])[0]) if (info and ('status' in info)) else None)\n return {'success': ((status >= 200) and (status < 300)), 'data': data, 'info': info, 'body': body}\n return data", "docstring": "Issue a request.\n\nArgs:\n method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None\n\n Kwargs:\n url (str): Destination URL\n post_data (str): A string of what to POST\n parse_data (bool): If true, parse response data\n key (string): If parse_data==True, look for this key when parsing data\n parameters (dict): Additional GET parameters to append to the URL\n listener (func): callback called when uploading a file\n full_return (bool): If set to True, get a full response (with success, data, info, body)\n\nReturns:\n dict. Response. If full_return==True, a dict with keys: success, data, info, body, otherwise the parsed data\n\nRaises:\n AuthenticationError, ConnectionError, urllib2.HTTPError, ValueError", "source": "codesearchnet_filtered"} +{"code": "def execute_plan(plan):\n results = [action() for action in plan]\n return [result for result in results if actns.step_has_failed(result)]", "docstring": "Execute the plan.\n\nArgs:\n plan (:obj:`list` of :obj:`actions.Step`): The plan we want to execute.\n\nReturns:\n (:obj:`list` of :obj:`actions.Step`): A list of failed actions.", "source": "codesearchnet_filtered"} +{"code": "def get_file(self, url, path_or_file=None, headers=None, filename=None):\n path_or_file = (path_or_file or filename)\n if self.debug:\n print(('GET FILE: %s, headers=%s' % (url, headers)))\n self.headers = self._get_default_headers()\n if (headers is not None):\n self.headers.update(headers)\n response = requests.get(url, headers=self.headers, auth=self.auth, verify=self.verify_ssl)\n self.http_status_code = response.status_code\n try:\n self._check_error(response)\n try:\n path_or_file.write(response.content)\n except AttributeError:\n fd = os.open(path_or_file, (os.O_CREAT | os.O_RDWR))\n with os.fdopen(fd, 'w+b') as f:\n f.write(response.content)\n except:\n return False\n return True", "docstring": "Get a file from a url and save it as `filename`\n\nArgs:\n url (str): URL to send the request to\n\n path_or_file (str or file): A writable File-like object or a path to save the file to.\n\n filename (str): [DEPRECATED] File name to save the file as, this can be either\n a full path or a relative path\n\n headers (str, optional): custom headers\n\nReturns:\n True if file is downloaded and written successfully, False\n otherwise.", "source": "codesearchnet_filtered"} +{"code": "def base_name_from_image(image):\n m = re.match('^(.+/)?([^:/]+)(:[^:]+)?$', image)\n algo_name = (m.group(2) if m else image)\n return algo_name", "docstring": "Extract the base name of the image to use as the 'algorithm name' for the job.\n\nArgs:\n image (str): Image name.\n\nReturns:\n str: Algorithm name, as extracted from the image name.", "source": "codesearchnet_filtered"} +{"code": "def _get_nan_block_id(partition_class, n_row=1, n_col=1, transpose=False):\n global _NAN_BLOCKS\n if transpose:\n (n_row, n_col) = (n_col, n_row)\n shape = (n_row, n_col)\n if (shape not in _NAN_BLOCKS):\n arr = np.tile(np.array(np.NaN), shape)\n _NAN_BLOCKS[shape] = partition_class.put(pandas.DataFrame(data=arr))\n return _NAN_BLOCKS[shape]", "docstring": "A memory efficient way to get a block of NaNs.\n\nArgs:\n partition_class (BaseFramePartition): The class to use to put the object\n in the remote format.\n n_row(int): The number of rows.\n n_col(int): The number of columns.\n transpose(bool): If true, swap rows and columns.\n\nReturns:\n ObjectID of the NaN block.", "source": "codesearchnet_filtered"} +{"code": "def create_graph_from_data(self, data, **kwargs):\n self.arguments['{SCORE}'] = self.scores[self.score]\n self.arguments['{CUTOFF}'] = str(self.cutoff)\n self.arguments['{VARSEL}'] = str(self.variablesel).upper()\n self.arguments['{SELMETHOD}'] = self.var_selection[self.selmethod]\n self.arguments['{PRUNING}'] = str(self.pruning).upper()\n self.arguments['{PRUNMETHOD}'] = self.var_selection[self.prunmethod]\n self.arguments['{NJOBS}'] = str(self.nb_jobs)\n self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n results = self._run_cam(data, verbose=self.verbose)\n return nx.relabel_nodes(nx.DiGraph(results), {idx: i for (idx, i) in enumerate(data.columns)})", "docstring": "Apply causal discovery on observational data using CAM.\n\nArgs:\n data (pandas.DataFrame): DataFrame containing the data\n\nReturns:\n networkx.DiGraph: Solution given by the CAM algorithm.", "source": "codesearchnet_filtered"} +{"code": "def defaultannotator(self, annotationtype, set=None):\n if (inspect.isclass(annotationtype) or isinstance(annotationtype, AbstractElement)):\n annotationtype = annotationtype.ANNOTATIONTYPE\n if (not set):\n set = self.defaultset(annotationtype)\n try:\n return self.annotationdefaults[annotationtype][set]['annotator']\n except KeyError:\n raise NoDefaultError", "docstring": "Obtain the default annotator for the specified annotation type and set.\n\nArgs:\n annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member of :class:`AnnotationType`, such as ``AnnotationType.POS``.\n set (str): the set, should formally be a URL pointing to the set definition\n\nReturns:\n the set (str)\n\nRaises:\n :class:`NoDefaultError` if the annotation type does not exist or if there is ambiguity (multiple sets for the same type)", "source": "codesearchnet_filtered"} +{"code": "def get_nn_info(self, structure, n):\n nns = self.get_voronoi_polyhedra(structure, n)\n return self._extract_nn_info(structure, nns)", "docstring": "Get all near-neighbor sites as well as the associated image locations\n and weights of the site with index n in structure\n using Voronoi decomposition.\n\nArgs:\n structure (Structure): input structure.\n n (integer): index of site for which to determine near-neighbor\n sites.\n\nReturns:\n siw (list of tuples (Site, array, float)): tuples, each one\n of which represents a coordinated site, its image location,\n and its weight.", "source": "codesearchnet_filtered"} +{"code": "def from_string(cls, model_id, default_project=None):\n (proj, dset, model) = _helpers._parse_3_part_id(model_id, default_project=default_project, property_name='model_id')\n return cls.from_api_repr({'projectId': proj, 'datasetId': dset, 'modelId': model})", "docstring": "Construct a model reference from model ID string.\n\nArgs:\n model_id (str):\n A model ID in standard SQL format. If ``default_project``\n is not specified, this must included a project ID, dataset\n ID, and model ID, each separated by ``.``.\n default_project (str):\n Optional. The project ID to use when ``model_id`` does not\n include a project ID.\n\nReturns:\n google.cloud.bigquery.model.ModelReference:\n Model reference parsed from ``model_id``.\n\nRaises:\n ValueError:\n If ``model_id`` is not a fully-qualified table ID in\n standard SQL format.", "source": "codesearchnet_filtered"} +{"code": "def load_config_file(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME, fallback_config_instance=None):\n if (not fallback_config_instance):\n fallback_config_instance = backend_config_to_configparser(get_default_backend_config(appdirs))\n config = SafeConfigParser()\n path = get_config_path(appdirs, file_name)\n if (not config.read(path)):\n config = write_config_file(fallback_config_instance, appdirs=appdirs, file_name=file_name)\n return config", "docstring": "Retrieve config information from file at default location.\n\n If no config file is found a new one will be created either with ``fallback_config_instance``\n as content or if none is provided with the result of ``get_default_backend_config``.\n\nArgs:\n appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific\n path information.\n file_name (text_type, optional): Name of the config file. Defaults to\n ``DEFAULT_CONFIG_FILENAME``.\n fallback_config_instance (ConfigParser): Backend config that is to be used to populate the\n config file that is created if no pre-existing one can be found.\n\nReturns:\n SafeConfigParser: Config loaded from file, either from the the pre-existing config\n file or the one created with fallback values.", "source": "codesearchnet_filtered"} +{"code": "def get_groups(self, **kwargs):\n params = {'cultureInfo': util.language_code(kwargs.get('lang'))}\n result = self.make_request('geo', 'get_groups', **params)\n if (not util.check_result(result)):\n return (False, result.get('resultDescription', 'UNKNOWN ERROR'))\n values = util.response_list(result, 'resultValues')\n return (True, [emtype.GeoGroupItem(**a) for a in values])", "docstring": "Obtain line types and details.\n\nArgs:\n lang (str): Language code (*es* or *en*).\n\nReturns:\n Status boolean and parsed response (list[GeoGroupItem]), or message\n string in case of error.", "source": "codesearchnet_filtered"} +{"code": "def get(self, public_key, spent=None, headers=None):\n return self.transport.forward_request(method='GET', path=self.path, params={'public_key': public_key, 'spent': spent}, headers=headers)", "docstring": "Get transaction outputs by public key. The public_key parameter\n must be a base58 encoded ed25519 public key associated with\n transaction output ownership.\n\nArgs:\n public_key (str): Public key for which unfulfilled\n conditions are sought.\n spent (bool): Indicate if the result set should include only spent\n or only unspent outputs. If not specified (``None``) the\n result includes all the outputs (both spent and unspent)\n associated with the public key.\n headers (dict): Optional headers to pass to the request.\n\nReturns:\n :obj:`list` of :obj:`str`: List of unfulfilled conditions.\n\nExample:\n Given a transaction with `id` ``da1b64a907ba54`` having an\n `ed25519` condition (at index ``0``) with alice's public\n key::\n\n >>> bdb = BigchainDB()\n >>> bdb.outputs.get(alice_pubkey)\n ... ['../transactions/da1b64a907ba54/conditions/0']", "source": "codesearchnet_filtered"} +{"code": "def download_archive_artifact_bundle(self, id_or_uri, file_path):\n uri = ((self.BACKUP_ARCHIVE_PATH + '/') + extract_id_from_uri(id_or_uri))\n return self._client.download(uri, file_path)", "docstring": "Downloads an archive for the Artifact Bundle.\n\nArgs:\n id_or_uri: ID or URI of the Artifact Bundle.\n file_path(str): Destination file path.\n\nReturns:\n bool: Successfully downloaded.", "source": "codesearchnet_filtered"} +{"code": "def _GetCachedEntryDataTypeMap(self, format_type, value_data, cached_entry_offset):\n if (format_type not in self._SUPPORTED_FORMAT_TYPES):\n raise errors.ParseError('Unsupported format type: {0:d}'.format(format_type))\n data_type_map_name = ''\n if (format_type == self._FORMAT_TYPE_XP):\n data_type_map_name = 'appcompatcache_cached_entry_xp_32bit'\n elif (format_type in (self._FORMAT_TYPE_8, self._FORMAT_TYPE_10)):\n data_type_map_name = 'appcompatcache_cached_entry_header_8'\n else:\n cached_entry = self._ParseCommon2003CachedEntry(value_data, cached_entry_offset)\n if ((cached_entry.path_offset_32bit == 0) and (cached_entry.path_offset_64bit != 0)):\n number_of_bits = '64'\n else:\n number_of_bits = '32'\n if (format_type == self._FORMAT_TYPE_2003):\n data_type_map_name = 'appcompatcache_cached_entry_2003_{0:s}bit'.format(number_of_bits)\n elif (format_type == self._FORMAT_TYPE_VISTA):\n data_type_map_name = 'appcompatcache_cached_entry_vista_{0:s}bit'.format(number_of_bits)\n elif (format_type == self._FORMAT_TYPE_7):\n data_type_map_name = 'appcompatcache_cached_entry_7_{0:s}bit'.format(number_of_bits)\n return self._GetDataTypeMap(data_type_map_name)", "docstring": "Determines the cached entry data type map.\n\nArgs:\n format_type (int): format type.\n value_data (bytes): value data.\n cached_entry_offset (int): offset of the first cached entry data\n relative to the start of the value data.\n\nReturns:\n dtfabric.DataTypeMap: data type map which contains a data type definition,\n such as a structure, that can be mapped onto binary data or None\n if the data type map is not defined.\n\nRaises:\n ParseError: if the cached entry data type map cannot be determined.", "source": "codesearchnet_filtered"} +{"code": "def _use_prototype(self, spec, prototypes):\n prototype = spec['based-on']\n del spec['based-on']\n for attr in prototype:\n if (attr not in spec):\n spec[attr] = copy.deepcopy(prototype[attr])\n return spec", "docstring": "Populates the given spec with the values of it's declared prototype\n\nArgs:\n spec (dict): spec to update\n prototypes (dict): Configuration spec containing the prototypes\n\nReturns:\n dict: updated spec", "source": "codesearchnet_filtered"} +{"code": "def memoise(cls, func):\n\n @functools.wraps(func)\n def f(*a):\n for arg in a:\n if isinstance(arg, User):\n user = arg\n break\n else:\n raise ValueError('One position argument must be a User')\n func_key = (func, tuple(a))\n cache = cls.get_cache(user)\n if (func_key not in cache):\n cache[func_key] = func(*a)\n return cache[func_key]\n return f", "docstring": "Decorator that stores the result of the stored function in the\n user's results cache until the batch completes. Keyword arguments are\n not yet supported.\n\nArgs:\n func (callable(*a)): The function whose results we want\n to store. The positional arguments, ``a``, are used as cache\n keys.\n\nReturns:\n callable(*a): The memosing version of ``func``.", "source": "codesearchnet_filtered"} +{"code": "def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False):\n if (self._dimension != 2):\n raise NotImplementedError('2D is the only supported dimension', 'Current dimension', self._dimension)\n if (ax is None):\n ax = _plot_helpers.new_axis()\n _plot_helpers.add_patch(ax, color, pts_per_edge, *self._get_edges())\n if with_nodes:\n ax.plot(self._nodes[(0, :)], self._nodes[(1, :)], color='black', marker='o', linestyle='None')\n return ax", "docstring": "Plot the current surface.\n\nArgs:\n pts_per_edge (int): Number of points to plot per edge.\n color (Optional[Tuple[float, float, float]]): Color as RGB profile.\n ax (Optional[matplotlib.artist.Artist]): matplotlib axis object\n to add plot to.\n with_nodes (Optional[bool]): Determines if the control points\n should be added to the plot. Off by default.\n\nReturns:\n matplotlib.artist.Artist: The axis containing the plot. This\n may be a newly created axis.\n\nRaises:\n NotImplementedError: If the surface's dimension is not ``2``.", "source": "codesearchnet_filtered"} +{"code": "def smooth(self, noise, strategy=INVERSE_STRATEGY):\n if (strategy is INVERSE_STRATEGY):\n self.points = with_inverse(self.points, noise)\n elif (strategy is EXTRAPOLATE_STRATEGY):\n self.points = with_extrapolation(self.points, noise, 30)\n elif (strategy is NO_STRATEGY):\n self.points = with_no_strategy(self.points, noise)\n return self", "docstring": "In-place smoothing\n\n See smooth_segment function\n\nArgs:\n noise (float): Noise expected\n strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY\n or smooth.EXTRAPOLATE_STRATEGY\n\nReturns:\n :obj:`Segment`", "source": "codesearchnet_filtered"} +{"code": "def get_street_from_xy(self, **kwargs):\n params = {'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'Radius': kwargs.get('radius'), 'cultureInfo': util.language_code(kwargs.get('lang'))}\n result = self.make_request('geo', 'get_street_from_xy', **params)\n if (not util.check_result(result, 'site')):\n return (False, 'UNKNOWN ERROR')\n values = util.response_list(result, 'site')\n return (True, [emtype.Street(**a) for a in values])", "docstring": "Obtain a list of streets around the specified point.\n\nArgs:\n latitude (double): Latitude in decimal degrees.\n longitude (double): Longitude in decimal degrees.\n radius (int): Radius (in meters) of the search.\n lang (str): Language code (*es* or *en*).\n\nReturns:\n Status boolean and parsed response (list[Street]), or message string\n in case of error.", "source": "codesearchnet_filtered"} +{"code": "def log_handler(self, handler):\n if (not self.opened()):\n handler = (handler or util.noop)\n self._log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)\n self._dll.JLINKARM_EnableLog(self._log_handler)", "docstring": "Setter for the log handler function.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n ``None``", "source": "codesearchnet_filtered"} +{"code": "def builtin(cls, name):\n names = {'nsdoe': LEGEND__NSDOE, 'canstrat': LEGEND__Canstrat, 'nagmdm__6_2': LEGEND__NAGMDM__6_2, 'nagmdm__6_1': LEGEND__NAGMDM__6_1, 'nagmdm__4_3': LEGEND__NAGMDM__4_3, 'sgmc': LEGEND__SGMC}\n return cls.from_csv(text=names[name.lower()])", "docstring": "Generate a default legend.\n\nArgs:\n name (str): The name of the legend you want. Not case sensitive.\n 'nsdoe': Nova Scotia Dept. of Energy\n 'canstrat': Canstrat\n 'nagmdm__6_2': USGS N. Am. Geol. Map Data Model 6.2\n 'nagmdm__6_1': USGS N. Am. Geol. Map Data Model 6.1\n 'nagmdm__4_3': USGS N. Am. Geol. Map Data Model 4.3\n 'sgmc': USGS State Geologic Map Compilation\n\n Default 'nagmdm__6_2'.\n\nReturns:\n Legend: The legend stored in `defaults.py`.", "source": "codesearchnet_filtered"} +{"code": "def remove_item(self, item):\n for (idx, _item) in enumerate(self.items):\n if (item == _item):\n del self.items[idx]\n return True\n return False", "docstring": "Remove the specified item from the menu.\n\nArgs:\n item (MenuItem): the item to be removed.\n\nReturns:\n bool: True if the item was removed; False otherwise.", "source": "codesearchnet_filtered"} +{"code": "def from_json(cls, jsonmsg):\n import json\n msg = json.loads(jsonmsg)\n obj = cls(**msg)\n obj.validate()\n return obj", "docstring": "Create an object directly from a JSON string.\n\n Applies general validation after creating the\n object to check whether all required fields are\n present.\n\nArgs:\n jsonmsg (str): An object encoded as a JSON string\n\nReturns:\n An object of the generated type\n\nRaises:\n ValidationError: if `jsonmsg` does not match the schema\n `cls` was generated from", "source": "codesearchnet_filtered"} +{"code": "def rebin(d, n_x, n_y=None):\n if (d.ndim == 2):\n if (n_y is None):\n n_y = 1\n if (n_x is None):\n n_x = 1\n d = d[(:(int((d.shape[0] // n_x)) * n_x), :(int((d.shape[1] // n_y)) * n_y))]\n d = d.reshape(((d.shape[0] // n_x), n_x, (d.shape[1] // n_y), n_y))\n d = d.mean(axis=3)\n d = d.mean(axis=1)\n elif (d.ndim == 1):\n d = d[:(int((d.shape[0] // n_x)) * n_x)]\n d = d.reshape(((d.shape[0] // n_x), n_x))\n d = d.mean(axis=1)\n else:\n raise RuntimeError('Only NDIM <= 2 supported')\n return d", "docstring": "Rebin data by averaging bins together\n\nArgs:\n d (np.array): data\n n_x (int): number of bins in x dir to rebin into one\n n_y (int): number of bins in y dir to rebin into one\n\nReturns:\n d: rebinned data with shape (n_x, n_y)", "source": "codesearchnet_filtered"} +{"code": "def margin_transfer(self, margin_profile_id, transfer_type, currency, amount):\n params = {'margin_profile_id': margin_profile_id, 'type': transfer_type, 'currency': currency, 'amount': amount}\n return self._send_message('post', '/profiles/margin-transfer', data=json.dumps(params))", "docstring": "Transfer funds between your standard profile and a margin profile.\n\nArgs:\n margin_profile_id (str): Margin profile ID to withdraw or deposit\n from.\n transfer_type (str): 'deposit' or 'withdraw'\n currency (str): Currency to transfer (eg. 'USD')\n amount (Decimal): Amount to transfer\n\nReturns:\n dict: Transfer details. Example::\n {\n \"created_at\": \"2017-01-25T19:06:23.415126Z\",\n \"id\": \"80bc6b74-8b1f-4c60-a089-c61f9810d4ab\",\n \"user_id\": \"521c20b3d4ab09621f000011\",\n \"profile_id\": \"cda95996-ac59-45a3-a42e-30daeb061867\",\n \"margin_profile_id\": \"45fa9e3b-00ba-4631-b907-8a98cbdf21be\",\n \"type\": \"deposit\",\n \"amount\": \"2\",\n \"currency\": \"USD\",\n \"account_id\": \"23035fc7-0707-4b59-b0d2-95d0c035f8f5\",\n \"margin_account_id\": \"e1d9862c-a259-4e83-96cd-376352a9d24d\",\n \"margin_product_id\": \"BTC-USD\",\n \"status\": \"completed\",\n \"nonce\": 25\n }", "source": "codesearchnet_filtered"} +{"code": "def build_parameters(self, stack, provider_stack=None):\n resolved = _resolve_parameters(stack.parameter_values, stack.blueprint)\n required_parameters = list(stack.required_parameter_definitions)\n all_parameters = list(stack.all_parameter_definitions)\n parameters = _handle_missing_parameters(resolved, all_parameters, required_parameters, provider_stack)\n param_list = []\n for (key, value) in parameters:\n param_dict = {'ParameterKey': key}\n if (value is UsePreviousParameterValue):\n param_dict['UsePreviousValue'] = True\n else:\n param_dict['ParameterValue'] = str(value)\n param_list.append(param_dict)\n return param_list", "docstring": "Builds the CloudFormation Parameters for our stack.\n\nArgs:\n stack (:class:`stacker.stack.Stack`): A stacker stack\n provider_stack (dict): An optional Stacker provider object\n\nReturns:\n dict: The parameters for the given stack", "source": "codesearchnet_filtered"} +{"code": "def get_sns_topic_arn(topic_name, account, region):\n if ((topic_name.count(':') == 5) and topic_name.startswith('arn:aws:sns:')):\n return topic_name\n session = boto3.Session(profile_name=account, region_name=region)\n sns_client = session.client('sns')\n topics = sns_client.list_topics()['Topics']\n matched_topic = None\n for topic in topics:\n topic_arn = topic['TopicArn']\n if (topic_name == topic_arn.split(':')[(- 1)]):\n matched_topic = topic_arn\n break\n else:\n LOG.critical('No topic with name %s found.', topic_name)\n raise SNSTopicNotFound('No topic with name {0} found'.format(topic_name))\n return matched_topic", "docstring": "Get SNS topic ARN.\n\nArgs:\n topic_name (str): Name of the topic to lookup.\n account (str): Environment, e.g. dev\n region (str): Region name, e.g. us-east-1\n\nReturns:\n str: ARN for requested topic name", "source": "codesearchnet_filtered"} +{"code": "def get_cmd_out(command):\n if isinstance(command, list):\n result = sp.check_output(command)\n else:\n result = sp.check_output(command, shell=True)\n return result.decode('utf-8').rstrip()", "docstring": "Get the output of a command.\n\n Gets a nice Unicode no-extra-whitespace string of the ``stdout`` of a given command.\n\nArgs:\n command (str or list): A string of the command, or a list of the arguments (as would be used in :class:`subprocess.Popen`).\n\nNote:\n If ``command`` is a ``str``, it will be evaluated with ``shell=True`` i.e. in the default shell (for example, bash).\n\nReturns:\n str: The ``stdout`` of the command.", "source": "codesearchnet_filtered"} +{"code": "def section(self, section):\n if (not isinstance(self._container, ConfigUpdater)):\n raise ValueError('Sections can only be added at section level!')\n if isinstance(section, str):\n section = Section(section, container=self._container)\n elif (not isinstance(section, Section)):\n raise ValueError('Parameter must be a string or Section type!')\n if (section.name in [block.name for block in self._container if isinstance(block, Section)]):\n raise DuplicateSectionError(section.name)\n self._container.structure.insert(self._idx, section)\n self._idx += 1\n return self", "docstring": "Creates a section block\n\nArgs:\n section (str or :class:`Section`): name of section or object\n\nReturns:\n self for chaining", "source": "codesearchnet_filtered"} +{"code": "def list(self, resource, url_prefix, auth, session, send_opts):\n req = self.get_request(resource, 'GET', 'application/json', url_prefix, auth, proj_list_req=True)\n prep = session.prepare_request(req)\n resp = session.send(prep, **send_opts)\n if (resp.status_code == 200):\n return self._get_resource_list(resp.json())\n err = 'List failed on {}, got HTTP response: ({}) - {}'.format(resource.name, resp.status_code, resp.text)\n raise HTTPError(err, request=req, response=resp)", "docstring": "List all resources of the same type as the given resource.\n\nArgs:\n resource (intern.resource.boss.BossResource): List resources of the same type as this..\n url_prefix (string): Protocol + host such as https://api.theboss.io\n auth (string): Token to send in the request header.\n session (requests.Session): HTTP session to use for request.\n send_opts (dictionary): Additional arguments to pass to session.send().\n\nReturns:\n (list): List of resources. Each resource is a dictionary.\n\nRaises:\n requests.HTTPError on failure.", "source": "codesearchnet_filtered"} +{"code": "def PyParseRangeCheck(lower_bound, upper_bound):\n\n def CheckRange(string, location, tokens):\n 'Parse the arguments.\\n\\n Args:\\n string (str): original string.\\n location (int): location in the string where the match was made\\n tokens (list[str]): tokens.\\n '\n try:\n check_number = tokens[0]\n except IndexError:\n check_number = (- 1)\n if (check_number < lower_bound):\n raise pyparsing.ParseException('Value: {0:d} precedes lower bound: {1:d}'.format(check_number, lower_bound))\n if (check_number > upper_bound):\n raise pyparsing.ParseException('Value: {0:d} exceeds upper bound: {1:d}'.format(check_number, upper_bound))\n return CheckRange", "docstring": "Verify that a number is within a defined range.\n\n This is a callback method for pyparsing setParseAction\n that verifies that a read number is within a certain range.\n\n To use this method it needs to be defined as a callback method\n in setParseAction with the upper and lower bound set as parameters.\n\nArgs:\n lower_bound (int): lower bound of the range.\n upper_bound (int): upper bound of the range.\n\nReturns:\n Function: callback method that can be used by pyparsing setParseAction.", "source": "codesearchnet_filtered"} +{"code": "def decode_metar(self, metar):\n try:\n from metar import Metar\n except:\n return 'Unable to parse metars. Please install parser from https://github.com/tomp/python-metar.'\n m = Metar.Metar(metar)\n return m.string()", "docstring": "Simple method that decodes a given metar string.\n\nArgs:\n metar (str): The metar data\n\nReturns:\n The metar data in readable format\n\n Example::\n\n from pyflightdata import FlightData\n f=FlightData()\n f.decode_metar('WSSS 181030Z 04009KT 010V080 9999 FEW018TCU BKN300 29/22 Q1007 NOSIG')", "source": "codesearchnet_filtered"} +{"code": "def dependency_of_fetches(fetches, op):\n try:\n from tensorflow.python.client.session import _FetchHandler as FetchHandler\n handler = FetchHandler(op.graph, fetches, {})\n targets = tuple((handler.fetches() + handler.targets()))\n except ImportError:\n if isinstance(fetches, list):\n targets = tuple(fetches)\n elif isinstance(fetches, dict):\n raise ValueError(\"Don't know how to parse dictionary to fetch list! This is a bug of tensorpack.\")\n else:\n targets = (fetches,)\n return dependency_of_targets(targets, op)", "docstring": "Check that op is in the subgraph induced by the dependencies of fetches.\n fetches may have more general structure.\n\nArgs:\n fetches: An argument to `sess.run`. Nested structure will affect performance.\n op (tf.Operation or tf.Tensor):\n\nReturns:\n bool: True if any of `fetches` depend on `op`.", "source": "codesearchnet_filtered"} +{"code": "def plot(self, num_pts, color=None, alpha=None, ax=None):\n if (self._dimension != 2):\n raise NotImplementedError('2D is the only supported dimension', 'Current dimension', self._dimension)\n s_vals = np.linspace(0.0, 1.0, num_pts)\n points = self.evaluate_multi(s_vals)\n if (ax is None):\n ax = _plot_helpers.new_axis()\n ax.plot(points[(0, :)], points[(1, :)], color=color, alpha=alpha)\n return ax", "docstring": "Plot the current curve.\n\nArgs:\n num_pts (int): Number of points to plot.\n color (Optional[Tuple[float, float, float]]): Color as RGB profile.\n alpha (Optional[float]): The alpha channel for the color.\n ax (Optional[matplotlib.artist.Artist]): matplotlib axis object\n to add plot to.\n\nReturns:\n matplotlib.artist.Artist: The axis containing the plot. This\n may be a newly created axis.\n\nRaises:\n NotImplementedError: If the curve's dimension is not ``2``.", "source": "codesearchnet_filtered"} +{"code": "def unlock(self, passphrase, encrypted_seed=None):\n wallet = self.resource\n if (not encrypted_seed):\n encrypted_seed = wallet.primary_private_seed\n try:\n if encrypted_seed['nonce']:\n primary_seed = NaclPassphraseBox.decrypt(passphrase, encrypted_seed)\n else:\n primary_seed = PassphraseBox.decrypt(passphrase, encrypted_seed)\n except:\n raise InvalidPassphraseError()\n self.multi_wallet = MultiWallet(private_seeds={'primary': primary_seed}, public={'cosigner': wallet.cosigner_public_seed, 'backup': wallet.backup_public_seed})\n return self", "docstring": "Unlock the Wallet by decrypting the primary_private_seed with the\n supplied passphrase. Once unlocked, the private seed is accessible in\n memory and calls to `account.pay` will succeed. This is a necessary step\n for creating transactions.\n\nArgs:\n passphrase (str): The passphrase the User used to encrypt this wallet.\n encrypted_seed (dict): A dictionary of the form\n {'ciphertext': longhexvalue,\n 'iterations': integer of pbkdf2 derivations,\n 'nonce': 24-byte hex value\n 'salt': 16-byte hex value}\n this dict represents an private seed (not a master key) encrypted\n with the `passphrase` using pbkdf2. You can obtain this value with\n wallet.generate. If this value is supplied, it overwrites (locally\n only) the encrypted primary_private_seed value, allowing you to load\n in a primary key that you didn't store with Gem. Note that the key\n MUST match the pubkey that this wallet was created with.\n\nReturns:\n self", "source": "codesearchnet_filtered"} +{"code": "def wait_for_job(self, job, poll=5):\n desc = _wait_until_training_done((lambda last_desc: _train_done(self.sagemaker_client, job, last_desc)), None, poll)\n self._check_job_status(job, desc, 'TrainingJobStatus')\n return desc", "docstring": "Wait for an Amazon SageMaker training job to complete.\n\nArgs:\n job (str): Name of the training job to wait for.\n poll (int): Polling interval in seconds (default: 5).\n\nReturns:\n (dict): Return value from the ``DescribeTrainingJob`` API.\n\nRaises:\n ValueError: If the training job fails.", "source": "codesearchnet_filtered"} +{"code": "def update(self, *args, **kwargs):\n for next_dict in chain(args, (kwargs,)):\n for (k, v) in next_dict.items():\n self[k] = v", "docstring": "Equivalent to the python dict update method.\n\n Update the dictionary with the key/value pairs from other, overwriting\n existing keys.\n\nArgs:\n other (dict): The source of key value pairs to add to headers\n Keyword Args:\n All keyword arguments are stored in header directly\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def get_structural_variant(self, variant):\n query = {'chrom': variant['chrom'], 'end_chrom': variant['end_chrom'], 'sv_type': variant['sv_type'], '$and': [{'pos_left': {'$lte': variant['pos']}}, {'pos_right': {'$gte': variant['pos']}}]}\n res = self.db.structural_variant.find(query).sort('pos_left', 1)\n match = None\n distance = None\n closest_hit = None\n for hit in res:\n if (hit['end_left'] > variant['end']):\n continue\n if (hit['end_right'] < variant['end']):\n continue\n distance = (abs((variant['pos'] - ((hit['pos_left'] + hit['pos_right']) / 2))) + abs((variant['end'] - ((hit['end_left'] + hit['end_right']) / 2))))\n if (closest_hit is None):\n match = hit\n closest_hit = distance\n continue\n if (distance < closest_hit):\n match = hit\n closest_hit = distance\n return match", "docstring": "Check if there are any overlapping sv clusters\n\n Search the sv variants with chrom start end_chrom end and sv_type\n\nArgs:\n variant (dict): A variant dictionary\n\nReturns:\n variant (dict): A variant dictionary", "source": "codesearchnet_filtered"} +{"code": "def flatten(vari):\n if isinstance(vari, Poly):\n shape = int(numpy.prod(vari.shape))\n return reshape(vari, (shape,))\n return numpy.array(vari).flatten()", "docstring": "Flatten a shapeable quantity.\n\nArgs:\n vari (chaospy.poly.base.Poly, numpy.ndarray):\n Shapeable input quantity.\n\nReturns:\n (chaospy.poly.base.Poly, numpy.ndarray):\n Same type as ``vari`` with `len(Q.shape)==1`.\n\nExample:\n >>> P = chaospy.reshape(chaospy.prange(4), (2,2))\n >>> print(P)\n [[1, q0], [q0^2, q0^3]]\n >>> print(chaospy.flatten(P))\n [1, q0, q0^2, q0^3]", "source": "codesearchnet_filtered"} +{"code": "def doECDHE(statprv_u, statpub_v, ephmprv_u, ephmpub_v, length=64, salt=None, info=None):\n zs = statprv_u.exchange(statpub_v)\n ze = ephmprv_u.exchange(ephmpub_v)\n z = (ze + zs)\n kdf = c_hkdf.HKDF(c_hashes.SHA256(), length=length, salt=salt, info=info, backend=default_backend())\n k = kdf.derive(z)\n return k", "docstring": "Perform one side of an Ecliptic Curve Diffie Hellman Ephemeral key exchange.\n\nArgs:\n statprv_u (PriKey): Static Private Key for U\n statpub_v (PubKey: Static Public Key for V\n ephmprv_u (PriKey): Ephemeral Private Key for U\n ephmpub_v (PubKey): Ephemeral Public Key for V\n length (int): Number of bytes to return\n salt (bytes): Salt to use when computing the key.\n info (bytes): Additional information to use when computing the key.\n\nNote:\n This makes no assumption about the reuse of the Ephemeral keys passed\n to the function. It is the caller's responsibility to destroy the keys\n after they are used for doing key generation. This implementation is\n the dhHybrid1 scheme described in NIST 800-56A Revision 2.\n\nReturns:\n bytes: The derived key.", "source": "codesearchnet_filtered"} +{"code": "def indicator(self, indicator_type, summary, **kwargs):\n indicator_obj = Indicator(indicator_type, summary, **kwargs)\n return self._indicator(indicator_obj)", "docstring": "Add Indicator data to Batch object.\n\nArgs:\n indicator_type (str): The ThreatConnect define Indicator type.\n summary (str): The value for this Indicator.\n confidence (str, kwargs): The threat confidence for this Indicator.\n date_added (str, kwargs): The date timestamp the Indicator was created.\n last_modified (str, kwargs): The date timestamp the Indicator was last modified.\n rating (str, kwargs): The threat rating for this Indicator.\n xid (str, kwargs): The external id for this Indicator.\n\nReturns:\n obj: An instance of Indicator.", "source": "codesearchnet_filtered"} +{"code": "def local_reduction_attention(x, block_length, multihead_params):\n\n @expert_utils.add_name_scope()\n def dot_product_self_local_attention_flattened(q, k, v):\n 'Strided block local self-attention.\\n\\n No overlap between the blocks.\\n\\n Args:\\n q (tf.Tensor): shape [batch, heads, length, depth_k]\\n k (tf.Tensor): shape [batch, heads, length, depth_k]\\n v (tf.Tensor): shape [batch, heads, length, depth_v]\\n\\n Returns:\\n tf.Tensor: shape [batch, heads, length, depth_v]\\n '\n (_, num_head, _, depth) = q.get_shape().as_list()\n\n def pad_and_reshape(x):\n 'Split the length dim into [num_block, block_length].'\n length_x = common_layers.shape_list(x)[2]\n x = tf.pad(x, [[0, 0], [0, 0], [0, ((- length_x) % block_length)], [0, 0]])\n x = tf.reshape(x, [common_layers.shape_list(x)[0], num_head, (common_layers.shape_list(x)[2] // block_length), block_length, depth])\n return x\n (q, k, v) = [pad_and_reshape(t) for t in (q, k, v)]\n logits = tf.matmul(q, k, transpose_b=True)\n logits = tf.reshape(logits, [common_layers.shape_list(logits)[0], num_head, common_layers.shape_list(logits)[2], (block_length ** 2)])\n weights = tf.nn.softmax(logits)\n weights = tf.reshape(weights, [common_layers.shape_list(weights)[0], num_head, common_layers.shape_list(weights)[2], block_length, block_length])\n weights = tf.reduce_sum(weights, axis=3, keep_dims=True)\n v_out = tf.matmul(weights, v)\n v_out = tf.squeeze(v_out, axis=3)\n return v_out\n return multihead_attention(x, None, bias=None, output_depth=x.get_shape().as_list()[(- 1)], attention_type=dot_product_self_local_attention_flattened, **multihead_params)", "docstring": "Reduce the length dimension using self attention.\n\nArgs:\n x (tf.Tensor): float32 of shape [batch, length, depth]\n block_length (int): Block length for local attention (Compression factor)\n multihead_params (dict): parameters for multihead attention\n\nReturns:\n tf.Tensor: Compressed tensor of shape [batch, length // factor, depth]", "source": "codesearchnet_filtered"} +{"code": "def with_scopes_if_required(credentials, scopes):\n if (isinstance(credentials, Scoped) and credentials.requires_scopes):\n return credentials.with_scopes(scopes)\n else:\n return credentials", "docstring": "Creates a copy of the credentials with scopes if scoping is required.\n\n This helper function is useful when you do not know (or care to know) the\n specific type of credentials you are using (such as when you use\n :func:`google.auth.default`). This function will call\n :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if\n the credentials require scoping. Otherwise, it will return the credentials\n as-is.\n\nArgs:\n credentials (google.auth.credentials.Credentials): The credentials to\n scope if necessary.\n scopes (Sequence[str]): The list of scopes to use.\n\nReturns:\n google.auth.credentials.Credentials: Either a new set of scoped\n credentials, or the passed in credentials instance if no scoping\n was required.", "source": "codesearchnet_filtered"} +{"code": "def upload_file(self, local_file, dest_path, mimetype):\n self.__validate_storage_path(dest_path)\n if dest_path.endswith('/'):\n raise StorageArgumentException('Must specify target file name in dest_path argument')\n if local_file.endswith(os.path.sep):\n raise StorageArgumentException('Must specify source file name in local_file argument, directory upload not supported')\n new_file = self.api_client.create_file(name=dest_path.split('/').pop(), content_type=mimetype, parent=self.get_parent(dest_path)['uuid'])\n etag = self.api_client.upload_file_content(new_file['uuid'], source=local_file)\n new_file['etag'] = etag\n return new_file", "docstring": "Upload local file content to a storage service destination folder.\n\nArgs:\n local_file(str)\n dest_path(str):\n absolute Storage service path '/project' prefix is essential\n suffix should be the name the file will have on in the destination folder\n i.e.: /project/folder/.../file_name\n mimetype(str): set the contentType attribute\n\nReturns:\n The uuid of created file entity as string\n\nRaises:\n StorageArgumentException: Invalid arguments\n StorageForbiddenException: Server response code 403\n StorageNotFoundException: Server response code 404\n StorageException: other 400-600 error codes", "source": "codesearchnet_filtered"} +{"code": "def _from_any_pb(pb_type, any_pb):\n msg = pb_type()\n if (not any_pb.Unpack(msg)):\n raise TypeError('Could not convert {} to {}'.format(any_pb.__class__.__name__, pb_type.__name__))\n return msg", "docstring": "Converts an Any protobuf to the specified message type\n\nArgs:\n pb_type (type): the type of the message that any_pb stores an instance\n of.\n any_pb (google.protobuf.any_pb2.Any): the object to be converted.\n\nReturns:\n pb_type: An instance of the pb_type message.\n\nRaises:\n TypeError: if the message could not be converted.", "source": "codesearchnet_filtered"} +{"code": "def newsim(f, G, y0, name='NewModel', modelType=ItoModel, T=60.0, dt=0.005, repeat=1, identical=True):\n NewModel = newmodel(f, G, y0, name, modelType)\n if (repeat == 1):\n return Simulation(NewModel(), T, dt)\n else:\n return RepeatedSim(NewModel, T, dt, repeat, identical)", "docstring": "Make a simulation of the system defined by functions f and G.\n\n dy = f(y,t)dt + G(y,t).dW with initial condition y0\n This helper function is for convenience, making it easy to define\n one-off simulations interactively in ipython.\n\nArgs:\n f: callable(y, t) (defined in global scope) returning (n,) array\n Vector-valued function to define the deterministic part of the system\n G: callable(y, t) (defined in global scope) returning (n,m) array\n Optional matrix-valued function to define noise coefficients of an Ito\n SDE system.\n y0 (array): Initial condition\n name (str): Optional class name for the new model\n modelType (type): The type of model to simulate. Must be a subclass of\n nsim.Model, for example nsim.ODEModel, nsim.ItoModel or\n nsim.StratonovichModel. The default is nsim.ItoModel.\n T: Total length of time to simulate, in seconds.\n dt: Timestep for numerical integration.\n repeat (int, optional)\n identical (bool, optional)\n\nReturns:\n Simulation\n\nRaises:\n SimValueError, SimTypeError", "source": "codesearchnet_filtered"} +{"code": "def _add_tag(self, tag):\n tags = self.data.get('tags', None)\n if tags:\n if (tag in [x['name'] for x in tags]):\n return False\n else:\n tags = list()\n tags.append({'name': tag})\n self.data['tags'] = tags\n return True", "docstring": "Add a tag\n\nArgs:\n tag (str): Tag to add\n\nReturns:\n bool: True if tag added or False if tag already present", "source": "codesearchnet_filtered"} +{"code": "def stack1d(*points):\n result = np.empty((2, len(points)), order='F')\n for (index, point) in enumerate(points):\n result[(:, index)] = point\n return result", "docstring": "Fill out the columns of matrix with a series of points.\n\n This is because ``np.hstack()`` will just make another 1D vector\n out of them and ``np.vstack()`` will put them in the rows.\n\nArgs:\n points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e.\n arrays with shape ``(2,)``.\n\nReturns:\n numpy.ndarray: The array with each point in ``points`` as its\n columns.", "source": "codesearchnet_filtered"} +{"code": "def create(self, name, command_to_run, description='', environment_variables=None, required_arguments=None, required_arguments_default_values=None, extra_data_to_post=None):\n if (environment_variables is None):\n environment_variables = []\n if (required_arguments is None):\n required_arguments = []\n if (required_arguments_default_values is None):\n required_arguments_default_values = {}\n request_url = (self._client.base_api_url + self.list_url)\n data_to_post = {'name': name, 'description': description, 'command_to_run': command_to_run, 'environment_variables': json.dumps(environment_variables), 'required_arguments': json.dumps(required_arguments), 'required_arguments_default_values': json.dumps(required_arguments_default_values)}\n if (extra_data_to_post is not None):\n data_to_post.update(extra_data_to_post)\n response = self._client.session.post(request_url, data=data_to_post)\n self.validate_request_success(response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_201_CREATED)\n return self.response_data_to_model_instance(response.json())", "docstring": "Create a task type.\n\nArgs:\n name (str): The name of the task.\n command_to_run (str): The command to run to execute the task.\n description (str, optional): The description of the task type.\n environment_variables (list, optional): The environment\n variables required on the host to execute the task.\n required_arguments (list, optional): The argument names for\n the task type.\n required_arguments_default_values (dict, optional): Default\n values for the tasks required arguments.\n extra_data_to_post (dict, optional): Extra key-value pairs\n to add to the request data. This is useful for\n subclasses which require extra parameters.\n\nReturns:\n :class:`saltant.models.base_task_instance.BaseTaskType`:\n A task type model instance representing the task type\n just created.", "source": "codesearchnet_filtered"} +{"code": "def add_prefix(self, name, *args, **kwargs):\n if os.path.exists(self.join(name)):\n raise LagoPrefixAlreadyExistsError(name, self.path)\n self.prefixes[name] = self.prefix_class(self.join(name), *args, **kwargs)\n self.prefixes[name].initialize()\n if (self.current is None):\n self.set_current(name)\n return self.prefixes[name]", "docstring": "Adds a new prefix to the workdir.\n\nArgs:\n name(str): Name of the new prefix to add\n *args: args to pass along to the prefix constructor\n *kwargs: kwargs to pass along to the prefix constructor\n\nReturns:\n The newly created prefix\n\nRaises:\n LagoPrefixAlreadyExistsError: if prefix name already exists in the\n workdir", "source": "codesearchnet_filtered"} +{"code": "def find_divisors(n):\n if (not isinstance(n, int)):\n raise TypeError('Expecting a strictly positive integer')\n if (n <= 0):\n raise ValueError('Expecting a strictly positive integer')\n for i in range(1, (int((n ** 0.5)) + 1)):\n if ((n % i) == 0):\n divisors = {i, (n // i)}\n for divisor in divisors:\n (yield divisor)", "docstring": "Find all the positive divisors of the given integer n.\n\nArgs:\n n (int): strictly positive integer\n\nReturns:\n A generator of all the positive divisors of n\n\nRaises:\n TypeError: if n is not an integer\n ValueError: if n is negative", "source": "codesearchnet_filtered"} +{"code": "def _get_package_name(prefix=settings.TEMP_DIR, book_id=None):\n if (book_id is None):\n book_id = str(uuid.uuid4())\n return os.path.join(prefix, book_id)", "docstring": "Return package path. Use uuid to generate package's directory name.\n\nArgs:\n book_id (str, default None): UUID of the book.\n prefix (str, default settings.TEMP_DIR): Where the package will be\n stored. Default :attr:`settings.TEMP_DIR`.\n\nReturns:\n str: Path to the root directory.", "source": "codesearchnet_filtered"} +{"code": "def from_sasl_name(cls, name=None):\n if (rfc5801 is None):\n raise NotImplementedError('Your GSSAPI implementation does not have support for RFC 5801')\n if isinstance(name, six.text_type):\n name = name.encode(_utils._get_encoding())\n m = rfc5801.inquire_mech_for_saslname(name)\n return cls(m)", "docstring": "Create a Mechanism from its SASL name\n\nArgs:\n name (str): SASL name of the desired mechanism\n\nReturns:\n Mechanism: the desired mechanism\n\nRaises:\n GSSError\n\n :requires-ext:`rfc5801`", "source": "codesearchnet_filtered"} +{"code": "def getConParams(virtualhost):\n return pika.ConnectionParameters(host=settings.RABBITMQ_HOST, port=int(settings.RABBITMQ_PORT), virtual_host=virtualhost, credentials=pika.PlainCredentials(settings.RABBITMQ_USER_NAME, settings.RABBITMQ_USER_PASSWORD))", "docstring": "Connection object builder.\n\nArgs:\n virtualhost (str): selected virtualhost in rabbitmq\n\nReturns:\n pika.ConnectionParameters: object filled by `constants` from\n :class:`edeposit.amqp.settings`.", "source": "codesearchnet_filtered"} +{"code": "def generate_output_whois_nets(self, json_data=None, hr=True, show_name=False, colorize=True):\n if (json_data is None):\n json_data = {}\n output = generate_output(line='0', short=(HR_WHOIS['nets']['_short'] if hr else 'nets'), name=(HR_WHOIS['nets']['_name'] if (hr and show_name) else None), is_parent=True, colorize=colorize)\n count = 0\n for net in json_data['nets']:\n if (count > 0):\n output += self.generate_output_newline(line='1', colorize=colorize)\n count += 1\n output += generate_output(line='1', short=net['handle'], is_parent=True, colorize=colorize)\n for (key, val) in net.items():\n if (val and ('\\n' in val)):\n output += generate_output(line='2', short=(HR_WHOIS['nets'][key]['_short'] if hr else key), name=(HR_WHOIS['nets'][key]['_name'] if (hr and show_name) else None), is_parent=(False if ((val is None) or (len(val) == 0)) else True), value=('None' if ((val is None) or (len(val) == 0)) else None), colorize=colorize)\n for v in val.split('\\n'):\n output += generate_output(line='3', value=v, colorize=colorize)\n else:\n output += generate_output(line='2', short=(HR_WHOIS['nets'][key]['_short'] if hr else key), name=(HR_WHOIS['nets'][key]['_name'] if (hr and show_name) else None), value=val, colorize=colorize)\n return output", "docstring": "The function for generating CLI output Legacy Whois networks results.\n\nArgs:\n json_data (:obj:`dict`): The data to process. Defaults to None.\n hr (:obj:`bool`): Enable human readable key translations. Defaults\n to True.\n show_name (:obj:`bool`): Show human readable name (default is to\n only show short). Defaults to False.\n colorize (:obj:`bool`): Colorize the console output with ANSI\n colors. Defaults to True.\n\nReturns:\n str: The generated output.", "source": "codesearchnet_filtered"} +{"code": "def register(self, key_or_value=None):\n\n def decorator(value, key):\n self[key] = value\n return value\n if callable(key_or_value):\n return decorator(value=key_or_value, key=None)\n else:\n return (lambda value: decorator(value, key=key_or_value))", "docstring": "Decorator to register a function, or registration itself.\n\n This is primarily intended for use as a decorator, either with or without\n a key/parentheses.\n ```python\n @my_registry.register('key1')\n def value_fn(x, y, z):\n pass\n\n @my_registry.register()\n def another_fn(x, y):\n pass\n\n @my_registry.register\n def third_func():\n pass\n ```\n\n Note if key_or_value is provided as a non-callable, registration only\n occurs once the returned callback is called with a callable as its only\n argument.\n ```python\n callback = my_registry.register('different_key')\n 'different_key' in my_registry # False\n callback(lambda (x, y): x + y)\n 'different_key' in my_registry # True\n ```\n\nArgs:\n key_or_value (optional): key to access the registered value with, or the\n function itself. If `None` (default), `self.default_key` will be called\n on `value` once the returned callback is called with `value` as the only\n arg. If `key_or_value` is itself callable, it is assumed to be the value\n and the key is given by `self.default_key(key)`.\n\nReturns:\n decorated callback, or callback generated a decorated function.", "source": "codesearchnet_filtered"} +{"code": "def process_input_data(filename, imager, grid_data, grid_norm, grid_weights):\n ms = oskar.MeasurementSet.open(filename)\n block_start = 0\n num_rows = ms.num_rows\n num_baselines = ((ms.num_stations * (ms.num_stations - 1)) // 2)\n while (block_start < num_rows):\n block_size = (num_rows - block_start)\n if (block_size > num_baselines):\n block_size = num_baselines\n uvw = ms.read_column('UVW', block_start, block_size)\n vis_weights = ms.read_column('WEIGHT', block_start, block_size)\n if (ms.num_pols == 4):\n vis_weights = (0.5 * (vis_weights[(:, 0)] + vis_weights[(:, 3)]))\n for j in range(ms.num_channels):\n coords = ((uvw * (ms.freq_start_hz + (j * ms.freq_inc_hz))) / 299792458.0)\n vis_data = None\n if (not imager.coords_only):\n vis_data = ms.read_vis(block_start, j, 1, block_size)\n if (ms.num_pols == 4):\n vis_data = (0.5 * (vis_data[(0, :, 0)] + vis_data[(0, :, 3)]))\n grid_norm = imager.update_plane(coords[(:, 0)], coords[(:, 1)], coords[(:, 2)], vis_data, vis_weights, grid_data, grid_norm, grid_weights)\n block_start += block_size\n return grid_norm", "docstring": "Reads visibility data from a Measurement Set.\n\n The visibility grid or weights grid is updated accordingly.\n\n Visibility data are read from disk in blocks of size num_baselines.\n\nArgs:\n filename (str): Name of Measurement Set to open.\n imager (oskar.Imager): Handle to configured imager.\n grid_data (numpy.ndarray or None): Visibility grid to populate.\n grid_norm (float) Current grid normalisation.\n grid_weights (numpy.ndarray): Weights grid to populate or read.\n\nReturns:\n grid_norm (float): Updated grid normalisation.", "source": "codesearchnet_filtered"} +{"code": "def symbolic_heisenberg_eom(self, X=None, noises=None, expand_simplify=True):\n (L, H) = (self.L, self.H)\n if (X is None):\n X = OperatorSymbol('X', hs=(L.space | H.space))\n summands = [(I * ((H * X) - (X * H)))]\n for Lk in L.matrix.ravel():\n summands.append(((adjoint(Lk) * X) * Lk))\n summands.append(((- (((adjoint(Lk) * Lk) * X) + ((X * adjoint(Lk)) * Lk))) / 2))\n if (noises is not None):\n if (not isinstance(noises, Matrix)):\n noises = Matrix(noises)\n LambdaT = (noises.adjoint().transpose() * noises.transpose()).transpose()\n assert (noises.shape == L.shape)\n S = self.S\n summands.append(((adjoint(noises) * S.adjoint()) * ((X * L) - (L * X))).expand()[(0, 0)])\n summand = ((((L.adjoint() * X) - (X * L.adjoint())) * S) * noises).expand()[(0, 0)]\n summands.append(summand)\n if len((S.space & X.space)):\n comm = (((S.adjoint() * X) * S) - X)\n summands.append((comm * LambdaT).expand().trace())\n ret = OperatorPlus.create(*summands)\n if expand_simplify:\n ret = ret.expand().simplify_scalar()\n return ret", "docstring": "Compute the symbolic Heisenberg equations of motion of a system\n operator X. If no X is given, an OperatorSymbol is created in its\n place. If no noises are given, this correspnds to the\n ensemble-averaged Heisenberg equation of motion.\n\nArgs:\n X (Operator): A system operator\n noises (Operator): A vector of noise inputs\n\nReturns:\n Operator: The RHS of the Heisenberg equations of motion of X.", "source": "codesearchnet_filtered"} +{"code": "def scan_file(path):\n path = os.path.abspath(path)\n assert os.path.exists(path), (\"Unreachable file '%s'.\" % path)\n result = sh.clamscan(path, no_summary=True, infected=True, _ok_code=[0, 1])\n return _parse_result(result)", "docstring": "Scan `path` for viruses using ``clamscan`` program.\n\nArgs:\n path (str): Relative or absolute path of file/directory you need to\n scan.\n\nReturns:\n dict: ``{filename: (\"FOUND\", \"virus type\")}`` or blank dict.\n\nRaises:\n AssertionError: When the internal file doesn't exists.", "source": "codesearchnet_filtered"} +{"code": "def replace_nones(list_, repl=(- 1)):\n repl_list = [(repl if (item is None) else (replace_nones(item, repl) if isinstance(item, list) else item)) for item in list_]\n return repl_list", "docstring": "r\"\"\"\n Recursively removes Nones in all lists and sublists and replaces them with\n the repl variable\n\nArgs:\n list_ (list):\n repl (obj): replacement value\n\nReturns:\n list\n\n CommandLine:\n python -m utool.util_list --test-replace_nones\n\nExample:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_list import * # NOQA\n >>> # build test data\n >>> list_ = [None, 0, 1, 2]\n >>> repl = -1\n >>> # execute function\n >>> repl_list = replace_nones(list_, repl)\n >>> # verify results\n >>> result = str(repl_list)\n >>> print(result)\n [-1, 0, 1, 2]", "source": "codesearchnet_filtered"} +{"code": "def max_entropy_distribution(node_indices, number_of_nodes):\n distribution = np.ones(repertoire_shape(node_indices, number_of_nodes))\n return (distribution / distribution.size)", "docstring": "Return the maximum entropy distribution over a set of nodes.\n\n This is different from the network's uniform distribution because nodes\n outside ``node_indices`` are fixed and treated as if they have only 1\n state.\n\nArgs:\n node_indices (tuple[int]): The set of node indices over which to take\n the distribution.\n number_of_nodes (int): The total number of nodes in the network.\n\nReturns:\n np.ndarray: The maximum entropy distribution over the set of nodes.", "source": "codesearchnet_filtered"} +{"code": "def reflection(n1, n2):\n r = (abs(((n1 - n2) / (n1 + n2))) ** 2)\n return r", "docstring": "Calculate the power reflection at the interface\n of two refractive index materials.\n\nArgs:\n n1 (float): Refractive index of material 1.\n n2 (float): Refractive index of material 2.\n\nReturns:\n float: The percentage of reflected power.", "source": "codesearchnet_filtered"} +{"code": "def x_www_form_urlencoded(post_data):\n if isinstance(post_data, dict):\n return '&'.join([u'{}={}'.format(key, value) for (key, value) in post_data.items()])\n else:\n return post_data", "docstring": "convert origin dict to x-www-form-urlencoded\n\nArgs:\n post_data (dict):\n {\"a\": 1, \"b\":2}\n\nReturns:\n str:\n a=1&b=2", "source": "codesearchnet_filtered"} +{"code": "def namespace_for_prefix(self, prefix):\n try:\n ni = self.__lookup_prefix(prefix)\n except PrefixNotFoundError:\n return None\n else:\n return ni.uri", "docstring": "Get the namespace the given prefix maps to.\n\nArgs:\n prefix (str): The prefix\n\nReturns:\n str: The namespace, or None if the prefix isn't mapped to\n anything in this set.", "source": "codesearchnet_filtered"} +{"code": "def basistransform(self, new_basis, old_basis=None, orthonormalize=True):\n if (old_basis is None):\n old_basis = np.identity(3)\n is_rotation_matrix = np.isclose(np.linalg.det(new_basis), 1)\n if ((not is_rotation_matrix) and orthonormalize):\n new_basis = xyz_functions.orthonormalize_righthanded(new_basis)\n is_rotation_matrix = True\n if is_rotation_matrix:\n return dot(np.dot(new_basis.T, old_basis), self)\n else:\n return dot(np.dot(np.linalg.inv(new_basis), old_basis), self)", "docstring": "Transform the frame to a new basis.\n\n This function transforms the cartesian coordinates from an\n old basis to a new one. Please note that old_basis and\n new_basis are supposed to have full Rank and consist of\n three linear independent vectors. If rotate_only is True,\n it is asserted, that both bases are orthonormal and right\n handed. Besides all involved matrices are transposed\n instead of inverted.\n In some applications this may require the function\n :func:`xyz_functions.orthonormalize` as a previous step.\n\nArgs:\n old_basis (np.array):\n new_basis (np.array):\n rotate_only (bool):\n\nReturns:\n Cartesian: The transformed molecule.", "source": "codesearchnet_filtered"} +{"code": "def to_dict(self, remove_nones=False):\n content = {}\n for key in self._translation:\n if hasattr(self, key):\n content[key] = getattr(self, key)\n content['parent_id'] = self.parent_id\n content['item_id'] = self.item_id\n content['restricted'] = self.restricted\n content['title'] = self.title\n if (self.resources != []):\n content['resources'] = [resource.to_dict(remove_nones=remove_nones) for resource in self.resources]\n content['desc'] = self.desc\n return content", "docstring": "Return the dict representation of the instance.\n\nArgs:\n remove_nones (bool, optional): Optionally remove dictionary\n elements when their value is `None`.\n\nReturns:\n dict: a dict representation of the `DidlObject`.", "source": "codesearchnet_filtered"} +{"code": "def df_first_row_to_dict(df):\n if (df is not None):\n return [dict(r) for (i, r) in df.head(1).iterrows()][0]", "docstring": "First DataFrame row to list of dict\n\nArgs:\n df (pandas.DataFrame): A DataFrame with at least one row\n\nReturns:\n A list of dict that looks like:\n\n [{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}]\n\n from a DataFrame that looks like:\n\n C1 C2 C3\n 1 x y z\n\n Else if `df` is `None`, returns `None`", "source": "codesearchnet_filtered"} +{"code": "def get_url_for_get(url, parameters=None):\n spliturl = urlsplit(url)\n getparams = OrderedDict(parse_qsl(spliturl.query))\n if (parameters is not None):\n getparams.update(parameters)\n spliturl = spliturl._replace(query=urlencode(getparams))\n return urlunsplit(spliturl)", "docstring": "Get full url for GET request including parameters\n\nArgs:\n url (str): URL to download\n parameters (Optional[Dict]): Parameters to pass. Defaults to None.\n\nReturns:\n str: Full url", "source": "codesearchnet_filtered"} +{"code": "def variant(self, document_id, gene_panels=None, case_id=None):\n query = {}\n if case_id:\n query['case_id'] = case_id\n query['variant_id'] = document_id\n else:\n query['_id'] = document_id\n variant_obj = self.variant_collection.find_one(query)\n if variant_obj:\n variant_obj = self.add_gene_info(variant_obj, gene_panels)\n if (variant_obj['chromosome'] in ['X', 'Y']):\n variant_obj['is_par'] = is_par(variant_obj['chromosome'], variant_obj['position'])\n return variant_obj", "docstring": "Returns the specified variant.\n\nArgs:\n document_id : A md5 key that represents the variant or \"variant_id\"\n gene_panels(List[GenePanel])\n case_id (str): case id (will search with \"variant_id\")\n\nReturns:\n variant_object(Variant): A odm variant object", "source": "codesearchnet_filtered"} +{"code": "def extractMonthTariff(self, month):\n ret = namedtuple('ret', ['Month', Field.kWh_Tariff_1, Field.kWh_Tariff_2, Field.kWh_Tariff_3, Field.kWh_Tariff_4, Field.kWh_Tot, Field.Rev_kWh_Tariff_1, Field.Rev_kWh_Tariff_2, Field.Rev_kWh_Tariff_3, Field.Rev_kWh_Tariff_4, Field.Rev_kWh_Tot])\n month += 1\n ret.Month = str(month)\n if ((month < 1) or (month > Extents.Months)):\n ret.kWh_Tariff_1 = ret.kWh_Tariff_2 = ret.kWh_Tariff_3 = ret.kWh_Tariff_4 = str(0)\n ret.Rev_kWh_Tariff_1 = ret.Rev_kWh_Tariff_2 = ret.Rev_kWh_Tariff_3 = ret.Rev_kWh_Tariff_4 = str(0)\n ret.kWh_Tot = ret.Rev_kWh_Tot = str(0)\n ekm_log(('Out of range(Extents.Months) month = ' + str(month)))\n return ret\n base_str = (('Month_' + str(month)) + '_')\n ret.kWh_Tariff_1 = self.m_mons[(base_str + 'Tariff_1')][MeterData.StringValue]\n ret.kWh_Tariff_2 = self.m_mons[(base_str + 'Tariff_2')][MeterData.StringValue]\n ret.kWh_Tariff_3 = self.m_mons[(base_str + 'Tariff_3')][MeterData.StringValue]\n ret.kWh_Tariff_4 = self.m_mons[(base_str + 'Tariff_4')][MeterData.StringValue]\n ret.kWh_Tot = self.m_mons[(base_str + 'Tot')][MeterData.StringValue]\n ret.Rev_kWh_Tariff_1 = self.m_rev_mons[(base_str + 'Tariff_1')][MeterData.StringValue]\n ret.Rev_kWh_Tariff_2 = self.m_rev_mons[(base_str + 'Tariff_2')][MeterData.StringValue]\n ret.Rev_kWh_Tariff_3 = self.m_rev_mons[(base_str + 'Tariff_3')][MeterData.StringValue]\n ret.Rev_kWh_Tariff_4 = self.m_rev_mons[(base_str + 'Tariff_4')][MeterData.StringValue]\n ret.Rev_kWh_Tot = self.m_rev_mons[(base_str + 'Tot')][MeterData.StringValue]\n return ret", "docstring": "Extract the tariff for a single month from the meter object buffer.\n\nArgs:\n month (int): A :class:`~ekmmeters.Months` value or range(Extents.Months).\n\nReturns:\n tuple: The eight tariff period totals for month. The return tuple breaks out as follows:\n\n ================= ======================================\n kWh_Tariff_1 kWh for tariff period 1 over month.\n kWh_Tariff_2 kWh for tariff period 2 over month\n kWh_Tariff_3 kWh for tariff period 3 over month\n kWh_Tariff_4 kWh for tariff period 4 over month\n kWh_Tot Total kWh over requested month\n Rev_kWh_Tariff_1 Rev kWh for tariff period 1 over month\n Rev_kWh_Tariff_3 Rev kWh for tariff period 2 over month\n Rev_kWh_Tariff_3 Rev kWh for tariff period 3 over month\n Rev_kWh_Tariff_4 Rev kWh for tariff period 4 over month\n Rev_kWh_Tot Total Rev kWh over requested month\n ================= ======================================", "source": "codesearchnet_filtered"} +{"code": "def add_update_resources(self, resources, ignore_datasetid=False):\n if (not isinstance(resources, list)):\n raise HDXError('Resources should be a list!')\n for resource in resources:\n self.add_update_resource(resource, ignore_datasetid)", "docstring": "Add new or update existing resources with new metadata to the dataset\n\nArgs:\n resources (List[Union[hdx.data.resource.Resource,Dict,str]]): A list of either resource ids or resources metadata from either Resource objects or dictionaries\n ignore_datasetid (bool): Whether to ignore dataset id in the resource. Defaults to False.\n\nReturns:\n None", "source": "codesearchnet_filtered"} +{"code": "def parse_cscore(infile):\n cscore_dict = {}\n with open(infile, 'r') as f:\n for ll in f.readlines():\n if ll.lower().startswith('model1'):\n l = ll.split()\n cscore = l[1]\n tmscore_full = l[2].split('+-')\n tmscore = tmscore_full[0]\n tmscore_err = tmscore_full[1]\n rmsd_full = l[3].split('+-')\n rmsd = rmsd_full[0]\n rmsd_err = rmsd_full[1]\n cscore_dict['c_score'] = float(cscore)\n cscore_dict['tm_score'] = float(tmscore)\n cscore_dict['tm_score_err'] = float(tmscore_err)\n cscore_dict['rmsd'] = float(rmsd)\n cscore_dict['rmsd_err'] = float(rmsd_err)\n return cscore_dict", "docstring": "Parse the cscore file to return a dictionary of scores.\n\nArgs:\n infile (str): Path to cscore\n\nReturns:\n dict: Dictionary of scores", "source": "codesearchnet_filtered"} +{"code": "def _ParseDateTimeValue(self, parser_mediator, date_time_value):\n if (date_time_value[14] != 'Z'):\n parser_mediator.ProduceExtractionWarning('invalid date and time value: {0!s}'.format(date_time_value))\n return None\n try:\n year = int(date_time_value[0:4], 10)\n month = int(date_time_value[4:6], 10)\n day_of_month = int(date_time_value[6:8], 10)\n hours = int(date_time_value[8:10], 10)\n minutes = int(date_time_value[10:12], 10)\n seconds = int(date_time_value[12:14], 10)\n except (TypeError, ValueError):\n parser_mediator.ProduceExtractionWarning('invalid date and time value: {0!s}'.format(date_time_value))\n return None\n time_elements_tuple = (year, month, day_of_month, hours, minutes, seconds)\n try:\n return dfdatetime_time_elements.TimeElements(time_elements_tuple=time_elements_tuple)\n except ValueError:\n parser_mediator.ProduceExtractionWarning('invalid date and time value: {0!s}'.format(date_time_value))\n return None", "docstring": "Parses a date time value.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n date_time_value (str): date time value\n (CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) in the format: \"YYYYMMDDhhmmssZ\".\n\nReturns:\n dfdatetime.TimeElements: date and time extracted from the value or None\n if the value does not represent a valid string.", "source": "codesearchnet_filtered"} +{"code": "def lsdirs(root='.', **kwargs):\n paths = ls(root=root, **kwargs)\n if isfile(root):\n return []\n return [_path for _path in paths if isdir(path(root, _path))]", "docstring": "Return only subdirectories from a directory listing.\n\nArgs:\n root (str): Path to directory. Can be relative or absolute.\n **kwargs: Any additional arguments to be passed to ls().\n\nReturns:\n list of str: A list of directory paths.\n\nRaises:\n OSError: If root directory does not exist.", "source": "codesearchnet_filtered"} +{"code": "def create(self, master_course_id, coach_email, max_students_allowed, title, modules=None):\n payload = {'master_course_id': master_course_id, 'coach_email': coach_email, 'max_students_allowed': max_students_allowed, 'display_name': title}\n if (modules is not None):\n payload['course_modules'] = modules\n resp = self.requester.post(parse.urljoin(self.base_url, '/api/ccx/v0/ccx/'), json=payload)\n try:\n resp.raise_for_status()\n except:\n log.error(resp.json())\n raise\n return resp.json()['ccx_course_id']", "docstring": "Creates a CCX\n\nArgs:\n master_course_id (str): edx course id of the master course\n coach_email (str): email of the user to make a coach. This user must exist on edx.\n max_students_allowed (int): Maximum number of students to allow in this ccx.\n title (str): Title of the CCX to be created\n modules (optional list): A list of locator_ids (str) for the modules to enable.\n\nReturns:\n ccx_id (str): The ID of the ccx.", "source": "codesearchnet_filtered"} +{"code": "def reviews(self, packageName, filterByDevice=False, sort=2, nb_results=None, offset=None):\n path = (REVIEWS_URL + '?doc={}&sort={}'.format(requests.utils.quote(packageName), sort))\n if (nb_results is not None):\n path += '&n={}'.format(nb_results)\n if (offset is not None):\n path += '&o={}'.format(offset)\n if filterByDevice:\n path += '&dfil=1'\n data = self.executeRequestApi2(path)\n output = []\n for review in data.payload.reviewResponse.getResponse.review:\n output.append(utils.parseProtobufObj(review))\n return output", "docstring": "Browse reviews for an application\n\nArgs:\n packageName (str): app unique ID.\n filterByDevice (bool): filter results for current device\n sort (int): sorting criteria (values are unknown)\n nb_results (int): max number of reviews to return\n offset (int): return reviews starting from an offset value\n\nReturns:\n dict object containing all the protobuf data returned from\n the api", "source": "codesearchnet_filtered"} +{"code": "def render(self, filename=None, directory=None, view=False, cleanup=False, format=None, renderer=None, formatter=None):\n filepath = self.save(filename, directory)\n if (format is None):\n format = self._format\n rendered = backend.render(self._engine, format, filepath, renderer, formatter)\n if cleanup:\n os.remove(filepath)\n if view:\n self._view(rendered, self._format)\n return rendered", "docstring": "Save the source to file and render with the Graphviz engine.\n\nArgs:\n filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)\n directory: (Sub)directory for source saving and rendering.\n view (bool): Open the rendered result with the default application.\n cleanup (bool): Delete the source file after rendering.\n format: The output format used for rendering (``'pdf'``, ``'png'``, etc.).\n renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).\n formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).\n\nReturns:\n The (possibly relative) path of the rendered file.\n\nRaises:\n ValueError: If ``format``, ``renderer``, or ``formatter`` are not known.\n graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.\n graphviz.ExecutableNotFound: If the Graphviz executable is not found.\n subprocess.CalledProcessError: If the exit status is non-zero.\n RuntimeError: If viewer opening is requested but not supported.", "source": "codesearchnet_filtered"} +{"code": "def get_tag(self, key, *, case_sensitive=True):\n key = (key if case_sensitive else key.lower())\n for tag in self.resource.tags:\n if (not case_sensitive):\n if (tag.key.lower() == key):\n return tag\n elif (key == tag.key):\n return tag\n return None", "docstring": "Return a tag by key, if found\n\nArgs:\n key (str): Name/key of the tag to locate\n case_sensitive (bool): Should tag keys be treated case-sensitive (default: true)\n\nReturns:\n `Tag`,`None`", "source": "codesearchnet_filtered"} +{"code": "def find_noncopyable_vars(class_type, already_visited_cls_vars=None):\n assert isinstance(class_type, class_declaration.class_t)\n logger = utils.loggers.cxx_parser\n mvars = class_type.variables((lambda v: (not v.type_qualifiers.has_static)), recursive=False, allow_empty=True)\n noncopyable_vars = []\n if (already_visited_cls_vars is None):\n already_visited_cls_vars = []\n message = ('__contains_noncopyable_mem_var - %s - TRUE - ' + 'contains const member variable')\n for mvar in mvars:\n var_type = type_traits.remove_reference(mvar.decl_type)\n if type_traits.is_const(var_type):\n no_const = type_traits.remove_const(var_type)\n if (type_traits.is_fundamental(no_const) or is_enum(no_const)):\n logger.debug((message + '- fundamental or enum'), var_type.decl_string)\n noncopyable_vars.append(mvar)\n if is_class(no_const):\n logger.debug((message + ' - class'), var_type.decl_string)\n noncopyable_vars.append(mvar)\n if type_traits.is_array(no_const):\n logger.debug((message + ' - array'), var_type.decl_string)\n noncopyable_vars.append(mvar)\n if type_traits.is_pointer(var_type):\n continue\n if class_traits.is_my_case(var_type):\n cls = class_traits.get_declaration(var_type)\n if (cls in already_visited_cls_vars):\n continue\n already_visited_cls_vars.append(cls)\n if is_noncopyable(cls, already_visited_cls_vars):\n logger.debug((message + ' - class that is not copyable'), var_type.decl_string)\n noncopyable_vars.append(mvar)\n logger.debug((\"__contains_noncopyable_mem_var - %s - FALSE - doesn't \" + 'contain noncopyable members'), class_type.decl_string)\n return noncopyable_vars", "docstring": "Returns list of all `noncopyable` variables.\n\n If an already_visited_cls_vars list is provided as argument, the returned\n list will not contain these variables. This list will be extended with\n whatever variables pointing to classes have been found.\n\nArgs:\n class_type (declarations.class_t): the class to be searched.\n already_visited_cls_vars (list): optional list of vars that should not\n be checked a second time, to prevent infinite recursions.\n\nReturns:\n list: list of all `noncopyable` variables.", "source": "codesearchnet_filtered"} +{"code": "def get_symbol(self, symbol):\n self._ensure_symbols_loaded()\n if (type(symbol) is int):\n return self._symbols_by_index[symbol]\n else:\n return self._symbols_by_name[symbol]", "docstring": "Get a specific symbol by index or name.\n\nArgs:\n symbol(int or str): The index or name of the symbol to return.\n\nReturns:\n ELF.Symbol: The symbol.\n\nRaises:\n KeyError: The requested symbol does not exist.", "source": "codesearchnet_filtered"} +{"code": "def from_lasio_curve(cls, curve, depth=None, basis=None, start=None, stop=None, step=0.1524, run=(- 1), null=(- 999.25), service_company=None, date=None):\n data = curve.data\n unit = curve.unit\n if (depth is not None):\n d = np.diff(depth)\n if (not np.allclose((d - np.mean(d)), np.zeros_like(d))):\n m = 'Irregular sampling in depth is not supported. '\n m += 'Interpolating to regular basis.'\n warnings.warn(m)\n step = np.nanmedian(d)\n (start, stop) = (depth[0], (depth[(- 1)] + 1e-05))\n basis = np.arange(start, stop, step)\n data = np.interp(basis, depth, data)\n else:\n step = np.nanmedian(d)\n start = depth[0]\n if (start is None):\n if (basis is not None):\n start = basis[0]\n step = (basis[1] - basis[0])\n else:\n raise CurveError('You must provide a basis or a start depth.')\n if (step == 0):\n if (stop is None):\n raise CurveError('You must provide a step or a stop depth.')\n else:\n step = ((stop - start) / (curve.data.shape[0] - 1))\n params = {}\n params['mnemonic'] = curve.mnemonic\n params['description'] = curve.descr\n params['start'] = start\n params['step'] = step\n params['units'] = unit\n params['run'] = run\n params['null'] = null\n params['service_company'] = service_company\n params['date'] = date\n params['code'] = curve.API_code\n return cls(data, params=params)", "docstring": "Makes a curve object from a lasio curve object and either a depth\n basis or start and step information.\n\nArgs:\n curve (ndarray)\n depth (ndarray)\n basis (ndarray)\n start (float)\n stop (float)\n step (float): default: 0.1524\n run (int): default: -1\n null (float): default: -999.25\n service_company (str): Optional.\n data (str): Optional.\n\nReturns:\n Curve. An instance of the class.", "source": "codesearchnet_filtered"} +{"code": "def parse_args(self, arglist=None):\n args = self._parser.parse_args(args=arglist)\n sub_cmd = args.loam_sub_name\n if (sub_cmd is None):\n for (opt, sct) in self._opt_bare.items():\n self._conf[sct][opt] = getattr(args, opt, None)\n else:\n for (opt, sct) in self._opt_cmds[sub_cmd].items():\n self._conf[sct][opt] = getattr(args, opt, None)\n return args", "docstring": "Parse arguments and update options accordingly.\n\nArgs:\n arglist (list of str): list of arguments to parse. If set to None,\n ``sys.argv[1:]`` is used.\n\nReturns:\n :class:`Namespace`: the argument namespace returned by the\n :class:`argparse.ArgumentParser`.", "source": "codesearchnet_filtered"} +{"code": "def has_auth_params(self, scheme):\n for (k, v) in iteritems(self.schemes[scheme][u'params']):\n if (not v):\n return False\n return True", "docstring": "Check whether all information required for a given auth scheme have\n been supplied.\n\nArgs:\n scheme (str): Name of the authentication scheme to check. One of\n Gem-Identify, Gem-Device, Gem-Application\n\nReturns:\n True if all required parameters for the specified scheme are present\n or False otherwise.", "source": "codesearchnet_filtered"} +{"code": "def url_builder(self, endpoint, *, root=None, params=None, url_params=None):\n if (root is None):\n root = self.ROOT\n return ''.join([root, endpoint, (('?' + urlencode(url_params)) if url_params else '')]).format(**(params or {}))", "docstring": "Create a URL for the specified endpoint.\n\nArgs:\n endpoint (:py:class:`str`): The API endpoint to access.\n root: (:py:class:`str`, optional): The root URL for the\n service API.\n params: (:py:class:`dict`, optional): The values for format\n into the created URL (defaults to ``None``).\n url_params: (:py:class:`dict`, optional): Parameters to add\n to the end of the URL (defaults to ``None``).\n\nReturns:\n :py:class:`str`: The resulting URL.", "source": "codesearchnet_filtered"} +{"code": "def default(self, interface, vrid):\n vrrp_str = ('default vrrp %d' % vrid)\n return self.configure_interface(interface, vrrp_str)", "docstring": "Defaults a vrrp instance from an interface\n\nNote:\n This method will attempt to default the vrrp on the node's\n operational config. Default results in the deletion of the\n specified vrrp . If the vrrp does not exist on the\n interface then this method will not perform any changes\n but still return True\n\nArgs:\n interface (string): The interface to configure.\n vrid (integer): The vrid number for the vrrp to be defaulted.\n\nReturns:\n True if the vrrp could be defaulted otherwise False (see Node)", "source": "codesearchnet_filtered"} +{"code": "def create_identical_dataset_and_algorithm_tuner(parent, additional_parents=None, sagemaker_session=None):\n parent_tuner = HyperparameterTuner.attach(tuning_job_name=parent, sagemaker_session=sagemaker_session)\n return parent_tuner.identical_dataset_and_algorithm_tuner(additional_parents=additional_parents)", "docstring": "Creates a new tuner by copying the request fields from the provided parent to the new instance of\n ``HyperparameterTuner`` followed by addition of warm start configuration with the type as\n \"IdenticalDataAndAlgorithm\" and ``parents`` as the union of provided list of ``additional_parents`` and the\n ``parent``.\n\nArgs:\n parent (str): Primary parent tuning job's name from which the Tuner and Estimator configuration has to be copied\n additional_parents (set{str}): Set of additional parent tuning job's names along with the primary parent tuning\n job name to be used in warm starting the transfer learning tuner.\n sagemaker_session (sagemaker.session.Session): Session object which manages interactions with\n Amazon SageMaker APIs and any other AWS services needed. If not specified, one is created\n using the default AWS configuration chain.\n\nReturns:\n sagemaker.tuner.HyperparameterTuner: a new ``HyperparameterTuner`` object for the warm-started\n hyperparameter tuning job", "source": "codesearchnet_filtered"} +{"code": "def QoI_Dist(poly, dist, sample=10000, **kws):\n shape = poly.shape\n poly = polynomials.flatten(poly)\n dim = len(dist)\n samples = dist.sample(sample, **kws)\n qoi_dists = []\n for i in range(0, len(poly)):\n if (dim == 1):\n dataset = poly[i](samples)\n else:\n dataset = poly[i](*samples)\n lo = dataset.min()\n up = dataset.max()\n qoi_dist = distributions.SampleDist(dataset, lo, up)\n qoi_dists.append(qoi_dist)\n qoi_dists = numpy.array(qoi_dists, distributions.Dist)\n qoi_dists = qoi_dists.reshape(shape)\n if (not shape):\n qoi_dists = qoi_dists.item()\n return qoi_dists", "docstring": "Constructs distributions for the quantity of interests.\n\n The function constructs a kernel density estimator (KDE) for each\n polynomial (poly) by sampling it. With the KDEs, distributions (Dists) are\n constructed. The Dists can be used for e.g. plotting probability density\n functions (PDF), or to make a second uncertainty quantification simulation\n with that newly generated Dists.\n\nArgs:\n poly (Poly):\n Polynomial of interest.\n dist (Dist):\n Defines the space where the samples for the KDE is taken from the\n poly.\n sample (int):\n Number of samples used in estimation to construct the KDE.\n\nReturns:\n (numpy.ndarray):\n The constructed quantity of interest (QoI) distributions, where\n ``qoi_dists.shape==poly.shape``.\n\nExample:\n >>> dist = chaospy.Normal(0, 1)\n >>> x = chaospy.variable(1)\n >>> poly = chaospy.Poly([x])\n >>> qoi_dist = chaospy.QoI_Dist(poly, dist)\n >>> values = qoi_dist[0].pdf([-0.75, 0., 0.75])\n >>> print(numpy.around(values, 8))\n [0.29143037 0.39931708 0.29536329]", "source": "codesearchnet_filtered"} +{"code": "def matchmaker_request(url, token, method, content_type=None, accept=None, data=None):\n headers = Headers()\n headers = {'X-Auth-Token': token}\n if content_type:\n headers['Content-Type'] = content_type\n if accept:\n headers['Accept'] = accept\n req_data = (data or {'timestamp': datetime.datetime.now().timestamp()})\n json_response = None\n try:\n LOG.info('Sending {} request to MME url {}. Data sent: {}'.format(method, url, req_data))\n resp = requests.request(method=method, url=url, headers=headers, data=json.dumps(req_data))\n json_response = resp.json()\n LOG.info('MME server response was:{}'.format(json_response))\n if isinstance(json_response, str):\n json_response = {'message': json_response}\n elif isinstance(json_response, list):\n return json_response\n json_response['status_code'] = resp.status_code\n except Exception as err:\n LOG.info('An error occurred while sending HTTP request to server ({})'.format(err))\n json_response = {'message': str(err)}\n return json_response", "docstring": "Send a request to MatchMaker and return its response\n\nArgs:\n url(str): url to send request to\n token(str): MME server authorization token\n method(str): 'GET', 'POST' or 'DELETE'\n content_type(str): MME request Content-Type\n accept(str): accepted response\n data(dict): eventual data to send in request\n\nReturns:\n json_response(dict): server response", "source": "codesearchnet_filtered"} +{"code": "def hardware_version(self):\n version = self._dll.JLINKARM_GetHardwareVersion()\n major = ((version / 10000) % 100)\n minor = ((version / 100) % 100)\n return ('%d.%02d' % (major, minor))", "docstring": "Returns the hardware version of the connected J-Link as a\n major.minor string.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n Hardware version string.", "source": "codesearchnet_filtered"} +{"code": "def read_nose(in_file):\n suites = {}\n doc_xml = minidom.parse(in_file)\n suite_xml = doc_xml.getElementsByTagName('testsuite')[0]\n for case_xml in suite_xml.getElementsByTagName('testcase'):\n classname = case_xml.getAttribute('classname')\n if (classname not in suites):\n suites[classname] = []\n case = {'name': case_xml.getAttribute('name'), 'time': float(case_xml.getAttribute('time'))}\n skipped_xml = case_xml.getElementsByTagName('skipped')\n if skipped_xml:\n if skipped_xml[0].hasAttribute('type'):\n type = skipped_xml[0].getAttribute('type')\n else:\n type = ''\n case['skipped'] = {'type': type, 'message': skipped_xml[0].getAttribute('message'), 'text': ''.join([child.nodeValue for child in skipped_xml[0].childNodes])}\n failure_xml = case_xml.getElementsByTagName('failure')\n if failure_xml:\n if failure_xml[0].hasAttribute('type'):\n type = failure_xml[0].getAttribute('type')\n else:\n type = ''\n case['failure'] = {'type': type, 'message': failure_xml[0].getAttribute('message'), 'text': ''.join([child.nodeValue for child in failure_xml[0].childNodes])}\n error_xml = case_xml.getElementsByTagName('error')\n if error_xml:\n if error_xml[0].hasAttribute('type'):\n type = error_xml[0].getAttribute('type')\n else:\n type = ''\n case['error'] = {'type': type, 'message': error_xml[0].getAttribute('message'), 'text': ''.join([child.nodeValue for child in error_xml[0].childNodes])}\n suites[classname].append(case)\n return suites", "docstring": "Parse nose-style test reports into a `dict`\n\nArgs:\n in_file (:obj:`str`): path to nose-style test report\n\nReturns:\n :obj:`dict`: dictionary of test suites", "source": "codesearchnet_filtered"} +{"code": "def from_bytes(b):\n if (len(b) != 64):\n raise ValueError('from_bytes: Signature length != 64.')\n r = int.from_bytes(b[0:32], 'big')\n s = int.from_bytes(b[32:64], 'big')\n return Signature(r, s)", "docstring": "Extracts the r and s components from a byte string.\n\nArgs:\n b (bytes): A 64-byte long string. The first 32 bytes are\n extracted as the r component and the second 32 bytes\n are extracted as the s component.\n\nReturns:\n Signature: A Signature object.\n\nRaises:\n ValueError: If signature is incorrect length", "source": "codesearchnet_filtered"} +{"code": "def create_releasenotes(project_dir=os.curdir, bugtracker_url=''):\n pkg_info_file = os.path.join(project_dir, 'PKG-INFO')\n if os.path.exists(pkg_info_file):\n return\n with open('RELEASE_NOTES', 'wb') as releasenotes_fd:\n releasenotes_fd.write((get_releasenotes(project_dir=project_dir, bugtracker_url=bugtracker_url).encode('utf-8') + b'\\n'))", "docstring": "Creates the release notes file, if not in a package.\n\nArgs:\n project_dir(str): Path to the git repo of the project.\n bugtracker_url(str): Url to the bug tracker for the issues.\n\nReturns:\n None\n\nRaises:\n RuntimeError: If the release notes could not be retrieved", "source": "codesearchnet_filtered"} +{"code": "def record_factory(app, fields=None):\n record = Record(app, {'$type': Record._type, 'isNew': True, 'applicationId': app.id, 'comments': {'$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.List`1[[Core.Models.Record.Comments, Core]], mscorlib]], mscorlib'}, 'values': {'$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib'}})\n fields = (fields or {})\n for (name, value) in six.iteritems(fields):\n record[name] = value\n copy_raw = copy.copy(record._raw)\n values_dict = {}\n for (key, value) in six.iteritems(copy_raw['values']):\n if (value is not None):\n values_dict[key] = value\n record._raw['values'] = values_dict\n return record", "docstring": "Return a temporary Record instance to be used for field validation and value parsing\n\nArgs:\n app (App): Target App to create a transient Record instance for\n fields (dict): Optional dict of fields and values to set on new Record instance before returning\n\nReturns:\n Record: Unsaved Record instance to be used for validation, creation, etc.", "source": "codesearchnet_filtered"} +{"code": "def compile_keywords(keywords):\n mdt = []\n cz_keywords = []\n en_keywords = []\n for keyword in keywords:\n keyword = keyword_to_info(keyword.encode('utf-8'))\n if (not keyword):\n continue\n cz_keywords.append({'uid': keyword['uid'], 'zahlavi': keyword['zahlavi'], 'zdroj': 'czenas'})\n if keyword.get('mdt'):\n mdt.append({'mdt': keyword['mdt'], 'mrf': keyword['mrf']})\n angl_ekvivalent = keyword.get('angl_ekvivalent')\n if angl_ekvivalent:\n en_keywords.append({'zahlavi': angl_ekvivalent, 'zdroj': (keyword.get('zdroj_angl_ekvivalentu') or 'eczenas')})\n return (mdt, cz_keywords, en_keywords)", "docstring": "Translate `keywords` to full keyword records as they are used in Aleph.\n\n Returns tuple with three lists, each of which is later used in different\n part of the MRC/MARC record.\n\nArgs:\n keywords (list): List of keyword strings.\n\nReturns:\n tuple: (mdt_list, cz_keyword_list, en_keyword_list)", "source": "codesearchnet_filtered"} +{"code": "def are_you_sure(msg=''):\n print(msg)\n from utool import util_arg\n from utool import util_str\n override = util_arg.get_argflag(('--yes', '--y', '-y'))\n if override:\n print('accepting based on command line flag')\n return True\n valid_ans = ['yes', 'y']\n valid_prompt = util_str.conj_phrase(valid_ans, 'or')\n ans = input(('Are you sure?\\n Enter %s to accept\\n' % valid_prompt))\n return (ans.lower() in valid_ans)", "docstring": "r\"\"\"\n Prompts user to accept or checks command line for -y\n\nArgs:\n msg (str):\n\nReturns:\n bool: accept or not", "source": "codesearchnet_filtered"} +{"code": "def authenticate_device(self, api_token, device_token, email=None, user_url=None, override=False, fetch=True):\n if (self.context.has_auth_params('Gem-Device') and (not override)):\n raise OverrideError('Gem-Device')\n if ((not api_token) or (not device_token) or ((not email) and (not user_url)) or (not self.context.authorize('Gem-Device', api_token=api_token, user_email=email, user_url=user_url, device_token=device_token))):\n raise AuthUsageError(self.context, 'Gem-Device')\n if fetch:\n user = (self.user(email) if email else self.user())\n return user.refresh()\n else:\n return True", "docstring": "Set credentials for Device authentication.\n\nArgs:\n api_token (str): Token issued to your Application through the Gem\n Developer Console.\n device_token (str): Physical device identifier. You will receive this\n from a user.devices.create call or from users.create.\n email (str, optional): User's email address, required if user_url is\n not provided.\n user_url (str, optional): User's Gem url.\n override (boolean, optional): Replace existing Application credentials.\n fetch (boolean, optional): Return the authenticated User.\n\nReturns:\n An User object if `fetch` is True.", "source": "codesearchnet_filtered"} +{"code": "def _get_snpeff_transcript(self, transcript_info):\n transcript = Transcript(hgnc_symbol=transcript_info.get('Gene_Name'), transcript_id=transcript_info.get('Feature'), ensembl_id=transcript_info.get('Gene_ID'), biotype=transcript_info.get('Transcript_BioType'), consequence=transcript_info.get('Annotation'), exon=transcript_info.get('Rank'), HGVSc=transcript_info.get('HGVS.c'), HGVSp=transcript_info.get('HGVS.p'))\n return transcript", "docstring": "Create a transcript based on the snpeff annotation\n\nArgs:\n transcript_info (dict): A dict with snpeff info\n\nReturns:\n transcript (puzzle.models.Transcript): A Transcripts", "source": "codesearchnet_filtered"} +{"code": "def argsort2(indexable, key=None, reverse=False):\n if isinstance(indexable, dict):\n vk_iter = ((v, k) for (k, v) in indexable.items())\n else:\n vk_iter = ((v, k) for (k, v) in enumerate(indexable))\n if (key is None):\n indices = [k for (v, k) in sorted(vk_iter, reverse=reverse)]\n else:\n indices = [k for (v, k) in sorted(vk_iter, key=(lambda vk: key(vk[0])), reverse=reverse)]\n return indices", "docstring": "Returns the indices that would sort a indexable object.\n\n This is similar to np.argsort, but it is written in pure python and works\n on both lists and dictionaries.\n\nArgs:\n indexable (list or dict): indexable to sort by\n\nReturns:\n list: indices: list of indices such that sorts the indexable\n\nExample:\n >>> # DISABLE_DOCTEST\n >>> import utool as ut\n >>> # argsort works on dicts\n >>> dict_ = indexable = {'a': 3, 'b': 2, 'c': 100}\n >>> indices = ut.argsort2(indexable)\n >>> assert list(ut.take(dict_, indices)) == sorted(dict_.values())\n >>> # argsort works on lists\n >>> indexable = [100, 2, 432, 10]\n >>> indices = ut.argsort2(indexable)\n >>> assert list(ut.take(indexable, indices)) == sorted(indexable)\n >>> # argsort works on iterators\n >>> indexable = reversed(range(100))\n >>> indices = ut.argsort2(indexable)\n >>> assert indices[0] == 99", "source": "codesearchnet_filtered"} +{"code": "def change_extension(self, filepath, new_extension):\n (filename, ext) = os.path.splitext(filepath)\n return '.'.join([filename, new_extension])", "docstring": "Change final filename extension.\n\nArgs:\n filepath (str): A file path (relative or absolute).\n new_extension (str): New extension name (without leading dot) to\n apply.\n\nReturns:\n str: Filepath with new extension.", "source": "codesearchnet_filtered"} +{"code": "def pauli_from_char(ch, n=0):\n ch = ch.upper()\n if (ch == 'I'):\n return I\n if (ch == 'X'):\n return X(n)\n if (ch == 'Y'):\n return Y(n)\n if (ch == 'Z'):\n return Z(n)\n raise ValueError('ch shall be X, Y, Z or I')", "docstring": "Make Pauli matrix from an character.\n\nArgs:\n ch (str): \"X\" or \"Y\" or \"Z\" or \"I\".\n n (int, optional): Make Pauli matrix as n-th qubits.\n\nReturns:\n If ch is \"X\" => X, \"Y\" => Y, \"Z\" => Z, \"I\" => I\n\nRaises:\n ValueError: When ch is not \"X\", \"Y\", \"Z\" nor \"I\".", "source": "codesearchnet_filtered"} +{"code": "def read_samples(self, sr=None, offset=0, duration=None):\n read_duration = self.duration\n if ((offset > 0) and (read_duration is not None)):\n read_duration -= offset\n if (duration is not None):\n if (read_duration is None):\n read_duration = duration\n else:\n read_duration = min(duration, read_duration)\n return self.track.read_samples(sr=sr, offset=(self.start + offset), duration=read_duration)", "docstring": "Read the samples of the utterance.\n\nArgs:\n sr (int): If None uses the sampling rate given by the track,\n otherwise resamples to the given sampling rate.\n offset (float): Offset in seconds to read samples from.\n duration (float): If not ``None`` read only this\n number of seconds in maximum.\n\nReturns:\n np.ndarray: A numpy array containing the samples\n as a floating point (numpy.float32) time series.", "source": "codesearchnet_filtered"} +{"code": "def load_extension(self, path, name_filter=None, class_filter=None, unique=False, component=None):\n import_name = None\n if (component is not None):\n import_name = _ensure_package_loaded(path, component)\n (name, ext) = _try_load_module(path, import_name=import_name)\n if ((name_filter is not None) and (name != name_filter)):\n return []\n found = [(name, x) for x in self._filter_subclasses(ext, class_filter)]\n found = [(name, x) for (name, x) in found if self._filter_nonextensions(x)]\n if (not unique):\n return found\n if (len(found) > 1):\n raise ArgumentError(('Extension %s should have had exactly one instance of class %s, found %d' % (path, class_filter.__name__, len(found))), classes=found)\n elif (len(found) == 0):\n raise ArgumentError(('Extension %s had no instances of class %s' % (path, class_filter.__name__)))\n return found[0]", "docstring": "Load a single python module extension.\n\n This function is similar to using the imp module directly to load a\n module and potentially inspecting the objects it declares to filter\n them by class.\n\nArgs:\n path (str): The path to the python file to load\n name_filter (str): If passed, the basename of the module must match\n name or nothing is returned.\n class_filter (type): If passed, only instance of this class are returned.\n unique (bool): If True (default is False), there must be exactly one object\n found inside this extension that matches all of the other criteria.\n component (IOTile): The component that this extension comes from if it is\n loaded from an installed component. This is used to properly import\n the extension as a submodule of the component's support package.\n\nReturns:\n list of (name, type): A list of the objects found at the extension path.\n\n If unique is True, then the list only contains a single entry and that\n entry will be directly returned.", "source": "codesearchnet_filtered"} +{"code": "def symbolic_master_equation(self, rho=None):\n (L, H) = (self.L, self.H)\n if (rho is None):\n rho = OperatorSymbol('rho', hs=self.space)\n return (((- I) * ((H * rho) - (rho * H))) + sum(((((Lk * rho) * adjoint(Lk)) - ((((adjoint(Lk) * Lk) * rho) + ((rho * adjoint(Lk)) * Lk)) / 2)) for Lk in L.matrix.ravel())))", "docstring": "Compute the symbolic Liouvillian acting on a state rho\n\n If no rho is given, an OperatorSymbol is created in its place.\n This correspnds to the RHS of the master equation\n in which an average is taken over the external noise degrees of\n freedom.\n\nArgs:\n rho (Operator): A symbolic density matrix operator\n\nReturns:\n Operator: The RHS of the master equation.", "source": "codesearchnet_filtered"} +{"code": "def _make_instance(self, node_data):\n node_data['from_db'] = self._from_db\n clone = self.__call__(**node_data)\n clone.setattrs(container=self, _is_item=True)\n for name in self._nodes:\n _name = un_camel(name)\n if (_name in node_data):\n getattr(clone, name)._load_data(node_data[_name])\n _key = clone._get_linked_model_key()\n if _key:\n self.node_dict[_key] = clone\n return clone", "docstring": "Create a ListNode instance from node_data\n\nArgs:\n node_data (dict): Data to create ListNode item.\n\nReturns:\n ListNode item.", "source": "codesearchnet_filtered"} +{"code": "def calcHairpin(seq, mv_conc=50.0, dv_conc=0.0, dntp_conc=0.8, dna_conc=50.0, temp_c=37, max_loop=30):\n _setThermoArgs(**locals())\n return _THERMO_ANALYSIS.calcHairpin(seq).checkExc()", "docstring": "Calculate the hairpin formation thermodynamics of a DNA sequence.\n\n **Note that the maximum length of `seq` is 60 bp.** This is a cap suggested\n by the Primer3 team as the longest reasonable sequence length for which\n a two-state NN model produces reliable results (see primer3/src/libnano/thal.h:50).\n\nArgs:\n seq (str): DNA sequence to analyze for hairpin formation\n\n mv_conc (float/int, optional): Monovalent cation conc. (mM)\n dv_conc (float/int, optional): Divalent cation conc. (mM)\n dntp_conc (float/int, optional): dNTP conc. (mM)\n dna_conc (float/int, optional): DNA conc. (nM)\n temp_c (int, optional): Simulation temperature for dG (Celsius)\n max_loop(int, optional): Maximum size of loops in the structure\n\nReturns:\n A `ThermoResult` object with thermodynamic characteristics of the\n hairpin formation.\n\nRaises:\n ``RuntimeError``", "source": "codesearchnet_filtered"} +{"code": "def _ReadLayoutDataTypeDefinition(self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_values):\n return self._ReadDataTypeDefinition(definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_values)", "docstring": "Reads a layout data type definition.\n\nArgs:\n definitions_registry (DataTypeDefinitionsRegistry): data type definitions\n registry.\n definition_values (dict[str, object]): definition values.\n data_type_definition_class (str): data type definition class.\n definition_name (str): name of the definition.\n supported_definition_values (set[str]): names of the supported definition\n values.\n\nReturns:\n LayoutDataTypeDefinition: layout data type definition.\n\nRaises:\n DefinitionReaderError: if the definitions values are missing or if\n the format is incorrect.", "source": "codesearchnet_filtered"} +{"code": "def count_matching(self, selector, offset=0):\n if selector.output:\n data = self.streaming_data\n elif selector.buffered:\n data = self.storage_data\n else:\n raise ArgumentError('You can only pass a buffered selector to count_matching', selector=selector)\n count = 0\n for i in range(offset, len(data)):\n reading = data[i]\n stream = DataStream.FromEncoded(reading.stream)\n if selector.matches(stream):\n count += 1\n return count", "docstring": "Count the number of readings matching selector.\n\nArgs:\n selector (DataStreamSelector): The selector that we want to\n count matching readings for.\n offset (int): The starting offset that we should begin counting at.\n\nReturns:\n int: The number of matching readings.", "source": "codesearchnet_filtered"} +{"code": "def sync_firmware(self):\n serial_no = self.serial_number\n if self.firmware_newer():\n try:\n self.invalidate_firmware()\n self.update_firmware()\n except errors.JLinkException as e:\n pass\n res = self.open(serial_no=serial_no)\n if self.firmware_newer():\n raise errors.JLinkException('Failed to sync firmware version.')\n return res\n elif self.firmware_outdated():\n try:\n self.update_firmware()\n except errors.JLinkException as e:\n pass\n if self.firmware_outdated():\n raise errors.JLinkException('Failed to sync firmware version.')\n return self.open(serial_no=serial_no)\n return None", "docstring": "Syncs the emulator's firmware version and the DLL's firmware.\n\n This method is useful for ensuring that the firmware running on the\n J-Link matches the firmware supported by the DLL.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n ``None``", "source": "codesearchnet_filtered"} +{"code": "def from_serializable(cls, obj):\n if (obj.get('version', {'bqm_schema': '1.0.0'})['bqm_schema'] != '2.0.0'):\n return cls._from_serializable_v1(obj)\n variables = [(tuple(v) if isinstance(v, list) else v) for v in obj['variable_labels']]\n if obj['use_bytes']:\n ldata = bytes2array(obj['linear_biases'])\n qdata = bytes2array(obj['quadratic_biases'])\n irow = bytes2array(obj['quadratic_head'])\n icol = bytes2array(obj['quadratic_tail'])\n else:\n ldata = obj['linear_biases']\n qdata = obj['quadratic_biases']\n irow = obj['quadratic_head']\n icol = obj['quadratic_tail']\n offset = obj['offset']\n vartype = obj['variable_type']\n bqm = cls.from_numpy_vectors(ldata, (irow, icol, qdata), offset, str(vartype), variable_order=variables)\n bqm.info.update(obj['info'])\n return bqm", "docstring": "Deserialize a binary quadratic model.\n\nArgs:\n obj (dict):\n A binary quadratic model serialized by :meth:`~.BinaryQuadraticModel.to_serializable`.\n\nReturns:\n :obj:`.BinaryQuadraticModel`\n\nExample:\n Encode and decode using JSON\n\n >>> import dimod\n >>> import json\n ...\n >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN)\n >>> s = json.dumps(bqm.to_serializable())\n >>> new_bqm = dimod.BinaryQuadraticModel.from_serializable(json.loads(s))\n\n See also:\n :meth:`~.BinaryQuadraticModel.to_serializable`\n\n :func:`json.loads`, :func:`json.load` JSON deserialization functions", "source": "codesearchnet_filtered"} +{"code": "def supports_card_actions(channel_id: str, button_cnt: int=100) -> bool:\n max_actions = {Channels.facebook: 3, Channels.skype: 3, Channels.ms_teams: 3, Channels.line: 99, Channels.slack: 100, Channels.emulator: 100, Channels.direct_line: 100, Channels.webchat: 100, Channels.cortana: 100}\n return ((button_cnt <= max_actions[channel_id]) if (channel_id in max_actions) else False)", "docstring": "Determine if a number of Card Actions are supported by a Channel.\n\nArgs:\n channel_id (str): The Channel to check if the Card Actions are supported in.\n button_cnt (int, optional): Defaults to 100. The number of Card Actions to check for the Channel.\n\nReturns:\n bool: True if the Channel supports the button_cnt total Card Actions, False if the Channel does not support that number of Card Actions.", "source": "codesearchnet_filtered"} +{"code": "def make(world_name, gl_version=GL_VERSION.OPENGL4, window_res=None, cam_res=None, verbose=False):\n holodeck_worlds = _get_worlds_map()\n if (world_name not in holodeck_worlds):\n raise HolodeckException('Invalid World Name')\n param_dict = copy(holodeck_worlds[world_name])\n param_dict['start_world'] = True\n param_dict['uuid'] = str(uuid.uuid4())\n param_dict['gl_version'] = gl_version\n param_dict['verbose'] = verbose\n if (window_res is not None):\n param_dict['window_width'] = window_res[0]\n param_dict['window_height'] = window_res[1]\n if (cam_res is not None):\n param_dict['camera_width'] = cam_res[0]\n param_dict['camera_height'] = cam_res[1]\n return HolodeckEnvironment(**param_dict)", "docstring": "Creates a holodeck environment using the supplied world name.\n\nArgs:\n world_name (str): The name of the world to load as an environment. Must match the name of a world in an\n installed package.\n gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENGL4.\n window_res ((int, int), optional): The resolution to load the game window at. Defaults to (512, 512).\n cam_res ((int, int), optional): The resolution to load the pixel camera sensors at. Defaults to (256, 256).\n verbose (bool): Whether to run in verbose mode. Defaults to False.\n\nReturns:\n HolodeckEnvironment: A holodeck environment instantiated with all the settings necessary for the specified\n world, and other supplied arguments.", "source": "codesearchnet_filtered"} +{"code": "def halted(self):\n result = int(self._dll.JLINKARM_IsHalted())\n if (result < 0):\n raise errors.JLinkException(result)\n return (result > 0)", "docstring": "Returns whether the CPU core was halted.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n ``True`` if the CPU core is halted, otherwise ``False``.\n\nRaises:\n JLinkException: on device errors.", "source": "codesearchnet_filtered"} +{"code": "def series_with_permutation(self, other):\n combined_permutation = tuple([self.permutation[p] for p in other.permutation])\n return CPermutation.create(combined_permutation)", "docstring": "Compute the series product with another channel permutation circuit\n\nArgs:\n other (CPermutation):\n\nReturns:\n Circuit: The composite permutation circuit (could also be the\n identity circuit for n channels)", "source": "codesearchnet_filtered"} +{"code": "def _ParsePropertiesXMLFile(self, xml_data):\n xml_root = ElementTree.fromstring(xml_data)\n properties = {}\n for xml_element in xml_root.iter():\n if (not xml_element.text):\n continue\n (_, _, name) = xml_element.tag.partition('}')\n if (name == 'lpstr'):\n continue\n property_name = self._PROPERTY_NAMES.get(name, None)\n if (not property_name):\n property_name = self._FormatPropertyName(name)\n properties[property_name] = xml_element.text\n return properties", "docstring": "Parses a properties XML file.\n\nArgs:\n xml_data (bytes): data of a _rels/.rels XML file.\n\nReturns:\n dict[str, object]: properties.\n\nRaises:\n zipfile.BadZipfile: if the properties XML file cannot be read.", "source": "codesearchnet_filtered"} +{"code": "def create_or_update_video_transcript(video_id, language_code, metadata, file_data=None):\n metadata = {prop: value for (prop, value) in six.iteritems(metadata) if ((prop in ['provider', 'language_code', 'file_name', 'file_format']) and value)}\n file_format = metadata.get('file_format')\n if (file_format and (file_format not in list(dict(TranscriptFormat.CHOICES).keys()))):\n raise InvalidTranscriptFormat('{} transcript format is not supported'.format(file_format))\n provider = metadata.get('provider')\n if (provider and (provider not in list(dict(TranscriptProviderType.CHOICES).keys()))):\n raise InvalidTranscriptProvider('{} transcript provider is not supported'.format(provider))\n try:\n video = Video.objects.get(edx_video_id=video_id)\n (video_transcript, __) = VideoTranscript.create_or_update(video, language_code, metadata, file_data)\n except Video.DoesNotExist:\n return None\n return video_transcript.url()", "docstring": "Create or Update video transcript for an existing video.\n\nArgs:\n video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component.\n language_code: language code of a video transcript\n metadata (dict): A dict containing (to be overwritten) properties\n file_data (InMemoryUploadedFile): Transcript data to be saved for a course video.\n\nReturns:\n video transcript url", "source": "codesearchnet_filtered"} +{"code": "def _init_project_service(self, version):\n project_cfg = self._load_config_section(CONFIG_PROJECT_SECTION)\n self._token_project = project_cfg[CONFIG_TOKEN]\n proto = project_cfg[CONFIG_PROTOCOL]\n host = project_cfg[CONFIG_HOST]\n self._project = ProjectService(host, version)\n self._project.base_protocol = proto\n self._project.set_auth(self._token_project)", "docstring": "Method to initialize the Project Service from the config data\n\nArgs:\n version (string): Version of Boss API to use.\n\nReturns:\n None\n\nRaises:\n (KeyError): if given invalid version.", "source": "codesearchnet_filtered"} +{"code": "def delete_keyvault_secret(access_token, vault_uri, secret_name):\n endpoint = ''.join([vault_uri, '/secrets/', secret_name, '?api-version=', '7.0'])\n return do_delete(endpoint, access_token)", "docstring": "Deletes a secret from a key vault using the key vault URI.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n vault_uri (str): Vault URI e.g. https://myvault.azure.net.\n secret_name (str): Name of the secret to add.\n\nReturns:\n HTTP response. 200 OK.", "source": "codesearchnet_filtered"} +{"code": "def set_description(self, name, value=None, default=False, disable=False):\n string = 'description'\n commands = self.command_builder(string, value=value, default=default, disable=disable)\n return self.configure_interface(name, commands)", "docstring": "Configures the interface description\n\n EosVersion:\n 4.13.7M\n\nArgs:\n name (string): The interface identifier. It must be a full\n interface name (ie Ethernet, not Et)\n value (string): The value to set the description to.\n default (boolean): Specifies to default the interface description\n disable (boolean): Specifies to negate the interface description\n\nReturns:\n True if the operation succeeds otherwise False", "source": "codesearchnet_filtered"} +{"code": "def _remove_hdxobject(self, objlist, obj, matchon='id', delete=False):\n if (objlist is None):\n return False\n if isinstance(obj, six.string_types):\n obj_id = obj\n elif (isinstance(obj, dict) or isinstance(obj, HDXObject)):\n obj_id = obj.get(matchon)\n else:\n raise HDXError('Type of object not a string, dict or T<=HDXObject')\n if (not obj_id):\n return False\n for (i, objdata) in enumerate(objlist):\n objid = objdata.get(matchon)\n if (objid and (objid == obj_id)):\n if delete:\n objlist[i].delete_from_hdx()\n del objlist[i]\n return True\n return False", "docstring": "Remove an HDX object from a list within the parent HDX object\n\nArgs:\n objlist (List[Union[T <= HDXObject,Dict]]): list of HDX objects\n obj (Union[T <= HDXObject,Dict,str]): Either an id or hdx object metadata either from an HDX object or a dictionary\n matchon (str): Field to match on. Defaults to id.\n delete (bool): Whether to delete HDX object. Defaults to False.\n\nReturns:\n bool: True if object removed, False if not", "source": "codesearchnet_filtered"} +{"code": "def _row_from_mapping(mapping, schema):\n if (len(schema) == 0):\n raise ValueError(_TABLE_HAS_NO_SCHEMA)\n row = []\n for field in schema:\n if (field.mode == 'REQUIRED'):\n row.append(mapping[field.name])\n elif (field.mode == 'REPEATED'):\n row.append(mapping.get(field.name, ()))\n elif (field.mode == 'NULLABLE'):\n row.append(mapping.get(field.name))\n else:\n raise ValueError('Unknown field mode: {}'.format(field.mode))\n return tuple(row)", "docstring": "Convert a mapping to a row tuple using the schema.\n\nArgs:\n mapping (Dict[str, object])\n Mapping of row data: must contain keys for all required fields in\n the schema. Keys which do not correspond to a field in the schema\n are ignored.\n schema (List[google.cloud.bigquery.schema.SchemaField]):\n The schema of the table destination for the rows\n\nReturns:\n Tuple[object]:\n Tuple whose elements are ordered according to the schema.\n\nRaises:\n ValueError: If schema is empty.", "source": "codesearchnet_filtered"} +{"code": "def find_pad_index(self, array):\n try:\n return list(array).index(self.pad_value)\n except ValueError:\n return len(array)", "docstring": "Find padding index.\n\nArgs:\n array (list): integer list.\n\nReturns:\n idx: padding index.\n\nExample:\n >>> array = [1, 2, 0]\n >>> self.find_pad_index(array)\n 2", "source": "codesearchnet_filtered"} +{"code": "def decode_jwt_payload(self, access_token=None):\n c = self.get_credentials()\n jwt = (access_token or c.access_token)\n try:\n (_, payload, _) = jwt.split('.')\n rem = (len(payload) % 4)\n if (rem > 0):\n payload += ('=' * (4 - rem))\n try:\n decoded_jwt = b64decode(payload).decode('utf-8')\n except TypeError as e:\n raise PanCloudError(('Failed to base64 decode JWT: %s' % e))\n else:\n try:\n x = loads(decoded_jwt)\n except ValueError as e:\n raise PanCloudError(('Invalid JSON: %s' % e))\n except (AttributeError, ValueError) as e:\n raise PanCloudError(('Invalid JWT: %s' % e))\n return x", "docstring": "Extract payload field from JWT.\n\nArgs:\n access_token (str): Access token to decode. Defaults to ``None``.\n\nReturns:\n dict: JSON object that contains the claims conveyed by the JWT.", "source": "codesearchnet_filtered"} +{"code": "def CheckTaskToMerge(self, task):\n with self._lock:\n is_abandoned = (task.identifier in self._tasks_abandoned)\n is_processing = (task.identifier in self._tasks_processing)\n is_queued = (task.identifier in self._tasks_queued)\n if ((not is_queued) and (not is_processing) and (not is_abandoned)):\n raise KeyError('Status of task {0:s} is unknown.'.format(task.identifier))\n return (is_queued or is_processing or (is_abandoned and (not task.has_retry)))", "docstring": "Checks if the task should be merged.\n\nArgs:\n task (Task): task.\n\nReturns:\n bool: True if the task should be merged.\n\nRaises:\n KeyError: if the task was not queued, processing or abandoned.", "source": "codesearchnet_filtered"} +{"code": "def get_image_data(self, ids=None, voxels=None, dense=True):\n if (dense and (ids is None) and (voxels is None)):\n logger.warning('Warning: get_image_data() is being called without specifying a subset of studies or voxels to retrieve. This may result in a very large amount of data (several GB) being read into memory. If you experience any problems, consider returning a sparse matrix by passing dense=False, or pass in a list of ids of voxels to retrieve only a portion of the data.')\n result = self.data\n if (ids is not None):\n idxs = np.where(np.in1d(np.array(self.ids), np.array(ids)))[0]\n result = result[(:, idxs)]\n if (voxels is not None):\n result = result[(voxels, :)]\n return (result.toarray() if dense else result)", "docstring": "Slices and returns a subset of image data.\n\nArgs:\n ids (list, array): A list or 1D numpy array of study ids to\n return. If None, returns data for all studies.\n voxels (list, array): A list or 1D numpy array of voxel indices\n (i.e., rows) to return. If None, returns data for all voxels.\n dense (bool): Optional boolean. When True (default), convert the\n result to a dense array before returning. When False, keep as\n sparse matrix.\n\nReturns:\n A 2D numpy array with voxels in rows and studies in columns.", "source": "codesearchnet_filtered"} +{"code": "def _brentq_cdf(self, value):\n bound_cdf = partial(scalarize(GaussianKDE.cumulative_distribution), self)\n\n def f(x):\n return (bound_cdf(x) - value)\n return f", "docstring": "Helper function to compute percent_point.\n\n As scipy.stats.gaussian_kde doesn't provide this functionality out of the box we need\n to make a numerical approach:\n\n - First we scalarize and bound cumulative_distribution.\n - Then we define a function `f(x) = cdf(x) - value`, where value is the given argument.\n - As value will be called from ppf we can assume value = cdf(z) for some z that is the\n value we are searching for. Therefore the zeros of the function will be x such that:\n cdf(x) - cdf(z) = 0 => (becasue cdf is monotonous and continous) x = z\n\nArgs:\n value(float): cdf value, that is, in [0,1]\n\nReturns:\n callable: function whose zero is the ppf of value.", "source": "codesearchnet_filtered"} +{"code": "def _cart_dists(self, s1, s2, avg_lattice, mask, normalization, lll_frac_tol=None):\n if (len(s2) > len(s1)):\n raise ValueError('s1 must be larger than s2')\n if (mask.shape != (len(s2), len(s1))):\n raise ValueError('mask has incorrect shape')\n (vecs, d_2) = pbc_shortest_vectors(avg_lattice, s2, s1, mask, return_d2=True, lll_frac_tol=lll_frac_tol)\n lin = LinearAssignment(d_2)\n s = lin.solution\n short_vecs = vecs[(np.arange(len(s)), s)]\n translation = np.average(short_vecs, axis=0)\n f_translation = avg_lattice.get_fractional_coords(translation)\n new_d2 = np.sum(((short_vecs - translation) ** 2), axis=(- 1))\n return (((new_d2 ** 0.5) * normalization), f_translation, s)", "docstring": "Finds a matching in cartesian space. Finds an additional\n fractional translation vector to minimize RMS distance\n\nArgs:\n s1, s2: numpy arrays of fractional coordinates. len(s1) >= len(s2)\n avg_lattice: Lattice on which to calculate distances\n mask: numpy array of booleans. mask[i, j] = True indicates\n that s2[i] cannot be matched to s1[j]\n normalization (float): inverse normalization length\n\nReturns:\n Distances from s2 to s1, normalized by (V/Natom) ^ 1/3\n Fractional translation vector to apply to s2.\n Mapping from s1 to s2, i.e. with numpy slicing, s1[mapping] => s2", "source": "codesearchnet_filtered"} +{"code": "def solve_sweep_wavelength(self, structure, wavelengths, filename='wavelength_n_effs.dat', plot=True):\n n_effs = []\n for w in tqdm.tqdm(wavelengths, ncols=70):\n structure.change_wavelength(w)\n self.solve(structure)\n n_effs.append(np.real(self.n_effs))\n if filename:\n self._write_n_effs_to_file(n_effs, (self._modes_directory + filename), wavelengths)\n if plot:\n if MPL:\n title = '$n_{eff}$ vs Wavelength'\n y_label = '$n_{eff}$'\n else:\n title = ('n_{effs} vs Wavelength' % x_label)\n y_label = 'n_{eff}'\n self._plot_n_effs((self._modes_directory + filename), (self._modes_directory + 'fraction_te.dat'), 'Wavelength', 'n_{eff}', title)\n return n_effs", "docstring": "Solve for the effective indices of a fixed structure at\n different wavelengths.\n\nArgs:\n structure (Slabs): The target structure to solve\n for modes.\n wavelengths (list): A list of wavelengths to sweep\n over.\n filename (str): The nominal filename to use when saving the\n effective indices. Defaults to 'wavelength_n_effs.dat'.\n plot (bool): `True` if plots should be generates,\n otherwise `False`. Default is `True`.\n\nReturns:\n list: A list of the effective indices found for each wavelength.", "source": "codesearchnet_filtered"} +{"code": "def extract(self, text: str) -> List[Extraction]:\n doc = self._parser(text)\n extractions = list()\n for sent in doc.sents:\n this_extraction = Extraction(value=sent.text, extractor_name=self.name, start_token=sent[0], end_token=sent[(- 1)], start_char=sent.text[0], end_char=sent.text[(- 1)])\n extractions.append(this_extraction)\n return extractions", "docstring": "Splits text by sentences.\n\nArgs:\n text (str): Input text to be extracted.\n\nReturns:\n List[Extraction]: the list of extraction or the empty list if there are no matches.", "source": "codesearchnet_filtered"} +{"code": "def unembed_samples(samples, embedding, chain_break_method=None):\n if (chain_break_method is None):\n chain_break_method = majority_vote\n return list(itertools.chain(*(chain_break_method(sample, embedding) for sample in samples)))", "docstring": "Return samples over the variables in the source graph.\n\nArgs:\n samples (iterable): An iterable of samples where each sample\n is a dict of the form {v: val, ...} where v is a variable\n in the target model and val is the associated value as\n determined by a binary quadratic model sampler.\n embedding (dict): The mapping from the source graph to the target graph.\n Should be of the form {v: {s, ...}, ...} where v is a node in the\n source graph and s is a node in the target graph.\n chain_break_method (function, optional): The method used to resolve chain\n breaks. Default is :method:`majority_vote`.\n\nReturns:\n list: A list of unembedded samples. Each sample is a dict of the form\n {v: val, ...} where v is a variable in the source graph and val\n is the value associated with the variable.", "source": "codesearchnet_filtered"} +{"code": "def get_attributes(self, uuid=None, attribute_names=None):\n batch_item = self._build_get_attributes_batch_item(uuid, attribute_names)\n request = self._build_request_message(None, [batch_item])\n response = self._send_and_receive_message(request)\n results = self._process_batch_items(response)\n return results[0]", "docstring": "Send a GetAttributes request to the server.\n\nArgs:\n uuid (string): The ID of the managed object with which the\n retrieved attributes should be associated. Optional, defaults\n to None.\n attribute_names (list): A list of AttributeName values indicating\n what object attributes the client wants from the server.\n Optional, defaults to None.\n\nReturns:\n result (GetAttributesResult): A structure containing the results\n of the operation.", "source": "codesearchnet_filtered"} +{"code": "def expand_abbreviations(self, text):\n if (not self.abbreviations):\n raise LexiconError('No abbreviations in lexicon.')\n\n def chunks(data, SIZE=25):\n '\\n Regex only supports 100 groups for munging callbacks. So we have to\\n chunk the abbreviation dicitonary.\\n '\n it = iter(data)\n for i in range(0, len(data), SIZE):\n (yield {k: data[k] for k in islice(it, SIZE)})\n\n def cb(g):\n 'Regex callback'\n return (self.abbreviations.get(g.group(0)) or g.group(0))\n text = re.sub('w/', 'wi', text)\n for subdict in chunks(self.abbreviations):\n regex = (('(\\\\b' + '\\\\b)|(\\\\b'.join(subdict.keys())) + '\\\\b)')\n text = re.sub(regex, cb, text)\n return text", "docstring": "Parse a piece of text and replace any abbreviations with their full\n word equivalents. Uses the lexicon.abbreviations dictionary to find\n abbreviations.\n\nArgs:\n text (str): The text to parse.\n\nReturns:\n str: The text with abbreviations replaced.", "source": "codesearchnet_filtered"} +{"code": "def list_container_instance_groups_sub(access_token, subscription_id):\n endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.ContainerInstance/ContainerGroups', '?api-version=', CONTAINER_API])\n return do_get(endpoint, access_token)", "docstring": "List the container groups in a subscription.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n\nReturns:\n HTTP response. JSON list of container groups and their properties.", "source": "codesearchnet_filtered"} +{"code": "def _ValidateCacheEntryHeader(self, cache_entry_header):\n return ((cache_entry_header.request_size > 0) and (cache_entry_header.request_size < self._MAXIMUM_URL_LENGTH) and (cache_entry_header.major_format_version == 1) and (cache_entry_header.last_fetched_time > 0) and (cache_entry_header.fetch_count > 0))", "docstring": "Determines whether the values in the cache entry header are valid.\n\nArgs:\n cache_entry_header (firefox_cache1_entry_header): cache entry header.\n\nReturns:\n bool: True if the cache entry header is valid.", "source": "codesearchnet_filtered"} +{"code": "def search(self, query_string):\n query = self.create_query()\n parser = QueryParser(query_string, query)\n parser.parse()\n return self.query(query)", "docstring": "Performs a search against the index using lunr query syntax.\n\n Results will be returned sorted by their score, the most relevant\n results will be returned first.\n\n For more programmatic querying use `lunr.Index.query`.\n\nArgs:\n query_string (str): A string to parse into a Query.\n\nReturns:\n dict: Results of executing the query.", "source": "codesearchnet_filtered"} +{"code": "def _parse_flowcontrol_receive(self, config):\n value = 'off'\n match = re.search('flowcontrol receive (\\\\w+)$', config, re.M)\n if match:\n value = match.group(1)\n return dict(flowcontrol_receive=value)", "docstring": "Scans the config block and returns the flowcontrol receive value\n\nArgs:\n config (str): The interface config block to scan\n\nReturns:\n dict: Returns a dict object with the flowcontrol receive value\n retrieved from the config block. The returned dict object\n is intended to be merged into the interface resource dict", "source": "codesearchnet_filtered"} +{"code": "def get_course_track_selection_url(course_run, query_parameters):\n try:\n course_root = reverse('course_modes_choose', kwargs={'course_id': course_run['key']})\n except KeyError:\n LOGGER.exception('KeyError while parsing course run data.\\nCourse Run: \\n[%s]', course_run)\n raise\n url = '{}{}'.format(settings.LMS_ROOT_URL, course_root)\n course_run_url = update_query_parameters(url, query_parameters)\n return course_run_url", "docstring": "Return track selection url for the given course.\n\nArgs:\n course_run (dict): A dictionary containing course run metadata.\n query_parameters (dict): A dictionary containing query parameters to be added to course selection url.\n\nRaises:\n (KeyError): Raised when course run dict does not have 'key' key.\n\nReturns:\n (str): Course track selection url.", "source": "codesearchnet_filtered"} +{"code": "def GetVolumeByIndex(self, volume_index):\n if (not self._is_parsed):\n self._Parse()\n self._is_parsed = True\n if ((volume_index < 0) or (volume_index >= len(self._volume_identifiers))):\n return None\n volume_identifier = self._volume_identifiers[volume_index]\n return self._volumes[volume_identifier]", "docstring": "Retrieves a specific volume based on the index.\n\nArgs:\n volume_index (int): index of the volume.\n\nReturns:\n Volume: a volume or None if not available.", "source": "codesearchnet_filtered"} +{"code": "def get_all(self, callsign, timestamp=timestamp_now):\n callsign_data = self._lookup_callsign(callsign, timestamp)\n try:\n cqz = self._lookuplib.lookup_zone_exception(callsign, timestamp)\n callsign_data[const.CQZ] = cqz\n except KeyError:\n pass\n return callsign_data", "docstring": "Lookup a callsign and return all data available from the underlying database\n\nArgs:\n callsign (str): Amateur Radio callsign\n timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\nReturns:\n dict: Dictionary containing the callsign specific data\n\nRaises:\n KeyError: Callsign could not be identified\n\nExample:\n The following code returns all available information from the country-files.com database for the\n callsign \"DH1TW\"\n\n >>> from pyhamtools import LookupLib, Callinfo\n >>> my_lookuplib = LookupLib(lookuptype=\"countryfile\")\n >>> cic = Callinfo(my_lookuplib)\n >>> cic.get_all(\"DH1TW\")\n {\n 'country': 'Fed. Rep. of Germany',\n 'adif': 230,\n 'continent': 'EU',\n 'latitude': 51.0,\n 'longitude': -10.0,\n 'cqz': 14,\n 'ituz': 28\n }\n\nNote:\n The content of the returned data depends entirely on the injected\n :py:class:`LookupLib` (and the used database). While the country-files.com provides\n for example the ITU Zone, Clublog doesn't. Consequently, the item \"ituz\"\n would be missing with Clublog (API or XML) :py:class:`LookupLib`.", "source": "codesearchnet_filtered"} +{"code": "def snapped_slice(size, frac, n):\n if (size < n):\n n = size\n start = (int(((size * frac) - ceil((n / 2)))) + 1)\n stop = (int(((size * frac) + floor((n / 2)))) + 1)\n buf = 0\n if (stop >= size):\n buf = (size - stop)\n elif (start < 0):\n buf = (0 - start)\n stop += buf\n start += buf\n assert (stop <= size), ('out of bounds [%r, %r]' % (stop, start))\n sl = slice(start, stop)\n return sl", "docstring": "r\"\"\"\n Creates a slice spanning `n` items in a list of length `size` at position\n `frac`.\n\nArgs:\n size (int): length of the list\n frac (float): position in the range [0, 1]\n n (int): number of items in the slice\n\nReturns:\n slice: slice object that best fits the criteria\n\n SeeAlso:\n take_percentile_parts\n\nExample:\n Example:\n >>> # DISABLE_DOCTEST\n >>> from utool.util_list import * # NOQA\n >>> import utool as ut\n >>> print(snapped_slice(0, 0, 10))\n >>> print(snapped_slice(1, 0, 10))\n >>> print(snapped_slice(100, 0, 10))\n >>> print(snapped_slice(9, 0, 10))\n >>> print(snapped_slice(100, 1, 10))\n pass", "source": "codesearchnet_filtered"} +{"code": "def from_file(cls, fp, is_outlook=False):\n log.debug('Parsing email from file {!r}'.format(fp))\n with ported_open(fp) as f:\n message = email.message_from_file(f)\n if is_outlook:\n log.debug('Removing temp converted Outlook email {!r}'.format(fp))\n os.remove(fp)\n return cls(message)", "docstring": "Init a new object from a file path.\n\nArgs:\n fp (string): file path of raw email\n is_outlook (boolean): if True is an Outlook email\n\nReturns:\n Instance of MailParser", "source": "codesearchnet_filtered"} +{"code": "def _build_endpoint(self, endpoint_name):\n endpoint_relative = settings.get('asmaster_endpoints', endpoint_name)\n return ('%s%s' % (self.host, endpoint_relative))", "docstring": "Generate an enpoint url from a setting name.\n\nArgs:\n endpoint_name(str): setting name for the enpoint to build\n\nReturns:\n (str) url enpoint", "source": "codesearchnet_filtered"} +{"code": "def estimate_mutual_information(x, y):\n xy = np.concatenate((x, y), axis=1)\n epsilon = _calculate_epsilon(xy)\n h_x = estimate_entropy(x, epsilon)\n h_y = estimate_entropy(y, epsilon)\n h_xy = estimate_entropy(xy, epsilon)\n return max(0, ((h_x + h_y) - h_xy))", "docstring": "Estimate the mutual information of two datasets.\n\n Mutual information is a measure of dependence between\n two datasets and is calculated as:\n\n $I(x;y) = H(x) + H(y) - H(x,y)$\n\n Where H(x) is the Shannon entropy of x. For continuous datasets,\n adapts the Kraskov Estimator [1] for mutual information.\n\nArgs:\n x (array-like): An array with shape (n_samples, n_features_x)\n y (array-like): An array with shape (n_samples, n_features_y)\n\nReturns:\n float: A floating point number representing the mutual\n information of x and y. This calculation is *exact*\n for entirely discrete datasets and *approximate* if\n there are continuous columns present.\n\n References:\n\n .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, \"Estimating mutual\n information\". Phys. Rev. E 69, 2004.", "source": "codesearchnet_filtered"} +{"code": "def get_sv_variants(self, chromosome=None, end_chromosome=None, sv_type=None, pos=None, end=None):\n query = {}\n if chromosome:\n query['chrom'] = chromosome\n if end_chromosome:\n query['end_chrom'] = end_chromosome\n if sv_type:\n query['sv_type'] = sv_type\n if pos:\n if (not ('$and' in query)):\n query['$and'] = []\n query['$and'].append({'pos_left': {'$lte': pos}})\n query['$and'].append({'pos_right': {'$gte': pos}})\n if end:\n if (not ('$and' in query)):\n query['$and'] = []\n query['$and'].append({'end_left': {'$lte': end}})\n query['$and'].append({'end_right': {'$gte': end}})\n LOG.info('Find all sv variants {}'.format(query))\n return self.db.structural_variant.find(query).sort([('chrom', ASCENDING), ('pos_left', ASCENDING)])", "docstring": "Return all structural variants in the database\n\nArgs:\n chromosome (str)\n end_chromosome (str)\n sv_type (str)\n pos (int): Left position of SV\n end (int): Right position of SV\n\nReturns:\n variants (Iterable(Variant))", "source": "codesearchnet_filtered"} +{"code": "def easeInOutExpo(n):\n _checkRange(n)\n if (n == 0):\n return 0\n elif (n == 1):\n return 1\n else:\n n = (n * 2)\n if (n < 1):\n return (0.5 * (2 ** (10 * (n - 1))))\n else:\n n -= 1\n return (0.5 * (((- 1) * (2 ** ((- 10) * n))) + 2))", "docstring": "An exponential tween function that accelerates, reaches the midpoint, and then decelerates.\n\nArgs:\n n (float): The time progress, starting at 0.0 and ending at 1.0.\n\nReturns:\n (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().", "source": "codesearchnet_filtered"} +{"code": "def _CheckIsPipe(self, file_entry):\n if (definitions.FILE_ENTRY_TYPE_PIPE not in self._file_entry_types):\n return False\n return file_entry.IsPipe()", "docstring": "Checks the is_pipe find specification.\n\nArgs:\n file_entry (FileEntry): file entry.\n\nReturns:\n bool: True if the file entry matches the find specification, False if not.", "source": "codesearchnet_filtered"} +{"code": "def mp_atan2(y, x):\n return 'if((x)>0, atan((y)/(x)), if(((x)<0) and ((y)>=0), atan((y)/(x))+pi, if(((x)<0) and ((y)<0), atan((y)/(x))-pi, if(((x)==0) and ((y)>0), pi/2, if(((x)==0) and ((y)<0), -pi/2, 0)))))'.replace('pi', str(math.pi)).replace('y', y).replace('x', x)", "docstring": "muparser atan2 function\n\n Implements an atan2(y,x) function for older muparser versions (<2.1.0);\n atan2 was added as a built-in function in muparser 2.1.0\n\nArgs:\n y (str): y argument of the atan2(y,x) function\n x (str): x argument of the atan2(y,x) function\n\nReturns:\n A muparser string that calculates atan2(y,x)", "source": "codesearchnet_filtered"} +{"code": "def load_pkl(filenames):\n if (not isinstance(filenames, (list, tuple))):\n filenames = [filenames]\n times = []\n for name in filenames:\n name = str(name)\n with open(name, 'rb') as file:\n loaded_obj = pickle.load(file)\n if (not isinstance(loaded_obj, Times)):\n raise TypeError('At least one loaded object is not a Times data object.')\n times.append(loaded_obj)\n return (times if (len(times) > 1) else times[0])", "docstring": "Unpickle file contents.\n\nArgs:\n filenames (str): Can be one or a list or tuple of filenames to retrieve.\n\nReturns:\n Times: A single object, or from a collection of filenames, a list of Times objects.\n\nRaises:\n TypeError: If any loaded object is not a Times object.", "source": "codesearchnet_filtered"} +{"code": "def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles):\n non_rgb_warning(img)\n input_dtype = img.dtype\n needs_float = False\n if (input_dtype == np.float32):\n img = from_float(img, dtype=np.dtype('uint8'))\n needs_float = True\n elif (input_dtype not in (np.uint8, np.float32)):\n raise ValueError('Unexpected dtype {} for RandomSunFlareaugmentation'.format(input_dtype))\n overlay = img.copy()\n output = img.copy()\n for (alpha, (x, y), rad3, (r_color, g_color, b_color)) in circles:\n cv2.circle(overlay, (x, y), rad3, (r_color, g_color, b_color), (- 1))\n cv2.addWeighted(overlay, alpha, output, (1 - alpha), 0, output)\n point = (int(flare_center_x), int(flare_center_y))\n overlay = output.copy()\n num_times = (src_radius // 10)\n alpha = np.linspace(0.0, 1, num=num_times)\n rad = np.linspace(1, src_radius, num=num_times)\n for i in range(num_times):\n cv2.circle(overlay, point, int(rad[i]), src_color, (- 1))\n alp = ((alpha[((num_times - i) - 1)] * alpha[((num_times - i) - 1)]) * alpha[((num_times - i) - 1)])\n cv2.addWeighted(overlay, alp, output, (1 - alp), 0, output)\n image_rgb = output\n if needs_float:\n image_rgb = to_float(image_rgb, max_value=255)\n return image_rgb", "docstring": "Add sun flare.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\nArgs:\n img (np.array):\n flare_center_x (float):\n flare_center_y (float):\n src_radius:\n src_color (int, int, int):\n circles (list):\n\n Returns:", "source": "codesearchnet_filtered"} +{"code": "def dtype_numpy(x):\n return dtypes_module.as_dtype(x.dtype).as_numpy_dtype", "docstring": "Returns the numpy dtype of a Keras tensor or variable.\n\nArgs:\n x: Tensor or variable.\n\nReturns:\n numpy.dtype, dtype of `x`.", "source": "github_repos"} +{"code": "def _capture_by_ref(self, graph: Any, lam: Callable[[], Any], key: Hashable=None) -> Any:\n if key is not None and key in self._by_ref_internal:\n return self._by_ref_internal[key]\n if key is None:\n key = len(self._by_ref_internal)\n while key in self._by_ref_internal:\n key += 1\n value_nested = lam()\n capture_trace_type = trace_type.from_value(value_nested)\n ctx = trace_type.InternalPlaceholderContext(graph)\n internal = capture_trace_type.placeholder_value(ctx)\n\n def lam_fn():\n value = lam()\n return capture_trace_type.to_tensors(value)\n self._by_ref_external[key] = lam_fn\n self._by_ref_internal[key] = internal\n self._by_ref_tracetype[key] = capture_trace_type\n return self._by_ref_internal[key]", "docstring": "Used during tracing process to create/retrive by-ref captures.\n\nArgs:\n graph: The FuncGraph that captures this tensor.\n lam: A callable that takes no arguments and returns tensor captures.\n key: A hashable identifier.\n\nReturns:\n Tensor from this FuncGraph.", "source": "github_repos"} +{"code": "def to_dataframe(self, view: views.View) -> pandas.DataFrame:\n resources = self._fetch_bundle_entries()\n flattened_view = self._flatten_fhir_to_view(view, resources)\n return pandas.json_normalize(flattened_view)", "docstring": "Returns a Pandas dataframe of the results, if Pandas is installed.\n\nArgs:\n view: the view that defines the desired format of the flattened FHIR\n output.\n\nReturns:\n pandas.DataFrame: dataframe of the view contents.", "source": "github_repos"} +{"code": "def __init__(self, name, func, create_scope_now=False, custom_getter=None, create_graph_function=False):\n if not context.executing_eagerly():\n raise RuntimeError('{} objects can only be used when eager execution is enabled, use tf.Template for graph construction'.format(type(self)))\n super(EagerTemplate, self).__init__(name, func, create_scope_now, None, custom_getter, create_graph_function)\n if self._variable_scope is not None:\n variable_scope_name = self._variable_scope.name\n else:\n variable_scope_name = None\n self._template_store = _EagerTemplateVariableStore(variable_scope_name)\n self._variable_scope_context_manager = None", "docstring": "Creates a template for the given function.\n\nArgs:\n name: A name for the scope created by this template. The name will be made\n unique by appending `_N` to the it (see how\n `tf.compat.v1.variable_scope` treats the `default_name` for details).\n func: The function to apply each time.\n create_scope_now: Whether to create the scope at Template construction\n time, rather than first call. Defaults to false. Creating the scope at\n construction time may be more convenient if the template is passed\n through much lower level code, and you want to be sure of the scope name\n without knowing exactly where it will be first called. If set to True,\n the scope will be created in the constructor, and all subsequent times\n in `__call__`, leading to a trailing numeral being added to the names of\n all created Tensors. If set to False, the scope will be created at the\n first call location.\n custom_getter: optional custom getter to pass to `variable_scope()`\n create_graph_function: When True, `func` will be executed as a graph\n function. Enabling this flag allows the caller to reap the performance\n benefits associated with executing graphs, at the cost of sacrificing\n debuggability; however, not all Python functions can be compiled into\n graph functions. See the documentation for `function.defun` for details.\n\nRaises:\n RuntimeError: if eager execution is not enabled.", "source": "github_repos"} +{"code": "def write_zip_data(self, temp_parfile, stored_resources):\n logging.debug('Storing Files...')\n with contextlib.closing(zipfile.ZipFile(temp_parfile, 'w', self.compression)) as z:\n items = sorted(stored_resources.items())\n for relative_path, resource in items:\n assert resource.zipinfo.filename == relative_path\n resource.store(z)", "docstring": "Write the second part of a parfile, consisting of ZIP data\n\nArgs:\n stored_resources: A dictionary mapping relative path to the\n content to store at that path.", "source": "github_repos"} +{"code": "def update_model_parameters(model: nn.Module) -> None:\n model._parameters = {}\n for name, module in model.named_modules():\n if name == '':\n continue\n param_name = name.replace('module.', '')\n if hasattr(module, 'weight') and module.weight is not None:\n model._parameters[f'{param_name}.weight'] = module.weight\n if hasattr(module, 'bias') and module.bias is not None:\n model._parameters[f'{param_name}.bias'] = module.bias", "docstring": "Update model._parameters using named_modules() to ensure all parameters are properly tracked.\n\nArgs:\n model (nn.Module): The model to update parameters for", "source": "github_repos"} +{"code": "def update_last_triggered_step(self, step):\n raise NotImplementedError", "docstring": "Update the last triggered time and step number.\n\nArgs:\n step: The current step.\n\nReturns:\n A pair `(elapsed_time, elapsed_steps)`, where `elapsed_time` is the number\n of seconds between the current trigger and the last one (a float), and\n `elapsed_steps` is the number of steps between the current trigger and\n the last one. Both values will be set to `None` on the first trigger.", "source": "github_repos"} +{"code": "def __init__(self, name, freevars, extra_locals):\n self._name = name\n self._freevars = freevars\n self._extra_locals = extra_locals\n self._unbound_factory = None\n self.module = None\n self.source_map = None", "docstring": "Creates a new factory for a Python function.\n\nArgs:\n name: The function name.\n freevars: The list of non-global free variables for the function.\n extra_locals: Dict[Text, Any], names and values for custom variables that\n are accessible to the generated code as local variables.", "source": "github_repos"} +{"code": "def tuple(tensors, name=None, control_inputs=None):\n if context.executing_eagerly():\n return tensors\n with ops.name_scope(name, 'tuple', tensors) as name:\n tensors = [t if isinstance(t, ops.Operation) or tensor_util.is_tf_type(t) or t is None else ops.convert_to_tensor(t) for t in tensors]\n gating_ops = [t if isinstance(t, ops.Operation) else t.op for t in tensors if t is not None]\n if control_inputs:\n for c in control_inputs:\n if isinstance(c, tensor_lib.Tensor):\n c = c.op\n elif not isinstance(c, ops.Operation):\n raise TypeError(f\"'control_inputs' must only contain Operation or Tensor. Received: {type(c)}\")\n gating_ops.append(c)\n gating_ops = sorted(set(gating_ops), key=lambda op: op._id)\n if not gating_ops:\n raise ValueError(f\"'tensors' must have at least one Tensor. Received: {tensors}.\")\n gate = group(*gating_ops)\n tpl = []\n for t in tensors:\n if tensor_util.is_tf_type(t):\n tpl.append(with_dependencies([gate], t))\n elif isinstance(t, ops.Operation):\n with ops.control_dependencies([gate]):\n tpl.append(group(t))\n else:\n tpl.append(None)\n return tpl", "docstring": "Group tensors together.\n\n This creates a tuple of tensors with the same values as the `tensors`\n argument, except that the value of each tensor is only returned after the\n values of all tensors have been computed.\n\n `control_inputs` contains additional ops that have to finish before this op\n finishes, but whose outputs are not returned.\n\n This can be used as a \"join\" mechanism for parallel computations: all the\n argument tensors can be computed in parallel, but the values of any tensor\n returned by `tuple` are only available after all the parallel computations\n are done.\n\n See also `tf.group` and\n `tf.control_dependencies`.\n\nArgs:\n tensors: A list of `Tensor`s or `IndexedSlices`, some entries can be `None`.\n name: (optional) A name to use as a `name_scope` for the operation.\n control_inputs: List of additional ops to finish before returning.\n\nReturns:\n Same as `tensors`.\n\nRaises:\n ValueError: If `tensors` does not contain any `Tensor` or `IndexedSlices`.\n TypeError: If `control_inputs` is not a list of `Operation` or `Tensor`\n objects.", "source": "github_repos"} +{"code": "def run(argv=None, save_main_session=True, test_pipeline=None) -> PipelineResult:\n known_args, pipeline_args = parse_known_args(argv)\n pipeline_options = PipelineOptions(pipeline_args)\n pipeline_options.view_as(SetupOptions).save_main_session = save_main_session\n pipeline = test_pipeline\n if not test_pipeline:\n pipeline = beam.Pipeline(options=pipeline_options)\n tokenizer = AutoTokenizer.from_pretrained(known_args.model_name)\n model_handler = HuggingFaceModelHandlerKeyedTensor(model_uri=known_args.model_name, model_class=known_args.model_class, framework='pt', max_batch_size=1, large_model=known_args.large_model)\n if not known_args.input:\n text = pipeline | 'CreateSentences' >> beam.Create(['The capital of France is Paris .', 'It is raining cats and dogs .', 'Today is Monday and tomorrow is Tuesday .', 'There are 5 coconuts on this palm tree .', 'The strongest person in the world is not famous .', 'The secret ingredient to his wonderful life was gratitude .', 'The biggest animal in the world is the whale .'])\n else:\n text = pipeline | 'ReadSentences' >> beam.io.ReadFromText(known_args.input)\n text_and_tokenized_text_tuple = text | 'FilterEmptyLines' >> beam.ParDo(filter_empty_lines) | 'AddMask' >> beam.Map(add_mask_to_last_word) | 'TokenizeSentence' >> beam.Map(lambda x: tokenize_sentence(x, tokenizer))\n output = text_and_tokenized_text_tuple | 'RunInference' >> RunInference(KeyedModelHandler(model_handler)) | 'ProcessOutput' >> beam.ParDo(PostProcessor(tokenizer=tokenizer))\n _ = output | 'WriteOutput' >> beam.io.WriteToText(known_args.output, shard_name_template='', append_trailing_newlines=True)\n result = pipeline.run()\n result.wait_until_finish()\n return result", "docstring": "Args:\n argv: Command line arguments defined for this example.\n save_main_session: Used for internal testing.\n test_pipeline: Used for internal testing.", "source": "github_repos"} +{"code": "def match_opcodes(opcode_traces, lineno, op_match_list):\n out = []\n for trace in opcode_traces[lineno]:\n for match_op, match_symbol in op_match_list:\n if trace.op == match_op and match_symbol in [None, trace.symbol]:\n out.append((trace.op, trace.symbol, trace.types))\n return out", "docstring": "Get all opcodes matching op_match_list on a given line.\n\nArgs:\n opcode_traces: traces\n lineno: line number to get ops from.\n op_match_list: [(opcode_name, symbol|None), ...]; None matches any symbol.\n\nReturns:\n A list of matching opcodes.", "source": "github_repos"} +{"code": "def create_pull_response(responses):\n from google.cloud import pubsub\n from google.protobuf import timestamp_pb2\n res = pubsub.types.PullResponse()\n for response in responses:\n received_message = pubsub.types.ReceivedMessage()\n message = received_message.message\n message.data = response.data\n if response.attributes is not None:\n for k, v in response.attributes.items():\n message.attributes[k] = v\n publish_time = timestamp_pb2.Timestamp()\n if response.publish_time_secs is not None:\n publish_time.seconds = response.publish_time_secs\n if response.publish_time_nanos is not None:\n publish_time.nanos = response.publish_time_nanos\n message.publish_time = publish_time\n if response.ack_id is not None:\n received_message.ack_id = response.ack_id\n res.received_messages.append(received_message)\n return res", "docstring": "Create an instance of ``google.cloud.pubsub.types.ReceivedMessage``.\n\n Used to simulate the response from pubsub.SubscriberClient().pull().\n\nArgs:\n responses: list of ``PullResponseMessage``\n\nReturns:\n An instance of ``google.cloud.pubsub.types.PullResponse`` populated with\n responses.", "source": "github_repos"} +{"code": "def from_signature(cls, sig: inspect.Signature, name: str, callable_type: CallableType, module_name: Optional[str]=None, qualname: Optional[str]=None, auto_typing: bool=False, docstr: Union[str, utils.DocStr, None]=None, parent_module: Optional[types.ModuleType]=None) -> 'Signature':\n args = []\n kwonly_args = []\n varargs = None\n varkw = None\n if isinstance(docstr, str):\n docstr = utils.DocStr.parse(docstr)\n\n def make_arg_spec(param: inspect.Parameter) -> Argument:\n \"\"\"Makes argument spec from inspect.Parameter.\"\"\"\n docstr_arg = docstr.parameter(param) if docstr else None\n return Argument.from_parameter(param, description=docstr_arg.description if docstr_arg else None, auto_typing=auto_typing, parent_module=parent_module)\n for param in sig.parameters.values():\n arg_spec = make_arg_spec(param)\n if param.kind == inspect.Parameter.POSITIONAL_ONLY or param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:\n args.append(arg_spec)\n elif param.kind == inspect.Parameter.KEYWORD_ONLY:\n kwonly_args.append(arg_spec)\n elif param.kind == inspect.Parameter.VAR_POSITIONAL:\n varargs = arg_spec\n else:\n assert param.kind == inspect.Parameter.VAR_KEYWORD, param.kind\n varkw = arg_spec\n return_value = None\n if sig.return_annotation is not inspect.Parameter.empty:\n return_value = class_schema.ValueSpec.from_annotation(sig.return_annotation, auto_typing=auto_typing, parent_module=parent_module)\n return cls(callable_type=callable_type, name=name, module_name=module_name, qualname=qualname, description=docstr.short_description if docstr else None, args=args, kwonlyargs=kwonly_args, varargs=varargs, varkw=varkw, return_value=return_value)", "docstring": "Returns PyGlove signature from Python signature.\n\nArgs:\n sig: Python signature.\n name: Name of the entity (class name or function/method name).\n callable_type: the type of this callable.\n module_name: Module name of the entity.\n qualname: (Optional) qualified name of the entity.\n auto_typing: If True, automatically convert argument annotations\n to PyGlove ValueSpec objects. Otherwise use pg.typing.Any()\n with annotations.\n docstr: (Optional) DocStr for this entity.\n parent_module: (Optional) Parent module from where the signature is\n derived. This is useful to infer classes with forward declarations.\n\nReturns:\n A PyGlove Signature object.", "source": "github_repos"} +{"code": "def _batch_prepare_for_model(self, batch_text_or_text_pairs, is_pair: Optional[bool]=None, boxes: Optional[List[List[int]]]=None, word_labels: Optional[List[List[int]]]=None, add_special_tokens: bool=True, padding_strategy: PaddingStrategy=PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy=TruncationStrategy.DO_NOT_TRUNCATE, max_length: Optional[int]=None, stride: int=0, pad_to_multiple_of: Optional[int]=None, padding_side: Optional[str]=None, return_tensors: Optional[str]=None, return_token_type_ids: Optional[bool]=None, return_attention_mask: Optional[bool]=None, return_overflowing_tokens: bool=False, return_special_tokens_mask: bool=False, return_length: bool=False, verbose: bool=True) -> BatchEncoding:\n batch_outputs = {}\n for idx, example in enumerate(zip(batch_text_or_text_pairs, boxes)):\n batch_text_or_text_pair, boxes_example = example\n outputs = self.prepare_for_model(batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair, batch_text_or_text_pair[1] if is_pair else None, boxes_example, word_labels=word_labels[idx] if word_labels is not None else None, add_special_tokens=add_special_tokens, padding=PaddingStrategy.DO_NOT_PAD.value, truncation=truncation_strategy.value, max_length=max_length, stride=stride, pad_to_multiple_of=None, padding_side=None, return_attention_mask=False, return_token_type_ids=return_token_type_ids, return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask, return_length=return_length, return_tensors=None, prepend_batch_axis=False, verbose=verbose)\n for key, value in outputs.items():\n if key not in batch_outputs:\n batch_outputs[key] = []\n batch_outputs[key].append(value)\n batch_outputs = self.pad(batch_outputs, padding=padding_strategy.value, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, padding_side=padding_side, return_attention_mask=return_attention_mask)\n batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)\n return batch_outputs", "docstring": "Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It\n adds special tokens, truncates sequences if overflowing while taking into account the special tokens and\n manages a moving window (with user defined stride) for overflowing tokens.\n\nArgs:\n batch_ids_pairs: list of tokenized input ids or input ids pairs", "source": "github_repos"} +{"code": "def _show_inputs_outputs(saved_model_dir, tag_set, signature_def_key, indent=0):\n meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set)\n _show_inputs_outputs_mgd(meta_graph_def, signature_def_key, indent)", "docstring": "Prints input and output TensorInfos.\n\n Prints the details of input and output TensorInfos for the SignatureDef mapped\n by the given signature_def_key.\n\nArgs:\n saved_model_dir: Directory containing the SavedModel to inspect.\n tag_set: Group of tag(s) of the MetaGraphDef, in string format, separated by\n ','. For tag-set contains multiple tags, all tags must be passed in.\n signature_def_key: A SignatureDef key string.\n indent: How far (in increments of 2 spaces) to indent each line of output.", "source": "github_repos"} +{"code": "def _num_image_tokens(image_size: Tuple[int, int], patch_size: Tuple[int, int]) -> int:\n height, width = image_size\n patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size)\n num_width_tokens = (width - 1) // patch_width + 1\n num_height_tokens = (height - 1) // patch_height + 1\n return (num_height_tokens, num_width_tokens)", "docstring": "Calculate the number of image tokens given the image size and patch size.\n\nArgs:\n image_size (`Tuple[int, int]`):\n The size of the image as `(height, width)`.\n patch_size (`Tuple[int, int]`):\n The patch size as `(height, width)`.\n\nReturns:\n `int`: The number of image tokens.", "source": "github_repos"} +{"code": "def _spectrum_to_circulant_2d(self, spectrum, shape, dtype):\n spectrum = _to_complex(spectrum)\n spectrum_shape = self._shape_to_spectrum_shape(shape)\n domain_dimension = spectrum_shape[-1]\n if not domain_dimension:\n return array_ops.zeros(shape, dtype)\n block_shape = spectrum_shape[-2:]\n matrix_rows = []\n for n0 in range(block_shape[0]):\n for n1 in range(block_shape[1]):\n x = np.zeros(block_shape)\n x[n0, n1] = 1.0\n fft_x = fft_ops.fft2d(math_ops.cast(x, spectrum.dtype))\n h_convolve_x = fft_ops.ifft2d(spectrum * fft_x)\n h_convolve_x = array_ops.reshape(h_convolve_x, shape[:-1])\n matrix_rows.append(h_convolve_x)\n matrix = array_ops_stack.stack(matrix_rows, axis=-1)\n return math_ops.cast(matrix, dtype)", "docstring": "Creates a block circulant matrix from a spectrum.\n\n Intentionally done in an explicit yet inefficient way. This provides a\n cross check to the main code that uses fancy reshapes.\n\nArgs:\n spectrum: Float or complex `Tensor`.\n shape: Python list. Desired shape of returned matrix.\n dtype: Type to cast the returned matrix to.\n\nReturns:\n Block circulant (batch) matrix of desired `dtype`.", "source": "github_repos"} +{"code": "def Convert(self, input_file, output_file):\n for version, schema, raw_binary, _ in self._schemas:\n try:\n data_candidate = self._Read(input_file, schema, raw_binary)\n except RuntimeError:\n continue\n if 'version' not in data_candidate:\n data_candidate['version'] = 1\n elif data_candidate['version'] == 0:\n data_candidate['version'] = 1\n if data_candidate['version'] == version:\n self._PerformUpgrade(data_candidate)\n self._Write(data_candidate, output_file)\n return\n raise RuntimeError('No schema that the converter understands worked with the data file you provided.')", "docstring": "Perform schema conversion from input_file to output_file.\n\nArgs:\n input_file: Filename of TensorFlow Lite data to convert from. Must\n be `.json` or `.bin` extension files for JSON or Binary forms of\n the TensorFlow FlatBuffer schema.\n output_file: Filename to write to. Extension also must be `.json`\n or `.bin`.\n\nRaises:\n RuntimeError: Generated when none of the upgrader supported schemas\n matche the `input_file` data.", "source": "github_repos"} +{"code": "def parallel_stack(values, name='parallel_stack'):\n if context.executing_eagerly():\n raise RuntimeError('tf.parallel_stack() is not compatible with eager execution.')\n with ops.name_scope(name):\n value_t = ops.convert_to_tensor(values[0])\n value_shape = ops.convert_to_tensor(value_t).get_shape()\n output_shape = tensor_shape.TensorShape([len(values)])\n output_shape = output_shape.concatenate(value_shape)\n return gen_array_ops.parallel_concat([expand_dims(value, 0) for value in values], shape=output_shape)", "docstring": "Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor in parallel.\n\n Requires that the shape of inputs be known at graph construction time.\n\n Packs the list of tensors in `values` into a tensor with rank one higher than\n each tensor in `values`, by packing them along the first dimension.\n Given a list of length `N` of tensors of shape `(A, B, C)`; the `output`\n tensor will have the shape `(N, A, B, C)`.\n\n For example:\n\n ```python\n x = tf.constant([1, 4])\n y = tf.constant([2, 5])\n z = tf.constant([3, 6])\n tf.parallel_stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]]\n ```\n\n The difference between `stack` and `parallel_stack` is that `stack` requires\n all the inputs be computed before the operation will begin but doesn't require\n that the input shapes be known during graph construction.\n\n `parallel_stack` will copy pieces of the input into the output as they become\n available, in some situations this can provide a performance benefit.\n\n Unlike `stack`, `parallel_stack` does NOT support backpropagation.\n\n This is the opposite of unstack. The numpy equivalent is\n\n tf.parallel_stack([x, y, z]) = np.asarray([x, y, z])\n\n @compatibility(eager)\n parallel_stack is not compatible with eager execution.\n @end_compatibility\n\nArgs:\n values: A list of `Tensor` objects with the same shape and type.\n name: A name for this operation (optional).\n\nReturns:\n output: A stacked `Tensor` with the same type as `values`.\n\nRaises:\n RuntimeError: if executed in eager mode.", "source": "github_repos"} +{"code": "def __init__(self, config: XLNetConfig):\n super().__init__()\n self.summary_type = getattr(config, 'summary_type', 'last')\n if self.summary_type == 'attn':\n raise NotImplementedError\n self.summary = nn.Identity()\n if hasattr(config, 'summary_use_proj') and config.summary_use_proj:\n if hasattr(config, 'summary_proj_to_labels') and config.summary_proj_to_labels and (config.num_labels > 0):\n num_classes = config.num_labels\n else:\n num_classes = config.hidden_size\n self.summary = nn.Linear(config.hidden_size, num_classes)\n activation_string = getattr(config, 'summary_activation', None)\n self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()\n self.first_dropout = nn.Identity()\n if hasattr(config, 'summary_first_dropout') and config.summary_first_dropout > 0:\n self.first_dropout = nn.Dropout(config.summary_first_dropout)\n self.last_dropout = nn.Identity()\n if hasattr(config, 'summary_last_dropout') and config.summary_last_dropout > 0:\n self.last_dropout = nn.Dropout(config.summary_last_dropout)", "docstring": "Compute a single vector summary of a sequence hidden states.\n\nArgs:\n config ([`XLNetConfig`]):\n The config used by the model. Relevant arguments in the config class of the model are (refer to the actual\n config class of your model for the default values it uses):\n\n - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:\n\n - `\"last\"` -- Take the last token hidden state (like XLNet)\n - `\"first\"` -- Take the first token hidden state (like Bert)\n - `\"mean\"` -- Take the mean of all tokens hidden states\n - `\"cls_index\"` -- Supply a Tensor of classification token position (GPT/GPT-2)\n - `\"attn\"` -- Not implemented now, use multi-head attention\n\n - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.\n - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes\n (otherwise to `config.hidden_size`).\n - **summary_activation** (`Optional[str]`) -- Set to `\"tanh\"` to add a tanh activation to the output,\n another string or `None` will add no activation.\n - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.\n - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.", "source": "github_repos"} +{"code": "def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) -> List[int]:\n if already_has_special_tokens:\n return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)\n result = [1] + [0] * len(token_ids_0) + [1]\n if token_ids_1 is not None:\n result += [0] * len(token_ids_1) + [1]\n return result", "docstring": "Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding\n special tokens using the tokenizer `prepare_for_model` method.\n\nArgs:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n already_has_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not the token list is already formatted with special tokens for the model.\n\nReturns:\n `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.", "source": "github_repos"} +{"code": "def int_shape(x):\n try:\n shape = x.shape\n if not isinstance(shape, tuple):\n shape = tuple(shape.as_list())\n return shape\n except ValueError:\n return None", "docstring": "Returns the shape of tensor or variable as a tuple of int or None entries.\n\nArgs:\n x: Tensor or variable.\n\nReturns:\n A tuple of integers (or None entries).\n\nExample:\n >>> input = tf.keras.backend.placeholder(shape=(2, 4, 5))\n >>> tf.keras.backend.int_shape(input)\n (2, 4, 5)\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = tf.keras.backend.variable(value=val)\n >>> tf.keras.backend.int_shape(kvar)\n (2, 2)", "source": "github_repos"} +{"code": "def _from_nested_row_partitions(cls, flat_values, nested_row_partitions, name=None, validate=True):\n if not isinstance(validate, bool):\n raise TypeError(f'Argument `validate` must have type bool. Received {validate}.')\n if isinstance(nested_row_partitions, RowPartition):\n raise TypeError(f'Argument `nested_row_partitions` must be a list of RowPartitions. Received {nested_row_partitions}.')\n if isinstance(nested_row_partitions, tensor_lib.Tensor):\n raise TypeError(f'Argument `nested_row_partitions` must be a list of RowPartitions. Received {nested_row_partitions}.')\n with ops.name_scope(name, 'RaggedFromNestedRowPartitions', [flat_values] + list(nested_row_partitions)):\n result = flat_values\n for partition in reversed(nested_row_partitions):\n result = cls._from_row_partition(result, partition, validate=validate)\n return result", "docstring": "Creates a `RaggedTensor` from a nested list of row partitions.\n\n Equivalent to:\n\n ```python\n result = flat_values\n for row_partition in reversed(nested_row_partitions):\n result = _from_row_partition(result, row_partition)\n ```\n\nArgs:\n flat_values: A potentially ragged tensor.\n nested_row_partitions: A list of row partitions. The `i`th element is\n used as the row partition for the `i`th ragged dimension.\n name: A name prefix for the RaggedTensor (optional).\n validate: If true, then use assertions to check that the arguments form\n a valid `RaggedTensor`. Note: these assertions incur a runtime cost,\n since they must be checked for each tensor value.\n\nReturns:\n A `RaggedTensor` (or `flat_values` if `nested_row_lengths` is empty).", "source": "github_repos"} +{"code": "def is_torch_support_available(self) -> bool:\n if is_torch_available():\n from transformers.utils import get_torch_version\n return version.parse(get_torch_version()) >= self.torch_onnx_minimum_version\n else:\n return False", "docstring": "The minimum PyTorch version required to export the model.\n\nReturns:\n `bool`: Whether the installed version of PyTorch is compatible with the model.", "source": "github_repos"} +{"code": "def generate(self, pixel_values: torch.FloatTensor, qformer_input_ids: Optional[torch.LongTensor]=None, qformer_attention_mask: Optional[torch.LongTensor]=None, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.LongTensor]=None, interpolate_pos_encoding: bool=False, **generate_kwargs) -> torch.LongTensor:\n if hasattr(self, 'hf_device_map'):\n self._preprocess_accelerate()\n batch_size = pixel_values.shape[0]\n language_model_inputs, vision_outputs, query_outputs = self.get_image_features(pixel_values, qformer_input_ids=qformer_input_ids, qformer_attention_mask=qformer_attention_mask, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=True)\n language_attention_mask = torch.ones(language_model_inputs.size()[:-1], dtype=torch.long, device=language_model_inputs.device)\n if input_ids is None:\n start_tokens = [self.config.text_config.bos_token_id]\n if getattr(self.config, 'image_token_id', None) is not None:\n start_tokens = [self.config.image_token_id] * self.config.num_query_tokens + start_tokens\n input_ids = torch.tensor([start_tokens], dtype=torch.long, device=pixel_values.device)\n input_ids = input_ids.repeat(batch_size, 1)\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n inputs_embeds = self.get_input_embeddings()(input_ids)\n if getattr(self.config, 'image_token_id', None) is not None:\n special_image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)\n inputs_embeds[special_image_mask] = language_model_inputs.flatten().to(inputs_embeds.device)\n else:\n logger.warning_once('Expanding inputs for image tokens in InstructBLIP should be done in processing. Please follow instruction here (https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042) to update your InstructBLIP model. Using processors without these attributes in the config is deprecated and will throw an error in v4.50.')\n inputs_embeds = torch.cat([language_model_inputs, inputs_embeds.to(language_model_inputs.device)], dim=1)\n attention_mask = torch.cat([language_attention_mask, attention_mask.to(language_attention_mask.device)], dim=1)\n if not self.language_model.config.is_encoder_decoder:\n generate_kwargs['max_length'] = generate_kwargs.get('max_length', 20) + language_model_inputs.shape[1] - 1\n generate_kwargs['min_length'] = generate_kwargs.get('min_length', 0) + language_model_inputs.shape[1]\n inputs = {'inputs_embeds': inputs_embeds, 'attention_mask': attention_mask}\n if not self.language_model.config.is_encoder_decoder:\n inputs['input_ids'] = input_ids\n outputs = self.language_model.generate(**inputs, **generate_kwargs)\n return outputs", "docstring": "Overrides `generate` function to be able to use the model as a conditional generator.\n\nArgs:\n pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):\n Input images to be processed.\n qformer_input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n The sequence used as a prompt to be fed to the Q-Former module.\n qformer_attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n Mask to avoid performing attention on padding token indices.\n input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n The sequence used as a prompt for the generation.\n attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n Mask to avoid performing attention on padding token indices.\n interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):\n Whether to interpolate the positional encoding of the image embeddings.\n\nReturns:\n captions (list): A list of strings of length batch_size * num_captions.", "source": "github_repos"} +{"code": "def configure_callbacks(callbacks, model, do_validation=False, batch_size=None, epochs=None, steps_per_epoch=None, samples=None, verbose=1, count_mode='steps', mode=ModeKeys.TRAIN):\n if isinstance(callbacks, CallbackList):\n return callbacks\n if not callbacks:\n callbacks = []\n if mode == ModeKeys.TRAIN:\n model.history = History()\n callbacks = [BaseLogger()] + (callbacks or []) + [model.history]\n if verbose:\n callbacks.append(ProgbarLogger(count_mode))\n callback_list = CallbackList(callbacks)\n callback_model = model._get_callback_model()\n callback_list.set_model(callback_model)\n set_callback_parameters(callback_list, model, do_validation=do_validation, batch_size=batch_size, epochs=epochs, steps_per_epoch=steps_per_epoch, samples=samples, verbose=verbose, mode=mode)\n callback_list.model.stop_training = False\n return callback_list", "docstring": "Configures callbacks for use in various training loops.\n\nArgs:\n callbacks: List of Callbacks.\n model: Model being trained.\n do_validation: Whether or not validation loop will be run.\n batch_size: Number of samples per batch.\n epochs: Number of epoch to train.\n steps_per_epoch: Number of batches to run per training epoch.\n samples: Number of training samples.\n verbose: int, 0 or 1. Keras logging verbosity to pass to ProgbarLogger.\n count_mode: One of 'steps' or 'samples'. Per-batch or per-sample count.\n mode: String. One of ModeKeys.TRAIN, ModeKeys.TEST, or ModeKeys.PREDICT.\n Which loop mode to configure callbacks for.\n\nReturns:\n Instance of CallbackList used to control all Callbacks.", "source": "github_repos"} +{"code": "def _infer_var_name(var):\n name_to_var_dict = saveable_object_util.op_list_to_dict(var)\n if len(name_to_var_dict) > 1:\n raise TypeError('`var` = %s passed as arg violates the constraints. name_to_var_dict = %s' % (var, name_to_var_dict))\n return list(name_to_var_dict.keys())[0]", "docstring": "Returns name of the `var`.\n\nArgs:\n var: A list. The list can contain either of the following:\n (i) A single `Variable`\n (ii) A single `ResourceVariable`\n (iii) Multiple `Variable` objects which must be slices of the same larger\n variable.\n (iv) A single `PartitionedVariable`\n\nReturns:\n Name of the `var`", "source": "github_repos"} +{"code": "def _lookup_tensor_name(self, tensor):\n return self._tensor_aliases.get(tensor.name, tensor.name)", "docstring": "Look up the name of a graph tensor.\n\n This method maps the name of a debugger-generated Identity or\n DebugIdentityV2 tensor to the name of the original instrumented tensor,\n if `tensor` is such a debugger-created tensor.\n Otherwise, it returns the name of `tensor` as is.\n\nArgs:\n tensor: The graph tensor to look up the name for.\n\nReturns:\n Name of the original instrumented tensor as known to the debugger.", "source": "github_repos"} +{"code": "def trace_tpu(self, graph, tensor_fetches, op_fetches=None, num_replicas=None, num_replicas_per_host=None, num_hosts=None):\n if isinstance(graph, func_graph.FuncGraph) or isinstance(graph, function._FuncGraph):\n logging.warning('Tensor Tracer is not supported for tracing FuncGraphs. Ignoring tracing.')\n return tensor_fetches\n if graph in TensorTracer._traced_graphs:\n logging.warning('Graph is already rewritten with tensor tracer, ignoring multiple calls.')\n return tensor_fetches\n else:\n TensorTracer._traced_graphs.add(graph)\n self._parameters = tensor_tracer_flags.TTParameters()\n self._tt_config.device_type = _DEVICE_TYPE_TPU\n self._tt_config.num_replicas = num_replicas\n self._tt_config.num_replicas_per_host = num_replicas_per_host\n self._tt_config.num_hosts = num_hosts\n if self._tt_config.num_replicas is not None:\n if self._tt_config.num_replicas_per_host is None:\n self._tt_config.num_replicas_per_host = 8\n if self._tt_config.num_hosts is None:\n self._tt_config.num_hosts = num_replicas // self._tt_config.num_replicas_per_host + (num_replicas % self._tt_config.num_replicas_per_host > 0)\n if self._parameters.graph_dump_path:\n graph_io.write_graph(graph, self._parameters.graph_dump_path, 'graph_before_tt.pbtxt')\n with graph.as_default():\n self._add_replica_id_to_graph()\n tensor_fetches = self._trace_execution(graph, tensor_fetches, op_fetches, on_tpu=True)\n if self._parameters.graph_dump_path:\n graph_io.write_graph(graph, self._parameters.graph_dump_path, 'graph_after_tt.pbtxt')\n return tensor_fetches", "docstring": "Traces the tensors generated by TPU Ops in a TF graph.\n\nArgs:\n graph: the graph of Ops executed on the TPU.\n tensor_fetches: a (list,tuple,or a single object) of tensor fetches\n returned by model_fn given to session.run. Function must be provided\n with as least one tensor to fetch.\n op_fetches: A list of op fetches returned by model_fn given to\n session.run. op_fetches and tensor_fetches are used to determine the\n nodes that will be executed. Can be None.\n num_replicas: number of replicas used on the TPU.\n num_replicas_per_host: number of replicas per TPU host.\n num_hosts: total number of TPU hosts.\n\nReturns:\n tensor_fetches: an exact copy of tensor_fetches that has additional\n dependencies.", "source": "github_repos"} +{"code": "def __init__(self, dataset_file_map: Mapping[str, _RepresentativeDatasetFile]) -> None:\n self.dataset_file_map = dataset_file_map", "docstring": "Initializes TFRecord represenatative dataset loader.\n\nArgs:\n dataset_file_map: Signature key -> `RepresentativeDatasetFile` mapping.\n\nRaises:\n DecodeError: If the sample is not RepresentativeDataSample.", "source": "github_repos"} +{"code": "def __init__(self, reduction='sum_over_batch_size', name='categorical_hinge', dtype=None):\n super().__init__(categorical_hinge, name=name, reduction=reduction, dtype=dtype)", "docstring": "Computes the categorical hinge loss between `y_true` & `y_pred`.\n\n Formula:\n\n ```python\n loss = maximum(neg - pos + 1, 0)\n ```\n\n where `neg=maximum((1-y_true)*y_pred)` and `pos=sum(y_true*y_pred)`\n\nArgs:\n reduction: Type of reduction to apply to the loss. In almost all cases\n this should be `\"sum_over_batch_size\"`. Supported options are\n `\"sum\"`, `\"sum_over_batch_size\"`, `\"mean\"`,\n `\"mean_with_sample_weight\"` or `None`. `\"sum\"` sums the loss,\n `\"sum_over_batch_size\"` and `\"mean\"` sum the loss and divide by the\n sample size, and `\"mean_with_sample_weight\"` sums the loss and\n divides by the sum of the sample weights. `\"none\"` and `None`\n perform no aggregation. Defaults to `\"sum_over_batch_size\"`.\n name: Optional name for the loss instance.\n dtype: The dtype of the loss's computations. Defaults to `None`, which\n means using `keras.backend.floatx()`. `keras.backend.floatx()` is a\n `\"float32\"` unless set to different value\n (via `keras.backend.set_floatx()`). If a `keras.DTypePolicy` is\n provided, then the `compute_dtype` will be utilized.", "source": "github_repos"} +{"code": "def make_ordered_column_names(include_label=True):\n result = ['clicked'] if include_label else []\n for name in _INTEGER_COLUMN_NAMES:\n result.append(name)\n for name in _CATEGORICAL_COLUMN_NAMES:\n result.append(name)\n return result", "docstring": "Returns the column names in the dataset in the order as they appear.\n\nArgs:\n include_label: Indicates whether the label feature should be included.\n\nReturns:\n A list of column names in the dataset.", "source": "github_repos"} +{"code": "def _post_process(self, feed_item, new_item):\n for third_party_url in feed_item.get('third_party_urls', []):\n third_party_url[FieldMap.CREATIVE_ID] = new_item['id']\n third_party_url[FieldMap.CREATIVE_NAME] = new_item['name']\n for association in feed_item.get('associations', []):\n association[FieldMap.CREATIVE_ID] = self.get(association)['id']\n association[FieldMap.CREATIVE_NAME] = self.get(association)['name']\n dcm_association = self.creative_asset_dao.get(association, required=True)\n if dcm_association:\n association[FieldMap.CREATIVE_ASSET_ID] = dcm_association.get('id', None)\n association[FieldMap.CREATIVE_ASSET_NAME] = dcm_association.get('name', None)\n backup_lp = self.landing_page_dao.get(feed_item, column_name=FieldMap.BACKUP_IMAGE_CLICK_THROUGH_LANDING_PAGE_ID)\n if backup_lp:\n association[FieldMap.BACKUP_IMAGE_CLICK_THROUGH_LANDING_PAGE_ID] = backup_lp['id']\n association[FieldMap.BACKUP_IMAGE_CLICK_THROUGH_LANDING_PAGE_NAME] = backup_lp['name']\n backup_asset = self.creative_asset_dao.get(association, column_name=FieldMap.CREATIVE_BACKUP_ASSET_ID)\n if backup_asset:\n association[FieldMap.CREATIVE_BACKUP_ASSET_ID] = backup_asset['id']\n for click_tag in feed_item.get('click_tags', []):\n click_tag[FieldMap.CREATIVE_ID] = new_item['id']\n click_tag[FieldMap.CREATIVE_NAME] = new_item['name']\n click_tag_lp = self.landing_page_dao.get(click_tag, column_name=FieldMap.CLICK_TAG_LANDING_PAGE_ID)\n if click_tag_lp:\n click_tag[FieldMap.CLICK_TAG_LANDING_PAGE_ID] = click_tag_lp['id']\n click_tag[FieldMap.CLICK_TAG_LANDING_PAGE_NAME] = click_tag_lp['name']\n backup_asset = self.creative_asset_dao.get(feed_item, column_name=FieldMap.CREATIVE_BACKUP_ASSET_ID)\n if backup_asset:\n feed_item[FieldMap.CREATIVE_BACKUP_ASSET_ID] = backup_asset['id']\n backup_lp = self.landing_page_dao.get(feed_item, column_name=FieldMap.BACKUP_IMAGE_CLICK_THROUGH_LANDING_PAGE_ID)\n if backup_lp:\n feed_item[FieldMap.BACKUP_IMAGE_CLICK_THROUGH_LANDING_PAGE_ID] = backup_lp['id']\n feed_item[FieldMap.BACKUP_IMAGE_CLICK_THROUGH_LANDING_PAGE_NAME] = backup_lp['name']", "docstring": "Maps ids and names of related entities so they can be updated in the Bulkdozer feed.\n\n When Bulkdozer is done processing an item, it writes back the updated names\n and ids of related objects, this method makes sure those are updated in the\n creative feed.\n\nArgs:\n feed_item: Feed item representing the creative from the Bulkdozer feed.\n item: The DCM creative being updated or created.", "source": "github_repos"} +{"code": "def str_of_constant(self, printer: 'Callable[[_base.BaseValue], str]') -> str:\n del printer\n return repr(self.pyval)", "docstring": "Get a string representation of this constant.\n\nArgs:\n printer: A BaseValue -> str function that will be used to print abstract\n values.\n\nReturns:\n A string of self.pyval.", "source": "github_repos"} +{"code": "def sample(self, num_samples: int):\n return self._sample(num_samples)", "docstring": "Returns samples from the EBM corresponding to `self.energy`.\n\nArgs:\n num_samples: Number of samples to draw from the EBM.", "source": "github_repos"} +{"code": "def __init__(self, caption, content, enabled=True):\n self._caption = caption\n self._content = content\n self._enabled = enabled", "docstring": "Menu constructor.\n\n TODO(cais): Nested menu is currently not supported. Support it.\n\nArgs:\n caption: (str) caption of the menu item.\n content: Content of the menu item. For a menu item that triggers\n a command, for example, content is the command string.\n enabled: (bool) whether this menu item is enabled.", "source": "github_repos"} +{"code": "def from_dict(cls, config_dict: dict[str, Any], **kwargs) -> 'PretrainedConfig':\n return_unused_kwargs = kwargs.pop('return_unused_kwargs', False)\n kwargs.pop('_from_auto', None)\n kwargs.pop('_from_pipeline', None)\n if '_commit_hash' in kwargs and '_commit_hash' in config_dict:\n kwargs['_commit_hash'] = config_dict['_commit_hash']\n config_dict['attn_implementation'] = kwargs.pop('attn_implementation', None)\n config = cls(**config_dict)\n if hasattr(config, 'pruned_heads'):\n config.pruned_heads = {int(key): value for key, value in config.pruned_heads.items()}\n if 'num_labels' in kwargs and 'id2label' in kwargs:\n num_labels = kwargs['num_labels']\n id2label = kwargs['id2label'] if kwargs['id2label'] is not None else []\n if len(id2label) != num_labels:\n raise ValueError(f'You passed along `num_labels={num_labels}` with an incompatible id to label map: {kwargs['id2label']}. Since those arguments are inconsistent with each other, you should remove one of them.')\n to_remove = []\n for key, value in kwargs.items():\n if hasattr(config, key):\n current_attr = getattr(config, key)\n if isinstance(current_attr, PretrainedConfig) and isinstance(value, dict):\n value = current_attr.__class__(**value)\n setattr(config, key, value)\n if key != 'torch_dtype':\n to_remove.append(key)\n for key in to_remove:\n kwargs.pop(key, None)\n logger.info(f'Model config {config}')\n if return_unused_kwargs:\n return (config, kwargs)\n else:\n return config", "docstring": "Instantiates a [`PretrainedConfig`] from a Python dictionary of parameters.\n\nArgs:\n config_dict (`Dict[str, Any]`):\n Dictionary that will be used to instantiate the configuration object. Such a dictionary can be\n retrieved from a pretrained checkpoint by leveraging the [`~PretrainedConfig.get_config_dict`] method.\n kwargs (`Dict[str, Any]`):\n Additional parameters from which to initialize the configuration object.\n\nReturns:\n [`PretrainedConfig`]: The configuration object instantiated from those parameters.", "source": "github_repos"} +{"code": "def get_task_states(self, job_configs):\n if self._context_handle:\n job_names, task_nums = zip(*job_configs)\n return pywrap_tfe.TFE_GetTaskStates(self._context_handle, job_names, task_nums)\n else:\n raise ValueError('Context is not initialized.')", "docstring": "Get task states from the Coordination Service.\n\nArgs:\n job_configs: A list of tuples of job name and task number.\n\nReturns:\n A list of TF_Status.", "source": "github_repos"} +{"code": "def device_name(self):\n return self._device_name", "docstring": "Name of the device that the tensor belongs to.\n\nReturns:\n (`str`) device name.", "source": "github_repos"} +{"code": "def sandbox_call(func: Callable[..., Any], *args, timeout: Optional[float]=None, **kwargs) -> Any:\n\n def _call(q, *args, **kwargs):\n\n def _run():\n r = func(*args, **kwargs)\n try:\n return pickle.dumps(r)\n except BaseException as e:\n raise errors.SerializationError(f'Cannot serialize sandbox result: {r}', e) from e\n try:\n q.put(_run())\n except Exception as e:\n q.put(e)\n q = multiprocessing.Queue()\n p = multiprocessing.Process(target=_call, args=tuple([q] + list(args)), kwargs=kwargs)\n try:\n p.start()\n x = q.get(timeout=timeout)\n except queue.Empty as e:\n if p.is_alive():\n p.kill()\n raise TimeoutError(f'Execution time exceed {timeout} seconds.') from e\n finally:\n q.close()\n if isinstance(x, Exception):\n raise x\n try:\n return pickle.loads(x)\n except Exception as e:\n raise errors.SerializationError('Cannot deserialize the output from sandbox.', e) from e", "docstring": "Calls a function with sandboxing.\n\nArgs:\n func: Function to call.\n *args: Positional arguments for `func`\n timeout: Execution timeout in seconds. If None, wait `func` to complete.\n **kwargs: Keyword arguments for `func`.\n\nReturns:\n Return value from `func`.\n\nRaises:\n TimeoutError: If the execution time exceeds the timeout.\n Exception: Exception raised from `func`.", "source": "github_repos"} +{"code": "def forward(self, inputs_embeds, attention_mask: Optional[torch.Tensor]=None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **kwargs: Unpack[FlashAttentionKwargs]) -> Union[Tuple, BaseModelOutput]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n encoder_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None\n hidden_states = inputs_embeds\n for encoder_layer in self.layers:\n if output_hidden_states:\n encoder_states = encoder_states + (hidden_states,)\n if self.gradient_checkpointing and self.training:\n layer_outputs = self._gradient_checkpointing_func(encoder_layer.__call__, hidden_states, attention_mask, position_embeddings, output_attentions)\n else:\n layer_outputs = encoder_layer(hidden_states, attention_mask, position_embeddings=position_embeddings, output_attentions=output_attentions, **kwargs)\n hidden_states = layer_outputs[0]\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n if output_hidden_states:\n encoder_states = encoder_states + (hidden_states,)\n if not return_dict:\n return tuple((v for v in [hidden_states, encoder_states, all_attentions] if v is not None))\n return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)", "docstring": "Args:\n inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Embeddings which serve as input to the Transformer.\n attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.", "source": "github_repos"} +{"code": "def variable_op_v2(shape, dtype, name='Variable', container='', shared_name=''):\n return gen_state_ops.variable_v2(shape=shape, dtype=dtype, name=name, container=container, shared_name=shared_name)", "docstring": "Create a variable Operation.\n\n See also variables.Variable.\n\nArgs:\n shape: The shape of the tensor managed by this variable\n dtype: The underlying type of the tensor values.\n name: optional name to use for the variable op.\n container: An optional string. Defaults to \"\".\n If non-empty, this variable is placed in the given container.\n Otherwise, a default container is used.\n shared_name: An optional string. Defaults to \"\".\n If non-empty, this variable is named in the given bucket\n with this shared_name. Otherwise, the node name is used instead.\n\nReturns:\n A variable tensor.", "source": "github_repos"} +{"code": "def get_change_point_config(params: Dict[str, Any]) -> ChangePointConfig:\n return ChangePointConfig(min_runs_between_change_points=params.get('min_runs_between_change_points', constants._DEFAULT_MIN_RUNS_BETWEEN_CHANGE_POINTS), num_runs_in_change_point_window=params.get('num_runs_in_change_point_window', constants._DEFAULT_NUM_RUMS_IN_CHANGE_POINT_WINDOW))", "docstring": "Args:\n params: Dict containing parameters to run change point analysis.\n\nReturns:\n ChangePointConfig object containing change point analysis parameters.", "source": "github_repos"} +{"code": "def most_specific_common_supertype(self, others: Sequence[trace.TraceType]) -> Optional['TensorShape']:\n if any((not isinstance(other, TensorShape) for other in others)):\n return None\n if self.rank is None:\n return unknown_shape()\n if any((other.dims is None or self.rank != other.rank for other in others)):\n return unknown_shape()\n dims = [dim if all((dim == other._dims[i] for other in others)) else None for i, dim in enumerate(self._dims)]\n return TensorShape(dims)", "docstring": "Returns the most specific supertype `TensorShape` of self and others.\n\n * `TensorShape([None, 1])` is the most specific `TensorShape` supertyping\n both `TensorShape([2, 1])` and `TensorShape([5, 1])`. Note that\n `TensorShape(None)` is also a supertype but it is not \"most specific\".\n\n * `TensorShape([1, 2, 3])` is the most specific `TensorShape` supertyping\n both `TensorShape([1, 2, 3])` and `TensorShape([1, 2, 3]`). There are\n other less specific TensorShapes that supertype above mentioned\n TensorShapes, e.g. `TensorShape([1, 2, None])`, `TensorShape(None)`.\n\n * `TensorShape([None, None])` is the most specific `TensorShape`\n supertyping both `TensorShape([2, None])` and `TensorShape([None, 3])`.\n As always, `TensorShape(None)` is also a supertype but not the most\n specific one.\n\n * `TensorShape(None`) is the only `TensorShape` supertyping both\n `TensorShape([1, 2, 3])` and `TensorShape([1, 2])`. In general, any two\n shapes that have different ranks will only have `TensorShape(None)`\n as a common supertype.\n\n * `TensorShape(None)` is the only `TensorShape` supertyping both\n `TensorShape([1, 2, 3])` and `TensorShape(None)`. In general, the common\n supertype of any shape with `TensorShape(None)` is `TensorShape(None)`.\n\nArgs:\n others: Sequence of `TensorShape`.\n\nReturns:\n A `TensorShape` which is the most specific supertype shape of `self`\n and `others`. None if it does not exist.", "source": "github_repos"} +{"code": "def ConvNeXtBlock(projection_dim, drop_path_rate=0.0, layer_scale_init_value=1e-06, name=None):\n if name is None:\n name = 'prestem' + str(backend.get_uid('prestem'))\n\n def apply(inputs):\n x = inputs\n x = layers.Conv2D(filters=projection_dim, kernel_size=7, padding='same', groups=projection_dim, name=name + '_depthwise_conv')(x)\n x = layers.LayerNormalization(epsilon=1e-06, name=name + '_layernorm')(x)\n x = layers.Dense(4 * projection_dim, name=name + '_pointwise_conv_1')(x)\n x = layers.Activation('gelu', name=name + '_gelu')(x)\n x = layers.Dense(projection_dim, name=name + '_pointwise_conv_2')(x)\n if layer_scale_init_value is not None:\n x = LayerScale(layer_scale_init_value, projection_dim, name=name + '_layer_scale')(x)\n if drop_path_rate:\n layer = StochasticDepth(drop_path_rate, name=name + '_stochastic_depth')\n else:\n layer = layers.Activation('linear', name=name + '_identity')\n return inputs + layer(x)\n return apply", "docstring": "ConvNeXt block.\n\n References:\n - https://arxiv.org/abs/2201.03545\n - https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py\n\nNote:\n In the original ConvNeXt implementation (linked above), the authors use\n `Dense` layers for pointwise convolutions for increased efficiency.\n Following that, this implementation also uses the same.\n\nArgs:\n projection_dim (int): Number of filters for convolution layers. In the\n ConvNeXt paper, this is referred to as projection dimension.\n drop_path_rate (float): Probability of dropping paths. Should be within\n [0, 1].\n layer_scale_init_value (float): Layer scale value.\n Should be a small float number.\n name: name to path to the keras layer.\n\nReturns:\n A function representing a ConvNeXtBlock block.", "source": "github_repos"} +{"code": "def value_container(val):\n container = None\n if not isinstance(val, values_lib.DistributedVariable):\n if hasattr(val, '_distributed_container'):\n container = val._distributed_container()\n elif isinstance(val, composite_tensor.CompositeTensor) and hasattr(val, 'handle') and hasattr(val.handle, '_distributed_container'):\n container = val.handle._distributed_container()\n return container if container is not None else val", "docstring": "Returns the container that this per-replica `value` belongs to.\n\nArgs:\n val: A value returned by `call_for_each_replica()` or a variable created in\n `scope()`.\n\nReturns:\n A container that `value` belongs to.\n If value does not belong to any container (including the case of\n container having been destroyed), returns the value itself.", "source": "github_repos"} +{"code": "def __init__(self, pool_size, strides, padding='valid', data_format='channels_last', name=None, **kwargs):\n if strides is None:\n raise ValueError('Argument `strides` must not be None.')\n super(MaxPooling2D, self).__init__(pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, name=name, **kwargs)", "docstring": "Max pooling layer for 2D inputs (e.g. images).\n\nArgs:\n pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width)\n specifying the size of the pooling window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the pooling operation.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n padding: A string. The padding method, either 'valid' or 'same'.\n Case-insensitive.\n data_format: A string. The ordering of the dimensions in the inputs.\n `channels_last` (default) and `channels_first` are supported.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, height, width)`.\n name: A string, the name of the layer.", "source": "github_repos"} +{"code": "def upsample_filters(filters, rate):\n num_spatial_dims = len(rate)\n spatial_shape = np.array(filters.shape[:num_spatial_dims])\n output_spatial_shape = (spatial_shape - 1) * rate + 1\n output = np.zeros(tuple(output_spatial_shape) + tuple(filters.shape[-2:]), filters.dtype)\n output[tuple((np.s_[::rate[i]] for i in range(num_spatial_dims)))] = filters\n return output", "docstring": "Upsamples the filters by a factor of rate along the spatial dimensions.\n\nArgs:\n filters: spatial_shape + [in_channels, out_channels]\n Original filters.\n rate: A list of len(spatial_shape) positive ints, specifying the\n upsampling rate.\n\nReturns:\n filters_up: output_spatial_shape + [in_channels, out_channels].\n Upsampled filters with\n output_spatial_shape[i] = (spatial_shape[i] - 1) * rate[i] + 1\n containing (rate[i] - 1) zeros between consecutive filter values along\n spatial dimension i.", "source": "github_repos"} +{"code": "def __init__(self, features, location_id=None, metadata=None, timeout=120, context_side_input=None):\n super().__init__()\n self.features = features\n self.location_id = location_id\n self.metadata = metadata\n self.timeout = timeout\n self.context_side_input = context_side_input", "docstring": "Args:\n features: (List[``videointelligence_v1.Feature``]) Required.\n The Video Intelligence API features to detect\n location_id: (str) Optional.\n Cloud region where annotation should take place.\n If no region is specified, a region will be determined\n based on video file location.\n metadata: (Sequence[Tuple[str, str]]) Optional.\n Additional metadata that is provided to the method.\n timeout: (int) Optional.\n The time in seconds to wait for the response from the\n Video Intelligence API\n context_side_input: (beam.pvalue.AsDict) Optional.\n An ``AsDict`` of a PCollection to be passed to the\n _VideoAnnotateFn as the video context mapping containing additional\n video context and/or feature-specific parameters.\n Example usage::\n\n video_contexts =\n [('gs://cloud-samples-data/video/cat.mp4', Union[dict,\n ``videointelligence_v1.VideoContext``]),\n ('gs://some-other-video/sample.mp4', Union[dict,\n ``videointelligence_v1.VideoContext``]),]\n\n context_side_input =\n (\n p\n | \"Video contexts\" >> beam.Create(video_contexts)\n )\n\n videointelligenceml.AnnotateVideo(features,\n context_side_input=beam.pvalue.AsDict(context_side_input)))", "source": "github_repos"} +{"code": "def _search_for_child_node(self, parent_id, path_to_child):\n if not path_to_child:\n return parent_id\n for child in self._proto.nodes[parent_id].children:\n if child.local_name == path_to_child[0]:\n return self._search_for_child_node(child.node_id, path_to_child[1:])\n return None", "docstring": "Returns node id of child node.\n\n A helper method for traversing the object graph proto.\n\n As an example, say that the object graph proto in the SavedModel contains an\n object with the following child and grandchild attributes:\n\n `parent.child_a.child_b`\n\n This method can be used to retrieve the node id of `child_b` using the\n parent's node id by calling:\n\n `_search_for_child_node(parent_id, ['child_a', 'child_b'])`.\n\nArgs:\n parent_id: node id of parent node\n path_to_child: list of children names.\n\nReturns:\n node_id of child, or None if child isn't found.", "source": "github_repos"} +{"code": "def _get_summary_signatures(self):\n signatures = self._flag_value_as_list(FLAG_NAME_SUMMARY_SIGNATURES)\n supported_signatures = self._supported_signatures()\n tt_signatures = []\n for signature in signatures:\n signature_with_prefix = '%s_%s' % (_TT_PREFIX, signature)\n if signature in supported_signatures:\n tt_signatures.append(signature)\n elif signature_with_prefix in supported_signatures:\n tt_signatures.append(signature_with_prefix)\n else:\n logging.warning('Unknown signature:%s. Supported signatures: %s' % (signature, supported_signatures))\n if not tt_signatures:\n return {TT_SUMMARY_MAX_ABS: 0, TT_SUMMARY_NORM: 1}\n else:\n return {signature: idx for idx, signature in enumerate(tt_signatures)}", "docstring": "Verifies and returns the summary signatures.\n\nReturns:\n A dictionary of the signature identifiers {signature: index} that will be\n computed when trace_mode is summary.", "source": "github_repos"} +{"code": "def _filter_out_metaclasses(bases, ctx):\n non_meta = []\n meta = None\n for base in bases:\n with_metaclass = False\n for b in base.data:\n if isinstance(b, metaclass.WithMetaclassInstance):\n with_metaclass = True\n if not meta:\n meta = b.cls.to_variable(ctx.root_node)\n non_meta.extend(b.bases)\n if not with_metaclass:\n non_meta.append(base)\n return (meta, non_meta)", "docstring": "Process the temporary classes created by six.with_metaclass.\n\n six.with_metaclass constructs an anonymous class holding a metaclass and a\n list of base classes; if we find instances in `bases`, store the first\n metaclass we find and remove all metaclasses from `bases`.\n\nArgs:\n bases: The list of base classes for the class being constructed.\n ctx: The current context.\n\nReturns:\n A tuple of (metaclass, base classes)", "source": "github_repos"} +{"code": "def broadcast_dynamic_shape(shape_x, shape_y):\n if not isinstance(shape_x, RaggedTensorDynamicShape):\n raise TypeError('shape_x must be a RaggedTensorDynamicShape')\n if not isinstance(shape_y, RaggedTensorDynamicShape):\n raise TypeError('shape_y must be a RaggedTensorDynamicShape')\n if shape_x.rank is None or shape_y.rank is None:\n raise ValueError('Unable to broadcast: unknown rank')\n broadcast_rank = max(shape_x.rank, shape_y.rank)\n shape_x = shape_x.broadcast_to_rank(broadcast_rank)\n shape_y = shape_y.broadcast_to_rank(broadcast_rank)\n for axis in range(broadcast_rank):\n shape_x = shape_x.broadcast_dimension(axis, shape_y.dimension_size(axis))\n shape_y = shape_y.broadcast_dimension(axis, shape_x.dimension_size(axis))\n return shape_x", "docstring": "Returns the shape formed by broadcasting two shapes to be compatible.\n\nArgs:\n shape_x: A `RaggedTensorDynamicShape`\n shape_y: A `RaggedTensorDynamicShape`\n\nReturns:\n A `RaggedTensorDynamicShape`.\n\nRaises:\n ValueError: If `shape_x` and `shape_y` are not broadcast-compatible.", "source": "github_repos"} +{"code": "def as_bool(self) -> bool:\n if len(self._messages) != 1:\n raise ValueError('FHIRPath did not evaluate to a single boolean.')\n return proto_utils.get_value_at_field(self._messages[0], 'value')", "docstring": "Returns the result as a boolean.\n\nRaises:\n ValueError if the `EvaluationResult` is not a single boolean.", "source": "github_repos"} +{"code": "def broadcast_recv(shape, dtype, group_size, group_key, instance_key, communication_hint='auto', timeout=0):\n if group_size <= 1:\n raise ValueError(f'Parameter `group_size` to broadcast_send must be at least 2. Received: {group_size}.')\n return gen_collective_ops.collective_bcast_recv(shape=shape, T=dtype, group_size=group_size, group_key=group_key, instance_key=instance_key, communication_hint=communication_hint.lower(), timeout_seconds=timeout)", "docstring": "Receives a broadcasts tensor, across devices.\n\nArgs:\n shape: Shape of the tensor to be received.\n dtype: Type of the tensor to be received.\n group_size: one plus the number of receiving tensors, i.e. the total\n number of devices participating. Each tensor must reside on a\n different device.\n group_key: an integer identifying the group of devices.\n instance_key: an integer identifying the participating group of Ops.\n communication_hint: preferred collective communication. The implementation\n may fall back to another mechanism. Options include `auto`, `ring`, and\n `nccl`.\n timeout: If set to a non zero, set a completion timeout to detect staleness.\n If the timer goes off, a DeadlineExceededError is raised.\n The timeout value in seconds. This feature is experimental.\n\nReturns:\n An Op implementing the broadcast receive.\n\nRaises:\n ValueError: if any of the input parameter constraints are not met.", "source": "github_repos"} +{"code": "def forward(self, pixel_values: Optional[torch.FloatTensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, interpolate_pos_encoding: bool=False, return_dict: Optional[bool]=None) -> Union[Tuple, BaseModelOutputWithPooling]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n return self.vision_model(pixel_values=pixel_values, output_attentions=output_attentions, output_hidden_states=output_hidden_states, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=return_dict)", "docstring": "Examples:\n\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import CLIPProcessor, ChineseCLIPVisionModel\n\n >>> model = ChineseCLIPVisionModel.from_pretrained(\"OFA-Sys/chinese-clip-vit-base-patch16\")\n >>> processor = CLIPProcessor.from_pretrained(\"OFA-Sys/chinese-clip-vit-base-patch16\")\n\n >>> url = \"https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> inputs = processor(images=image, return_tensors=\"pt\")\n\n >>> outputs = model(**inputs)\n >>> last_hidden_state = outputs.last_hidden_state\n >>> pooled_output = outputs.pooler_output # pooled CLS states\n ```", "source": "github_repos"} +{"code": "def as_dimension(value):\n if isinstance(value, Dimension):\n return value\n else:\n return Dimension(value)", "docstring": "Converts the given value to a Dimension.\n\n A Dimension input will be returned unmodified.\n An input of `None` will be converted to an unknown Dimension.\n An integer input will be converted to a Dimension with that value.\n\nArgs:\n value: The value to be converted.\n\nReturns:\n A Dimension corresponding to the given value.", "source": "github_repos"} +{"code": "def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:\n raise NotImplementedError(f'{self.__class__} is an abstract class. Only classes inheriting this class can call `get_candidates`.')", "docstring": "Fetches the candidates to be tried for the current input.\n\nArgs:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)\n\nReturns:\n `torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be\n assessed by the model and, optionally, a `torch.FloatTensor` of shape `(batch_size, candidate_length,\n vocabulary_size)` containing the logits associated to each candidate.", "source": "github_repos"} +{"code": "def should_run_validation(validation_freq, epoch):\n one_indexed_epoch = epoch + 1\n if isinstance(validation_freq, int):\n if validation_freq < 1:\n raise ValueError('`validation_freq` can not be less than 1.')\n return one_indexed_epoch % validation_freq == 0\n if not isinstance(validation_freq, collections.abc.Container):\n raise ValueError('`validation_freq` must be an Integer or `collections.abc.Container` (e.g. list, tuple, etc.)')\n return one_indexed_epoch in validation_freq", "docstring": "Checks if validation should be run this epoch.\n\nArgs:\n validation_freq: Integer or list. If an integer, specifies how many training\n epochs to run before a new validation run is performed. If a list,\n specifies the epochs on which to run validation.\n epoch: Integer, the number of the training epoch just completed.\n\nReturns:\n Bool, True if validation should be run.\n\nRaises:\n ValueError: if `validation_freq` is an Integer and less than 1, or if\n it is neither an Integer nor a Sequence.", "source": "github_repos"} +{"code": "def data_gen_sig1() -> repr_dataset.RepresentativeDataset:\n for _ in range(4):\n yield {'x1': random_ops.random_uniform(shape=in_placeholder_1.shape)}", "docstring": "Generates tuple-style samples.\n\n The first element of the tuple identifies the signature key the input data\n is for.\n\nYields:\n Representative samples for signature 'sig1'.", "source": "github_repos"} +{"code": "def update_checkpoint_state(save_dir, model_checkpoint_path, all_model_checkpoint_paths=None, latest_filename=None, all_model_checkpoint_timestamps=None, last_preserved_timestamp=None):\n update_checkpoint_state_internal(save_dir=save_dir, model_checkpoint_path=model_checkpoint_path, all_model_checkpoint_paths=all_model_checkpoint_paths, latest_filename=latest_filename, save_relative_paths=False, all_model_checkpoint_timestamps=all_model_checkpoint_timestamps, last_preserved_timestamp=last_preserved_timestamp)", "docstring": "Updates the content of the 'checkpoint' file.\n\n This updates the checkpoint file containing a CheckpointState\n proto.\n\nArgs:\n save_dir: Directory where the model was saved.\n model_checkpoint_path: The checkpoint file.\n all_model_checkpoint_paths: List of strings. Paths to all not-yet-deleted\n checkpoints, sorted from oldest to newest. If this is a non-empty list,\n the last element must be equal to model_checkpoint_path. These paths\n are also saved in the CheckpointState proto.\n latest_filename: Optional name of the checkpoint file. Default to\n 'checkpoint'.\n all_model_checkpoint_timestamps: Optional list of timestamps (floats,\n seconds since the Epoch) indicating when the checkpoints in\n `all_model_checkpoint_paths` were created.\n last_preserved_timestamp: A float, indicating the number of seconds since\n the Epoch when the last preserved checkpoint was written, e.g. due to a\n `keep_checkpoint_every_n_hours` parameter (see\n `tf.train.CheckpointManager` for an implementation).\n\nRaises:\n RuntimeError: If any of the model checkpoint paths conflict with the file\n containing CheckpointSate.", "source": "github_repos"} +{"code": "def convert(self):\n saved_model_convert_result = self._convert_as_saved_model()\n if saved_model_convert_result:\n return saved_model_convert_result\n graph_def, input_tensors, output_tensors, frozen_func = self._freeze_keras_model()\n graph_def = self._optimize_tf_model(graph_def, input_tensors, output_tensors, frozen_func)\n return super(TFLiteKerasModelConverterV2, self).convert(graph_def, input_tensors, output_tensors)", "docstring": "Converts a keras model based on instance variables.\n\nReturns:\n The converted data in serialized format.\n\nRaises:\n ValueError:\n Multiple concrete functions are specified.\n Input shape is not specified.\n Invalid quantization parameters.", "source": "github_repos"} +{"code": "def get_inlined_extension_url(field: descriptor.FieldDescriptor) -> str:\n options = annotation_utils.get_options(field)\n if options.HasExtension(annotations_pb2.fhir_inlined_extension_url):\n return options.Extensions[annotations_pb2.fhir_inlined_extension_url]\n return field.camelcase_name", "docstring": "Returns the FHIR inlined extension URL for a field.\n\nArgs:\n field: The FieldDescriptor to examine.\n\nReturns:\n The FHIR inlined extension URL, if one exists, otherwise returns the camel-\n case name of the FieldDescriptor.", "source": "github_repos"} +{"code": "def __mod__(self, other):\n other = as_dimension(other)\n if self._value is None or other.value is None:\n return Dimension(None)\n else:\n return Dimension(self._value % other.value)", "docstring": "Returns `self` modulo `other`.\n\n Dimension modulo are computed as follows:\n\n ```python\n tf.compat.v1.Dimension(m) % tf.compat.v1.Dimension(n) ==\n tf.compat.v1.Dimension(m % n)\n tf.compat.v1.Dimension(m) % tf.compat.v1.Dimension(None) # equiv. to\n tf.compat.v1.Dimension(None)\n tf.compat.v1.Dimension(None) % tf.compat.v1.Dimension(n) # equiv. to\n tf.compat.v1.Dimension(None)\n tf.compat.v1.Dimension(None) % tf.compat.v1.Dimension(None) # equiv. to\n tf.compat.v1.Dimension(None)\n ```\n\nArgs:\n other: Another Dimension, or a value accepted by `as_dimension`.\n\nReturns:\n A Dimension whose value is `self` modulo `other`.", "source": "github_repos"} +{"code": "def format_tensor(tensor, tensor_name, np_printoptions, print_all=False, tensor_slicing=None, highlight_options=None, include_numeric_summary=False, write_path=None):\n if tensor_slicing:\n value = command_parser.evaluate_tensor_slice(tensor, tensor_slicing)\n sliced_name = tensor_name + tensor_slicing\n else:\n value = tensor\n sliced_name = tensor_name\n auxiliary_message = None\n if write_path:\n with gfile.Open(write_path, 'wb') as output_file:\n np.save(output_file, value)\n line = debugger_cli_common.RichLine('Saved value to: ')\n line += debugger_cli_common.RichLine(write_path, font_attr='bold')\n line += ' (%sB)' % bytes_to_readable_str(gfile.Stat(write_path).length)\n auxiliary_message = debugger_cli_common.rich_text_lines_from_rich_line_list([line, debugger_cli_common.RichLine('')])\n if print_all:\n np_printoptions['threshold'] = value.size\n else:\n np_printoptions['threshold'] = DEFAULT_NDARRAY_DISPLAY_THRESHOLD\n return tensor_format.format_tensor(value, sliced_name, include_metadata=True, include_numeric_summary=include_numeric_summary, auxiliary_message=auxiliary_message, np_printoptions=np_printoptions, highlight_options=highlight_options)", "docstring": "Generate formatted str to represent a tensor or its slices.\n\nArgs:\n tensor: (numpy ndarray) The tensor value.\n tensor_name: (str) Name of the tensor, e.g., the tensor's debug watch key.\n np_printoptions: (dict) Numpy tensor formatting options.\n print_all: (bool) Whether the tensor is to be displayed in its entirety,\n instead of printing ellipses, even if its number of elements exceeds\n the default numpy display threshold.\n (Note: Even if this is set to true, the screen output can still be cut\n off by the UI frontend if it consist of more lines than the frontend\n can handle.)\n tensor_slicing: (str or None) Slicing of the tensor, e.g., \"[:, 1]\". If\n None, no slicing will be performed on the tensor.\n highlight_options: (tensor_format.HighlightOptions) options to highlight\n elements of the tensor. See the doc of tensor_format.format_tensor()\n for more details.\n include_numeric_summary: Whether a text summary of the numeric values (if\n applicable) will be included.\n write_path: A path to save the tensor value (after any slicing) to\n (optional). `numpy.save()` is used to save the value.\n\nReturns:\n An instance of `debugger_cli_common.RichTextLines` representing the\n (potentially sliced) tensor.", "source": "github_repos"} +{"code": "def __init__(self, granularity: Granularity) -> None:\n \"\"\"Initializes the HTML parser for the KNBC corpus.\n\nArgs:\n granularity: Granularity of the output chunks.\n\"\"\"\n super().__init__()\n self.chunks = ['']\n self.row = 0\n self.col = 0\n self.current_word = ''\n self.on_split_row = False\n self.granularity = granularity", "docstring": "Parses the HTML files in the KNBC corpus to collect chunks.\n\nAttributes:\n chunks: The collected chunks.\n row: The current row index.\n col: The current column index.\n current_word: The current word to process.\n on_split_row: Whether the scan is on the splitting row.\n granularity: Granularity of the output chunks.", "source": "github_repos"} +{"code": "def _TestGradient(self, nccl_reduce, numpy_fn):\n\n def _Gradient(tensors, devices):\n inputs = [array_ops.placeholder(t.dtype, t.shape) for t in tensors]\n reduce_tensors = nccl_reduce(inputs, devices)\n losses = _DeviceTensors(tensors, [t.device for t in reduce_tensors])\n grads = gradients.gradients(reduce_tensors, inputs, losses, colocate_gradients_with_ops=True)\n return [g for g in grads if g is not None]\n self._Test(_Gradient, numpy_fn)", "docstring": "Tests the gradient of nccl_reduce.\n\nArgs:\n nccl_reduce: A function taking a list of tensors and a list of devices,\n and returns a list of reduced tensors and a list of ops to perform the\n reduction.\n numpy_fn: A function taking two tensors and returning the gradient of the\n reduction of the two.", "source": "github_repos"} +{"code": "def _swap_where(condition, x, y):\n return (tf.where(condition, y, x), tf.where(condition, x, y))", "docstring": "Swaps the elements of `x` and `y` based on `condition`.\n\nArgs:\n condition: A `Tensor` of dtype bool.\n x: A `Tensor` with the same shape as `condition`.\n y: A `Tensor` with the same shape and dtype as `x`.\n\nReturns:\n Two `Tensors` with the same shape as `x` and `y`.", "source": "github_repos"} +{"code": "def sort(x, axis=-1):\n if any_symbolic_tensors((x,)):\n return Sort(axis=axis).symbolic_call(x)\n return backend.numpy.sort(x, axis=axis)", "docstring": "Sorts the elements of `x` along a given axis in ascending order.\n\nArgs:\n x: Input tensor.\n axis: Axis along which to sort. If `None`, the tensor is flattened\n before sorting. Defaults to `-1`; the last axis.\n\nReturns:\n Sorted tensor.", "source": "github_repos"} +{"code": "def _create_op_from_tf_operation(self, c_op, compute_device=True) -> 'Operation':\n self._check_not_finalized()\n ret = Operation._from_c_op(c_op=c_op, g=self)\n name_key = ret.name.lower()\n if name_key not in self._names_in_use:\n self._names_in_use[name_key] = 1\n self._create_op_helper(ret, compute_device=compute_device)\n return ret", "docstring": "Creates an `Operation` in this graph from the supplied TF_Operation.\n\n This method is like create_op() except the new Operation is constructed\n using `c_op`. The returned Operation will have `c_op` as its _c_op\n field. This is used to create Operation objects around TF_Operations created\n indirectly by the C API (e.g. by TF_ImportGraphDef, TF_FinishWhile).\n\n This function does not call Operation._control_flow_post_processing or\n Graph._control_dependencies_for_inputs (since the inputs may not be\n available yet). The caller is responsible for calling these methods.\n\nArgs:\n c_op: a wrapped TF_Operation\n compute_device: (Optional.) If True, device functions will be executed to\n compute the device property of the Operation.\n\nReturns:\n An `Operation` object.", "source": "github_repos"} +{"code": "def constant(value, dtype=None, shape=None, name=None):\n if dtype is None:\n dtype = floatx()\n return constant_op.constant(value, dtype=dtype, shape=shape, name=name)", "docstring": "Creates a constant tensor.\n\nArgs:\n value: A constant value (or list)\n dtype: The type of the elements of the resulting tensor.\n shape: Optional dimensions of resulting tensor.\n name: Optional name for the tensor.\n\nReturns:\n A Constant Tensor.", "source": "github_repos"} +{"code": "def __init__(self, cardinalities: List[int], embedding_dims: List[int]) -> None:\n super().__init__()\n self.num_features = len(cardinalities)\n self.embedders = nn.ModuleList([nn.Embedding(c, d) for c, d in zip(cardinalities, embedding_dims)])", "docstring": "Embed a sequence of categorical features.\n\nArgs:\n cardinalities (`list[int]`):\n List of cardinalities of the categorical features.\n embedding_dims (`list[int]`):\n List of embedding dimensions of the categorical features.", "source": "github_repos"} +{"code": "def fixed_size_partitioner(num_shards, axis=0):\n\n def _partitioner(shape, **unused_args):\n partitions_list = [1] * len(shape)\n partitions_list[axis] = min(num_shards, shape.dims[axis].value)\n return partitions_list\n return _partitioner", "docstring": "Partitioner to specify a fixed number of shards along given axis.\n\n @compatibility(TF2)\n This API is deprecated in TF2. In TF2, partitioner is no longer part of\n the variable declaration via `tf.Variable`.\n [ParameterServer Training]\n (https://www.tensorflow.org/tutorials/distribute/parameter_server_training)\n handles partitioning of variables. The corresponding TF2 partitioner class of\n `fixed_size_partitioner` is\n `tf.distribute.experimental.partitioners.FixedShardsPartitioner`.\n\n Check the [migration guide]\n (https://www.tensorflow.org/guide/migrate#2_use_python_objects_to_track_variables_and_losses)\n on the differences in treatment of variables and losses between TF1 and TF2.\n\n Before:\n\n ```\n x = tf.compat.v1.get_variable(\n \"x\", shape=(2,), partitioner=tf.compat.v1.fixed_size_partitioner(2)\n )\n ```\n After:\n\n ```\n partitioner = (\n tf.distribute.experimental.partitioners.FixedShardsPartitioner(\n num_shards=2)\n )\n strategy = tf.distribute.experimental.ParameterServerStrategy(\n cluster_resolver=cluster_resolver,\n variable_partitioner=partitioner)\n\n with strategy.scope():\n x = tf.Variable([1.0, 2.0])\n ```\n @end_compatibility\n\nArgs:\n num_shards: `int`, number of shards to partition variable.\n axis: `int`, axis to partition on.\n\nReturns:\n A partition function usable as the `partitioner` argument to\n `variable_scope` and `get_variable`.", "source": "github_repos"} +{"code": "def zeros(shape, dtype=None):\n return backend.numpy.zeros(shape, dtype=dtype)", "docstring": "Return a new tensor of given shape and type, filled with zeros.\n\nArgs:\n shape: Shape of the new tensor.\n dtype: Desired data type of the tensor.\n\nReturns:\n Tensor of zeros with the given shape and dtype.", "source": "github_repos"} +{"code": "def serialize_keras_object(instance):\n instance = inspect.unwrap(instance)\n if instance is None:\n return None\n if hasattr(instance, 'get_config'):\n name = object_registration.get_registered_name(instance.__class__)\n try:\n config = instance.get_config()\n except NotImplementedError as e:\n if _SKIP_FAILED_SERIALIZATION:\n return serialize_keras_class_and_config(name, {_LAYER_UNDEFINED_CONFIG_KEY: True})\n raise e\n serialization_config = {}\n for key, item in config.items():\n if isinstance(item, str):\n serialization_config[key] = item\n continue\n try:\n serialized_item = serialize_keras_object(item)\n if isinstance(serialized_item, dict) and (not isinstance(item, dict)):\n serialized_item['__passive_serialization__'] = True\n serialization_config[key] = serialized_item\n except ValueError:\n serialization_config[key] = item\n name = object_registration.get_registered_name(instance.__class__)\n return serialize_keras_class_and_config(name, serialization_config, instance)\n if hasattr(instance, '__name__'):\n return object_registration.get_registered_name(instance)\n raise ValueError(f\"Cannot serialize {instance} because it doesn't implement `get_config()`.\")", "docstring": "Serialize a Keras object into a JSON-compatible representation.\n\n Calls to `serialize_keras_object` while underneath the\n `SharedObjectSavingScope` context manager will cause any objects re-used\n across multiple layers to be saved with a special shared object ID. This\n allows the network to be re-created properly during deserialization.\n\nArgs:\n instance: The object to serialize.\n\nReturns:\n A dict-like, JSON-compatible representation of the object's config.", "source": "github_repos"} +{"code": "def get_num_bytes(self, batch: Sequence[pandas.DataFrame]) -> int:\n return sum((df.memory_usage(deep=True).sum() for df in batch))", "docstring": "Returns:\n The number of bytes of data for a batch.", "source": "github_repos"} +{"code": "def put(self, resource_json: Dict[str, Any], parent_bundle: Optional[Dict[str, Any]]=None) -> None:\n if parent_bundle is None:\n self.resources_by_uri[resource_json['url']] = resource_json\n else:\n self.resources_by_uri[resource_json['url']] = parent_bundle", "docstring": "Puts the given resource into this collection.\n\n Adds the resource represented by `resource_json` found inside\n `parent_bundle` into this collection for subsequent lookup via the Get\n method. `parent_bundle` may be None if `resource_json` is not located inside\n a bundle.\n\nArgs:\n resource_json: The JSON object representing the resource.\n parent_bundle: The bundle `resource_json` is located inside, if any.", "source": "github_repos"} +{"code": "def is_tf2_saved_model(export_dir):\n try:\n fingerprint = fingerprinting.read_fingerprint(export_dir)\n if fingerprint.saved_object_graph_hash != 0:\n logging.info('SavedModel at %s is a TF2 SavedModel', export_dir)\n return True\n except Exception:\n logging.info('Failed to read fingerprint from SavedModel. Parsing MetaGraph ...')\n saved_model_proto = loader_impl.parse_saved_model(export_dir)\n if len(saved_model_proto.meta_graphs) == 1 and saved_model_proto.meta_graphs[0].HasField('object_graph_def'):\n logging.info('SavedModel at %s is a TF2 SavedModel', export_dir)\n return True\n logging.info('SavedModel at %s is a TF1 SavedModel', export_dir)\n return False", "docstring": "Identifies if an exported SavedModel is a TF2 SavedModel.\n\n There are differences in SavedModel semantics between TF1 and TF2 that are\n documented here:\n https://www.tensorflow.org/guide/migrate/saved_model#savedmodel. This helper\n util function serves to distinguish the TF1 vs TF2 semantics used when\n exporting SavedModels.\n\nArgs:\n export_dir: The SavedModel directory to load from.\n\nReturns:\n True if TF2 SavedModel semantics are used, False if TF1 SavedModel semantics\n are used.", "source": "github_repos"} +{"code": "def __init__(self, on_ui_exit=None, config=None):\n self._on_ui_exit = on_ui_exit\n self._command_handler_registry = debugger_cli_common.CommandHandlerRegistry()\n self._tab_completion_registry = debugger_cli_common.TabCompletionRegistry()\n self._tab_completion_registry.register_tab_comp_context([''], self.CLI_EXIT_COMMANDS + [debugger_cli_common.CommandHandlerRegistry.HELP_COMMAND] + debugger_cli_common.CommandHandlerRegistry.HELP_COMMAND_ALIASES)\n self._config = config or cli_config.CLIConfig()\n self._config_argparser = argparse.ArgumentParser(description='config command', usage=argparse.SUPPRESS)\n subparsers = self._config_argparser.add_subparsers()\n set_parser = subparsers.add_parser('set')\n set_parser.add_argument('property_name', type=str)\n set_parser.add_argument('property_value', type=str)\n set_parser = subparsers.add_parser('show')\n self.register_command_handler('config', self._config_command_handler, self._config_argparser.format_help(), prefix_aliases=['cfg'])", "docstring": "Constructor of the base class.\n\nArgs:\n on_ui_exit: (`Callable`) the callback to be called when the UI exits.\n config: An instance of `cli_config.CLIConfig()` carrying user-facing\n configurations.", "source": "github_repos"} +{"code": "def register_converter(src_type: Union[Type[Any], Tuple[Type[Any], ...]], dest_type: Union[Type[Any], Tuple[Type[Any], ...]], convert_fn: Callable[[Any], Any]) -> None:\n _TYPE_CONVERTER_REGISTRY.register(src_type, dest_type, convert_fn)", "docstring": "Register converter from source type to destination type.\n\n Examples::\n\n # Add converter from int to float.\n pg.typing.register_converter(int, float, float)\n\n assert pg.typing.Float().apply(1) is 1.0\n\n # Add converter from a dict to class A.\n def from_dict(d):\n return A(**d)\n\n assert isinstance(pg.typing.Object(A).apply({'x': 1, 'y': 2}), A)\n\nArgs:\n src_type: Source value type.\n dest_type: Target value type.\n convert_fn: Function that performs the conversion, in signature\n (src_type) -> dest_type.", "source": "github_repos"} +{"code": "def get_subtype(self):\n raise NotImplementedError('Base class should not be called directly!')", "docstring": "This function returns the sub-type of the sniffer.\n\nReturns:\n The sub-type (string) of the sniffer. Corresponds to the 'SubType'\n key of the sniffer configuration.", "source": "github_repos"} +{"code": "def _calculate_scores(self, query, key):\n return NotImplementedError", "docstring": "Calculates attention scores.\n\nArgs:\n query: Query tensor of shape `[batch_size, Tq, dim]`.\n key: Key tensor of shape `[batch_size, Tv, dim]`.\n\nReturns:\n Tensor of shape `[batch_size, Tq, Tv]`.", "source": "github_repos"} +{"code": "def avro_union_type_to_beam_type(union_type: List) -> schema_pb2.FieldType:\n if len(union_type) == 2 and 'null' in union_type:\n for avro_type in union_type:\n if avro_type in AVRO_PRIMITIVES_TO_BEAM_PRIMITIVES:\n return schema_pb2.FieldType(atomic_type=AVRO_PRIMITIVES_TO_BEAM_PRIMITIVES[avro_type], nullable=True)\n return schemas.typing_to_runner_api(Any)\n return schemas.typing_to_runner_api(Any)", "docstring": "convert an avro union type to a beam type\n\n if the union type is a nullable, and it is a nullable union of an avro\n primitive with a corresponding beam primitive then create a nullable beam\n field of the corresponding beam type, otherwise return an Any type.\n\nArgs:\n union_type: the avro union type to convert.\n\nReturns:\n the beam type of the avro union.", "source": "github_repos"} +{"code": "def get_dense_tensor(self, transformation_cache, state_manager):\n return transformation_cache.get(self, state_manager)", "docstring": "Returns dense `Tensor` representing numeric feature.\n\nArgs:\n transformation_cache: A `FeatureTransformationCache` object to access\n features.\n state_manager: A `StateManager` to create / access resources such as\n lookup tables.\n\nReturns:\n Dense `Tensor` created within `transform_feature`.", "source": "github_repos"} +{"code": "def event_shape_tensor(self, name='event_shape_tensor'):\n with self._name_scope(name):\n if self.event_shape.is_fully_defined():\n return ops.convert_to_tensor(self.event_shape.as_list(), dtype=dtypes.int32, name='event_shape')\n return self._event_shape_tensor()", "docstring": "Shape of a single sample from a single batch as a 1-D int32 `Tensor`.\n\nArgs:\n name: name to give to the op\n\nReturns:\n event_shape: `Tensor`.", "source": "github_repos"} +{"code": "def create_datasets():\n if use_device:\n datasets = []\n for i in range(len(self.embedding_devices)):\n datasets.append(dataset_ops.DatasetV2.from_tensor_slices({'feature': [[[i % self._num_cores_per_replica]]]}).repeat())\n return datasets\n else:\n dataset = strategy.distribute_datasets_from_function(input_fn, options=distribute_lib.InputOptions(experimental_fetch_to_device=False))\n return [dataset]", "docstring": "Creates either a per-replica dataset, or multiple per-devices ones.\n\n This function explicitly creates per-device datasets because the strategy\n does not produce a distributed dataset in the model-parallel case; there\n is only one replica. Without this consideration, the embeddings would be\n read as [0, 0] instead of the expected [0, 1] since all the devices would\n receive the same value.\n\nReturns:\n A list of one or more dataset(s).", "source": "github_repos"} +{"code": "def make_one_shot_iterator(self):\n return self._make_one_shot_iterator()", "docstring": "Get a one time use iterator for DistributedDatasetV1.\n\n Note: This API is deprecated. Please use `for ... in dataset:` to iterate\n over the dataset or `iter` to create an iterator.\n\nReturns:\n A DistributedIteratorV1 instance.", "source": "github_repos"} +{"code": "def run_inference(self, batch: Sequence[datatable.Frame], model: Union[xgboost.Booster, xgboost.XGBModel], inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionResult]:\n return self._inference_fn(batch, model, inference_args)", "docstring": "Runs inferences on a batch of datatable dataframe.\n\nArgs:\n batch: A sequence of examples as datatable dataframes. Each\n row in a dataframe is a single example. The dimensions\n must match the dimensions of the data used to train\n the model.\n model: XGBoost booster or XBGModel (sklearn interface). Must implement\n predict(X). Where the parameter X is a datatable dataframe.\n inference_args: Any additional arguments for an inference.\n\nReturns:\n An Iterable of type PredictionResult.", "source": "github_repos"} +{"code": "def assert_eventual(self, func, required, allowed, timeout_secs=300.0):\n required = set(required)\n assert required\n seen = set()\n start_time = time.time()\n while timeout_secs is None or time.time() - start_time < timeout_secs:\n if seen == required:\n return\n value = func()\n if value not in allowed:\n self.fail(msg=f'Disallowed value: {value}.')\n if value in required:\n seen.add(value)\n missing = [v for v in required if v not in seen]\n self.fail(msg=f'Timed out. Missing values: {str([str(v) for v in missing])}.')", "docstring": "Tests that calls to the given function meet required and allowed values.\n\nArgs:\n func: function to test.\n required: iterable of required values. Must be hashable and non-empty.\n allowed: iterable of allowed values. Must be hashable and non-empty.\n timeout_secs: fails if more than this time is required.", "source": "github_repos"} +{"code": "def _build_all_reduce_ring(core_locations: List[_CoreLocation], rotate: bool=False) -> List[int]:\n permutation = list(range(len(core_locations)))\n if not permutation:\n return permutation\n logging.vlog(2, 'Core locations in: %s', core_locations)\n first_column = min([l.x for l in core_locations])\n first_row = min([l.y for l in core_locations])\n same_z = len(set([l.z for l in core_locations])) == 1\n logging.vlog(2, 'first_column: %d', first_column)\n logging.vlog(2, 'first_row: %d', first_row)\n logging.vlog(2, 'same_z: %s', same_z)\n\n def _cmp_2d(ia: int, ib: int) -> int:\n if not rotate:\n a = core_locations[ia]\n b = core_locations[ib]\n a_first = a.x == first_column and a.y != first_row\n b_first = b.x == first_column and b.y != first_row\n if a_first != b_first:\n return -1 if b_first else 1\n if a.y != b.y:\n return b.y - a.y if a_first else a.y - b.y\n if a.x != b.x:\n return a.x - b.x if a.y % 2 == 0 else b.x - a.x\n return a.core - b.core\n else:\n a = core_locations[ia]\n b = core_locations[ib]\n a_first = a.y == first_row and a.x != first_column\n b_first = b.y == first_row and b.x != first_column\n if a_first != b_first:\n return -1 if b_first else 1\n if a.x != b.x:\n return b.x - a.x if a_first else a.x - b.x\n if a.y != b.y:\n return a.y - b.y if a.x % 2 == 0 else b.y - a.y\n return a.core - b.core\n\n def _cmp_3d(ia: int, ib: int) -> int:\n a = core_locations[ia]\n b = core_locations[ib]\n a_corner = a.x == first_column and a.y == first_row\n b_corner = b.x == first_column and b.y == first_row\n if a_corner and b_corner:\n return b.z - a.z if a.z != b.z else a.core - b.core\n if a_corner != b_corner:\n return -1 if b_corner else 1\n if a.z == b.z:\n return _cmp_2d(ia, ib) if a.z % 2 == 0 else -_cmp_2d(ia, ib)\n return a.z - b.z\n if same_z:\n permutation.sort(key=functools.cmp_to_key(_cmp_2d))\n else:\n permutation.sort(key=functools.cmp_to_key(_cmp_3d))\n logging.vlog(2, 'Permutation out: %s', permutation)\n return permutation", "docstring": "Reorders a list of TPU cores to optimize for AllReduce performance.\n\n This is ported from the C++ tensorflow::BuildAllReduceRing function,\n mixed with some logic from TF TPU's device_assignment._ring_3d.\n\nArgs:\n core_locations: A list of core locations expressed as [x, y, z, core].\n rotate: If true, scan the cores in a column-major order. False by default.\n\nReturns:\n A permutation of the input list such that neighbors in the sequence are\n nearby in the TPU topology.", "source": "github_repos"} +{"code": "def update_state(self, y_true, y_pred, sample_weight=None):\n return metrics_utils.update_confusion_matrix_variables({self._confusion_matrix_cond: self.accumulator}, y_true, y_pred, thresholds=self.thresholds, thresholds_distributed_evenly=self._thresholds_distributed_evenly, sample_weight=sample_weight)", "docstring": "Accumulates the metric statistics.\n\nArgs:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to `1`.\n Can be a tensor whose rank is either 0, or the same rank as\n `y_true`, and must be broadcastable to `y_true`.", "source": "github_repos"} +{"code": "def get_extended_attention_mask(self, attention_mask: torch.Tensor, input_shape: Tuple[int], device: torch.device, has_query: bool=False) -> torch.Tensor:\n if attention_mask.dim() == 3:\n extended_attention_mask = attention_mask[:, None, :, :]\n elif attention_mask.dim() == 2:\n extended_attention_mask = attention_mask[:, None, None, :]\n else:\n raise ValueError('Wrong shape for input_ids (shape {}) or attention_mask (shape {})'.format(input_shape, attention_mask.shape))\n extended_attention_mask = extended_attention_mask.to(dtype=self.dtype)\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n return extended_attention_mask", "docstring": "Makes broadcastable attention and causal masks so that future and masked tokens are ignored.\n\nArgs:\n attention_mask (`torch.Tensor`):\n Mask with ones indicating tokens to attend to, zeros for tokens to ignore.\n input_shape (`Tuple[int]`):\n The shape of the input to the model.\n device (`torch.device`):\n The device of the input to the model.\n\nReturns:\n `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.", "source": "github_repos"} +{"code": "def decode(self, token_ids, **kwargs):\n return super().decode(token_ids, **kwargs)", "docstring": "Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special\n tokens and clean up tokenization spaces.\n\n Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n\nArgs:\n token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):\n List of tokenized input ids. Can be obtained using the `__call__` method.\n skip_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not to remove special tokens in the decoding.\n clean_up_tokenization_spaces (`bool`, *optional*):\n Whether or not to clean up the tokenization spaces. If `None`, will default to\n `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).\n use_source_tokenizer (`bool`, *optional*, defaults to `False`):\n Whether or not to use the source tokenizer to decode sequences (only applicable in sequence-to-sequence\n problems).\n kwargs (additional keyword arguments, *optional*):\n Will be passed to the underlying model specific decode method.\n\nReturns:\n `str`: The decoded sentence.", "source": "github_repos"} +{"code": "def _normalize(self, text: str) -> str:\n accepted = [chr(i) for i in range(ord('a'), ord('z') + 1)] + [chr(i) for i in range(ord('A'), ord('Z') + 1)] + [chr(i) for i in range(ord('0'), ord('9') + 1)] + ['.']\n accepted = frozenset(accepted)\n pattern = re.compile('_+')\n text = ''.join([c if c in accepted else '_' for c in text.lower()])\n text = pattern.sub('_', text).strip('_')\n return text", "docstring": "Normalizes the input text. This process is for the genres and the artist\n\nArgs:\n text (`str`):\n Artist or Genre string to normalize", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[Tuple, BaseModelOutputWithPooling]:\n return self.text_model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)", "docstring": "Examples:\n\n ```python\n >>> from transformers import AutoTokenizer, XCLIPTextModel\n\n >>> model = XCLIPTextModel.from_pretrained(\"microsoft/xclip-base-patch32\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"microsoft/xclip-base-patch32\")\n\n >>> inputs = tokenizer([\"a photo of a cat\", \"a photo of a dog\"], padding=True, return_tensors=\"pt\")\n\n >>> outputs = model(**inputs)\n >>> last_hidden_state = outputs.last_hidden_state\n >>> pooled_output = outputs.pooler_output # pooled (EOS token) states\n ```", "source": "github_repos"} +{"code": "def __init__(self, bits: int=4, p: int=2, modules_to_not_convert: Optional[List[str]]=None, hadamard_size: int=512, group_size: int=256, tune_metadata: Optional[Dict[str, Any]]=None, **kwargs):\n if tune_metadata is None:\n tune_metadata = {}\n self.quant_method = QuantizationMethod.HIGGS\n self.bits = bits\n self.p = p\n self.modules_to_not_convert = modules_to_not_convert\n self.hadamard_size = hadamard_size\n self.group_size = group_size\n self.tune_metadata = tune_metadata\n self.post_init()", "docstring": "HiggsConfig is a configuration class for quantization using the HIGGS method.\n\nArgs:\n bits (int, *optional*, defaults to 4):\n Number of bits to use for quantization. Can be 2, 3 or 4. Default is 4.\n p (int, *optional*, defaults to 2):\n Quantization grid dimension. 1 and 2 are supported. 2 is always better in practice. Default is 2.\n modules_to_not_convert (`list`, *optional*, default to [\"lm_head\"]):\n List of linear layers that should not be quantized.\n hadamard_size (int, *optional*, defaults to 512):\n Hadamard size for the HIGGS method. Default is 512. Input dimension of matrices is padded to this value. Decreasing this below 512 will reduce the quality of the quantization.\n group_size (int, *optional*, defaults to 256):\n Group size for the HIGGS method. Can be 64, 128 or 256. Decreasing it barely affects the performance. Default is 256. Must be a divisor of hadamard_size.\n tune_metadata ('dict', *optional*, defaults to {}):\n Module-wise metadata (gemm block shapes, GPU metadata, etc.) for saving the kernel tuning results. Default is an empty dictionary. Is set automatically during tuning.", "source": "github_repos"} +{"code": "def basic_train_loop(supervisor, train_step_fn, args=None, kwargs=None, master=''):\n if args is None:\n args = []\n if kwargs is None:\n kwargs = {}\n should_retry = True\n while should_retry:\n try:\n should_retry = False\n with supervisor.managed_session(master) as sess:\n while not supervisor.should_stop():\n train_step_fn(sess, *args, **kwargs)\n except errors.AbortedError:\n should_retry = True", "docstring": "Basic loop to train a model.\n\n Calls `train_step_fn` in a loop to train a model. The function is called as:\n\n ```python\n train_step_fn(session, *args, **kwargs)\n ```\n\n It is passed a `tf.compat.v1.Session` in addition to `args` and `kwargs`. The\n function\n typically runs one training step in the session.\n\nArgs:\n supervisor: `tf.compat.v1.train.Supervisor` to run the training services.\n train_step_fn: Callable to execute one training step. Called repeatedly as\n `train_step_fn(session, *args **kwargs)`.\n args: Optional positional arguments passed to `train_step_fn`.\n kwargs: Optional keyword arguments passed to `train_step_fn`.\n master: Master to use to create the training session. Defaults to `\"\"`\n which causes the session to be created in the local process.", "source": "github_repos"} +{"code": "def get_factors(dividend: int) -> Set[int]:\n factors_set = set()\n for i in range(1, int(dividend ** 0.5) + 1):\n if dividend % i == 0:\n factors_set.add(i)\n factors_set.add(dividend // i)\n return factors_set", "docstring": "Calculate all factors of a given number, i.e. a divisor that leaves\n no remainder. For example, if dividend=12, it will return {1, 2, 3, 4, 6, 12}.\n\nArgs:\n dividend (int): The number to find factors for.\n\nReturns:\n set: A set containing all factors of the number.", "source": "github_repos"} +{"code": "def translate_distribution(distribution_update, metric_update_proto):\n dist_update_proto = dataflow.DistributionUpdate()\n dist_update_proto.min = to_split_int(distribution_update.min)\n dist_update_proto.max = to_split_int(distribution_update.max)\n dist_update_proto.count = to_split_int(distribution_update.count)\n dist_update_proto.sum = to_split_int(distribution_update.sum)\n if isinstance(distribution_update, DataflowDistributionCounter):\n dist_update_proto.histogram = dataflow.Histogram()\n distribution_update.translate_to_histogram(dist_update_proto.histogram)\n metric_update_proto.distribution = dist_update_proto", "docstring": "Translate metrics DistributionUpdate to dataflow distribution update.\n\nArgs:\n distribution_update: Instance of DistributionData,\n DistributionInt64Accumulator or DataflowDistributionCounter.\n metric_update_proto: Used for report metrics.", "source": "github_repos"} +{"code": "def __init__(self, layer, **kwargs):\n if not isinstance(layer, Layer):\n raise ValueError(f'Please initialize `TimeDistributed` layer with a `keras.layers.Layer` instance. Received: {layer}')\n super().__init__(layer, **kwargs)\n self.supports_masking = True", "docstring": "This wrapper allows to apply a layer to every temporal slice of an input.\n\n Every input should be at least 3D, and the dimension of index one of the\n first input will be considered to be the temporal dimension.\n\n Consider a batch of 32 video samples, where each sample is a 128x128 RGB\n image with `channels_last` data format, across 10 timesteps.\n The batch input shape is `(32, 10, 128, 128, 3)`.\n\n You can then use `TimeDistributed` to apply the same `Conv2D` layer to each\n of the 10 timesteps, independently:\n\n >>> inputs = layers.Input(shape=(10, 128, 128, 3), batch_size=32)\n >>> conv_2d_layer = layers.Conv2D(64, (3, 3))\n >>> outputs = layers.TimeDistributed(conv_2d_layer)(inputs)\n >>> outputs.shape\n (32, 10, 126, 126, 64)\n\n Because `TimeDistributed` applies the same instance of `Conv2D` to each of\n the timestamps, the same set of weights are used at each timestamp.\n\nArgs:\n layer: a `keras.layers.Layer` instance.\n\n Call arguments:\n inputs: Input tensor of shape (batch, time, ...) or nested tensors,\n and each of which has shape (batch, time, ...).\n training: Python boolean indicating whether the layer should behave in\n training mode or in inference mode. This argument is passed to the\n wrapped layer (only if the layer supports this argument).\n mask: Binary tensor of shape `(samples, timesteps)` indicating whether\n a given timestep should be masked. This argument is passed to the\n wrapped layer (only if the layer supports this argument).", "source": "github_repos"} +{"code": "def __init__(self, data_format=None, **kwargs):\n super().__init__(**kwargs)\n self.data_format = backend.standardize_data_format(data_format)\n self.input_spec = InputSpec(min_ndim=1)\n self._channels_first = self.data_format == 'channels_first'", "docstring": "Flattens the input. Does not affect the batch size.\n\n Note: If inputs are shaped `(batch,)` without a feature axis, then\n flattening adds an extra channel dimension and output shape is `(batch, 1)`.\n\nArgs:\n data_format: A string, one of `\"channels_last\"` (default) or\n `\"channels_first\"`. The ordering of the dimensions in the inputs.\n `\"channels_last\"` corresponds to inputs with shape\n `(batch, ..., channels)` while `\"channels_first\"` corresponds to\n inputs with shape `(batch, channels, ...)`.\n When unspecified, uses `image_data_format` value found in your Keras\n config file at `~/.keras/keras.json` (if exists). Defaults to\n `\"channels_last\"`.\n\nExample:\n >>> x = keras.Input(shape=(10, 64))\n >>> y = keras.layers.Flatten()(x)\n >>> y.shape\n (None, 640)", "source": "github_repos"} +{"code": "def _load_method(self, state, self_obj, name):\n state, result = self.load_attr(state, self_obj, name)\n state = self._push_null(state)\n return (state.push(result), result)", "docstring": "Loads and pushes a method on the stack.\n\nArgs:\n state: the current VM state.\n self_obj: the `self` object of the method.\n name: the name of the method.\n\nReturns:\n (state, method) where `state` is the updated VM state and `method` is the\n method that was loaded. The method is already pushed onto the stack,\n either at the top or below the `self` object.", "source": "github_repos"} +{"code": "def test_pass(self, e=None):\n self._test_end(TestResultEnums.TEST_RESULT_PASS, e)", "docstring": "To mark the test as passed in this record.\n\nArgs:\n e: An instance of mobly.signals.TestPass.", "source": "github_repos"} +{"code": "def split_if_relative_reference(reference: message.Message) -> None:\n _validate_reference(reference)\n uri_field = reference.DESCRIPTOR.fields_by_name.get('uri')\n if not proto_utils.field_is_set(reference, uri_field):\n return\n uri = proto_utils.get_value_at_field(reference, uri_field)\n internal_match = re.fullmatch(_INTERNAL_REFERENCE_PATTERN, uri.value)\n if internal_match is not None:\n reference_id_field = get_reference_id_field_for_resource(reference, internal_match.group('resource_type'))\n reference_id = proto_utils.create_message_from_descriptor(reference_id_field.message_type)\n populate_typed_reference_id(reference_id, internal_match.group('resource_id'), internal_match.group('version'))\n proto_utils.copy_common_field(uri, reference_id, 'id')\n proto_utils.copy_common_field(uri, reference_id, 'extension')\n proto_utils.set_value_at_field(reference, reference_id_field, reference_id)\n return\n fragment_match = re.fullmatch(_FRAGMENT_REFERENCE_PATTERN, uri.value)\n if fragment_match is not None:\n fragment_field = reference.DESCRIPTOR.fields_by_name['fragment']\n fragment = proto_utils.create_message_from_descriptor(fragment_field.message_type)\n value_field = fragment.DESCRIPTOR.fields_by_name['value']\n proto_utils.set_value_at_field(fragment, value_field, uri.value[1:])\n proto_utils.copy_common_field(uri, fragment, 'id')\n proto_utils.copy_common_field(uri, fragment, 'extension')\n proto_utils.set_value_at_field(reference, fragment_field, fragment)\n return", "docstring": "If possible, parses a `Reference` `uri` into more structured fields.\n\n This is only possible for two forms of reference uris:\n * Relative references of the form $TYPE/$ID, e.g., \"Patient/1234\"\n In this case, this will be parsed to a proto of the form:\n {patient_id: {value: \"1234\"}}\n * Fragments of the form \"#$FRAGMENT\", e.g., \"#vs1\". In this case, this would\n be parsed into a proto of the form:\n {fragment: {value: \"vs1\"} }\n\n If the reference URI matches one of these schemas, the `uri` field will be\n cleared, and the appropriate structured fields set. Otherwise, the reference\n will be unchanged.\n\nArgs:\n reference: The FHIR reference to potentially split.\n\nRaises:\n ValueError: If the message is not a valid FHIR Reference proto.", "source": "github_repos"} +{"code": "def get_container_image_from_options(pipeline_options):\n worker_options = pipeline_options.view_as(WorkerOptions)\n if worker_options.sdk_container_image:\n return worker_options.sdk_container_image\n container_repo = names.DATAFLOW_CONTAINER_IMAGE_REPOSITORY\n image_name = '{repository}/beam_python{major}.{minor}_sdk'.format(repository=container_repo, major=sys.version_info[0], minor=sys.version_info[1])\n image_tag = _get_required_container_version()\n return image_name + ':' + image_tag", "docstring": "For internal use only; no backwards-compatibility guarantees.\n\nArgs:\n pipeline_options (PipelineOptions): A container for pipeline options.\n\nReturns:\n str: Container image for remote execution.", "source": "github_repos"} +{"code": "def symmetric_kl_divergence(predicted, actual):\n epsilon = tf.constant(1e-07, dtype=tf.float32, name='epsilon')\n p = tf.math.maximum(predicted, epsilon)\n q = tf.math.maximum(actual, epsilon)\n kld_1 = tf.math.reduce_sum(tf.math.multiply(p, tf.math.log(tf.math.divide(p, q))))\n kld_2 = tf.math.reduce_sum(tf.math.multiply(q, tf.math.log(tf.math.divide(q, p))))\n return tf.add(kld_1, kld_2)", "docstring": "Calculate symmetric KL-divergence over two classification tensors.\n\n Note that here the classifications do not form a probability distribution.\n They are, however normalized to 0..1 and calculating a KL-divergence over them\n gives reasonable numerical results.\n\n Shape of the two inputs must be the same at inference time but is otherwise\n unconstrained.\n\nArgs:\n predicted: classification outputs from model\n actual: golden classification outputs\n\nReturns:\n Single scalar tensor with symmetric KL-divergence between predicted and\n actual.", "source": "github_repos"} +{"code": "def __init__(self, value_type, default: typing.Optional[numbers.Number]=MISSING_VALUE, min_value: typing.Optional[numbers.Number]=None, max_value: typing.Optional[numbers.Number]=None, is_noneable: bool=False, frozen: bool=False):\n if min_value is not None and max_value is not None and (min_value > max_value):\n raise ValueError(f'\"max_value\" must be equal or greater than \"min_value\". Encountered: min_value={min_value}, max_value={max_value}.')\n self._min_value = min_value\n self._max_value = max_value\n super().__init__(value_type, default, is_noneable=is_noneable, frozen=frozen)", "docstring": "Constructor.\n\nArgs:\n value_type: Type of number.\n default: Default value for this spec.\n min_value: (Optional) minimum value of acceptable values.\n max_value: (Optional) maximum value of acceptable values.\n is_noneable: If True, None is acceptable.\n frozen: If True, values other than the default value is not accceptable.", "source": "github_repos"} +{"code": "def sticky_attribute_assignment(trackable, name, value):\n if isinstance(value, (tracking.TrackedList, tracking.TrackedDict, tracking.TrackedSet)) and hasattr(trackable, '_tracked'):\n trackable._tracked.append(name)\n if not tracking.is_tracking_enabled():\n return value\n if isinstance(value, tf.__internal__.tracking.Trackable):\n trackable._track_trackable(value, name=name, overwrite=True)\n return value", "docstring": "Adds dependencies, called from __setattr__.\n\nArgs:\n trackable: The object to add dependencies to (generally the one having\n an attribute assigned).\n name: The attribute name being assigned.\n value: The value being assigned. Not necessarily a trackable object.\n\nReturns:\n The value which should be stored in the attribute.", "source": "github_repos"} +{"code": "def decode(self, spec, encoded_value):\n raise NotImplementedError(f'{type(self).__name__}.decode')", "docstring": "Decodes `value` from a batchable tensor encoding.\n\nArgs:\n spec: The TypeSpec for the result value. If encoded values with spec `s`\n were batched, then `spec` should be `s.batch(batch_size)`; or if encoded\n values with spec `s` were unbatched, then `spec` should be\n `s.unbatch()`.\n encoded_value: A nest of values returned by `encode`; or a nest of values\n that was formed by stacking, unstacking, or concatenating the\n corresponding elements of values returned by `encode`.\n\nReturns:\n A value compatible with `type_spec`.", "source": "github_repos"} +{"code": "def json_fhir_string_to_proto(raw_json: str, proto_cls: Type[_T], *, validate: bool=True, default_timezone: str=_primitive_time_utils.SIMPLE_ZULU) -> _T:\n resource = proto_cls()\n merge_json_fhir_string_into_proto(raw_json, resource, validate=validate, default_timezone=default_timezone)\n return resource", "docstring": "Creates a resource of proto_cls and merges contents of raw_json into it.\n\nArgs:\n raw_json: The raw FHIR JSON string to convert.\n proto_cls: A subclass of message.Message to instantiate and return.\n validate: A Boolean value indicating if validation should be performed on\n the resultant Message. Validation takes the form of ensuring that basic\n checks such as cardinality guarantees, required field adherence, etc. are\n met. Defaults to True.\n default_timezone: A string specifying the timezone string to use for time-\n like FHIR data during parsing. Defaults to 'Z' for UTC.\n\nRaises:\n fhir_errors.InvalidFhirError: In the event that raw_json was not valid FHIR.\n\nReturns:\n An instance of proto_cls with FHIR JSON data from the raw_json\n representation.", "source": "github_repos"} +{"code": "def __init__(self, founded_command='_silence_', score=0.0, is_new_command=False):\n self._founded_command = founded_command\n self._score = score\n self._is_new_command = is_new_command", "docstring": "Construct a recognition result.\n\nArgs:\n founded_command: A string indicating the word just founded.\n score: A float representing the confidence of founded word.\n is_new_command: A boolean indicating if the founded command is a new one\n against the last one.", "source": "github_repos"} +{"code": "def forward(self, spectrogram: torch.FloatTensor, global_conditioning: Optional[torch.FloatTensor]=None) -> torch.FloatTensor:\n hidden_states = self.conv_pre(spectrogram)\n if global_conditioning is not None:\n hidden_states = hidden_states + self.cond(global_conditioning)\n for i in range(self.num_upsamples):\n hidden_states = nn.functional.leaky_relu(hidden_states, self.config.leaky_relu_slope)\n hidden_states = self.upsampler[i](hidden_states)\n res_state = self.resblocks[i * self.num_kernels](hidden_states)\n for j in range(1, self.num_kernels):\n res_state += self.resblocks[i * self.num_kernels + j](hidden_states)\n hidden_states = res_state / self.num_kernels\n hidden_states = nn.functional.leaky_relu(hidden_states)\n hidden_states = self.conv_post(hidden_states)\n waveform = torch.tanh(hidden_states)\n return waveform", "docstring": "Converts a spectrogram into a speech waveform.\n\nArgs:\n spectrogram (`torch.FloatTensor` of shape `(batch_size, config.spectrogram_bins, sequence_length)`):\n Tensor containing the spectrograms.\n global_conditioning (`torch.FloatTensor` of shape `(batch_size, config.speaker_embedding_size, 1)`, *optional*):\n Tensor containing speaker embeddings, for multispeaker models.\n\nReturns:\n `torch.FloatTensor`: Tensor of shape shape `(batch_size, 1, num_frames)` containing the speech waveform.", "source": "github_repos"} +{"code": "def on_test_begin(self, logs=None):", "docstring": "Called at the beginning of evaluation or validation.\n\n Subclasses should override for any actions to run.\n\nArgs:\n logs: Dict. Currently no data is passed to this argument for this\n method but that may change in the future.", "source": "github_repos"} +{"code": "def convert_to_tensor_or_ragged_tensor(value, dtype=None, preferred_dtype=None, name=None):\n if isinstance(value, RaggedTensor):\n if dtype and (not dtype.is_compatible_with(value.dtype)):\n raise ValueError(f'Tensor conversion requested dtype {dtype.name} for RaggedTensor with dtype {value.dtype.name}: {value}.')\n return value\n elif isinstance(value, ragged_tensor_value.RaggedTensorValue):\n with ops.name_scope(name, 'ConvertToTensorOrRaggedTensor', []):\n flat_values = ops.convert_to_tensor(value=value.flat_values, dtype=dtype, dtype_hint=preferred_dtype, name='flat_values')\n return RaggedTensor.from_nested_row_splits(flat_values, value.nested_row_splits, validate=False)\n else:\n return tensor_conversion.convert_to_tensor_v2_with_dispatch(value=value, dtype=dtype, dtype_hint=preferred_dtype, name=name)", "docstring": "Converts value to a `RaggedTensor` or `Tensor`.\n\n * If `value` is a `RaggedTensor`, then return it as-is.\n * If `value` is a `RaggedTensorValue`, return a corresponding constant\n `RaggedTensor`.\n * Otherwise, use `convert_to_tensor` to convert `value` to a `Tensor`.\n\nArgs:\n value: A `RaggedTensor`, a `RaggedTensorValue`, or an object whose type has\n a registered `Tensor` conversion function.\n dtype: Optional element type for the returned tensor. If missing the type\n is inferred from the type of `value`.\n preferred_dtype: Optional element type for the returned tensor, used when\n dtype is None. This argument has no effect if `value` is already a\n tensor, or when conversion is not possible.\n name: Optional name to use if a new `Tensor` is created.\n\nReturns:\n A `Tensor` or `RaggedTensor`.", "source": "github_repos"} +{"code": "def deconv_output_length(input_length, filter_size, padding, stride):\n if input_length is None:\n return None\n input_length *= stride\n if padding == 'valid':\n input_length += max(filter_size - stride, 0)\n elif padding == 'full':\n input_length -= stride + filter_size - 2\n return input_length", "docstring": "Determines output length of a transposed convolution given input length.\n\nArgs:\n input_length: integer.\n filter_size: integer.\n padding: one of \"same\", \"valid\", \"full\".\n stride: integer.\n\nReturns:\n The output length (integer).", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.Tensor, original_hidden_states: Optional[torch.Tensor]=None, layer_idx: Optional[int]=None, attention_mask: Optional[torch.Tensor]=None, causal_mask: Optional[torch.Tensor]=None, past_key_value: Optional[Zamba2HybridDynamicCache]=None, output_attentions: Optional[bool]=False, use_cache: Optional[bool]=False, position_embeddings: Optional[torch.LongTensor]=None) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n layer_outputs = self.shared_transformer(hidden_states, original_hidden_states=original_hidden_states, layer_idx=layer_idx, attention_mask=causal_mask, past_key_value=past_key_value, output_attentions=output_attentions, position_embeddings=position_embeddings)\n transformer_hidden_states = layer_outputs[0]\n if output_attentions:\n self_attn_weights = layer_outputs[1]\n transformer_hidden_states = self.linear(transformer_hidden_states)\n layer_outputs = self.mamba_decoder(hidden_states, transformer_hidden_states=transformer_hidden_states, attention_mask=attention_mask, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, position_embeddings=position_embeddings)\n if output_attentions:\n layer_outputs = (layer_outputs[0], self_attn_weights) + layer_outputs[2:]\n return layer_outputs", "docstring": "Args:\n hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\n original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with\n hidden activations to form the input of the shared transformer layer.\n layer_idx (`int`): layer number.\n attention_mask (`torch.FloatTensor`, *optional*): attention mask of size\n `(batch, sequence_length)` where padding elements are indicated by 0.\n past_key_value (`Zamba2HybridDynamicCache`, *optional*): cached past key and value projection states\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding\n (see `past_key_values`).\n position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):\n Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,\n with `head_dim` being the embedding dimension of each attention head.", "source": "github_repos"} +{"code": "def _wrap_and_check_metrics(self, metrics):\n if not isinstance(metrics, dict):\n metrics = {self.METRICS_NAME: metrics}\n outputs = {}\n for key, value in metrics.items():\n if isinstance(value, tuple):\n metric_val, metric_op = value\n else:\n metric_val = value.result()\n assert len(value.updates) == 1\n metric_op = value.updates[0]\n key = self._check_output_key(key, self.METRICS_NAME)\n key = self._prefix_key(key, self.METRICS_NAME)\n val_name = key + self._SEPARATOR_CHAR + self.METRIC_VALUE_SUFFIX\n op_name = key + self._SEPARATOR_CHAR + self.METRIC_UPDATE_SUFFIX\n if not isinstance(metric_val, tensor.Tensor):\n raise ValueError('{} output value must be a Tensor; got {}.'.format(key, metric_val))\n if not (tensor_util.is_tf_type(metric_op) or isinstance(metric_op, ops.Operation)):\n raise ValueError('{} update_op must be a Tensor or Operation; got {}.'.format(key, metric_op))\n metric_op_tensor = metric_op\n if not isinstance(metric_op, tensor.Tensor):\n with ops.control_dependencies([metric_op]):\n metric_op_tensor = constant_op.constant([], name='metric_op_wrapper')\n outputs[val_name] = metric_val\n outputs[op_name] = metric_op_tensor\n return outputs", "docstring": "Handle the saving of metrics.\n\n Metrics is either a tuple of (value, update_op), or a dict of such tuples.\n Here, we separate out the tuples and create a dict with names to tensors.\n\nArgs:\n metrics: Dict of metric results keyed by name.\n The values of the dict can be one of the following:\n (1) instance of `Metric` class.\n (2) (metric_value, update_op) tuples, or a single tuple.\n metric_value must be a Tensor, and update_op must be a Tensor or Op.\n\nReturns:\n dict of output_names to tensors\n\nRaises:\n ValueError: if the dict key is not a string, or the metric values or ops\n are not tensors.", "source": "github_repos"} +{"code": "def cos(self: EventSetOrNode) -> EventSetOrNode:\n from temporian.core.operators.unary import cos\n return cos(self)", "docstring": "Calculates the cosine of an [`EventSet`][temporian.EventSet]'s features.\n\n Can only be used on floating point features.\n\nExample:\n ```python\n >>> a = tp.event_set(\n ... timestamps=[1, 2, 3, 4, 5],\n ... features={\"M\": [0, np.pi/3, np.pi/2, np.pi, 2*np.pi]},\n ... )\n >>> a.cos()\n indexes: ...\n timestamps: [1. 2. 3. 4. 5.]\n 'M': [ 1.0000e+00 5.0000e-01 6.1232e-17 -1.0000e+00 1.0000e+00]\n ...\n\n ```\n\nReturns:\n EventSetOrNode with cosine of input features.", "source": "github_repos"} +{"code": "def _list_all_concrete_functions_for_serialization(self):\n seen_signatures = []\n if self.input_signature is not None:\n seen_signatures.append((self.input_signature, {}))\n else:\n concrete_functions = self._list_all_concrete_functions()\n for concrete_function in concrete_functions:\n signature = concrete_function.structured_input_signature\n flattened = nest.flatten(signature)\n if any((isinstance(arg, func_graph_module.UnknownArgument) for arg in flattened)):\n logging.info('Unsupported signature for serialization: %s.', signature)\n continue\n equal_to_signature = functools.partial(function_type_utils.is_same_structure, signature, check_values=True)\n if not any((equal_to_signature(s) for s in seen_signatures)):\n seen_signatures.append(signature)\n concrete_functions = []\n for args, kwargs in seen_signatures:\n concrete_functions.append(self.get_concrete_function(*args, **kwargs))\n return concrete_functions", "docstring": "Returns all concrete functions for serialization.\n\nReturns:\n A list of instances of `ConcreteFunction`.", "source": "github_repos"} +{"code": "def execution_to_tensor_values(self, execution):\n debug_event = self._reader.read_execution_event(execution.locator)\n return [_parse_tensor_value(tensor_proto) for tensor_proto in debug_event.execution.tensor_protos]", "docstring": "Read the full tensor values from an Execution or ExecutionDigest.\n\nArgs:\n execution: An `ExecutionDigest` or `ExecutionDigest` object.\n\nReturns:\n A list of numpy arrays representing the output tensor values of the\n execution event.", "source": "github_repos"} +{"code": "def _client_receive(self):\n try:\n return self._client.readline()\n except socket.error as e:\n raise errors.Error(self._device, f'Encountered socket error \"{e}\" reading RPC response') from e", "docstring": "Receives the server's response of an RPC message.\n\nReturns:\n Raw bytes of the response.\n\nRaises:\n errors.Error: if a socket error occurred during the read.", "source": "github_repos"} +{"code": "def __init__(self, save_steps=None, save_secs=None, output_dir=None, summary_writer=None, scaffold=None, summary_op=None):\n if scaffold is None and summary_op is None or (scaffold is not None and summary_op is not None):\n raise ValueError('Exactly one of scaffold or summary_op must be provided.')\n self._summary_op = summary_op\n self._summary_writer = summary_writer\n self._output_dir = output_dir\n self._scaffold = scaffold\n self._timer = SecondOrStepTimer(every_secs=save_secs, every_steps=save_steps)", "docstring": "Initializes a `SummarySaverHook`.\n\nArgs:\n save_steps: `int`, save summaries every N steps. Exactly one of\n `save_secs` and `save_steps` should be set.\n save_secs: `int`, save summaries every N seconds.\n output_dir: `string`, the directory to save the summaries to. Only used if\n no `summary_writer` is supplied.\n summary_writer: `SummaryWriter`. If `None` and an `output_dir` was passed,\n one will be created accordingly.\n scaffold: `Scaffold` to get summary_op if it's not provided.\n summary_op: `Tensor` of type `string` containing the serialized `Summary`\n protocol buffer or a list of `Tensor`. They are most likely an output by\n TF summary methods like `tf.compat.v1.summary.scalar` or\n `tf.compat.v1.summary.merge_all`. It can be passed in as one tensor; if\n more than one, they must be passed in as a list.\n\nRaises:\n ValueError: Exactly one of scaffold or summary_op should be set.", "source": "github_repos"} +{"code": "def infer_schema(stats_path, schema_path):\n print('Infering schema from statistics.')\n schema = tfdv.infer_schema(tfdv.load_statistics(stats_path), infer_feature_shape=False)\n print(text_format.MessageToString(schema))\n print('Writing schema to output path.')\n file_io.write_string_to_file(schema_path, text_format.MessageToString(schema))", "docstring": "Infers a schema from stats in stats_path.\n\nArgs:\n stats_path: Location of the stats used to infer the schema.\n schema_path: Location where the inferred schema is materialized.", "source": "github_repos"} +{"code": "def convert_old_keys_to_new_keys(state_dict_keys: Optional[dict]=None):\n output_dict = {}\n if state_dict_keys is not None:\n old_text = '\\n'.join(state_dict_keys)\n new_text = old_text\n for pattern, replacement in ORIGINAL_TO_CONVERTED_KEY_MAPPING.items():\n if replacement is None:\n new_text = re.sub(pattern, '', new_text)\n continue\n new_text = re.sub(pattern, replacement, new_text)\n output_dict = dict(zip(old_text.split('\\n'), new_text.split('\\n')))\n return output_dict", "docstring": "Converts old keys to new keys using the mapping and dynamically removes the 'ijepa.' prefix if necessary.\n\nArgs:\n state_dict_keys (dict): The keys from the state_dict to convert.\n\nReturns:\n dict: A mapping from old keys to new keys.", "source": "github_repos"} +{"code": "def should_fire(self, time_domain, timestamp, window, context):\n pass", "docstring": "Whether this trigger should cause the window to fire.\n\nArgs:\n time_domain: WATERMARK for event-time timers and REAL_TIME for\n processing-time timers.\n timestamp: for time_domain WATERMARK, it represents the\n watermark: (a lower bound on) the watermark of the system\n and for time_domain REAL_TIME, it represents the\n trigger: timestamp of the processing-time timer.\n window: the window whose trigger is being considered\n context: a context (e.g. a TriggerContext instance) for managing state\n and setting timers\n\nReturns:\n whether this trigger should cause a firing", "source": "github_repos"} +{"code": "def Encode(self):\n assert self.value_dict_or_array is not None\n logging.log(1, 'Encoding ' + self.name)\n resolved = MessageValue._ResolveVars(self.value_dict_or_array)\n logging.debug('Resolved: ' + str(resolved))\n return self.msg.encoding.SerializeToString(resolved, self.msg)", "docstring": "Encode this message instance into actual data stream.\n\n The supported encoding methods are: json, protobuf, and user-defined\n encodings.\n\nReturns:\n A string encoded.", "source": "github_repos"} +{"code": "def __call__(self, images: ImageInput=None, text: Optional[Union[str, List[str], TextInput, PreTokenizedInput]]=None, audio=None, videos=None, **kwargs: Unpack[BlipProcessorKwargs]) -> BatchEncoding:\n if images is None and text is None:\n raise ValueError('You have to specify either images or text.')\n text_encoding = None\n output_kwargs = self._merge_kwargs(BlipProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs)\n if text is not None:\n text_encoding = self.tokenizer(text, **output_kwargs['text_kwargs'])\n if images is not None:\n encoding_image_processor = self.image_processor(images, **output_kwargs['images_kwargs'])\n if text_encoding is not None:\n encoding_image_processor.update(text_encoding)\n return encoding_image_processor\n return text_encoding", "docstring": "This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and\n [`BertTokenizerFast.__call__`] to prepare text for the model.\n\n Please refer to the docstring of the above two methods for more information.\n\nArgs:\n images (`ImageInput`):\n The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch\n tensor. Both channels-first and channels-last formats are supported.\n text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):\n The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings\n (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set\n `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors of a particular framework. Acceptable values are:\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return NumPy `np.ndarray` objects.\n - `'jax'`: Return JAX `jnp.ndarray` objects.", "source": "github_repos"} +{"code": "def __init__(self, config, exclusions=None):\n self.config = config\n self.stored_ids = {name: set() for name in self.config.keys()}\n self.locked = False\n self._lock_violation_msg = None\n self.exclusions = exclusions or {}", "docstring": "Attribute tracker, used for e.g. Variable tracking.\n\n Monitors certain attribute types\n and put them in appropriate lists in case of a match.\n\n Also passively tracks certain mutable collections\n (dict, list) so that items added to them later\n still get tracked. This is done by wrapping these\n collections into an equivalent, tracking-aware object.\n\nExample:\n ```python\n def __init__(self):\n self.tracker = Tracker(\n # Format: `name: (test_fn, store)`\n {\n \"variables\":\n (lambda x: isinstance(x, Variable), self._variables),\n \"metrics\": (lambda x: isinstance(x, Metric), self._metrics),\n \"layers\": (lambda x: isinstance(x, Layer), self._layers),\n }\n )\n\n def __setattr__(self, name, value):\n if hasattr(self, \"_tracker\"):\n value = self._tracker.track(value)\n return super().__setattr__(name, value)\n ```", "source": "github_repos"} +{"code": "def _check_params(window_length, dtype):\n if not dtype.is_floating:\n raise ValueError('dtype must be a floating point type. Found %s' % dtype)\n window_length = ops.convert_to_tensor(window_length, dtype=dtypes.int32)\n window_length.shape.assert_has_rank(0)\n return window_length", "docstring": "Check window_length and dtype params.\n\nArgs:\n window_length: A scalar value or `Tensor`.\n dtype: The data type to produce. Must be a floating point type.\n\nReturns:\n window_length converted to a tensor of type int32.\n\nRaises:\n ValueError: If `dtype` is not a floating point type or window_length is not\n a scalar.", "source": "github_repos"} +{"code": "def __init__(self, unique_id, start_logits, end_logits, start_top_index=None, end_top_index=None, cls_logits=None):\n self.start_logits = start_logits\n self.end_logits = end_logits\n self.unique_id = unique_id\n if start_top_index:\n self.start_top_index = start_top_index\n self.end_top_index = end_top_index\n self.cls_logits = cls_logits", "docstring": "Constructs a SquadResult which can be used to evaluate a model's output on the SQuAD dataset.\n\nArgs:\n unique_id: The unique identifier corresponding to that example.\n start_logits: The logits corresponding to the start of the answer\n end_logits: The logits corresponding to the end of the answer", "source": "github_repos"} +{"code": "def call_with_mapped_args(self, mapped_args: MappedArgs[FrameType]) -> _HasReturnT:", "docstring": "Calls this function with the given mapped arguments.\n\nArgs:\n mapped_args: The function arguments mapped to parameter names.\n\nReturns:\n An object with information about the result of the function call, with a\n get_return_value() method that retrieves the return value.", "source": "github_repos"} +{"code": "def _pad_for_batching(self, pixel_values: List[np.ndarray], data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None):\n max_patch = max((len(x) for x in pixel_values))\n pixel_values = [self.pad(image, padding=((0, max_patch - image.shape[0]), (0, 0), (0, 0), (0, 0)), data_format=data_format, input_data_format=input_data_format) for image in pixel_values]\n return pixel_values", "docstring": "Pads images on the `num_of_patches` dimension with zeros to form a batch of same number of patches.\n\nArgs:\n pixel_values (`List[np.ndarray]`):\n An array of pixel values of each images of shape (`batch_size`, `num_patches`, `image_in_3D`)\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format for the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use the inferred format of the input image.\n\nReturns:\n List[`np.ndarray`]: The padded images.", "source": "github_repos"} +{"code": "def validate_slicing_string(slicing_string):\n return bool(re.search('^\\\\[(\\\\d|,|\\\\s|:)+\\\\]$', slicing_string))", "docstring": "Validate a slicing string.\n\n Check if the input string contains only brackets, digits, commas and\n colons that are valid characters in numpy-style array slicing.\n\nArgs:\n slicing_string: (str) Input slicing string to be validated.\n\nReturns:\n (bool) True if and only if the slicing string is valid.", "source": "github_repos"} +{"code": "def volatility(self, strike: types.FloatTensor, expiry_dates: Optional[types.DateTensor]=None, expiry_times: Optional[types.FloatTensor]=None, term: Optional[types.Period]=None) -> types.FloatTensor:\n pass", "docstring": "Returns the interpolated volatility on a specified set of expiries.\n\nArgs:\n strike: The strikes for which the interpolation is desired.\n expiry_dates: Optional input specifying the expiry dates for which\n interpolation is desired. The user should supply either `expiry_dates`\n or `expiry_times` for interpolation.\n expiry_times: Optional real `Tensor` containing the time to expiration\n for which interpolation is desired. The user should supply either\n `expiry_dates` or `expiry_times` for interpolation.\n term: Optional input specifying the term of the underlying rate for\n which the interpolation is desired. Relevant for interest rate implied\n volatility data.\n\nReturns:\n A `Tensor` of the same shape as `expiry` with the interpolated volatility\n from the volatility surface.", "source": "github_repos"} +{"code": "def _BiasAddGradV1(unused_bias_op: ops.Operation, received_grad):\n reduction_dim_tensor = math_ops.range(array_ops.rank(received_grad) - 1)\n return (received_grad, math_ops.reduce_sum(received_grad, reduction_dim_tensor))", "docstring": "Return the gradients for the 2 inputs of bias_op.\n\n The first input of unused_bias_op is the tensor t, and its gradient is\n just the gradient the unused_bias_op received.\n\n The second input of unused_bias_op is the bias vector which has one fewer\n dimension than \"received_grad\" (the batch dimension.) Its gradient is the\n received gradient Summed on the batch dimension, which is the first dimension.\n\nArgs:\n unused_bias_op: The BiasOp for which we need to generate gradients.\n received_grad: Tensor. The gradients passed to the BiasOp.\n\nReturns:\n Two tensors, the first one for the \"tensor\" input of the BiasOp,\n the second one for the \"bias\" input of the BiasOp.", "source": "github_repos"} +{"code": "def update_state(self, y_true, y_pred, sample_weight=None):\n metrics_utils.update_confusion_matrix_variables({metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives, metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives}, y_true, y_pred, thresholds=self.thresholds, thresholds_distributed_evenly=self._thresholds_distributed_evenly, top_k=self.top_k, class_id=self.class_id, sample_weight=sample_weight)", "docstring": "Accumulates true positive and false negative statistics.\n\nArgs:\n y_true: The ground truth values, with the same dimensions as\n `y_pred`. Will be cast to `bool`.\n y_pred: The predicted values. Each element must be in the range\n `[0, 1]`.\n sample_weight: Optional weighting of each example. Defaults to `1`.\n Can be a tensor whose rank is either 0, or the same rank as\n `y_true`, and must be broadcastable to `y_true`.", "source": "github_repos"} +{"code": "def forward(self, input_tensor: torch.LongTensor, attention_mask: Optional[bool]=None, output_hidden_states: Optional[bool]=None, output_attentions: Optional[bool]=False, return_dict: Optional[bool]=None):\n feature_representation = input_tensor\n if self.embed is not None:\n feature_representation = self.embed(feature_representation)\n hidden_states, pos_emb = self.pos_enc(feature_representation)\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n for conformer_layer in self.conformer_layers:\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n layer_outputs = conformer_layer(hidden_states, pos_emb, attention_mask, output_attentions)\n hidden_states = layer_outputs[0]\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[1],)\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n if not return_dict:\n return tuple((v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None))\n return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions)", "docstring": "Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you\n provide it.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n for more detail.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n\nReturns:\n `torch.Tensor`:\n Output tensor of shape `(batch, time, attention_dim)`.", "source": "github_repos"} +{"code": "def _get_executor_init(self, workers):\n\n def pool_fn(seqs):\n pool = get_pool_class(True)(workers, initializer=init_pool_generator, initargs=(seqs, self.random_seed, get_worker_id_queue()))\n _DATA_POOLS.add(pool)\n return pool\n return pool_fn", "docstring": "Gets the Pool initializer for multiprocessing.\n\nArgs:\n workers: Number of works.\n\nReturns:\n A Function to initialize the pool", "source": "github_repos"} +{"code": "def add_ordinary_node(self, ast_node):\n node = self._add_new_node(ast_node)\n self.leaves = set((node,))\n return node", "docstring": "Grows the graph by adding an ordinary CFG node.\n\n Ordinary nodes are followed by the next node, in lexical order, that is,\n they become the new leaf set.\n\nArgs:\n ast_node: ast.AST\n\nReturns:\n Node", "source": "github_repos"} +{"code": "def _preprocess_grad(grad, body_graph_output, while_op_input, while_op_output):\n if not _is_trainable(body_graph_output):\n return None\n if while_op_output.dtype in (dtypes.resource, dtypes.variant) and default_gradient.supports_default_grad(while_op_input) and (grad is None):\n return _zeros_like(while_op_input, while_op_output)\n if isinstance(grad, indexed_slices.IndexedSlices):\n return ops.convert_to_tensor(grad)\n return grad", "docstring": "Returns the initial gradient to be used for a given output tensor.\n\nArgs:\n grad: the original gradient Tensor passed to the gradient function.\n body_graph_output: the corresponding Tensor in the body graph.\n while_op_input: the corresponding Tensor input of the While op.\n while_op_output: the corresponding Tensor output of the While op.\n\nReturns:\n A Tensor or None.", "source": "github_repos"} +{"code": "def find_all_documented_objects() -> List[str]:\n documented_obj = []\n documented_methods_map = {}\n for doc_file in Path(PATH_TO_DOC).glob('**/*.md'):\n with open(doc_file, 'r', encoding='utf-8', newline='\\n') as f:\n content = f.read()\n raw_doc_objs = re.findall('\\\\[\\\\[autodoc\\\\]\\\\]\\\\s+(\\\\S+)\\\\s+', content)\n documented_obj += [obj.split('.')[-1] for obj in raw_doc_objs]\n for obj in raw_doc_objs:\n obj_public_methods = re.findall(f'\\\\[\\\\[autodoc\\\\]\\\\] {obj}((\\\\n\\\\s+-.*)+)', content)\n if len(obj_public_methods) == 0:\n continue\n else:\n documented_methods_map[obj] = re.findall('(?<=-\\\\s).*', obj_public_methods[0][0])\n return (documented_obj, documented_methods_map)", "docstring": "Parse the content of all doc files to detect which classes and functions it documents.\n\nReturns:\n `List[str]`: The list of all object names being documented.\n `Dict[str, List[str]]`: A dictionary mapping the object name (full import path, e.g.\n `integrations.PeftAdapterMixin`) to its documented methods", "source": "github_repos"} +{"code": "def __init__(self, variables, name='ShardedVariable'):\n super(ShardedVariableMixin, self).__init__()\n self._variables = variables\n self._name = name\n if not isinstance(variables, Sequence) or not variables or any((not isinstance(v, variables_lib.Variable) for v in variables)):\n raise TypeError(f'Argument `variables` should be a non-empty list of `variables.Variable`s. Received {variables}')\n var_dtypes = {v.dtype for v in variables}\n if len(var_dtypes) > 1:\n raise ValueError(f'All elements in argument `variables` must have the same dtype. Received dtypes: {[v.dtype for v in variables]}')\n first_var = variables[0]\n self._dtype = first_var.dtype\n higher_dim_shapes = {tuple(v.shape.as_list()[1:]) for v in variables}\n if len(higher_dim_shapes) > 1:\n raise ValueError(f'All elements in argument `variables` must have the same shapes except for the first axis. Received shapes: {[v.shape for v in variables]}')\n first_dim = sum((int(v.shape.as_list()[0]) for v in variables))\n self._shape = tensor_shape.TensorShape([first_dim] + first_var.shape.as_list()[1:])\n for v in variables:\n v._sharded_container = weakref.ref(self)\n self._var_offsets = [[0 for _ in range(len(first_var.shape))] for _ in range(len(variables))]\n for i in range(1, len(variables)):\n self._var_offsets[i][0] += self._var_offsets[i - 1][0] + variables[i - 1].shape.as_list()[0]\n save_slice_info = [v._get_save_slice_info() for v in variables]\n if any((slice_info is not None for slice_info in save_slice_info)):\n raise ValueError(f'`SaveSliceInfo` should not be set for all elements in argument `variables`. `ShardedVariable` will infer `SaveSliceInfo` according to the order of the elements `variables`. Received save slice info {save_slice_info}')\n self._saving_variable = resource_variable_ops.UninitializedVariable(shape=self._shape, dtype=self._dtype, name=self._name, trainable=self._variables[0].trainable, synchronization=variables_lib.VariableSynchronization.NONE, aggregation=variables_lib.VariableAggregation.NONE)", "docstring": "Treats `variables` as shards of a larger Variable.\n\nExample:\n ```\n variables = [\n tf.Variable(..., shape=(10, 100), dtype=tf.float32),\n tf.Variable(..., shape=(15, 100), dtype=tf.float32),\n tf.Variable(..., shape=(5, 100), dtype=tf.float32)\n ]\n sharded_variable = ShardedVariableMixin(variables)\n assert sharded_variable.shape.as_list() == [30, 100]\n ```\n\nArgs:\n variables: A list of `ResourceVariable`s that comprise this sharded\n variable. Variables should not be shared between different\n `ShardedVariableMixin` objects.\n name: String. Name of this container. Defaults to \"ShardedVariable\".", "source": "github_repos"} +{"code": "def read_up_to(self, queue, num_records, name=None):\n if isinstance(queue, tensor_lib.Tensor):\n queue_ref = queue\n else:\n queue_ref = queue.queue_ref\n if self._reader_ref.dtype == dtypes.resource:\n return gen_io_ops.reader_read_up_to_v2(self._reader_ref, queue_ref, num_records, name=name)\n else:\n old_queue_op = gen_data_flow_ops.fake_queue(queue_ref)\n return gen_io_ops.reader_read_up_to(self._reader_ref, old_queue_op, num_records, name=name)", "docstring": "Returns up to num_records (key, value) pairs produced by a reader.\n\n Will dequeue a work unit from queue if necessary (e.g., when the\n Reader needs to start reading from a new file since it has\n finished with the previous file).\n It may return less than num_records even before the last batch.\n\nArgs:\n queue: A Queue or a mutable string Tensor representing a handle\n to a Queue, with string work items.\n num_records: Number of records to read.\n name: A name for the operation (optional).\n\nReturns:\n A tuple of Tensors (keys, values).\n keys: A 1-D string Tensor.\n values: A 1-D string Tensor.", "source": "github_repos"} +{"code": "def check_alive(self, worker_name):\n if self._context_handle:\n return pywrap_tfe.TFE_ContextCheckAlive(self._context_handle, worker_name)\n else:\n raise ValueError('Context is not initialized.')", "docstring": "Checks whether a remote worker is alive or not.\n\nArgs:\n worker_name: a string representing the remote worker. It must be a fully\n specified name like \"/job:worker/replica:0/task:0\".\n\nReturns:\n a boolean indicating whether the remote worker is alive or not.\n\nRaises:\n ValueError: if context is not initialized.", "source": "github_repos"} +{"code": "def upload_file(filename: str, config: Config, full_table_id: str, action: Action=Action.APPEND, service_account_email: Optional[str]=None) -> None:\n if service_account_email:\n auth_config = AuthConfig(service_account_email=service_account_email)\n else:\n auth_config = None\n table_metadata = build_table_metadata(full_table_id)\n credentials = get_credentials(auth_config)\n bq_legacy_client = get_bq_legacy_client(table_metadata.project_id, credentials)\n table_exists = get_table(bq_legacy_client, table_metadata) is not None\n if table_exists and action == Action.REPLACE:\n bq_legacy_client.delete_table(table_metadata.full_table_id)\n table_exists = False\n if not table_exists:\n schema = generate_bigquery_schema(config)\n create_table(bq_legacy_client, table_metadata, schema)\n row_count = get_csv_row_count(filename)\n columns = [column.bq_name for column in config]\n with open(filename, 'r') as f:\n csv = DictReader(f, fieldnames=columns)\n buffer_: List[Row] = []\n buffer_size = row_count // 100\n buffer = Buffer[Row](buffer_, buffer_size, lambda rows: upload_rows(bq_legacy_client, table_metadata, rows))\n for row in csv:\n buffer.push(row)\n buffer.flush(force=True)", "docstring": "Upload a data file conforming to the given config to BigQuery.\n\nArgs:\n * filename: Local path to csv file to be uploaded\n * config: Config key from configs.CONFIGS dictionary\n * full_table_id: BigQuery table id\n * action: APPEND to table or REPLACE table\n * service_account_email: Email address of service account", "source": "github_repos"} +{"code": "def _compute_llama3_parameters(config: PretrainedConfig, device: 'torch.device', seq_len: Optional[int]=None, **rope_kwargs) -> tuple['torch.Tensor', float]:\n inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)\n factor = config.rope_scaling['factor']\n low_freq_factor = config.rope_scaling['low_freq_factor']\n high_freq_factor = config.rope_scaling['high_freq_factor']\n old_context_len = config.rope_scaling['original_max_position_embeddings']\n low_freq_wavelen = old_context_len / low_freq_factor\n high_freq_wavelen = old_context_len / high_freq_factor\n wavelen = 2 * math.pi / inv_freq\n inv_freq_llama = torch.where(wavelen > low_freq_wavelen, inv_freq / factor, inv_freq)\n smooth_factor = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)\n smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / factor + smooth_factor * inv_freq_llama\n is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen)\n inv_freq_llama = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama)\n return (inv_freq_llama, attention_factor)", "docstring": "Computes the inverse frequencies for llama 3.1.\n\nArgs:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length. Unused for this type of RoPE.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n\nReturns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin.", "source": "github_repos"} +{"code": "def sparsemax(x, axis=-1):\n if any_symbolic_tensors((x,)):\n return Sparsemax(axis).symbolic_call(x)\n return backend.nn.sparsemax(x, axis=axis)", "docstring": "Sparsemax activation function.\n\n For each batch `i`, and class `j`,\n sparsemax activation function is defined as:\n\n `sparsemax(x)[i, j] = max(x[i, j] - τ(x[i, :]), 0).`\n\nArgs:\n x: Input tensor.\n axis: `int`, axis along which the sparsemax operation is applied.\n\nReturns:\n A tensor, output of sparsemax transformation. Has the same type and\n shape as `x`.\n\nExample:\n >>> x = np.array([-1., 0., 1.])\n >>> x_sparsemax = keras.ops.sparsemax(x)\n >>> print(x_sparsemax)\n array([0., 0., 1.], shape=(3,), dtype=float64)", "source": "github_repos"} +{"code": "def make_collective(self, num_processes, gpu_per_process):\n cluster_resolver = cluster_resolver_lib.TFConfigClusterResolver()\n devices = ['/job:worker/replica:0/task:%d/device:CPU:0' % cluster_resolver.task_id]\n if gpu_per_process > 0:\n devices = ['/job:worker/replica:0/task:%d/device:GPU:%d' % (cluster_resolver.task_id, i) for i in range(gpu_per_process)]\n group_size = num_processes * len(devices)\n collective = cross_device_ops_lib.CollectiveAllReduce(devices=devices, group_size=group_size, options=collective_util.Options())\n return (collective, devices, cluster_resolver.task_id)", "docstring": "Returns collectives and other info to be used in tests.\n\nArgs:\n num_processes: an integer indicating the number of processes that\n participate in the collective.\n gpu_per_process: number of GPUs (0 if no GPUs) used by each process.\n\nReturns:\n A tuple of (collective, devices, pid) where collective is a instance\n of `CollectiveAllReduce`, devices are a list of local devices (str)\n attached to the current process, and pid is the id of this process among\n all participant processes.", "source": "github_repos"} +{"code": "def _convert(value, dtype=None):\n result = numpy_compat.np_asarray(value, dtype=dtype, order='C')\n if result.dtype.char == 'S' and result is not value:\n return numpy_compat.np_asarray(value, order='C', dtype=object)\n elif result.dtype.char == 'U' and result is not value:\n value = np.vectorize(lambda x: x.encode('utf8'))(value)\n return numpy_compat.np_asarray(value, order='C', dtype=object)\n elif result.dtype.char == 'U':\n return result.astype(np.bytes_)\n else:\n return result", "docstring": "Converts an arg to numpy, avoiding dangerous string and unicode dtypes.\n\n Numpy pads with zeros when using string and unicode dtypes if different\n components of a tensor have different lengths. This is bad: ignoring the\n padding is wrong for text data, and removing the padding is wrong for binary\n data. To avoid this bug, we redo the conversion using an object dtype.\n Additionally, we convert unicode strings to (byte-)strings for\n compatibility.\n\nArgs:\n value: Value to convert to a numpy array.\n dtype: (Optional.) Desired NumPy type for the returned value.\n\nReturns:\n A numpy array.", "source": "github_repos"} +{"code": "def insert_model_in_doc_toc(old_model_patterns, new_model_patterns):\n toc_file = REPO_PATH / 'docs' / 'source' / 'en' / '_toctree.yml'\n with open(toc_file, 'r', encoding='utf8') as f:\n content = yaml.safe_load(f)\n api_idx = 0\n while content[api_idx]['title'] != 'API':\n api_idx += 1\n api_doc = content[api_idx]['sections']\n model_idx = 0\n while api_doc[model_idx]['title'] != 'Models':\n model_idx += 1\n model_doc = api_doc[model_idx]['sections']\n old_model_type = old_model_patterns.model_type\n section_idx = 0\n while section_idx < len(model_doc):\n sections = [entry['local'] for entry in model_doc[section_idx]['sections']]\n if f'model_doc/{old_model_type}' in sections:\n break\n section_idx += 1\n if section_idx == len(model_doc):\n old_model = old_model_patterns.model_name\n new_model = new_model_patterns.model_name\n print(f'Did not find {old_model} in the table of content, so you will need to add {new_model} manually.')\n return\n toc_entry = {'local': f'model_doc/{new_model_patterns.model_type}', 'title': new_model_patterns.model_name}\n model_doc[section_idx]['sections'].append(toc_entry)\n model_doc[section_idx]['sections'] = sorted(model_doc[section_idx]['sections'], key=lambda s: s['title'].lower())\n api_doc[model_idx]['sections'] = model_doc\n content[api_idx]['sections'] = api_doc\n with open(toc_file, 'w', encoding='utf-8') as f:\n f.write(yaml.dump(content, allow_unicode=True))", "docstring": "Insert the new model in the doc TOC, in the same section as the old model.\n\nArgs:\n old_model_patterns (`ModelPatterns`): The patterns for the old model.\n new_model_patterns (`ModelPatterns`): The patterns for the new model.", "source": "github_repos"} +{"code": "def __init__(self, eos_token_id: Optional[torch.Tensor]=None, num_output_tokens: int=10, max_matching_ngram_size: Optional[int]=None, max_length: int=20):\n self.num_output_tokens = num_output_tokens\n self.max_matching_ngram_size = max_matching_ngram_size if max_matching_ngram_size else 2\n self.max_length = max_length\n self.eos_token_id = eos_token_id\n if self.max_matching_ngram_size <= 0 or self.num_output_tokens <= 0:\n raise ValueError('Invalid max_matching_ngram_size or num_output_tokens')", "docstring": "`CandidateGenerator` class to be used for prompt lookup generation. This class generates candidates by looking up\n likely continuations in the provided prompt (input_ids) itself.\n Read the following blog post for more information: https://github.com/apoorvumang/prompt-lookup-decoding\n\nArgs:\n max_matching_ngram_size (`int`):\n The maximum ngram size to be considered for matching in the prompt\n num_output_tokens (`int`):\n The number of tokens to be output as candidate tokens.\n max_length (`int`):\n The number of total maximum tokens that can be generated. For decoder-only models that includes the prompt length.\n Defaults to 20, which is the max length used as default in generation config.", "source": "github_repos"} +{"code": "def ask_to_proceed_with_overwrite(filepath):\n overwrite = input('[WARNING] %s already exists - overwrite? [y/n]' % filepath).strip().lower()\n while overwrite not in ('y', 'n'):\n overwrite = input('Enter \"y\" (overwrite) or \"n\" (cancel).').strip().lower()\n if overwrite == 'n':\n return False\n print('[TIP] Next time specify overwrite=True!')\n return True", "docstring": "Produces a prompt asking about overwriting a file.\n\nArgs:\n filepath: the path to the file to be overwritten.\n\nReturns:\n True if we can proceed with overwrite, False otherwise.", "source": "github_repos"} +{"code": "def _to_backend_layout(tensor_layout):\n if tensor_layout.device_mesh is None:\n raise ValueError('Cannot create sharding when device mesh is not set for TensorLayout.')\n sharding_specs = [axis if axis else dtensor.UNSHARDED for axis in tensor_layout.axes]\n dtensor_mesh = tensor_layout.device_mesh.backend_mesh\n return dtensor.Layout(sharding_specs=sharding_specs, mesh=dtensor_mesh)", "docstring": "Convert the TensorLayout to Tensorflow backend specific Sharding.\n\nArgs:\n tensor_layout: TensorLayout instance to convert.\n\nReturns:\n A `tf.dtensor.Layout` instance.", "source": "github_repos"} +{"code": "def get_input_mask_at(self, node_index):\n inputs = self.get_input_at(node_index)\n if isinstance(inputs, list):\n return [getattr(x, '_keras_mask', None) for x in inputs]\n else:\n return getattr(inputs, '_keras_mask', None)", "docstring": "Retrieves the input mask tensor(s) of a layer at a given node.\n\nArgs:\n node_index: Integer, index of the node\n from which to retrieve the attribute.\n E.g. `node_index=0` will correspond to the\n first time the layer was called.\n\nReturns:\n A mask tensor\n (or list of tensors if the layer has multiple inputs).", "source": "github_repos"} +{"code": "def prune(self, feeds, fetches, name=None, input_signature=None, are_keyword_args_also_positional=False):\n name = name or 'pruned'\n flat_feeds = nest.flatten(feeds, expand_composites=True)\n flat_feeds = [self.graph.as_graph_element(t) for t in flat_feeds]\n for f in flat_feeds:\n if not isinstance(f, tensor_lib.Tensor):\n raise ValueError(f'All members of argument `feeds` must be tensors. Got {f} with type {type(f)}.')\n internal_captures = {id(c) for c in self.graph.internal_captures}\n flat_feeds = [f for f in flat_feeds if id(f) not in internal_captures]\n operation_fetches = []\n tensor_fetches = []\n tensor_infos = []\n\n def _fetch_preprocessing_callback(fetch):\n \"\"\"Extract out lists of ops, tensors, and tensor type info.\n\n Turns TensorInfos into Tensors in the original `fetches` structure.\n Also extracts ops from `fetches`.\n\n Args:\n fetch: The fetch to preprocess: Tensor, TensorInfo, or Operation, or\n string identifying a Tensor or Operation.\n\n Returns:\n `fetch` converted to a Tensor.\n \"\"\"\n if isinstance(fetch, ops.Operation):\n operation_fetches.append(fetch)\n return fetch\n elif isinstance(fetch, meta_graph_pb2.TensorInfo):\n tensor_infos.append(fetch)\n decoded = _get_element_from_tensor_info(fetch, self._func_graph)\n if tensor_util.is_tf_type(decoded) or isinstance(decoded, composite_tensor.CompositeTensor):\n tensor_fetches.append(decoded)\n else:\n operation_fetches.append(decoded)\n return decoded\n elif isinstance(fetch, (tensor_lib.Tensor, composite_tensor.CompositeTensor)):\n tensor_fetches.append(fetch)\n return fetch\n else:\n graph_element = self.graph.as_graph_element(fetch)\n return _fetch_preprocessing_callback(graph_element)\n fetches = nest.map_structure(_fetch_preprocessing_callback, fetches)\n tensor_fetches = nest.flatten(tensor_fetches, expand_composites=True)\n for f in flat_feeds + tensor_fetches + operation_fetches:\n if f.graph is not self._func_graph:\n raise ValueError(f'Can only prune function whose feeds and fetches from graph {self._func_graph}. Input {f} is from a different graph {f.graph}.')\n with self._func_graph.as_default():\n pruned_graph = func_graph.FuncGraph(name)\n lift_map = lift_to_graph.lift_to_graph(operation_fetches + tensor_fetches, pruned_graph, sources=flat_feeds + self.graph.internal_captures, base_graph=self._func_graph)\n pruned_graph.outputs.extend((lift_map[x] for x in tensor_fetches))\n pruned_graph.control_outputs.extend([lift_map[operation] for operation in operation_fetches])\n pruned_graph.inputs.extend((lift_map[x] for x in flat_feeds))\n for external_capture, internal_capture in self.graph.captures:\n pruned_graph.add_capture(external_capture, lift_map[internal_capture])\n for ti in tensor_infos:\n if ti.WhichOneof('encoding') == 'name':\n t = pruned_graph.as_graph_element(ti.name)\n if tensor_util.is_tf_type(t):\n t.set_shape(tensor_shape.TensorShape(ti.tensor_shape))\n for f in self.graph._functions.values():\n pruned_graph._add_function(f)\n pruned_graph.variables = self.graph.variables\n\n def _structured_output_mapping(fetched):\n \"\"\"callback for `nest.map_structure()`\"\"\"\n lifted = lift_map[fetched]\n if isinstance(lifted, ops.Operation):\n return None\n return lifted\n pruned_graph.structured_outputs = nest.map_structure(_structured_output_mapping, fetches, expand_composites=True)\n if input_signature:\n args, kwargs = input_signature\n args = () if args is None else args\n input_signature = (args, kwargs)\n pruned_graph.structured_input_signature = input_signature\n pruned_fn = WrappedFunction(pruned_graph, variable_holder=self._variable_holder, are_keyword_args_also_positional=are_keyword_args_also_positional)\n pruned_fn._num_positional_args = len(flat_feeds)\n pruned_fn._arg_keywords = [tensor.op.name for tensor in flat_feeds]\n return pruned_fn", "docstring": "Extract a subgraph of this function's underlying graph.\n\n Wraps the subgraph in a new `WrappedFunction` object.\n\nArgs:\n feeds: Input tensors to the subgraph to extract, as `Tensor` objects.\n fetches: Possibly-nested Python data structure containing information\n about outputs of the target subgraph. Each entry can either be a\n `Tensor` object (for data outputs), an `Operation` object (for control\n outputs), or a `TensorInfo` proto. Any additional shape/dtype\n information provided in a `TensorInfo` and not present in the original\n graph will be added to the returned subgraph.\n name: (optional) Name to give to the underlying `FuncGraph` of the\n returned object. If no name is provided, the graph's name will be\n `\"pruned\"`.\n input_signature: (optional) possibly-nested Python data structure\n containing `TensorSpec` objects, with which to populate the returned\n functions's `FuncGraph`'s `structured_input_signature` field.\n are_keyword_args_also_positional: whether the keyword arguments\n in `input_signature` are `POSITIONAL_OR_KEYWORD` arguments. If\n `False` (default), they are treated as `KEYWORD_ONLY`\n arguments.\n\nReturns:\n A new `WrappedFunction` object containing a copy of the portion of this\n object's graph that goes from `feeds` to `fetches`.", "source": "github_repos"} +{"code": "def _get_node_attribute_at_index(self, node_index, attr, attr_name):\n if not self._inbound_nodes:\n raise RuntimeError('The layer has never been called and thus has no defined ' + attr_name + '.')\n if not len(self._inbound_nodes) > node_index:\n raise ValueError('Asked to get ' + attr_name + ' at node ' + str(node_index) + ', but the layer has only ' + str(len(self._inbound_nodes)) + ' inbound nodes.')\n values = getattr(self._inbound_nodes[node_index], attr)\n if isinstance(values, list) and len(values) == 1:\n return values[0]\n else:\n return values", "docstring": "Private utility to retrieves an attribute (e.g. inputs) from a node.\n\n This is used to implement the methods:\n - get_input_shape_at\n - get_output_shape_at\n - get_input_at\n etc...\n\nArgs:\n node_index: Integer index of the node from which\n to retrieve the attribute.\n attr: Exact node attribute name.\n attr_name: Human-readable attribute name, for error messages.\n\nReturns:\n The layer's attribute `attr` at the node of index `node_index`.\n\nRaises:\n RuntimeError: If the layer has no inbound nodes, or if called in Eager\n mode.\n ValueError: If the index provided does not match any node.", "source": "github_repos"} +{"code": "def call(self, input_ids: tf.Tensor, pixel_values: tf.Tensor | None=None, decoder_input_ids: tf.Tensor | None=None, decoder_attention_mask: tf.Tensor | None=None, attention_mask: tf.Tensor | None=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: tf.Tensor | None=None, return_dict: Optional[bool]=None, training: Optional[bool]=None) -> Union[Tuple, TFBlipTextVisionModelOutput]:\n if labels is None and decoder_input_ids is None:\n raise ValueError('Either `decoder_input_ids` or `labels` should be passed when calling `TFBlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`')\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n vision_outputs = self.vision_model(pixel_values=pixel_values, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training)\n image_embeds = vision_outputs[0]\n image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int64)\n question_embeds = self.text_encoder(input_ids=input_ids, attention_mask=attention_mask, encoder_hidden_states=image_embeds, encoder_attention_mask=image_attention_mask, return_dict=return_dict, training=training)\n question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state\n if labels is not None and decoder_input_ids is None:\n decoder_input_ids = labels\n answer_output = self.text_decoder(input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, encoder_hidden_states=question_embeds, encoder_attention_mask=attention_mask, labels=labels, return_dict=return_dict, training=training)\n if labels is not None:\n decoder_loss = tf.reduce_mean(answer_output.loss) if return_dict else tf.reduce_mean(answer_output[0])\n else:\n decoder_loss = None\n if not return_dict:\n outputs = (decoder_loss, image_embeds, vision_outputs[0]) + vision_outputs[2:]\n return tuple((output for output in outputs if output is not None))\n return TFBlipTextVisionModelOutput(loss=decoder_loss, image_embeds=image_embeds, last_hidden_state=vision_outputs.last_hidden_state, hidden_states=vision_outputs.hidden_states, attentions=vision_outputs.attentions)", "docstring": "Returns:\n\nExample:\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, TFBlipForQuestionAnswering\n\n >>> model = TFBlipForQuestionAnswering.from_pretrained(\"Salesforce/blip-vqa-base\")\n >>> processor = AutoProcessor.from_pretrained(\"Salesforce/blip-vqa-base\")\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> # training\n >>> text = \"How many cats are in the picture?\"\n >>> label = \"2\"\n >>> inputs = processor(images=image, text=text, return_tensors=\"tf\")\n >>> labels = processor(text=label, return_tensors=\"tf\").input_ids\n\n >>> inputs[\"labels\"] = labels\n >>> outputs = model(**inputs)\n >>> loss = outputs.loss\n\n >>> # inference\n >>> text = \"How many cats are in the picture?\"\n >>> inputs = processor(images=image, text=text, return_tensors=\"tf\")\n >>> outputs = model.generate(**inputs)\n >>> print(processor.decode(outputs[0], skip_special_tokens=True))\n 2\n ```", "source": "github_repos"} +{"code": "def __init__(self, pool_size, strides, padding='valid', data_format='channels_last', name=None, **kwargs):\n if strides is None:\n raise ValueError('Argument `strides` must not be None.')\n super(MaxPooling3D, self).__init__(pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, name=name, **kwargs)", "docstring": "Max pooling layer for 3D inputs (e.g. volumes).\n\nArgs:\n pool_size: An integer or tuple/list of 3 integers:\n (pool_depth, pool_height, pool_width)\n specifying the size of the pooling window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the pooling operation.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n padding: A string. The padding method, either 'valid' or 'same'.\n Case-insensitive.\n data_format: A string. The ordering of the dimensions in the inputs.\n `channels_last` (default) and `channels_first` are supported.\n `channels_last` corresponds to inputs with shape\n `(batch, depth, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, depth, height, width)`.\n name: A string, the name of the layer.", "source": "github_repos"} +{"code": "def _pyval_update_fields(pyval, fields, depth):\n if not isinstance(pyval, (dict, list, tuple)):\n raise ValueError('Expected dict or nested list/tuple of dict')\n for key, target in fields.items():\n for _ in range(1, depth):\n target = target[-1]\n target.append(pyval[key] if isinstance(pyval, dict) else [])\n if isinstance(pyval, (list, tuple)):\n for child in pyval:\n _pyval_update_fields(child, fields, depth + 1)", "docstring": "Append the field values from `pyval` to `fields`.\n\nArgs:\n pyval: A python `dict`, or nested list/tuple of `dict`, whose value(s)\n should be appended to `fields`.\n fields: A dictionary mapping string keys to field values. Field values\n extracted from `pyval` are appended to this dictionary's values.\n depth: The depth at which `pyval` should be appended to the field values.", "source": "github_repos"} +{"code": "def _relocate_if_symbolic(self, key: Union[str, int], value: Any) -> Any:\n if isinstance(value, Symbolic):\n root_path = utils.KeyPath(key, self.sym_path)\n if value.sym_parent is not None and (value.sym_parent is not self or root_path != value.sym_path):\n value = value.clone()\n if isinstance(value, TopologyAware):\n value.sym_setpath(utils.KeyPath(key, self.sym_path))\n value.sym_setparent(self._sym_parent_for_children())\n return value", "docstring": "Relocate if a symbolic value is to be inserted as member.\n\n NOTE(daiyip): when a symbolic value is inserted into the object tree,\n if it already has a parent, we need to make a shallow copy of this object\n to avoid multiple parents. Otherwise we need to set its parent and root_path\n according to current object.\n\nArgs:\n key: Key used to insert the value.\n value: formal value to be inserted.\n\nReturns:\n Formalized value that is ready for insertion as members.", "source": "github_repos"} +{"code": "def plot_model(model, to_file='model.png', show_shapes=False, show_dtype=False, show_layer_names=False, rankdir='TB', expand_nested=False, dpi=200, show_layer_activations=False, show_trainable=False, **kwargs):\n if not model.built:\n raise ValueError('This model has not yet been built. Build the model first by calling `build()` or by calling the model on a batch of data.')\n if not check_pydot():\n message = 'You must install pydot (`pip install pydot`) for `plot_model` to work.'\n if 'IPython.core.magics.namespace' in sys.modules:\n io_utils.print_msg(message)\n return\n else:\n raise ImportError(message)\n if not check_graphviz():\n message = 'You must install graphviz (see instructions at https://graphviz.gitlab.io/download/) for `plot_model` to work.'\n if 'IPython.core.magics.namespace' in sys.modules:\n io_utils.print_msg(message)\n return\n else:\n raise ImportError(message)\n if kwargs.pop('layer_range', None) is not None:\n raise ValueError('Argument `layer_range` is no longer supported.')\n if kwargs:\n raise ValueError(f'Unrecognized keyword arguments: {kwargs}')\n dot = model_to_dot(model, show_shapes=show_shapes, show_dtype=show_dtype, show_layer_names=show_layer_names, rankdir=rankdir, expand_nested=expand_nested, dpi=dpi, show_layer_activations=show_layer_activations, show_trainable=show_trainable)\n to_file = str(to_file)\n if dot is None:\n return\n _, extension = os.path.splitext(to_file)\n if not extension:\n extension = 'png'\n else:\n extension = extension[1:]\n dot.write(to_file, format=extension)\n if extension != 'pdf':\n try:\n from IPython import display\n return display.Image(filename=to_file)\n except ImportError:\n pass", "docstring": "Converts a Keras model to dot format and save to a file.\n\nExample:\n ```python\n inputs = ...\n outputs = ...\n model = keras.Model(inputs=inputs, outputs=outputs)\n\n dot_img_file = '/tmp/model_1.png'\n keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True)\n ```\n\nArgs:\n model: A Keras model instance\n to_file: File name of the plot image.\n show_shapes: whether to display shape information.\n show_dtype: whether to display layer dtypes.\n show_layer_names: whether to display layer names.\n rankdir: `rankdir` argument passed to PyDot,\n a string specifying the format of the plot: `\"TB\"`\n creates a vertical plot; `\"LR\"` creates a horizontal plot.\n expand_nested: whether to expand nested Functional models\n into clusters.\n dpi: Image resolution in dots per inch.\n show_layer_activations: Display layer activations (only for layers that\n have an `activation` property).\n show_trainable: whether to display if a layer is trainable.\n\nReturns:\n A Jupyter notebook Image object if Jupyter is installed.\n This enables in-line display of the model plots in notebooks.", "source": "github_repos"} +{"code": "def get_test_data(train_samples, test_samples, input_shape, num_classes, random_seed=None):\n np.random.seed(random_seed)\n total_samples = train_samples + test_samples\n samples_per_class = total_samples // num_classes\n y = np.array([i for i in range(num_classes) for _ in range(samples_per_class)], dtype=np.int32)\n extra_samples = total_samples - len(y)\n y_extra = np.array([i % num_classes for i in range(extra_samples)], dtype=np.int64)\n y = np.concatenate([y, y_extra])\n templates = 2 * num_classes * np.random.random((num_classes,) + input_shape)\n x = np.zeros((total_samples,) + input_shape, dtype=np.float32)\n for i in range(total_samples):\n x[i] = templates[y[i]] + np.random.normal(loc=0, scale=1.0, size=input_shape)\n indices = np.arange(total_samples)\n np.random.shuffle(indices)\n x, y = (x[indices], y[indices])\n x_train, y_train, x_test, y_test = ([], [], [], [])\n for cls in range(num_classes):\n cls_indices = np.where(y == cls)[0]\n np.random.shuffle(cls_indices)\n train_count = int(train_samples / num_classes)\n x_train.extend(x[cls_indices[:train_count]])\n y_train.extend(y[cls_indices[:train_count]])\n x_test.extend(x[cls_indices[train_count:]])\n y_test.extend(y[cls_indices[train_count:]])\n x_train, y_train = (np.array(x_train), np.array(y_train))\n x_test, y_test = (np.array(x_test), np.array(y_test))\n train_indices = np.arange(len(x_train))\n test_indices = np.arange(len(x_test))\n np.random.shuffle(train_indices)\n np.random.shuffle(test_indices)\n x_train, y_train = (x_train[train_indices], y_train[train_indices])\n x_test, y_test = (x_test[test_indices], y_test[test_indices])\n return ((x_train, y_train), (x_test, y_test))", "docstring": "Generates balanced, stratified synthetic test data to train a model on.\n\nArgs:\n train_samples: Integer, how many training samples to generate.\n test_samples: Integer, how many test samples to generate.\n input_shape: Tuple of integers, shape of the inputs.\n num_classes: Integer, number of classes for the data and targets.\n random_seed: Integer, random seed used by Numpy to generate data.\n\nReturns:\n A tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.", "source": "github_repos"} +{"code": "def _select_class_id(ids, selected_id):\n ids = sparse_tensor.convert_to_tensor_or_sparse_tensor(ids)\n if isinstance(ids, sparse_tensor.SparseTensor):\n return sparse_ops.sparse_retain(ids, math_ops.equal(ids.values, selected_id))\n ids_shape = array_ops.shape(ids, out_type=dtypes.int64)\n ids_last_dim = array_ops.size(ids_shape) - 1\n filled_selected_id_shape = math_ops.reduced_shape(ids_shape, array_ops.reshape(ids_last_dim, [1]))\n filled_selected_id = array_ops.fill(filled_selected_id_shape, math_ops.cast(selected_id, dtypes.int64))\n result = sets.set_intersection(filled_selected_id, ids)\n return sparse_tensor.SparseTensor(indices=result.indices, values=result.values, dense_shape=ids_shape)", "docstring": "Filter all but `selected_id` out of `ids`.\n\nArgs:\n ids: `int64` `Tensor` or `SparseTensor` of IDs.\n selected_id: Int id to select.\n\nReturns:\n `SparseTensor` of same dimensions as `ids`. This contains only the entries\n equal to `selected_id`.", "source": "github_repos"} +{"code": "def add_model_tags(self, tags: Union[List[str], str]) -> None:\n if isinstance(tags, str):\n tags = [tags]\n if self.model_tags is None:\n self.model_tags = []\n for tag in tags:\n if tag not in self.model_tags:\n self.model_tags.append(tag)", "docstring": "Add custom tags into the model that gets pushed to the Hugging Face Hub. Will\n not overwrite existing tags in the model.\n\nArgs:\n tags (`Union[List[str], str]`):\n The desired tags to inject in the model\n\nExample:\n ```python\n from transformers import AutoModel\n\n model = AutoModel.from_pretrained(\"google-bert/bert-base-cased\")\n\n model.add_model_tags([\"custom\", \"custom-bert\"])\n\n # Push the model to your namespace with the name \"my-custom-bert\".\n model.push_to_hub(\"my-custom-bert\")\n ```", "source": "github_repos"} +{"code": "def squareplus(x, b=4):\n if any_symbolic_tensors((x,)):\n return Squareplus(b).symbolic_call(x)\n return backend.nn.squareplus(x, b)", "docstring": "Squareplus activation function.\n\n The Squareplus activation function is defined as:\n\n `f(x) = (x + sqrt(x^2 + b)) / 2`\n\nArgs:\n x: Input tensor.\n b: Smoothness parameter. Defaults to 4.\n\nReturns:\n A tensor with the same shape as `x`.\n\nExample:\n >>> x = np.array([-1.0, 0.0, 1.0])\n >>> x_squareplus = keras.ops.squareplus(x)\n >>> print(x_squareplus)\n array([0.6180, 1.0000, 1.6180], dtype=float32)", "source": "github_repos"} +{"code": "def emit_counter(self, category: str, name: str, pid: int, timestamp: int, counter: str, value: int) -> None:\n event = self._create_event('C', category, name, pid, 0, timestamp)\n event['args'] = {counter: value}\n self._events.append(event)", "docstring": "Emits a record for a single counter.\n\nArgs:\n category: The event category as a string.\n name: The event name as a string.\n pid: Identifier of the process generating this event as an integer.\n timestamp: The timestamp of this event as a long integer.\n counter: Name of the counter as a string.\n value: Value of the counter as an integer.", "source": "github_repos"} +{"code": "def replace_tensors_by_numpy_ndarrays(repr_ds: RepresentativeDataset, sess: session.Session) -> RepresentativeDataset:\n new_repr_ds = []\n for sample in repr_ds:\n new_sample = {}\n for input_key, input_data in sample.items():\n if isinstance(input_data, core.Tensor):\n input_data = input_data.eval(session=sess)\n new_sample[input_key] = input_data\n new_repr_ds.append(new_sample)\n return new_repr_ds", "docstring": "Replaces tf.Tensors in samples by their evaluated numpy arrays.\n\n Note: This should be run in graph mode (default in TF1) only.\n\nArgs:\n repr_ds: Representative dataset to replace the tf.Tensors with their\n evaluated values. `repr_ds` is iterated through, so it may not be reusable\n (e.g. if it is a generator object).\n sess: Session instance used to evaluate tf.Tensors.\n\nReturns:\n The new representative dataset where each tf.Tensor is replaced by its\n evaluated numpy ndarrays.", "source": "github_repos"} +{"code": "def _merge_tensor_signatures(self, signatures):\n sorted_update = []\n if self._num_signature_dimensions() > 1:\n signature_indices = self._signature_types()\n for _, val in sorted(signatures.items(), key=lambda item: signature_indices[item[0]]):\n sorted_update.append(val)\n updates = array_ops_stack.stack(sorted_update, axis=0, name='merge_single_op_signatures')\n elif self._num_signature_dimensions() == 1:\n (_, val), = signatures.items()\n updates = val\n else:\n raise ValueError('Cannot merge 0 signatures. Check the value passed for flag --signatures.')\n return updates", "docstring": "Returns a tensor that merges the given signatures.\n\nArgs:\n signatures: A dictionary of the signature updates from signature name to\n a tensor of dimension [1].\n\nReturns:\n A tensor that concats the signature values in a predefined order.\n\nRaises:\n ValueError: Unable to merge signatures.", "source": "github_repos"} +{"code": "def test_encode_with_non_root_fhir_path_constraint_succeeds(self, fhir_path_expression: str, expected_sql_expression: str, expected_fhir_path_sql_expression: str, expected_fields_referenced: List[str]):\n self.maxDiff = None\n constraint = self.build_constraint(fhir_path_expression=fhir_path_expression)\n self.assert_constraint_is_equal_to_expression(base_id='Hospital', element_definition_id='Hospital.patients', constraint=constraint, expected_sql_expression=expected_sql_expression, expected_fhir_path_sql_expression=expected_fhir_path_sql_expression, expected_fields_referenced=expected_fields_referenced)", "docstring": "Tests that a \"transitive constraint\" is properly encoded.\n\n A \"transitive constraint\" is a constraint defined relative to a resource\n elsewhere in the FHIR resource graph than what we're querying against.\n\nArgs:\n fhir_path_expression: The FHIRPath expression to encode.\n expected_sql_expression: The expected generated Standard SQL.\n expected_fhir_path_sql_expression: The expected generated Standard SQL\n without any contextual subqueries.\n expected_fields_referenced: The expected fields_referenced_by_expression\n attribute on the resulting constraint.", "source": "github_repos"} +{"code": "def uses_keras_history(tensors):\n checked_tensors = set()\n tensors_to_check = nest.flatten(tensors)\n while tensors_to_check:\n new_tensors_to_check = []\n for tensor in tensors_to_check:\n if id(tensor) in checked_tensors:\n continue\n checked_tensors.add(id(tensor))\n if getattr(tensor, '_keras_history_checked', None) is not None:\n continue\n if getattr(tensor, '_keras_history', None) is not None:\n return True\n try:\n new_tensors_to_check.extend(tensor.op.inputs)\n except AttributeError:\n pass\n tensors_to_check = new_tensors_to_check\n mark_checked(tensors)\n return False", "docstring": "Check if at least one Tensor originates from a `keras.Input`.\n\n This is `True` if at least one Tensor has its origin in a `keras.Input`.\n Any Tensor that originates from a `keras.Input` will have a dependency\n Tensor with a `_keras_history` attribute attached. Tensors that have\n already been checked to not originate from a `keras.Input`\n are marked as `_keras_history_checked`.\n\nArgs:\n tensors: An arbitrary nested structure of Tensors.\n\nReturns:\n Bool, whether at least one Tensor originates from a `keras.Input`.", "source": "github_repos"} +{"code": "def load(self, sess, tags, import_scope=None, **saver_kwargs):\n saved_model_proto = parse_saved_model(self._export_dir)\n metrics.IncrementReadApi(_LOADER_LABEL)\n with sess.graph.as_default():\n saver, _ = self.load_graph(sess.graph, tags, import_scope, **saver_kwargs)\n self.restore_variables(sess, saver, import_scope)\n self.run_init_ops(sess, tags, import_scope)\n meta_graph_def = self.get_meta_graph_def_from_tags(tags)\n if len(saved_model_proto.meta_graphs) == 1 and saved_model_proto.meta_graphs[0].HasField('object_graph_def'):\n metrics.IncrementRead(write_version='2')\n else:\n metrics.IncrementRead(write_version='1')\n return meta_graph_def", "docstring": "Load the MetaGraphDef graph and restore variable values into the session.\n\nArgs:\n sess: tf.compat.v1.Session to restore variable values.\n tags: a set of string tags identifying a MetaGraphDef.\n import_scope: Optional `string` -- if specified, prepend this string\n followed by '/' to all loaded tensor names. This scope is applied to\n tensor instances loaded into the passed session, but it is *not* written\n through to the static `MetaGraphDef` protocol buffer that is returned.\n **saver_kwargs: keyword arguments to pass to tf.train.import_meta_graph.\n\nReturns:\n `MetagraphDef` proto of the graph that was loaded.", "source": "github_repos"} +{"code": "def session(self, graph: Optional[ops.Graph]=None, config: Optional[config_pb2.ConfigProto]=None, use_gpu: bool=True, force_gpu: bool=False) -> Iterator[s.Session]:\n if context.executing_eagerly():\n yield EagerSessionWarner()\n else:\n with self._create_session(graph, config, force_gpu) as sess:\n with self._constrain_devices_and_set_default(sess, use_gpu, force_gpu):\n yield sess", "docstring": "A context manager for a TensorFlow Session for use in executing tests.\n\n Note that this will set this session and the graph as global defaults.\n\n Use the `use_gpu` and `force_gpu` options to control where ops are run. If\n `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if\n `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as\n possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to\n the CPU.\n\nExample:\n ``` python\n class MyOperatorTest(test_util.TensorFlowTestCase):\n def testMyOperator(self):\n with self.session():\n valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]\n result = MyOperator(valid_input).eval()\n self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]\n invalid_input = [-1.0, 2.0, 7.0]\n with self.assertRaisesOpError(\"negative input not supported\"):\n MyOperator(invalid_input).eval()\n ```\n\nArgs:\n graph: Optional graph to use during the returned session.\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n use_gpu: If True, attempt to run as many ops as possible on GPU.\n force_gpu: If True, pin all ops to `/device:GPU:0`.\n\nYields:\n A Session object that should be used as a context manager to surround\n the graph building and execution code in a test case.", "source": "github_repos"} +{"code": "def complete_multipart_upload(self, request):\n parts = {'Parts': request.parts}\n try:\n self.client.complete_multipart_upload(Bucket=request.bucket, Key=request.object, UploadId=request.upload_id, MultipartUpload=parts)\n except Exception as e:\n raise messages.S3ClientError(str(e), get_http_error_code(e))", "docstring": "Completes a multipart upload to S3\n\nArgs:\n request: (UploadPartRequest) input message\n\nReturns:\n (Void) The response message.", "source": "github_repos"} +{"code": "def test_enrichment(pcoll, enrichment_handler: str, handler_config: Dict[str, Any], timeout: Optional[float]=30):\n if enrichment_handler == 'BigTable':\n row_key = handler_config['row_key']\n bt_data = INPUT_TABLES['BigTable', handler_config['instance_id'], handler_config['table_id']]\n products = {str(data[row_key]): data for data in bt_data}\n\n def _fn(row):\n left = row._asdict()\n right = products[str(left[row_key])]\n left['product'] = left.get('product', None) or right\n return beam.Row(**left)\n elif enrichment_handler == 'BigQuery':\n row_key = handler_config['fields']\n dataset, table = handler_config['table_name'].split('.')[-2:]\n bq_data = INPUT_TABLES['BigQuery', str(dataset), str(table)]\n bq_data = {tuple((str(data[key]) for key in row_key)): data for data in bq_data}\n\n def _fn(row):\n left = row._asdict()\n right = bq_data[tuple((str(left[k]) for k in row_key))]\n row = {key: left.get(key, None) or right[key] for key in {*left.keys(), *right.keys()}}\n return beam.Row(**row)\n else:\n raise ValueError(f'{enrichment_handler} is not a valid enrichment_handler.')\n return pcoll | beam.Map(_fn)", "docstring": "Mocks the Enrichment transform for testing purposes.\n\n This PTransform simulates the behavior of the Enrichment transform by\n looking up data from predefined in-memory tables based on the provided\n `enrichment_handler` and `handler_config`.\n\n Note: The Github action that invokes these tests does not have gcp\n dependencies installed which is a prerequisite to\n apache_beam.transforms.enrichment.Enrichment as a top-level import.\n\nArgs:\n pcoll: The input PCollection.\n enrichment_handler: A string indicating the type of enrichment handler\n to simulate (e.g., 'BigTable', 'BigQuery').\n handler_config: A dictionary containing configuration details for the\n simulated handler (e.g., table names, row keys, fields).\n timeout: An optional timeout value (ignored in this mock).\n\nReturns:\n A PCollection containing the enriched data.", "source": "github_repos"} +{"code": "def private_map(self):\n return self._private_map", "docstring": "A map from parents to symbols that should not be included at all.\n\n This map can be edited, but it should not be edited once traversal has\n begun.\n\nReturns:\n The map marking symbols to not include.", "source": "github_repos"} +{"code": "def pool_direct_single_axis(input, axis, window_size, pooling_type, padding, dilation_rate, stride):\n effective_window_size = (window_size - 1) * dilation_rate + 1\n input_size = input.shape[axis]\n if padding == 'SAME':\n output_size = int(math.ceil(input_size / stride))\n total_padding_amount = max(0, (output_size - 1) * stride + effective_window_size - input_size)\n before_padding = total_padding_amount // 2\n elif padding == 'VALID':\n output_size = int(math.ceil((input_size - effective_window_size + 1) / stride))\n before_padding = 0\n else:\n raise ValueError('Unsupported padding type: %r' % (padding,))\n output_shape = input.shape[:axis] + (output_size,) + input.shape[axis + 1:]\n output = np.zeros(output_shape, input.dtype)\n initial_dim_selector = tuple((np.s_[:] for _ in range(axis)))\n if pooling_type == 'MAX':\n pooling_func = np.max\n elif pooling_type == 'AVG':\n pooling_func = np.mean\n else:\n raise ValueError('Unsupported pooling type: %r' % (pooling_type,))\n for output_pos in range(output_size):\n input_start_pos = output_pos * stride - before_padding\n input_end_pos = min(input_start_pos + effective_window_size, input_size)\n if input_start_pos < 0:\n input_start_pos += dilation_rate\n input_slice = np.s_[input_start_pos:input_end_pos:dilation_rate]\n output[initial_dim_selector + (output_pos,)] = pooling_func(input[initial_dim_selector + (input_slice,)], axis=axis)\n return output", "docstring": "Numpy implementation of pooling along a single axis.\n\n This is intended for testing only, and therefore isn't particularly efficient.\n\n See pool_direct below for the meaning of the arguments.\n\nArgs:\n input: numpy array.\n axis: axis along which to perform pooling.\n window_size: int >= 1. Size of pooling window within axis.\n pooling_type: either \"MAX\" or \"AVG\".\n padding: either \"SAME\" or \"VALID\".\n dilation_rate: int >= 1. Dilation factor for window, i.e. stride at which\n to sample input.\n stride: int >= 1. Stride at which to generate output.\n\nReturns:\n pooling output array of rank N+2.\n\nRaises:\n ValueError: if arguments are invalid.", "source": "github_repos"} +{"code": "def forward(self, input_ids: torch.LongTensor, speaker_id: torch.Tensor, lang_id: torch.Tensor) -> Tuple[torch.Tensor]:\n hidden_states = self.unit_embedding(input_ids).transpose(1, 2)\n spkr = self.speaker_embedding(speaker_id).transpose(1, 2)\n lang = self.language_embedding(lang_id).transpose(1, 2)\n log_dur_pred = self.dur_predictor(hidden_states.transpose(1, 2))\n dur_out = torch.clamp(torch.round(torch.expm1(log_dur_pred)).long(), min=1)\n if hidden_states.size(0) == 1:\n hidden_states = torch.repeat_interleave(hidden_states, dur_out.view(-1), dim=2)\n else:\n if hidden_states.shape[0] > 1 and self.training:\n logger.warning('`self.training=True` and you use batching. You lose parallelism during the hifigan\\n forward pass because the samples are interleaved.')\n hidden_states = [torch.repeat_interleave(hidden_state, duration, dim=-1).transpose(0, 1) for hidden_state, duration in zip(hidden_states, dur_out)]\n hidden_states = nn.utils.rnn.pad_sequence(hidden_states, batch_first=True).transpose(1, 2)\n spkr = spkr.repeat(1, 1, hidden_states.shape[-1])\n lang = lang.repeat(1, 1, hidden_states.shape[-1])\n hidden_states = torch.cat([lang, hidden_states, spkr], dim=1)\n hidden_states = self.hifi_gan(hidden_states)\n unit_lengths = self._get_dur_output_lengths(input_ids, dur_out)\n lengths = self._get_output_hifigan_lengths(unit_lengths)\n return (hidden_states, lengths)", "docstring": "Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`SeamlessM4Tv2TextToUnitForConditionalGeneration`]. [What are input\n IDs?](../glossary#input-ids)\n speaker_id (`int`, *optional*):\n The id of the speaker used for speech synthesis. Must be lower than `config.vocoder_num_spkrs`.\n tgt_lang (`str`, *optional*):\n The language id to use as target language for translation.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.FloatTensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[MaskedLMOutput, Tuple]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.albert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n sequence_outputs = outputs[0]\n prediction_scores = self.predictions(sequence_outputs)\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n if not return_dict:\n output = (prediction_scores,) + outputs[2:]\n return (masked_lm_loss,) + output if masked_lm_loss is not None else output\n return MaskedLMOutput(loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the\n loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n\nExample:\n ```python\n >>> import torch\n >>> from transformers import AutoTokenizer, AlbertForMaskedLM\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"albert/albert-base-v2\")\n >>> model = AlbertForMaskedLM.from_pretrained(\"albert/albert-base-v2\")\n\n >>> # add mask_token\n >>> inputs = tokenizer(\"The capital of [MASK] is Paris.\", return_tensors=\"pt\")\n >>> with torch.no_grad():\n ... logits = model(**inputs).logits\n\n >>> # retrieve index of [MASK]\n >>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]\n >>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)\n >>> tokenizer.decode(predicted_token_id)\n 'france'\n ```\n\n ```python\n >>> labels = tokenizer(\"The capital of France is Paris.\", return_tensors=\"pt\")[\"input_ids\"]\n >>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)\n >>> outputs = model(**inputs, labels=labels)\n >>> round(outputs.loss.item(), 2)\n 0.81\n ```", "source": "github_repos"} +{"code": "def num_accelerators(self, task_type=None, task_id=None, config_proto=None):\n if self._tpu == 'local':\n return {'TPU': len([d for d in framework_config.list_logical_devices() if d.device_type == 'TPU'])}\n retry_count = 1\n while True:\n try:\n device_details = TPUClusterResolver._get_device_dict_and_cores(cluster_resolver_lib.get_accelerator_devices(self.master(), config_proto=config_proto))\n break\n except errors.DeadlineExceededError:\n error_message = 'Failed to connect to master. The TPU might not be ready (e.g. still scheduling) or the master address is incorrect: got (%s)' % self.master()\n if retry_count <= _TPU_CONN_RETRIES:\n logging.warning(error_message)\n logging.warning('Retrying (%d/%d)...', retry_count, _TPU_CONN_RETRIES)\n retry_count += 1\n else:\n raise RuntimeError(error_message)\n if device_details.total_cores:\n return {'TPU': TPUClusterResolver._verify_and_return_same_core_count(device_details.device_map)}\n return {'TPU': 0}", "docstring": "Returns the number of TPU cores per worker.\n\n Connects to the master and list all the devices present in the master,\n and counts them up. Also verifies that the device counts per host in the\n cluster is the same before returning the number of TPU cores per host.\n\nArgs:\n task_type: Unused.\n task_id: Unused.\n config_proto: Used to create a connection to a TPU master in order to\n retrieve the system metadata.\n\nRaises:\n RuntimeError: If we cannot talk to a TPU worker after retrying or if the\n number of TPU devices per host is different.", "source": "github_repos"} +{"code": "def write_build_info(filename, key_value_list):\n build_info = {}\n if cuda_config:\n build_info.update(cuda_config.config)\n if tensorrt_config:\n build_info.update(tensorrt_config.config)\n for arg in key_value_list:\n key, value = arg.split('=')\n if value.lower() == 'true':\n build_info[key] = True\n elif value.lower() == 'false':\n build_info[key] = False\n else:\n build_info[key] = value.format(**build_info)\n sorted_build_info_pairs = sorted(build_info.items())\n contents = '\\n# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\\n#\\n# Licensed under the Apache License, Version 2.0 (the \"License\");\\n# you may not use this file except in compliance with the License.\\n# You may obtain a copy of the License at\\n#\\n# http://www.apache.org/licenses/LICENSE-2.0\\n#\\n# Unless required by applicable law or agreed to in writing, software\\n# distributed under the License is distributed on an \"AS IS\" BASIS,\\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\n# See the License for the specific language governing permissions and\\n# limitations under the License.\\n# ==============================================================================\\n\"\"\"Auto-generated module providing information about the build.\"\"\"\\nimport collections\\n\\nbuild_info = collections.OrderedDict(%s)\\n' % sorted_build_info_pairs\n open(filename, 'w').write(contents)", "docstring": "Writes a Python that describes the build.\n\nArgs:\n filename: filename to write to.\n key_value_list: A list of \"key=value\" strings that will be added to the\n module's \"build_info\" dictionary as additional entries.", "source": "github_repos"} +{"code": "def expand_value_set_url(self, url: str) -> Optional[value_set_pb2.ValueSet]:\n value_set = self._value_set_from_url(url)\n if value_set is None:\n return None\n concept_sets = itertools.chain(value_set.compose.include, value_set.compose.exclude)\n if any((concept_set.filter for concept_set in concept_sets)):\n return None\n includes = [self._concept_set_to_expansion(value_set, include) for include in value_set.compose.include]\n excludes = [self._concept_set_to_expansion(value_set, exclude) for exclude in value_set.compose.exclude]\n if None in includes or None in excludes:\n return None\n logging.info('Expanding value set url: %s version: %s locally', value_set.url.value, value_set.version.value)\n includes = itertools.chain.from_iterable(includes)\n excludes = itertools.chain.from_iterable(excludes)\n codes_to_remove = set(((concept.version.value, concept.system.value, concept.code.value) for concept in excludes))\n codes = [concept for concept in includes if (concept.version.value, concept.system.value, concept.code.value) not in codes_to_remove]\n expanded_value_set = copy.deepcopy(value_set)\n expanded_value_set.expansion.contains.extend(codes)\n return expanded_value_set", "docstring": "Attempts to expand value sets without contacting a terminology service.\n\n For value sets with an extensional set of codes, collect all codes\n referenced in the value set's 'compose' field.\n\n For value sets which reference a code system without specifying the\n extensional set of codes within it, attempt to find the definition of the\n code system in the ValueSetResolver and expand to all codes in the code\n system. If the code system resource is not available locally, returns `None`\n indicating a terminology service should instead be used to find the value\n set expansion.\n\n If the value set has an intensional set of codes, returns `None` indicating\n a terminology service should instead be used to find the value set\n expansion.\n\n See https://www.hl7.org/fhir/valueset.html#int-ext\n for more details about value set expansion and intensional versus\n extensional value sets.\n\nArgs:\n url: The url of the value set for which to retrieve expanded codes.\n\nReturns:\n The expanded value set or None if a terminology service should be\n consulted instead.", "source": "github_repos"} +{"code": "def conv(inp, fltr, window_strides, padding, dimension_numbers, filter_dilation=None):\n input_spec, filter_spec, output_spec = dimension_numbers\n if input_spec != output_spec:\n raise ValueError('Input and output data formats must be the same; got %s and %s' % (input_spec, output_spec))\n supported_filter_spec = ['WIO', 'HWIO', 'DHWIO']\n if filter_spec not in supported_filter_spec:\n raise ValueError('The supported data format for the filter are %s; got %s' % (supported_filter_spec, filter_spec))\n if input_spec[1:-1] != filter_spec[:-2]:\n raise ValueError('Input data format (%s) is not compatible with filter data format (%s)' % (input_spec, filter_spec))\n dtype = tf_np.result_type(inp, fltr)\n inp = tf_np.asarray(inp, dtype)\n fltr = tf_np.asarray(fltr, dtype)\n return tf_np.asarray(nn_ops.convolution_v2(input=inp, filters=fltr, padding=padding, strides=window_strides, dilations=filter_dilation, data_format=input_spec))", "docstring": "Convolution over an N-D array.\n\n See https://www.tensorflow.org/api_docs/python/tf/nn/convolution and\n https://www.tensorflow.org/xla/operation_semantics#conv_convolution for\n reference.\n\nArgs:\n inp: an (N+2)-D array. The input of the convolution.\n fltr: an (N+2)-D array. The filter (i.e. kernel) of the convolution.\n window_strides: a sequence of N ints, the strides for moving the convolution\n window.\n padding: a string, either \"VALID\" or \"SAME\". The padding algorithm.\n dimension_numbers: a tuple of three strings encoding the data format of\n input, filter and output. \"I\" means input; \"O\" means output; \"C\" means\n channel; other characters such as \"W\", \"H\" and \"D\" means spatial\n dimensions.\n filter_dilation: the dilation rates for the filter. Dilating the filter\n means adding \"holes\" to the filter.\n\nReturns:\n An (N+2)-D array. The convolution result.", "source": "github_repos"} +{"code": "def generate_block_graph(block_graph: blocks.BlockGraph, loader: jinja2.BaseLoader) -> str:\n return _generate_visualization(template_file=_BLOCKGRAPH_TEMPLATE_NAME, loader=loader, graph_data=block_serializer.encode_merged_graph(block_graph))", "docstring": "Generate the visualization webpage.\n\nArgs:\n block_graph: blocks.BlockGraph. The block graph of the code.\n loader: A jinja22 loader\n\nReturns:\n str. The rendered visualization page.", "source": "github_repos"} +{"code": "def __init__(self):\n self.all_node_names = []\n self.name_node_values = []", "docstring": "A tree visitor that collects the names of all tree nodes into a list.\n\nAttributes:\n all_node_names: collected list of the names, available when the traversal\n is over.\n name_node_values: collects a list of NAME leaves (in addition to those going\n into all_node_names).", "source": "github_repos"} +{"code": "def pack_images(batch_images: List[List[np.ndarray]], max_image_tiles: int) -> Tuple[np.ndarray, List[List[int]]]:\n batch_size = len(batch_images)\n max_num_images = max([len(images) for images in batch_images])\n shapes = [image.shape for images in batch_images for image in images]\n _, channels, tile_height, tile_width = shapes[0]\n stacked_images = np.zeros((batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width), dtype=np.float32)\n all_num_tiles = []\n for i, images in enumerate(batch_images):\n num_sample_tiles = []\n for j, image in enumerate(images):\n num_tiles = image.shape[0]\n stacked_images[i, j, :num_tiles] = image\n num_sample_tiles.append(num_tiles)\n all_num_tiles.append(num_sample_tiles)\n return (stacked_images, all_num_tiles)", "docstring": "Stack a list of lists of images with variable lengths into a numpy array, applying zero padding as needed.\n Each list in the input represents a batch sample, and each image within a list is expected to be\n pre-split into tiles. The resulting array will have a shape of\n (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width).\n\nArgs:\n batch_images (`List[List[np.ndarray]]`):\n A list of lists of image tiles. Each inner list represents\n a batch sample containing multiple images, where each image is pre-split into tiles.\n The shape of each tile array is (num_tiles, channels, tile_height, tile_width).\n max_image_tiles (int):\n The maximum number of tiles any image was potantially split.\n\nReturns:\n `Tuple[np.ndarray, List[List[int]]]`: A tuple containing:\n - stacked_images (`np.ndarray`):\n A numpy array of stacked images with shape\n (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width).\n - all_num_tiles (`List[List[int]]`):\n A list of lists containing the number of tiles\n for each image in each batch sample.", "source": "github_repos"} +{"code": "def unnormalize(self, image: np.array, image_mean: Union[float, Iterable[float]], image_std: Union[float, Iterable[float]], input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.array:\n num_channels = 3\n if isinstance(image_mean, Iterable):\n if len(image_mean) != num_channels:\n raise ValueError(f'mean must have {num_channels} elements if it is an iterable, got {len(image_mean)}')\n else:\n image_mean = [image_mean] * num_channels\n if isinstance(image_std, Iterable):\n if len(image_std) != num_channels:\n raise ValueError(f'std must have {num_channels} elements if it is an iterable, got {len(image_std)}')\n else:\n image_std = [image_std] * num_channels\n rev_image_mean = tuple((-mean / std for mean, std in zip(image_mean, image_std)))\n rev_image_std = tuple((1 / std for std in image_std))\n image = self.normalize(image=image, mean=rev_image_mean, std=rev_image_std, input_data_format=input_data_format)\n return image", "docstring": "Unnormalizes `image` using the mean and standard deviation specified by `mean` and `std`.\n image = (image * image_std) + image_mean\n\nArgs:\n image (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)` or `(num_channels, image_size, image_size)`):\n Batch of pixel values to postprocess.\n image_mean (`float` or `Iterable[float]`):\n The mean to use for unnormalization.\n image_std (`float` or `Iterable[float]`):\n The standard deviation to use for unnormalization.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.", "source": "github_repos"} +{"code": "def _resolve_if_choice_type(fhir_message: message.Message) -> Optional[message.Message]:\n if annotation_utils.is_choice_type(fhir_message):\n choice_field = fhir_message.WhichOneof('choice')\n if choice_field is None:\n return None\n return cast(message.Message, proto_utils.get_value_at_field(fhir_message, choice_field))\n return fhir_message", "docstring": "Resolve to the proper field if given a choice type, return as-is if not.\n\n Each value in a FHIR choice type is a different field on the protobuf\n representation wrapped under a proto onoeof field. Therefore, if\n an expression points to a choice type, we should return the populated\n field -- while just returning the field as-is for non-choice types. This\n way we can simply pass nested messages through this class, and return the\n populated item when appropriate.\n\nArgs:\n fhir_message: the evaluation result which may or may not be a choice type\n\nReturns:\n The result value, resolved to the sub-field if it is a choice type.", "source": "github_repos"} +{"code": "def _from_components(self, components):\n raise NotImplementedError('%s._from_components()' % type(self).__name__)", "docstring": "Reconstructs a value from a nested structure of Tensor/CompositeTensor.\n\nArgs:\n components: A nested structure of `tf.Tensor` or `tf.CompositeTensor`,\n compatible with `self._component_specs`. (Caller is responsible for\n ensuring compatibility.)\n\nReturns:\n A value that is compatible with this `TypeSpec`.", "source": "github_repos"} +{"code": "def __init__(self, element_spec):\n self._element_spec = element_spec", "docstring": "Type specification for `tf.data.Iterator`.\n\n For instance, `tf.data.IteratorSpec` can be used to define a tf.function that\n takes `tf.data.Iterator` as an input argument:\n\n >>> @tf.function(input_signature=[tf.data.IteratorSpec(\n ... tf.TensorSpec(shape=(), dtype=tf.int32, name=None))])\n ... def square(iterator):\n ... x = iterator.get_next()\n ... return x * x\n >>> dataset = tf.data.Dataset.from_tensors(5)\n >>> iterator = iter(dataset)\n >>> print(square(iterator))\n tf.Tensor(25, shape=(), dtype=int32)\n\nAttributes:\n element_spec: A (nested) structure of `tf.TypeSpec` objects that represents\n the type specification of the iterator elements.", "source": "github_repos"} +{"code": "def _convert_dynamic_dimension_to_zero(shape):\n if shape.rank is None:\n return shape\n return tensor_shape.TensorShape([0 if d is None else d for d in shape.as_list()])", "docstring": "Converts dynamic dimensions in `shape` to zero.\n\n The fake params created to match the intermediates captured in other branches\n could have dynamic dimensions. But the XLA shape is not able to handle\n dynamic dimensions in TF TensorShape. Setting the dynamic dimensions to\n size zero will help avoid failing safety checks in bridge. When XLA\n DynamicConditional op reconciles branch differences, XLA will replace the\n dimension size 0 with a bounded dimension determined from the shape of\n real argument in the other branch.\n\n Note: Rank unknown shapes are returned as they are.\n\nArgs:\n shape: The TensorShape of fake param.\n\nReturns:\n The new TensorShape with dynamic dimensions set to zero.", "source": "github_repos"} +{"code": "def _get_indices_and_values(x, jump_locations, values, side, batch_rank):\n indices = tf.searchsorted(jump_locations, x, side=side)\n num_data_points = tf.shape(values)[batch_rank] - 2\n if side == 'right':\n indices_jump = indices - 1\n indices_jump = tf.maximum(indices_jump, 0)\n else:\n indices_jump = tf.minimum(indices, num_data_points)\n value = tf.gather(values, indices, axis=batch_rank, batch_dims=batch_rank)\n jump_location = tf.gather(jump_locations, indices_jump, axis=batch_rank, batch_dims=batch_rank)\n return (value, jump_location, indices_jump)", "docstring": "Computes values and jump locations of the piecewise constant function.\n\n Given `jump_locations` and the `values` on the corresponding segments of the\n piecewise constant function, the function identifies the nearest jump to `x`\n from the right or left (which is determined by the `side` argument) and the\n corresponding value of the piecewise constant function at `x`\n\nArgs:\n x: A real `Tensor` of shape `batch_shape + [num_points]`. Points at which\n the function has to be evaluated.\n jump_locations: A `Tensor` of the same `dtype` as `x` and shape\n `batch_shape + [num_jump_points]`. The locations where the function\n changes its values. Note that the values are expected to be ordered\n along the last dimension.\n values: A `Tensor` of the same `dtype` as `x` and shape\n `batch_shape + [num_jump_points + 1]`. Defines `values[..., i]` on\n `jump_locations[..., i - 1], jump_locations[..., i]`.\n side: A Python string. Whether the function is left- or right- continuous.\n The corresponding values for side should be `left` and `right`.\n batch_rank: A Python scalar stating the batch rank of `x`.\n\nReturns:\n A tuple of three `Tensor` of the same `dtype` as `x` and shapes\n `batch_shape + [num_points] + event_shape`, `batch_shape + [num_points]`,\n and `batch_shape + [num_points] + [2 * len(batch_shape)]`. The `Tensor`s\n correspond to the values, jump locations at `x`, and the corresponding\n indices used to obtain jump locations via `tf.gather_nd`.", "source": "github_repos"} +{"code": "def _save_and_write_assets(self, meta_graph_def, assets_list=None):\n write_fn = functools.partial(_add_asset_to_metagraph, meta_graph_def)\n asset_filename_map = _maybe_save_assets(write_fn, assets_list)\n if not asset_filename_map:\n tf_logging.info('No assets to write.')\n return\n copy_assets_to_destination_dir(asset_filename_map, self._export_dir, self._saved_asset_files)", "docstring": "Saves asset to the meta graph and writes asset files to disk.\n\nArgs:\n meta_graph_def: The meta graph def to which the assets will be added.\n assets_list: The list where the asset paths are setup.", "source": "github_repos"} +{"code": "def __init__(self, sequence, use_multiprocessing=False):\n self.sequence = sequence\n self.use_multiprocessing = use_multiprocessing\n global _SEQUENCE_COUNTER\n if _SEQUENCE_COUNTER is None:\n try:\n _SEQUENCE_COUNTER = multiprocessing.Value('i', 0)\n except OSError:\n _SEQUENCE_COUNTER = 0\n if isinstance(_SEQUENCE_COUNTER, int):\n self.uid = _SEQUENCE_COUNTER\n _SEQUENCE_COUNTER += 1\n else:\n with _SEQUENCE_COUNTER.get_lock():\n self.uid = _SEQUENCE_COUNTER.value\n _SEQUENCE_COUNTER.value += 1\n self.workers = 0\n self.executor_fn = None\n self.queue = None\n self.run_thread = None\n self.stop_signal = None", "docstring": "Base class to enqueue inputs.\n\n The task of an Enqueuer is to use parallelism to speed up preprocessing.\n This is done with processes or threads.\n\nExample:\n ```python\n enqueuer = SequenceEnqueuer(...)\n enqueuer.start()\n datas = enqueuer.get()\n for data in datas:\n # Use the inputs; training, evaluating, predicting.\n # ... stop sometime.\n enqueuer.stop()\n ```\n\n The `enqueuer.get()` should be an infinite stream of datas.", "source": "github_repos"} +{"code": "def avg_pool(value, ksize, strides, padding, data_format='NHWC', name=None, input=None):\n with ops.name_scope(name, 'AvgPool', [value]) as name:\n value = deprecation.deprecated_argument_lookup('input', input, 'value', value)\n if data_format is None:\n data_format = 'NHWC'\n channel_index = 1 if data_format.startswith('NC') else 3\n ksize = _get_sequence(ksize, 2, channel_index, 'ksize')\n strides = _get_sequence(strides, 2, channel_index, 'strides')\n return gen_nn_ops.avg_pool(value, ksize=ksize, strides=strides, padding=padding, data_format=data_format, name=name)", "docstring": "Performs the average pooling on the input.\n\n Each entry in `output` is the mean of the corresponding size `ksize`\n window in `value`.\n\nArgs:\n value: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type\n `float32`, `float64`, `qint8`, `quint8`, or `qint32`.\n ksize: An int or list of `ints` that has length `1`, `2` or `4`. The size of\n the window for each dimension of the input tensor.\n strides: An int or list of `ints` that has length `1`, `2` or `4`. The\n stride of the sliding window for each dimension of the input tensor.\n padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.\n See the \"returns\" section of `tf.nn.convolution` for details.\n data_format: A string. 'NHWC' and 'NCHW' are supported.\n name: Optional name for the operation.\n input: Alias for value.\n\nReturns:\n A `Tensor` with the same type as `value`. The average pooled output tensor.", "source": "github_repos"} +{"code": "def __mul__(self, right: torch.Tensor) -> Rigid:\n if not isinstance(right, torch.Tensor):\n raise TypeError('The other multiplicand must be a Tensor')\n new_rots = self._rots * right\n new_trans = self._trans * right[..., None]\n return Rigid(new_rots, new_trans)", "docstring": "Pointwise left multiplication of the transformation with a tensor. Can be used to e.g. mask the Rigid.\n\nArgs:\n right:\n The tensor multiplicand\n\nReturns:\n The product", "source": "github_repos"} +{"code": "def __init__(self, *, indent: int=4):\n self._lines: list[_Line] = []\n self._indent_size = indent\n self._indent_lvl = 0", "docstring": "Util to build multi-line text.\n\n Useful for pretty-print tools and human readable `__repr__`.\n\nExample:\n ```python\n d = {'a': 1, 'b': 2}\n\n lines = epy.Lines()\n lines += 'dict('\n with lines.indent():\n for k, v in d.items():\n lines += f'{k}={v},'\n lines += ')'\n text = lines.join()\n ```\n\n Output:\n\n ```\n dict(\n a=1,\n b=2,\n )\n ```", "source": "github_repos"} +{"code": "def custom_apply(self, path: utils.KeyPath, value_spec: pg_typing.ValueSpec, allow_partial: bool, child_transform: Optional[Callable[[utils.KeyPath, pg_typing.Field, Any], Any]]=None) -> Tuple[bool, 'List']:\n proceed_with_standard_apply = True\n if self._value_spec:\n if value_spec and (not value_spec.is_compatible(self._value_spec)):\n raise ValueError(utils.message_on_path(f'List (spec={self._value_spec!r}) cannot be assigned to an incompatible field (spec={value_spec!r}).', path))\n if self._allow_partial == allow_partial:\n proceed_with_standard_apply = False\n else:\n self._allow_partial = allow_partial\n elif isinstance(value_spec, pg_typing.List):\n self._value_spec = value_spec\n return (proceed_with_standard_apply, self)", "docstring": "Implement pg.typing.CustomTyping interface.\n\nArgs:\n path: KeyPath of current object.\n value_spec: Origin value spec of the field.\n allow_partial: Whether allow partial object to be created.\n child_transform: Function to transform child node values in dict_obj into\n their final values. Transform function is called on leaf nodes first,\n then on their containers, recursively.\n\nReturns:\n A tuple (proceed_with_standard_apply, transformed value)", "source": "github_repos"} +{"code": "def _scale_loss_for_estimator_enabled(self):\n self._scale_loss_for_estimator = True\n try:\n yield\n finally:\n self._scale_loss_for_estimator = False", "docstring": "Scope which sets a flag used for scaling losses in optimizer.\n\nYields:\n `_scale_loss_for_estimator_enabled` is a context manager with a\n side effect, but doesn't return a value.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.Tensor]=None, position_ids: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **kwargs) -> Union[Tuple, NextSentencePredictorOutput]:\n if 'next_sentence_label' in kwargs:\n warnings.warn('The `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.', FutureWarning)\n labels = kwargs.pop('next_sentence_label')\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.fnet(input_ids, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_hidden_states=output_hidden_states, return_dict=return_dict)\n pooled_output = outputs[1]\n seq_relationship_scores = self.cls(pooled_output)\n next_sentence_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))\n if not return_dict:\n output = (seq_relationship_scores,) + outputs[2:]\n return (next_sentence_loss,) + output if next_sentence_loss is not None else output\n return NextSentencePredictorOutput(loss=next_sentence_loss, logits=seq_relationship_scores, hidden_states=outputs.hidden_states)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair\n (see `input_ids` docstring). Indices should be in `[0, 1]`:\n\n - 0 indicates sequence B is a continuation of sequence A,\n - 1 indicates sequence B is a random sequence.\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, FNetForNextSentencePrediction\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google/fnet-base\")\n >>> model = FNetForNextSentencePrediction.from_pretrained(\"google/fnet-base\")\n >>> prompt = \"In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced.\"\n >>> next_sentence = \"The sky is blue due to the shorter wavelength of blue light.\"\n >>> encoding = tokenizer(prompt, next_sentence, return_tensors=\"pt\")\n >>> outputs = model(**encoding, labels=torch.LongTensor([1]))\n >>> logits = outputs.logits\n >>> assert logits[0, 0] < logits[0, 1] # next sentence was random\n ```", "source": "github_repos"} +{"code": "def sheets_clear(config, auth, sheet_url_or_name, sheet_tab, sheet_range):\n if config.verbose:\n print('SHEETS CLEAR', sheet_url_or_name, sheet_tab, sheet_range)\n sheet_id = sheets_id(config, auth, sheet_url_or_name)\n if sheet_id:\n API_Sheets(config, auth).spreadsheets().values().clear(spreadsheetId=sheet_id, range=sheets_tab_range(sheet_tab, sheet_range), body={}).execute()\n else:\n raise ValueError('Sheet does not exist for %s: %s' % (config, auth, sheet_url_or_name))", "docstring": "Clear a sheet in the specified range.\n\nArgs:\n config - see starthinker/util/configuration.py\n auth - user or service\n url_or_name - one of: URL, document title, or id\n sheet_tab - name of tab to get id for\n sheet_range - A1 notation or blank if whole sheet\n\n No Return", "source": "github_repos"} +{"code": "def log_optimal_transport(scores: torch.Tensor, reg_param: torch.Tensor, iterations: int) -> torch.Tensor:\n batch_size, num_rows, num_columns = scores.shape\n one_tensor = scores.new_tensor(1)\n num_rows_tensor, num_columns_tensor = ((num_rows * one_tensor).to(scores), (num_columns * one_tensor).to(scores))\n source_reg_param = reg_param.expand(batch_size, num_rows, 1)\n target_reg_param = reg_param.expand(batch_size, 1, num_columns)\n reg_param = reg_param.expand(batch_size, 1, 1)\n couplings = torch.cat([torch.cat([scores, source_reg_param], -1), torch.cat([target_reg_param, reg_param], -1)], 1)\n log_normalization = -(num_rows_tensor + num_columns_tensor).log()\n log_source_distribution = torch.cat([log_normalization.expand(num_rows), num_columns_tensor.log()[None] + log_normalization])\n log_target_distribution = torch.cat([log_normalization.expand(num_columns), num_rows_tensor.log()[None] + log_normalization])\n log_source_distribution, log_target_distribution = (log_source_distribution[None].expand(batch_size, -1), log_target_distribution[None].expand(batch_size, -1))\n log_optimal_transport_matrix = log_sinkhorn_iterations(couplings, log_source_distribution, log_target_distribution, num_iterations=iterations)\n log_optimal_transport_matrix = log_optimal_transport_matrix - log_normalization\n return log_optimal_transport_matrix", "docstring": "Perform Differentiable Optimal Transport in Log-space for stability\n\nArgs:\n scores: (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`):\n Cost matrix.\n reg_param: (`torch.Tensor` of shape `(batch_size, 1, 1)`):\n Regularization parameter.\n iterations: (`int`):\n Number of Sinkhorn iterations.\n\nReturns:\n log_optimal_transport_matrix: (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`): Logarithm of the\n optimal transport matrix.", "source": "github_repos"} +{"code": "def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]]=None, prepend_batch_axis: bool=False):\n if tensor_type is None:\n return self\n if not isinstance(tensor_type, TensorType):\n tensor_type = TensorType(tensor_type)\n if tensor_type == TensorType.TENSORFLOW:\n if not is_tf_available():\n raise ImportError('Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.')\n import tensorflow as tf\n as_tensor = tf.constant\n is_tensor = tf.is_tensor\n elif tensor_type == TensorType.PYTORCH:\n if not is_torch_available():\n raise ImportError('Unable to convert output to PyTorch tensors format, PyTorch is not installed.')\n import torch\n is_tensor = torch.is_tensor\n\n def as_tensor(value, dtype=None):\n if isinstance(value, list) and isinstance(value[0], np.ndarray):\n return torch.from_numpy(np.array(value))\n return torch.tensor(value)\n elif tensor_type == TensorType.JAX:\n if not is_flax_available():\n raise ImportError('Unable to convert output to JAX tensors format, JAX is not installed.')\n import jax.numpy as jnp\n as_tensor = jnp.array\n is_tensor = is_jax_tensor\n elif tensor_type == TensorType.MLX:\n if not is_mlx_available():\n raise ImportError('Unable to convert output to MLX tensors format, MLX is not installed.')\n import mlx.core as mx\n as_tensor = mx.array\n\n def is_tensor(obj):\n return isinstance(obj, mx.array)\n else:\n\n def as_tensor(value, dtype=None):\n if isinstance(value, (list, tuple)) and isinstance(value[0], (list, tuple, np.ndarray)):\n value_lens = [len(val) for val in value]\n if len(set(value_lens)) > 1 and dtype is None:\n value = as_tensor([np.asarray(val) for val in value], dtype=object)\n return np.asarray(value, dtype=dtype)\n is_tensor = is_numpy_array\n for key, value in self.items():\n try:\n if prepend_batch_axis:\n value = [value]\n if not is_tensor(value):\n tensor = as_tensor(value)\n self[key] = tensor\n except Exception as e:\n if key == 'overflowing_tokens':\n raise ValueError('Unable to create tensor returning overflowing tokens of different lengths. Please see if a fast version of this tokenizer is available to have this feature available.') from e\n raise ValueError(f\"Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your features (`{key}` in this case) have excessive nesting (inputs type `list` where type `int` is expected).\") from e\n return self", "docstring": "Convert the inner content to tensors.\n\nArgs:\n tensor_type (`str` or [`~utils.TensorType`], *optional*):\n The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If\n `None`, no modification is done.\n prepend_batch_axis (`int`, *optional*, defaults to `False`):\n Whether or not to add the batch dimension during the conversion.", "source": "github_repos"} +{"code": "def __init__(self, threshold_fn_spec: Spec):\n assert isinstance(threshold_fn_spec.config, dict)\n threshold_fn_spec.config['_run_init'] = True\n threshold_fn = Specifiable.from_spec(threshold_fn_spec)\n assert isinstance(threshold_fn, ThresholdFn)\n assert threshold_fn.is_stateful, 'This DoFn can only take stateful function as threshold_fn'\n self._threshold_fn_spec = threshold_fn_spec", "docstring": "Applies a stateful ThresholdFn to anomaly detection results.\n\n This DoFn is designed for stateful `ThresholdFn` implementations. It leverages\n Beam's state management to persist and update the state of the `ThresholdFn`\n across multiple elements. This is necessary for `ThresholdFn`s that need to\n accumulate information or adapt over time, such as quantile-based thresholds.\n\nArgs:\n threshold_fn_spec (Spec): Specification defining the `ThresholdFn` to be\n used.\n\nRaises:\n AssertionError: If the provided `threshold_fn_spec` leads to the\n creation of a stateless `ThresholdFn`.", "source": "github_repos"} +{"code": "def group(self, group_id):\n self._validate_group_id(group_id)\n return self._Context(self, group_id)", "docstring": "Enter a context where the lock is with group `group_id`.\n\nArgs:\n group_id: The group for which to acquire and release the lock.\n\nReturns:\n A context manager which will acquire the lock for `group_id`.", "source": "github_repos"} +{"code": "def read_fingerprint(export_dir: str) -> Fingerprint:\n try:\n fingerprint = fingerprinting_pywrap.ReadSavedModelFingerprint(export_dir)\n except fingerprinting_pywrap.FileNotFoundException as e:\n raise FileNotFoundError(f'SavedModel Fingerprint Error: {e}') from None\n except fingerprinting_pywrap.FingerprintException as e:\n raise RuntimeError(f'SavedModel Fingerprint Error: {e}') from None\n return Fingerprint.from_proto(fingerprint_pb2.FingerprintDef().FromString(fingerprint))", "docstring": "Reads the fingerprint of a SavedModel in `export_dir`.\n\n Returns a `tf.saved_model.experimental.Fingerprint` object that contains\n the values of the SavedModel fingerprint, which is persisted on disk in the\n `fingerprint.pb` file in the `export_dir`.\n\n Read more about fingerprints in the SavedModel guide at\n https://www.tensorflow.org/guide/saved_model.\n\nArgs:\n export_dir: The directory that contains the SavedModel.\n\nReturns:\n A `tf.saved_model.experimental.Fingerprint`.\n\nRaises:\n FileNotFoundError: If no or an invalid fingerprint is found.", "source": "github_repos"} +{"code": "def __init__(self, input_dataset, target_device, source_device='/cpu:0'):\n self._input_dataset = input_dataset._apply_debug_options()\n self._target_device = target_device\n spec = framework_device.DeviceSpec().from_string(self._target_device)\n self._is_gpu_target = spec.device_type == 'GPU'\n self._source_device_string = source_device\n self._source_device = ops.convert_to_tensor(source_device)\n wrap_ds_variant = gen_dataset_ops.wrap_dataset_variant(self._input_dataset._variant_tensor)\n\n @def_function.function()\n def _init_func():\n \"\"\"Creates an iterator for the input dataset.\n\n Returns:\n A `string` tensor that encapsulates the iterator created.\n \"\"\"\n ds_variant = gen_dataset_ops.unwrap_dataset_variant(wrap_ds_variant)\n resource = gen_dataset_ops.anonymous_iterator(**self._input_dataset._flat_structure)\n with ops.control_dependencies([gen_dataset_ops.make_iterator(ds_variant, resource)]):\n return gen_dataset_ops.iterator_to_string_handle(resource)\n init_func_concrete = _init_func.get_concrete_function()\n\n @def_function.function()\n def _remote_init_func():\n return functional_ops.remote_call(target=self._source_device, args=init_func_concrete.captured_inputs, Tout=[dtypes.string], f=init_func_concrete)\n self._init_func = _remote_init_func.get_concrete_function()\n self._init_captured_args = self._init_func.captured_inputs\n\n @def_function.function(input_signature=[tensor_spec.TensorSpec([], dtypes.string)])\n def _next_func(string_handle):\n \"\"\"Calls get_next for created iterator.\n\n Args:\n string_handle: An iterator string handle created by _init_func\n Returns:\n The elements generated from `input_dataset`\n \"\"\"\n with ops.device(self._source_device_string):\n iterator = iterator_ops.Iterator.from_string_handle(string_handle, dataset_ops.get_legacy_output_types(self), dataset_ops.get_legacy_output_shapes(self), dataset_ops.get_legacy_output_classes(self))\n return structure.to_tensor_list(self.element_spec, iterator.get_next())\n next_func_concrete = _next_func.get_concrete_function()\n\n @def_function.function(input_signature=[tensor_spec.TensorSpec([], dtypes.string)], experimental_attributes={'experimental_ints_on_device': True})\n def _remote_next_func(string_handle):\n return functional_ops.remote_call(target=self._source_device, args=[string_handle] + next_func_concrete.captured_inputs, Tout=self._input_dataset._flat_types, f=next_func_concrete)\n self._next_func = _remote_next_func.get_concrete_function()\n self._next_captured_args = self._next_func.captured_inputs\n\n @def_function.function(input_signature=[tensor_spec.TensorSpec([], dtypes.string)])\n def _finalize_func(string_handle):\n \"\"\"Destroys the iterator resource created.\n\n Args:\n string_handle: An iterator string handle created by _init_func\n Returns:\n Tensor constant 0\n \"\"\"\n iterator_resource = gen_dataset_ops.iterator_from_string_handle_v2(string_handle, **self._input_dataset._flat_structure)\n with ops.control_dependencies([resource_variable_ops.destroy_resource_op(iterator_resource, ignore_lookup_error=True)]):\n return array_ops.constant(0, dtypes.int64)\n finalize_func_concrete = _finalize_func.get_concrete_function()\n\n @def_function.function(input_signature=[tensor_spec.TensorSpec([], dtypes.string)])\n def _remote_finalize_func(string_handle):\n return functional_ops.remote_call(target=self._source_device, args=[string_handle] + finalize_func_concrete.captured_inputs, Tout=[dtypes.int64], f=finalize_func_concrete)\n self._finalize_func = _remote_finalize_func.get_concrete_function()\n self._finalize_captured_args = self._finalize_func.captured_inputs\n g = ops.get_default_graph()\n self._init_func.add_to_graph(g)\n self._next_func.add_to_graph(g)\n self._finalize_func.add_to_graph(g)\n with ops.device(self._target_device):\n variant_tensor = gen_dataset_ops.generator_dataset(self._init_captured_args, self._next_captured_args, self._finalize_captured_args, init_func=self._init_func, next_func=self._next_func, finalize_func=self._finalize_func, **self._input_dataset._flat_structure)\n super(_CopyToDeviceDataset, self).__init__(input_dataset, variant_tensor)", "docstring": "Constructs a _CopyToDeviceDataset.\n\nArgs:\n input_dataset: `Dataset` to be copied\n target_device: The name of the device to which elements would be copied.\n source_device: Device where input_dataset would be placed.", "source": "github_repos"} +{"code": "def __init__(self, conf, conn=None):\n super(HttpFilesSource, self).__init__(conf)\n self._SetDefaults(conf)\n if not conn:\n conn = pycurl.Curl()\n conn.setopt(pycurl.NOPROGRESS, 1)\n conn.setopt(pycurl.NOSIGNAL, 1)\n conn.setopt(pycurl.TIMEOUT, 60)\n conn.setopt(pycurl.USERAGENT, 'nsscache')\n if self.conf['http_proxy']:\n conn.setopt(pycurl.PROXY, self.conf['http_proxy'])\n self.conn = conn", "docstring": "Initialise the HTTP Data Source.\n\nArgs:\n conf: config.Config instance\n conn: pycurl Curl object", "source": "github_repos"} +{"code": "def print_generic_type(self, t: types.BaseValue) -> str:", "docstring": "Returns a string of the generic type of t.\n\n For example, if t is `[0]`, then this method returns \"list[int]\".\n\nArgs:\n t: An abstract value.", "source": "github_repos"} +{"code": "def to_numpy(evset: EventSet, timestamp_to_datetime: bool=True, timestamps: bool=True) -> Dict[str, ndarray]:\n timestamp_key = 'timestamp'\n index_names = evset.schema.index_names()\n feature_names = evset.schema.feature_names()\n column_names = index_names + feature_names\n if timestamps:\n column_names += [timestamp_key]\n dst = {column_name: [] for column_name in column_names}\n for index, data in evset.data.items():\n assert isinstance(index, tuple)\n if timestamps:\n if evset.schema.is_unix_timestamp and timestamp_to_datetime:\n dst[timestamp_key].append(data.timestamps.astype('datetime64[s]'))\n else:\n dst[timestamp_key].append(data.timestamps)\n for feature_name, feature in zip(feature_names, data.features):\n dst[feature_name].append(feature)\n num_timestamps = len(data.timestamps)\n for index_name, index_item in zip(index_names, index):\n dst[index_name].append(np.repeat(index_item, num_timestamps))\n dst = {k: np.concatenate(v) for k, v in dst.items()}\n return dst", "docstring": "Converts an [`EventSet`][temporian.EventSet] to a flattened dictionary with\n numpy arrays.\n\n Usage example:\n ```python\n >>> from datetime import datetime\n\n >>> evset = tp.event_set(\n ... timestamps=['2023-11-08T17:14:38', '2023-11-29T21:44:46'],\n ... features={\n ... \"store\": ['STORE_1', 'STORE_2'],\n ... \"revenue\": [1571, 6101]\n ... },\n ... indexes=[\"store\"],\n ... )\n\n # Timestamps are exported as datetime64[s] if they were created as datetimes,\n # otherwhise they are floats\n >>> res = tp.to_numpy(evset)\n >>> res\n {'store': array([b'STORE_2', b'STORE_1'], dtype='|S7'), 'revenue': array([6101, 1571]),\n 'timestamp': array(['2023-11-29T21:44:46', '2023-11-08T17:14:38'], dtype='datetime64[s]')}\n\n ```\n\nArgs:\n evset: input event set.\n timestamp_to_datetime: If true, cast Temporian timestamps to datetime64\n when is_unix_timestamp is set to True.\n timestamps: If true, the timestamps are included as a column.\n\nReturns:\n object with numpy arrays created from EventSet.", "source": "github_repos"} +{"code": "def simple_two_objective_reward(example):\n num = int(example * 10) % 9 + 1\n return [num, 10 - num]", "docstring": "Reward for the trivial search space.\n\n The reward (i.e. fitness) is a 2-element list. The goal of the search,\n therefore, is to find the pareto frontier in simple_two_objective_pareto\n function.\n\nArgs:\n example: a materialized value.\n\nReturns:\n A 2-element list.", "source": "github_repos"} +{"code": "def abort_class_if(expr, reason, extras=None):\n if expr:\n abort_class(reason, extras)", "docstring": "Abort all subsequent tests within the same test class in one iteration,\n if expression evaluates to True.\n\n If one test class is requested multiple times in a test run, this can\n only abort one of the requested executions, NOT all.\n\nArgs:\n expr: The expression that is evaluated.\n reason: The reason to abort.\n extras: An optional field for extra information to be included in\n test result.\n\nRaises:\n signals.TestAbortClass: Abort all subsequent tests in a test class.", "source": "github_repos"} +{"code": "def get_current_human_time():\n return time.strftime('%m-%d-%Y %H:%M:%S ')", "docstring": "Returns the current time in human readable format.\n\nReturns:\n The current time stamp in Month-Day-Year Hour:Min:Sec format.", "source": "github_repos"} +{"code": "def compute_gradient_error(x, x_shape, y, y_shape, x_init_value=None, delta=0.001, init_targets=None, extra_feed_dict=None):\n grad = compute_gradient(x, x_shape, y, y_shape, x_init_value, delta, init_targets, extra_feed_dict=extra_feed_dict)\n return _compute_error(grad)", "docstring": "Computes the gradient error.\n\n Computes the maximum error for dy/dx between the computed Jacobian and the\n numerically estimated Jacobian.\n\n This function will modify the tensors passed in as it adds more operations\n and hence changing the consumers of the operations of the input tensors.\n\n This function adds operations to the current session. To compute the error\n using a particular device, such as a GPU, use the standard methods for\n setting a device (e.g. using with sess.graph.device() or setting a device\n function in the session constructor).\n\nArgs:\n x: a tensor or list of tensors\n x_shape: the dimensions of x as a tuple or an array of ints. If x is a list,\n then this is the list of shapes.\n y: a tensor\n y_shape: the dimensions of y as a tuple or an array of ints.\n x_init_value: (optional) a numpy array of the same shape as \"x\"\n representing the initial value of x. If x is a list, this should be a list\n of numpy arrays. If this is none, the function will pick a random tensor\n as the initial value.\n delta: (optional) the amount of perturbation.\n init_targets: list of targets to run to initialize model params.\n extra_feed_dict: dict that allows fixing specified tensor values\n during the Jacobian calculation.\n\nReturns:\n The maximum error in between the two Jacobians.", "source": "github_repos"} +{"code": "def unravel_index(indices, shape):\n if any_symbolic_tensors((indices,)):\n return UnravelIndex(shape).symbolic_call(indices)\n return backend.numpy.unravel_index(indices, shape)", "docstring": "Convert flat indices to coordinate arrays in a given array shape.\n\nArgs:\n indices: An integer or array of integers representing flat indices.\n shape: The shape of the array to unravel into.\n\nReturns:\n Tuple of arrays for each dimension with unraveled indices.\n\nExample:\n >>> indices = 5\n >>> shape = (3, 3)\n >>> unravel_index(indices, shape)\n (1, 2) # 5 is at row 1, column 2 in a 3x3 array", "source": "github_repos"} +{"code": "def sample_g_values(self, ngram_keys: torch.LongTensor) -> torch.LongTensor:\n sampling_table_size, = self.sampling_table.shape\n sampling_table = self.sampling_table.reshape((1, 1, sampling_table_size))\n ngram_keys = ngram_keys % sampling_table_size\n return torch.take_along_dim(sampling_table, indices=ngram_keys, dim=2)", "docstring": "Samples g values from Bernoulli distribution.\n\n It is not possible to pass random keys in a vectorized way in torch. Instead\n we pre-compute a random sampling table, and use apply modulo table size to\n map from ngram keys (int64) to g values.\n\nArgs:\n ngram_keys (`torch.LongTensor`):\n Random keys (batch_size, num_ngrams, depth).\n\nReturns:\n G values (batch_size, num_ngrams, depth).", "source": "github_repos"} +{"code": "def forward(self, pixel_values: torch.FloatTensor, pixel_attention_mask: torch.Tensor, spatial_shapes: torch.LongTensor, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None) -> BaseModelOutputWithPooling:\n return self.vision_model(pixel_values=pixel_values, attention_mask=pixel_attention_mask, spatial_shapes=spatial_shapes, output_attentions=output_attentions, output_hidden_states=output_hidden_states)", "docstring": "pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):\n Mask to avoid performing attention on padding pixel indices.\n spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):\n Tensor containing the spatial dimensions (height, width) of the input images.\n\nExample:\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, Siglip2VisionModel\n\n >>> model = Siglip2VisionModel.from_pretrained(\"google/siglip2-base-patch16-224\")\n >>> processor = AutoProcessor.from_pretrained(\"google/siglip2-base-patch16-224\")\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> inputs = processor(images=image, return_tensors=\"pt\")\n\n >>> outputs = model(**inputs)\n >>> last_hidden_state = outputs.last_hidden_state\n >>> pooled_output = outputs.pooler_output # pooled features\n ```", "source": "github_repos"} +{"code": "def graph_defs_equal(graph_def_1: graph_pb2.GraphDef, graph_def_2: graph_pb2.GraphDef, treat_nan_as_equal: bool=False) -> bool:\n if not isinstance(graph_def_1, graph_pb2.GraphDef):\n raise TypeError(f'graph_def_1 must be a graph_pb2.GraphDef proto, but got type {type(graph_def_1)}.')\n if not isinstance(graph_def_2, graph_pb2.GraphDef):\n raise TypeError(f'graph_def_2 must be a graph_pb2.GraphDef proto, but got type {type(graph_def_2)}.')\n options = _proto_comparators.ProtoComparisonOptions(treat_nan_as_equal)\n return _proto_comparators.EqualsGraphDef(graph_def_1.SerializeToString(), graph_def_2.SerializeToString(), options)", "docstring": "Returns True iff the graph def arguments are structurally equivalent.\n\n The notion of equivalence encoded here checks that the set of NodeDefs in\n the GraphDef's function library and main graph body are identical.\n Additionally, it checks that the functions in the function library are equal\n as sets.\n\n Example usage:\n\n ```\n with tf.Graph().as_default() as g1:\n tf.constant(1)\n\n with tf.Graph().as_default() as g2:\n tf.constant(2)\n\n with tf.Graph().as_default() as g3:\n tf.constant(1)\n\n assert tf.__internal__.graph_util.graph_defs_equal(g1.as_graph_def(),\n g3.as_graph_def())\n\n assert not tf.__internal__.graph_util.graph_defs_equal(g1.as_graph_def(),\n g2.as_graph_def())\n ```\n\nArgs:\n graph_def_1: Instance of `graph_pb2.GraphDef` to compare.\n graph_def_2: Instance of `graph_pb2.GraphDef` to compare.\n treat_nan_as_equal: Boolean indicating whether or not to treat nan\n floating-point values as equal. This is crucial for any equivalence\n relation defined over GraphDefs, to ensure symmetry.\n\nReturns:\n Boolean indicating structural equivalence as described above.\n\nRaises:\n TypeError: If either of the GraphDefs are not instances of\n `graph_pb2.GraphDef`.", "source": "github_repos"} +{"code": "def assertProtoEqual(self, a, b, check_initialized=True, normalize_numbers=False, msg=None, relative_tolerance=None):\n pool = descriptor_pool.Default()\n if isinstance(a, str):\n a = text_format.Parse(a, b.__class__(), descriptor_pool=pool)\n for pb in (a, b):\n if check_initialized:\n errors = pb.FindInitializationErrors()\n if errors:\n self.fail('Initialization errors: %s\\n%s' % (errors, pb))\n if normalize_numbers:\n NormalizeNumberFields(pb)\n if relative_tolerance is not None:\n checkFloatEqAndReplace(self, expected=b, actual=a, relative_tolerance=relative_tolerance)\n a_str = text_format.MessageToString(a, descriptor_pool=pool)\n b_str = text_format.MessageToString(b, descriptor_pool=pool)\n if len(a_str) < 2 ** 16 and len(b_str) < 2 ** 16:\n self.assertMultiLineEqual(a_str, b_str, msg=msg)\n else:\n diff = ''.join(difflib.unified_diff(a_str.splitlines(True), b_str.splitlines(True)))\n if diff:\n self.fail('%s :\\n%s' % (msg, diff))", "docstring": "Fails with a useful error if a and b aren't equal.\n\n Comparison of repeated fields matches the semantics of\n unittest.TestCase.assertEqual(), ie order and extra duplicates fields matter.\n\nArgs:\n self: googletest.TestCase\n a: proto2 PB instance, or text string representing one.\n b: proto2 PB instance -- message.Message or subclass thereof.\n check_initialized: boolean, whether to fail if either a or b isn't\n initialized.\n normalize_numbers: boolean, whether to normalize types and precision of\n numbers before comparison.\n msg: if specified, is used as the error message on failure.\n relative_tolerance: float, relative tolerance. If this is not provided, then\n all floats are compared using string comparison otherwise, floating point\n comparisons are done using the relative tolerance provided.", "source": "github_repos"} +{"code": "def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> Tuple[np.ndarray, np.ndarray]:\n raise NotImplementedError", "docstring": "For each query in the batch, retrieves `n_docs` documents.\n\nArgs:\n question_hidden_states (`np.ndarray` of shape `(batch_size, vector_size)`):\n An array of query vectors.\n n_docs (`int`):\n The number of docs retrieved per query.\n\nReturns:\n `np.ndarray` of shape `(batch_size, n_docs)`: A tensor of indices of retrieved documents. `np.ndarray` of\n shape `(batch_size, vector_size)`: A tensor of vector representations of retrieved documents.", "source": "github_repos"} +{"code": "def set_signature(self, signature_map: signature_serialization._SignatureMap, wrapped_functions: Dict[Callable[..., Any], Callable[..., Any]]):\n self.list_children(self.root)\n name = signature_serialization.SIGNATURE_ATTRIBUTE_NAME\n self._children_cache[self.root][name] = signature_map\n self._wrapped_functions.update(wrapped_functions)", "docstring": "Attach signature to the root object.\n\nArgs:\n signature_map: An object that contains signature functions.\n wrapped_functions: A dictionary mapping functions to functions that are\n guaranteed to not capture cached variables (functions that capture\n cached variables can't be saved).", "source": "github_repos"} +{"code": "def arctan2(x1, x2):\n if any_symbolic_tensors((x1, x2)):\n return Arctan2().symbolic_call(x1, x2)\n return backend.numpy.arctan2(x1, x2)", "docstring": "Element-wise arc tangent of `x1/x2` choosing the quadrant correctly.\n\n The quadrant (i.e., branch) is chosen so that `arctan2(x1, x2)` is the\n signed angle in radians between the ray ending at the origin and passing\n through the point `(1, 0)`, and the ray ending at the origin and passing\n through the point `(x2, x1)`. (Note the role reversal: the \"y-coordinate\"\n is the first function parameter, the \"x-coordinate\" is the second.) By IEEE\n convention, this function is defined for `x2 = +/-0` and for either or both\n of `x1` and `x2` `= +/-inf`.\n\nArgs:\n x1: First input tensor.\n x2: Second input tensor.\n\nReturns:\n Tensor of angles in radians, in the range `[-pi, pi]`.\n\nExample:\n Consider four points in different quadrants:\n >>> x = keras.ops.convert_to_tensor([-1, +1, +1, -1])\n >>> y = keras.ops.convert_to_tensor([-1, -1, +1, +1])\n >>> keras.ops.arctan2(y, x) * 180 / numpy.pi\n array([-135., -45., 45., 135.], dtype=float32)\n\n Note the order of the parameters. `arctan2` is defined also when x2=0 and\n at several other points, obtaining values in the range `[-pi, pi]`:\n >>> keras.ops.arctan2(\n ... keras.ops.array([1., -1.]),\n ... keras.ops.array([0., 0.]),\n ... )\n array([ 1.5707964, -1.5707964], dtype=float32)\n >>> keras.ops.arctan2(\n ... keras.ops.array([0., 0., numpy.inf]),\n ... keras.ops.array([+0., -0., numpy.inf]),\n ... )\n array([0., 3.1415925, 0.7853982], dtype=float32)", "source": "github_repos"} +{"code": "def _validate_paths_for_modules(self, actual_paths, expected_paths, file_to_update_on_error):\n self.assertTrue(actual_paths)\n self.assertTrue(expected_paths)\n missing_paths = expected_paths - actual_paths\n extra_paths = actual_paths - expected_paths\n missing_paths = [\"'%s'\" % path for path in missing_paths]\n extra_paths = [\"'%s'\" % path for path in extra_paths]\n self.assertFalse(missing_paths, 'Please add %s to %s.' % (',\\n'.join(sorted(missing_paths)), file_to_update_on_error))\n self.assertFalse(extra_paths, 'Redundant paths, please remove %s in %s.' % (',\\n'.join(sorted(extra_paths)), file_to_update_on_error))", "docstring": "Validates that actual_paths match expected_paths.\n\nArgs:\n actual_paths: */__init__.py file paths listed in file_to_update_on_error.\n expected_paths: */__init__.py file paths that we need to create for\n TensorFlow API.\n file_to_update_on_error: File that contains list of */__init__.py files.\n We include it in error message printed if the file list needs to be\n updated.", "source": "github_repos"} +{"code": "def __init__(self, ast, visit_decorators=True):\n self._ast = ast\n maybe_decorators = ['decorator_list'] if visit_decorators else []\n self._node_children = {self._ast.Module: ['body'], self._ast.ClassDef: maybe_decorators + ['keywords', 'bases', 'body'], self._ast.FunctionDef: maybe_decorators + ['body', 'args', 'returns'], self._ast.Assign: ['targets', 'value']}", "docstring": "A base class for writing AST visitors.\n\n Subclasses should define {visit,enter,leave}_X to process nodes of type X.\n If a visit method returns a non-None value, the visited node is replaced\n with that value.\n\nAttributes:\n _ast: Any module whose interface matches the standard ast library, such as\n typed_ast. The same module must be used to generate the AST to visit.", "source": "github_repos"} +{"code": "def run(argv=None, save_main_session=True, test_pipeline=None) -> PipelineResult:\n known_args, pipeline_args = parse_known_args(argv)\n pipeline_options = PipelineOptions(pipeline_args)\n pipeline_options.view_as(SetupOptions).save_main_session = save_main_session\n pipeline = test_pipeline\n if not test_pipeline:\n pipeline = beam.Pipeline(options=pipeline_options)\n model_handler = HuggingFacePipelineModelHandler(task=PipelineTask.QuestionAnswering, model=known_args.model_name, load_model_args={'framework': 'pt', 'revision': known_args.revision})\n if not known_args.input:\n text = pipeline | 'CreateSentences' >> beam.Create(['What does Apache Beam do?;Apache Beam enables batch and streaming data processing.', 'What is the capital of France?;The capital of France is Paris .', 'Where was beam summit?;Apache Beam Summit 2023 was in NYC.'])\n else:\n text = pipeline | 'ReadSentences' >> beam.io.ReadFromText(known_args.input)\n processed_text = text | 'PreProcess' >> beam.ParDo(preprocess) | 'SquadExample' >> beam.ParDo(create_squad_example)\n output = processed_text | 'RunInference' >> RunInference(KeyedModelHandler(model_handler)) | 'ProcessOutput' >> beam.ParDo(PostProcessor())\n _ = output | 'WriteOutput' >> beam.io.WriteToText(known_args.output, shard_name_template='', append_trailing_newlines=True)\n result = pipeline.run()\n result.wait_until_finish()\n return result", "docstring": "Args:\n argv: Command line arguments defined for this example.\n save_main_session: Used for internal testing.\n test_pipeline: Used for internal testing.", "source": "github_repos"} +{"code": "def save_counter(self):\n return self.checkpointer().save_counter", "docstring": "An integer variable numbering the checkpoint events.\n\n This is maintained by the underlying tf.train.Checkpoint object employed by\n AsyncCheckpoint class. The number starts at 0 and gets incremented for each\n checkpoint event.\n\nReturns:\n The save counter variable.", "source": "github_repos"} +{"code": "def _get_key_counter(seed, alg):\n if alg == Algorithm.AUTO_SELECT.value:\n key, counter = gen_stateless_random_ops_v2.stateless_random_get_key_counter(seed)\n elif alg == Algorithm.PHILOX.value:\n key, counter = _philox_scramble_seed(seed)\n elif alg == Algorithm.THREEFRY.value:\n key = array_ops.reshape(_uint32s_to_uint64(math_ops.cast(seed, dtypes.uint32)), [1])\n counter = array_ops.zeros([1], dtypes.uint64)\n else:\n raise ValueError(unsupported_alg_error_msg(alg))\n return (key, counter)", "docstring": "Calculates the key and counter to pass to raw RNG ops.\n\n This function calculates the key and counter that will be passed to\n the raw RNG ops like `StatelessRandomUniformV2`. Depending on the\n input `alg`, the key and counter may be scrambled or copied from\n `seed`. If `alg` is `\"auto_select\"`, the key and counter will be\n determined at runtime based on device type.\n\nArgs:\n seed: An integer tensor of shape [2]. The seed to calculate the key and\n counter from.\n alg: The RNG algorithm. See `tf.random.stateless_uniform` for an\n explanation.\n\nReturns:\n A pair (key, counter) suitable for V2 stateless RNG ops like\n `StatelessRandomUniformV2`.", "source": "github_repos"} +{"code": "def convert_ids_to_tokens(self, ids: Union[int, list[int]], skip_special_tokens: bool=False) -> Union[str, list[str]]:\n if isinstance(ids, int):\n if ids in self._added_tokens_decoder:\n return self._added_tokens_decoder[ids].content\n else:\n return self._convert_id_to_token(ids)\n tokens = []\n for index in ids:\n index = int(index)\n if skip_special_tokens and index in self.all_special_ids:\n continue\n if index in self._added_tokens_decoder:\n tokens.append(self._added_tokens_decoder[index].content)\n else:\n tokens.append(self._convert_id_to_token(index))\n return tokens", "docstring": "Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and\n added tokens.\n\nArgs:\n ids (`int` or `List[int]`):\n The token id (or token ids) to convert to tokens.\n skip_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not to remove special tokens in the decoding.\n\nReturns:\n `str` or `List[str]`: The decoded token(s).", "source": "github_repos"} +{"code": "def process_data_fn(self, inputs: dict[str, common_types.ConsistentTensorType]) -> dict[str, common_types.ConsistentTensorType]:\n outputs = inputs.copy()\n for transform in self.transforms:\n columns = transform.columns\n for col in columns:\n intermediate_result = transform(outputs[col], output_column_name=col)\n for key, value in intermediate_result.items():\n outputs[key] = value\n return outputs", "docstring": "This method is used in the AnalyzeAndTransformDataset step. It applies\n the transforms to the `inputs` in sequential order on the columns\n provided for a given transform.\n\nArgs:\n inputs: A dictionary of column names and data.\n\nReturns:\n A dictionary of column names and transformed data.", "source": "github_repos"} +{"code": "def __init__(self, reduction='sum_over_batch_size', name='mean_absolute_error', dtype=None):\n super().__init__(mean_absolute_error, name=name, reduction=reduction, dtype=dtype)", "docstring": "Computes the mean of absolute difference between labels and predictions.\n\n Formula:\n\n ```python\n loss = mean(abs(y_true - y_pred))\n ```\n\nArgs:\n reduction: Type of reduction to apply to the loss. In almost all cases\n this should be `\"sum_over_batch_size\"`. Supported options are\n `\"sum\"`, `\"sum_over_batch_size\"`, `\"mean\"`,\n `\"mean_with_sample_weight\"` or `None`. `\"sum\"` sums the loss,\n `\"sum_over_batch_size\"` and `\"mean\"` sum the loss and divide by the\n sample size, and `\"mean_with_sample_weight\"` sums the loss and\n divides by the sum of the sample weights. `\"none\"` and `None`\n perform no aggregation. Defaults to `\"sum_over_batch_size\"`.\n name: Optional name for the loss instance.\n dtype: The dtype of the loss's computations. Defaults to `None`, which\n means using `keras.backend.floatx()`. `keras.backend.floatx()` is a\n `\"float32\"` unless set to different value\n (via `keras.backend.set_floatx()`). If a `keras.DTypePolicy` is\n provided, then the `compute_dtype` will be utilized.", "source": "github_repos"} +{"code": "def VisitFunction(self, f):\n groups = self._GroupByArguments(f.signatures)\n new_signatures = []\n for stripped_signature, ret_exc in groups.items():\n ret = pytd_utils.JoinTypes(ret_exc.return_types)\n exc = tuple(ret_exc.exceptions)\n new_signatures.append(stripped_signature.Replace(return_type=ret, exceptions=exc))\n return f.Replace(signatures=tuple(new_signatures))", "docstring": "Merge signatures of a function.\n\n This groups signatures by arguments and then for each group creates a\n single signature that joins the return values / exceptions using \"or\".\n\nArgs:\n f: A pytd.Function instance\n\nReturns:\n Function with simplified / combined signatures.", "source": "github_repos"} +{"code": "def saveable_objects_for_op(op, name):\n if not isinstance(name, str):\n raise TypeError(f'names_to_saveables must be a dict mapping string names to trackable operations. Name is not a string: {name}')\n if isinstance(op, saveable_object.SaveableObject):\n yield op\n elif isinstance(op, (list, tuple, variables.PartitionedVariable)):\n if isinstance(op, variables.PartitionedVariable):\n op = list(op)\n slice_name = None\n for variable in op:\n if isinstance(variable, saveable_object.SaveableObject):\n yield variable\n continue\n if not isinstance(variable, variables.Variable):\n raise ValueError(f'Slices must all be Variables: {variable}')\n if not variable._save_slice_info:\n raise ValueError(f'Slices must all be slices: {variable}')\n if slice_name is None:\n slice_name = variable._save_slice_info.full_name\n elif slice_name != variable._save_slice_info.full_name:\n raise ValueError(f'Slices must all be from the same tensor: {slice_name} != {variable._save_slice_info.full_name}')\n if variable.op.type in _REF_VARIABLE_OPS:\n yield ReferenceVariableSaveable(variable, variable._save_slice_info.spec, name)\n else:\n yield ResourceVariableSaveable(variable, variable._save_slice_info.spec, name)\n elif isinstance(op, trackable.Trackable) and (not isinstance(op, variables.Variable)):\n for attr, factory in saveable_objects_from_trackable(op, tf1_saver=True).items():\n if attr == trackable.VARIABLE_VALUE_KEY:\n full_name = name\n elif attr == trackable_utils.SERIALIZE_TO_TENSORS_NAME:\n full_name = name\n else:\n full_name = name + '_' + attr\n op = factory(full_name) if callable(factory) else factory\n for op in saveable_objects_for_op(op, op.name):\n yield op\n elif isinstance(op, resource_variable_ops.BaseResourceVariable):\n if op._in_graph_mode:\n variable = op._graph_element\n else:\n variable = op\n yield ResourceVariableSaveable(variable, '', name)\n else:\n if context.executing_eagerly():\n raise ValueError(f'Can only save/restore ResourceVariables when executing eagerly, got type: {type(op)}.')\n variable = ops.convert_to_tensor(op, as_ref=True)\n if not _tensor_comes_from_variable(variable):\n raise TypeError(f'names_to_saveables must be a dict mapping string names to Tensors/Variables. Not a variable: {variable}')\n if variable.op.type in _REF_VARIABLE_OPS:\n yield ReferenceVariableSaveable(variable, '', name)\n else:\n yield ResourceVariableSaveable(variable, '', name)", "docstring": "Create `SaveableObject`s from an operation.\n\nArgs:\n op: A variable, operation, or SaveableObject to coerce into a\n SaveableObject.\n name: A string name for the SaveableObject.\n\nYields:\n `SaveableObject`s which together save/restore `op`.\n\nRaises:\n TypeError: If `name` is not a string.\n ValueError: For operations with no known conversion to SaveableObject.", "source": "github_repos"} +{"code": "def _should_stop(state, stopping_policy_fn):\n return tf.convert_to_tensor(stopping_policy_fn(state.finished), name='should_stop', dtype=tf.bool)", "docstring": "Indicates whether the overall Brent search should continue.\n\nArgs:\n state: A Python `_BrentSearchState` namedtuple.\n stopping_policy_fn: Python `callable` controlling the algorithm termination.\n\nReturns:\n A boolean value indicating whether the overall search should continue.", "source": "github_repos"} +{"code": "def __init__(self, name, encode_name, is_array, external):\n Message.__init__(self, name, encode_name, is_array)\n if stl.base.IsString(external):\n module, message_type = external.rsplit('.', 1)\n self.descriptor = importlib.import_module(module).__getattribute__(message_type).DESCRIPTOR\n else:\n self.descriptor = external\n self.external = MessageFromExternal._MakeClass(self.descriptor)\n self._ExtractFieldsFromDesc(self.descriptor)", "docstring": "A protocol specification external.\n\n message mProtocolExample {\n encode \"json\";\n external \"external.class.Name\";\n\nAttributes:\n external: External message class name.\n descriptor: google.protobuf.descriptor.Descriptor to generate self.external.", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.FloatTensor, attention_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[Tuple, BaseModelOutput]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if attention_mask is not None:\n attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.dropout(hidden_states)\n position_bias = self.embed_positions(hidden_states)\n synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n if head_mask is not None:\n if head_mask.size()[0] != len(self.layers):\n raise ValueError(f'The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}.')\n for idx, encoder_layer in enumerate(self.layers):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n skip_the_layer = False\n if self.training:\n dropout_probability = torch.rand([])\n skip_the_layer = dropout_probability < self.layerdrop\n if not skip_the_layer or synced_gpus:\n if self.gradient_checkpointing and self.training:\n layer_outputs = self._gradient_checkpointing_func(encoder_layer.__call__, hidden_states, attention_mask, head_mask[idx] if head_mask is not None else None, position_bias, output_attentions)\n else:\n layer_outputs = encoder_layer(hidden_states, attention_mask=attention_mask, position_bias=position_bias, layer_head_mask=head_mask[idx] if head_mask is not None else None, output_attentions=output_attentions)\n hidden_states = layer_outputs[0]\n if skip_the_layer:\n layer_outputs = (None, None)\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[1],)\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n if not return_dict:\n return tuple((v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None))\n return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions)", "docstring": "Args:\n hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, feature_size)`):\n Features extracted from the speech or text input by the encoder prenet.\n attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing convolution and attention on padding token indices. Mask values selected in\n `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):\n Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.", "source": "github_repos"} +{"code": "def get_vocabulary(self, include_special_tokens=True):\n if self.lookup_table.size() == 0:\n vocab, indices = ([], [])\n else:\n keys, values = self.lookup_table.export()\n vocab, indices = (values, keys) if self.invert else (keys, values)\n vocab, indices = (self._tensor_vocab_to_numpy(vocab), indices.numpy())\n lookup = collections.defaultdict(lambda: self.oov_token, zip(indices, vocab))\n vocab = [lookup[x] for x in range(self.vocabulary_size())]\n if self.mask_token is not None and self.output_mode == 'int':\n vocab[0] = self.mask_token\n if not include_special_tokens:\n vocab = vocab[self._token_start_index():]\n if self.vocabulary_dtype == 'string':\n return [i.decode('utf-8') if isinstance(i, bytes) else i for i in vocab]\n else:\n return vocab", "docstring": "Returns the current vocabulary of the layer.\n\nArgs:\n include_special_tokens: If `True`, the returned vocabulary\n will include mask and OOV tokens,\n and a term's index in the vocabulary\n will equal the term's index when calling the layer.\n If `False`, the returned vocabulary will not include\n any mask or OOV tokens.", "source": "github_repos"} +{"code": "def flip_channel_order(image: np.ndarray, data_format: Optional[ChannelDimension]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:\n input_data_format = infer_channel_dimension_format(image) if input_data_format is None else input_data_format\n if input_data_format == ChannelDimension.LAST:\n image = image[..., ::-1]\n elif input_data_format == ChannelDimension.FIRST:\n image = image[::-1, ...]\n else:\n raise ValueError(f'Unsupported channel dimension: {input_data_format}')\n if data_format is not None:\n image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n return image", "docstring": "Flips the channel order of the image.\n\n If the image is in RGB format, it will be converted to BGR and vice versa.\n\nArgs:\n image (`np.ndarray`):\n The image to flip.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format for the output image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use same as the input image.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format for the input image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use the inferred format of the input image.", "source": "github_repos"} +{"code": "def GetTermIdentifier(self):\n return self._term", "docstring": "Returns the TERM environment variable for the console.\n\nReturns:\n str: A str that describes the console's text capabilities", "source": "github_repos"} +{"code": "def hard_silu(x):\n if any_symbolic_tensors((x,)):\n return HardSilu().symbolic_call(x)\n return backend.nn.hard_silu(x)", "docstring": "Hard SiLU activation function, also known as Hard Swish.\n\n It is defined as:\n\n - `0` if `if x < -3`\n - `x` if `x > 3`\n - `x * (x + 3) / 6` if `-3 <= x <= 3`\n\n It's a faster, piecewise linear approximation of the silu activation.\n\nArgs:\n x: Input tensor.\n\nReturns:\n A tensor with the same shape as `x`.\n\nExample:\n >>> x = keras.ops.convert_to_tensor([-3.0, -1.0, 0.0, 1.0, 3.0])\n >>> keras.ops.hard_silu(x)\n array([-0.0, -0.3333333, 0.0, 0.6666667, 3.0], shape=(5,), dtype=float32)", "source": "github_repos"} +{"code": "def _Inputs(op: ops.Operation, xs_set):\n if _IsFunction(op.graph):\n inputs = []\n for t in op.inputs:\n if t not in xs_set:\n t = _MaybeCaptured(t)\n inputs.append(t)\n return inputs\n else:\n return op.inputs", "docstring": "Returns the inputs of op, crossing closure boundaries where necessary.\n\nArgs:\n op: Operation\n xs_set: ObjectIdentitySet of Tensors we are differentiating w.r.t.\n\nReturns:\n A list of tensors. The tensors may be from multiple Graph/FuncGraphs if op\n is in a FuncGraph and has captured inputs.", "source": "github_repos"} +{"code": "def __init__(self, agg_func: Callable[[Iterable[int]], int], agg_model_id: Optional[str]=None, include_source_predictions: bool=False, normal_label: int=DEFAULT_NORMAL_LABEL, outlier_label: int=DEFAULT_OUTLIER_LABEL, missing_label: int=DEFAULT_MISSING_LABEL):\n self._agg = agg_func\n self._normal_label = normal_label\n self._outlier_label = outlier_label\n self._missing_label = missing_label\n _AggModelIdMixin.__init__(self, agg_model_id)\n _SourcePredictionMixin.__init__(self, include_source_predictions)", "docstring": "Aggregates anomaly predictions based on their labels.\n\n This is an abstract base class for `AggregationFn`s that combine multiple\n `AnomalyPrediction` objects into a single `AnomalyPrediction` based on\n the labels of the input predictions.\n\nArgs:\n agg_func (Callable[[Iterable[int]], int]): A function that aggregates\n a collection of anomaly labels (integers) into a single label.\n agg_model_id (Optional[str]): The model id used in aggregated predictions.\n Defaults to None.\n include_source_predictions (bool): If True, include the input predictions in\n the `source_predictions` of the output. Defaults to False.", "source": "github_repos"} +{"code": "def _format_time(self, time_per_unit, unit_name):\n formatted = ''\n if time_per_unit >= 1 or time_per_unit == 0:\n formatted += f' {time_per_unit:.0f}s/{unit_name}'\n elif time_per_unit >= 0.001:\n formatted += f' {time_per_unit * 1000.0:.0f}ms/{unit_name}'\n else:\n formatted += f' {time_per_unit * 1000000.0:.0f}us/{unit_name}'\n return formatted", "docstring": "format a given duration to display to the user.\n\n Given the duration, this function formats it in either milliseconds\n or seconds and displays the unit (i.e. ms/step or s/epoch).\n\nArgs:\n time_per_unit: the duration to display\n unit_name: the name of the unit to display\n\nReturns:\n A string with the correctly formatted duration and units", "source": "github_repos"} +{"code": "def unshuffle_from_sc_to_cpu(t: tensor.Tensor, num_sparse_cores: int, offset_in_shard: int, size_in_shard: int, shard_rotation: int=0) -> tensor.Tensor:\n old_shape = t.shape\n if t.shape[0] % num_sparse_cores != 0:\n raise ValueError('The dim of table ({}) should be multiple of number of sparse cores ({})'.format(t.shape[1], num_sparse_cores))\n shards_t = array_ops.reshape(t, (num_sparse_cores, t.shape[0] // num_sparse_cores, t.shape[1]))\n shards = shards_t[:, offset_in_shard:offset_in_shard + size_in_shard, :]\n if shard_rotation:\n shards = manip_ops.roll(shards, -shard_rotation, axis=0)\n intermediate_tensor = array_ops.transpose(shards, (1, 0, 2))\n new_shape = (size_in_shard * num_sparse_cores, old_shape[1])\n return array_ops.reshape(intermediate_tensor, new_shape)", "docstring": "Unshuffles the sparse core sharded embedding tables to unsharded.\n\n This converts an input tensor respresenting stacked and sharded embedding\n table into a specific embedding table variable by using the provided\n metadata about the said table within the stacked, sharded embedding table.\n\nArgs:\n t: The input stacked and sharded embedding table from sparsecore.\n num_sparse_cores: The number of sparsecores, this determines the number of\n shards that are present in the input t.\n offset_in_shard: Offset within a shard where the queried table starts.\n size_in_shard: size (number of rows) of this queried table within each shard\n of the input t.\n shard_rotation: The rotation of this table's shards.\n\nReturns:\n An embedding table which is part of the stacked embedding table t.", "source": "github_repos"} +{"code": "def isanytargetmethod(object):\n decorators, target = tf_decorator.unwrap(object)\n for decorator in decorators:\n if _inspect.ismethod(decorator.decorated_target):\n return True\n while isinstance(target, functools.partial):\n target = target.func\n return callable(target) and (not _inspect.isfunction(target))", "docstring": "Checks if `object` or a TF Decorator wrapped target contains self or cls.\n\n This function could be used along with `tf_inspect.getfullargspec` to\n determine if the first argument of `object` argspec is self or cls. If the\n first argument is self or cls, it needs to be excluded from argspec when we\n compare the argspec to the input arguments and, if provided, the tf.function\n input_signature.\n\n Like `tf_inspect.getfullargspec` and python `inspect.getfullargspec`, it\n does not unwrap python decorators.\n\nArgs:\n obj: An method, function, or functool.partial, possibly decorated by\n TFDecorator.\n\nReturns:\n A bool indicates if `object` or any target along the chain of TF decorators\n is a method.", "source": "github_repos"} +{"code": "def attr_chain(obj, attr):\n next = getattr(obj, attr)\n while next:\n yield next\n next = getattr(next, attr)", "docstring": "Follow an attribute chain.\n\n If you have a chain of objects where a.foo -> b, b.foo-> c, etc, use this to\n iterate over all objects in the chain. Iteration is terminated by getattr(x,\n attr) is None.\n\nArgs:\n obj: the starting object\n attr: the name of the chaining attribute\n\nYields:\n Each successive object in the chain.", "source": "github_repos"} +{"code": "def forward(self, pixel_values: Optional[torch.Tensor]=None, bool_masked_pos: Optional[torch.BoolTensor]=None, head_mask: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, interpolate_pos_encoding: bool=False, return_dict: Optional[bool]=None) -> Union[tuple, MaskedLMOutput]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.beit(pixel_values, bool_masked_pos=bool_masked_pos, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=return_dict)\n sequence_output = outputs[0]\n sequence_output = self.layernorm(sequence_output)\n prediction_scores = self.lm_head(sequence_output[:, 1:])\n masked_lm_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(prediction_scores[bool_masked_pos], labels)\n if not return_dict:\n output = (prediction_scores,) + outputs[1:]\n return (masked_lm_loss,) + output if masked_lm_loss is not None else output\n return MaskedLMOutput(loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):\n Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\nExample:\n ```python\n >>> from transformers import AutoImageProcessor, BeitForMaskedImageModeling\n >>> import torch\n >>> from PIL import Image\n >>> import requests\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> image_processor = AutoImageProcessor.from_pretrained(\"microsoft/beit-base-patch16-224-pt22k\")\n >>> model = BeitForMaskedImageModeling.from_pretrained(\"microsoft/beit-base-patch16-224-pt22k\")\n\n >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2\n >>> pixel_values = image_processor(images=image, return_tensors=\"pt\").pixel_values\n >>> # create random boolean mask of shape (batch_size, num_patches)\n >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()\n\n >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)\n >>> loss, logits = outputs.loss, outputs.logits\n >>> list(logits.shape)\n [1, 196, 8192]\n ```", "source": "github_repos"} +{"code": "def __init__(self, bos_token_id: int):\n if bos_token_id < 0:\n raise ValueError(f'The forced bos token id must be a non-negative integer, got {bos_token_id}')\n self.bos_token_id = bos_token_id", "docstring": "[`TFLogitsProcessor`] that enforces the specified token as the first generated token.\n\nArgs:\n bos_token_id (`int`):\n The id of the token to force as the first generated token.", "source": "github_repos"} +{"code": "def _check_tf1_flags(flags, unparsed):\n\n def _get_message_unparsed(flag, orig_flag, new_flag):\n if flag.startswith(orig_flag):\n return '\\n Use {0} instead of {1}'.format(new_flag, orig_flag)\n return ''\n if unparsed:\n output = ''\n for flag in unparsed:\n output += _get_message_unparsed(flag, '--input_file', '--graph_def_file')\n output += _get_message_unparsed(flag, '--savedmodel_directory', '--saved_model_dir')\n output += _get_message_unparsed(flag, '--std_value', '--std_dev_values')\n output += _get_message_unparsed(flag, '--batch_size', '--input_shapes')\n output += _get_message_unparsed(flag, '--dump_graphviz', '--dump_graphviz_dir')\n if output:\n raise ValueError(output)\n if flags.graph_def_file and (not flags.input_arrays or not flags.output_arrays):\n raise ValueError('--input_arrays and --output_arrays are required with --graph_def_file')\n if flags.input_shapes:\n if not flags.input_arrays:\n raise ValueError('--input_shapes must be used with --input_arrays')\n if flags.input_shapes.count(':') != flags.input_arrays.count(','):\n raise ValueError('--input_shapes and --input_arrays must have the same number of items')\n if flags.std_dev_values or flags.mean_values:\n if bool(flags.std_dev_values) != bool(flags.mean_values):\n raise ValueError('--std_dev_values and --mean_values must be used together')\n if flags.std_dev_values.count(',') != flags.mean_values.count(','):\n raise ValueError('--std_dev_values, --mean_values must have the same number of items')\n if (flags.default_ranges_min is None) != (flags.default_ranges_max is None):\n raise ValueError('--default_ranges_min and --default_ranges_max must be used together')\n if flags.dump_graphviz_video and (not flags.dump_graphviz_dir):\n raise ValueError('--dump_graphviz_video must be used with --dump_graphviz_dir')\n if flags.custom_opdefs and (not flags.experimental_new_converter):\n raise ValueError('--custom_opdefs must be used with --experimental_new_converter')\n if flags.custom_opdefs and (not flags.allow_custom_ops):\n raise ValueError('--custom_opdefs must be used with --allow_custom_ops')\n if flags.experimental_select_user_tf_ops and (not flags.experimental_new_converter):\n raise ValueError('--experimental_select_user_tf_ops must be used with --experimental_new_converter')", "docstring": "Checks the parsed and unparsed flags to ensure they are valid in 1.X.\n\n Raises an error if previously support unparsed flags are found. Raises an\n error for parsed flags that don't meet the required conditions.\n\nArgs:\n flags: argparse.Namespace object containing TFLite flags.\n unparsed: List of unparsed flags.\n\nRaises:\n ValueError: Invalid flags.", "source": "github_repos"} +{"code": "def uses_star_kwargs_in_call(node):\n if sys.version_info[:2] >= (3, 5):\n for keyword in node.keywords:\n if keyword.arg is None:\n return True\n elif node.kwargs:\n return True\n return False", "docstring": "Check if an ast.Call node uses arbitrary-length **kwargs.\n\n This function works with the AST call node format of Python3.5+\n as well as the different AST format of earlier versions of Python.\n\nArgs:\n node: The ast.Call node to check arg values for.\n\nReturns:\n True if the node uses starred variadic positional args or keyword args.\n False if it does not.", "source": "github_repos"} +{"code": "def _HandleDuplicates(self, new_aliases):\n name_to_alias = {}\n out = []\n for a in new_aliases:\n if a.name not in name_to_alias:\n name_to_alias[a.name] = a\n out.append(a)\n continue\n existing = name_to_alias[a.name]\n if self._EquivalentAliases(existing, a):\n continue\n existing_name = existing.type.name or existing.type.__class__.__name__\n a_name = a.type.name or a.type.__class__.__name__\n raise KeyError(f'Duplicate top level items: {existing_name!r}, {a_name!r}')\n return out", "docstring": "Handle duplicate module-level aliases.\n\n Aliases pointing to qualified names could be the result of importing the\n same entity through multiple import paths, which should not count as an\n error; instead we just deduplicate them.\n\nArgs:\n new_aliases: The list of new aliases to deduplicate\n\nReturns:\n A deduplicated list of aliases.\n\nRaises:\n KeyError: If there is a name clash.", "source": "github_repos"} +{"code": "def remove_undocumented(module_name, allowed_exception_list=None, doc_string_modules=None):\n current_symbols = set(dir(_sys.modules[module_name]))\n should_have = make_all(module_name, doc_string_modules)\n should_have += allowed_exception_list or []\n extra_symbols = current_symbols - set(should_have)\n target_module = _sys.modules[module_name]\n for extra_symbol in extra_symbols:\n if extra_symbol.startswith('_'):\n continue\n fully_qualified_name = module_name + '.' + extra_symbol\n _HIDDEN_ATTRIBUTES[fully_qualified_name] = (target_module, getattr(target_module, extra_symbol))\n delattr(target_module, extra_symbol)", "docstring": "Removes symbols in a module that are not referenced by a docstring.\n\nArgs:\n module_name: the name of the module (usually `__name__`).\n allowed_exception_list: a list of names that should not be removed.\n doc_string_modules: a list of modules from which to take the docstrings.\n If None, then a list containing only the module named `module_name` is used.\n\n Furthermore, if a symbol previously added with `add_to_global_allowlist`,\n then it will always be allowed. This is useful for internal tests.\n\nReturns:\n None", "source": "github_repos"} +{"code": "def __init__(self, loss=None, predictions=None, metrics=None):\n if loss is not None:\n loss_dict = self._wrap_and_check_outputs(loss, self.LOSS_NAME)\n self._loss = self._prefix_output_keys(loss_dict, self.LOSS_NAME)\n if predictions is not None:\n pred_dict = self._wrap_and_check_outputs(predictions, self.PREDICTIONS_NAME)\n self._predictions = self._prefix_output_keys(pred_dict, self.PREDICTIONS_NAME)\n if metrics is not None:\n self._metrics = self._wrap_and_check_metrics(metrics)", "docstring": "Constructor for SupervisedOutput (ie, Train or Eval output).\n\nArgs:\n loss: dict of Tensors or single Tensor representing calculated loss.\n predictions: dict of Tensors or single Tensor representing model\n predictions.\n metrics: Dict of metric results keyed by name.\n The values of the dict can be one of the following:\n (1) instance of `Metric` class.\n (2) (metric_value, update_op) tuples, or a single tuple.\n metric_value must be a Tensor, and update_op must be a Tensor or Op.\n\nRaises:\n ValueError: if any of the outputs' dict keys are not strings or tuples of\n strings or the values are not Tensors (or Operations in the case of\n update_op).", "source": "github_repos"} +{"code": "def fuse_awq_modules(model, quantization_config):\n if isinstance(quantization_config, dict):\n quantization_config = AwqConfig.from_dict(quantization_config)\n backend = quantization_config.backend\n modules_to_fuse = get_modules_to_fuse(model, quantization_config)\n modules_to_not_convert = getattr(quantization_config, 'modules_to_not_convert', None)\n if backend == AwqBackendPackingMethod.AUTOAWQ:\n from awq.modules.fused.attn import QuantAttentionFused\n from awq.modules.fused.mlp import QuantFusedMLP\n from awq.modules.fused.norm import FasterTransformerRMSNorm\n else:\n raise ValueError('Fusing is only supported for the AutoAWQ backend')\n fused_attention_modules = []\n for name, module in model.named_modules():\n if modules_to_not_convert is not None:\n if any((module_name_to_not_convert in name for module_name_to_not_convert in modules_to_not_convert)):\n continue\n _fuse_awq_layernorm(modules_to_fuse['layernorm'], module, FasterTransformerRMSNorm)\n if quantization_config.version != 'ipex':\n _fuse_awq_mlp(model, name, modules_to_fuse['mlp'], module, QuantFusedMLP)\n else:\n logger.info('The IPEX version AWQ does not support fuse mlp for now.')\n attention_has_been_fused = _fuse_awq_attention_layers(model, module, modules_to_fuse, name, QuantAttentionFused)\n if attention_has_been_fused:\n fused_attention_modules.append(name.split('.')[0])\n if len(fused_attention_modules) > 0:\n for module_name, module in model.named_modules():\n if any((module_name in fused_attention_modules for fused_attention_parent_module in fused_attention_modules)):\n if hasattr(module, 'config') and hasattr(module.config, '_attn_implementation'):\n module.config._attn_implementation = 'custom'\n return model", "docstring": "Optionally fuse some modules in the model to speedup inference.\n\nArgs:\n model (`~PreTrainedModel`):\n The model to fuse - note this model should have been converted into AWQ format beforehand.\n quantization_config (`Union[AwqConfig, dict]`):\n The quantization configuration to use.", "source": "github_repos"} +{"code": "def post_process_pose_estimation(self, outputs: 'VitPoseEstimatorOutput', boxes: Union[List[List[List[float]]], np.ndarray], kernel_size: int=11, threshold: Optional[float]=None, target_sizes: Union[TensorType, List[Tuple]]=None):\n batch_size, num_keypoints, _, _ = outputs.heatmaps.shape\n if target_sizes is not None:\n if batch_size != len(target_sizes):\n raise ValueError('Make sure that you pass in as many target sizes as the batch dimension of the logits')\n centers = np.zeros((batch_size, 2), dtype=np.float32)\n scales = np.zeros((batch_size, 2), dtype=np.float32)\n flattened_boxes = list(itertools.chain(*boxes))\n for i in range(batch_size):\n if target_sizes is not None:\n image_width, image_height = (target_sizes[i][0], target_sizes[i][1])\n scale_factor = np.array([image_width, image_height, image_width, image_height])\n flattened_boxes[i] = flattened_boxes[i] * scale_factor\n width, height = (self.size['width'], self.size['height'])\n center, scale = box_to_center_and_scale(flattened_boxes[i], image_width=width, image_height=height)\n centers[i, :] = center\n scales[i, :] = scale\n preds, scores = self.keypoints_from_heatmaps(outputs.heatmaps.cpu().numpy(), centers, scales, kernel=kernel_size)\n all_boxes = np.zeros((batch_size, 4), dtype=np.float32)\n all_boxes[:, 0:2] = centers[:, 0:2]\n all_boxes[:, 2:4] = scales[:, 0:2]\n poses = torch.tensor(preds)\n scores = torch.tensor(scores)\n labels = torch.arange(0, num_keypoints)\n bboxes_xyxy = torch.tensor(coco_to_pascal_voc(all_boxes))\n results: List[List[Dict[str, torch.Tensor]]] = []\n pose_bbox_pairs = zip(poses, scores, bboxes_xyxy)\n for image_bboxes in boxes:\n image_results: List[Dict[str, torch.Tensor]] = []\n for _ in image_bboxes:\n pose, score, bbox_xyxy = next(pose_bbox_pairs)\n score = score.squeeze()\n keypoints_labels = labels\n if threshold is not None:\n keep = score > threshold\n pose = pose[keep]\n score = score[keep]\n keypoints_labels = keypoints_labels[keep]\n pose_result = {'keypoints': pose, 'scores': score, 'labels': keypoints_labels, 'bbox': bbox_xyxy}\n image_results.append(pose_result)\n results.append(image_results)\n return results", "docstring": "Transform the heatmaps into keypoint predictions and transform them back to the image.\n\nArgs:\n outputs (`VitPoseEstimatorOutput`):\n VitPoseForPoseEstimation model outputs.\n boxes (`List[List[List[float]]]` or `np.ndarray`):\n List or array of bounding boxes for each image. Each box should be a list of 4 floats representing the bounding\n box coordinates in COCO format (top_left_x, top_left_y, width, height).\n kernel_size (`int`, *optional*, defaults to 11):\n Gaussian kernel size (K) for modulation.\n threshold (`float`, *optional*, defaults to None):\n Score threshold to keep object detection predictions.\n target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):\n Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size\n `(height, width)` of each image in the batch. If unset, predictions will be resize with the default value.\n\nReturns:\n `List[List[Dict]]`: A list of dictionaries, each dictionary containing the keypoints and boxes for an image\n in the batch as predicted by the model.", "source": "github_repos"} +{"code": "def run_suite_class(argv=None):\n cli_args = _parse_cli_args(argv)\n suite_class = _find_suite_class()\n if cli_args.list_tests:\n _print_test_names_for_suite(suite_class)\n sys.exit(0)\n test_configs = config_parser.load_test_config_file(cli_args.config, cli_args.test_bed)\n config_count = len(test_configs)\n if config_count != 1:\n logging.error('Expect exactly one test config, found %d', config_count)\n config = test_configs[0]\n runner = test_runner.TestRunner(log_dir=config.log_path, testbed_name=config.testbed_name)\n suite = suite_class(runner, config)\n test_selector = _parse_raw_test_selector(cli_args.tests)\n suite.set_test_selector(test_selector)\n suite_record = SuiteInfoRecord(suite_class_name=suite_class.__name__)\n console_level = logging.DEBUG if cli_args.verbose else logging.INFO\n ok = False\n with runner.mobly_logger(console_level=console_level) as log_path:\n try:\n suite.setup_suite(config.copy())\n try:\n suite_record.suite_begin()\n runner.run()\n ok = runner.results.is_all_pass\n print(ok)\n except signals.TestAbortAll:\n pass\n finally:\n suite.teardown_suite()\n suite_record.suite_end()\n suite_record.suite_run_display_name = suite.get_suite_run_display_name()\n suite_record.extras = suite.get_suite_info().copy()\n _dump_suite_info(suite_record, log_path)\n if not ok:\n sys.exit(1)", "docstring": "Executes tests in the test suite.\n\nArgs:\n argv: A list that is then parsed as CLI args. If None, defaults to sys.argv.", "source": "github_repos"} +{"code": "def register_keras_serializable(package='Custom', name=None):\n\n def decorator(arg):\n \"\"\"Registers a class with the Keras serialization framework.\"\"\"\n class_name = name if name is not None else arg.__name__\n registered_name = package + '>' + class_name\n if tf_inspect.isclass(arg) and (not hasattr(arg, 'get_config')):\n raise ValueError('Cannot register a class that does not have a get_config() method.')\n if registered_name in _GLOBAL_CUSTOM_OBJECTS:\n raise ValueError('%s has already been registered to %s' % (registered_name, _GLOBAL_CUSTOM_OBJECTS[registered_name]))\n if arg in _GLOBAL_CUSTOM_NAMES:\n raise ValueError('%s has already been registered to %s' % (arg, _GLOBAL_CUSTOM_NAMES[arg]))\n _GLOBAL_CUSTOM_OBJECTS[registered_name] = arg\n _GLOBAL_CUSTOM_NAMES[arg] = registered_name\n return arg\n return decorator", "docstring": "Registers an object with the Keras serialization framework.\n\n This decorator injects the decorated class or function into the Keras custom\n object dictionary, so that it can be serialized and deserialized without\n needing an entry in the user-provided custom object dict. It also injects a\n function that Keras will call to get the object's serializable string key.\n\n Note that to be serialized and deserialized, classes must implement the\n `get_config()` method. Functions do not have this requirement.\n\n The object will be registered under the key 'package>name' where `name`,\n defaults to the object name if not passed.\n\nArgs:\n package: The package that this class belongs to.\n name: The name to serialize this class under in this package. If None, the\n class' name will be used.\n\nReturns:\n A decorator that registers the decorated class with the passed names.", "source": "github_repos"} +{"code": "def flip(x, axis=None):\n if any_symbolic_tensors((x,)):\n return Flip(axis=axis).symbolic_call(x)\n return backend.numpy.flip(x, axis=axis)", "docstring": "Reverse the order of elements in the tensor along the given axis.\n\n The shape of the tensor is preserved, but the elements are reordered.\n\nArgs:\n x: Input tensor.\n axis: Axis or axes along which to flip the tensor. The default,\n `axis=None`, will flip over all of the axes of the input tensor.\n\nReturns:\n Output tensor with entries of `axis` reversed.", "source": "github_repos"} +{"code": "def process_queries(self, text: Union[TextInput, List[TextInput]], **kwargs: Unpack[ColPaliProcessorKwargs]) -> BatchFeature:\n return self.__call__(text=text, **kwargs)", "docstring": "Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's\n [`ColPaliProcessor.__call__`].\n\n This method forwards the `text` and `kwargs` arguments to the tokenizer.\n\nArgs:\n text (`str`, `List[str]`, `List[List[str]]`):\n The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings\n (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set\n `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors of a particular framework. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return NumPy `np.ndarray` objects.\n - `'jax'`: Return JAX `jnp.ndarray` objects.\n\nReturns:\n [`BatchFeature`]: A [`BatchFeature`] with the following fields:\n\n - **input_ids** -- List of token ids to be fed to a model.\n - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when\n `return_attention_mask=True` or if *\"attention_mask\"* is in `self.model_input_names` and if `text` is not\n `None`).", "source": "github_repos"} +{"code": "def on_epoch_begin(self, epoch, logs=None):\n logs = self._process_logs(logs)\n for callback in self.callbacks:\n callback.on_epoch_begin(epoch, logs)", "docstring": "Calls the `on_epoch_begin` methods of its callbacks.\n\n This function should only be called during TRAIN mode.\n\nArgs:\n epoch: Integer, index of epoch.\n logs: Dict. Currently no data is passed to this argument for this method\n but that may change in the future.", "source": "github_repos"} +{"code": "def categorical_crossentropy(target, output, from_logits=False, axis=-1):\n target = tensor_conversion.convert_to_tensor_v2_with_dispatch(target)\n output = tensor_conversion.convert_to_tensor_v2_with_dispatch(output)\n target.shape.assert_is_compatible_with(output.shape)\n if hasattr(output, '_keras_logits'):\n output = output._keras_logits\n if from_logits:\n warnings.warn('\"`categorical_crossentropy` received `from_logits=True`, but the `output` argument was produced by a sigmoid or softmax activation and thus does not represent logits. Was this intended?\"')\n from_logits = True\n if from_logits:\n return nn.softmax_cross_entropy_with_logits_v2(labels=target, logits=output, axis=axis)\n if (not isinstance(output, (ops.EagerTensor, variables_module.Variable)) and output.op.type == 'Softmax') and (not hasattr(output, '_keras_history')):\n assert len(output.op.inputs) == 1\n output = output.op.inputs[0]\n return nn.softmax_cross_entropy_with_logits_v2(labels=target, logits=output, axis=axis)\n output = output / math_ops.reduce_sum(output, axis, True)\n epsilon_ = _constant_to_tensor(epsilon(), output.dtype.base_dtype)\n output = clip_ops.clip_by_value(output, epsilon_, 1.0 - epsilon_)\n return -math_ops.reduce_sum(target * math_ops.log(output), axis)", "docstring": "Categorical crossentropy between an output tensor and a target tensor.\n\nArgs:\n target: A tensor of the same shape as `output`.\n output: A tensor resulting from a softmax\n (unless `from_logits` is True, in which\n case `output` is expected to be the logits).\n from_logits: Boolean, whether `output` is the\n result of a softmax, or is a tensor of logits.\n axis: Int specifying the channels axis. `axis=-1` corresponds to data\n format `channels_last`, and `axis=1` corresponds to data format\n `channels_first`.\n\nReturns:\n Output tensor.\n\nRaises:\n ValueError: if `axis` is neither -1 nor one of the axes of `output`.\n\nExample:\n >>> a = tf.constant([1., 0., 0., 0., 1., 0., 0., 0., 1.], shape=[3,3])\n >>> print(a)\n tf.Tensor(\n [[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]], shape=(3, 3), dtype=float32)\n >>> b = tf.constant([.9, .05, .05, .05, .89, .06, .05, .01, .94], shape=[3,3])\n >>> print(b)\n tf.Tensor(\n [[0.9 0.05 0.05]\n [0.05 0.89 0.06]\n [0.05 0.01 0.94]], shape=(3, 3), dtype=float32)\n >>> loss = tf.keras.backend.categorical_crossentropy(a, b)\n >>> print(np.around(loss, 5))\n [0.10536 0.11653 0.06188]\n >>> loss = tf.keras.backend.categorical_crossentropy(a, a)\n >>> print(np.around(loss, 5))\n [0. 0. 0.]", "source": "github_repos"} +{"code": "def NeedsSeparatingHyphenHyphen(self, flag='help'):\n element = self.GetLastHealthyElement()\n component = element.component\n spec = inspectutils.GetFullArgSpec(component)\n return spec.varkw is not None or flag in spec.args or flag in spec.kwonlyargs", "docstring": "Returns whether a the trace need '--' before '--help'.\n\n '--' is needed when the component takes keyword arguments, when the value of\n flag matches one of the argument of the component, or the component takes in\n keyword-only arguments(e.g. argument with default value).\n\nArgs:\n flag: the flag available for the trace\n\nReturns:\n True for needed '--', False otherwise.", "source": "github_repos"} +{"code": "def _gather(self, per_replica_value, destinations, axis, options=None):\n if isinstance(per_replica_value, indexed_slices.IndexedSlices):\n raise NotImplementedError('gather/all_gather does not support IndexedSlices')\n if options is None:\n options = collective_util.Options()\n per_replica_value = _make_tensor_into_per_replica(per_replica_value)\n validate_destinations(destinations)\n if self._num_between_graph_workers == 1 and len(per_replica_value.values) == 1 and _devices_match(per_replica_value, destinations, self._canonicalize_devices):\n with ops.device(per_replica_value.values[0].device):\n v = array_ops.identity(per_replica_value.values[0])\n return distribute_utils.regroup((v,), wrap_class=value_lib.Mirrored)\n return self._gather_implementation(per_replica_value, destinations, axis, options)", "docstring": "Gather `per_replica_value` to `destinations`.\n\nArgs:\n per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor`\n like object.\n destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a\n `tf.Tensor` alike object, or a device string. It specifies the devices\n to gather to. To perform an all-gather, pass the same to `value` and\n `destinations`. Note that if it's a `tf.Variable`, the value is gathered\n to the devices of that variable, and this method doesn't update the\n variable.\n axis: specifies the dimension to gather along within each replica's\n tensor.\n options: a `tf.distribute.experimental.CommunicationOptions`. See\n `tf.distribute.experimental.CommunicationOptions` for details.\n\nReturns:\n A `tf.Tensor` or `tf.distribute.DistributedValues`\n\nRaises:\n ValueError: if per_replica_value can't be converted to a\n `tf.distribute.DistributedValues` or if destinations is not a string,\n `tf.Variable` or `tf.distribute.DistributedValues`.", "source": "github_repos"} +{"code": "def _combine_named_parameters(**kwargs) -> list[OrderedDict[str, Any]]:\n sort_by_key = lambda k: k[0]\n combinations: list[list[tuple[str, Any]]] = []\n for key, values in sorted(kwargs.items(), key=sort_by_key):\n if not isinstance(values, list):\n values = [values]\n combinations.append([(key, value) for value in values])\n return [OrderedDict(result) for result in itertools.product(*combinations)]", "docstring": "Generate combinations based on its keyword arguments.\n\n Two sets of returned combinations can be concatenated using +. Their product\n can be computed using `times()`.\n\nArgs:\n **kwargs: keyword arguments of form `option=[possibilities, ...]` or\n `option=the_only_possibility`.\n\nReturns:\n a list of dictionaries for each combination. Keys in the dictionaries are\n the keyword argument names. Each key has one value - one of the\n corresponding keyword argument values.", "source": "github_repos"} +{"code": "def unpad_image(tensor, original_size):\n if not isinstance(original_size, (list, tuple)):\n if not isinstance(original_size, (torch.Tensor, np.ndarray)):\n raise TypeError(f'image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor')\n original_size = original_size.tolist()\n original_height, original_width = original_size\n current_height, current_width = tensor.shape[1:]\n original_aspect_ratio = original_width / original_height\n current_aspect_ratio = current_width / current_height\n if original_aspect_ratio > current_aspect_ratio:\n scale_factor = current_width / original_width\n new_height = int(round(original_height * scale_factor, 7))\n padding = (current_height - new_height) // 2\n unpadded_tensor = tensor[:, padding:current_height - padding, :]\n else:\n scale_factor = current_height / original_height\n new_width = int(round(original_width * scale_factor, 7))\n padding = (current_width - new_width) // 2\n unpadded_tensor = tensor[:, :, padding:current_width - padding]\n return unpadded_tensor", "docstring": "Unpads a PyTorch tensor of a padded and resized image.\n\nArgs:\n tensor (`torch.Tensor`):\n The image tensor, assumed to be of shape (num_channels, height, width).\n original_size (`tuple`):\n The original size of the image (height, width).\n\nReturns:\n `torch.Tensor`: The unpadded image tensor.", "source": "github_repos"} +{"code": "def create_analyzer_cli(dump):\n analyzer = analyzer_cli.DebugAnalyzer(dump, _cli_config_from_temp_file())\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler('list_tensors', analyzer.list_tensors, analyzer.get_help('list_tensors'), prefix_aliases=['lt'])\n registry.register_command_handler('node_info', analyzer.node_info, analyzer.get_help('node_info'), prefix_aliases=['ni'])\n registry.register_command_handler('list_inputs', analyzer.list_inputs, analyzer.get_help('list_inputs'), prefix_aliases=['li'])\n registry.register_command_handler('list_outputs', analyzer.list_outputs, analyzer.get_help('list_outputs'), prefix_aliases=['lo'])\n registry.register_command_handler('print_tensor', analyzer.print_tensor, analyzer.get_help('print_tensor'), prefix_aliases=['pt'])\n registry.register_command_handler('print_source', analyzer.print_source, analyzer.get_help('print_source'), prefix_aliases=['ps'])\n registry.register_command_handler('list_source', analyzer.list_source, analyzer.get_help('list_source'), prefix_aliases=['ls'])\n registry.register_command_handler('eval', analyzer.evaluate_expression, analyzer.get_help('eval'), prefix_aliases=['ev'])\n return (analyzer, registry)", "docstring": "Create an analyzer CLI.\n\nArgs:\n dump: A `DebugDumpDir` object to base the analyzer CLI on.\n\nReturns:\n 1) A `DebugAnalyzer` object created based on `dump`.\n 2) A `CommandHandlerRegistry` that is based on the `DebugAnalyzer` object\n and has the common tfdbg commands, e.g., lt, ni, li, lo, registered.", "source": "github_repos"} +{"code": "def add_chunk(self, chunk: Union[message.Message, bytes], field_tags: util.FieldTypes, index=None) -> None:\n if self._parent_splitter is not None:\n self._parent_splitter.add_chunk(chunk, self._fields_in_parent + field_tags, index)\n else:\n assert self._chunks is not None\n assert self._chunked_message is not None\n field = self._chunked_message.chunked_fields.add(field_tag=util.get_field_tag(self._proto, field_tags))\n new_chunk_index = len(self._chunks)\n field.message.chunk_index = new_chunk_index\n self._add_chunk_order.append(id(chunk))\n if index is None:\n self._chunks.append(chunk)\n else:\n self._chunks.insert(index, chunk)\n self._fix_chunk_order = True", "docstring": "Adds a new chunk and updates the ChunkedMessage proto.\n\nArgs:\n chunk: Proto message or bytes.\n field_tags: Field information about the placement of the chunked data\n within self._proto.\n index: Optional index at which to insert the chunk. The chunk ordering is\n important for merging.", "source": "github_repos"} +{"code": "def square(x):\n if any_symbolic_tensors((x,)):\n return Square().symbolic_call(x)\n return backend.numpy.square(x)", "docstring": "Return the element-wise square of the input.\n\nArgs:\n x: Input tensor.\n\nReturns:\n Output tensor, the square of `x`.", "source": "github_repos"} +{"code": "def report_delete(config, auth, account, report_id=None, name=None):\n report = report_get(config, auth, account, report_id, name)\n if report:\n account_id, advertiser_ids = parse_account(config, auth, account)\n is_superuser, profile_id = get_profile_for_api(config, auth, account_id)\n kwargs = {'profileId': profile_id, 'accountId': account_id} if is_superuser else {'profileId': profile_id}\n kwargs['reportId'] = report['id']\n API_DCM(config, auth, internal=is_superuser).reports().delete(**kwargs).execute()\n elif config.verbose:\n print('DCM DELETE: No Report')", "docstring": "Deletes a DCM report based on name or ID.\n\n Bulletproofing:\n https://developers.google.com/doubleclick-advertisers/v3.2/reports/delete\n\nArgs:\n * auth: (string) Either user or service.\n * account: (string) [account:advertiser@profile] token.\n * report_id: (int) ID of DCm report to fetch ( either or name ).\n * name: (string) Name of report to fetch ( either or report_id ).\n\nReturns:\n * None", "source": "github_repos"} +{"code": "def flush(self, force: bool=False) -> bool | Any:\n return self._messages.flush(force=force)", "docstring": "Flushes the underlying log message queue.\n\nArgs:\n * force: If True, force queue to flush\n\nReturns:\n * True, if flushed with no errors\n * False, if not flushed\n * Error value from logger, if flushed with errors", "source": "github_repos"} +{"code": "def _check_instance_type(type_constraint, instance, var_name=None, verbose=False):\n hint_type = \"argument: '%s'\" % var_name if var_name is not None else 'return type'\n try:\n check_constraint(type_constraint, instance)\n except SimpleTypeHintError:\n if verbose:\n verbose_instance = '%s, ' % instance\n else:\n verbose_instance = ''\n raise TypeCheckError('Type-hint for %s violated. Expected an instance of %s, instead found %san instance of %s.' % (hint_type, type_constraint, verbose_instance, type(instance)))\n except CompositeTypeHintError as e:\n raise TypeCheckError('Type-hint for %s violated: %s' % (hint_type, e))", "docstring": "A helper function to report type-hint constraint violations.\n\nArgs:\n type_constraint: An instance of a 'TypeConstraint' or a built-in Python\n type.\n instance: The candidate object which will be checked by to satisfy\n 'type_constraint'.\n var_name: If 'instance' is an argument, then the actual name for the\n parameter in the original function definition.\n\nRaises:\n TypeCheckError: If 'instance' fails to meet the type-constraint of\n 'type_constraint'.", "source": "github_repos"} +{"code": "def build_from_items(self, items: list[_ItemType] | None) -> imports_map.ImportsMap | None:\n if not items:\n return None\n imports_multimap = self._build_multimap(items)\n assert imports_multimap is not None\n return self._finalize(imports_multimap)", "docstring": "Create a file mapping from a list of (short path, path) tuples.\n\n Builds a dict of short_path to full name\n (e.g. \"path/to/file.py\" =>\n \"$GENDIR/rulename~~pytype-gen/path_to_file.py~~pytype\"\n\nArgs:\n items: A list of (short_path, full_path) tuples.\n\nReturns:\n Dict of .py short_path to list of .pytd path or None if no items", "source": "github_repos"} +{"code": "def convertDateStrToDateTimeStr(date, time='00:00:00'):\n if not date == None:\n date = '%sT%sZ' % (date, time)\n return date", "docstring": "Convert Date string (YYYY-MM-DD) to a datetime string by adding the desired time (YYYY-MM-DDTHH:mm:SSZ)\n\nArgs:\n date: the date as a string to be converted\n time: the time as a string to be added to the date\n\nReturns:\n A string representation of a datetime in the following\n format YYYY-MM-DDTHH:mm:SSZ", "source": "github_repos"} +{"code": "def verify_multiple_breaks(self, ds_fn, num_outputs, num_breaks=10, sparse_tensors=False, verify_exhausted=True, assert_items_equal=False):\n self.verify_run_with_breaks(ds_fn, self.gen_break_points(num_outputs, num_breaks), num_outputs, sparse_tensors=sparse_tensors, verify_exhausted=verify_exhausted, assert_items_equal=assert_items_equal)", "docstring": "Attempts to save/restore at multiple break points.\n\nArgs:\n ds_fn: 0-argument function that returns a Dataset.\n num_outputs: Total number of outputs expected from this Dataset.\n num_breaks: The number of break points. These are uniformly spread in [0,\n num_outputs] both inclusive.\n sparse_tensors: Whether dataset is built from SparseTensor(s).\n verify_exhausted: Whether to verify that the iterator has been exhausted\n after producing `num_outputs` elements.\n assert_items_equal: Tests the output has the expected elements regardless\n of order.\n\nRaises:\n AssertionError if any test fails.", "source": "github_repos"} +{"code": "def _strip_debug_nodes(meta_graph_def: meta_graph_pb2.MetaGraphDef) -> None:\n\n def erase_regular_node_attributes(node: node_def_pb2.NodeDef) -> None:\n \"\"\"Erases regular node attributes.\"\"\"\n attributes_to_remove = [attribute for attribute in node.attr.keys() if not attribute.startswith('_')]\n for attribute in attributes_to_remove:\n node.attr.pop(attribute)\n\n def prune_all_non_t_attributes(node: node_def_pb2.NodeDef) -> None:\n \"\"\"Prunes all attributes that are not `T`.\"\"\"\n if 'T' in node.attr:\n t_value = node.attr['T']\n node.ClearField('attr')\n node.attr['T'].CopyFrom(t_value)\n else:\n node.ClearField('attr')\n\n def is_control_input(name: str) -> str:\n \"\"\"Returns whether or not the input is a control input.\"\"\"\n return name and name[0] == '^'\n\n def as_control_dep(name: str) -> str:\n \"\"\"Returns the input as a control dependency.\"\"\"\n return '^' + name.split(':')[0]\n\n def maybe_do_strip(node: node_def_pb2.NodeDef) -> None:\n \"\"\"Strips the graph from Assert and CheckNumerics ops.\n\n For Assert ops, this function also rewrites all of the inputs to the nodes\n that were transformed by making them into control dependencies. It also\n removes all of the regular node attributes, that is all node attributes\n that do not start with `_`.\n\n For CheckNumerics ops, this function turns the op into an Identity op,\n which will be pruned later (according to the original implementation in\n grappler's `debug_stripper.cc`. Then, since Identity ops only take one\n input, it leaves the first input as is while transforming the other ones\n into control dependencies.\n\n Args:\n node: The node to potentally strip.\n \"\"\"\n if node.op == 'Assert' or node.op == 'PrintV2':\n node.op = 'NoOp'\n erase_regular_node_attributes(node)\n new_inputs = []\n for inp in node.input:\n if not is_control_input(inp):\n new_inputs.append(as_control_dep(inp))\n else:\n new_inputs.append(inp)\n node.ClearField('input')\n node.input.extend(new_inputs)\n elif node.op == 'CheckNumerics' or node.op == 'Print':\n node.op = 'Identity'\n prune_all_non_t_attributes(node)\n for i in range(1, len(node.input)):\n if not is_control_input(node.input[i]):\n node.input[i] = as_control_dep(node.input[i])\n for node in meta_graph_def.graph_def.node:\n maybe_do_strip(node)\n for func in meta_graph_def.graph_def.library.function:\n for node in func.node_def:\n maybe_do_strip(node)", "docstring": "An experimental function to remove debug nodes from the final graph.\n\n This function removes all Assert and CheckNumerics nodes from the meta_graph.\n It strips the operators in both the nodes and in all of the function defs,\n with the Assert ops being replaced by `NoOp`s and the CheckNumerics ops being\n transformed into `Identity` ops. In addition to this, it creates control\n inputs for the nodes that are not relevant for the op. For more information\n about control inputs please see go/how-tensors-flow#control-dependencies.\n\nArgs:\n meta_graph_def: The meta_graph that will be exported.", "source": "github_repos"} +{"code": "def partition_or_replicate_on_host(tensor, dims):\n if dims is None:\n return itertools.repeat(tensor)\n dims = np.array(dims)\n output = [tensor]\n shape_list = np.array(tensor.shape.as_list())\n quotients, remainders = np.divmod(shape_list, dims)\n for axis, (quotient, remainder, dim, original_size) in enumerate(zip(quotients, remainders, dims, shape_list)):\n if dim <= 1:\n continue\n if remainder > 0:\n ceil_ratio = quotient + 1\n num_full_slots, left_over = np.divmod(original_size, ceil_ratio)\n num_or_size_splits = [ceil_ratio] * num_full_slots + [left_over]\n if len(num_or_size_splits) < dim:\n num_or_size_splits += [0] * (dim - len(num_or_size_splits))\n new_output = []\n for x in output:\n new_output.append(array_ops.split(x, num_or_size_splits=num_or_size_splits, axis=axis))\n output = new_output\n else:\n output = [array_ops.split(x, int(dim), axis=axis) for x in output]\n output = nest.flatten(output)\n return output", "docstring": "Partitions or replicates the input tensor.\n\n The ops inside this function are placed on the host side.\n\nArgs:\n tensor: The input tensor which will be partitioned or replicated.\n dims: A list of integer describes how to partition the input tensor.\n\nReturns:\n An iterator of `Tensor`s or a list of partitioned tensors.", "source": "github_repos"} +{"code": "def get_parent_dir_for_name(module_name):\n name_split = module_name.split('.')\n if not name_split:\n return None\n try:\n spec = importlib.util.find_spec(name_split[0])\n except ValueError:\n return None\n if not spec or not spec.origin:\n return None\n base_path = os.path.dirname(spec.origin)\n return os.path.join(base_path, *name_split[1:-1])", "docstring": "Get parent directory for module with the given name.\n\nArgs:\n module_name: Module name, e.g. tf_keras.api._v2.keras.\n\nReturns:\n Path to the parent directory if module is found and None otherwise.\n Given example above, it should return:\n /root_path/tf_keras/api/_v2.", "source": "github_repos"} +{"code": "def _get_accumulator(tensor):\n assert isinstance(tensor.graph, func_graph_module.FuncGraph)\n\n def get_func_graph_output(t):\n \"\"\"Returns t or Identity(t) whichever exists in graph outputs else None.\"\"\"\n for output in tensor.graph.outputs:\n if output is t:\n return t\n identity_op = t.consumers()[0]\n if identity_op.type == 'Identity' and any((identity_op.outputs[0] is t for t in tensor.graph.outputs)):\n return identity_op.outputs[0]\n return None\n for consumer in tensor.consumers():\n if consumer.type != 'TensorListPushBack':\n continue\n accum_input_idx = -1\n for accum_input_idx, inp in enumerate(tensor.graph.inputs):\n if inp is consumer.inputs[0]:\n break\n else:\n continue\n output = get_func_graph_output(consumer.outputs[0])\n if output is None:\n continue\n for accum_output_idx, out in enumerate(tensor.graph.outputs):\n if out is output:\n if accum_input_idx == accum_output_idx:\n return output\n break\n return None", "docstring": "Returns TensorList if any containing accumulated values of tensor.\n\n We try to find a pattern of the form:\n\n input_tl tensor\n \\ /\n (TensorListPushBack)\n |\n output_tl\n\n which satisfies the following conditions:\n\n 1. input_tl must be in tensor.graph.inputs.\n 2. output_tl or Identity(output_tl) must be in tensor.graph.outputs.\n 3. tensor.graph.input_index(input_tl) == tensor.graph.output_index(output_t).\n\n output_tl or Identity(output_tl) (whichever is in tensor.graph.outputs) is\n returned if such a pattern is found else None is returned.\n\nArgs:\n tensor: The Tensor to be accumulated.\n\nReturns:\n A variant tensor in the same graph as `tensor` or None if no accumulator is\n found.", "source": "github_repos"} +{"code": "def post_process_panoptic_sample(out_logits: np.ndarray, masks: np.ndarray, boxes: np.ndarray, processed_size: Tuple[int, int], target_size: Tuple[int, int], is_thing_map: Dict, threshold=0.85) -> Dict:\n scores, labels = score_labels_from_class_probabilities(out_logits)\n keep = (labels != out_logits.shape[-1] - 1) & (scores > threshold)\n cur_scores = scores[keep]\n cur_classes = labels[keep]\n cur_boxes = center_to_corners_format(boxes[keep])\n if len(cur_boxes) != len(cur_classes):\n raise ValueError('Not as many boxes as there are classes')\n cur_masks = masks[keep]\n cur_masks = resize(cur_masks[:, None], processed_size, resample=PILImageResampling.BILINEAR)\n cur_masks = safe_squeeze(cur_masks, 1)\n b, h, w = cur_masks.shape\n cur_masks = cur_masks.reshape(b, -1)\n stuff_equiv_classes = defaultdict(list)\n for k, label in enumerate(cur_classes):\n if not is_thing_map[label]:\n stuff_equiv_classes[label].append(k)\n seg_img = get_segmentation_image(cur_masks, processed_size, target_size, stuff_equiv_classes, deduplicate=True)\n area = get_mask_area(cur_masks, processed_size, n_classes=len(cur_scores))\n if cur_classes.size() > 0:\n filtered_small = np.array([a <= 4 for a in area], dtype=bool)\n while filtered_small.any():\n cur_masks = cur_masks[~filtered_small]\n cur_scores = cur_scores[~filtered_small]\n cur_classes = cur_classes[~filtered_small]\n seg_img = get_segmentation_image(cur_masks, (h, w), target_size, stuff_equiv_classes, deduplicate=True)\n area = get_mask_area(seg_img, target_size, n_classes=len(cur_scores))\n filtered_small = np.array([a <= 4 for a in area], dtype=bool)\n else:\n cur_classes = np.ones((1, 1), dtype=np.int64)\n segments_info = [{'id': i, 'isthing': is_thing_map[cat], 'category_id': int(cat), 'area': a} for i, (cat, a) in enumerate(zip(cur_classes, area))]\n del cur_classes\n with io.BytesIO() as out:\n PIL.Image.fromarray(seg_img).save(out, format='PNG')\n predictions = {'png_string': out.getvalue(), 'segments_info': segments_info}\n return predictions", "docstring": "Converts the output of [`DetrForSegmentation`] into panoptic segmentation predictions for a single sample.\n\nArgs:\n out_logits (`torch.Tensor`):\n The logits for this sample.\n masks (`torch.Tensor`):\n The predicted segmentation masks for this sample.\n boxes (`torch.Tensor`):\n The prediced bounding boxes for this sample. The boxes are in the normalized format `(center_x, center_y,\n width, height)` and values between `[0, 1]`, relative to the size the image (disregarding padding).\n processed_size (`Tuple[int, int]`):\n The processed size of the image `(height, width)`, as returned by the preprocessing step i.e. the size\n after data augmentation but before batching.\n target_size (`Tuple[int, int]`):\n The target size of the image, `(height, width)` corresponding to the requested final size of the\n prediction.\n is_thing_map (`Dict`):\n A dictionary mapping class indices to a boolean value indicating whether the class is a thing or not.\n threshold (`float`, *optional*, defaults to 0.85):\n The threshold used to binarize the segmentation masks.", "source": "github_repos"} +{"code": "def _gen_save_and_restore_functions(checkpoint_factory_map: object_identity.ObjectIdentityDictionary) -> object_identity.ObjectIdentityDictionary:\n saveable_fn_map = object_identity.ObjectIdentityDictionary()\n for obj, factory_data_list in checkpoint_factory_map.items():\n if resource_variable_ops.is_resource_variable(obj) or not factory_data_list:\n continue\n if factory_data_list[0].name == trackable_utils.SERIALIZE_TO_TENSORS_NAME:\n assert len(factory_data_list) == 1\n saveable_fn_map[obj] = {trackable_utils.SERIALIZE_TO_TENSORS_NAME: tracing_utils.trace_save_and_restore(obj)}\n else:\n saveable_fn_map[obj] = trace_saveable_util.trace_save_restore_function_map(obj, factory_data_list)\n return saveable_fn_map", "docstring": "Generates global and individual save/restore concrete functions.\n\n The global functions records the ops to save and restore the entire object to\n a file prefix, while the individual functions save and restore value tensors\n for resources.\n\n This function is intended to run on the output of\n `save_util_v1.get_checkpoint_factories_and_keys(object_names)`,\n which returns the generated a map of `_CheckpointFactoryData`.\n\nArgs:\n checkpoint_factory_map: A dictionary mapping trackable objects to\n a list of `_CheckpointFactoryData`.\n\nReturns:\n Tuple of (\n saveable_fn_map: Maps obj -> factory name -> (concrete save, restore)\n )", "source": "github_repos"} +{"code": "def _ParseTensorName(tensor_name):\n components = tensor_name.split(':')\n if len(components) == 2:\n try:\n output_index = int(components[1])\n except ValueError:\n raise ValueError(f'Cannot convert {tensor_name!r} to a tensor name. Second component of the name following the `:` should be an int. Got {components[1]}.')\n return (components[0], output_index)\n elif len(components) == 1:\n return (components[0], 0)\n else:\n raise ValueError(f\"Cannot convert '{tensor_name}' to a tensor name. Tensor names should not contain more than 1 `:`. Obtained {len(components) - 1}\")", "docstring": "Parses a tensor name into an operation name and output index.\n\n This function will canonicalize tensor names as follows:\n\n * \"foo:0\" -> (\"foo\", 0)\n * \"foo:7\" -> (\"foo\", 7)\n * \"foo\" -> (\"foo\", 0)\n * \"foo:bar:baz\" -> ValueError\n\nArgs:\n tensor_name: The name of a tensor.\n\nReturns:\n A tuple containing the operation name, and the output index.\n\nRaises:\n ValueError: If `tensor_name' cannot be interpreted as the name of a tensor.", "source": "github_repos"} +{"code": "def assertNumpyObjectTensorsRecursivelyEqual(self, a, b, msg):\n if isinstance(a, np.ndarray) and a.dtype == object:\n self.assertEqual(a.dtype, b.dtype, msg)\n self.assertEqual(a.shape, b.shape, msg)\n self.assertLen(a, len(b), msg)\n for a_val, b_val in zip(a, b):\n self.assertNumpyObjectTensorsRecursivelyEqual(a_val, b_val, msg)\n else:\n self.assertAllEqual(a, b, msg)", "docstring": "Check that two numpy arrays are equal.\n\n For arrays with dtype=object, check values recursively to see if a and b\n are equal. (c.f. `np.array_equal`, which checks dtype=object values using\n object identity.)\n\nArgs:\n a: A numpy array.\n b: A numpy array.\n msg: Message to display if a != b.", "source": "github_repos"} +{"code": "def histogram(namespace: Union[Type, str], name: str, bucket_type: 'BucketType', logger: Optional['MetricLogger']=None) -> 'Metrics.DelegatingHistogram':\n namespace = UserMetrics.get_namespace(namespace)\n return Metrics.DelegatingHistogram(MetricName(namespace, name), bucket_type, logger)", "docstring": "Obtains or creates a Histogram metric.\n\nArgs:\n namespace: A class or string that gives the namespace to a metric\n name: A string that gives a unique name to a metric\n bucket_type: A type of bucket used in a histogram. A subclass of\n apache_beam.utils.histogram.BucketType\n logger: MetricLogger for logging locally aggregated metric\n\nReturns:\n A Histogram object.", "source": "github_repos"} +{"code": "def map_subgraph(init_tensor, sources, disallowed_placeholders, visited_ops, op_outputs, add_sources):\n ops_to_visit = [_as_operation(init_tensor)]\n extra_sources = object_identity.ObjectIdentitySet()\n while ops_to_visit:\n op = ops_to_visit.pop()\n if op in visited_ops:\n continue\n visited_ops.add(op)\n should_raise = False\n if disallowed_placeholders is not None and op in disallowed_placeholders:\n should_raise = True\n elif op.type == 'Placeholder':\n if disallowed_placeholders is None and (not add_sources):\n should_raise = True\n extra_sources.update(op.outputs)\n if should_raise:\n raise UnliftableError('Unable to lift tensor %s because it depends transitively on placeholder %s via at least one path, e.g.: %s' % (repr(init_tensor), repr(op), show_path(op, init_tensor, sources)))\n for inp in graph_inputs(op):\n op_outputs[inp].add(op)\n if inp not in visited_ops and inp not in (sources or extra_sources):\n ops_to_visit.append(inp)\n return extra_sources", "docstring": "Walk a Graph and capture the subgraph between init_tensor and sources.\n\n Note: This function mutates visited_ops and op_outputs.\n\nArgs:\n init_tensor: A Tensor or Operation where the subgraph terminates.\n sources: A set of Tensors where subgraph extraction should stop.\n disallowed_placeholders: An optional set of ops which may not appear in the\n lifted graph. Defaults to all placeholders.\n visited_ops: A set of operations which were visited in a prior pass.\n op_outputs: A defaultdict containing the outputs of an op which are to be\n copied into the new subgraph.\n add_sources: A boolean indicating whether placeholders which are not in\n sources should be allowed.\n\nReturns:\n The set of placeholders upon which init_tensor depends and are not in\n sources.\n\nRaises:\n UnliftableError: if init_tensor depends on a placeholder which is not in\n sources and add_sources is False.", "source": "github_repos"} +{"code": "def get_const_dim_count(node_def):\n const_value = values_from_const(node_def)\n return const_value.ndim", "docstring": "Get the number of dimensions for a Const node.\n\nArgs:\n node_def: Const NodeDef.\n\nReturns:\n Number of dimensions for the Const node.", "source": "github_repos"} +{"code": "def _prune_nodes_from_input_and_recipient_maps(self, nodes_to_prune):\n for node in nodes_to_prune:\n del self._node_inputs[node]\n del self._node_ctrl_inputs[node]\n del self._node_recipients[node]\n del self._node_ctrl_recipients[node]", "docstring": "Prune nodes out of input and recipient maps.\n\nArgs:\n nodes_to_prune: (`list` of `str`) Names of the nodes to be pruned.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.Tensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.Tensor]=None, position_ids: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **kwargs: Any) -> Union[Tuple, SequenceClassifierOutputWithPast]:\n if 'pixel_values' in kwargs:\n warnings.warn('The `pixel_values` argument is deprecated and will be removed in v4.47, use `input_ids` instead.', FutureWarning)\n if input_ids is not None:\n raise ValueError('You cannot pass both `pixel_values` and `input_ids`. Please make sure to only pass `input_ids`.')\n input_ids = kwargs.pop('pixel_values')\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n hidden_states = transformer_outputs[0]\n pooled_hidden_states = hidden_states.mean(dim=1)\n logits = self.score(pooled_hidden_states)\n loss = None\n if labels is not None:\n if self.config.problem_type is None:\n if self.num_labels == 1:\n self.config.problem_type = 'regression'\n elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = 'single_label_classification'\n else:\n self.config.problem_type = 'multi_label_classification'\n if self.config.problem_type == 'regression':\n loss_fct = MSELoss()\n if self.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == 'single_label_classification':\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == 'multi_label_classification':\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n if not return_dict:\n output = (logits,) + transformer_outputs[1:]\n return (loss,) + output if loss is not None else output\n return SequenceClassifierOutputWithPast(loss=loss, logits=logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)", "docstring": "input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):\n `input_ids_length` = `sequence_length` if `past_key_values` is `None` else\n `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input\n sequence tokens in the vocabulary.\n\n If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as\n `input_ids`.\n\n Indices can be obtained using [`AutoImageProcessor`]. See [`ImageGPTImageProcessor.__call__`] for details.\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\nExample:\n ```python\n >>> from transformers import AutoImageProcessor, ImageGPTForImageClassification\n >>> from PIL import Image\n >>> import requests\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> image_processor = AutoImageProcessor.from_pretrained(\"openai/imagegpt-small\")\n >>> model = ImageGPTForImageClassification.from_pretrained(\"openai/imagegpt-small\")\n\n >>> inputs = image_processor(images=image, return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n >>> logits = outputs.logits\n ```", "source": "github_repos"} +{"code": "def _caching_device(rnn_cell):\n if context.executing_eagerly():\n return None\n if not getattr(rnn_cell, '_enable_caching_device', False):\n return None\n if control_flow_util.IsInWhileLoop(ops.get_default_graph()):\n logging.warning('Variable read device caching has been disabled because the RNN is in tf.while_loop loop context, which will cause reading stalled value in forward path. This could slow down the training due to duplicated variable reads. Please consider updating your code to remove tf.while_loop if possible.')\n return None\n if rnn_cell._dtype_policy.compute_dtype != rnn_cell._dtype_policy.variable_dtype:\n logging.warning(\"Variable read device caching has been disabled since it doesn't work with the mixed precision API. This is likely to cause a slowdown for RNN training due to duplicated read of variable for each timestep, which will be significant in a multi remote worker setting. Please consider disabling mixed precision API if the performance has been affected.\")\n return None\n return lambda op: op.device", "docstring": "Returns the caching device for the RNN variable.\n\n This is useful for distributed training, when variable is not located as same\n device as the training worker. By enabling the device cache, this allows\n worker to read the variable once and cache locally, rather than read it every\n time step from remote when it is needed.\n\n Note that this is assuming the variable that cell needs for each time step is\n having the same value in the forward path, and only gets updated in the\n backprop. It is true for all the default cells (SimpleRNN, GRU, LSTM). If the\n cell body relies on any variable that gets updated every time step, then\n caching device will cause it to read the stall value.\n\nArgs:\n rnn_cell: the rnn cell instance.", "source": "github_repos"} +{"code": "def on_run_end(self, request):\n self._is_run_start = False\n if request.performed_action == framework.OnRunStartAction.DEBUG_RUN:\n partition_graphs = None\n if request.run_metadata and request.run_metadata.partition_graphs:\n partition_graphs = request.run_metadata.partition_graphs\n elif request.client_graph_def:\n partition_graphs = [request.client_graph_def]\n if request.tf_error and (not os.path.isdir(self._dump_root)):\n raise request.tf_error\n debug_dump = debug_data.DebugDumpDir(self._dump_root, partition_graphs=partition_graphs)\n debug_dump.set_python_graph(self._sess.graph)\n passed_filter = None\n passed_filter_exclude_node_names = None\n if self._active_tensor_filter:\n if not debug_dump.find(self._tensor_filters[self._active_tensor_filter], first_n=1, exclude_node_names=self._active_filter_exclude_node_names):\n self._remove_dump_root()\n return framework.OnRunEndResponse()\n else:\n passed_filter = self._active_tensor_filter\n passed_filter_exclude_node_names = self._active_filter_exclude_node_names\n self._active_tensor_filter = None\n self._active_filter_exclude_node_names = None\n self._prep_debug_cli_for_run_end(debug_dump, request.tf_error, passed_filter, passed_filter_exclude_node_names)\n self._run_start_response = self._launch_cli()\n self._remove_dump_root()\n elif request.performed_action == framework.OnRunStartAction.PROFILE_RUN:\n self._prep_profile_cli_for_run_end(self._sess.graph, request.run_metadata)\n self._run_start_response = self._launch_cli()\n else:\n self._run_start_response = None\n return framework.OnRunEndResponse()", "docstring": "Overrides on-run-end callback.\n\n Actions taken:\n 1) Load the debug dump.\n 2) Bring up the Analyzer CLI.\n\nArgs:\n request: An instance of OnSessionInitRequest.\n\nReturns:\n An instance of OnSessionInitResponse.", "source": "github_repos"} +{"code": "def _add_collection_def(meta_graph_def, key, export_scope=None):\n meta_graph.add_collection_def(meta_graph_def, key, export_scope=export_scope)", "docstring": "Adds a collection to MetaGraphDef protocol buffer.\n\nArgs:\n meta_graph_def: MetaGraphDef protocol buffer.\n key: One of the GraphKeys or user-defined string.\n export_scope: Optional `string`. Name scope to remove.", "source": "github_repos"} +{"code": "def _evalDecodeJpeg(self, image_name, parallelism, num_iters, crop_during_decode=None, crop_window=None, tile=None):\n ops.reset_default_graph()\n image_file_path = resource_loader.get_path_to_datafile(os.path.join('core', 'lib', 'jpeg', 'testdata', image_name))\n if not os.path.exists(image_file_path):\n image_file_path = resource_loader.get_path_to_datafile(os.path.join('..', '..', 'core', 'lib', 'jpeg', 'testdata', image_name))\n if tile is None:\n image_content = variable_scope.get_variable('image_%s' % image_name, initializer=io_ops.read_file(image_file_path))\n else:\n single_image = image_ops.decode_jpeg(io_ops.read_file(image_file_path), channels=3, name='single_image')\n tiled_image = array_ops.tile(single_image, tile)\n image_content = variable_scope.get_variable('tiled_image_%s' % image_name, initializer=image_ops.encode_jpeg(tiled_image))\n with session.Session() as sess:\n self.evaluate(variables.global_variables_initializer())\n images = []\n for _ in range(parallelism):\n if crop_window is None:\n image = image_ops.decode_jpeg(image_content, channels=3)\n elif crop_during_decode:\n image = image_ops.decode_and_crop_jpeg(image_content, crop_window, channels=3)\n else:\n image = image_ops.decode_jpeg(image_content, channels=3)\n image = image_ops.crop_to_bounding_box(image, offset_height=crop_window[0], offset_width=crop_window[1], target_height=crop_window[2], target_width=crop_window[3])\n images.append(image)\n r = control_flow_ops.group(*images)\n for _ in range(3):\n self.evaluate(r)\n start_time = time.time()\n for _ in range(num_iters):\n self.evaluate(r)\n end_time = time.time()\n return end_time - start_time", "docstring": "Evaluate DecodeJpegOp for the given image.\n\n TODO(tanmingxing): add decoding+cropping as well.\n\nArgs:\n image_name: a string of image file name (without suffix).\n parallelism: the number of concurrent decode_jpeg ops to be run.\n num_iters: number of iterations for evaluation.\n crop_during_decode: If true, use fused DecodeAndCropJpeg instead of\n separate decode and crop ops. It is ignored if crop_window is None.\n crop_window: if not None, crop the decoded image. Depending on\n crop_during_decode, cropping could happen during or after decoding.\n tile: if not None, tile the image to composite a larger fake image.\n\nReturns:\n The duration of the run in seconds.", "source": "github_repos"} +{"code": "def __init__(self, config):\n super().__init__()\n in_channels = config.bottleneck_features\n self.transformer_encoder = nn.ModuleList([ZoeDepthTransformerEncoderLayer(config) for _ in range(config.num_patch_transformer_layers)])\n self.embedding_convPxP = nn.Conv2d(in_channels, config.patch_transformer_hidden_size, kernel_size=1, stride=1, padding=0)", "docstring": "ViT-like transformer block\n\nArgs:\n config (`ZoeDepthConfig`):\n Model configuration class defining the model architecture.", "source": "github_repos"} +{"code": "def id_in_cluster(cluster_spec, task_type, task_id):\n _validate_cluster_spec(cluster_spec, task_type, task_id)\n cluster_spec = normalize_cluster_spec(cluster_spec).as_dict()\n if task_type == 'chief':\n return 0\n if task_type == 'worker':\n return task_id + len(cluster_spec.get('chief', []))\n if task_type == 'evaluator':\n return task_id\n raise ValueError('There is no id for task_type %r' % task_type)", "docstring": "Returns a unique id for the task in the `task_type`'s cluster.\n\n It returns an id ranging from [0, `worker_count(task_type, task_id)`).\n\n Note: this function assumes that \"evaluate\" job is in its own cluster or its\n own partition of a cluster.\n\nArgs:\n cluster_spec: a dict, `ClusterDef` or `ClusterSpec` object to be validated.\n task_type: string indicating the type of the task.\n task_id: the id of the `task_type` in this cluster.\n\nReturns:\n an int indicating the unique id.\n\n Throws:\n ValueError: if `task_type` is not \"chief\", \"worker\" or \"evaluator\".", "source": "github_repos"} +{"code": "def index_update(x, idx, y):\n return _index_update_helper(tf_np.ndarray._with_index_update, x, idx, y)", "docstring": "Pure equivalent of `x[idx] = y`.\n\n Returns the value of x that would result from the NumPy-style indexed\n assignment `x[idx] = y`. Because it's a pure function, `x` itself won't be\n changed.\n\nArgs:\n x: an array with the values to be updated.\n idx: a Numpy-style index, consisting of `None`, integers, slice objects,\n ellipses, ndarrays with integer dtypes, or a tuple of the above.\n y: the array of updates. `y` must be broadcastable to the shape of the array\n that would be returned by `x[idx]`.\n\nReturns:\n The updated version of `x`.", "source": "github_repos"} +{"code": "def rot_vec_mul(r: torch.Tensor, t: torch.Tensor) -> torch.Tensor:\n x, y, z = torch.unbind(t, dim=-1)\n return torch.stack([r[..., 0, 0] * x + r[..., 0, 1] * y + r[..., 0, 2] * z, r[..., 1, 0] * x + r[..., 1, 1] * y + r[..., 1, 2] * z, r[..., 2, 0] * x + r[..., 2, 1] * y + r[..., 2, 2] * z], dim=-1)", "docstring": "Applies a rotation to a vector. Written out by hand to avoid transfer to avoid AMP downcasting.\n\nArgs:\n r: [*, 3, 3] rotation matrices\n t: [*, 3] coordinate tensors\n\nReturns:\n [*, 3] rotated coordinates", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, position_embeddings: Optional[torch.Tensor]=None, reference_points=None, spatial_shapes=None, spatial_shapes_list=None, level_start_index=None, output_attentions: bool=False):\n residual = hidden_states\n hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask, encoder_hidden_states=hidden_states, encoder_attention_mask=attention_mask, position_embeddings=position_embeddings, reference_points=reference_points, spatial_shapes=spatial_shapes, spatial_shapes_list=spatial_shapes_list, level_start_index=level_start_index, output_attentions=output_attentions)\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n hidden_states = residual + hidden_states\n hidden_states = self.self_attn_layer_norm(hidden_states)\n residual = hidden_states\n hidden_states = self.activation_fn(self.fc1(hidden_states))\n hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)\n hidden_states = self.fc2(hidden_states)\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n hidden_states = residual + hidden_states\n hidden_states = self.final_layer_norm(hidden_states)\n if self.training:\n if torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any():\n clamp_value = torch.finfo(hidden_states.dtype).max - 1000\n hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)\n return (hidden_states, attn_weights)", "docstring": "Args:\n hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Input to the layer.\n attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):\n Attention mask.\n position_embeddings (`torch.FloatTensor`, *optional*):\n Position embeddings, to be added to `hidden_states`.\n reference_points (`torch.FloatTensor`, *optional*):\n Reference points.\n spatial_shapes (`torch.LongTensor`, *optional*):\n Spatial shapes of the backbone feature maps.\n spatial_shapes_list (`List[Tuple[int, int]]`, *optional*):\n Spatial shapes of the backbone feature maps (but as list for export compatibility).\n level_start_index (`torch.LongTensor`, *optional*):\n Level start index.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.", "source": "github_repos"} +{"code": "def metrics(expected_box_encodings, expected_scores, actual_box_encodings, actual_scores):\n squashed_expected_scores = tf.math.divide(1.0, 1.0 + tf.math.exp(-expected_scores))\n squashed_actual_scores = tf.math.divide(1.0, 1.0 + tf.math.exp(-actual_scores))\n kld_metric = kl_divergence.symmetric_kl_divergence(expected_scores, actual_scores)\n high_scoring_indices = tf.math.logical_or(tf.math.greater(squashed_expected_scores, 0.1), tf.math.greater(squashed_actual_scores, 0.1))\n high_scoring_actual_boxes = tf.where(condition=tf.broadcast_to(input=high_scoring_indices, shape=tf.shape(actual_box_encodings)), x=actual_box_encodings, y=expected_box_encodings)\n box_diff = high_scoring_actual_boxes - expected_box_encodings\n box_squared_diff = tf.math.pow(box_diff, 2)\n box_mse = tf.divide(tf.math.reduce_sum(box_squared_diff), tf.math.maximum(tf.math.count_nonzero(high_scoring_indices, dtype=tf.float32), 1.0))\n ok = tf.logical_and(kld_metric < 0.1, box_mse < 0.01)\n return [kld_metric, box_mse, ok]", "docstring": "Calculate metrics from expected and actual blazeface outputs.\n\nArgs:\n expected_box_encodings: box encodings from model\n expected_scores: classifications from model\n actual_box_encodings: golden box encodings\n actual_scores: golden classifications\n\nReturns:\n two-item list with classification error and localization error", "source": "github_repos"} +{"code": "def _decorator(func):\n func.__doc__ = '\\n Assert the condition `x {sym} y` holds element-wise.\\n\\n This Op checks that `x[i] {sym} y[i]` holds for every pair of (possibly\\n broadcast) elements of `x` and `y`. If both `x` and `y` are empty, this is\\n trivially satisfied.\\n\\n If `x` {sym} `y` does not hold, `message`, as well as the first `summarize`\\n entries of `x` and `y` are printed, and `InvalidArgumentError` is raised.\\n\\n When using inside `tf.function`, this API takes effects during execution.\\n It\\'s recommended to use this API with `tf.control_dependencies` to\\n ensure the correct execution order.\\n\\n In the following example, without `tf.control_dependencies`, errors may\\n not be raised at all.\\n Check `tf.control_dependencies` for more details.\\n\\n >>> def check_size(x):\\n ... with tf.control_dependencies([\\n ... tf.debugging.{opname}(tf.size(x), {test_var},\\n ... message=\\'Bad tensor size\\')]):\\n ... return x\\n\\n >>> check_size(tf.ones([2, 3], tf.float32))\\n Traceback (most recent call last):\\n ...\\n InvalidArgumentError: ...\\n\\n Args:\\n x: Numeric `Tensor`.\\n y: Numeric `Tensor`, same dtype as and broadcastable to `x`.\\n message: A string to prefix to the default message. (optional)\\n summarize: Print this many entries of each tensor. (optional)\\n name: A name for this operation (optional). Defaults to \"{opname}\".\\n\\n Returns:\\n Op that raises `InvalidArgumentError` if `x {sym} y` is False. This can\\n be used with `tf.control_dependencies` inside of `tf.function`s to\\n block followup computation until the check has executed.\\n @compatibility(eager)\\n returns None\\n @end_compatibility\\n\\n Raises:\\n InvalidArgumentError: if the check can be performed immediately and\\n `x == y` is False. The check can be performed immediately during eager\\n execution or if `x` and `y` are statically known.\\n '.format(sym=sym, opname=opname, test_var=test_var)\n return func", "docstring": "Decorator that adds docstring to the function for symbol `sym`.\n\nArgs:\n func: Function for a TensorFlow op\n\nReturns:\n A version of `func` with documentation attached.", "source": "github_repos"} +{"code": "def generate(self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, attention_mask: Optional[torch.LongTensor]=None, interpolate_pos_encoding: bool=False, **generate_kwargs) -> torch.LongTensor:\n vision_outputs = self.vision_model(pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)\n image_embeds = vision_outputs[0]\n image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)\n if isinstance(input_ids, list):\n input_ids = torch.LongTensor(input_ids)\n question_outputs = self.text_encoder(input_ids=input_ids, attention_mask=attention_mask, encoder_hidden_states=image_embeds, encoder_attention_mask=image_attention_mask, return_dict=False)\n question_embeds = question_outputs[0]\n question_attention_mask = torch.ones(question_embeds.size()[:-1], dtype=torch.long, device=question_embeds.device)\n bos_ids = torch.full((question_embeds.size(0), 1), fill_value=self.decoder_start_token_id, device=question_embeds.device)\n outputs = self.text_decoder.generate(input_ids=bos_ids, eos_token_id=self.config.text_config.sep_token_id, pad_token_id=self.config.text_config.pad_token_id, encoder_hidden_states=question_embeds, encoder_attention_mask=question_attention_mask, **generate_kwargs)\n return outputs", "docstring": "Overrides *generate* function to be able to use the model as a conditional generator\n\n Parameters:\n input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*):\n The sequence used as a prompt for the generation.\n pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:\n Input image to be processed\n attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for\n tokens that are NOT MASKED, `0` for MASKED tokens.\n **generate_kwargs:\n Additional arguments passed to the *generate* function of the decoder\n\nExample:\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, BlipForQuestionAnswering\n\n >>> model = BlipForQuestionAnswering.from_pretrained(\"Salesforce/blip-vqa-base\")\n >>> processor = AutoProcessor.from_pretrained(\"Salesforce/blip-vqa-base\")\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n >>> text = \"How many cats are in the picture?\"\n\n >>> inputs = processor(images=image, text=text, return_tensors=\"pt\")\n\n >>> outputs = model.generate(**inputs)\n >>> print(processor.decode(outputs[0], skip_special_tokens=True))\n 2\n ```", "source": "github_repos"} +{"code": "def direct_transformers_import(path: str, file='__init__.py') -> ModuleType:\n name = 'transformers'\n location = os.path.join(path, file)\n spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path])\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n module = sys.modules[name]\n return module", "docstring": "Imports transformers directly\n\nArgs:\n path (`str`): The path to the source file\n file (`str`, *optional*): The file to join with the path. Defaults to \"__init__.py\".\n\nReturns:\n `ModuleType`: The resulting imported module", "source": "github_repos"} +{"code": "def _maybe_load_initial_epoch_from_ckpt(self, initial_epoch):\n if self._training_state is not None:\n return self._training_state.maybe_load_initial_epoch_from_ckpt(initial_epoch, mode=ModeKeys.TRAIN)\n return initial_epoch", "docstring": "Maybe load initial epoch from ckpt considering possible worker recovery.\n\n Refer to tensorflow/python/keras/distribute/worker_training_state.py\n for more information.\n\nArgs:\n initial_epoch: The original initial_epoch user passes in in `fit()`.\n\nReturns:\n If the training is recovering from previous failure under multi-worker\n training setting, return the epoch the training is supposed to continue\n at. Otherwise, return the `initial_epoch` the user passes in.", "source": "github_repos"} +{"code": "def eval(self, session=None):\n return self._variable.eval(session=session)", "docstring": "In a session, computes and returns the value of this variable.\n\n This is not a graph construction method, it does not add ops to the graph.\n\n This convenience method requires a session where the graph\n containing this variable has been launched. If no session is\n passed, the default session is used. See `tf.compat.v1.Session` for more\n information on launching a graph and on sessions.\n\n ```python\n v = tf.Variable([1, 2])\n init = tf.compat.v1.global_variables_initializer()\n\n with tf.compat.v1.Session() as sess:\n sess.run(init)\n # Usage passing the session explicitly.\n print(v.eval(sess))\n # Usage with the default session. The 'with' block\n # above makes 'sess' the default session.\n print(v.eval())\n ```\n\nArgs:\n session: The session to use to evaluate this variable. If none, the\n default session is used.\n\nReturns:\n A numpy `ndarray` with a copy of the value of this variable.", "source": "github_repos"} +{"code": "def get_resize_output_image_size(input_image: ImageInput, size: Union[int, Tuple[int, int], List[int], Tuple[int]], patch_size: Union[int, Tuple[int, int], List[int], Tuple[int]], input_data_format: Optional[Union[str, ChannelDimension]]=None) -> tuple:\n max_height, max_width = size if isinstance(size, (tuple, list)) else (size, size)\n patch_height, patch_width = patch_size if isinstance(patch_size, (tuple, list)) else (patch_size, patch_size)\n height, width = get_image_size(input_image, input_data_format)\n ratio = max(height / max_height, width / max_width)\n if ratio > 1:\n height = int(math.floor(height / ratio))\n width = int(math.floor(width / ratio))\n num_height_tokens, num_width_tokens = _num_image_tokens((height, width), (patch_height, patch_width))\n return (num_height_tokens * patch_height, num_width_tokens * patch_width)", "docstring": "Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\nArgs:\n input_image (`ImageInput`):\n The image to resize.\n size (`int` or `Tuple[int, int]`):\n Max image size an input image can be. Must be a dictionary with the key \"longest_edge\".\n patch_size (`int` or `Tuple[int, int]`):\n The patch_size as `(height, width)` to use for resizing the image. If patch_size is an integer, `(patch_size, patch_size)`\n will be used\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\nReturns:\n `tuple`: The target (height, width) dimension of the output image after resizing.", "source": "github_repos"} +{"code": "def clean_args(self, args, keys):\n for k in keys:\n if getattr(args, k) is None:\n delattr(args, k)", "docstring": "Clean None values out of the arg namespace.\n\n This lets us check for a config file arg based on whether the None default\n was overwritten.\n\nArgs:\n args: an argparse.Namespace.\n keys: Keys to clean if None", "source": "github_repos"} +{"code": "def create_script(target_test):\n script = f'\\nimport os\\nimport subprocess\\n\\nresult = subprocess.run(\\n [\"python3\", \"-m\", \"pytest\", \"-v\", \"-rfEp\", f\"{target_test}\"],\\n capture_output = True,\\n text=True,\\n)\\nprint(result.stdout)\\n\\nif f\"PASSED {target_test}\" in result.stdout:\\n print(\"test passed\")\\n exit(0)\\nelif len(result.stderr) > 0:\\n if \"ERROR: file or directory not found: \" in result.stderr:\\n print(\"test file or directory not found in this commit\")\\n exit(0)\\n elif \"ERROR: not found: \" in result.stderr:\\n print(\"test not found in this commit\")\\n exit(0)\\n else:\\n print(f\"pytest failed to run: {{result.stderr}}\")\\n exit(-1)\\nelif f\"FAILED {target_test}\" in result.stdout:\\n print(\"test failed\")\\n exit(2)\\n\\nexit(0)\\n'\n with open('target_script.py', 'w') as fp:\n fp.write(script.strip())", "docstring": "Create a python script to be run by `git bisect run` to determine if `target_test` passes or fails.\n If a test is not found in a commit, the script with exit code `0` (i.e. `Success`).\n\nArgs:\n target_test (`str`): The test to check.\n\nReturns:\n `str`: The script to be run by `git bisect run`.", "source": "github_repos"} +{"code": "def __call__(self, *args, **kwargs):\n if not self._verified:\n model = self._get_func()\n concrete_func = model.get_concrete_function(*args, **kwargs)\n converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func], model)\n if self._converter_target_spec is not None:\n converter.target_spec = self._converter_target_spec\n if self._converter_allow_custom_ops is not None:\n converter.allow_custom_ops = self._converter_allow_custom_ops\n try:\n converter.convert()\n except convert.ConverterError as err:\n self._decode_error(err)\n finally:\n self._verified = True\n return self._get_func()(*args, **kwargs)", "docstring": "Calls decorated function object.\n\n Also verifies if the function is compatible with TFLite.\n\nReturns:\n A execution result of the decorated function.", "source": "github_repos"} +{"code": "def with_step(self, step):\n self._options['step'] = step\n return self", "docstring": "Which profile step to use for profiling.\n\n The 'step' here refers to the step defined by `Profiler.add_step()` API.\n\nArgs:\n step: When multiple steps of profiles are available, select which step's\n profile to use. If -1, use average of all available steps.\n\nReturns:\n self", "source": "github_repos"} +{"code": "def compute_ngram_keys(self, ngrams: torch.LongTensor) -> torch.LongTensor:\n if len(ngrams.shape) != 3:\n raise ValueError(f'Ngrams should be of shape (batch_size, num_ngrams, ngram_len), but is {ngrams.shape}')\n if ngrams.shape[2] != self.ngram_len:\n raise ValueError(f'Ngrams should be of shape (batch_size, num_ngrams, ngram_len), where ngram_len is {self.ngram_len}, but is {ngrams.shape}')\n batch_size, _, _ = ngrams.shape\n hash_result = torch.ones(batch_size, device=self.device, dtype=torch.long)\n hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 1), out_dims=1)(hash_result, ngrams)\n keys = self.keys[None, None, :, None]\n hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 2), out_dims=2)(hash_result, keys)\n return hash_result", "docstring": "Computes random keys for each ngram and depth.\n\nArgs:\n ngrams (`torch.LongTensor`):\n Ngrams (batch_size, num_ngrams, ngram_len).\n\nReturns:\n ngram keys (batch_size, num_ngrams, depth).", "source": "github_repos"} +{"code": "def is_directory_v2(path):\n try:\n return _pywrap_file_io.IsDirectory(compat.path_to_bytes(path))\n except errors.OpError:\n return False", "docstring": "Returns whether the path is a directory or not.\n\nArgs:\n path: string, path to a potential directory\n\nReturns:\n True, if the path is a directory; False otherwise", "source": "github_repos"} +{"code": "def get_public_api(api_mapping_files: Sequence[str], file_prefixes_to_strip: Sequence[str], packages_to_ignore: Sequence[str], output_package: str, module_prefix: str) -> PublicAPI:\n ea = exported_api.ExportedApi()\n for f in api_mapping_files:\n ea.read(f)\n v1_entrypoints_by_module = collections.defaultdict(set)\n v2_entrypoints_by_module = collections.defaultdict(set)\n\n def add_exported_symbols(api_names: list[str], s: exported_api.ExportedSymbol, entrypoints_by_module: Mapping[str, set[_Entrypoint]]):\n for api_name in api_names:\n index_of_last_dot = api_name.rfind('.')\n index_of_first_dot = api_name.find('.')\n module = output_package\n if index_of_first_dot + 1 < index_of_last_dot:\n module += f'.{api_name[index_of_first_dot + 1:index_of_last_dot]}'\n name = api_name[index_of_last_dot + 1:]\n entrypoints_by_module[module].add(_Entrypoint(module, name, s))\n for s in ea.symbols:\n if _should_skip_file(s.file_name, file_prefixes_to_strip, packages_to_ignore, module_prefix):\n continue\n add_exported_symbols(s.v1_apis, s, v1_entrypoints_by_module)\n add_exported_symbols(s.v2_apis, s, v2_entrypoints_by_module)\n v1_generated_imports_by_module = collections.defaultdict(set)\n v2_generated_imports_by_module = collections.defaultdict(set)\n\n def add_generated_imports(entrypoints_by_module: Mapping[str, set[_Entrypoint]], generated_imports_by_module: Mapping[str, set[str]]):\n for module in entrypoints_by_module:\n i = module.rfind('.')\n if i == -1:\n continue\n while i != -1:\n parent = module[:i]\n generated_imports_by_module[parent].add(module)\n module = parent\n i = module.rfind('.')\n add_generated_imports(v1_entrypoints_by_module, v1_generated_imports_by_module)\n add_generated_imports(v2_entrypoints_by_module, v2_generated_imports_by_module)\n docs_by_module = {}\n for d in ea.docs:\n for m in d.modules:\n if m in docs_by_module:\n raise DocExportedTwiceError(f'Docstring at {d.file_name}:{d.line_no} is registered for {m}, which already has a registered docstring.')\n docs_by_module[m] = d.docstring\n return PublicAPI(v1_entrypoints_by_module=v1_entrypoints_by_module, v2_entrypoints_by_module=v2_entrypoints_by_module, v1_generated_imports_by_module=v1_generated_imports_by_module, v2_generated_imports_by_module=v2_generated_imports_by_module, docs_by_module=docs_by_module)", "docstring": "Generates the structure of the public API from the given files.\n\nArgs:\n api_mapping_files: List of files containing the exported API mappings and\n docstrings.\n file_prefixes_to_strip: A list of prefixes to strip from files when\n determining the packages to ignore.\n packages_to_ignore: A list of python packages that should be ignored when\n searching for tf_exports.\n output_package: The package to use for the imports.\n module_prefix: A prefix to add to the non-generated imports.\n\nRaises:\n DocExportedTwiceError: Two docstrings are registered for the same module.\n\nReturns:\n The public API structure.", "source": "github_repos"} +{"code": "def configure_worker(worker):\n ip_address = worker['ipAddress']\n url = (_VERSION_SWITCHER_ENDPOINT + '/{}?restartType={}').format(ip_address, version, restart_type)\n req = urllib.request.Request(url, data=b'')\n try:\n urllib.request.urlopen(req)\n except urllib.error.HTTPError as e:\n status_code = e.code\n if status_code == 404:\n raise Exception('Tensorflow version {} is not available on Cloud TPU, try a previous nightly version or refer to https://cloud.google.com/tpu/docs/release-notes for the latest official version.'.format(version))\n else:\n raise Exception('Failed to configure worker {}'.format(ip_address))", "docstring": "Configure individual TPU worker.\n\nArgs:\n worker: A dict with the field ipAddress where the configure request will\n be sent.", "source": "github_repos"} +{"code": "def _process_update(self, item, feed_item):\n lp = self.landing_page_dao.get(feed_item, required=True)\n feed_item[FieldMap.CAMPAIGN_LANDING_PAGE_ID] = lp['id']\n feed_item[FieldMap.CAMPAIGN_LANDING_PAGE_NAME] = lp['name']\n item['startDate'] = StringExtensions.convertDateTimeStrToDateStr(feed_item.get(FieldMap.CAMPAIGN_START_DATE, None))\n item['endDate'] = StringExtensions.convertDateTimeStrToDateStr(feed_item.get(FieldMap.CAMPAIGN_END_DATE, None))\n item['name'] = feed_item.get(FieldMap.CAMPAIGN_NAME, None)\n item['defaultLandingPageId'] = lp['id']", "docstring": "Updates a campaign based on the values from the feed.\n\nArgs:\n item: Object representing the campaign to be updated, this object is\n updated directly.\n feed_item: Feed item representing campaign values from the Bulkdozer feed.", "source": "github_repos"} +{"code": "def message_to_extension(msg: message.Message, extension_cls: Type[_T]) -> _T:\n extension = extension_cls()\n add_message_to_extension(msg, extension)\n return extension", "docstring": "Converts an Extension profile into a generic Extension type.\n\nArgs:\n msg: The Message to convert.\n extension_cls: The type of FHIR Extension to convert to.\n\nReturns:\n A an instance of extension_cls.", "source": "github_repos"} +{"code": "def __init__(self, config: PatchTSMixerConfig):\n super().__init__(config)\n self.use_return_dict = config.use_return_dict\n self.patcher = nn.Linear(config.patch_length, config.d_model)\n if config.use_positional_encoding:\n self.positional_encoder = PatchTSMixerPositionalEncoding(config=config)\n else:\n self.positional_encoder = None\n self.mlp_mixer_encoder = PatchTSMixerBlock(config=config)\n if config.post_init:\n self.post_init()", "docstring": "Encoder for PatchTSMixer which inputs patched time-series and outputs patched embeddings.\n\nArgs:\n config (`PatchTSMixerConfig`):\n Configuration.", "source": "github_repos"} +{"code": "def _pad_images(self, images: 'torch.Tensor'):\n height, width = get_image_size(images, channel_dim=ChannelDimension.FIRST)\n pad_height = int(np.sqrt(height / 2) * 3)\n pad_width = int(np.sqrt(width / 2) * 3)\n return F.pad(images, padding=(pad_width, pad_height), padding_mode='reflect')", "docstring": "Args:\n image (`torch.Tensor`):\n Image to pad.", "source": "github_repos"} +{"code": "def floor(x):\n if any_symbolic_tensors((x,)):\n return Floor().symbolic_call(x)\n return backend.numpy.floor(x)", "docstring": "Return the floor of the input, element-wise.\n\n The floor of the scalar `x` is the largest integer `i`, such that `i <= x`.\n\nArgs:\n x: Input tensor.\n\nReturns:\n Output tensor, element-wise floor of `x`.", "source": "github_repos"} +{"code": "def default_compute_objective(metrics: dict[str, float]) -> float:\n metrics = copy.deepcopy(metrics)\n loss = metrics.pop('eval_loss', None)\n _ = metrics.pop('epoch', None)\n speed_metrics = [m for m in metrics.keys() if m.endswith('_runtime') or m.endswith('_per_second') or m.endswith('_compilation_time')]\n for sm in speed_metrics:\n _ = metrics.pop(sm, None)\n return loss if len(metrics) == 0 else sum(metrics.values())", "docstring": "The default objective to maximize/minimize when doing an hyperparameter search. It is the evaluation loss if no\n metrics are provided to the [`Trainer`], the sum of all metrics otherwise.\n\nArgs:\n metrics (`Dict[str, float]`): The metrics returned by the evaluate method.\n\nReturns:\n `float`: The objective to minimize or maximize", "source": "github_repos"} +{"code": "def _last_path_token(builder: expressions.Builder) -> str:\n if isinstance(builder.node, _evaluation.RootMessageNode):\n return ''\n return builder.node.to_path_token()", "docstring": "Returns `builder`'s last path token less the resource type.\n\n For example:\n * \"Foo\" returns \"\" (empty string)\n * \"Foo.bar\" returns \"bar\"\n * \"Foo.bar.bats\" returns \"bats\"\n\nArgs:\n builder: The `builder` whose relative path to return.", "source": "github_repos"} +{"code": "def get_static_batch_size(layer):\n batch_input_shape, _ = get_input_shape_and_dtype(layer)\n if batch_input_shape is not None:\n return tensor_shape.Dimension(batch_input_shape[0]).value\n return None", "docstring": "Gets the static batch size of a Layer.\n\nArgs:\n layer: a `Layer` instance.\n\nReturns:\n The static batch size of a Layer.", "source": "github_repos"} +{"code": "def parse_device_list(device_list_str, key=None):\n try:\n clean_lines = str(device_list_str, 'utf-8').strip().split('\\n')\n except UnicodeDecodeError:\n logging.warning('unicode decode error, origin str: %s', device_list_str)\n raise\n results = []\n for line in clean_lines:\n tokens = line.strip().split('\\t')\n if len(tokens) == 2 and (key is None or tokens[1] == key):\n results.append(tokens[0])\n return results", "docstring": "Parses a byte string representing a list of devices.\n\n The string is generated by calling either adb or fastboot. The tokens in\n each string is tab-separated.\n\nArgs:\n device_list_str: Output of adb or fastboot.\n key: The token that signifies a device in device_list_str. Only devices\n with the specified key in device_list_str are parsed, such as 'device' or\n 'fastbootd'. If not specified, all devices listed are parsed.\n\nReturns:\n A list of android device serial numbers.", "source": "github_repos"} +{"code": "def __init__(self, label=None, prefix='', with_timestamp=False, with_window=False, level=None):\n super().__init__(label)\n self.prefix = prefix\n self.with_timestamp = with_timestamp\n self.with_window = with_window\n self.level = level", "docstring": "PTransform for printing the elements of a PCollection.\n\nArgs:\n label (str): (optional) A custom label for the transform.\n prefix (str): (optional) A prefix string to prepend to each logged element.\n with_timestamp (bool): (optional) Whether to include element's timestamp.\n with_window (bool): (optional) Whether to include element's window.\n level: (optional) The logging level for the output (e.g. `logging.DEBUG`,\n `logging.INFO`, `logging.WARNING`, `logging.ERROR`). If not specified,\n the log is printed to stdout.", "source": "github_repos"} +{"code": "def field_content_length(msg: message.Message, field: Union[descriptor.FieldDescriptor, str]) -> int:\n if isinstance(field, str):\n field = _field_descriptor_for_name(msg, field)\n if field_is_repeated(field):\n return len(getattr(msg, field.name))\n return 1 if msg.HasField(field.name) else 0", "docstring": "Returns the size of the field.\n\nArgs:\n msg: The Message whose fields to examine.\n field: The FieldDescriptor or name of the field to examine.\n\nReturns:\n The number of elements at the provided field. If field describes a singular\n protobuf field, this will return 1. If the field is not set, returns 0.", "source": "github_repos"} +{"code": "def _symmetric_projection(self, n):\n q = self._orthogonal_matrix(n)\n mask = math_ops.cast(random_ops.random_normal([n], seed=self.seed) > 0, self.dtype)\n if self.seed:\n self.seed += 1\n c = math_ops.multiply(q, mask)\n return math_ops.matmul(c, array_ops.matrix_transpose(c))", "docstring": "Compute a n x n symmetric projection matrix.\n\nArgs:\n n: Dimension.\n\nReturns:\n A n x n symmetric projection matrix, i.e. a matrix P s.t. P=P*P, P=P^T.", "source": "github_repos"} +{"code": "def __init__(self, *args, **kwargs):\n \"\"\"Initializes the instance of _MockAdbProxy.\"\"\"\n super().__init__(*args, **kwargs)\n self.default_host_port = MOCK_HOST_PORT\n self.mock_shell_func = mock.Mock()\n self.mock_forward_func = mock.Mock()", "docstring": "Mock class of adb proxy which covers all the calls used by snippet clients.\n\n To enable testing snippet clients, this class extends the functionality of\n base class from the following aspects:\n * Records the arguments of all the calls to the shell method and forward\n method.\n * Handles the adb calls to stop the snippet server in the shell function\n properly.\n\nAttributes:\n default_host_port: int, return this port if `self.forward` got 'tcp:0' as\n host port.\n mock_shell_func: mock.Mock, used for recording the calls to the shell\n method.\n mock_forward_func: mock.Mock, used for recording the calls to the forward\n method.", "source": "github_repos"} +{"code": "def transform(self, y):\n if y.ndim == 1:\n return y.reshape(-1, 1)\n return y", "docstring": "Makes 1D y 2D.\n\nArgs:\n y : np.ndarray\n Target y to be transformed.\n\nReturns:\n np.ndarray\n A numpy array, of dimension at least 2.", "source": "github_repos"} +{"code": "def load_batch(fpath, label_key='labels'):\n with open(fpath, 'rb') as f:\n d = cPickle.load(f, encoding='bytes')\n d_decoded = {}\n for k, v in d.items():\n d_decoded[k.decode('utf8')] = v\n d = d_decoded\n data = d['data']\n labels = d[label_key]\n data = data.reshape(data.shape[0], 3, 32, 32)\n return (data, labels)", "docstring": "Internal utility for parsing CIFAR data.\n\nArgs:\n fpath: path the file to parse.\n label_key: key for label data in the retrieve\n dictionary.\n\nReturns:\n A tuple `(data, labels)`.", "source": "github_repos"} +{"code": "def __call__(self, shardable_tensors: Sequence[sharding_util.ShardableTensor]) -> Sequence[sharding_util.Shard]:\n tensors_by_task = {}\n for shardable_tensor in shardable_tensors:\n tensor = shardable_tensor.tensor\n checkpoint_key = shardable_tensor.checkpoint_key\n slice_spec = shardable_tensor.slice_spec\n tensors_by_task.setdefault(checkpoint_key, {})[slice_spec] = tensor\n return [tensors_by_task]", "docstring": "Callback to split tensors into shards based on their device spec task.\n\nArgs:\n shardable_tensors: A list of ShardableTensors.\n\nReturns:\n List of shard dicts containing tensors.\n [ {checkpoint key: {slice_spec: tensor} } ]", "source": "github_repos"} +{"code": "def _compute_euclidean_distance(cls, inputs, clusters):\n output = []\n for inp in inputs:\n with ops.colocate_with(inp, ignore_existing=True):\n squared_distance = math_ops.reduce_sum(math_ops.square(inp), 1, keepdims=True) - 2 * math_ops.matmul(inp, clusters, transpose_b=True) + array_ops.transpose(math_ops.reduce_sum(math_ops.square(clusters), 1, keepdims=True))\n output.append(squared_distance)\n return output", "docstring": "Computes Euclidean distance between each input and each cluster center.\n\nArgs:\n inputs: list of input Tensors.\n clusters: cluster Tensor.\n\nReturns:\n list of Tensors, where each element corresponds to each element in inputs.\n The value is the distance of each row to all the cluster centers.", "source": "github_repos"} +{"code": "def _create_uninitialized_mirrored_tpu_variables(**kwargs):\n if kwargs.get('initial_value', None) is None:\n return _create_mirrored_tpu_variables(**kwargs)\n value_list = []\n initial_value = None\n for i, d in enumerate(devices):\n with ops.device(d):\n if i == 0:\n initial_value = kwargs.get('initial_value', None)\n with maybe_init_scope():\n if initial_value is not None:\n if callable(initial_value):\n initial_value = initial_value()\n initial_value = ops.convert_to_tensor(initial_value, dtype=kwargs.get('dtype', None))\n if i > 0:\n var0name = value_list[0].name.split(':')[0]\n kwargs['name'] = '%s/replica_%d/' % (var0name, i)\n kwargs['initial_value'] = initial_value\n if kwargs.get('dtype', None) is None:\n kwargs['dtype'] = kwargs['initial_value'].dtype\n if kwargs.get('shape', None) is None:\n kwargs['shape'] = kwargs['initial_value'].shape\n with context.device_policy(context.DEVICE_PLACEMENT_SILENT):\n v = uninitialized_variable_creator(**kwargs)\n assert not isinstance(v, tpu_values.TPUMirroredVariable)\n value_list.append(v)\n return value_list", "docstring": "Returns a list of `tf.Variable`s.\n\n The list contains `number_replicas` `tf.Variable`s and can be used to\n initialize a `TPUMirroredVariable`.\n\nArgs:\n **kwargs: the keyword arguments for creating a variable", "source": "github_repos"} +{"code": "def replace_model_patterns(text: str, old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns) -> Tuple[str, str]:\n attributes_to_check = ['config_class']\n for attr in ['tokenizer_class', 'image_processor_class', 'image_processor_fast_class', 'feature_extractor_class', 'processor_class']:\n if getattr(old_model_patterns, attr) is not None and getattr(new_model_patterns, attr) is not None:\n attributes_to_check.append(attr)\n if old_model_patterns.checkpoint not in [old_model_patterns.model_type, old_model_patterns.model_lower_cased]:\n attributes_to_check.append('checkpoint')\n if old_model_patterns.model_type != old_model_patterns.model_lower_cased:\n attributes_to_check.append('model_type')\n else:\n text = re.sub(f'(\\\\s*)model_type = \"{old_model_patterns.model_type}\"', '\\\\1model_type = \"[MODEL_TYPE]\"', text)\n if old_model_patterns.model_upper_cased == old_model_patterns.model_camel_cased:\n old_model_value = old_model_patterns.model_upper_cased\n if re.search(f'{old_model_value}_[A-Z_]*[^A-Z_]', text) is not None:\n text = re.sub(f'{old_model_value}([A-Z_]*)([^a-zA-Z_])', '[MODEL_UPPER_CASED]\\\\1\\\\2', text)\n else:\n attributes_to_check.append('model_upper_cased')\n attributes_to_check.extend(['model_camel_cased', 'model_lower_cased', 'model_name'])\n for attr in attributes_to_check:\n text = text.replace(getattr(old_model_patterns, attr), ATTRIBUTE_TO_PLACEHOLDER[attr])\n replacements = []\n for attr, placeholder in ATTRIBUTE_TO_PLACEHOLDER.items():\n if placeholder in text:\n replacements.append((getattr(old_model_patterns, attr), getattr(new_model_patterns, attr)))\n text = text.replace(placeholder, getattr(new_model_patterns, attr))\n old_replacement_values = [old for old, new in replacements]\n if len(set(old_replacement_values)) != len(old_replacement_values):\n return (text, '')\n replacements = simplify_replacements(replacements)\n replacements = [f'{old}->{new}' for old, new in replacements]\n return (text, ','.join(replacements))", "docstring": "Replace all patterns present in a given text.\n\nArgs:\n text (`str`): The text to treat.\n old_model_patterns (`ModelPatterns`): The patterns for the old model.\n new_model_patterns (`ModelPatterns`): The patterns for the new model.\n\nReturns:\n `Tuple(str, str)`: A tuple of with the treated text and the replacement actually done in it.", "source": "github_repos"} +{"code": "def sort_all_auto_mappings(overwrite: bool=False):\n fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE) if f.endswith('.py')]\n diffs = [sort_auto_mapping(fname, overwrite=overwrite) for fname in fnames]\n if not overwrite and any(diffs):\n failures = [f for f, d in zip(fnames, diffs) if d]\n raise ValueError(f'The following files have auto mappings that need sorting: {', '.join(failures)}. Run `make style` to fix this.')", "docstring": "Sort all auto mappings in the library.\n\nArgs:\n overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file.", "source": "github_repos"} +{"code": "def _load_metadata_files(self):\n metadata_paths = file_io.get_matching_files(os.path.join(self._dump_root, '*%s' % self._METADATA_SUFFIX))\n if not metadata_paths:\n raise ValueError('Cannot find any tfdbg metadata file in directory: %s' % self._dump_root)\n wall_times = []\n run_ids = []\n tensorflow_versions = []\n file_versions = []\n for metadata_path in metadata_paths:\n reader = tf_record.tf_record_random_reader(metadata_path)\n try:\n record = reader.read(0)[0]\n debug_event = debug_event_pb2.DebugEvent.FromString(record)\n wall_times.append(debug_event.wall_time)\n run_ids.append(debug_event.debug_metadata.tfdbg_run_id)\n tensorflow_versions.append(debug_event.debug_metadata.tensorflow_version)\n file_versions.append(debug_event.debug_metadata.file_version)\n except Exception as e:\n raise errors.DataLossError(None, None, 'Error reading tfdbg metadata from paths %s' % metadata_paths) from e\n finally:\n reader.close()\n self._starting_wall_time = wall_times[0]\n self._tfdbg_run_id = run_ids[0]\n self._tensorflow_version = tensorflow_versions[0]\n self._file_version = file_versions[0]\n if len(metadata_paths) == 1:\n return metadata_paths\n num_no_id = len([run_id for run_id in run_ids if not run_id])\n if num_no_id:\n paths_without_run_id = [metadata_path for metadata_path, run_id in zip(metadata_paths, run_ids) if not run_id]\n raise ValueError('Found %d tfdbg metadata files and %d of them do not have tfdbg run ids. The metadata files without run ids are: %s' % (len(run_ids), num_no_id, paths_without_run_id))\n elif len(set(run_ids)) != 1:\n raise ValueError('Unexpected: Found multiple (%d) tfdbg2 runs in directory %s' % (len(set(run_ids)), self._dump_root))\n paths_and_timestamps = sorted(zip(metadata_paths, wall_times), key=lambda t: t[1])\n self._starting_wall_time = paths_and_timestamps[0][1]\n return [path[0] for path in paths_and_timestamps]", "docstring": "Load and parse metadata files in the dump root.\n\n Check that all metadata files have a common tfdbg_run_id, and raise\n a ValueError if their tfdbg_run_ids differ.\n\nReturns:\n A list of metadata file paths in ascending order of their starting\n wall_time timestamp.", "source": "github_repos"} +{"code": "def operator_and_matrix(self, shapes_info, dtype, use_placeholder, ensure_self_adjoint_and_pd=False):\n raise NotImplementedError('Not implemented yet.')", "docstring": "Build a batch matrix and an Operator that should have similar behavior.\n\n Every operator acts like a (batch) matrix. This method returns both\n together, and is used by tests.\n\nArgs:\n shapes_info: `OperatorShapesInfo`, encoding shape information about the\n operator.\n dtype: Numpy dtype. Data type of returned array/operator.\n use_placeholder: Python bool. If True, initialize the operator with a\n placeholder of undefined shape and correct dtype.\n ensure_self_adjoint_and_pd: If `True`,\n construct this operator to be Hermitian Positive Definite, as well\n as ensuring the hints `is_positive_definite` and `is_self_adjoint`\n are set.\n This is useful for testing methods such as `cholesky`.\n\nReturns:\n operator: `LinearOperator` subclass instance.\n mat: `Tensor` representing operator.", "source": "github_repos"} +{"code": "def configure_tpu_version(self, version, restart_type='always'):\n\n def configure_worker(worker):\n \"\"\"Configure individual TPU worker.\n\n Args:\n worker: A dict with the field ipAddress where the configure request will\n be sent.\n \"\"\"\n ip_address = worker['ipAddress']\n url = (_VERSION_SWITCHER_ENDPOINT + '/{}?restartType={}').format(ip_address, version, restart_type)\n req = urllib.request.Request(url, data=b'')\n try:\n urllib.request.urlopen(req)\n except urllib.error.HTTPError as e:\n status_code = e.code\n if status_code == 404:\n raise Exception('Tensorflow version {} is not available on Cloud TPU, try a previous nightly version or refer to https://cloud.google.com/tpu/docs/release-notes for the latest official version.'.format(version))\n else:\n raise Exception('Failed to configure worker {}'.format(ip_address))\n workers = self.network_endpoints()\n with futures.ThreadPoolExecutor(max_workers=len(workers)) as executor:\n results = executor.map(configure_worker, workers)\n for result in results:\n if result:\n result.result()", "docstring": "Configure TPU software version.\n\nArgs:\n version (string): Version of software to configure the TPU with.\n restart_type (string): Restart behaviour when switching versions,\n defaults to always restart. Options are 'always', 'ifNeeded'.", "source": "github_repos"} +{"code": "def control_status_ctx():\n ret = _control_ctx()[-1]\n return ret", "docstring": "Returns the current control context for autograph.\n\n This method is useful when calling `tf.__internal__.autograph.tf_convert`,\n The context will be used by tf_convert to determine whether it should convert\n the input function. See the sample usage like below:\n\n ```\n def foo(func):\n return tf.__internal__.autograph.tf_convert(\n input_fn, ctx=tf.__internal__.autograph.control_status_ctx())()\n ```\n\nReturns:\n The current control context of autograph.", "source": "github_repos"} +{"code": "def verify_error_on_save(self, ds_fn, num_outputs, error, break_point=None, sparse_tensors=False, assert_items_equal=False):\n del assert_items_equal\n break_point = num_outputs // 2 if not break_point else break_point\n if context.executing_eagerly():\n iterator = iter(ds_fn())\n ckpt = tracking_util.Checkpoint(iterator=iterator)\n for _ in range(break_point):\n next(iterator)\n with self.assertRaises(error):\n ckpt.save(self._ckpt_path())\n else:\n with ops.Graph().as_default() as g:\n init_op, get_next_op, saver = self._build_graph(ds_fn, sparse_tensors=sparse_tensors)\n get_next_op = remove_variants(get_next_op)\n with self.session(graph=g) as sess:\n self._initialize(init_op, sess)\n for _ in range(break_point):\n sess.run(get_next_op)\n with self.assertRaises(error):\n self._save(sess, saver)", "docstring": "Attempts to save a non-saveable iterator.\n\nArgs:\n ds_fn: 0-argument function that returns a Dataset.\n num_outputs: Total number of outputs expected from this Dataset.\n error: Declared error when trying to save iterator.\n break_point: Break point. Optional. Defaults to num_outputs/2.\n sparse_tensors: Whether dataset is built from SparseTensor(s).\n assert_items_equal: Tests the output has the expected elements regardless\n of order.\n\nRaises:\n AssertionError if any test fails.", "source": "github_repos"} +{"code": "def parse_single_example(serialized, features, name=None, example_names=None):\n return parse_single_example_v2(serialized, features, example_names, name)", "docstring": "Parses a single `Example` proto.\n\n Similar to `parse_example`, except:\n\n For dense tensors, the returned `Tensor` is identical to the output of\n `parse_example`, except there is no batch dimension, the output shape is the\n same as the shape given in `dense_shape`.\n\n For `SparseTensor`s, the first (batch) column of the indices matrix is removed\n (the indices matrix is a column vector), the values vector is unchanged, and\n the first (`batch_size`) entry of the shape vector is removed (it is now a\n single element vector).\n\n One might see performance advantages by batching `Example` protos with\n `parse_example` instead of using this function directly.\n\nArgs:\n serialized: A scalar string Tensor, a single serialized Example.\n features: A mapping of feature keys to `FixedLenFeature` or\n `VarLenFeature` values.\n name: A name for this operation (optional).\n example_names: (Optional) A scalar string Tensor, the associated name.\n\nReturns:\n A `dict` mapping feature keys to `Tensor` and `SparseTensor` values.\n\nRaises:\n ValueError: if any feature is invalid.", "source": "github_repos"} +{"code": "def to_dict(self):\n output = asdict(self)\n output['structure_module'] = self.structure_module.to_dict()\n return output", "docstring": "Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].\n\nReturns:\n `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,", "source": "github_repos"} +{"code": "def until_next(self: EventSetOrNode, sampling: EventSetOrNode, timeout: Duration) -> EventSetOrNode:\n from temporian.core.operators.until_next import until_next\n return until_next(self, timeout=timeout, sampling=sampling)", "docstring": "Gets the duration until the next sampling event for each input event.\n\n If no sampling event is observed before `timeout` time-units, returns\n NaN.\n\n `until_next` is different from `since_last` in that `since_last` returns\n one value for each sampling (sampling events are after input events),\n while `until_next` returns one value for each input value (here again,\n sampling events are after input events).\n\n The output [`EventSet`][temporian.EventSet] has one event for each event\n in input, but with its timestamp moved forward to the nearest future\n event in `sampling`. If no timestamp in sampling is closer than timeout,\n it is moved by `timeout` into the future instead.\n\n `until_next` is useful to measure the time it takes for an issue\n (`input`) to be detected by an alert (`sampling`).\n\n Basic example with 1 and 2 steps:\n ```python\n >>> a = tp.event_set(timestamps=[0, 10, 11, 20, 30])\n >>> b = tp.event_set(timestamps=[1, 12, 21, 22, 42])\n >>> c = a.until_next(sampling=b, timeout=5)\n >>> c\n indexes: []\n features: [('until_next', float64)]\n events:\n (5 events):\n timestamps: [ 1. 12. 12. 21. 35.]\n 'until_next': [ 1. 2. 1. 1. nan]\n ...\n\n ```\n\nArgs:\n sampling: EventSet to use the sampling of.\n timeout: Maximum amount of time to wait. If no sampling is observed\n before the timeout expires, the output feature value is NaN.\n\nReturns:\n Resulting EventSet.", "source": "github_repos"} +{"code": "def coder_benchmark_factory(coder, generate_fn):\n\n class CoderBenchmark(object):\n\n def __init__(self, num_elements_per_benchmark):\n self._coder = coders.IterableCoder(coder)\n self._list = [generate_fn() for _ in range(num_elements_per_benchmark)]\n\n def __call__(self):\n _ = self._coder.decode(self._coder.encode(self._list))\n CoderBenchmark.__name__ = '%s, %s' % (generate_fn.__name__, str(coder))\n return CoderBenchmark", "docstring": "Creates a benchmark that encodes and decodes a list of elements.\n\nArgs:\n coder: coder to use to encode an element.\n generate_fn: a callable that generates an element.", "source": "github_repos"} +{"code": "def __init__(self, config: MT5Config):\n super().__init__(config)\n self.shared = nn.Embedding(config.vocab_size, config.d_model)\n encoder_config = copy.deepcopy(config)\n encoder_config.use_cache = False\n encoder_config.is_encoder_decoder = False\n self.encoder = MT5Stack(encoder_config, self.shared)\n self.post_init()\n self.model_parallel = False\n self.device_map = None", "docstring": "Examples:\n\n ```python\n >>> from transformers import MT5EncoderModel, AutoTokenizer\n\n >>> model = MT5EncoderModel.from_pretrained(\"google/mt5-small\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google/mt5-small\")\n >>> article = \"UN Offizier sagt, dass weiter verhandelt werden muss in Syrien.\"\n >>> input_ids = tokenizer(article, return_tensors=\"pt\").input_ids\n >>> outputs = model(input_ids)\n >>> hidden_state = outputs.last_hidden_state\n ```", "source": "github_repos"} +{"code": "def check_accessible(value_provider_list):\n assert isinstance(value_provider_list, list)\n\n def _check_accessible(fnc):\n\n @wraps(fnc)\n def _f(self, *args, **kwargs):\n for obj in [getattr(self, vp) for vp in value_provider_list]:\n if not obj.is_accessible():\n raise error.RuntimeValueProviderError('%s not accessible' % obj)\n return fnc(self, *args, **kwargs)\n return _f\n return _check_accessible", "docstring": "A decorator that checks accessibility of a list of ValueProvider objects.\n\nArgs:\n value_provider_list: list of ValueProvider objects\n\nRaises:\n ``RuntimeValueProviderError``: if any of the provided objects are not\n accessible.", "source": "github_repos"} +{"code": "def __init__(self, queue, ev_writer, flush_secs, flush_complete, flush_sentinel, close_sentinel):\n threading.Thread.__init__(self, name='EventLoggerThread')\n self.daemon = True\n self._queue = queue\n self._ev_writer = ev_writer\n self._flush_secs = flush_secs\n self._next_event_flush_time = 0\n self._flush_complete = flush_complete\n self._flush_sentinel = flush_sentinel\n self._close_sentinel = close_sentinel\n self.failure_exc_info = ()", "docstring": "Creates an _EventLoggerThread.\n\nArgs:\n queue: A CloseableQueue from which to dequeue events. The queue will be\n closed just before the thread exits, whether due to `close_sentinel` or\n any exception raised in the writing loop.\n ev_writer: An event writer. Used to log brain events for\n the visualizer.\n flush_secs: How often, in seconds, to flush the\n pending file to disk.\n flush_complete: A threading.Event that will be set whenever a flush\n operation requested via `flush_sentinel` has been completed.\n flush_sentinel: A sentinel element in queue that tells this thread to\n flush the writer and mark the current flush operation complete.\n close_sentinel: A sentinel element in queue that tells this thread to\n terminate and close the queue.", "source": "github_repos"} +{"code": "def soft_shrink(x, threshold=0.5):\n return ops.soft_shrink(x, threshold=threshold)", "docstring": "Soft Shrink activation function.\n\n It is defined as:\n\n `soft_shrink(x) = x - threshold` if `x > threshold`,\n `soft_shrink(x) = x + threshold` if `x < -threshold`,\n `soft_shrink(x) = 0` otherwise.\n\nArgs:\n x: Input tensor.\n threshold: Threshold value. Defaults to 0.5.", "source": "github_repos"} +{"code": "def variables(self):\n return self._opt.variables()", "docstring": "Fetches a list of optimizer variables in the default graph.\n\n This wraps `variables()` from the actual optimizer. It does not include\n the `SyncReplicasOptimizer`'s local step.\n\nReturns:\n A list of variables.", "source": "github_repos"} +{"code": "def get_numpy_to_framework_fn(arr) -> Callable:\n if isinstance(arr, np.ndarray):\n return np.array\n if is_tf_available() and is_tf_tensor(arr):\n import tensorflow as tf\n return tf.convert_to_tensor\n if is_torch_available() and is_torch_tensor(arr):\n import torch\n return torch.tensor\n if is_flax_available() and is_jax_tensor(arr):\n import jax.numpy as jnp\n return jnp.array\n raise ValueError(f'Cannot convert arrays of type {type(arr)}')", "docstring": "Returns a function that converts a numpy array to the framework of the input array.\n\nArgs:\n arr (`np.ndarray`): The array to convert.", "source": "github_repos"} +{"code": "def alias_inplace_add(x, i, v):\n return _inplace_helper(x, i, v, gen_array_ops.inplace_add)", "docstring": "Applies an inplace add on input x at index i with value v. Aliases x.\n\n If i is None, x and v must be the same shape. Computes\n x += v;\n If i is a scalar, x has a rank 1 higher than v's. Computes\n x[i, :] += v;\n Otherwise, x and v must have the same rank. Computes\n x[i, :] += v;\n\nArgs:\n x: A Tensor.\n i: None, a scalar or a vector.\n v: A Tensor.\n\nReturns:\n Returns x.", "source": "github_repos"} +{"code": "def assertNotAllClose(self, a, b, rtol=1e-06, atol=1e-06, msg=None):\n try:\n self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg)\n except AssertionError:\n return\n msg = msg or ''\n raise AssertionError('The two values are close at all elements. %s' % msg)", "docstring": "Assert that two numpy arrays, or Tensors, do not have near values.\n\nArgs:\n a: The expected numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor), or any arbitrarily nested of\n structure of these.\n b: The actual numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor), or any arbitrarily nested of\n structure of these.\n rtol: relative tolerance.\n atol: absolute tolerance.\n msg: Optional message to report on failure.\n\nRaises:\n AssertionError: If `a` and `b` are unexpectedly close at all elements.", "source": "github_repos"} +{"code": "def name_scope_only_in_function_or_graph(name):\n if not context.executing_eagerly():\n return ops.name_scope_v1(name)\n else:\n return NullContextmanager()", "docstring": "Internal-only entry point for `name_scope*`.\n\n Enters a compat.v1.name_scope only when in a function or graph,\n not when running fully eagerly.\n\nArgs:\n name: The name argument that is passed to the op function.\n\nReturns:\n `name_scope*` context manager.", "source": "github_repos"} +{"code": "def _infer_num_gpus_per_worker(devices):\n if _is_device_list_single_worker(devices):\n return sum((1 for d in devices if _is_gpu_device(d)))\n else:\n device_dict = _group_device_list(devices)\n num_gpus = None\n for _, devices_in_task in device_dict.items():\n for device_in_task in devices_in_task:\n if num_gpus is None:\n num_gpus = sum((1 for d in device_in_task if _is_gpu_device(d)))\n elif num_gpus != sum((1 for d in device_in_task if _is_gpu_device(d))):\n raise ValueError('All workers should have the same number of GPUs.')\n for d in device_in_task:\n d_spec = tf_device.DeviceSpec.from_string(d)\n if d_spec.device_type == 'GPU' and d_spec.device_index >= num_gpus:\n raise ValueError('GPU `device_index` on a worker should be consecutive and start from 0.')\n return num_gpus", "docstring": "Infers the number of GPUs on each worker.\n\n Currently to make multi-worker cross device ops work, we need all workers to\n have the same number of GPUs.\n\nArgs:\n devices: a list of device strings, can be either local devices or remote\n devices.\n\nReturns:\n number of GPUs per worker.\n\nRaises:\n ValueError if workers have different number of GPUs or GPU indices are not\n consecutive and starting from 0.", "source": "github_repos"} +{"code": "def ragged_binary_elementwise_assert_op_impl(op, x, y):\n x_is_ragged = ragged_tensor.is_ragged(x)\n y_is_ragged = ragged_tensor.is_ragged(y)\n x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x, preferred_dtype=y.dtype if y_is_ragged else None)\n y = ragged_tensor.convert_to_tensor_or_ragged_tensor(y, preferred_dtype=x.dtype)\n if x_is_ragged and y_is_ragged:\n x, y = ragged_tensor.match_row_splits_dtypes(x, y)\n if x_is_ragged and y_is_ragged or (x_is_ragged and x.flat_values.shape.ndims <= y.shape.ndims) or (y_is_ragged and y.flat_values.shape.ndims <= x.shape.ndims):\n shape_x = DynamicRaggedShape.from_tensor(x)\n shape_y = DynamicRaggedShape.from_tensor(y)\n if shape_x.dtype != shape_y.dtype:\n if not x_is_ragged:\n shape_x = shape_x.with_dtype(shape_y.dtype)\n elif not y_is_ragged:\n shape_y = shape_y.with_dtype(shape_x.dtype)\n if _row_partitions_identical(shape_x, shape_y):\n return op(x.flat_values, y.flat_values)\n _, bcast_xz, bcast_yz = broadcast_dynamic_shape_extended(shape_x, shape_y)\n x_new_flat = bcast_xz.broadcast_flat_values(x, inner_dimensions=False)\n y_new_flat = bcast_yz.broadcast_flat_values(y, inner_dimensions=False)\n return op(x_new_flat, y_new_flat)\n x_values = x.flat_values if ragged_tensor.is_ragged(x) else x\n y_values = y.flat_values if ragged_tensor.is_ragged(y) else y\n return op(x_values, y_values)", "docstring": "Binary elementwise assert api handler for RaggedTensors.\n\n This handles binary assert operations for ragged tensors. Compared with\n `ragged_binary_elementwise_op_impl`, this handler does not compute a ragged\n tensor as output. Instead, it applies the assert operation `op` to input\n tensors based on their ragged shapes and flat_values, and returns the result\n of the assertion operation.\n\nArgs:\n op: a binary assert operation on Tensors.\n x: something that can be coerced to a Tensor or RaggedTensor.\n y: something that can be coerced to a Tensor or RaggedTensor.\n\nReturns:\n the result of the assertion operation.", "source": "github_repos"} +{"code": "def __init__(self, initializer: tf.keras.initializers.Initializer=tf.keras.initializers.RandomUniform()):\n super().__init__()\n self._initializer = initializer", "docstring": "Initializes a VariableDot layer.\n\nArgs:\n initializer: A `tf.keras.initializers.Initializer` which specifies how to\n initialize the values of the parameters.", "source": "github_repos"} +{"code": "def _select_forward_and_backward_functions(self, args, possible_gradient_type, executing_eagerly):\n if executing_eagerly:\n input_tangents = forwardprop_util.pack_tangents(args)\n else:\n input_tangents = forwardprop_util.TangentInfo()\n need_gradients_for_jvps = record.should_record_backprop(input_tangents.tangents)\n cache_key = (need_gradients_for_jvps, input_tangents.indices)\n if possible_gradient_type == gradients_util.POSSIBLE_GRADIENT_TYPES_FIRST_ORDER:\n if input_tangents.indices or executing_eagerly:\n functions = self._first_order_tape_functions.get(cache_key, None)\n if functions is None:\n functions = _FirstOrderTapeGradientFunctions(self._func_graph, self._attrs, self._garbage_collector, forwardprop_input_indices=input_tangents.indices, delayed_rewrite_functions=self._delayed_rewrite_functions, need_gradients_for_jvps=need_gradients_for_jvps)\n self._first_order_tape_functions[cache_key] = functions\n return _ForwardBackwardCall(functions, args, input_tangents.tangents, tape_watching=True)\n else:\n return _ForwardBackwardCall(self._delayed_rewrite_functions, args, input_tangents.tangents, tape_watching=True)\n elif possible_gradient_type == gradients_util.POSSIBLE_GRADIENT_TYPES_HIGHER_ORDER:\n functions = self._higher_order_tape_functions.get(cache_key, None)\n if functions is None:\n functions = _HigherOrderTapeGradientFunctions(self._func_graph, self._attrs, self._garbage_collector, forwardprop_input_indices=input_tangents.indices, delayed_rewrite_functions=self._delayed_rewrite_functions, need_gradients_for_jvps=need_gradients_for_jvps)\n self._higher_order_tape_functions[cache_key] = functions\n return _ForwardBackwardCall(functions, args, input_tangents.tangents, tape_watching=True)\n return _ForwardBackwardCall(self._delayed_rewrite_functions, args, input_tangents.tangents, tape_watching=False)", "docstring": "Selects forward and backward functions based on the calling context.\n\n The forward function computes the \"real\" function outputs, `self._outputs`,\n and any extra values needed by the corresponding backward function.\n\nArgs:\n args: A flat list of Tensors with all of the inputs to the forward\n function (including user-specified and captured inputs).\n possible_gradient_type: One of gradients_util.POSSIBLE_GRADIENT_TYPES_*.\n executing_eagerly: Boolean, the value of context.executing_eagerly().\n\nReturns:\n An object with a `forward` method returning a tuple of (forward_function :\n AtomicFunction, augmented_arguments : List), and a corresponding\n `record` method which takes outputs from the forward function and records\n the operation. forward_function should be called with augmented_arguments.", "source": "github_repos"} +{"code": "def get_config(self):\n raise NotImplementedError(f'{self} does not implement get_config()')", "docstring": "Returns the config of the quantizer.\n\n A quantizer config is a Python dictionary (serializable)\n containing all configuration parameters of the quantizer.\n The same quantizer can be reinstantiated later\n (without any saved state) from this configuration.\n\n This method is optional if you are just training and executing models,\n exporting to and from SavedModels, or using weight checkpoints.\n\n This method is required for Keras `model_to_estimator`, saving and\n loading models to HDF5 formats, Keras model cloning, some visualization\n utilities, and exporting models to and from JSON.\n\nReturns:\n Python dictionary.", "source": "github_repos"} +{"code": "def output_all_intermediates():\n if _EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE is not None:\n return _EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE\n if in_defun():\n return False\n if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()):\n return False\n if context.context().function_call_options.executor_type == 'SINGLE_THREADED_EXECUTOR':\n return False\n return _is_building_keras_layer()", "docstring": "Whether to output all intermediates of a functional control flow op.\n\n The default behavior is to output intermediates only when building a Keras\n Layer in graph mode and that too when certain other conditions are met:\n 1. We do not output intermediates if the functional control flow op\n is being built inside a FuncGraph which is not a If/While graph. This\n guards against outputting intermediates in eager mode since keras adds\n tensors to a FuncGraph named \"keras_graph\" in that case. Also because we\n do not output intermediates of tf.function (since this feature is only for\n backwards compatibility) outputting intermediates of functional control\n flow ops built inside tf.function is of no value.\n 2. We do not output intermediates when the compilation is using XLA or for a\n TPU.\n 3. We do not output intermediates when a single threaded executor is used\n since that does not perform inlining and pruning.\n\nReturns:\n A bool telling whether to output all intermediates.", "source": "github_repos"} +{"code": "def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='hinge'):\n super().__init__(hinge, name=name, reduction=reduction)", "docstring": "Initializes `Hinge` instance.\n\nArgs:\n reduction: Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training) for\n more details.\n name: Optional name for the instance. Defaults to 'hinge'.", "source": "github_repos"} +{"code": "def __init__(self, options=None):\n if options is not None:\n self._options = copy.deepcopy(options)\n else:\n self._options = {'max_depth': 100, 'min_bytes': 0, 'min_micros': 0, 'min_params': 0, 'min_float_ops': 0, 'min_occurrence': 0, 'order_by': 'name', 'account_type_regexes': ['.*'], 'start_name_regexes': ['.*'], 'trim_name_regexes': [], 'show_name_regexes': ['.*'], 'hide_name_regexes': [], 'account_displayed_op_only': False, 'select': ['micros'], 'step': -1, 'output': 'stdout'}", "docstring": "Constructor.\n\nArgs:\n options: Optional initial option dict to start with.", "source": "github_repos"} +{"code": "def enable_collective_ops(self, server_def):\n if not server_def:\n raise ValueError('server_def is None.')\n self._collective_ops_server_def = server_def\n if self._context_handle is not None:\n logging.warning('Enabling collective ops after program startup may cause error when accessing previously created tensors.')\n with self._initialize_lock:\n assert self._initialized\n server_def_str = self._collective_ops_server_def.SerializeToString()\n pywrap_tfe.TFE_EnableCollectiveOps(self._context_handle, server_def_str)\n self._initialize_logical_devices()\n self._clear_caches()", "docstring": "Enable distributed collective ops with an appropriate server_def.\n\nArgs:\n server_def: A tensorflow::ServerDef proto. Enables execution on remote\n devices.\n\nRaises:\n ValueError: if server_def is None.\n RuntimeError: if this method is not called at program startup.", "source": "github_repos"} +{"code": "def create_position_ids_from_inputs_embeds(self, inputs_embeds):\n input_shape = shape_list(inputs_embeds)[:-1]\n sequence_length = input_shape[1]\n position_ids = tf.range(start=self.padding_idx + 1, limit=sequence_length + self.padding_idx + 1, dtype=tf.int64)\n return tf.broadcast_to(tf.expand_dims(position_ids, 0), input_shape)", "docstring": "We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.\n\nArgs:\n inputs_embeds: tf.Tensor\n\n Returns: tf.Tensor", "source": "github_repos"} +{"code": "def get_graph_debug_info(self, name):\n with c_api_util.tf_buffer() as buffer_:\n pywrap_tfe.TFE_ContextGetGraphDebugInfo(self._handle, name, buffer_)\n proto_data = pywrap_tf_session.TF_GetBuffer(buffer_)\n graph_debug_info = graph_debug_info_pb2.GraphDebugInfo()\n graph_debug_info.ParseFromString(proto_data)\n return graph_debug_info", "docstring": "Get GraphDebugInfo associated with a function from the context.\n\nArgs:\n name: function signature name.\n\nReturns:\n The requested GraphDebugInfo.\n\nRaises:\n tf.errors.NotFoundError: if name is not the name of a registered function.", "source": "github_repos"} +{"code": "def __call__(self, text_inputs: Union[str, List[str]], **forward_params) -> Union[Dict[str, Any], List[Dict[str, Any]]]:\n return super().__call__(text_inputs, **forward_params)", "docstring": "Generates speech/audio from the inputs. See the [`TextToAudioPipeline`] documentation for more information.\n\nArgs:\n text_inputs (`str` or `List[str]`):\n The text(s) to generate.\n forward_params (`dict`, *optional*):\n Parameters passed to the model generation/forward method. `forward_params` are always passed to the\n underlying model.\n generate_kwargs (`dict`, *optional*):\n The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a\n complete overview of generate, check the [following\n guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). `generate_kwargs` are\n only passed to the underlying model if the latter is a generative model.\n\nReturns:\n A `dict` or a list of `dict`: The dictionaries have two keys:\n\n - **audio** (`np.ndarray` of shape `(nb_channels, audio_length)`) -- The generated audio waveform.\n - **sampling_rate** (`int`) -- The sampling rate of the generated audio waveform.", "source": "github_repos"} +{"code": "def moving_sum(self: EventSetOrNode, window_length: WindowLength, sampling: Optional[EventSetOrNode]=None) -> EventSetOrNode:\n from temporian.core.operators.window.moving_sum import moving_sum\n return moving_sum(self, window_length=window_length, sampling=sampling)", "docstring": "Computes the sum of values in a sliding window over an\n [`EventSet`][temporian.EventSet].\n\n For each t in sampling, and for each feature independently, returns at\n time t the sum of values for the feature in the window\n (t - window_length, t].\n\n `sampling` can't be specified if a variable `window_length` is\n specified (i.e. if `window_length` is an EventSet).\n\n If `sampling` is specified or `window_length` is an EventSet, the moving\n window is sampled at each timestamp in them, else it is sampled on the\n input's.\n\n Missing values (such as NaNs) are ignored.\n\n If the window does not contain any values (e.g., all the values are\n missing, or the window does not contain any sampling), outputs missing\n values.\n\nExample:\n ```python\n >>> a = tp.event_set(\n ... timestamps=[0, 1, 2, 5, 6, 7],\n ... features={\"value\": [np.nan, 1, 5, 10, 15, 20]},\n ... )\n\n >>> b = a.moving_sum(tp.duration.seconds(4))\n >>> b\n indexes: ...\n (6 events):\n timestamps: [0. 1. 2. 5. 6. 7.]\n 'value': [ 0. 1. 6. 15. 25. 45.]\n ...\n\n ```\n\n See [`EventSet.moving_count()`][temporian.EventSet.moving_count] for\n examples of moving window operations with external sampling and indices.\n\nArgs:\n window_length: Sliding window's length.\n sampling: Timestamps to sample the sliding window's value at. If not\n provided, timestamps in the input are used.\n\nReturns:\n EventSet containing the moving sum of each feature in the input.", "source": "github_repos"} +{"code": "def _clone_sequential_model(model, clone_function, input_tensors=None):\n if not isinstance(model, Sequential):\n raise ValueError(f'Expected `model` argument to be a `Sequential` model instance. Received: model={model}')\n if not callable(clone_function):\n raise ValueError(f'Expected `clone_function` argument to be a callable. Received: clone_function={clone_function}')\n new_layers = [clone_function(layer) for layer in model.layers]\n if isinstance(model._layers[0], InputLayer):\n ref_input_layer = model._layers[0]\n input_name = ref_input_layer.name\n input_batch_shape = ref_input_layer.batch_shape\n input_dtype = ref_input_layer._dtype\n else:\n input_name = None\n input_dtype = None\n input_batch_shape = None\n if input_tensors is not None:\n if isinstance(input_tensors, (list, tuple)):\n if len(input_tensors) != 1:\n raise ValueError('Argument `input_tensors` must contain a single tensor.')\n input_tensors = input_tensors[0]\n if not isinstance(input_tensors, backend.KerasTensor):\n raise ValueError(f'Argument `input_tensors` must be a KerasTensor. Received invalid value: input_tensors={input_tensors}')\n inputs = Input(tensor=input_tensors, name=input_name)\n new_layers = [inputs] + new_layers\n elif input_batch_shape is not None:\n inputs = Input(batch_shape=input_batch_shape, dtype=input_dtype, name=input_name)\n new_layers = [inputs] + new_layers\n cloned_model = Sequential(new_layers, name=model.name, trainable=model.trainable)\n if model.compiled:\n compiled_config = model.get_compile_config()\n cloned_model.compile_from_config(compiled_config)\n return cloned_model", "docstring": "Clone a `Sequential` model instance.\n\n Model cloning is similar to calling a model on new inputs,\n except that it creates new layers (and thus new weights) instead\n of sharing the weights of the existing layers.\n\nArgs:\n model: Instance of `Sequential`.\n input_tensors: optional list of input tensors\n to build the model upon. If not provided,\n placeholders will be created.\n clone_function: callable to be applied on non-input layers in the model.\n By default, it clones the layer (without copying the weights).\n\nReturns:\n An instance of `Sequential` reproducing the behavior\n of the original model, on top of new inputs tensors,\n using newly instantiated weights.", "source": "github_repos"} +{"code": "def get(self, key=None, indices=None, name=None):\n if key is None:\n return self._popitem(indices=indices, name=name)\n else:\n return self._pop(key, indices=indices, name=name)", "docstring": "If the key is provided, the associated (key, value) is returned from the staging area.\n\n If the key is not in the staging area, this method will block until\n the associated (key, value) is inserted.\n If no key is provided and the staging area is ordered,\n the (key, value) with the smallest key will be returned.\n Otherwise, a random (key, value) will be returned.\n\n If the staging area is empty when this operation executes,\n it will block until there is an element to dequeue.\n\nArgs:\n key: Key associated with the required data (Optional)\n indices: Partial list of tensors to retrieve (optional).\n A list of integer or string indices.\n String indices are only valid if the Staging Area\n has names associated with it.\n name: A name for the operation (optional)\n\nReturns:\n The created op", "source": "github_repos"} +{"code": "def objects_ids_and_slot_variables_and_paths(graph_view, skip_slot_variables=False):\n trackable_objects, node_paths = graph_view.breadth_first_traversal()\n object_names = object_identity.ObjectIdentityDictionary()\n for obj, path in node_paths.items():\n object_names[obj] = trackable_utils.object_path_to_string(path)\n node_ids = object_identity.ObjectIdentityDictionary()\n for node_id, node in enumerate(trackable_objects):\n node_ids[node] = node_id\n if skip_slot_variables:\n slot_variables = object_identity.ObjectIdentityDictionary()\n else:\n slot_variables = serialize_slot_variables(trackable_objects=trackable_objects, node_ids=node_ids, object_names=object_names)\n return (trackable_objects, node_paths, node_ids, slot_variables, object_names)", "docstring": "Traverse the object graph and list all accessible objects.\n\n Looks for `Trackable` objects which are dependencies of\n `root_trackable`. Includes slot variables only if the variable they are\n slotting for and the optimizer are dependencies of `root_trackable`\n (i.e. if they would be saved with a checkpoint).\n\nArgs:\n graph_view: A GraphView object.\n skip_slot_variables: If True does not return trackables for slot variable.\n Default False.\n\nReturns:\n A tuple of (trackable objects, paths from root for each object,\n object -> node id, slot variables, object_names)", "source": "github_repos"} +{"code": "def __init__(self, num_packs=1):\n if num_packs < 0:\n raise ValueError('HierarchicalCopy requires num_packs >= 0, but {} is specified'.format(num_packs))\n super(HierarchicalCopyAllReduce, self).__init__(all_reduce_alg='hierarchical_copy', num_packs=num_packs)", "docstring": "Initializes the object.\n\nArgs:\n num_packs: a non-negative integer. The number of packs to split values\n into. If zero, no packing will be done.\n\nRaises:\n ValueError if `num_packs` is negative.", "source": "github_repos"} +{"code": "def _annotate_variable_ops(func, graph_def):\n ph_shape_map = {}\n for ph, var in zip(func.graph.internal_captures, func.variables):\n ph_shape_map[ph.name] = var.shape\n name_to_node = {node.name: node for node in graph_def.node}\n for node in graph_def.node:\n if node.op == 'ReadVariableOp' or node.op == 'ResourceGather':\n node_ = node\n while name_to_node[node_.input[0]].op == 'Identity':\n node_ = name_to_node[node_.input[0]]\n ph_name = node_.input[0] + ':0'\n if ph_name in ph_shape_map:\n shape = ph_shape_map[ph_name]\n node.attr['_shape'].shape.CopyFrom(shape.as_proto())\n else:\n raise RuntimeError('Not found in the function captures: {}'.format(ph_name))", "docstring": "Annotates variable operations with custom `_shape` attribute.\n\n This is required for the converters and shape inference. The graph\n definition is modified in-place.\n\nArgs:\n func: Function represented by the graph definition.\n graph_def: Graph definition to be annotated in-place.\n\nRaises:\n RuntimeError: if some shapes cannot be annotated.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **kwargs) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:\n if 'next_sentence_label' in kwargs:\n warnings.warn('The `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.', FutureWarning)\n labels = kwargs.pop('next_sentence_label')\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.nezha(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n pooled_output = outputs[1]\n seq_relationship_scores = self.cls(pooled_output)\n next_sentence_loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))\n if not return_dict:\n output = (seq_relationship_scores,) + outputs[2:]\n return (next_sentence_loss,) + output if next_sentence_loss is not None else output\n return NextSentencePredictorOutput(loss=next_sentence_loss, logits=seq_relationship_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair\n (see `input_ids` docstring). Indices should be in `[0, 1]`:\n\n - 0 indicates sequence B is a continuation of sequence A,\n - 1 indicates sequence B is a random sequence.\n\nReturns:\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, NezhaForNextSentencePrediction\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"sijunhe/nezha-cn-base\")\n >>> model = NezhaForNextSentencePrediction.from_pretrained(\"sijunhe/nezha-cn-base\")\n\n >>> prompt = \"In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced.\"\n >>> next_sentence = \"The sky is blue due to the shorter wavelength of blue light.\"\n >>> encoding = tokenizer(prompt, next_sentence, return_tensors=\"pt\")\n\n >>> outputs = model(**encoding, labels=torch.LongTensor([1]))\n >>> logits = outputs.logits\n >>> assert logits[0, 0] < logits[0, 1] # next sentence was random\n ```", "source": "github_repos"} +{"code": "def GetIamPolicy(self, request, global_params=None):\n config = self.GetMethodConfig('GetIamPolicy')\n return self._RunMethod(config, request, global_params=global_params)", "docstring": "Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.\n\nArgs:\n request: (BigqueryTablesGetIamPolicyRequest) input message\n global_params: (StandardQueryParameters, default: None) global arguments\n\nReturns:\n (Policy) The response message.", "source": "github_repos"} +{"code": "def __init__(self, debug_dump, config):\n self._debug_dump = debug_dump\n self._evaluator = evaluator.ExpressionEvaluator(self._debug_dump)\n self._tensor_filters = {}\n self._build_argument_parsers(config)\n config.set_callback('graph_recursion_depth', self._build_argument_parsers)", "docstring": "DebugAnalyzer constructor.\n\nArgs:\n debug_dump: A DebugDumpDir object.\n config: A `cli_config.CLIConfig` object that carries user-facing\n configurations.", "source": "github_repos"} +{"code": "def preface_inference(f):\n\n @functools.wraps(f)\n def wrapper(self, *args, **kwargs):\n self._preface_inference()\n return f(self, *args, **kwargs)\n return wrapper", "docstring": "Wraps given function with things to run before every inference call.\n\nArgs:\n f: The method of `EnergyInference` to wrap.\n\nReturns:\n wrapper: The wrapped function.", "source": "github_repos"} +{"code": "def set_clang_compiler_path(environ_cp):\n default_clang_path = '/usr/lib/llvm-18/bin/clang'\n if not os.path.exists(default_clang_path):\n default_clang_path = '/usr/lib/llvm-17/bin/clang'\n if not os.path.exists(default_clang_path):\n default_clang_path = '/usr/lib/llvm-16/bin/clang'\n if not os.path.exists(default_clang_path):\n default_clang_path = shutil.which('clang') or ''\n clang_compiler_path = prompt_loop_or_load_from_env(environ_cp, var_name='CLANG_COMPILER_PATH', var_default=default_clang_path, ask_for_var='Please specify the path to clang executable.', check_success=os.path.exists, resolve_symlinks=True, error_msg='Invalid clang path. %s cannot be found. Note that TensorFlow now requires clang to compile. You may override this behavior by setting TF_NEED_CLANG=0')\n write_action_env_to_bazelrc('CLANG_COMPILER_PATH', clang_compiler_path)\n write_to_bazelrc('build --repo_env=CC=%s' % clang_compiler_path)\n write_to_bazelrc('build --repo_env=BAZEL_COMPILER=%s' % clang_compiler_path)\n return clang_compiler_path", "docstring": "Set CLANG_COMPILER_PATH and environment variables.\n\n Loop over user prompts for clang path until receiving a valid response.\n Default is used if no input is given. Set CLANG_COMPILER_PATH and write\n environment variables CC and BAZEL_COMPILER to .bazelrc.\n\nArgs:\n environ_cp: (Dict) copy of the os.environ.\n\nReturns:\n string value for clang_compiler_path.", "source": "github_repos"} +{"code": "def post_process_video_grounding(self, logits, video_durations):\n start, end = (round(logits.tolist()[0][0] * video_durations, 1), round(logits.tolist()[0][1] * video_durations, 1))\n return (start, end)", "docstring": "Compute the time of the video.\n\nArgs:\n logits (`torch.Tensor`):\n The logits output of TvpForVideoGrounding.\n video_durations (`float`):\n The video's duration.\n\nReturns:\n start (`float`):\n The start time of the video.\n end (`float`):\n The end time of the video.", "source": "github_repos"} +{"code": "def period_from_dict(period: Dict[int, List[int]]) -> dateslib.PeriodTensor:\n amount = period['frequency']\n period_type = period_pb2.PeriodType.Name(period['type'])\n return dateslib.PeriodTensor(amount, dateslib.PeriodType[period_type])", "docstring": "Utility to convert a dictionary of periods to a PeriodTensor.\n\nArgs:\n period: A dictionary with keys \"type\" (which corresponds to the proto type\n of the period (see `period_pb2.Period`)) and \"frequency\".\n\nReturns:\n An instance of the `PeriodTensor`.", "source": "github_repos"} +{"code": "def convert_padding(padding, expected_length=4):\n explicit_paddings = []\n if padding == 'EXPLICIT':\n raise ValueError(\"'EXPLICIT' is not a valid value for `padding`. To use explicit padding, `padding` must be a list.\")\n if isinstance(padding, (list, tuple)):\n for i, dim_paddings in enumerate(padding):\n if not isinstance(dim_paddings, (list, tuple)):\n raise ValueError(f'When `padding` is a list, each element of `padding` must be a list/tuple of size 2. Received: padding={padding} with element at index {i} of type {type(dim_paddings)}')\n if len(dim_paddings) != 2:\n raise ValueError(f'When `padding` is a list, each element of `padding` must be a list/tuple of size 2. Received: padding={padding} with element at index {i} of size {len(dim_paddings)}')\n explicit_paddings.extend(dim_paddings)\n if len(padding) != expected_length:\n raise ValueError(f'When padding is a list, it must be of size {expected_length}. Received: padding={padding} of size {len(padding)}')\n padding = 'EXPLICIT'\n return (padding, explicit_paddings)", "docstring": "Converts Python padding to C++ padding for ops which take EXPLICIT padding.\n\nArgs:\n padding: the `padding` argument for a Python op which supports EXPLICIT\n padding.\n expected_length: Expected number of entries in the padding list when\n explicit padding is used.\n\nReturns:\n (padding, explicit_paddings) pair, which should be passed as attributes to a\n C++ op.\n\nRaises:\n ValueError: If padding is invalid.", "source": "github_repos"} +{"code": "def _create_saveables_by_attribute_name(self, saveable_factories):\n named_saveables = {}\n existing_restore_ops = []\n created_compat_names = set()\n for serialized_tensor in self.object_proto.attributes:\n if context.executing_eagerly():\n existing_op = None\n else:\n existing_op = self._checkpoint.restore_ops_by_name.get(serialized_tensor.checkpoint_key, None)\n if existing_op is not None:\n existing_restore_ops.append(existing_op)\n continue\n if any((serialized_tensor.name.startswith(name) for name in created_compat_names)):\n continue\n saveables_cache = self._checkpoint.saveables_cache\n if saveables_cache is None:\n saveable = None\n else:\n saveable_list = saveables_cache.get(self.trackable, {}).get(serialized_tensor.name, (None,))\n if len(saveable_list) == 1:\n saveable, = saveable_list\n else:\n saveable = None\n if saveable is not None:\n if serialized_tensor.checkpoint_key not in saveable.name:\n saveable = None\n del saveables_cache[self.trackable]\n if saveable is None:\n saveable = _get_saveable_from_factory(saveable_factories, serialized_tensor, created_compat_names)\n if saveable is None:\n self._checkpoint.unused_attributes.setdefault(self._proto_id, []).append(serialized_tensor.name)\n continue\n if saveables_cache is not None:\n saveables_cache.setdefault(self.trackable, {})[serialized_tensor.name] = [saveable]\n named_saveables[serialized_tensor.checkpoint_key] = saveable\n return (existing_restore_ops, named_saveables)", "docstring": "Creates or caches SaveableObjects by matching the attribute names.\n\n The attribute name keys in the `saveable_factories` is used to find the\n corresponding attribute in the object proto. Attributes contain checkpoint\n keys which are passed to the factory function to generate the\n SaveableObject.\n\nArgs:\n saveable_factories: a dict mapping attribute name to a callable factory\n function that produces a SaveableObject.\n\nReturns:\n A tuple of (\n existing_restore_ops: list,\n named_saveables: dict)", "source": "github_repos"} +{"code": "def decode_csv(records, record_defaults, field_delim=',', use_quote_delim=True, name=None, na_value='', select_cols=None):\n return decode_csv_v2(records, record_defaults, field_delim, use_quote_delim, na_value, select_cols, name)", "docstring": "Convert CSV records to tensors. Each column maps to one tensor.\n\n RFC 4180 format is expected for the CSV records.\n (https://tools.ietf.org/html/rfc4180)\n Note that we allow leading and trailing spaces with int or float field.\n\nArgs:\n records: A `Tensor` of type `string`.\n Each string is a record/row in the csv and all records should have\n the same format.\n record_defaults: A list of `Tensor` objects with specific types.\n Acceptable types are `float32`, `float64`, `int32`, `int64`, `string`.\n One tensor per column of the input record, with either a\n scalar default value for that column or an empty vector if the column is\n required.\n field_delim: An optional `string`. Defaults to `\",\"`.\n char delimiter to separate fields in a record.\n use_quote_delim: An optional `bool`. Defaults to `True`.\n If false, treats double quotation marks as regular\n characters inside of the string fields (ignoring RFC 4180, Section 2,\n Bullet 5).\n name: A name for the operation (optional).\n na_value: Additional string to recognize as NA/NaN.\n select_cols: Optional sorted list of column indices to select. If specified,\n only this subset of columns will be parsed and returned.\n\nReturns:\n A list of `Tensor` objects. Has the same type as `record_defaults`.\n Each tensor will have the same shape as records.\n\nRaises:\n ValueError: If any of the arguments is malformed.", "source": "github_repos"} +{"code": "def ragged_tensor_to_string(rt, summarize=None):\n if summarize is not None and summarize != -1 and (not (isinstance(summarize, int) and summarize > 0)):\n raise ValueError('Expected summarize to be -1 or a positive int, got %r' % summarize)\n with ops.name_scope(None, 'AsString', [rt]):\n rt = ragged_tensor.convert_to_tensor_or_ragged_tensor(rt)\n if rt.shape.rank is None:\n raise ValueError('RaggedTensor to_string requires that rt.shape.rank is not None.')\n if rt.dtype == dtypes.string:\n escaped = string_ops.regex_replace(rt.flat_values, \"(['\\\\\\\\])\", '\\\\\\\\\\\\1')\n str_t = rt.with_flat_values(\"'\" + escaped + \"'\")\n else:\n str_t = rt.with_flat_values(string_ops.as_string(rt.flat_values))\n return _ragged_tensor_to_string(str_t, summarize)", "docstring": "Returns a scalar string tensor with the contents of a RaggedTensor.\n\n Requires that `rt.shape.rank` is not `None`.\n\n Note: this converts the entire `RaggedTensor` into a single string scalar.\n If you want to convert individual elements, use `tf.strings.as_string(rt)`.\n\n >>> rt1 = tf.ragged.constant([[1, 2, 3], [4, 5]])\n >>> ragged_tensor_to_string(rt1).numpy()\n b'[[1, 2, 3], [4, 5]]'\n\n >>> rt2 = tf.ragged.constant([[['a'], ['b', 'c']], [['d', 'e', 'f'], []]])\n >>> ragged_tensor_to_string(rt2).numpy()\n b\"[[['a'], ['b', 'c']], [['d', 'e', 'f'], []]]\"\n\n >>> rt3 = tf.ragged.constant([[1], [2, 3, 4, 5, 6], [], [], [7], [8, 9]])\n >>> ragged_tensor_to_string(rt3, summarize=2).numpy()\n b'[[1], [2, 3, ..., 5, 6], ..., [7], [8, 9]]'\n\nArgs:\n rt: The RaggedTensor that should be converted to a string.\n summarize: If specified, then only the first and last `summarize` elements\n within each dimension are included in the string. If `-1` or `None`, then\n all elements are included.", "source": "github_repos"} +{"code": "def _GetMaxSizeFromNestedMaximumIterations(value, while_ctxt):\n value_name = value.name\n curr_ctxt = ops.get_default_graph()._get_control_flow_context()\n curr_ctxt_name = curr_ctxt.name if curr_ctxt is not None else ''\n max_size = constant_op.constant(1)\n while while_ctxt not in (None, curr_ctxt):\n max_iter = while_ctxt.maximum_iterations\n if max_iter is None:\n raise ValueError(\"Cannot create a gradient accumulator for tensor '%s' inside XLA while_loop because maximum_iterations was not passed to the tf.while_loop call ('%s').\" % (value_name, while_ctxt.name))\n max_iter_ctxt = max_iter.op._get_control_flow_context()\n if util.IsContainingContext(curr_ctxt, max_iter_ctxt):\n max_size *= max_iter\n else:\n const_max_iter = tensor_util.constant_value(max_iter)\n if const_max_iter is None:\n raise ValueError(\"Cannot create a gradient accumulator for tensor '%s' inside XLA while_loop. maximum_iterations tensor '%s' for while_loop context '%s' must be statically known (e.g. a constant value or known shape dimension), or be defined at or outside the while loop context '%s' (currently defined in '%s').\" % (value_name, max_iter.name, while_ctxt.name, curr_ctxt_name, max_iter_ctxt.name))\n max_size *= const_max_iter\n while_ctxt = util.GetContainingWhileContext(while_ctxt.outer_context, stop_ctxt=curr_ctxt)\n return max_size", "docstring": "Calculate a max_size for use by stack ops inside an XLA while_loop.\n\nArgs:\n value: The value inside the while_loop forward context. Used for printing\n error messages.\n while_ctxt: The forward context inside which value resides. This does not\n always match the value's immediate context, as `value` may be inside e.g.\n a cond context inside the while_loop.\n\nReturns:\n A tensor containing the `max_size` to feed to a Stack initializer.\n\nRaises:\n ValueError: If `value` is nested inside a `while_loop` that either\n lacks a `maximum_iterations` parameter, or the `maximum_iterations`\n parameter:\n\n - is inside a `while_loop` that is a parent of the calling context, and\n - cannot be evaluated at graph build time to a constant.", "source": "github_repos"} +{"code": "def _IsFlag(argument):\n return _IsSingleCharFlag(argument) or _IsMultiCharFlag(argument)", "docstring": "Determines if the argument is a flag argument.\n\n If it starts with a hyphen and isn't a negative number, it's a flag.\n\nArgs:\n argument: A command line argument that may or may not be a flag.\n\nReturns:\n A boolean indicating whether the argument is a flag.", "source": "github_repos"} +{"code": "def get_resource(self, uri: str) -> Optional[message.Message]:\n for collection in (self.structure_definitions, self.search_parameters, self.code_systems, self.value_sets):\n resource = collection.get(uri)\n if resource is not None:\n return resource\n return None", "docstring": "Retrieves a protocol buffer representation of the given resource.\n\nArgs:\n uri: The URI of the resource to retrieve.\n\nReturns:\n Protocol buffer for the resource or `None` if the `uri` can not be found.", "source": "github_repos"} +{"code": "def __init__(self, name, shape, dtype, variable_list, partitions):\n if not isinstance(variable_list, (list, tuple)):\n raise TypeError('variable_list is not a list or tuple: %s' % variable_list)\n if not isinstance(partitions, (list, tuple)):\n raise TypeError('partitions is not a list or tuple: %s' % partitions)\n if not all((p >= 1 for p in partitions)):\n raise ValueError('partition values must be positive: %s' % partitions)\n if not variable_list:\n raise ValueError('variable_list may not be empty')\n for v in variable_list:\n if not all((v._get_save_slice_info() is not None for v in variable_list)):\n raise ValueError('All variables must have a save_slice_info available: %s' % [v.name for v in variable_list])\n if len(shape) != len(partitions):\n raise ValueError('len(shape) != len(partitions): %s vs. %s' % (shape, partitions))\n if v._get_save_slice_info().full_shape != shape:\n raise ValueError(\"All variables' full shapes must match shape: %s; but full shapes were: %s\" % (shape, str([v._get_save_slice_info().full_shape])))\n self._variable_list = sorted(variable_list, key=lambda v: v._get_save_slice_info().var_offset)\n self._name = name\n self._shape = shape\n self._dtype = dtype\n self._partitions = partitions\n self._as_tensor = None", "docstring": "Creates a new partitioned variable wrapper.\n\n Variables passed via the variable_list must contain a save_slice_info\n field. Concatenation and iteration is in lexicographic order according\n to the var_offset property of the save_slice_info.\n\nArgs:\n name: String. Overall name of the variables.\n shape: List of integers. Overall shape of the variables.\n dtype: Type of the variables.\n variable_list: List of `Variable` that comprise this partitioned variable.\n partitions: List of integers. Number of partitions for each dimension.\n\nRaises:\n TypeError: If `variable_list` is not a list of `Variable` objects, or\n `partitions` is not a list.\n ValueError: If `variable_list` is empty, or the `Variable` shape\n information does not match `shape`, or `partitions` has invalid values.", "source": "github_repos"} +{"code": "def serialized_tensors_to_saveable_cache(serialized_tensors):\n saveables_cache = object_identity.ObjectIdentityWeakKeyDictionary()\n for obj, tensor_dict in serialized_tensors.items():\n if not tensor_dict:\n continue\n if isinstance(obj, SaveableCompatibilityConverter):\n trackable_obj = obj.obj\n saveables_cache[trackable_obj] = {}\n for saveable in obj.saveables:\n local_name = trackable_utils.extract_local_name(saveable.name)\n saveables_cache[trackable_obj][local_name] = [saveable]\n continue\n specs = []\n local_names = []\n prefix = saveable_compat.get_saveable_name(obj) or ''\n for checkpoint_key, maybe_tensor in tensor_dict.items():\n if not isinstance(maybe_tensor, dict):\n maybe_tensor = {'': maybe_tensor}\n for slice_spec, tensor in maybe_tensor.items():\n if isinstance(tensor, saveable_object.SaveSpec):\n specs.append(tensor)\n else:\n specs.append(saveable_object.SaveSpec(tensor, slice_spec, checkpoint_key))\n local_names.append(trackable_utils.extract_local_name(checkpoint_key, prefix))\n object_name = trackable_utils.extract_object_name(next(iter(tensor_dict.keys())))\n saveables_cache[obj] = {trackable_utils.SERIALIZE_TO_TENSORS_NAME: [TrackableSaveable(obj, specs, object_name, local_names=local_names, prefix=prefix)]}\n return saveables_cache", "docstring": "Converts a tensor dict to a SaveableObject cache.\n\nArgs:\n serialized_tensors: Map from Trackable to a tensor dict. The tensor dict\n maps checkpoint key (-> slice_spec) -> Tensor\n\nReturns:\n A dict mapping Trackable objects to a map from local savable name to\n SaveableObject.", "source": "github_repos"} +{"code": "def sequence_like(instance, args):\n if _is_mutable_mapping(instance):\n result = dict(zip(_tf_core_sorted(instance), args))\n instance_type = type(instance)\n if instance_type == _collections.defaultdict:\n d = _collections.defaultdict(instance.default_factory)\n else:\n d = instance_type()\n for key in instance:\n d[key] = result[key]\n return d\n elif _is_mapping(instance):\n result = dict(zip(_tf_core_sorted(instance), args))\n instance_type = type(instance)\n if not getattr(instance_type, '__supported_by_tf_nest__', False):\n tf_logging.log_first_n(tf_logging.WARN, 'Mapping types may not work well with tf.nest. Prefer using MutableMapping for {}'.format(instance_type), 1)\n try:\n return instance_type(((key, result[key]) for key in instance))\n except TypeError as err:\n raise TypeError('Error creating an object of type {} like {}. Note that it must accept a single positional argument representing an iterable of key-value pairs, in addition to self. Cause: {}'.format(type(instance), instance, err))\n elif _is_mapping_view(instance):\n return list(args)\n elif is_namedtuple(instance) or _is_attrs(instance):\n if isinstance(instance, _wrapt.ObjectProxy):\n instance_type = type(instance.__wrapped__)\n else:\n instance_type = type(instance)\n return instance_type(*args)\n elif _is_composite_tensor(instance):\n assert len(args) == 1\n spec = instance._type_spec\n return spec._from_components(args[0])\n elif _is_type_spec(instance):\n assert len(args) == 1\n return instance._from_components(args[0])\n elif isinstance(instance, range):\n return sequence_like(list(instance), args)\n elif isinstance(instance, _wrapt.ObjectProxy):\n return type(instance)(sequence_like(instance.__wrapped__, args))\n elif isinstance(instance, CustomNestProtocol):\n metadata = instance.__tf_flatten__()[0]\n return instance.__tf_unflatten__(metadata, tuple(args))\n else:\n return type(instance)(args)", "docstring": "Converts the sequence `args` to the same type as `instance`.\n\nArgs:\n instance: an instance of `tuple`, `list`, `namedtuple`, `dict`,\n `collections.OrderedDict`, or `composite_tensor.Composite_Tensor` or\n `type_spec.TypeSpec`.\n args: items to be converted to the `instance` type.\n\nReturns:\n `args` with the type of `instance`.", "source": "github_repos"} +{"code": "def seek(self, offset=None, whence=0, position=None):\n self._preread_check()\n if offset is None and position is None:\n raise TypeError('seek(): offset argument required')\n if offset is not None and position is not None:\n raise TypeError('seek(): offset and position may not be set simultaneously.')\n if position is not None:\n offset = position\n if whence == 0:\n pass\n elif whence == 1:\n offset += self.tell()\n elif whence == 2:\n offset += self.size()\n else:\n raise errors.InvalidArgumentError(None, None, 'Invalid whence argument: {}. Valid values are 0, 1, or 2.'.format(whence))\n self._read_buf.seek(offset)", "docstring": "Seeks to the offset in the file.\n\nArgs:\n offset: The byte count relative to the whence argument.\n whence: Valid values for whence are:\n 0: start of the file (default)\n 1: relative to the current position of the file\n 2: relative to the end of file. `offset` is usually negative.", "source": "github_repos"} +{"code": "def __init__(self, do_lower_case=False, never_split=None, normalize_text=True, trim_whitespace=False):\n self.do_lower_case = do_lower_case\n self.never_split = never_split if never_split is not None else []\n self.normalize_text = normalize_text\n self.trim_whitespace = trim_whitespace\n try:\n import rhoknp\n except ImportError:\n raise ImportError('You need to install rhoknp to use JumanppTokenizer. See https://github.com/ku-nlp/rhoknp for installation.')\n self.juman = rhoknp.Jumanpp()", "docstring": "Constructs a JumanppTokenizer.\n\nArgs:\n **do_lower_case**: (*optional*) boolean (default True)\n Whether to lowercase the input.\n **never_split**: (*optional*) list of str\n Kept for backward compatibility purposes. Now implemented directly at the base class level (see\n [`PreTrainedTokenizer.tokenize`]) List of tokens not to split.\n **normalize_text**: (*optional*) boolean (default True)\n Whether to apply unicode normalization to text before tokenization.\n **trim_whitespace**: (*optional*) boolean (default False)\n Whether to trim all whitespace, tab, newline from tokens.", "source": "github_repos"} +{"code": "def Decrement(self, key):\n with self._lock:\n if _IsHashable(key):\n if key in self._d:\n if self._d[key] > 1:\n self._d[key] -= 1\n else:\n del self._d[key]\n else:\n try:\n i = self._unhashable_items.index(key)\n if self._unhashable_counts[i] > 1:\n self._unhashable_counts[i] -= 1\n else:\n del self._unhashable_counts[i]\n del self._unhashable_items[i]\n except ValueError:\n pass", "docstring": "Atomically decrement a count by 1. Expunge the item if the count is 0.\n\n If the item is not present, has no effect.\n\nArgs:\n key: the key being counted.", "source": "github_repos"} +{"code": "def _compute_linear_scaling_rope_parameters(config: Optional[PretrainedConfig]=None, device: Optional['torch.device']=None, seq_len: Optional[int]=None, **rope_kwargs) -> tuple['torch.Tensor', float]:\n if config is not None and len(rope_kwargs) > 0:\n raise ValueError(f'Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in `_compute_linear_scaling_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}')\n if len(rope_kwargs) > 0:\n factor = rope_kwargs['factor']\n elif config is not None:\n factor = config.rope_scaling['factor']\n inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)\n inv_freq /= factor\n return (inv_freq, attention_factor)", "docstring": "Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev\n\nArgs:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length. Unused for this type of RoPE.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n\nReturns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).", "source": "github_repos"} +{"code": "def nl_to_sql_query(input_statement: str) -> str:\n api_key = os.getenv('GOOGLE_API_KEY')\n if api_key is None:\n raise RuntimeError('Environment variable GOOGLE_API_KEY is not set.')\n table_map_prompt, table_map = get_table_map_prompt()\n model = ChatGoogleGenerativeAI(model='gemini-pro')\n select_dataset_model = get_invocation_steps(DEFINED_PROMPTS['select_dataset'], model)\n generate_sql_model = get_invocation_steps(DEFINED_PROMPTS['generate_sql'], model)\n select_dataset_res = select_dataset_model.invoke({'question': input_statement, 'table_map': table_map_prompt})\n dataset_key = select_dataset_res.split(':')[-1].strip()\n dataset_metadata = table_map[dataset_key]\n generate_sql_res = generate_sql_model.invoke({'question': input_statement, 'table': dataset_metadata['uri'], 'columns': dataset_metadata['columns'], 'few_shot_examples': few_shots, 'dims': dataset_metadata['dims'], 'latitude_dim': dataset_metadata['latitude_dim'], 'latitude_range': dataset_metadata['latitude_range'], 'longitude_dim': dataset_metadata['longitude_dim'], 'longitude_range': dataset_metadata['longitude_range']})\n sql_query = generate_sql_res[11:-1]\n return sql_query", "docstring": "Convert a natural language query to SQL.\n\n Parameters:\n - input_statement (str): The natural language query.\n\nReturns:\n - str: The generated SQL query.", "source": "github_repos"} +{"code": "def _pyval_find_struct_keys_and_depth(pyval, keys):\n if isinstance(pyval, dict):\n keys.update(pyval.keys())\n return 0\n elif isinstance(pyval, (list, tuple)):\n depth = None\n for child in pyval:\n child_depth = _pyval_find_struct_keys_and_depth(child, keys)\n if child_depth is not None:\n if depth is None:\n depth = child_depth + 1\n elif depth != child_depth + 1:\n raise ValueError('Inconsistent depth of dictionaries')\n return depth\n else:\n return None", "docstring": "Finds the keys & depth of nested dictionaries in `pyval`.\n\nArgs:\n pyval: A nested structure of lists, tuples, and dictionaries.\n keys: (output parameter) A set, which will be updated with any keys that are\n found in the nested dictionaries.\n\nReturns:\n The nesting depth of dictionaries in `pyval`, or `None` if `pyval` does\n not contain any dictionaries.\n\nRaises:\n ValueError: If dictionaries have inconsistent depth.", "source": "github_repos"} +{"code": "def _maybe_stacked(self, cache, inp):\n if inp in cache:\n return cache[inp]\n if not self.op_is_inside_loop(inp.op):\n return False\n op = inp.op\n output = False\n if op.type in ['OnesLike', 'Shape', 'Rank', 'ShapeN', 'ZerosLike', 'TensorArrayV3', 'TensorArraySizeV3']:\n output = False\n elif _is_stateful_pfor_op(op):\n output = True\n elif op.type == 'Exit':\n output = True\n else:\n for t in op.inputs:\n if self._maybe_stacked(cache, t):\n output = True\n break\n cache[inp] = output\n return output", "docstring": "Heuristic to figure out if the converting inp leads to a stacked value.\n\nArgs:\n cache: map from Tensor to boolean indicating stacked/unstacked.\n inp: input Tensor.\n\nReturns:\n True if `inp` could get stacked. If the function returns False, the\n converted value should be guaranteed to be unstacked. If returning True,\n it may or may not be stacked.", "source": "github_repos"} +{"code": "def _get_scopes(state, names: Sequence[str], ctx) -> Sequence[abstract.InterpreterClass | abstract.InterpreterFunction]:\n scopes = []\n for name in names:\n prev = scopes[-1] if scopes else None\n if not prev:\n try:\n _, var = ctx.vm.load_global(state, name)\n except KeyError:\n break\n elif isinstance(prev, abstract.InterpreterClass):\n if name in prev.members:\n var = prev.members[name]\n else:\n break\n else:\n assert isinstance(prev, abstract.InterpreterFunction)\n if prev.last_frame and name in prev.last_frame.f_locals.pyval:\n var = prev.last_frame.f_locals.pyval[name]\n else:\n break\n try:\n scopes.append(abstract_utils.get_atomic_value(var, (abstract.InterpreterClass, abstract.InterpreterFunction)))\n except abstract_utils.ConversionError:\n break\n return scopes", "docstring": "Gets the class or function objects for a sequence of nested scope names.\n\n For example, if the code under analysis is:\n class Foo:\n def f(self):\n def g(): ...\n then when called with ['Foo', 'f', 'g'], this method returns\n [InterpreterClass(Foo), InterpreterFunction(f), InterpreterFunction(g)].\n\nArgs:\n state: The current state.\n names: A sequence of names for consecutive nested scopes in the module under\n analysis. Must start with a module-level name.\n ctx: The current context.\n\nReturns:\n The class or function object corresponding to each name in 'names'.", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.Tensor, original_hidden_states: Optional[torch.Tensor]=None, layer_idx: Optional[int]=None, attention_mask: Optional[torch.Tensor]=None, causal_mask: Optional[torch.Tensor]=None, past_key_value: Optional[ZambaHybridDynamicCache]=None, output_attentions: Optional[bool]=False, use_cache: Optional[bool]=False, cache_position: Optional[torch.LongTensor]=None, transformer_hidden_states: Optional[torch.Tensor]=None, **kwargs) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n residual = hidden_states\n hidden_states = hidden_states + transformer_hidden_states if transformer_hidden_states is not None else hidden_states\n hidden_states = self.input_layernorm(hidden_states)\n hidden_states = self.mamba(hidden_states=hidden_states, cache_params=past_key_value, attention_mask=attention_mask)\n self_attn_weights = None\n hidden_states = residual + hidden_states\n outputs = (hidden_states,)\n if output_attentions:\n outputs += (self_attn_weights,)\n if use_cache:\n outputs += (past_key_value,)\n return outputs", "docstring": "Args:\n hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\n attention_mask (`torch.FloatTensor`, *optional*): attention mask of size\n `(batch, sequence_length)` where padding elements are indicated by 0.\n past_key_value (`ZambaHybridDynamicCache`, *optional*): cached past key and value projection states\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding\n (see `past_key_values`).\n cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):\n Indices depicting the position of the input sequence tokens in the sequence.", "source": "github_repos"} +{"code": "def _process_new(self, feed_item):\n creative = {'advertiserId': feed_item.get(FieldMap.ADVERTISER_ID, None), 'name': feed_item.get(FieldMap.CREATIVE_NAME, None), 'active': True}\n self._associate_third_party_urls(feed_item, creative)\n self._associate_click_tags(feed_item, creative)\n if feed_item.get(FieldMap.CREATIVE_TYPE, None) == 'VIDEO':\n creative['type'] = 'INSTREAM_VIDEO'\n for association in feed_item.get('associations', []):\n identifier = self.creative_asset_dao.get_identifier(association, self._creative_asset_feed)\n creative['creativeAssets'] = [{'assetIdentifier': identifier, 'role': 'PARENT_VIDEO'}]\n del creative['active']\n elif feed_item.get(FieldMap.CREATIVE_TYPE, None) == 'DISPLAY':\n creative['type'] = 'DISPLAY'\n if feed_item.get(FieldMap.CREATIVE_WIDTH, None) and feed_item.get(FieldMap.CREATIVE_HEIGHT, None):\n creative['size'] = {'kind': 'dfareporting#size', 'width': feed_item.get(FieldMap.CREATIVE_WIDTH, None), 'height': feed_item.get(FieldMap.CREATIVE_HEIGHT, None)}\n for association in feed_item.get('associations', []):\n identifier = self.creative_asset_dao.get_identifier(association, self._creative_asset_feed)\n creative['creativeAssets'] = [{'assetIdentifier': identifier, 'role': 'PRIMARY'}]\n if feed_item.get(FieldMap.CREATIVE_BACKUP_ASSET_ID, None) and feed_item.get(FieldMap.CREATIVE_BACKUP_ASSET_ID, None) != '':\n backup_identifier = self.creative_asset_dao.get_backup_identifier(association, self._creative_asset_feed)\n creative['backupImageReportingLabel'] = feed_item.get(FieldMap.CREATIVE_BACKUP_NAME, None)\n backup_features = feed_item.get(FieldMap.BACKUP_IMAGE_FEATURES, None)\n if backup_features != None or backup_features != '':\n features = backup_features.split(',')\n creative['backupImageFeatures'] = features\n creative['backupImageTargetWindow'] = {'targetWindowOption': feed_item.get(FieldMap.BACKUP_IMAGE_TARGET_WINDOW_OPTION, None), 'customHtml': feed_item.get(FieldMap.BACKUP_IMAGE_CUSTOM_HTML, None)}\n lp = self.landing_page_dao.get(feed_item, column_name=FieldMap.BACKUP_IMAGE_CLICK_THROUGH_LANDING_PAGE_ID)\n creative['backupImageClickThroughUrl'] = {'landingPageId': feed_item.get(FieldMap.BACKUP_IMAGE_CLICK_THROUGH_LANDING_PAGE_ID) if not lp else lp['id']}\n creative['creativeAssets'].append({'assetIdentifier': backup_identifier, 'role': 'BACKUP_IMAGE'})\n del creative['active']\n else:\n raise Exception('Only video and display are supported at the moment!')\n return creative", "docstring": "Creates a new creative DCM object from a feed item representing an creative from the Bulkdozer feed.\n\n This function simply creates the object to be inserted later by the BaseDAO\n object.\n\nArgs:\n feed_item: Feed item representing the creative from the Bulkdozer feed.\n\nReturns:\n A creative object ready to be inserted in DCM through the API.", "source": "github_repos"} +{"code": "def _event_set_dict_to_event_set(input: Dict[str, Any], schema: Schema, timestamp_key: str) -> Iterator[FeatureItemWithIdx]:\n timestamps = input[timestamp_key]\n if not isinstance(timestamps, np.ndarray) or timestamps.dtype.type != np.float64:\n raise ValueError(f'Timestamp with value {timestamps} is expected to be np.float64 numpy array, but has dtype {type(timestamps)} instead.')\n index = []\n for index_schema in schema.indexes:\n expected_type = tp_dtype_to_py_type(index_schema.dtype)\n src_value = input[index_schema.name]\n if not isinstance(src_value, expected_type):\n raise ValueError(f'Index \"{index_schema.name}\" with value \"{src_value}\" is expected to be of type {expected_type} (since the Temporian dtype is {index_schema.dtype}) but type {type(src_value)} was found.')\n index.append(src_value)\n index_tuple = tuple(index)\n for feature_idx, feature_schema in enumerate(schema.features):\n expected_dtype = tp_dtype_to_np_dtype(feature_schema.dtype)\n src_value = input[feature_schema.name]\n if not isinstance(src_value, np.ndarray) or src_value.dtype.type != expected_dtype:\n if isinstance(src_value, np.ndarray):\n effective_type = src_value.dtype.type\n else:\n effective_type = type(src_value)\n raise ValueError(f'Feature \"{feature_schema.name}\" with value \"{src_value}\" is expected to be a numpy array with dtype {expected_dtype} (since the Temporian dtype is {feature_schema.dtype}) but numpy dtype {effective_type} was found.')\n yield (index_tuple, (timestamps, src_value, feature_idx))", "docstring": "Converts a `indexedEvents` event-set into an internal event-set.\n\nExample:\n Input\n Schema\n features=[(\"f1\", DType.INT64), (\"f2\", DType.STRING)]\n indexes=[(\"i1\", DType.INT64), (\"i2\", DType.STRING)]\n\n input (one item):\n {\n \"timestamp\": [100.0, 101.0, 102.0],\n \"f1\": [1, 2, 3],\n \"f2\": [b\"a\", b\"b\", b\"c\"],\n \"i1\": 10,\n \"i2\": b\"x\",\n }\n\n Output (two items)\n # Feature \"f1\"\n ((10, b\"x\"), 0, ([100.0, 101.0, 102.0], [1, 2, 3])\n # Feature \"f2\"\n ((10, b\"x\"), 1, ([100.0, 101.0, 102.0], [b\"a\", b\"b\", b\"c\"])", "source": "github_repos"} +{"code": "def GetContainingWhileContext(ctxt, stop_ctxt=None):\n while ctxt:\n if ctxt.IsWhileContext() or ctxt == stop_ctxt:\n return ctxt\n ctxt = ctxt.outer_context\n return None", "docstring": "Returns the first ancestor WhileContext of `ctxt`.\n\n Returns `ctxt` if `ctxt` is a WhileContext, or None if `ctxt` is not in a\n while loop.\n\nArgs:\n ctxt: ControlFlowContext\n stop_ctxt: ControlFlowContext, optional. If provided, the search will end\n if it sees stop_ctxt.\n\nReturns:\n `ctxt` if `ctxt` is a WhileContext, the most nested WhileContext containing\n `ctxt`, or None if `ctxt` is not in a while loop. If `stop_ctxt` is not\n `None`, this returns `ctxt` if it matches `stop_ctxt` in its traversal.", "source": "github_repos"} +{"code": "def on_train_batch_end(self, batch, logs=None):\n if self._should_call_train_batch_hooks:\n self._call_batch_hook(ModeKeys.TRAIN, 'end', batch, logs=logs)", "docstring": "Calls the `on_train_batch_end` methods of its callbacks.\n\nArgs:\n batch: Integer, index of batch within the current epoch.\n logs: Dict. Aggregated metric results up until this batch.", "source": "github_repos"} +{"code": "def _dbParamsMom01(self):\n db_grad = [[]] * 10\n db_out = [[]] * 10\n db_grad[0] = [0.00096264342, 0.17914793, 0.93945462, 0.41396621, 0.53037018, 0.93197989, 0.78648776, 0.50036013, 0.55345792, 0.96722615]\n db_out[0] = [-9.6264346e-05, -0.017914793, -0.093945466, -0.041396622, -0.053037018, -0.093197994, -0.078648776, -0.050036013, -0.055345792, -0.096722618]\n db_grad[1] = [0.17075552, 0.88821375, 0.20873757, 0.25236958, 0.57578111, 0.15312378, 0.5513742, 0.94687688, 0.16012503, 0.22159521]\n db_out[1] = [-0.017181443, -0.10852765, -0.12421377, -0.070773244, -0.11591884, -0.11783017, -0.14165108, -0.14972731, -0.076892875, -0.1285544]\n db_grad[2] = [0.35077485, 0.47304362, 0.44412705, 0.44368884, 0.078527533, 0.81223965, 0.31168157, 0.43203235, 0.16792089, 0.24644311]\n db_out[2] = [-0.053967446, -0.1648933, -0.1716533, -0.1180798, -0.13005978, -0.20151734, -0.17911947, -0.20289968, -0.095839672, -0.15638189]\n db_grad[3] = [0.9694621, 0.75035888, 0.28171822, 0.83813518, 0.53807181, 0.3728098, 0.81454384, 0.03848977, 0.89759839, 0.93665648]\n db_out[3] = [-0.15459226, -0.24556576, -0.20456907, -0.20662397, -0.18528105, -0.24716705, -0.2643207, -0.21206589, -0.18749419, -0.2528303]\n db_grad[4] = [0.38578293, 0.8536852, 0.88722926, 0.66276771, 0.13678469, 0.94036359, 0.69107032, 0.81897682, 0.5433259, 0.67860287]\n db_out[4] = [-0.20323303, -0.33900154, -0.29658359, -0.28175515, -0.20448165, -0.34576839, -0.34194785, -0.29488021, -0.25099224, -0.33033544]\n db_grad[5] = [0.27885768, 0.76100707, 0.24625534, 0.81354135, 0.18959245, 0.48038563, 0.84163809, 0.41172323, 0.83259648, 0.44941229]\n db_out[5] = [-0.23598288, -0.42444581, -0.33041057, -0.3706224, -0.22536094, -0.40366709, -0.43387437, -0.34433398, -0.34060168, -0.38302717]\n db_grad[6] = [0.27233034, 0.056316052, 0.5039115, 0.24105175, 0.35697976, 0.75913221, 0.73577434, 0.16014607, 0.57500273, 0.071136251]\n db_out[6] = [-0.26649091, -0.43862185, -0.38418442, -0.40361428, -0.26314685, -0.48537019, -0.51664448, -0.36529395, -0.40706289, -0.39540997]\n db_grad[7] = [0.58697265, 0.2494842, 0.08106143, 0.39954534, 0.15892942, 0.12683646, 0.74053431, 0.16033, 0.66625422, 0.73515922]\n db_out[7] = [-0.32823896, -0.46498787, -0.39766794, -0.446868, -0.28281838, -0.50622416, -0.59897494, -0.38342294, -0.48033443, -0.47016418]\n db_grad[8] = [0.8215279, 0.41994119, 0.95172721, 0.68000203, 0.79439718, 0.43384039, 0.55561525, 0.22567581, 0.93331909, 0.29438227]\n db_out[8] = [-0.41656655, -0.50961858, -0.49418902, -0.51919359, -0.36422527, -0.55169362, -0.6627695, -0.40780342, -0.58099347, -0.50707781]\n db_grad[9] = [0.68297005, 0.67758518, 0.1748755, 0.13266537, 0.70697063, 0.055731893, 0.68593478, 0.50580865, 0.12602448, 0.093537711]\n db_out[9] = [-0.49369633, -0.58184016, -0.52132869, -0.5396927, -0.44306302, -0.56181377, -0.73774242, -0.46082234, -0.60366184, -0.52012295]\n return (db_grad, db_out)", "docstring": "Return dist-belief momentum values.\n\n Return values been generated from the dist-belief momentum unittest,\n running with a learning rate of 0.1 and a momentum of 0.1.\n\n These values record how a parameter vector of size 10, initialized with 0.0,\n gets updated with 10 consecutive momentum steps. It uses random gradients.\n\nReturns:\n db_grad: The gradients to apply\n db_out: The parameters after the momentum update.", "source": "github_repos"} +{"code": "def _create_simple_tf1_gather_model(self, input_type: dtypes.DType, use_variable_for_filter=False) -> Tuple[core.Tensor, core.Tensor]:\n in_placeholder = array_ops.placeholder(input_type, shape=6)\n filters = np.random.randn(128, 32).astype(np.float32)\n if use_variable_for_filter:\n filters = variables.Variable(filters)\n output_tensor = array_ops.gather_v2(filters, in_placeholder)\n return (in_placeholder, output_tensor)", "docstring": "Creates a basic gather model.\n\n This is intended to be used for TF1 (graph mode) tests.\n\nArgs:\n input_type: type of the input index tensor for gather operation.\n use_variable_for_filter: Setting this to `True` makes the filter for the\n gather operation a `tf.Variable`.\n\nReturns:\n in_placeholder: Input tensor placeholder.\n output_tensor: The resulting tensor of the gather operation.", "source": "github_repos"} +{"code": "def temp_pubsub_emulator(project_id='apache-beam-testing'):\n with PubSubContainer(project=project_id) as pubsub_container:\n publisher = pubsub_v1.PublisherClient()\n random_front_charactor = random.choice(string.ascii_lowercase)\n topic_id = f'{random_front_charactor}{uuid.uuid4().hex[:8]}'\n topic_name_to_create = f'projects/{pubsub_container.project}/topics/{topic_id}'\n created_topic_object = publisher.create_topic(name=topic_name_to_create)\n yield created_topic_object.name", "docstring": "Context manager to provide a temporary Pub/Sub emulator for testing.\n\n This function uses 'testcontainers' to spin up a Google Cloud SDK\n container running the Pub/Sub emulator. It yields the emulator host\n string (e.g., \"localhost:xxxxx\") that can be used to configure Pub/Sub\n clients.\n\n The Docker container is automatically managed and torn down when the\n context manager exits.\n\nArgs:\n project_id (str): The GCP project ID to be used by the emulator.\n This doesn't need to be a real project for the emulator.\n\nYields:\n str: The host and port for the Pub/Sub emulator (e.g., \"localhost:xxxx\").\n This will be the address to point your Pub/Sub client to.\n\nRaises:\n Exception: If the container fails to start or the emulator isn't ready.", "source": "github_repos"} +{"code": "def load_file_to_base64_str(f_path):\n path = abs_path(f_path)\n with io.open(path, 'rb') as f:\n f_bytes = f.read()\n base64_str = base64.b64encode(f_bytes).decode('utf-8')\n return base64_str", "docstring": "Loads the content of a file into a base64 string.\n\nArgs:\n f_path: full path to the file including the file name.\n\nReturns:\n A base64 string representing the content of the file in utf-8 encoding.", "source": "github_repos"} +{"code": "def read(self, save_path, options=None):\n if options and options.experimental_enable_async_checkpoint:\n self._checkpoint_options = options\n if self._checkpoint_options and self._checkpoint_options.experimental_enable_async_checkpoint:\n if context.executing_eagerly():\n return self._async_checkpointer().read(save_path, options)\n else:\n logging.warning('Saving async checkpoint in graph mode is currently not supported; switching to regular sync checkpoint instead.')\n start_time = time.time()\n if isinstance(save_path, os.PathLike):\n save_path = os.fspath(save_path)\n options = options or checkpoint_options.CheckpointOptions()\n result = self._saver.restore(save_path=save_path, options=options)\n metrics.AddCheckpointReadDuration(api_label=_CHECKPOINT_V2, microseconds=_get_duration_microseconds(start_time, time.time()))\n return result", "docstring": "Reads a training checkpoint written with `write`.\n\n Reads this `Checkpoint` and any objects it depends on.\n\n This method is just like `restore()` but does not expect the `save_counter`\n variable in the checkpoint. It only restores the objects that the checkpoint\n already depends on.\n\n The method is primarily intended for use by higher level checkpoint\n management utilities that use `write()` instead of `save()` and have their\n own mechanisms to number and track checkpoints.\n\n Example usage:\n\n ```python\n # Create a checkpoint with write()\n ckpt = tf.train.Checkpoint(v=tf.Variable(1.))\n path = ckpt.write('/tmp/my_checkpoint')\n\n # Later, load the checkpoint with read()\n # With restore() assert_consumed() would have failed.\n checkpoint.read(path).assert_consumed()\n\n # You can also pass options to read(). For example this\n # runs the IO ops on the localhost:\n options = tf.train.CheckpointOptions(\n experimental_io_device=\"/job:localhost\")\n checkpoint.read(path, options=options)\n ```\n\nArgs:\n save_path: The path to the checkpoint as returned by `write`.\n options: Optional `tf.train.CheckpointOptions` object.\n\nReturns:\n A load status object, which can be used to make assertions about the\n status of a checkpoint restoration. See `restore` for details.", "source": "github_repos"} +{"code": "def _parse_tensor_value(tensor_proto, return_list=False):\n try:\n ndarray = tensor_util.MakeNdarray(tensor_proto)\n return ndarray.tolist() if return_list else ndarray\n except TypeError:\n return None", "docstring": "Helper method for reading a tensor value from a tensor proto.\n\n The rationale for the distinction between `True` and `False value of\n `return_list` is as follows:\n - `return_list=True` is used for TensorDebugMode values other than\n FULL_TENSOR, e.g., CONCISE_HEALTH, SHAPE and FULL_HEATLH. Under\n those modes, the value is guaranteed (by contract) to be a 1D float64\n tensor.\n - `return_list=False` is used for the FULL_HEALTH TensorDebugMode\n specifically. Instead, we use `numpy.ndarray` to maximally preserve\n the shape, dtype and value information regarding the underlying tensor\n value. Under that mode, we don't use a python list to represent the\n tensor value because that can lead to loss of information (e.g., both\n float16 and float32 dtypes get mapped to Python floats).\n\nArgs:\n tensor_proto: The TensorProto instance from which the tensor value will be\n loaded.\n return_list: Whether the return value will be a nested Python list that\n comes out from `numpy.ndarray.tolist()`.\n\nReturns:\n If parsing is successful, the tensor value as a `numpy.ndarray` or the\n nested Python list converted from it.\n If parsing fails, `None`.", "source": "github_repos"} +{"code": "def _spectrum_to_circulant_1d(self, spectrum, shape, dtype):\n spectrum = _to_complex(spectrum)\n spectrum_shape = self._shape_to_spectrum_shape(shape)\n domain_dimension = spectrum_shape[-1]\n if not domain_dimension:\n return array_ops.zeros(shape, dtype)\n matrix_rows = []\n for m in range(domain_dimension):\n x = np.zeros([domain_dimension])\n x[m] = 1.0\n fft_x = fft_ops.fft(math_ops.cast(x, spectrum.dtype))\n h_convolve_x = fft_ops.ifft(spectrum * fft_x)\n matrix_rows.append(h_convolve_x)\n matrix = array_ops_stack.stack(matrix_rows, axis=-1)\n return math_ops.cast(matrix, dtype)", "docstring": "Creates a circulant matrix from a spectrum.\n\n Intentionally done in an explicit yet inefficient way. This provides a\n cross check to the main code that uses fancy reshapes.\n\nArgs:\n spectrum: Float or complex `Tensor`.\n shape: Python list. Desired shape of returned matrix.\n dtype: Type to cast the returned matrix to.\n\nReturns:\n Circulant (batch) matrix of desired `dtype`.", "source": "github_repos"} +{"code": "def _orthogonal_kernel(self, ksize, cin, cout):\n if cin > cout:\n raise ValueError(f'The number of input channels (cin={cin}) cannot exceed the number of output channels (cout={cout}).')\n orth = self._orthogonal_matrix(cout)[0:cin, :]\n if ksize == 1:\n return array_ops.expand_dims(array_ops.expand_dims(orth, 0), 0)\n p = self._block_orth(self._symmetric_projection(cout), self._symmetric_projection(cout))\n for _ in range(ksize - 2):\n temp = self._block_orth(self._symmetric_projection(cout), self._symmetric_projection(cout))\n p = self._matrix_conv(p, temp)\n for i in range(ksize):\n for j in range(ksize):\n p[i, j] = math_ops.matmul(orth, p[i, j])\n return self._dict_to_tensor(p, ksize, ksize)", "docstring": "Construct orthogonal kernel for convolution.\n\nArgs:\n ksize: Kernel size.\n cin: Number of input channels.\n cout: Number of output channels.\n\nReturns:\n An [ksize, ksize, cin, cout] orthogonal kernel.\n\nRaises:\n ValueError: If cin > cout.", "source": "github_repos"} +{"code": "def get(self):\n with warnings.catch_warnings(record=False):\n warnings.simplefilter('ignore')\n return np.nanquantile(self._queue, self._q)", "docstring": "Calculates and returns the specified quantile of the current sliding\n window.\n\nReturns:\n float: The specified quantile of the values in the current sliding window.\n Returns NaN if the window is empty.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, cache_position: Optional[torch.LongTensor]=None, logits_to_keep: Union[int, torch.Tensor]=0, **kwargs: Unpack[KwargsForCausalLM]) -> CausalLMOutputWithPast:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n outputs: BaseModelOutputWithPast = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, **kwargs)\n hidden_states = outputs.last_hidden_state\n slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep\n logits = self.lm_head(hidden_states[:, slice_indices, :])\n logits = logits * self.logit_scale\n loss = None\n if labels is not None:\n loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)\n return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\nExample:\n ```python\n >> from transformers import AutoTokenizer, Cohere2ForCausalLM\n\n >> model = Cohere2ForCausalLM.from_pretrained(\"Cohere2ForAI/c4ai-command-r-v01\")\n >> tokenizer = AutoTokenizer.from_pretrained(\"Cohere2ForAI/c4ai-command-r-v01\")\n\n >> prompt = \"Hey, are you conscious? Can you talk to me?\"\n >> inputs = tokenizer(prompt, return_tensors=\"pt\")\n\n >> # Generate\n >> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"Hey, are you conscious? Can you talk to me?\\nI'm not conscious, but I can talk to you.\"\n ```", "source": "github_repos"} +{"code": "def _get_bounding_box(self, box: 'torch.Tensor') -> Dict[str, int]:\n if self.framework != 'pt':\n raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.')\n xmin, ymin, xmax, ymax = box.int().tolist()\n bbox = {'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax}\n return bbox", "docstring": "Turns list [xmin, xmax, ymin, ymax] into dict { \"xmin\": xmin, ... }\n\nArgs:\n box (`torch.Tensor`): Tensor containing the coordinates in corners format.\n\nReturns:\n bbox (`Dict[str, int]`): Dict containing the coordinates in corners format.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, cache_position: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, logits_to_keep: Union[int, torch.Tensor]=0, **kwargs) -> Union[Tuple, MoshiCausalLMOutputWithPast]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position)\n hidden_states = outputs[0]\n if labels is None and (not is_torchdynamo_compiling()):\n logger.warning_once('Starting from v4.46, the `logits` model output will have the same type as the model (except at train time, where it will always be FP32)')\n slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep\n logits = self.lm_head(hidden_states[:, slice_indices, :])\n loss = None\n if labels is not None:\n logits = logits.float()\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n shift_logits = shift_logits.view(-1, self.config.vocab_size)\n shift_labels = shift_labels.view(-1)\n shift_labels = shift_labels.to(shift_logits.device)\n loss = self.loss_function(shift_logits, shift_labels, vocab_size=self.config.vocab_size, **kwargs)\n if not return_dict:\n output = (logits, hidden_states) + outputs[1:]\n return (loss,) + output if loss is not None else output\n return MoshiCausalLMOutputWithPast(loss=loss, logits=logits, last_hidden_state=hidden_states, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, MoshiForCausalLM\n\n >>> model = MoshiForCausalLM.from_pretrained(\"kmhf/hf-moshiko\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"kmhf/hf-moshiko\")\n\n >>> prompt = \"What is your favorite condiment?\"\n >>> inputs = tokenizer(prompt, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"What is your favorite condiment?\"\n ```", "source": "github_repos"} +{"code": "def triu(x, k=0):\n if any_symbolic_tensors((x,)):\n return Triu(k=k).symbolic_call(x)\n return backend.numpy.triu(x, k=k)", "docstring": "Return upper triangle of a tensor.\n\n For tensors with `ndim` exceeding 2, `triu` will apply to the\n final two axes.\n\nArgs:\n x: Input tensor.\n k: Diagonal below which to zero elements. Defaults to `0`. the\n main diagonal. `k < 0` is below it, and `k > 0` is above it.\n\nReturns:\n Upper triangle of `x`, of same shape and data type as `x`.", "source": "github_repos"} +{"code": "def moments(x, axes, shift=None, name=None, keep_dims=None, keepdims=None):\n keep_dims = deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)\n if keep_dims is None:\n keep_dims = False\n with ops.name_scope(name, 'moments', [x, axes]):\n y = math_ops.cast(x, dtypes.float32) if x.dtype == dtypes.float16 else x\n mean = math_ops.reduce_mean(y, axes, keepdims=True, name='mean')\n variance = math_ops.reduce_mean(math_ops.squared_difference(y, array_ops.stop_gradient(mean)), axes, keepdims=True, name='variance')\n if not keep_dims:\n mean = array_ops.squeeze(mean, axes)\n variance = array_ops.squeeze(variance, axes)\n if x.dtype == dtypes.float16:\n return (math_ops.cast(mean, dtypes.float16), math_ops.cast(variance, dtypes.float16))\n else:\n return (mean, variance)", "docstring": "Calculate the mean and variance of `x`.\n\n The mean and variance are calculated by aggregating the contents of `x`\n across `axes`. If `x` is 1-D and `axes = [0]` this is just the mean\n and variance of a vector.\n\n Note: shift is currently not used; the true mean is computed and used.\n\n When using these moments for batch normalization (see\n `tf.nn.batch_normalization`):\n\n * for so-called \"global normalization\", used with convolutional filters with\n shape `[batch, height, width, depth]`, pass `axes=[0, 1, 2]`.\n * for simple batch normalization pass `axes=[0]` (batch only).\n\nArgs:\n x: A `Tensor`.\n axes: Array of ints. Axes along which to compute mean and\n variance.\n shift: Not used in the current implementation\n name: Name used to scope the operations that compute the moments.\n keep_dims: produce moments with the same dimensionality as the input.\n keepdims: Alias to keep_dims.\n\nReturns:\n Two `Tensor` objects: `mean` and `variance`.", "source": "github_repos"} +{"code": "def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):\n vision_data = {}\n if image_sizes is not None:\n images_kwargs = LlavaNextProcessorKwargs._defaults.get('images_kwargs', {})\n images_kwargs.update(kwargs)\n size = images_kwargs.get('size', None) or self.image_processor.size\n size = (size['shortest_edge'], size['shortest_edge']) if 'shortest_edge' in size else (min(size['height'], size['width']), min(size['height'], size['width']))\n processed_height, processed_width = size\n batch_num_image_tokens = []\n num_image_patches = [1] * len(image_sizes)\n for image_size in image_sizes:\n orig_height, orig_width = image_size\n num_image_tokens = self._get_number_of_features(orig_height, orig_width, processed_height, processed_width)\n if self.vision_feature_select_strategy == 'default':\n num_image_tokens -= 1\n batch_num_image_tokens.append(num_image_tokens)\n vision_data.update({'num_image_tokens': batch_num_image_tokens, 'num_image_patches': num_image_patches})\n return MultiModalData(**vision_data)", "docstring": "Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.\n\nArgs:\n image_sizes (List[List[str]], *optional*):\n The input sizes formatted as (height, width) per each image.\n video_sizes (List[List[str]], *optional*):\n The input sizes formatted as (num_frames, height, width) per each video.\n audio_lengths (List[int], *optional*):\n The input length formatted as per each audio.\n\nReturns:\n Dict[str, List[int]]: A dictionary mapping each modality (\"image\", \"video\", \"audio\")\n to a list containing the number of placeholder tokens required. If the model doesn't accept\n a certain modality or no input sizes are provided, the dict value is set to an empty list.", "source": "github_repos"} +{"code": "def _VerifyValues(self, input_sizes=None, filter_sizes=None, out_backprop_sizes=None, strides=None, dilations=None, padding=None, data_format_src='NHWC', data_format_dst='NHWC', expected=None):\n total_size_1 = np.prod(input_sizes)\n total_size_2 = np.prod(out_backprop_sizes)\n x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(input_sizes)\n x2 = np.arange(1, total_size_2 + 1, dtype=np.float32).reshape(out_backprop_sizes)\n strides = [1] + strides + [1]\n if dilations is not None:\n dilations = [1] + dilations + [1]\n expected = np.reshape(expected, filter_sizes)\n x1 = test_utils.ConvertBetweenDataFormats(x1, data_format_src, data_format_dst)\n x2 = test_utils.ConvertBetweenDataFormats(x2, data_format_src, data_format_dst)\n input_sizes = test_utils.PermuteDimsBetweenDataFormats(input_sizes, data_format_src, data_format_dst)\n out_backprop_sizes = test_utils.PermuteDimsBetweenDataFormats(out_backprop_sizes, data_format_src, data_format_dst)\n strides = test_utils.PermuteDimsBetweenDataFormats(strides, data_format_src, data_format_dst)\n if dilations is not None:\n dilations = test_utils.PermuteDimsBetweenDataFormats(dilations, data_format_src, data_format_dst)\n with self.session() as sess:\n t1 = array_ops.placeholder(dtypes.float32, shape=input_sizes)\n t2 = array_ops.placeholder(dtypes.float32, shape=out_backprop_sizes)\n with self.test_scope():\n tensor = gen_nn_ops.conv2d_backprop_filter(input=t1, filter_sizes=filter_sizes, out_backprop=t2, strides=strides, dilations=dilations, padding=padding, data_format=data_format_dst)\n value = sess.run(tensor, {t1: x1, t2: x2})\n self.assertAllEqual(filter_sizes, value.shape)\n self.assertAllClose(expected, value, 0.001)", "docstring": "Tests that gen_nn_ops.conv2d_backprop_filter produces the right output.\n\nArgs:\n input_sizes: Input tensor dimensions in\n [batch, input_rows, input_cols, input_depth].\n filter_sizes: Filter tensor dimensions in\n [kernel_rows, kernel_cols, input_depth, output_depth].\n out_backprop_sizes: Output gradients tensor dimensions.\n strides: Stride.\n dilations: Dilations.\n padding: Padding type.\n data_format_src: Data format input is in.\n data_format_dst: Data format verification will run and input is converted\n to.\n expected: Expected output.", "source": "github_repos"} +{"code": "def interruptible(inner: Iterable[_T] | Iterator[_T]) -> Iterator[_T]:\n interrupted = threading.Event()\n\n def handler(unused_signum, unused_frame):\n if interrupted.is_set():\n raise KeyboardInterrupt\n interrupted.set()\n previous_handler = signal.signal(signal.SIGINT, handler)\n try:\n for i in inner:\n yield i\n if interrupted.is_set():\n return\n finally:\n signal.signal(signal.SIGINT, previous_handler)", "docstring": "Catch KeyboardInterrupts to end the loop without raising an Exception.\n\n While this iterator is running, the first SIGINT (e.g. from interrupting\n the colab runtime, or pressing Ctrl+C ) will not raise an exception but\n instead end the loop after the current iteration.\n A second SIGINT will raise a KeyboardInterrupt Exception as usual.\n\nExample:\n ```python\n for i in interruptible(range(10)):\n print(i)\n time.sleep(3)\n ```\n\nArgs:\n inner: arbitrary iterable or iterator\n\nYields:\n elements from inner", "source": "github_repos"} +{"code": "def sharded_filename(filename_tensor: tensor_lib.Tensor, shard: int, num_shards: tensor_lib.Tensor) -> tensor_lib.Tensor:\n return gen_io_ops.sharded_filename(filename_tensor, shard, num_shards)", "docstring": "Append sharding information to a filename.\n\nArgs:\n filename_tensor: A string tensor.\n shard: Integer. The shard for the filename.\n num_shards: An int Tensor for the number of shards.\n\nReturns:\n A string tensor.", "source": "github_repos"} +{"code": "def compute_one_match(self, var, other_type, name=None, match_all_views=True, keep_all_views=False, alias_map=None) -> MatchResult:\n bad_matches = []\n good_matches = _UniqueMatches(self._node, keep_all_views)\n views = abstract_utils.get_views([var], self._node)\n skip_future = None\n while True:\n try:\n view = views.send(skip_future)\n except StopIteration:\n break\n subst = datatypes.AliasingDict(aliases=alias_map)\n subst = self.match_var_against_type(var, other_type, subst, view)\n if subst is None:\n if self._node.CanHaveCombination(list(view.values())):\n bad_matches.append(BadMatch(view=view, expected=self._get_bad_type(name, other_type), actual=var))\n skip_future = False\n else:\n skip_future = True\n good_matches.insert(view, subst)\n good_matches = [GoodMatch(view, datatypes.HashableDict(subst)) for view, subst in good_matches.unique()]\n if good_matches and (not match_all_views) or not bad_matches:\n success = True\n elif good_matches:\n bad_matches = [m for m in bad_matches if self._node.HasCombination(list(m.view.values()))]\n success = not bad_matches\n else:\n success = False\n return MatchResult(success=success, good_matches=good_matches, bad_matches=bad_matches)", "docstring": "Match a Variable against a type.\n\nArgs:\n var: A cfg.Variable, containing instances.\n other_type: An instance of BaseValue.\n name: Optionally, the variable name.\n match_all_views: If True, every possible match must succeed for the\n overall match to be considered a success. Otherwise, the overall match\n succeeds as long as at least one possible match succeeds.\n keep_all_views: If True, avoid optimizations that discard views.\n alias_map: Optionally, a datatypes.UnionFind, which stores all the type\n renaming information, mapping of type parameter name to its\n representative.\n\nReturns:\n The match result.", "source": "github_repos"} +{"code": "def __init__(self, use_resource_alias: bool=False, value_set_codes_table: Optional[str]=None, value_set_codes_definitions: Optional[fhir_package.FhirPackageManager]=None) -> None:\n self._use_resource_alias = use_resource_alias\n self._value_set_codes_table = value_set_codes_table\n self._value_set_codes_definitions = value_set_codes_definitions", "docstring": "Creates a SparkSqlInterpreter.\n\nArgs:\n use_resource_alias: Determines whether it is necessary to call the\n resource table directly through an alias.\n value_set_codes_table: The name of the database table containing value set\n code definitions. Used when building SQL for memberOf expressions. If\n given, value set definitions needed for memberOf expressions will be\n retrieved from this table if they can not be found in\n `value_set_codes_definitions`. If neither this nor\n `value_set_codes_definitions` is given, no memberOf SQL will be\n generated.\n value_set_codes_definitions: A package manager containing value set\n definitions which can be used to build SQL for memberOf expressions.\n These value set definitions can be consulted in favor of using an\n external `value_set_codes_table`. If neither this nor\n `value_set_codes_definitions` is given, no memberOf SQL will be\n generated.", "source": "github_repos"} +{"code": "def as_str_any(value, encoding='utf-8'):\n if isinstance(value, bytes):\n return as_str(value, encoding=encoding)\n else:\n return str(value)", "docstring": "Converts input to `str` type.\n\n Uses `str(value)`, except for `bytes` typed inputs, which are converted\n using `as_str`.\n\nArgs:\n value: A object that can be converted to `str`.\n encoding: Encoding for `bytes` typed inputs.\n\nReturns:\n A `str` object.", "source": "github_repos"} +{"code": "def to(self, *args, **kwargs) -> 'BatchFeature':\n requires_backends(self, ['torch'])\n import torch\n new_data = {}\n device = kwargs.get('device')\n if device is None and len(args) > 0:\n arg = args[0]\n if is_torch_dtype(arg):\n pass\n elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):\n device = arg\n else:\n raise ValueError(f'Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.')\n\n def _to(elem):\n if torch.is_floating_point(elem):\n return elem.to(*args, **kwargs)\n if device is not None:\n return elem.to(device=device)\n return elem\n for k, v in self.items():\n if isinstance(v, list) and isinstance(v[0], list):\n new_v = []\n for elems in v:\n new_v.append([_to(elem) for elem in elems])\n new_data[k] = new_v\n elif isinstance(v, list):\n new_data[k] = [_to(elem) for elem in v]\n else:\n new_data[k] = _to(v)\n self.data = new_data\n return self", "docstring": "Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in\n different `dtypes` and sending the `BatchFeature` to a different `device`.\n\nArgs:\n args (`Tuple`):\n Will be passed to the `to(...)` function of the tensors.\n kwargs (`Dict`, *optional*):\n Will be passed to the `to(...)` function of the tensors.\n\nReturns:\n [`BatchFeature`]: The same instance after modification.", "source": "github_repos"} +{"code": "def _unshard_from_sc_to_cpu(stacked_table: tensor.Tensor, from_shard_layouts: Sequence[sparse_core_layout_pb2.SparseCoreTableLayout]) -> Sequence[tensor.Tensor]:\n logging.vlog(1, 'To unshuffle_from_sc_to_cpu on stacked_table.shape: %s', stacked_table[0].shape)\n ret_tensors = []\n for layout in from_shard_layouts:\n padded_table = tpu_embedding_v3_utils.unshuffle_from_sc_to_cpu(stacked_table[0], num_sparse_cores=layout.num_sparse_cores, offset_in_shard=layout.sparse_core_shard_row_offset, size_in_shard=layout.unsharded_padded_shape[0] // layout.num_sparse_cores, shard_rotation=layout.sparse_core_shard_rotation)\n orig_table = tpu_embedding_v3_utils.remove_padding_from_sc(padded_table, layout.unsharded_shape)\n logging.vlog(1, 'orig_tensors.shape[%s]: %s', layout.table_name, orig_table.shape)\n ret_tensors.append(orig_table)\n return ret_tensors", "docstring": "Undo the shard the feature tables into SparseCore stacked table.\n\nArgs:\n stacked_table: The value of a SparseCore stacked and sharded table.\n from_shard_layouts: The target layouts for the target hardware.\n\nReturns:\n The unsharded feature tables.", "source": "github_repos"} +{"code": "def get_metric(name, constructor, *args, **kwargs):\n metric = _registered_metrics.get(name)\n if metric is not None:\n return metric\n else:\n return constructor(name, *args, **kwargs)", "docstring": "Return an existing metric or create a new one for the given name.\n\nArgs:\n name: The name of the metric.\n constructor: A class to instantiate if a new metric is required.\n *args: Additional positional args to pass to the constructor.\n **kwargs: Keyword args for the constructor.\n\nReturns:\n The current metric registered to name, or a new one created by\n invoking constructor(name, *args, **kwargs).", "source": "github_repos"} +{"code": "def __init__(self, l1=0.0, l2=0.0, **kwargs):\n super(ActivityRegularization, self).__init__(activity_regularizer=regularizers.L1L2(l1=l1, l2=l2), **kwargs)\n self.supports_masking = True\n self.l1 = l1\n self.l2 = l2", "docstring": "Layer that applies an update to the cost function based input activity.\n\nArgs:\n l1: L1 regularization factor (positive float).\n l2: L2 regularization factor (positive float).\n\n Input shape:\n Arbitrary. Use the keyword argument `input_shape`\n (tuple of integers, does not include the samples axis)\n when using this layer as the first layer in a model.\n\n Output shape:\n Same shape as input.", "source": "github_repos"} +{"code": "def set_tensor(self, tensor_index, value):\n self._interpreter.SetTensor(tensor_index, value)", "docstring": "Sets the value of the input tensor.\n\n Note this copies data in `value`.\n\n If you want to avoid copying, you can use the `tensor()` function to get a\n numpy buffer pointing to the input buffer in the tflite interpreter.\n\nArgs:\n tensor_index: Tensor index of tensor to set. This value can be gotten from\n the 'index' field in get_input_details.\n value: Value of tensor to set.\n\nRaises:\n ValueError: If the interpreter could not set the tensor.", "source": "github_repos"} +{"code": "def __init__(self, model_name: str, columns: list[str], dimension: Optional[int], project: Optional[str]=None, location: Optional[str]=None, credentials: Optional[Credentials]=None, **kwargs):\n self.model_name = model_name\n self.project = project\n self.location = location\n self.credentials = credentials\n if dimension is not None and dimension not in (128, 256, 512, 1408):\n raise ValueError('dimension argument must be one of 128, 256, 512, or 1408')\n self.dimension = dimension\n super().__init__(columns=columns, **kwargs)", "docstring": "Embedding Config for Vertex AI Image Embedding models following\n https://cloud.google.com/vertex-ai/docs/generative-ai/embeddings/get-multimodal-embeddings # pylint: disable=line-too-long\n Image Embeddings are generated for a batch of images using the Vertex AI API.\n Embeddings are returned in a list for each image in the batch. This\n transform makes remote calls to the Vertex AI service and may incur costs\n for use.\n\nArgs:\n model_name: The name of the Vertex AI Multi-Modal Embedding model.\n columns: The columns containing the image to be embedded.\n dimension: The length of the embedding vector to generate. Must be one of\n 128, 256, 512, or 1408. If not set, Vertex AI's default value is 1408.\n project: The default GCP project for API calls.\n location: The default location for API calls.\n credentials: Custom credentials for API calls.\n Defaults to environment credentials.", "source": "github_repos"} +{"code": "def _get_details(self):\n detail_parts = [self._get_full_name(), self._error_message]\n return '\\n'.join(filter(None, detail_parts))", "docstring": "Gets the output for the detail section of the TestResultRecord.\n\nReturns:\n A string to set for a TestResultRecord's details.", "source": "github_repos"} +{"code": "def __enter__(self) -> str:\n if self._name is None and self._values is not None:\n raise ValueError('At least one of name (%s) and default_name (%s) must be provided.' % (self._name, self._default_name))\n g = get_default_graph()\n if self._values and (not g.building_function):\n g_from_inputs = _get_graph_from_inputs(self._values)\n if g_from_inputs is not g:\n g = g_from_inputs\n self._g_manager = g.as_default()\n self._g_manager.__enter__()\n else:\n self._g_manager = None\n else:\n self._g_manager = None\n try:\n self._name_scope = g.name_scope(self._name)\n return self._name_scope.__enter__()\n except:\n if self._g_manager is not None:\n self._g_manager.__exit__(*sys.exc_info())\n raise", "docstring": "Start the scope block.\n\nReturns:\n The scope name.\n\nRaises:\n ValueError: if neither `name` nor `default_name` is provided\n but `values` are.", "source": "github_repos"} +{"code": "def notnan(self: EventSetOrNode) -> EventSetOrNode:\n from temporian.core.operators.unary import notnan\n return notnan(self)", "docstring": "Returns boolean features, `False` in the NaN elements of an\n [`EventSet`][temporian.EventSet].\n\n Equivalent to `~evset.isnan(...)`.\n\n Note that for `int` and `bool` this will always be `True` since those types\n don't support NaNs. It only makes actual sense to use on `float` (or\n `tp.float32`) features.\n\n See also `evset.isnan()`.\n\nExample:\n ```python\n >>> a = tp.event_set(\n ... timestamps=[1, 2, 3],\n ... features={\"M\":[np.nan, 5., np.nan], \"N\": [-1, 0, 5]},\n ... )\n >>> b = a.notnan()\n >>> b\n indexes: ...\n 'M': [False True False]\n 'N': [ True True True]\n ...\n\n >>> # Filter only rows where \"M\" is not nan\n >>> a.filter(b[\"M\"])\n indexes: ...\n 'M': [5.]\n 'N': [0]\n ...\n\n ```\n\nReturns:\n EventSet with boolean features.", "source": "github_repos"} +{"code": "def _to_values_def(self, export_scope=None):\n values_def = control_flow_pb2.ValuesDef()\n values_def.values.extend([ops.strip_name_scope(v, export_scope) for v in sorted(self._values)])\n for k, v in self._external_values.items():\n k = ops.strip_name_scope(k, export_scope)\n values_def.external_values[k] = ops.strip_name_scope(v.name, export_scope)\n return values_def", "docstring": "Converts the values to a `ValuesDef` protocol buffer.\n\nArgs:\n export_scope: Optional `string`. Name scope to remove.\n\nReturns:\n A `ValuesDef` protocol buffer.", "source": "github_repos"} +{"code": "def __init__(self, source: SourceBase) -> None:\n super().__init__()\n self.source = source", "docstring": "Initializes a Read transform.\n\nArgs:\n source: Data source to read from.", "source": "github_repos"} +{"code": "def __init__(self, input_size: int, num_experts: int, top_k: int):\n super().__init__()\n self.num_experts = num_experts\n self.input_size = input_size\n self.top_k = top_k\n self.layer = nn.Linear(input_size, num_experts, bias=False)", "docstring": "Initialize the top-k gating mechanism.\n\nArgs:\n input_size (`int`):\n Size of the input.\n num_experts (`int`):\n Number of experts.\n top_k (`int`):\n Number of top experts to select.", "source": "github_repos"} +{"code": "def get_config(self, obj):\n try:\n shared_object_config = self._shared_objects_config[obj]\n except (TypeError, KeyError):\n return None\n shared_object_config.increment_ref_count()\n return shared_object_config", "docstring": "Gets a `SharedObjectConfig` if one has already been seen for `obj`.\n\nArgs:\n obj: The object for which to retrieve the `SharedObjectConfig`.\n\nReturns:\n The SharedObjectConfig for a given object, if already seen. Else,\n `None`.", "source": "github_repos"} +{"code": "def __init__(self, rate, seed=None, **kwargs):\n super().__init__(**kwargs)\n if not 0 <= rate <= 1:\n raise ValueError(f'Invalid value received for argument `rate`. Expected a float value between 0 and 1. Received: rate={rate}')\n self.rate = rate\n self.seed = seed\n if rate > 0:\n self.seed_generator = backend.random.SeedGenerator(seed)\n self.supports_masking = True\n self._build_at_init()", "docstring": "Apply multiplicative 1-centered Gaussian noise.\n\n As it is a regularization layer, it is only active at training time.\n\nArgs:\n rate: Float, drop probability (as with `Dropout`).\n The multiplicative noise will have\n standard deviation `sqrt(rate / (1 - rate))`.\n seed: Integer, optional random seed to enable deterministic behavior.\n\n Call arguments:\n inputs: Input tensor (of any rank).\n training: Python boolean indicating whether the layer should behave in\n training mode (adding dropout) or in inference mode (doing nothing).", "source": "github_repos"} +{"code": "def update_scores(self, scores: torch.FloatTensor, g_values: torch.FloatTensor) -> torch.FloatTensor:\n _, _, depth = g_values.shape\n probs = torch.softmax(scores, dim=1)\n for i in range(depth):\n g_values_at_depth = g_values[:, :, i]\n g_mass_at_depth = (g_values_at_depth * probs).sum(axis=1, keepdims=True)\n probs = probs * (1 + g_values_at_depth - g_mass_at_depth)\n log_probs = torch.log(probs)\n log_probs = torch.where(torch.isfinite(log_probs), log_probs, torch.finfo(log_probs.dtype).min)\n return log_probs", "docstring": "Updates scores using the g values.\n\n We assume that the scores are in the log space.\n\nArgs:\n scores (`torch.FloatTensor`): Scores (batch_size, vocab_size).\n g_values (`torch.FloatTensor`): G values (batch_size, vocab_size, depth).\n\nReturns:\n Updated scores (batch_size, vocab_size).", "source": "github_repos"} +{"code": "def symlink_force(target, link_name):\n try:\n os.symlink(target, link_name)\n except OSError as e:\n if e.errno == errno.EEXIST:\n os.remove(link_name)\n os.symlink(target, link_name)\n else:\n raise e", "docstring": "Force symlink, equivalent of 'ln -sf'.\n\nArgs:\n target: items to link to.\n link_name: name of the link.", "source": "github_repos"} +{"code": "def __call__(self):\n output_shapes = self._output_shapes()\n cond_is_stacked = [None]\n indices_to_stack = []\n\n def cond(not_all_done, *_):\n return not_all_done\n\n def body(not_all_done, indices, *args):\n num_inputs = self._pfor_input.num_inputs\n inputs = args[:num_inputs]\n output_tas = args[num_inputs:]\n inputs_stacked = [x.is_stacked for x in self._pfor_input.inputs]\n assert len(inputs) >= len(output_tas)\n assert len(inputs) == len(inputs_stacked)\n with ops.name_scope('while_cond'):\n cond_pfor = PFor(loop_var=self._pfor.loop_var, loop_len=array_ops.size(indices), pfor_ops=self._cond_func.graph.get_operations(), fallback_to_while_loop=self._pfor.fallback_to_while_loop, all_indices=indices, all_indices_partitioned=True, pfor_config=self._pfor.pfor_config)\n wrapped_inputs = [wrap(inp, stacked) for inp, stacked in zip(inputs, inputs_stacked)]\n conditions, cond_stacked, _ = _convert_function_call(self._cond_func, cond_pfor, wrapped_inputs)[0]\n cond_is_stacked[0] = cond_stacked\n if not cond_stacked:\n not_all_done, new_indices, new_inputs, new_output_tas = self._process_cond_unstacked(conditions, indices, inputs, output_tas)\n else:\n not_all_done, new_indices, new_inputs, new_output_tas = self._process_cond_stacked(conditions, indices, inputs, inputs_stacked, output_tas)\n with ops.name_scope('while_body'):\n new_outputs, mismatching_stacked_indices = self._process_body(inputs_stacked, new_indices, cond_stacked, new_inputs, not_all_done)\n indices_to_stack[:] = mismatching_stacked_indices\n for i, new_output in enumerate(new_outputs):\n new_output.set_shape(output_shapes[i])\n new_args = [not_all_done, new_indices] + new_outputs + list(new_output_tas)\n return tuple(new_args)\n\n @def_function.function\n def while_fn():\n init_values = self._init_values()\n ta_shape_invariants = [tensor_shape.TensorShape([]) for _ in self._pfor_input.outputs]\n shape_invariants = [tensor_shape.TensorShape([]), tensor_shape.TensorShape([None])] + output_shapes + ta_shape_invariants\n while_outputs = while_loop.while_loop(cond, body, init_values, shape_invariants=shape_invariants, parallel_iterations=self._parallel_iterations)\n if indices_to_stack:\n return while_outputs\n else:\n num_inputs = self._pfor_input.num_inputs\n new_inputs = while_outputs[2:num_inputs + 2]\n output_tas = while_outputs[num_inputs + 2:]\n assert cond_is_stacked[0] is not None\n outputs = []\n for i, inp in enumerate(new_inputs):\n if cond_is_stacked[0]:\n if i in self._body_pass_through_indices:\n outputs.append(init_values[i + 2])\n else:\n ta = output_tas[i]\n if _variant_type_id(inp) == full_type_pb2.TFT_ARRAY:\n shape_and_type = _parse_variant_shapes_and_types(inp)[0]\n length = list_ops.tensor_list_length(inp)\n\n def _stack_loop_body(index, output_list):\n current_value = ta.read(index)\n output_list = list_ops.tensor_list_set_item(output_list, index, list_ops.tensor_list_stack(current_value, shape_and_type.dtype))\n return (index + 1, output_list)\n output_list = list_ops.tensor_list_reserve(tensor_shape.TensorShape(shape_and_type.shape), length, shape_and_type.dtype)\n _, output_list = while_loop.while_loop(lambda index, _: index < length, _stack_loop_body, [0, output_list])\n outputs.append(output_list)\n else:\n outputs.append(ta.stack())\n else:\n outputs.append(inp)\n return outputs\n _ = while_fn.get_concrete_function()\n if indices_to_stack:\n self._pfor_input.stack_inputs(stack_indices=indices_to_stack, tile_variants=True)\n return self()\n else:\n outputs = while_fn()\n wrapped_outputs = []\n for i, (out, inp) in enumerate(zip(outputs, self._pfor_input.inputs)):\n if i not in self._body_pass_through_indices and cond_is_stacked[0]:\n wrapped_outputs.append(wrap(out, True))\n else:\n wrapped_outputs.append(wrap(out, inp.is_stacked))\n return wrapped_outputs", "docstring": "Converter for the V2 while_loop.\n\n The conversion of a while_loop is another while_loop.\n\n The arguments to this converted while_loop are as follows:\n not_all_done: Boolean scalar Tensor indicating if all the pfor iterations\n are done.\n indices: int32 1-D Tensor storing the id of the pfor iterations that are not\n done.\n args: Remaining arguments. These can be divided into 2 categories:\n - The first set of arguments correspond one-to-one to the inputs to the\n unvectorized while_loop.\n - The second set are TensorArrays, corresponding one-to-one to each output\n of the unvectorized while_loop. Each TensorArray has `PFor.loop_len`\n elements, i.e. the number of pfor iterations. At the end, the i'th\n element of each TensorArray will contain the output computed by the i'th\n iteration of pfor. Note that elements can be written into these tensors\n arrays in any order, depending on when the corresponding pfor iteration\n is done.\n In each iteration, the while_loop body recomputes the condition for all\n active pfor iterations to see which of them are now done. It then partitions\n all the inputs and passes them along to the converted body. Values for all\n the iterations that are done are written to TensorArrays indexed by the pfor\n iteration number. When all iterations are done, the TensorArrays are stacked\n to get the final value.\n\nReturns:\n List of converted outputs.", "source": "github_repos"} +{"code": "def reduced_shape(input_shape, axes):\n constant_input_shape = tensor_util.constant_value(input_shape)\n if constant_input_shape is not None:\n constant_axes = tensor_util.constant_value(axes)\n if constant_axes is not None:\n constant_axes = np.array(constant_axes, dtype=np.int32)\n constant_input_shape = np.array(constant_input_shape, dtype=np.int32)\n constant_input_shape[constant_axes] = 1\n return constant_input_shape\n axes = ops.convert_to_tensor(axes)\n input_rank = array_ops.size(input_shape, out_type=axes.dtype)\n axes = (axes + input_rank) % input_rank\n axes_shape = array_ops.shape(axes)\n return gen_data_flow_ops.dynamic_stitch([range(input_rank), axes], [input_shape, array_ops.ones(axes_shape, dtype=input_shape.dtype)])", "docstring": "Helper function for reduction ops.\n\nArgs:\n input_shape: 1-D Tensor, the shape of the Tensor being reduced.\n axes: 1-D Tensor, the reduction axes.\n\nReturns:\n A 1-D Tensor, the output shape as if keepdims were set to True.", "source": "github_repos"} +{"code": "def _objective_and_vega(volatilities):\n vols = volatilities * sqrt_t / normalization\n d1 = (norm_forwards - norm_strikes) / vols\n implied_prices = (norm_forwards - norm_strikes) * _cdf(d1) + vols * _pdf(d1)\n if is_call_options is not None:\n put_prices = implied_prices - norm_forwards + norm_strikes\n implied_prices = tf.where(is_call_options, implied_prices, put_prices)\n vega = _pdf(d1) * sqrt_t / discount_factors / normalization\n return (implied_prices - normalized_prices, vega)", "docstring": "Calculate the Bachelier price and vega for a given volatility.\n\n This method returns normalized results.\n\nArgs:\n volatilities: A real `Tensor` of same shape and dtype as `forwards`. The\n volatility to expiry.\n\nReturns:\n A tuple containing (value, gradient) of the black scholes price, both of\n which are `Tensor`s of the same shape and dtype as `volatilities`.", "source": "github_repos"} +{"code": "def range_input_producer(limit, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None):\n with ops.name_scope(name, 'input_producer', [limit]) as name:\n range_tensor = math_ops.range(limit)\n return input_producer(range_tensor, [], num_epochs, shuffle, seed, capacity, shared_name, 'fraction_of_%d_full' % capacity, name)", "docstring": "Produces the integers from 0 to limit-1 in a queue.\n\n Note: if `num_epochs` is not `None`, this function creates local counter\n `epochs`. Use `local_variables_initializer()` to initialize local variables.\n\nArgs:\n limit: An int32 scalar tensor.\n num_epochs: An integer (optional). If specified, `range_input_producer`\n produces each integer `num_epochs` times before generating an\n OutOfRange error. If not specified, `range_input_producer` can cycle\n through the integers an unlimited number of times.\n shuffle: Boolean. If true, the integers are randomly shuffled within each\n epoch.\n seed: An integer (optional). Seed used if shuffle == True.\n capacity: An integer. Sets the queue capacity.\n shared_name: (optional). If set, this queue will be shared under the given\n name across multiple sessions.\n name: A name for the operations (optional).\n\nReturns:\n A Queue with the output integers. A `QueueRunner` for the Queue\n is added to the current `Graph`'s `QUEUE_RUNNER` collection.\n\n @compatibility(eager)\n Input pipelines based on Queues are not supported when eager execution is\n enabled. Please use the `tf.data` API to ingest data under eager execution.\n @end_compatibility", "source": "github_repos"} +{"code": "def __init__(self, lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, **kwargs):\n super(Adamax, self).__init__(**kwargs)\n with backend.name_scope(self.__class__.__name__):\n self.iterations = backend.variable(0, dtype='int64', name='iterations')\n self.lr = backend.variable(lr, name='lr')\n self.beta_1 = backend.variable(beta_1, name='beta_1')\n self.beta_2 = backend.variable(beta_2, name='beta_2')\n self.decay = backend.variable(decay, name='decay')\n if epsilon is None:\n epsilon = backend.epsilon()\n self.epsilon = epsilon\n self.initial_decay = decay", "docstring": "Adamax optimizer from Adam paper's Section 7.\n\n It is a variant of Adam based on the infinity norm.\n Default parameters follow those provided in the paper.\n\nArgs:\n lr: float >= 0. Learning rate.\n beta_1/beta_2: floats, 0 < beta < 1. Generally close to 1.\n epsilon: float >= 0. Fuzz factor.\n If `None`, defaults to `backend.epsilon()`.\n decay: float >= 0. Learning rate decay over each update.", "source": "github_repos"} +{"code": "def aggregate_and_return_name_for_input(self, out_graphdef):\n del out_graphdef\n raise RuntimeError('Unimplemented abstract method.')", "docstring": "This adds the node(s) to out_graphdef and returns the input node name.\n\nArgs:\n out_graphdef: A graphdef that is ready to have this input added.\n\nReturns:\n The output that the stub should use as an input for this operand.\n\nRaises:\n RuntimeError: if the method is not implemented.", "source": "github_repos"} +{"code": "def execute_command(self, command: str, read: bool=False) -> None:\n if self.debug:\n print(command)\n return 'SIMULATING VALUE' if read else True\n else:\n print('\\nCOMMAND\\n', command, '\\n' + '-' * 40)\n try:\n cmd = subprocess.run(command, shell=True, capture_output=read, text=True, check=True)\n if read:\n return cmd.stdout.strip()\n return True\n except subprocess.CalledProcessError as e:\n return False", "docstring": "Helper function that either executes or prints each command.\n\nArgs:\n command - a command line command, typically a gcloud command.\n read - if True, the commands output is passed back to the caller.\n\nReturns:\n Bool - if command value is not required, simply indicate successor failure.\n String - if read is specified, the command output or error is returned.", "source": "github_repos"} +{"code": "def apply(self, score: Optional[float]) -> Optional[int]:\n raise NotImplementedError", "docstring": "Applies the threshold function to a given score to classify it as\n normal or outlier.\n\nArgs:\n score: The outlier score generated from the detector (model).\n\nReturns:\n The label assigned to the score, either `self._normal_label`\n or `self._outlier_label`", "source": "github_repos"} +{"code": "def preprocess(text):\n if len(text.strip()) > 0:\n question, context = text.split(';')\n yield (question, context)", "docstring": "preprocess separates the text into question and context\n by splitting on semi-colon.\n\nArgs:\n text (str): string with question and context separated by semi-colon.\n\nYields:\n (str, str): yields question and context from text.", "source": "github_repos"} +{"code": "def patchify_image(self, image: 'torch.Tensor', patch_size: Optional[Dict[str, int]]=None) -> 'torch.Tensor':\n requires_backends(self, ['torch'])\n patch_size = patch_size if patch_size is not None else self.patch_size\n patch_height, patch_width = (patch_size['height'], patch_size['width'])\n batch_size, channels, _, _ = image.shape\n unfolded_along_height = image.unfold(2, patch_height, patch_height)\n patches = unfolded_along_height.unfold(3, patch_width, patch_width)\n patches = patches.contiguous()\n patches = patches.view(batch_size, channels, -1, patch_height, patch_width)\n patches = patches.permute(0, 2, 3, 4, 1)\n patches = patches.reshape(batch_size, -1, channels * patch_height * patch_width)\n return patches", "docstring": "Convert an image into a tensor of patches.\n\nArgs:\n image (`torch.Tensor`):\n Image to convert. Shape: [batch, channels, height, width]\n patch_size (`Dict[str, int]`, *optional*, defaults to `self.patch_size`):\n Dictionary in the format `{\"height\": int, \"width\": int}` specifying the size of the patches.", "source": "github_repos"} +{"code": "def get_text_features(self, input_ids: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> torch.FloatTensor:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n text_outputs = self.text_model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n pooled_output = text_outputs[1] if return_dict is not None else text_outputs.pooler_output\n text_features = self.text_projection(pooled_output)\n text_features = F.normalize(text_features, dim=-1)\n return text_features", "docstring": "Returns:\n text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by\n applying the projection layer to the pooled output of [`ClapTextModel`].\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, ClapModel\n\n >>> model = ClapModel.from_pretrained(\"laion/clap-htsat-unfused\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"laion/clap-htsat-unfused\")\n\n >>> inputs = tokenizer([\"the sound of a cat\", \"the sound of a dog\"], padding=True, return_tensors=\"pt\")\n >>> text_features = model.get_text_features(**inputs)\n ```", "source": "github_repos"} +{"code": "def log_every_n(level, msg, n, *args):\n count = _GetNextLogCountPerToken(_GetFileAndLine())\n log_if(level, msg, not count % n, *args)", "docstring": "Log 'msg % args' at level 'level' once per 'n' times.\n\n Logs the 1st call, (N+1)st call, (2N+1)st call, etc.\n Not threadsafe.\n\nArgs:\n level: The level at which to log.\n msg: The message to be logged.\n n: The number of times this should be called before it is logged.\n *args: The args to be substituted into the msg.", "source": "github_repos"} +{"code": "def __init__(self, name, func, create_scope_now=False, unique_name=None, custom_getter=None, create_graph_function=False):\n if create_graph_function:\n self._func = def_function.function(func)\n else:\n self._func = func\n self._stacktrace = traceback.format_stack()[:-2]\n self._name = name\n self._unique_name = unique_name\n self._custom_getter = custom_getter\n if name is None:\n raise ValueError('name cannot be None.')\n if create_scope_now:\n with variable_scope._pure_variable_scope(self._unique_name or variable_scope._get_unique_variable_scope(self._name), custom_getter=self._custom_getter) as vs:\n self._variable_scope = vs\n else:\n self._variable_scope = None\n self._variables_created = False\n self._first_call = True", "docstring": "Creates a template for the given function.\n\nArgs:\n name: A name for the scope created by this template. The name will be made\n unique by appending `_N` to the it (see how\n `tf.compat.v1.variable_scope` treats the `default_name` for details).\n func: The function to apply each time.\n create_scope_now: Whether to create the scope at Template construction\n time, rather than first call. Defaults to false. Creating the scope at\n construction time may be more convenient if the template is to passed\n through much lower level code, and you want to be sure of the scope name\n without knowing exactly where it will be first called. If set to True,\n the scope will be created in the constructor, and all subsequent times\n in `__call__`, leading to a trailing numeral being added to the names of\n all created Tensors. If set to False, the scope will be created at the\n first call location.\n unique_name: When used, it overrides `name` and is not made unique. If a\n template of the same scope/unique_name already exists and reuse is\n false, an error is raised. Defaults to None.\n custom_getter: optional custom getter to pass to `variable_scope()`\n create_graph_function: When True, `func` will be executed as a graph\n function. Enabling this flag gives the caller access to graph-function\n semantics, i.e., accesses to variables are totally ordered and\n side-effecting ops are not pruned.\n\nRaises:\n ValueError: if `name` is None.", "source": "github_repos"} +{"code": "def recipe_to_python(name, description, instructions, tasks, parameters={}, project=None, client_credentials=None, user_credentials=None, service_credentials=None):\n tasks = json_expand_queries(tasks)\n code = DISCLAIMER\n code += 'import argparse\\n'\n code += 'import textwrap\\n\\n'\n code += 'from starthinker.util.configuration import Configuration\\n'\n imported = set()\n for task in tasks:\n script, task = next(iter(task.items()))\n if script not in imported:\n code += 'from starthinker.task.%s.run import %s\\n' % (script, script)\n imported.add(script)\n code += '\\n'\n code += '\\n'\n fields = json_get_fields(tasks)\n if fields:\n code += 'def recipe_%s(config, %s):\\n' % (name, ', '.join([f['name'] for f in fields]))\n else:\n code += 'def recipe_%s(config):\\n' % name\n if description or fields:\n code += ' \"\"\"' + textwrap.fill(description, width=80, subsequent_indent=' ') + '\\n'\n if fields:\n code += '\\n Args:\\n'\n for field in fields:\n code += ' %s (%s) - %s\\n' % (field['name'], field['kind'], field.get('description', 'NA'))\n code += ' \"\"\"\\n\\n'\n for task in tasks:\n script, task = next(iter(task.items()))\n code += ' %s(config, %s)\\n\\n' % (script, dict_to_python(task, indent=1))\n code += '\\n'\n code += '\\n'\n code += 'if __name__ == \"__main__\":\\n'\n code += parameters_to_argparse(description, instructions, fields)\n code += '\\n'\n code += ' args = parser.parse_args()\\n'\n code += '\\n'\n code += ' config = Configuration(\\n project=args.project,\\n user=args.user,\\n service=args.service,\\n client=args.client,\\n key=args.key,\\n verbose=args.verbose\\n )'\n code += '\\n\\n'\n if fields:\n code += ' recipe_%s(config, %s)\\n' % (name, ', '.join(['args.%s' % f['name'] for f in fields]))\n else:\n code += ' recipe_%s(config)\\n' % name\n return code", "docstring": "Converts a JSON recipe into a python stand alone example.\n\n Sets up multiple steps to execute recipe:\n 1. Install starthinker from repository\n 2. Get Cloud Project ID.\n 3. Get Client Credentials ( optional if User Credentials exist ).\n 4. Enter Recipe parameters if fields present.\n 5. Execute recipe tasks.\n\nArgs:\n * name: (string) The name of the notebook.\n * description: (string) A description fo the recipe.\n * instructions: (string) Recipe manual instructions, for example connecting datastudios.\n * tasks: (list) The task JSON to execute.\n * parameters: (dict) Values for field parameters in tasks, optional.\n * project: (string) The GCP project id.\n * client_credentials: (string) The GCP Desktop Client Credentials in JSON string.\n * user_credentials: (string) Not used, placeholder.\n * service_credentials: (string) Not used, placeholder.\n\nReturns:\n * (string) Rendered example source code to be written to a py file.", "source": "github_repos"} +{"code": "def _InsertNodeAt(new_node, target, after=False):\n if new_node.parent is not None:\n raise RuntimeError('inserting node which already has a parent', (new_node, new_node.parent))\n parent_of_target = target.parent\n if parent_of_target is None:\n raise RuntimeError('expected target node to have a parent', (target,))\n for i, child in enumerate(parent_of_target.children):\n if child is target:\n insertion_index = i + 1 if after else i\n parent_of_target.insert_child(insertion_index, new_node)\n return\n raise RuntimeError('unable to find insertion point for target node', (target,))", "docstring": "Underlying implementation for node insertion.\n\nArgs:\n new_node: a new node to insert (this node should not be in the tree).\n target: the target node.\n after: if True, new_node is inserted after target. Otherwise, it's inserted\n before target.\n\nReturns:\n nothing\n\nRaises:\n RuntimeError: if the tree is corrupted, or the insertion would corrupt it.", "source": "github_repos"} +{"code": "def make_parser():\n\n def add_kythe_field(parser, field):\n parser.add_argument('--' + field, dest=field, type=str, action='store', default='', help=\"Part of kythe's file-level vname proto.\")\n parser = argparse.ArgumentParser(usage='%(prog)s [options] input')\n add_kythe_field(parser, 'kythe_corpus')\n add_kythe_field(parser, 'kythe_root')\n add_kythe_field(parser, 'kythe_path')\n parser.add_argument('--show-types', action='store_true', dest='show_types', default=None, help='Display inferred types.')\n parser.add_argument('--show-kythe', action='store_true', dest='show_kythe', default=None, help='Display kythe facts.')\n parser.add_argument('--show-spans', action='store_true', dest='show_spans', default=None, help='Display kythe spans.')\n parser.add_argument('--skip-stdlib', action='store_true', dest='skip_stdlib', default=None, help='Display inferred types.')\n wrapper = datatypes.ParserWrapper(parser)\n pytype_config.add_basic_options(wrapper)\n with wrapper.add_only(['--imports_info', '--debug']):\n pytype_config.add_infrastructure_options(wrapper)\n pytype_config.add_debug_options(wrapper)\n wrapper.add_argument('input', metavar='input', nargs=1, help='A .py file to index')\n return XrefParser(parser, pytype_single_args=wrapper.actions)", "docstring": "Make parser for command line args.\n\nReturns:\n A Parser object.", "source": "github_repos"} +{"code": "def to_dict(self) -> dict[str, Any]:\n output = copy.deepcopy(self.__dict__)\n sig = inspect.signature(self.__init__)\n attrs_to_save = sig.parameters\n attrs_to_save = [x for x in attrs_to_save if x not in self.__class__.attributes]\n attrs_to_save += ['auto_map']\n output = {k: v for k, v in output.items() if k in attrs_to_save}\n output['processor_class'] = self.__class__.__name__\n if 'tokenizer' in output:\n del output['tokenizer']\n if 'image_processor' in output:\n del output['image_processor']\n if 'video_processor' in output:\n del output['video_processor']\n if 'feature_extractor' in output:\n del output['feature_extractor']\n if 'chat_template' in output:\n del output['chat_template']\n output = {k: v for k, v in output.items() if not (isinstance(v, PushToHubMixin) or v.__class__.__name__ == 'BeamSearchDecoderCTC')}\n return output", "docstring": "Serializes this instance to a Python dictionary.\n\nReturns:\n `Dict[str, Any]`: Dictionary of all the attributes that make up this processor instance.", "source": "github_repos"} +{"code": "def _get_saver_or_default():\n collection_key = ops.GraphKeys.SAVERS\n savers = ops.get_collection(collection_key)\n if savers:\n if len(savers) > 1:\n raise RuntimeError('More than one item in collection {}. Please indicate which one to use by passing it to the constructor.'.format(collection_key))\n return savers[0]\n saver = Saver(sharded=True, allow_empty=True)\n if saver is not None:\n ops.add_to_collection(collection_key, saver)\n return saver", "docstring": "Returns the saver from SAVERS collection, or creates a default one.\n\n This method is used by other members of the training module, such as\n `Scaffold`, or `CheckpointSaverHook`.\n\nReturns:\n `Saver`.\n\nRaises:\n RuntimeError: If the SAVERS collection already has more than one items.", "source": "github_repos"} +{"code": "def parse_module_content(content: str) -> List[str]:\n objects = []\n current_object = []\n lines = content.split('\\n')\n end_markers = [')', ']', '}', '\"\"\"']\n for line in lines:\n is_valid_object = len(current_object) > 0\n if is_valid_object and len(current_object) == 1:\n is_valid_object = not current_object[0].startswith('# Copied from')\n if not is_empty_line(line) and find_indent(line) == 0 and is_valid_object:\n if line in end_markers:\n current_object.append(line)\n objects.append('\\n'.join(current_object))\n current_object = []\n else:\n objects.append('\\n'.join(current_object))\n current_object = [line]\n else:\n current_object.append(line)\n if len(current_object) > 0:\n objects.append('\\n'.join(current_object))\n return objects", "docstring": "Parse the content of a module in the list of objects it defines.\n\nArgs:\n content (`str`): The content to parse\n\nReturns:\n `List[str]`: The list of objects defined in the module.", "source": "github_repos"} +{"code": "def prod(x, axis=None, keepdims=False, dtype=None):\n if any_symbolic_tensors((x,)):\n return Prod(axis=axis, keepdims=keepdims, dtype=dtype).symbolic_call(x)\n return backend.numpy.prod(x, axis=axis, keepdims=keepdims, dtype=dtype)", "docstring": "Return the product of tensor elements over a given axis.\n\nArgs:\n x: Input tensor.\n axis: Axis or axes along which a product is performed. The default,\n `axis=None`, will compute the product of all elements\n in the input tensor.\n keepdims: If this is set to `True`, the axes which are reduce\n are left in the result as dimensions with size one.\n dtype: Data type of the returned tensor.\n\nReturns:\n Product of elements of `x` over the given axis or axes.", "source": "github_repos"} +{"code": "def __init__(self, cluster_resolver, checkpoint_or_checkpoint_manager, checkpoint_dir=None, termination_config=None):\n if isinstance(checkpoint_or_checkpoint_manager, checkpoint_lib.Checkpoint) and (not checkpoint_dir):\n raise errors.InvalidArgumentError('When a checkpoint is passed, a checkpoint_dir must be passed as well.')\n self._cluster_resolver = cluster_resolver\n self._termination_config = termination_config\n self._checkpoint_or_checkpoint_manager = checkpoint_or_checkpoint_manager\n self._checkpoint_dir = checkpoint_dir\n self._platform_device = failure_handling_util.detect_platform()\n completed_termination_config = _complete_config_for_environment(self._platform_device, self._termination_config)\n self._termination_watcher_fn = completed_termination_config.termination_watcher_fn\n self._exit_fn = completed_termination_config.exit_fn\n self._grace_period = completed_termination_config.grace_period\n self._save_fn = completed_termination_config.save_fn\n self._local_mode = True\n if self._platform_device in (failure_handling_util.PlatformDevice.GCE_TPU, failure_handling_util.PlatformDevice.GCE_CPU):\n logging.warning('PreemptionCheckpointHandler does not support usage with TPU or CPU device on GCP.')\n elif self._platform_device == failure_handling_util.PlatformDevice.INTERNAL_TPU:\n self._initialize_for_tpu_strategy()\n else:\n if cluster_resolver and 'ps' in cluster_resolver.cluster_spec().as_dict():\n raise NotImplementedError('PreemptionCheckpointHandler does not supportusage with tf.distribute.experimental.ParameterServerStrategy.')\n self._initialize_for_mirrored_and_multi_worker_mirrored()\n logging.info('PreemptionCheckpointHandler initialized or restored.')", "docstring": "Creates the `PreemptionCheckpointHandler`.\n\nArgs:\n cluster_resolver: a `tf.distribute.cluster_resolver.ClusterResolver`\n object. You may also obtain it through the `cluster_resolver` attribute\n of the distribution strategy in use.\n checkpoint_or_checkpoint_manager: a `tf.train.CheckpointManager` or a\n `tf.train.Checkpoint`. If you are using a `tf.train.CheckpointManager`\n to manage checkpoints outside the `PreemptionCheckpointHandler` for\n backup purpose as well, pass it as `checkpoint_or_checkpoint_manager`\n argument. Otherwise, pass a `tf.train.Checkpoint` and the\n `PreemptionCheckpointHandler` will create\n a `tf.train.CheckpointManager` to manage it in the `checkpoint_dir`.\n checkpoint_dir: a directory where the `PreemptionCheckpointHandler` saves\n and restores checkpoints. When a `PreemptionCheckpointHandler` is\n created, the latest checkpoint in the `checkpoint_dir` will be restored.\n (This is not needed if a `tf.train.CheckpointManager` instead of a\n `tf.train.Checkpoint` is passed as the\n `checkpoint_or_checkpoint_manager` argument.)\n termination_config: optional, a\n `tf.distribute.experimental.TerminationConfig` object to configure for a\n platform other than Google Borg or GCP.", "source": "github_repos"} +{"code": "def _preload_simple_restoration(self, name):\n deferred_dependencies_list = self._deferred_dependencies.get(name, ())\n if not deferred_dependencies_list:\n return\n for checkpoint_position in deferred_dependencies_list:\n if not checkpoint_position.is_simple_variable():\n return None\n checkpoint_position = max(deferred_dependencies_list, key=lambda restore: restore.checkpoint.restore_uid)\n return CheckpointInitialValueCallable(checkpoint_position=checkpoint_position)", "docstring": "Return a dependency's value for restore-on-create.\n\n Note the restoration is not deleted; if for some reason preload is called\n and then not assigned to the variable (for example because a custom getter\n overrides the initializer), the assignment will still happen once the\n variable is tracked (determined based on checkpoint.restore_uid).\n\nArgs:\n name: The object-local name of the dependency holding the variable's\n value.\n\nReturns:\n An callable for use as a variable's initializer/initial_value, or None if\n one should not be set (either because there was no variable with this name\n in the checkpoint or because it needs more complex deserialization). Any\n non-trivial deserialization will happen when the variable object is\n tracked.", "source": "github_repos"} +{"code": "def __init__(self, weight_shape: Sequence[int]) -> None:\n self.filters = np.random.uniform(low=-1.0, high=1.0, size=weight_shape)\n if bias_fn is not None:\n self.bias = np.random.uniform(low=-1.0, high=1.0, size=weight_shape[-1])", "docstring": "Initializes a MatmulModel.\n\nArgs:\n weight_shape: Shape of the weight tensor.", "source": "github_repos"} +{"code": "def align_long_axis(self, image: np.ndarray, size: Dict[str, int], data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:\n input_height, input_width = get_image_size(image, channel_dim=input_data_format)\n output_height, output_width = (size['height'], size['width'])\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n if input_data_format == ChannelDimension.LAST:\n rot_axes = (0, 1)\n elif input_data_format == ChannelDimension.FIRST:\n rot_axes = (1, 2)\n else:\n raise ValueError(f'Unsupported data format: {input_data_format}')\n if output_width < output_height and input_width > input_height or (output_width > output_height and input_width < input_height):\n image = np.rot90(image, 3, axes=rot_axes)\n if data_format is not None:\n image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n return image", "docstring": "Align the long axis of the image to the longest axis of the specified size.\n\nArgs:\n image (`np.ndarray`):\n The image to be aligned.\n size (`Dict[str, int]`):\n The size `{\"height\": h, \"width\": w}` to align the long axis to.\n data_format (`str` or `ChannelDimension`, *optional*):\n The data format of the output image. If unset, the same format as the input image is used.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.\n\nReturns:\n `np.ndarray`: The aligned image.", "source": "github_repos"} +{"code": "def process_one_file(options):\n log.info('Process %s => %s', options.input, options.output)\n try:\n ret = check_or_generate_pyi(options)\n except utils.UsageError:\n logging.exception('')\n return 1\n if not options.check:\n if options.pickle_output:\n pyi_output = options.verify_pickle\n else:\n pyi_output = options.output\n if pyi_output:\n _write_pyi_output(options, ret.pyi, pyi_output)\n if options.pickle_output:\n log.info('write pickle %r => %r', options.input, options.output)\n write_pickle(ret.ast, options, ret.context.loader)\n if options.unused_imports_info_files:\n if options.use_rewrite:\n pass\n else:\n cwd = os.getcwd()\n unused_paths = sorted(ret.context.loader.get_unused_imports_map_paths())\n with options.open_function(options.unused_imports_info_files, 'wt', encoding='utf-8') as f:\n for unused_path in unused_paths:\n f.write(f'{os.path.relpath(unused_path, cwd)}\\n')\n exit_status = handle_errors(ret.context.errorlog, options)\n ret.context.program = None\n if options.touch and (not exit_status):\n with options.open_function(options.touch, 'a'):\n os.utime(options.touch, None)\n return exit_status", "docstring": "Check a .py file or generate a .pyi for it, according to options.\n\nArgs:\n options: config.Options object.\n\nReturns:\n An error code (0 means no error).", "source": "github_repos"} +{"code": "def create_model() -> tf.keras.Model:\n return tf.keras.Sequential(pg.oneof([lambda: [tf.keras.layers.Flatten(), tf.keras.layers.Dense(pg.oneof([64, 128]), pg.oneof(['relu', 'sigmoid']))], lambda: [tf.keras.layers.Lambda(lambda x: tf.reshape(x, (-1, 28, 28, 1))), tf.keras.layers.Conv2D(pg.oneof([64, 128]), pg.oneof([(3, 3), (5, 5)]), activation=pg.oneof(['relu', 'sigmoid'])), tf.keras.layers.Flatten()]]) + [tf.keras.layers.Dense(10, activation='softmax')])", "docstring": "Create model for training.\n\n Create a simple tf.keras model for training.\n\nReturns:\n The model to use for training.", "source": "github_repos"} +{"code": "def normalize(self, image, mean, std, rescale=False):\n self._ensure_format_supported(image)\n if isinstance(image, PIL.Image.Image):\n image = self.to_numpy_array(image, rescale=True)\n elif rescale:\n if isinstance(image, np.ndarray):\n image = self.rescale(image.astype(np.float32), 1 / 255.0)\n elif is_torch_tensor(image):\n image = self.rescale(image.float(), 1 / 255.0)\n if isinstance(image, np.ndarray):\n if not isinstance(mean, np.ndarray):\n mean = np.array(mean).astype(image.dtype)\n if not isinstance(std, np.ndarray):\n std = np.array(std).astype(image.dtype)\n elif is_torch_tensor(image):\n import torch\n if not isinstance(mean, torch.Tensor):\n if isinstance(mean, np.ndarray):\n mean = torch.from_numpy(mean)\n else:\n mean = torch.tensor(mean)\n if not isinstance(std, torch.Tensor):\n if isinstance(std, np.ndarray):\n std = torch.from_numpy(std)\n else:\n std = torch.tensor(std)\n if image.ndim == 3 and image.shape[0] in [1, 3]:\n return (image - mean[:, None, None]) / std[:, None, None]\n else:\n return (image - mean) / std", "docstring": "Normalizes `image` with `mean` and `std`. Note that this will trigger a conversion of `image` to a NumPy array\n if it's a PIL Image.\n\nArgs:\n image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):\n The image to normalize.\n mean (`List[float]` or `np.ndarray` or `torch.Tensor`):\n The mean (per channel) to use for normalization.\n std (`List[float]` or `np.ndarray` or `torch.Tensor`):\n The standard deviation (per channel) to use for normalization.\n rescale (`bool`, *optional*, defaults to `False`):\n Whether or not to rescale the image to be between 0 and 1. If a PIL image is provided, scaling will\n happen automatically.", "source": "github_repos"} +{"code": "def write(self, dataset):\n if not isinstance(dataset, data_types.DatasetV2):\n raise TypeError(f'Invalid `dataset.` Expected a `tf.data.Dataset` object but got {type(dataset)}.')\n if not dataset_ops.get_structure(dataset).is_compatible_with(tensor_spec.TensorSpec([], dtypes.string)):\n raise TypeError(f'Invalid `dataset`. Expected a`dataset` that produces scalar `tf.string` elements, but got a dataset which produces elements with shapes {dataset_ops.get_legacy_output_shapes(dataset)} and types {dataset_ops.get_legacy_output_types(dataset)}.')\n dataset = dataset._apply_debug_options()\n return gen_experimental_dataset_ops.dataset_to_tf_record(dataset._variant_tensor, self._filename, self._compression_type)", "docstring": "Writes a dataset to a TFRecord file.\n\n An operation that writes the content of the specified dataset to the file\n specified in the constructor.\n\n If the file exists, it will be overwritten.\n\nArgs:\n dataset: a `tf.data.Dataset` whose elements are to be written to a file\n\nReturns:\n In graph mode, this returns an operation which when executed performs the\n write. In eager mode, the write is performed by the method itself and\n there is no return value.\n\n Raises\n TypeError: if `dataset` is not a `tf.data.Dataset`.\n TypeError: if the elements produced by the dataset are not scalar strings.", "source": "github_repos"} +{"code": "def __init__(self, num_participants):\n self._num_participants = num_participants\n self._counter = 0\n self._flag = False\n self._local_sense = threading.local()\n self._lock = threading.Lock()\n self._condition = threading.Condition()", "docstring": "Initializes the barrier object.\n\nArgs:\n num_participants: an integer which is the expected number of calls of\n `wait` pass to through this barrier.", "source": "github_repos"} +{"code": "def trace(name, *trace_args):\n\n def decorator(f):\n\n def wrapper(*args, **kwargs):\n t = tracer(name)\n if t.getEffectiveLevel() < logging.DEBUG:\n return f(*args, **kwargs)\n argspec = inspect.getfullargspec(f)\n t.debug('%s: {', f.__name__)\n for arg in trace_args:\n if isinstance(arg, int):\n argname = argspec.args[arg]\n val = args[arg]\n else:\n argname = arg\n val = kwargs[arg]\n t.debug('%s: %s = %s', f.__name__, argname, show(val))\n ret = f(*args, **kwargs)\n t.debug('%s: -> %s', f.__name__, show(ret))\n t.debug('%s: }', f.__name__)\n return ret\n return wrapper\n return decorator", "docstring": "Record args and return value for a function call.\n\n The trace is of the form\n function name: {\n function name: arg = value\n function name: arg = value\n ...\n function name: -> return\n function name: }\n\n This will let us write tools to pretty print the traces with indentation etc.\n\nArgs:\n name: module name, usually `__name__`\n *trace_args: function arguments to log\n\nReturns:\n a decorator", "source": "github_repos"} +{"code": "def generate_dequeue_op(self, tpu_device=0):\n self.freeze()\n if self._generated_dequeue_op and (not ops.inside_function()):\n raise ValueError(\"Can't generate two dequeue Ops from the same queue\")\n self._generated_dequeue_op = True\n full_name = '%s/dequeue' % self._name\n sharded_shapes = [policy.get_sharded_shape(shape) for shape, policy in zip(self._tuple_shapes, self._sharding_policies)]\n with ops.device(tpu_name_util.core(tpu_device)):\n values = tpu_ops.infeed_dequeue_tuple(dtypes=self._tuple_types, shapes=sharded_shapes, name=full_name)\n return tag_sharding_attribute_for_dequeued_tensors(values, self._input_partition_dims)", "docstring": "Generate TPU dequeue ops.\n\nArgs:\n tpu_device: The TPU device ordinal where the infeed instruction should be\n placed.\n\nReturns:\n A list of Outputs corresponding to a partition of infeed dequeued\n into XLA, suitable for use within a replicated block.\n\nRaises:\n ValueError: if the types or shapes of the tuple elements have not been\n set; or if a dequeue op has already been generated.", "source": "github_repos"} +{"code": "def __init__(self, state_handler: sdk_worker.CachingStateHandler, transform_id: str, key_coder: coders.Coder, window_coder: coders.Coder) -> None:\n self._state_handler = state_handler\n self._transform_id = transform_id\n self._key_coder = key_coder\n self._window_coder = window_coder\n self._timers_info: Dict[str, TimerInfo] = {}\n self._all_states: Dict[tuple, FnApiUserRuntimeStateTypes] = {}", "docstring": "Initialize a ``FnApiUserStateContext``.\n\nArgs:\n state_handler: A StateServicer object.\n transform_id: The name of the PTransform that this context is associated.\n key_coder: Coder for the key type.\n window_coder: Coder for the window type.", "source": "github_repos"} +{"code": "def create(configs):\n if not configs:\n raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG)\n elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN:\n ads = get_all_instances()\n elif not isinstance(configs, list):\n raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)\n elif isinstance(configs[0], dict):\n ads = get_instances_with_configs(configs)\n elif isinstance(configs[0], str):\n ads = get_instances(configs)\n else:\n raise Error('No valid config found in: %s' % configs)\n _start_services_on_ads(ads)\n return ads", "docstring": "Creates AndroidDevice controller objects.\n\nArgs:\n configs: Represents configurations for Android devices, this can take one of\n the following forms:\n * str, only asterisk symbol is accepted, indicating that all connected\n Android devices will be used\n * A list of dict, each representing a configuration for an Android device.\n * A list of str, each representing the serial number of Android device.\n\nReturns:\n A list of AndroidDevice objects.", "source": "github_repos"} +{"code": "def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BILINEAR, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:\n if 'shortest_edge' in size and 'longest_edge' in size:\n size = get_resize_output_image_size(image, size, input_data_format)\n elif 'height' in size and 'width' in size:\n size = (size['height'], size['width'])\n else:\n raise ValueError(\"size must be a dictionary with keys 'shortest_edge' and 'longest_edge' or 'height' and 'width'.\")\n return resize(image, size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs)", "docstring": "Resize an image. The shortest edge of the image is resized to size[\"shortest_edge\"], with the longest edge\n resized to keep the input aspect ratio.\n\nArgs:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.", "source": "github_repos"} +{"code": "def get_channel_dimension_axis(image: np.ndarray, input_data_format: Optional[Union[ChannelDimension, str]]=None) -> int:\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n if input_data_format == ChannelDimension.FIRST:\n return image.ndim - 3\n elif input_data_format == ChannelDimension.LAST:\n return image.ndim - 1\n raise ValueError(f'Unsupported data format: {input_data_format}')", "docstring": "Returns the channel dimension axis of the image.\n\nArgs:\n image (`np.ndarray`):\n The image to get the channel dimension axis of.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the image. If `None`, will infer the channel dimension from the image.\n\nReturns:\n The channel dimension axis of the image.", "source": "github_repos"} +{"code": "def _CTCLossGrad(op, grad_loss, _):\n return _CTCLossGradImpl(op, grad_loss, _)", "docstring": "The derivative provided by CTC Loss.\n\nArgs:\n op: the CTCLoss op.\n grad_loss: The backprop for cost.\n\nReturns:\n The CTC Loss gradient.", "source": "github_repos"} +{"code": "def count_nonzero(x, axis=None):\n if any_symbolic_tensors((x,)):\n return CountNonzero(axis=axis).symbolic_call(x)\n return backend.numpy.count_nonzero(x, axis=axis)", "docstring": "Counts the number of non-zero values in `x` along the given `axis`.\n\n If no axis is specified then all non-zeros in the tensor are counted.\n\nArgs:\n x: Input tensor.\n axis: Axis or tuple of axes along which to count the number of\n non-zeros. Defaults to `None`.\n\nReturns:\n int or tensor of ints.\n\nExample:\n >>> x = keras.ops.array([[0, 1, 7, 0], [3, 0, 2, 19]])\n >>> keras.ops.count_nonzero(x)\n 5\n >>> keras.ops.count_nonzero(x, axis=0)\n array([1, 1, 2, 1], dtype=int64)\n >>> keras.ops.count_nonzero(x, axis=1)\n array([2, 3], dtype=int64)", "source": "github_repos"} +{"code": "def __init__(self, parameter_name=None):\n self._parameter_name = parameter_name", "docstring": "Construct a parameter modifier that may be specific to a parameter.\n\nArgs:\n parameter_name: A `ParameterModifier` instance may operate on a class of\n parameters or on a parameter with a particular name. Only\n `ParameterModifier` instances that are of a unique type or were\n initialized with a unique `parameter_name` will be executed.\n See `__eq__` and `__hash__`.", "source": "github_repos"} +{"code": "def log_sinkhorn_iterations(log_cost_matrix: torch.Tensor, log_source_distribution: torch.Tensor, log_target_distribution: torch.Tensor, num_iterations: int) -> torch.Tensor:\n log_u_scaling = torch.zeros_like(log_source_distribution)\n log_v_scaling = torch.zeros_like(log_target_distribution)\n for _ in range(num_iterations):\n log_u_scaling = log_source_distribution - torch.logsumexp(log_cost_matrix + log_v_scaling.unsqueeze(1), dim=2)\n log_v_scaling = log_target_distribution - torch.logsumexp(log_cost_matrix + log_u_scaling.unsqueeze(2), dim=1)\n return log_cost_matrix + log_u_scaling.unsqueeze(2) + log_v_scaling.unsqueeze(1)", "docstring": "Perform Sinkhorn Normalization in Log-space for stability\n\nArgs:\n log_cost_matrix (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`):\n Logarithm of the cost matrix.\n log_source_distribution (`torch.Tensor` of shape `(batch_size, num_rows)`):\n Logarithm of the source distribution.\n log_target_distribution (`torch.Tensor` of shape `(batch_size, num_columns)`):\n Logarithm of the target distribution.\n\nReturns:\n log_cost_matrix (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`): Logarithm of the optimal\n transport matrix.", "source": "github_repos"} +{"code": "def _run_test_class(self, config, test_class, tests=None):\n test_instance = test_class(config)\n logging.debug('Executing test class \"%s\" with config: %s', test_class.__name__, config)\n try:\n cls_result = test_instance.run(tests)\n self.results += cls_result\n except signals.TestAbortAll as e:\n self.results += e.results\n raise e", "docstring": "Instantiates and executes a test class.\n\n If tests is None, the tests listed in self.tests will be executed\n instead. If self.tests is empty as well, every test in this test class\n will be executed.\n\nArgs:\n config: A config_parser.TestRunConfig object.\n test_class: class, test class to execute.\n tests: Optional list of test names within the class to execute.", "source": "github_repos"} +{"code": "def benchmarks_main(true_main, argv=None):\n if argv is None:\n argv = sys.argv\n found_arg = [arg for arg in argv if arg.startswith('--benchmark_filter=') or arg.startswith('-benchmark_filter=')]\n if found_arg:\n argv.remove(found_arg[0])\n regex = found_arg[0].split('=')[1]\n app.run(lambda _: _run_benchmarks(regex), argv=argv)\n else:\n true_main()", "docstring": "Run benchmarks as declared in argv.\n\nArgs:\n true_main: True main function to run if benchmarks are not requested.\n argv: the command line arguments (if None, uses sys.argv).", "source": "github_repos"} +{"code": "def run_saved_model_with_feed_dict(saved_model_dir, tag_set, signature_def_key, input_tensor_key_feed_dict, outdir, overwrite_flag, worker=None, init_tpu=False, use_tfrt=False, tf_debug=False):\n meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set)\n inputs_tensor_info = _get_inputs_tensor_info_from_meta_graph_def(meta_graph_def, signature_def_key)\n for input_key_name in input_tensor_key_feed_dict.keys():\n if input_key_name not in inputs_tensor_info:\n raise ValueError('\"%s\" is not a valid input key. Please choose from %s, or use --show option.' % (input_key_name, '\"' + '\", \"'.join(inputs_tensor_info.keys()) + '\"'))\n inputs_feed_dict = {inputs_tensor_info[key].name: tensor for key, tensor in input_tensor_key_feed_dict.items()}\n outputs_tensor_info = _get_outputs_tensor_info_from_meta_graph_def(meta_graph_def, signature_def_key)\n output_tensor_keys_sorted = sorted(outputs_tensor_info.keys())\n output_tensor_names_sorted = [outputs_tensor_info[tensor_key].name for tensor_key in output_tensor_keys_sorted]\n config = None\n if use_tfrt:\n logging.info('Using TFRT session.')\n config = config_pb2.ConfigProto(experimental=config_pb2.ConfigProto.Experimental(use_tfrt=True))\n with session.Session(worker, graph=ops_lib.Graph(), config=config) as sess:\n if init_tpu:\n print('Initializing TPU System ...')\n sess.run(tpu.initialize_system())\n loader.load(sess, tag_set.split(','), saved_model_dir)\n if tf_debug:\n sess = local_cli_wrapper.LocalCLIDebugWrapperSession(sess)\n outputs = sess.run(output_tensor_names_sorted, feed_dict=inputs_feed_dict)\n for i, output in enumerate(outputs):\n output_tensor_key = output_tensor_keys_sorted[i]\n print('Result for output key %s:\\n%s' % (output_tensor_key, output))\n if outdir:\n if not os.path.isdir(outdir):\n os.makedirs(outdir)\n output_full_path = os.path.join(outdir, output_tensor_key + '.npy')\n if not overwrite_flag and os.path.exists(output_full_path):\n raise RuntimeError('Output file %s already exists. Add \"--overwrite\" to overwrite the existing output files.' % output_full_path)\n np.save(output_full_path, output)\n print('Output %s is saved to %s' % (output_tensor_key, output_full_path))", "docstring": "Runs SavedModel and fetch all outputs.\n\n Runs the input dictionary through the MetaGraphDef within a SavedModel\n specified by the given tag_set and SignatureDef. Also save the outputs to file\n if outdir is not None.\n\nArgs:\n saved_model_dir: Directory containing the SavedModel to execute.\n tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in\n string format, separated by ','. For tag-set contains multiple tags, all\n tags must be passed in.\n signature_def_key: A SignatureDef key string.\n input_tensor_key_feed_dict: A dictionary maps input keys to numpy ndarrays.\n outdir: A directory to save the outputs to. If the directory doesn't exist,\n it will be created.\n overwrite_flag: A boolean flag to allow overwrite output file if file with\n the same name exists.\n worker: If provided, the session will be run on the worker. Valid worker\n specification is a bns or gRPC path.\n init_tpu: If true, the TPU system will be initialized after the session\n is created.\n use_tfrt: If true, TFRT session will be used.\n tf_debug: A boolean flag to use TensorFlow Debugger (TFDBG) to observe the\n intermediate Tensor values and runtime GraphDefs while running the\n SavedModel.\n\nRaises:\n ValueError: When any of the input tensor keys is not valid.\n RuntimeError: An error when output file already exists and overwrite is not\n enabled.", "source": "github_repos"} +{"code": "def resize_position_embeddings(self, new_num_position_embeddings: int):\n logger.info(f'Setting `config.max_position_embeddings={new_num_position_embeddings}`...')\n self.config.max_position_embeddings = new_num_position_embeddings\n self.embed_positions = PegasusXSinusoidalPositionalEmbedding(self.config.d_model)\n self.embed_positions.to(self.device)", "docstring": "Resizes position embeddings matrix of the model if `new_num_position_embeddings !=\n config.max_position_embeddings`.\n\nArgs:\n new_num_position_embeddings (`int`):\n The number of new position embeddings. If position embeddings are learned, increasing the size will add\n newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If\n position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will\n add correct vectors at the end following the position encoding algorithm, whereas reducing the size\n will remove vectors from the end.", "source": "github_repos"} +{"code": "def forward(self, pixel_values: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> ImageClassifierOutputWithNoAttention:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.textnet(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)\n last_hidden_state = outputs[0]\n for layer in self.classifier:\n last_hidden_state = layer(last_hidden_state)\n logits = self.fc(last_hidden_state)\n loss = None\n if labels is not None:\n if self.config.problem_type is None:\n if self.num_labels == 1:\n self.config.problem_type = 'regression'\n elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = 'single_label_classification'\n else:\n self.config.problem_type = 'multi_label_classification'\n if self.config.problem_type == 'regression':\n loss_fct = MSELoss()\n if self.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == 'single_label_classification':\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == 'multi_label_classification':\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n if not return_dict:\n output = (logits,) + outputs[2:]\n return (loss,) + output if loss is not None else output\n return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n\nExample:\n ```python\n >>> import torch\n >>> import requests\n >>> from transformers import TextNetForImageClassification, TextNetImageProcessor\n >>> from PIL import Image\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> processor = TextNetImageProcessor.from_pretrained(\"czczup/textnet-base\")\n >>> model = TextNetForImageClassification.from_pretrained(\"czczup/textnet-base\")\n\n >>> inputs = processor(images=image, return_tensors=\"pt\")\n >>> with torch.no_grad():\n ... outputs = model(**inputs)\n >>> outputs.logits.shape\n torch.Size([1, 2])\n ```", "source": "github_repos"} +{"code": "def _compute_gradients_wrt_embedding_table(self, gradient_wrt_activation, embedding_table, feature_indices, feature_values, combiner):\n if combiner not in ('mean', 'sum'):\n raise ValueError('`combiner` must be mean or sum; got {}.'.format(combiner))\n grads_shape = gradient_wrt_activation.shape[:-1] + embedding_table.shape\n grads = np.zeros(shape=grads_shape)\n count = np.zeros(shape=grads_shape)\n for feature_indice, vocabulary_id in zip(feature_indices, feature_values):\n batch_index = tuple(feature_indice[:-1])\n grads[batch_index][vocabulary_id] += gradient_wrt_activation[batch_index]\n count[batch_index] += 1\n count[count == 0] = 1\n if combiner == 'mean':\n grads = grads / count\n return np.reshape(grads, (-1, *embedding_table.shape))", "docstring": "Compute gradients wrt embedding_table.\n\nArgs:\n gradient_wrt_activation: `np.array` with shape `batch_size` by embedding\n `dimension`.\n embedding_table: `np.array` with shape `vocabulary_size` by embedding\n `dimension`.\n feature_indices: `indices` as used to construct `SparseTensor`.\n feature_values: `values` as used to construct `SparseTensor`.\n combiner: `String`, 'mean' or 'sum'.\n\nReturns:\n Gradients wrt `embedding_table`, an `np.array`s with shape\n `batch_size` by `vocabulary_size` by\n embedding `dimension`.\n\nRaises:\n ValueError: if `combiner` is not one of 'mean' or 'sum'.", "source": "github_repos"} +{"code": "def assert_scalar_v2(tensor, message=None, name=None):\n assert_scalar(tensor=tensor, message=message, name=name)", "docstring": "Asserts that the given `tensor` is a scalar.\n\n This function raises `ValueError` unless it can be certain that the given\n `tensor` is a scalar. `ValueError` is also raised if the shape of `tensor` is\n unknown.\n\n This is always checked statically, so this method returns nothing.\n\nArgs:\n tensor: A `Tensor`.\n message: A string to prefix to the default message.\n name: A name for this operation. Defaults to \"assert_scalar\"\n\nRaises:\n ValueError: If the tensor is not scalar (rank 0), or if its shape is\n unknown.", "source": "github_repos"} +{"code": "def _next_power_of_two(x):\n return 1 if x == 0 else 2 ** (int(x) - 1).bit_length()", "docstring": "Calculates the smallest enclosing power of two for an input.\n\nArgs:\n x: Positive float or integer number.\n\nReturns:\n Next largest power of two integer.", "source": "github_repos"} +{"code": "def is_emulator(self):\n if EMULATOR_SERIAL_REGEX.match(self.serial):\n return True\n elif self.build_info['build_characteristics'] == 'emulator':\n return True\n elif self.build_info['hardware'] in ['ranchu', 'goldfish', 'cutf_cvm']:\n return True\n else:\n return False", "docstring": "Whether this device is probably an emulator.\n\nReturns:\n True if this is probably an emulator.", "source": "github_repos"} +{"code": "def get_sequence_length_feature_key_name_from_feature_key_name(feature_name):\n return feature_name + _SEQUENCE_FEATURE_LENGTH_POSTFIX", "docstring": "Gets the name of the sequence length feature from that of the base feature.\n\nArgs:\n feature_name: The feature key of a sequence column.\n\nReturns:\n A string which is the feature key for the associated feature length column.", "source": "github_repos"} +{"code": "def __init__(self, quantum_h_terms: List[cirq.PauliSum], classical_h_terms: List[cirq.PauliSum], num_layers: int, initializer=tf.keras.initializers.RandomUniform(0, 2 * np.pi), name=None):\n quantum_symbols = []\n classical_symbols = []\n for j in range(num_layers):\n quantum_symbols.append([])\n classical_symbols.append([])\n for k, _ in enumerate(quantum_h_terms):\n quantum_symbols[-1].append(f'gamma_{j}_{k}')\n for k, _ in enumerate(classical_h_terms):\n classical_symbols[-1].append(f'eta_{j}_{k}')\n pqc = cirq.Circuit()\n flat_symbols = []\n for q_symb, c_symb in zip(quantum_symbols, classical_symbols):\n pqc += tfq.util.exponential(quantum_h_terms, coefficients=q_symb)\n pqc += tfq.util.exponential(classical_h_terms, coefficients=c_symb)\n flat_symbols.extend(q_symb + c_symb)\n symbol_names = tf.constant(flat_symbols)\n value_layers_inputs = [[tf.Variable(initializer(shape=[num_layers])), tf.Variable(initializer(shape=[len(classical_h_terms)])), tf.Variable(initializer(shape=[num_layers, len(quantum_h_terms)]))]]\n\n def embed_params(inputs):\n \"\"\"Tiles up the variables to properly tie QAIA parameters.\"\"\"\n exp_etas = tf.expand_dims(inputs[0], 1)\n tiled_thetas = tf.tile(tf.expand_dims(inputs[1], 0), [tf.shape(inputs[0])[0], 1])\n classical_params = exp_etas * tiled_thetas\n return tf.reshape(tf.concat([classical_params, inputs[2]], 1), [-1])\n value_layers = [[tf.keras.layers.Lambda(embed_params)]]\n super().__init__(tfq.convert_to_tensor([pqc]), pqc.all_qubits(), symbol_names, value_layers_inputs, value_layers)", "docstring": "Initializes a QAIA.\n\n The ansatz is QAOA-like, with the exponential of the EBM ansatz in place\n of the usual \"problem Hamiltonian\". Mathematically, it is represented as:\n\n $$\\prod_{\\ell=1}^P \\left[\n \\left(\n \\prod_{\\bm{b} \\in \\mathcal{B}_K}\n e^{i\\eta_\\ell \\theta_{\\bm{b}}\\bm{\\hat{Z}}^{\\bm{b}}}\n \\right)\\left(\n \\prod_{r\\in \\mathcal{I}}\n e^{i\\gamma_{r\\ell}\\hat{H}_r}\n \\right)\n \\right],$$\n\n where $\\hat{H}_r$ is `quantum_h_terms`, $\\bm{\\hat{Z}}^{\\bm{b}}$ is\n `classical_h_terms`, and $P$ is `num_layers`.\n\n # TODO(#119): add link to new version of the paper.\n For further discussion, see the section \"Physics-Inspired Architecture:\n Quantum Adiabatic-Inspired Ansatz\" in the QHBM paper.\n\nArgs:\n quantum_h_terms: Non-commuting terms of the target thermal state\n assumed in the QAIA ansatz.\n classical_h_terms: Hamiltonian representation of the EBM chosen to model\n the target thermal state.\n num_layers: How many layers of the ansatz to apply.\n initializer: A `tf.keras.initializers.Initializer` which specifies how to\n initialize the values of the parameters in `circuit`.\n name: Optional name for the model.", "source": "github_repos"} +{"code": "def parse_float(value: Any) -> Numeric:\n return float(value)", "docstring": "Attempts to parse a valid floating point value from the provided value.\n\nArgs:\n * value: of Any type\n\nReturns:\n * float value: if valid\n\nRaises:\n * ValueError: if parsing failed", "source": "github_repos"} +{"code": "def ops_used_by_graph_def(graph_def):\n name_to_function = {}\n for fun in graph_def.library.function:\n name_to_function[fun.signature.name] = fun\n used_ops = set()\n functions_to_process = []\n\n def mark_op_as_used(op):\n if op not in used_ops and op in name_to_function:\n functions_to_process.append(name_to_function[op])\n used_ops.add(op)\n\n def process_node(node):\n mark_op_as_used(node.op)\n if node.op in ['PartitionedCall', 'StatefulPartitionedCall']:\n mark_op_as_used(node.attr['f'].func.name)\n for node in graph_def.node:\n process_node(node)\n while functions_to_process:\n fun = functions_to_process.pop()\n for node in fun.node_def:\n process_node(node)\n return [op for op in used_ops if op not in name_to_function]", "docstring": "Collect the list of ops used by a graph.\n\n Does not validate that the ops are all registered.\n\nArgs:\n graph_def: A `GraphDef` proto, as from `graph.as_graph_def()`.\n\nReturns:\n A list of strings, each naming an op used by the graph.", "source": "github_repos"} +{"code": "def _try_load_par_source(source_file_path):\n prefix_path = source_file_path\n while True:\n prefix_path, basename = os.path.split(prefix_path)\n if not basename:\n break\n suffix_path = os.path.normpath(os.path.relpath(source_file_path, start=prefix_path))\n if prefix_path.endswith('.par') and os.path.isfile(prefix_path):\n with zipfile.ZipFile(prefix_path) as z:\n norm_names = [os.path.normpath(name) for name in z.namelist()]\n if suffix_path in norm_names:\n with z.open(z.namelist()[norm_names.index(suffix_path)]) as zf:\n source_text = zf.read().decode('utf-8')\n return source_text.split('\\n')", "docstring": "Try loading the source code inside a .par file.\n\n A .par file is a zip-compressed, self-contained Python executable.\n It contains the content of individual Python source files that can\n be read only through extracting from the zip file.\n\nArgs:\n source_file_path: The full path to the file inside the .par file. This\n path should include the path to the .par file itself, followed by the\n intra-par path, e.g.,\n \"/tmp/my_executable.par/org-tensorflow/tensorflow/python/foo/bar.py\".\n\nReturns:\n If successful, lines of the source file as a `list` of `str`s.\n Else, `None`.", "source": "github_repos"} +{"code": "def __init__(self):\n self.return_types = []\n self.exceptions = []", "docstring": "Mutable class for collecting return types and exceptions of functions.\n\n The collecting is stable: Items are kept in the order in which they were\n encountered.\n\nAttributes:\n return_types: Return types seen so far.\n exceptions: Exceptions seen so far.", "source": "github_repos"} +{"code": "def shape_equal(shape1, shape2, axis=None, allow_none=True):\n if len(shape1) != len(shape2):\n return False\n shape1 = list(shape1)\n shape2 = list(shape2)\n if axis is not None:\n if isinstance(axis, int):\n axis = [axis]\n for ax in axis:\n shape1[ax] = -1\n shape2[ax] = -1\n if allow_none:\n for i in range(len(shape1)):\n if shape1[i] is None:\n shape1[i] = shape2[i]\n if shape2[i] is None:\n shape2[i] = shape1[i]\n return shape1 == shape2", "docstring": "Check if two shapes are equal.\n\nArgs:\n shape1: A list or tuple of integers for first shape to be compared.\n shape2: A list or tuple of integers for second shape to be compared.\n axis: An integer, list, or tuple of integers (optional):\n Axes to ignore during comparison. Defaults to `None`.\n allow_none (bool, optional): If `True`, allows `None` in a shape\n to match any value in the corresponding position of the other shape.\n Defaults to `True`.\n\nReturns:\n bool: `True` if shapes are considered equal based on the criteria,\n `False` otherwise.\n\nExample:\n >>> shape_equal((32, 64, 128), (32, 64, 128))\n True\n >>> shape_equal((32, 64, 128), (32, 64, 127))\n False\n >>> shape_equal((32, 64, None), (32, 64, 128), allow_none=True)\n True\n >>> shape_equal((32, 64, None), (32, 64, 128), allow_none=False)\n False\n >>> shape_equal((32, 64, 128), (32, 63, 128), axis=1)\n True\n >>> shape_equal((32, 64, 128), (32, 63, 127), axis=(1, 2))\n True\n >>> shape_equal((32, 64, 128), (32, 63, 127), axis=[1,2])\n True\n >>> shape_equal((32, 64), (32, 64, 128))\n False", "source": "github_repos"} +{"code": "def _kernel_label_map(self, op_to_kernel_label_map) -> Iterator[None]:\n if not isinstance(op_to_kernel_label_map, dict):\n raise TypeError('op_to_kernel_label_map must be a dictionary mapping strings to strings')\n saved_labels = {}\n for op_type, label in op_to_kernel_label_map.items():\n if not (isinstance(op_type, str) and isinstance(label, str)):\n raise TypeError('op_to_kernel_label_map must be a dictionary mapping strings to strings')\n try:\n saved_labels[op_type] = self._op_to_kernel_label_map[op_type]\n except KeyError:\n pass\n self._op_to_kernel_label_map[op_type] = label\n try:\n yield\n finally:\n for op_type, label in op_to_kernel_label_map.items():\n try:\n self._op_to_kernel_label_map[op_type] = saved_labels[op_type]\n except KeyError:\n del self._op_to_kernel_label_map[op_type]", "docstring": "EXPERIMENTAL: A context manager for setting kernel labels.\n\n This context manager can be used to select particular\n implementations of kernels within the scope of the context.\n\n For example:\n\n with ops.Graph().as_default() as g:\n f_1 = Foo() # Uses the default registered kernel for the Foo op.\n with g.kernel_label_map({\"Foo\": \"v_2\"}):\n f_2 = Foo() # Uses the registered kernel with label \"v_2\"\n # for the Foo op.\n with g.kernel_label_map({\"Foo\": \"v_3\"}):\n f_3 = Foo() # Uses the registered kernel with label \"v_3\"\n # for the Foo op.\n with g.kernel_label_map({\"Foo\": \"\"}):\n f_4 = Foo() # Uses the default registered kernel\n # for the Foo op.\n\nArgs:\n op_to_kernel_label_map: A dictionary mapping op type strings to kernel\n label strings.\n\nReturns:\n A context manager that sets the kernel label to be used for one or more\n ops created in that context.\n\nRaises:\n TypeError: If op_to_kernel_label_map is not a dictionary mapping\n strings to strings.", "source": "github_repos"} +{"code": "def __init__(self, l2=0.01):\n l2 = 0.01 if l2 is None else l2\n validate_float_arg(l2, name='l2')\n self.l2 = l2", "docstring": "A regularizer that applies a L2 regularization penalty.\n\n The L2 regularization penalty is computed as:\n `loss = l2 * reduce_sum(square(x))`\n\n L2 may be passed to a layer as a string identifier:\n\n >>> dense = Dense(3, kernel_regularizer='l2')\n\n In this case, the default value used is `l2=0.01`.\n\nArgs:\n l2: float, L2 regularization factor.", "source": "github_repos"} +{"code": "def _filter_valid_filepaths(self, df, x_col):\n filepaths = df[x_col].map(lambda fname: os.path.join(self.directory, fname))\n mask = filepaths.apply(validate_filename, args=(self.white_list_formats,))\n n_invalid = (~mask).sum()\n if n_invalid:\n warnings.warn('Found {} invalid image filename(s) in x_col=\"{}\". These filename(s) will be ignored.'.format(n_invalid, x_col))\n return df[mask]", "docstring": "Keep only dataframe rows with valid filenames.\n\nArgs:\n df: Pandas dataframe containing filenames in a column\n x_col: string, column in `df` that contains the filenames or\n filepaths\n\nReturns:\n absolute paths to image files", "source": "github_repos"} +{"code": "def __init__(self, x: int, y: int=1, **kwargs):\n self.z = x + y + sum(kwargs.values())", "docstring": "Class A.\n\nArgs:\n x: The first integer.\n y: The second integer.\n **kwargs: Other arguments.", "source": "github_repos"} +{"code": "def __init__(self, config, n_bins=16, mlp_dim=256, min_depth=0.001, max_depth=10):\n super().__init__()\n self.in_features = config.bottleneck_features\n self.bin_centers_type = config.bin_centers_type\n self.min_depth = min_depth\n self.max_depth = max_depth\n self.conv1 = nn.Conv2d(self.in_features, mlp_dim, 1, 1, 0)\n self.act1 = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(mlp_dim, n_bins, 1, 1, 0)\n self.act2 = nn.ReLU(inplace=True) if self.bin_centers_type == 'normed' else nn.Softplus()", "docstring": "Bin center regressor network.\n\n Can be \"normed\" or \"unnormed\". If \"normed\", bin centers are bounded on the (min_depth, max_depth) interval.\n\nArgs:\n config (`int`):\n Model configuration.\n n_bins (`int`, *optional*, defaults to 16):\n Number of bin centers.\n mlp_dim (`int`, *optional*, defaults to 256):\n Hidden dimension.\n min_depth (`float`, *optional*, defaults to 1e-3):\n Min depth value.\n max_depth (`float`, *optional*, defaults to 10):\n Max depth value.", "source": "github_repos"} +{"code": "def run(argv=None):\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', dest='input', default='gs://dataflow-samples/wikipedia_edits/*.json', help='Input specified as a GCS path containing a BigQuery table exported as json.')\n parser.add_argument('--output', required=True, help='Output file to write results to.')\n parser.add_argument('--sampling_threshold', type=float, default=0.1, help='Fraction of entries used for session tracking')\n known_args, pipeline_args = parser.parse_known_args(argv)\n pipeline_options = PipelineOptions(pipeline_args)\n pipeline_options.view_as(SetupOptions).save_main_session = True\n with beam.Pipeline(options=pipeline_options) as p:\n p | ReadFromText(known_args.input) | ComputeTopSessions(known_args.sampling_threshold) | WriteToText(known_args.output)", "docstring": "Runs the Wikipedia top edits pipeline.\n\nArgs:\n argv: Pipeline options as a list of arguments.", "source": "github_repos"} +{"code": "def cumsum(x, axis=None, dtype=None):\n return Cumsum(axis=axis, dtype=dtype)(x)", "docstring": "Returns the cumulative sum of elements along a given axis.\n\nArgs:\n x: Input tensor.\n axis: Axis along which the cumulative sum is computed.\n By default the input is flattened.\n dtype: dtype of returned tensor. Defaults to x.dtype.\n\nReturns:\n Output tensor.", "source": "github_repos"} +{"code": "def remat(f):\n\n def wrapped(*args, **kwargs):\n return torch.utils.checkpoint.checkpoint(f, *args, use_reentrant=False)\n return wrapped", "docstring": "Implementation of rematerialization.\n\nArgs:\n f: The function or operation to rematerialize.\n\nReturns:\n A function wrapping f that defines a custom gradient, which\n recomputes f on the backwards pass of a gradient call.", "source": "github_repos"} +{"code": "def GetConsoleAttr(encoding=None, reset=False):\n attr = ConsoleAttr._CONSOLE_ATTR_STATE\n if not reset:\n if not attr:\n reset = True\n elif encoding and encoding != attr.GetEncoding():\n reset = True\n if reset:\n attr = ConsoleAttr(encoding=encoding)\n ConsoleAttr._CONSOLE_ATTR_STATE = attr\n return attr", "docstring": "Gets the console attribute state.\n\n If this is the first call or reset is True or encoding is not None and does\n not match the current encoding or out is not None and does not match the\n current out then the state is (re)initialized. Otherwise the current state\n is returned.\n\n This call associates the out file stream with the console. All console related\n output should go to the same stream.\n\nArgs:\n encoding: Encoding override.\n ascii -- ASCII. This is the default.\n utf8 -- UTF-8 unicode.\n win -- Windows code page 437.\n reset: Force re-initialization if True.\n\nReturns:\n The global ConsoleAttr state object.", "source": "github_repos"} +{"code": "def _einsum_v1_reduction(t0, t0_axis_labels, t1, t1_axis_labels, axes_to_sum):\n if len(t0_axis_labels) != len(t0.shape):\n raise ValueError(f'Tensor `t0` of rank {len(t0.shape)} does not match einsum reduction of length {len(t0_axis_labels)}.')\n if len(t1_axis_labels) != len(t1.shape):\n raise ValueError(f'Tensor `t1` of rank {len(t1.shape)} does not match einsum reduction of length {len(t1_axis_labels)}')\n assert all((a in t0_axis_labels and a in t1_axis_labels for a in axes_to_sum))\n preserved_axes = (set(t0_axis_labels) & set(t1_axis_labels)) - axes_to_sum\n broadcast_axes = {}\n for i, sym_list in enumerate([t0_axis_labels, t1_axis_labels]):\n broadcast_axes[i] = set(sym_list) - preserved_axes - axes_to_sum\n\n def sort_key(input_index, a):\n if a in preserved_axes:\n return (-1, a)\n elif input_index == 0 and a in broadcast_axes[0] or (input_index == 1 and a in axes_to_sum):\n return (0, a)\n else:\n return (1, a)\n axis_labels = [t0_axis_labels, t1_axis_labels]\n sorted_axes = [sorted(sym_list, key=lambda a: sort_key(i, a)) for i, sym_list in enumerate(axis_labels)]\n inputs = [t0, t1]\n for i, axes_str in enumerate(axis_labels):\n perm = [axes_str.find(a) for a in sorted_axes[i]]\n inputs[i] = _transpose_if_necessary(inputs[i], perm)\n t0, t1 = inputs\n if not axes_to_sum:\n for _ in broadcast_axes[1]:\n t0 = array_ops.expand_dims(t0, -1)\n for _ in broadcast_axes[0]:\n t1 = array_ops.expand_dims(t1, len(preserved_axes))\n product = math_ops.multiply(t0, t1)\n product_axes = sorted_axes[0] + sorted_axes[1][len(preserved_axes):]\n return (product, ''.join(product_axes))\n else:\n t0_shape = _get_shape(t0)\n num_broadcast_elements_t0 = _total_size(t0_shape[len(preserved_axes):-len(axes_to_sum)])\n num_summed_elements = _total_size(t0_shape[-len(axes_to_sum):])\n new_shape = t0_shape[:len(preserved_axes)] + [num_broadcast_elements_t0, num_summed_elements]\n t0 = _reshape_if_necessary(t0, new_shape)\n t1_shape = _get_shape(t1)\n num_broadcast_elements_t1 = _total_size(t1_shape[len(preserved_axes) + len(axes_to_sum):])\n new_shape = t1_shape[:len(preserved_axes)] + [num_summed_elements, num_broadcast_elements_t1]\n t1 = _reshape_if_necessary(t1, new_shape)\n product = math_ops.matmul(t0, t1)\n uncompacted_shape = t0_shape[:len(preserved_axes) + len(broadcast_axes[0])] + t1_shape[len(t1_shape) - len(broadcast_axes[1]):]\n product = _reshape_if_necessary(product, uncompacted_shape)\n product_axes = sorted_axes[0][:len(preserved_axes) + len(broadcast_axes[0])] + sorted_axes[1][len(sorted_axes[1]) - len(broadcast_axes[1]):]\n return (product, ''.join(product_axes))", "docstring": "Helper for einsum() that computes the result of a two-argument einsum().\n\nArgs:\n t0: a `Tensor`\n t0_axis_labels: a string of axis labels. This string's length must equal\n the rank of t0.\n t1: a `Tensor`\n t1_axis_labels: a string to axis labels. This string's length must equal\n the rank of t1.\n axes_to_sum: set of labels of axes to be summed over\n\nReturns:\n A `Tensor` whose elements are obtained by summing, over all axes in\n `axes_to_sum`, the corresponding elements of `t0` and `t1`.\n\n For example, if t0_axis_labels == 'abijk', t1_axis_labels == 'acjkl', and\n axes_to_sum == {j,k}, this will return a tensor x where\n\n out[a,b,c,i,l] = sum_j sum_k t0[a,b,i,j,k] * t1[a,c,j,k,l]\n\nRaises:\n ValueError: if the rank of `t0` does not match the length of\n `t0_axis_labels`, or that of `t1` does not match the length of\n `t1_axis_labels`.", "source": "github_repos"} +{"code": "def chain(processor_list: Sequence[Processor | PartProcessor]) -> Processor:\n if not processor_list:\n raise ValueError('processor_list is empty')\n chain_processor = processor_list[0]\n for p in processor_list[1:]:\n chain_processor = chain_processor + p\n if isinstance(chain_processor, PartProcessor):\n chain_processor = chain_processor.to_processor()\n return chain_processor", "docstring": "Chain a sequence of processors.\n\nArgs:\n processor_list: list of part processors or generic processors.\n\nReturns:\n A processor consisting of the chain of all the processors in the list. The\n execution is sequential from the first processor to the last but parts are\n processed concurrently overall.", "source": "github_repos"} +{"code": "def __init__(self, tokenizer=None, **kwargs):\n if tokenizer is None:\n raise ValueError('You need to specify a `tokenizer`.')\n super().__init__(tokenizer)", "docstring": "Constructs a Bros processor which wraps a BERT tokenizer.\n\n [`BrosProcessor`] offers all the functionalities of [`BertTokenizerFast`]. See the docstring of\n [`~BrosProcessor.__call__`] and [`~BrosProcessor.decode`] for more information.\n\nArgs:\n tokenizer (`BertTokenizerFast`, *optional*):\n An instance of ['BertTokenizerFast`]. The tokenizer is a required input.", "source": "github_repos"} +{"code": "def _skip_parameter_matching(self) -> bool:\n if self.signature.type_params:\n return False\n if self.ctx.options.analyze_annotated:\n return False\n return self.signature.has_return_annotation or self.full_name == '__init__'", "docstring": "Check whether we should skip parameter matching.\n\n This is use to skip parameter matching for function calls in the context of\n inference (pyi generation). This is to optimize the case where we don't\n need to match parameters in cases which the function has explicit type\n annotations, meaning that we don't need to infer the type.\n\nReturns:\n True if we should skip parameter matching.", "source": "github_repos"} +{"code": "def delete(paths):\n if isinstance(paths, str):\n raise BeamIOError('Delete passed string argument instead of list: %s' % paths)\n if len(paths) == 0:\n return\n filesystem = FileSystems.get_filesystem(paths[0])\n return filesystem.delete(paths)", "docstring": "Deletes files or directories at the provided paths.\n Directories will be deleted recursively.\n\nArgs:\n paths: list of paths that give the file objects to be deleted\n\nRaises:\n ``BeamIOError``: if any of the delete operations fail", "source": "github_repos"} +{"code": "def max_pooling3d(inputs, pool_size, strides, padding='valid', data_format='channels_last', name=None):\n warnings.warn('`tf.layers.max_pooling3d` is deprecated and will be removed in a future version. Please use `tf.keras.layers.MaxPooling3D` instead.')\n layer = MaxPooling3D(pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, name=name)\n return layer.apply(inputs)", "docstring": "Max pooling layer for 3D inputs (e.g.\n\n volumes).\n\nArgs:\n inputs: The tensor over which to pool. Must have rank 5.\n pool_size: An integer or tuple/list of 3 integers: (pool_depth, pool_height,\n pool_width) specifying the size of the pooling window. Can be a single\n integer to specify the same value for all spatial dimensions.\n strides: An integer or tuple/list of 3 integers, specifying the strides of\n the pooling operation. Can be a single integer to specify the same value\n for all spatial dimensions.\n padding: A string. The padding method, either 'valid' or 'same'.\n Case-insensitive.\n data_format: A string. The ordering of the dimensions in the inputs.\n `channels_last` (default) and `channels_first` are supported.\n `channels_last` corresponds to inputs with shape `(batch, depth, height,\n width, channels)` while `channels_first` corresponds to inputs with shape\n `(batch, channels, depth, height, width)`.\n name: A string, the name of the layer.\n\nReturns:\n Output tensor.\n\nRaises:\n ValueError: if eager execution is enabled.", "source": "github_repos"} +{"code": "def compute_column_logits(sequence_output, column_output_weights, column_output_bias, cell_index, cell_mask, allow_empty_column_selection):\n token_logits = torch.einsum('bsj,j->bs', sequence_output, column_output_weights) + column_output_bias\n cell_logits, cell_logits_index = reduce_mean(token_logits, cell_index)\n column_index = cell_index.project_inner(cell_logits_index)\n column_logits, out_index = reduce_sum(cell_logits * cell_mask, column_index)\n cell_count, _ = reduce_sum(cell_mask, column_index)\n column_logits /= cell_count + EPSILON_ZERO_DIVISION\n is_padding = torch.logical_and(cell_count < 0.5, ~torch.eq(out_index.indices, 0))\n column_logits += CLOSE_ENOUGH_TO_LOG_ZERO * torch.as_tensor(is_padding, dtype=torch.float32, device=is_padding.device)\n if not allow_empty_column_selection:\n column_logits += CLOSE_ENOUGH_TO_LOG_ZERO * torch.as_tensor(torch.eq(out_index.indices, 0), dtype=torch.float32, device=out_index.indices.device)\n return column_logits", "docstring": "Computes the column logits.\n\nArgs:\n sequence_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Also known as last_hidden_state. Sequence of hidden-states at the output of the last layer of the model.\n column_output_weights (`torch.FloatTensor` of shape `(hidden_size)`):\n Weights of the linear layer for column selection.\n column_output_bias (`torch.FloatTensor` of shape `()`):\n Bias of the linear layer for column selection.\n cell_index (`ProductIndexMap`):\n Index that groups tokens into cells.\n cell_mask (`torch.FloatTensor` of shape `(batch_size, max_num_rows * max_num_cols)`):\n Mask for cells that exist in the table (i.e. that are not padding).\n allow_empty_column_selection (`bool`):\n Whether to allow not to select any column\n\nReturns:\n column_logits (`torch.FloatTensor`of shape `(batch_size, max_num_cols)`): Tensor containing the column logits\n for every example in the batch.", "source": "github_repos"} +{"code": "def _get_dequantized_hist_mids_after_quantize(self, quant_min: float, quant_max: float) -> np.ndarray:\n maxbound = 2 ** self._num_bits - 1\n minbound = 0\n scale = (quant_max - quant_min) / maxbound\n zero_point = -quant_min / scale\n if abs(zero_point) > 9000000000.0:\n zero_point = 9000000000.0\n if abs(scale) < 1e-09:\n scale = 1e-09\n zero_point = round(zero_point)\n quantized_hist_mids = np.clip(np.round(self._hist_mids / scale) + zero_point, minbound, maxbound)\n dequantized_hist_mids = scale * (quantized_hist_mids - zero_point)\n return dequantized_hist_mids", "docstring": "Quantizes and dequantizes hist_mids using quant_min and quant_max.\n\n Quantization converts the range of numbers from [quant_min, quant_max] to\n [0, 2^num_bits - 1]. Values less than quant_min are converted to 0, and\n values greater than quant_max are converted to 2^num_bits - 1.\n\n The histogram represents the distribution of the data, and our goal is to\n find the quant_min and quant_max that best describe this distribution. To do\n this, we quantize hist_mids using quant_min and quant_max and dequantize\n them again. Then the difference between hist_mids and dequantized hist_mids\n equates to quantization error when using quant_min and quant_max.\n\nArgs:\n quant_min: The minimum real value that can be represented by a quantized\n value.\n quant_max: The maximum real value that can be represented by a quantized\n value.\n\nReturns:\n dequantized hist_mids after quantizing by quant_min and quant_max", "source": "github_repos"} +{"code": "def slice_arrays(arrays, start=None, stop=None):\n if arrays is None:\n return [None]\n if isinstance(start, list) and stop is not None:\n raise ValueError('The stop argument has to be None if the value of start is a list.')\n elif isinstance(arrays, list):\n if hasattr(start, '__len__'):\n if hasattr(start, 'shape'):\n start = start.tolist()\n return [None if x is None else x[start] for x in arrays]\n return [None if x is None else None if not hasattr(x, '__getitem__') else x[start:stop] for x in arrays]\n else:\n if hasattr(start, '__len__'):\n if hasattr(start, 'shape'):\n start = start.tolist()\n return arrays[start]\n if hasattr(start, '__getitem__'):\n return arrays[start:stop]\n return [None]", "docstring": "Slice an array or list of arrays.\n\n This takes an array-like, or a list of\n array-likes, and outputs:\n - arrays[start:stop] if `arrays` is an array-like\n - [x[start:stop] for x in arrays] if `arrays` is a list\n\n Can also work on list/array of indices: `slice_arrays(x, indices)`\n\nArgs:\n arrays: Single array or list of arrays.\n start: can be an integer index (start index) or a list/array of indices\n stop: integer (stop index); should be None if `start` was a list.\n\nReturns:\n A slice of the array(s).\n\nRaises:\n ValueError: If the value of start is a list and stop is not None.", "source": "github_repos"} +{"code": "def rot90(array, k=1, axes=(0, 1)):\n if any_symbolic_tensors((array,)):\n return Rot90(k=k, axes=axes).symbolic_call(array)\n return backend.numpy.rot90(array, k=k, axes=axes)", "docstring": "Rotate an array by 90 degrees in the plane specified by axes.\n\n This function rotates an array counterclockwise\n by 90 degrees `k` times in the plane specified by `axes`.\n Supports arrays of two or more dimensions.\n\nArgs:\n array: Input array to rotate.\n k: Number of times the array is rotated by 90 degrees.\n axes: A tuple of two integers specifying the\n plane of rotation (defaults to `(0, 1)`).\n\nReturns:\n Rotated array.\n\nExample:\n >>> import numpy as np\n >>> from keras import ops\n >>> m = np.array([[1, 2], [3, 4]])\n >>> rotated = ops.rot90(m)\n >>> rotated\n array([[2, 4],\n [1, 3]])\n\n >>> m = np.arange(8).reshape((2, 2, 2))\n >>> rotated = ops.rot90(m, k=1, axes=(1, 2))\n >>> rotated\n array([[[1, 3],\n [0, 2]],\n [[5, 7],\n [4, 6]]])", "source": "github_repos"} +{"code": "def load_img(path, color_mode='rgb', target_size=None, interpolation='nearest', keep_aspect_ratio=False):\n if pil_image is None:\n raise ImportError('Could not import PIL.Image. The use of `load_img` requires PIL.')\n if isinstance(path, io.BytesIO):\n img = pil_image.open(path)\n elif isinstance(path, (pathlib.Path, bytes, str)):\n if isinstance(path, pathlib.Path):\n path = str(path.resolve())\n with open(path, 'rb') as f:\n img = pil_image.open(io.BytesIO(f.read()))\n else:\n raise TypeError(f'path should be path-like or io.BytesIO, not {type(path)}')\n if color_mode == 'grayscale':\n if img.mode not in ('L', 'I;16', 'I'):\n img = img.convert('L')\n elif color_mode == 'rgba':\n if img.mode != 'RGBA':\n img = img.convert('RGBA')\n elif color_mode == 'rgb':\n if img.mode != 'RGB':\n img = img.convert('RGB')\n else:\n raise ValueError('color_mode must be \"grayscale\", \"rgb\", or \"rgba\"')\n if target_size is not None:\n width_height_tuple = (target_size[1], target_size[0])\n if img.size != width_height_tuple:\n if interpolation not in PIL_INTERPOLATION_METHODS:\n raise ValueError('Invalid interpolation method {} specified. Supported methods are {}'.format(interpolation, ', '.join(PIL_INTERPOLATION_METHODS.keys())))\n resample = PIL_INTERPOLATION_METHODS[interpolation]\n if keep_aspect_ratio:\n width, height = img.size\n target_width, target_height = width_height_tuple\n crop_height = width * target_height // target_width\n crop_width = height * target_width // target_height\n crop_height = min(height, crop_height)\n crop_width = min(width, crop_width)\n crop_box_hstart = (height - crop_height) // 2\n crop_box_wstart = (width - crop_width) // 2\n crop_box_wend = crop_box_wstart + crop_width\n crop_box_hend = crop_box_hstart + crop_height\n crop_box = [crop_box_wstart, crop_box_hstart, crop_box_wend, crop_box_hend]\n img = img.resize(width_height_tuple, resample, box=crop_box)\n else:\n img = img.resize(width_height_tuple, resample)\n return img", "docstring": "Loads an image into PIL format.\n\nExample:\n ```python\n image = keras.utils.load_img(image_path)\n input_arr = keras.utils.img_to_array(image)\n input_arr = np.array([input_arr]) # Convert single image to a batch.\n predictions = model.predict(input_arr)\n ```\n\nArgs:\n path: Path to image file.\n color_mode: One of `\"grayscale\"`, `\"rgb\"`, `\"rgba\"`. Default: `\"rgb\"`.\n The desired image format.\n target_size: Either `None` (default to original size) or tuple of ints\n `(img_height, img_width)`.\n interpolation: Interpolation method used to resample the image if the\n target size is different from that of the loaded image. Supported\n methods are `\"nearest\"`, `\"bilinear\"`, and `\"bicubic\"`.\n If PIL version 1.1.3 or newer is installed, `\"lanczos\"`\n is also supported. If PIL version 3.4.0 or newer is installed,\n `\"box\"` and `\"hamming\"` are also\n supported. By default, `\"nearest\"` is used.\n keep_aspect_ratio: Boolean, whether to resize images to a target\n size without aspect ratio distortion. The image is cropped in\n the center with target aspect ratio before resizing.\n\nReturns:\n A PIL Image instance.", "source": "github_repos"} +{"code": "def get_rots(self) -> Rotation:\n return self._rots", "docstring": "Getter for the rotation.\n\nReturns:\n The rotation object", "source": "github_repos"} +{"code": "def __init__(self, conf):\n super(S3FilesSource, self).__init__(conf)\n self._SetDefaults(conf)\n self.s3_client = None", "docstring": "Initialise the S3FilesSource object.\n\nArgs:\n conf: A dictionary of key/value pairs.\n\nRaises:\n RuntimeError: object wasn't initialised with a dict", "source": "github_repos"} +{"code": "def delete_weight(self, object_name, weight_name):\n\n def delete_weight_fn(weights_dict, source_name, target_name=None):\n if weight_name not in weights_dict[source_name]:\n raise ValueError(f'Weight {weight_name} not found in object {object_name}. Weights found: {list(weights_dict[source_name].keys())}')\n weights_dict[source_name].pop(weight_name)\n self._edit_object(delete_weight_fn, object_name)", "docstring": "Removes a weight from an existing object.\n\nArgs:\n object_name: String, name or path of the\n object from which to remove the weight\n (e.g. `\"dense_2\"` or `\"layers/dense_2\"`).\n weight_name: String, name of the weight to\n delete (e.g. `\"0\"`).", "source": "github_repos"} +{"code": "def set_base_log(self, dqm_version_id: str, workflow_execution_id: str, table_metadata: TableMetadata, run_dt_utc: datetime) -> None:\n self._base_log = LogMessage(dqm_version_id=dqm_version_id, workflow_execution_id=workflow_execution_id, project_id=table_metadata.project_id, dataset_id=table_metadata.dataset_id, table_name=table_metadata.table_name, full_table_id=table_metadata.full_table_id, run_timestamp_utc=get_formatted_timestamp(run_dt_utc))", "docstring": "Set the common values for each log message.\n\nArgs:\n * dqm_version_id: DQM version ID\n * workflow_execution_id: Workflow execution ID\n * table_metadata: Source TableMetadata\n * run_dt_utc: UTC timestamp object\n\nReturns:\n * None", "source": "github_repos"} +{"code": "def sample_point(input_features: torch.Tensor, point_coordinates: torch.Tensor, add_dim=False, **kwargs) -> torch.Tensor:\n if point_coordinates.dim() == 3:\n add_dim = True\n point_coordinates = point_coordinates.unsqueeze(2)\n point_features = torch.nn.functional.grid_sample(input_features, 2.0 * point_coordinates - 1.0, **kwargs)\n if add_dim:\n point_features = point_features.squeeze(3)\n return point_features", "docstring": "A wrapper around `torch.nn.functional.grid_sample` to support 3D point_coordinates tensors.\n\nArgs:\n input_features (`torch.Tensor` of shape (batch_size, channels, height, width)):\n A tensor that contains features map on a height * width grid\n point_coordinates (`torch.Tensor` of shape (batch_size, num_points, 2) or (batch_size, grid_height, grid_width,:\n 2)):\n A tensor that contains [0, 1] * [0, 1] normalized point coordinates\n add_dim (`bool`):\n boolean value to keep track of added dimension\n\nReturns:\n point_features (`torch.Tensor` of shape (batch_size, channels, num_points) or (batch_size, channels,\n height_grid, width_grid):\n A tensor that contains features for points in `point_coordinates`.", "source": "github_repos"} +{"code": "def add_to_tensor(self, mat, name='add_to_tensor'):\n with self._name_scope(name):\n multiplier_vector = array_ops.expand_dims(self.multiplier, -1)\n mat = tensor_conversion.convert_to_tensor_v2_with_dispatch(mat, name='mat')\n mat_diag = array_ops.matrix_diag_part(mat)\n new_diag = multiplier_vector + mat_diag\n return array_ops.matrix_set_diag(mat, new_diag)", "docstring": "Add matrix represented by this operator to `mat`. Equiv to `I + mat`.\n\nArgs:\n mat: `Tensor` with same `dtype` and shape broadcastable to `self`.\n name: A name to give this `Op`.\n\nReturns:\n A `Tensor` with broadcast shape and same `dtype` as `self`.", "source": "github_repos"} +{"code": "def AddTokenToState(self, newline, dry_run, must_split=False):\n self._PushParameterListState(newline)\n penalty = 0\n if newline:\n penalty = self._AddTokenOnNewline(dry_run, must_split)\n else:\n self._AddTokenOnCurrentLine(dry_run)\n penalty += self._CalculateComprehensionState(newline)\n penalty += self._CalculateParameterListState(newline)\n return self.MoveStateToNextToken() + penalty", "docstring": "Add a token to the format decision state.\n\n Allow the heuristic to try out adding the token with and without a newline.\n Later on, the algorithm will determine which one has the lowest penalty.\n\nArgs:\n newline: (bool) Add the token on a new line if True.\n dry_run: (bool) Don't commit whitespace changes to the FormatToken if\n True.\n must_split: (bool) A newline was required before this token.\n\nReturns:\n The penalty of splitting after the current token.", "source": "github_repos"} +{"code": "def singleprint(self) -> fingerprinting_pywrap.Singleprint:\n try:\n return fingerprinting_pywrap.Singleprint(self.graph_def_program_hash, self.signature_def_hash, self.saved_object_graph_hash, self.checkpoint_hash)\n except (TypeError, fingerprinting_pywrap.FingerprintException) as e:\n raise ValueError(f'Encounted invalid fingerprint values when constructing singleprint.graph_def_program_hash: {self.graph_def_program_hash}signature_def_hash: {self.signature_def_hash}saved_object_graph_hash: {self.saved_object_graph_hash}checkpoint_hash: {self.checkpoint_hash}{e}') from None", "docstring": "Canonical fingerprinting ID for a SavedModel.\n\n Uniquely identifies a SavedModel based on the regularized fingerprint\n attributes. (saved_model_checksum is sensitive to immaterial changes and\n thus non-deterministic.)\n\nReturns:\n The string concatenation of `graph_def_program_hash`,\n `signature_def_hash`, `saved_object_graph_hash`, and `checkpoint_hash`\n fingerprint attributes (separated by '/').\n\nRaises:\n ValueError: If the fingerprint fields cannot be used to construct the\n singleprint.", "source": "github_repos"} +{"code": "def get_header(graphs, proto_fileformat='rawproto', default_ops='NoOp:NoOp,_Recv:RecvOp,_Send:SendOp'):\n ops_and_kernels = get_ops_and_kernels(proto_fileformat, graphs, default_ops)\n if not ops_and_kernels:\n print('Error reading graph!')\n return 1\n return get_header_from_ops_and_kernels(ops_and_kernels, default_ops == 'all')", "docstring": "Computes a header for use with tensorflow SELECTIVE_REGISTRATION.\n\nArgs:\n graphs: a list of paths to GraphDef files to include.\n proto_fileformat: optional format of proto file, either 'textproto',\n 'rawproto' (default) or ops_list. The ops_list is the file contain the\n list of ops in JSON format, Ex: \"[[\"Transpose\", \"TransposeCpuOp\"]]\".\n default_ops: optional comma-separated string of operator:kernel pairs to\n always include implementation for. Pass 'all' to have all operators and\n kernels included. Default: 'NoOp:NoOp,_Recv:RecvOp,_Send:SendOp'.\n\nReturns:\n the string of the header that should be written as ops_to_register.h.", "source": "github_repos"} +{"code": "def filter_hunks_by_path(hunks: Iterable[diff_parser.Hunk], *, path_regexes: list[str], path_regex_exclusions: list[str]) -> list[diff_parser.Hunk]:\n if not path_regexes:\n path_regexes = ['.*']\n path_regexes = [re.compile(regex) for regex in path_regexes]\n\n def should_include(path: str) -> bool:\n return any((regex.search(path) for regex in path_regexes))\n path_regex_exclusions = [re.compile(regex) for regex in path_regex_exclusions]\n\n def should_exclude(path: str) -> bool:\n return any((regex.search(path) for regex in path_regex_exclusions))\n return [hunk for hunk in hunks if should_include(hunk.file) and (not should_exclude(hunk.file))]", "docstring": "Filters files according to path_regexes.\n\n If a file matches both a path_regex and a path_regex_exclusion, then\n it will be filtered out.\n\nArgs:\n hunks: A sequence of Hunk objects representing the hunks of the diff in the\n change.\n path_regexes: A list of regexes. Paths matching these will pass through the\n filter. By default, every path is matched.\n path_regex_exclusions: A list of regexes. Paths that match both a path_regex\n and a path_regex_exclusion won't pass through the filter.\n\nReturns:\n A list of FileDiffs whose paths match a path_regex and don't match\n any path_regex_exclusions.", "source": "github_repos"} +{"code": "def _Consumers(t, func_graphs):\n consumers = t.consumers()\n for func in func_graphs:\n for input_t, placeholder in _Captures(func):\n if input_t is t:\n consumers.extend(_Consumers(placeholder, func_graphs))\n return consumers", "docstring": "Returns the consumers of t, crossing closure boundaries where necessary.\n\nArgs:\n t: Tensor\n func_graphs: a list of FuncGraphs that may have captured t.\n\nReturns:\n A list of tensors. The tensors will be from the current graph and/or\n func_graphs.", "source": "github_repos"} +{"code": "def _bigbird_block_rand_mask(self, from_seq_length, to_seq_length, from_block_size, to_block_size, num_rand_blocks, last_idx=-1):\n if from_seq_length // from_block_size != to_seq_length // to_block_size:\n raise ValueError('Error the number of blocks needs to be same!')\n rand_attn = np.zeros((from_seq_length // from_block_size - 2, num_rand_blocks), dtype=np.int32)\n if not self.training:\n return rand_attn\n middle_seq = np.arange(1, to_seq_length // to_block_size - 1, dtype=np.int32)\n last = to_seq_length // to_block_size - 1\n if last_idx > 2 * to_block_size:\n last = last_idx // to_block_size - 1\n r = num_rand_blocks\n for i in range(1, from_seq_length // from_block_size - 1):\n start = i - 2\n end = i\n if i == 1:\n rand_attn[i - 1, :] = np.random.permutation(middle_seq[2:last])[:r]\n elif i == 2:\n rand_attn[i - 1, :] = np.random.permutation(middle_seq[3:last])[:r]\n elif i == from_seq_length // from_block_size - 3:\n rand_attn[i - 1, :] = np.random.permutation(middle_seq[:last])[:r]\n elif i == from_seq_length // from_block_size - 2:\n rand_attn[i - 1, :] = np.random.permutation(middle_seq[:last])[:r]\n elif start > last:\n start = last\n rand_attn[i - 1, :] = np.random.permutation(middle_seq[:start])[:r]\n elif end + 1 == last:\n rand_attn[i - 1, :] = np.random.permutation(middle_seq[:start])[:r]\n else:\n rand_attn[i - 1, :] = np.random.permutation(np.concatenate((middle_seq[:start], middle_seq[end + 1:last])))[:r]\n return rand_attn", "docstring": "Create adjacency list of random attention.\n\nArgs:\n from_seq_length: int. length of from sequence.\n to_seq_length: int. length of to sequence.\n from_block_size: int. size of block in from sequence.\n to_block_size: int. size of block in to sequence.\n num_rand_blocks: int. Number of random chunks per row.\n last_idx: if -1 then num_rand_blocks blocks chosen anywhere in to sequence,\n if positive then num_rand_blocks blocks chosen only up to last_idx.\n\nReturns:\n adjacency list of size from_seq_length//from_block_size-2 by num_rand_blocks", "source": "github_repos"} +{"code": "def _get_analytic_path(path: str, elem_id: str) -> str:\n extension_slice_names = _EXTENSION_SLICE_NAMES_RE.findall(elem_id)\n if extension_slice_names:\n extension_path_elements = _EXTENSION_PATH_ELEMENTS_RE.finditer(path)\n index_adjustment = 0\n for slice_name, path_element in zip(extension_slice_names, extension_path_elements):\n start = path_element.start(1) + index_adjustment\n end = path_element.end(1) + index_adjustment\n path = path[:start] + slice_name + path[end:]\n index_adjustment += len(slice_name) - 9\n path = path.replace('[x]', '')\n return path", "docstring": "Builds a usable FHIRPath given an element path and id.\n\n Removes choice type indicators '[x]'\n\n Some element definitions reference attributes from extension slices. These\n elements will have ids like 'Foo.extension:someExtension' but\n paths like 'Foo.extension' We want to treat these paths as\n 'Foo.someExtension' so we replace the 'extension' part of the\n path with the slice name.\n\nArgs:\n path: The path attribute from the element definition to clean.\n elem_id: The id attribute from the element definition to clean.\n\nReturns:\n The cleaned path name.", "source": "github_repos"} +{"code": "def Encode(string, encoding=None):\n del encoding\n return string", "docstring": "Encode the text string to a byte string.\n\nArgs:\n string: str, The text string to encode.\n encoding: The suggested encoding if known.\n\nReturns:\n str, The binary string.", "source": "github_repos"} +{"code": "def get_image_features(self, pixel_values: torch.FloatTensor, pixel_attention_mask: torch.LongTensor=None):\n batch_size, num_images, num_channels, height, width = pixel_values.shape\n pixel_values = pixel_values.view(batch_size * num_images, *pixel_values.shape[2:])\n nb_values_per_image = pixel_values.shape[1:].numel()\n real_images_inds = (pixel_values == 0.0).sum(dim=(-1, -2, -3)) != nb_values_per_image\n if not any(real_images_inds):\n real_images_inds[0] = True\n pixel_values = pixel_values[real_images_inds].contiguous()\n if pixel_attention_mask is None:\n pixel_attention_mask = torch.ones(size=[pixel_values.shape[i] for i in (0, 2, 3)], dtype=torch.bool, device=pixel_values.device)\n else:\n pixel_attention_mask = pixel_attention_mask.view(batch_size * num_images, *pixel_attention_mask.shape[2:])\n pixel_attention_mask = pixel_attention_mask[real_images_inds].contiguous()\n patch_size = self.config.vision_config.patch_size\n patches_subgrid = pixel_attention_mask.unfold(dimension=1, size=patch_size, step=patch_size)\n patches_subgrid = patches_subgrid.unfold(dimension=2, size=patch_size, step=patch_size)\n patch_attention_mask = (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()\n image_hidden_states = self.vision_model(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)\n image_hidden_states = image_hidden_states.last_hidden_state\n image_hidden_states = self.connector(image_hidden_states)\n return image_hidden_states", "docstring": "Encodes images into continuous embeddings that can be forwarded to the language model.\n\nArgs:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):\n The tensors corresponding to the input images.\n pixel_attention_mask (`torch.LongTensor`, *optional*):\n The attention mask indicating padded regions in the image.", "source": "github_repos"} +{"code": "def register(self, obj, value):\n if obj in self._registry:\n raise KeyError(f'{type(obj)} has already been registered.')\n self._registry[obj] = value", "docstring": "Registers a Python object within the registry.\n\nArgs:\n obj: The object to add to the registry.\n value: The stored value for the 'obj' type.\n\nRaises:\n KeyError: If the same obj is used twice.", "source": "github_repos"} +{"code": "def _from_config(cls, config, **kwargs):\n torch_dtype = kwargs.pop('torch_dtype', config.torch_dtype)\n if isinstance(torch_dtype, str):\n torch_dtype = getattr(torch, torch_dtype)\n dtype_orig = None\n if torch_dtype is not None:\n dtype_orig = cls._set_default_torch_dtype(torch_dtype)\n config = copy.deepcopy(config)\n if config._attn_implementation_internal is not None:\n attn_implementation = config._attn_implementation_internal\n else:\n attn_implementation = None\n config._attn_implementation = kwargs.pop('attn_implementation', attn_implementation)\n if not getattr(config, '_attn_implementation_autoset', False):\n config = cls._autoset_attn_implementation(config, check_device_map=False, torch_dtype=torch_dtype)\n if is_deepspeed_zero3_enabled() and (not _is_quantized) and (not _is_ds_init_called):\n logger.info('Detected DeepSpeed ZeRO-3: activating zero.init() for this model')\n import deepspeed\n init_contexts = [deepspeed.zero.Init(config_dict_or_path=deepspeed_config()), set_zero3_state()]\n with ContextManagers(init_contexts):\n model = cls(config, **kwargs)\n else:\n model = cls(config, **kwargs)\n if dtype_orig is not None:\n torch.set_default_dtype(dtype_orig)\n return model", "docstring": "All context managers that the model should be initialized under go here.\n\nArgs:\n torch_dtype (`torch.dtype`, *optional*):\n Override the default `torch.dtype` and load the model under this dtype.", "source": "github_repos"} +{"code": "def most_recent_n(self, n):\n return self._commands[-n:]", "docstring": "Look up the n most recent commands.\n\nArgs:\n n: Number of most recent commands to look up.\n\nReturns:\n A list of n most recent commands, or all available most recent commands,\n if n exceeds size of the command history, in chronological order.", "source": "github_repos"} +{"code": "def __init__(self, dtype, size=None, dynamic_size=None, clear_after_read=None, tensor_array_name=None, handle=None, flow=None, infer_shape=True, element_shape=None, colocate_with_first_write_call=True, name=None):\n assert handle is None\n del handle\n del clear_after_read\n del tensor_array_name\n del colocate_with_first_write_call\n self._dynamic_size = dynamic_size\n self._size = size\n if flow is not None and (not isinstance(flow, tensor_lib.Tensor) or flow.dtype != dtypes.variant):\n raise TypeError(f'Expected `flow` to be a variant tensor, but received `{flow.dtype}` instead.')\n if flow is None and size is None:\n raise ValueError('Argument `size` must be provided if argument `flow` is not provided.')\n if flow is not None and size is not None:\n raise ValueError('Cannot provide both `flow` and `size` arguments at the same time.')\n if flow is not None and element_shape is not None:\n raise ValueError('Cannot provide both `flow` and `element_shape` argumentsat the same time.')\n self._dtype = dtypes.as_dtype(dtype).base_dtype\n self._element_shape = [tensor_shape.as_shape(element_shape)]\n self._infer_shape = infer_shape\n with ops.name_scope(name, 'TensorArrayV2', [size, flow]) as scope:\n if flow is None:\n self._flow = list_ops.tensor_list_reserve(element_shape=element_shape, num_elements=size, element_dtype=dtype, name=scope)\n else:\n self._flow = flow\n self._colocate_with_first_write_call = None\n self._colocate_with = None", "docstring": "Constructs a graph mode TensorArray.\n\nArgs:\n dtype: (required) data type of the TensorArray.\n size: (optional) int32 scalar `Tensor`: the size of the TensorArray.\n Required if flow is not provided.\n dynamic_size: (optional) Python bool: If true, writes to the TensorArray\n can grow the TensorArray past its initial size. Default: False.\n clear_after_read: (optional) unused. Not supported in TensorLists.\n tensor_array_name: (optional) unused.\n handle: (optional) Must always be None.\n flow: (optional) A variant `Tensor` scalar for a TensorList.\n infer_shape: (optional, default: True) If True, shape inference is\n enabled. In this case, all elements must have the same shape.\n element_shape: (optional, default: None) A `TensorShape` object specifying\n the shape constraints of each of the elements of the TensorArray. Need\n not be fully defined.\n colocate_with_first_write_call: (optional). unused.\n name: (optional) A name for the operation.\n\nRaises:\n ValueError: if both handle and tensor_array_name are provided.\n TypeError: if handle is provided but is not a Tensor.", "source": "github_repos"} +{"code": "def get_num_bytes(self, batch: Sequence[tf.Tensor]) -> int:\n return sum((sys.getsizeof(element) for element in batch))", "docstring": "Returns:\n The number of bytes of data for a batch of Tensors.", "source": "github_repos"} +{"code": "def __init__(self, name, qual_type, external):\n Qualifier.__init__(self, name, qual_type)\n self.external_name = external\n module, event = external.rsplit('.', 1)\n self.external = importlib.import_module(module).__getattribute__(event)()", "docstring": "Wraps an external qualifier defined in a python file.\n\nExample:\n qualifier int RandomInt() = external \"foo.bar.RandomInt\";\n\n There should be a python module \"foo.bar\" with a class RandomInt that inherits\n stl.lib.Qualifier.\n\nAttributes:\n external_name: Name of class that extends stl.lib.Qualifier.\n external: An instance of the stl.lib.Qualifier class.", "source": "github_repos"} +{"code": "def __init__(self, window_ms: int=1, bucket_ms: int=1, overload_ratio: float=2, delay_secs: int=5):\n self.throttler = AdaptiveThrottler(window_ms=window_ms, bucket_ms=bucket_ms, overload_ratio=overload_ratio)\n self.delay_secs = delay_secs", "docstring": "Default throttler that uses\n :class:`apache_beam.io.components.adaptive_throttler.AdaptiveThrottler`\n\nArgs:\n window_ms (int): length of history to consider, in ms, to set throttling.\n bucket_ms (int): granularity of time buckets that we store data in, in ms.\n overload_ratio (float): the target ratio between requests sent and\n successful requests. This is \"K\" in the formula in\n https://landing.google.com/sre/book/chapters/handling-overload.html.\n delay_secs (int): minimum number of seconds to throttle a request.", "source": "github_repos"} +{"code": "def do_quantize_training_on_graphdef(input_graph, num_bits):\n graph = graph_pb2.GraphDef()\n result_graph_string = DoQuantizeTrainingOnGraphDefHelper(input_graph.SerializeToString(), num_bits)\n graph.ParseFromString(result_graph_string)\n return graph", "docstring": "A general quantization scheme is being developed in `tf.contrib.quantize`.\n\n Consider using that instead, though since it is in the tf.contrib namespace,\n it is not subject to backward compatibility guarantees.\n\nArgs:\n input_graph: A `GraphDef`.\n num_bits: The number of bits for quantize training.\n\nReturns:\n The graph with quantize training done.", "source": "github_repos"} +{"code": "def run_metadata_graphs(name, data, step=None):\n summary_metadata = summary_pb2.SummaryMetadata()\n summary_metadata.plugin_data.plugin_name = 'graph_run_metadata_graph'\n summary_metadata.plugin_data.content = b'1'\n data = config_pb2.RunMetadata(function_graphs=data.function_graphs, partition_graphs=data.partition_graphs)\n with summary_scope(name, 'graph_run_metadata_graph_summary', [data, step]) as (tag, _):\n with ops.device('cpu:0'):\n tensor = constant_op.constant(data.SerializeToString(), dtype=dtypes.string)\n return write(tag=tag, tensor=tensor, step=step, metadata=summary_metadata)", "docstring": "Writes graphs from a RunMetadata summary.\n\nArgs:\n name: A name for this summary. The summary tag used for TensorBoard will be\n this name prefixed by any active name scopes.\n data: A RunMetadata proto to write.\n step: Explicit `int64`-castable monotonic step value for this summary. If\n omitted, this defaults to `tf.summary.experimental.get_step()`, which must\n not be None.\n\nReturns:\n True on success, or false if no summary was written because no default\n summary writer was available.\n\nRaises:\n ValueError: if a default writer exists, but no step was provided and\n `tf.summary.experimental.get_step()` is None.", "source": "github_repos"} +{"code": "def __init__(self, features, retry=None, timeout=120, max_batch_size=None, min_batch_size=None, client_options=None, metadata=None):\n super().__init__(features=features, retry=retry, timeout=timeout, max_batch_size=max_batch_size, min_batch_size=min_batch_size, client_options=client_options, metadata=metadata)", "docstring": "Args:\n features: (List[``vision.Feature``]) Required.\n The Vision API features to detect\n retry: (google.api_core.retry.Retry) Optional.\n A retry object used to retry requests.\n If None is specified (default), requests will not be retried.\n timeout: (float) Optional.\n The time in seconds to wait for the response from the Vision API.\n Default is 120.\n max_batch_size: (int) Optional.\n Maximum number of images to batch in the same request to the Vision API.\n Default is 5 (which is also the Vision API max).\n This parameter is primarily intended for testing.\n min_batch_size: (int) Optional.\n Minimum number of images to batch in the same request to the Vision API.\n Default is None. This parameter is primarily intended for testing.\n client_options:\n (Union[dict, google.api_core.client_options.ClientOptions]) Optional.\n Client options used to set user options on the client.\n API Endpoint should be set through client_options.\n metadata: (Optional[Sequence[Tuple[str, str]]]): Optional.\n Additional metadata that is provided to the method.", "source": "github_repos"} +{"code": "def update_state(self, y_true, y_pred, sample_weight=None):\n y_true = math_ops.cast(y_true, self._dtype)\n y_pred = math_ops.cast(y_pred, self._dtype)\n y_pred, y_true = losses_utils.squeeze_or_expand_dimensions(y_pred, y_true)\n error_sq = math_ops.squared_difference(y_pred, y_true)\n return super(RootMeanSquaredError, self).update_state(error_sq, sample_weight=sample_weight)", "docstring": "Accumulates root mean squared error statistics.\n\nArgs:\n y_true: The ground truth values.\n y_pred: The predicted values.\n sample_weight: Optional weighting of each example. Defaults to 1. Can be a\n `Tensor` whose rank is either 0, or the same rank as `y_true`, and must\n be broadcastable to `y_true`.\n\nReturns:\n Update op.", "source": "github_repos"} +{"code": "def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:\n batch_size_and_num_heads, seq_length, _ = x.shape\n batch_size = batch_size_and_num_heads // self.num_heads\n x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)\n x = x.permute(0, 2, 1, 3)\n return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)", "docstring": "Merge heads together over the last dimension\n\nArgs:\n x (`torch.tensor`): [batch_size * num_heads, seq_length, head_dim]\n\nReturns:\n torch.tensor: [batch_size, seq_length, num_heads * head_dim]", "source": "github_repos"} +{"code": "def __init__(self, step, metric, labels=None):\n self.step = step\n self.metric = metric\n self.labels = labels if labels else {}", "docstring": "Initializes ``MetricKey``.\n\nArgs:\n step: A string with the step this metric cell is part of.\n metric: A ``MetricName`` namespace+name that identifies a metric.\n labels: An arbitrary set of labels that also identifies the metric.", "source": "github_repos"} +{"code": "def _iceberg_io_read_test_preprocessor(test_spec: dict, expected: List[str], env: TestEnvironment):\n if (pipeline := test_spec.get('pipeline', None)):\n for transform in pipeline.get('transforms', []):\n if transform.get('type', '') == 'ReadFromIceberg':\n config = transform['config']\n db_name, table_name, field_value_dynamic_destinations = config['table'].split('.')\n transform['type'] = 'Create'\n transform['config'] = {k: v for k, v in config.items() if k.startswith('__')}\n transform['config']['elements'] = INPUT_TABLES[str(db_name), str(table_name), str(field_value_dynamic_destinations)]\n return test_spec", "docstring": "Preprocessor for tests that involve reading from Iceberg.\n\n This preprocessor replaces any ReadFromIceberg transform with a Create\n transform that reads from a predefined in-memory dictionary. This allows\n the test to verify the pipeline's correctness without relying on Iceberg\n tables stored externally.\n\nArgs:\n test_spec: The dictionary representation of the YAML pipeline specification.\n expected: A list of strings representing the expected output of the\n pipeline.\n env: The TestEnvironment object providing utilities for creating temporary\n files.\n\nReturns:\n The modified test_spec dictionary with ReadFromIceberg transforms replaced.", "source": "github_repos"} +{"code": "def get_unconditional_inputs(self, num_samples=1, return_tensors='pt'):\n inputs = self.tokenizer([''] * num_samples, return_tensors=return_tensors, return_attention_mask=True)\n inputs['attention_mask'][:] = 0\n return inputs", "docstring": "Helper function to get null inputs for unconditional generation, enabling the model to be used without the\n feature extractor or tokenizer.\n\nArgs:\n num_samples (int, *optional*):\n Number of audio samples to unconditionally generate.\n\nExample:\n ```python\n >>> from transformers import MusicgenMelodyForConditionalGeneration, MusicgenMelodyProcessor\n\n >>> model = MusicgenMelodyForConditionalGeneration.from_pretrained(\"facebook/musicgen-melody\")\n\n >>> # get the unconditional (or 'null') inputs for the model\n >>> processor = MusicgenMelodyProcessor.from_pretrained(\"facebook/musicgen-melody\")\n >>> unconditional_inputs = processor.get_unconditional_inputs(num_samples=1)\n\n >>> audio_samples = model.generate(**unconditional_inputs, max_new_tokens=256)\n ```", "source": "github_repos"} +{"code": "def _make_callable(self, feed_arrays, feed_symbols, symbol_vals, session):\n callable_opts = config_pb2.CallableOptions()\n for x in feed_arrays:\n callable_opts.feed.append(x.name)\n if self.feed_dict:\n for key in sorted(self.feed_dict.keys()):\n callable_opts.feed.append(key.name)\n for x, y in zip(feed_symbols, symbol_vals):\n connection = callable_opts.tensor_connection.add()\n if x.dtype != y.dtype:\n y = math_ops.cast(y, dtype=x.dtype)\n from_tensor = _as_graph_element(y)\n if from_tensor is None:\n from_tensor = y\n connection.from_tensor = from_tensor.name\n connection.to_tensor = x.name\n for x in self.outputs + self.fetches:\n callable_opts.fetch.append(x.name)\n callable_opts.target.append(self.updates_op.name)\n if self.run_options:\n callable_opts.run_options.CopyFrom(self.run_options)\n callable_fn = session._make_callable_from_options(callable_opts)\n self._callable_fn = callable_fn\n self._feed_arrays = feed_arrays\n self._feed_symbols = feed_symbols\n self._symbol_vals = symbol_vals\n self._fetches = list(self.fetches)\n self._session = session", "docstring": "Generates a callable that runs the graph.\n\nArgs:\n feed_arrays: List of input tensors to be fed Numpy arrays at runtime.\n feed_symbols: List of input tensors to be fed symbolic tensors at runtime.\n symbol_vals: List of symbolic tensors to be fed to `feed_symbols`.\n session: Session to use to generate the callable.\n\nReturns:\n Function that runs the graph according to the above options.", "source": "github_repos"} +{"code": "def center_crop(self, image: np.ndarray, crop_size: Dict[str, int], size: Optional[int]=None, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:\n size = self.size if size is None else size\n size = get_size_dict(size)\n crop_size = get_size_dict(crop_size, param_name='crop_size')\n height, width = get_image_size(image, channel_dim=input_data_format)\n min_dim = min(height, width)\n cropped_height = size['height'] / crop_size['height'] * min_dim\n cropped_width = size['width'] / crop_size['width'] * min_dim\n return center_crop(image, size=(cropped_height, cropped_width), data_format=data_format, input_data_format=input_data_format, **kwargs)", "docstring": "Center crop an image to `(size[\"height\"] / crop_size[\"height\"] * min_dim, size[\"width\"] / crop_size[\"width\"] *\n min_dim)`. Where `min_dim = min(size[\"height\"], size[\"width\"])`.\n\n If the input size is smaller than `crop_size` along any edge, the image will be padded with zeros and then\n center cropped.\n\nArgs:\n image (`np.ndarray`):\n Image to center crop.\n crop_size (`Dict[str, int]`):\n Desired output size after applying the center crop.\n size (`Dict[str, int]`, *optional*):\n Size of the image after resizing. If not provided, the self.size attribute will be used.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.", "source": "github_repos"} +{"code": "def _static_value_provider_of(value_type):\n\n def _f(value):\n _f.__name__ = value_type.__name__\n return StaticValueProvider(value_type, value)\n return _f", "docstring": "Helper function to plug a ValueProvider into argparse.\n\nArgs:\n value_type: the type of the value. Since the type param of argparse's\n add_argument will always be ValueProvider, we need to\n preserve the type of the actual value.\n\nReturns:\n A partially constructed StaticValueProvider in the form of a function.", "source": "github_repos"} +{"code": "def __init__(self, num_groups=2):\n if num_groups < 1:\n raise ValueError(f'Argument `num_groups` must be a positive integer. Received: num_groups={num_groups}')\n self._ready = threading.Condition(threading.Lock())\n self._num_groups = num_groups\n self._group_member_counts = [0] * self._num_groups", "docstring": "Initialize a group lock.\n\nArgs:\n num_groups: The number of groups that will be accessing the resource under\n consideration. Should be a positive number.\n\nReturns:\n A group lock that can then be used to synchronize code.\n\nRaises:\n ValueError: If num_groups is less than 1.", "source": "github_repos"} +{"code": "def _preprocess_async_for_and_yield(idx: int, bytecode: Sequence[opcodes.Opcode], prev_block: Block, processed_blocks: set[Block]) -> tuple[list[Block], int]:\n assert isinstance(bytecode[idx], opcodes.SEND)\n i = next((i for i in range(idx + 1, len(bytecode)) if isinstance(bytecode[i], opcodes.JUMP_BACKWARD_NO_INTERRUPT)))\n end_block_idx = i + 1\n if isinstance(bytecode[end_block_idx], opcodes.CLEANUP_THROW):\n end_block_idx += 1\n send_block = Block(bytecode[idx:idx + 1])\n yield_value_block = Block(bytecode[idx + 1:end_block_idx])\n prev_block.connect_outgoing(send_block)\n send_block.connect_outgoing(yield_value_block)\n processed_blocks.update(send_block, yield_value_block)\n return ([send_block, yield_value_block], end_block_idx)", "docstring": "Process bytecode instructions for yield and async for in a way that pytype can iterate correctly.\n\n 'Async for' and yield statements, contains instructions that starts with SEND\n and ends with END_SEND.\n\n The reason why we need to pre process async for is because the control flow of\n async for is drastically different from regular control flows also due to the\n fact that the termination of the loop happens by STOP_ASYNC_ITERATION\n exception, not a regular control flow. So we need to split (or merge) the\n basic blocks in a way that pytype executes in the order that what'd happen in\n the runtime, so that it doesn't fail with wrong order of execution, which can\n result in a stack underrun.\n\nArgs:\n idx: The index of the SEND instruction.\n bytecode: A list of instances of opcodes.Opcode\n prev_block: The previous block that we want to connect the new blocks to.\n processed_blocks: Blocks that has been processed so that it doesn't get\n processed again by compute_order.\n\nReturns:\n A tuple of (list[Block], int), where the Block is the block containing the\n iteration part of the async for construct, and the int is the index of the\n END_SEND instruction.", "source": "github_repos"} +{"code": "def __init__(self, schema: dict[str, Any], error_handling: Optional[Mapping[str, Any]]=None):\n self._schema = schema\n self._exception_handling_args = exception_handling_args(error_handling)", "docstring": "Validates each element of a PCollection against a json schema.\n\nArgs:\n schema: A json schema against which to validate each element.\n error_handling: Whether and how to handle errors during iteration.\n If this is not set, invalid elements will fail the pipeline, otherwise\n invalid elements will be passed to the specified error output along\n with information about how the schema was invalidated.", "source": "github_repos"} +{"code": "def _strip_padding(tensors, pad_len):\n if not tensors:\n raise ValueError('tensors cannot be empty')\n shape = tensors[0].shape\n if len(shape) > 1:\n raise ValueError('tensors must be 1D')\n prefix_len = int(shape[0] - pad_len)\n if prefix_len < 0:\n raise ValueError('pad_len longer than tensor')\n stripped = []\n for t in tensors:\n with ops.colocate_with(t):\n stripped.append(array_ops.slice(t, [0], [prefix_len]))\n return stripped", "docstring": "Strip the suffix padding added by _padded_split.\n\nArgs:\n tensors: list of `tf.Tensor` of identical length 1D tensors.\n pad_len: number of elements to be stripped from the end of each tensor.\n\nReturns:\n list of `tf.Tensor` which are the stripped inputs.\n\nRaises:\n ValueError: tensors must be a non-empty list of 1D tensors, and\n each must be longer than pad_len.", "source": "github_repos"} +{"code": "def __init__(self, constructor: Callable[[], T], tag: Any, *, path: str=tempfile.gettempdir(), always_proxy: Optional[bool]=None):\n self._constructor = constructor\n self._tag = tag\n self._path = path\n self._always_proxy = False if always_proxy is None else always_proxy\n self._proxy = None\n self._manager = None\n self._rpc_address = None\n self._cross_process_lock = fasteners.InterProcessLock(os.path.join(self._path, self._tag) + '.lock')", "docstring": "MultiProcessShared is used to share a single object across processes.\n\n For example, one could have the class::\n\n class MyExpensiveObject(object):\n def __init__(self, args):\n [expensive initialization and memory allocation]\n\n def method(self, arg):\n ...\n\n One could share a single instance of this class by wrapping it as::\n\n shared_ptr = MultiProcessShared(lambda: MyExpensiveObject(...))\n my_expensive_object = shared_ptr.acquire()\n\n which could then be invoked as::\n\n my_expensive_object.method(arg)\n\n This can then be released with::\n\n shared_ptr.release(my_expensive_object)\n\n but care should be taken to avoid releasing the object too soon or\n expensive re-initialization may be required, defeating the point of\n using a shared object.\n\nArgs:\n constructor: function that initialises / constructs the object if not\n present in the cache. This function should take no arguments. It should\n return an initialised object, or raise an exception if the object could\n not be initialised / constructed.\n tag: an indentifier to store with the cached object. If multiple\n MultiProcessShared instances are created with the same tag, they will all\n share the same proxied object.\n path: a temporary path in which to create the inter-process lock\n always_proxy: whether to direct all calls through the proxy, rather than\n call the object directly for the process that created it", "source": "github_repos"} +{"code": "def argmin(x, axis=-1):\n return math_ops.argmin(x, axis)", "docstring": "Returns the index of the minimum value along an axis.\n\nArgs:\n x: Tensor or variable.\n axis: axis along which to perform the reduction.\n\nReturns:\n A tensor.", "source": "github_repos"} +{"code": "def __init__(self, config, in_features, condition_dim, n_classes=256, bottleneck_factor=2):\n super().__init__()\n bottleneck = (in_features + condition_dim) // bottleneck_factor\n self.mlp = nn.Sequential(nn.Conv2d(in_features + condition_dim, bottleneck, kernel_size=1, stride=1, padding=0), nn.GELU(), nn.Conv2d(bottleneck, 2 + 2, kernel_size=1, stride=1, padding=0), nn.Softplus())\n self.p_eps = 0.0001\n self.max_temp = config.max_temp\n self.min_temp = config.min_temp\n self.log_binomial_transform = LogBinomialSoftmax(n_classes, act=torch.softmax)", "docstring": "Per-pixel MLP followed by a Conditional Log Binomial softmax.\n\nArgs:\n in_features (`int`):\n Number of input channels in the main feature.\n condition_dim (`int`):\n Number of input channels in the condition feature.\n n_classes (`int`, *optional*, defaults to 256):\n Number of classes.\n bottleneck_factor (`int`, *optional*, defaults to 2):\n Hidden dim factor.", "source": "github_repos"} +{"code": "def relayout(tensor: tensor_lib.Tensor, layout: layout_lib.Layout, name: Optional[str]=None) -> tensor_lib.Tensor:\n layout_str = layout.to_string()\n with default_mesh(layout.mesh):\n return gen_dtensor_ops.relayout(tensor, layout_str, name=name)", "docstring": "Changes the layout of `tensor`.\n\n Changes the layout of `tensor` to `layout`. This is used to fine-tune the\n behavior of ops following/connected to `tensor`, such as choosing one SPMD\n expansion pattern over another. This works by forward propagating `layout`\n to connected TensorFlow computation graphs during layout propagation.\n\n Currently, only converting layouts from replicated to sharded or sharded to\n replicated per mesh dimension is supported. That is, \"x, y\" -> \"unsharded, y\"\n is supported, while \"x, y\" -> \"z, y\" is not supported.\n\n We also support a special \"match\" sharding spec, which instructs the relayout\n to act as an identity operation with respect to any sharding on these\n mesh dimensions.\n\n Relayout is internally lowered to a set of Split and/or AllToAll ops. When\n tensor layouts are converted from replicated to sharded, the cost is\n comparatively low because we only insert Split ops and no cross-device\n communication is needed. However, when tensor layouts are converted from\n sharded to replicated, cross-device communication may occur, causing potential\n performance impact.\n\nArgs:\n tensor: A DTensor to specify a new layout for.\n layout: A Layout object specifying a new sharding spec.\n name: name of the Op.\n\nReturns:\n A DTensor output from the Relayout op.", "source": "github_repos"} +{"code": "def cancel(self):\n raise NotImplementedError()", "docstring": "Cancels the pipeline execution.\n\nRaises:\n IOError: If there is a persistent problem getting job\n information.\n NotImplementedError: If the runner does not support this\n operation.\n\nReturns:\n The final state of the pipeline.", "source": "github_repos"} +{"code": "def reduce_mean(values, index, name='segmented_reduce_mean'):\n return _segment_reduce(values, index, tf.math.unsorted_segment_mean, name)", "docstring": "Averages a tensor over its segments. Outputs 0 for empty segments. This operations computes the mean over segments,\n with support for:\n\n - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.\n - Vectorization using the last dimension [V1, V2, ...]. If they are present the output will be a mean of vectors\n rather than scalars.\n Only the middle dimensions [I1, ..., Ik] are reduced by the operation.\n\nArgs:\n values: [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..] tensor of values to be\n averaged.\n index: IndexMap [B1, B2, ..., Bn, I1, .., Ik] index defining the segments.\n name: Name for the TensorFlow ops.\n\nReturns:\n A pair (output_values, output_index) where `output_values` is a tensor of shape [B1, B2, ..., Bn, num_segments,\n V1, V2, ..] and `index` is an IndexMap with shape [B1, B2, ..., Bn, num_segments].", "source": "github_repos"} +{"code": "def num_gpus():\n return context().num_gpus()", "docstring": "Get the number of available GPU devices.\n\nReturns:\n The number of available GPU devices.", "source": "github_repos"} +{"code": "def sanity_check_type(self, other):\n if type(self) is not type(other):\n raise ValueError('No TypeSpec is compatible with both %s and %s' % (self, other))\n if self._input_workers.serialize() != other._input_workers.serialize():\n raise ValueError('_input_workers is not compatible with both %s and %s' % (self, other))\n if self._strategy is not other._strategy:\n raise ValueError('tf.distribute strategy is not compatible with both %s and %s' % (self, other))", "docstring": "Returns the most specific TypeSpec compatible with `self` and `other`.\n\nArgs:\n other: A `TypeSpec`.\n\nRaises:\n ValueError: If there is no TypeSpec that is compatible with both `self`\n and `other`.", "source": "github_repos"} +{"code": "def test_sample_sabr(self, supply_grad_vol_fn):\n dtype = np.float64\n drift_fn = lambda _, x: tf.zeros_like(x)\n beta = tf.constant(0.5, dtype=dtype)\n volvol = tf.constant(1.0, dtype=dtype)\n rho = tf.constant(0.2, dtype=dtype)\n\n def vol_fn(t, x):\n \"\"\"The volatility function for the SABR model.\"\"\"\n del t\n f = x[..., 0]\n v = x[..., 1]\n fb = f ** beta\n m11 = v * fb * tf.math.sqrt(1 - tf.square(rho))\n m12 = v * fb * rho\n m21 = tf.zeros_like(m11)\n m22 = volvol * v\n mc1 = tf.concat([tf.expand_dims(m11, -1), tf.expand_dims(m21, -1)], -1)\n mc2 = tf.concat([tf.expand_dims(m12, -1), tf.expand_dims(m22, -1)], -1)\n should_be_zero = tf.expand_dims(tf.expand_dims((beta != 0) & (f <= 0.0), -1), -1)\n vol_matrix = tf.concat([tf.expand_dims(mc1, -1), tf.expand_dims(mc2, -1)], -1)\n return tf.where(should_be_zero, tf.zeros_like(vol_matrix), vol_matrix)\n if supply_grad_vol_fn:\n\n def _grad_volatility_fn(current_time, current_state, input_gradients):\n return gradient.fwd_gradient(functools.partial(vol_fn, current_time), current_state, input_gradients=input_gradients, unconnected_gradients=tf.UnconnectedGradients.ZERO)\n grad_volatility_fn = _grad_volatility_fn\n else:\n grad_volatility_fn = None\n times = np.array([0.0, 0.1, 0.21, 0.32, 0.43, 0.55])\n x0 = np.array([0.1, 0.2])\n paths = self.evaluate(milstein_sampling.sample(dim=2, drift_fn=drift_fn, volatility_fn=vol_fn, times=times, num_samples=1000, initial_state=x0, grad_volatility_fn=grad_volatility_fn, random_type=tff.math.random.RandomType.STATELESS_ANTITHETIC, time_step=0.01, seed=[1, 42]))\n mean = np.average(paths)\n stddev = np.std(paths)\n euler_paths = self.evaluate(euler_sampling.sample(dim=2, drift_fn=drift_fn, volatility_fn=vol_fn, times=times, time_step=0.01, num_samples=10000, initial_state=x0, random_type=tff.math.random.RandomType.STATELESS_ANTITHETIC, seed=[1, 42]))\n euler_mean = np.average(euler_paths)\n euler_stddev = np.std(euler_paths)\n self.assertAllClose((mean, stddev), (euler_mean, euler_stddev), rtol=0.05, atol=0.05)", "docstring": "Tests path properties for SABR.\n\n We construct the following Ito process.\n\n ```\n dF_t = v_t * F_t ^ beta * dW_{F,t}\n dv_t = volvol * v_t * dW_{v,t}\n dW_{F,t} * dW_{v,t} = rho * dt\n ```\n\n `F_t` is the forward. `v_t` is volatility. `beta` is the CEV parameter.\n `volvol` is volatility of volatility. `W_{F,t}` and `W_{v,t}` are two\n correlated Wiener processes with instantaneous correlation `rho`.\n\nArgs:\n supply_grad_vol_fn: A bool. Whether or not to supply a grad_volatility_fn.", "source": "github_repos"} +{"code": "def annotate_source(dump, source_file_path, do_dumped_tensors=False, file_stack_top=False, min_line=None, max_line=None):\n py_graph = dump.python_graph\n if not py_graph:\n raise ValueError('Cannot perform source annotation due to a lack of set Python graph in the dump object')\n source_file_path = _norm_abs_path(source_file_path)\n line_to_op_names = {}\n for op in py_graph.get_operations():\n for file_path, line_number, _, _ in reversed(dump.node_traceback(op.name)):\n if min_line is not None and line_number < min_line or (max_line is not None and line_number >= max_line):\n continue\n if _norm_abs_path(file_path) != source_file_path:\n continue\n if do_dumped_tensors:\n watch_keys = dump.debug_watch_keys(op.name)\n items_to_append = list(set(map(_convert_watch_key_to_tensor_name, watch_keys)))\n else:\n items_to_append = [op.name]\n if line_number in line_to_op_names:\n line_to_op_names[line_number].extend(items_to_append)\n else:\n line_to_op_names[line_number] = items_to_append\n if file_stack_top:\n break\n return line_to_op_names", "docstring": "Annotate a Python source file with a list of ops created at each line.\n\n (The annotation doesn't change the source file itself.)\n\nArgs:\n dump: (`DebugDumpDir`) A `DebugDumpDir` object of which the Python graph\n has been loaded.\n source_file_path: (`str`) Path to the source file being annotated.\n do_dumped_tensors: (`str`) Whether dumped Tensors, instead of ops are to be\n used to annotate the source file.\n file_stack_top: (`bool`) Whether only the top stack trace in the\n specified source file is to be annotated.\n min_line: (`None` or `int`) The 1-based line to start annotate the source\n file from (inclusive).\n max_line: (`None` or `int`) The 1-based line number to end the annotation\n at (exclusive).\n\nReturns:\n A `dict` mapping 1-based line number to a list of op name(s) created at\n that line, or tensor names if `do_dumped_tensors` is True.\n\nRaises:\n ValueError: If the dump object does not have a Python graph set.", "source": "github_repos"} +{"code": "def push(self, x):\n self._queue.append(x)", "docstring": "Adds a new value to the data window.\n\nArgs:\n x: The value to be added to the window.", "source": "github_repos"} +{"code": "def _AssertProtoDictEquals(self, expected_dict, actual_dict, verbose=False, update_goldens=False, additional_missing_object_message='', api_version=2):\n diffs = []\n verbose_diffs = []\n expected_keys = set(expected_dict.keys())\n actual_keys = set(actual_dict.keys())\n only_in_expected = expected_keys - actual_keys\n only_in_actual = actual_keys - expected_keys\n all_keys = expected_keys | actual_keys\n updated_keys = []\n for key in all_keys:\n diff_message = ''\n verbose_diff_message = ''\n if key in only_in_expected:\n diff_message = 'Object %s expected but not found (removed). %s' % (key, additional_missing_object_message)\n verbose_diff_message = diff_message\n elif key in only_in_actual:\n diff_message = 'New object %s found (added).' % key\n verbose_diff_message = diff_message\n else:\n self.maxDiff = None\n try:\n self.assertProtoEquals(expected_dict[key], actual_dict[key])\n except AssertionError as e:\n updated_keys.append(key)\n diff_message = 'Change detected in python object: %s.' % key\n verbose_diff_message = str(e)\n if diff_message:\n diffs.append(diff_message)\n verbose_diffs.append(verbose_diff_message)\n if diffs:\n diff_count = len(diffs)\n logging.error(self._test_readme_message)\n logging.error('%d differences found between API and golden.', diff_count)\n if update_goldens:\n logging.warning(self._update_golden_warning)\n for key in only_in_expected:\n filepath = _KeyToFilePath(key, api_version)\n file_io.delete_file(filepath)\n for key in only_in_actual | set(updated_keys):\n filepath = _KeyToFilePath(key, api_version)\n file_io.write_string_to_file(filepath, text_format.MessageToString(actual_dict[key]))\n else:\n for d, verbose_d in zip(diffs, verbose_diffs):\n logging.error(' %s', d)\n logging.error(' %s', verbose_d)\n self.fail('%d differences found between API and golden.' % diff_count)\n else:\n logging.info('No differences found between API and golden.')", "docstring": "Diff given dicts of protobufs and report differences a readable way.\n\nArgs:\n expected_dict: a dict of TFAPIObject protos constructed from golden files.\n actual_dict: a dict of TFAPIObject protos constructed by reading from the\n TF package linked to the test.\n verbose: Whether to log the full diffs, or simply report which files were\n different.\n update_goldens: Whether to update goldens when there are diffs found.\n additional_missing_object_message: Message to print when a symbol is\n missing.\n api_version: TensorFlow API version to test.", "source": "github_repos"} +{"code": "def start_app_and_connect(self):\n try:\n self._start_app_and_connect()\n except AppStartPreCheckError:\n raise\n except Exception as e:\n self._ad.log.exception('Failed to start app and connect.')\n try:\n self.stop_app()\n except Exception:\n self._ad.log.exception('Failed to stop app after failure to start and connect.')\n raise e", "docstring": "Starts snippet apk on the device and connects to it.\n\n This wraps the main logic with safe handling\n\nRaises:\n AppStartPreCheckError, when pre-launch checks fail.", "source": "github_repos"} +{"code": "def _run_graph(self, device, dtype, data_format, input_shape, filter_shape, strides, padding, num_iters, warmup_iters):\n graph = ops.Graph()\n with graph.as_default():\n warmup_outputs, outputs = build_graph(device, dtype, data_format, input_shape, filter_shape, strides, padding, num_iters, warmup_iters)\n config = config_pb2.ConfigProto()\n config.graph_options.optimizer_options.opt_level = -1\n rewrite_options = config.graph_options.rewrite_options\n rewrite_options.layout_optimizer = rewriter_config_pb2.RewriterConfig.ON if FLAGS.enable_layout_optimizer else rewriter_config_pb2.RewriterConfig.OFF\n rewrite_options.dependency_optimization = rewriter_config_pb2.RewriterConfig.OFF\n with session_lib.Session(graph=graph, config=config) as session:\n variables.global_variables_initializer().run()\n session.run(warmup_outputs)\n start_time = time.time()\n session.run(outputs)\n duration = (time.time() - start_time) / num_iters\n print('%s %s %s inputshape:%s filtershape:%s strides:%s padding:%s %d iters: %.8f sec' % (device, str(dtype), data_format, str(input_shape).replace(' ', ''), str(filter_shape).replace(' ', ''), str(strides).replace(' ', ''), padding, num_iters, duration))\n name_template = 'conv2d_{device}_{datatype}_{data_format}_input_shape_{inputshape}_filter_shape_{filtershape}_strides_{strides}_padding_{padding}'\n self.report_benchmark(name=name_template.format(device=device, datatype=str(dtype), data_format=str(data_format), inputshape=str(input_shape).replace(' ', ''), filtershape=str(filter_shape).replace(' ', ''), strides=str(strides).replace(' ', ''), padding=padding).replace(' ', ''), iters=num_iters, wall_time=duration)\n return duration", "docstring": "runs the graph and print its execution time.\n\nArgs:\n device: String, the device to run on.\n dtype: Data type for the convolution.\n data_format: A string from: \"NHWC\" or \"NCHW\". Data format for input and\n output data.\n input_shape: Shape of the input tensor.\n filter_shape: Shape of the filter tensor.\n strides: A list of ints. 1-D of length 4. The stride of sliding\n window for each dimension of input.\n padding: A string from: \"SAME\", \"VALID\". The type of padding\n algorithm to use. num_iters: Number of iterations to run the\n benchmark.\n num_iters: number of iterations to run conv2d.\n warmup_iters: number of iterations for warmup runs.\n\nReturns:\n The duration of the run in seconds.", "source": "github_repos"} +{"code": "def n_gpu(self):\n requires_backends(self, ['torch'])\n if not hasattr(self, '_n_gpu'):\n _ = self._setup_devices\n return self._n_gpu", "docstring": "The number of GPUs used by this process.\n\nNote:\n This will only be greater than one when you have multiple GPUs available but are not using distributed\n training. For distributed training, it will always be 1.", "source": "github_repos"} +{"code": "def model_type_scope(value):\n previous_value = _thread_local_data.model_type\n try:\n _thread_local_data.model_type = value\n yield value\n finally:\n _thread_local_data.model_type = previous_value", "docstring": "Provides a scope within which the model type to test is equal to `value`.\n\n The model type gets restored to its original value upon exiting the scope.\n\nArgs:\n value: model type value\n\nYields:\n The provided value.", "source": "github_repos"} +{"code": "def __init__(self, drop_prob, **kwargs):\n super().__init__(**kwargs)\n self.drop_prob = drop_prob", "docstring": "Optimized dropout module for stabilizing the training\n\nArgs:\n drop_prob (float): the dropout probabilities", "source": "github_repos"} +{"code": "def _process_landing_page(self, item, feed_item):\n if feed_item.get(FieldMap.AD_LANDING_PAGE_ID, ''):\n landing_page = self._landing_page_dao.get(feed_item, required=True)\n item['clickThroughUrl'] = {'landingPageId': landing_page['id']}\n if feed_item.get(FieldMap.AD_URL_SUFFIX, ''):\n item['clickThroughUrlSuffixProperties'] = {'overrideInheritedSuffix': True, 'clickThroughUrlSuffix': feed_item.get(FieldMap.AD_URL_SUFFIX, '')}\n else:\n item['clickThroughUrlSuffixProperties'] = {'overrideInheritedSuffix': False}", "docstring": "Configures ad landing page.\n\nArgs:\n item: DCM ad object to update.\n feed_item: Feed item representing the ad from the Bulkdozer feed", "source": "github_repos"} +{"code": "def broadcast_to(x, shape):\n if any_symbolic_tensors((x,)):\n return BroadcastTo(shape=shape).symbolic_call(x)\n return backend.numpy.broadcast_to(x, shape)", "docstring": "Broadcast a tensor to a new shape.\n\nArgs:\n x: The tensor to broadcast.\n shape: The shape of the desired tensor. A single integer `i` is\n interpreted as `(i,)`.\n\nReturns:\n A tensor with the desired shape.\n\nExample:\n >>> x = keras.ops.array([1, 2, 3])\n >>> keras.ops.broadcast_to(x, (3, 3))\n array([[1, 2, 3],\n [1, 2, 3],\n [1, 2, 3]])", "source": "github_repos"} +{"code": "def to_parquet(evset: EventSet, path: str, **kwargs):\n df = to_pandas(evset)\n df.to_parquet(path, **kwargs)", "docstring": "Saves an [`EventSet`][temporian.EventSet] to a CSV file.\n\nExample:\n ```python\n >>> output_path = str(tmp_dir / \"output_data.parquet\")\n >>> evset = tp.event_set(timestamps=[1,], features={\"f1\": [0.1]})\n >>> tp.to_parquet(evset, output_path)\n\n ```\n\nArgs:\n evset: EventSet to save.\n path: Path to the file.", "source": "github_repos"} +{"code": "def reset(self, state):\n state = _convert_to_state_tensor(state)\n state.shape.assert_is_compatible_with([_get_state_size(self.algorithm)])\n self._state_var.assign(state)", "docstring": "Resets the generator by a new state.\n\n See `__init__` for the meaning of \"state\".\n\nArgs:\n state: the new state.", "source": "github_repos"} +{"code": "def tanh_shrink(x):\n return ops.tanh_shrink(x)", "docstring": "Tanh shrink activation function.\n\n It is defined as:\n\n `f(x) = x - tanh(x)`.\n\nArgs:\n x: Input tensor.", "source": "github_repos"} +{"code": "def __sub__(self, other: Union[None, int, str, 'KeyPath']) -> 'KeyPath':\n if other is None:\n return self\n if isinstance(other, str):\n other = KeyPath.parse(other)\n elif isinstance(other, int):\n other = KeyPath(other)\n if not isinstance(other, KeyPath):\n raise TypeError(f'Cannot subtract KeyPath({self}) by {other!r}.')\n max_len = max(len(self), len(other))\n for pos in range(max_len):\n if pos >= len(self):\n raise ValueError(f'KeyPath subtraction failed: left path {self!r} is an ancestor of right path {other!r}.')\n if pos >= len(other):\n return KeyPath(self.keys[pos:])\n if self.keys[pos] != other.keys[pos]:\n raise ValueError(f'KeyPath subtraction failed: left path {self!r} and right path {other!r} are in different subtree.')\n return KeyPath()", "docstring": "Finds the relative path of this path to the other.\n\n Example::\n\n path1 = pg.KeyPath.parse('a.b.c.d')\n path2 = pg.KeyPath.parse('a.b')\n assert path1 - path2 == 'c.d'\n\nArgs:\n other: Object to subtract, which can be None, int (as a depth-1 KeyPath),\n string (parsed as a KeyPath) or a KeyPath object.\n\nReturns:\n Relative path of this path to the other.\n\nRaises:\n ValueError: This path is an ancestor node of the other path,\n or these two paths are in different branch.", "source": "github_repos"} +{"code": "def get_attr_location(self, name, location):\n line, _ = location\n src_line = self.line(line)\n attr = name.split('.')[-1]\n dot_attr = '.' + attr\n if dot_attr in src_line:\n col = src_line.index(dot_attr)\n return (Location(line, col + 1), len(attr))\n else:\n attr_loc = self._get_multiline_location(location, 5, dot_attr)\n if attr_loc:\n return (Location(attr_loc.line, attr_loc.column + 1), len(attr))\n else:\n for l in self.get_closest_line_range(line, line + 5):\n if self.line(l).endswith('.'):\n next_line = self.next_non_comment_line(l)\n text = self.line(next_line)\n if text.lstrip().startswith(attr):\n c = text.index(attr)\n return (Location(next_line, c), len(attr))\n return (location, len(name))", "docstring": "Returns the location and span of the attribute in an attribute access.\n\nArgs:\n name: The attribute name.\n location: The location of the value the attribute is accessed on.", "source": "github_repos"} +{"code": "def set_learning_phase(value):\n warnings.warn('`tf.keras.backend.set_learning_phase` is deprecated and will be removed after 2020-10-11. To update it, simply pass a True/False value to the `training` argument of the `__call__` method of your layer or model.')\n deprecated_internal_set_learning_phase(value)", "docstring": "Sets the learning phase to a fixed value.\n\n The backend learning phase affects any code that calls\n `backend.learning_phase()`\n In particular, all Keras built-in layers use the learning phase as the default\n for the `training` arg to `Layer.__call__`.\n\n User-written layers and models can achieve the same behavior with code that\n looks like:\n\n ```python\n def call(self, inputs, training=None):\n if training is None:\n training = backend.learning_phase()\n ```\n\nArgs:\n value: Learning phase value, either 0 or 1 (integers).\n 0 = test, 1 = train\n\nRaises:\n ValueError: if `value` is neither `0` nor `1`.", "source": "github_repos"} +{"code": "def save_prefixed_metrics(results, output_dir, file_name: str='all_results.json', metric_key_prefix: str='eval'):\n for key in list(results.keys()):\n if not key.startswith(f'{metric_key_prefix}_'):\n results[f'{metric_key_prefix}_{key}'] = results.pop(key)\n with open(os.path.join(output_dir, file_name), 'w') as f:\n json.dump(results, f, indent=4)", "docstring": "Save results while prefixing metric names.\n\nArgs:\n results: (:obj:`dict`):\n A dictionary of results.\n output_dir: (:obj:`str`):\n An output directory.\n file_name: (:obj:`str`, `optional`, defaults to :obj:`all_results.json`):\n An output file name.\n metric_key_prefix: (:obj:`str`, `optional`, defaults to :obj:`eval`):\n A metric name prefix.", "source": "github_repos"} +{"code": "def __init__(self, max_length: int, eos_token_id: Union[int, List[int], torch.Tensor], device: str='cpu'):\n self.max_length = max_length\n if not isinstance(eos_token_id, torch.Tensor):\n if isinstance(eos_token_id, int):\n eos_token_id = [eos_token_id]\n eos_token_id = torch.tensor(eos_token_id, device=device)\n self.eos_token_id = eos_token_id\n if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():\n raise ValueError(f'`eos_token_id` has to be a list of positive integers, but is {eos_token_id}')", "docstring": "[`LogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.\n\nArgs:\n max_length (`int`):\n The maximum length of the sequence to be generated.\n eos_token_id (`Union[int, List[int], torch.Tensor]`):\n The id(s) of the *end-of-sequence* token.\n device (`str`, *optional*, defaults to `\"cpu\"`):\n The device to allocate the tensors.\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, AutoModelForCausalLM\n\n >>> model = AutoModelForCausalLM.from_pretrained(\"distilbert/distilgpt2\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilgpt2\")\n\n >>> inputs = tokenizer(\"A sequence: 1, 2, 3\", return_tensors=\"pt\")\n\n >>> # By default, it continues generating according to the model's logits\n >>> outputs = model.generate(**inputs, max_new_tokens=10)\n >>> print(tokenizer.batch_decode(outputs)[0])\n A sequence: 1, 2, 3, 4, 5, 6, 7, 8\n\n >>> # `forced_eos_token_id` ensures the generation ends with a EOS token\n >>> outputs = model.generate(**inputs, max_new_tokens=10, forced_eos_token_id=tokenizer.eos_token_id)\n >>> print(tokenizer.batch_decode(outputs)[0])\n A sequence: 1, 2, 3, 4, 5, 6, 7,<|endoftext|>\n ```", "source": "github_repos"} +{"code": "def generator_next_fn(iterator_id_t):\n if output_types and output_shapes:\n flattened_types = [dtypes.as_dtype(dt) for dt in nest.flatten(output_types)]\n flattened_shapes = nest.flatten(output_shapes)\n\n def generator_py_func(iterator_id):\n \"\"\"A `py_func` that will be called to invoke the iterator.\"\"\"\n values = next(generator_state.get_iterator(iterator_id))\n try:\n flattened_values = nest.flatten_up_to(output_types, values)\n except (TypeError, ValueError) as e:\n raise TypeError(f'`generator` yielded an element that did not match the expected structure. The expected structure was {output_types}, but the yielded element was {values}.') from e\n ret_arrays = []\n for ret, dtype in zip(flattened_values, flattened_types):\n try:\n ret_arrays.append(script_ops.FuncRegistry._convert(ret, dtype=dtype.as_numpy_dtype))\n except (TypeError, ValueError) as e:\n raise TypeError(f'`generator` yielded an element that could not be converted to the expected type. The expected type was {dtype.name}, but the yielded element was {ret}.') from e\n for ret_array, expected_dtype, expected_shape in zip(ret_arrays, flattened_types, flattened_shapes):\n if ret_array.dtype != expected_dtype.as_numpy_dtype:\n raise TypeError(f'`generator` yielded an element of type {ret_array.dtype} where an element of type {expected_dtype.as_numpy_dtype} was expected.')\n if not expected_shape.is_compatible_with(ret_array.shape):\n raise TypeError(f'`generator` yielded an element of shape {ret_array.shape} where an element of shape {expected_shape} was expected.')\n return ret_arrays\n flat_values = script_ops.numpy_function(generator_py_func, [iterator_id_t], flattened_types)\n if not isinstance(flat_values, (list, tuple)):\n flat_values = [flat_values]\n if output_shapes is not None:\n for ret_t, shape in zip(flat_values, flattened_shapes):\n ret_t.set_shape(shape)\n return nest.pack_sequence_as(output_types, flat_values)\n else:\n flat_output_types = structure.get_flat_tensor_types(output_signature)\n\n def generator_py_func(iterator_id):\n \"\"\"A `py_func` that will be called to invoke the iterator.\"\"\"\n values = next(generator_state.get_iterator(iterator_id.numpy()))\n try:\n values = structure.normalize_element(values, output_signature)\n except (TypeError, ValueError) as e:\n raise TypeError(f'`generator` yielded an element that did not match the expected structure. The expected structure was {output_signature}, but the yielded element was {values}.') from e\n values_spec = structure.type_spec_from_value(values)\n if not structure.are_compatible(values_spec, output_signature):\n raise TypeError(f'`generator` yielded an element of {values_spec} where an element of {output_signature} was expected.')\n return structure.to_tensor_list(output_signature, values)\n return script_ops.eager_py_func(generator_py_func, inp=[iterator_id_t], Tout=flat_output_types)", "docstring": "Generates the next element from iterator with ID `iterator_id_t`.\n\n We map this function across an infinite repetition of the\n `iterator_id_t`, and raise `StopIteration` to terminate the iteration.\n\nArgs:\n iterator_id_t: A `tf.int64` tensor whose value uniquely identifies the\n iterator in `generator_state` from which to generate an element.\n\nReturns:\n The next element to generate from the iterator.", "source": "github_repos"} +{"code": "def __init__(self, value: T, proxy: Optional[T]=None):\n if proxy is None:\n proxy = value\n super().__init__('constant', proxy)\n self._value = value", "docstring": "Initialize a constant expression.\n\nArgs:\n value: The constant value to be produced by this expression.\n proxy: (Optional) a proxy object with same type as `value` to use for\n rapid type checking at pipeline construction time. If not provided,\n `value` will be used directly.", "source": "github_repos"} +{"code": "def assert_no_new_tensors(f: _F) -> _F:\n\n def decorator(self: 'TensorFlowTestCase', **kwargs):\n \"\"\"Finds existing Tensors, runs the test, checks for new Tensors.\"\"\"\n\n def _is_tensorflow_object(obj) -> bool:\n try:\n return isinstance(obj, (tensor_lib.Tensor, variables.Variable, tensor_shape.Dimension, tensor_shape.TensorShape))\n except (ReferenceError, AttributeError):\n return False\n tensors_before = set((id(obj) for obj in gc.get_objects() if _is_tensorflow_object(obj)))\n outside_executed_eagerly = cast(bool, context.executing_eagerly())\n outside_graph_key = ops.get_default_graph()._graph_key\n with ops.Graph().as_default():\n ops.get_default_graph()._graph_key = outside_graph_key\n if outside_executed_eagerly:\n with context.eager_mode():\n result = f(self, **kwargs)\n else:\n result = f(self, **kwargs)\n context.context()._clear_caches()\n gc.collect()\n tensors_after = [obj for obj in gc.get_objects() if _is_tensorflow_object(obj) and id(obj) not in tensors_before]\n if tensors_after:\n raise AssertionError('%d Tensors not deallocated after test: %s' % (len(tensors_after), str(tensors_after)))\n return result\n return tf_decorator.make_decorator(f, decorator)", "docstring": "Decorator for asserting that no new Tensors persist after a test.\n\n Mainly useful for checking that code using the Python C API has correctly\n manipulated reference counts.\n\n Clears the caches that it knows about, runs the garbage collector, then checks\n that there are no Tensor or Tensor-like objects still around. This includes\n Tensors to which something still has a reference (e.g. from missing\n Py_DECREFs) and uncollectable cycles (i.e. Python reference cycles where one\n of the objects has __del__ defined).\n\nArgs:\n f: The test case to run.\n\nReturns:\n The decorated test case.", "source": "github_repos"} +{"code": "def testSaveAndLoadSingleVariable(self, shard_config):\n strategy = self._create_strategy(shard_config[0])\n with strategy.scope():\n var = variables_lib.Variable([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])\n model_dir = self.get_temp_dir()\n save.save(var, model_dir)\n strategy2 = self._create_strategy(shard_config[1])\n with strategy2.scope():\n loaded = load.load(model_dir)\n if shard_config[1] > 1:\n loaded = array_ops.concat(loaded.variables, axis=0)\n self.assertLen(loaded.numpy(), 6)\n if shard_config[0] > 1:\n var = array_ops.concat(var.variables, axis=0)\n self.assertAllClose(var.numpy(), loaded.numpy())", "docstring": "Test saving and loading ShardedVariable with different numbers of shards.\n\n Loading tf.Variables into multiple Shards is not yet supported\n\nArgs:\n shard_config: The number of shards to use before and after loading. For\n example, [2, 1] means to create and save the variable with 2 shards and\n load it into 1 shard (i.e., a regular tf.Variable).", "source": "github_repos"} +{"code": "def is_leap_year(years):\n years = tf.convert_to_tensor(years, tf.int32)\n\n def divides_by(n):\n return tf.math.equal(years % n, 0)\n return tf.math.logical_and(divides_by(4), tf.math.logical_or(~divides_by(100), divides_by(400)))", "docstring": "Calculates whether years are leap years.\n\nArgs:\n years: Tensor of int32 type. Elements should be positive.\n\nReturns:\n Tensor of bool type.", "source": "github_repos"} +{"code": "def _is_instance(self, obj, class_spec):\n cls = obj.cls\n if isinstance(obj, abstract.AMBIGUOUS_OR_EMPTY) or isinstance(cls, abstract.AMBIGUOUS_OR_EMPTY):\n return None\n return abstract_utils.check_against_mro(self.ctx, cls, class_spec)", "docstring": "Check if the object matches a class specification.\n\nArgs:\n obj: A BaseValue, generally the left hand side of an isinstance() call.\n class_spec: A BaseValue, generally the right hand side of an isinstance()\n call.\n\nReturns:\n True if the object is derived from a class in the class_spec, False if\n it is not, and None if it is ambiguous whether obj matches class_spec.", "source": "github_repos"} +{"code": "def reduce_min(values, index, name='segmented_reduce_min'):\n return _segment_reduce(values, index, 'amin', name)", "docstring": "Computes the minimum over segments.\n\n This operations computes the minimum over segments, with support for:\n\n - Batching using the first dimensions [B1, B2, ..., Bn]. Each element in a batch can have different indices.\n - Vectorization using the last dimension [V1, V2, ...]. If they are present, the output will be an element-wise\n minimum of vectors rather than scalars.\n\n Only the middle dimensions [I1, ..., Ik] are reduced by the operation.\n\nArgs:\n values (`torch.Tensor` of shape [B1, B2, ..., Bn, I1, .., Ik, V1, V2, ..]):\n Tensor containing the values of which the min must be taken segment-wise.\n index (`IndexMap`, indices are of shape [B1, B2, ..., Bn, I1, .., Ik].):\n Index defining the segments.\n name (`str`, *optional*, defaults to 'segmented_reduce_sum'):\n Name for the operation. Currently not used\n\nReturns:\n output_values (`torch.Tensor`of shape [B1, B2, ..., Bn, num_segments, V1, V2, ..]): Tensor containing the\n output values. output_index (`IndexMap`): IndexMap with shape [B1, B2, ..., Bn, num_segments].", "source": "github_repos"} +{"code": "def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) -> List[int]:\n if already_has_special_tokens:\n return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)\n if not self.add_bos_token:\n return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False)\n if token_ids_1 is None:\n return [1] + [0] * len(token_ids_0)\n return [1] + [0] * len(token_ids_0) + [1] + [0] * len(token_ids_1)", "docstring": "Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding\n special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.\n\nArgs:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n already_has_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not the token list is already formatted with special tokens for the model.\n\nReturns:\n `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.", "source": "github_repos"} +{"code": "def resize_image_with_pad_v2(image, target_height, target_width, method=ResizeMethod.BILINEAR, antialias=False):\n\n def _resize_fn(im, new_size):\n return resize_images_v2(im, new_size, method, antialias=antialias)\n return _resize_image_with_pad_common(image, target_height, target_width, _resize_fn)", "docstring": "Resizes and pads an image to a target width and height.\n\n Resizes an image to a target width and height by keeping\n the aspect ratio the same without distortion. If the target\n dimensions don't match the image dimensions, the image\n is resized and then padded with zeroes to match requested\n dimensions.\n\nArgs:\n image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor\n of shape `[height, width, channels]`.\n target_height: Target height.\n target_width: Target width.\n method: Method to use for resizing image. See `image.resize()`\n antialias: Whether to use anti-aliasing when resizing. See 'image.resize()'.\n\nRaises:\n ValueError: if `target_height` or `target_width` are zero or negative.\n\nReturns:\n Resized and padded image.\n If `images` was 4-D, a 4-D float Tensor of shape\n `[batch, new_height, new_width, channels]`.\n If `images` was 3-D, a 3-D float Tensor of shape\n `[new_height, new_width, channels]`.", "source": "github_repos"} +{"code": "def __init__(self, ctx: base.ContextType, name: str, param_names: tuple[str, ...], *, posonly_count: int=0, varargs_name: str | None=None, kwonly_params: tuple[str, ...]=(), kwargs_name: str | None=None, defaults: Mapping[str, base.BaseValue]=datatypes.EMPTY_MAP, annotations: Mapping[str, base.BaseValue]=datatypes.EMPTY_MAP):\n self._ctx = ctx\n self.name = name\n self.param_names = param_names\n self.posonly_count = posonly_count\n self.varargs_name = varargs_name\n self.kwonly_params = kwonly_params\n self.kwargs_name = kwargs_name\n self.defaults = defaults\n self.annotations = annotations", "docstring": "Representation of a Python function signature.\n\nAttributes:\n name: Name of the function.\n param_names: A tuple of positional parameter names. This DOES include\n positional-only parameters and does NOT include keyword-only parameters.\n posonly_count: Number of positional-only parameters.\n varargs_name: Name of the varargs parameter. (The \"args\" in *args)\n kwonly_params: Tuple of keyword-only parameters.\n E.g. (\"x\", \"y\") for \"def f(a, *, x, y=2)\". These do NOT appear in\n param_names. Ordered like in the source file.\n kwargs_name: Name of the kwargs parameter. (The \"kwargs\" in **kwargs)\n defaults: Dictionary, name to value, for all parameters with default values.\n annotations: A dictionary of type annotations. (string to type)\n posonly_params: Tuple of positional-only parameters (i.e., the first\n posonly_count names in param_names).", "source": "github_repos"} +{"code": "def get_image_features(self, pixel_values_images: torch.FloatTensor, vision_feature_layer: Optional[Union[int, List[int]]]=None, vision_feature_select_strategy: Optional[str]=None):\n vision_feature_layer = vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer\n vision_feature_select_strategy = vision_feature_select_strategy if vision_feature_select_strategy is not None else self.config.vision_feature_select_strategy\n if vision_feature_select_strategy not in ['default', 'full']:\n raise ValueError(f'Unexpected select feature strategy: {self.config.vision_feature_select_strategy}')\n image_outputs = self.image_tower(pixel_values_images, output_hidden_states=True)\n if isinstance(vision_feature_layer, int):\n image_outputs = image_outputs.hidden_states[vision_feature_layer]\n if vision_feature_select_strategy == 'default':\n image_outputs = image_outputs[:, 1:]\n else:\n hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]\n if vision_feature_select_strategy == 'default':\n hs_pool = [hs[:, 1:] for hs in hs_pool]\n image_outputs = torch.cat(hs_pool, dim=-1)\n image_features = self.multi_modal_projector(image_outputs)\n return image_features", "docstring": "Obtains image last hidden states from the vision tower and apply multimodal projection.\n\nArgs:\n pixel_values_images (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)\n The tensors corresponding to the input images.\n vision_feature_layer (`Union[int, List[int]]`, *optional*):\n The index of the layer to select the vision feature. If multiple indices are provided,\n the vision feature of the corresponding indices will be concatenated to form the\n vision features.\n vision_feature_select_strategy (`str`, *optional*):\n The feature selection strategy used to select the vision feature from the vision backbone.\n Can be one of `\"default\"` or `\"full\"`\n\nReturns:\n image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).", "source": "github_repos"} +{"code": "def GenerateCostReport(metagraph, per_node_report=False, verbose=False, cluster=None):\n if cluster is None:\n cluster = gcluster.Cluster(disable_detailed_stats=False)\n return tf_wrap.GenerateCostReport(metagraph.SerializeToString(), per_node_report, verbose, cluster.tf_cluster)", "docstring": "Analyze the cost of each TensorFlow op and node in the provided metagraph.\n\nArgs:\n metagraph: A TensorFlow MetaGraphDef.\n per_node_report: by default the report contains stats aggregated on a per op\n type basis, setting per_node_report to True adds results for each\n individual node to the report.\n verbose: Prints out the entire operation proto instead of a summary table.\n cluster: Analyze the costs using the specified cluster, or the local machine\n if no cluster was specified.\n\nReturns:\n A string of cost report.", "source": "github_repos"} +{"code": "def list_files_by_mtime(dirpath):\n files = [f for f in os.listdir(dirpath) if is_real_file(dirpath, f)]\n return sorted(files, key=lambda f: get_mtime(dirpath, f))", "docstring": "Return a list of files in the directory, sorted in increasing \"mtime\".\n\n Return a list of files in the given directory, sorted from older to newer file\n according to their modification times. Only return actual files, skipping\n directories, symbolic links, pipes, etc.\n\nArgs:\n dirpath: directory pathname\n\nReturns:\n A list of file names relative to the given directory path.", "source": "github_repos"} +{"code": "def enter_loop_section(self, section_id, entry_node):\n assert section_id not in self.section_entry\n assert section_id not in self.continues\n self.continues[section_id] = set()\n node = self.add_ordinary_node(entry_node)\n self.section_entry[section_id] = node", "docstring": "Enters a loop section.\n\n Loop sections define an entry node. The end of the section always flows back\n to the entry node. These admit continue jump nodes which also flow to the\n entry node.\n\nArgs:\n section_id: Hashable, the same node that will be used in calls to the\n ast_node arg passed to add_continue_node\n entry_node: ast.AST, the entry node into the loop (e.g. the test node for\n while loops)", "source": "github_repos"} +{"code": "def forward(self, outputs, targets):\n outputs_without_aux = {k: v for k, v in outputs.items() if 'auxiliary_outputs' not in k}\n indices = self.matcher(outputs_without_aux, targets)\n num_boxes = sum((len(t['class_labels']) for t in targets))\n num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)\n num_boxes = torch.clamp(num_boxes, min=1).item()\n losses = {}\n for loss in self.losses:\n l_dict = self.get_loss(loss, outputs, targets, indices, num_boxes)\n l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}\n losses.update(l_dict)\n if 'auxiliary_outputs' in outputs:\n for i, auxiliary_outputs in enumerate(outputs['auxiliary_outputs']):\n indices = self.matcher(auxiliary_outputs, targets)\n for loss in self.losses:\n if loss == 'masks':\n continue\n l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes)\n l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}\n l_dict = {k + f'_aux_{i}': v for k, v in l_dict.items()}\n losses.update(l_dict)\n if 'dn_auxiliary_outputs' in outputs:\n if 'denoising_meta_values' not in outputs:\n raise ValueError(\"The output must have the 'denoising_meta_values` key. Please, ensure that 'outputs' includes a 'denoising_meta_values' entry.\")\n indices = self.get_cdn_matched_indices(outputs['denoising_meta_values'], targets)\n num_boxes = num_boxes * outputs['denoising_meta_values']['dn_num_group']\n for i, auxiliary_outputs in enumerate(outputs['dn_auxiliary_outputs']):\n for loss in self.losses:\n if loss == 'masks':\n continue\n kwargs = {}\n l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes, **kwargs)\n l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}\n l_dict = {k + f'_dn_{i}': v for k, v in l_dict.items()}\n losses.update(l_dict)\n return losses", "docstring": "This performs the loss computation.\n\nArgs:\n outputs (`dict`, *optional*):\n Dictionary of tensors, see the output specification of the model for the format.\n targets (`List[dict]`, *optional*):\n List of dicts, such that `len(targets) == batch_size`. The expected keys in each dict depends on the\n losses applied, see each loss' doc.", "source": "github_repos"} +{"code": "def _convert_value(value, expected_type, path, context=_ConversionContext.VALUE):\n assert isinstance(path, tuple)\n if expected_type is None:\n expected_type = _NoneType\n if expected_type is tensor.Tensor:\n return _convert_tensor(value, path, context)\n elif isinstance(expected_type, type) and _issubclass(expected_type, composite_tensor.CompositeTensor):\n return _convert_composite_tensor(value, expected_type, path, context)\n elif expected_type is tensor_shape.TensorShape:\n try:\n return tensor_shape.as_shape(value)\n except TypeError as e:\n raise TypeError(f\"{''.join(path)}: expected 'tf.TensorShape', got {type(value).__name__!r}\") from e\n elif expected_type is dtypes.DType:\n try:\n return dtypes.as_dtype(value)\n except TypeError as e:\n raise TypeError(f\"{''.join(path)}: expected 'tf.DType', got {type(value).__name__!r}\") from e\n elif expected_type in (int, float, bool, str, bytes, _NoneType):\n if not isinstance(value, expected_type):\n raise TypeError(f'{''.join(path)}: expected {expected_type.__name__!r}, got {type(value).__name__!r}')\n return value\n elif type_annotations.is_generic_tuple(expected_type):\n return _convert_tuple(value, expected_type, path, context)\n elif type_annotations.is_generic_mapping(expected_type):\n return _convert_mapping(value, expected_type, path, context)\n elif type_annotations.is_generic_union(expected_type):\n return _convert_union(value, expected_type, path, context)\n else:\n raise TypeError(f'{''.join(path)}: Unsupported type annotation {expected_type!r}')", "docstring": "Type-checks and converts a value.\n\nArgs:\n value: The value to type-check.\n expected_type: The expected type for the value.\n path: Tuple of `str` naming the value (used for exception messages).\n context: _ConversionContext, indicates what kind of value we are converting.\n\nReturns:\n A copy of `value`, converted to the expected type.\n\nRaises:\n TypeError: If `value` can not be converted to the expected type.", "source": "github_repos"} +{"code": "def np_reshape(a, /, shape=None, *, newshape=None, order='C', copy=None):\n if shape is None:\n shape = newshape\n if np.lib.NumpyVersion(np.__version__) >= '2.1.0.rc0':\n if shape is None and newshape is None:\n return np.asarray(a, order=order, copy=copy)\n return np.reshape(a, shape, order=order, copy=copy)\n return np.reshape(a, shape, order=order)", "docstring": "Reshapes an array without changing its data.\n\n NumPy 2.1.0rc1 added shape and copy arguments to numpy.reshape. See\n https://github.com/numpy/numpy/pull/26292. Both newshape and shape keywords\n are supported, but newshape is going to be deprecated. Use `shape` instead.\n\n Besides, shape cannot be None now. See\n https://github.com/numpy/numpy/blob/v2.1.0rc1/numpy/_core/fromnumeric.py#L309.\n Previously, np.reshape with newshape=None returned a copy. To maintain this\n behavior, we now use asarray to create an ndarray.\n\nArgs:\n a: Array_like. Array to be reshaped.\n shape: The new shape of the array.\n newshape: The new shape of the array (deprecated).\n order: {‘C’, ‘F’, ‘K’}.\n copy: bool. If True, then the array data is copied. If None, a copy will\n only be made if it’s required by order. For False it raises a ValueError if\n a copy cannot be avoided.\n\nReturns:\n This will be a new view object if possible; otherwise, it will be a copy.", "source": "github_repos"} +{"code": "def __init__(self, name):\n NamedObject.__init__(self, name)\n self.values = []", "docstring": "Expressions to expand to other objects.\n\n Messages, events, states, transitions can be parameterized. A parameterized\n object can be expanded with values.\n Note that Resolve() is only used to expand parameterized messages. Other\n parameterized objects are expanded differently.\n\nAttributes:\n values: List of values to be used when expanding to other object.", "source": "github_repos"} +{"code": "def column_type(self, agencyId: int, advertiserId: int, column: str) -> str:\n if column not in self.columns:\n for saved_column in API_SearchAds(self.config, self.auth, iterate=True).savedcolumns().list(agencyId=agencyId, advertiserId=advertiserId).execute():\n self.columns[saved_column['savedColumnName']] = SA_TYPES.get(saved_column['type'], 'STRING')\n return self.columns.get(column, 'STRING')", "docstring": "Return the column type for the given column name.\n\n Intended mostly as an internl helper function but left open for convenience.\n Leverages both saved columns and standard columns.\n Does not distinguish saved from standard, will this be a problem?\n\nArgs:\n agencyId - required only for saved columns, usually derived from report\n advertiserid - required only for saved columns, usually derived from report\n\nReturns:\n Column type as defnined by BigQuery. Defaults to STRING if not found.", "source": "github_repos"} +{"code": "def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:\n size = get_size_dict(size)\n if 'height' not in size or 'width' not in size:\n raise ValueError(f'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}')\n output_size = (size['height'], size['width'])\n return resize(image, size=output_size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs)", "docstring": "Resize an image to `(size[\"height\"], size[\"width\"])`.\n\nArgs:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Dictionary in the format `{\"height\": int, \"width\": int}` specifying the size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.\n data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the output image. If unset, the channel dimension format of the input\n image is used. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n\nReturns:\n `np.ndarray`: The resized image.", "source": "github_repos"} +{"code": "def _contains_composite_function_call(self, graphdef: graph_pb2.GraphDef) -> bool:\n return any(map(self._is_composite_function, graphdef.library.function))", "docstring": "Determines if the graph def has composite function call.\n\nArgs:\n graphdef: A GraphDef object.\n\nReturns:\n True if and only if the graph def contains a composite function call.", "source": "github_repos"} +{"code": "def __init__(self, callable_type: CallableType, name: str, module_name: str, args: Optional[List[Argument]]=None, kwonlyargs: Optional[List[Argument]]=None, varargs: Optional[Argument]=None, varkw: Optional[Argument]=None, return_value: Optional[class_schema.ValueSpec]=None, qualname: Optional[str]=None, description: Optional[str]=None):\n args = args or []\n self.callable_type = callable_type\n self.name = name\n self.module_name = module_name\n self.args = args or []\n self.kwonlyargs = kwonlyargs or []\n self.varargs = varargs\n self.varkw = varkw\n self.return_value = return_value\n self.qualname = qualname or name\n self.description = description", "docstring": "Constructor.\n\nArgs:\n callable_type: Type of callable.\n name: Function name.\n module_name: Module name.\n args: Specification for positional arguments\n kwonlyargs: Specification for keyword only arguments (PY3).\n varargs: Specification for wildcard list argument, e.g, 'args' is the name\n for `*args`.\n varkw: Specification for wildcard keyword argument, e.g, 'kwargs' is the\n name for `**kwargs`.\n return_value: Optional value spec for return value.\n qualname: Optional qualified name.\n description: Optional description of the signature.", "source": "github_repos"} +{"code": "def unload_snippet(self, name):\n self.services.snippets.remove_snippet_client(name)", "docstring": "Stops a snippet apk.\n\nArgs:\n name: The attribute name the snippet server is attached with.\n\nRaises:\n SnippetError: The given snippet name is not registered.", "source": "github_repos"} +{"code": "def add_timestamps(with_ms: bool=False, substream_name: str | None=None) -> processor.Processor:\n if substream_name is None:\n substream_name = ''\n return processor.processor_function(functools.partial(_add_timestamps, with_ms=with_ms, substream_name=substream_name))", "docstring": "Adds timestamps to image chunks.\n\n By default the timestamps are added with the format `mm:ss` where\n `mm` is the number of minutes, `ss` is the number of seconds.\n\nArgs:\n with_ms: Whether to add milliseconds to the timestamp. When `True`, the\n timestamp is added with the format `mm:ss.SSS` where `SSS` is the number\n of milliseconds.\n substream_name: The substream name to use for the timestamps.\n\nReturns:\n A processor that adds timestamps after each image chunk.", "source": "github_repos"} +{"code": "def convert(self, calibration_inputs: Optional[Mapping[str, np.ndarray]]=None, num_runs=1) -> None:", "docstring": "Converts the model with TensorRT and calibrates if using INT8 precision mode.\n\nArgs:\n calibration_inputs: Mapping from input names to ndarrays in TF1. Or a\n sequence of tensors in TF2. Used as calibration data.\n num_runs: Number of calibration runs.", "source": "github_repos"} +{"code": "def as_decimal(self) -> decimal.Decimal:\n if len(self._messages) != 1:\n raise ValueError('FHIRPath did not evaluate to a single decimal.')\n return decimal.Decimal(proto_utils.get_value_at_field(self._messages[0], 'value'))", "docstring": "Returns the result as a decimal.\n\nRaises:\n ValueError if the `EvaluationResult` is not a single decimal.", "source": "github_repos"} +{"code": "def unique_object_name(name, name_uid_map=None, avoid_names=None, namespace='', zero_based=False, avoid_observed_names=False):\n if name_uid_map is None:\n name_uid_map = get_default_graph_uid_map()\n if avoid_names is None:\n if avoid_observed_names:\n avoid_names = OBSERVED_NAMES\n else:\n avoid_names = set()\n proposed_name = None\n while proposed_name is None or proposed_name in avoid_names:\n name_key = (namespace, name)\n if zero_based:\n number = name_uid_map[name_key]\n if number:\n proposed_name = name + '_' + str(number)\n else:\n proposed_name = name\n name_uid_map[name_key] += 1\n else:\n name_uid_map[name_key] += 1\n proposed_name = name + '_' + str(name_uid_map[name_key])\n return proposed_name", "docstring": "Makes a object name (or arbitrary string) unique within a TensorFlow graph.\n\nArgs:\n name: String name to make unique.\n name_uid_map: An optional defaultdict(int) to use when creating unique\n names. If None (default), uses a per-Graph dictionary.\n avoid_names: An optional set or dict with names which should not be used. If\n None (default), don't avoid any names unless `avoid_observed_names` is\n True.\n namespace: Gets a name which is unique within the (graph, namespace). Layers\n which are not Networks use a blank namespace and so get graph-global\n names.\n zero_based: If True, name sequences start with no suffix (e.g. \"dense\",\n \"dense_1\"). If False, naming is one-based (\"dense_1\", \"dense_2\").\n avoid_observed_names: If True, avoid any names that have been observed by\n `backend.observe_object_name`.\n\nReturns:\n Unique string name.\n\nExample:\n unique_object_name('dense') # dense_1\n unique_object_name('dense') # dense_2", "source": "github_repos"} +{"code": "def pad(self, images: list['torch.Tensor'], constant_values: Union[float, Iterable[float]]=0, return_pixel_mask: bool=True) -> tuple:\n pad_size = get_max_height_width(images)\n grouped_images, grouped_images_index = group_images_by_shape(images)\n processed_images_grouped = {}\n processed_masks_grouped = {}\n for shape, stacked_images in grouped_images.items():\n stacked_images = self._pad_image(stacked_images, pad_size, constant_values=constant_values)\n processed_images_grouped[shape] = stacked_images\n if return_pixel_mask:\n stacked_masks = make_pixel_mask(image=stacked_images, output_size=pad_size)\n processed_masks_grouped[shape] = stacked_masks\n processed_images = reorder_images(processed_images_grouped, grouped_images_index)\n processed_masks = None\n if return_pixel_mask:\n processed_masks = reorder_images(processed_masks_grouped, grouped_images_index)\n return (processed_images, processed_masks)", "docstring": "Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width\n in the batch and optionally returns their corresponding pixel mask.\n\nArgs:\n image (`torch.Tensor`):\n Image to pad.\n constant_values (`float` or `Iterable[float]`, *optional*):\n The value to use for the padding if `mode` is `\"constant\"`.\n return_pixel_mask (`bool`, *optional*, defaults to `True`):\n Whether to return a pixel mask.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.", "source": "github_repos"} +{"code": "def _load_data_file(filename, text):\n path = filename if path_utils.isabs(filename) else get_full_path(filename)\n loader = globals().get('__loader__', None)\n if loader:\n data = loader.get_data(path)\n if text:\n return re.sub('\\r\\n?', '\\n', data.decode('utf-8'))\n return data\n with open(path, 'r' if text else 'rb') as fi:\n return fi.read()", "docstring": "Get the contents of a data file from the pytype installation.\n\nArgs:\n filename: the path, relative to \"pytype/\"\n text: whether to load the file as text or bytes.\n\nReturns:\n The contents of the file as a bytestring\n\nRaises:\n IOError: if file not found", "source": "github_repos"} +{"code": "def run_inference(self, batch: Sequence[str], model: _VLLMModelServer, inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionResult]:\n return asyncio.run(self._async_run_inference(batch, model, inference_args))", "docstring": "Runs inferences on a batch of text strings.\n\nArgs:\n batch: A sequence of examples as text strings.\n model: A _VLLMModelServer containing info for connecting to the server.\n inference_args: Any additional arguments for an inference.\n\nReturns:\n An Iterable of type PredictionResult.", "source": "github_repos"} +{"code": "def ctc_batch_cost(y_true, y_pred, input_length, label_length):\n label_length = math_ops.cast(array_ops.squeeze(label_length, axis=-1), dtypes_module.int32)\n input_length = math_ops.cast(array_ops.squeeze(input_length, axis=-1), dtypes_module.int32)\n sparse_labels = math_ops.cast(ctc_label_dense_to_sparse(y_true, label_length), dtypes_module.int32)\n y_pred = math_ops.log(array_ops.transpose(y_pred, perm=[1, 0, 2]) + epsilon())\n return array_ops.expand_dims(ctc.ctc_loss(inputs=y_pred, labels=sparse_labels, sequence_length=input_length), 1)", "docstring": "Runs CTC loss algorithm on each batch element.\n\nArgs:\n y_true: tensor `(samples, max_string_length)`\n containing the truth labels.\n y_pred: tensor `(samples, time_steps, num_categories)`\n containing the prediction, or output of the softmax.\n input_length: tensor `(samples, 1)` containing the sequence length for\n each batch item in `y_pred`.\n label_length: tensor `(samples, 1)` containing the sequence length for\n each batch item in `y_true`.\n\nReturns:\n Tensor with shape (samples,1) containing the\n CTC loss of each element.", "source": "github_repos"} +{"code": "def markdown_compatible(text: str) -> str:\n text = re.sub('^\\\\(([\\\\d.]+[a-zA-Z]?)\\\\) \\\\\\\\\\\\[(.+?)\\\\\\\\\\\\]$', '\\\\[\\\\2 \\\\\\\\tag{\\\\1}\\\\]', text, flags=re.M)\n text = re.sub('^\\\\\\\\\\\\[(.+?)\\\\\\\\\\\\] \\\\(([\\\\d.]+[a-zA-Z]?)\\\\)$', '\\\\[\\\\1 \\\\\\\\tag{\\\\2}\\\\]', text, flags=re.M)\n text = re.sub('^\\\\\\\\\\\\[(.+?)\\\\\\\\\\\\] \\\\(([\\\\d.]+[a-zA-Z]?)\\\\) (\\\\\\\\\\\\[.+?\\\\\\\\\\\\])$', '\\\\[\\\\1 \\\\\\\\tag{\\\\2}\\\\] \\\\3', text, flags=re.M)\n text = text.replace('\\\\. ', '. ')\n text = text.replace('\\\\bm{', '\\\\mathbf{').replace('{\\\\\\\\bm ', '\\\\mathbf{')\n text = re.sub('\\\\\\\\mbox{ ?\\\\\\\\boldmath\\\\$(.*?)\\\\$}', '\\\\\\\\mathbf{\\\\1}', text)\n text = re.sub('((?:http|ftp|https):\\\\/\\\\/(?:[\\\\w_-]+(?:(?:\\\\.[\\\\w_-]+)+))(?:[\\\\w.,@?^=%&:\\\\/~+#-]*[\\\\w@?^=%&\\\\/~+#-]))', '[\\\\1](\\\\1)', text)\n text = re.sub('```\\\\s*(.+?)\\\\s*```', '```\\\\n\\\\1\\\\n```', text, flags=re.S)\n return text", "docstring": "Make text compatible with Markdown formatting.\n\n This function makes various text formatting adjustments to make it compatible with Markdown.\n\nArgs:\n text (`str`):\n The input text to be made Markdown-compatible.\n\nReturns:\n `str`: The Markdown-compatible text.", "source": "github_repos"} +{"code": "def output_shapes(self):\n return nest.map_structure(lambda component_spec: component_spec._to_legacy_output_shapes(), self._element_spec)", "docstring": "Returns the shape of each component of an element of this iterator.\n\nReturns:\n A (nested) structure of `tf.TensorShape` objects corresponding to each\n component of an element of this dataset.", "source": "github_repos"} +{"code": "def from_dict(event_dict):\n return SnippetEvent(callback_id=event_dict['callbackId'], name=event_dict['name'], creation_time=event_dict['time'], data=event_dict['data'])", "docstring": "Create a SnippetEvent object from a dictionary.\n\n DEPRECATED: Use mobly.snippet.callback_event.from_dict instead.\n\nArgs:\n event_dict: a dictionary representing an event.\n\nReturns:\n A SnippetEvent object.", "source": "github_repos"} +{"code": "def days(value: Union[int, float]) -> Duration:\n return float(value * 60 * 60 * 24)", "docstring": "Converts input value from number of days to a `Duration` in seconds.\n\nExample:\n ```python\n >>> a = tp.event_set(\n ... # Dates are converted to unix timestamps\n ... timestamps=[\"2020-01-01\", \"2020-01-02\", \"2020-01-31\"],\n ... features={\"f1\": [1, 5, -5]}\n ... )\n\n >>> a.moving_sum(window_length=tp.duration.days(2))\n indexes: ...\n timestamps: ['2020-01-01T00:00:00' '2020-01-02T00:00:00'\n '2020-01-31T00:00:00']\n 'f1': [ 1 6 -5]\n ...\n\n ```\n\nArgs:\n value: number of days.\n\nReturns:\n Equivalent number of seconds.", "source": "github_repos"} +{"code": "def _print_if_not_none(obj):\n if obj is not None:\n print(repr(obj))", "docstring": "Print like a notebook: Show the repr if the object is not None.\n\n `_patch_compile` Uses this on the final expression in each cell.\n\n This way the outputs feel like notebooks.\n\nArgs:\n obj: the object to print.", "source": "github_repos"} +{"code": "def _stop_profiler(self, save=True):\n if not self._profiler_started:\n return\n try:\n profiler.stop(save=save)\n except errors.UnavailableError as e:\n logging.error('Failed to stop profiler: %s', e.message)\n finally:\n self._profiler_started = False", "docstring": "Stops the profiler if currently active.\n\nArgs:\n save: Whether to save the profiler results to TensorBoard.", "source": "github_repos"} +{"code": "def _generate_unique_name(self, symbol_name: str) -> str:\n normalized_symbol_name = self._NON_SYMBOL_NAME_CHARS_REGEX.sub('_', symbol_name)\n normalized_name_conflict_count = self._num_symbols_with_normalized_name.get(normalized_symbol_name, 0)\n self._num_symbols_with_normalized_name[normalized_symbol_name] = normalized_name_conflict_count + 1\n optional_disambiguation_suffix = '' if normalized_name_conflict_count == 0 else f'_{normalized_name_conflict_count}'\n return f'{normalized_symbol_name}{optional_disambiguation_suffix}'", "docstring": "Translates a symbol name to a unique FileCheck capture name.\n\n Replaces all characters other than letters, numbers, and underscores with\n underscores. If the resulting name has already been used, appends a counter\n to disambiguate it. For example, this could result in the following sequence\n of replacements:\n 1.) \"foo.bar.baz\" -> \"foo_bar_baz\"\n 2.) \"foo.bar_baz\" -> \"foo_bar_baz_1\"\n 3.) \"foo_bar.baz\" -> \"foo_bar_baz_2\"\n 4.) \"foo_bar_baz\" -> \"foo_bar_baz_3\"\n\nArgs:\n symbol_name: The original symbol name.\n\nReturns:\n The generated FileCheck capture name.", "source": "github_repos"} +{"code": "def __init__(self, in_group_size: int=8, out_group_size: int=1, num_codebooks: int=1, nbits_per_codebook: int=16, linear_weights_not_to_quantize: Optional[List[str]]=None, **kwargs):\n self.quant_method = QuantizationMethod.AQLM\n self.in_group_size = in_group_size\n self.out_group_size = out_group_size\n self.num_codebooks = num_codebooks\n self.nbits_per_codebook = nbits_per_codebook\n self.linear_weights_not_to_quantize = linear_weights_not_to_quantize\n self.post_init()", "docstring": "This is a wrapper class about `aqlm` parameters.\n\nArgs:\n in_group_size (`int`, *optional*, defaults to 8):\n The group size along the input dimension.\n out_group_size (`int`, *optional*, defaults to 1):\n The group size along the output dimension. It's recommended to always use 1.\n num_codebooks (`int`, *optional*, defaults to 1):\n Number of codebooks for the Additive Quantization procedure.\n nbits_per_codebook (`int`, *optional*, defaults to 16):\n Number of bits encoding a single codebook vector. Codebooks size is 2**nbits_per_codebook.\n linear_weights_not_to_quantize (`Optional[List[str]]`, *optional*):\n List of full paths of `nn.Linear` weight parameters that shall not be quantized.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional parameters from which to initialize the configuration object.", "source": "github_repos"} +{"code": "def trace(x, name=None):\n with ops.name_scope(name, 'Trace', [x]) as name:\n x = ops.convert_to_tensor(x, name='x')\n return reduce_sum(array_ops.matrix_diag_part(x), [-1], name=name)", "docstring": "Compute the trace of a tensor `x`.\n\n `trace(x)` returns the sum along the main diagonal of each inner-most matrix\n in x. If x is of rank `k` with shape `[I, J, K, ..., L, M, N]`, then output\n is a tensor of rank `k-2` with dimensions `[I, J, K, ..., L]` where\n\n `output[i, j, k, ..., l] = trace(x[i, j, k, ..., l, :, :])`\n\n For example:\n\n ```python\n x = tf.constant([[1, 2], [3, 4]])\n tf.linalg.trace(x) # 5\n\n x = tf.constant([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n tf.linalg.trace(x) # 15\n\n x = tf.constant([[[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]],\n [[-1, -2, -3],\n [-4, -5, -6],\n [-7, -8, -9]]])\n tf.linalg.trace(x) # [15, -15]\n ```\n\nArgs:\n x: tensor.\n name: A name for the operation (optional).\n\nReturns:\n The trace of input tensor.", "source": "github_repos"} +{"code": "def rank(input, name=None):\n return rank_internal(input, name, optimize=True)", "docstring": "Returns the rank of a tensor.\n\n See also `tf.shape`.\n\n Returns a 0-D `int32` `Tensor` representing the rank of `input`.\n\n For example:\n\n ```python\n # shape of tensor 't' is [2, 2, 3]\n t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n tf.rank(t) # 3\n ```\n\n **Note**: The rank of a tensor is not the same as the rank of a matrix. The\n rank of a tensor is the number of indices required to uniquely select each\n element of the tensor. Rank is also known as \"order\", \"degree\", or \"ndims.\"\n\nArgs:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n\nReturns:\n A `Tensor` of type `int32`.\n\n @compatibility(numpy)\n Equivalent to np.ndim\n @end_compatibility", "source": "github_repos"} +{"code": "def validate_primitive_without_value(fhir_primitive: message.Message) -> None:\n name = fhir_primitive.DESCRIPTOR.full_name\n if len(extensions.get_fhir_extensions(fhir_primitive)) < 2:\n raise fhir_errors.InvalidFhirError(f'{name!r} must have either extensions or a value present.')\n for field, _ in fhir_primitive.ListFields():\n if field.name not in extensions.NON_VALUE_FIELDS:\n raise fhir_errors.InvalidFhirError(f'{name!r} contains PrimitiveHasNoValue but {field.name!r} is set.')", "docstring": "Validates a Message which has the PrimitiveWithoutValue extension.\n\n Given that there is a PrimitiveWithoutValue extension present, there must be\n at least one other extension. Otherwise, there is truly no value set other\n than id and/or extension (non-value fields).\n\nArgs:\n fhir_primitive: The FHIR primitive Message to validate.\n\nRaises:\n fhir_errors.InvalidFhirError: In the event that there is less than one\n extension present, or there are values set other than id and/or extension.", "source": "github_repos"} +{"code": "def _parse(json_str: str, primitive_cls: Type[Date], *, default_timezone: str) -> Date:\n try:\n dt = datetime.datetime.strptime(json_str, '%Y')\n return _primitive_time_utils.build_date_like(dt, default_timezone, _primitive_time_utils.DateTimePrecision.YEAR, primitive_cls)\n except ValueError:\n pass\n try:\n dt = datetime.datetime.strptime(json_str, '%Y-%m')\n return _primitive_time_utils.build_date_like(dt, default_timezone, _primitive_time_utils.DateTimePrecision.MONTH, primitive_cls)\n except ValueError:\n pass\n try:\n dt = datetime.datetime.strptime(json_str, '%Y-%m-%d')\n return _primitive_time_utils.build_date_like(dt, default_timezone, _primitive_time_utils.DateTimePrecision.DAY, primitive_cls)\n except ValueError:\n pass\n raise fhir_errors.InvalidFhirError('Invalid Date.')", "docstring": "Parses the json_str into a Date FHIR primitive.\n\nArgs:\n json_str: The raw JSON string to parse.\n primitive_cls: The FHIR primitive to parse into.\n default_timezone: The default timezone to use when parsing in the event that\n no timezone information is present.\n\nReturns:\n A FHIR primitive Date.\n\nRaises:\n fhir_errors.InvalidFhirError: In the event that no datetime format was\n able to properly parse the json_str.", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool=False) -> torch.Tensor:\n residual = hidden_states\n hidden_states = self.self_attn_layer_norm(hidden_states)\n hidden_states, attn_weights, _ = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions)\n hidden_states = self.attn_dropout(hidden_states)\n hidden_states = residual + hidden_states\n residual = hidden_states\n hidden_states = self.ffn_layer_norm(hidden_states)\n hidden_states = self.ffn(hidden_states)\n hidden_states = self.ffn_dropout(hidden_states)\n hidden_states = residual + hidden_states\n outputs = (hidden_states,)\n if output_attentions:\n outputs += (attn_weights,)\n return outputs", "docstring": "Args:\n hidden_states (`torch.FloatTensor`):\n input to the layer of shape `(batch, seq_len, embed_dim)`\n attention_mask (`torch.FloatTensor`):\n attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very\n large negative values.", "source": "github_repos"} +{"code": "def run(self):\n if not self._test_run_infos:\n raise Error('No tests to execute.')\n self._test_run_metadata.set_start_point()\n utils.create_dir(self._test_run_metadata.root_output_path)\n summary_writer = records.TestSummaryWriter(self._test_run_metadata.summary_file_path)\n\n def sigterm_handler(*args):\n logging.warning('Test received a SIGTERM. Aborting all tests.')\n raise signals.TestAbortAll('Test received a SIGTERM.')\n signal.signal(signal.SIGTERM, sigterm_handler)\n try:\n for test_run_info in self._test_run_infos:\n test_config = test_run_info.config.copy()\n test_config.log_path = self._test_run_metadata.root_output_path\n test_config.summary_writer = summary_writer\n test_config.test_class_name_suffix = test_run_info.test_class_name_suffix\n try:\n self._run_test_class(config=test_config, test_class=test_run_info.test_class, tests=test_run_info.tests)\n except signals.TestAbortAll as e:\n logging.warning('Abort all subsequent test classes. Reason: %s', e)\n raise\n finally:\n summary_writer.dump(self.results.summary_dict(), records.TestSummaryEntryType.SUMMARY)\n self._test_run_metadata.set_end_point()\n summary_lines = [f'Summary for test run {self._test_run_metadata.run_id}:', f'Total time elapsed {self._test_run_metadata.time_elapsed_sec}s', f'Artifacts are saved in \"{self._test_run_metadata.root_output_path}\"', f'Test summary saved in \"{self._test_run_metadata.summary_file_path}\"', f'Test results: {self.results.summary_str()}']\n logging.info('\\n'.join(summary_lines))", "docstring": "Executes tests.\n\n This will instantiate controller and test classes, execute tests, and\n print a summary.\n\n This meethod should usually be called within the runner's `mobly_logger`\n context. If you must use this method outside of the context, you should\n make sure `self._test_run_metadata.generate_test_run_log_path` is called\n before each invocation of `run`.\n\nRaises:\n Error: if no tests have previously been added to this runner using\n add_test_class(...).", "source": "github_repos"} +{"code": "def check_target_module_exists(optim_target_modules, key: str, return_is_regex: bool=False):\n target_module_found = False\n is_regex = False\n if isinstance(optim_target_modules, str):\n target_module_found = bool(re.fullmatch(optim_target_modules, key))\n is_regex = True if not optim_target_modules == key else False\n elif key in optim_target_modules:\n target_module_found = True\n elif any((target_key in key for target_key in optim_target_modules)):\n target_module_found = True\n elif any((bool(re.fullmatch(optim_target_module, key)) for optim_target_module in optim_target_modules)):\n target_module_found = True\n is_regex = True\n if return_is_regex:\n return (target_module_found, is_regex)\n return target_module_found", "docstring": "A helper method to check if the passed module's key name matches any of the target modules in the optim_target_modules.\n\nArgs:\n optim_target_modules (`Union[str, List[str]]`):\n A list of strings to try to match. Can be also a full string.\n key (`str`):\n A key to search any matches in optim_target_modules\n return_is_regex (`bool`):\n If set to `True`, the method will return whether the passed `optim_target_modules`\n is a regex or not.\n\nReturns:\n `bool` : True of match object if key matches any target modules from config, False or\n None if no match found\n `bool` : If the matched target module is a regex to silence out the warnings in Trainer\n for extra modules being found (only if `target_module_found=True` for an array of regex).", "source": "github_repos"} +{"code": "def events_from_file(filepath):\n records = list(tf_record.tf_record_iterator(filepath))\n result = []\n for r in records:\n event = event_pb2.Event()\n event.ParseFromString(r)\n result.append(event)\n return result", "docstring": "Returns all events in a single event file.\n\nArgs:\n filepath: Path to the event file.\n\nReturns:\n A list of all tf.Event protos in the event file.", "source": "github_repos"} +{"code": "def set_tpu_core_ids(self, mesh_name, tpu_core_ids):\n _pywrap_dtensor_device.SetTPUCoreIDs(self._device_info, mesh_name, tpu_core_ids)", "docstring": "Sets the singleton global device ID-to-physical core ID map.\n\nArgs:\n mesh_name: The name of a mesh. If empty, set the default mapping.\n tpu_core_ids: TPU core IDs sorted by TF task/device ordinal.", "source": "github_repos"} +{"code": "def random_channel_shift(x, intensity_range, channel_axis=0):\n intensity = np.random.uniform(-intensity_range, intensity_range)\n return apply_channel_shift(x, intensity, channel_axis=channel_axis)", "docstring": "Performs a random channel shift.\n\n DEPRECATED.\n\nArgs:\n x: Input tensor. Must be 3D.\n intensity_range: Transformation intensity.\n channel_axis: Index of axis for channels in the input tensor.\n\nReturns:\n Numpy image tensor.", "source": "github_repos"} +{"code": "def __init__(self, build_info_key, system_prop_key):\n self.build_info_key = build_info_key\n self.system_prop_key = system_prop_key", "docstring": "Enums for build info constants used for AndroidDevice build info.\n\nAttributes:\n build_info_key: The key used for the build_info dictionary in AndroidDevice.\n system_prop_key: The key used for getting the build info from system\n properties.", "source": "github_repos"} +{"code": "def chunk_embedding_fn(chunk: Chunk) -> str:\n if chunk.embedding is None or chunk.embedding.dense_embedding is None:\n raise ValueError(f'Expected chunk to contain embedding. {chunk}')\n return '{' + ','.join((str(x) for x in chunk.embedding.dense_embedding)) + '}'", "docstring": "Convert embedding to PostgreSQL array string.\n\n Formats dense embedding as a PostgreSQL-compatible array string.\n Example: [1.0, 2.0] -> '{1.0,2.0}'\n\nArgs:\n chunk: Input Chunk object.\n\nReturns:\n str: PostgreSQL array string representation of the embedding.\n\nRaises:\n ValueError: If chunk has no dense embedding.", "source": "github_repos"} +{"code": "def conv1d(x, kernel, strides=1, padding='valid', data_format=None, dilation_rate=1):\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format: ' + str(data_format))\n kernel_shape = kernel.shape.as_list()\n if padding == 'causal':\n left_pad = dilation_rate * (kernel_shape[0] - 1)\n x = temporal_padding(x, (left_pad, 0))\n padding = 'valid'\n padding = _preprocess_padding(padding)\n x, tf_data_format = _preprocess_conv1d_input(x, data_format)\n x = nn.convolution(input=x, filter=kernel, dilation_rate=dilation_rate, strides=strides, padding=padding, data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NWC':\n x = array_ops.transpose(x, (0, 2, 1))\n return x", "docstring": "1D convolution.\n\nArgs:\n x: Tensor or variable.\n kernel: kernel tensor.\n strides: stride integer.\n padding: string, `\"same\"`, `\"causal\"` or `\"valid\"`.\n data_format: string, one of \"channels_last\", \"channels_first\".\n dilation_rate: integer dilate rate.\n\nReturns:\n A tensor, result of 1D convolution.\n\nRaises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.", "source": "github_repos"} +{"code": "def _verify_spec_compatible(input_name, spec_name, input_, spec):\n assert isinstance(spec, tensor_spec.TensorSpec)\n if input is None:\n raise ValueError('{} cannot be None'.format(input_name))\n if isinstance(input_, (bool, int, float, str, np.ndarray)):\n input_ = tensor_conversion.convert_to_tensor_v2(input_)\n input_dtype = getattr(input_, 'dtype', None)\n if input_dtype != spec.dtype:\n input_dtype_str = 'no dtype' if input_dtype is None else str(input_dtype)\n raise TypeError('{} must have the same dtype as {}. Expected {}, got {}'.format(input_name, spec_name, spec.dtype, input_dtype_str))", "docstring": "Verifies that a symbol has a type compatible vith a given spec.\n\n Here, compatibility is viewed in the general TensorFlow sense: that the dtypes\n are the same after implicit conversion, if both are tensors.\n\n This verifier ensures consistent treatment of types across AutoGraph.\n\nArgs:\n input_name: A name to use for `input_` in error messages.\n spec_name: A name to use for `spec` in error messages.\n input_: Any, value to verify.\n spec: TypeSpec that `input_` must be compatible with.\n\nRaises:\n ValueError if the two types have been determined not to be compatible.", "source": "github_repos"} +{"code": "def get_matching_files_v2(pattern):\n if isinstance(pattern, six.string_types):\n return [compat.as_str_any(matching_filename) for matching_filename in _pywrap_file_io.GetMatchingFiles(compat.as_bytes(pattern))]\n else:\n return [compat.as_str_any(matching_filename) for single_filename in pattern for matching_filename in _pywrap_file_io.GetMatchingFiles(compat.as_bytes(single_filename))]", "docstring": "Returns a list of files that match the given pattern(s).\n\n The patterns are defined as strings. Supported patterns are defined\n here. Note that the pattern can be a Python iteratable of string patterns.\n\n The format definition of the pattern is:\n\n **pattern**: `{ term }`\n\n **term**:\n * `'*'`: matches any sequence of non-'/' characters\n * `'?'`: matches a single non-'/' character\n * `'[' [ '^' ] { match-list } ']'`: matches any single\n character (not) on the list\n * `c`: matches character `c` where `c != '*', '?', '\\\\', '['`\n * `'\\\\' c`: matches character `c`\n\n **character range**:\n * `c`: matches character `c` while `c != '\\\\', '-', ']'`\n * `'\\\\' c`: matches character `c`\n * `lo '-' hi`: matches character `c` for `lo <= c <= hi`\n\nExample:\n >>> tf.io.gfile.glob(\"*.py\")\n ... # For example, ['__init__.py']\n\n >>> tf.io.gfile.glob(\"__init__.??\")\n ... # As above\n\n >>> files = {\"*.py\"}\n >>> the_iterator = iter(files)\n >>> tf.io.gfile.glob(the_iterator)\n ... # As above\n\n See the C++ function `GetMatchingPaths` in\n [`core/platform/file_system.h`]\n (../../../core/platform/file_system.h)\n for implementation details.\n\nArgs:\n pattern: string or iterable of strings. The glob pattern(s).\n\nReturns:\n A list of strings containing filenames that match the given pattern(s).\n\nRaises:\n errors.OpError: If there are filesystem / directory listing errors.\n errors.NotFoundError: If pattern to be matched is an invalid directory.", "source": "github_repos"} +{"code": "def tensor_rank(self, name='tensor_rank'):\n with self._name_scope(name):\n return self.shape.ndims", "docstring": "Rank (in the sense of tensors) of matrix corresponding to this operator.\n\n If this operator acts like the batch matrix `A` with\n `A.shape = [B1,...,Bb, M, N]`, then this returns `b + 2`.\n\nArgs:\n name: A name for this `Op`.\n\nReturns:\n Python integer, or None if the tensor rank is undefined.", "source": "github_repos"} +{"code": "def is_extension_type(tensor):\n return isinstance(tensor, composite_tensor.CompositeTensor)", "docstring": "Returns whether a tensor is of an ExtensionType.\n\n github.com/tensorflow/community/pull/269\n Currently it works by checking if `tensor` is a `CompositeTensor` instance,\n but this will be changed to use an appropriate extensiontype protocol\n check once ExtensionType is made public.\n\nArgs:\n tensor: An object to test\n\nReturns:\n True if the tensor is an extension type object, false if not.", "source": "github_repos"} +{"code": "def shape(self):\n return self._shape", "docstring": "The statically known shape of the RaggedTensor.\n\nExample:\n >>> rt = tf.ragged.constant([[0], [1, 2]])\n >>> tf.type_spec_from_value(rt).shape\n TensorShape([2, None])\n\n >>> rt = tf.ragged.constant([[[0, 1]], [[1, 2], [3, 4]]], ragged_rank=1)\n >>> tf.type_spec_from_value(rt).shape\n TensorShape([2, None, 2])\n\nReturns:\n A `tf.TensorShape` containing the statically known shape of the\n RaggedTensor. Ragged dimensions have a size of `None`.", "source": "github_repos"} +{"code": "def __init__(self, config: CLIPConfig, **kwargs):\n super().__init__(**kwargs)\n self.layers = [TFCLIPEncoderLayer(config, name=f'layers_._{i}') for i in range(config.num_hidden_layers)]", "docstring": "Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a\n [`TFCLIPEncoderLayer`].\n\nArgs:\n config: CLIPConfig", "source": "github_repos"} +{"code": "def row_splits_to_segment_ids(splits, name=None, out_type=None):\n with ops.name_scope(name, 'RaggedSplitsToSegmentIds', [splits]) as name:\n splits = ops.convert_to_tensor(splits, name='splits', preferred_dtype=dtypes.int64)\n if splits.dtype not in (dtypes.int32, dtypes.int64):\n raise ValueError('splits must have dtype int32 or int64')\n splits.shape.assert_has_rank(1)\n if tensor_shape.dimension_value(splits.shape[0]) == 0:\n raise ValueError('Invalid row_splits: []')\n if out_type is None:\n out_type = splits.dtype\n else:\n out_type = dtypes.as_dtype(out_type)\n row_lengths = splits[1:] - splits[:-1]\n nrows = array_ops.shape(splits, out_type=out_type)[-1] - 1\n indices = math_ops.range(nrows)\n return ragged_util.repeat(indices, repeats=row_lengths, axis=0)", "docstring": "Generates the segmentation corresponding to a RaggedTensor `row_splits`.\n\n Returns an integer vector `segment_ids`, where `segment_ids[i] == j` if\n `splits[j] <= i < splits[j+1]`. Example:\n\n >>> print(tf.ragged.row_splits_to_segment_ids([0, 3, 3, 5, 6, 9]))\n tf.Tensor([0 0 0 2 2 3 4 4 4], shape=(9,), dtype=int64)\n\nArgs:\n splits: A sorted 1-D integer Tensor. `splits[0]` must be zero.\n name: A name prefix for the returned tensor (optional).\n out_type: The dtype for the return value. Defaults to `splits.dtype`,\n or `tf.int64` if `splits` does not have a dtype.\n\nReturns:\n A sorted 1-D integer Tensor, with `shape=[splits[-1]]`\n\nRaises:\n ValueError: If `splits` is invalid.", "source": "github_repos"} +{"code": "def ReportStatus(self, request, global_params=None):\n config = self.GetMethodConfig('ReportStatus')\n return self._RunMethod(config, request, global_params=global_params)", "docstring": "Reports the status of dataflow WorkItems leased by a worker.\n\nArgs:\n request: (DataflowProjectsLocationsJobsWorkItemsReportStatusRequest) input message\n global_params: (StandardQueryParameters, default: None) global arguments\n\nReturns:\n (ReportWorkItemStatusResponse) The response message.", "source": "github_repos"} +{"code": "def _print_primitive_field(self, field_name: str, field: descriptor.FieldDescriptor, value: Any) -> None:\n if proto_utils.field_is_repeated(field):\n string_values = []\n elements = []\n extensions_found = False\n nonnull_values_found = False\n for primitive in value:\n wrapper = self.primitive_handler.primitive_wrapper_from_primitive(primitive)\n string_values.append(wrapper.json_value())\n elements.append(wrapper.get_element())\n nonnull_values_found = nonnull_values_found or wrapper.has_value()\n extensions_found = extensions_found or wrapper.has_element()\n if nonnull_values_found:\n self.generator.add_field(field_name)\n self._print_list(string_values, self.generator.push)\n if extensions_found:\n if nonnull_values_found:\n self.generator.push(',')\n self.generator.add_newline()\n self.generator.add_field(f'_{field_name}')\n self._print_list(elements, self._print)\n elif self.json_format == _FhirJsonFormat.ANALYTIC and field.message_type.name == 'ReferenceId':\n str_value = proto_utils.get_value_at_field(value, 'value')\n self.generator.add_field(field_name, f'\"{str_value}\"')\n else:\n wrapper = self.primitive_handler.primitive_wrapper_from_primitive(value)\n if wrapper.has_value():\n self.generator.add_field(field_name, wrapper.json_value())\n if wrapper.has_element() and self.json_format == _FhirJsonFormat.PURE:\n if wrapper.has_value():\n self.generator.push(',')\n self.generator.add_newline()\n self.generator.add_field(f'_{field_name}')\n self._print(wrapper.get_element())", "docstring": "Prints the primitive field.\n\nArgs:\n field_name: The name of the field.\n field: The FielDescriptor whose contents to print.\n value: The value present at field to print.", "source": "github_repos"} +{"code": "def print_type_of_instance(self, t: types.BaseValue, instance=None) -> str:", "docstring": "Returns a string of the type of an instance of t.\n\n For example, if t is `int`, then this method returns \"int\".\n\nArgs:\n t: An abstract value.\n instance: A specific instance of t to print.", "source": "github_repos"} +{"code": "def __init__(self, base: ModelHandler[ExampleT, PredictionT, ModelT]):\n self._base = base\n self._env_vars = getattr(base, '_env_vars', {})", "docstring": "A ModelHandler that skips batching in RunInference.\n\nArgs:\n base: An implementation of the underlying model handler.", "source": "github_repos"} +{"code": "def GetSubClasses():\n return utils.invert_dict(GetSuperClasses())", "docstring": "Get a reverse Python type hierarchy mapping.\n\n This generates a dictionary that can be used to look up the (known)\n subclasses of a type in the abstract base class hierarchy.\n\nReturns:\n A dictionary mapping a type, as string, to a list of direct\n subclasses (also as strings).\n E.g. \"Sized\" -> [\"Set\", \"Mapping\", \"MappingView\", \"Sequence\"].", "source": "github_repos"} +{"code": "def recipe_includes(recipe, path=None):\n expanded_tasks = []\n for task in recipe['tasks']:\n function, parameters = next(iter(task.items()))\n if function == 'include':\n if path:\n tasks = get_recipe(path + '/' + parameters['script'])['tasks']\n json_merge_fields(tasks, parameters['parameters'])\n expanded_tasks.extend(tasks)\n else:\n raise FileNotFoundError('Script contains INCLUDE but no include path specified: %s' % path + '/' + parameters['script'])\n else:\n expanded_tasks.append({function: parameters})\n recipe['tasks'] = expanded_tasks\n return recipe", "docstring": "Expands include block and merges fields.\n\n This ONLY transforms a recipe by merging fields not resolving them.\n All fields remain as fields but parameters in the include are written\n over the fields in the included recipe.\n\n For example:\n\n { \"include\":{\n \"script\":\"scripts/dv360_segmentology.json\",\n \"parameters\":{\n \"auth_read\":\"user\",\n \"auth_write\":\"service\",\n \"recipe_name\":{\"field\":{ \"name\":\"test_run_id\", \"kind\":\"string\", \"description\":\"The name to use for the test.\", \"prefix\":\"StarThinker Test Segmentology DV \", \"default\": \"Manual\"}},\n \"partners\":{\"field\":{ \"name\":\"partners\", \"kind\":\"integer_list\", \"default\":[], \"description\":\"DV360 partner id.\" }},\n }\n\n Generated by:\n\n python starthinker/tool/test.py -i scripts/dv360_segmentology.json\n\nArgs:\n - recipe: (dict) A json recipe that may include { \"include\":... } task.\n - path: (string) The file path where included recipes are to be read from.\n\nReturns:\n Dictionary with tasks from all includes and fields merged.", "source": "github_repos"} +{"code": "def process_column(body: ProcessColumnRequest) -> ResponseReturnValue:\n credentials = get_credentials(body.auth_config)\n logger: Logger\n if not body.log_table:\n logger = PrintLogger()\n else:\n logger = BigQueryLogger(body.log_table, body.auth_config)\n logger.set_base_log(__version__, body.workflow_execution_id, body.display_source_table, datetime.utcnow())\n bq_read_client = get_bq_read_client(credentials)\n parser, usable_rules = map_parser_to_rules(body.column_config['parser'])\n rules = generate_selected_rules(body.column_config['rules'], usable_rules)\n column_name = body.column_config['column']\n cells_iterator = get_cells_iterator(bq_read_client, body.source_table, column_name)\n row_counter = 0\n parse_failures = 0\n rule_errors = 0\n check_violations = 0\n for cell in cells_iterator:\n try:\n value = parser(cell)\n except Exception as e:\n logger.parser(column_name, parser.__name__, str(e), cell)\n parse_failures += 1\n else:\n for rule in rules:\n try:\n result = rule(value)\n except Exception as e:\n logger.rule(column_name, rule.__name__, str(e), value, rule.__kwdefaults__)\n rule_errors += 1\n else:\n if result is not None:\n logger.rule(column_name, rule.__name__, result, value, rule.__kwdefaults__)\n check_violations += 1\n row_counter += 1\n logger.flush(force=True)\n if row_counter == 0:\n raise RuntimeError('Source table was empty.')\n message = f'DQM processed {row_counter} rows, with {parse_failures} parse failures, {rule_errors} rule errors, {check_violations} rule check violations.'\n return (DQMResponse(name='', description=message, code=200), 200)", "docstring": "Process a given column from the specified table.\n\nArgs:\n * body: ProcessColumnRequest HTTP request body\n\nReturns:\n * DQMResponse for the run with a 200 status code\n\nRaises:\n * MalformedConfigError: if the request body was malformed", "source": "github_repos"} +{"code": "def softsign(x):\n return nn.softsign(x)", "docstring": "Softsign of a tensor.\n\nArgs:\n x: A tensor or variable.\n\nReturns:\n A tensor.", "source": "github_repos"} +{"code": "def process(self, element: tuple[str, prediction_log_pb2.PredictionLog]) -> Iterable[str]:\n filename, predict_log = (element[0], element[1].predict_log)\n output_value = predict_log.response.outputs\n output_tensor = tf.io.decode_raw(output_value['output_0'].tensor_content, out_type=tf.float32)\n max_index_output_tensor = tf.math.argmax(output_tensor, axis=0)\n yield (filename + ',' + str(tf.get_static_value(max_index_output_tensor)))", "docstring": "Args:\n element: Tuple of str, and PredictionLog. Inference can be parsed\n from prediction_log\n\nReturns:\n str of filename and inference.", "source": "github_repos"} +{"code": "def concatenate_context_input(context_input, sequence_input):\n seq_rank_check = check_ops.assert_rank(sequence_input, 3, message='sequence_input must have rank 3', data=[array_ops.shape(sequence_input)])\n seq_type_check = check_ops.assert_type(sequence_input, dtypes.float32, message='sequence_input must have dtype float32; got {}.'.format(sequence_input.dtype))\n ctx_rank_check = check_ops.assert_rank(context_input, 2, message='context_input must have rank 2', data=[array_ops.shape(context_input)])\n ctx_type_check = check_ops.assert_type(context_input, dtypes.float32, message='context_input must have dtype float32; got {}.'.format(context_input.dtype))\n with ops.control_dependencies([seq_rank_check, seq_type_check, ctx_rank_check, ctx_type_check]):\n padded_length = array_ops.shape(sequence_input)[1]\n tiled_context_input = array_ops.tile(array_ops.expand_dims(context_input, 1), array_ops.concat([[1], [padded_length], [1]], 0))\n return array_ops.concat([sequence_input, tiled_context_input], 2)", "docstring": "Replicates `context_input` across all timesteps of `sequence_input`.\n\n Expands dimension 1 of `context_input` then tiles it `sequence_length` times.\n This value is appended to `sequence_input` on dimension 2 and the result is\n returned.\n\nArgs:\n context_input: A `Tensor` of dtype `float32` and shape `[batch_size, d1]`.\n sequence_input: A `Tensor` of dtype `float32` and shape `[batch_size,\n padded_length, d0]`.\n\nReturns:\n A `Tensor` of dtype `float32` and shape `[batch_size, padded_length,\n d0 + d1]`.\n\nRaises:\n ValueError: If `sequence_input` does not have rank 3 or `context_input` does\n not have rank 2.", "source": "github_repos"} +{"code": "def __init__(self, major, minor, patch, identifier_string, version_type):\n self.major = major\n self.minor = minor\n self.patch = patch\n self.identifier_string = identifier_string\n self.version_type = version_type\n self._update_string()", "docstring": "Constructor.\n\nArgs:\n major: major string eg. (1)\n minor: minor string eg. (3)\n patch: patch string eg. (1)\n identifier_string: extension string eg. (-rc0)\n version_type: version parameter ((SNAPSHOT|NIGHTLY)_VERSION)", "source": "github_repos"} +{"code": "def _TestCase(self, shape, indices, scatter_op=state_ops.scatter_add):\n super(ScatterAddSubTest, self).setUp()\n with self.cached_session(use_gpu=False):\n p_init = np.random.rand(*shape).astype('f')\n vals_shape = [len(indices)] + shape[1:]\n vals_init = np.random.rand(*vals_shape).astype('f')\n v_i = [float(x) for x in vals_init.ravel()]\n p = variables.Variable(p_init)\n vals = constant_op.constant(v_i, shape=vals_shape, name='vals')\n ind = constant_op.constant(indices, dtype=dtypes.int32)\n p2 = scatter_op(p, ind, vals, name='updated_p')\n self.evaluate(variables.global_variables_initializer())\n result = self.evaluate(p2)\n for i, ind in enumerate(indices):\n if scatter_op == state_ops.scatter_add:\n p_init.reshape(shape[0], -1)[ind, :] += vals_init.reshape(vals_shape[0], -1)[i, :]\n else:\n p_init.reshape(shape[0], -1)[ind, :] -= vals_init.reshape(vals_shape[0], -1)[i, :]\n self.assertTrue(all((p_init == result).ravel()))", "docstring": "Run a random test case with the given shape and indices.\n\nArgs:\n shape: Shape of the parameters array.\n indices: One-dimensional array of ints, the indices of the last dimension\n of the parameters to update.\n scatter_op: ScatterAdd or ScatterSub.", "source": "github_repos"} +{"code": "def floating_point_ops(self, inputs: dict[str, Union[torch.Tensor, Any]]):\n if hasattr(self.model, 'floating_point_ops'):\n return self.model.floating_point_ops(inputs)\n else:\n return 0", "docstring": "For models that inherit from [`PreTrainedModel`], uses that method to compute the number of floating point\n operations for every backward + forward pass. If using another model, either implement such a method in the\n model or subclass and override this method.\n\nArgs:\n inputs (`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\nReturns:\n `int`: The number of floating-point operations.", "source": "github_repos"} +{"code": "def partial_run_setup(self, fetches, feeds=None):\n\n def _feed_fn(feed):\n for tensor_type, _, _, feed_fn in _REGISTERED_EXPANSIONS:\n if isinstance(feed, tensor_type):\n return feed_fn(feed)\n raise TypeError(f'Feed argument {feed} has invalid type \"{type(feed).__name__}\"')\n if self._closed:\n raise RuntimeError('Attempted to use a closed Session.')\n if self.graph.version == 0:\n raise RuntimeError('The Session graph is empty. Add operations to the graph before calling run().')\n if feeds is None:\n feeds = []\n feed_list = []\n is_list_feed = isinstance(feeds, (list, tuple))\n if not is_list_feed:\n feeds = [feeds]\n for feed in feeds:\n for subfeed in _feed_fn(feed):\n try:\n subfeed_t = self.graph.as_graph_element(subfeed, allow_tensor=True, allow_operation=False)\n feed_list.append(subfeed_t._as_tf_output())\n except Exception as e:\n e.message = f'Cannot interpret argument `feed` key as Tensor: {e.message}'\n e.args = (e.message,)\n raise e\n fetch_handler = _FetchHandler(self._graph, fetches, {})\n\n def _setup_fn(session, feed_list, fetch_list, target_list):\n self._extend_graph()\n return tf_session.TF_SessionPRunSetup_wrapper(session, feed_list, fetch_list, target_list)\n final_fetches = [t._as_tf_output() for t in fetch_handler.fetches()]\n final_targets = [op._c_op for op in fetch_handler.targets()]\n return self._do_call(_setup_fn, self._session, feed_list, final_fetches, final_targets)", "docstring": "Sets up a graph with feeds and fetches for partial run.\n\n NOTE: This function is deprecated and we do not expect adding new\n functionality to it. Please do not have your code depending on this\n function.\n\n This is EXPERIMENTAL and subject to change.\n\n Note that contrary to `run`, `feeds` only specifies the graph elements.\n The tensors will be supplied by the subsequent `partial_run` calls.\n\nArgs:\n fetches: A single graph element, or a list of graph elements.\n feeds: A single graph element, or a list of graph elements.\n\nReturns:\n A handle for partial run.\n\nRaises:\n RuntimeError: If this `Session` is in an invalid state (e.g. has been\n closed).\n TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type.\n tf.errors.OpError: Or one of its subclasses if a TensorFlow error happens.", "source": "github_repos"} +{"code": "def run(argv=None, save_main_session=True):\n known_args, pipeline_args = parse_known_args(argv)\n pipeline_options = PipelineOptions(pipeline_args)\n pipeline_options.view_as(SetupOptions).save_main_session = save_main_session\n engine_handler = KeyedModelHandler(TensorRTEngineHandlerNumPy(min_batch_size=1, max_batch_size=1, engine_path=known_args.engine_path))\n with beam.Pipeline(options=pipeline_options) as p:\n filename_value_pair = p | 'ReadImageNames' >> beam.io.ReadFromText(known_args.input) | 'ReadImageData' >> beam.Map(lambda image_name: read_image(image_file_name=image_name, path_to_dir=known_args.images_dir)) | 'AttachImageSizeToKey' >> beam.Map(attach_im_size_to_key) | 'PreprocessImages' >> beam.MapTuple(lambda file_name, data: (file_name, preprocess_image(data)))\n predictions = filename_value_pair | 'TensorRTRunInference' >> RunInference(engine_handler) | 'ProcessOutput' >> beam.ParDo(PostProcessor())\n _ = predictions | 'WriteOutputToGCS' >> beam.io.WriteToText(known_args.output, shard_name_template='', append_trailing_newlines=True)", "docstring": "Args:\n argv: Command line arguments defined for this example.", "source": "github_repos"} +{"code": "def _test_dir(self, test_name):\n test_dir = os.path.join(self.get_temp_dir(), test_name)\n if os.path.isdir(test_dir):\n for f in glob.glob('%s/*' % test_dir):\n os.remove(f)\n else:\n os.makedirs(test_dir)\n return test_dir", "docstring": "Create an empty dir to use for tests.\n\nArgs:\n test_name: Name of the test.\n\nReturns:\n Absolute path to the test directory.", "source": "github_repos"} +{"code": "def Filter(fn, *args, **kwargs):\n if not callable(fn):\n raise TypeError('Filter can be used only with callable objects. Received %r instead.' % fn)\n wrapper = lambda x, *args, **kwargs: [x] if fn(x, *args, **kwargs) else []\n label = 'Filter(%s)' % ptransform.label_from_callable(fn)\n if hasattr(fn, '__name__'):\n wrapper.__name__ = fn.__name__\n fn_type_hints = typehints.decorators.IOTypeHints.from_callable(fn)\n if fn_type_hints is not None:\n fn_type_hints = fn_type_hints.with_output_types()\n type_hints = get_type_hints(fn).with_defaults(fn_type_hints)\n if type_hints.input_types is not None:\n wrapper = with_input_types(*type_hints.input_types[0], **type_hints.input_types[1])(wrapper)\n output_hint = type_hints.simple_output_type(label)\n if output_hint is None and get_type_hints(wrapper).input_types and get_type_hints(wrapper).input_types[0]:\n output_hint = get_type_hints(wrapper).input_types[0][0]\n if output_hint:\n wrapper = with_output_types(typehints.Iterable[_strip_output_annotations(output_hint)])(wrapper)\n wrapper._argspec_fn = fn\n pardo = FlatMap(wrapper, *args, **kwargs)\n pardo.label = label\n return pardo", "docstring": ":func:`Filter` is a :func:`FlatMap` with its callable filtering out\n elements.\n\n Filter accepts a function that keeps elements that return True, and filters\n out the remaining elements.\n\nArgs:\n fn (``Callable[..., bool]``): a callable object. First argument will be an\n element.\n *args: positional arguments passed to the transform callable.\n **kwargs: keyword arguments passed to the transform callable.\n\nReturns:\n ~apache_beam.pvalue.PCollection:\n A :class:`~apache_beam.pvalue.PCollection` containing the\n :func:`Filter` outputs.\n\nRaises:\n TypeError: If the **fn** passed as argument is not a callable.\n Typical error is to pass a :class:`DoFn` instance which is supported only\n for :class:`ParDo`.", "source": "github_repos"} +{"code": "def get_metrics_namespace(self) -> str:\n return 'BeamML_TF_Numpy'", "docstring": "Returns:\n A namespace for metrics collected by the RunInference transform.", "source": "github_repos"} +{"code": "def run_trials(runs):\n inside_runs = 0\n for _ in range(runs):\n x = random.uniform(0, 1)\n y = random.uniform(0, 1)\n inside_runs += 1 if x * x + y * y <= 1.0 else 0\n return (runs, inside_runs, 0)", "docstring": "Run trials and return a 3-tuple representing the results.\n\nArgs:\n runs: Number of trial runs to be executed.\n\nReturns:\n A 3-tuple (total trials, inside trials, 0).\n\n The final zero is needed solely to make sure that the combine_results function\n has same type for inputs and outputs (a requirement for combiner functions).", "source": "github_repos"} +{"code": "def __init__(self, pya: pyaudio.PyAudio, substream_name: str='realtime', audio_format: AudioFormats=pyaudio.paInt16, channels: int=1, rate: int=24000):\n self._pya = pya\n self._format = audio_format\n self._channels = channels\n self._rate = rate\n self._substream_name = substream_name", "docstring": "Initializes the audio input processor.\n\nArgs:\n pya: The pyaudio object to use for capturing audio.\n substream_name: The name of the substream that will contain all the audio\n parts captured from the mic.\n audio_format: The audio format to use for the audio.\n channels: The number of channels in the audio.\n rate: The sample rate of the audio.", "source": "github_repos"} +{"code": "def get_unconditional_inputs(self, num_samples=1):\n last_hidden_state = torch.zeros((num_samples, 1, self.config.text_encoder.hidden_size), device=self.device, dtype=self.dtype)\n attention_mask = torch.zeros((num_samples, 1), device=self.device, dtype=torch.long)\n return MusicgenUnconditionalInput(encoder_outputs=(last_hidden_state,), attention_mask=attention_mask, guidance_scale=1.0)", "docstring": "Helper function to get null inputs for unconditional generation, enabling the model to be used without the\n feature extractor or tokenizer.\n\nArgs:\n num_samples (int, *optional*):\n Number of audio samples to unconditionally generate.\n max_new_tokens (int, *optional*):\n Number of tokens to generate for each sample. More tokens means longer audio samples, at the expense of\n longer inference (since more audio tokens need to be generated per sample).\n\nExample:\n ```python\n >>> from transformers import MusicgenForConditionalGeneration\n\n >>> model = MusicgenForConditionalGeneration.from_pretrained(\"facebook/musicgen-small\")\n\n >>> # get the unconditional (or 'null') inputs for the model\n >>> unconditional_inputs = model.get_unconditional_inputs(num_samples=1)\n >>> audio_samples = model.generate(**unconditional_inputs, max_new_tokens=256)\n ```", "source": "github_repos"} +{"code": "def lists_to_tuples(structure):\n return tree_impl.lists_to_tuples(structure)", "docstring": "Returns the structure with list instances changed to tuples.\n\nArgs:\n structure: Arbitrarily nested structure.\n\nReturns:\n The same structure but with tuples instead of lists.", "source": "github_repos"} +{"code": "def _GenerateTestData(self, num_classes, dim, batch_size, num_true, labels, sampled, subtract_log_q):\n weights = np.random.randn(num_classes, dim).astype(np.float32)\n biases = np.random.randn(num_classes).astype(np.float32)\n hidden_acts = np.random.randn(batch_size, dim).astype(np.float32)\n true_exp = np.full([batch_size, 1], fill_value=0.5, dtype=np.float32)\n sampled_exp = np.full([len(sampled)], fill_value=0.5, dtype=np.float32)\n sampled_vals = (sampled, true_exp, sampled_exp)\n sampled_w, sampled_b = (weights[sampled], biases[sampled])\n true_w, true_b = (weights[labels], biases[labels])\n true_logits = np.sum(hidden_acts.reshape((batch_size, 1, dim)) * true_w.reshape((batch_size, num_true, dim)), axis=2)\n true_b = true_b.reshape((batch_size, num_true))\n true_logits += true_b\n sampled_logits = np.dot(hidden_acts, sampled_w.T) + sampled_b\n if subtract_log_q:\n true_logits -= np.log(true_exp)\n sampled_logits -= np.log(sampled_exp[np.newaxis, :])\n exp_logits = np.concatenate([true_logits, sampled_logits], axis=1)\n exp_labels = np.hstack((np.ones_like(true_logits) / num_true, np.zeros_like(sampled_logits)))\n return (weights, biases, hidden_acts, sampled_vals, exp_logits, exp_labels)", "docstring": "Randomly generates input/output data for a single test case.\n\n This function returns numpy constants for use in a test case.\n\nArgs:\n num_classes: An int. The number of embedding classes in the test case.\n dim: An int. The dimension of the embedding.\n batch_size: An int. The batch size.\n num_true: An int. The number of target classes per training example.\n labels: A list of batch_size * num_true ints. The target classes.\n sampled: A list of indices in [0, num_classes).\n subtract_log_q: A bool corresponding to the parameter in\n _compute_sampled_logits().\n\nReturns:\n weights: Embedding weights to use as test input. It is a numpy array\n of shape [num_classes, dim]\n biases: Embedding biases to use as test input. It is a numpy array\n of shape [num_classes].\n hidden_acts: Forward activations of the network to use as test input.\n It is a numpy array of shape [batch_size, dim].\n sampled_vals: A tuple based on `sampled` to use as test input in the\n format returned by a *_candidate_sampler function.\n exp_logits: The output logits expected from _compute_sampled_logits().\n It is a numpy array of shape [batch_size, num_true + len(sampled)].\n exp_labels: The output labels expected from _compute_sampled_logits().\n It is a numpy array of shape [batch_size, num_true + len(sampled)].", "source": "github_repos"} +{"code": "def _flat_structure(self):\n return {'output_shapes': self._flat_shapes, 'output_types': self._flat_types}", "docstring": "Helper for setting `output_shapes` and `output_types` attrs of an op.\n\n Most dataset op constructors expect `output_shapes` and `output_types`\n arguments that represent the flattened structure of an element. This helper\n function generates these attrs as a keyword argument dictionary, allowing\n `Dataset._variant_tensor` implementations to pass `**self._flat_structure`\n to the op constructor.\n\nReturns:\n A dictionary of keyword arguments that can be passed to a dataset op\n constructor.", "source": "github_repos"} +{"code": "def _flag_value_as_list(self, wanted_flag_name):\n string_value_list = []\n found, flag_value = self.get_flag_value(wanted_flag_name)\n if found:\n assert flag_value is not None\n string_value_list = flag_value.split(',')\n return string_value_list", "docstring": "Returns the string list of a TensorTracer flag.\n\nArgs:\n wanted_flag_name: the name of the flag we are looking for.\n\nReturns:\n The list value of the flag.", "source": "github_repos"} +{"code": "def build_results(self, values):\n raise NotImplementedError('build_results must be implemented by subclasses')", "docstring": "Build results that match the original shape of the fetch.\n\nArgs:\n values: List of values returned by run(). The values correspond exactly to\n the list tensors or ops returned by unique_fetches().\n\nReturns:\n A struct of the same shape as the original fetch object handled by\n this fetch mapper. In the returned struct, the original fetches are\n replaced by their fetched values.", "source": "github_repos"} +{"code": "def _preprocess_op_time(self, op_time: str) -> None:\n if op_time == 'schedule':\n self._step_stats = self._origin_step_stats\n return\n self._step_stats = copy.deepcopy(self._origin_step_stats)\n stream_all_stats = []\n job_stats = []\n for stats in self._step_stats.dev_stats:\n if '/stream:all' in stats.device:\n stream_all_stats.append(stats)\n elif '/job' in stats.device:\n job_stats.append(stats)\n op_gpu_start = {}\n op_gpu_end = {}\n for stats in stream_all_stats:\n for kernel in stats.node_stats:\n name, _ = self._parse_kernel_label(kernel.timeline_label, kernel.node_name)\n start = kernel.all_start_micros\n end = kernel.all_start_micros + kernel.all_end_rel_micros\n if name in op_gpu_start:\n op_gpu_start[name] = min(op_gpu_start[name], start)\n op_gpu_end[name] = max(op_gpu_end[name], end)\n else:\n op_gpu_start[name] = start\n op_gpu_end[name] = end\n for stats in job_stats:\n for op in stats.node_stats:\n if op.node_name in op_gpu_start:\n end = max(op_gpu_end[op.node_name], op.all_start_micros + op.all_end_rel_micros)\n if op_time == 'gpu':\n op.all_start_micros = op_gpu_start[op.node_name]\n op.all_end_rel_micros = end - op.all_start_micros", "docstring": "Update the start and end time of ops in step stats.\n\nArgs:\n op_time: How the execution time of op is shown in timeline. Possible\n values are \"schedule\", \"gpu\" and \"all\". \"schedule\" will show op from\n the time it is scheduled to the end of the scheduling. Notice by the end\n of its scheduling its async kernels may not start yet. It is shown using\n the default value from step_stats. \"gpu\" will show op with the execution\n time of its kernels on GPU. \"all\" will show op from the start of its\n scheduling to the end of its last kernel.", "source": "github_repos"} +{"code": "def get_attribute(self, node, obj, name, valself=None):\n obj = abstract_utils.unwrap_final(obj)\n special_attribute = obj.get_special_attribute(node, name, valself)\n if special_attribute is not None:\n return (node, special_attribute)\n if isinstance(obj, abstract.Function):\n if name == '__get__':\n return (node, None)\n else:\n return self._get_instance_attribute(node, obj, name, valself)\n elif isinstance(obj, abstract.ParameterizedClass):\n return self.get_attribute(node, obj.base_cls, name, valself)\n elif isinstance(obj, abstract.Class):\n return self._get_class_attribute(node, obj, name, valself)\n elif isinstance(obj, overlay.Overlay):\n return self._get_module_attribute(node, obj.get_module(name), name, valself)\n elif isinstance(obj, abstract.Module):\n return self._get_module_attribute(node, obj, name, valself)\n elif isinstance(obj, abstract.SimpleValue):\n return self._get_instance_attribute(node, obj, name, valself)\n elif isinstance(obj, abstract.Union):\n if name == '__getitem__':\n return (node, self.ctx.new_unsolvable(node))\n nodes = []\n ret = self.ctx.program.NewVariable()\n for o in obj.options:\n node2, attr = self.get_attribute(node, o, name, valself)\n if attr is not None:\n ret.PasteVariable(attr, node2)\n nodes.append(node2)\n if ret.bindings:\n return (self.ctx.join_cfg_nodes(nodes), ret)\n else:\n return (node, None)\n elif isinstance(obj, special_builtins.SuperInstance):\n return self._get_attribute_from_super_instance(node, obj, name, valself)\n elif isinstance(obj, special_builtins.Super):\n return self.get_attribute(node, self.ctx.convert.super_type, name, valself)\n elif isinstance(obj, (abstract.StaticMethod, abstract.ClassMethod)):\n return self.get_attribute(node, obj.method, name, valself)\n elif isinstance(obj, abstract.BoundFunction):\n return self.get_attribute(node, obj.underlying, name, valself)\n elif isinstance(obj, abstract.TypeParameterInstance):\n param_var = obj.instance.get_instance_type_parameter(obj.name)\n if not param_var.bindings:\n param_var = obj.param.instantiate(self.ctx.root_node)\n results = []\n nodes = []\n for b in param_var.bindings:\n if b.data == obj:\n continue\n node2, ret = self.get_attribute(node, b.data, name, valself)\n if ret is None:\n if b.IsVisible(node):\n return (node, None)\n else:\n results.append(ret)\n nodes.append(node2)\n if nodes:\n node = self.ctx.join_cfg_nodes(nodes)\n return (node, self.ctx.join_variables(node, results))\n else:\n return (node, self.ctx.new_unsolvable(node))\n elif isinstance(obj, abstract.Empty):\n return (node, None)\n elif isinstance(obj, abstract.ParamSpec):\n if name == 'args':\n return (node, abstract.ParamSpecArgs(obj, self.ctx).to_variable(node))\n elif name == 'kwargs':\n return (node, abstract.ParamSpecKwargs(obj, self.ctx).to_variable(node))\n else:\n return (node, None)\n else:\n return (node, None)", "docstring": "Get the named attribute from the given object.\n\nArgs:\n node: The current CFG node.\n obj: The object.\n name: The name of the attribute to retrieve.\n valself: A cfg.Binding to a self reference to include in the attribute's\n origins. If obj is an abstract.Class, valself can be a binding to:\n * an instance of obj - obj will be treated strictly as a class.\n * obj itself - obj will be treated as an instance of its metaclass.\n * None - if name == \"__getitem__\", obj is a type annotation; else, obj\n is strictly a class, but the attribute is left unbound.\n Else, valself is optional and should be a binding to obj when given.\n\nReturns:\n A tuple (CFGNode, cfg.Variable). If this attribute doesn't exist,\n the Variable will be None.", "source": "github_repos"} +{"code": "def is_variable_initialized(ref, name=None):\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.is_variable_initialized(ref=ref, name=name)\n return ref.is_initialized(name=name)", "docstring": "Checks whether a tensor has been initialized.\n\n Outputs boolean scalar indicating whether the tensor has been initialized.\n\nArgs:\n ref: A mutable `Tensor`.\n Should be from a `Variable` node. May be uninitialized.\n name: A name for the operation (optional).\n\nReturns:\n A `Tensor` of type `bool`.", "source": "github_repos"} +{"code": "def _EmitLineUnformatted(state):\n while state.next_token:\n previous_token = state.next_token.previous_token\n previous_lineno = previous_token.lineno\n if previous_token.is_multiline_string or previous_token.is_string:\n previous_lineno += previous_token.value.count('\\n')\n if previous_token.is_continuation:\n newline = False\n else:\n newline = state.next_token.lineno > previous_lineno\n state.AddTokenToState(newline=newline, dry_run=False)", "docstring": "Emit the line without formatting.\n\n The line contains code that if reformatted would break a non-syntactic\n convention. E.g., i18n comments and function calls are tightly bound by\n convention. Instead, we calculate when / if a newline should occur and honor\n that. But otherwise the code emitted will be the same as the original code.\n\nArgs:\n state: (format_decision_state.FormatDecisionState) The format decision\n state.", "source": "github_repos"} +{"code": "def freeze_graph(session, outputs):\n return convert_to_constants.convert_variables_to_constants(session, session.graph.as_graph_def(), [x.op.name for x in outputs])", "docstring": "Freeze the current graph.\n\nArgs:\n session: Tensorflow sessions containing the graph\n outputs: List of output tensors\n\nReturns:\n The frozen graph_def.", "source": "github_repos"} +{"code": "def sequence_ids(self, batch_index: int=0) -> List[Optional[int]]:\n if not self._encodings:\n raise ValueError('sequence_ids() is not available when using non-fast tokenizers (e.g. instance of a `XxxTokenizerFast` class).')\n return self._encodings[batch_index].sequence_ids", "docstring": "Return a list mapping the tokens to the id of their original sentences:\n\n - `None` for special tokens added around or between sequences,\n - `0` for tokens corresponding to words in the first sequence,\n - `1` for tokens corresponding to words in the second sequence when a pair of sequences was jointly\n encoded.\n\nArgs:\n batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.\n\nReturns:\n `List[Optional[int]]`: A list indicating the sequence id corresponding to each token. Special tokens added\n by the tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding\n sequence.", "source": "github_repos"} +{"code": "def sparse_reduce_sum_sparse(sp_input, axis=None, keepdims=None, reduction_axes=None, keep_dims=None):\n keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, 'keep_dims', keep_dims)\n axis = deprecation.deprecated_argument_lookup('axis', axis, 'reduction_axes', reduction_axes)\n if keepdims is None:\n keepdims = False\n output_ind, output_val, output_shape = gen_sparse_ops.sparse_reduce_sum_sparse(sp_input.indices, sp_input.values, sp_input.dense_shape, math_ops._ReductionDims(sp_input, axis), keepdims)\n return sparse_tensor.SparseTensor(output_ind, output_val, output_shape)", "docstring": "Computes the sum of elements across dimensions of a SparseTensor.\n\n This Op takes a SparseTensor and is the sparse counterpart to\n `tf.reduce_sum()`. In contrast to SparseReduceSum, this Op returns a\n SparseTensor.\n\n Note: A gradient is not defined for this function, so it can't be used\n in training models that need gradient descent.\n\n Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in\n `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained\n with length 1.\n\n If `reduction_axes` has no entries, all dimensions are reduced, and a tensor\n with a single element is returned. Additionally, the axes can be negative,\n which are interpreted according to the indexing rules in Python.\n\nArgs:\n sp_input: The SparseTensor to reduce. Should have numeric type.\n axis: The dimensions to reduce; list or scalar. If `None` (the\n default), reduces all dimensions.\n keepdims: If true, retain reduced dimensions with length 1.\n reduction_axes: Deprecated name of axis.\n keep_dims: Deprecated alias for `keepdims`.\n\nReturns:\n The reduced SparseTensor.", "source": "github_repos"} +{"code": "def row_starts(self):\n return self._row_splits[:-1]", "docstring": "Returns the start indices for rows in this row partition.\n\n These indices specify where the values for each row begin.\n `partition.row_starts()` is equal to `partition.row_splits()[:-1]`.\n\nReturns:\n A 1-D integer Tensor with shape `[self.nrows()]`.\n The returned tensor is nonnegative, and is sorted in ascending order.\n `self.row_starts()[0] == 0`.\n `self.row_starts()[-1] <= self.nvals()`.", "source": "github_repos"} +{"code": "def __init__(self, matcher, focal_alpha, losses):\n nn.Module.__init__(self)\n self.matcher = matcher\n self.focal_alpha = focal_alpha\n self.losses = losses", "docstring": "This class computes the losses for `GroundingDinoForObjectDetection`. The process happens in two steps: 1) we\n compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of\n matched ground-truth / prediction (supervise class and box).\n\nArgs:\n matcher (`GroundingDinoHungarianMatcher`):\n Module able to compute a matching between targets and proposals.\n focal_alpha (`float`):\n Alpha parameter in focal loss.\n losses (`List[str]`):\n List of all the losses to be applied. See `get_loss` for a list of all available losses.", "source": "github_repos"} +{"code": "def kl_divergence(y_true, y_pred):\n y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n y_true = backend.clip(y_true, backend.epsilon(), 1)\n y_pred = backend.clip(y_pred, backend.epsilon(), 1)\n return math_ops.reduce_sum(y_true * math_ops.log(y_true / y_pred), axis=-1)", "docstring": "Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.\n\n `loss = y_true * log(y_true / y_pred)`\n\n See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence\n\n Standalone usage:\n\n >>> y_true = np.random.randint(0, 2, size=(2, 3)).astype(np.float64)\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.kullback_leibler_divergence(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> y_true = tf.keras.backend.clip(y_true, 1e-7, 1)\n >>> y_pred = tf.keras.backend.clip(y_pred, 1e-7, 1)\n >>> assert np.array_equal(\n ... loss.numpy(), np.sum(y_true * np.log(y_true / y_pred), axis=-1))\n\nArgs:\n y_true: Tensor of true targets.\n y_pred: Tensor of predicted targets.\n\nReturns:\n A `Tensor` with loss.\n\nRaises:\n TypeError: If `y_true` cannot be cast to the `y_pred.dtype`.", "source": "github_repos"} +{"code": "def _shard_counts(layout: layout_lib.Layout, batch_dim: Optional[str]=None) -> List[int]:\n shard_counts = []\n for spec in layout.sharding_specs:\n if spec in (batch_dim, layout_lib.UNSHARDED):\n shard_counts.append(1)\n else:\n shard_counts.append(layout.mesh.dim_size(spec))\n return shard_counts", "docstring": "Computes a list of the number of shards in each dimension of the layout.\n\n The shard counts are used to slice each dataset element. The batch dimension's\n count is overridden to 1 since we only consider how many shards to make\n locally (within each local replica). Sharding across clients is handled by\n either tf.data.Dataset's shard transformation (in the single-client case) or\n tf.data service's distribute function (in the multi-client case).\n\nArgs:\n layout: the layout to compute the shard counts for.\n batch_dim: the name of the batch dimension of the layout, if present.\n\nReturns:\n A list of shard counts, one element per dimension of the layout.", "source": "github_repos"} +{"code": "def start(self):\n self._server.start()", "docstring": "Starts this server.\n\n >>> dispatcher = tf.data.experimental.service.DispatchServer(start=False)\n >>> dispatcher.start()\n\nRaises:\n tf.errors.OpError: Or one of its subclasses if an error occurs while\n starting the server.", "source": "github_repos"} +{"code": "def request(self, body: dict) -> dict:\n if 'relativeTimeRange' in body:\n if body['relativeTimeRange'] == 'TODAY':\n body['timeRange'] = {'startDate': self.config.date, 'endDate': self.config.date}\n elif body['relativeTimeRange'] == 'YESTERDAY':\n body['timeRange'] = {'startDate': self.config.date - timedelta(days=1), 'endDate': self.config.date - timedelta(days=1)}\n elif body['relativeTimeRange'] == 'LAST_7_DAYS':\n body['timeRange'] = {'startDate': self.config.date - timedelta(days=6), 'endDate': self.config.date}\n elif body['relativeTimeRange'] == 'LAST_14_DAYS':\n body['timeRange'] = {'startDate': self.config.date - timedelta(days=13), 'endDate': self.config.date}\n elif body['relativeTimeRange'] == 'LAST_30_DAYS':\n body['timeRange'] = {'startDate': self.config.date - timedelta(days=29), 'endDate': self.config.date}\n elif body['relativeTimeRange'] == 'LAST_60_DAYS':\n body['timeRange'] = {'startDate': self.config.date - timedelta(days=59), 'endDate': self.config.date}\n elif body['relativeTimeRange'] == 'LAST_90_DAYS':\n body['timeRange'] = {'startDate': self.config.date - timedelta(days=89), 'endDate': self.config.date}\n elif body['relativeTimeRange'] == 'LAST_365_DAYS':\n body['timeRange'] = {'startDate': self.config.date - timedelta(days=364), 'endDate': self.config.date}\n elif body['relativeTimeRange'] == 'LAST_24_MONTHS':\n body['timeRange'] = {'startDate': self.config.date - timedelta(days=729), 'endDate': self.config.date}\n del body['relativeTimeRange']\n self.reportId = API_SearchAds(self.config, self.auth).reports().request(body=body).execute()['id']\n return self.reportId", "docstring": "Create a new SA360 report and return its JSON definition.\n\n If report is missing, date it will be added.\n Also added relativeTimeRange pattern from CM/DV reporting. If present, timeRange will be created.\n\nArgs:\n body - required, the JSON definition of a report: https://developers.google.com/search-ads/v2/reference/reports\n\nReturns:\n A dictionary defining the newly created report and status.", "source": "github_repos"} +{"code": "def build_linear_positions(index_dims, output_range=(-1.0, 1.0)):\n\n def _linspace(n_xels_per_dim):\n return torch.linspace(start=output_range[0], end=output_range[1], steps=n_xels_per_dim, dtype=torch.float32)\n dim_ranges = [_linspace(n_xels_per_dim) for n_xels_per_dim in index_dims]\n array_index_grid = meshgrid(*dim_ranges, indexing='ij')\n return torch.stack(array_index_grid, dim=-1)", "docstring": "Generate an array of position indices for an N-D input array.\n\nArgs:\n index_dims (`List[int]`):\n The shape of the index dimensions of the input array.\n output_range (`Tuple[float]`, *optional*, defaults to `(-1.0, 1.0)`):\n The min and max values taken by each input index dimension.\n\nReturns:\n `torch.FloatTensor` of shape `(index_dims[0], index_dims[1], .., index_dims[-1], N)`.", "source": "github_repos"} +{"code": "def __init__(self, name=None, reduction='sum_over_batch_size', dtype=None):\n self.name = name or auto_name(self.__class__.__name__)\n self.reduction = standardize_reduction(reduction)\n self._dtype_policy = dtype_policies.get(dtype or backend.floatx())\n self._dtype = self._dtype_policy.compute_dtype", "docstring": "Loss base class.\n\n This is the class to subclass in order to create new custom losses.\n\nArgs:\n reduction: Type of reduction to apply to the loss. In almost all cases\n this should be `\"sum_over_batch_size\"`. Supported options are\n `\"sum\"`, `\"sum_over_batch_size\"`, `\"mean\"`,\n `\"mean_with_sample_weight\"` or `None`. `\"sum\"` sums the loss,\n `\"sum_over_batch_size\"` and `\"mean\"` sum the loss and divide by the\n sample size, and `\"mean_with_sample_weight\"` sums the loss and\n divides by the sum of the sample weights. `\"none\"` and `None`\n perform no aggregation. Defaults to `\"sum_over_batch_size\"`.\n name: Optional name for the loss instance.\n dtype: The dtype of the loss's computations. Defaults to `None`, which\n means using `keras.backend.floatx()`. `keras.backend.floatx()` is a\n `\"float32\"` unless set to different value\n (via `keras.backend.set_floatx()`). If a `keras.DTypePolicy` is\n provided, then the `compute_dtype` will be utilized.\n\n To be implemented by subclasses:\n\n * `call()`: Contains the logic for loss calculation using `y_true`,\n `y_pred`.\n\n Example subclass implementation:\n\n ```python\n class MeanSquaredError(Loss):\n def call(self, y_true, y_pred):\n return ops.mean(ops.square(y_pred - y_true), axis=-1)\n ```", "source": "github_repos"} +{"code": "def recipe_email_cm_to_bigquery(config, auth_read, email, subject, dataset, table, is_incremental_load):\n email(config, {'auth': auth_read, 'read': {'from': 'noreply-cm@google.com', 'to': email, 'subject': subject, 'attachment': '.*'}, 'write': {'bigquery': {'dataset': dataset, 'table': table, 'header': True, 'is_incremental_load': is_incremental_load}}})", "docstring": "Pulls a CM Report from a gMail powered email account into BigQuery.\n\nArgs:\n auth_read (authentication) - Credentials used for reading data.\n email (string) - Email address report was sent to.\n subject (string) - Regular expression to match subject. Double escape backslashes.\n dataset (string) - Existing dataset in BigQuery.\n table (string) - Name of table to be written to.\n is_incremental_load (boolean) - Append report data to table based on date column, de-duplicates.", "source": "github_repos"} +{"code": "def _is_statically_shaped(element_spec):\n for spec in nest.flatten(element_spec):\n if isinstance(spec, (sparse_tensor.SparseTensorSpec, ragged_tensor.RaggedTensorSpec)):\n if spec.shape.rank > 0 and spec.shape.as_list()[0] is None:\n return False\n else:\n for component in spec._flat_tensor_specs:\n if not component.shape.is_fully_defined():\n return False\n return True", "docstring": "Test if an iterator output is statically shaped.\n\n For sparse and ragged tensors this only tests the batch dimension.\n\nArgs:\n element_spec: a nest structure of `tf.TypeSpec`. The element spec of the\n dataset of the iterator.\n\nReturns:\n True if the shape is static, false otherwise.", "source": "github_repos"} +{"code": "def generate(self, pixel_values: torch.FloatTensor, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.LongTensor]=None, interpolate_pos_encoding: bool=False, **generate_kwargs) -> torch.LongTensor:\n batch_size = pixel_values.shape[0]\n vision_outputs = self.vision_model(pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)\n image_embeds = vision_outputs[0]\n image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)\n if isinstance(input_ids, list):\n input_ids = torch.LongTensor(input_ids)\n elif input_ids is None:\n input_ids = torch.LongTensor([[self.decoder_input_ids, self.config.text_config.eos_token_id]]).repeat(batch_size, 1).to(image_embeds.device)\n input_ids[:, 0] = self.config.text_config.bos_token_id\n attention_mask = attention_mask[:, :-1] if attention_mask is not None else None\n outputs = self.text_decoder.generate(input_ids=input_ids[:, :-1], eos_token_id=self.config.text_config.sep_token_id, pad_token_id=self.config.text_config.pad_token_id, attention_mask=attention_mask, encoder_hidden_states=image_embeds, encoder_attention_mask=image_attention_mask, **generate_kwargs)\n return outputs", "docstring": "Overrides *generate* function to be able to use the model as a conditional generator\n\n Parameters:\n pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:\n Input image to be processed\n input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):\n The sequence used as a prompt for the generation.\n attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\nExample:\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, BlipForConditionalGeneration\n\n >>> model = BlipForConditionalGeneration.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n >>> processor = AutoProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> inputs = processor(images=image, return_tensors=\"pt\")\n\n >>> outputs = model.generate(**inputs)\n >>> print(processor.decode(outputs[0], skip_special_tokens=True))\n two cats sleeping on a couch\n ```", "source": "github_repos"} +{"code": "def forward(self, input_ids: torch.Tensor, cache_position: torch.Tensor) -> torch.Tensor:\n batch_size = input_ids.shape[0]\n position_ids = cache_position.unsqueeze(0).expand(batch_size, -1)\n outputs = self.model(input_ids=input_ids, attention_mask=None, position_ids=position_ids, past_key_values=self.cache, use_cache=True, cache_position=cache_position)\n return outputs.logits", "docstring": "Forward pass of the module, which is compatible with the ExecuTorch llm runner.\n\nArgs:\n input_ids (`torch.Tensor`): Tensor representing current input token id to the module.\n cache_position (`torch.Tensor`): Tensor representing current input position in the cache.\n\nReturns:\n torch.Tensor: Logits output from the model.", "source": "github_repos"} +{"code": "def session(self, graph=None, config=None, target=None):\n config = self._create_config(config)\n if target is None:\n target = self._default_target\n with session.Session(graph=graph, config=config, target=target) as sess:\n yield sess", "docstring": "Create a test session with master target set to the testing cluster.\n\n Creates a test session that connects to the local testing cluster.\n\nArgs:\n graph: Optional graph to use during the returned session.\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n target: the target of session to connect to.\n\nYields:\n A Session object that should be used as a context manager to surround\n the graph building and execution code in a test case.", "source": "github_repos"} +{"code": "def convert_variables_to_constants_v2(func, lower_control_flow=True, aggressive_inlining=False):\n converter_data = _FunctionConverterDataInEager(func=func, lower_control_flow=lower_control_flow, aggressive_inlining=aggressive_inlining)\n output_graph_def, converted_input_indices = _replace_variables_by_constants(converter_data=converter_data)\n return _construct_concrete_function(func, output_graph_def, converted_input_indices)", "docstring": "Replaces all the variables in a graph with constants of the same values.\n\n TensorFlow 2.0 function for converting all Variable ops into Const ops holding\n the same values. This makes it possible to describe the network fully with a\n single GraphDef file, and allows the removal of a lot of ops related to\n loading and saving the variables. This function runs Grappler's function\n inlining optimization in order to return a single subgraph.\n\n The current implementation only works for graphs that do not contain any\n control flow or embedding related ops.\n\nArgs:\n func: ConcreteFunction.\n lower_control_flow: Boolean indicating whether or not to lower control flow\n ops such as If and While. (default True)\n aggressive_inlining: Boolean indicating whether or not to do aggressive\n function inlining (might be unsafe if function has stateful ops, not\n properly connected to control outputs). (default False)\n\nReturns:\n ConcreteFunction containing a simplified version of the original.", "source": "github_repos"} +{"code": "def convert_ids_to_tokens(self, ids: Union[int, list[int]], skip_special_tokens: bool=False) -> Union[str, list[str]]:\n if isinstance(ids, int):\n return self._tokenizer.id_to_token(ids)\n tokens = []\n ids_to_skip = set(self.all_special_ids) if skip_special_tokens else set()\n for index in ids:\n index = int(index)\n if index in ids_to_skip:\n continue\n tokens.append(self._tokenizer.id_to_token(index))\n return tokens", "docstring": "Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and\n added tokens.\n\nArgs:\n ids (`int` or `List[int]`):\n The token id (or token ids) to convert to tokens.\n skip_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not to remove special tokens in the decoding.\n\nReturns:\n `str` or `List[str]`: The decoded token(s).", "source": "github_repos"} +{"code": "def _create_variables_and_slots(self) -> Dict[Text, Dict[Text, tf_variables.Variable]]:\n variables = {}\n for table in self._table_config:\n variables[table.name] = self._create_variables(table, trainable=True)\n return variables", "docstring": "Create variables for TPU embeddings.\n\n Note that this will always ensure that the variable is created under the\n TPUStrategy.\n\nReturns:\n A dict of dicts. The outer dict is keyed by the table names and the inner\n dicts are keyed by 'parameters' and the slot variable names.", "source": "github_repos"} +{"code": "def __init__(self, qualifier, args, func_set=None):\n Value.__init__(self, None)\n self.qualifier = qualifier\n self.qual_type = qualifier.qual_type\n self.args = args\n self.func_set = func_set", "docstring": "Resolved value from a QualifierValue.\n\n This is resolved instance of a QualifierValue; it is used directly by the\n test driver to validate and generate field values. This class accepts a\n list of resolved arguments which can be python primitives, STL local\n variables, or runnable STL functions.\n\nAttributes:\n qualifier: qualifier.Qualifier instance.\n qual_type: The field type to be qualified (int, bool, string, message).\n args: List of concrete arguments to be run in\n self.qualifier.Validate()/Generate().\n func_set: Output FuncSet for this qualifier. Qualifiers can be used to\n assign values to local variables in a Transition or to fields in a\n Role via func_set.", "source": "github_repos"} +{"code": "def configure_tests(tests, test_run_id):\n print('UPDATE CONFIG')\n os.makedirs(HARNESS_DIRECTORY, exist_ok=True)\n for filename, script in tests:\n script_fields = json_get_fields(script)\n script_name = filename.split('.')[0]\n harness_fields = {}\n harness_path = HARNESS_DIRECTORY + script_name + '.json'\n if os.path.exists(harness_path):\n with open(harness_path, 'r') as f:\n harness_fields = json.load(f)\n new_fields = {}\n for field in script_fields:\n if field['name'] == 'test_run_id':\n new_fields['test_run_id'] = test_run_id\n else:\n new_fields[field['name']] = harness_fields.get(field['name'], field.get('default'))\n new_fields['%s_description' % field['name']] = '(%s) %s' % (field.get('kind', 'string'), field.get('description', 'No description.'))\n if field['name'] not in harness_fields:\n print('NEW FIELD ADDED', script_name, field['name'])\n if new_fields:\n with open(harness_path, 'w') as f:\n json.dump(new_fields, f, indent=2)\n elif os.path.exists(harness_path):\n os.remove(harness_path)\n print('')\n print('------')\n print('------------')\n print('------------------------')\n print('Some tests require custom values. Update the necessary fields for the tests you wish to run.')\n print('EDIT: ' + HARNESS_DIRECTORY)\n print('------------------------')\n print('Some tests require external assets. Join the following group to gain access.')\n print('VISIT: https://groups.google.com/forum/#!forum/starthinker-assets')\n print('------------------------')\n print('------------')\n print('------')\n print('')\n sleep(3)", "docstring": "Initialize the starthinker_assets/tests.json variable harness.\n\n Read all existing tests from tests/*.json and create a harness file in\n starthinker_assets/tests/*.json so developer can configure tests.\n\nArgs:\n test: List of (filename, json) pairs containing all the tests.\n\nReturns:\n None", "source": "github_repos"} +{"code": "def make_pool3d_tests(pool_op):\n\n def f(options, expected_tf_failures=0):\n \"\"\"Actual function that generates examples.\n\n Args:\n options: An Options instance.\n expected_tf_failures: number of expected tensorflow failures.\n \"\"\"\n test_parameters = [{'ksize': [[1, 1, 1, 1, 1], [1, 2, 2, 2, 1], [1, 2, 3, 4, 1]], 'strides': [[1, 1, 1, 1, 1], [1, 2, 1, 2, 1], [1, 2, 2, 4, 1]], 'input_shape': [[1, 1, 1, 1, 1], [1, 16, 15, 14, 1], [3, 16, 15, 14, 3]], 'padding': ['SAME', 'VALID'], 'data_format': ['NDHWC']}]\n\n def build_graph(parameters):\n input_tensor = tf.compat.v1.placeholder(dtype=tf.float32, name='input', shape=parameters['input_shape'])\n out = pool_op(input_tensor, ksize=parameters['ksize'], strides=parameters['strides'], data_format=parameters['data_format'], padding=parameters['padding'])\n return ([input_tensor], [out])\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(tf.float32, parameters['input_shape'])\n return ([input_values], sess.run(outputs, feed_dict=dict(zip(inputs, [input_values]))))\n extra_convert_options = ExtraConvertOptions()\n extra_convert_options.allow_custom_ops = True\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs, extra_convert_options, expected_tf_failures=expected_tf_failures)\n return f", "docstring": "Make a set of tests to do pooling.\n\nArgs:\n pool_op: TensorFlow pooling operation to test i.e. `tf.nn.max_pool3d`.\n\nReturns:\n A function representing the true generator (after curried pool_op).", "source": "github_repos"} +{"code": "def builder(structdef_url: str, fhir_context: context.FhirPathContext) -> expressions.Builder:\n structdef = fhir_context.get_structure_definition(structdef_url)\n struct_type = _fhir_path_data_types.StructureDataType.from_proto(structdef)\n return expressions.Builder(_evaluation.RootMessageNode(fhir_context, struct_type), _PRIMITIVE_HANDLER)", "docstring": "Returns a FHIRPath expression builder.\n\n This gives the caller tab suggestions and early error detection when\n building FHIRPath expressions. See the documentation on the returned\n expressions.Builder for more details.\n\nArgs:\n structdef_url: the URL of the FHIR StructureDefinition to use.\n fhir_context: a DefinitionLoader used to load FHIR structure definitions and\n dependencies.\n Returns: a builder object to creae FHIRPath expressions.", "source": "github_repos"} +{"code": "def index_of(self, file_path, function_name, function_start_line):\n function_key = (file_path, function_name, function_start_line)\n if function_key in self._function_key_to_function:\n return self._function_key_to_function[function_key].id\n else:\n function_index = len(self._function_key_to_function) + 1\n function = profile_pb2.Function()\n function.id = function_index\n function.name = self._string_table.index_of(function_name)\n function.filename = self._string_table.index_of(file_path)\n function.start_line = function_start_line\n self._function_key_to_function[function_key] = function\n return function_index", "docstring": "Returns index of the function, adding the function if needed.\n\nArgs:\n file_path: (string) Path to file where the function is defined.\n function_name: (string) Function name.\n function_start_line: (integer) Start line number of function definition.\n\nReturns:\n Function index.", "source": "github_repos"} +{"code": "def bind_object(self, trackable):\n checkpoint = self.checkpoint\n checkpoint.all_python_objects.add(trackable)\n current_assignment = checkpoint.object_by_proto_id.get(self._proto_id, None)\n checkpoint.matched_proto_ids.add(self._proto_id)\n if current_assignment is None:\n checkpoint.object_by_proto_id[self._proto_id] = trackable\n return True\n else:\n if current_assignment is not trackable:\n logging.warning(f'Inconsistent references when loading the checkpoint into this object graph. For example, in the saved checkpoint object, `model.layer.weight` and `model.layer_copy.weight` reference the same variable, while in the current object these are two different variables. The referenced variables are:({current_assignment} and {trackable}).')\n return False", "docstring": "Set a checkpoint<->object correspondence.\n\nArgs:\n trackable: The object to record a correspondence for.\n\nReturns:\n True if this is a new assignment, False if this object has already been\n mapped to a checkpointed `Object` proto.\n\nRaises:\n AssertionError: If another object is already bound to the `Object` proto.", "source": "github_repos"} +{"code": "def compute_pooling_output_shape(input_shape, pool_size, strides, padding='valid', data_format='channels_last'):\n strides = pool_size if strides is None else strides\n input_shape_origin = list(input_shape)\n input_shape = np.array(input_shape)\n if data_format == 'channels_last':\n spatial_shape = input_shape[1:-1]\n else:\n spatial_shape = input_shape[2:]\n none_dims = []\n for i in range(len(spatial_shape)):\n if spatial_shape[i] is None:\n spatial_shape[i] = -1\n none_dims.append(i)\n pool_size = np.array(pool_size)\n if padding == 'valid':\n output_spatial_shape = np.floor((spatial_shape - pool_size) / strides) + 1\n for i in range(len(output_spatial_shape)):\n if i not in none_dims and output_spatial_shape[i] < 0:\n raise ValueError(f'Computed output size would be negative. Received: `inputs.shape={input_shape}` and `pool_size={pool_size}`.')\n elif padding == 'same':\n output_spatial_shape = np.floor((spatial_shape - 1) / strides) + 1\n else:\n raise ValueError(f\"Argument `padding` must be either 'valid' or 'same'. Received: padding={padding}\")\n output_spatial_shape = [int(i) for i in output_spatial_shape]\n for i in none_dims:\n output_spatial_shape[i] = None\n output_spatial_shape = tuple(output_spatial_shape)\n if data_format == 'channels_last':\n output_shape = (input_shape_origin[0],) + output_spatial_shape + (input_shape_origin[-1],)\n else:\n output_shape = (input_shape_origin[0], input_shape_origin[1]) + output_spatial_shape\n return output_shape", "docstring": "Computes the output shape of pooling operations.\n\nArgs:\n input_shape: Input shape. Must be a tuple of integers.\n pool_size: Size of the pooling operation. Must be a tuple of integers.\n strides: Stride of the pooling operation. Must be a tuple of integers.\n Defaults to `pool_size`.\n padding: Padding method. Available methods are `\"valid\"` or `\"same\"`.\n Defaults to `\"valid\"`.\n data_format: String, either `\"channels_last\"` or `\"channels_first\"`.\n The ordering of the dimensions in the inputs. `\"channels_last\"`\n corresponds to inputs with shape `(batch, height, width, channels)`\n while `\"channels_first\"` corresponds to inputs with shape\n `(batch, channels, height, weight)`. Defaults to `\"channels_last\"`.\n\nReturns:\n Tuple of ints: The output shape of the pooling operation.\n\nExample:\n # Basic usage with square pooling on a single image\n >>> compute_pooling_output_shape((1, 4, 4, 1), (2, 2))\n (1, 2, 2, 1)\n\n # Strided pooling on a single image with strides different from pool_size\n >>> compute_pooling_output_shape((1, 4, 4, 1), (2, 2), strides=(1, 1))\n (1, 3, 3, 1)\n\n # Pooling on a batch of images\n >>> compute_pooling_output_shape((32, 4, 4, 3), (2, 2))\n (32, 2, 2, 3)", "source": "github_repos"} +{"code": "def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader:\n return self._get_dataloader(dataset=test_dataset, description='test', batch_size=self.args.eval_batch_size, sampler_fn=self._get_eval_sampler)", "docstring": "Returns the test [`~torch.utils.data.DataLoader`].\n\n Subclass and override this method if you want to inject some custom behavior.\n\nArgs:\n test_dataset (`torch.utils.data.Dataset`, *optional*):\n The test dataset to use. If it is a [`~datasets.Dataset`], columns not accepted by the\n `model.forward()` method are automatically removed. It must implement `__len__`.", "source": "github_repos"} +{"code": "def apply_sync(fn: StreamFn, content: Iterable[_T]) -> list[_T]:\n\n async def run_with_context():\n async with context.context():\n as_async = streams.stream_content(content)\n return await streams.gather_stream(fn(as_async))\n return asyncio.run(run_with_context())", "docstring": "Applies a part function synchronously.\n\nArgs:\n fn: the part function to apply to the content.\n content: a collection of inputs/parts on which to apply the function.\n\nReturns:\n the content, with the function `fn` applied to each input/part.", "source": "github_repos"} +{"code": "def scalar_spec(value_spec: pg.typing.ValueSpec) -> pg.typing.ValueSpec:\n return pg.typing.Union([value_spec, pg.typing.Callable([pg.typing.Int()], returns=value_spec)])", "docstring": "Returns the value spec for a schedule scalar.\n\nArgs:\n value_spec: a value spec for the schedule-based scalar type.\n\nReturns:\n A value spec for either the value itself or a callable that produces such\n value based on a step (integer).", "source": "github_repos"} +{"code": "def resize_position_embeddings(self, new_num_position_embeddings: int):\n self.config.max_position_embeddings = new_num_position_embeddings\n self.encoder.resize_position_embeddings(new_num_position_embeddings)\n self.decoder.resize_position_embeddings(new_num_position_embeddings)", "docstring": "Resizes position embeddings matrix of the model if `new_num_position_embeddings !=\n config.max_position_embeddings`.\n\nArgs:\n new_num_position_embeddings (`int`):\n The number of new position embeddings. If position embeddings are learned, increasing the size will add\n newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If\n position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will\n add correct vectors at the end following the position encoding algorithm, whereas reducing the size\n will remove vectors from the end.", "source": "github_repos"} +{"code": "def __init__(self, name='squared_hinge', dtype=None):\n super(SquaredHinge, self).__init__(squared_hinge, name, dtype=dtype)", "docstring": "Computes the squared hinge metric between `y_true` and `y_pred`.\n\n `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are\n provided we will convert them to -1 or 1.\n\nArgs:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n\n Standalone usage:\n\n >>> m = tf.keras.metrics.SquaredHinge()\n >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])\n >>> m.result().numpy()\n 1.86\n\n >>> m.reset_state()\n >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],\n ... sample_weight=[1, 0])\n >>> m.result().numpy()\n 1.46\n\n Usage with `compile()` API:\n\n ```python\n model.compile(\n optimizer='sgd',\n loss='mse',\n metrics=[tf.keras.metrics.SquaredHinge()])\n ```", "source": "github_repos"} +{"code": "def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:\n sep = [self.sep_token_id]\n if token_ids_1 is None:\n return len(token_ids_0 + sep) * [0]\n return len(token_ids_0 + sep + token_ids_1 + sep) * [0]", "docstring": "Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does\n not make use of token type ids, therefore a list of zeros is returned.\n\nArgs:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n\nReturns:\n `List[int]`: List of zeros.", "source": "github_repos"} +{"code": "def merge_bindings(program: cfg.Program, node: cfg.CFGNode, bindings: Sequence[cfg.Binding]) -> cfg.Variable:\n v = program.NewVariable()\n for b in bindings:\n v.PasteBinding(b, node)\n return v", "docstring": "Create a combined Variable for a list of bindings.\n\nArgs:\n program: A cfg.Program instance.\n node: The current CFG node.\n bindings: A list of cfg.Bindings.\n\nReturns:\n A cfg.Variable.", "source": "github_repos"} +{"code": "def cluster_spec(self):\n if self._tpu != 'local':\n network_endpoints = self._cloud_tpu_client.network_endpoints()\n worker_list = ['%s:%s' % (endpoint['ipAddress'], endpoint['port']) for endpoint in network_endpoints]\n cluster_spec = {self.task_type: worker_list}\n if self._coordinator_address:\n cluster_spec[self._coordinator_name] = [self._coordinator_address]\n return server_lib.ClusterSpec(cluster_spec)\n else:\n return server_lib.ClusterSpec({})", "docstring": "Returns a ClusterSpec object based on the latest TPU information.\n\n We retrieve the information from the GCE APIs every time this method is\n called.\n\nReturns:\n A ClusterSpec containing host information returned from Cloud TPUs,\n or None.\n\nRaises:\n RuntimeError: If the provided TPU is not healthy.", "source": "github_repos"} +{"code": "def _scoped_subscribe(tensor, side_effects, control_cache):\n with ops.device(tensor.device):\n with _preserve_control_flow_context(tensor):\n return _subscribe(tensor, side_effects, control_cache)", "docstring": "Helper method that subscribes a single tensor to a list of side_effects.\n\n This is a thin wrapper around `_subscribe` and ensures that the side effect\n ops are added within the same device and control flow context of the\n subscribed tensor.\n\nArgs:\n tensor: The `tf.Tensor` to be subscribed.\n side_effects: List of side_effect functions, see subscribe for details.\n control_cache: `_ControlOutputCache` helper to get control_outputs faster.\n\nReturns:\n The modified replacement to the passed in tensor which triggers the side\n effects or the given tensor, if it was already been subscribed.", "source": "github_repos"} +{"code": "def call(self, pixel_values: tf.Tensor, input_ids: tf.Tensor | None=None, attention_mask: tf.Tensor | None=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, labels: tf.Tensor | None=None, return_dict: Optional[bool]=None, training: Optional[bool]=None) -> Union[Tuple, TFBlipForConditionalGenerationModelOutput]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n vision_outputs = self.vision_model(pixel_values=pixel_values, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training)\n image_embeds = vision_outputs[0]\n outputs = self.text_decoder(input_ids=input_ids, attention_mask=attention_mask, encoder_hidden_states=image_embeds, labels=labels, return_dict=False, training=training)\n if not return_dict:\n outputs = (outputs[0], outputs[1], image_embeds, vision_outputs[0]) + vision_outputs[2:]\n return tuple((output for output in outputs if output is not None))\n if labels is not None:\n loss = outputs[0]\n logits = outputs[1]\n else:\n loss = None\n logits = outputs[0]\n if loss is not None and loss.shape.rank == 0:\n loss = tf.reshape(loss, (1,))\n return TFBlipForConditionalGenerationModelOutput(loss=loss, logits=logits, image_embeds=image_embeds, last_hidden_state=vision_outputs.last_hidden_state, hidden_states=vision_outputs.hidden_states, attentions=vision_outputs.attentions)", "docstring": "Returns:\n\nExample:\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, TFBlipForConditionalGeneration\n\n >>> processor = AutoProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n >>> model = TFBlipForConditionalGeneration.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n >>> text = \"A picture of\"\n\n >>> inputs = processor(images=image, text=text, return_tensors=\"tf\")\n\n >>> outputs = model(**inputs)\n ```", "source": "github_repos"} +{"code": "def _get_clang_major_version(path_to_clang: str) -> int:\n logging.info('Running echo __clang_major__ | %s -E -P -', path_to_clang)\n clang_version_proc = subprocess.run([path_to_clang, '-E', '-P', '-'], input='__clang_major__', check=True, capture_output=True, text=True)\n major_version = int(clang_version_proc.stdout)\n logging.info('%s reports major version %s.', path_to_clang, major_version)\n return major_version", "docstring": "Gets the major version of the clang at `path_to_clang`.\n\nArgs:\n path_to_clang: Path to a clang executable\n\nReturns:\n The major version.", "source": "github_repos"} +{"code": "def __init__(self, engine: trt.ICudaEngine):\n from cuda import cuda\n import tensorrt as trt\n self.engine = engine\n self.context = engine.create_execution_context()\n self.context_lock = threading.RLock()\n self.inputs = []\n self.outputs = []\n self.gpu_allocations = []\n self.cpu_allocations = []\n try:\n _ = np.bool\n except AttributeError:\n np.bool = np.bool_\n for i in range(self.engine.num_bindings):\n name = self.engine.get_binding_name(i)\n dtype = self.engine.get_binding_dtype(i)\n shape = self.engine.get_binding_shape(i)\n size = trt.volume(shape) * dtype.itemsize\n allocation = _assign_or_fail(cuda.cuMemAlloc(size))\n binding = {'index': i, 'name': name, 'dtype': np.dtype(trt.nptype(dtype)), 'shape': list(shape), 'allocation': allocation, 'size': size}\n self.gpu_allocations.append(allocation)\n if self.engine.binding_is_input(i):\n self.inputs.append(binding)\n else:\n self.outputs.append(binding)\n assert self.context\n assert len(self.inputs) > 0\n assert len(self.outputs) > 0\n assert len(self.gpu_allocations) > 0\n for output in self.outputs:\n self.cpu_allocations.append(np.zeros(output['shape'], output['dtype']))\n self.stream = _assign_or_fail(cuda.cuStreamCreate(0))", "docstring": "Implementation of the TensorRTEngine class which handles\n allocations associated with TensorRT engine.\n\n Example Usage::\n\n TensorRTEngine(engine)\n\nArgs:\n engine: trt.ICudaEngine object that contains TensorRT engine", "source": "github_repos"} +{"code": "def __init__(self, detector: AnomalyDetector):\n self._detector = detector", "docstring": "Applies the _ScoreAndLearnDoFn to a PCollection of data.\n\n This PTransform scores and learns from data points using an anomaly\n detection model.\n\nArgs:\n detector: The anomaly detection model to use.", "source": "github_repos"} +{"code": "def call(self, input_ids: tf.Tensor | None=None, pixel_values: tf.Tensor | None=None, attention_mask: tf.Tensor | None=None, position_ids: tf.Tensor | None=None, return_loss: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, training: Optional[bool]=None) -> Union[Tuple, TFBlipOutput]:\n outputs = self.blip(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask, position_ids=position_ids, return_loss=return_loss, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training)\n return outputs", "docstring": "Returns:\n\nExample:\n ```python\n >>> from PIL import Image\n >>> import requests\n >>> from transformers import AutoProcessor, TFBlipModel\n\n >>> model = TFBlipModel.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n >>> processor = AutoProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> inputs = processor(\n ... text=[\"a photo of a cat\", \"a photo of a dog\"], images=image, return_tensors=\"tf\", padding=True\n ... )\n\n >>> outputs = model(**inputs)\n >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score\n >>> probs = tf.nn.softmax(logits_per_image, axis=1) # we can take the softmax to get the label probabilities\n ```", "source": "github_repos"} +{"code": "def _tf_glue_convert_examples_to_features(examples: tf.data.Dataset, tokenizer: PreTrainedTokenizer, task=str, max_length: Optional[int]=None) -> tf.data.Dataset:\n processor = glue_processors[task]()\n examples = [processor.tfds_map(processor.get_example_from_tensor_dict(example)) for example in examples]\n features = glue_convert_examples_to_features(examples, tokenizer, max_length=max_length, task=task)\n label_type = tf.float32 if task == 'sts-b' else tf.int64\n\n def gen():\n for ex in features:\n d = {k: v for k, v in asdict(ex).items() if v is not None}\n label = d.pop('label')\n yield (d, label)\n input_names = tokenizer.model_input_names\n return tf.data.Dataset.from_generator(gen, (dict.fromkeys(input_names, tf.int32), label_type), ({k: tf.TensorShape([None]) for k in input_names}, tf.TensorShape([])))", "docstring": "Returns:\n A `tf.data.Dataset` containing the task-specific features.", "source": "github_repos"} +{"code": "def create(self, url, mime_type='application/octet-stream', compression_type=CompressionTypes.AUTO) -> BinaryIO:\n _, path = self._parse_url(url)\n return self._create(path, mime_type, compression_type)", "docstring": "Returns:\n A Python File-like object.", "source": "github_repos"} +{"code": "def kaiser(x, beta):\n if any_symbolic_tensors((x,)):\n return Kaiser(beta).symbolic_call(x)\n return backend.numpy.kaiser(x, beta)", "docstring": "Kaiser window function.\n\n The Kaiser window is defined as:\n `w[n] = I0(beta * sqrt(1 - (2n / (N - 1) - 1)^2)) / I0(beta)`\n where I0 is the modified zeroth-order Bessel function of the first kind.\n\nArgs:\n x: Scalar or 1D Tensor. The window length.\n beta: Float. Shape parameter for the Kaiser window.\n\nReturns:\n A 1D tensor containing the Kaiser window values.\n\nExample:\n >>> x = keras.ops.convert_to_tensor(5)\n >>> keras.ops.kaiser(x, beta=14.0)\n array([7.7268669e-06, 1.6493219e-01, 1.0000000e+00, 1.6493219e-01,\n 7.7268669e-06], dtype=float32)", "source": "github_repos"} +{"code": "def assert_same_structure(nest1, nest2, check_types=True):\n nest_util.assert_same_structure(nest_util.Modality.DATA, nest1, nest2, check_types)", "docstring": "Asserts that two structures are nested in the same way.\n\nArgs:\n nest1: an arbitrarily nested structure.\n nest2: an arbitrarily nested structure.\n check_types: if `True` (default) types of sequences should be same as\n well. For dictionary, \"type\" of dictionary is considered to include its\n keys. In other words, two dictionaries with different keys are considered\n to have a different \"type\". If set to `False`, two iterables are\n considered same as long as they yield the elements that have same\n structures.\n\nRaises:\n ValueError: If the two structures do not have the same number of elements or\n if the two structures are not nested in the same way.\n TypeError: If the two structures differ in the type of sequence in any of\n their substructures. Only possible if `check_types` is `True`.", "source": "github_repos"} +{"code": "def _rename_if_any_arg_found_transformer(parent, node, full_name, name, logs, arg_names=None, arg_ok_predicate=None, remove_if_ok=False, message=None):\n for arg_name in arg_names:\n rename_node = _rename_if_arg_found_transformer(parent, node, full_name, name, logs, arg_name, arg_ok_predicate, remove_if_ok, message)\n node = rename_node if rename_node else node\n return node", "docstring": "Replaces the given call with tf.compat.v1 if any of the arg_names is found.\n\nArgs:\n parent: Parent of node.\n node: ast.Call node to modify.\n full_name: full name of function to modify.\n name: name of function to modify.\n logs: list of logs to append to.\n arg_names: list of names of the argument to look for.\n arg_ok_predicate: predicate callable with the ast of the argument value,\n returns whether the argument value is allowed.\n remove_if_ok: remove the argument if present and ok as determined by\n arg_ok_predicate.\n message: message to print if a non-ok arg is found (and hence, the function\n is renamed to its compat.v1 version).\n\nReturns:\n node, if it was modified, else None.", "source": "github_repos"} +{"code": "def on_predict_end(self, logs=None):", "docstring": "Called at the end of prediction.\n\n Subclasses should override for any actions to run.\n\nArgs:\n logs: Dict. Currently no data is passed to this argument for this\n method but that may change in the future.", "source": "github_repos"} +{"code": "def __init__(self, pool_size, strides, padding='valid', data_format='channels_last', name=None, **kwargs):\n if strides is None:\n raise ValueError('Argument `strides` must not be None.')\n super(AveragePooling3D, self).__init__(pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, name=name, **kwargs)", "docstring": "Average pooling layer for 3D inputs (e.g. volumes).\n\nArgs:\n pool_size: An integer or tuple/list of 3 integers:\n (pool_depth, pool_height, pool_width)\n specifying the size of the pooling window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the pooling operation.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n padding: A string. The padding method, either 'valid' or 'same'.\n Case-insensitive.\n data_format: A string. The ordering of the dimensions in the inputs.\n `channels_last` (default) and `channels_first` are supported.\n `channels_last` corresponds to inputs with shape\n `(batch, depth, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, depth, height, width)`.\n name: A string, the name of the layer.", "source": "github_repos"} +{"code": "def all_reduce(self, input_tensor: core.TensorLike, control_input: Optional[Union[core.TensorLike, ops.Operation]]=None, options: Optional[collective_util.Options]=None) -> core.Tensor:\n instance_key = self._next_instance_key()\n options = self._options.merge(options)\n ordering_token = self._get_ordering_token()\n with ops.device(self._device), self._control_input(control_input):\n return collective_ops.all_reduce_v2(input_tensor, self._group_size, self._group_key, instance_key, communication_hint=options.implementation.value, timeout=options.timeout_seconds, ordering_token=ordering_token)", "docstring": "All-reduce a dense tensor.\n\nArgs:\n input_tensor: a dense tensor. It must have the same shape on all replicas.\n control_input: if not None, add control edges between control_input and\n the all-reduce.\n options: an optional tf.distribute.experimental.CommunicationOptions. If\n provided, it overrides the default options.\n\nReturns:\n The reduced tensor.", "source": "github_repos"} +{"code": "def _name_list(tensor_list):\n return [compat.as_bytes(t.name) for t in tensor_list]", "docstring": "Utility function for transitioning to the new session API.\n\nArgs:\n tensor_list: a list of `Tensor`s.\n\nReturns:\n A list of each `Tensor`s name (as byte arrays).", "source": "github_repos"} +{"code": "def load_model(file_path: str) -> NormalizedModel:\n with open(file_path) as f:\n model = json.load(f)\n model_flat = OrderedDict()\n for category in model:\n for item in model[category]:\n model_flat['%s:%s' % (category, item)] = model[category][item]\n weights = jnp.array(list(model_flat.values()))\n weights = weights / weights.std()\n weights = weights - weights.mean()\n keys = list(model_flat.keys())\n return NormalizedModel(keys, weights)", "docstring": "Loads a model as a pair of a features list and a normalized weight vector.\n\nArgs:\n file_path: A file path for the model JSON file.\n\nReturns:\n A normalized model, which is a pair of a list of feature identifiers and a\n normalized weight vector.", "source": "github_repos"} +{"code": "def load_function_def_library(library, saved_object_graph=None, load_shared_name_suffix=None, wrapper_function=None):\n library_function_names = set((fdef.signature.name for fdef in library.function))\n functions = {}\n renamed_functions = {}\n if ops.executing_eagerly_outside_functions():\n graph = ops.Graph()\n else:\n graph = ops.get_default_graph()\n if load_shared_name_suffix is None:\n load_shared_name_suffix = '_load_{}'.format(ops.uid())\n library_gradient_names = {}\n new_gradient_op_types = {}\n gradients_to_register = {}\n for gdef in library.registered_gradients:\n if gdef.registered_op_type:\n new_op_type = custom_gradient.generate_name()\n old_op_type = compat.as_bytes(gdef.registered_op_type)\n library_gradient_names[old_op_type] = gdef.gradient_func\n new_gradient_op_types[old_op_type] = new_op_type\n gradients_to_register[gdef.gradient_func] = new_op_type\n function_deps = {}\n for fdef in library.function:\n function_deps[fdef.signature.name] = _list_function_deps(fdef, library_function_names, library_gradient_names)\n loaded_gradients = {}\n for fdef in _sort_function_defs(library, function_deps):\n orig_name = _fix_fdef_in_place(fdef, functions, load_shared_name_suffix, new_gradient_op_types)\n structured_input_signature = None\n structured_outputs = None\n if saved_object_graph is not None and orig_name in saved_object_graph.concrete_functions:\n proto = saved_object_graph.concrete_functions[orig_name]\n structured_input_signature = nested_structure_coder.decode_proto(proto.canonicalized_input_signature)\n structured_outputs = nested_structure_coder.decode_proto(proto.output_signature)\n with graph.as_default():\n func_graph = function_def_lib.function_def_to_graph(fdef, structured_input_signature=structured_input_signature, structured_outputs=structured_outputs)\n _restore_gradient_functions(func_graph, renamed_functions, loaded_gradients)\n for dep in function_deps[orig_name]:\n functions[dep].add_to_graph(func_graph)\n if '_input_shapes' in fdef.attr:\n del fdef.attr['_input_shapes']\n function_type = function_type_lib.from_structured_signature(func_graph.structured_input_signature, func_graph.structured_outputs, func_graph.function_captures.capture_types)\n func = function_lib.ConcreteFunction.from_func_graph(func_graph, function_type, attrs=fdef.attr)\n if wrapper_function:\n func = wrapper_function(func)\n func.add_to_graph(graph)\n functions[orig_name] = func\n renamed_functions[func.name] = func\n if any((op.type == 'TRTEngineOp' for op in func_graph.get_operations())):\n func.add_to_graph(ops.get_default_graph())\n if orig_name in gradients_to_register:\n gradient_op_type = gradients_to_register[orig_name]\n loaded_gradients[compat.as_bytes(gradient_op_type)] = func\n ops.RegisterGradient(gradient_op_type)(_gen_gradient_func(func))\n return functions", "docstring": "Load a set of functions as concrete functions without captured inputs.\n\n Functions names are manipulated during load such that they do not overlap\n with previously created ones.\n\n Gradients are re-registered under new names. Ops that reference the gradients\n are updated to reflect the new registered names.\n\nArgs:\n library: FunctionDefLibrary proto message.\n saved_object_graph: SavedObjectGraph proto message. If not passed in,\n concrete function structured signatures and outputs will not be set.\n load_shared_name_suffix: If specified, used to uniquify shared names.\n Otherwise, a unique name is generated.\n wrapper_function: An object that will be wrapped on newly created functions.\n\nReturns:\n Map of original function names in the library to instances of\n `ConcreteFunction` without captured inputs.\n\nRaises:\n ValueError: if functions dependencies have a cycle.", "source": "github_repos"} +{"code": "def __hash__(self) -> int:\n return self._text.__hash__()", "docstring": "Hash function.\n\n NOTE(daiyip): ConstStrKey shares the same hash with its text, which\n makes it easy to lookup a dict of string by an ConstStrKey object, and\n vice versa.\n\nReturns:\n Hash code.", "source": "github_repos"} +{"code": "def run_without_tensor_float_32(description: str) -> Callable[[Callable[..., Any]], Callable[..., None]]:\n\n def decorator(f: Callable[..., Any]) -> Callable[..., None]:\n\n @functools.wraps(f)\n def decorated(*args, **kwargs):\n allowed = config.tensor_float_32_execution_enabled()\n try:\n config.enable_tensor_float_32_execution(False)\n f(*args, **kwargs)\n finally:\n config.enable_tensor_float_32_execution(allowed)\n return tf_decorator.make_decorator(f, decorated)\n return decorator", "docstring": "Execute test with TensorFloat-32 disabled.\n\n While almost every real-world deep learning model runs fine with\n TensorFloat-32, many tests use assertAllClose or similar methods.\n TensorFloat-32 matmuls typically will cause such methods to fail with the\n default tolerances.\n\nArgs:\n description: A description used for documentation purposes, describing why\n the test requires TensorFloat-32 to be disabled.\n\nReturns:\n Decorator which runs a test with TensorFloat-32 disabled.", "source": "github_repos"} +{"code": "def compute_global_attention_representations(self, global_q, global_k, global_v, local_k, local_v, mask, dim: DimensionInfo):\n global_and_local_k = torch.cat([global_k, local_k], dim=2)\n global_and_local_v = torch.cat([global_v, local_v], dim=2)\n extended_mask = nn.functional.pad(mask, pad=(dim.global_len, 0), value=0)\n attn_weights = torch.einsum('BHGF,BHXF->BHGX', global_q, global_and_local_k)\n attn_weights = attn_weights + extended_mask[:, None, None, :]\n attn_probs = nn.functional.softmax(attn_weights, dim=-1)\n attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)\n attn_output = torch.einsum('BHGX,BHXF->BHGF', attn_probs, global_and_local_v)\n return (attn_output, attn_probs)", "docstring": "Compute attention representations for global tokens.\n\n Global tokens will attend to both global tokens as well as all input sequence tokens. Because the input\n sequence tokens are arranged in blocks for local attention, we unblock them and compute attention.\n\nArgs:\n global_q (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:\n query vectors from global tokens\n global_k (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:\n key vectors from global tokens\n global_v (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:\n value vectors from global tokens\n local_k (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:\n key vectors from local tokens\n local_v (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:\n value vectors from local tokens\n mask (`torch.FloatTensor`) of shape [batch_size, padded_seq_len]: attention mask\n dim (DimensionInfo): DimensionInfo wrapper for dimensions\n\nReturns:\n output of shape `[batch_sizes, length, features]`. where length will be padded to a multiple of block_size", "source": "github_repos"} +{"code": "def post_process_image_text_to_text(self, generated_outputs, skip_special_tokens=True, **kwargs):\n beginning_of_answer = self.tokenizer.convert_tokens_to_ids(BEGINNING_OF_ANSWER_STRING)\n unpadded_output_sequences = [seq[(seq == beginning_of_answer).nonzero(as_tuple=True)[0] + 1:] for seq in generated_outputs]\n max_len = max((len(seq) for seq in unpadded_output_sequences))\n padded_output_sequences = torch.full((len(unpadded_output_sequences), max_len), self.pad_token_id)\n for i, seq in enumerate(unpadded_output_sequences):\n padded_output_sequences[i, :len(seq)] = torch.tensor(seq)\n return self.batch_decode(padded_output_sequences, skip_special_tokens=skip_special_tokens, **kwargs)", "docstring": "Post-processes the output of `FuyuForConditionalGeneration` to only return the text output.\n\nArgs:\n generated_outputs (`torch.Tensor` or `np.ndarray`):\n The output of the model. The output is expected to be a tensor of shape `(batch_size, sequence_length)`\n containing the token ids of the generated sequences.\n skip_special_tokens (`bool`, *optional*, defaults to `True`):\n Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.\n **kwargs:\n Additional arguments to be passed to the tokenizer's `batch_decode method`.\n\nReturns:\n `List[str]`: The decoded text output.", "source": "github_repos"} +{"code": "def get_func_graphs(op):\n\n def _get_func_graph_for_branch(name_attr_list, cached_attr_name=None):\n \"\"\"Generates and returns a FuncGraph for the given branch.\"\"\"\n func_graph = None\n if cached_attr_name is not None:\n func_graph = getattr(op, cached_attr_name, None)\n inputs = op.inputs[1:]\n if func_graph is None:\n input_shapes = [t.shape for t in inputs]\n func_graph = util.get_func_graph(op, input_shapes, name_attr_list.name)\n for external_t, internal_t in zip(inputs, func_graph.inputs):\n handle_data_util.copy_handle_data(external_t, internal_t)\n func_graph.function_captures.reset_captures(inputs, func_graph.inputs)\n func_graph._forward_cond = op\n return func_graph\n if op.type in ['If', 'StatelessIf']:\n return (_get_func_graph_for_branch(op.get_attr('then_branch'), '_true_graph'), _get_func_graph_for_branch(op.get_attr('else_branch'), '_false_graph'))\n elif op.type in ['Case', 'StatelessCase']:\n return [_get_func_graph_for_branch(branch_fn, '_branch_graph_{}'.format(i)) for i, branch_fn in enumerate(op.get_attr('branches'))]\n else:\n raise ValueError('Unsupported op type: {}'.format(op.type))", "docstring": "Returns `FuncGraph`s for the input op branches.\n\nArgs:\n op: The If or Case Operation.\n\nReturns:\n A tuple of the `FuncGraph`s of the then_branch and else_branch (all branches\n for Case).", "source": "github_repos"} +{"code": "def _gen_data(m, k, n, nnz, row_occupied_rate, data_type, seed):\n random.seed(seed)\n np.random.seed(seed)\n occupied_rows = random.sample(range(m), int(m * row_occupied_rate))\n sparse_input_dense_shape = [m, k]\n dense_input_shape = (k, n)\n indices = []\n for _ in range(nnz):\n row = random.choice(occupied_rows)\n col = random.randint(0, k - 1)\n indices.append([row, col])\n\n def maybe_complex(x):\n if x.dtype.kind == 'c':\n return (x + 1j * x) / 2\n return x\n sparse_values = maybe_complex(np.random.normal(size=len(indices)).astype(data_type))\n dense_values = maybe_complex(np.random.normal(size=dense_input_shape).astype(data_type))\n sparse_input = sparse_tensor.SparseTensor(indices, sparse_values, sparse_input_dense_shape)\n dense_input = constant_op.constant(dense_values)\n return (sparse_input, dense_input)", "docstring": "Generate valid input data for tf.sparse.sparse_dense_matmul\n\n returns sparse matrix a (type SparseTensor), dense matrix b (type Tensor)\n\n Parameters:\n m: row count of dense version of matrix a / row count of output matrix\n k: col count of dense version of matrix a / row count of matrix b\n n: col could of matrix b / col count of output matrix\n nnz: number of non-zero elements in matrix a\n row_occupied_rate: prob that row in a has one or more non-zero element", "source": "github_repos"} +{"code": "def enumerate_dataset(start=0):\n\n def _apply_fn(dataset):\n return dataset.enumerate(start)\n return _apply_fn", "docstring": "A transformation that enumerates the elements of a dataset.\n\n It is similar to python's `enumerate`.\n For example:\n\n ```python\n # NOTE: The following examples use `{ ... }` to represent the\n # contents of a dataset.\n a = { 1, 2, 3 }\n b = { (7, 8), (9, 10) }\n\n # The nested structure of the `datasets` argument determines the\n # structure of elements in the resulting dataset.\n a.apply(tf.data.experimental.enumerate_dataset(start=5))\n => { (5, 1), (6, 2), (7, 3) }\n b.apply(tf.data.experimental.enumerate_dataset())\n => { (0, (7, 8)), (1, (9, 10)) }\n ```\n\nArgs:\n start: A `tf.int64` scalar `tf.Tensor`, representing the start value for\n enumeration.\n\nReturns:\n A `Dataset` transformation function, which can be passed to\n `tf.data.Dataset.apply`.", "source": "github_repos"} +{"code": "def ragged_shape(input: ragged_tensor.Ragged, name: Optional[str]=None, out_type=dtypes.int32) -> dynamic_ragged_shape.DynamicRaggedShape:\n with ops.name_scope(name, 'RaggedShape', [input]):\n return dynamic_ragged_shape.DynamicRaggedShape.from_tensor(input, out_type)", "docstring": "Returns the shape of a RaggedTensor.\n\nArgs:\n input: A `RaggedTensor`\n name: A name for the operation (optional).\n out_type: dtype used to encode the shape.\n\nReturns:\n A `tf.experimental.DynamicRaggedShape`", "source": "github_repos"} +{"code": "def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int=0) -> nn.Linear:\n index = index.to(layer.weight.device)\n W = layer.weight.index_select(dim, index).detach().clone()\n if layer.bias is not None:\n if dim == 1:\n b = layer.bias.detach().clone()\n else:\n b = layer.bias[index].detach().clone()\n new_size = list(layer.weight.size())\n new_size[dim] = len(index)\n new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None).to(layer.weight.device)\n new_layer.weight.requires_grad = False\n new_layer.weight.copy_(W.contiguous())\n new_layer.weight.requires_grad = True\n if layer.bias is not None:\n new_layer.bias.requires_grad = False\n new_layer.bias.copy_(b.contiguous())\n new_layer.bias.requires_grad = True\n return new_layer", "docstring": "Prune a linear layer to keep only entries in index.\n\n Used to remove heads.\n\nArgs:\n layer (`torch.nn.Linear`): The layer to prune.\n index (`torch.LongTensor`): The indices to keep in the layer.\n dim (`int`, *optional*, defaults to 0): The dimension on which to keep the indices.\n\nReturns:\n `torch.nn.Linear`: The pruned layer as a new layer with `requires_grad=True`.", "source": "github_repos"} +{"code": "def register_for_auto_class(cls, auto_class='AutoTokenizer'):\n if not isinstance(auto_class, str):\n auto_class = auto_class.__name__\n import transformers.models.auto as auto_module\n if not hasattr(auto_module, auto_class):\n raise ValueError(f'{auto_class} is not a valid auto class.')\n cls._auto_class = auto_class", "docstring": "Register this class with a given auto class. This should only be used for custom tokenizers as the ones in the\n library are already mapped with `AutoTokenizer`.\n\nArgs:\n auto_class (`str` or `type`, *optional*, defaults to `\"AutoTokenizer\"`):\n The auto class to register this new tokenizer with.", "source": "github_repos"} +{"code": "def _FullUpdateFromFile(self, cache, source_map, force_write=False):\n return_val = 0\n for entry in source_map:\n if not entry.Verify():\n raise error.InvalidMap('Map is not valid. Aborting')\n if len(source_map) == 0 and (not force_write):\n raise error.EmptyMap('Source map empty during full update, aborting. Use --force-write to override.')\n return_val += cache.WriteMap(map_data=source_map, force_write=force_write)\n if return_val == 0:\n mtime = os.stat(cache.GetCacheFilename()).st_mtime\n self.log.debug('Cache filename %s has mtime %d', cache.GetCacheFilename(), mtime)\n self.WriteModifyTimestamp(mtime)\n self.WriteUpdateTimestamp()\n return return_val", "docstring": "Write a new map into the provided cache (overwrites).\n\nArgs:\n cache: A nss_cache.caches.Cache object.\n source_map: The map whose contents we're replacing the cache with, that is\n used for verification.\n force_write: A boolean flag forcing empty map updates when False,\n defaults to False.\n\nReturns:\n 0 if succesful, non-zero indicating number of failures otherwise.\n\nRaises:\n EmptyMap: Update is an empty map, not raised if force_write=True.\n InvalidMap:", "source": "github_repos"} +{"code": "def __init__(self, dataset, class_weight=None, distribution=None):\n from keras.src.utils.module_utils import tensorflow as tf\n if not isinstance(dataset, (tf.data.Dataset, tf.distribute.DistributedDataset)):\n raise ValueError(f'Expected argument `dataset` to be a tf.data.Dataset. Received: {dataset}')\n if class_weight is not None:\n dataset = dataset.map(make_class_weight_map_fn(class_weight)).prefetch(tf.data.AUTOTUNE)\n if distribution is not None:\n dataset = distribution.distribute_dataset(dataset)\n self._dataset = dataset", "docstring": "Initialize the TFDatasetAdapter.\n\nArgs:\n dataset: The input `tf.data.Dataset` instance.\n class_weight: A map where the keys are integer class ids and values\n are the class weights, e.g. `{0: 0.2, 1: 0.6, 2: 0.3}`.\n distribution: A `keras.distribution.Distribution` instance. Used to\n shard the input dataset into per worker/process dataset\n instance.", "source": "github_repos"} +{"code": "def no_automatic_dependency_tracking_scope(obj):\n previous_value = getattr(obj, '_setattr_tracking', True)\n obj._setattr_tracking = False\n try:\n yield\n finally:\n obj._setattr_tracking = previous_value", "docstring": "A context that disables automatic dependency tracking when assigning attrs.\n\n Objects that inherit from Autotrackable automatically creates dependencies\n to trackable objects through attribute assignments, and wraps data structures\n (lists or dicts) with trackable classes. This scope may be used to temporarily\n disable this behavior. This works similar to the decorator\n `no_automatic_dependency_tracking`.\n\n Example usage:\n ```\n model = tf.keras.Model()\n model.arr1 = [] # Creates a ListWrapper object\n with no_automatic_dependency_tracking_scope(model):\n model.arr2 = [] # Creates a regular, untracked python list\n ```\n\nArgs:\n obj: A trackable object.\n\nYields:\n a scope in which the object doesn't track dependencies.", "source": "github_repos"} +{"code": "def __init__(self, columns: list[str], vocab_size: Optional[int]=None, smooth: bool=True, name: Optional[str]=None):\n super().__init__(columns)\n self.vocab_size = vocab_size\n self.smooth = smooth\n self.name = name\n self.tfidf_weight = None", "docstring": "This function applies a tf-idf transformation on the given columns\n of incoming data.\n\n TFIDF outputs two artifacts for each column: the vocabulary index and\n the tfidf weight. The vocabulary index is a mapping from the original\n vocabulary to the new vocabulary. The tfidf weight is a mapping\n from the original vocabulary to the tfidf score.\n\n Input passed to the TFIDF is not modified and used to calculate the\n required artifacts.\n\nArgs:\n columns: List of column names to apply the transformation.\n vocab_size: (Optional) An integer that specifies the size of the\n vocabulary. Defaults to None.\n\n If vocab_size is None, then the size of the vocabulary is\n determined by `tft.get_num_buckets_for_transformed_feature`.\n smooth: (Optional) A boolean that specifies whether to apply\n smoothing to the tf-idf score. Defaults to True.\n name: (Optional) A string that specifies the name of the operation.", "source": "github_repos"} +{"code": "def forward(ctx, forward_fn, *args, **kwargs):\n ctx.forward_fn = forward_fn\n ctx.save_for_backward(*args)\n try:\n output, ctx.grad_fn = forward_fn(*args, **kwargs)\n except:\n output = forward_fn(*args, **kwargs)\n ctx.grad_fn = lambda *args, **kwargs: torch.full((), float('nan'))\n return output", "docstring": "Forward pass computation specification.\n\nArgs:\n ctx: Context object.\n forward_fn: Function to compute forward pass.\n *args: Arguments for the forward pass.\n **kwargs: Keyword arguments for the forward pass.", "source": "github_repos"} +{"code": "def bloom_gelu_back(g: torch.Tensor, x: torch.Tensor) -> torch.Tensor:\n x = x[0]\n tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))\n ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh_out)\n return ff * g", "docstring": "gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) +\n 0.3989423 * x * torch.exp(-0.5 * x * x)\n\nArgs:\n g (`torch.tensor`):\n gradient output tensor\n x (`torch.tensor`):\n input tensor", "source": "github_repos"} +{"code": "def save(fn: Callable[..., Dict[str, EventSetOrNode]], path: str, *args: Union[EventSetNode, EventSet, Schema], **kwargs: Union[EventSetNode, EventSet, Schema]) -> None:\n if not hasattr(fn, 'is_tp_compiled'):\n raise ValueError('Can only save a function that has been compiled with `@tp.compile`.')\n merged_kwargs = _kwargs_from_args_and_kwargs(list(inspect.signature(fn).parameters.keys()), args, kwargs)\n node_kwargs = {k: _process_fn_input(v) for k, v in merged_kwargs.items()}\n outputs = fn(**node_kwargs)\n _check_fn_outputs(outputs)\n save_graph(inputs=node_kwargs, outputs=outputs, path=path)", "docstring": "Saves a compiled Temporian function to a file.\n\n The saved function must only take\n [`EventSetOrNodes`][temporian.types.EventSetOrNode] as arguments, return a\n dictionary of names to EventSetOrNodes, and be decorated with\n [`@tp.compile`][temporian.compile].\n\n Temporian saves the graph built between the function's input and output\n nodes, not the function itself. Any arbitrary code that\n is executed in the function will not be ran when loading it back up and\n executing it.\n\n If you need to save a function that additionally takes other types of\n arguments, try using `functools.partial` to create a new function that takes\n only EventSetNodes, and save that instead. Note that the partial function\n needs to be compiled too, with `tp.compile(partial(...))`.\n\nArgs:\n fn: The function to save.\n path: The path to save the function to.\n args: Positional arguments to pass to the function to trace it. The\n arguments can be either EventSets, EventSetNodes, or raw Schemas. In\n all cases, the values will be converted to EventSetNodes before\n being passed to the function to trace it.\n kwargs: Keyword arguments to pass to the function to trace it. Same\n restrictions as for `args`.\n\nRaises:\n ValueError: If the received function is not compiled.\n ValueError: If any of the received inputs is not of the specified types.\n ValueError: If the function doesn't return the specified type.", "source": "github_repos"} +{"code": "def MaxBipartiteMatching(self, graph):\n self.g = nx.Graph(graph)\n self.left = set((n for n, d in self.g.nodes(data=True) if not d['bipartite']))\n self.right = set(self.g) - self.left\n self.num_matched = 0\n self.s = set()\n self.t = set()\n self.matches = {}\n self.slack = {}\n self.slackx = {}\n self.prev = {}\n self.labels = {}\n for x in self.left:\n self.labels[x] = max([val['weight'] for val in self.g[x].values()])\n for y in self.right:\n self.labels[y] = 0\n while self.num_matched != len(self.left):\n self._Augment()\n ret = {}\n for k in self.left:\n ret[k] = self.matches[k]\n return ret", "docstring": "Find a maximum matching for a bipartite graph.\n\n This is O(n^3) implementation of the Hungarian method for complete bipartite\n matching problems.\n\nArgs:\n graph: A networkx graph object, assumed to be bipartite.\n\nReturns:\n A dictionary keyed on node names in left to node names in right.", "source": "github_repos"} +{"code": "def __init__(self, stddev, seed=None, **kwargs):\n super().__init__(**kwargs)\n if not 0 <= stddev <= 1:\n raise ValueError(f'Invalid value received for argument `stddev`. Expected a float value between 0 and 1. Received: stddev={stddev}')\n self.stddev = stddev\n self.seed = seed\n if stddev > 0:\n self.seed_generator = backend.random.SeedGenerator(seed)\n self.supports_masking = True\n self._build_at_init()", "docstring": "Apply additive zero-centered Gaussian noise.\n\n This is useful to mitigate overfitting\n (you could see it as a form of random data augmentation).\n Gaussian Noise (GS) is a natural choice as corruption process\n for real valued inputs.\n\n As it is a regularization layer, it is only active at training time.\n\nArgs:\n stddev: Float, standard deviation of the noise distribution.\n seed: Integer, optional random seed to enable deterministic behavior.\n\n Call arguments:\n inputs: Input tensor (of any rank).\n training: Python boolean indicating whether the layer should behave in\n training mode (adding noise) or in inference mode (doing nothing).", "source": "github_repos"} +{"code": "def _kl_dirichlet_dirichlet(d1, d2, name=None):\n with ops.name_scope(name, 'kl_dirichlet_dirichlet', values=[d1.concentration, d2.concentration]):\n digamma_sum_d1 = math_ops.digamma(math_ops.reduce_sum(d1.concentration, axis=-1, keepdims=True))\n digamma_diff = math_ops.digamma(d1.concentration) - digamma_sum_d1\n concentration_diff = d1.concentration - d2.concentration\n return math_ops.reduce_sum(concentration_diff * digamma_diff, axis=-1) - special_math_ops.lbeta(d1.concentration) + special_math_ops.lbeta(d2.concentration)", "docstring": "Batchwise KL divergence KL(d1 || d2) with d1 and d2 Dirichlet.\n\nArgs:\n d1: instance of a Dirichlet distribution object.\n d2: instance of a Dirichlet distribution object.\n name: (optional) Name to use for created operations.\n default is \"kl_dirichlet_dirichlet\".\n\nReturns:\n Batchwise KL(d1 || d2)", "source": "github_repos"} +{"code": "def _show_ops_in_metagraph(saved_model_dir, tag_set):\n meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set)\n _show_ops_in_metagraph_mgd(meta_graph_def)", "docstring": "Prints the ops in the MetaGraph.\n\n Prints all the ops used in the MetaGraphDef indicated by the tag_set stored in\n SavedModel directory.\n\nArgs:\n saved_model_dir: Directory containing the SavedModel to inspect.\n tag_set: Group of tag(s) of the MetaGraphDef in string format, separated by\n ','. For tag-set contains multiple tags, all tags must be passed in.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, encoder_hidden_states: Optional[torch.FloatTensor]=None, encoder_attention_mask: Optional[torch.FloatTensor]=None, head_mask: Optional[torch.Tensor]=None, cross_attn_head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, cache_position: Optional[torch.LongTensor]=None) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.model.decoder(input_ids=input_ids, attention_mask=attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, head_mask=head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position)\n logits = self.lm_head(outputs[0])\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n return CausalLMOutputWithCrossAttentions(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions)", "docstring": "cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):\n Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, BigBirdPegasusForCausalLM\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google/bigbird-pegasus-large-arxiv\")\n >>> model = BigBirdPegasusForCausalLM.from_pretrained(\n ... \"google/bigbird-pegasus-large-arxiv\", add_cross_attention=False\n ... )\n >>> assert model.config.is_decoder, f\"{model.__class__} has to be configured as a decoder.\"\n >>> inputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> logits = outputs.logits\n ```", "source": "github_repos"} +{"code": "def __init__(self, value_type: typing.Union[typing.Type[typing.Any], typing.Tuple[typing.Type[typing.Any], ...]], default: typing.Any=MISSING_VALUE, is_noneable: bool=False, frozen: bool=False):\n super().__init__(value_type, default, is_noneable=is_noneable, frozen=frozen)", "docstring": "Constructor.\n\nArgs:\n value_type: Acceptable value type(s).\n default: Default value.\n is_noneable: If True, None is acceptable.\n frozen: If True, values other than the default value is not accceptable.", "source": "github_repos"} +{"code": "def _boundaries_to_sizes(a, boundaries, axis):\n if axis >= len(a.shape):\n raise ValueError('axis %s is out of bound for shape %s' % (axis, a.shape))\n total_size = a.shape[axis]\n sizes = []\n sizes_sum = 0\n prev = 0\n for i, b in enumerate(boundaries):\n size = b - prev\n if size < 0:\n raise ValueError('The %s-th boundary %s is smaller than the previous boundary %s' % (i, b, prev))\n size = builtins.min(size, builtins.max(0, total_size - sizes_sum))\n sizes.append(size)\n sizes_sum += size\n prev = b\n sizes.append(builtins.max(0, total_size - sizes_sum))\n return sizes", "docstring": "Converting boundaries of splits to sizes of splits.\n\nArgs:\n a: the array to be split.\n boundaries: the boundaries, as in np.split.\n axis: the axis along which to split.\n\nReturns:\n A list of sizes of the splits, as in tf.split.", "source": "github_repos"} +{"code": "def run_stages(self, stage_context: translations.TransformContext, stages: List[translations.Stage]) -> 'RunnerResult':\n worker_handler_manager = WorkerHandlerManager(stage_context.components.environments, self._provision_info)\n pipeline_metrics = MetricsContainer('')\n pipeline_metrics.get_counter(MetricName(str(type(self)), self.NUM_FUSED_STAGES_COUNTER, urn='internal:' + self.NUM_FUSED_STAGES_COUNTER)).update(len(stages))\n monitoring_infos_by_stage: MutableMapping[str, Iterable['metrics_pb2.MonitoringInfo']] = {}\n runner_execution_context = execution.FnApiRunnerExecutionContext(stages, worker_handler_manager, stage_context.components, stage_context.safe_coders, stage_context.data_channel_coders, self._num_workers, split_managers=self._split_managers)\n try:\n with self.maybe_profile():\n runner_execution_context.setup()\n bundle_counter = 0\n while len(runner_execution_context.queues.ready_inputs) > 0:\n _LOGGER.debug('Remaining ready bundles: %s\\n\\tWatermark pending bundles: %s\\n\\tTime pending bundles: %s', len(runner_execution_context.queues.ready_inputs), len(runner_execution_context.queues.watermark_pending_inputs), len(runner_execution_context.queues.time_pending_inputs))\n consuming_stage_name, bundle_input = runner_execution_context.queues.ready_inputs.deque()\n stage = runner_execution_context.stages[consuming_stage_name]\n bundle_context_manager = runner_execution_context.bundle_manager_for(stage)\n _BUNDLE_LOGGER.debug('Running bundle for stage %s\\n\\tExpected outputs: %s timers: %s', bundle_context_manager.stage.name, bundle_context_manager.stage_data_outputs, bundle_context_manager.stage_timer_outputs)\n assert consuming_stage_name == bundle_context_manager.stage.name\n bundle_counter += 1\n bundle_results = self._execute_bundle(runner_execution_context, bundle_context_manager, bundle_input)\n if consuming_stage_name in monitoring_infos_by_stage:\n monitoring_infos_by_stage[consuming_stage_name] = consolidate_monitoring_infos(itertools.chain(bundle_results.process_bundle.monitoring_infos, monitoring_infos_by_stage[consuming_stage_name]))\n else:\n assert isinstance(bundle_results.process_bundle.monitoring_infos, Iterable)\n monitoring_infos_by_stage[consuming_stage_name] = bundle_results.process_bundle.monitoring_infos\n if '' not in monitoring_infos_by_stage:\n monitoring_infos_by_stage[''] = list(pipeline_metrics.to_runner_api_monitoring_infos('').values())\n else:\n monitoring_infos_by_stage[''] = consolidate_monitoring_infos(itertools.chain(pipeline_metrics.to_runner_api_monitoring_infos('').values(), monitoring_infos_by_stage['']))\n if len(runner_execution_context.queues.ready_inputs) == 0:\n self._schedule_ready_bundles(runner_execution_context)\n assert len(runner_execution_context.queues.ready_inputs) == 0, 'A total of %d ready bundles did not execute.' % len(runner_execution_context.queues.ready_inputs)\n assert len(runner_execution_context.queues.watermark_pending_inputs) == 0, 'A total of %d watermark-pending bundles did not execute.' % len(runner_execution_context.queues.watermark_pending_inputs)\n assert len(runner_execution_context.queues.time_pending_inputs) == 0, 'A total of %d time-pending bundles did not execute.' % len(runner_execution_context.queues.time_pending_inputs)\n finally:\n worker_handler_manager.close_all()\n return RunnerResult(runner.PipelineState.DONE, monitoring_infos_by_stage)", "docstring": "Run a list of topologically-sorted stages in batch mode.\n\nArgs:\n stage_context (translations.TransformContext)\n stages (list[fn_api_runner.translations.Stage])", "source": "github_repos"} +{"code": "def offsets_in_rows(self):\n return gen_ragged_math_ops.ragged_range(starts=constant_op.constant(0, self.dtype), limits=self.row_lengths(), deltas=constant_op.constant(1, self.dtype)).rt_dense_values", "docstring": "Return the offset of each value.\n\n RowPartition takes an array x and converts it into sublists.\n offsets[i] is the index of x[i] in its sublist.\n Given a shape, such as:\n [*,*,*],[*,*],[],[*,*]\n This returns:\n 0,1,2,0,1,0,1\n\nReturns:\n an offset for every value.", "source": "github_repos"} +{"code": "def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:\n sep = [self.sep_token_id]\n cls = [self.cls_token_id]\n if token_ids_1 is None:\n return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0]\n return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]", "docstring": "Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel\n Transformer sequence pair mask has the following format:\n\n ```\n 2 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1\n | first sequence | second sequence |\n ```\n\n If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).\n\nArgs:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n\nReturns:\n `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.LongTensor]=None, past_key_value: Optional[Tuple[torch.Tensor]]=None, output_attentions: Optional[bool]=False, output_router_logits: Optional[bool]=False, use_cache: Optional[bool]=False, cache_position: Optional[torch.LongTensor]=None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]]=None, **kwargs) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n residual = hidden_states\n hidden_states = self.input_layernorm(hidden_states)\n hidden_states, self_attn_weights, present_key_value = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings)\n hidden_states = residual + hidden_states\n residual = hidden_states\n hidden_states = self.post_attention_layernorm(hidden_states)\n hidden_states, router_logits = self.block_sparse_moe(hidden_states)\n hidden_states = residual + hidden_states\n outputs = (hidden_states,)\n if output_attentions:\n outputs += (self_attn_weights,)\n if use_cache:\n outputs += (present_key_value,)\n if output_router_logits:\n outputs += (router_logits,)\n return outputs", "docstring": "Args:\n hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\n attention_mask (`torch.FloatTensor`, *optional*): attention mask of size\n `(batch, sequence_length)` where padding elements are indicated by 0.\n past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n output_router_logits (`bool`, *optional*):\n Whether or not to return the logits of all the routers. They are useful for computing the router loss, and\n should not be returned during inference.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding\n (see `past_key_values`).\n cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):\n Indices depicting the position of the input sequence tokens in the sequence.\n kwargs (`dict`, *optional*):\n Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code\n into the model", "source": "github_repos"} +{"code": "def _experimental_default_mesh(self, mesh: layout_lib.Mesh):\n previous_default = self._current_default_mesh\n self._register_mesh(mesh)\n _pywrap_dtensor_device.ExperimentalSetDefaultMesh(self._device_info, mesh.to_string().encode('utf-8'))\n self._current_default_mesh = mesh\n yield\n _pywrap_dtensor_device.ExperimentalClearDefaultMesh(self._device_info)\n if previous_default:\n _pywrap_dtensor_device.ExperimentalSetDefaultMesh(self._device_info, previous_default.to_string().encode('utf-8'))\n self._current_default_mesh = previous_default", "docstring": "Sets a default mesh for all ops in the scope.\n\n Note: This is an internal helper method, which is not user facing api.\n\n Useful for requesting a specific mesh for ops which would have no inferred\n layout, e.g. tf.zeros.\n\nArgs:\n mesh: A Mesh to be used for ops without Mesh.\n\nYields:\n Nothing.", "source": "github_repos"} +{"code": "def lookup(self, obj):\n for registered in self._registry:\n if isinstance(obj, registered):\n return self._registry[registered]\n raise LookupError(f'{type(obj)} has not been registered.')", "docstring": "Looks up 'obj'.\n\nArgs:\n obj: The object to lookup within the registry.\n\nReturns:\n Value for 'obj' in the registry if found.\n\nRaises:\n LookupError: if 'obj' has not been registered.", "source": "github_repos"} +{"code": "def recipe_cm_user_editor(config, recipe_name):\n drive(config, {'auth': 'user', 'hour': [], 'copy': {'source': 'https://docs.google.com/spreadsheets/d/1Mw4kDJfaWVloyjSayJSkgE8i28Svoj1756fyQtIpmRE/', 'destination': recipe_name}})", "docstring": "A tool for rapidly bulk editing Campaign Manager profiles, roles, and sub\n accounts.\n\nArgs:\n recipe_name (string) - Name of document to deploy to.", "source": "github_repos"} +{"code": "def __add__(self, other):\n try:\n other = as_dimension(other)\n except (TypeError, ValueError):\n return NotImplemented\n if self._value is None or other.value is None:\n return Dimension(None)\n else:\n return Dimension(self._value + other.value)", "docstring": "Returns the sum of `self` and `other`.\n\n Dimensions are summed as follows:\n\n ```python\n tf.compat.v1.Dimension(m) + tf.compat.v1.Dimension(n) ==\n tf.compat.v1.Dimension(m + n)\n tf.compat.v1.Dimension(m) + tf.compat.v1.Dimension(None) # equiv. to\n tf.compat.v1.Dimension(None)\n tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(n) # equiv. to\n tf.compat.v1.Dimension(None)\n tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) # equiv. to\n tf.compat.v1.Dimension(None)\n ```\n\nArgs:\n other: Another Dimension, or a value accepted by `as_dimension`.\n\nReturns:\n A Dimension whose value is the sum of `self` and `other`.", "source": "github_repos"} +{"code": "def in_range(self, ver, req):\n if req.exclude is not None:\n for v in ver:\n if v in req.exclude:\n return False\n include_checked = False\n if req.include is not None:\n for v in ver:\n if v in req.include:\n return True\n include_checked = True\n if req.range != [None, None]:\n min_v = req.range[0]\n max_v = req.range[1]\n ver = ver[0]\n lg = _compare_versions(min_v, ver)['larger']\n sm = _compare_versions(ver, max_v)['smaller']\n if lg in [ver, 'equal'] and sm in [ver, 'equal', 'inf']:\n return True\n else:\n err_msg = '[Error] Version is outside of supported range. '\n err_msg += '(config = %s, ' % str(req.config)\n err_msg += 'version = %s, ' % str(ver)\n err_msg += 'supported range = %s)' % str(req.range)\n logging.warning(err_msg)\n self.warning_msg.append(err_msg)\n return False\n else:\n err_msg = ''\n if include_checked:\n err_msg = '[Error] Version is outside of supported range. '\n else:\n err_msg = '[Error] Missing specification. '\n err_msg += '(config = %s, ' % str(req.config)\n err_msg += 'version = %s, ' % str(ver)\n err_msg += 'supported range = %s)' % str(req.range)\n logging.warning(err_msg)\n self.warning_msg.append(err_msg)\n return False", "docstring": "Checks if a version satisfies a version and/or compatibility requirement.\n\nArgs:\n ver: List whose first item is a config version that needs to be checked\n for support status and version compatibility.\n e.g. ver = [`1.0`]\n req: `_Reqs` class instance that represents a configuration version and\n compatibility specifications.\n\nReturns:\n Boolean output of checking if version `ver` meets the requirement\n stored in `req` (or a `_Reqs` requirements class instance).", "source": "github_repos"} +{"code": "def write_line(self, values):\n if self.inner_table is None:\n self.inner_table = [list(values.keys()), list(values.values())]\n else:\n columns = self.inner_table[0]\n for key in values.keys():\n if key not in columns:\n columns.append(key)\n self.inner_table[0] = columns\n if len(self.inner_table) > 1:\n last_values = self.inner_table[-1]\n first_column = self.inner_table[0][0]\n if last_values[0] != values[first_column]:\n self.inner_table.append([values[c] if c in values else 'No Log' for c in columns])\n else:\n new_values = values\n for c in columns:\n if c not in new_values.keys():\n new_values[c] = last_values[columns.index(c)]\n self.inner_table[-1] = [new_values[c] for c in columns]\n else:\n self.inner_table.append([values[c] for c in columns])", "docstring": "Write the values in the inner table.\n\nArgs:\n values (`Dict[str, float]`): The values to display.", "source": "github_repos"} +{"code": "def __init__(self, data=None, _KEY=None, _ATTRS=None):\n if self.__class__ is MapEntry:\n raise TypeError('MapEntry is an abstract class.')\n if data is None:\n return\n else:\n for key in data:\n setattr(self, key, data[key])\n self.log = logging.getLogger(__name__)", "docstring": "This is an abstract class.\n\nArgs:\n data: An optional dict of attribute, value pairs to populate with.\n\nRaises:\n TypeError: Bad argument, or attempt to instantiate abstract class.", "source": "github_repos"} +{"code": "def _set_device(self, device) -> None:\n self._set_device_from_string(compat.as_str(_device_string(device)))", "docstring": "Set the device of this operation.\n\nArgs:\n device: string or device.. The device to set.", "source": "github_repos"} +{"code": "def dummy_inputs(self) -> Dict[str, tf.Tensor]:\n return {self.main_input_name: tf.random.uniform([1, self.config.num_mel_bins, self.config.max_source_positions * 2 - 1], dtype=tf.float32), 'decoder_input_ids': tf.constant([[1, 3]], dtype=tf.int32)}", "docstring": "Dummy inputs to build the network.\n\nReturns:\n `Dict[str, tf.Tensor]`: The dummy inputs.", "source": "github_repos"} +{"code": "def device(self) -> torch.device:\n if self._rot_mats is not None:\n return self._rot_mats.device\n elif self._quats is not None:\n return self._quats.device\n else:\n raise ValueError('Both rotations are None')", "docstring": "The device of the underlying rotation\n\nReturns:\n The device of the underlying rotation", "source": "github_repos"} +{"code": "def get_range(self, request, start, end):\n file_ = self.get_file(request.bucket, request.object)\n if start < 0 or end <= start:\n return file_.contents\n return file_.contents[start:end]", "docstring": "Retrieves an object.\n\nArgs:\n request: (GetRequest) request\n\nReturns:\n (bytes) The response message.", "source": "github_repos"} +{"code": "def on_train_begin(self, logs=None):", "docstring": "Called at the beginning of training.\n\n Subclasses should override for any actions to run.\n\nArgs:\n logs: Dict. Currently no data is passed to this argument for this\n method but that may change in the future.", "source": "github_repos"} +{"code": "def _make_output_composite_tensors_match(op_type, branch_graphs):\n assert branch_graphs\n branch_outputs = [g.structured_outputs for g in branch_graphs]\n outputs_per_branch = list((len(outs) for outs in branch_outputs))\n assert len(set(outputs_per_branch)) == 1, outputs_per_branch\n for output_idx, branch_outs in enumerate(zip(*branch_outputs)):\n if len(set((type(out) for out in branch_outs))) == 1:\n continue\n if not any((isinstance(out, indexed_slices.IndexedSlices) for out in branch_outs)):\n continue\n for branch_idx, branch_out in enumerate(branch_outs):\n if isinstance(branch_out, indexed_slices.IndexedSlices):\n continue\n elif isinstance(branch_out, tensor_lib.Tensor):\n with branch_graphs[branch_idx].as_default():\n branch_outputs[branch_idx][output_idx] = math_ops._as_indexed_slices(branch_out)\n else:\n raise TypeError('Cannot reconcile {op_name} {output_idx}-th outputs:\\n outputs from all branches: {outputs}'.format(op_name='tf.cond' if op_type == _COND else 'tf.switch_case', output_idx=output_idx, outputs=branch_outs))\n for branch_graph, branch_outs in zip(branch_graphs, branch_outputs):\n branch_graph.structured_outputs = branch_outs\n branch_graph.outputs = [t for t in func_graph_module.flatten(branch_outs) if t is not None]", "docstring": "Modifies each branch_graph's outputs to have the same output signature.\n\n Currently the only transformation implemented is turning a Tensor into an\n equivalent IndexedSlices if the other branch returns an IndexedSlices.\n Updates branch_graph.{outputs,structured_outputs} for each branch_graph in\n branch_graphs.\n\nArgs:\n op_type: _COND or _CASE\n branch_graphs: `list` of `FuncGraph`\n\nRaises:\n TypeError: if a set of outputs cannot be rewritten.", "source": "github_repos"} +{"code": "def _maybe_broadcast_to_outputs(self, outputs, objects):\n if not self._should_broadcast(objects):\n return objects\n should_copy_objects = len(nest.flatten(outputs)) > 1\n\n def _broadcast_fn():\n if should_copy_objects:\n return nest.map_structure(self._copy_object, objects)\n return objects\n return nest.map_structure(lambda _: _broadcast_fn(), outputs)", "docstring": "Determines if losses / metrics should be applied to all outputs.\n\n NOTE: This method should only be called for Metrics / Losses, not for\n y_true / sample_weight.\n\nArgs:\n outputs: Model predictions.\n objects: Arbitrary nested structure (e.g. of losses or metrics)\n\nReturns:\n Arbitrary nested structure of objects, maybe copied to each output.\n\n Applies a Loss / Metric to all outputs.", "source": "github_repos"} +{"code": "def weights(self):\n return self._dedup_weights(self._undeduplicated_weights)", "docstring": "Returns the list of all layer variables/weights.\n\n Note: This will not track the weights of nested `tf.Modules` that are not\n themselves Keras layers.\n\nReturns:\n A list of variables.", "source": "github_repos"} +{"code": "def _replace_tensors_for_gradient(x, grad):\n if not isinstance(x, composite_tensor.CompositeTensor):\n return grad\n if not isinstance(x, CompositeTensorGradientProtocol):\n raise ValueError(f'Type {type(x).__name__} is not supported as a gradient source.')\n composite_gradient = x.__composite_gradient__\n x_components = composite_gradient.get_gradient_components(x)\n if x_components is x:\n grad_components = grad\n else:\n grad_components = nest.map_structure_up_to(x_components, _replace_tensors_for_gradient, x_components, grad)\n if grad_components is None:\n return None\n return composite_gradient.replace_gradient_components(x, grad_components)", "docstring": "Replaces the tensors in `x` that should be differentiated with `grad`.\n\nArgs:\n x: A `Tensor` or `CompositeTensor`.\n grad: A nested structure of `Tensor`, with the same structure as the value\n returned by `_get_tensors_for_gradient(x)`.\n\nReturns:\n A `Tensor` or `CompositeTensor`.", "source": "github_repos"} +{"code": "def get_image_size_fit_to_canvas(image_height: int, image_width: int, canvas_height: int, canvas_width: int, tile_size: int) -> Tuple[int, int]:\n target_width = np.clip(image_width, tile_size, canvas_width)\n target_height = np.clip(image_height, tile_size, canvas_height)\n scale_h = target_height / image_height\n scale_w = target_width / image_width\n if scale_w < scale_h:\n new_width = target_width\n new_height = min(math.floor(image_height * scale_w) or 1, target_height)\n else:\n new_height = target_height\n new_width = min(math.floor(image_width * scale_h) or 1, target_width)\n return (new_height, new_width)", "docstring": "Calculates the new size of an image to fit within a canvas while maintaining aspect ratio.\n\n This function calculates the optimal size for an image to fit within a canvas defined by\n canvas_height and canvas_width, while ensuring that the image dimensions are not smaller than\n tile_size. If the image is larger than the canvas, the returned size will fit within the canvas.\n If the image already fits within the canvas, the size remains unchanged.\n The aspect ratio of the original image is preserved as much as possible.\n\nArgs:\n image_height (`int`):\n The height of the original image.\n image_width (`int`):\n The width of the original image.\n canvas_height (`int`):\n The height of the canvas.\n canvas_width (`int`):\n The width of the canvas.\n tile_size (`int`):\n The tile size.\n\nReturns:\n `Tuple[int, int]`: A tuple containing the new height and width of the image.", "source": "github_repos"} +{"code": "def sheets_tab_range(sheet_tab, sheet_range):\n if sheet_range:\n return '%s!%s' % (sheet_tab, sheet_range)\n else:\n return sheet_tab", "docstring": "Helper for creating range format.\n\nArgs:\n sheet_tab - name of tab in sheet\n sheet_range - A1 notation\n\nReturns:\n String containing full sheet range specification.", "source": "github_repos"} +{"code": "def _CheckUnresolved(cls):\n with cls._unresolved_subjects_lock:\n if cls._unresolved_subjects:\n msg = ['The following assertions were unresolved. Perhaps you called \"AssertThat(thing.IsEmpty())\" instead of \"AssertThat(thing).IsEmpty()\".']\n for u in sorted(cls._unresolved_subjects):\n msg.append(' * {0}'.format(u))\n raise UnresolvedAssertionError('\\n'.join(msg))", "docstring": "Ensures that all created subjects were eventually resolved.\n\n A subject is considered resolved what at least one proposition has been\n executed on it. An unresolved or dangling assertion is almost certainly a\n test author error.\n\nRaises:\n UnresolvedAssertionError: if any subjects remain unresolved at the time of\n this function call.", "source": "github_repos"} +{"code": "def _apply_threshold_to_predictions(self, result: AnomalyResult) -> AnomalyResult:\n predictions = [dataclasses.replace(p, label=self._threshold_fn.apply(p.score), threshold=self._threshold_fn.threshold) for p in result.predictions]\n return dataclasses.replace(result, predictions=predictions)", "docstring": "Updates the prediction labels in an AnomalyResult using the ThresholdFn.\n\nArgs:\n result (AnomalyResult): The input `AnomalyResult` containing anomaly\n scores.\n\nReturns:\n AnomalyResult: A new `AnomalyResult` with updated prediction labels\n and threshold values.", "source": "github_repos"} +{"code": "def set_iterator_element_layouts(self, iterator_resource_dtensor, layouts: List[layout_lib.Layout]):\n _pywrap_dtensor_device.SetIteratorElementLayouts(context.context()._handle, iterator_resource_dtensor, [layout.to_string() for layout in layouts], self._device_info)", "docstring": "Sets the element layouts on an iterator resource tensor.\n\nArgs:\n iterator_resource_dtensor: a DTensor created by packing the individiual\n iterator resource tensors.\n layouts: the flattened list of layouts to be applied to the elements\n emitted by the iterator resource DTensor.", "source": "github_repos"} +{"code": "def _add_file_argument(parser, types, args, custom_kwargs=None):\n custom_kwargs = custom_kwargs or {}\n arg = args[-1]\n dest = custom_kwargs.get('dest', arg.lstrip(_ARG_PREFIX).replace('-', '_'))\n kwargs = {'type': types.get(dest), 'action': 'store', 'default': config.ITEMS[dest].default, 'help': config.ITEMS[dest].comment}\n kwargs.update(custom_kwargs)\n if kwargs['type'] is None:\n del kwargs['type']\n if arg.startswith(_ARG_PREFIX):\n kwargs['dest'] = dest\n elif 'type' in kwargs:\n kwargs['default'] = kwargs['type'](kwargs['default'])\n parser.add_argument(*args, **kwargs)", "docstring": "Add a file-configurable option to the parser.\n\nArgs:\n parser: The parser.\n types: A map from option destination to type.\n args: The option's name(s). Either a 2-tuple of (short_arg, arg) or a\n 1-tuple of (arg,).\n custom_kwargs: The option's custom kwargs.", "source": "github_repos"} +{"code": "def crop_image_to_patches(self, images: 'torch.Tensor', min_patches: int, max_patches: int, use_thumbnail: bool=True, patch_size: Optional[Union[Tuple, int, dict]]=None, interpolation: Optional['F.InterpolationMode']=None):\n patch_size_height, patch_size_width = (patch_size.height, patch_size.width)\n original_height, original_width = images.shape[-2:]\n num_columns, num_rows = get_optimal_tiled_canvas((original_height, original_width), (patch_size_height, patch_size_width), min_patches, max_patches)\n target_width = patch_size_width * num_columns\n target_height = patch_size_height * num_rows\n num_blocks = num_columns * num_rows\n resized_image = self.resize(images, SizeDict(height=target_height, width=target_width), interpolation=interpolation)\n processed_images = []\n for i in range(num_blocks):\n column = i % num_columns\n row = i // num_columns\n box = (column * patch_size_width, row * patch_size_height, (column + 1) * patch_size_width, (row + 1) * patch_size_height)\n patch_image = resized_image[..., box[1]:box[3], box[0]:box[2]]\n processed_images.append(patch_image)\n if use_thumbnail and len(processed_images) != 1:\n thumbnail_img = self.resize(images, patch_size, interpolation=interpolation)\n processed_images.append(thumbnail_img)\n processed_images = torch.stack(processed_images, dim=0).transpose(0, 1).contiguous()\n return processed_images", "docstring": "Crop the images to patches and return a list of cropped images.\n The number of patches and their grid arrangement are determined by the original image size,\n the target patch size and the minimum and maximum number of patches.\n The aspect ratio of the patches grid is chosen to be the closest to the original image aspect ratio.\n\nArgs:\n images (`torch.Tensor`):\n The images to be cropped.\n min_patches (`int`):\n The minimum number of patches to be extracted from the image.\n max_patches (`int`):\n The maximum number of patches to be extracted from the image.\n use_thumbnail (`bool`, *optional*, defaults to `True`):\n Whether to add a thumbnail image to the list of cropped patches.\n patch_size (`int`, `Tuple[int, int]`, `dict`, *optional*):\n The size of the output patches.\n The format of the image data. If `None`, the format is inferred from the input image.\n\nReturns:\n List[`PIL.Image.Image`] or List[np.ndarray]: The list of cropped images.", "source": "github_repos"} +{"code": "def copy_file(src_file: str, dst_dir: str, strip: str=None, dest_file: str=None) -> None:\n dest = dest_file if dest_file else src_file\n if dest.startswith('bazel-out'):\n dest = dest[dest.index('bin') + 4:]\n if strip:\n dest = dest.removeprefix(strip)\n dest_dir_path = os.path.join(dst_dir, os.path.dirname(dest))\n os.makedirs(dest_dir_path, exist_ok=True)\n shutil.copy(src_file, dest_dir_path)\n os.chmod(os.path.join(dst_dir, dest), 420)", "docstring": "Copy a file to the destination directory.\n\nArgs:\n src_file: file to be copied\n dst_dir: destination directory\n strip: prefix to strip before copying to destination\n dest_file: destanation file location if different from src_file", "source": "github_repos"} +{"code": "def _hertz_to_mel(frequencies_hertz, name=None):\n with ops.name_scope(name, 'hertz_to_mel', [frequencies_hertz]):\n frequencies_hertz = ops.convert_to_tensor(frequencies_hertz)\n return _MEL_HIGH_FREQUENCY_Q * math_ops.log(1.0 + frequencies_hertz / _MEL_BREAK_FREQUENCY_HERTZ)", "docstring": "Converts frequencies in `frequencies_hertz` in Hertz to the mel scale.\n\nArgs:\n frequencies_hertz: A `Tensor` of frequencies in Hertz.\n name: An optional name for the operation.\n\nReturns:\n A `Tensor` of the same shape and type of `frequencies_hertz` containing\n frequencies in the mel scale.", "source": "github_repos"} +{"code": "def __init__(self, input_dataset, num_workers, index, num_replicas=None):\n self._input_dataset = input_dataset\n self._element_spec = input_dataset.element_spec\n variant_tensor = ged_ops.auto_shard_dataset(self._input_dataset._variant_tensor, num_workers=num_workers, index=index, auto_shard_policy=int(input_dataset.options().experimental_distribute.auto_shard_policy), num_replicas=num_replicas, **self._flat_structure)\n super(_AutoShardDataset, self).__init__(input_dataset, variant_tensor)", "docstring": "A `Dataset` that shards the `Dataset` automatically.\n\n This dataset takes in an existing dataset and tries to automatically figure\n out how to shard the dataset in a multi-worker scenario using graph rewrites.\n\n If the AutoShardPolicy is set to FILE, it walks up the dataset graph until\n it finds a reader dataset, then inserts a ShardDataset op before that node\n so that each worker only sees some files.\n\n If the AutoShardPolicy is set to DATA, it inserts a ShardDataset op at the\n end of the input pipeline, before any terminal PrefetchDataset if there is\n one. Additionally, if there is a RebatchDatasetV2 in the input pipeline, it\n is written to legacy RebatchDataset for correctness reasons, since\n RebatchDatasetV2 is incompatible with data sharding.\n\n If the AutoShardPolicy is set to AUTO, it tries to do file-based sharding.\n If it cannot find a reader dataset, it falls back to doing data-based\n sharding.\n\n If the AutoShardPolicy is set to OFF, it does nothing.\n\nAttributes:\n num_workers: Total number of workers to shard this dataset across.\n index: The current worker index (out of the total number of workers) this\n dataset is for.\n num_replicas: The total number of replicas across all workers. This is used\n only when sharding by data (either DATA or AUTO) in order to rewrite\n RebatchDatasetV2 to RebatchDataset.\n\nRaises:\n NotFoundError: If we cannot find a suitable reader dataset to begin\n automatically sharding the dataset.", "source": "github_repos"} +{"code": "def _add_name_scope_wrapper(func, api_signature):\n if 'name' not in api_signature.parameters:\n return func\n func_signature = tf_inspect.signature(func)\n func_argspec = tf_inspect.getargspec(func)\n if 'name' in func_signature.parameters or func_argspec.keywords is not None:\n return func\n name_index = list(api_signature.parameters).index('name')\n\n def wrapped_func(*args, **kwargs):\n if name_index < len(args):\n name = args[name_index]\n args = args[:name_index] + args[name_index + 1:]\n else:\n name = kwargs.pop('name', None)\n if name is None:\n return func(*args, **kwargs)\n else:\n with ops.name_scope(name):\n return func(*args, **kwargs)\n wrapped_func = tf_decorator.make_decorator(func, wrapped_func)\n wrapped_func.__signature__ = func_signature.replace(parameters=list(func_signature.parameters.values()) + [api_signature.parameters['name']])\n del wrapped_func._tf_decorator\n return wrapped_func", "docstring": "Wraps `func` to expect a \"name\" arg, and use it to call `ops.name_scope`.\n\n If `func` already expects a \"name\" arg, or if `api_signature` does not\n expect a \"name\" arg, then returns `func` as-is.\n\nArgs:\n func: The function to wrap. Signature must match `api_signature` (except\n the \"name\" parameter may be missing.\n api_signature: The signature of the original API (used to find the index for\n the \"name\" parameter).\n\nReturns:\n The wrapped function (or the original function if no wrapping is needed).", "source": "github_repos"} +{"code": "def hasValue(self) -> 'Builder':\n return self._to_builder(_evaluation.HasValueFunction(self.node.context, self.node, []))", "docstring": "The FHIRPath hasValue() function.\n\nReturns:\n An expression that evaluates to True if the parent has a single value\n that is a primitive.", "source": "github_repos"} +{"code": "def reset_logical_devices(device_type, count):\n reset_context()\n devices = tf_config.list_physical_devices(device_type)\n if device_type.upper() not in ('CPU', 'GPU'):\n raise ValueError('resetting logical device for non-supported device type : %s' % device_type)\n if count < len(devices):\n devices = devices[:count]\n tf_config.set_visible_devices(devices, device_type=device_type.upper())\n for i, device in enumerate(devices):\n n = (i + 1) * count // len(devices) - i * count // len(devices)\n assert n > 0\n configs = []\n for ordinal in range(n):\n if device_type.upper() == 'GPU':\n dev_config = context.LogicalDeviceConfiguration(memory_limit=_DEFAULT_GPU_MEMORY_LIMIT, experimental_device_ordinal=ordinal)\n else:\n dev_config = context.LogicalDeviceConfiguration()\n configs.append(dev_config)\n tf_config.set_logical_device_configuration(device, configs)", "docstring": "Resets logical devices for CPU/GPU.\n\n Logical devices can only be instantiated once on a particular context. For\n now, context re-use is triggering some function duplication errors, so we\n reset the context on each call.\n\nArgs:\n device_type: The device_type to reset.\n count: numbers of virtual device to reset to.", "source": "github_repos"} +{"code": "def _psum(tensor, axis_name=None):\n if axis_name != _pmap_config.axis_name():\n raise ValueError('axis_name (%s) is not equal to that of the surrounding pmap (%s)' % (axis_name, _pmap_config.axis_name()))\n devices = _pmap_config.devices()\n if devices is None:\n raise ValueError(\"Can't retrieve the device list from the surrounding pmap\")\n tensor = tf_np.asarray(tensor)\n if tpu_devices(devices):\n is_int64 = False\n is_float64 = False\n if tensor.dtype == np.int64:\n is_int64 = True\n tensor = tensor.astype(np.int32)\n elif tensor.dtype == np.float64:\n is_float64 = True\n tensor = tensor.astype(np.float32)\n tensor = tpu_ops.cross_replica_sum(tensor)\n if is_int64:\n tensor = math_ops.cast(tensor, dtypes.int64)\n elif is_float64:\n tensor = math_ops.cast(tensor, dtypes.float64)\n else:\n tensor = gen_collective_ops.collective_reduce(input=tensor, group_size=len(devices), group_key=_GROUP_KEY, instance_key=_get_instance_key(), merge_op='Add', final_op='Id', subdiv_offsets=(0,))\n return tf_np.asarray(tensor)", "docstring": "Sum all-reduction.\n\nArgs:\n tensor: A tensor.\n axis_name: The axis name to reduce. Must equal to that of the surrounding\n pmap.\n\nReturns:\n The sum of the `tensor` replicas on each participating devices.", "source": "github_repos"} +{"code": "def testConcreteFunctionFlatSignatureError(self, conc_args=(), conc_kwargs=None, call_args=(), call_kwargs=None, error='.*', exception=TypeError):\n conc_args = conc_args() if callable(conc_args) else conc_args\n conc_kwargs = conc_kwargs() if callable(conc_kwargs) else conc_kwargs or {}\n call_args = call_args() if callable(call_args) else call_args\n call_kwargs = call_kwargs() if callable(call_kwargs) else call_kwargs or {}\n self.assertIsInstance(conc_args, tuple)\n self.assertIsInstance(call_args, tuple)\n self.assertIsInstance(conc_kwargs, dict)\n self.assertIsInstance(call_kwargs, dict)\n\n @polymorphic_function.function\n def func(x, y=5, *varargs, **kwargs):\n del y, varargs, kwargs\n return x\n conc = func.get_concrete_function(*conc_args, **conc_kwargs)\n with self.assertRaisesRegex(exception, error):\n self.evaluate(conc._call_with_flat_signature(call_args, call_kwargs))", "docstring": "Tests for errors in the flat signature.\n\nArgs:\n conc_args: Positional arguments used for get_concrete_function.\n conc_kwargs: Keyword arguments used for get_concrete_function.\n call_args: Positional arguments used to call the function.\n call_kwargs: Keyword arguments used to call the function.\n error: Expected exception message.\n exception: Expected exception type.", "source": "github_repos"} +{"code": "def _read_fhir_package_npm(npm_file: BinaryIO) -> Iterator[Tuple[str, str]]:\n with tarfile.open(fileobj=npm_file, mode='r:gz') as f:\n for member in f.getmembers():\n if member.name.endswith('.json'):\n content = f.extractfile(member)\n if content is not None:\n yield (member.name, content.read().decode('utf-8-sig'))\n else:\n logging.info('Skipping entry: %s.', member.name)", "docstring": "Yields the file entries for JSON resources in `npm_file` and their contents.\n\nArgs:\n npm_file: The `.tar.gz` or `.tgz` file following NPM conventions that should\n be parsed.\n\nYields:\n A tuple of filename and the raw JSON contained in that file.", "source": "github_repos"} +{"code": "def get_sine_pos_embed(pos_tensor: torch.Tensor, num_pos_feats: int=128, temperature: int=10000, exchange_xy: bool=True) -> Tensor:\n scale = 2 * math.pi\n dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos_tensor.device)\n dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode='floor') / num_pos_feats)\n\n def sine_func(x: torch.Tensor):\n sin_x = x * scale / dim_t\n sin_x = torch.stack((sin_x[..., 0::2].sin(), sin_x[..., 1::2].cos()), dim=3).flatten(2)\n return sin_x\n pos_tensor = pos_tensor.split([1] * pos_tensor.shape[-1], dim=-1)\n position_embeddings = [sine_func(x) for x in pos_tensor]\n if exchange_xy:\n position_embeddings[0], position_embeddings[1] = (position_embeddings[1], position_embeddings[0])\n position_embeddings = torch.cat(position_embeddings, dim=-1)\n return position_embeddings", "docstring": "Generate sine position embeddings from a position tensor.\n\nArgs:\n pos_tensor (torch.Tensor):\n Tensor containing positions. Shape: [..., n].\n num_pos_feats (`int`, *optional*, defaults to 128):\n Projected shape for each float in the tensor.\n temperature (`int`, *optional*, defaults to 10000):\n Temperature in the sine/cosine function.\n exchange_xy (`bool`, *optional*, defaults to `True`):\n Exchange pos x and pos y. For example, input tensor is [x,y], the results will be [pos(y), pos(x)].\n\nReturns:\n position_embeddings (torch.Tensor): shape: [..., n * hidden_size].", "source": "github_repos"} +{"code": "def _testCompareToExplicitDerivative(self, dtype):\n delta = 0.001\n np_dtype = dtype.as_numpy_dtype\n try:\n from scipy import differentiate\n from scipy import special\n alpha_val = np.logspace(-2, 3, dtype=np_dtype)\n alpha = constant_op.constant(alpha_val)\n sample = random_ops.random_gamma([], alpha, np_dtype(1.0), dtype=dtype, seed=12345)\n actual = gradients_impl.gradients(sample, alpha)[0]\n sample_val, actual_val = self.evaluate((sample, actual))\n u = special.gammainc(alpha_val, sample_val)\n expected_val = differentiate.derivative(special.gammaincinv, alpha_val, args=(u,), initial_step=delta * alpha_val, order=2, preserve_shape=True).df\n self.assertAllClose(actual_val, expected_val, rtol=0.001, atol=0.001)\n except ImportError as e:\n tf_logging.warn('Cannot use special functions in a test: %s' % str(e))", "docstring": "Compare to the explicit reparameterization derivative.\n\n Verifies that the computed derivative satisfies\n dsample / dalpha = d igammainv(alpha, u) / dalpha,\n where u = igamma(alpha, sample).\n\nArgs:\n dtype: TensorFlow dtype to perform the computations in.", "source": "github_repos"} +{"code": "def _parse_test_option_args(self, argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--test-pipeline-options', type=str, action='store', help='only run tests providing service options')\n parser.add_argument('--not-use-test-runner-api', action='store_true', default=False, help='whether not to use test-runner-api')\n known, unused_argv = parser.parse_known_args(argv)\n test_pipeline_options = known.test_pipeline_options or TestPipeline.pytest_test_pipeline_options\n if self.is_integration_test and (not test_pipeline_options):\n raise SkipTest('IT is skipped because --test-pipeline-options is not specified')\n self.not_use_test_runner_api = known.not_use_test_runner_api\n return shlex.split(test_pipeline_options) if test_pipeline_options else []", "docstring": "Parse value of command line argument: --test-pipeline-options to get\n pipeline options.\n\nArgs:\n argv: An iterable of command line arguments to be used. If not specified\n then sys.argv will be used as input for parsing arguments.\n\nReturns:\n An argument list of options that can be parsed by argparser or directly\n build a pipeline option.", "source": "github_repos"} +{"code": "def replace_batch_norm(model):\n for name, module in model.named_children():\n if isinstance(module, nn.BatchNorm2d):\n new_module = DetaFrozenBatchNorm2d(module.num_features)\n if not module.weight.device == torch.device('meta'):\n new_module.weight.data.copy_(module.weight)\n new_module.bias.data.copy_(module.bias)\n new_module.running_mean.data.copy_(module.running_mean)\n new_module.running_var.data.copy_(module.running_var)\n model._modules[name] = new_module\n if len(list(module.children())) > 0:\n replace_batch_norm(module)", "docstring": "Recursively replace all `torch.nn.BatchNorm2d` with `DetaFrozenBatchNorm2d`.\n\nArgs:\n model (torch.nn.Module):\n input model", "source": "github_repos"} +{"code": "def variable_axis_size_partitioner(max_shard_bytes, axis=0, bytes_per_string_element=16, max_shards=None):\n if max_shard_bytes < 1 or bytes_per_string_element < 1:\n raise ValueError(f'Both max_shard_bytes and bytes_per_string_element must be positive. Currently, max_shard_bytes is {max_shard_bytes} andbytes_per_string_element is {bytes_per_string_element}')\n if max_shards and max_shards < 1:\n raise ValueError('max_shards must be positive.')\n\n def _partitioner(shape, dtype):\n \"\"\"Partitioner that partitions shards to have max_shard_bytes total size.\n\n Args:\n shape: A `TensorShape`.\n dtype: A `DType`.\n\n Returns:\n A tuple representing how much to slice each axis in shape.\n\n Raises:\n ValueError: If shape is not a fully defined `TensorShape` or dtype is not\n a `DType`.\n \"\"\"\n if not isinstance(shape, tensor_shape.TensorShape):\n raise ValueError(f'shape is not a TensorShape: {shape}')\n if not shape.is_fully_defined():\n raise ValueError(f'shape is not fully defined: {shape}')\n dtype = dtypes.as_dtype(dtype)\n if dtype.base_dtype == dtypes.string:\n element_size = bytes_per_string_element\n else:\n element_size = dtype.size\n partitions = [1] * shape.ndims\n bytes_per_slice = 1.0 * (shape.num_elements() / shape.dims[axis].value) * element_size\n slices_per_shard = max(1, math.floor(max_shard_bytes / bytes_per_slice))\n axis_shards = int(math.ceil(1.0 * shape.dims[axis].value / slices_per_shard))\n if max_shards:\n axis_shards = min(max_shards, axis_shards)\n partitions[axis] = axis_shards\n return partitions\n return _partitioner", "docstring": "Get a partitioner for VariableScope to keep shards below `max_shard_bytes`.\n\n This partitioner will shard a Variable along one axis, attempting to keep\n the maximum shard size below `max_shard_bytes`. In practice, this is not\n always possible when sharding along only one axis. When this happens,\n this axis is sharded as much as possible (i.e., every dimension becomes\n a separate shard).\n\n If the partitioner hits the `max_shards` limit, then each shard may end up\n larger than `max_shard_bytes`. By default `max_shards` equals `None` and no\n limit on the number of shards is enforced.\n\n One reasonable value for `max_shard_bytes` is `(64 << 20) - 1`, or almost\n `64MB`, to keep below the protobuf byte limit.\n\nArgs:\n max_shard_bytes: The maximum size any given shard is allowed to be.\n axis: The axis to partition along. Default: outermost axis.\n bytes_per_string_element: If the `Variable` is of type string, this provides\n an estimate of how large each scalar in the `Variable` is.\n max_shards: The maximum number of shards in int created taking precedence\n over `max_shard_bytes`.\n\nReturns:\n A partition function usable as the `partitioner` argument to\n `variable_scope` and `get_variable`.\n\nRaises:\n ValueError: If any of the byte counts are non-positive.", "source": "github_repos"} +{"code": "def auto_docstring(obj=None, *, custom_intro=None, custom_args=None, checkpoint=None):\n\n def auto_docstring_decorator(obj):\n if len(obj.__qualname__.split('.')) > 1:\n return auto_method_docstring(obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint)\n else:\n return auto_class_docstring(obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint)\n if obj:\n return auto_docstring_decorator(obj)\n return auto_docstring_decorator", "docstring": "Automatically generates docstrings for classes and methods in the Transformers library.\n\n This decorator can be used in the following forms:\n @auto_docstring\n def my_function(...):\n ...\n or\n @auto_docstring()\n def my_function(...):\n ...\n or\n @auto_docstring(custom_intro=\"Custom intro\", ...)\n def my_function(...):\n ...\n\nArgs:\n custom_intro (str, optional): Custom introduction text to add to the docstring. This will replace the default\n introduction text generated by the decorator before the Args section.\n checkpoint (str, optional): Checkpoint name to use in the docstring. This should be automatically inferred from the\n model configuration class, but can be overridden if needed.", "source": "github_repos"} +{"code": "def segment_max(data, segment_ids, num_segments=None, sorted=False):\n _segment_reduce_validation(data, segment_ids)\n if any_symbolic_tensors((data,)):\n return SegmentMax(num_segments, sorted).symbolic_call(data, segment_ids)\n return backend.math.segment_max(data, segment_ids, num_segments=num_segments, sorted=sorted)", "docstring": "Computes the max of segments in a tensor.\n\nArgs:\n data: Input tensor.\n segment_ids: A N-D tensor containing segment indices for each\n element in `data`. data.shape[:len(segment_ids.shape)] should match.\n num_segments: An integer representing the total number of\n segments. If not specified, it is inferred from the maximum\n value in `segment_ids`.\n sorted: A boolean indicating whether `segment_ids` is sorted.\n Defaults to `False`.\n\nReturns:\n A tensor containing the max of segments, where each element\n represents the max of the corresponding segment in `data`.\n\nExample:\n >>> data = keras.ops.convert_to_tensor([1, 2, 10, 20, 100, 200])\n >>> segment_ids = keras.ops.convert_to_tensor([0, 0, 1, 1, 2, 2])\n >>> num_segments = 3\n >>> keras.ops.segment_max(data, segment_ids, num_segments)\n array([2, 20, 200], dtype=int32)", "source": "github_repos"} +{"code": "def _set_state_variables(self, updates):\n if not self.built:\n raise RuntimeError('_set_state_variables() must be called after build().')\n with ops.init_scope():\n for var_name, value in updates.items():\n self.state_variables[var_name].assign(value)", "docstring": "Directly update the internal state of this Layer.\n\n This method expects a string-keyed dict of {state_variable_name: state}. The\n precise nature of the state, and the names associated, are describe by\n the subclasses of CombinerPreprocessingLayer.\n\nArgs:\n updates: A string keyed dict of weights to update.\n\nRaises:\n RuntimeError: if 'build()' was not called before 'set_processing_state'.", "source": "github_repos"} +{"code": "def post_process_object_detection(self, outputs: 'Owlv2ObjectDetectionOutput', threshold: float=0.1, target_sizes: Optional[Union[TensorType, List[Tuple]]]=None):\n batch_logits, batch_boxes = (outputs.logits, outputs.pred_boxes)\n batch_size = len(batch_logits)\n if target_sizes is not None and len(target_sizes) != batch_size:\n raise ValueError('Make sure that you pass in as many target sizes as images')\n batch_class_logits = torch.max(batch_logits, dim=-1)\n batch_scores = torch.sigmoid(batch_class_logits.values)\n batch_labels = batch_class_logits.indices\n batch_boxes = center_to_corners_format(batch_boxes)\n if target_sizes is not None:\n batch_boxes = _scale_boxes(batch_boxes, target_sizes)\n results = []\n for scores, labels, boxes in zip(batch_scores, batch_labels, batch_boxes):\n keep = scores > threshold\n scores = scores[keep]\n labels = labels[keep]\n boxes = boxes[keep]\n results.append({'scores': scores, 'labels': labels, 'boxes': boxes})\n return results", "docstring": "Converts the raw output of [`Owlv2ForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,\n bottom_right_x, bottom_right_y) format.\n\nArgs:\n outputs ([`Owlv2ObjectDetectionOutput`]):\n Raw outputs of the model.\n threshold (`float`, *optional*, defaults to 0.1):\n Score threshold to keep object detection predictions.\n target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):\n Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size\n `(height, width)` of each image in the batch. If unset, predictions will not be resized.\n\nReturns:\n `List[Dict]`: A list of dictionaries, each dictionary containing the following keys:\n - \"scores\": The confidence scores for each predicted box on the image.\n - \"labels\": Indexes of the classes predicted by the model on the image.\n - \"boxes\": Image bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format.", "source": "github_repos"} +{"code": "def _ragged_tensor_apply_loss(loss_fn, y_true, y_pred, y_pred_extra_dim=False):\n\n def rt_is_equiv_dense(rt):\n \"\"\"Returns true if this RaggedTensor has the same row_lengths across\n\n all ragged dimensions and thus can be converted to a dense tensor\n without loss of information.\n\n Args:\n rt: RaggedTensor.\n \"\"\"\n return math_ops.reduce_all([math_ops.equal(math_ops.reduce_variance(math_ops.cast(row_lens, backend.floatx())), constant_op.constant([0.0])) for row_lens in rt.nested_row_lengths()])\n\n def _convert_to_dense(inputs):\n return tuple((rt.to_tensor() if isinstance(rt, ragged_tensor.RaggedTensor) else rt for rt in inputs))\n\n def _call_loss(inputs, ragged_output):\n \"\"\" Adapt the result to ragged or dense tensor according to the expected\n\n output type. This is done so that all the return values of the map\n operation have the same type.\n \"\"\"\n r = loss_fn(*inputs)\n if ragged_output and (not isinstance(r, ragged_tensor.RaggedTensor)):\n r = ragged_tensor.RaggedTensor.from_tensor(r)\n elif not ragged_output and isinstance(r, ragged_tensor.RaggedTensor):\n r = r.to_tensor()\n return r\n\n def _wrapper(inputs, ragged_output):\n _, y_pred = inputs\n if isinstance(y_pred, ragged_tensor.RaggedTensor):\n return cond.cond(rt_is_equiv_dense(y_pred), lambda: _call_loss(_convert_to_dense(inputs), ragged_output), lambda: _call_loss(inputs, ragged_output))\n return loss_fn(*inputs)\n if not isinstance(y_true, ragged_tensor.RaggedTensor):\n return loss_fn(y_true, y_pred.to_tensor())\n lshape = y_pred.shape.as_list()[1:-1]\n if len(lshape) > 0:\n spec = ragged_tensor.RaggedTensorSpec(shape=lshape, dtype=y_pred.dtype)\n else:\n spec = tensor_spec.TensorSpec(shape=[], dtype=y_pred.dtype)\n nested_splits_list = [rt.nested_row_splits for rt in (y_true, y_pred)]\n if y_pred_extra_dim:\n rdims = [len(slist) for slist in nested_splits_list]\n if rdims[0] == rdims[1] - 1:\n nested_splits_list[1] = nested_splits_list[1][:-1]\n map_fn = functools.partial(_wrapper, ragged_output=len(lshape) > 1)\n assertion_list = ragged_util.assert_splits_match(nested_splits_list)\n with ops.control_dependencies(assertion_list):\n return ragged_map_ops.map_fn(map_fn, elems=(y_true, y_pred), dtype=spec)", "docstring": "Apply a loss function on a per batch basis.\n\nArgs:\n loss_fn: The loss function\n y_true: truth values (RaggedTensor)\n y_pred: predicted values (RaggedTensor)\n y_pred_extra_dim: whether y_pred has an additional dimension compared to\n y_true\n\nReturns:\n Loss-function result. A dense tensor if the output has a single dimension\n (per-batch loss value); a ragged tensor otherwise.", "source": "github_repos"} +{"code": "def __init__(self, min_length: int, eos_token_id: int):\n if not isinstance(min_length, int) or min_length < 0:\n raise ValueError(f'`min_length` has to be a positive integer, but is {min_length}')\n if not isinstance(eos_token_id, int) or eos_token_id < 0:\n raise ValueError(f'`eos_token_id` has to be a positive integer, but is {eos_token_id}')\n self.min_length = min_length\n self.eos_token_id = eos_token_id", "docstring": "[`FlaxLogitsProcessor`] enforcing a min-length by setting EOS probability to 0.\n\nArgs:\n min_length (`int`):\n The minimum length below which the score of `eos_token_id` is set to `-float(\"Inf\")`.\n eos_token_id (`int`):\n The id of the *end-of-sequence* token.", "source": "github_repos"} +{"code": "def backend():\n return _BACKEND", "docstring": "Publicly accessible method for determining the current backend.\n\nReturns:\n String, the name of the backend Keras is currently using. One of\n `\"tensorflow\"`, `\"torch\"`, or `\"jax\"`.\n\nExample:\n >>> keras.config.backend()\n 'tensorflow'", "source": "github_repos"} +{"code": "def get_replacement_transform_for_applied_ptransform(self, applied_ptransform):\n return self.get_replacement_transform(applied_ptransform.transform)", "docstring": "Provides a runner specific override for a given `AppliedPTransform`.\n\nArgs:\n applied_ptransform: `AppliedPTransform` containing the `PTransform` to be\n replaced.\n\nReturns:\n A `PTransform` that will be the replacement for the `PTransform` inside\n the `AppliedPTransform` given as an argument.", "source": "github_repos"} +{"code": "def advise(self, options):\n advise_pb = tfprof_output_pb2.AdviceProto()\n opts = _build_advisor_options(options)\n advise_pb.ParseFromString(print_mdl.Profile('advise'.encode('utf-8'), opts.SerializeToString()))\n return advise_pb", "docstring": "Automatically detect problems and generate reports.\n\nArgs:\n options: A dict of options. See ALL_ADVICE example above.\n\nReturns:\n An Advise proto that contains the reports from all checkers.", "source": "github_repos"} +{"code": "def get_device(ads, **kwargs):\n filtered = get_devices(ads, **kwargs)\n if len(filtered) == 1:\n return filtered[0]\n else:\n serials = [ad.serial for ad in filtered]\n raise Error('More than one device matched: %s' % serials)", "docstring": "Finds a unique AndroidDevice instance from a list that has specific\n attributes of certain values.\n\nExample:\n get_device(android_devices, label='foo', phone_number='1234567890')\n get_device(android_devices, model='angler')\n\nArgs:\n ads: A list of AndroidDevice instances.\n kwargs: keyword arguments used to filter AndroidDevice instances.\n\nReturns:\n The target AndroidDevice instance.\n\nRaises:\n Error: None or more than one device is matched.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.FloatTensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, next_sentence_label: Optional[torch.LongTensor]=None, output_attentions: Optional[torch.FloatTensor]=None, output_hidden_states: Optional[torch.FloatTensor]=None, return_dict: Optional[torch.FloatTensor]=None) -> Union[Tuple, MobileBertForPreTrainingOutput]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.mobilebert(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n sequence_output, pooled_output = outputs[:2]\n prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)\n total_loss = None\n if labels is not None and next_sentence_label is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n total_loss = masked_lm_loss + next_sentence_loss\n if not return_dict:\n output = (prediction_scores, seq_relationship_score) + outputs[2:]\n return (total_loss,) + output if total_loss is not None else output\n return MobileBertForPreTrainingOutput(loss=total_loss, prediction_logits=prediction_scores, seq_relationship_logits=seq_relationship_score, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the\n loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair\n (see `input_ids` docstring) Indices should be in `[0, 1]`:\n\n - 0 indicates sequence B is a continuation of sequence A,\n - 1 indicates sequence B is a random sequence.\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, MobileBertForPreTraining\n >>> import torch\n\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google/mobilebert-uncased\")\n >>> model = MobileBertForPreTraining.from_pretrained(\"google/mobilebert-uncased\")\n\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\", add_special_tokens=True)).unsqueeze(0)\n >>> # Batch size 1\n >>> outputs = model(input_ids)\n\n >>> prediction_logits = outputs.prediction_logits\n >>> seq_relationship_logits = outputs.seq_relationship_logits\n ```", "source": "github_repos"} +{"code": "def check_models_are_tested(module: types.ModuleType, test_file: str) -> List[str]:\n defined_models = get_models(module)\n tested_models = find_tested_models(test_file)\n if tested_models is None:\n if test_file.replace(os.path.sep, '/') in TEST_FILES_WITH_NO_COMMON_TESTS:\n return\n return [f'{test_file} should define `all_model_classes` to apply common tests to the models it tests. ' + 'If this intentional, add the test filename to `TEST_FILES_WITH_NO_COMMON_TESTS` in the file ' + '`utils/check_repo.py`.']\n failures = []\n for model_name, _ in defined_models:\n if model_name not in tested_models and should_be_tested(model_name):\n failures.append(f'{model_name} is defined in {module.__name__} but is not tested in ' + f'{os.path.join(PATH_TO_TESTS, test_file)}. Add it to the all_model_classes in that file.' + 'If common tests should not applied to that model, add its name to `IGNORE_NON_TESTED`' + 'in the file `utils/check_repo.py`.')\n return failures", "docstring": "Check models defined in a module are all tested in a given file.\n\nArgs:\n module (`types.ModuleType`): The module in which we get the models.\n test_file (`str`): The path to the file where the module is tested.\n\nReturns:\n `List[str]`: The list of error messages corresponding to models not tested.", "source": "github_repos"} +{"code": "def meshgrid(*args, **kwargs):\n indexing = kwargs.pop('indexing', 'xy')\n name = kwargs.pop('name', 'meshgrid')\n if kwargs:\n key = list(kwargs.keys())[0]\n raise TypeError(\"'{}' is an invalid keyword argument for this function\".format(key))\n if indexing not in ('xy', 'ij'):\n raise ValueError(f\"Argument `indexing` parameter must be either 'xy' or 'ij', got '{indexing}'\")\n with ops.name_scope(name, 'meshgrid', args) as name:\n ndim = len(args)\n s0 = (1,) * ndim\n if not ndim:\n return []\n output = []\n for i, x in enumerate(args):\n output.append(reshape(array_ops_stack.stack(x), s0[:i] + (-1,) + s0[i + 1:]))\n shapes = [size(x) for x in args]\n output_dtype = ops.convert_to_tensor(args[0]).dtype.base_dtype\n if indexing == 'xy' and ndim > 1:\n output[0] = reshape(output[0], (1, -1) + (1,) * (ndim - 2))\n output[1] = reshape(output[1], (-1, 1) + (1,) * (ndim - 2))\n shapes[0], shapes[1] = (shapes[1], shapes[0])\n mult_fact = ones(shapes, output_dtype)\n return [x * mult_fact for x in output]", "docstring": "Broadcasts parameters for evaluation on an N-D grid.\n\n Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`\n of N-D coordinate arrays for evaluating expressions on an N-D grid.\n\nNote:\n `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.\n When the `indexing` argument is set to 'xy' (the default), the broadcasting\n instructions for the first two dimensions are swapped.\n\nExample:\n Calling `X, Y = meshgrid(x, y)` with the tensors\n\n ```python\n x = [1, 2, 3]\n y = [4, 5, 6]\n X, Y = tf.meshgrid(x, y)\n # X = [[1, 2, 3],\n # [1, 2, 3],\n # [1, 2, 3]]\n # Y = [[4, 4, 4],\n # [5, 5, 5],\n # [6, 6, 6]]\n ```\n\nArgs:\n *args: `Tensor`s with rank 1.\n **kwargs:\n - indexing: Either 'xy' or 'ij' (optional, default: 'xy').\n - name: A name for the operation (optional).\n\nReturns:\n outputs: A list of N `Tensor`s with rank N.\n\nRaises:\n TypeError: When no keyword arguments (kwargs) are passed.\n ValueError: When indexing keyword argument is not one of `xy` or `ij`.", "source": "github_repos"} +{"code": "def _add_weight(self, name, initial_value, dtype=None):\n variable = variable_v1.VariableV1(initial_value=initial_value, name=name, dtype=dtype, trainable=False, use_resource=True, synchronization=variables.VariableSynchronization.AUTO, aggregation=variables.VariableAggregation.NONE)\n if context.executing_eagerly():\n graph_key = None\n else:\n graph = ops.get_default_graph()\n graph_key = graph._graph_key\n key = (name, graph_key)\n if self._weights.get(key, None) is not None:\n raise RuntimeError('Duplicate variables detected. {}'.format(key))\n self._weights[key] = variable\n self._handle_deferred_dependencies(name=name, trackable=variable)\n return variable", "docstring": "Adds a weight to this loss scale.\n\nArgs:\n name: Variable name.\n initial_value: The variable's initial value.\n dtype: The type of the variable.\n\nReturns:\n A variable.\n\nRaises:\n RuntimeError: If a weight with `name` has already been added.", "source": "github_repos"} +{"code": "def read_saved_model(saved_model_dir):\n path_to_pbtxt = os.path.join(compat.as_bytes(saved_model_dir), compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT))\n path_to_pb = os.path.join(compat.as_bytes(saved_model_dir), compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB))\n if not file_io.file_exists(path_to_pbtxt) and (not file_io.file_exists(path_to_pb)):\n raise IOError('SavedModel file does not exist at: %s' % saved_model_dir)\n saved_model = saved_model_pb2.SavedModel()\n if file_io.file_exists(path_to_pb):\n with file_io.FileIO(path_to_pb, 'rb') as f:\n file_content = f.read()\n try:\n saved_model.ParseFromString(file_content)\n return saved_model\n except message.DecodeError as e:\n raise IOError('Cannot parse proto file %s: %s.' % (path_to_pb, str(e)))\n elif file_io.file_exists(path_to_pbtxt):\n with file_io.FileIO(path_to_pbtxt, 'rb') as f:\n file_content = f.read()\n try:\n text_format.Merge(file_content.decode('utf-8'), saved_model)\n return saved_model\n except text_format.ParseError as e:\n raise IOError('Cannot parse pbtxt file %s: %s.' % (path_to_pbtxt, str(e)))\n else:\n raise IOError('SavedModel file does not exist at: %s/{%s|%s}' % (saved_model_dir, constants.SAVED_MODEL_FILENAME_PBTXT, constants.SAVED_MODEL_FILENAME_PB))", "docstring": "Reads the saved_model.pb or saved_model.pbtxt file containing `SavedModel`.\n\nArgs:\n saved_model_dir: Directory containing the SavedModel file.\n\nReturns:\n A `SavedModel` protocol buffer.\n\nRaises:\n IOError: If the file does not exist, or cannot be successfully parsed.", "source": "github_repos"} +{"code": "def actual_actual_isda(*, start_date, end_date, schedule_info=None, dtype=None, name=None):\n del schedule_info\n with tf.name_scope(name or 'actual_actual_isda'):\n end_date = dt.convert_to_date_tensor(end_date)\n start_date = dt.convert_to_date_tensor(start_date)\n dtype = dtype or tf.float32\n days_in_leap_years, days_in_nonleap_years = du.days_in_leap_and_nonleap_years_between(start_date, end_date)\n days_in_leap_years = tf.cast(days_in_leap_years, dtype=dtype)\n days_in_nonleap_years = tf.cast(days_in_nonleap_years, dtype=dtype)\n return days_in_leap_years / 366 + days_in_nonleap_years / 365", "docstring": "Computes the year fraction between the specified dates.\n\n Computes the year fraction between the dates by dividing the actual number of\n days in a leap year by 366 and the actual number of days in a standard year by\n 365.\n\n When determining whether a leap day is contained in the date range,\n 'start_date' is excluded and 'end_date' is included.\n\n Note that the schedule info is not needed for this convention and is ignored\n if supplied.\n\n https://en.wikipedia.org/wiki/Day_count_convention#Actual/Actual_ISDA\n\nArgs:\n start_date: A `DateTensor` object of any shape.\n end_date: A `DateTensor` object of compatible shape with `start_date`.\n schedule_info: The schedule info. Ignored for this convention.\n dtype: The dtype of the result. Either `tf.float32` or `tf.float64`. If not\n supplied, `tf.float32` is returned.\n name: Python `str` name prefixed to ops created by this function. If not\n supplied, `actual_actual_isda` is used.\n\nReturns:\n A real `Tensor` of supplied `dtype` and shape of `start_date`. The year\n fraction between the start and end date as computed by Actual/Actual ISDA\n convention.", "source": "github_repos"} +{"code": "def __init__(self, cardinalities: List[int], embedding_dims: List[int]) -> None:\n super().__init__()\n self.num_features = len(cardinalities)\n self.embedders = nn.ModuleList([nn.Embedding(c, d) for c, d in zip(cardinalities, embedding_dims)])", "docstring": "Embed a sequence of categorical features.\n\nArgs:\n cardinalities (`list[int]`):\n List of cardinalities of the categorical features.\n embedding_dims (`list[int]`):\n List of embedding dimensions of the categorical features.", "source": "github_repos"} +{"code": "def __init__(self, key_dtype, value_dtype):\n self._key_dtype = dtypes.as_dtype(key_dtype)\n self._value_dtype = dtypes.as_dtype(value_dtype)", "docstring": "Construct a table initializer object.\n\nArgs:\n key_dtype: Type of the table keys.\n value_dtype: Type of the table values.", "source": "github_repos"} +{"code": "def GetShadowMap(self, since=None):\n return ShadowUpdateGetter(self.conf).GetUpdates(source=self, search_base=self.conf['base'], search_filter=self.conf['filter'], search_scope=self.conf['scope'], since=since)", "docstring": "Return the shadow map from this source.\n\nArgs:\n since: Get data only changed since this timestamp (inclusive) or None\n for all data.\n\nReturns:\n instance of ShadowMap", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.FloatTensor]=None, head_mask: Optional[torch.FloatTensor]=None, past_key_values: Optional[Union[List[torch.FloatTensor], Cache]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, start_positions: Optional[torch.LongTensor]=None, end_positions: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, position_ids: Optional[torch.LongTensor]=None) -> Union[Tuple, QuestionAnsweringModelOutput]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n transformer_outputs = self.model(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n hidden_states = transformer_outputs[0]\n logits = self.qa_outputs(hidden_states)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n total_loss = None\n if start_positions is not None and end_positions is not None:\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index).to(logits.device)\n end_positions = end_positions.clamp(0, ignored_index).to(logits.device)\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n if not return_dict:\n output = (start_logits, end_logits) + transformer_outputs[2:]\n return (total_loss,) + output if total_loss is not None else output\n return QuestionAnsweringModelOutput(loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)", "docstring": "Example:\n\n ```python\n >>> from transformers import AutoTokenizer, OPTForQuestionAnswering\n >>> import torch\n\n >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/opt-350m\")\n\n >>> # note: we are loading a OPTForQuestionAnswering from the hub here,\n >>> # so the head will be randomly initialized, hence the predictions will be random\n >>> model = OPTForQuestionAnswering.from_pretrained(\"facebook/opt-350m\")\n\n >>> question, text = \"Who was Jim Henson?\", \"Jim Henson was a nice puppet\"\n\n >>> inputs = tokenizer(question, text, return_tensors=\"pt\")\n >>> with torch.no_grad():\n ... outputs = model(**inputs)\n\n >>> answer_start_index = outputs.start_logits.argmax()\n >>> answer_end_index = outputs.end_logits.argmax()\n\n >>> answer_offset = len(tokenizer(question)[0])\n\n >>> predict_answer_tokens = inputs.input_ids[\n ... 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1\n ... ]\n >>> predicted = tokenizer.decode(predict_answer_tokens)\n >>> predicted\n ' a nice puppet'\n ```", "source": "github_repos"} +{"code": "def test_batch_sample_paths_2d(self, batch_rank):\n dtype = tf.float64\n mu = np.array([0.2, 0.7])\n a = np.array([[0.4, 0.1], [0.3, 0.2]])\n b = np.array([[0.33, -0.03], [0.21, 0.5]])\n\n def drift_fn(t, x):\n return mu * tf.sqrt(t) * tf.ones_like(x, dtype=t.dtype)\n\n def vol_fn(t, x):\n return (a * t + b) * tf.ones(x.shape.as_list() + [2], dtype=t.dtype)\n process = tff.models.GenericItoProcess(dim=2, drift_fn=drift_fn, volatility_fn=vol_fn, dtype=dtype)\n times = np.array([0.1, 0.21, 0.32, 0.43, 0.55])\n x0 = np.array([0.1, -1.1]) * np.ones([2] * batch_rank + [1, 2])\n times_grid = None\n time_step = 0.01\n num_samples = 10000\n normal_draws = None\n paths = self.evaluate(process.sample_paths(times, num_samples=num_samples, initial_state=x0, time_step=time_step, times_grid=times_grid, normal_draws=normal_draws, seed=12134))\n num_samples = 10000\n self.assertAllClose(list(paths.shape), [2] * batch_rank + [num_samples, 5, 2], atol=0)\n means = np.mean(paths, axis=batch_rank)\n times = np.reshape(times, [1] * batch_rank + [-1, 1])\n expected_means = np.reshape(x0, [2] * batch_rank + [1, 2]) + 2.0 / 3.0 * mu * np.power(times, 1.5)\n self.assertAllClose(means, expected_means, rtol=0.01, atol=0.01)", "docstring": "Tests path properties for a batch of 2-dimentional Ito process.\n\n We construct the following Ito processes.\n\n dX_1 = mu_1 sqrt(t) dt + s11 dW_1 + s12 dW_2\n dX_2 = mu_2 sqrt(t) dt + s21 dW_1 + s22 dW_2\n\n mu_1, mu_2 are constants.\n s_ij = a_ij t + b_ij\n\n For this process expected value at time t is (x_0)_i + 2/3 * mu_i * t^1.5.\n\nArgs:\n batch_rank: The rank of the batch of processes being simulated.", "source": "github_repos"} +{"code": "def __init__(self, modules: Sequence[RelativePositionBiasBase]):\n super().__init__()\n self.biases = nn.ModuleList(modules)", "docstring": "Class which sums up various computed biases.\n\nArgs:\n modules (Sequence[RelativePositionBiasBase]):\n List of relative bias modules.", "source": "github_repos"} +{"code": "def patch_on_type(src: symbolic.Symbolic, value_type: Union[Type[Any], Tuple[Type[Any], ...]], value: Any=None, value_fn: Optional[Callable[[Any], Any]]=None, skip_notification: Optional[bool]=None) -> Any:\n return _conditional_patch(src, lambda k, v, p: isinstance(v, value_type), value, value_fn, skip_notification)", "docstring": "Recursively patch values on matched types.\n\n Example::\n\n d = pg.Dict(a={'x': 1}, b=2)\n print(pg.patching.patch_on_type(d, int, value_fn=lambda x: x * 2))\n # {a={x=2}, b=4}\n\nArgs:\n src: symbolic value to patch.\n value_type: Value type to match.\n value: New value for field that satisfy `condition`.\n value_fn: Callable object that produces new value based on old value.\n If not None, `value` must be None.\n skip_notification: If True, `on_change` event will not be triggered for this\n operation. If None, the behavior is decided by `pg.notify_on_rebind`.\n Please see `symbolic.Symbolic.rebind` for details.\n\nReturns:\n `src` after being patched.", "source": "github_repos"} +{"code": "def __init__(self, alpha=1.0, **kwargs):\n super(ELU, self).__init__(**kwargs)\n if alpha is None:\n raise ValueError('Alpha of an ELU layer cannot be None, requires a float. Got %s' % alpha)\n self.supports_masking = True\n self.alpha = backend.cast_to_floatx(alpha)", "docstring": "Exponential Linear Unit.\n\n It follows:\n\n ```\n f(x) = alpha * (exp(x) - 1.) for x < 0\n f(x) = x for x >= 0\n ```\n\n Input shape:\n Arbitrary. Use the keyword argument `input_shape`\n (tuple of integers, does not include the samples axis)\n when using this layer as the first layer in a model.\n\n Output shape:\n Same shape as the input.\n\nArgs:\n alpha: Scale for the negative factor.", "source": "github_repos"} +{"code": "def recipe_dcm_to_bigquery(config, auth_read, auth_write, account, report_id, report_name, dataset, table, is_incremental_load):\n dcm(config, {'auth': auth_read, 'report': {'account': account, 'report_id': report_id, 'name': report_name}, 'out': {'bigquery': {'auth': auth_write, 'dataset': dataset, 'table': table, 'header': True, 'is_incremental_load': is_incremental_load}}})", "docstring": "Move existing CM report into a BigQuery table.\n\nArgs:\n auth_read (authentication) - Credentials used for reading data.\n auth_write (authentication) - Credentials used for writing data.\n account (integer) - CM network id.\n report_id (integer) - CM report id, empty if using name .\n report_name (string) - CM report name, empty if using id instead.\n dataset (string) - Dataset to be written to in BigQuery.\n table (string) - Table to be written to in BigQuery.\n is_incremental_load (boolean) - Clear data in destination table during this report's time period, then append report data to existing table.", "source": "github_repos"} +{"code": "def filter_tensor(value: types.IntTensor, bit_mask: types.IntTensor, bit_index: types.IntTensor) -> types.IntTensor:\n is_bit_set = tf.equal(tf.cast(1, value.dtype), tf.bitwise.bitwise_and(tf.bitwise.right_shift(bit_mask, bit_index), tf.cast(1, value.dtype)))\n return tf.where(is_bit_set, value, 0)", "docstring": "Filters an input `Tensor` based on bits set in a mask `Tensor`.\n\n #### Examples\n\n ```python\n import tensorflow as tf\n import tf_quant_finance as tff\n\n # Example: Filtering a given vector based on a mask.\n\n tff.math.qmc.utils.filter_tensor(\n tf.constant([5, 6, 7, 8]),\n tf.constant([1, 2, 3, 4]),\n tf.constant([1, 1, 2, 2]))\n # ==> tf.Tensor([0, 6, 0, 8], shape=(4,), dtype=int32)\n ```\n\nArgs:\n value: Scalar `Tensor` of integers.\n bit_mask: Positive scalar `Tensor` of integers with the same `shape` and\n `dtype` as `value`.\n bit_index: Positive scalar `Tensor` of integers with the same `shape` and\n `dtype` as `value`.\n\nReturns:\n `Tensor` with the same `shape` as `value` equal to `value` if the\n `bit_index`-th bit in `LSB 0` order is set in `bit_mask`, or `zero`\n otherwise i.e.: `value * (1 & (bit_mask >>> bit_index))`", "source": "github_repos"} +{"code": "def __init__(self, primals, tangents):\n self._accumulator = pywrap_tfe.TFE_Py_ForwardAccumulatorNew(False)\n self._recording = False\n primal_ids = set()\n for primal in nest.flatten(primals):\n if id(primal) in primal_ids:\n raise ValueError('Tensor {} was specified as a primal multiple times. This may indicate an error. If it was intended, please sum the corresponding tangents.')\n primal_ids.add(id(primal))\n self._watch(primals, tangents)", "docstring": "Specify tensors to watch and their Jacobian-vector products.\n\n Mathematically, `tangents` is a vector right-multiplying the Jacobian matrix\n (a Jacobian-vector product) for the function computed while this accumulator\n is active. Since JVPs are computed in forward mode as the computation\n happens, this vector must be supplied in advance.\n\n Listing a single tensor multiple times in `primals` raises an\n exception. Excluding a tensor from `primals` is equivalent to watching it\n with a tangent tensor of zeros.\n\nArgs:\n primals: A tensor or nested structure of tensors to watch.\n tangents: A tensor or nested structure of tensors, with the same nesting\n structure as `primals`, with each element being a vector with the same\n size as the corresponding primal element.\n\nRaises:\n ValueError: If the same tensor or variable is specified multiple times in\n `primals`.", "source": "github_repos"} +{"code": "def check(self, src, expected=None, prologue=None, name=None, version=None, platform='linux'):\n ast = self.parse(src, name, version, platform)\n actual = pytd_utils.Print(ast)\n if expected != IGNORE:\n if expected is None:\n expected = src\n expected = textwrap.dedent(expected).lstrip()\n if prologue:\n expected = f'{textwrap.dedent(prologue)}\\n\\n{expected}'\n self.assertMultiLineEqual(expected.rstrip(), actual)\n return ast", "docstring": "Check the parsing of src.\n\n This checks that parsing the source and then printing the resulting\n AST results in the expected text.\n\nArgs:\n src: A source string.\n expected: Optional expected result string. If not provided, src is used\n instead. The special value IGNORE can be used to skip checking the\n parsed results against expected text.\n prologue: An optional prologue to be prepended to the expected text before\n comparison. Useful for imports that are introduced during printing the\n AST.\n name: The name of the module.\n version: A python version tuple (None for default value).\n platform: A platform string (defaults to \"linux\").\n\nReturns:\n The parsed pytd.TypeDeclUnit.", "source": "github_repos"} +{"code": "def get_image(width, height, want_grayscale, filepath):\n with ops.Graph().as_default():\n with session.Session():\n file_data = io_ops.read_file(filepath)\n channels = 1 if want_grayscale else 3\n image_tensor = image_ops.decode_image(file_data, channels=channels).eval()\n resized_tensor = image_ops.resize_images_v2(image_tensor, (height, width)).eval()\n return resized_tensor", "docstring": "Returns an image loaded into an np.ndarray with dims [height, width, (3 or 1)].\n\nArgs:\n width: Width to rescale the image to.\n height: Height to rescale the image to.\n want_grayscale: Whether the result should be converted to grayscale.\n filepath: Path of the image file..\n\nReturns:\n np.ndarray of shape (height, width, channels) where channels is 1 if\n want_grayscale is true, otherwise 3.", "source": "github_repos"} +{"code": "def check_server_proc_running(self):", "docstring": "Checks whether the server is still running.\n\n If the server is not running, it throws an error. As this function is called\n each time the client tries to send an RPC, this should be a quick check\n without affecting performance. Otherwise it is fine to not check anything.\n\nRaises:\n errors.ServerDiedError: if the server died.", "source": "github_repos"} +{"code": "def extensions(self, prefix: str):\n prefix_node = self._get_node(prefix)\n ret = self._collect_tokens(prefix_node)\n return [prefix + token for token in ret]", "docstring": "Generates all extensions of a given prefix token in the Trie.\n\nExample:\n ```python\n >>> trie = Trie()\n >>> trie.add(\"apple\")\n >>> trie.add(\"app\")\n >>> trie.add(\"application\")\n >>> trie.extensions(\"app\")\n ['app', 'apple', 'application']\n ```", "source": "github_repos"} +{"code": "def set_number_of_shards(self, number_of_shards):\n for policy in self._sharding_policies:\n policy.set_number_of_shards(number_of_shards)\n policy.set_number_of_partitions(self._number_of_partitions)\n self._validate()", "docstring": "Sets the number of shards to use for the InfeedQueue.\n\nArgs:\n number_of_shards: number of ways to shard the InfeedQueue.\n\nRaises:\n ValueError: if number_of_shards is not > 0; or the policies have\n been frozen and number_of_shards was already set to something\n else.", "source": "github_repos"} +{"code": "def show_backref(target, max_depth=3):\n if objgraph is None:\n raise NotImplementedError('objgraph is not installed.')\n string_io = io.StringIO()\n objgraph.show_backrefs(target, max_depth=max_depth, output=string_io)\n graph = string_io.getvalue()\n string_io.close()\n return graph", "docstring": "Returns a dot graph of all the objects that are referencing the target.\n\n A object referencing graph is useful to debug memory leak like circular\n reference. objgraph provides a good visualization of the memory graph than\n most python built-in utilities like gc.get_referrers(), which are not\n human-readable sometimes.\n\n The dot graph will be written to a string IO object, and can be rendered with\n graphviz in operating system.\n E.g. dot -Tpng {$dot_graph} -o output.png\n\nArgs:\n target: The target object for the memory graph.\n max_depth: The maximum depth of the graph. By default 3 layers of references\n are used. Increases this a lot may result in the graph growing too big.\n\nReturns:\n A string that contains the object reference graph.\n\nRaises:\n NotImplementedError: if objgraph is not installed.", "source": "github_repos"} +{"code": "def get_auto_remove_tmp_dir(self, tmp_dir=None, before=None, after=None):\n if tmp_dir is not None:\n if before is None:\n before = True\n if after is None:\n after = False\n path = Path(tmp_dir).resolve()\n if not tmp_dir.startswith('./'):\n raise ValueError(f'`tmp_dir` can only be a relative path, i.e. `./some/path`, but received `{tmp_dir}`')\n if before is True and path.exists():\n shutil.rmtree(tmp_dir, ignore_errors=True)\n path.mkdir(parents=True, exist_ok=True)\n else:\n if before is None:\n before = True\n if after is None:\n after = True\n tmp_dir = tempfile.mkdtemp()\n if after is True:\n self.teardown_tmp_dirs.append(tmp_dir)\n return tmp_dir", "docstring": "Args:\n tmp_dir (`string`, *optional*):\n if `None`:\n\n - a unique temporary path will be created\n - sets `before=True` if `before` is `None`\n - sets `after=True` if `after` is `None`\n else:\n\n - `tmp_dir` will be created\n - sets `before=True` if `before` is `None`\n - sets `after=False` if `after` is `None`\n before (`bool`, *optional*):\n If `True` and the `tmp_dir` already exists, make sure to empty it right away if `False` and the\n `tmp_dir` already exists, any existing files will remain there.\n after (`bool`, *optional*):\n If `True`, delete the `tmp_dir` at the end of the test if `False`, leave the `tmp_dir` and its contents\n intact at the end of the test.\n\nReturns:\n tmp_dir(`string`): either the same value as passed via *tmp_dir* or the path to the auto-selected tmp dir", "source": "github_repos"} +{"code": "def generate_typegraph(program: cfg.Program, var_table: dict[int, str], loader: jinja2.BaseLoader) -> str:\n encoder = typegraph_serializer.TypegraphEncoder()\n enc_prog = encoder.default(program)\n return _generate_visualization(template_file=_TYPEGRAPH_TEMPLATE_NAME, loader=loader, program=json.dumps(enc_prog), query_table=enc_prog['queries'], var_table=var_table)", "docstring": "Generate the visualization webpage.\n\nArgs:\n program: cfg.Program. The instance of the program to visualize.\n var_table: dict[int, str]. A mapping of cfg.Variable IDs to names.\n loader: A jinja2 loader\n\nReturns:\n str. The rendered visualization page.", "source": "github_repos"} +{"code": "def _jvp_helper_wrapper(op_name, attr_tuple, inputs, outputs, tangents, use_batch):\n if use_batch:\n for primal, tangent in zip(inputs, tangents):\n if not tangent.shape.is_compatible_with([None] + primal.shape):\n raise ValueError('Tangent {} was expected to be of shape {} but is instead of shape {}'.format(tangent, [None] + primal.shape, tangent.shape))\n return control_flow_ops.vectorized_map(functools.partial(_jvp_helper, op_name, attr_tuple, inputs, outputs), tangents)\n return _jvp_helper(op_name, attr_tuple, inputs, outputs, tangents)", "docstring": "Computes a batch of Jacobian-vector product for an op.\n\nArgs:\n op_name: A string, the type of operation being executed.\n attr_tuple: Attributes of the operation.\n inputs: A flat list of input Tensors to the operation.\n outputs: A flat list of output Tensors from the operation.\n tangents: A flat list of Tensors, compatible with shape `[None] +\n input_shape`.\n use_batch: A bool, True to vetorize over batch of tangents of shape `[None]\n + input_shape`.\n\nReturns:\n A flat list of tangents compatible with `outputs`\n or `[None] + output_shape`.\n\nRaises:\n ValueError: if tangent shapes are not compatible with input shapes.", "source": "github_repos"} +{"code": "def _process_new(self, feed_item):\n lp = self.landing_page_dao.get(feed_item, required=True)\n feed_item[FieldMap.CAMPAIGN_LANDING_PAGE_ID] = lp['id']\n feed_item[FieldMap.CAMPAIGN_LANDING_PAGE_NAME] = lp['name']\n return {'advertiserId': feed_item.get(FieldMap.ADVERTISER_ID, None), 'name': feed_item.get(FieldMap.CAMPAIGN_NAME, None), 'startDate': StringExtensions.convertDateTimeStrToDateStr(feed_item.get(FieldMap.CAMPAIGN_START_DATE, None)), 'endDate': StringExtensions.convertDateTimeStrToDateStr(feed_item.get(FieldMap.CAMPAIGN_END_DATE, None)), 'defaultLandingPageId': lp['id']}", "docstring": "Creates a new campaign DCM object from a feed item representing a campaign from the Bulkdozer feed.\n\n This function simply creates the object to be inserted later by the BaseDAO\n object.\n\nArgs:\n feed_item: Feed item representing the campaign from the Bulkdozer feed.\n\nReturns:\n A campaign object ready to be inserted in DCM through the API.", "source": "github_repos"} +{"code": "def __init__(self, name):\n stl.base.ParameterizedObject.__init__(self, name)\n self.expand = None", "docstring": "User defined events.\n\n A user defined event must be an expression of a external event with arguments.\n For example,\n\n event eUserDefinedEvent = eBuiltInEvent(arg1, arg2);\n\n It provides all information to turn event.EventInTransition into\n stl.base.Func.\n\nAttributes:\n expand: Expression to expand to a resolved event, stl.base.Func.", "source": "github_repos"} +{"code": "def expand(self, pcoll: beam.PCollection[Union[beam.Row, NamedTuple]]) -> beam.PCollection[common_types.InstanceDictType]:\n return pcoll | beam.Map(lambda x: x._asdict())", "docstring": "Args:\n pcoll: A PCollection of NamedTuples or Rows.\n\nReturns:\n A PCollection of dictionaries.", "source": "github_repos"} +{"code": "def pad_image(self, image: np.ndarray, size: Dict[str, int], random_padding: bool=False, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:\n output_height, output_width = (size['height'], size['width'])\n input_height, input_width = get_image_size(image, channel_dim=input_data_format)\n delta_width = output_width - input_width\n delta_height = output_height - input_height\n if random_padding:\n pad_top = np.random.randint(low=0, high=delta_height + 1)\n pad_left = np.random.randint(low=0, high=delta_width + 1)\n else:\n pad_top = delta_height // 2\n pad_left = delta_width // 2\n pad_bottom = delta_height - pad_top\n pad_right = delta_width - pad_left\n padding = ((pad_top, pad_bottom), (pad_left, pad_right))\n return pad(image, padding, data_format=data_format, input_data_format=input_data_format)", "docstring": "Pad the image to the specified size.\n\nArgs:\n image (`np.ndarray`):\n The image to be padded.\n size (`Dict[str, int]`):\n The size `{\"height\": h, \"width\": w}` to pad the image to.\n random_padding (`bool`, *optional*, defaults to `False`):\n Whether to use random padding or not.\n data_format (`str` or `ChannelDimension`, *optional*):\n The data format of the output image. If unset, the same format as the input image is used.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.", "source": "github_repos"} +{"code": "def __init__(self, bytes_per_pack=0, timeout_seconds=None):\n \"\"\"Creates a CollectiveHints.\n\nArgs:\n bytes_per_pack: a non-negative integer. Breaks collective operations into\n packs of certain size. If it's zero, the value is determined\n automatically. This only applies to all-reduce with\n `MultiWorkerMirroredStrategy` currently.\n timeout_seconds: a float or None, timeout in seconds. If not None, the\n collective raises `tf.errors.DeadlineExceededError` if it takes longer\n than this timeout. This can be useful when debugging hanging issues.\n This should only be used for debugging since it creates a new thread for\n each collective, i.e. an overhead of `timeout_seconds *\n num_collectives_per_second` more threads. This only works for\n `tf.distribute.experimental.MultiWorkerMirroredStrategy`.\n\nRaises:\n ValueError: When arguments have invalid value.\n\"\"\"\n pass", "docstring": "Hints for collective operations like AllReduce.\n\n This can be passed to methods like\n `tf.distribute.get_replica_context().all_reduce()` to optimize collective\n operation performance. Note that these are only hints, which may or may not\n change the actual behavior. Some options only apply to certain strategy and\n are ignored by others.\n\n One common optimization is to break gradients all-reduce into multiple packs\n so that weight updates can overlap with gradient all-reduce.\n\nExample:\n - bytes_per_pack\n\n ```python\n hints = tf.distribute.experimental.CollectiveHints(\n bytes_per_pack=50 * 1024 * 1024)\n grads = tf.distribute.get_replica_context().all_reduce(\n 'sum', grads, experimental_hints=hints)\n optimizer.apply_gradients(zip(grads, vars),\n experimental_aggregate_gradients=False)\n ```\n\n - timeout_seconds\n\n ```python\n strategy = tf.distribute.MirroredStrategy()\n hints = tf.distribute.experimental.CollectiveHints(\n timeout_seconds=120.0)\n try:\n strategy.reduce(\"sum\", v, axis=None, experimental_hints=hints)\n except tf.errors.DeadlineExceededError:\n do_something()\n ```", "source": "github_repos"} +{"code": "def __init__(self, count_mode='samples', stateful_metrics=None):\n super(ProgbarLogger, self).__init__()\n self._supports_tf_logs = True\n if count_mode == 'samples':\n self.use_steps = False\n elif count_mode == 'steps':\n self.use_steps = True\n else:\n raise ValueError('Unknown `count_mode`: ' + str(count_mode))\n self.stateful_metrics = set(stateful_metrics) if stateful_metrics else set()\n self.seen = 0\n self.progbar = None\n self.target = None\n self.verbose = 1\n self.epochs = 1\n self._train_step, self._test_step, self._predict_step = (None, None, None)\n self._call_batch_hooks = True\n self._called_in_fit = False", "docstring": "Callback that prints metrics to stdout.\n\nArgs:\n count_mode: One of `\"steps\"` or `\"samples\"`.\n Whether the progress bar should\n count samples seen or steps (batches) seen.\n stateful_metrics: Iterable of string names of metrics that\n should *not* be averaged over an epoch.\n Metrics in this list will be logged as-is.\n All others will be averaged over time (e.g. loss, etc).\n If not provided, defaults to the `Model`'s metrics.\n\nRaises:\n ValueError: In case of invalid `count_mode`.", "source": "github_repos"} +{"code": "def binomial(self, shape, counts, probs, dtype=dtypes.int32, name=None):\n dtype = dtypes.as_dtype(dtype)\n with ops.name_scope(name, 'binomial', [shape, counts, probs]) as name:\n counts = ops.convert_to_tensor(counts, name='counts')\n probs = ops.convert_to_tensor(probs, name='probs')\n shape_tensor = _shape_tensor(shape)\n return gen_stateful_random_ops.stateful_random_binomial(self.state.handle, self.algorithm, shape=shape_tensor, counts=counts, probs=probs, dtype=dtype, name=name)", "docstring": "Outputs random values from a binomial distribution.\n\n The generated values follow a binomial distribution with specified count and\n probability of success parameters.\n\nExample:\n ```python\n counts = [10., 20.]\n # Probability of success.\n probs = [0.8]\n\n rng = tf.random.Generator.from_seed(seed=234)\n binomial_samples = rng.binomial(shape=[2], counts=counts, probs=probs)\n\n\n counts = ... # Shape [3, 1, 2]\n probs = ... # Shape [1, 4, 2]\n shape = [3, 4, 3, 4, 2]\n rng = tf.random.Generator.from_seed(seed=1717)\n # Sample shape will be [3, 4, 3, 4, 2]\n binomial_samples = rng.binomial(shape=shape, counts=counts, probs=probs)\n ```\n\nArgs:\n shape: A 1-D integer Tensor or Python array. The shape of the output\n tensor.\n counts: Tensor. The counts of the binomial distribution. Must be\n broadcastable with `probs`, and broadcastable with the rightmost\n dimensions of `shape`.\n probs: Tensor. The probability of success for the\n binomial distribution. Must be broadcastable with `counts` and\n broadcastable with the rightmost dimensions of `shape`.\n dtype: The type of the output. Default: tf.int32\n name: A name for the operation (optional).\n\nReturns:\n samples: A Tensor of the specified shape filled with random binomial\n values. For each i, each samples[i, ...] is an independent draw from\n the binomial distribution on counts[i] trials with probability of\n success probs[i].", "source": "github_repos"} +{"code": "def __init__(self, input_resolution: Tuple[int], dim: int, norm_layer: nn.Module=nn.LayerNorm) -> None:\n super().__init__()\n self.input_resolution = input_resolution\n self.dim = dim\n self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)\n self.norm = norm_layer(4 * dim)", "docstring": "Patch Merging Layer.\n\nArgs:\n input_resolution (`Tuple[int]`):\n Resolution of input feature.\n dim (`int`):\n Number of input channels.\n norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):\n Normalization layer class.", "source": "github_repos"} +{"code": "def make(self, path, metadata=None):\n self.current_shard_filenames = []\n if self.h5_file is not None:\n self.current_shard_filenames.append(pathlib.Path(self.h5_file.filename).name)\n return super().make(path, metadata)", "docstring": "Make a new H5 entry group.\n\n This method is only available in write mode. It defers the creation of\n the H5 entry group until `__setitem__` is called, preventing the\n creation of empty groups.\n\n The information about the current shard is reset.\n\nArgs:\n path: `str`. The variable path.\n metadata: Optional `dict`. The metadata to save with the H5 entry\n group. Defaults to `None`.", "source": "github_repos"} +{"code": "def check_termination(self) -> None:\n if self._is_thread_joined:\n if self.is_alive():\n raise RuntimeError('Thread was not joined with main thread, and is still running when the test finished.')\n else:\n self._testcase.fail('A checked thread was not joined.')", "docstring": "Returns whether the checked thread was properly used and did terminate.\n\n Every checked thread should be \"join\"ed after starting, and before the\n test tears down. If it is not joined, it is possible the thread will hang\n and cause flaky failures in tests.\n\nRaises:\n self._testcase.failureException: If check_termination was called before\n thread was joined.\n\n RuntimeError: If the thread is not terminated. This means thread was not\n joined with the main thread.", "source": "github_repos"} +{"code": "def __init__(self, trainer_id):\n if not trainer_id:\n raise ValueError('tf.data service cross-trainer cache requires a non-empty trainer ID.')\n self.trainer_id = trainer_id", "docstring": "Constructs a CrossTrainerCache.\n\nArgs:\n trainer_id: Each training job has a unique ID. Once a job has consumed\n data, the data remains in the cache and is re-used by jobs with different\n `trainer_id`s. Requests with the same `trainer_id` do not re-use data.\n\nRaises:\n ValueError if `trainer_id` is empty.", "source": "github_repos"} +{"code": "def npmfile_containing(file_contents: Sequence[Tuple[str, str]]):\n with tempfile.NamedTemporaryFile(suffix='.tgz') as temp_file:\n with tarfile.open(fileobj=temp_file, mode='w:gz') as tar_file:\n for file_name, contents in file_contents:\n info = tarfile.TarInfo(name=f'package/{file_name}')\n info.size = len(contents)\n tar_file.addfile(tarinfo=info, fileobj=io.BytesIO(contents.encode('utf-8')))\n temp_file.flush()\n yield temp_file", "docstring": "Builds a temp file containing a NPM .tar.gz file with the given contents.\n\nArgs:\n file_contents: Sequence of (file_name, file_contents) tuples to be written\n to the NPM file.\n\nYields:\n A tempfile.NamedTemporaryFile for the written zip file.", "source": "github_repos"} +{"code": "def _get_ops_from_nodedefs(node_defs):\n ops = set()\n for node_def in node_defs:\n op_and_kernel = get_ops_from_nodedef(node_def)\n if op_and_kernel:\n ops.add(op_and_kernel)\n return ops", "docstring": "Gets the ops and kernels needed from the list of NodeDef.\n\n If a NodeDef's op is not in the allowlist of ops without kernel and there is\n no kernel found for this NodeDef, then skip that NodeDef and proceed to the\n next one.\n\nArgs:\n node_defs: list of NodeDef's to get op/kernel information.\n\nReturns:\n A set of (op_name, kernel_name) tuples.", "source": "github_repos"} +{"code": "def _all_reduce(self, reduce_op, value, replica_id, options):\n raise NotImplementedError('_all_reduce must be implemented in descendants.')", "docstring": "All-reduce the `value` across all replicas so that all get the result.\n\n `value` can be a nested structure of tensors or `IndexedSlices`. The\n implementation should generally batch the all-reduces when possible.\n `options` can be set to hint the batching behavior.\n\n This API must be called in a replica context.\n\nArgs:\n reduce_op: A `tf.distribute.ReduceOp` value specifying how values should\n be combined.\n value: Value to be reduced. A tensor or a nested structure of tensors or\n `IndexedSlices`.\n replica_id: An integer indicating the id of the replica where this\n all_reduce is called under. This is the local replica id that ranges\n from 0 to len(local_devices) - 1.\n options: A `tf.distribute.experimental.CommunicationOptions`.\n\nReturns:\n A tensor/IndexedSlices or a nested structure of tensors/IndexedSlices with\n the reduced values. The structure is the same as `value`.", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, layer_head_mask: torch.Tensor, output_attentions: bool=False, output_router_logits: bool=False) -> torch.Tensor:\n residual = hidden_states\n hidden_states = self.self_attn_layer_norm(hidden_states)\n hidden_states, attn_weights, _ = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask, output_attentions=output_attentions)\n hidden_states = self.attn_dropout(hidden_states)\n hidden_states = residual + hidden_states\n residual = hidden_states\n hidden_states = self.ff_layer_norm(hidden_states)\n if self.is_sparse:\n hidden_states, router_states = self.ffn(hidden_states, attention_mask)\n else:\n hidden_states, router_states = (self.ffn(hidden_states), None)\n hidden_states = self.ff_dropout(hidden_states)\n hidden_states = residual + hidden_states\n if hidden_states.dtype == torch.float16 and (torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()):\n clamp_value = torch.finfo(hidden_states.dtype).max - 1000\n hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)\n outputs = (hidden_states,)\n if output_attentions:\n outputs += (attn_weights,)\n if output_router_logits:\n outputs += (router_states,)\n return outputs", "docstring": "Args:\n hidden_states (`torch.FloatTensor`):\n input to the layer of shape `(batch, seq_len, embed_dim)`\n attention_mask (`torch.FloatTensor`):\n attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very\n large negative values.\n layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size\n `(encoder_attention_heads,)`.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.", "source": "github_repos"} +{"code": "def get_fhir_extensions(msg: message.Message) -> List[message.Message]:\n extension_field = msg.DESCRIPTOR.fields_by_name.get('extension')\n if extension_field is None:\n raise ValueError(f'Message of type {msg.DESCRIPTOR.name} does not have an extension attribute.')\n return proto_utils.get_value_at_field(msg, extension_field)", "docstring": "Returns a list of FHIR extensions from the provided FHIR primitive.\n\nArgs:\n msg: The Message to extract FHIR extensions from.\n\nReturns:\n A list of Extension values found on the instance.\n\nRaises:\n ValueError: If the provided FHIR primitive doesn't have an extension\n attribute.", "source": "github_repos"} +{"code": "def _get_scope(node_name):\n if not node_name:\n raise ValueError(f'Node name cannot be empty or None. Received: {node_name}.')\n if node_name.startswith('^'):\n node_name = node_name[1:]\n if '/' in node_name:\n scope, _ = node_name.rsplit('/', 1)\n return scope\n return ''", "docstring": "Extract the scope name from a node name.\n\n The scope name is everything before the final slash,\n not including any ^ prefix denoting a control dependency.\n\nArgs:\n node_name: the full name of an Op or a Tensor in the graph.\n\nReturns:\n The deepest named scope containing the node.\n\nRaises:\n ValueError: if tensor_name is None or empty", "source": "github_repos"} +{"code": "def split(self, text: str) -> list[str]:\n states = OrderedDict()\n offsets = [0]\n skip = 0\n for current, current_char in enumerate(text):\n if skip and current < skip:\n continue\n to_remove = set()\n reset = False\n for start, trie_pointer in states.items():\n if '' in trie_pointer:\n for lookstart, looktrie_pointer in states.items():\n if lookstart > start:\n break\n elif lookstart < start:\n lookahead_index = current + 1\n end = current + 1\n else:\n lookahead_index = current\n end = current\n next_char = text[lookahead_index] if lookahead_index < len(text) else None\n if '' in looktrie_pointer:\n start = lookstart\n end = lookahead_index\n skip = lookahead_index\n while next_char in looktrie_pointer:\n looktrie_pointer = looktrie_pointer[next_char]\n lookahead_index += 1\n if '' in looktrie_pointer:\n start = lookstart\n end = lookahead_index\n skip = lookahead_index\n if lookahead_index == len(text):\n break\n next_char = text[lookahead_index]\n offsets.append(start)\n offsets.append(end)\n reset = True\n break\n elif current_char in trie_pointer:\n trie_pointer = trie_pointer[current_char]\n states[start] = trie_pointer\n else:\n to_remove.add(start)\n if reset:\n states = {}\n else:\n for start in to_remove:\n del states[start]\n if current >= skip and current_char in self.data:\n states[current] = self.data[current_char]\n for start, trie_pointer in states.items():\n if '' in trie_pointer:\n end = len(text)\n offsets.append(start)\n offsets.append(end)\n break\n return self.cut_text(text, offsets)", "docstring": "Will look for the words added to the trie within `text`. Output is the original string splitted along the\n boundaries of the words found.\n\n This trie will match the longest possible word first !\n\nExample:\n ```python\n >>> trie = Trie()\n >>> trie.split(\"[CLS] This is a extra_id_100\")\n [\"[CLS] This is a extra_id_100\"]\n\n >>> trie.add(\"[CLS]\")\n >>> trie.add(\"extra_id_1\")\n >>> trie.add(\"extra_id_100\")\n >>> trie.split(\"[CLS] This is a extra_id_100\")\n [\"[CLS]\", \" This is a \", \"extra_id_100\"]\n ```", "source": "github_repos"} +{"code": "def weighting_function(max_num_bins: int, up: torch.Tensor, reg_scale: int) -> torch.Tensor:\n upper_bound1 = abs(up[0]) * abs(reg_scale)\n upper_bound2 = abs(up[0]) * abs(reg_scale) * 2\n step = (upper_bound1 + 1) ** (2 / (max_num_bins - 2))\n left_values = [-step ** i + 1 for i in range(max_num_bins // 2 - 1, 0, -1)]\n right_values = [step ** i - 1 for i in range(1, max_num_bins // 2)]\n values = [-upper_bound2] + left_values + [torch.zeros_like(up[0][None])] + right_values + [upper_bound2]\n values = torch.cat(values, 0)\n return values", "docstring": "Generates the non-uniform Weighting Function W(n) for bounding box regression.\n\nArgs:\n max_num_bins (int): Max number of the discrete bins.\n up (Tensor): Controls upper bounds of the sequence,\n where maximum offset is ±up * H / W.\n reg_scale (float): Controls the curvature of the Weighting Function.\n Larger values result in flatter weights near the central axis W(max_num_bins/2)=0\n and steeper weights at both ends.\n\nReturns:\n Tensor: Sequence of Weighting Function.", "source": "github_repos"} +{"code": "def apply(self, predictions: Iterable[AnomalyPrediction]) -> AnomalyPrediction:\n result_dict: dict[str, Any] = {}\n _AggModelIdMixin.add_model_id(self, result_dict)\n _SourcePredictionMixin.add_source_predictions(self, result_dict, predictions)\n scores = [prediction.score for prediction in predictions if prediction.score is not None and (not math.isnan(prediction.score))]\n if len(scores) > 0:\n result_dict['score'] = self._agg(scores)\n elif all(map(lambda x: x.score is None, predictions)):\n result_dict['score'] = None\n else:\n result_dict['score'] = float('NaN')\n return AnomalyPrediction(**result_dict)", "docstring": "Applies the score aggregation function to a list of predictions.\n\nArgs:\n predictions (Iterable[AnomalyPrediction]): A collection of\n `AnomalyPrediction` objects to be aggregated.\n\nReturns:\n AnomalyPrediction: A single `AnomalyPrediction` object with the\n aggregated score. The aggregated score is determined as follows:\n\n - If there are any non-missing and non-error scores, the `agg_func` is\n applied to aggregate them.\n - If all scores are error scores (`None`), the aggregated score is also\n `None`.\n - If there are a mix of missing (`NaN`) and error scores (`None`), the\n aggregated score is `NaN`.", "source": "github_repos"} +{"code": "def _variable_product_items(variableitems: Iterable[tuple[str, cfg.Variable]], complexity_limit: 'ComplexityLimit') -> Generator[list[tuple[str, cfg.Binding]], None, None]:\n variableitems_iter = iter(variableitems)\n try:\n headkey, headvar = next(variableitems_iter)\n except StopIteration:\n yield []\n else:\n for tail in _variable_product_items(variableitems_iter, complexity_limit):\n for headvalue in headvar.bindings:\n complexity_limit.inc()\n yield ([(headkey, headvalue)] + tail)", "docstring": "Take the Cartesian product of a list of (key, value) tuples.\n\n See variable_product_dict below.\n\nArgs:\n variableitems: A dict mapping object to cfg.Variable.\n complexity_limit: A counter that tracks how many combinations we've yielded\n and aborts if we go over the limit.\n\nYields:\n A sequence of [(key, cfg.Binding), ...] lists.", "source": "github_repos"} +{"code": "def __init__(self, indent, last_space):\n self.indent = indent\n self.last_space = last_space\n self.closing_scope_indent = 0\n self.split_before_closing_bracket = False\n self.num_line_splits = 0", "docstring": "Maintains the state of the bracket enclosures.\n\n A stack of _ParenState objects are kept so that we know how to indent relative\n to the brackets.\n\nAttributes:\n indent: The column position to which a specified parenthesis level needs to\n be indented.\n last_space: The column position of the last space on each level.\n closing_scope_indent: The column position of the closing indentation.\n split_before_closing_bracket: Whether a newline needs to be inserted before\n the closing bracket. We only want to insert a newline before the closing\n bracket if there also was a newline after the beginning left bracket.\n num_line_splits: Number of line splits this _ParenState contains already.\n Each subsequent line split gets an increasing penalty.", "source": "github_repos"} +{"code": "def row_splits(self):\n return self._row_partition.row_splits()", "docstring": "The row-split indices for this ragged tensor's `values`.\n\n `rt.row_splits` specifies where the values for each row begin and end in\n `rt.values`. In particular, the values for row `rt[i]` are stored in\n the slice `rt.values[rt.row_splits[i]:rt.row_splits[i+1]]`.\n\nReturns:\n A 1-D integer `Tensor` with shape `[self.nrows+1]`.\n The returned tensor is non-empty, and is sorted in ascending order.\n `self.row_splits[0]` is zero, and `self.row_splits[-1]` is equal to\n `self.values.shape[0]`.\n\n #### Example:\n\n >>> rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []])\n >>> print(rt.row_splits) # indices of row splits in rt.values\n tf.Tensor([0 4 4 7 8 8], shape=(6,), dtype=int64)", "source": "github_repos"} +{"code": "def DefaultNodeVisit(self, node):\n for child in node.children:\n self.Visit(child)", "docstring": "Default visitor for Node: visits the node's children depth-first.\n\n This method is invoked when no specific visitor for the node is defined.\n\nArgs:\n node: the node to visit", "source": "github_repos"} +{"code": "def copy_clean(node, preserve_annos=None):\n return CleanCopier(preserve_annos).copy(node)", "docstring": "Creates a deep copy of an AST.\n\n The copy will not include fields that are prefixed by '__', with the\n exception of user-specified annotations.\n\nArgs:\n node: ast.AST\n preserve_annos: Optional[Set[Hashable]], annotation keys to include in the\n copy\n\nReturns:\n ast.AST", "source": "github_repos"} +{"code": "def add(self, profile_datum):\n self.total_op_time += profile_datum.op_time\n self.total_exec_time += profile_datum.exec_time\n device_and_node = '%s:%s' % (profile_datum.device_name, profile_datum.node_exec_stats.node_name)\n device_and_node = '%s:%s' % (profile_datum.device_name, profile_datum.node_exec_stats.node_name)\n if device_and_node in self._node_to_exec_count:\n self._node_to_exec_count[device_and_node] += 1\n else:\n self._node_to_exec_count[device_and_node] = 1", "docstring": "Accumulate a new instance of ProfileDatum.\n\nArgs:\n profile_datum: (`ProfileDatum`) an instance of `ProfileDatum` to\n accumulate to this object.", "source": "github_repos"} +{"code": "def GetNetgroupMap(self, since=None):\n return NetgroupUpdateGetter().GetUpdates(self, self.conf['netgroup_url'], since)", "docstring": "Return the netgroup map from this source.\n\nArgs:\n since: Get data only changed since this timestamp (inclusive) or None\n for all data.\n\nReturns:\n instance of netgroup.NetgroupMap", "source": "github_repos"} +{"code": "def terminate(self, task_type, task_id):\n with self._process_lock:\n p = self._processes.get((task_type, task_id), None)\n if p is None:\n raise ValueError('{}-{} does not exist'.format(task_type, task_id))\n self._terminated.add((task_type, task_id))\n self._parent_to_sub_queue.put('terminate {} {}'.format(task_type, task_id))\n p.join()", "docstring": "Terminates the process with `task_type` and `task_id`.\n\n If auto_retart=True, the terminated task will be restarted unless the chief\n has already exited with zero exit code.\n\nArgs:\n task_type: the task type.\n task_id: the task id.", "source": "github_repos"} +{"code": "def _parse_unknown_block_line(self, instrumentation_block, line):\n if line.startswith(_InstrumentationStructurePrefixes.STATUS):\n return self._parse_method_block_line(self._transition_instrumentation_block(instrumentation_block, new_state=_InstrumentationBlockStates.METHOD), line)\n elif line.startswith(_InstrumentationStructurePrefixes.RESULT) or _InstrumentationStructurePrefixes.FAILED in line:\n return self._parse_result_block_line(self._transition_instrumentation_block(instrumentation_block, new_state=_InstrumentationBlockStates.RESULT), line)\n else:\n instrumentation_block.add_value(line)\n return instrumentation_block", "docstring": "Parses a line from the instrumentation output from the UNKNOWN\n parser state.\n\nArgs:\n instrumentation_block: _InstrumentationBlock, the current\n instrumenation block, where the correct categorization it noti\n yet known.\n line: string, the raw instrumenation output line to be used to\n deteremine the correct categorization.\n\nReturns:\n The next instrumentation block to continue parsing with. Usually,\n this is the same instrumentation block but with the state\n transitioned appropriately.", "source": "github_repos"} +{"code": "def __call__(self, images: ImageInput=None, text: Optional[Union[List[str], List[List[str]]]]=None, audio=None, videos=None, **kwargs: Unpack[OmDetTurboProcessorKwargs]) -> BatchFeature:\n if images is None or text is None:\n raise ValueError('You have to specify both `images` and `text`')\n output_kwargs = self._merge_kwargs(OmDetTurboProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs)\n if isinstance(text, str):\n text = text.strip(' ').split(',')\n if not (len(text) and isinstance(text[0], (list, tuple))):\n text = [text]\n task = output_kwargs['text_kwargs'].pop('task', None)\n if task is None:\n task = ['Detect {}.'.format(', '.join(text_single)) for text_single in text]\n elif not isinstance(task, (list, tuple)):\n task = [task]\n encoding_image_processor = self.image_processor(images, **output_kwargs['images_kwargs'])\n tasks_encoding = self.tokenizer(text=task, **output_kwargs['text_kwargs'])\n classes = text\n classes_structure = torch.tensor([len(class_single) for class_single in classes], dtype=torch.long)\n classes_flattened = [class_single for class_batch in classes for class_single in class_batch]\n classes_encoding = self.tokenizer(text=classes_flattened, **output_kwargs['text_kwargs'])\n encoding = BatchFeature()\n encoding.update({f'tasks_{key}': value for key, value in tasks_encoding.items()})\n encoding.update({f'classes_{key}': value for key, value in classes_encoding.items()})\n encoding.update({'classes_structure': classes_structure})\n encoding.update(encoding_image_processor)\n return encoding", "docstring": "This method uses [*DetrImageProcessor.__call__] method to prepare image(s) for the model, and\n [CLIPTokenizerFast.__call__] to prepare text for the model.\n\n Please refer to the docstring of the above two methods for more information.\n\nArgs:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255.\n text (`Union[str, List[str], List[List[str]]]`):\n The classes used to limit the scope of the open vocabulary detection. Expects a list of strings or a list\n of list of strings. Batched classes can be of different lengths.\n Examples: [\"cat\", \"dog\", \"bird\"], [[\"cat\", \"dog\", \"bird\"], [\"hat\", \"person\"], [\"car\"]]\n Kwargs:\n task (`Union[str, List[str], TextInput, PreTokenizedInput]`):\n The grounded text used to guide open vocabulary detection. Expects a single string or a list of strings.\n Examples: \"Detect a cat, a dog, and a bird.\",[ \"Detect everything.\", \"Detect trees and flowers.\"]\n When not provided, the default task is \"Detect [class1], [class2], [class3]\" etc.\n ...", "source": "github_repos"} +{"code": "def deserialize(config, custom_objects=None):\n return deserialize_keras_object(config, module_objects=globals(), custom_objects=custom_objects, printable_module_name='metric function')", "docstring": "Deserializes a serialized metric class/function instance.\n\nArgs:\n config: Metric configuration.\n custom_objects: Optional dictionary mapping names (strings) to custom\n objects (classes and functions) to be considered during deserialization.\n\nReturns:\n A Keras `Metric` instance or a metric function.", "source": "github_repos"} +{"code": "def apply_indexed_slices_grad(self, grad, local_step=0, name=None):\n return self.apply_grad(grad_indices=grad.indices, grad_values=grad.values, grad_shape=grad.dense_shape, local_step=local_step, name=name)", "docstring": "Attempts to apply a gradient to the accumulator.\n\n The attempt is silently dropped if the gradient is stale, i.e., `local_step`\n is less than the accumulator's global time step.\n\nArgs:\n grad: The gradient `IndexedSlices` to be applied.\n local_step: Time step at which the gradient was computed.\n name: Optional name for the operation.\n\nReturns:\n The operation that (conditionally) applies a gradient to the accumulator.\n\nRaises:\n InvalidArgumentError: If grad is of the wrong shape", "source": "github_repos"} +{"code": "def _set_variable_or_list_initializer(variable_or_list, ckpt_file, tensor_name):\n if isinstance(variable_or_list, (list, tuple)):\n slice_name = None\n for v in variable_or_list:\n slice_info = v._save_slice_info\n if slice_name is None:\n slice_name = slice_info.full_name\n elif slice_name != slice_info.full_name:\n raise ValueError('Slices must all be from the same tensor: %s != %s' % (slice_name, slice_info.full_name))\n _set_checkpoint_initializer(v, ckpt_file, tensor_name, slice_info.spec)\n else:\n _set_checkpoint_initializer(variable_or_list, ckpt_file, tensor_name, '')", "docstring": "Overrides initialization op of given variable or list of variables.\n\n Calls `_set_checkpoint_initializer` for each variable in the given list of\n variables.\n\nArgs:\n variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects.\n ckpt_file: string, full path of the checkpoint.\n tensor_name: Name of the tensor to load from the checkpoint.\n\nRaises:\n ValueError: if all objects in `variable_or_list` are not partitions of the\n same large variable.", "source": "github_repos"} +{"code": "def auto_call_functors(enabled: bool=True) -> ContextManager[None]:\n return thread_local.thread_local_value_scope(_TLS_AUTO_CALL_FUNCTORS, enabled, False)", "docstring": "Returns a context manager to enable or disable auto call for functors.\n\n `auto_call_functors` is thread-safe and can be nested. For example::\n\n @pg.symbolize\n def foo(x, y):\n return x + y\n\n with pg.auto_call_functors(True):\n a = foo(1, 2)\n assert a == 3\n with pg.auto_call_functors(False):\n b = foo(1, 2)\n assert isinstance(b, foo)\n\nArgs:\n enabled: If True, enable auto call for functors.\n Otherwise, auto call will be disabled.\n\nReturns:\n A context manager for enabling/disabling auto call for functors.", "source": "github_repos"} +{"code": "def call(self, input_features: TFModelInputType | None=None, decoder_input_ids: np.ndarray | tf.Tensor | None=None, decoder_attention_mask: np.ndarray | tf.Tensor | None=None, decoder_position_ids: np.ndarray | tf.Tensor | None=None, head_mask: np.ndarray | tf.Tensor | None=None, decoder_head_mask: np.ndarray | tf.Tensor | None=None, cross_attn_head_mask: np.ndarray | tf.Tensor | None=None, encoder_outputs: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]]=None, past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]]=None, decoder_inputs_embeds: Optional[Tuple[Union[np.ndarray, tf.Tensor]]]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, training: bool=False) -> Union[Tuple[tf.Tensor], TFSeq2SeqModelOutput]:\n outputs = self.model(input_features=input_features, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, decoder_position_ids=decoder_position_ids, head_mask=head_mask, decoder_head_mask=decoder_head_mask, cross_attn_head_mask=cross_attn_head_mask, encoder_outputs=encoder_outputs, past_key_values=past_key_values, decoder_inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, training=training)\n return outputs", "docstring": "Returns:\n\nExample:\n ```python\n >>> import tensorflow as tf\n >>> from transformers import TFWhisperModel, AutoFeatureExtractor\n >>> from datasets import load_dataset\n\n >>> model = TFWhisperModel.from_pretrained(\"openai/whisper-base\")\n >>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"openai/whisper-base\")\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> inputs = feature_extractor(ds[0][\"audio\"][\"array\"], return_tensors=\"tf\")\n >>> input_features = inputs.input_features\n >>> decoder_input_ids = tf.convert_to_tensor([[1, 1]]) * model.config.decoder_start_token_id\n >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state\n >>> list(last_hidden_state.shape)\n [1, 2, 512]\n ```", "source": "github_repos"} +{"code": "def resize(self, image: np.ndarray, size: Union[Dict[str, int], int], resample: PILImageResampling=PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n height, width = get_image_size(image, input_data_format)\n max_size = max(height, width)\n size = get_size_dict(size, default_to_square=True)\n if size['height'] != size['width']:\n raise ValueError(f'Output height and width must be the same. Got height={size['height']} and width={size['width']}')\n size = size['height']\n delta = size / max_size\n output_size_nonpadded = [max(int(height * delta), self.min_size), max(int(width * delta), self.min_size)]\n image = resize(image, size=output_size_nonpadded, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs)\n image = self.pad_to_square(image=image, background_color=self.background_color, input_data_format=input_data_format)\n return image", "docstring": "Resize an image to dynamically calculated size.\n\nArgs:\n image (`np.ndarray`):\n Image to resize.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.\n data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the output image. If unset, the channel dimension format of the input\n image is used. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `None`: will be inferred from input\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n\nReturns:\n `np.ndarray`: The resized image.", "source": "github_repos"} +{"code": "def _get_split_key(client_keys, num_splits):\n if not client_keys or len(client_keys) < num_splits - 1:\n return client_keys\n num_keys_per_split = max(1.0, float(len(client_keys)) / (num_splits - 1))\n split_client_keys = []\n for i in range(1, num_splits):\n split_index = int(round(i * num_keys_per_split) - 1)\n split_client_keys.append(client_keys[split_index])\n return split_client_keys", "docstring": "Given a list of keys and a number of splits find the keys to split on.\n\nArgs:\n client_keys: the list of keys.\n num_splits: the number of splits.\n\nReturns:\n A list of keys to split on.", "source": "github_repos"} +{"code": "def _escape_identifier(identifier_value: str) -> str:\n identifier_value = identifier_value.replace('-', '_')\n if identifier_value.upper() in _sql_data_types.STANDARD_SQL_KEYWORDS:\n return f'`{identifier_value}`'\n return identifier_value", "docstring": "Returns the value in a valid column name format.\n\nArgs:\n identifier_value: Raw identifier string.\n\nReturns:\n If the identifier is a keyword, then it will be surrounded by backticks. If\n the identifier contains a hyphen, the hyphen will be replaced by an\n underscore.", "source": "github_repos"} +{"code": "def custom_apply(self, path: utils.KeyPath, value_spec: pg_typing.ValueSpec, allow_partial: bool, child_transform: Optional[Callable[[utils.KeyPath, pg_typing.Field, Any], Any]]=None) -> Tuple[bool, Any]:\n del path, value_spec, allow_partial, child_transform\n return (False, self)", "docstring": "Custom apply on a value based on its original value spec.\n\n This implements ``pg.pg_typing.CustomTyping``, allowing a pure symbolic\n value to be assigned to any field. To customize this behavior, override\n this method in subclasses.\n\nArgs:\n path: KeyPath of current object under its object tree.\n value_spec: Original value spec for this field.\n allow_partial: Whether allow partial object to be created.\n child_transform: Function to transform child node values into their final\n values. Transform function is called on leaf nodes first, then on their\n parents, recursively.\n\nReturns:\n A tuple (proceed_with_standard_apply, value_to_proceed).\n If proceed_with_standard_apply is set to False, value_to_proceed\n will be used as final value.\n\nRaises:\n Error when the value is not compatible with the value spec.", "source": "github_repos"} +{"code": "def resource_schema(self, resource: str) -> dict:\n entry = self.api_document['schemas'][resource]['properties']\n return self.to_schema(entry)", "docstring": "Return BigQuery schema for a Discovery API resource.\n\nArgs:\n resource: the name of the Google API resource\n\nReturns:\n A dictionary representation of the resource.", "source": "github_repos"} +{"code": "def _findSourceLine(self, annotated_source, line_number):\n index = None\n for i, line in enumerate(annotated_source.lines):\n if line.startswith('L%d ' % line_number):\n index = i\n break\n return index", "docstring": "Find line of given line number in annotated source.\n\nArgs:\n annotated_source: (debugger_cli_common.RichTextLines) the annotated source\n line_number: (int) 1-based line number\n\nReturns:\n (int) If line_number is found, 0-based line index in\n annotated_source.lines. Otherwise, None.", "source": "github_repos"} +{"code": "def eye(size, dtype=None, name=None):\n if dtype is None:\n dtype = floatx()\n tf_dtype = dtypes_module.as_dtype(dtype)\n return variable(linalg_ops.eye(size, dtype=tf_dtype), dtype, name)", "docstring": "Instantiate an identity matrix and returns it.\n\nArgs:\n size: Integer, number of rows/columns.\n dtype: String, data type of returned Keras variable.\n name: String, name of returned Keras variable.\n\nReturns:\n A Keras variable, an identity matrix.\n\nExample:\n >>> kvar = tf.keras.backend.eye(3)\n >>> tf.keras.backend.eval(kvar)\n array([[1., 0., 0.],\n [0., 1., 0.],\n [0., 0., 1.]], dtype=float32)", "source": "github_repos"} +{"code": "def run_bq_pipeline(argv=None):\n parser = argparse.ArgumentParser()\n parser.add_argument('--query', required=True, help='Query to process for the table.')\n parser.add_argument('--output', required=True, help='Output BQ table to write results to.')\n parser.add_argument('--output_schema', dest='output_schema', required=True, help='Schema for output BQ table.')\n parser.add_argument('--use_standard_sql', action='store_true', dest='use_standard_sql', help='Output BQ table to write results to.')\n parser.add_argument('--kms_key', default=None, help='Use this Cloud KMS key with BigQuery.')\n parser.add_argument('--native', default=False, action='store_true', help='Use NativeSources and Sinks.')\n parser.add_argument('--use_json_exports', default=False, action='store_true', help='Use JSON as the file format for exports.')\n known_args, pipeline_args = parser.parse_known_args(argv)\n table_schema = parse_table_schema_from_json(known_args.output_schema)\n kms_key = known_args.kms_key\n options = PipelineOptions(pipeline_args)\n p = TestPipeline(options=options)\n if known_args.native:\n data = p | 'read' >> beam.io.Read(beam.io.BigQuerySource(query=known_args.query, use_standard_sql=known_args.use_standard_sql, kms_key=kms_key))\n else:\n data = p | 'read' >> beam.io.gcp.bigquery.ReadFromBigQuery(query=known_args.query, project=options.view_as(GoogleCloudOptions).project, use_standard_sql=known_args.use_standard_sql, use_json_exports=known_args.use_json_exports, kms_key=kms_key)\n temp_file_format = 'NEWLINE_DELIMITED_JSON' if known_args.use_json_exports else 'AVRO'\n _ = data | 'write' >> beam.io.WriteToBigQuery(known_args.output, schema=table_schema, create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED, write_disposition=beam.io.BigQueryDisposition.WRITE_EMPTY, temp_file_format=temp_file_format, kms_key=kms_key)\n result = p.run()\n result.wait_until_finish()", "docstring": "Run the sample BigQuery pipeline.\n\nArgs:\n argv: Arguments to the run function.", "source": "github_repos"} +{"code": "def with_max_depth(self, max_depth):\n self._options['max_depth'] = max_depth\n return self", "docstring": "Set the maximum depth of display.\n\n The depth depends on profiling view. For 'scope' view, it's the\n depth of name scope hierarchy (tree), for 'op' view, it's the number\n of operation types (list), etc.\n\nArgs:\n max_depth: Maximum depth of the data structure to display.\n\nReturns:\n self", "source": "github_repos"} +{"code": "def _MeanAggregator(inputs, segments):\n result = []\n for inputs_i, segments_i in zip(array_ops.split(inputs, inputs.shape[0]), array_ops.split(segments, segments.shape[0])):\n means_i = math_ops.unsorted_segment_mean(inputs_i, segments_i, num_segments=math_ops.reduce_max(segments_i) + 1)\n result.append(array_ops.reshape(array_ops.gather(means_i, segments_i), [-1]))\n return array_ops_stack.stack(result, axis=0)", "docstring": "Replaces each segment with its mean along the last axis.\n\n Specifically, each value in the `inputs` tensor gets replaced by the mean\n value computed from the values that belong to the same segment.\n\nArgs:\n inputs: A 2-tensor. Aggregation is done over dimension 1.\n segments: A 2-tensor, same shape as `input`.\n\nReturns:\n The result, same shape and type as `inputs`.", "source": "github_repos"} +{"code": "def check_copies(overwrite: bool=False, file: Optional[str]=None):\n buffer = {}\n if file is None:\n all_files = glob.glob(os.path.join(TRANSFORMERS_PATH, '**/*.py'), recursive=True)\n all_test_files = glob.glob(os.path.join(MODEL_TEST_PATH, '**/*.py'), recursive=True)\n all_files = list(all_files) + list(all_test_files)\n else:\n all_files = [file]\n diffs = []\n for filename in all_files:\n new_diffs = is_copy_consistent(filename, overwrite, buffer)\n diffs += [f'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs]\n if not overwrite and len(diffs) > 0:\n diff = '\\n'.join(diffs)\n raise Exception('Found the following copy inconsistencies:\\n' + diff + '\\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.')", "docstring": "Check every file is copy-consistent with the original. Also check the model list in the main README and other\n READMEs are consistent.\n\nArgs:\n overwrite (`bool`, *optional*, defaults to `False`):\n Whether or not to overwrite the copies when they don't match.\n file (`bool`, *optional*):\n The path to a specific file to check and/or fix.", "source": "github_repos"} +{"code": "def pixel_shuffle(self, vision_features: torch.Tensor, scale_factor: float=0.5):\n batch_size, width, height, channels = vision_features.size()\n if height % scale_factor != 0 or width % scale_factor != 0:\n raise ValueError('Height and width must be divisible by scale_factor for proper downsampling.')\n vision_features = vision_features.view(batch_size, width, int(height * scale_factor), int(channels / scale_factor))\n vision_features = vision_features.permute(0, 2, 1, 3).contiguous()\n vision_features = vision_features.view(batch_size, int(height * scale_factor), int(width * scale_factor), int(channels / scale_factor ** 2))\n vision_features = vision_features.permute(0, 2, 1, 3).contiguous()\n return vision_features", "docstring": "Perform pixel shuffle downsampling on vision features.\n\nArgs:\n vision_features (`torch.Tensor`):\n Input tensor of shape (batch_size, width, height, channels).\n scale_factor (`float`, *optional*, defaults to `0.5`):\n Factor by which to downsample. Default is 0.5, which halves the dimensions.\n\nReturns:\n vision_features (`torch.Tensor`):\n Downsampled tensor of shape (batch_size, height*scale_factor, width*scale_factor, channels/(scale_factor^2)).", "source": "github_repos"} +{"code": "def combine(**kwargs):\n if not kwargs:\n return [OrderedDict()]\n sort_by_key = lambda k: k[0]\n kwargs = OrderedDict(sorted(kwargs.items(), key=sort_by_key))\n first = list(kwargs.items())[0]\n rest = dict(list(kwargs.items())[1:])\n rest_combined = combine(**rest)\n key = first[0]\n values = first[1]\n if not isinstance(values, list):\n values = [values]\n return [OrderedDict(sorted(list(combined.items()) + [(key, v)], key=sort_by_key)) for v in values for combined in rest_combined]", "docstring": "Generate combinations based on its keyword arguments.\n\n Two sets of returned combinations can be concatenated using +. Their product\n can be computed using `times()`.\n\nArgs:\n **kwargs: keyword arguments of form `option=[possibilities, ...]`\n or `option=the_only_possibility`.\n\nReturns:\n a list of dictionaries for each combination. Keys in the dictionaries are\n the keyword argument names. Each key has one value - one of the\n corresponding keyword argument values.", "source": "github_repos"} +{"code": "def correct_pad(inputs, kernel_size):\n img_dim = 2 if backend.image_data_format() == 'channels_first' else 1\n input_size = inputs.shape[img_dim:img_dim + 2]\n if isinstance(kernel_size, int):\n kernel_size = (kernel_size, kernel_size)\n if input_size[0] is None:\n adjust = (1, 1)\n else:\n adjust = (1 - input_size[0] % 2, 1 - input_size[1] % 2)\n correct = (kernel_size[0] // 2, kernel_size[1] // 2)\n return ((correct[0] - adjust[0], correct[0]), (correct[1] - adjust[1], correct[1]))", "docstring": "Returns a tuple for zero-padding for 2D convolution with downsampling.\n\nArgs:\n inputs: Input tensor.\n kernel_size: An integer or tuple/list of 2 integers.\n\nReturns:\n A tuple.", "source": "github_repos"} +{"code": "def split_image(self, image: np.ndarray, input_data_format: Optional[Union[str, ChannelDimension]]=None):\n height, width = get_image_size(image, input_data_format)\n mid_width = width // 2\n mid_height = height // 2\n return [self._crop(image, 0, 0, mid_width, mid_height, input_data_format), self._crop(image, mid_width, 0, width, mid_height, input_data_format), self._crop(image, 0, mid_height, mid_width, height, input_data_format), self._crop(image, mid_width, mid_height, width, height, input_data_format), image]", "docstring": "Split an image into 4 equal sub-images, and the concatenate that sequence with the original image.\n That means that a single image becomes a sequence of 5 images.\n This is a \"trick\" to spend more compute on each image with no changes in the vision encoder.\n\nArgs:\n image (`np.ndarray`):\n Images to split.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.", "source": "github_repos"} +{"code": "def _calculate_aggregation_loss_known(logits_aggregation, aggregate_mask, aggregation_labels, use_answer_as_supervision, num_aggregation_labels):\n if use_answer_as_supervision:\n target_aggregation = tf.zeros_like(aggregate_mask, dtype=tf.int32)\n else:\n target_aggregation = aggregation_labels\n one_hot_labels = tf.one_hot(target_aggregation, depth=num_aggregation_labels, dtype=tf.float32)\n log_probs = tf.nn.log_softmax(logits_aggregation, axis=-1)\n per_example_aggregation_intermediate = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n if use_answer_as_supervision:\n return per_example_aggregation_intermediate * (1 - aggregate_mask)\n else:\n return per_example_aggregation_intermediate", "docstring": "Calculates aggregation loss when its type is known during training.\n\n In the weakly supervised setting, the only known information is that for cell selection examples, \"no aggregation\"\n should be predicted. For other examples (those that require aggregation), no loss is accumulated. In the setting\n where aggregation type is always known, standard cross entropy loss is accumulated for all examples\n\nArgs:\n logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):\n Logits per aggregation operation.\n aggregate_mask (`tf.Tensor` of shape `(batch_size, )`):\n A mask set to 1 for examples that should use aggregation functions.\n aggregation_labels (`tf.Tensor` of shape `(batch_size, )`):\n Aggregation function id for every example in the batch.\n use_answer_as_supervision (`bool`, *optional*):\n Whether to use the answer as the only supervision for aggregation examples.\n num_aggregation_labels (`int`, *optional*, defaults to 0):\n The number of aggregation operators to predict.\n\nReturns:\n aggregation_loss_known (`tf.Tensor` of shape `(batch_size,)`): Aggregation loss (when its type is known during\n training) per example.", "source": "github_repos"} +{"code": "def __init__(self, input_bytes):\n self.fdp = atheris.FuzzedDataProvider(input_bytes)", "docstring": "FuzzingHelper initializer.\n\nArgs:\n input_bytes: Input randomized bytes used to create a FuzzedDataProvider.", "source": "github_repos"} +{"code": "def scatter_div(self, sparse_delta, use_locking=False, name=None):\n if not isinstance(sparse_delta, indexed_slices.IndexedSlices):\n raise TypeError('sparse_delta is not IndexedSlices: %s' % sparse_delta)\n return gen_state_ops.scatter_div(self._variable, sparse_delta.indices, sparse_delta.values, use_locking=use_locking, name=name)", "docstring": "Divide this variable by `tf.IndexedSlices`.\n\nArgs:\n sparse_delta: `tf.IndexedSlices` to divide this variable by.\n use_locking: If `True`, use locking during the operation.\n name: the name of the operation.\n\nReturns:\n A `Tensor` that will hold the new value of this variable after\n the scattered division has completed.\n\nRaises:\n TypeError: if `sparse_delta` is not an `IndexedSlices`.", "source": "github_repos"} +{"code": "def interp(x: Array['*d'], from_: Tuple[_MinMaxValue, _MinMaxValue], to: Tuple[_MinMaxValue, _MinMaxValue], *, axis: int=-1, xnp: numpy_utils.NpModule=...) -> FloatArray['*d']:\n if axis != -1:\n raise NotImplementedError('Only last axis supported for now. Please send a feature request.')\n from_ = tuple((xnp.asarray(v) for v in from_))\n to = tuple((xnp.asarray(v) for v in to))\n a, b = _linear_interp_factors(*from_, *to)\n return a * x + b", "docstring": "Linearly scale the given value by the given range.\n\n Somehow similar to `np.interp` or `scipy.interpolate.inter1d` with some\n differences like support scaling an axis by a different factors and\n extrapolate values outside the boundaries.\n\n `from_` and `to` are expected to be `(min, max)` tuples and the function\n interpolate between the two ranges.\n\n Example: Normalizing a uint8 image to `(-1, 1)`.\n\n ```python\n img = jnp.array([\n [0, 0],\n [127, 255],\n ])\n img = enp.interp(img, (0, 255), (0, 1))\n img == jnp.array([\n [-1, -1],\n [0.498..., 1],\n ])\n ```\n\n `min` and `max` can be either float values or array like structure, in which\n case the numpy broadcasting rules applies (x should be a `Array[... d]` and\n min/max values should be `Array[d]`.\n\n Example: Converting normalized 3d coordinates to world coordinates.\n\n ```python\n coords = enp.interp(coords, from_=(-1, 1), to=(0, (h, w, d)))\n ```\n\n * `coords[:, 0]` is interpolated from `(-1, 1)` to `(0, h)`\n * `coords[:, 1]` is interpolated from `(-1, 1)` to `(0, w)`\n * `coords[:, 2]` is interpolated from `(-1, 1)` to `(0, d)`\n\nArgs:\n x: Array to scale\n from_: Range of x.\n to: Range to which normalize x.\n axis: Axis on which normalizing. Only relevant if `from_` or `to` items\n contains range value.\n xnp: Numpy module to use\n\nReturns:\n Float tensor with same shape as x, but with normalized coordinates.", "source": "github_repos"} +{"code": "def forward(self, pixel_values: Optional[torch.Tensor]=None, noise: Optional[torch.FloatTensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, interpolate_pos_encoding: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[tuple, HieraForPreTrainingOutput]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n outputs = self.hiera(pixel_values, noise=noise, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=True, interpolate_pos_encoding=interpolate_pos_encoding, return_dict=return_dict)\n feature_maps = outputs[-1]\n bool_masked_pos = outputs[1]\n ids_to_restore = outputs[2]\n feature_maps = feature_maps[1:self.hiera.config.num_query_pool + 1] + (feature_maps[-1],)\n fused_hidden_states = self.multiscale_fusion(feature_maps)\n fused_hidden_states = self.encoder_norm(fused_hidden_states)\n logits, bool_masked_pos = self.decoder(fused_hidden_states, bool_masked_pos=bool_masked_pos, head_mask=head_mask, output_attentions=output_attentions)\n loss = self.forward_loss(pixel_values, logits, bool_masked_pos)\n if not return_dict:\n output = (logits, bool_masked_pos, ids_to_restore)\n if output_hidden_states:\n output = output + (outputs[3],)\n if output_attentions:\n output = output + (outputs[4],)\n if output_hidden_states:\n output = output + (outputs[-1],)\n return (loss,) + output if loss is not None else output\n return HieraForPreTrainingOutput(loss=loss, logits=logits, bool_masked_pos=bool_masked_pos, ids_restore=ids_to_restore, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions, reshaped_hidden_states=outputs.reshaped_hidden_states if output_hidden_states else None)", "docstring": "noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*):\n Mainly used for testing purposes to control randomness and maintain the reproducibility\n\nExample:\n ```python\n >>> from transformers import AutoImageProcessor, HieraForPreTraining\n >>> import torch\n >>> from PIL import Image\n >>> import requests\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> image_processor = AutoImageProcessor.from_pretrained(\"facebook/hiera-tiny-224-mae-hf\")\n >>> model = HieraForPreTraining.from_pretrained(\"facebook/hiera-tiny-224-mae-hf\")\n\n >>> inputs = image_processor(images=image, return_tensors=\"pt\")\n\n >>> outputs = model(**inputs)\n >>> logits = outputs.logits\n >>> loss = outputs.loss\n >>> print(list(logits.shape))\n [1, 196, 768]\n ```", "source": "github_repos"} +{"code": "def round(x):\n return math_ops.round(x)", "docstring": "Element-wise rounding to the closest integer.\n\n In case of tie, the rounding mode used is \"half to even\".\n\nArgs:\n x: Tensor or variable.\n\nReturns:\n A tensor.", "source": "github_repos"} +{"code": "def gradient_override_map(self, op_type_map) -> Iterator[None]:\n if not isinstance(op_type_map, dict):\n raise TypeError('op_type_map must be a dictionary mapping strings to strings')\n saved_mappings = {}\n for op_type, mapped_op_type in op_type_map.items():\n if not (isinstance(op_type, str) and isinstance(mapped_op_type, str)):\n raise TypeError('op_type_map must be a dictionary mapping strings to strings')\n try:\n saved_mappings[op_type] = self._gradient_override_map[op_type]\n except KeyError:\n pass\n self._gradient_override_map[op_type] = mapped_op_type\n try:\n yield\n finally:\n for op_type, mapped_op_type in op_type_map.items():\n try:\n self._gradient_override_map[op_type] = saved_mappings[op_type]\n except KeyError:\n del self._gradient_override_map[op_type]", "docstring": "EXPERIMENTAL: A context manager for overriding gradient functions.\n\n This context manager can be used to override the gradient function\n that will be used for ops within the scope of the context.\n\n For example:\n\n ```python\n @tf.RegisterGradient(\"CustomSquare\")\n def _custom_square_grad(op, grad):\n # ...\n\n with tf.Graph().as_default() as g:\n c = tf.constant(5.0)\n s_1 = tf.square(c) # Uses the default gradient for tf.square.\n with g.gradient_override_map({\"Square\": \"CustomSquare\"}):\n s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the\n # gradient of s_2.\n ```\n\nArgs:\n op_type_map: A dictionary mapping op type strings to alternative op type\n strings.\n\nReturns:\n A context manager that sets the alternative op type to be used for one\n or more ops created in that context.\n\nRaises:\n TypeError: If `op_type_map` is not a dictionary mapping strings to\n strings.", "source": "github_repos"} +{"code": "def __getitem__(self, key):\n if key is None:\n key = self._key()\n value = self._get_recursive(key)\n if value is None:\n value = self[key] = self.default_factory()\n return value", "docstring": "Gets the value at key (or current context), or sets default value.\n\nArgs:\n key: May be `None` or `Graph`object. When `None`, the key is set to the\n current context.\n\nReturns:\n Either the cached or default value.", "source": "github_repos"} +{"code": "def __init__(self, config: Owlv2Config):\n super().__init__()\n self.layers = nn.ModuleList([Owlv2EncoderLayer(config) for _ in range(config.num_hidden_layers)])\n self.gradient_checkpointing = False", "docstring": "Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a\n [`Owlv2EncoderLayer`].\n\nArgs:\n config: Owlv2Config", "source": "github_repos"} +{"code": "def bessel_j0(x, name=None):\n with ops.name_scope(name, 'bessel_j0', [x]):\n return gen_special_math_ops.bessel_j0(x)", "docstring": "Computes the Bessel j0 function of `x` element-wise.\n\n Modified Bessel function of order 0.\n\n >>> tf.math.special.bessel_j0([0.5, 1., 2., 4.]).numpy()\n array([ 0.93846981, 0.76519769, 0.22389078, -0.39714981], dtype=float32)\n\nArgs:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`,\n `float32`, `float64`.\n name: A name for the operation (optional).\n\nReturns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.j0\n @end_compatibility", "source": "github_repos"} +{"code": "def get_plugin_asset(plugin_asset_cls, graph=None):\n if graph is None:\n graph = ops.get_default_graph()\n if not plugin_asset_cls.plugin_name:\n raise ValueError('Class %s has no plugin_name' % plugin_asset_cls.__name__)\n name = _PLUGIN_ASSET_PREFIX + plugin_asset_cls.plugin_name\n container = graph.get_collection(name)\n if container:\n if len(container) != 1:\n raise ValueError('Collection for %s had %d items, expected 1' % (name, len(container)))\n instance = container[0]\n if not isinstance(instance, plugin_asset_cls):\n raise ValueError('Plugin name collision between classes %s and %s' % (plugin_asset_cls.__name__, instance.__class__.__name__))\n else:\n instance = plugin_asset_cls()\n graph.add_to_collection(name, instance)\n graph.add_to_collection(_PLUGIN_ASSET_PREFIX, plugin_asset_cls.plugin_name)\n return instance", "docstring": "Acquire singleton PluginAsset instance from a graph.\n\n PluginAssets are always singletons, and are stored in tf Graph collections.\n This way, they can be defined anywhere the graph is being constructed, and\n if the same plugin is configured at many different points, the user can always\n modify the same instance.\n\nArgs:\n plugin_asset_cls: The PluginAsset class\n graph: (optional) The graph to retrieve the instance from. If not specified,\n the default graph is used.\n\nReturns:\n An instance of the plugin_asset_class\n\nRaises:\n ValueError: If we have a plugin name collision, or if we unexpectedly find\n the wrong number of items in a collection.", "source": "github_repos"} +{"code": "def scatter_nd_update(self, indices, updates, name=None):\n return self._lazy_read(gen_state_ops.resource_scatter_nd_update(self.handle, indices, ops.convert_to_tensor(updates, self.dtype), name=name))", "docstring": "Applies sparse assignment to individual values or slices in a Variable.\n\n `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into `ref`.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of `ref`.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n ```\n\n For example, say we want to add 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n op = ref.scatter_nd_update(indices, updates)\n with tf.compat.v1.Session() as sess:\n print sess.run(op)\n ```\n\n The resulting update to ref would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\n See `tf.scatter_nd` for more details about how to make updates to\n slices.\n\nArgs:\n indices: The indices to be used in the operation.\n updates: The values to be used in the operation.\n name: the name of the operation.\n\nReturns:\n The updated variable.", "source": "github_repos"} +{"code": "def num_accelerators(self, task_type=None, task_id=None, config_proto=None):\n master = self.master(task_type, task_id)\n devices = get_accelerator_devices(master, config_proto)\n mapping = collections.defaultdict(int)\n for device in devices:\n if task_type is not None and task_id is not None:\n job_path = '/job:%s' % task_type\n task_path = '/task:%s' % task_id\n if job_path not in device.name or task_path not in device.name:\n continue\n mapping[device.device_type] += 1\n return mapping", "docstring": "Returns the number of accelerator cores per worker.\n\n This returns the number of accelerator cores (such as GPUs and TPUs)\n available per worker.\n\n Optionally, we allow callers to specify the task_type, and task_id, for\n if they want to target a specific TensorFlow task to query\n the number of accelerators. This is to support heterogenous environments,\n where the number of accelerators cores per host is different.\n\nArgs:\n task_type: (Optional) The type of the TensorFlow task of the machine we\n want to query.\n task_id: (Optional) The index of the TensorFlow task of the machine we\n want to query.\n config_proto: (Optional) Configuration for starting a new session to\n query how many accelerator cores it has.\n\nReturns:\n A map of accelerator types to number of cores.", "source": "github_repos"} +{"code": "def compute_mask(self, inputs, mask=None):\n if not self._supports_masking:\n if any((m is not None for m in nest.flatten(mask))):\n raise TypeError('Layer ' + self.name + ' does not support masking, but was passed an input_mask: ' + str(mask))\n return None\n return mask", "docstring": "Computes an output mask tensor.\n\nArgs:\n inputs: Tensor or list of tensors.\n mask: Tensor or list of tensors.\n\nReturns:\n None or a tensor (or list of tensors,\n one per output tensor of the layer).", "source": "github_repos"} +{"code": "def fit(weights: Array, train_dataset: Dataset, iters: int, learning_rate: float, log_span: int, val_dataset: typing.Optional[Dataset]=None) -> Array:\n grad_loss = jit(grad(cross_entropy_loss, argnums=0))\n for t in range(iters):\n weights = weights - learning_rate * grad_loss(weights, train_dataset.X, train_dataset.Y)\n if (t + 1) % log_span != 0:\n continue\n metrics_train = jit(get_metrics)(weights, train_dataset)\n print()\n print('iter:\\t%d' % (t + 1))\n print()\n print('train accuracy:\\t%.5f' % metrics_train.accuracy)\n print('train prec.:\\t%.5f' % metrics_train.precision)\n print('train recall:\\t%.5f' % metrics_train.recall)\n print('train fscore:\\t%.5f' % metrics_train.fscore)\n print('train loss:\\t%.5f' % metrics_train.loss)\n print()\n if val_dataset is None:\n continue\n metrics_val = jit(get_metrics)(weights, val_dataset)\n print('val accuracy:\\t%.5f' % metrics_val.accuracy)\n print('val prec.:\\t%.5f' % metrics_val.precision)\n print('val recall:\\t%.5f' % metrics_val.recall)\n print('val fscore:\\t%.5f' % metrics_val.fscore)\n print('val loss:\\t%.5f' % metrics_val.loss)\n print()\n return weights", "docstring": "Updates the weights with the given dataset.\n\nArgs:\n weights: A weight vector.\n train_dataset: A train dataset.\n iters: A number of iterations.\n learning_rate: A learning rate.\n log_span: A span to log metrics.\n val_dataset: A validation dataset (optional).\n\nReturns:\n An updated weight vector.", "source": "github_repos"} +{"code": "def __init__(self, padding=1, **kwargs):\n super(ZeroPadding1D, self).__init__(**kwargs)\n self.padding = conv_utils.normalize_tuple(padding, 2, 'padding')\n self.input_spec = InputSpec(ndim=3)", "docstring": "Zero-padding layer for 1D input (e.g. temporal sequence).\n\nExample:\n >>> input_shape = (2, 2, 3)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> print(x)\n [[[ 0 1 2]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 9 10 11]]]\n >>> y = tf.keras.layers.ZeroPadding1D(padding=2)(x)\n >>> print(y)\n tf.Tensor(\n [[[ 0 0 0]\n [ 0 0 0]\n [ 0 1 2]\n [ 3 4 5]\n [ 0 0 0]\n [ 0 0 0]]\n [[ 0 0 0]\n [ 0 0 0]\n [ 6 7 8]\n [ 9 10 11]\n [ 0 0 0]\n [ 0 0 0]]], shape=(2, 6, 3), dtype=int64)\n\nArgs:\n padding: Int, or tuple of int (length 2), or dictionary.\n - If int:\n How many zeros to add at the beginning and end of\n the padding dimension (axis 1).\n - If tuple of int (length 2):\n How many zeros to add at the beginning and the end of\n the padding dimension (`(left_pad, right_pad)`).\n\n Input shape:\n 3D tensor with shape `(batch_size, axis_to_pad, features)`\n\n Output shape:\n 3D tensor with shape `(batch_size, padded_axis, features)`", "source": "github_repos"} +{"code": "def _num_present(losses, weights, per_batch=False):\n if isinstance(weights, float) and weights != 0.0 or (context.executing_eagerly() and weights._rank() == 0 and (not math_ops.equal(weights, 0.0))):\n return _num_elements(losses)\n with ops.name_scope(None, 'num_present', (losses, weights)) as scope:\n weights = math_ops.cast(weights, dtype=dtypes.float32)\n present = array_ops.where(math_ops.equal(weights, 0.0), array_ops.zeros_like(weights), array_ops.ones_like(weights))\n present = weights_broadcast_ops.broadcast_weights(present, losses)\n if per_batch:\n return math_ops.reduce_sum(present, axis=math_ops.range(1, array_ops.rank(present)), keepdims=True, name=scope)\n return math_ops.reduce_sum(present, name=scope)", "docstring": "Computes the number of elements in the loss function induced by `weights`.\n\n A given weights tensor induces different numbers of usable elements in the\n `losses` tensor. The `weights` tensor is broadcast across `losses` for all\n possible dimensions. For example, if `losses` is a tensor of dimension\n `[4, 5, 6, 3]` and `weights` is a tensor of shape `[4, 5]`, then `weights` is,\n in effect, tiled to match the shape of `losses`. Following this effective\n tile, the total number of present elements is the number of non-zero weights.\n\nArgs:\n losses: `Tensor` of shape `[batch_size, d1, ... dN]`.\n weights: `Tensor` of shape `[]`, `[batch_size]` or\n `[batch_size, d1, ... dK]`, where K < N.\n per_batch: Whether to return the number of elements per batch or as a sum\n total.\n\nReturns:\n The number of present (non-zero) elements in the losses tensor. If\n `per_batch` is `True`, the value is returned as a tensor of size\n `[batch_size]`. Otherwise, a single scalar tensor is returned.", "source": "github_repos"} +{"code": "def list_key_values(input: t.Dict[str, str]) -> None:\n for cmd, desc in input.items():\n print(f'{cmd} => {desc}')", "docstring": "Display key-value pairs from a dictionary.\n\nArgs:\n input (Dict[str, str]): The dictionary containing key-value pairs.", "source": "github_repos"} +{"code": "def _post_process_masks_pt(self, masks, original_sizes, reshaped_input_sizes, mask_threshold=0.0, binarize=True, pad_size=None):\n requires_backends(self, ['torch'])\n pad_size = self.pad_size if pad_size is None else pad_size\n target_image_size = (pad_size['height'], pad_size['width'])\n if isinstance(original_sizes, (torch.Tensor, np.ndarray)):\n original_sizes = original_sizes.tolist()\n if isinstance(reshaped_input_sizes, (torch.Tensor, np.ndarray)):\n reshaped_input_sizes = reshaped_input_sizes.tolist()\n output_masks = []\n for i, original_size in enumerate(original_sizes):\n if isinstance(masks[i], np.ndarray):\n masks[i] = torch.from_numpy(masks[i])\n elif not isinstance(masks[i], torch.Tensor):\n raise ValueError('Input masks should be a list of `torch.tensors` or a list of `np.ndarray`')\n interpolated_mask = F.interpolate(masks[i], target_image_size, mode='bilinear', align_corners=False)\n interpolated_mask = interpolated_mask[..., :reshaped_input_sizes[i][0], :reshaped_input_sizes[i][1]]\n interpolated_mask = F.interpolate(interpolated_mask, original_size, mode='bilinear', align_corners=False)\n if binarize:\n interpolated_mask = interpolated_mask > mask_threshold\n output_masks.append(interpolated_mask)\n return output_masks", "docstring": "Remove padding and upscale masks to the original image size.\n\nArgs:\n masks (`Union[List[torch.Tensor], List[np.ndarray]]`):\n Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.\n original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):\n The original sizes of each image before it was resized to the model's expected input shape, in (height,\n width) format.\n reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):\n The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.\n mask_threshold (`float`, *optional*, defaults to 0.0):\n The threshold to use for binarizing the masks.\n binarize (`bool`, *optional*, defaults to `True`):\n Whether to binarize the masks.\n pad_size (`int`, *optional*, defaults to `self.pad_size`):\n The target size the images were padded to before being passed to the model. If None, the target size is\n assumed to be the processor's `pad_size`.\n\nReturns:\n (`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)\n is given by original_size.", "source": "github_repos"} +{"code": "def _compare_constant_tuple_prefix(op, prefix, constant_tuple, reverse):\n length = min(len(prefix), len(constant_tuple))\n trimmed_prefix = prefix[:length]\n trimmed_constant_tuple = constant_tuple[:length]\n if trimmed_prefix == trimmed_constant_tuple:\n if len(prefix) >= len(constant_tuple):\n if reverse:\n return op in (slots.LT, slots.LE, slots.NE)\n else:\n return op in (slots.NE, slots.GE, slots.GT)\n return None\n if reverse:\n return _compare_constants(op, trimmed_constant_tuple, trimmed_prefix)\n else:\n return _compare_constants(op, trimmed_prefix, trimmed_constant_tuple)", "docstring": "Compares a tuple's constant prefix against a constant tuple.\n\nArgs:\n op: A comparison operator, such as LT (less than).\n prefix: A constant prefix of a non-constant tuple (referred to as \"left\" in\n the inline comments). So if left=(3, 2, ...), prefix=(3, 2).\n constant_tuple: A constant tuple (referred to as \"right\").\n reverse: Whether left and right should be reversed for the comparison.\n\nReturns:\n A bool of the comparison result if it can be determined, None otherwise.", "source": "github_repos"} +{"code": "def potentially_ragged_concat(tensors):\n if len(tensors) == 1:\n return tensors[0]\n elif isinstance(tensors[0], tf.SparseTensor):\n return tf.sparse.concat(axis=0, sp_inputs=tensors)\n elif isinstance(tensors[0], tf.RaggedTensor):\n return tf.concat(tensors, axis=0)\n non_batch_shapes = tf.stack([tf.shape(tensor)[1:] for tensor in tensors])\n constant_dims = tf.math.reduce_all(non_batch_shapes == non_batch_shapes[:1], axis=0)\n if tf.math.reduce_all(constant_dims).numpy().item():\n if _is_scalar(tensors[0]):\n return tf.stack(tensors, axis=0)\n else:\n return tf.concat(tensors, axis=0)\n constant_inner_dimensions = constant_dims.numpy().tolist()[::-1].index(False)\n if constant_inner_dimensions == 0:\n constant_inner_shape = None\n else:\n constant_inner_shape = tensors[0].shape[-constant_inner_dimensions:]\n return tf.ragged.constant([tensor.numpy() for tensor in tensors], inner_shape=constant_inner_shape).merge_dims(0, 1)", "docstring": "Concats `Tensor`s along their first dimension.\n\nArgs:\n tensors: List of `Tensor`s.\n\nReturns:\n Concatenation of the inputs along the first dimension -- of type\n `np.ndarray` if all input shapes are compatible, or `tf.RaggedTensor`\n if not.", "source": "github_repos"} +{"code": "def SmartBroadcastGradientArgs(x, y, grad=None):\n del grad\n x_shape = array_ops.shape(x)\n y_shape = array_ops.shape(y)\n if not context.executing_eagerly() and isinstance(x, tensor.Tensor) and isinstance(y, tensor.Tensor):\n x_axes, y_axes = _InferGradientReductionAxes(x.shape, y.shape)\n else:\n x_axes, y_axes = (None, None)\n if x_axes is None or y_axes is None:\n x_axes, y_axes = gen_array_ops.broadcast_gradient_args(x_shape, y_shape)\n x_must_reduce = True\n y_must_reduce = True\n else:\n x_must_reduce = x_axes or x.shape.rank < y.shape.rank\n y_must_reduce = y_axes or y.shape.rank < x.shape.rank\n return ((x_shape, x_axes, x_must_reduce), (y_shape, y_axes, y_must_reduce))", "docstring": "Version of `BroadcastGradientArgs` optimized for partially-known shapes.\n\nArgs:\n x: The first argument of a broadcasting binary op.\n y: The second argument of a broadcasting binary op.\n grad: Deprecated.\n\nReturns:\n A pair of triples, one per argument with\n * Shape of the argument (tensor);\n * Reduction axes for the argument (list or tensor);\n * Boolean indicating whether the reduction must be applied.", "source": "github_repos"} +{"code": "def add_inputs(self, mutable_accumulator, elements, *args, **kwargs):\n for element in elements:\n mutable_accumulator = self.add_input(mutable_accumulator, element, *args, **kwargs)\n return mutable_accumulator", "docstring": "Returns the result of folding each element in elements into accumulator.\n\n This is provided in case the implementation affords more efficient\n bulk addition of elements. The default implementation simply loops\n over the inputs invoking add_input for each one.\n\nArgs:\n mutable_accumulator: the current accumulator,\n may be modified and returned for efficiency\n elements: the elements to add, should not be mutated\n *args: Additional arguments and side inputs.\n **kwargs: Additional arguments and side inputs.", "source": "github_repos"} +{"code": "def solve(a, b):\n if any_symbolic_tensors((a, b)):\n return Solve().symbolic_call(a, b)\n return _solve(a, b)", "docstring": "Solves a linear system of equations given by `a x = b`.\n\nArgs:\n a: A tensor of shape `(..., M, M)` representing the coefficients matrix.\n b: A tensor of shape `(..., M)` or `(..., M, N)` representing the\n right-hand side or \"dependent variable\" matrix.\n\nReturns:\n A tensor of shape `(..., M)` or `(..., M, N)` representing the solution\n of the linear system. Returned shape is identical to `b`.", "source": "github_repos"} +{"code": "def resume(resume_delay=0):\n return ProcessContinuation(resume_delay=resume_delay)", "docstring": "A convenient method that produces a ``ProcessContinuation``.\n\nArgs:\n resume_delay: delay after which processing current element should be\n resumed.\n Returns: a ``ProcessContinuation`` for signalling the runner that current\n input element has not been fully processed and should be resumed later.", "source": "github_repos"} +{"code": "def enable_eager_execution_internal(config=None, device_policy=None, execution_mode=None, server_def=None) -> None:\n if config is not None and (not isinstance(config, config_pb2.ConfigProto)):\n raise TypeError('config must be a tf.ConfigProto, but got %s' % type(config))\n if device_policy not in (None, context.DEVICE_PLACEMENT_EXPLICIT, context.DEVICE_PLACEMENT_WARN, context.DEVICE_PLACEMENT_SILENT, context.DEVICE_PLACEMENT_SILENT_FOR_INT32):\n raise ValueError('device_policy must be one of None, DEVICE_PLACEMENT_*')\n if execution_mode not in (None, context.SYNC, context.ASYNC):\n raise ValueError('execution_mode must be one of None, SYNC, ASYNC')\n if context.default_execution_mode == context.GRAPH_MODE:\n graph_mode_has_been_used = _default_graph_stack._global_default_graph is not None\n if graph_mode_has_been_used:\n raise ValueError('tf.enable_eager_execution must be called at program startup.')\n context.default_execution_mode = context.EAGER_MODE\n with context._context_lock:\n if context._context is None:\n context._set_context_locked(context.Context(config=config, device_policy=device_policy, execution_mode=execution_mode, server_def=server_def))\n elif config is not None and config is not context._context._config or (device_policy is not None and device_policy is not context._context._device_policy) or (execution_mode is not None and execution_mode is not context._context._execution_mode):\n raise ValueError('Trying to change the options of an active eager execution. Context config: %s, specified config: %s. Context device policy: %s, specified device policy: %s. Context execution mode: %s, specified execution mode %s.' % (context._context._config, config, context._context._device_policy, device_policy, context._context._execution_mode, execution_mode))\n else:\n context._context._thread_local_data.is_eager = True\n context.context = context.context_safe", "docstring": "Enables eager execution for the lifetime of this program.\n\n Most of the doc string for enable_eager_execution is relevant here as well.\n\nArgs:\n config: See enable_eager_execution doc string\n device_policy: See enable_eager_execution doc string\n execution_mode: See enable_eager_execution doc string\n server_def: (Optional.) A tensorflow::ServerDef proto. Enables execution on\n remote devices. GrpcServers need to be started by creating an identical\n server_def to this, and setting the appropriate task_indexes, so that the\n servers can communicate. It will then be possible to execute operations on\n remote devices.\n\nRaises:\n ValueError", "source": "github_repos"} +{"code": "def pow(x, y, name=None):\n with ops.name_scope(name, 'Pow', [x]) as name:\n return gen_math_ops._pow(x, y, name=name)", "docstring": "Computes the power of one value to another.\n\n Given a tensor `x` and a tensor `y`, this operation computes \\\\(x^y\\\\) for\n corresponding elements in `x` and `y`. For example:\n\n ```python\n x = tf.constant([[2, 2], [3, 3]])\n y = tf.constant([[8, 16], [2, 3]])\n tf.pow(x, y) # [[256, 65536], [9, 27]]\n ```\n\nArgs:\n x: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, `int64`,\n `complex64`, or `complex128`.\n y: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, `int64`,\n `complex64`, or `complex128`.\n name: A name for the operation (optional).\n\nReturns:\n A `Tensor`.", "source": "github_repos"} +{"code": "def __init__(self, entity=None, key=None):\n self.entity = entity\n self.key = key\n self._pb = FakeMessage(entity, key)", "docstring": "Fake mutation request object.\n\n Requires exactly one of entity or key to be set.\n\nArgs:\n entity: (``google.cloud.datastore.entity.Entity``) entity representing\n this upsert mutation\n key: (``google.cloud.datastore.key.Key``) key representing\n this delete mutation", "source": "github_repos"} +{"code": "def convert_pil_frames_to_video(videos: List[VideoInput]) -> List[Union['np.ndarray', 'torch.Tensor']]:\n if not isinstance(videos[0], (list, tuple)):\n return videos\n video_converted = []\n for video in videos:\n video = [np.array(frame) for frame in video]\n video = np.stack(video)\n video_converted.append(video)\n return video_converted", "docstring": "Given a batch of videos, converts each video to a 4D array. If video is already in array type,\n it is simply returned. We assume that all inputs in the list are in the same format, based on the type of the first element.\n\nArgs:\n videos (`VideoInput`):\n Video inputs to turn into a list of videos.", "source": "github_repos"} +{"code": "def basis(sample_paths):\n samples = tf.convert_to_tensor(sample_paths)\n dim = samples.shape.as_list()[-1]\n grid = tf.range(0, degree + 1, dtype=samples.dtype)\n samples_centered = samples - tf.math.reduce_mean(samples, axis=0)\n samples_centered = tf.expand_dims(samples_centered, -2)\n grid = tf.meshgrid(*dim * [grid])\n grid = tf.reshape(tf.stack(grid, -1), [-1, dim])\n basis_expansion = tf.reduce_prod(samples_centered ** grid, -1)\n return tf.transpose(basis_expansion)", "docstring": "Computes polynomial basis expansion at the given sample points.\n\nArgs:\n sample_paths: A `Tensor`s of either `flot32` or `float64` dtype and of\n shape `[num_samples, dim]` where `dim` has to be statically known.\n\nReturns:\n A `Tensor`s of shape `[degree * dim, num_samples]`.", "source": "github_repos"} +{"code": "def push(self, is_building_function, enter_context_fn, device_stack):\n self.stack.append(ContextSwitch(is_building_function, enter_context_fn, device_stack))", "docstring": "Push metadata about a context switch onto the stack.\n\n A context switch can take any one of the two forms: installing a graph as\n the default graph, or entering the eager context. For each context switch,\n we record whether or not the entered context is building a function.\n\nArgs:\n is_building_function: (bool.) Whether the context is building a function.\n enter_context_fn: (function.) A callable that executes the context switch.\n For example, `graph.as_default` or `eager_mode`.\n device_stack: If applicable, the device function stack for this graph.\n When breaking out of graphs in init_scope, the innermost nonempty device\n stack is used. Eager contexts put `None` here and the value is never\n used.", "source": "github_repos"} +{"code": "def interpolate(hidden_states, ratio):\n batch_size, time_length, classes_num = hidden_states.shape\n upsampled = hidden_states[:, :, None, :].repeat(1, 1, ratio, 1)\n upsampled = upsampled.reshape(batch_size, time_length * ratio, classes_num)\n return upsampled", "docstring": "Interpolate data in time domain. This is used to compensate the resolution reduction in downsampling of a CNN.\n\nArgs:\n hidden_states (`torch.FloatTensor` of shape (batch_size, time_length, classes_num)):\n Input hidden states\n ratio (`int`):\n The ratio of the length of the output to the length of the input.", "source": "github_repos"} +{"code": "def most_specific_compatible_shape(self, other) -> 'TensorShape':\n other = as_shape(other)\n if self.dims is None or other.dims is None or self.rank != other.rank:\n return unknown_shape()\n dims = [d1 if d1 is not None and d2 is not None and (d1 == d2) else None for d1, d2 in zip(self.dims, other.dims)]\n return TensorShape(dims)", "docstring": "Returns the most specific TensorShape compatible with `self` and `other`.\n\n * TensorShape([None, 1]) is the most specific TensorShape compatible with\n both TensorShape([2, 1]) and TensorShape([5, 1]). Note that\n TensorShape(None) is also compatible with above mentioned TensorShapes.\n\n * TensorShape([1, 2, 3]) is the most specific TensorShape compatible with\n both TensorShape([1, 2, 3]) and TensorShape([1, 2, 3]). There are more\n less specific TensorShapes compatible with above mentioned TensorShapes,\n e.g. TensorShape([1, 2, None]), TensorShape(None).\n\nArgs:\n other: Another `TensorShape`.\n\nReturns:\n A `TensorShape` which is the most specific compatible shape of `self`\n and `other`.", "source": "github_repos"} +{"code": "def _replacer(self, match: re.Match[str], is_verbatim: bool, is_global: bool) -> str:\n symbol_name = match.group(0)\n if symbol_name in self._local_symbol_replacement_cache:\n return self._local_symbol_replacement_cache[symbol_name]\n if symbol_name in self._global_symbol_replacement_cache:\n return self._global_symbol_replacement_cache[symbol_name]\n if is_verbatim:\n declaration_replacement = symbol_name\n reference_replacement = symbol_name\n else:\n capture_name = self._generate_unique_name(symbol_name)\n capture_pattern = '[^ ]+'\n maybe_global_flag = '$' if is_global else ''\n declaration_replacement = f'[[{maybe_global_flag}{capture_name}:{capture_pattern}]]'\n reference_replacement = f'[[{maybe_global_flag}{capture_name}]]'\n if is_global:\n self._global_symbol_replacement_cache[symbol_name] = reference_replacement\n else:\n self._local_symbol_replacement_cache[symbol_name] = reference_replacement\n return declaration_replacement", "docstring": "A symbol-name replacement function for use in `re.sub`.\n\nArgs:\n match: The match object produced by `self._SYMBOL_NAME_REGEX`.\n is_verbatim: Whether the newly matched symbol appears in a \"CHECK-LABEL\"\n directive, in which case it should be checked verbatim (not replaced\n with a regex capture).\n is_global: Whether the newly matched symbol appears in a declaration at\n global scope, i.e. whether it's a function name. If so, it should be\n remembered across function boundaries.\n\nReturns:\n The replacement string for the symbol name.", "source": "github_repos"} +{"code": "def _model_setup():\n context.set_log_device_placement(True)\n batch_size = 64\n steps = 2\n with collective_strategy.CollectiveAllReduceStrategy().scope():\n train_ds, _ = mnist_testing_utils.mnist_synthetic_dataset(batch_size, steps)\n model = mnist_testing_utils.get_mnist_model((28, 28, 1))\n return (batch_size, steps, train_ds, model)", "docstring": "Set up a MNIST Keras model for testing purposes.\n\n Builds a MNIST Keras model and returns model information.\n\nReturns:\n A tuple of (batch_size, steps, train_dataset, mode)", "source": "github_repos"} +{"code": "def __init__(self, name='logcosh', dtype=None):\n super(LogCoshError, self).__init__(logcosh, name, dtype=dtype)", "docstring": "Computes the logarithm of the hyperbolic cosine of the prediction error.\n\n `logcosh = log((exp(x) + exp(-x))/2)`, where x is the error (y_pred - y_true)\n\nArgs:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n\n Standalone usage:\n\n >>> m = tf.keras.metrics.LogCoshError()\n >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])\n >>> m.result().numpy()\n 0.10844523\n\n >>> m.reset_state()\n >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],\n ... sample_weight=[1, 0])\n >>> m.result().numpy()\n 0.21689045\n\n Usage with `compile()` API:\n\n ```python\n model.compile(optimizer='sgd',\n loss='mse',\n metrics=[tf.keras.metrics.LogCoshError()])\n ```", "source": "github_repos"} +{"code": "def __init__(self, model, preprocess_input=None, input_dtype=None, feature_description=None, **kwargs):\n \"\"\"\nmodel: model: Base tensorflow model used for TFX-BSL RunInference transform.\npreprocess_input: Preprocess method to be included as part of the\n model's serving signature.\ninput_dtype: tf dtype of the inputs passed to the model.\n For eg: tf.int32, tf.uint8.\nfeature_description: Feature spec to parse inputs from tf.train.Example\n using tf.parse_example(). For more details, please take a look at\n https://www.tensorflow.org/api_docs/python/tf/io/parse_example\nIf there are extra arguments(for eg: training=False) that should be\npassed to the base tf model during inference, please pass them in kwargs.\n\"\"\"\n super().__init__()\n self.model = model\n self.preprocess_input = preprocess_input\n self.input_dtype = input_dtype\n self.feature_description = feature_description\n if not feature_description:\n self.feature_description = {'image': tf.io.FixedLenFeature((), tf.string)}\n self._kwargs = kwargs", "docstring": "Helper class used to wrap a based tf.keras.Model object with a serving\n signature that can passed to the tfx_bsl RunInference transform.\n\n A TF model saved using this helper class expects inputs as\n images serialized to tf.string using tf.io.parse_tensor\n and then passing serialized images to the RunInference transform\n in the tf.train.Example. More about tf.train.Example at\n https://www.tensorflow.org/api_docs/python/tf/train/Example\n\n Usage:\n Step 1:\n # Save the base TF model with modified signature .\n signature_model = TFModelWrapperWithSignature(\n model=model,\n preprocess_input=preprocess_input,\n input_dtype=input_dtype,\n feature_description=feature_description,\n **kwargs\n )\n tf.saved_model.save(signature_model, path)\n\n Step 2:\n # Load the saved_model in the beam pipeline to create ModelHandler.\n saved_model_spec = model_spec_pb2.SavedModelSpec(\n model_path=known_args.model_path)\n inferece_spec_type = model_spec_pb2.InferenceSpecType(\n saved_model_spec=saved_model_spec)\n model_handler = CreateModelHandler(inferece_spec_type)", "source": "github_repos"} +{"code": "def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:\n if token_ids_1 is None:\n raise ValueError('With TAPAS, you must provide both question IDs and table IDs.')\n return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1", "docstring": "Build model inputs from a question and flattened table for question answering or sequence classification tasks\n by concatenating and adding special tokens.\n\nArgs:\n token_ids_0 (`List[int]`): The ids of the question.\n token_ids_1 (`List[int]`, *optional*): The ids of the flattened table.\n\nReturns:\n `List[int]`: The model input with special tokens.", "source": "github_repos"} +{"code": "def _SparseReorderGrad(op: ops.Operation, unused_output_indices_grad, output_values_grad):\n input_indices = op.inputs[0]\n input_shape = op.inputs[2]\n num_entries = array_ops.shape(input_indices)[0]\n entry_indices = math_ops.range(num_entries)\n sp_unordered = sparse_tensor.SparseTensor(input_indices, entry_indices, input_shape)\n sp_ordered = sparse_ops.sparse_reorder(sp_unordered)\n inverted_permutation = array_ops.invert_permutation(sp_ordered.values)\n return (None, array_ops.gather(output_values_grad, inverted_permutation), None)", "docstring": "Gradients for the SparseReorder op.\n\nArgs:\n op: the SparseReorder op\n unused_output_indices_grad: the incoming gradients of the output indices\n output_values_grad: the incoming gradients of the output values\n\nReturns:\n Gradient for each of the 3 input tensors:\n (input_indices, input_values, input_shape)\n The gradients for input_indices and input_shape is None.", "source": "github_repos"} +{"code": "def write_model(model_object, output_tflite_file):\n if sys.byteorder == 'big':\n model_object = copy.deepcopy(model_object)\n byte_swap_tflite_model_obj(model_object, 'big', 'little')\n model_bytearray = convert_object_to_bytearray(model_object)\n with gfile.GFile(output_tflite_file, 'wb') as output_file_handle:\n output_file_handle.write(model_bytearray)", "docstring": "Writes the tflite model, a python object, into the output file.\n\n NOTE: This API only works for TFLite generated with\n _experimental_use_buffer_offset=false\n\nArgs:\n model_object: A tflite model as a python object\n output_tflite_file: Full path name to the output tflite file.\n\nRaises:\n IOError: If output_tflite_file path is invalid or cannot be opened.", "source": "github_repos"} +{"code": "def lu_matrix_inverse(lower_upper, perm, validate_args=False, name=None):\n with ops.name_scope(name or 'lu_matrix_inverse'):\n lower_upper = ops.convert_to_tensor(lower_upper, dtype_hint=dtypes.float32, name='lower_upper')\n perm = ops.convert_to_tensor(perm, dtype_hint=dtypes.int32, name='perm')\n assertions = lu_reconstruct_assertions(lower_upper, perm, validate_args)\n if assertions:\n with ops.control_dependencies(assertions):\n lower_upper = array_ops.identity(lower_upper)\n perm = array_ops.identity(perm)\n shape = array_ops.shape(lower_upper)\n return lu_solve(lower_upper, perm, rhs=eye(shape[-1], batch_shape=shape[:-2], dtype=lower_upper.dtype), validate_args=False)", "docstring": "Computes the inverse given the LU decomposition(s) of one or more matrices.\n\n This op is conceptually identical to,\n\n ```python\n inv_X = tf.lu_matrix_inverse(*tf.linalg.lu(X))\n tf.assert_near(tf.matrix_inverse(X), inv_X)\n # ==> True\n ```\n\n Note: this function does not verify the implied matrix is actually invertible\n nor is this condition checked even when `validate_args=True`.\n\nArgs:\n lower_upper: `lu` as returned by `tf.linalg.lu`, i.e., if `matmul(P,\n matmul(L, U)) = X` then `lower_upper = L + U - eye`.\n perm: `p` as returned by `tf.linag.lu`, i.e., if `matmul(P, matmul(L, U)) =\n X` then `perm = argmax(P)`.\n validate_args: Python `bool` indicating whether arguments should be checked\n for correctness. Note: this function does not verify the implied matrix is\n actually invertible, even when `validate_args=True`.\n Default value: `False` (i.e., don't validate arguments).\n name: Python `str` name given to ops managed by this object.\n Default value: `None` (i.e., 'lu_matrix_inverse').\n\nReturns:\n inv_x: The matrix_inv, i.e.,\n `tf.matrix_inverse(tf.linalg.lu_reconstruct(lu, perm))`.\n\n #### Examples\n\n ```python\n import numpy as np\n import tensorflow as tf\n import tensorflow_probability as tfp\n\n x = [[[3., 4], [1, 2]],\n [[7., 8], [3, 4]]]\n inv_x = tf.linalg.lu_matrix_inverse(*tf.linalg.lu(x))\n tf.assert_near(tf.matrix_inverse(x), inv_x)\n # ==> True\n ```", "source": "github_repos"} +{"code": "def _prepare_images_structure(self, images: ImageInput) -> ImageInput:\n return make_flat_list_of_images(images)", "docstring": "Prepare the images structure for processing.\n\nArgs:\n images (`ImageInput`):\n The input images to process.\n\nReturns:\n `ImageInput`: The images with a valid nesting.", "source": "github_repos"} +{"code": "def update_hash_with_array(hash_value, int_array):\n if int_array is not None:\n for i in int_array:\n hash_value = update_hash_with_primitive_value(hash_value, i)\n return hash_value", "docstring": "Update the hash value using a TFLite int array.\n\nArgs:\n hash_value (int): The current hash value.\n int_array: A TFLite int array to incorporate into the hash.\n\nReturns:\n int: The updated hash value.", "source": "github_repos"} +{"code": "def compute_local_attention_representations(self, global_k, global_v, local_q, local_k, local_v, mask, dim: DimensionInfo):\n blocked_local_q = local_q.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)\n blocked_local_k = local_k.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)\n blocked_local_v = local_v.view(dim.batch_size, dim.num_heads, dim.num_blocks, dim.block_size, dim.dim_per_head)\n extended_mask = nn.functional.pad(mask.view(dim.batch_size, dim.num_blocks, dim.block_size), pad=(dim.global_len, 0), value=0)\n blocked_local2global = torch.einsum('BHNKF,BHGF->BHNKG', blocked_local_q, global_k)\n blocked_local2local = torch.einsum('BHNKF,BHNXF->BHNKX', blocked_local_q, blocked_local_k)\n attn_weights = torch.cat([blocked_local2global, blocked_local2local], dim=-1)\n attn_weights = attn_weights + extended_mask[:, None, :, None, :]\n attn_probs = nn.functional.softmax(attn_weights, dim=-1)\n attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)\n local2global_attn_probs = attn_probs[:, :, :, :, :dim.global_len]\n local2local_attn_probs = attn_probs[:, :, :, :, dim.global_len:]\n local2global_attn_output = torch.einsum('BHNKG,BHGF->BHNKF', local2global_attn_probs, global_v)\n local2local_attn_output = torch.einsum('BHNKX,BHNXF->BHNKF', local2local_attn_probs, blocked_local_v)\n attn_output = local2global_attn_output + local2local_attn_output\n return (attn_output, attn_probs)", "docstring": "Compute attention representations for local tokens.\n\n Local tokens will attend to both global tokens as well as all other tokens within the same local block. Hence,\n we need to tile and concatenate the global tokens to every local block\n\nArgs:\n global_k (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:\n key vectors from global tokens\n global_v (`torch.FloatTensor`) of shape [batch_size, num_heads, global_len, dim_per_head]:\n value vectors from global tokens\n local_q (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:\n query vectors from local tokens\n local_k (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:\n key vectors from local tokens\n local_v (`torch.FloatTensor`) of shape [batch_size, num_heads, padded_seq_len, dim_per_head]:\n value vectors from local tokens\n mask (`torch.FloatTensor`) of shape [batch_size, padded_seq_len]: attention mask\n dim (DimensionInfo): DimensionInfo wrapper for dimensions\n\nReturns:\n output of shape `[batch_sizes, length, features]`. where length will be padded to a multiple of block_size", "source": "github_repos"} +{"code": "def __getitem__(self, index):\n raise NotImplementedError", "docstring": "Gets batch at position `index`.\n\nArgs:\n index: position of the batch in the Sequence.\n\nReturns:\n A batch", "source": "github_repos"} +{"code": "def lu_factor(x):\n if any_symbolic_tensors((x,)):\n return LuFactor().symbolic_call(x)\n return _lu_factor(x)", "docstring": "Computes the lower-upper decomposition of a square matrix.\n\nArgs:\n x: A tensor of shape `(..., M, M)`.\n\nReturns:\n A tuple of two tensors: a tensor of shape `(..., M, M)` containing the\n lower and upper triangular matrices and a tensor of shape `(..., M)`\n containing the pivots.", "source": "github_repos"} +{"code": "def test_sample_paths_1d(self, use_batch, watch_params, supply_normal_draws, random_type):\n dtype = tf.float64\n mu = 0.2\n a = 0.4\n b = 0.33\n\n def drift_fn(t, x):\n drift = mu * tf.sqrt(t) * tf.ones_like(x, dtype=t.dtype)\n return drift\n\n def vol_fn(t, x):\n del x\n if not use_batch:\n return (a * t + b) * tf.ones([1, 1], dtype=t.dtype)\n else:\n return (a * t + b) * tf.ones([2, 1, 1, 1], dtype=t.dtype)\n times = np.array([0.0, 0.1, 0.21, 0.32, 0.43, 0.55])\n num_samples = 10000\n if supply_normal_draws:\n normal_draws = tf.random.stateless_normal(shape=[2, 5000, 55, 1], seed=[1, 42], dtype=dtype)\n normal_draws = tf.concat([normal_draws, -normal_draws], axis=1)\n else:\n normal_draws = None\n if use_batch:\n x0 = np.array([[[0.1]], [[0.1]]])\n else:\n x0 = np.array([0.1])\n paths = self.evaluate(euler_sampling.sample(dim=1, drift_fn=drift_fn, volatility_fn=vol_fn, times=times, num_samples=num_samples, initial_state=x0, random_type=random_type, normal_draws=normal_draws, watch_params=watch_params, time_step=0.01, seed=[1, 42], dtype=dtype))\n paths_no_zero = self.evaluate(euler_sampling.sample(dim=1, drift_fn=drift_fn, volatility_fn=vol_fn, times=times[1:], num_samples=num_samples, initial_state=x0, random_type=random_type, normal_draws=normal_draws, time_step=0.01, seed=[1, 42], dtype=dtype))\n with self.subTest('CorrectShape'):\n if not use_batch:\n self.assertAllClose(paths.shape, (num_samples, 6, 1), atol=0)\n else:\n self.assertAllClose(paths.shape, (2, num_samples, 6, 1), atol=0)\n if not use_batch:\n means = np.mean(paths, axis=0).reshape(-1)\n else:\n means = np.mean(paths, axis=1).reshape([2, 1, 6])\n expected_means = x0 + 2.0 / 3.0 * mu * np.power(times, 1.5)\n with self.subTest('ExpectedResult'):\n self.assertAllClose(means, expected_means, rtol=0.01, atol=0.01)\n if not use_batch:\n with self.subTest('IncludeInitialState'):\n self.assertAllClose(paths[:, 1:, :], paths_no_zero)", "docstring": "Tests path properties for 1-dimentional Ito process.\n\n We construct the following Ito process.\n\n ````\n dX = mu * sqrt(t) * dt + (a * t + b) dW\n ````\n\n For this process expected value at time t is x_0 + 2/3 * mu * t^1.5 .\n\nArgs:\n use_batch: Test parameter to specify if we are testing the batch of Euler\n sampling.\n watch_params: Triggers custom for loop.\n supply_normal_draws: Supply normal draws.\n random_type: `RandomType` of the sampled normal draws.", "source": "github_repos"} +{"code": "def save(self, file_prefix, checkpoint_number=None, session=None, options=None):\n options = options or checkpoint_options.CheckpointOptions()\n feed_dict = {}\n use_session = not context.executing_eagerly() and (not ops.inside_function())\n if checkpoint_number:\n file_prefix = '%s-%d' % (file_prefix, checkpoint_number)\n if use_session:\n if self._object_graph_feed_tensor is None:\n with ops.device('/cpu:0'):\n self._object_graph_feed_tensor = constant_op.constant('', dtype=dtypes.string)\n self._file_prefix_feed_tensor = constant_op.constant('', dtype=dtypes.string)\n object_graph_tensor = self._object_graph_feed_tensor\n file_prefix_tensor = self._file_prefix_feed_tensor\n feed_dict[file_prefix_tensor] = file_prefix\n else:\n with ops.device('/cpu:0'):\n file_prefix_tensor = ops.convert_to_tensor(file_prefix, dtype=dtypes.string)\n object_graph_tensor = None\n if not tensor_util.is_tensor(file_prefix):\n file_io.recursive_create_dir(os.path.dirname(file_prefix))\n save_path, new_feed_additions = self._save_cached_when_graph_building(file_prefix_tensor, object_graph_tensor, options)\n if new_feed_additions:\n feed_dict.update(new_feed_additions)\n if not use_session:\n session = None\n elif session is None:\n session = get_session()\n if session:\n return session.run(save_path, feed_dict=feed_dict)\n elif use_session:\n raise RuntimeError(f'Unable to save checkpoint to \"{file_prefix}\" in graph mode without a default session. Please use `with tf.Session():` to create a session.')\n else:\n return save_path", "docstring": "Save a training checkpoint.\n\n The saved checkpoint includes variables created by this object and any\n Trackable objects it depends on at the time `Saver.save()` is called.\n\nArgs:\n file_prefix: A prefix to use for the checkpoint filenames\n (/path/to/directory/and_a_prefix). Names are generated based on this\n prefix and `checkpoint_number`, if provided.\n checkpoint_number: An integer variable or Tensor, used to number\n checkpoints. Typically this value is saved along with other variables in\n training checkpoints, which will happen automatically if it was created\n by `root_trackable` or one of its dependencies (via\n `Trackable._add_variable`).\n session: The session to evaluate variables in. Ignored when executing\n eagerly. If not provided when graph building, the default session is\n used.\n options: Optional `tf.train.CheckpointOptions` object.\n\nReturns:\n The full path to the checkpoint.\n\nRaises:\n RuntimeError: if called in V1 Graph mode without a default session.", "source": "github_repos"} +{"code": "def Py3GetFullArgSpec(fn):\n try:\n sig = inspect._signature_from_callable(fn, skip_bound_arg=True, follow_wrapper_chains=True, sigcls=inspect.Signature)\n except Exception:\n raise TypeError('Unsupported callable.')\n args = []\n varargs = None\n varkw = None\n kwonlyargs = []\n defaults = ()\n annotations = {}\n defaults = ()\n kwdefaults = {}\n if sig.return_annotation is not sig.empty:\n annotations['return'] = sig.return_annotation\n for param in sig.parameters.values():\n kind = param.kind\n name = param.name\n if kind is inspect._POSITIONAL_ONLY:\n args.append(name)\n elif kind is inspect._POSITIONAL_OR_KEYWORD:\n args.append(name)\n if param.default is not param.empty:\n defaults += (param.default,)\n elif kind is inspect._VAR_POSITIONAL:\n varargs = name\n elif kind is inspect._KEYWORD_ONLY:\n kwonlyargs.append(name)\n if param.default is not param.empty:\n kwdefaults[name] = param.default\n elif kind is inspect._VAR_KEYWORD:\n varkw = name\n if param.annotation is not param.empty:\n annotations[name] = param.annotation\n if not kwdefaults:\n kwdefaults = None\n if not defaults:\n defaults = None\n return inspect.FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwdefaults, annotations)", "docstring": "A alternative to the builtin getfullargspec.\n\n The builtin inspect.getfullargspec uses:\n `skip_bound_args=False, follow_wrapped_chains=False`\n in order to be backwards compatible.\n\n This function instead skips bound args (self) and follows wrapped chains.\n\nArgs:\n fn: The function or class of interest.\n\nReturns:\n An inspect.FullArgSpec namedtuple with the full arg spec of the function.", "source": "github_repos"} +{"code": "def load(archive_file: fhir_package.PackageSource) -> fhir_package.FhirPackage[structure_definition_pb2.StructureDefinition, search_parameter_pb2.SearchParameter, code_system_pb2.CodeSystem, value_set_pb2.ValueSet]:\n return fhir_package.FhirPackage.load(archive_file, _PRIMITIVE_HANDLER, structure_definition_pb2.StructureDefinition, search_parameter_pb2.SearchParameter, code_system_pb2.CodeSystem, value_set_pb2.ValueSet)", "docstring": "Instantiates and returns a new `FhirPackage` for FHIR R4.\n\nArgs:\n archive_file: The zip or tar file path or a function returning a file-like\n containing resources represented by this collection.\n\nReturns:\n An instance of `FhirPackage`.\n\nRaises:\n ValueError: In the event that the file or contents are invalid.", "source": "github_repos"} +{"code": "def prefer_static_broadcast_shape(shape1, shape2, name='prefer_static_broadcast_shape'):\n with ops.name_scope(name, values=[shape1, shape2]):\n\n def make_shape_tensor(x):\n return ops.convert_to_tensor(x, name='shape', dtype=dtypes.int32)\n\n def get_tensor_shape(s):\n if isinstance(s, tensor_shape.TensorShape):\n return s\n s_ = tensor_util.constant_value(make_shape_tensor(s))\n if s_ is not None:\n return tensor_shape.TensorShape(s_)\n return None\n\n def get_shape_tensor(s):\n if not isinstance(s, tensor_shape.TensorShape):\n return make_shape_tensor(s)\n if s.is_fully_defined():\n return make_shape_tensor(s.as_list())\n raise ValueError('Cannot broadcast from partially defined `TensorShape`.')\n shape1_ = get_tensor_shape(shape1)\n shape2_ = get_tensor_shape(shape2)\n if shape1_ is not None and shape2_ is not None:\n return array_ops.broadcast_static_shape(shape1_, shape2_)\n shape1_ = get_shape_tensor(shape1)\n shape2_ = get_shape_tensor(shape2)\n return array_ops.broadcast_dynamic_shape(shape1_, shape2_)", "docstring": "Convenience function which statically broadcasts shape when possible.\n\nArgs:\n shape1: `1-D` integer `Tensor`. Already converted to tensor!\n shape2: `1-D` integer `Tensor`. Already converted to tensor!\n name: A string name to prepend to created ops.\n\nReturns:\n The broadcast shape, either as `TensorShape` (if broadcast can be done\n statically), or as a `Tensor`.", "source": "github_repos"} +{"code": "def on_train_batch_begin(self, batch, logs=None):\n self.on_batch_begin(batch, logs=logs)", "docstring": "Called at the beginning of a training batch in `fit` methods.\n\n Subclasses should override for any actions to run.\n\n Note that if the `steps_per_execution` argument to `compile` in\n `Model` is set to `N`, this method will only be called every\n `N` batches.\n\nArgs:\n batch: Integer, index of batch within the current epoch.\n logs: Dict. Currently no data is passed to this argument for this\n method but that may change in the future.", "source": "github_repos"} +{"code": "def _cast_to_known_type(name):\n if name is None:\n return None\n return name.rstrip('.')", "docstring": "Canonicalizes a string representing a type if possible.\n\n # TODO(dbieber): Support additional canonicalization, such as string/str, and\n # boolean/bool.\n\nExample:\n _cast_to_known_type(\"str.\") == \"str\"\n\nArgs:\n name: A string representing a type, or None.\n\nReturns:\n A canonicalized version of the type string.", "source": "github_repos"} +{"code": "def get_type_parameters(self, annot, seen=None):\n seen = seen or set()\n if annot in seen or not annot.formal:\n return []\n if isinstance(annot, mixin.NestedAnnotation):\n seen = seen | {annot}\n if isinstance(annot, abstract.TypeParameter):\n return [annot]\n elif isinstance(annot, abstract.TupleClass):\n annots = []\n for idx in range(annot.tuple_length):\n annots.extend(self.get_type_parameters(annot.formal_type_parameters[idx], seen))\n return annots\n elif isinstance(annot, mixin.NestedAnnotation):\n return sum((self.get_type_parameters(t, seen) for _, t in annot.get_inner_types()), [])\n return []", "docstring": "Returns all the TypeParameter instances that appear in the annotation.\n\n Note that if you just need to know whether or not the annotation contains\n type parameters, you can check its `.formal` attribute.\n\nArgs:\n annot: An annotation.\n seen: A seen set.", "source": "github_repos"} +{"code": "def __init__(self, max_shard_bytes, max_shards=None, bytes_per_string=16):\n \"\"\"Creates a new `MaxSizePartitioner`.\n\nArgs:\n max_shard_bytes: The maximum size any given shard is allowed to be.\n max_shards: The maximum number of shards in `int` created taking\n precedence over `max_shard_bytes`.\n bytes_per_string: If the partition value is of type string, this provides\n an estimate of how large each string is.\n\"\"\"\n if max_shard_bytes < 1:\n raise ValueError(f'Argument `max_shard_bytes` must be positive. Received {max_shard_bytes}')\n if max_shards and max_shards < 1:\n raise ValueError(f'Argument `max_shards` must be positive. Received {max_shards}')\n if bytes_per_string < 1:\n raise ValueError(f'Argument `bytes_per_string` must be positive. Received: {bytes_per_string}')\n self._max_shard_bytes = max_shard_bytes\n self._max_shards = max_shards\n self._bytes_per_string = bytes_per_string", "docstring": "Partitioner that keeps shards below `max_shard_bytes`.\n\n This partitioner ensures each shard has at most `max_shard_bytes`, and tries\n to allocate as few shards as possible, i.e., keeping shard size as large\n as possible.\n\n If the partitioner hits the `max_shards` limit, then each shard may end up\n larger than `max_shard_bytes`. By default `max_shards` equals `None` and no\n limit on the number of shards is enforced.\n\nExample:\n >>> partitioner = MaxSizePartitioner(max_shard_bytes=4)\n >>> partitions = partitioner(tf.TensorShape([6, 1]), tf.float32)\n >>> [6, 1]\n >>> partitioner = MaxSizePartitioner(max_shard_bytes=4, max_shards=2)\n >>> partitions = partitioner(tf.TensorShape([6, 1]), tf.float32)\n >>> [2, 1]\n >>> partitioner = MaxSizePartitioner(max_shard_bytes=1024)\n >>> partitions = partitioner(tf.TensorShape([6, 1]), tf.float32)\n >>> [1, 1]\n >>>\n >>> # use in ParameterServerStrategy\n >>> # strategy = tf.distribute.experimental.ParameterServerStrategy(\n >>> # cluster_resolver=cluster_resolver, variable_partitioner=partitioner)", "source": "github_repos"} +{"code": "def _get_pmap_impl(f, devices, has_tpu):\n if has_tpu:\n output_is_list = [False]\n\n def recorder(args, kwargs, res):\n del args, kwargs\n output_is_list[0] = isinstance(res, list)\n return res\n f = _record_result_type(recorder, f)\n\n def tf_f(*tf_args):\n \"\"\"A wrapper for `f` that takes/returns tensors.\"\"\"\n np_args = _tf_to_np(tf_args)\n np_out = f(*np_args)\n return np_out\n if has_tpu:\n\n @polymorphic_function.function(autograph=False)\n def fn(inputs):\n res = tpu.replicate(tf_f, inputs)\n if res and isinstance(res[0], list) and (len(res[0]) == 1) and (not output_is_list[0]):\n res = [x[0] for x in res]\n return res\n return fn\n else:\n jit_tf_f = polymorphic_function.function(tf_f, autograph=False)\n\n @polymorphic_function.function(autograph=False)\n def fn(all_per_device_args):\n \"\"\"Multi-device function with calls placed on the correct device.\"\"\"\n results = []\n for per_device_args, device in zip(all_per_device_args, devices):\n with ops.device(device):\n results.append(jit_tf_f(*per_device_args))\n return results\n return fn", "docstring": "This is a helper function to return the pmap impl.\n\nArgs:\n f: a function that takes ndarrays and returns ndarrays.\n devices: a list of strings; the device list.\n has_tpu: boolean; whether `devices` contains TPU devices.\n\nReturns:\n A function that takes tensors and returns tensors.", "source": "github_repos"} +{"code": "def logdet(x):\n if any_symbolic_tensors((x,)):\n return Logdet().symbolic_call(x)\n return backend.math.logdet(x)", "docstring": "Computes log of the determinant of a hermitian positive definite matrix.\n\nArgs:\n x: Input matrix. It must 2D and square.\n\nReturns:\n The natural log of the determinant of matrix.", "source": "github_repos"} +{"code": "def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor]=None):\n pixel_values = pixel_values.type(self.visual.dtype)\n image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)\n return image_embeds", "docstring": "Encodes images into continuous embeddings that can be forwarded to the language model.\n\nArgs:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):\n The tensors corresponding to the input images.\n image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):\n The temporal, height and width of feature shape of each image in LLM.", "source": "github_repos"} +{"code": "def getqualifiedname(namespace, object_, max_depth=5, visited=None):\n if visited is None:\n visited = set()\n namespace = dict(namespace)\n for name in namespace:\n if object_ is namespace[name]:\n return name\n parent = tf_inspect.getmodule(object_)\n if parent is not None and parent is not object_ and (parent is not namespace):\n parent_name = getqualifiedname(namespace, parent, max_depth=0, visited=visited)\n if parent_name is not None:\n name_in_parent = getqualifiedname(parent.__dict__, object_, max_depth=0, visited=visited)\n assert name_in_parent is not None, 'An object should always be found in its owner module'\n return '{}.{}'.format(parent_name, name_in_parent)\n if max_depth:\n for name in namespace.keys():\n value = namespace[name]\n if tf_inspect.ismodule(value) and id(value) not in visited:\n visited.add(id(value))\n name_in_module = getqualifiedname(value.__dict__, object_, max_depth - 1, visited)\n if name_in_module is not None:\n return '{}.{}'.format(name, name_in_module)\n return None", "docstring": "Returns the name by which a value can be referred to in a given namespace.\n\n If the object defines a parent module, the function attempts to use it to\n locate the object.\n\n This function will recurse inside modules, but it will not search objects for\n attributes. The recursion depth is controlled by max_depth.\n\nArgs:\n namespace: Dict[str, Any], the namespace to search into.\n object_: Any, the value to search.\n max_depth: Optional[int], a limit to the recursion depth when searching\n inside modules.\n visited: Optional[Set[int]], ID of modules to avoid visiting.\n Returns: Union[str, None], the fully-qualified name that resolves to the value\n o, or None if it couldn't be found.", "source": "github_repos"} +{"code": "def _normalize_feature_columns(feature_columns):\n if isinstance(feature_columns, fc_types.FeatureColumn):\n feature_columns = [feature_columns]\n if isinstance(feature_columns, collections_abc.Iterator):\n feature_columns = list(feature_columns)\n if isinstance(feature_columns, dict):\n raise ValueError('Expected feature_columns to be iterable, found dict.')\n for column in feature_columns:\n if not isinstance(column, fc_types.FeatureColumn):\n raise ValueError('Items of feature_columns must be a FeatureColumn. Given (type {}): {}.'.format(type(column), column))\n if not feature_columns:\n raise ValueError('feature_columns must not be empty.')\n name_to_column = {}\n for column in feature_columns:\n if column.name in name_to_column:\n raise ValueError('Duplicate feature column name found for columns: {} and {}. This usually means that these columns refer to same base feature. Either one must be discarded or a duplicated but renamed item must be inserted in features dict.'.format(column, name_to_column[column.name]))\n name_to_column[column.name] = column\n return sorted(feature_columns, key=lambda x: x.name)", "docstring": "Normalizes the `feature_columns` input.\n\n This method converts the `feature_columns` to list type as best as it can. In\n addition, verifies the type and other parts of feature_columns, required by\n downstream library.\n\nArgs:\n feature_columns: The raw feature columns, usually passed by users.\n\nReturns:\n The normalized feature column list.\n\nRaises:\n ValueError: for any invalid inputs, such as empty, duplicated names, etc.", "source": "github_repos"} +{"code": "def returns_collection(self) -> bool:\n return self.cardinality == Cardinality.COLLECTION or self.cardinality == Cardinality.CHILD_OF_COLLECTION", "docstring": "Indicates if the data type will evaluate to a collection.\n\nReturns:\n True in the following circumstances\n - The data type represents an element with cardinality greater than one.\n - The data type represents an element with a cardinality less than or\n equal to one, but that element is a child of a collection and will\n evaluate to a collection. For example, the path Patient.name.use will\n return a collection, despite 'use' being a scalar, because it is a\n child of the collection, 'name.'\n False if the data type represents a scalar element whose parents are all\n also scalars.", "source": "github_repos"} +{"code": "def embed_check_categorical_event_shape(categorical_param, name='embed_check_categorical_event_shape'):\n with ops.name_scope(name, values=[categorical_param]):\n x = ops.convert_to_tensor(categorical_param, name='categorical_param')\n x_dtype = x.dtype.base_dtype\n max_event_size = _largest_integer_by_dtype(x_dtype) if x_dtype.is_floating else 0\n if max_event_size == 0:\n raise TypeError('Unable to validate size of unrecognized dtype ({}).'.format(x_dtype.name))\n try:\n x_shape_static = x.get_shape().with_rank_at_least(1)\n except ValueError:\n raise ValueError('A categorical-distribution parameter must have at least 1 dimension.')\n if tensor_shape.dimension_value(x_shape_static[-1]) is not None:\n event_size = x_shape_static.dims[-1].value\n if event_size < 2:\n raise ValueError('A categorical-distribution parameter must have at least 2 events.')\n if event_size > max_event_size:\n raise ValueError('Number of classes exceeds `dtype` precision, i.e., {} implies shape ({}) cannot exceed {}.'.format(x_dtype.name, event_size, max_event_size))\n return x\n else:\n event_size = array_ops.shape(x, name='x_shape')[-1]\n return control_flow_ops.with_dependencies([check_ops.assert_rank_at_least(x, 1, message='A categorical-distribution parameter must have at least 1 dimension.'), check_ops.assert_greater_equal(array_ops.shape(x)[-1], 2, message='A categorical-distribution parameter must have at least 2 events.'), check_ops.assert_less_equal(event_size, max_event_size, message='Number of classes exceeds `dtype` precision, i.e., {} dtype cannot exceed {} shape.'.format(x_dtype.name, max_event_size))], x)", "docstring": "Embeds checks that categorical distributions don't have too many classes.\n\n A categorical-type distribution is one which, e.g., returns the class label\n rather than a one-hot encoding. E.g., `Categorical(probs)`.\n\n Since distributions output samples in the same dtype as the parameters, we\n must ensure that casting doesn't lose precision. That is, the\n `parameter.dtype` implies a maximum number of classes. However, since shape is\n `int32` and categorical variables are presumed to be indexes into a `Tensor`,\n we must also ensure that the number of classes is no larger than the largest\n possible `int32` index, i.e., `2**31-1`.\n\n In other words the number of classes, `K`, must satisfy the following\n condition:\n\n ```python\n K <= min(\n int(2**31 - 1), # Largest float as an index.\n {\n dtypes.float16: int(2**11), # Largest int as a float16.\n dtypes.float32: int(2**24),\n dtypes.float64: int(2**53),\n }.get(categorical_param.dtype.base_dtype, 0))\n ```\n\nArgs:\n categorical_param: Floating-point `Tensor` representing parameters of\n distribution over categories. The rightmost shape is presumed to be the\n number of categories.\n name: A name for this operation (optional).\n\nReturns:\n categorical_param: Input `Tensor` with appropriate assertions embedded.\n\nRaises:\n TypeError: if `categorical_param` has an unknown `dtype`.\n ValueError: if we can statically identify `categorical_param` as being too\n large (for being closed under int32/float casting).", "source": "github_repos"} +{"code": "def __init__(self, cell, residual_fn=None, **kwargs):\n super(ResidualWrapperBase, self).__init__(cell, **kwargs)\n self._residual_fn = residual_fn", "docstring": "Constructs a `ResidualWrapper` for `cell`.\n\nArgs:\n cell: An instance of `RNNCell`.\n residual_fn: (Optional) The function to map raw cell inputs and raw cell\n outputs to the actual cell outputs of the residual network.\n Defaults to calling nest.map_structure on (lambda i, o: i + o), inputs\n and outputs.\n **kwargs: dict of keyword arguments for base layer.", "source": "github_repos"} +{"code": "def forward(self, pixel_values: torch.FloatTensor, bool_masked_pos: torch.BoolTensor, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[tuple, VideoMAEForPreTrainingOutput]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.videomae(pixel_values, bool_masked_pos=bool_masked_pos, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n sequence_output = outputs[0]\n sequence_output = self.encoder_to_decoder(sequence_output)\n batch_size, seq_len, num_channels = sequence_output.shape\n if bool_masked_pos is None:\n raise ValueError('One must provided a boolean mask ')\n expanded_position_embeddings = self.position_embeddings.expand(batch_size, -1, -1).type_as(pixel_values)\n expanded_position_embeddings = expanded_position_embeddings.detach().to(device=pixel_values.device, copy=True)\n pos_emb_visible = expanded_position_embeddings[~bool_masked_pos].reshape(batch_size, -1, num_channels)\n pos_emb_mask = expanded_position_embeddings[bool_masked_pos].reshape(batch_size, -1, num_channels)\n x_full = torch.cat([sequence_output + pos_emb_visible, self.mask_token + pos_emb_mask], dim=1)\n decoder_outputs = self.decoder(x_full, pos_emb_mask.shape[1])\n logits = decoder_outputs.logits\n loss = None\n with torch.no_grad():\n if self.config.num_channels != 3:\n frames = pixel_values\n else:\n device = pixel_values.device\n dtype = pixel_values.dtype\n mean = torch.as_tensor(IMAGENET_DEFAULT_MEAN).to(device=device, dtype=dtype)[None, None, :, None, None]\n std = torch.as_tensor(IMAGENET_DEFAULT_STD).to(device=device, dtype=dtype)[None, None, :, None, None]\n frames = pixel_values * std + mean\n batch_size, time, num_channels, height, width = frames.shape\n tubelet_size, patch_size = (self.config.tubelet_size, self.config.patch_size)\n if self.config.norm_pix_loss:\n frames = frames.view(batch_size, time // tubelet_size, tubelet_size, num_channels, height // patch_size, patch_size, width // patch_size, patch_size)\n frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()\n frames = frames.view(batch_size, time // tubelet_size * height // patch_size * width // patch_size, tubelet_size * patch_size * patch_size, num_channels)\n frames_norm = (frames - frames.mean(dim=-2, keepdim=True)) / (frames.var(dim=-2, unbiased=True, keepdim=True).sqrt() + 1e-06)\n videos_patch = frames_norm.view(batch_size, time // tubelet_size * height // patch_size * width // patch_size, tubelet_size * patch_size * patch_size * num_channels)\n else:\n if self.config.num_channels != 3:\n raise ValueError(\"Can't unnormalize non-RGB images. Consider setting config.norm_pix_loss to False.\")\n frames = frames.view(batch_size, time // tubelet_size, tubelet_size, num_channels, height // patch_size, patch_size, width // patch_size, patch_size)\n frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()\n videos_patch = frames.view(batch_size, time // tubelet_size * height // patch_size * width // patch_size, tubelet_size * patch_size * patch_size * num_channels)\n batch_size, _, num_channels = videos_patch.shape\n labels = videos_patch[bool_masked_pos].reshape(batch_size, -1, num_channels)\n loss_fct = MSELoss()\n loss = loss_fct(logits, labels)\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n return VideoMAEForPreTrainingOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):\n Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Each video in the\n batch must have the same number of masked patches. Sequence length is `(num_frames // tubelet_size) *\n (image_size // patch_size) ** 2`.\n\nExample:\n ```python\n >>> from transformers import AutoImageProcessor, VideoMAEForPreTraining\n >>> import numpy as np\n >>> import torch\n\n >>> num_frames = 16\n >>> video = list(np.random.randint(0, 256, (num_frames, 3, 224, 224)))\n\n >>> image_processor = AutoImageProcessor.from_pretrained(\"MCG-NJU/videomae-base\")\n >>> model = VideoMAEForPreTraining.from_pretrained(\"MCG-NJU/videomae-base\")\n\n >>> pixel_values = image_processor(video, return_tensors=\"pt\").pixel_values\n\n >>> num_patches_per_frame = (model.config.image_size // model.config.patch_size) ** 2\n >>> seq_length = (num_frames // model.config.tubelet_size) * num_patches_per_frame\n >>> bool_masked_pos = torch.randint(0, 2, (1, seq_length)).bool()\n\n >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)\n >>> loss = outputs.loss\n ```", "source": "github_repos"} +{"code": "def FormatTree(tree, style_config=None, lines=None):\n style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))\n comment_splicer.SpliceComments(tree)\n continuation_splicer.SpliceContinuations(tree)\n subtype_assigner.AssignSubtypes(tree)\n identify_container.IdentifyContainers(tree)\n split_penalty.ComputeSplitPenalties(tree)\n blank_line_calculator.CalculateBlankLines(tree)\n llines = pytree_unwrapper.UnwrapPyTree(tree)\n for lline in llines:\n lline.CalculateFormattingInformation()\n lines = _LineRangesToSet(lines)\n _MarkLinesToFormat(llines, lines)\n return reformatter.Reformat(_SplitSemicolons(llines), lines)", "docstring": "Format a parsed lib2to3 pytree.\n\n This provides an alternative entry point to YAPF.\n\nArgs:\n tree: (pytree.Node) The root of the pytree to format.\n style_config: (string) Either a style name or a path to a file that contains\n formatting style settings. If None is specified, use the default style\n as set in style.DEFAULT_STYLE_FACTORY\n lines: (list of tuples of integers) A list of tuples of lines, [start, end],\n that we want to format. The lines are 1-based indexed. It can be used by\n third-party code (e.g., IDEs) when reformatting a snippet of code rather\n than a whole file.\n\nReturns:\n The source formatted according to the given formatting style.", "source": "github_repos"} +{"code": "def get_keras_mask(x):\n return get_tensor_attr(x, '_keras_mask')", "docstring": "Gets the Keras mask attribute from the given tensor.\n\nArgs:\n x: Input tensor.\n\nReturns:\n The mask tensor associated with the input tensor, or `None` if no mask\n has been set.", "source": "github_repos"} +{"code": "def build_graph(device, n, m, k, transpose_a, transpose_b, dtype):\n with ops.device('%s' % device):\n if not transpose_a:\n x = variable_v1.VariableV1(random_ops.random_uniform([n, m], dtype=dtype), use_resource=False)\n else:\n x = variable_v1.VariableV1(random_ops.random_uniform([m, n], dtype=dtype), use_resource=False)\n if not transpose_b:\n y = variable_v1.VariableV1(random_ops.random_uniform([m, k], dtype=dtype), use_resource=False)\n else:\n y = variable_v1.VariableV1(random_ops.random_uniform([k, m], dtype=dtype), use_resource=False)\n z = math_ops.matmul(x, y, transpose_a=transpose_a, transpose_b=transpose_b)\n return control_flow_ops.group(z)", "docstring": "Build a graph containing a sequence of matmul operations.\n\nArgs:\n device: String, the device to run on.\n n: tensor A's first dimension size.\n m: tensor A's second dimension size.\n k: tensor B's second dimension size.\n transpose_a: boolean value to show if tensor A is transposed.\n transpose_b: boolean value to show if tensor B is transposed.\n dtype: numpy data type of the input tensor.\n\nReturns:\n A matmul operation to run()", "source": "github_repos"} +{"code": "def random_masking(self, sequence: tf.Tensor, noise: tf.Tensor | None=None):\n batch_size, seq_length, dim = shape_list(sequence)\n len_keep = int(seq_length * (1 - self.config.mask_ratio))\n if noise is None:\n noise = tf.random.uniform(shape=(batch_size, seq_length), minval=0.0, maxval=1.0)\n ids_shuffle = tf.argsort(noise, axis=1)\n ids_restore = tf.argsort(ids_shuffle, axis=1)\n ids_keep = ids_shuffle[:, :len_keep]\n sequence_unmasked = tf.gather(sequence, axis=1, batch_dims=1, indices=ids_keep)\n mask_keep = tf.zeros((batch_size, len_keep))\n mask_remove = tf.ones((batch_size, seq_length - len_keep))\n mask = tf.concat([mask_keep, mask_remove], axis=-1)\n mask = tf.gather(mask, axis=1, batch_dims=1, indices=ids_restore)\n return (sequence_unmasked, mask, ids_restore)", "docstring": "Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random\n noise.\n\nArgs:\n sequence (`tf.Tensor` of shape `(batch_size, sequence_length, dim)`)\n noise (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*) which is\n mainly used for testing purposes to control randomness and maintain the reproducibility", "source": "github_repos"} +{"code": "def sheets_tab_id(config, auth, sheet_url_or_name, sheet_tab):\n sheet_id = None\n tab_id = None\n spreadsheet = sheets_get(config, auth, sheet_url_or_name)\n if spreadsheet:\n sheet_id = spreadsheet['spreadsheetId']\n for tab in spreadsheet.get('sheets', []):\n if tab['properties']['title'] == sheet_tab:\n tab_id = tab['properties']['sheetId']\n break\n return (sheet_id, tab_id)", "docstring": "Pull sheet tab id from URL, name, or id itself.\n\nArgs:\n config - see starthinker/util/configuration.py\n auth - user or service\n url_or_name - one of: URL, document title, or id\n sheet_tab - name of tab to get id for\n\nReturns:\n Pair of sheet id and tab id.", "source": "github_repos"} +{"code": "def to_pil_image(self, image, rescale=None):\n self._ensure_format_supported(image)\n if is_torch_tensor(image):\n image = image.numpy()\n if isinstance(image, np.ndarray):\n if rescale is None:\n rescale = isinstance(image.flat[0], np.floating)\n if image.ndim == 3 and image.shape[0] in [1, 3]:\n image = image.transpose(1, 2, 0)\n if rescale:\n image = image * 255\n image = image.astype(np.uint8)\n return PIL.Image.fromarray(image)\n return image", "docstring": "Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if\n needed.\n\nArgs:\n image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):\n The image to convert to the PIL Image format.\n rescale (`bool`, *optional*):\n Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will\n default to `True` if the image type is a floating type, `False` otherwise.", "source": "github_repos"} +{"code": "def starting_wall_time(self):\n return self._starting_wall_time", "docstring": "Get the starting timestamp of the instrumented TensorFlow program.\n\n When there are multiple hosts (i.e., multiple tfdbg file sets), the earliest\n timestamp among the file sets is returned. It is assumed to be the job that\n starts first (e.g., the coordinator).\n\nReturns:\n Starting timestamp in seconds since the epoch, as a float.", "source": "github_repos"} +{"code": "def before_run(self, run_context):\n if not self._grpc_debug_wrapper_session:\n self._grpc_debug_wrapper_session = grpc_wrapper.GrpcDebugWrapperSession(run_context.session, self._grpc_debug_server_addresses, watch_fn=self._watch_fn, thread_name_filter=self._thread_name_filter)\n fetches = run_context.original_args.fetches\n feed_dict = run_context.original_args.feed_dict\n watch_options = self._watch_fn(fetches, feed_dict)\n run_options = config_pb2.RunOptions()\n debug_utils.watch_graph(run_options, run_context.session.graph, debug_urls=self._grpc_debug_wrapper_session.prepare_run_debug_urls(fetches, feed_dict), debug_ops=watch_options.debug_ops, node_name_regex_allowlist=watch_options.node_name_regex_allowlist, op_type_regex_allowlist=watch_options.op_type_regex_allowlist, tensor_dtype_regex_allowlist=watch_options.tensor_dtype_regex_allowlist, tolerate_debug_op_creation_failures=watch_options.tolerate_debug_op_creation_failures)\n return session_run_hook.SessionRunArgs(None, feed_dict=None, options=run_options)", "docstring": "Called right before a session is run.\n\nArgs:\n run_context: A session_run_hook.SessionRunContext. Encapsulates\n information on the run.\n\nReturns:\n A session_run_hook.SessionRunArgs object.", "source": "github_repos"} +{"code": "def split(pcoll, regex, outputEmpty=False):\n regex = Regex._regex_compile(regex)\n outputEmpty = bool(outputEmpty)\n\n def _process(element):\n r = regex.split(element)\n if r and (not outputEmpty):\n r = list(filter(None, r))\n yield r\n return pcoll | FlatMap(_process)", "docstring": "Returns the list string which was splitted on the basis of regular\n expression. It will not output empty items (by defaults).\n\nArgs:\n regex: the regular expression string or (re.compile) pattern.\n outputEmpty: (optional) Should empty be output. True to output empties\n and false if not.", "source": "github_repos"} +{"code": "def functions_to_serialize(self, serialization_cache):\n raise NotImplementedError", "docstring": "Returns extra functions to include when serializing a Keras object.\n\n Normally, when calling exporting an object to SavedModel, only the\n functions and objects defined by the user are saved. For example:\n\n ```\n obj = tf.Module()\n obj.v = tf.Variable(1.)\n\n @tf.function\n def foo(...): ...\n\n obj.foo = foo\n\n w = tf.Variable(1.)\n\n tf.saved_model.save(obj, 'path/to/saved/model')\n loaded = tf.saved_model.load('path/to/saved/model')\n\n loaded.v # Variable with the same value as obj.v\n loaded.foo # Equivalent to obj.foo\n loaded.w # AttributeError\n ```\n\n Assigning trackable objects to attributes creates a graph, which is used for\n both checkpointing and SavedModel serialization.\n\n When the graph generated from attribute tracking is insufficient, extra\n objects and functions may be added at serialization time. For example,\n most models do not have their call function wrapped with a @tf.function\n decorator. This results in `model.call` not being saved. Since Keras objects\n should be revivable from the SavedModel format, the call function is added\n as an extra function to serialize.\n\n This function and `objects_to_serialize` is called multiple times when\n exporting to SavedModel. Please use the cache to avoid generating new\n functions and objects. A fresh cache is created for each SavedModel export.\n\nArgs:\n serialization_cache: Dictionary passed to all objects in the same object\n graph during serialization.\n\nReturns:\n A dictionary mapping attribute names to `Function` or\n `ConcreteFunction`.", "source": "github_repos"} +{"code": "def __init__(self, options, autograph_module=None):\n self.options = options\n self.autograph_module = autograph_module", "docstring": "ProgramContext keeps track of converting function hierarchies.\n\nAttributes:\n options: ConversionOptions\n autograph_module: Deprecated. Do not use.", "source": "github_repos"} +{"code": "def _MaxPoolAlongRows(self, input_matrix, row_seq, overlapping):\n output_image = np.zeros(input_matrix.shape[1])\n row_max = row_seq[-1]\n for i in range(row_seq.shape[0] - 1):\n row_start = row_seq[i]\n row_end = row_seq[i + 1] + 1 if overlapping else row_seq[i + 1]\n row_end = min(row_end, row_max)\n output_image = np.vstack((output_image, np.amax(input_matrix[row_start:row_end, :], axis=0)))\n return output_image[1:, :]", "docstring": "Perform max pool along row of a 2-D matrix based on row_seq.\n\nArgs:\n input_matrix: A 2-D matrix.\n row_seq: Cumulative pooling sequence along row.\n overlapping: Whether or not use overlapping when pooling.\n\nReturns:\n A 2-D matrix, with\n * num_rows = len(row_seq)-1\n * num_cols = input_matrix.num_cols.", "source": "github_repos"} +{"code": "def account_displayed_op_only(self, is_true):\n self._options['account_displayed_op_only'] = is_true\n return self", "docstring": "Whether only account the statistics of displayed profiler nodes.\n\nArgs:\n is_true: If true, only account statistics of nodes eventually\n displayed by the outputs.\n Otherwise, a node's statistics are accounted by its parents\n as long as it's types match 'account_type_regexes', even if\n it is hidden from the output, say, by hide_name_regexes.\n\nReturns:\n self", "source": "github_repos"} +{"code": "def _prepare_4d_causal_attention_mask_with_cache_position(attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, cache_position: torch.Tensor, batch_size: int, config: MoshiDepthConfig, past_key_values: Cache):\n if attention_mask is not None and attention_mask.dim() == 4:\n causal_mask = attention_mask\n else:\n min_dtype = torch.finfo(dtype).min\n causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device)\n diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)\n text_config = config.get_text_config()\n if getattr(text_config, 'use_sliding_window', True) and text_config.sliding_window is not None:\n if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:\n sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= cache_position.reshape(-1, 1) - text_config.sliding_window\n diagonal_attend_mask.bitwise_or_(sliding_attend_mask)\n causal_mask *= diagonal_attend_mask\n causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)\n if attention_mask is not None:\n causal_mask = causal_mask.clone()\n if attention_mask.shape[-1] > target_length:\n attention_mask = attention_mask[:, :target_length]\n mask_length = attention_mask.shape[-1]\n padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)\n padding_mask = padding_mask == 0\n causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(padding_mask, min_dtype)\n return causal_mask", "docstring": "Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape\n `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.\n\nArgs:\n attention_mask (`torch.Tensor`):\n A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.\n sequence_length (`int`):\n The sequence length being processed.\n target_length (`int`):\n The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.\n dtype (`torch.dtype`):\n The dtype to use for the 4D attention mask.\n cache_position (`torch.Tensor`):\n Indices depicting the position of the input sequence tokens in the sequence.\n batch_size (`torch.Tensor`):\n Batch size.\n config (`MoshiDepthConfig`):\n The model's configuration class\n past_key_values (`Cache`):\n The cache class that is being used currently to generate", "source": "github_repos"} +{"code": "def forward(self, hidden_features):\n hidden_features = hidden_features.transpose(-1, -2)\n if self.head_aggregation == 'use_last':\n hidden_features = hidden_features[..., -1]\n elif self.head_aggregation == 'max_pool':\n hidden_features = hidden_features.max(dim=-1).values\n elif self.head_aggregation == 'avg_pool':\n hidden_features = hidden_features.mean(dim=-1)\n if self.flatten:\n hidden_features = self.flatten(hidden_features)\n hidden_features = self.dropout(hidden_features)\n hidden_features = self.projection(hidden_features)\n if self.distribution_output is None and self.output_range is not None:\n hidden_features = torch.sigmoid(hidden_features) * (self.output_range[1] - self.output_range[0]) + self.output_range[0]\n return hidden_features", "docstring": "Args:\n hidden_features (`torch.Tensor` of shape `(batch_size x num_patch x d_model)` in `flatten` mode\n or `(batch_size x n_vars x num_patch x d_model)` in `common_channel`/`mix_channel` mode.): Input hidden\n features.\n\nReturns:\n `torch.Tensor` of shape `(batch_size x num_targets)`.", "source": "github_repos"} +{"code": "def __init__(self, content: str, type: Union[str, language_v1.Document.Type]='PLAIN_TEXT', language_hint: Optional[str]=None, encoding: Optional[str]='UTF8', from_gcs: bool=False):\n self.content = content\n self.type = type\n self.encoding = encoding\n self.language_hint = language_hint\n self.from_gcs = from_gcs", "docstring": "Represents the input to :class:`AnnotateText` transform.\n\nArgs:\n content (str): The content of the input or the Google Cloud Storage URI\n where the file is stored.\n type (`Union[str, google.cloud.language_v1.Document.Type]`): Text type.\n Possible values are `HTML`, `PLAIN_TEXT`. The default value is\n `PLAIN_TEXT`.\n language_hint (`Optional[str]`): The language of the text. If not specified,\n language will be automatically detected. Values should conform to\n ISO-639-1 standard.\n encoding (`Optional[str]`): Text encoding. Possible values are: `NONE`,\n `UTF8`, `UTF16`, `UTF32`. The default value is `UTF8`.\n from_gcs (bool): Whether the content should be interpret as a Google Cloud\n Storage URI. The default value is :data:`False`.", "source": "github_repos"} +{"code": "def __init__(self, name, default_name=None, values=None) -> None:\n self._name_scope = name_scope(name, default_name, values, skip_on_eager=False)\n self._name = default_name if name is None else name", "docstring": "Initialize the context manager.\n\nArgs:\n name: The name argument that is passed to the op function.\n default_name: The default name to use if the `name` argument is `None`.\n values: The list of `Tensor` arguments that are passed to the op function.\n\nRaises:\n TypeError: if `default_name` is passed in but not a string.", "source": "github_repos"} +{"code": "def repeat_ranges(params, splits, repeats):\n splits_checks = [check_ops.assert_non_negative(splits, message=\"Input argument 'splits' must be non-negative\"), check_ops.assert_integer(splits, message=f\"Input argument 'splits' must be integer, but got {splits.dtype} instead\")]\n repeats_checks = [check_ops.assert_non_negative(repeats, message=\"Input argument 'repeats' must be non-negative\"), check_ops.assert_integer(repeats, message=f\"Input argument 'repeats' must be integer, but got {repeats.dtype} instead\")]\n splits = control_flow_ops.with_dependencies(splits_checks, splits)\n repeats = control_flow_ops.with_dependencies(repeats_checks, repeats)\n if repeats.shape.ndims != 0:\n repeated_starts = repeat(splits[:-1], repeats, axis=0)\n repeated_limits = repeat(splits[1:], repeats, axis=0)\n else:\n repeated_splits = repeat(splits, repeats, axis=0)\n n_splits = array_ops.shape(repeated_splits, out_type=repeats.dtype)[0]\n repeated_starts = repeated_splits[:n_splits - repeats]\n repeated_limits = repeated_splits[repeats:]\n one = array_ops.ones((), repeated_starts.dtype)\n offsets = gen_ragged_math_ops.ragged_range(repeated_starts, repeated_limits, one)\n return array_ops.gather(params, offsets.rt_dense_values)", "docstring": "Repeats each range of `params` (as specified by `splits`) `repeats` times.\n\n Let the `i`th range of `params` be defined as\n `params[splits[i]:splits[i + 1]]`. Then this function returns a tensor\n containing range 0 repeated `repeats[0]` times, followed by range 1 repeated\n `repeats[1]`, ..., followed by the last range repeated `repeats[-1]` times.\n\nArgs:\n params: The `Tensor` whose values should be repeated.\n splits: A splits tensor indicating the ranges of `params` that should be\n repeated. Elements should be non-negative integers.\n repeats: The number of times each range should be repeated. Supports\n broadcasting from a scalar value. Elements should be non-negative\n integers.\n\nReturns:\n A `Tensor` with the same rank and type as `params`.\n\n #### Example:\n\n >>> print(repeat_ranges(\n ... params=tf.constant(['a', 'b', 'c']),\n ... splits=tf.constant([0, 2, 3]),\n ... repeats=tf.constant(3)))\n tf.Tensor([b'a' b'b' b'a' b'b' b'a' b'b' b'c' b'c' b'c'],\n shape=(9,), dtype=string)", "source": "github_repos"} +{"code": "def create_model(fingerprint_input, model_settings, model_architecture, is_training, runtime_settings=None):\n if model_architecture == 'single_fc':\n return create_single_fc_model(fingerprint_input, model_settings, is_training)\n elif model_architecture == 'conv':\n return create_conv_model(fingerprint_input, model_settings, is_training)\n elif model_architecture == 'low_latency_conv':\n return create_low_latency_conv_model(fingerprint_input, model_settings, is_training)\n elif model_architecture == 'low_latency_svdf':\n return create_low_latency_svdf_model(fingerprint_input, model_settings, is_training, runtime_settings)\n elif model_architecture == 'tiny_conv':\n return create_tiny_conv_model(fingerprint_input, model_settings, is_training)\n elif model_architecture == 'tiny_embedding_conv':\n return create_tiny_embedding_conv_model(fingerprint_input, model_settings, is_training)\n else:\n raise Exception('model_architecture argument \"' + model_architecture + '\" not recognized, should be one of \"single_fc\", \"conv\",' + ' \"low_latency_conv, \"low_latency_svdf\",' + ' \"tiny_conv\", or \"tiny_embedding_conv\"')", "docstring": "Builds a model of the requested architecture compatible with the settings.\n\n There are many possible ways of deriving predictions from a spectrogram\n input, so this function provides an abstract interface for creating different\n kinds of models in a black-box way. You need to pass in a TensorFlow node as\n the 'fingerprint' input, and this should output a batch of 1D features that\n describe the audio. Typically this will be derived from a spectrogram that's\n been run through an MFCC, but in theory it can be any feature vector of the\n size specified in model_settings['fingerprint_size'].\n\n The function will build the graph it needs in the current TensorFlow graph,\n and return the tensorflow output that will contain the 'logits' input to the\n softmax prediction process. If training flag is on, it will also return a\n placeholder node that can be used to control the dropout amount.\n\n See the implementations below for the possible model architectures that can be\n requested.\n\nArgs:\n fingerprint_input: TensorFlow node that will output audio feature vectors.\n model_settings: Dictionary of information about the model.\n model_architecture: String specifying which kind of model to create.\n is_training: Whether the model is going to be used for training.\n runtime_settings: Dictionary of information about the runtime.\n\nReturns:\n TensorFlow node outputting logits results, and optionally a dropout\n placeholder.\n\nRaises:\n Exception: If the architecture type isn't recognized.", "source": "github_repos"} +{"code": "def _preprocess_conv3d_input(x, data_format):\n tf_data_format = 'NDHWC'\n if data_format == 'channels_first':\n if not _has_nchw_support():\n x = array_ops.transpose(x, (0, 2, 3, 4, 1))\n else:\n tf_data_format = 'NCDHW'\n return (x, tf_data_format)", "docstring": "Transpose and cast the input before the conv3d.\n\nArgs:\n x: input tensor.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\nReturns:\n A tensor.", "source": "github_repos"} +{"code": "def compact(self, accumulator, *args, **kwargs):\n return accumulator", "docstring": "Optionally returns a more compact representation of the accumulator.\n\n This is called before an accumulator is sent across the wire, and can\n be useful in cases where values are buffered or otherwise lazily\n kept unprocessed when added to the accumulator. Should return an\n equivalent, though possibly modified, accumulator.\n\n By default returns the accumulator unmodified.\n\nArgs:\n accumulator: the current accumulator\n *args: Additional arguments and side inputs.\n **kwargs: Additional arguments and side inputs.", "source": "github_repos"} +{"code": "def close(self, cancel_pending_enqueues=False, name=None):\n if name is None:\n name = '%s_BarrierClose' % self._name\n return gen_data_flow_ops.barrier_close(self._barrier_ref, cancel_pending_enqueues=cancel_pending_enqueues, name=name)", "docstring": "Closes this barrier.\n\n This operation signals that no more new key values will be inserted in the\n given barrier. Subsequent InsertMany operations with new keys will fail.\n InsertMany operations that just complement already existing keys with other\n components, will continue to succeed. Subsequent TakeMany operations will\n continue to succeed if sufficient elements remain in the barrier. Subsequent\n TakeMany operations that would block will fail immediately.\n\n If `cancel_pending_enqueues` is `True`, all pending requests to the\n underlying queue will also be canceled, and completing of already\n started values is also not acceptable anymore.\n\nArgs:\n cancel_pending_enqueues: (Optional.) A boolean, defaulting to\n `False` (described above).\n name: Optional name for the op.\n\nReturns:\n The operation that closes the barrier.", "source": "github_repos"} +{"code": "def WriteExecution(self, execution):\n debug_event = debug_event_pb2.DebugEvent(execution=execution)\n self._EnsureTimestampAdded(debug_event)\n _pywrap_debug_events_writer.WriteExecution(self._dump_root, debug_event)", "docstring": "Write a Execution proto with the writer.\n\nArgs:\n execution: An Execution proto, describing a TensorFlow op or graph\n execution event.", "source": "github_repos"} +{"code": "def _get_cuda_compute_capabilities_or_die() -> list[str]:\n try:\n nvidia_smi = _find_executable_or_die('nvidia-smi')\n nvidia_smi_proc = subprocess.run([nvidia_smi, '--query-gpu=compute_cap', '--format=csv,noheader'], capture_output=True, check=True, text=True)\n capabilities = sorted(set(nvidia_smi_proc.stdout.strip().split('\\n')))\n logging.info('Found CUDA compute capabilities: %s', capabilities)\n return capabilities\n except (RuntimeError, subprocess.CalledProcessError) as e:\n logging.info('Could not find nvidia-smi, or nvidia-smi command failed. Please pass capabilities directly using --cuda_compute_capabilities.')\n raise e", "docstring": "Finds compute capabilities via nvidia-smi or rasies exception.\n\nReturns:\n list of unique, sorted strings representing compute capabilities:\n\nRaises:\n RuntimeError: if path to nvidia-smi couldn't be found.\n subprocess.CalledProcessError: if nvidia-smi process failed.", "source": "github_repos"} +{"code": "def isnan(self: EventSetOrNode) -> EventSetOrNode:\n from temporian.core.operators.unary import isnan\n return isnan(self)", "docstring": "Returns boolean features, `True` in the NaN elements of the\n [`EventSet`][temporian.EventSet].\n\n Note that for `int` and `bool` this will always be `False` since those types\n don't support NaNs. It only makes actual sense to use on `float` (or\n `tp.float32`) features.\n\n See also `evset.notnan()`.\n\nExample:\n ```python\n >>> a = tp.event_set(\n ... timestamps=[1, 2, 3],\n ... features={\"M\":[np.nan, 5., np.nan], \"N\": [-1, 0, 5]},\n ... )\n >>> b = a.isnan()\n >>> b\n indexes: ...\n 'M': [ True False True]\n 'N': [False False False]\n ...\n\n >>> # Count nans\n >>> b[\"M\"].cast(int).cumsum()\n indexes: ...\n timestamps: [1. 2. 3.]\n 'M': [1 1 2]\n ...\n\n ```\n\nReturns:\n EventSet with boolean features.", "source": "github_repos"} +{"code": "def stack_inputs(self, stack_indices=None, tile_variants=False):\n if stack_indices is None:\n stack_indices = range(len(self._inputs))\n length = self.pfor.loop_len_vector\n for i in stack_indices:\n inp = self._inputs[i]\n is_variant = inp.t.dtype == dtypes.variant\n if not inp.is_stacked:\n self._inputs[i] = _stack(inp.t, length)\n if tile_variants and is_variant:\n self._inputs[i] = wrap(_tile_variant_with_length(self._inputs[i].t, length), True)\n elif not tile_variants and is_variant:\n self._inputs[i] = wrap(_untile_variant(self._inputs[i].t), True)", "docstring": "Stacks unstacked inputs at `stack_indices`.\n\nArgs:\n stack_indices: indices of inputs at which stacking is done. If None,\n stacking is done at all indices.\n tile_variants: If True, affected indices which have a variant dtype will\n be tiled after this operation to match the expected shape of a\n vectorized tensor. Variants generally need to be un-tiled when they are\n inputs to operations and tiled when returned.", "source": "github_repos"} +{"code": "def LSTMCell(weights, m_prev, c_prev, x, pad):\n xm = array_ops.concat([x, m_prev], 1)\n xmw = math_ops.matmul(xm, weights)\n in_value, in_gate, forget_gate, out_gate = array_ops.split(value=xmw, num_or_size_splits=4, axis=1)\n in_value = math_ops.tanh(in_value)\n in_gate = math_ops.sigmoid(in_gate)\n forget_gate = math_ops.sigmoid(forget_gate)\n out_gate = math_ops.sigmoid(out_gate)\n c_next = Clip(Clip(forget_gate * c_prev) + Clip(in_gate * in_value))\n m_next = Clip(out_gate * c_next)\n c_next = c_prev * pad + c_next * (1.0 - pad)\n m_next = m_prev * pad + m_next * (1.0 - pad)\n return (m_next, c_next)", "docstring": "Unrolls a single LSTM cell with clipped activations forward by one step.\n\nArgs:\n weights: Weight matrix with shape LSTMCellWeightsShape.\n m_prev: Previous m states with shape [batch_size, num_nodes].\n c_prev: Previous c states with shape [batch_size, num_nodes].\n x: Input with shape [batch_size, num_inputs].\n pad: Padding with shape [batch_size, 1]. Each padding value is either\n 0 or 1, where 1 indicates padding; i.e. the input is shorter than the\n sequence length, and the (m, c) states should simply be passed through\n from the previous states.\n\nReturns:\n The next (m, c) states, each with shape [batch_size, num_nodes].", "source": "github_repos"} +{"code": "def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:\n size = get_size_dict(size, default_to_square=True, param_name='size')\n if 'height' not in size or 'width' not in size:\n raise ValueError(f'The `size` argument must contain `height` and `width` keys. Got {size.keys()}')\n return resize(image, size=(size['height'], size['width']), resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs)", "docstring": "Resize an image to (size[\"height\"], size[\"width\"]).\n\nArgs:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PIL.Image.BICUBIC`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.", "source": "github_repos"} +{"code": "def sym_descendants(self, where: Optional[Callable[[Any], bool]]=None, option: DescendantQueryOption=DescendantQueryOption.ALL, include_self: bool=False) -> List[Any]:\n descendants = []\n where = where or (lambda x: True)\n\n def visit(k, v, p):\n del k, p\n if not where(v):\n return TraverseAction.ENTER\n if not include_self and self is v:\n return TraverseAction.ENTER\n if option == DescendantQueryOption.IMMEDIATE:\n descendants.append(v)\n return TraverseAction.CONTINUE\n leaf_descendants = []\n if isinstance(v, Symbolic):\n leaf_descendants = v.sym_descendants(where, option)\n if option is DescendantQueryOption.ALL or not leaf_descendants:\n descendants.append(v)\n descendants.extend(leaf_descendants)\n return TraverseAction.CONTINUE\n traverse(self, visit)\n return descendants", "docstring": "Returns all descendants of specific classes.\n\nArgs:\n where: Optional callable object as the filter of descendants to return.\n option: Descendant query options, indicating whether all matched,\n immediate matched or only the matched leaf nodes will be returned.\n include_self: If True, `self` will be included in the query, otherwise\n only strict descendants are included.\n\nReturns:\n A list of objects that match the descendant_cls.", "source": "github_repos"} +{"code": "def _init_from_proto(self, context_def, import_scope=None):\n assert isinstance(context_def, control_flow_pb2.WhileContextDef)\n g = ops.get_default_graph()\n self._name = ops.prepend_name_scope(context_def.context_name, import_scope)\n if context_def.maximum_iterations_name:\n self._maximum_iterations = g.as_graph_element(ops.prepend_name_scope(context_def.maximum_iterations_name, import_scope))\n else:\n self._maximum_iterations = None\n self._parallel_iterations = context_def.parallel_iterations\n self._back_prop = context_def.back_prop\n self._swap_memory = context_def.swap_memory\n self._pivot_for_pred = g.as_graph_element(ops.prepend_name_scope(context_def.pivot_for_pred_name, import_scope))\n self._pivot_for_body = g.as_graph_element(ops.prepend_name_scope(context_def.pivot_for_body_name, import_scope))\n self._pivot = g.as_graph_element(ops.prepend_name_scope(context_def.pivot_name, import_scope))\n self._loop_exits = [g.as_graph_element(ops.prepend_name_scope(exit_name, import_scope)) for exit_name in context_def.loop_exit_names]\n self._loop_enters = [g.as_graph_element(ops.prepend_name_scope(enter_name, import_scope)) for enter_name in context_def.loop_enter_names]\n super(WhileContext, self).__init__(values_def=context_def.values_def, import_scope=import_scope)\n if import_scope:\n for tensor_name in self._values:\n op = g.as_graph_element(tensor_name).op\n if util.IsLoopEnter(op):\n op._set_attr('frame_name', attr_value_pb2.AttrValue(s=compat.as_bytes(self.name)))\n self._graph = ops.get_default_graph()", "docstring": "Creates a new `WhileContext` from protocol buffer.\n\nArgs:\n context_def: `WhileContextDef` protocol buffer.\n import_scope: Optional `string`. Name scope to add.", "source": "github_repos"} +{"code": "def __init__(self, config: GPT2Config):\n super().__init__()\n self.summary_type = getattr(config, 'summary_type', 'last')\n if self.summary_type == 'attn':\n raise NotImplementedError\n self.summary = nn.Identity()\n if hasattr(config, 'summary_use_proj') and config.summary_use_proj:\n if hasattr(config, 'summary_proj_to_labels') and config.summary_proj_to_labels and (config.num_labels > 0):\n num_classes = config.num_labels\n else:\n num_classes = config.hidden_size\n self.summary = nn.Linear(config.hidden_size, num_classes)\n activation_string = getattr(config, 'summary_activation', None)\n self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()\n self.first_dropout = nn.Identity()\n if hasattr(config, 'summary_first_dropout') and config.summary_first_dropout > 0:\n self.first_dropout = nn.Dropout(config.summary_first_dropout)\n self.last_dropout = nn.Identity()\n if hasattr(config, 'summary_last_dropout') and config.summary_last_dropout > 0:\n self.last_dropout = nn.Dropout(config.summary_last_dropout)", "docstring": "Compute a single vector summary of a sequence hidden states.\n\nArgs:\n config ([`GPT2Config`]):\n The config used by the model. Relevant arguments in the config class of the model are (refer to the actual\n config class of your model for the default values it uses):\n\n - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:\n\n - `\"last\"` -- Take the last token hidden state (like XLNet)\n - `\"first\"` -- Take the first token hidden state (like Bert)\n - `\"mean\"` -- Take the mean of all tokens hidden states\n - `\"cls_index\"` -- Supply a Tensor of classification token position (GPT/GPT-2)\n - `\"attn\"` -- Not implemented now, use multi-head attention\n\n - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.\n - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes\n (otherwise to `config.hidden_size`).\n - **summary_activation** (`Optional[str]`) -- Set to `\"tanh\"` to add a tanh activation to the output,\n another string or `None` will add no activation.\n - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.\n - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.", "source": "github_repos"} +{"code": "def _eventual_warn_about_too_long_sequence(self, ids: List[int], max_length: Optional[int], verbose: bool):\n if max_length is None and len(ids) > self.model_max_length and verbose and (self.model_max_length != 0):\n if not self.deprecation_warnings.get('sequence-length-is-longer-than-the-specified-maximum', False):\n logger.warning(f'Token indices sequence length is longer than the specified maximum sequence length for this model ({len(ids)} > {self.model_max_length}). Running this sequence through the model will result in indexing errors')\n self.deprecation_warnings['sequence-length-is-longer-than-the-specified-maximum'] = True", "docstring": "Depending on the input and internal state we might trigger a warning about a sequence that is too long for its\n corresponding model\n\nArgs:\n ids (`List[str]`): The ids produced by the tokenization\n max_length (`int`, *optional*): The max_length desired (does not trigger a warning if it is set)\n verbose (`bool`): Whether or not to print more information and warnings.", "source": "github_repos"} +{"code": "def _get_index(self, data: _instance_base.Instance | ConcreteValue) -> int | None:\n if isinstance(data, ConcreteValue):\n return self.ctx.convert.value_to_constant(data, (int, type(None)))\n elif isinstance(data, _instance_base.Instance):\n if data.cls != self.ctx.convert.int_type:\n raise abstract_utils.ConversionError()\n else:\n return None\n else:\n raise abstract_utils.ConversionError()", "docstring": "Helper function for getslice_slot that extracts int or None from data.\n\n If data is an Instance of int, None is returned.\n\nArgs:\n data: The object to extract from. Usually a ConcreteValue or an Instance.\n\nReturns:\n The value (an int or None) of the index.\n\nRaises:\n abstract_utils.ConversionError: If the data could not be converted.", "source": "github_repos"} +{"code": "def sample_points_using_uncertainty(self, logits: torch.Tensor, uncertainty_function, num_points: int, oversample_ratio: int, importance_sample_ratio: float) -> torch.Tensor:\n num_boxes = logits.shape[0]\n num_points_sampled = int(num_points * oversample_ratio)\n point_coordinates = torch.rand(num_boxes, num_points_sampled, 2, device=logits.device)\n point_logits = sample_point(logits, point_coordinates, align_corners=False)\n point_uncertainties = uncertainty_function(point_logits)\n num_uncertain_points = int(importance_sample_ratio * num_points)\n num_random_points = num_points - num_uncertain_points\n idx = torch.topk(point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1]\n shift = num_points_sampled * torch.arange(num_boxes, dtype=torch.long, device=logits.device)\n idx += shift[:, None]\n point_coordinates = point_coordinates.view(-1, 2)[idx.view(-1), :].view(num_boxes, num_uncertain_points, 2)\n if num_random_points > 0:\n point_coordinates = torch.cat([point_coordinates, torch.rand(num_boxes, num_random_points, 2, device=logits.device)], dim=1)\n return point_coordinates", "docstring": "This function is meant for sampling points in [0, 1] * [0, 1] coordinate space based on their uncertainty. The\n uncertainty is calculated for each point using the passed `uncertainty function` that takes points logit\n prediction as input.\n\nArgs:\n logits (`float`):\n Logit predictions for P points.\n uncertainty_function:\n A function that takes logit predictions for P points and returns their uncertainties.\n num_points (`int`):\n The number of points P to sample.\n oversample_ratio (`int`):\n Oversampling parameter.\n importance_sample_ratio (`float`):\n Ratio of points that are sampled via importance sampling.\n\nReturns:\n point_coordinates (`torch.Tensor`):\n Coordinates for P sampled points.", "source": "github_repos"} +{"code": "def start_server(self):\n persists_shell_cmd = self._get_persisting_command()\n self.log.debug('Snippet server for package %s is using protocol %d.%d', self.package, _PROTOCOL_MAJOR_VERSION, _PROTOCOL_MINOR_VERSION)\n option_str = self._get_instrument_options_str()\n cmd = _LAUNCH_CMD.format(shell_cmd=persists_shell_cmd, user=self._get_user_command_string(), snippet_package=self.package, instrument_options=option_str)\n self._proc = self._run_adb_cmd(cmd)\n self._server_start_stdout = []\n line = self._read_protocol_line()\n match = re.match('^SNIPPET START, PROTOCOL ([0-9]+) ([0-9]+)$', line)\n if not match or int(match.group(1)) != _PROTOCOL_MAJOR_VERSION:\n raise errors.ServerStartProtocolError(self._device, line)\n line = self._read_protocol_line()\n match = re.match('^SNIPPET SERVING, PORT ([0-9]+)$', line)\n if not match:\n message = _SNIPPET_SERVER_START_ERROR_DEBUG_TIP.format(instrumentation_result=line, server_start_stdout='\\n'.join(self._server_start_stdout))\n raise errors.ServerStartProtocolError(self._device, message)\n self.device_port = int(match.group(1))", "docstring": "Starts the server on the remote device.\n\n This function starts the snippet server with adb command, checks the\n protocol version of the server, parses device port from the server\n output and sets it to self.device_port.\n\nRaises:\n errors.ServerStartProtocolError: if the protocol reported by the server\n startup process is unknown.\n errors.ServerStartError: if failed to start the server or process the\n server output.", "source": "github_repos"} +{"code": "def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, data_type, data_format='NHWC'):\n total_size_1 = 1\n total_size_2 = 1\n for s in tensor_in_sizes:\n total_size_1 *= s\n for s in filter_in_sizes:\n total_size_2 *= s\n x1 = np.array([f * 1.0 for f in range(1, total_size_1 + 1)], dtype=data_type).reshape(tensor_in_sizes)\n x2 = np.array([f * 1.0 for f in range(1, total_size_2 + 1)], dtype=data_type).reshape(filter_in_sizes)\n with self.session() as sess:\n if data_type == np.float32:\n tolerance = 0.0001\n else:\n self.assertEqual(data_type, np.float64)\n tolerance = 1e-08\n t1 = array_ops.placeholder(shape=tensor_in_sizes, dtype=data_type)\n t2 = array_ops.placeholder(shape=filter_in_sizes, dtype=data_type)\n native_t1 = t1\n strides = [1, stride, stride, 1]\n if data_format == 'NCHW':\n native_t1 = array_ops.transpose(t1, [0, 3, 1, 2])\n strides = [1, 1, stride, stride]\n with self.test_scope():\n conv_native = nn_ops.depthwise_conv2d_native(native_t1, t2, strides=strides, data_format=data_format, padding=padding)\n if data_format == 'NCHW':\n conv_native = array_ops.transpose(conv_native, [0, 2, 3, 1])\n with ops.device('CPU'):\n conv_interface = ReferenceDepthwiseConv2D(t1, t2, strides=[1, stride, stride, 1], padding=padding)\n native_result = sess.run(conv_native, {t1: x1, t2: x2})\n interface_result = sess.run(conv_interface, {t1: x1, t2: x2})\n print('data_type:', data_type, 'max diff = ', np.amax(np.absolute(native_result - interface_result)))\n self.assertAllClose(np.ravel(native_result), np.ravel(interface_result), rtol=tolerance)", "docstring": "Verifies the output values of the convolution function.\n\nArgs:\n tensor_in_sizes: Input tensor dimensions in\n [batch, input_rows, input_cols, input_depth].\n filter_in_sizes: Filter tensor dimensions in\n [filter_rows, filter_cols, input_depth, depth_multiplier].\n stride: Stride.\n padding: Padding type.\n data_type: The data type to use.\n data_format: The data_format of the input. \"NHWC\" or \"NCHW\".", "source": "github_repos"} +{"code": "def _composition_must_be_self_adjoint(operators):\n if len(operators) == 1 and operators[0].is_self_adjoint:\n return True\n if linear_operator_util.is_aat_form(operators):\n return True\n return False", "docstring": "Runs some checks to see if composition operators must be SA.\n\nArgs:\n operators: List of LinearOperators.\n\nReturns:\n True if the composition must be SA. False if it is not SA OR if we did not\n determine whether the composition is SA.", "source": "github_repos"} +{"code": "def input(self):\n if not self._inbound_nodes:\n raise AttributeError('Layer ' + self.name + ' is not connected, no input to return.')\n return self._get_node_attribute_at_index(0, 'input_tensors', 'input')", "docstring": "Retrieves the input tensor(s) of a layer.\n\n Only applicable if the layer has exactly one input,\n i.e. if it is connected to one incoming layer.\n\nReturns:\n Input tensor or list of input tensors.\n\nRaises:\n RuntimeError: If called in Eager mode.\n AttributeError: If no inbound nodes are found.", "source": "github_repos"} +{"code": "def build_alibi_tensor(attention_mask: jnp.ndarray, num_heads: int, dtype: Optional[jnp.dtype]=jnp.float32):\n batch_size, seq_length = attention_mask.shape\n closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))\n base = jnp.array(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), dtype=jnp.float32)\n powers = jnp.arange(1, 1 + closest_power_of_2, dtype=jnp.float32)\n slopes = jax.lax.pow(base, powers)\n if closest_power_of_2 != num_heads:\n extra_base = jnp.array(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), dtype=jnp.float32)\n num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)\n extra_powers = jnp.arange(1, 1 + 2 * num_remaining_heads, 2, dtype=jnp.float32)\n slopes = jnp.cat([slopes, jax.lax.pow(extra_base, extra_powers)], axis=0)\n arange_tensor = ((attention_mask.cumsum(axis=-1) - 1) * attention_mask)[:, None, :]\n alibi = slopes[..., None] * arange_tensor\n alibi = jnp.expand_dims(alibi, axis=2)\n return jnp.asarray(alibi, dtype)", "docstring": "Flax implementation of the BLOOM Alibi tensor. BLOOM Alibi tensor is not causal as the original paper mentions, it\n relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value\n `softmax(l+a) = softmax(l)`. Based on\n https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742\n Link to paper: https://huggingface.co/papers/2108.12409\n\nArgs:\n attention_mask (`jnp.ndarray`):\n Token-wise attention mask, this should be of shape `(batch_size, max_seq_len)`.\n num_heads (`int`):\n Number of attention heads.\n dtype (`jnp.dtype`, *optional*, defaults to `jnp.float32`):\n The data type (dtype) of the output tensor.\n\n Returns: Alibi tensor of shape `(batch_size * num_heads, 1, max_seq_len)`.", "source": "github_repos"} +{"code": "def set_floatx(value):\n global _FLOATX\n accepted_dtypes = {'bfloat16', 'float16', 'float32', 'float64'}\n if value not in accepted_dtypes:\n raise ValueError(f'Unknown `floatx` value: {value}. Expected one of {accepted_dtypes}')\n _FLOATX = str(value)", "docstring": "Set the default float dtype.\n\n Note: It is not recommended to set this to `\"float16\"` for training,\n as this will likely cause numeric stability issues.\n Instead, mixed precision, which leverages\n a mix of `float16` and `float32`. It can be configured by calling\n `keras.mixed_precision.set_dtype_policy('mixed_float16')`.\n\nArgs:\n value: String; `'bfloat16'`, `'float16'`, `'float32'`, or `'float64'`.\n\nExample:\n >>> keras.config.floatx()\n 'float32'\n\n >>> keras.config.set_floatx('float64')\n >>> keras.config.floatx()\n 'float64'\n\n >>> # Set it back to float32\n >>> keras.config.set_floatx('float32')\n\nRaises:\n ValueError: In case of invalid value.", "source": "github_repos"} +{"code": "def is_flaky(max_attempts: int=5, wait_before_retry: Optional[float]=None, description: Optional[str]=None):\n\n def decorator(test_func_ref):\n\n @functools.wraps(test_func_ref)\n def wrapper(*args, **kwargs):\n retry_count = 1\n while retry_count < max_attempts:\n try:\n return test_func_ref(*args, **kwargs)\n except Exception as err:\n logger.error(f'Test failed with {err} at try {retry_count}/{max_attempts}.')\n if wait_before_retry is not None:\n time.sleep(wait_before_retry)\n retry_count += 1\n return test_func_ref(*args, **kwargs)\n return unittest.skipUnless(_run_flaky_tests, 'test is flaky')(wrapper)\n return decorator", "docstring": "To decorate flaky tests. They will be retried on failures.\n\n Please note that our push tests use `pytest-rerunfailures`, which prompts the CI to rerun certain types of\n failed tests. More specifically, if the test exception contains any substring in `FLAKY_TEST_FAILURE_PATTERNS`\n (in `.circleci/create_circleci_config.py`), it will be rerun. If you find a recurrent pattern of failures,\n expand `FLAKY_TEST_FAILURE_PATTERNS` in our CI configuration instead of using `is_flaky`.\n\nArgs:\n max_attempts (`int`, *optional*, defaults to 5):\n The maximum number of attempts to retry the flaky test.\n wait_before_retry (`float`, *optional*):\n If provided, will wait that number of seconds before retrying the test.\n description (`str`, *optional*):\n A string to describe the situation (what / where / why is flaky, link to GH issue/PR comments, errors,\n etc.)", "source": "github_repos"} +{"code": "def forward(self, **super_kwargs) -> CausalLMOutputWithPast:\n return super().forward(**super_kwargs)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, BitNetForCausalLM\n\n >>> model = BitNetForCausalLM.from_pretrained(\"microsoft/bitnet-b1.58-2B-4T\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"microsoft/bitnet-b1.58-2B-4T\")\n\n >>> prompt = f'<|begin_of_text|>User: Hey, are you conscious? Can you talk to me?<|eot_id|>Assistant: '\n >>> inputs = tokenizer(prompt, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(inputs.input_ids, max_length=100)\n >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"User: Hey, are you conscious? Can you talk to me?Assistant: No, I'm not conscious. I'm an artificial intelligence designed to assist with information and tasks. How can I help you today?\"\n ```", "source": "github_repos"} +{"code": "def run_benchmark(self, dataset, num_elements, iters=1, warmup=True, apply_default_optimizations=False, session_config=None):\n options = options_lib.Options()\n options.experimental_optimization.apply_default_optimizations = apply_default_optimizations\n dataset = dataset.with_options(options)\n dataset = dataset.skip(num_elements - 1)\n if context.executing_eagerly():\n median_duration = self._run_eager_benchmark(iterable=dataset, iters=iters, warmup=warmup)\n return median_duration / float(num_elements)\n iterator = dataset_ops.make_initializable_iterator(dataset)\n next_element = iterator.get_next()\n op = nest.flatten(next_element)[0].op\n median_duration = self._run_graph_benchmark(iterable=op, iters=iters, warmup=warmup, session_config=session_config, initializer=iterator.initializer)\n return median_duration / float(num_elements)", "docstring": "Benchmarks the dataset.\n\n Runs the dataset `iters` times. In each iteration, the benchmark measures\n the time it takes to go through `num_elements` elements of the dataset.\n\nArgs:\n dataset: Dataset to benchmark.\n num_elements: Number of dataset elements to iterate through each benchmark\n iteration.\n iters: Number of times to repeat the timing.\n warmup: If true, warms up the session caches by running an untimed run.\n apply_default_optimizations: Determines whether default optimizations\n should be applied.\n session_config: A ConfigProto protocol buffer with configuration options\n for the session. Applicable only for benchmarking in graph mode.\n\nReturns:\n A float, representing the per-element wall time of the dataset in seconds.\n This is the median time (with respect to `iters`) it takes for the dataset\n to go through `num_elements` elements, divided by `num_elements.`", "source": "github_repos"} +{"code": "def assert_no_garbage_created(f: _F) -> _F:\n\n def decorator(self: 'TensorFlowTestCase', **kwargs):\n \"\"\"Sets DEBUG_SAVEALL, runs the test, and checks for new garbage.\"\"\"\n gc.disable()\n previous_debug_flags = gc.get_debug()\n gc.set_debug(gc.DEBUG_UNCOLLECTABLE)\n gc.collect()\n previous_garbage = len(gc.garbage)\n result = f(self, **kwargs)\n gc.collect()\n new_garbage = len(gc.garbage)\n if new_garbage > previous_garbage:\n for i, obj in enumerate(gc.garbage[previous_garbage:]):\n if getattr(obj, '__module__', '') == 'ast':\n new_garbage -= 3\n if new_garbage > previous_garbage:\n logging.error(\"The decorated test created work for Python's garbage collector, likely due to a reference cycle. New objects in cycle(s):\")\n for i, obj in enumerate(gc.garbage[previous_garbage:]):\n try:\n logging.error('Object %d of %d', i, len(gc.garbage) - previous_garbage)\n\n def _safe_object_str(obj) -> str:\n return '<%s %d>' % (obj.__class__.__name__, id(obj))\n logging.error(' Object type: %s', _safe_object_str(obj))\n logging.error(' Referrer types: %s', ', '.join([_safe_object_str(ref) for ref in gc.get_referrers(obj)]))\n logging.error(' Referent types: %s', ', '.join([_safe_object_str(ref) for ref in gc.get_referents(obj)]))\n logging.error(' Object attribute names: %s', dir(obj))\n logging.error(' Object __str__:')\n logging.error(obj)\n logging.error(' Object __repr__:')\n logging.error(repr(obj))\n except Exception:\n logging.error('(Exception while printing object)')\n if new_garbage > previous_garbage:\n for i in range(previous_garbage, new_garbage):\n if _find_reference_cycle(gc.garbage, i):\n break\n self.assertEqual(previous_garbage, new_garbage)\n gc.set_debug(previous_debug_flags)\n gc.enable()\n return result\n return decorator", "docstring": "Test method decorator to assert that no garbage has been created.\n\n Note that this decorator sets DEBUG_SAVEALL, which in some Python interpreters\n cannot be un-set (i.e. will disable garbage collection for any other unit\n tests in the same file/shard).\n\nArgs:\n f: The function to decorate.\n\nReturns:\n The decorated function.", "source": "github_repos"} +{"code": "def rgb_to_grayscale(images, data_format=None):\n if any_symbolic_tensors((images,)):\n return RGBToGrayscale(data_format=data_format).symbolic_call(images)\n return backend.image.rgb_to_grayscale(images, data_format=data_format)", "docstring": "Convert RGB images to grayscale.\n\n This function converts RGB images to grayscale images. It supports both\n 3D and 4D tensors.\n\nArgs:\n images: Input image or batch of images. Must be 3D or 4D.\n data_format: A string specifying the data format of the input tensor.\n It can be either `\"channels_last\"` or `\"channels_first\"`.\n `\"channels_last\"` corresponds to inputs with shape\n `(batch, height, width, channels)`, while `\"channels_first\"`\n corresponds to inputs with shape `(batch, channels, height, width)`.\n If not specified, the value will default to\n `keras.config.image_data_format`.\n\nReturns:\n Grayscale image or batch of grayscale images.\n\nExample:\n >>> import numpy as np\n >>> from keras import ops\n >>> x = np.random.random((2, 4, 4, 3))\n >>> y = ops.image.rgb_to_grayscale(x)\n >>> y.shape\n (2, 4, 4, 1)\n\n >>> x = np.random.random((4, 4, 3)) # Single RGB image\n >>> y = ops.image.rgb_to_grayscale(x)\n >>> y.shape\n (4, 4, 1)\n\n >>> x = np.random.random((2, 3, 4, 4))\n >>> y = ops.image.rgb_to_grayscale(x, data_format=\"channels_first\")\n >>> y.shape\n (2, 1, 4, 4)", "source": "github_repos"} +{"code": "def __init__(self, axis=-1, **kwargs):\n super().__init__(**kwargs)\n self.axis = axis\n self.supports_masking = True\n self._build_at_init()", "docstring": "Softmax activation layer.\n\n Formula:\n ``` python\n exp_x = exp(x - max(x))\n f(x) = exp_x / sum(exp_x)\n ```\n\nExample:\n >>> softmax_layer = keras.layers.Softmax()\n >>> input = np.array([1.0, 2.0, 1.0])\n >>> result = softmax_layer(input)\n >>> result\n [0.21194157, 0.5761169, 0.21194157]\n\nArgs:\n axis: Integer, or list of Integers, axis along which the softmax\n normalization is applied.\n **kwargs: Base layer keyword arguments, such as `name` and `dtype`.\n\n Call arguments:\n inputs: The inputs (logits) to the softmax layer.\n mask: A boolean mask of the same shape as `inputs`. The mask\n specifies 1 to keep and 0 to mask. Defaults to `None`.\n\nReturns:\n Softmaxed output with the same shape as `inputs`.", "source": "github_repos"} +{"code": "def sparse_subtract(x1, x2):\n if isinstance(x2, tf.SparseTensor):\n return tf.sparse.add(x1, tf.sparse.map_values(tf.negative, x2))\n else:\n return tf.sparse.add(x1, tf.negative(x2))", "docstring": "Subtraction for `tf.SparseTensor`s.\n\n Either `x1` or `x2` or both can be `tf.SparseTensor`s.\n\nArgs:\n x1: fist tensor to add.\n x2: second tensor to add.\n\nReturns:\n The sum of `x1` and `x2`, which is a `tf.SparseTensor` if and only if\n both `x1` or `x2` are `tf.SparseTensor`s.", "source": "github_repos"} +{"code": "def node_info(self, args, screen_info=None):\n _ = screen_info\n parsed = self._arg_parsers['node_info'].parse_args(args)\n node_name, unused_slot = debug_graphs.parse_node_or_tensor_name(parsed.node_name)\n if not self._debug_dump.node_exists(node_name):\n output = cli_shared.error('There is no node named \"%s\" in the partition graphs' % node_name)\n _add_main_menu(output, node_name=None, enable_list_tensors=True, enable_node_info=False, enable_list_inputs=False, enable_list_outputs=False)\n return output\n lines = ['Node %s' % node_name]\n font_attr_segs = {0: [(len(lines[-1]) - len(node_name), len(lines[-1]), 'bold')]}\n lines.append('')\n lines.append(' Op: %s' % self._debug_dump.node_op_type(node_name))\n lines.append(' Device: %s' % self._debug_dump.node_device(node_name))\n output = debugger_cli_common.RichTextLines(lines, font_attr_segs=font_attr_segs)\n inputs = self._exclude_denylisted_ops(self._debug_dump.node_inputs(node_name))\n ctrl_inputs = self._exclude_denylisted_ops(self._debug_dump.node_inputs(node_name, is_control=True))\n output.extend(self._format_neighbors('input', inputs, ctrl_inputs))\n recs = self._exclude_denylisted_ops(self._debug_dump.node_recipients(node_name))\n ctrl_recs = self._exclude_denylisted_ops(self._debug_dump.node_recipients(node_name, is_control=True))\n output.extend(self._format_neighbors('recipient', recs, ctrl_recs))\n if parsed.attributes:\n output.extend(self._list_node_attributes(node_name))\n if parsed.dumps:\n output.extend(self._list_node_dumps(node_name))\n if parsed.traceback:\n output.extend(self._render_node_traceback(node_name))\n _add_main_menu(output, node_name=node_name, enable_node_info=False)\n return output", "docstring": "Command handler for node_info.\n\n Query information about a given node.\n\nArgs:\n args: Command-line arguments, excluding the command prefix, as a list of\n str.\n screen_info: Optional dict input containing screen information such as\n cols.\n\nReturns:\n Output text lines as a RichTextLines object.", "source": "github_repos"} +{"code": "def load_custom_generate(self, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]]=None, trust_remote_code: Optional[bool]=None, **kwargs) -> Callable:\n is_local_code = os.path.exists(pretrained_model_name_or_path)\n has_custom_generate_folder = True\n if is_local_code:\n if not os.path.exists(os.path.join(pretrained_model_name_or_path, 'custom_generate/generate.py')):\n has_custom_generate_folder = False\n elif not file_exists(pretrained_model_name_or_path, 'custom_generate/generate.py'):\n has_custom_generate_folder = False\n if not has_custom_generate_folder:\n raise OSError(f\"`{pretrained_model_name_or_path}` does not contain a `custom_generate` subdirectory with a `generate.py` file, can't load the custom generate function.\")\n error_message = f'The repository `{pretrained_model_name_or_path}` contains custom generation code that will override the default `generate` method.'\n resolve_trust_remote_code(trust_remote_code, pretrained_model_name_or_path, has_local_code=is_local_code, has_remote_code=not is_local_code, error_message=error_message)\n check_python_requirements(pretrained_model_name_or_path, requirements_file='custom_generate/requirements.txt', **kwargs)\n module = get_cached_module_file(pretrained_model_name_or_path, module_file='custom_generate/generate.py', **kwargs)\n custom_generate_function = get_class_in_module('generate', module)\n return custom_generate_function", "docstring": "Loads and returns a custom generate function, given a model repo.\n\nArgs:\n pretrained_model_name_or_path (`str` or `os.PathLike`):\n Can be either:\n - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.\n - A path to a *directory* containing model weights saved using\n [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.\n trust_remote_code (`bool`, *optional*):\n Whether or not to allow for custom models defined on the Hub in their own modeling files. This option\n should only be set to `True` for repositories you trust and in which you have read the code, as it will\n execute code present on the Hub on your local machine.\n **kwargs:\n Additional keyword arguments for remote code loading.\n\nRaises:\n OSError: If `pretrained_model_name_or_path` does not contain a `custom_generate` subdirectory.\n\nReturns:\n A callable that can be used to generate text.", "source": "github_repos"} +{"code": "def __new__(cls, *args) -> 'InvokeExpressionNode':\n if not args:\n return super().__new__(cls)\n _, identifier, parent_node = args\n if identifier == 'reference' and isinstance(parent_node.return_type, _fhir_path_data_types.ReferenceStructureDataType):\n return super().__new__(InvokeReferenceNode)\n return super().__new__(InvokeExpressionNode)", "docstring": "Creates a new InvokeExpressionNode node or one of its subclasses.\n\n Creates either an InvokeExpressionNode or InvokeReferenceNode, a subclass of\n InvokeExpressionNode. The InvokeReferenceNode is returned when a field named\n 'reference' is invoked against a FHIR Reference resource. Database backends\n have special behavior for reference nodes. This reference-specific node type\n allows them to define visitors to implement their reference-specific logic.\n\nArgs:\n *args: The args passed to `__init__`.\n\nReturns:\n A new InvokeExpressionNode of the appropriate type.", "source": "github_repos"} +{"code": "def forward(self, input_ids: torch.LongTensor, spkr_id: torch.Tensor, lang_id: torch.Tensor) -> Tuple[torch.Tensor]:\n hidden_states = self.unit_embedding(input_ids).transpose(1, 2)\n spkr = self.speaker_embedding(spkr_id).transpose(1, 2)\n lang = self.language_embedding(lang_id).transpose(1, 2)\n log_dur_pred = self.dur_predictor(hidden_states.transpose(1, 2))\n dur_out = torch.clamp(torch.round(torch.expm1(log_dur_pred)).long(), min=1)\n if hidden_states.size(0) == 1:\n hidden_states = torch.repeat_interleave(hidden_states, dur_out.view(-1), dim=2)\n else:\n if hidden_states.shape[0] > 1 and self.training:\n logger.warning('`self.training=True` and you use batching. You lose parallelism during the hifigan\\n forward pass because the samples are interleaved.')\n hidden_states = [torch.repeat_interleave(hidden_state, duration, dim=-1).transpose(0, 1) for hidden_state, duration in zip(hidden_states, dur_out)]\n hidden_states = nn.utils.rnn.pad_sequence(hidden_states, batch_first=True).transpose(1, 2)\n spkr = spkr.repeat(1, 1, hidden_states.shape[-1])\n lang = lang.repeat(1, 1, hidden_states.shape[-1])\n hidden_states = torch.cat([lang, hidden_states, spkr], dim=1)\n hidden_states = self.hifi_gan(hidden_states)\n unit_lengths = self._get_dur_output_lengths(input_ids, dur_out)\n lengths = self._get_output_hifigan_lengths(unit_lengths)\n return (hidden_states, lengths)", "docstring": "Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`SeamlessM4TTextToUnitForConditionalGeneration`]. [What are input\n IDs?](../glossary#input-ids)\n spkr_id (`int`, *optional*):\n The id of the speaker used for speech synthesis. Must be lower than `config.vocoder_num_spkrs`.\n tgt_lang (`str`, *optional*):\n The language id to use as target language for translation.", "source": "github_repos"} +{"code": "def convert_fields_for_spec(fields, field_values):\n _convert_fields(fields, field_values, context=_ConversionContext.SPEC)", "docstring": "Type-checks and converts field values for a TypeSpec (in place).\n\n This is similar to `convert_fields`, except that we expect a `TypeSpec` for\n tensor-like types. In particular, if the `value_type` of a field is\n `tf.Tensor` or a `CompositeTensor` subclass, then the corresponding value in\n `fields` is expected to contain a `TypeSpec` (rather than a value described by\n that `TypeSpec`).\n\nArgs:\n fields: A list of `ExtensionTypeField` objects.\n field_values: A `dict` mapping field names to values. Must contain an entry\n for each field. I.e., `set(field_values.keys())` must be equal to\n `set([f.name for f in fields])`.\n\nRaises:\n ValueError: If the keys of `field_values` do not match the names of\n the fields in `fields`.\n TypeError: If any value in `field_values` does not have the type indicated\n by the corresponding `ExtensionTypeField` object.", "source": "github_repos"} +{"code": "def __init__(self, name, state):\n stl.base.ParameterizedObject.__init__(self, name)\n self.state = state\n self.resolved_params = []", "docstring": "State specified in trasition spec and resolved.\n\nAttributes:\n state: Original parameterized state.\n resolved_params: List of parameter values resolved. The order of values is\n same to that of parameters.", "source": "github_repos"} +{"code": "def num_records_produced(self, name=None):\n if self._reader_ref.dtype == dtypes.resource:\n return gen_io_ops.reader_num_records_produced_v2(self._reader_ref, name=name)\n else:\n return gen_io_ops.reader_num_records_produced(self._reader_ref, name=name)", "docstring": "Returns the number of records this reader has produced.\n\n This is the same as the number of Read executions that have\n succeeded.\n\nArgs:\n name: A name for the operation (optional).\n\nReturns:\n An int64 Tensor.", "source": "github_repos"} +{"code": "def set_shard_dimensions(self, shard_dimensions):\n if len(shard_dimensions) != self.number_of_tuple_elements:\n raise ValueError(f'shard_dimensions is {str(shard_dimensions)}, but must be a list of length {self.number_of_tuple_elements}')\n for policy, dimension in zip(self._sharding_policies, shard_dimensions):\n policy.set_shard_dimension(dimension)\n self._validate()", "docstring": "Sets the shard_dimension of each element of the queue.\n\n shard_dimensions must be a list of length\n self.number_of_tuple_elements, and each element must be\n convertible to a Dimension compatible with self.tuple_shapes.\n\nArgs:\n shard_dimensions: the dimensions of each queue element.\n\nRaises:\n ValueError: if shard_dimensions is not of length\n self.number_of_tuple_elements; or an element of\n shard_dimensions cannot be converted to a Dimension; or an\n element of shard_dimensions is a Dimension that is out of\n range for the corresponding tuple element shape.", "source": "github_repos"} +{"code": "def segment_ids_to_row_splits(segment_ids, num_segments=None, out_type=None, name=None):\n from tensorflow.python.ops import bincount_ops\n if out_type is None:\n if isinstance(segment_ids, tensor.Tensor):\n out_type = segment_ids.dtype\n elif isinstance(num_segments, tensor.Tensor):\n out_type = num_segments.dtype\n else:\n out_type = dtypes.int64\n else:\n out_type = dtypes.as_dtype(out_type)\n with ops.name_scope(name, 'SegmentIdsToRaggedSplits', [segment_ids]) as name:\n segment_ids = ragged_util.convert_to_int_tensor(segment_ids, 'segment_ids', dtype=dtypes.int32)\n segment_ids.shape.assert_has_rank(1)\n if num_segments is not None:\n num_segments = ragged_util.convert_to_int_tensor(num_segments, 'num_segments', dtype=dtypes.int32)\n num_segments.shape.assert_has_rank(0)\n row_lengths = bincount_ops.bincount(segment_ids, minlength=num_segments, maxlength=num_segments, dtype=out_type)\n splits = array_ops.concat([[0], math_ops.cumsum(row_lengths)], axis=0)\n if num_segments is not None:\n const_num_segments = tensor_util.constant_value(num_segments)\n if const_num_segments is not None:\n splits.set_shape(tensor_shape.TensorShape([const_num_segments + 1]))\n return splits", "docstring": "Generates the RaggedTensor `row_splits` corresponding to a segmentation.\n\n Returns an integer vector `splits`, where `splits[0] = 0` and\n `splits[i] = splits[i-1] + count(segment_ids==i)`. Example:\n\n >>> print(tf.ragged.segment_ids_to_row_splits([0, 0, 0, 2, 2, 3, 4, 4, 4]))\n tf.Tensor([0 3 3 5 6 9], shape=(6,), dtype=int64)\n\nArgs:\n segment_ids: A 1-D integer Tensor.\n num_segments: A scalar integer indicating the number of segments. Defaults\n to `max(segment_ids) + 1` (or zero if `segment_ids` is empty).\n out_type: The dtype for the return value. Defaults to `segment_ids.dtype`,\n or `tf.int64` if `segment_ids` does not have a dtype.\n name: A name prefix for the returned tensor (optional).\n\nReturns:\n A sorted 1-D integer Tensor, with `shape=[num_segments + 1]`.", "source": "github_repos"} +{"code": "def _encode_fhir_path_builder(self, builder: expressions.Builder) -> Optional[str]:\n try:\n sql_expression = self._bq_interpreter.encode(builder)\n except Exception as e:\n self._error_reporter.report_fhir_path_error(self._abs_path_invocation(builder), str(builder), self._error_message_for_exception(e))\n return None\n return sql_expression", "docstring": "Returns a Standard SQL translation of the constraint `fhir_path_expression`.\n\n If an error is encountered during encoding, the associated error reporter\n will be notified, and this method will return `None`.\n\nArgs:\n builder: Builder containing the information to be encoded to Standard SQL.\n\nReturns:\n A Standard SQL encoding of the constraint `fhir_path_expression` upon\n successful completion. The SQL will evaluate to a single boolean\n indicating whether the constraint is satisfied.", "source": "github_repos"} +{"code": "def cuda(self) -> Rotation:\n if self._rot_mats is not None:\n return Rotation(rot_mats=self._rot_mats.cuda(), quats=None)\n elif self._quats is not None:\n return Rotation(rot_mats=None, quats=self._quats.cuda(), normalize_quats=False)\n else:\n raise ValueError('Both rotations are None')", "docstring": "Analogous to the cuda() method of torch Tensors\n\nReturns:\n A copy of the Rotation in CUDA memory", "source": "github_repos"} +{"code": "def test_sample_paths_2d(self, random_type, seed):\n mu = np.array([0.2, 0.7])\n a = np.array([[0.4, 0.1], [0.3, 0.2]])\n b = np.array([[0.33, -0.03], [0.21, 0.5]])\n\n def drift_fn(t, x):\n return mu * tf.sqrt(t) * tf.ones_like(x, dtype=t.dtype)\n\n def vol_fn(t, x):\n del x\n return (a * t + b) * tf.ones([2, 2], dtype=t.dtype)\n num_samples = 10000\n times = np.array([0.1, 0.21, 0.32, 0.43, 0.55])\n x0 = np.array([0.1, -1.1])\n paths = self.evaluate(euler_sampling.sample(dim=2, drift_fn=drift_fn, volatility_fn=vol_fn, times=times, num_samples=num_samples, initial_state=x0, time_step=0.01, random_type=random_type, seed=seed))\n self.assertAllClose(paths.shape, (num_samples, 5, 2), atol=0)\n means = np.mean(paths, axis=0)\n times = np.reshape(times, [-1, 1])\n expected_means = x0 + 2.0 / 3.0 * mu * np.power(times, 1.5)\n self.assertAllClose(means, expected_means, rtol=0.01, atol=0.01)", "docstring": "Tests path properties for 2-dimentional Ito process.\n\n We construct the following Ito processes.\n\n dX_1 = mu_1 sqrt(t) dt + s11 dW_1 + s12 dW_2\n dX_2 = mu_2 sqrt(t) dt + s21 dW_1 + s22 dW_2\n\n mu_1, mu_2 are constants.\n s_ij = a_ij t + b_ij\n\n For this process expected value at time t is (x_0)_i + 2/3 * mu_i * t^1.5.\n\nArgs:\n random_type: Random number type defined by tff.math.random.RandomType\n enum.\n seed: Random seed.", "source": "github_repos"} +{"code": "def enable_cpu_offload(self, accelerator_id: Optional[int]=0, **kwargs):\n if is_accelerate_available():\n from accelerate import cpu_offload_with_hook\n else:\n raise ImportError('`enable_model_cpu_offload` requires `accelerate`.')\n gpu_id = kwargs.get('gpu_id', 0)\n if gpu_id != 0:\n warnings.warn('The argument `gpu_id` is deprecated and will be removed in version 4.54.0 of Transformers. Please use `accelerator_id` instead.', FutureWarning)\n accelerator_id = gpu_id\n device_type = 'cuda'\n if is_torch_accelerator_available():\n device_type = torch.accelerator.current_accelerator().type\n device = torch.device(f'{device_type}:{accelerator_id}')\n torch_accelerator_module = getattr(torch, device_type)\n if self.device.type != 'cpu':\n self.to('cpu')\n torch_accelerator_module.empty_cache()\n self.semantic.input_embeds_layer, _ = cpu_offload_with_hook(self.semantic.input_embeds_layer, device)\n hook = None\n for cpu_offloaded_model in [self.semantic, self.coarse_acoustics, self.fine_acoustics]:\n _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)\n self.fine_acoustics_hook = hook\n _, hook = cpu_offload_with_hook(self.codec_model, device, prev_module_hook=hook)\n self.codec_model_hook = hook", "docstring": "Offloads all sub-models to CPU using accelerate, reducing memory usage with a low impact on performance. This\n method moves one whole sub-model at a time to the accelerator when it is used, and the sub-model remains in accelerator until the next sub-model runs.\n\nArgs:\n accelerator_id (`int`, *optional*, defaults to 0):\n accelerator id on which the sub-models will be loaded and offloaded. This argument is deprecated.\n kwargs (`dict`, *optional*):\n additional keyword arguments:\n `gpu_id`: accelerator id on which the sub-models will be loaded and offloaded.", "source": "github_repos"} +{"code": "def distribute_tensor(tensor, layout):\n from keras.src.distribution import TensorLayout\n if isinstance(layout, TensorLayout):\n layout = layout.backend_layout\n if jax_utils.is_in_jax_tracing_scope():\n return jax.lax.with_sharding_constraint(tensor, layout)\n if isinstance(tensor, jax.Array):\n if isinstance(layout, jax.sharding.Sharding) and tensor.sharding.is_equivalent_to(layout, ndim=len(tensor.shape)):\n return tensor\n elif isinstance(layout, jax_layout.Layout):\n current_layout = getattr(tensor, 'layout', None)\n if current_layout == layout:\n return tensor\n return jax.device_put(tensor, layout)", "docstring": "Distribute the tensor based on the layout.\n\n Note that this function can be used both in eager context, or within a\n jitted function.\n\nArgs:\n tensor: `jax.Array` that need to be distributed.\n layout: `TensorLayout` for the created variable, or a\n JAX-supported layout instance\n (e.g. `jax.experimental.layout.Layout`, `jax.sharding.Sharding`).\n\nReturns:\n Distributed value.", "source": "github_repos"} +{"code": "def forward(self, pixel_values: Optional[torch.Tensor]=None, bool_masked_pos: Optional[torch.BoolTensor]=None, head_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, interpolate_pos_encoding: Optional[bool]=None, return_dict: Optional[bool]=None) -> Union[tuple, BaseModelOutput]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n if pixel_values is None:\n raise ValueError('You have to specify pixel_values')\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n embedding_output = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding)\n encoder_outputs = self.encoder(embedding_output, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n sequence_output = encoder_outputs[0]\n sequence_output = self.layernorm(sequence_output)\n if not return_dict:\n head_outputs = (sequence_output,)\n return head_outputs + encoder_outputs[1:]\n return BaseModelOutput(last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions)", "docstring": "bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):\n Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).\n\nExample:\n ```python\n >>> from transformers import AutoImageProcessor, ViTMSNModel\n >>> import torch\n >>> from PIL import Image\n >>> import requests\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> image_processor = AutoImageProcessor.from_pretrained(\"facebook/vit-msn-small\")\n >>> model = ViTMSNModel.from_pretrained(\"facebook/vit-msn-small\")\n >>> inputs = image_processor(images=image, return_tensors=\"pt\")\n >>> with torch.no_grad():\n ... outputs = model(**inputs)\n >>> last_hidden_states = outputs.last_hidden_state\n ```", "source": "github_repos"} +{"code": "def get_conversion_metadata(model_buffer):\n model_object = flatbuffer_utils.convert_bytearray_to_object(model_buffer)\n if not model_object or not model_object.metadata:\n return None\n for meta in model_object.metadata:\n if meta.name.decode('utf-8') == CONVERSION_METADATA_FIELD_NAME:\n metadata_buf = model_object.buffers[meta.buffer].data.tobytes()\n return conversion_metadata_fb.ConversionMetadataT.InitFromObj(conversion_metadata_fb.ConversionMetadata.GetRootAsConversionMetadata(metadata_buf, 0))\n return None", "docstring": "Read conversion metadata from a tflite model.\n\nArgs:\n model_buffer: A tflite model.\n\nReturns:\n The conversion metadata or None if it is not populated.", "source": "github_repos"} +{"code": "def stateless_random_shuffle(input_tensor, seed, name=None):\n with tf.compat.v1.name_scope(name, default_name='stateless_random_shuffle', values=[input_tensor, seed]):\n input_tensor = tf.convert_to_tensor(input_tensor, name='input_tensor')\n seed = tf.convert_to_tensor(seed, name='random_seed')\n uniforms = tf.random.stateless_uniform(shape=[tf.shape(input_tensor)[0]], seed=seed, dtype=tf.float64)\n return tf.gather(input_tensor, tf.argsort(uniforms, stable=True, axis=0))", "docstring": "Produces stateless random shuffle of the 1st dimension of an input Tensor.\n\n This is a stateless version of `tf.random_shuffle`. If run twice with the same\n seed, produces the same result.\n\n Example\n ```python\n identity_shuffle = tf.range(100)\n random_shuffle = stateless_random_shuffle(identity_shuffle, seed=(42, 2))\n ```\n\nArgs:\n input_tensor: float32, float64, int32 or int64 1-D Tensor.\n seed: int32 or int64 Tensor of shape [2].\n name: Python `str` name prefixed to ops created by this function.\n\nReturns:\n A Tensor of the same shape and dtype as `input_tensor`.", "source": "github_repos"} +{"code": "def match_next_flag(tt_flags, pos):\n match = _FLAG_DOUBLE_QUOTE_PAT.match(tt_flags, pos)\n if match:\n return (match, True)\n match = _FLAG_SINGLE_QUOTE_PAT.match(tt_flags, pos)\n if match:\n return (match, True)\n match = _FLAG_NO_QUOTE_PAT.match(tt_flags, pos)\n if match:\n return (match, True)\n match = _FLAG_NO_EQUAL_PAT.match(tt_flags, pos)\n if match:\n return (match, False)\n return (None, False)", "docstring": "Returns the match for the next TensorTracer flag.\n\nArgs:\n tt_flags: a string that contains the flags.\n pos: where in flags to start the search.\n\nReturns:\n A pair where the first element is the regular-expression\n match found and the second element indicates if the match\n has a value.", "source": "github_repos"} +{"code": "def _broadcast_normalize_batch_in_training(x, gamma, beta, reduction_axes, epsilon=0.001):\n mean, var = nn.moments(x, reduction_axes, None, None, False)\n target_shape = []\n for axis in range(ndim(x)):\n if axis in reduction_axes:\n target_shape.append(1)\n else:\n target_shape.append(array_ops.shape(x)[axis])\n target_shape = array_ops_stack.stack(target_shape)\n broadcast_mean = array_ops.reshape(mean, target_shape)\n broadcast_var = array_ops.reshape(var, target_shape)\n if gamma is None:\n broadcast_gamma = None\n else:\n broadcast_gamma = array_ops.reshape(gamma, target_shape)\n if beta is None:\n broadcast_beta = None\n else:\n broadcast_beta = array_ops.reshape(beta, target_shape)\n normed = nn.batch_normalization(x, broadcast_mean, broadcast_var, broadcast_beta, broadcast_gamma, epsilon)\n return (normed, mean, var)", "docstring": "Non-fused, broadcast version of `normalize_batch_in_training`.\n\nArgs:\n x: Input tensor or variable.\n gamma: Tensor by which to scale the input.\n beta: Tensor with which to center the input.\n reduction_axes: iterable of integers,\n axes over which to normalize.\n epsilon: Fuzz factor.\n\nReturns:\n A tuple length of 3, `(normalized_tensor, mean, variance)`.", "source": "github_repos"} +{"code": "def _test_runner(test_id, test_env):\n global _running_in_worker, _env\n _running_in_worker = True\n _env = test_env\n test = unittest.defaultTestLoader.loadTestsFromName(test_id)\n runner = unittest.TextTestRunner()\n result = runner.run(test)\n failures = result.failures + result.expectedFailures + result.errors\n if failures:\n ret = _TestResult(status='failure', message=failures[0][1])\n elif result.skipped:\n ret = _TestResult(status='skipped', message=result.skipped[0][1])\n else:\n ret = _TestResult(status='ok', message=None)\n if ret.message:\n print(ret.message)\n return ret", "docstring": "Executes the test with the given test_id.\n\n This is a simple wrapper around TestRunner to be used with\n multi_process_runner. Similar to test.main(), but it executes only one test\n specified by test_id and returns whether the test succeeds. If the test fails,\n the function prints failures and errors to stdout.\n\nArgs:\n test_id: TestCase.id()\n test_env: a TestEnvironment object.\n\nReturns:\n A boolean indicates whether the test succeeds.", "source": "github_repos"} +{"code": "def __init__(self, state, value):\n stl.base.NamedObject.__init__(self, state)\n self.value = value\n self.param_values = []", "docstring": "State instance defined in a state transition spec.\n\n A state instance is defined either in \"pre_states\", \"post_states\", or\n \"error_states\" in a state transition spec. Resolve() turns this into\n state.StateValue resolved.\n\nAttributes:\n value: Current value of state of |name|.\n param_values: List of unresolved parameters of state of |name|.", "source": "github_repos"} +{"code": "def log_get(recipe_id=[], timezone='America/Los_Angeles', days=1):\n body = {'resourceNames': ['projects/%s' % UI_PROJECT], 'filter': ' logName=\"projects/%s/logs/StarThinker\" AND labels.version=\"%s\" AND labels.layer=\"JOB\" ' % (UI_PROJECT, LOG_VERSION), 'orderBy': 'timestamp desc', 'pageSize': 1000}\n if recipe_id:\n if isinstance(recipe_id, str):\n recipe_id = [recipe_id]\n body['filter'] += ' AND ( %s )' % ' OR '.join(('operation.id=\"%s\"' % r for r in recipe_id))\n for entry in API_StackDriver(Configuration(service=UI_SERVICE, project=UI_PROJECT), 'service', iterate=True).entries().list(body=body).execute():\n yield entry", "docstring": "Returns last actionable job run for a specific recipe or all recipes.\n\n Pulls status entries from StackDriver in reverse order. A single recipe may\n be run multiple times for multiple tasks at different hours, do not\n assume a JOB_END means a recipe is complete. Only way to ensure a recipe is\n complete\n is to compare all tasks run against all tasks in recipe ( not done by log\n code).\n\n Args: - recipe_id ( string or list ) - Optional, if provided returns a single\n record for a single job. - timezone ( string ) - The local timezone to cast\n all record times into.\n\nReturns:\n - ( iterator ) - Each log entry.", "source": "github_repos"} +{"code": "def _try_put(self, item):\n try:\n self._event_queue.put(item)\n except QueueClosedError:\n self._internal_close()\n if self._worker.failure_exc_info:\n _, exception, _ = self._worker.failure_exc_info\n raise exception from None", "docstring": "Attempts to enqueue an item to the event queue.\n\n If the queue is closed, this will close the EventFileWriter and reraise the\n exception that caused the queue closure, if one exists.\n\nArgs:\n item: the item to enqueue", "source": "github_repos"} +{"code": "def recipe_bigquery_storage(config, auth_read, bucket, auth_write, path, dataset, table, schema):\n bigquery(config, {'auth': auth_read, 'from': {'bucket': bucket, 'path': path}, 'to': {'auth': auth_write, 'dataset': dataset, 'table': table}, 'schema': schema})", "docstring": "Move using bucket and path prefix.\n\nArgs:\n auth_read (authentication) - Credentials used for reading data.\n bucket (string) - Google cloud bucket.\n auth_write (authentication) - Credentials used for writing data.\n path (string) - Path prefix to read from, no * required.\n dataset (string) - Existing BigQuery dataset.\n table (string) - Table to create from this query.\n schema (json) - Schema provided in JSON list format or empty list.", "source": "github_repos"} +{"code": "def _time_step(time, output_ta_t, state):\n if in_graph_mode:\n input_t = tuple((ta.read(time) for ta in input_ta))\n for input_, shape in zip(input_t, inputs_got_shape):\n input_.set_shape(shape[1:])\n else:\n input_t = tuple((ta[time.numpy()] for ta in input_ta))\n input_t = nest.pack_sequence_as(structure=inputs, flat_sequence=input_t)\n call_cell = lambda: cell(input_t, state)\n if sequence_length is not None:\n output, new_state = _rnn_step(time=time, sequence_length=sequence_length, min_sequence_length=min_sequence_length, max_sequence_length=max_sequence_length, zero_output=zero_output, state=state, call_cell=call_cell, state_size=state_size, skip_conditionals=True)\n else:\n output, new_state = call_cell()\n output = nest.flatten(output)\n if in_graph_mode:\n output_ta_t = tuple((ta.write(time, out) for ta, out in zip(output_ta_t, output)))\n else:\n for ta, out in zip(output_ta_t, output):\n ta[time.numpy()] = out\n return (time + 1, output_ta_t, new_state)", "docstring": "Take a time step of the dynamic RNN.\n\nArgs:\n time: int32 scalar Tensor.\n output_ta_t: List of `TensorArray`s that represent the output.\n state: nested tuple of vector tensors that represent the state.\n\nReturns:\n The tuple (time + 1, output_ta_t with updated flow, new_state).", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, layer_head_mask: torch.Tensor, is_index_masked=None, is_index_global_attn=None, is_global_attn=None, output_attentions=False):\n residual = hidden_states\n attn_outputs = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask, is_index_masked=is_index_masked, is_index_global_attn=is_index_global_attn, is_global_attn=is_global_attn, output_attentions=output_attentions)\n hidden_states = attn_outputs[0]\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n hidden_states = residual + hidden_states\n hidden_states = self.self_attn_layer_norm(hidden_states)\n residual = hidden_states\n hidden_states = self.activation_fn(self.fc1(hidden_states))\n hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)\n hidden_states = self.fc2(hidden_states)\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n hidden_states = residual + hidden_states\n hidden_states = self.final_layer_norm(hidden_states)\n if hidden_states.dtype == torch.float16 and (torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()):\n clamp_value = torch.finfo(hidden_states.dtype).max - 1000\n hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)\n return (hidden_states,) + attn_outputs[1:]", "docstring": "Args:\n hidden_states (`torch.FloatTensor`): input to the layer of shape *(batch, seq_len, embed_dim)*\n attention_mask (`torch.FloatTensor`): attention mask of size\n *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.\n layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size\n *(encoder_attention_heads,)*.", "source": "github_repos"} +{"code": "def _to_int(operand: List[WorkSpaceMessage]) -> Optional[int]:\n if not operand:\n return None\n if len(operand) > 1:\n raise ValueError('Expected single int result but got multiple items.')\n if not fhir_types.is_integer(operand[0].message):\n raise ValueError('Expected single int but got a non-int value.')\n return proto_utils.get_value_at_field(operand[0].message, 'value')", "docstring": "Converts an evaluation result to an int value or None.\n\nArgs:\n operand: an expression operand result to convert to int.\n\nReturns:\n the int value, or None if the operand was empty.\n\nRaises:\n ValueError if it is not an empty result or a single, int value.", "source": "github_repos"} +{"code": "def __init__(self, tensor_proto, initialized=True):\n self._tensor_proto = tensor_proto\n self._initialized = initialized", "docstring": "Constructor.\n\nArgs:\n tensor_proto: the `TensorProto` object that cannot be represented as a\n `np.ndarray` object.\n initialized: (`bool`) whether the Tensor is initialized.", "source": "github_repos"} +{"code": "def _maybe_save_assets(write_fn, assets_to_add=None):\n asset_filename_map = {}\n if assets_to_add is None:\n tf_logging.info('No assets to save.')\n return asset_filename_map\n for asset_tensor in assets_to_add:\n asset_source_filepath = _asset_path_from_tensor(asset_tensor)\n if not asset_source_filepath:\n raise ValueError(f'Asset filepath tensor {asset_tensor} in is invalid.')\n asset_filename = get_asset_filename_to_add(asset_source_filepath, asset_filename_map)\n write_fn(asset_filename, asset_tensor)\n asset_filename_map[asset_filename] = asset_source_filepath\n tf_logging.info('Assets added to graph.')\n return asset_filename_map", "docstring": "Saves assets to the meta graph.\n\nArgs:\n write_fn: A function callback that writes assets into meta graph.\n assets_to_add: The list where the asset paths are setup.\n\nReturns:\n A dict of asset basenames for saving to the original full path to the asset.\n\nRaises:\n ValueError: Indicating an invalid filepath tensor.", "source": "github_repos"} +{"code": "def mask_to_rgb(self, image: np.ndarray, palette: Optional[List[Tuple[int, int]]]=None, data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:\n return mask_to_rgb(image, palette=palette, data_format=data_format)", "docstring": "Converts a segmentation map to RGB format.\n\nArgs:\n image (`np.ndarray`):\n Segmentation map with dimensions (height, width) where pixel values represent the class index.\n palette (`List[Tuple[int, int]]`, *optional*, defaults to `None`):\n Palette to use to convert the mask to RGB format. If unset, the mask is duplicated across the channel\n dimension.\n data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the output image. If unset, the channel dimension format of the input\n image is used. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n\nReturns:\n `np.ndarray`: The mask in RGB format.", "source": "github_repos"} +{"code": "def add_session_log(self, session_log, global_step=None):\n event = event_pb2.Event(session_log=session_log)\n self._add_event(event, global_step)", "docstring": "Adds a `SessionLog` protocol buffer to the event file.\n\n This method wraps the provided session in an `Event` protocol buffer\n and adds it to the event file.\n\nArgs:\n session_log: A `SessionLog` protocol buffer.\n global_step: Number. Optional global step value to record with the\n summary.", "source": "github_repos"} +{"code": "def parse_step(step_name):\n prefix = 'step'\n step_name = step_name.lower().replace(' ', '_')\n step_name = step_name[len(prefix):] if prefix and step_name.startswith(prefix) else step_name\n return step_name.strip(':_')", "docstring": "Replaces white spaces and removes 'Step:' label\n\nArgs:\n step_name(str): step name passed in metric ParDo\n\nReturns:\n lower case step name without namespace and step label", "source": "github_repos"} +{"code": "def _create_controller_info_record(self, controller_module_name):\n module = self._controller_modules[controller_module_name]\n controller_info = None\n try:\n controller_info = module.get_info(copy.copy(self._controller_objects[controller_module_name]))\n except AttributeError:\n logging.warning('No optional debug info found for controller %s. To provide it, implement `get_info`.', controller_module_name)\n try:\n yaml.dump(controller_info)\n except TypeError:\n logging.warning('The info of controller %s in class \"%s\" is not YAML serializable! Coercing it to string.', controller_module_name, self._class_name)\n controller_info = str(controller_info)\n return records.ControllerInfoRecord(self._class_name, module.MOBLY_CONTROLLER_CONFIG_NAME, controller_info)", "docstring": "Creates controller info record for a particular controller type.\n\n Info is retrieved from all the controller objects spawned from the\n specified module, using the controller module's `get_info` function.\n\nArgs:\n controller_module_name: string, the name of the controller module\n to retrieve info from.\n\nReturns:\n A records.ControllerInfoRecord object.", "source": "github_repos"} +{"code": "def relative_batch_tokens_ids_to_midi(self, tokens: np.ndarray, beatstep: np.ndarray, beat_offset_idx: int=0, bars_per_batch: int=2, cutoff_time_idx: int=12):\n beat_offset_idx = 0 if beat_offset_idx is None else beat_offset_idx\n notes = self.relative_batch_tokens_ids_to_notes(tokens=tokens, beat_offset_idx=beat_offset_idx, bars_per_batch=bars_per_batch, cutoff_time_idx=cutoff_time_idx)\n midi = self.notes_to_midi(notes, beatstep, offset_sec=beatstep[beat_offset_idx])\n return midi", "docstring": "Converts tokens to Midi. This method calls `relative_batch_tokens_ids_to_notes` method to convert batch tokens\n to notes then uses `notes_to_midi` method to convert them to Midi.\n\nArgs:\n tokens (`numpy.ndarray`):\n Denotes tokens which alongside beatstep will be converted to Midi.\n beatstep (`np.ndarray`):\n We get beatstep from feature extractor which is also used to get Midi.\n beat_offset_idx (`int`, *optional*, defaults to 0):\n Denotes beat offset index for each note in generated Midi.\n bars_per_batch (`int`, *optional*, defaults to 2):\n A parameter to control the Midi output generation.\n cutoff_time_idx (`int`, *optional*, defaults to 12):\n Denotes the cutoff time index for each note in generated Midi.", "source": "github_repos"} +{"code": "def _create_all_weights(self, params):\n raise NotImplementedError", "docstring": "Creates and sets all optimizer weights.\n\nArgs:\n params: list or tuple of `Variable` objects that will be minimized\n using this optimizer.\n\nReturns:\n Specific weight values that are used in `get_updates`", "source": "github_repos"} +{"code": "def __init__(self, config: GraniteMoeHybridConfig):\n super(GraniteMoeHybridMoE, self).__init__()\n self.input_size = config.hidden_size\n self.hidden_size = config.intermediate_size\n self.activation = ACT2FN[config.hidden_act]\n self.input_linear = GraniteMoeHybridParallelExperts(config.num_local_experts, self.input_size, self.hidden_size * 2)\n self.output_linear = GraniteMoeHybridParallelExperts(config.num_local_experts, self.hidden_size, self.input_size)\n self.router = GraniteMoeHybridTopKGating(input_size=self.input_size, num_experts=config.num_local_experts, top_k=config.num_experts_per_tok)", "docstring": "A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.\n\nArgs:\n config:\n Configuration object with model hyperparameters.", "source": "github_repos"} +{"code": "def _MaybeColocateWith(inputs):\n if not inputs:\n yield\n else:\n with ops.colocate_with(inputs[0]), _MaybeColocateWith(inputs[1:]):\n yield", "docstring": "A context manager for (maybe) colocating with a list of input tensors.\n\nArgs:\n inputs: A list of `Tensor` or `Operation` objects.\n\nReturns:\n A context manager.", "source": "github_repos"} +{"code": "def make_initializable_iterator(dataset: DatasetV1, shared_name=None) -> iterator_ops.Iterator:\n try:\n return dataset._make_initializable_iterator(shared_name)\n except AttributeError:\n return DatasetV1Adapter(dataset)._make_initializable_iterator(shared_name)", "docstring": "Creates an iterator for elements of `dataset`.\n\n Note: The returned iterator will be in an uninitialized state,\n and you must run the `iterator.initializer` operation before using it:\n\n ```python\n dataset = ...\n iterator = tf.compat.v1.data.make_initializable_iterator(dataset)\n # ...\n sess.run(iterator.initializer)\n ```\n\nArgs:\n dataset: A `tf.data.Dataset`.\n shared_name: (Optional.) If non-empty, the returned iterator will be shared\n under the given name across multiple sessions that share the same devices\n (e.g. when using a remote server).\n\nReturns:\n A `tf.data.Iterator` for elements of `dataset`.\n\nRaises:\n RuntimeError: If eager execution is enabled.\n\n @compatibility(TF2)\n This is a legacy API for consuming dataset elements and should only be used\n during transition from TF 1 to TF 2. Note that using this API should be\n a transient state of your code base as there are in general no guarantees\n about the interoperability of TF 1 and TF 2 code.\n\n In TF 2 datasets are Python iterables which means you can consume their\n elements using `for elem in dataset: ...` or by explicitly creating iterator\n via `iterator = iter(dataset)` and fetching its elements via\n `values = next(iterator)`.\n @end_compatibility", "source": "github_repos"} +{"code": "def _cmp_rel(self, state, op_name, x, y):\n ret = self.ctx.program.NewVariable()\n leftover_x = self.ctx.program.NewVariable()\n leftover_y = self.ctx.program.NewVariable()\n op_not_eq = op_name not in ('EQ', 'NE')\n reported = False\n for b1 in x.bindings:\n for b2 in y.bindings:\n op = getattr(slots, op_name)\n try:\n err = False\n val = compare.cmp_rel(self.ctx, op, b1.data, b2.data)\n except compare.CmpTypeError:\n val = None\n if state.node.HasCombination([b1, b2]):\n err = True\n reported = True\n self.ctx.errorlog.unsupported_operands(self.frames, op, x, y)\n if val is None:\n if op_not_eq and isinstance(b1.data, abstract.Class) and err:\n ret.AddBinding(self.ctx.convert.unsolvable, {b1, b2}, state.node)\n elif isinstance(b1.data, abstract.SequenceLength):\n ret.AddBinding(self.ctx.convert.bool_values[val], {b1, b2}, state.node)\n else:\n leftover_x.PasteBinding(b1, state.node)\n leftover_y.PasteBinding(b2, state.node)\n else:\n ret.AddBinding(self.ctx.convert.bool_values[val], {b1, b2}, state.node)\n if leftover_x.bindings:\n op = f'__{op_name.lower()}__'\n report_errors = op_not_eq and (not bool(ret.bindings)) and (not reported)\n state, leftover_ret = vm_utils.call_binary_operator(state, op, leftover_x, leftover_y, report_errors=report_errors, ctx=self.ctx)\n ret.PasteVariable(leftover_ret, state.node)\n return (state, ret)", "docstring": "Implementation of relational operators CMP_(LT|LE|EQ|NE|GE|GT).\n\nArgs:\n state: Initial FrameState.\n op_name: An operator name, e.g., \"EQ\".\n x: A variable of the lhs value.\n y: A variable of the rhs value.\n\nReturns:\n A tuple of the new FrameState and the return variable.", "source": "github_repos"} +{"code": "def _assign_stablehlo_quantization_config_or_populate_default(self, args):\n if self.experimental_stablehlo_quantizer_config is not None and Optimize.DEFAULT not in self.optimizations:\n args['quantization_config'] = self.experimental_stablehlo_quantizer_config\n elif Optimize.DEFAULT in self.optimizations and self.representative_dataset:\n if len(self._saved_model_exported_names) != 1:\n raise ValueError('StableHLO quantizer is only supported when converting from a SavedModel with one signature key.')\n signature_key = self._saved_model_exported_names[0]\n tfrecord_file_path = tempfile.mkstemp(suffix='.tfrecord', prefix=signature_key)[1]\n rd.TfRecordRepresentativeDatasetSaver({signature_key: tfrecord_file_path}).save({signature_key: self.representative_dataset()})\n quantization_config = qc.QuantizationConfig(static_range_ptq_preset=qc.StaticRangePtqPreset(representative_datasets=[qc.RepresentativeDatasetConfig(tf_record=qc.TfRecordFile(path=tfrecord_file_path))], enable_per_channel_quantized_weight=True, enable_full_int_quantization=True), pipeline_config=qc.PipelineConfig(unpack_quantized_types=False))\n args['quantization_config'] = quantization_config\n else:\n raise ValueError('StableHLO quantizer only supports static-range and weight-only PTQ.')", "docstring": "Assigns `QuantizationConfig` to `args` or populate default.\n\nArgs:\n args: Dictionary of argument names and associated values.", "source": "github_repos"} +{"code": "def assert_type_v2(tensor, tf_type, message=None, name=None):\n assert_type(tensor=tensor, tf_type=tf_type, message=message, name=name)", "docstring": "Asserts that the given `Tensor` is of the specified type.\n\n This can always be checked statically, so this method returns nothing.\n\nExample:\n >>> a = tf.Variable(1.0)\n >>> tf.debugging.assert_type(a, tf_type= tf.float32)\n\n >>> b = tf.constant(21)\n >>> tf.debugging.assert_type(b, tf_type=tf.bool)\n Traceback (most recent call last):\n ...\n TypeError: ...\n\n >>> c = tf.SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2],\n ... dense_shape=[3, 4])\n >>> tf.debugging.assert_type(c, tf_type= tf.int32)\n\nArgs:\n tensor: A `Tensor`, `SparseTensor` or `tf.Variable` .\n tf_type: A tensorflow type (`dtypes.float32`, `tf.int64`, `dtypes.bool`,\n etc).\n message: A string to prefix to the default message.\n name: A name for this operation. Defaults to \"assert_type\"\n\nRaises:\n TypeError: If the tensor's data type doesn't match `tf_type`.", "source": "github_repos"} +{"code": "def from_fn(cls, dna_spec: DNASpec, generator_fn: Callable[['DecisionPoint'], Union[List[int], float, str, 'DNA']]) -> 'DNA':\n if not isinstance(dna_spec, DNASpec):\n raise TypeError(f\"Argument 'dna_spec' should be DNASpec type. Encountered {dna_spec}.\")\n if dna_spec.is_space:\n children = []\n for child_spec in dna_spec.elements:\n children.append(DNA.from_fn(child_spec, generator_fn))\n if len(children) == 1:\n return children[0]\n dna = DNA(None, children)\n elif dna_spec.is_categorical:\n assert isinstance(dna_spec, DecisionPoint), dna_spec\n decision = generator_fn(dna_spec)\n if isinstance(decision, DNA):\n dna = decision\n else:\n if len(decision) != dna_spec.num_choices:\n raise ValueError(f'Number of DNA child values does not match the number of choices. Child values: {decision!r}, Choices: {dna_spec.num_choices}, Location: {dna_spec.location.path}.')\n children = []\n for i, choice in enumerate(decision):\n choice_location = utils.KeyPath(i, dna_spec.location)\n if not isinstance(choice, int):\n raise ValueError(f'Choice value should be int. Encountered: {choice}, Location: {choice_location.path}.')\n if choice >= len(dna_spec.candidates):\n raise ValueError(f'Choice out of range. Value: {choice}, Candidates: {len(dna_spec.candidates)}, Location: {choice_location.path}.')\n child_dna = DNA.from_fn(dna_spec.candidates[choice], generator_fn)\n children.append(DNA(choice, [child_dna]))\n dna = DNA(None, children)\n else:\n assert isinstance(dna_spec, DecisionPoint), dna_spec\n decision = generator_fn(dna_spec)\n if isinstance(decision, DNA):\n dna = decision\n else:\n dna = DNA(decision)\n dna_spec.validate(dna)\n return dna", "docstring": "Generate a DNA with user generator function.\n\nArgs:\n dna_spec: The DNASpec for the DNA.\n generator_fn: A callable object with signature:\n\n `(decision_point) -> decision`\n\n The decision_point is a `Choices` object or a `Float` object.\n The returned decision should be:\n\n * a list of integer or a DNA object for a `Choices` decision point.\n When a DNA is returned, it will be used as the DNA for the entire\n sub-tree, hence `generate_fn` will not be called on sub-decision\n points.\n * a float or a DNA object for a Float decision point.\n * a string or a DNA object for a CustomDecisionPoint.\n\nReturns:\n A DNA generated from the user function.", "source": "github_repos"} +{"code": "def regularized_evolution(mutator=mutators.Uniform(), population_size: int=100, tournament_size: int=10, seed: Optional[int]=None):\n if tournament_size < 2:\n raise ValueError(f'`tournament_size` must be no less than 2. Encountered: {tournament_size}')\n if population_size < tournament_size:\n raise ValueError(f'The value of `population_size` ({population_size}) must be no less than the value of `tournament_size` ({tournament_size}).')\n return base.Evolution(selectors.Random(tournament_size, seed=seed) >> selectors.Top(1) >> mutator, population_init=(pg.geno.Random(seed=seed), population_size), population_update=selectors.Last(population_size))", "docstring": "Regularized Evolution algorithm.\n\n https://www.aaai.org/ojs/index.php/AAAI/article/view/4405.\n\nArgs:\n mutator: Mutator to use.\n population_size: Population size. Must be larger than tournament size.\n tournament_size: Tournament size.\n seed: Random seed. If None, the current system time is used as seed.\n\nReturns:\n An `Evolution` object.", "source": "github_repos"} +{"code": "def Save(obj: _Serializable, filename: Path, compress: bool=False, open_function=open) -> None:\n with open_function(filename, 'wb') as fi:\n if compress:\n with gzip.GzipFile(filename='', mode='wb', fileobj=fi, mtime=1.0) as zfi:\n zfi.write(Encode(obj))\n else:\n fi.write(Encode(obj))", "docstring": "Saves a serializable object to a file.\n\nArgs:\n obj: The object to serialize.\n filename: filename to write to.\n compress: if True, the data will be compressed using gzip. The given\n filename will be used, unaltered.\n open_function: The function to use to open files. Defaults to the builtin\n open() function.", "source": "github_repos"} +{"code": "def slice_update(inputs, start_indices, updates):\n if any_symbolic_tensors((inputs, start_indices, updates)):\n return SliceUpdate().symbolic_call(inputs, start_indices, updates)\n return backend.core.slice_update(inputs, start_indices, updates)", "docstring": "Update an input by slicing in a tensor of updated values.\n\n At a high level, this operation does\n `inputs[start_indices: start_indices + updates.shape] = updates`.\n Assume inputs is a tensor of shape `(D0, D1, ..., Dn)`,\n `start_indices` must be a list/tuple of n integers, specifying the starting\n indices. `updates` must have the same rank as `inputs`, and the size of each\n dim must not exceed `Di - start_indices[i]`. For example, if we have 2D\n inputs `inputs = np.zeros((5, 5))`, and we want to update the intersection\n of last 2 rows and last 2 columns as 1, i.e.,\n `inputs[3:, 3:] = np.ones((2, 2))`, then we can use the code below:\n\n ```python\n inputs = np.zeros((5, 5))\n start_indices = [3, 3]\n updates = np.ones((2, 2))\n inputs = keras.ops.slice_update(inputs, start_indices, updates)\n ```\n\nArgs:\n inputs: A tensor, the tensor to be updated.\n start_indices: A list/tuple of shape `(inputs.ndim,)`, specifying\n the starting indices for updating.\n updates: A tensor, the new values to be put to `inputs` at `indices`.\n `updates` must have the same rank as `inputs`.\n\nReturns:\n A tensor, has the same shape and dtype as `inputs`.", "source": "github_repos"} +{"code": "def matches(pcoll, regex, group=0):\n regex = Regex._regex_compile(regex)\n\n def _process(element):\n m = regex.match(element)\n if m:\n yield m.group(group)\n return pcoll | FlatMap(_process)", "docstring": "Returns the matches (group 0 by default) if zero or more characters at the\n beginning of string match the regular expression. To match the entire\n string, add \"$\" sign at the end of regex expression.\n\n Group can be integer value or a string value.\n\nArgs:\n regex: the regular expression string or (re.compile) pattern.\n group: (optional) name/number of the group, it can be integer or a string\n value. Defaults to 0, meaning the entire matched string will be\n returned.", "source": "github_repos"} +{"code": "def ConvertOutputToUnicode(self, buf):\n if isinstance(buf, str):\n buf = buf.encode(self._encoding)\n return str(buf, self._encoding, 'replace')", "docstring": "Converts a console output string buf to unicode.\n\n Mainly used for testing. Allows test comparisons in unicode while ensuring\n that unicode => encoding => unicode works.\n\nArgs:\n buf: The console output string to convert.\n\nReturns:\n The console output string buf converted to unicode.", "source": "github_repos"} +{"code": "def if_false(self, predicate: Callable[..., bool]):\n return Conditional(predicate, None, self)", "docstring": "Conditionally applies current operation when predicate returns False.\n\nArgs:\n predicate: The predicate that takes the outputs from the previous\n operation as input, with optional keyword arguments `global_state` and\n `step`. Returns False if current operation needs to be enabled.\n Otherwise no operation will be performed.\n\nReturns:\n A conditional operation.", "source": "github_repos"} +{"code": "def report_proto(self):\n if self._report_proto:\n return self._report_proto\n else:\n raise ValueError('Call to report_proto must be done after tracing.Report proto only exists for trace_mode=[summary|full_tensor_summary]')", "docstring": "Getter for tensor_tracer.proto object for summary and full_tensor_summary modes.\n\nReturns:\n A tensor_tracer.proto object.\n\nRaises:\n ValueError if called before tracing happens, or when trace mode is not\n summary or full_tensor_summary.", "source": "github_repos"} +{"code": "def __init__(self, c_in, c_hidden, no_heads, starting=True, inf=1000000000.0):\n super().__init__()\n self.c_in = c_in\n self.c_hidden = c_hidden\n self.no_heads = no_heads\n self.starting = starting\n self.inf = inf\n self.layer_norm = LayerNorm(self.c_in)\n self.linear = EsmFoldLinear(c_in, self.no_heads, bias=False, init='normal')\n self.mha = EsmFoldAttention(self.c_in, self.c_in, self.c_in, self.c_hidden, self.no_heads)", "docstring": "Args:\n c_in:\n Input channel dimension\n c_hidden:\n Overall hidden channel dimension (not per-head)\n no_heads:\n Number of attention heads", "source": "github_repos"} +{"code": "def forward(self, hidden_state):\n output_tensor = hidden_state\n output_tensor = self.conv1(self.snake1(output_tensor))\n output_tensor = self.conv2(self.snake2(output_tensor))\n padding = (hidden_state.shape[-1] - output_tensor.shape[-1]) // 2\n if padding > 0:\n hidden_state = hidden_state[..., padding:-padding]\n output_tensor = hidden_state + output_tensor\n return output_tensor", "docstring": "Forward pass through the residual unit.\n\nArgs:\n hidden_state (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):\n Input tensor .\n\nReturns:\n output_tensor (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):\n Input tensor after passing through the residual unit.", "source": "github_repos"} +{"code": "def GetLogicalLines(self):\n self._StartNewLine()\n return self._logical_lines", "docstring": "Fetch the result of the tree walk.\n\n Note: only call this after visiting the whole tree.\n\nReturns:\n A list of LogicalLine objects.", "source": "github_repos"} +{"code": "def parse_cluster_spec(cluster_spec, cluster, verbose=False):\n job_strings = cluster_spec.split(',')\n if not cluster_spec:\n raise ValueError('Empty cluster_spec string')\n for job_string in job_strings:\n job_def = cluster.job.add()\n if job_string.count('|') != 1:\n raise ValueError(\"Not exactly one instance of '|' in cluster_spec\")\n job_name = job_string.split('|')[0]\n if not job_name:\n raise ValueError('Empty job_name in cluster_spec')\n job_def.name = job_name\n if verbose:\n logging.info('Added job named \"%s\"', job_name)\n job_tasks = job_string.split('|')[1].split(';')\n for i in range(len(job_tasks)):\n if not job_tasks[i]:\n raise ValueError('Empty task string at position %d' % i)\n job_def.tasks[i] = job_tasks[i]\n if verbose:\n logging.info(' Added task \"%s\" to job \"%s\"', job_tasks[i], job_name)", "docstring": "Parse content of cluster_spec string and inject info into cluster protobuf.\n\nArgs:\n cluster_spec: cluster specification string, e.g.,\n \"local|localhost:2222;localhost:2223\"\n cluster: cluster protobuf.\n verbose: If verbose logging is requested.\n\nRaises:\n ValueError: if the cluster_spec string is invalid.", "source": "github_repos"} +{"code": "def __init__(self, weight_shape: Sequence[int], bias_size: Optional[int]=None, activation_fn: Optional[ops.Operation]=None, use_biasadd: bool=True) -> None:\n self.bias_size = bias_size\n self.activation_fn = activation_fn\n self.use_biasadd = use_biasadd\n self.filters = np.random.uniform(low=-1.0, high=1.0, size=weight_shape)\n if bias_size is not None:\n self.bias = np.random.uniform(low=-1.0, high=1.0, size=bias_size)", "docstring": "Initializes a MatmulModel.\n\nArgs:\n weight_shape: Shape of the weight tensor.\n bias_size: If None, do not use bias. Else, use given size as bias.\n activation_fn: The activation function to be used. No activation\n function if None.\n use_biasadd: If True, use BiasAdd for adding bias, else use AddV2.", "source": "github_repos"} +{"code": "def _ConstructAndTestGradient(self, image_shape, kernel_shape, strides, rates, padding, use_gpu, dtype=dtypes.float32):\n assert image_shape[3] == kernel_shape[2]\n np.random.seed(1)\n image = np.random.random_sample(image_shape).astype(np.float32)\n kernel = np.random.random_sample(kernel_shape).astype(np.float32)\n strides = [1] + strides + [1]\n rates = [1] + rates + [1]\n image_tensor = constant_op.constant(image, shape=image_shape, name='input', dtype=dtype)\n kernel_tensor = constant_op.constant(kernel, shape=kernel_shape, name='filter', dtype=dtype)\n\n def compute_dilation2d(image_tensor, kernel_tensor):\n return nn_ops.dilation2d(image_tensor, kernel_tensor, strides=strides, rates=rates, padding=padding, name='dilation2d')\n with test_util.device(use_gpu=use_gpu):\n with self.cached_session():\n err1 = gradient_checker_v2.max_error(*gradient_checker_v2.compute_gradient(lambda x: compute_dilation2d(x, kernel_tensor), [image_tensor]))\n err2 = gradient_checker_v2.max_error(*gradient_checker_v2.compute_gradient(lambda x: compute_dilation2d(image_tensor, x), [kernel_tensor]))\n err = max(err1, err2)\n print('Dilation gradient error = %f' % err)\n if dtype == dtypes.bfloat16:\n self.assertLess(err, 4.0)\n else:\n self.assertLess(err, 0.0001)", "docstring": "Verifies the gradients of the dilation function.\n\nArgs:\n image_shape: Input shape, [batch, in_height, in_width, channels].\n kernel_shape: Filter shape, [filter_height, filter_width, channels].\n strides: Output strides, specified as [stride_height, stride_width].\n rates: Atrous rates, specified as [rate_height, rate_width].\n padding: Padding type.\n use_gpu: Whether we are running on GPU.", "source": "github_repos"} +{"code": "def check_destinations(destinations):\n if isinstance(destinations, (resource_variable_ops.BaseResourceVariable, tensor_lib.Tensor)):\n return bool(destinations.device)\n return bool(destinations)", "docstring": "Checks whether `destinations` is not empty.\n\nArgs:\n destinations: a `DistributedValues`, variable, or string object.\n\nReturns:\n Boolean which is True if `destinations` is not empty.", "source": "github_repos"} +{"code": "def get_model_class_for_feature(feature: str, framework: str='pt') -> Type:\n task = FeaturesManager.feature_to_task(feature)\n FeaturesManager._validate_framework_choice(framework)\n if framework == 'pt':\n task_to_automodel = FeaturesManager._TASKS_TO_AUTOMODELS\n else:\n task_to_automodel = FeaturesManager._TASKS_TO_TF_AUTOMODELS\n if task not in task_to_automodel:\n raise KeyError(f'Unknown task: {feature}. Possible values are {list(FeaturesManager._TASKS_TO_AUTOMODELS.values())}')\n return task_to_automodel[task]", "docstring": "Attempts to retrieve an AutoModel class from a feature name.\n\nArgs:\n feature (`str`):\n The feature required.\n framework (`str`, *optional*, defaults to `\"pt\"`):\n The framework to use for the export.\n\nReturns:\n The AutoModel class corresponding to the feature.", "source": "github_repos"} +{"code": "def get_tensor_by_name(self, name) -> tensor_lib.Tensor:\n if not isinstance(name, str):\n raise TypeError('Tensor names are strings (or similar), not %s.' % type(name).__name__)\n tensor = cast(tensor_lib.Tensor, self.as_graph_element(name, allow_tensor=True, allow_operation=False))\n return tensor", "docstring": "Returns the `Tensor` with the given `name`.\n\n This method may be called concurrently from multiple threads.\n\nArgs:\n name: The name of the `Tensor` to return.\n\nReturns:\n The `Tensor` with the given `name`.\n\nRaises:\n TypeError: If `name` is not a string.\n KeyError: If `name` does not correspond to a tensor in this graph.", "source": "github_repos"} +{"code": "def _ValidateFractionalAvgPoolResult(self, input_tensor, pooling_ratio, pseudo_random, overlapping):\n with self.cached_session() as sess:\n p, r, c = nn_ops.fractional_avg_pool_v2(input_tensor, pooling_ratio, pseudo_random, overlapping, seed=self._SEED)\n actual, row_seq, col_seq = self.evaluate([p, r, c])\n expected = self._GetExpectedFractionalAvgPoolResult(input_tensor, row_seq, col_seq, overlapping)\n self.assertShapeEqual(expected, p)\n self.assertAllClose(expected, actual)", "docstring": "Validate FractionalAvgPool's result against expected.\n\n Expected result is computed given input_tensor, and pooling region defined\n by row_seq and col_seq.\n\nArgs:\n input_tensor: A tensor or numpy ndarray.\n pooling_ratio: A list or tuple of length 4, first and last element be 1.\n pseudo_random: Use pseudo random method to generate pooling sequence.\n overlapping: Use overlapping when pooling.\n\nReturns:\n None", "source": "github_repos"} +{"code": "def _init_init_op(self, init_op=USE_DEFAULT, init_feed_dict=None):\n if init_op is Supervisor.USE_DEFAULT:\n init_op = self._get_first_op_from_collection(ops.GraphKeys.INIT_OP)\n if init_op is None:\n init_op = variables.global_variables_initializer()\n ops.add_to_collection(ops.GraphKeys.INIT_OP, init_op)\n self._init_op = init_op\n self._init_feed_dict = init_feed_dict", "docstring": "Initializes init_op.\n\nArgs:\n init_op: `Operation` to initialize the variables. If set to USE_DEFAULT,\n create an op that initializes all variables and tables.\n init_feed_dict: A dictionary that maps `Tensor` objects to feed values.\n This feed dictionary will be used when `init_op` is evaluated.", "source": "github_repos"} +{"code": "def _compute_dynamic_ntk_parameters(config: Optional[PretrainedConfig]=None, device: Optional['torch.device']=None, seq_len: Optional[int]=None, **rope_kwargs) -> tuple['torch.Tensor', float]:\n if config is not None and len(rope_kwargs) > 0:\n raise ValueError(f'Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in `_compute_dynamic_ntk_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}')\n if len(rope_kwargs) > 0:\n base = rope_kwargs['base']\n dim = rope_kwargs['dim']\n max_position_embeddings = rope_kwargs['max_position_embeddings']\n factor = rope_kwargs['factor']\n elif config is not None:\n base = config.rope_theta\n partial_rotary_factor = config.partial_rotary_factor if hasattr(config, 'partial_rotary_factor') else 1.0\n head_dim = getattr(config, 'head_dim', config.hidden_size // config.num_attention_heads)\n dim = int(head_dim * partial_rotary_factor)\n max_position_embeddings = config.max_position_embeddings\n factor = config.rope_scaling['factor']\n attention_factor = 1.0\n seq_len = seq_len if seq_len is not None and seq_len > max_position_embeddings else max_position_embeddings\n base = base * (factor * seq_len / max_position_embeddings - (factor - 1)) ** (dim / (dim - 2))\n inv_freq = 1.0 / base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)\n return (inv_freq, attention_factor)", "docstring": "Computes the inverse frequencies with NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla\n\nArgs:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length, used to update the dynamic RoPE at inference time.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n\nReturns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).", "source": "github_repos"} +{"code": "def __init__(self, supported_ops=None, supported_types=None, experimental_select_user_tf_ops=None, experimental_supported_backends=None):\n if supported_ops is None:\n supported_ops = {OpsSet.TFLITE_BUILTINS}\n self.supported_ops = supported_ops\n if supported_types is None:\n supported_types = set()\n self.supported_types = supported_types\n if experimental_select_user_tf_ops is None:\n experimental_select_user_tf_ops = set()\n self.experimental_select_user_tf_ops = experimental_select_user_tf_ops\n self.experimental_supported_backends = experimental_supported_backends\n self._experimental_custom_op_registerers = []\n self._experimental_supported_accumulation_type = None", "docstring": "Specification of target device used to optimize the model.\n\nAttributes:\n supported_ops: Experimental flag, subject to change. Set of `tf.lite.OpsSet`\n options, where each option represents a set of operators supported by the\n target device. (default {tf.lite.OpsSet.TFLITE_BUILTINS}))\n supported_types: Set of `tf.dtypes.DType` data types supported on the target\n device. If initialized, optimization might be driven by the smallest type\n in this set. (default set())\n experimental_select_user_tf_ops: Experimental flag, subject to change. Set\n of user's TensorFlow operators' names that are required in the TensorFlow\n Lite runtime. These ops will be exported as select TensorFlow ops in the\n model (in conjunction with the tf.lite.OpsSet.SELECT_TF_OPS flag). This is\n an advanced feature that should only be used if the client is using TF ops\n that may not be linked in by default with the TF ops that are provided\n when using the SELECT_TF_OPS path. The client is responsible for linking\n these ops into the target runtime.\n experimental_supported_backends: Experimental flag, subject to change. Set\n containing names of supported backends. Currently only \"GPU\" is supported,\n more options will be available later.", "source": "github_repos"} +{"code": "def _parse_logline_timestamp(t):\n date, time = t.split(' ')\n month, day = date.split('-')\n h, m, s = time.split(':')\n s, ms = s.split('.')\n return (month, day, h, m, s, ms)", "docstring": "Parses a logline timestamp into a tuple.\n\nArgs:\n t: Timestamp in logline format.\n\nReturns:\n An iterable of date and time elements in the order of month, day, hour,\n minute, second, microsecond.", "source": "github_repos"} +{"code": "def extended_timestamp(self):\n return self._extended_timestamp", "docstring": "Extended timestamp, possibly with an index suffix.\n\n The index suffix, e.g., \"-1\", is for disambiguating multiple dumps of the\n same tensor with the same timestamp, which can occur if the dumping events\n are spaced by shorter than the temporal resolution of the timestamps.\n\nReturns:\n (`str`) The extended timestamp.", "source": "github_repos"} +{"code": "def parse_readable_size_str(size_str):\n size_str = size_str.strip()\n if size_str.endswith('B'):\n size_str = size_str[:-1]\n if size_str.isdigit():\n return int(size_str)\n elif size_str.endswith('k'):\n return int(float(size_str[:-1]) * 1024)\n elif size_str.endswith('M'):\n return int(float(size_str[:-1]) * 1048576)\n elif size_str.endswith('G'):\n return int(float(size_str[:-1]) * 1073741824)\n else:\n raise ValueError('Failed to parsed human-readable byte size str: \"%s\"' % size_str)", "docstring": "Convert a human-readable str representation to number of bytes.\n\n Only the units \"kB\", \"MB\", \"GB\" are supported. The \"B character at the end\n of the input `str` may be omitted.\n\nArgs:\n size_str: (`str`) A human-readable str representing a number of bytes\n (e.g., \"0\", \"1023\", \"1.1kB\", \"24 MB\", \"23GB\", \"100 G\".\n\nReturns:\n (`int`) The parsed number of bytes.\n\nRaises:\n ValueError: on failure to parse the input `size_str`.", "source": "github_repos"} +{"code": "def __init__(self, element_spec):\n super().__init__()\n self._element_spec = element_spec", "docstring": "Type specification for `tf.experimental.Optional`.\n\n For instance, `tf.OptionalSpec` can be used to define a tf.function that takes\n `tf.experimental.Optional` as an input argument:\n\n >>> @tf.function(input_signature=[tf.OptionalSpec(\n ... tf.TensorSpec(shape=(), dtype=tf.int32, name=None))])\n ... def maybe_square(optional):\n ... if optional.has_value():\n ... x = optional.get_value()\n ... return x * x\n ... return -1\n >>> optional = tf.experimental.Optional.from_value(5)\n >>> print(maybe_square(optional))\n tf.Tensor(25, shape=(), dtype=int32)\n\nAttributes:\n element_spec: A (nested) structure of `TypeSpec` objects that represents the\n type specification of the optional element.", "source": "github_repos"} +{"code": "def __init__(self, config: AriaTextConfig):\n super().__init__(self)\n self.intermediate_size = config.intermediate_size * config.moe_num_shared_experts", "docstring": "Shared Expert MLP for shared experts.\n\n Unlike routed experts, shared experts process all tokens without routing.\n This class reconfigures the intermediate size in comparison to the LlamaMLP.\n\nArgs:\n config (`AriaTextConfig`): Configuration object for the Aria language model.", "source": "github_repos"} +{"code": "def get(self):\n raise NotImplementedError()", "docstring": "Get the current tracking value.\n\nReturns:\n The current tracked value, the type of which depends on the specific\n tracker implementation.", "source": "github_repos"} +{"code": "def _einsum_v1_parse_and_resolve_equation(equation, input_shapes):\n equation = equation.replace(' ', '')\n match = re.match('^([a-zA-Z,.]+)(->[a-zA-Z.]*)?$', equation)\n if not match:\n raise ValueError(f'Indices have incorrect format. Received: {equation}.')\n input_axis_labels = match.group(1).split(',')\n output_axis_labels = match.group(2)[2:] if match.group(2) else None\n if len(input_shapes) != len(input_axis_labels):\n raise ValueError(f'Got {len(input_shapes)} arguments for equation \"{equation}\", expecting {len(input_axis_labels)}.')\n ellipsis_axes = ''\n if '...' in equation:\n unused = ''.join((c for c in string.ascii_letters if c not in ''.join(input_axis_labels)))\n for i, ax in enumerate(input_axis_labels):\n if '...' in ax:\n parts = ax.split('...')\n if len(parts) != 2:\n raise ValueError(f'Unable to resolve ellipsis. Excess number found: {len(parts) - 1} vs 1.')\n if input_shapes[i].ndims is None:\n raise ValueError('Unable to statically infer ellipsis axes. The input shapes has a dynamic dimensionality.')\n n = input_shapes[i].ndims - len(''.join(parts))\n if n < 0:\n raise ValueError('Ellipses lengths do not match.')\n if len(unused) < n:\n raise ValueError('Unable to resolve ellipsis, too many distinct labels.')\n replace_axes = unused[-n:] if n > 0 else ''\n input_axis_labels[i] = input_axis_labels[i].replace('...', replace_axes)\n if len(replace_axes) > len(ellipsis_axes):\n ellipsis_axes = replace_axes\n if any(('.' in ax for ax in input_axis_labels)):\n raise ValueError(f'Period \".\" found outside of ellipsis in input {input_axis_labels}.')\n if output_axis_labels is not None:\n output_axis_labels = output_axis_labels.replace('...', ellipsis_axes)\n if '.' in output_axis_labels:\n raise ValueError(f'Period \".\" found outside of ellipsis in output {output_axis_labels}.')\n if output_axis_labels is None:\n axis_labels = set(''.join(input_axis_labels)) - set(ellipsis_axes)\n indices = ''.join(sorted(axis_labels))\n counts = {ax: 0 for ax in indices}\n for axes_ in input_axis_labels:\n for ax in axes_:\n if ax not in ellipsis_axes:\n counts[ax] += 1\n output_axis_labels = ellipsis_axes + ''.join(sorted((ax for ax in axis_labels if counts[ax] == 1)))\n return (input_axis_labels, output_axis_labels)", "docstring": "Helper for einsum() that splits/resolves inputs & outputs.\n\nArgs:\n equation: Equation string given as argument to einsum().\n input_shapes: List of the shapes of all inputs given to einsum()\n\nReturns:\n input_axis_labels, output_axis_labels where:\n input_axis_labels: List of length len(input_shapes) of strings\n representing the character label for each dimension of each given input,\n resolving any broadcast (...) axes,\n output_axis_labels: A string of character labels for each axes of output\n tensor, filling in missing output subscripts and broadcast axes.\n\nRaises:\n ValueError: If equation is in the uncorrect format, incorrect number of\n inputs given or broadcast axes \"...\" or output axes could not be resolved.", "source": "github_repos"} +{"code": "def train_validation_split(arrays, validation_split):\n\n def _can_split(t):\n tensor_types = _get_tensor_types()\n return isinstance(t, tensor_types) or t is None\n flat_arrays = nest.flatten(arrays)\n unsplitable = [type(t) for t in flat_arrays if not _can_split(t)]\n if unsplitable:\n raise ValueError('`validation_split` is only supported for Tensors or NumPy arrays, found following types in the input: {}'.format(unsplitable))\n if all((t is None for t in flat_arrays)):\n return (arrays, arrays)\n first_non_none = None\n for t in flat_arrays:\n if t is not None:\n first_non_none = t\n break\n batch_dim = int(first_non_none.shape[0])\n split_at = int(math.floor(batch_dim * (1.0 - validation_split)))\n if split_at == 0 or split_at == batch_dim:\n raise ValueError('Training data contains {batch_dim} samples, which is not sufficient to split it into a validation and training set as specified by `validation_split={validation_split}`. Either provide more data, or a different value for the `validation_split` argument.'.format(batch_dim=batch_dim, validation_split=validation_split))\n\n def _split(t, start, end):\n if t is None:\n return t\n return t[start:end]\n train_arrays = nest.map_structure(functools.partial(_split, start=0, end=split_at), arrays)\n val_arrays = nest.map_structure(functools.partial(_split, start=split_at, end=batch_dim), arrays)\n return (train_arrays, val_arrays)", "docstring": "Split arrays into train and validation subsets in deterministic order.\n\n The last part of data will become validation data.\n\nArgs:\n arrays: Tensors to split. Allowed inputs are arbitrarily nested structures\n of Tensors and NumPy arrays.\n validation_split: Float between 0 and 1. The proportion of the dataset to\n include in the validation split. The rest of the dataset will be included\n in the training split.\n\nReturns:\n `(train_arrays, validation_arrays)`", "source": "github_repos"} +{"code": "def __init__(self, config: MaskFormerConfig):\n super().__init__()\n if getattr(config, 'backbone_config') is not None and config.backbone_config.model_type == 'swin':\n backbone_config = config.backbone_config\n backbone_config = MaskFormerSwinConfig.from_dict(backbone_config.to_dict())\n backbone_config.out_features = ['stage1', 'stage2', 'stage3', 'stage4']\n config.backbone_config = backbone_config\n self.encoder = load_backbone(config)\n feature_channels = self.encoder.channels\n self.decoder = MaskFormerPixelDecoder(in_features=feature_channels[-1], feature_size=config.fpn_feature_size, mask_feature_size=config.mask_feature_size, lateral_widths=feature_channels[:-1])", "docstring": "Pixel Level Module proposed in [Per-Pixel Classification is Not All You Need for Semantic\n Segmentation](https://huggingface.co/papers/2107.06278). It runs the input image through a backbone and a pixel\n decoder, generating an image feature map and pixel embeddings.\n\nArgs:\n config ([`MaskFormerConfig`]):\n The configuration used to instantiate this model.", "source": "github_repos"} +{"code": "def correct_tables(self, generation: str) -> str:\n for l in generation.split('\\n'):\n if l.count('\\\\begin{tabular}') > 15 or l.count('\\\\multicolumn') > 60 or l.count('&') > 400:\n generation = generation.replace(l, '')\n generation = generation.replace('\\\\begin{table} \\\\begin{tabular}', '\\\\begin{table}\\n\\\\begin{tabular}')\n generation = generation.replace('\\\\end{tabular} \\\\end{table}', '\\\\end{tabular}\\n\\\\end{table}')\n generation = generation.replace('\\\\end{table} Tab', '\\\\end{table}\\nTab')\n generation = re.sub('(^.+)\\\\\\\\begin{tab', '\\\\1\\\\n\\\\\\\\begin{tab', generation, flags=re.M)\n generation = generation.replace('\\\\begin{tabular}{l l} & \\\\\\\\ \\\\end{tabular}', '')\n generation = generation.replace('\\\\begin{tabular}{}\\n\\n\\\\end{tabular}', '')\n return generation", "docstring": "Takes a generated string and fixes tables/tabulars to make them match the markdown format needed.\n\nArgs:\n generation (str): The generated text to be postprocessed.\n\nReturns:\n str: The postprocessed text.\n\nExample:\n ```python\n correct_tables(\"\\begin{table} \\begin{tabular}{l l} & \\ \\end{tabular} \\end{table}\")\n \"\\begin{table}\n \\begin{tabular}{l l} & \\ \\end{tabular}\n \\end{table}\"\n ```", "source": "github_repos"} +{"code": "def __call__(self, raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], padding: Union[bool, str, PaddingStrategy]=False, max_length: Optional[int]=None, pad_to_multiple_of: Optional[int]=None, padding_side: Optional[str]=None, return_tensors: Optional[Union[str, TensorType]]=None, verbose: bool=True, **kwargs) -> BatchEncoding:\n is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1\n if is_batched_numpy and len(raw_speech.shape) > 2:\n raise ValueError(f'Only mono-channel audio is supported for input to {self}')\n is_batched = is_batched_numpy or (isinstance(raw_speech, (list, tuple)) and isinstance(raw_speech[0], (np.ndarray, tuple, list)))\n if is_batched and (not isinstance(raw_speech[0], np.ndarray)):\n raw_speech = [np.asarray(speech) for speech in raw_speech]\n elif not is_batched and (not isinstance(raw_speech, np.ndarray)):\n raw_speech = np.asarray(raw_speech)\n if not is_batched:\n raw_speech = [raw_speech]\n if self.do_normalize:\n raw_speech = [(x - np.mean(x)) / np.sqrt(np.var(x) + 1e-05) for x in raw_speech]\n encoded_inputs = BatchEncoding({'input_values': raw_speech})\n padded_inputs = self.pad(encoded_inputs, padding=padding, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, padding_side=padding_side, return_attention_mask=self.return_attention_mask, return_tensors=return_tensors, verbose=verbose)\n return padded_inputs", "docstring": "Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of\n sequences.\n\nArgs:\n raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):\n The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float\n values, a list of numpy array or a list of list of float values. Must be mono channel audio, not\n stereo, i.e. single float per timestep.\n\n padding_side (`str`, *optional*):\n The side on which the model should have padding applied. Should be selected between ['right', 'left'].\n Default value is picked from the class attribute of the same name.", "source": "github_repos"} +{"code": "def _parse_args():\n parser = argparse.ArgumentParser(description='preprocess_coco_minival: Preprocess COCO minival dataset')\n parser.add_argument('--images_folder', type=str, help='Full path of the validation images folder.', required=True)\n parser.add_argument('--instances_file', type=str, help='Full path of the input JSON file, like instances_val20xx.json.', required=True)\n parser.add_argument('--allowlist_file', type=str, help='File with COCO image ids to preprocess, one on each line.', required=False)\n parser.add_argument('--num_images', type=int, help='Number of allowlisted images to preprocess into the output folder.', required=False)\n parser.add_argument('--output_folder', type=str, help='Full path to output images & text proto files into.', required=True)\n return parser.parse_known_args(args=sys.argv[1:])[0]", "docstring": "Creates a parser that parse the command line arguments.\n\nReturns:\n A namespace parsed from command line arguments.", "source": "github_repos"} +{"code": "def _section_from_possible_title(possible_title):\n for section in SECTION_TITLES:\n if _matches_section(possible_title, section):\n return section\n return None", "docstring": "Returns a section matched by the possible title, or None if none match.\n\nArgs:\n possible_title: A string that may be the title of a new section.\n\nReturns:\n A Section type if one matches, or None if no section type matches.", "source": "github_repos"} +{"code": "def __init__(self, *, separator_stride_cls: Type[message.Message], code_cls: Type[message.Message], default_timezone: str) -> None:\n self.separator_stride_cls = separator_stride_cls\n self.code_cls = code_cls\n self.default_timezone = default_timezone", "docstring": "Creates a new instance of primitive_wrappers.Context.\n\nArgs:\n separator_stride_cls: The Base64BinarySeparatorStride type to use when\n parsing/printing Base64Binary FHIR primitives.\n code_cls: The Code type to use when parsing/printing profiled-Code\n primitives.\n default_timezone: The default timezone to use for date/time-like primitive\n parsing/printing.", "source": "github_repos"} +{"code": "def diff_contains_doc_examples(repo: Repo, branching_point: str, filename: str) -> bool:\n folder = Path(repo.working_dir)\n with checkout_commit(repo, branching_point):\n with open(folder / filename, 'r', encoding='utf-8') as f:\n old_content = f.read()\n with open(folder / filename, 'r', encoding='utf-8') as f:\n new_content = f.read()\n old_content_clean = keep_doc_examples_only(old_content)\n new_content_clean = keep_doc_examples_only(new_content)\n return old_content_clean != new_content_clean", "docstring": "Check if the diff is only in code examples of the doc in a filename.\n\nArgs:\n repo (`git.Repo`): A git repository (for instance the Transformers repo).\n branching_point (`str`): The commit reference of where to compare for the diff.\n filename (`str`): The filename where we want to know if the diff is only in codes examples.\n\nReturns:\n `bool`: Whether the diff is only in code examples of the doc or not.", "source": "github_repos"} +{"code": "def write_object_proto_for_resource_variable(resource_variable, proto, options, enforce_naming=True):\n proto.variable.SetInParent()\n if enforce_naming and (not resource_variable.name.endswith(':0')):\n raise ValueError(f\"Cowardly refusing to save variable {resource_variable.name} because of unexpected suffix in the name (expected ':0')which won't be restored.\")\n proto.variable.name = tensor_module.get_op_name(resource_variable.name)\n proto.variable.trainable = resource_variable.trainable\n proto.variable.dtype = resource_variable.dtype.as_datatype_enum\n proto.variable.synchronization = resource_variable.synchronization.value\n proto.variable.aggregation = resource_variable.aggregation.value\n proto.variable.shape.CopyFrom(resource_variable.shape.as_proto())\n if options.experimental_variable_policy._save_variable_devices():\n if hasattr(resource_variable, 'device'):\n proto.variable.device = resource_variable.device", "docstring": "Writes additional information of the variable into the SavedObject proto.\n\n This allows users to define a `hook` to provide extra information of the\n variable to the SavedObject.\n\n For example, DistributedVariable class would fill in components in the\n distributed context.\n\nArgs:\n resource_variable: A `ResourceVariable` or `DistributedValue` that has the\n information to be saved into the proto.\n proto: `SavedObject` proto to update.\n options: A `SaveOption` instance that configures save behavior.\n enforce_naming: A bool determining whether to check that names end in the\n expected string ':0'", "source": "github_repos"} +{"code": "def get(logdir):\n with FileWriterCache._lock:\n if logdir not in FileWriterCache._cache:\n FileWriterCache._cache[logdir] = FileWriter(logdir, graph=ops.get_default_graph())\n return FileWriterCache._cache[logdir]", "docstring": "Returns the FileWriter for the specified directory.\n\nArgs:\n logdir: str, name of the directory.\n\nReturns:\n A `FileWriter`.", "source": "github_repos"} +{"code": "def get_decomposed_rel_pos(self, query: torch.Tensor, rel_pos_h: torch.Tensor, rel_pos_w: torch.Tensor, q_size: Tuple[int, int], k_size: Tuple[int, int]) -> torch.Tensor:\n query_height, query_width = q_size\n key_height, key_width = k_size\n relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)\n relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)\n batch_size, _, dim = query.shape\n reshaped_query = query.reshape(batch_size, query_height, query_width, dim)\n rel_h = torch.einsum('bhwc,hkc->bhwk', reshaped_query, relative_position_height)\n rel_w = torch.einsum('bhwc,wkc->bhwk', reshaped_query, relative_position_width)\n decomposed_rel_pos = rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]\n return decomposed_rel_pos", "docstring": "Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.\n https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py\n\nArgs:\n query (`torch.Tensor`):\n query q in the attention layer with shape (batch_size, query_height * query_width, channel).\n rel_pos_h (`torch.Tensor`):\n relative position embeddings (Lh, channel) for height axis.\n rel_pos_w (`torch.Tensor`):\n relative position embeddings (Lw, channel) for width axis.\n q_size (tuple):\n spatial sequence size of query q with (query_height, query_width).\n k_size (tuple):\n spatial sequence size of key k with (key_height, key_width).\n\nReturns:\n decomposed_rel_pos (`torch.Tensor`):\n decomposed relative position embeddings.", "source": "github_repos"} +{"code": "def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs):\n\n def _should_dropout(p):\n return not isinstance(p, float) or p < 1\n if _should_dropout(self._input_keep_prob):\n inputs = self._dropout(inputs, 'input', self._recurrent_input_noise, self._input_keep_prob)\n output, new_state = cell_call_fn(inputs, state, **kwargs)\n if _should_dropout(self._state_keep_prob):\n shallow_filtered_substructure = nest.get_traverse_shallow_structure(self._dropout_state_filter, new_state)\n new_state = self._dropout(new_state, 'state', self._recurrent_state_noise, self._state_keep_prob, shallow_filtered_substructure)\n if _should_dropout(self._output_keep_prob):\n output = self._dropout(output, 'output', self._recurrent_output_noise, self._output_keep_prob)\n return (output, new_state)", "docstring": "Runs the wrapped cell and applies dropout.\n\nArgs:\n inputs: A tensor with wrapped cell's input.\n state: A tensor or tuple of tensors with wrapped cell's state.\n cell_call_fn: Wrapped cell's method to use for step computation (cell's\n `__call__` or 'call' method).\n **kwargs: Additional arguments.\n\nReturns:\n A pair containing:\n\n - Output: A tensor with cell's output.\n - New state: A tensor or tuple of tensors with new wrapped cell's state.", "source": "github_repos"} +{"code": "def decode(self, music_tokens, start_level=0, end_level=None, bs_chunks=1) -> torch.Tensor:\n token_chunks = [torch.chunk(token, bs_chunks, dim=0) for token in music_tokens]\n dequantised_states = []\n for i in range(bs_chunks):\n music_tokens_i = [chunks[i] for chunks in token_chunks]\n dequantised_state = self._decode(music_tokens_i, start_level=start_level, end_level=end_level)\n dequantised_states.append(dequantised_state)\n return torch.cat(dequantised_states, dim=0)", "docstring": "Transforms the input `music_tokens` to their `raw_audio` representation.\n\nArgs:\n music_tokens (`torch.LongTensor`):\n Tensor of music tokens which will be decoded to raw audio by using the codebook. Each music token\n should be an index to a corresponding `code` vector in the codebook.\n start_level (`int`, *optional*):\n Level at which the decoding process will start. Default to 0.\n end_level (`int`, *optional*):\n Level at which the decoding process will start. Default to None.\n bs_chunks (int, *optional*):\n Number of chunks to process at the same time.", "source": "github_repos"} +{"code": "def _print_tensor(tensor_name, num_elements, tensor, output_tensor):\n if self._parameters.is_brief_mode():\n if tensor_name not in tensor_trace_order.tensorname_to_cache_idx:\n raise ValueError('Tensor %s with name %s is not in the tensorname_to_cache_idx' % (tensor, tensor_name))\n msg = '%d' % tensor_trace_order.tensorname_to_cache_idx[tensor_name]\n else:\n msg = '\"%s\"' % tensor_name\n if self._parameters.trace_dir:\n output_path = os.path.join(self._parameters.trace_dir, _TRACE_FILE_NAME + self._get_outfile_suffix())\n output_stream = _OUTPUT_STREAM_ESCAPE + output_path\n else:\n output_stream = sys.stderr\n return logging_ops.print_v2(msg, array_ops.shape(output_tensor), '@', self._replica_id, '\\n', output_tensor, '\\n', summarize=num_elements, output_stream=output_stream)", "docstring": "Prints a tensor value to a file.\n\nArgs:\n tensor_name: name of the tensor being traced.\n num_elements: number of elements to print (-1 means print all).\n tensor: the tensor needs to be returned.\n output_tensor: the tensor needs to be printed.\n\nReturns:\n The same tensor passed via the \"tensor\" argument.\n\nRaises:\n ValueError: If tensor_name is not already in\n tensor_trace_order.tensorname_to_cache_idx.", "source": "github_repos"} +{"code": "def user_set_string(namespace, name, metric, ptransform=None):\n labels = create_labels(ptransform=ptransform, namespace=namespace, name=name)\n if isinstance(metric, StringSetData):\n metric = metric.string_set\n if isinstance(metric, set):\n metric = list(metric)\n if isinstance(metric, list):\n metric = coders.IterableCoder(coders.StrUtf8Coder()).encode(metric)\n return create_monitoring_info(USER_STRING_SET_URN, STRING_SET_TYPE, metric, labels)", "docstring": "Return the string set monitoring info for the URN, metric and labels.\n\nArgs:\n namespace: User-defined namespace of StringSet.\n name: Name of StringSet.\n metric: The StringSetData representing the metrics.\n ptransform: The ptransform id used as a label.", "source": "github_repos"} +{"code": "def weighted_moving_average(value, decay, weight, truediv=True, collections=None, name=None):\n if collections is None:\n collections = [ops.GraphKeys.GLOBAL_VARIABLES]\n with variable_scope.variable_scope(name, 'WeightedMovingAvg', [value, weight, decay]) as scope:\n value_x_weight_var = variable_scope.get_variable('value_x_weight', shape=value.get_shape(), dtype=value.dtype, initializer=init_ops.zeros_initializer(), trainable=False, collections=collections)\n weight_var = variable_scope.get_variable('weight', shape=weight.get_shape(), dtype=weight.dtype, initializer=init_ops.zeros_initializer(), trainable=False, collections=collections)\n numerator = assign_moving_average(value_x_weight_var, value * weight, decay, zero_debias=False)\n denominator = assign_moving_average(weight_var, weight, decay, zero_debias=False)\n if truediv:\n return math_ops.truediv(numerator, denominator, name=scope.name)\n else:\n return math_ops.divide(numerator, denominator, name=scope.name)", "docstring": "Compute the weighted moving average of `value`.\n\n Conceptually, the weighted moving average is:\n `moving_average(value * weight) / moving_average(weight)`,\n where a moving average updates by the rule\n `new_value = decay * old_value + (1 - decay) * update`\n Internally, this Op keeps moving average variables of both `value * weight`\n and `weight`.\n\nArgs:\n value: A numeric `Tensor`.\n decay: A float `Tensor` or float value. The moving average decay.\n weight: `Tensor` that keeps the current value of a weight. Shape should be\n able to multiply `value`.\n truediv: Boolean, if `True`, dividing by `moving_average(weight)` is\n floating point division. If `False`, use division implied by dtypes.\n collections: List of graph collections keys to add the internal variables\n `value * weight` and `weight` to. Defaults to\n `[GraphKeys.GLOBAL_VARIABLES]`.\n name: Optional name of the returned operation. Defaults to\n \"WeightedMovingAvg\".\n\nReturns:\n An Operation that updates and returns the weighted moving average.", "source": "github_repos"} +{"code": "def _get_numeric_relations(self, question, column_ids, row_ids, table):\n numeric_relations = [0] * len(column_ids)\n cell_indices_to_relations = collections.defaultdict(set)\n if question is not None and table is not None:\n for numeric_value_span in question.numeric_spans:\n for value in numeric_value_span.values:\n for column_index in range(len(table.columns)):\n table_numeric_values = self._get_column_values(table, column_index)\n sort_key_fn = self._get_numeric_sort_key_fn(table_numeric_values, value)\n if sort_key_fn is None:\n continue\n for row_index, cell_value in table_numeric_values.items():\n relation = get_numeric_relation(value, cell_value, sort_key_fn)\n if relation is not None:\n cell_indices_to_relations[column_index, row_index].add(relation)\n for (column_index, row_index), relations in cell_indices_to_relations.items():\n relation_set_index = 0\n for relation in relations:\n assert relation.value >= Relation.EQ.value\n relation_set_index += 2 ** (relation.value - Relation.EQ.value)\n for cell_token_index in self._get_cell_token_indexes(column_ids, row_ids, column_index, row_index):\n numeric_relations[cell_token_index] = relation_set_index\n return numeric_relations", "docstring": "Returns numeric relations embeddings\n\nArgs:\n question: Question object.\n column_ids: Maps word piece position to column id.\n row_ids: Maps word piece position to row id.\n table: The table containing the numeric cell values.", "source": "github_repos"} +{"code": "def cosine_similarity(y_true, y_pred, axis=-1):\n y_pred = ops.convert_to_tensor(y_pred)\n y_true = ops.convert_to_tensor(y_true, dtype=y_pred.dtype)\n y_true, y_pred = squeeze_or_expand_to_same_rank(y_true, y_pred)\n y_pred = normalize(y_pred, axis=axis)\n y_true = normalize(y_true, axis=axis)\n return -ops.sum(y_true * y_pred, axis=axis)", "docstring": "Computes the cosine similarity between labels and predictions.\n\n Formula:\n ```python\n loss = -sum(l2_norm(y_true) * l2_norm(y_pred))\n ```\n\n Note that it is a number between -1 and 1. When it is a negative number\n between -1 and 0, 0 indicates orthogonality and values closer to -1\n indicate greater similarity. This makes it usable as a loss function in a\n setting where you try to maximize the proximity between predictions and\n targets. If either `y_true` or `y_pred` is a zero vector, cosine\n similarity will be 0 regardless of the proximity between predictions\n and targets.\n\nArgs:\n y_true: Tensor of true targets.\n y_pred: Tensor of predicted targets.\n axis: Axis along which to determine similarity. Defaults to `-1`.\n\nReturns:\n Cosine similarity tensor.\n\nExample:\n >>> y_true = [[0., 1.], [1., 1.], [1., 1.]]\n >>> y_pred = [[1., 0.], [1., 1.], [-1., -1.]]\n >>> loss = keras.losses.cosine_similarity(y_true, y_pred, axis=-1)\n [-0., -0.99999994, 0.99999994]", "source": "github_repos"} +{"code": "def convert_to_date_tensor(date_inputs):\n if isinstance(date_inputs, DateTensor):\n return date_inputs\n if hasattr(date_inputs, 'year'):\n return from_datetimes(date_inputs)\n if isinstance(date_inputs, np.ndarray):\n date_inputs = date_inputs.astype('datetime64[D]')\n return from_np_datetimes(date_inputs)\n if tf.is_tensor(date_inputs):\n return from_ordinals(date_inputs)\n if isinstance(date_inputs, collections.abc.Sequence):\n if not date_inputs:\n return from_ordinals([])\n test_element = date_inputs[0]\n if hasattr(test_element, 'year'):\n return from_datetimes(date_inputs)\n if isinstance(test_element, collections.abc.Sequence):\n return from_tuples(date_inputs)\n if len(date_inputs) == 3:\n return from_year_month_day(date_inputs[0], date_inputs[1], date_inputs[2])\n try:\n as_ordinals = tf.convert_to_tensor(date_inputs, dtype=tf.int32)\n return from_ordinals(as_ordinals)\n except ValueError as e:\n raise ValueError('Failed to convert inputs to DateTensor. Unrecognized format. Error: ' + e)", "docstring": "Converts supplied data to a `DateTensor` if possible.\n\nArgs:\n date_inputs: One of the supported types that can be converted to a\n DateTensor. The following input formats are supported. 1. Sequence of\n `datetime.datetime`, `datetime.date`, or any other structure with data\n attributes called 'year', 'month' and 'day'. 2. A numpy array of\n `datetime64` type. 3. Sequence of (year, month, day) Tuples. Months are\n 1-based (with January as 1) and constants.Months enum may be used instead\n of ints. Days are also 1-based. 4. A tuple of three int32 `Tensor`s\n containing year, month and date as positive integers in that order. 5. A\n single int32 `Tensor` containing ordinals (i.e. number of days since 31\n Dec 0 with 1 being 1 Jan 1.)\n\nReturns:\n A `DateTensor` object representing the supplied dates.\n\nRaises:\n ValueError: If conversion fails for any reason.", "source": "github_repos"} +{"code": "def query_origin_stack(self):\n ret = []\n for stack, id_to_string in zip(self._origin_stacks, self._origin_id_to_strings):\n ret.append(self._code_def_to_traceback(stack, id_to_string))\n return ret", "docstring": "Query the stack of the origin of the execution call.\n\nReturns:\n A `list` of all tracebacks. Each item corresponds to an execution call,\n i.e., a `SendTracebacks` request. Each item is a `list` of 3-tuples:\n (filename, lineno, function_name).", "source": "github_repos"} +{"code": "def window_partition(self, hidden_states: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:\n batch_size, height, width, channel = hidden_states.shape\n pad_h = (window_size - height % window_size) % window_size\n pad_w = (window_size - width % window_size) % window_size\n hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))\n pad_height, pad_width = (height + pad_h, width + pad_w)\n hidden_states = hidden_states.reshape(batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel)\n windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(-1, window_size, window_size, channel)\n return (windows, (pad_height, pad_width))", "docstring": "Args:\n Partition into non-overlapping windows with padding if needed.\n hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window\n size.\n\nReturns:\n windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].\n (pad_height, pad_width): padded height and width before partition", "source": "github_repos"} +{"code": "def export_run_metadata(self):\n if not self._context_handle:\n return None\n with c_api_util.tf_buffer() as buffer_:\n pywrap_tfe.TFE_ContextExportRunMetadata(self._context_handle, buffer_)\n proto_data = pywrap_tf_session.TF_GetBuffer(buffer_)\n run_metadata = config_pb2.RunMetadata()\n run_metadata.ParseFromString(compat.as_bytes(proto_data))\n return run_metadata", "docstring": "Returns a RunMetadata proto with accumulated information.\n\n The returned protocol buffer contains information since the most recent call\n to either enable_run_metadata or export_run_metadata.\n\nReturns:\n A RunMetadata protocol buffer. Or None if not enabled.", "source": "github_repos"} +{"code": "def add_loss(loss, loss_collection=ops.GraphKeys.LOSSES):\n if loss_collection and (not context.executing_eagerly()):\n ops.add_to_collection(loss_collection, loss)", "docstring": "Adds a externally defined loss to the collection of losses.\n\nArgs:\n loss: A loss `Tensor`.\n loss_collection: Optional collection to add the loss to.", "source": "github_repos"} +{"code": "def last_updated(self, path):\n try:\n return self._blobstorageIO().last_updated(path)\n except Exception as e:\n raise BeamIOError('Last updated operation failed', {path: e})", "docstring": "Get UNIX Epoch time in seconds on the FileSystem.\n\nArgs:\n path: string path of file.\n\n Returns: float UNIX Epoch time\n\nRaises:\n ``BeamIOError``: if path doesn't exist.", "source": "github_repos"} +{"code": "def sequence_categorical_column_with_hash_bucket(key, hash_bucket_size, dtype=dtypes.string):\n return fc.SequenceCategoricalColumn(fc.categorical_column_with_hash_bucket(key=key, hash_bucket_size=hash_bucket_size, dtype=dtype))", "docstring": "A sequence of categorical terms where ids are set by hashing.\n\n Pass this to `embedding_column` or `indicator_column` to convert sequence\n categorical data into dense representation for input to sequence NN, such as\n RNN.\n\nExample:\n ```python\n tokens = sequence_categorical_column_with_hash_bucket(\n 'tokens', hash_bucket_size=1000)\n tokens_embedding = embedding_column(tokens, dimension=10)\n columns = [tokens_embedding]\n\n features = tf.io.parse_example(..., features=make_parse_example_spec(columns))\n sequence_feature_layer = SequenceFeatures(columns)\n sequence_input, sequence_length = sequence_feature_layer(features)\n sequence_length_mask = tf.sequence_mask(sequence_length)\n\n rnn_cell = tf.keras.layers.SimpleRNNCell(hidden_size)\n rnn_layer = tf.keras.layers.RNN(rnn_cell)\n outputs, state = rnn_layer(sequence_input, mask=sequence_length_mask)\n ```\n\nArgs:\n key: A unique string identifying the input feature.\n hash_bucket_size: An int > 1. The number of buckets.\n dtype: The type of features. Only string and integer types are supported.\n\nReturns:\n A `SequenceCategoricalColumn`.\n\nRaises:\n ValueError: `hash_bucket_size` is not greater than 1.\n ValueError: `dtype` is neither string nor integer.", "source": "github_repos"} +{"code": "def apply_grad(self, grad, local_step=0, name=None):\n grad = ops.convert_to_tensor(grad, self._dtype)\n grad.get_shape().assert_is_compatible_with(self._shape)\n local_step = math_ops.cast(ops.convert_to_tensor(local_step), _dtypes.int64)\n return gen_data_flow_ops.resource_accumulator_apply_gradient(self._accumulator_ref, local_step=local_step, gradient=grad, name=name)", "docstring": "Attempts to apply a gradient to the accumulator.\n\n The attempt is silently dropped if the gradient is stale, i.e., local_step\n is less than the accumulator's global time step.\n\nArgs:\n grad: The gradient tensor to be applied.\n local_step: Time step at which the gradient was computed.\n name: Optional name for the operation.\n\nReturns:\n The operation that (conditionally) applies a gradient to the accumulator.\n\nRaises:\n ValueError: If grad is of the wrong shape", "source": "github_repos"} +{"code": "def _expand_dims_impl(st, axis, name=None):\n axis = array_ops.get_positive_axis(axis, st.rank + 1, axis_name='axis', ndims_name='rank(st)')\n with ops.name_scope(name, 'ExpandDims', [st, axis]):\n new_fields = {k: array_ops.expand_dims(v, axis) for k, v in st._fields.items()}\n new_shape = st.shape[:axis] + (1,) + st.shape[axis:]\n new_row_partitions = _expand_st_row_partitions(st, axis)\n new_nrows = st.nrows() if axis > 0 else 1\n return StructuredTensor.from_fields(new_fields, shape=new_shape, row_partitions=new_row_partitions, nrows=new_nrows)", "docstring": "Creates a StructuredTensor with a length 1 axis inserted at index `axis`.\n\n This is an implementation of tf.expand_dims for StructuredTensor. Note\n that the `axis` must be less than or equal to rank.\n\n >>> st = StructuredTensor.from_pyval([[{\"x\": 1}, {\"x\": 2}], [{\"x\": 3}]])\n >>> tf.expand_dims(st, 0).to_pyval()\n [[[{'x': 1}, {'x': 2}], [{'x': 3}]]]\n >>> tf.expand_dims(st, 1).to_pyval()\n [[[{'x': 1}, {'x': 2}]], [[{'x': 3}]]]\n >>> tf.expand_dims(st, 2).to_pyval()\n [[[{'x': 1}], [{'x': 2}]], [[{'x': 3}]]]\n >>> tf.expand_dims(st, -1).to_pyval() # -1 is the same as 2\n [[[{'x': 1}], [{'x': 2}]], [[{'x': 3}]]]\n\nArgs:\n st: the original StructuredTensor.\n axis: the axis to insert the dimension: `-(rank + 1) <= axis <= rank`\n name: the name of the op.\n\nReturns:\n a new structured tensor with larger rank.\n\nRaises:\n an error if `axis < -(rank + 1)` or `rank < axis`.", "source": "github_repos"} +{"code": "def create_attention_mask_from_sequences(self, query_ids: List[int], table_values: List[TableValue]) -> List[int]:\n return [1] * (1 + len(query_ids) + 1 + len(table_values))", "docstring": "Creates the attention mask according to the query token IDs and a list of table values.\n\nArgs:\n query_ids (`List[int]`): list of token IDs corresponding to the ID.\n table_values (`List[TableValue]`): lift of table values, which are named tuples containing the\n token value, the column ID and the row ID of said token.\n\nReturns:\n `List[int]`: List of ints containing the attention mask values.", "source": "github_repos"} +{"code": "def check_attribute_being_used(config_class, attributes, default_value, source_strings):\n attribute_used = False\n for attribute in attributes:\n for modeling_source in source_strings:\n if f'config.{attribute}' in modeling_source or f'getattr(config, \"{attribute}\"' in modeling_source or f'getattr(self.config, \"{attribute}\"' in modeling_source or ('TextConfig' in config_class.__name__ and f'config.get_text_config().{attribute}' in modeling_source):\n attribute_used = True\n elif re.search(f'getattr[ \\\\t\\\\v\\\\n\\\\r\\\\f]*\\\\([ \\\\t\\\\v\\\\n\\\\r\\\\f]*(self\\\\.)?config,[ \\\\t\\\\v\\\\n\\\\r\\\\f]*\"{attribute}\"', modeling_source) is not None:\n attribute_used = True\n if attribute_used:\n break\n if attribute_used:\n break\n attributes_to_allow = ['initializer_range', 'bos_index', 'eos_index', 'pad_index', 'unk_index', 'mask_index', 'image_token_id', 'video_token_id', 'image_seq_length', 'video_seq_length', 'image_size', 'text_config', 'use_cache', 'out_features', 'out_indices', 'sampling_rate', 'use_pretrained_backbone', 'backbone', 'backbone_config', 'use_timm_backbone', 'backbone_kwargs', 'rope_theta', 'partial_rotary_factor', 'pretraining_tp', 'boi_token_id', 'eoi_token_id']\n attributes_used_in_generation = ['encoder_no_repeat_ngram_size']\n case_allowed = True\n if not attribute_used:\n case_allowed = False\n for attribute in attributes:\n if attribute in ['is_encoder_decoder'] and default_value is True:\n case_allowed = True\n elif attribute in ['tie_word_embeddings'] and default_value is False:\n case_allowed = True\n elif attribute in attributes_to_allow + attributes_used_in_generation:\n case_allowed = True\n elif attribute.endswith('_token_id'):\n case_allowed = True\n if not case_allowed:\n allowed_cases = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__, [])\n case_allowed = allowed_cases is True or attribute in allowed_cases\n return attribute_used or case_allowed", "docstring": "Check if any name in `attributes` is used in one of the strings in `source_strings`\n\nArgs:\n config_class (`type`):\n The configuration class for which the arguments in its `__init__` will be checked.\n attributes (`List[str]`):\n The name of an argument (or attribute) and its variant names if any.\n default_value (`Any`):\n A default value for the attribute in `attributes` assigned in the `__init__` of `config_class`.\n source_strings (`List[str]`):\n The python source code strings in the same modeling directory where `config_class` is defined. The file\n containing the definition of `config_class` should be excluded.", "source": "github_repos"} +{"code": "def numpy(self) -> npt.ArrayLike:\n maybe_arr = self._numpy()\n return maybe_arr.copy() if isinstance(maybe_arr, np.ndarray) else maybe_arr", "docstring": "Copy of the contents of this Tensor into a NumPy array or scalar.\n\n Unlike NumPy arrays, Tensors are immutable, so this method has to copy\n the contents to ensure safety. Use `memoryview` to get a readonly\n view of the contents without doing a copy:\n\n >>> t = tf.constant([42])\n >>> np.asarray(memoryview(t))\n array([42], dtype=int32)\n\n Note that `memoryview` is only zero-copy for Tensors on CPU. If a Tensor\n is on GPU, it will have to be transferred to CPU first in order for\n `memoryview` to work.\n\nReturns:\n A NumPy array of the same shape and dtype or a NumPy scalar, if this\n Tensor has rank 0.\n\nRaises:\n ValueError: If the dtype of this Tensor does not have a compatible\n NumPy dtype.", "source": "github_repos"} +{"code": "def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str]=None) -> Tuple[str]:\n if not os.path.isdir(save_directory):\n logger.error(f'Vocabulary path ({save_directory}) should be a directory')\n return\n vocab_file = os.path.join(save_directory, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])\n with open(vocab_file, 'w', encoding='utf-8') as f:\n f.write(json.dumps(self.get_vocab(), ensure_ascii=False))\n return (vocab_file,)", "docstring": "Save the vocabulary and special tokens file to a directory.\n\nArgs:\n save_directory (`str`):\n The directory in which to save the vocabulary.\n\nReturns:\n `Tuple(str)`: Paths to the files saved.", "source": "github_repos"} +{"code": "def _is_sequence_right_padded(mask):\n max_seq_length = mask.shape[1]\n count_of_true = torch.sum(mask, dim=1)\n batch_size = mask.shape[0]\n indices = torch.arange(max_seq_length, device=mask.device).repeat(batch_size, 1)\n right_padded_mask = indices < count_of_true.unsqueeze(1)\n return torch.all(mask == right_padded_mask)", "docstring": "Check the mask tensor and see if it right padded.\n\n cuDNN uses the sequence length param to skip the tailing\n timestep. If the data is left padded, or not a strict right padding (has\n masked value in the middle of the sequence), then cuDNN won't work\n properly in those cases.\n\n Left padded data: [[False, False, True, True, True]].\n Right padded data: [[True, True, True, False, False]].\n Mixture of mask/unmasked data: [[True, False, True, False, False]].\n\n Note that for the mixed data example above, the actually data RNN should see\n are those 2 Trues (index 0 and 2), the index 1 False should be ignored and\n not pollute the internal states.\n\nArgs:\n mask: the Boolean tensor with shape [batch, timestep]\n\nReturns:\n boolean scalar tensor, whether the mask is strictly right padded.", "source": "github_repos"} +{"code": "def with_forward_compatibility_horizons(*horizons: Optional[tuple[int, int, int]]) -> Callable[[Callable[..., Any]], Callable[..., None]]:\n if not horizons:\n raise ValueError('Expected at least one horizon.')\n for horizon in horizons:\n if not (horizon is None or (len(horizon) == 3 and all((isinstance(x, int) for x in horizon)))):\n raise ValueError('Bad horizon value: %r' % horizon)\n\n def decorator(f: Callable[..., Any]) -> Callable[..., None]:\n if tf_inspect.isclass(f):\n raise ValueError('`with_forward_compatibility_horizons` only supports test methods.')\n\n def decorated(*args, **kwargs):\n for horizon in horizons:\n if horizon is None:\n f(*args, **kwargs)\n else:\n year, month, day = horizon\n with forward_compatibility_horizon(year, month, day):\n f(*args, **kwargs)\n return tf_decorator.make_decorator(f, decorated)\n return decorator", "docstring": "Executes the decorated test with the specified forward-compat horizons.\n\nArgs:\n *horizons: A list of (year, month, day) tuples. If the list includes\n `None`, then the test will also be run with no forward-compatibility\n horizon set.\n\nReturns:\n A decorator that will execute the test with the specified horizons.", "source": "github_repos"} +{"code": "def _supervised_signature_def(method_name, inputs, loss=None, predictions=None, metrics=None):\n if inputs is None or not inputs:\n raise ValueError('{} inputs cannot be None or empty.'.format(method_name))\n signature_inputs = {key: utils.build_tensor_info(tensor) for key, tensor in inputs.items()}\n signature_outputs = {}\n for output_set in (loss, predictions, metrics):\n if output_set is not None:\n sig_out = {key: utils.build_tensor_info(tensor) for key, tensor in output_set.items()}\n signature_outputs.update(sig_out)\n signature_def = signature_def_utils.build_signature_def(signature_inputs, signature_outputs, method_name)\n return signature_def", "docstring": "Creates a signature for training and eval data.\n\n This function produces signatures that describe the inputs and outputs\n of a supervised process, such as training or evaluation, that\n results in loss, metrics, and the like. Note that this function only requires\n inputs to be not None.\n\nArgs:\n method_name: Method name of the SignatureDef as a string.\n inputs: dict of string to `Tensor`.\n loss: dict of string to `Tensor` representing computed loss.\n predictions: dict of string to `Tensor` representing the output predictions.\n metrics: dict of string to `Tensor` representing metric ops.\n\nReturns:\n A train- or eval-flavored signature_def.\n\nRaises:\n ValueError: If inputs or outputs is `None`.", "source": "github_repos"} +{"code": "def get_output_shape_at(self, node_index):\n return self._get_node_attribute_at_index(node_index, 'output_shapes', 'output shape')", "docstring": "Retrieves the output shape(s) of a layer at a given node.\n\nArgs:\n node_index: Integer, index of the node\n from which to retrieve the attribute.\n E.g. `node_index=0` will correspond to the\n first time the layer was called.\n\nReturns:\n A shape tuple\n (or list of shape tuples if the layer has multiple outputs).\n\nRaises:\n RuntimeError: If called in Eager mode.", "source": "github_repos"} +{"code": "def douglas_adi_step(theta=0.5):\n\n def _step_fn(time, next_time, coord_grid, value_grid, boundary_conditions, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, num_steps_performed, dtype=None, name=None):\n \"\"\"Performs the step.\"\"\"\n del num_steps_performed\n name = name or 'douglas_adi_step'\n return multidim_parabolic_equation_step(time, next_time, coord_grid, value_grid, boundary_conditions, douglas_adi_scheme(theta), second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, dtype=dtype, name=name)\n return _step_fn", "docstring": "Creates a stepper function with Crank-Nicolson time marching scheme.\n\n Douglas ADI scheme is the simplest time marching scheme for solving parabolic\n PDEs with multiple spatial dimensions. The time step consists of several\n substeps: the first one is fully explicit, and the following `N` steps are\n implicit with respect to contributions of one of the `N` axes (hence \"ADI\" -\n alternating direction implicit). See `douglas_adi_scheme` below for more\n details.\n\nArgs:\n theta: positive Number. `theta = 0` corresponds to fully explicit scheme.\n The larger `theta` the stronger are the corrections by the implicit\n substeps. The recommended value is `theta = 0.5`, because the scheme is\n second order accurate in that case, unless mixed second derivative terms are\n present in the PDE.\n\nReturns:\n Callable to be used in finite-difference PDE solvers (see fd_solvers.py).", "source": "github_repos"} +{"code": "def __init__(self, columns: list[str], split_string_by_delimiter: Optional[str]=None, *, ngram_range: tuple[int, int]=(1, 1), ngrams_separator: Optional[str]=None, compute_word_count: bool=False, key_vocab_filename: Optional[str]=None, name: Optional[str]=None):\n self.columns = columns\n self.ngram_range = ngram_range\n self.ngrams_separator = ngrams_separator\n self.name = name\n self.split_string_by_delimiter = split_string_by_delimiter\n self.key_vocab_filename = key_vocab_filename\n if compute_word_count:\n self.compute_word_count_fn = count_unique_words\n else:\n self.compute_word_count_fn = lambda *args, **kwargs: None\n if ngram_range != (1, 1) and (not ngrams_separator):\n raise ValueError('ngrams_separator must be specified when ngram_range is not (1, 1)')", "docstring": "Bag of words contains the unique words present in the input text.\n This operation applies a bag of words transformation to specified\n columns of incoming data. Also, the transformation accepts a Tuple of\n integers specifying the range of n-gram sizes. The transformation\n splits the input data into a set of consecutive n-grams if ngram_range\n is specified. The n-grams are then converted to a bag of words.\n Also, you can specify a seperator string that will be inserted between\n each ngram.\n\nArgs:\n columns: A list of column names to apply the transformation on.\n split_string_by_delimiter: (Optional) A string that specifies the\n delimiter to split the input strings before computing ngrams.\n ngram_range: A tuple of integers(inclusive) specifying the range of\n n-gram sizes.\n seperator: A string that will be inserted between each ngram.\n compute_word_count: A boolean that specifies whether to compute\n the unique word count over the entire dataset. Defaults to False.\n key_vocab_filename: The file name for the key vocabulary file when\n compute_word_count is True. If empty, a file name\n will be chosen based on the current scope. If provided, the vocab\n file will be suffixed with the column name.\n name: A name for the operation (optional).\n\n Note that original order of the input may not be preserved.", "source": "github_repos"} +{"code": "def forward(self, hidden_state):\n residual = hidden_state\n hidden_state = self.norm(hidden_state)\n if self.self_attn:\n batch_size, n_vars, num_patches, d_model = hidden_state.shape\n hidden_state_reshaped = hidden_state.reshape(batch_size * n_vars, num_patches, d_model)\n x_attn, _, _ = self.self_attn_layer(hidden_state_reshaped, output_attentions=False)\n x_attn = x_attn.reshape(batch_size, n_vars, num_patches, d_model)\n hidden_state = hidden_state.transpose(2, 3)\n hidden_state = self.mlp(hidden_state)\n if self.gated_attn:\n hidden_state = self.gating_block(hidden_state)\n hidden_state = hidden_state.transpose(2, 3)\n if self.self_attn:\n hidden_state = self.norm_attn(hidden_state + x_attn)\n out = hidden_state + residual\n return out", "docstring": "Args:\n hidden_state (`torch.Tensor`): Input tensor.\n\nReturns:\n `torch.Tensor`: Transformed tensor.", "source": "github_repos"} +{"code": "def f(options, expected_tf_failures=0):\n test_parameters = [{'ksize': [[1, 1, 1, 1, 1], [1, 2, 2, 2, 1], [1, 2, 3, 4, 1]], 'strides': [[1, 1, 1, 1, 1], [1, 2, 1, 2, 1], [1, 2, 2, 4, 1]], 'input_shape': [[1, 1, 1, 1, 1], [1, 16, 15, 14, 1], [3, 16, 15, 14, 3]], 'padding': ['SAME', 'VALID'], 'data_format': ['NDHWC']}]\n\n def build_graph(parameters):\n input_tensor = tf.compat.v1.placeholder(dtype=tf.float32, name='input', shape=parameters['input_shape'])\n out = pool_op(input_tensor, ksize=parameters['ksize'], strides=parameters['strides'], data_format=parameters['data_format'], padding=parameters['padding'])\n return ([input_tensor], [out])\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(tf.float32, parameters['input_shape'])\n return ([input_values], sess.run(outputs, feed_dict=dict(zip(inputs, [input_values]))))\n extra_convert_options = ExtraConvertOptions()\n extra_convert_options.allow_custom_ops = True\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs, extra_convert_options, expected_tf_failures=expected_tf_failures)", "docstring": "Actual function that generates examples.\n\nArgs:\n options: An Options instance.\n expected_tf_failures: number of expected tensorflow failures.", "source": "github_repos"} +{"code": "def leaky_relu(features, alpha=0.2, name=None):\n with ops.name_scope(name, 'LeakyRelu', [features, alpha]) as name:\n features = ops.convert_to_tensor(features, name='features')\n if features.dtype.is_integer:\n features = math_ops.cast(features, dtypes.float32)\n if isinstance(alpha, np.ndarray):\n alpha = alpha.item()\n return gen_nn_ops.leaky_relu(features, alpha=alpha, name=name)", "docstring": "Compute the Leaky ReLU activation function.\n\n Source: [Rectifier Nonlinearities Improve Neural Network Acoustic Models.\n AL Maas, AY Hannun, AY Ng - Proc. ICML, 2013]\n (https://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf).\n\nArgs:\n features: A `Tensor` representing preactivation values. Must be one of\n the following types: `float16`, `float32`, `float64`, `int32`, `int64`.\n alpha: Slope of the activation function at x < 0.\n name: A name for the operation (optional).\n\nReturns:\n The activation value.\n\n References:\n Rectifier Nonlinearities Improve Neural Network Acoustic Models:\n [Maas et al., 2013]\n (http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.693.1422)\n ([pdf]\n (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.693.1422&rep=rep1&type=pdf))", "source": "github_repos"} +{"code": "def infer_steps_for_dataset(model, dataset, steps, epochs=1, steps_name='steps'):\n assert isinstance(dataset, data_types.DatasetV2)\n if model._in_multi_worker_mode() and dataset.options().experimental_distribute.auto_shard_policy != options_lib.AutoShardPolicy.OFF:\n return None\n size = backend.get_value(cardinality.cardinality(dataset))\n if size == cardinality.INFINITE and steps is None:\n raise ValueError('When passing an infinitely repeating dataset, you must specify the `%s` argument.' % (steps_name,))\n if size >= 0:\n if steps is not None and steps * epochs > size:\n if epochs > 1:\n raise ValueError('The dataset you passed contains %s batches, but you passed `epochs=%s` and `%s=%s`, which is a total of %s steps. We cannot draw that many steps from this dataset. We suggest to set `%s=%s`.' % (size, epochs, steps_name, steps, steps * epochs, steps_name, size // epochs))\n else:\n raise ValueError('The dataset you passed contains %s batches, but you passed `%s=%s`. We cannot draw that many steps from this dataset. We suggest to set `%s=%s`.' % (size, steps_name, steps, steps_name, size))\n if steps is None:\n if size >= 0:\n return size\n return None\n return steps", "docstring": "Infers steps_per_epoch needed to loop through a dataset.\n\nArgs:\n model: Keras model instance.\n dataset: Input data of type tf.data.Dataset.\n steps: Number of steps to draw from the dataset (may be None if unknown).\n epochs: Number of times to iterate over the dataset.\n steps_name: The string name of the steps argument, either `steps`,\n `validation_steps`, or `steps_per_epoch`. Only used for error message\n formatting.\n\nReturns:\n Integer or `None`. Inferred number of steps to loop through the dataset.\n `None` is returned if 1) the size of the dataset is unknown and `steps` was\n not specified, or 2) this is multi-worker training and auto sharding is\n enabled.\n\nRaises:\n ValueError: In case of invalid argument values.", "source": "github_repos"} +{"code": "def get_cuda_compute_capability(source_from_url=False):\n if not GPU_TYPE:\n if FLAGS.debug:\n print('Warning: GPU_TYPE is empty. Make sure to call `get_gpu_type()` first.')\n elif GPU_TYPE == 'unknown':\n if FLAGS.debug:\n print('Warning: Unknown GPU is detected. Skipping CUDA compute capability retrieval.')\n else:\n if source_from_url:\n cuda_compute_capa = cuda_compute_capability.retrieve_from_web()\n else:\n cuda_compute_capa = cuda_compute_capability.retrieve_from_golden()\n return cuda_compute_capa[GPU_TYPE]\n return", "docstring": "Retrieves CUDA compute capability based on the detected GPU type.\n\n This function uses the `cuda_compute_capability` module to retrieve the\n corresponding CUDA compute capability for the given GPU type.\n\nArgs:\n source_from_url: Boolean deciding whether to source compute capability\n from NVIDIA website or from a local golden file.\n\nReturns:\n List of all supported CUDA compute capabilities for the given GPU type.\n e.g. ['3.5', '3.7']", "source": "github_repos"} +{"code": "def __enter__(self):\n self._old = self._var_scope_store.current_scope\n if isinstance(self._name_or_scope, VariableScope):\n self._var_scope_store.open_variable_scope(self._new_name)\n self._old_subscopes = copy.copy(self._var_scope_store.variable_scopes_count)\n variable_scope_object = self._cached_variable_scope_object\n else:\n self._new_name = self._old.name + '/' + self._name_or_scope if self._old.name else self._name_or_scope\n self._reuse = self._reuse or self._old.reuse\n if self._old_name_scope is None:\n name_scope = self._name_or_scope\n else:\n name_scope = self._old_name_scope\n variable_scope_object = VariableScope(self._reuse, name=self._new_name, initializer=self._old.initializer, regularizer=self._old.regularizer, caching_device=self._old.caching_device, partitioner=self._old.partitioner, dtype=self._old.dtype, use_resource=self._old.use_resource, custom_getter=self._old.custom_getter, name_scope=name_scope, constraint=self._constraint)\n if self._initializer is not None:\n variable_scope_object.set_initializer(self._initializer)\n if self._regularizer is not None:\n variable_scope_object.set_regularizer(self._regularizer)\n if self._caching_device is not None:\n variable_scope_object.set_caching_device(self._caching_device)\n if self._partitioner is not None:\n variable_scope_object.set_partitioner(self._partitioner)\n if self._custom_getter is not None:\n variable_scope_object.set_custom_getter(_maybe_wrap_custom_getter(self._custom_getter, self._old.custom_getter))\n if self._dtype is not None:\n variable_scope_object.set_dtype(self._dtype)\n if self._use_resource is not None:\n variable_scope_object.set_use_resource(self._use_resource)\n self._var_scope_store.open_variable_scope(self._new_name)\n self._var_scope_store.current_scope = variable_scope_object\n self._last_variable_scope_object = variable_scope_object\n return variable_scope_object", "docstring": "Begins the scope block.\n\nReturns:\n A VariableScope.\n\nRaises:\n ValueError: when trying to reuse within a create scope, or create within\n a reuse scope, or if reuse is not `None` or `True`.\n TypeError: when the types of some arguments are not appropriate.", "source": "github_repos"} +{"code": "def unwrap_outputs(distribution_strategy, grouped_outputs, with_loss_tensor=False):\n if not with_loss_tensor:\n return flatten_per_replica_values(distribution_strategy, grouped_outputs)\n if not isinstance(grouped_outputs, list):\n grouped_outputs = [grouped_outputs]\n loss = distribution_strategy.reduce(reduce_util.ReduceOp.SUM, grouped_outputs[0], axis=None)\n all_outputs = flatten_per_replica_values(distribution_strategy, grouped_outputs[1:])\n if backend.is_tpu_strategy(distribution_strategy) and ops.executing_eagerly_outside_functions():\n all_outputs = all_outputs[::distribution_strategy.num_replicas_in_sync]\n return [loss] + all_outputs", "docstring": "Unwrap the list of outputs contained in the PerReplica parameters.\n\n This function calls `flatten_per_replica_values` to parse each of the input\n parameters into a list of outputs on the different devices. If we set\n `with_loss_tensor` to be True, we also call `reduce` on the list of losses on\n the different devices to give us one loss tensor.\n\nArgs:\n distribution_strategy: DistributionStrategy used to distribute training and\n validation.\n grouped_outputs: PerReplica outputs returned from the train or test function\n that we ran on each device.\n with_loss_tensor: Boolean that indicates if we need to add the reduced loss\n tensor as one of the outputs.\n\nReturns:\n Values of each of the PerReplica outputs.", "source": "github_repos"} +{"code": "def _prepare_4d_causal_attention_mask_with_cache_position(attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, cache_position: torch.Tensor, batch_size: int, **kwargs):\n if attention_mask is not None and attention_mask.dim() == 4:\n causal_mask = attention_mask\n else:\n min_dtype = torch.finfo(dtype).min\n causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device)\n if sequence_length != 1:\n causal_mask = torch.triu(causal_mask, diagonal=1)\n causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)\n causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)\n if attention_mask is not None:\n causal_mask = causal_mask.clone()\n mask_length = attention_mask.shape[-1]\n padding_attention_mask = (attention_mask[:, None, None, :] == attention_mask[:, None, :, None])[:, :, -sequence_length:, :].to(dtype)\n padding_mask = causal_mask[:, :, :, :mask_length] + padding_attention_mask\n padding_mask = padding_mask == 0\n causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(padding_mask, min_dtype)\n return causal_mask", "docstring": "Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape\n `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.\n\nArgs:\n attention_mask (`torch.Tensor`):\n A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape\n `(batch_size, 1, query_length, key_value_length)`.\n sequence_length (`int`):\n The sequence length being processed.\n target_length (`int`):\n The target length: when generating with static cache, the mask should be as long as the static cache,\n to account for the 0 padding, the part of the cache that is not filled yet.\n dtype (`torch.dtype`):\n The dtype to use for the 4D attention mask.\n cache_position (`torch.Tensor`):\n Indices depicting the position of the input sequence tokens in the sequence.\n batch_size (`torch.Tensor`):\n Batch size.", "source": "github_repos"} +{"code": "def is_deterministic(self):\n return False", "docstring": "Whether this coder is guaranteed to encode values deterministically.\n\n A deterministic coder is required for key coders in GroupByKey operations\n to produce consistent results.\n\n For example, note that the default coder, the PickleCoder, is not\n deterministic: the ordering of picked entries in maps may vary across\n executions since there is no defined order, and such a coder is not in\n general suitable for usage as a key coder in GroupByKey operations, since\n each instance of the same key may be encoded differently.\n\nReturns:\n Whether coder is deterministic.", "source": "github_repos"} +{"code": "def determine_framework(model: str, framework: Optional[str]=None) -> str:\n if framework is not None:\n return framework\n framework_map = {'pt': 'PyTorch', 'tf': 'TensorFlow'}\n exporter_map = {'pt': 'torch', 'tf': 'tf2onnx'}\n if os.path.isdir(model):\n if os.path.isfile(os.path.join(model, WEIGHTS_NAME)):\n framework = 'pt'\n elif os.path.isfile(os.path.join(model, TF2_WEIGHTS_NAME)):\n framework = 'tf'\n else:\n raise FileNotFoundError(f'Cannot determine framework from given checkpoint location. There should be a {WEIGHTS_NAME} for PyTorch or {TF2_WEIGHTS_NAME} for TensorFlow.')\n logger.info(f'Local {framework_map[framework]} model found.')\n elif is_torch_available():\n framework = 'pt'\n elif is_tf_available():\n framework = 'tf'\n else:\n raise OSError('Neither PyTorch nor TensorFlow found in environment. Cannot export to ONNX.')\n logger.info(f'Framework not requested. Using {exporter_map[framework]} to export to ONNX.')\n return framework", "docstring": "Determines the framework to use for the export.\n\n The priority is in the following order:\n 1. User input via `framework`.\n 2. If local checkpoint is provided, use the same framework as the checkpoint.\n 3. Available framework in environment, with priority given to PyTorch\n\nArgs:\n model (`str`):\n The name of the model to export.\n framework (`str`, *optional*, defaults to `None`):\n The framework to use for the export. See above for priority if none provided.\n\nReturns:\n The framework to use for the export.", "source": "github_repos"} +{"code": "def __init__(self, filename, separator=',', append=False):\n self.sep = separator\n self.filename = path_to_string(filename)\n self.append = append\n self.writer = None\n self.keys = None\n self.append_header = True\n super(CSVLogger, self).__init__()", "docstring": "Callback that streams epoch results to a CSV file.\n\n Supports all values that can be represented as a string,\n including 1D iterables such as `np.ndarray`.\n\nExample:\n ```python\n csv_logger = CSVLogger('training.log')\n model.fit(X_train, Y_train, callbacks=[csv_logger])\n ```\n\nArgs:\n filename: Filename of the CSV file, e.g. `'run/log.csv'`.\n separator: String used to separate elements in the CSV file.\n append: Boolean. True: append if file exists (useful for continuing\n training). False: overwrite existing file.", "source": "github_repos"} +{"code": "def resize_positional_embeddings(positional_embeddings: torch.Tensor, spatial_shapes: torch.LongTensor, max_length: int) -> torch.Tensor:\n batch_size = spatial_shapes.shape[0]\n embed_dim = positional_embeddings.shape[-1]\n source_dtype = positional_embeddings.dtype\n resulted_positional_embeddings = torch.empty((batch_size, max_length, embed_dim), device=positional_embeddings.device, dtype=source_dtype)\n positional_embeddings = positional_embeddings.permute(2, 0, 1).unsqueeze(0)\n if positional_embeddings.device.type == 'cpu':\n positional_embeddings = positional_embeddings.to(torch.float32)\n for i in range(batch_size):\n height, width = spatial_shapes[i]\n resized_embeddings = F.interpolate(positional_embeddings, size=(height, width), mode='bilinear', align_corners=False, antialias=True)\n resized_embeddings = resized_embeddings.reshape(embed_dim, height * width).transpose(0, 1)\n resized_embeddings = resized_embeddings.to(source_dtype)\n resulted_positional_embeddings[i, :height * width] = resized_embeddings\n resulted_positional_embeddings[i, height * width:] = resized_embeddings[0]\n return resulted_positional_embeddings", "docstring": "Resize positional embeddings to image-specific size and pad to a fixed size.\n\nArgs:\n positional_embeddings (`torch.Tensor`):\n Position embeddings of shape (height, width, embed_dim)\n spatial_shapes (`torch.LongTensor`):\n Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to\n max_length (`int`):\n Maximum length of the positional embeddings to pad resized positional embeddings to\n\nReturns:\n `torch.Tensor`: Embeddings of shape (batch_size, max_length, embed_dim)", "source": "github_repos"} +{"code": "def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BILINEAR, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:\n default_to_square = True\n if 'shortest_edge' in size:\n size = size['shortest_edge']\n default_to_square = False\n elif 'height' in size and 'width' in size:\n size = (size['height'], size['width'])\n else:\n raise ValueError(\"Size must contain either 'shortest_edge' or 'height' and 'width'.\")\n output_size = get_resize_output_image_size(image, size=size, default_to_square=default_to_square, input_data_format=input_data_format)\n return resize(image, size=output_size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs)", "docstring": "Resize an image. The shortest edge of the image is resized to size[\"shortest_edge\"], with the longest edge\n resized to keep the input aspect ratio.\n\nArgs:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.", "source": "github_repos"} +{"code": "def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:\n if token_ids_1 is None:\n return self.prefix_tokens + token_ids_0 + self.suffix_tokens\n return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens", "docstring": "Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and\n adding special tokens. An NLLB sequence has the following format, where `X` represents the sequence:\n\n - `input_ids` (for encoder) `X [eos, src_lang_code]`\n - `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]`\n\n BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a\n separator.\n\nArgs:\n token_ids_0 (`List[int]`):\n List of IDs to which the special tokens will be added.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n\nReturns:\n `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.", "source": "github_repos"} +{"code": "def __init__(self, config: PretrainedConfig, generation_config: GenerationConfig, device: torch.device, dtype: torch.dtype=torch.float16, layer_device_map: Optional[Dict[int, Union[str, torch.device, int]]]=None, initial_prompt_shapes: Optional[List[List[int]]]=None) -> None:\n self.num_key_value_heads = config.num_attention_heads if getattr(config, 'num_key_value_heads', None) is None else config.num_key_value_heads\n self.head_dim = config.head_dim if hasattr(config, 'head_dim') else config.hidden_size // config.num_attention_heads\n self.num_hidden_layers = config.num_hidden_layers\n num_blocks = getattr(generation_config, 'num_blocks', None)\n block_size = getattr(generation_config, 'block_size', None)\n if num_blocks is None or block_size is None:\n logger.info('Calculating optimal block size and number...')\n num_blocks, block_size = compute_optimal_blocks(device, config, generation_config, initial_prompt_shapes or [], dtype, median_prefill_length=200)\n logger.info(f'Using calculated num_blocks={num_blocks}, block_size={block_size}')\n self.block_size = block_size\n self.num_blocks = num_blocks\n self.cache_shape = (self.num_key_value_heads, num_blocks, self.block_size, self.head_dim)\n self.dtype = dtype\n self.device = device\n self.key_cache: List[torch.Tensor] = []\n self.value_cache: List[torch.Tensor] = []\n for idx in range(config.num_hidden_layers):\n layer_device = layer_device_map[idx] if layer_device_map is not None else device\n new_layer_key_cache = torch.zeros(self.cache_shape, dtype=self.dtype, device=layer_device)\n new_layer_value_cache = torch.zeros(self.cache_shape, dtype=self.dtype, device=layer_device)\n torch._dynamo.mark_static_address(new_layer_key_cache)\n torch._dynamo.mark_static_address(new_layer_value_cache)\n self.key_cache.append(new_layer_key_cache)\n self.value_cache.append(new_layer_value_cache)\n self._free_blocks = deque(range(num_blocks))\n self._block_tables: Dict[str, List[int]] = {}", "docstring": "Initialize a paged attention cache for efficient memory usage.\n\nArgs:\n config: Model configuration\n generation_config: Generation configuration containing cache parameters\n device: Device for the cache tensors\n dtype: Data type for the cache tensors\n layer_device_map: Optional mapping of layer indices to devices\n initial_prompt_shapes: Optional sample prompts to help calculate optimal cache size", "source": "github_repos"} +{"code": "def get_all_plugin_assets(graph=None):\n if graph is None:\n graph = ops.get_default_graph()\n out = []\n for name in graph.get_collection(_PLUGIN_ASSET_PREFIX):\n collection = graph.get_collection(_PLUGIN_ASSET_PREFIX + name)\n if len(collection) != 1:\n raise ValueError('Collection for %s had %d items, expected 1' % (name, len(collection)))\n out.append(collection[0])\n return out", "docstring": "Retrieve all PluginAssets stored in the graph collection.\n\nArgs:\n graph: Optionally, the graph to get assets from. If unspecified, the default\n graph is used.\n\nReturns:\n A list with all PluginAsset instances in the graph.\n\nRaises:\n ValueError: if we unexpectedly find a collection with the wrong number of\n PluginAssets.", "source": "github_repos"} +{"code": "def _find_suite_class():\n test_suites = _find_suite_classes_in_module(sys.modules['__main__'])\n if len(test_suites) == 0:\n logging.debug('No suite class found in the __main__ module, trying to find it in the module of the caller of suite_runner.run_suite_class method.')\n stacks = inspect.stack()\n if len(stacks) < 2:\n logging.debug('Failed to get the caller stack of run_suite_class. Got stacks: %s', stacks)\n else:\n run_suite_class_caller_frame_info = inspect.stack()[2]\n caller_frame = run_suite_class_caller_frame_info.frame\n module = inspect.getmodule(caller_frame)\n if module is None:\n logging.debug('Failed to find module for frame %s', caller_frame)\n else:\n test_suites = _find_suite_classes_in_module(module)\n if len(test_suites) != 1:\n logging.error('Expected 1 test class per file, found %s.', [t.__name__ for t in test_suites])\n sys.exit(1)\n return test_suites[0]", "docstring": "Finds the test suite class.\n\n First search for test suite classes in the __main__ module. If no test suite\n class is found, search in the module that is calling\n `suite_runner.run_suite_class`.\n\n Walk through module members and find the subclass of BaseSuite. Only\n one subclass is allowed.\n\nReturns:\n The test suite class in the test module.", "source": "github_repos"} +{"code": "def _convert_concrete_functions_to_saved_model(self, output_dir):\n if len(self._funcs) == 0:\n raise ValueError('No ConcreteFunction is specified.')\n if not self.experimental_lower_to_saved_model:\n return (None, None, None)\n if not self._trackable_obj or isinstance(self._trackable_obj, (_function.ConcreteFunction, _def_function.Function)):\n return (None, None, None)\n signatures = {}\n signature_keys = []\n try:\n if len(self._funcs) == 1:\n signatures[_signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = self._funcs[0]\n signature_keys = [_signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\n else:\n for func in self._funcs:\n signatures[func.graph.name] = func\n signature_keys.append(func.graph.name)\n _save.save(self._trackable_obj, output_dir, signatures=signatures, options=_save_options.SaveOptions(save_debug_info=True))\n except Exception:\n return (None, None, None)\n self.saved_model_dir = output_dir\n self._saved_model_tags = set([_tag_constants.SERVING])\n self._saved_model_exported_names = signature_keys\n self._parse_saved_model_args(always_enable_saved_model_import=True)\n if self.saved_model_dir:\n graph_def, input_tensors, output_tensors = self._load_saved_model(self.saved_model_dir, self._saved_model_tags)\n self._trackable_obj = _load(self.saved_model_dir, self._saved_model_tags)\n return (graph_def, input_tensors, output_tensors)\n return (None, None, None)", "docstring": "Save concrete functions to the SavedModel format.\n\nArgs:\n output_dir: The output directory to save the SavedModel.\n\nReturns:\n graph_def: The frozen GraphDef.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.", "source": "github_repos"} +{"code": "def _finalize_func(string_handle):\n iterator_resource = gen_dataset_ops.iterator_from_string_handle_v2(string_handle, **self._input_dataset._flat_structure)\n with ops.control_dependencies([resource_variable_ops.destroy_resource_op(iterator_resource, ignore_lookup_error=True)]):\n return array_ops.constant(0, dtypes.int64)", "docstring": "Destroys the iterator resource created.\n\nArgs:\n string_handle: An iterator string handle created by _init_func\n\nReturns:\n Tensor constant 0", "source": "github_repos"} +{"code": "def count(self) -> 'Builder':\n return self._to_builder(_evaluation.CountFunction(self.node.context, self.node, []))", "docstring": "The FHIRPath count() function.\n\nReturns:\n An expression that evaluates to the count of items in the parent.", "source": "github_repos"} +{"code": "def with_outputs(self, *tags, main=None, allow_unknown_tags=None):\n if main in tags:\n raise ValueError('Main output tag %r must be different from side output tags %r.' % (main, tags))\n return _MultiParDo(self, tags, main, allow_unknown_tags)", "docstring": "Returns a tagged tuple allowing access to the outputs of a\n :class:`ParDo`.\n\n The resulting object supports access to the\n :class:`~apache_beam.pvalue.PCollection` associated with a tag\n (e.g. ``o.tag``, ``o[tag]``) and iterating over the available tags\n (e.g. ``for tag in o: ...``).\n\nArgs:\n *tags: if non-empty, list of valid tags. If a list of valid tags is given,\n it will be an error to use an undeclared tag later in the pipeline.\n **main_kw: dictionary empty or with one key ``'main'`` defining the tag to\n be used for the main output (which will not have a tag associated with\n it).\n\nReturns:\n ~apache_beam.pvalue.DoOutputsTuple: An object of type\n :class:`~apache_beam.pvalue.DoOutputsTuple` that bundles together all\n the outputs of a :class:`ParDo` transform and allows accessing the\n individual :class:`~apache_beam.pvalue.PCollection` s for each output\n using an ``object.tag`` syntax.\n\nRaises:\n TypeError: if the **self** object is not a\n :class:`~apache_beam.pvalue.PCollection` that is the result of a\n :class:`ParDo` transform.\n ValueError: if **main_kw** contains any key other than\n ``'main'``.", "source": "github_repos"} +{"code": "def _get_compatible_spec(value_or_spec1, value_or_spec2):\n spec1 = _get_spec_for(value_or_spec1)\n spec2 = _get_spec_for(value_or_spec2)\n common = spec1._without_tensor_names().most_specific_common_supertype([spec2._without_tensor_names()])\n if common is None:\n raise TypeError(f'No common supertype of {spec1} and {spec2}.')\n return common", "docstring": "Returns the most specific compatible spec.\n\nArgs:\n value_or_spec1: A TypeSpecs or a value that has a defined TypeSpec.\n value_or_spec2: A TypeSpecs or a value that has a defined TypeSpec.\n\nReturns:\n The most specific compatible TypeSpecs of the input.\n\nRaises:\n ValueError: If value_or_spec1 is not compatible with value_or_spec2.", "source": "github_repos"} +{"code": "def fields_to_string(fields, values={}):\n items = [repr(field['name']) + ':' + repr(values.get(field['name'], field.get('default', ''))) + ',' + (' # %s' % field['description'] if 'description' in field else '') for field in fields]\n return '{\\n %s\\n}' % '\\n '.join(items) if items else '{}'", "docstring": "Converts fields to a dictionary of parameters as a string.\n\n Used to generate input blocks in generated code.\n\n For example:\n {\n 'auth':'user', # authentication to use for call.\n 'name':'value', # parameter to pass to function.\n }\n\nArgs:\n - fields: (list) Contains {\"field\":{...}} objects to be rendered as imputs.\n - values: (dict) Default values to use for each field.\n\nReturns:\n String representing python code to be written to a generated file.", "source": "github_repos"} +{"code": "def make_polynomial_basis(degree):\n tf.debugging.assert_greater_equal(degree, 0, message='Degree of polynomial basis can not be negative.')\n\n def basis(sample_paths, time_index):\n \"\"\"Computes polynomial basis expansion at the given sample points.\n\n Args:\n sample_paths: A `Tensor` of either `flaot32` or `float64` dtype and of\n either shape `[num_samples, num_times, dim]` or\n `[batch_size, num_samples, num_times, dim]`.\n time_index: An integer scalar `Tensor` that corresponds to the time\n coordinate at which the basis function is computed.\n\n Returns:\n A `Tensor`s of shape `[batch_size, (degree + 1)**dim, num_samples]`.\n \"\"\"\n sample_paths = tf.convert_to_tensor(sample_paths, name='sample_paths')\n if sample_paths.shape.rank == 3:\n sample_paths = tf.expand_dims(sample_paths, axis=0)\n shape = tf.shape(sample_paths)\n num_samples = shape[1]\n batch_size = shape[0]\n dim = sample_paths.shape[-1]\n slice_samples = tf.slice(sample_paths, [0, 0, time_index, 0], [batch_size, num_samples, 1, dim])\n samples_centered = slice_samples - tf.math.reduce_mean(slice_samples, axis=1, keepdims=True)\n grid = tf.range(degree + 1, dtype=samples_centered.dtype)\n grid = tf.meshgrid(*dim * [grid])\n grid = tf.reshape(tf.stack(grid, -1), [-1, dim])\n basis_expansion = tf.reduce_prod(samples_centered ** grid, axis=-1)\n return tf.transpose(basis_expansion, [0, 2, 1])\n return basis", "docstring": "Produces a callable from samples to polynomial basis for use in regression.\n\n The output callable accepts a scalar `Tensor` `t` and a `Tensor` `X` of\n shape `[num_samples, dim]`, computes a centered value\n `Y = X - mean(X, axis=0)` and outputs a `Tensor` of shape\n `[degree * dim, num_samples]`, where\n ```\n Z[i*j, k] = X[k, j]**(degree - i) * X[k, j]**i, 0<=i List[int]:\n if already_has_special_tokens:\n return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)\n if token_ids_1 is None:\n return [1] + [0] * len(token_ids_0) + [1]\n return [1] + [0] * len(token_ids_0) + [1] + [1] + [0] * len(token_ids_1) + [1]", "docstring": "Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding\n special tokens using the tokenizer `prepare_for_model` method.\n\nArgs:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n already_has_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not the token list is already formatted with special tokens for the model.\n\nReturns:\n `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.", "source": "github_repos"} +{"code": "def _train_model(self, checkpoint_dir, num_steps):\n with ops.Graph().as_default():\n random_seed.set_random_seed(0)\n tf_inputs = constant_op.constant(self._inputs, dtype=dtypes.float32)\n tf_labels = constant_op.constant(self._labels, dtype=dtypes.float32)\n tf_predictions = logistic_classifier(tf_inputs)\n loss_op = losses.log_loss(labels=tf_labels, predictions=tf_predictions)\n optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=1.0)\n train_op = optimizer.minimize(loss_op, training.get_or_create_global_step())\n with monitored_session.MonitoredTrainingSession(checkpoint_dir=checkpoint_dir, hooks=[basic_session_run_hooks.StopAtStepHook(num_steps)]) as session:\n loss = None\n while not session.should_stop():\n _, loss = session.run([train_op, loss_op])\n if num_steps >= 300:\n assert loss < 0.015", "docstring": "Trains a simple classification model.\n\n Note that the data has been configured such that after around 300 steps,\n the model has memorized the dataset (e.g. we can expect %100 accuracy).\n\nArgs:\n checkpoint_dir: The directory where the checkpoint is written to.\n num_steps: The number of steps to train for.", "source": "github_repos"} +{"code": "def relu(x, negative_slope=0.0, max_value=None, threshold=0.0):\n if backend.any_symbolic_tensors((x,)):\n return ReLU(negative_slope=negative_slope, max_value=max_value, threshold=threshold)(x)\n return ReLU.static_call(x, negative_slope=negative_slope, max_value=max_value, threshold=threshold)", "docstring": "Applies the rectified linear unit activation function.\n\n With default values, this returns the standard ReLU activation:\n `max(x, 0)`, the element-wise maximum of 0 and the input tensor.\n\n Modifying default parameters allows you to use non-zero thresholds,\n change the max value of the activation,\n and to use a non-zero multiple of the input for values below the threshold.\n\nExample:\n >>> x = [-10, -5, 0.0, 5, 10]\n >>> keras.activations.relu(x)\n [ 0., 0., 0., 5., 10.]\n >>> keras.activations.relu(x, negative_slope=0.5)\n [-5. , -2.5, 0. , 5. , 10. ]\n >>> keras.activations.relu(x, max_value=5.)\n [0., 0., 0., 5., 5.]\n >>> keras.activations.relu(x, threshold=5.)\n [-0., -0., 0., 0., 10.]\n\nArgs:\n x: Input tensor.\n negative_slope: A `float` that controls the slope\n for values lower than the threshold.\n max_value: A `float` that sets the saturation threshold (the largest\n value the function will return).\n threshold: A `float` giving the threshold value of the activation\n function below which values will be damped or set to zero.\n\nReturns:\n A tensor with the same shape and dtype as input `x`.", "source": "github_repos"} +{"code": "def __init__(self, initial_learning_rate, decay_steps, decay_rate, staircase=False, name=None):\n super(InverseTimeDecay, self).__init__()\n self.initial_learning_rate = initial_learning_rate\n self.decay_steps = decay_steps\n self.decay_rate = decay_rate\n self.staircase = staircase\n self.name = name", "docstring": "Applies inverse time decay to the initial learning rate.\n\nArgs:\n initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a\n Python number. The initial learning rate.\n decay_steps: How often to apply decay.\n decay_rate: A Python number. The decay rate.\n staircase: Whether to apply decay in a discrete staircase, as opposed to\n continuous, fashion.\n name: String. Optional name of the operation. Defaults to\n 'InverseTimeDecay'.", "source": "github_repos"} +{"code": "def _test_or_class_decorator(test_or_class, single_method_decorator):\n\n def _decorate_test_or_class(obj):\n if isinstance(obj, collections.abc.Iterable):\n return itertools.chain.from_iterable((single_method_decorator(method) for method in obj))\n if isinstance(obj, type):\n cls = obj\n for name, value in cls.__dict__.copy().items():\n if callable(value) and name.startswith(unittest.TestLoader.testMethodPrefix):\n setattr(cls, name, single_method_decorator(value))\n cls = type(cls).__new__(type(cls), cls.__name__, cls.__bases__, cls.__dict__.copy())\n return cls\n return single_method_decorator(obj)\n if test_or_class is not None:\n return _decorate_test_or_class(test_or_class)\n return _decorate_test_or_class", "docstring": "Decorate a test or class with a decorator intended for one method.\n\n If the test_or_class is a class:\n This will apply the decorator to all test methods in the class.\n\n If the test_or_class is an iterable of already-parameterized test cases:\n This will apply the decorator to all the cases, and then flatten the\n resulting cross-product of test cases. This allows stacking the Keras\n parameterized decorators w/ each other, and to apply them to test methods\n that have already been marked with an absl parameterized decorator.\n\n Otherwise, treat the obj as a single method and apply the decorator directly.\n\nArgs:\n test_or_class: A test method (that may have already been decorated with a\n parameterized decorator, or a test class that extends\n keras_parameterized.TestCase\n single_method_decorator:\n A parameterized decorator intended for a single test method.\n\nReturns:\n The decorated result.", "source": "github_repos"} +{"code": "def read_video_decord(video_path: str, sample_indices_fn: Optional[Callable]=None, **kwargs):\n requires_backends(read_video_decord, ['decord'])\n from decord import VideoReader, cpu\n vr = VideoReader(uri=video_path, ctx=cpu(0))\n video_fps = vr.get_avg_fps()\n total_num_frames = len(vr)\n duration = total_num_frames / video_fps if video_fps else 0\n metadata = VideoMetadata(total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend='decord')\n indices = sample_indices_fn(metadata=metadata, **kwargs)\n frames = vr.get_batch(indices).asnumpy()\n metadata.frames_indices = indices\n return (frames, metadata)", "docstring": "Decode a video using the Decord backend.\n\nArgs:\n video_path (`str`):\n Path to the video file.\n sample_indices_fn (`Callable`, *optional*):\n A callable function that will return indices at which the video should be sampled. If the video has to be loaded using\n by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.\n If not provided, simple uniform sampling with fps is performed.\n\nExample:\n def sample_indices_fn(metadata, **kwargs):\n return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)\n\nReturns:\n Tuple[`np.array`, `VideoMetadata`]: A tuple containing:\n - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).\n - `VideoMetadata` object.", "source": "github_repos"} +{"code": "def __init__(self, initlist: List[T], max_size: int, flusher: FlushFunction) -> None:\n self.queue = initlist\n self.max_size = max_size\n self.flusher = flusher", "docstring": "Representation of a Buffer (FIFO queue) with the ability to\n consume the current queue into a flush function when max_size is reached.\n\n It can queue any list of items, e.g. logs, rows, and API calls.\n\nArgs:\n * initlist: Initial list of items\n * max_size: Maximum queue size\n * flusher: Function to be called with list of items", "source": "github_repos"} +{"code": "def _convert_fields(fields, field_values, context):\n converted = {}\n if len(fields) != len(field_values):\n _report_field_mismatches(fields, field_values)\n for field in fields:\n if field.name not in field_values:\n _report_field_mismatches(fields, field_values)\n field_value = field_values[field.name]\n converted[field.name] = _convert_value(field_value, field.value_type, (field.name,), context)\n field_values.update(converted)", "docstring": "Type-checks and converts each field in `field_values` (in place).\n\nArgs:\n fields: A list of `ExtensionTypeField` objects.\n field_values: A `dict` mapping field names to values. Must contain an entry\n for each field. I.e., `set(field_values.keys())` must be equal to\n `set([f.name for f in fields])`.\n context: _ConversionContext, indicates what kind of value we are converting.\n\nRaises:\n ValueError: If the keys of `field_values` do not match the names of\n the fields in `fields`.\n TypeError: If any value in `field_values` does not have the type indicated\n by the corresponding `ExtensionTypeField` object.", "source": "github_repos"} +{"code": "def forward(self, hidden_states: List[torch.Tensor], patch_height, patch_width) -> List[torch.Tensor]:\n batch_size = hidden_states[0].shape[0]\n hidden_states = torch.cat(hidden_states, dim=0)\n cls_token, hidden_states = (hidden_states[:, 0], hidden_states[:, 1:])\n total_batch_size, sequence_length, num_channels = hidden_states.shape\n hidden_states = hidden_states.reshape(total_batch_size, patch_height, patch_width, num_channels)\n hidden_states = hidden_states.permute(0, 3, 1, 2).contiguous()\n if self.readout_type == 'project':\n hidden_states = hidden_states.flatten(2).permute((0, 2, 1))\n readout = cls_token.unsqueeze(dim=1).expand_as(hidden_states)\n hidden_states = torch.cat((hidden_states, readout), -1)\n elif self.readout_type == 'add':\n hidden_states = hidden_states + cls_token.unsqueeze(-1)\n out = []\n for stage_idx, hidden_state in enumerate(hidden_states.split(batch_size, dim=0)):\n if self.readout_type == 'project':\n hidden_state = self.readout_projects[stage_idx](hidden_state)\n hidden_state = hidden_state.permute(0, 2, 1).reshape(batch_size, -1, patch_height, patch_width)\n hidden_state = self.layers[stage_idx](hidden_state)\n out.append(hidden_state)\n return out", "docstring": "Args:\n hidden_states (`List[torch.FloatTensor]`, each of shape `(batch_size, sequence_length + 1, hidden_size)`):\n List of hidden states from the backbone.", "source": "github_repos"} +{"code": "def decode(self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray]=None, decoder_attention_mask: Optional[jnp.ndarray]=None, decoder_position_ids: Optional[jnp.ndarray]=None, past_key_values: Optional[dict]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, train: bool=False, params: Optional[dict]=None, dropout_rng: PRNGKey=None):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.config.return_dict\n encoder_hidden_states = encoder_outputs[0]\n if encoder_attention_mask is None:\n batch_size, sequence_length = encoder_hidden_states.shape[:2]\n encoder_attention_mask = jnp.ones((batch_size, sequence_length))\n batch_size, sequence_length = decoder_input_ids.shape\n if decoder_attention_mask is None:\n decoder_attention_mask = jnp.ones((batch_size, sequence_length))\n if decoder_position_ids is None:\n if past_key_values is not None:\n raise ValueError('Make sure to provide `decoder_position_ids` when passing `past_key_values`.')\n decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))\n rngs = {}\n if dropout_rng is not None:\n rngs['dropout'] = dropout_rng\n params = {'params': params or self.params}\n if past_key_values:\n params['cache'] = past_key_values\n mutable = ['cache']\n else:\n mutable = False\n\n def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, encoder_hidden_states, **kwargs):\n projection_module = module._get_projection_module()\n decoder_module = module._get_decoder_module()\n if projection_module is not None:\n encoder_hidden_states = projection_module(encoder_hidden_states)\n return decoder_module(decoder_input_ids, decoder_attention_mask, decoder_position_ids, encoder_hidden_states=encoder_hidden_states, **kwargs)\n outputs = self.module.apply(params, decoder_input_ids=jnp.array(decoder_input_ids, dtype='i4'), decoder_attention_mask=jnp.array(decoder_attention_mask, dtype='i4'), decoder_position_ids=jnp.array(decoder_position_ids, dtype='i4'), encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=jnp.array(encoder_attention_mask, dtype='i4'), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, rngs=rngs, mutable=mutable, method=_decoder_forward)\n if past_key_values is not None and return_dict:\n outputs, past = outputs\n outputs['past_key_values'] = unfreeze(past['cache'])\n return outputs\n elif past_key_values is not None and (not return_dict):\n outputs, past = outputs\n outputs = outputs[:1] + (unfreeze(past['cache']),) + outputs[1:]\n return outputs", "docstring": "Returns:\n\nExample:\n ```python\n >>> from transformers import FlaxSpeechEncoderDecoderModel\n >>> import jax.numpy as jnp\n\n >>> # initialize a wav2vec2-2-bart from pretrained wav2vec2 and bart models. Note that the cross-attention layers will be randomly initialized\n >>> model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(\n ... \"facebook/wav2vec2-large-lv60\", \"facebook/bart-large\"\n ... )\n\n >>> inputs = jnp.ones((2, 5000), dtype=jnp.float32)\n >>> encoder_outputs = model.encode(inputs)\n\n >>> decoder_start_token_id = model.config.decoder.bos_token_id\n >>> decoder_input_ids = jnp.ones((inputs.shape[0], 1), dtype=\"i4\") * decoder_start_token_id\n\n >>> outputs = model.decode(decoder_input_ids, encoder_outputs)\n >>> logits = outputs.logits\n ```", "source": "github_repos"} +{"code": "def __init__(self, image_processor, tokenizer):\n tokenizer.return_token_type_ids = False\n super().__init__(image_processor, tokenizer)", "docstring": "Constructs a PIX2STRUCT processor which wraps a BERT tokenizer and PIX2STRUCT image processor into a single\n processor.\n\n [`Pix2StructProcessor`] offers all the functionalities of [`Pix2StructImageProcessor`] and [`T5TokenizerFast`]. See\n the docstring of [`~Pix2StructProcessor.__call__`] and [`~Pix2StructProcessor.decode`] for more information.\n\nArgs:\n image_processor (`Pix2StructImageProcessor`):\n An instance of [`Pix2StructImageProcessor`]. The image processor is a required input.\n tokenizer (Union[`T5TokenizerFast`, `T5Tokenizer`]):\n An instance of ['T5TokenizerFast`] or ['T5Tokenizer`]. The tokenizer is a required input.", "source": "github_repos"} +{"code": "def reduce(self, reduce_op, per_replica_value, destinations, options=None):\n if options is None:\n options = collective_util.Options()\n per_replica_value = _make_tensor_into_per_replica(per_replica_value)\n validate_destinations(destinations)\n if self._num_between_graph_workers == 1 and len(per_replica_value.values) == 1 and _devices_match(per_replica_value, destinations, self._canonicalize_devices):\n with ops.device(per_replica_value.values[0].device):\n v = array_ops.identity(per_replica_value.values[0])\n return distribute_utils.regroup((v,), wrap_class=value_lib.Mirrored)\n if options is None:\n options = collective_util.Options()\n return self.reduce_implementation(reduce_op, per_replica_value, destinations, options)", "docstring": "Reduce `per_replica_value` to `destinations`.\n\n See `tf.distribute.StrategyExtended.reduce_to`. This can only be called in\n the cross-replica context.\n\nArgs:\n reduce_op: a `tf.distribute.ReduceOp` specifying how values should be\n combined.\n per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor`\n like object.\n destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a\n `tf.Tensor` alike object, or a device string. It specifies the devices\n to reduce to. To perform an all-reduce, pass the same to `value` and\n `destinations`. Note that if it's a `tf.Variable`, the value is reduced\n to the devices of that variable, and this method doesn't update the\n variable.\n options: a `tf.distribute.experimental.CommunicationOptions`. See\n `tf.distribute.experimental.CommunicationOptions` for details.\n\nReturns:\n A `tf.Tensor` or `tf.distribute.DistributedValues`.\n\nRaises:\n ValueError: if per_replica_value can't be converted to a\n `tf.distribute.DistributedValues` or if destinations is not a string,\n `tf.Variable` or `tf.distribute.DistributedValues`.", "source": "github_repos"} +{"code": "def keras_layer_tracepoint(layer, checkpoint_name):\n try:\n outputs = layer.output\n if tensor_util.is_tf_type(outputs):\n trace_tensor(outputs, '%s' % checkpoint_name)\n else:\n idx = 0\n for output_tensor in outputs:\n if tensor_util.is_tf_type(outputs):\n trace_tensor(output_tensor, '%s_%d' % (checkpoint_name, idx))\n idx += 1\n except AttributeError:\n pass\n except RuntimeError:\n pass\n return layer", "docstring": "An interface for adding the tensor outputs of a keras layer.\n\n Encapsulates trace_tensor.\n\nArgs:\n layer: A keras layer.\n checkpoint_name: a string name for the checkpoint. This name has to be a\n unique name if used within model comparison. The tensors that have the same\n checkpoint identifier is compared in model comparison.\n\nReturns:\n The provided layer.", "source": "github_repos"} +{"code": "def int64_user_counter(namespace, name, metric, ptransform=None) -> metrics_pb2.MonitoringInfo:\n labels = create_labels(ptransform=ptransform, namespace=namespace, name=name)\n if isinstance(metric, int):\n metric = coders.VarIntCoder().encode(metric)\n return create_monitoring_info(USER_COUNTER_URN, SUM_INT64_TYPE, metric, labels)", "docstring": "Return the counter monitoring info for the specifed URN, metric and labels.\n\nArgs:\n urn: The URN of the monitoring info/metric.\n metric: The payload field to use in the monitoring info or an int value.\n ptransform: The ptransform id used as a label.", "source": "github_repos"} +{"code": "def load_subset_weights_from_hdf5_group(f):\n weight_names = load_attributes_from_hdf5_group(f, 'weight_names')\n return [np.asarray(f[weight_name]) for weight_name in weight_names]", "docstring": "Load layer weights of a model from hdf5.\n\nArgs:\n f: A pointer to a HDF5 group.\n\nReturns:\n List of NumPy arrays of the weight values.\n\nRaises:\n ValueError: in case of mismatch between provided model\n and weights file.", "source": "github_repos"} +{"code": "def _subscribe_extend(tensor, side_effects):\n assert len(tensor.op.inputs) == 1, 'Op {} must only have one input'.format(tensor.op.name)\n source_tensor = tensor.op.inputs[0]\n outs = []\n name_scope = source_tensor.op.name + '/subscription/'\n with ops.name_scope(name_scope):\n for s in side_effects:\n outs += s(source_tensor)\n out_ops = [out.op if isinstance(out, tensor_lib.Tensor) else out for out in outs]\n tensor.op._add_control_inputs(out_ops)\n return tensor", "docstring": "Helper method to extend the list of side_effects for a subscribed tensor.\n\nArgs:\n tensor: A `tf.Tensor` as returned by subscribe().\n side_effects: List of side_effect functions, see subscribe for details.\n\nReturns:\n The given subscribed tensor (for API consistency).", "source": "github_repos"} +{"code": "def _add_while_inputs(self, tensors) -> None:\n with self.graph._c_graph.get() as c_graph:\n for tensor in tensors:\n if not isinstance(tensor, tensor_lib.Tensor):\n raise TypeError('tensor must be a Tensor: %s' % tensor)\n _assert_same_graph(self, tensor)\n self._inputs_val = None\n pywrap_tf_session.AddWhileInputHack(c_graph, tensor._as_tf_output(), self._c_op)", "docstring": "See AddWhileInputHack in python_api.h.\n\n NOTE: This is for TF internal use only. Please don't use it.\n\nArgs:\n tensors: list of Tensors\n\nRaises:\n TypeError: if tensor is not a Tensor,\n or if input tensor type is not convertible to dtype.\n ValueError: if the Tensor is from a different graph.", "source": "github_repos"} +{"code": "def _filter_top_k(x, k):\n _, top_k_idx = nn_ops.top_k(x, k, sorted=False)\n top_k_mask = math_ops.reduce_sum(array_ops.one_hot(top_k_idx, array_ops.shape(x)[-1], axis=-1), axis=-2)\n return x * top_k_mask + NEG_INF * (1 - top_k_mask)", "docstring": "Filters top-k values in the last dim of x and set the rest to NEG_INF.\n\n Used for computing top-k prediction values in dense labels (which has the same\n shape as predictions) for recall and precision top-k metrics.\n\nArgs:\n x: tensor with any dimensions.\n k: the number of values to keep.\n\nReturns:\n tensor with same shape and dtype as x.", "source": "github_repos"} +{"code": "def exp2(x):\n if any_symbolic_tensors((x,)):\n return Exp2().symbolic_call(x)\n return backend.numpy.exp2(x)", "docstring": "Calculate the base-2 exponential of all elements in the input tensor.\n\nArgs:\n x: Input tensor.\n\nReturns:\n Output tensor, element-wise base-2 exponential of `x`.", "source": "github_repos"} +{"code": "def __init__(self, spanner_configuration):\n self._spanner_configuration = spanner_configuration\n self._snapshot = None\n self._session = None\n self.base_labels = {monitoring_infos.SERVICE_LABEL: 'Spanner', monitoring_infos.METHOD_LABEL: 'Read', monitoring_infos.SPANNER_PROJECT_ID: self._spanner_configuration.project, monitoring_infos.SPANNER_DATABASE_ID: self._spanner_configuration.database}", "docstring": "A naive version of Spanner read which uses the transaction API of the\n cloud spanner.\n https://googleapis.dev/python/spanner/latest/transaction-api.html\n In Naive reads, this transform performs single reads, where as the\n Batch reads use the spanner partitioning query to create batches.\n\nArgs:\n spanner_configuration: (_BeamSpannerConfiguration) Connection details to\n connect with cloud spanner.", "source": "github_repos"} +{"code": "def jobs(self):\n return list(self._cluster_spec.keys())", "docstring": "Returns a list of job names in this cluster.\n\nReturns:\n A list of strings, corresponding to the names of jobs in this cluster.", "source": "github_repos"} +{"code": "def __init__(self, features: List[np.ndarray], timestamps: np.ndarray, schema: Optional[Schema]=None) -> None:\n \"\"\"Initializes the IndexData object by checking and setting the features\n and timestamps.\n\n Raises:\n ValueError: If features are not one-dimensional arrays.\n ValueError: If the number of elements in features and timestamps\n do not match.\n \"\"\"\n self.features = features\n self.timestamps = timestamps\n if schema is not None:\n self.check_schema(schema)", "docstring": "Features and timestamps data for a single index group.\n\n Note: The `schema` constructor argument is only used for checking. If\n `schema=None`, no checking is done. Checking can be done manually with\n `index_data.check_schema(...)`.\n\nAttributes:\n features: List of one-dimensional NumPy arrays representing the\n features.\n timestamps: One-dimensional NumPy array representing the timestamps.\n\n Usage example:\n ```\n >>> features = [np.array([1, 2, 3]), np.array([4, 5, 6])]\n >>> timestamps = np.array([0, 1, 2])\n >>> index_data = tp.IndexData(features, timestamps)\n >>> len(index_data)\n 3\n\n ```", "source": "github_repos"} +{"code": "def batch(iterable: Iterable[_T], n: int) -> Generator[tuple[_T, ...], None, None]:\n iterator = iter(iterable)\n while True:\n try:\n yield tuple([next(iterator) for _ in range(n)])\n except StopIteration:\n return", "docstring": "Splits an iterable into chunks of size n.\n\n TODO(ddunleavy): once python 3.12 is available, use itertools.batch.\n\nArgs:\n iterable: the iterable to batch.\n n: the number of elements in each batch.\n\nYields:\n A tuple of length n of the type that the iterable produces.", "source": "github_repos"} +{"code": "def __init__(self, input_qhbm: qhbm.QHBM):\n self.qhbm = input_qhbm", "docstring": "Initializes a QHBMData.\n\nArgs:\n qhbm: An inference engine for a QHBM.", "source": "github_repos"} +{"code": "def ensure_graph_is_valid(graph_def: graph_pb2.GraphDef) -> None:\n node_map = {}\n for node in graph_def.node:\n if node.name not in node_map:\n node_map[node.name] = node\n else:\n raise ValueError('Duplicate node names detected for ', node.name)\n for node in graph_def.node:\n for input_name in node.input:\n input_node_name = node_name_from_input(input_name)\n if input_node_name not in node_map:\n raise ValueError('Input for ', node.name, ' not found: ', input_name)", "docstring": "Makes sure that the graph is internally consistent.\n\n Checks basic properties of the graph def and raises an exception if there are\n input references to missing nodes, duplicated names, or other logic errors.\n\nArgs:\n graph_def: Definition of a graph to be checked.\n\nRaises:\n ValueError: If the graph is incorrectly constructed.", "source": "github_repos"} +{"code": "def _gather_beams(tensor: torch.Tensor, beam_indices: torch.Tensor) -> torch.Tensor:\n while len(beam_indices.shape) < len(tensor.shape):\n beam_indices = beam_indices.unsqueeze(-1)\n gathered_tensor = torch.take_along_dim(input=tensor, indices=beam_indices, dim=1)\n return gathered_tensor", "docstring": "Gathers the beam slices indexed by beam_indices into new beam array.\n\nArgs:\n tensor (`torch.Tensor`): A tensor containing data to be gathered. The tensor is a 2D or a 3D tensor\n with the two first dimensions depicting the batch and the beam dimensions.\n beam_indices (`torch.Tensor` of shape `(batch_size, num_beams_to_select)`): The indices of the beams to\n select .\n\nReturns:\n A tensor with the selected beams", "source": "github_repos"} +{"code": "def t0(self):\n return self._t0", "docstring": "Absolute timestamp of the first dumped tensor across all devices.\n\nReturns:\n (`int`) absolute timestamp of the first dumped tensor, in microseconds.", "source": "github_repos"} +{"code": "def get_all_supported_aspect_ratios(min_image_tiles: int, max_image_tiles: int) -> List[Tuple[int, int]]:\n aspect_ratios = []\n for width in range(1, max_image_tiles + 1):\n for height in range(1, max_image_tiles + 1):\n if width * height <= max_image_tiles and width * height >= min_image_tiles:\n aspect_ratios.append((width, height))\n aspect_ratios = sorted(aspect_ratios, key=lambda x: x[0] * x[1])\n return aspect_ratios", "docstring": "Computes all allowed aspect ratios for a given minimum and maximum number of input tiles.\n\n This function calculates all possible arrangements of tiles that can be formed\n within the constraint of the minimum and maximum number of tiles. Each arrangement is\n represented by its aspect ratio (width/height) and the corresponding tile configuration.\n\nArgs:\n min_image_tiles (`int`):\n The minimum number of tiles allowed.\n max_image_tiles (`int`):\n The maximum number of tiles allowed.\n\nReturns:\n `List[Tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)\n configuration in terms of number of tiles.\n\nExample:\n >>> get_all_supported_aspect_ratios(1, 4)\n [(1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (1, 4), (2, 2), (4, 1)]", "source": "github_repos"} +{"code": "def __init__(self, config, align_corners=True):\n super().__init__()\n self.align_corners = align_corners\n self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)\n self.residual_layer1 = ZoeDepthPreActResidualLayer(config)\n self.residual_layer2 = ZoeDepthPreActResidualLayer(config)", "docstring": "Feature fusion layer, merges feature maps from different stages.\n\nArgs:\n config (`[ZoeDepthConfig]`):\n Model configuration class defining the model architecture.\n align_corners (`bool`, *optional*, defaults to `True`):\n The align_corner setting for bilinear upsample.", "source": "github_repos"} +{"code": "def parse(a: t.Union[xr.DataArray, str], b: t.Union[xr.DataArray, str]) -> t.Tuple[t.Union[xr.DataArray, str], t.Union[xr.DataArray, str]]:\n if isinstance(a, str):\n a, b = (b, a)\n arr_type = a.dtype.name\n if arr_type == 'float64':\n b = np.float64(b)\n elif arr_type == 'float32':\n b = np.float32(b)\n elif arr_type == 'datetime64[ns]':\n b = np.datetime64(b)\n return (a, b)", "docstring": "Parse input values 'a' and 'b' into NumPy arrays with compatible types for evaluation.\n\n Parameters:\n - a (Union[xr.DataArray, str]): The first input value.\n - b (Union[xr.DataArray, str]): The second input value.\n\nReturns:\n - Tuple[xr.DataArray, Union[np.float64, np.float32, np.datetime64]]: Parsed NumPy arrays 'a' and 'b'.", "source": "github_repos"} +{"code": "def from_sparse(cls, st_input, name=None, row_splits_dtype=dtypes.int64):\n row_splits_dtype = dtypes.as_dtype(row_splits_dtype)\n if not sparse_tensor.is_sparse(st_input):\n raise TypeError(f'Argument `st_input` must be of type SparseTensor, but is of type {type(st_input).__name__}.')\n with ops.name_scope(name, 'RaggedFromSparse', [st_input]):\n st_input = sparse_tensor.convert_to_tensor_or_sparse_tensor(st_input, name='st_input')\n if st_input.dense_shape.shape.ndims is None:\n static_rank_from_dense_shape = None\n else:\n static_rank_from_dense_shape = st_input.dense_shape.shape.dims[0].value\n if st_input.indices.shape.ndims is None:\n static_rank_from_indices = None\n else:\n static_rank_from_indices = st_input.indices.shape.dims[1].value\n if static_rank_from_dense_shape != 2 and static_rank_from_indices != 2:\n raise ValueError('rank(st_input) must be 2.')\n with ops.control_dependencies(_assert_sparse_indices_are_ragged_right(st_input.indices)):\n segment_ids = math_ops.cast(st_input.indices[:, 0], row_splits_dtype)\n num_segments = math_ops.cast(st_input.dense_shape[0], row_splits_dtype)\n return cls.from_value_rowids(st_input.values, segment_ids, num_segments, validate=False)", "docstring": "Converts a 2D `tf.sparse.SparseTensor` to a `RaggedTensor`.\n\n Each row of the `output` `RaggedTensor` will contain the explicit values\n from the same row in `st_input`. `st_input` must be ragged-right. If not\n it is not ragged-right, then an error will be generated.\n\nExample:\n >>> indices = [[0, 0], [0, 1], [0, 2], [1, 0], [3, 0]]\n >>> st = tf.sparse.SparseTensor(indices=indices,\n ... values=[1, 2, 3, 4, 5],\n ... dense_shape=[4, 3])\n >>> tf.RaggedTensor.from_sparse(st).to_list()\n [[1, 2, 3], [4], [], [5]]\n\n Currently, only two-dimensional `SparseTensors` are supported.\n\nArgs:\n st_input: The sparse tensor to convert. Must have rank 2.\n name: A name prefix for the returned tensors (optional).\n row_splits_dtype: `dtype` for the returned `RaggedTensor`'s `row_splits`\n tensor. One of `tf.int32` or `tf.int64`.\n\nReturns:\n A `RaggedTensor` with the same values as `st_input`.\n `output.ragged_rank = rank(st_input) - 1`.\n `output.shape = [st_input.dense_shape[0], None]`.\n\nRaises:\n ValueError: If the number of dimensions in `st_input` is not known\n statically, or is not two.", "source": "github_repos"} +{"code": "def track(self, resource):\n if isinstance(resource, layers.Layer) and (not resource.built):\n raise ValueError('The layer provided has not yet been built. It must be built before export.')\n if isinstance(resource, tf.__internal__.tracking.Trackable):\n if not hasattr(self, '_tracked'):\n self._tracked = []\n self._tracked.append(resource)\n if isinstance(resource, layers.Layer):\n self._track_layer(resource)\n elif not isinstance(resource, tf.__internal__.tracking.Trackable):\n raise ValueError(f\"Invalid resource type. Expected a Keras `Layer` or `Model` or a TensorFlow `Trackable` object. Received object {resource} of type '{type(resource)}'. \")", "docstring": "Track the variables (of a layer or model) and other assets.\n\n By default, all variables used by an endpoint function are automatically\n tracked when you call `add_endpoint()`. However, non-variables assets\n such as lookup tables need to be tracked manually. Note that lookup\n tables used by built-in Keras layers (`TextVectorization`,\n `IntegerLookup`, `StringLookup`) are automatically tracked by\n `add_endpoint()`.\n\nArgs:\n resource: A layer, model or a TensorFlow trackable resource.", "source": "github_repos"} +{"code": "def _to_proto_str(self, for_publish=False):\n if len(self.data) > 10000000:\n raise ValueError('A pubsub message data field must not exceed 10MB')\n if self.attributes:\n if len(self.attributes) > 100:\n raise ValueError('A pubsub message must not have more than 100 attributes.')\n for key, value in self.attributes.items():\n if len(key) > 256:\n raise ValueError('A pubsub message attribute key must not exceed 256 bytes.')\n if len(value) > 1024:\n raise ValueError('A pubsub message attribute value must not exceed 1024 bytes')\n message_id = None\n publish_time = None\n if not for_publish:\n if self.message_id:\n message_id = self.message_id\n if self.publish_time:\n publish_time = self.publish_time\n if len(self.ordering_key) > 1024:\n raise ValueError('A pubsub message ordering key must not exceed 1024 bytes.')\n msg = pubsub.types.PubsubMessage(data=self.data, attributes=self.attributes, message_id=message_id, publish_time=publish_time, ordering_key=self.ordering_key)\n serialized = pubsub.types.PubsubMessage.serialize(msg)\n if len(serialized) > 10000000:\n raise ValueError('Serialized pubsub message exceeds the publish request limit of 10MB')\n return serialized", "docstring": "Get serialized form of ``PubsubMessage``.\n\n The serialized message is validated against pubsub message limits specified\n at https://cloud.google.com/pubsub/quotas#resource_limits\n\nArgs:\n proto_msg: str containing a serialized protobuf.\n for_publish: bool, if True strip out message fields which cannot be\n published (currently message_id and publish_time) per\n https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#pubsubmessage\n\nReturns:\n A str containing a serialized protobuf of type\n https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#google.pubsub.v1.PubsubMessage\n containing the payload of this object.", "source": "github_repos"} +{"code": "def ReadTimestamp(filename):\n if not os.path.exists(filename):\n return None\n try:\n timestamp_file = open(filename, 'r')\n timestamp_string = timestamp_file.read().strip()\n except IOError as e:\n logging.warning('error opening timestamp file: %s', e)\n timestamp_string = None\n else:\n timestamp_file.close()\n logging.debug('read timestamp %s from file %r', timestamp_string, filename)\n if timestamp_string is not None:\n try:\n timestamp = time.strptime(timestamp_string + ' UTC', '%Y-%m-%dT%H:%M:%SZ %Z')\n except ValueError as e:\n logging.error('cannot parse timestamp file %r: %s', filename, e)\n timestamp = None\n else:\n timestamp = None\n logging.debug('Timestamp is: %r', timestamp)\n now = time.gmtime()\n logging.debug(' Now is: %r', now)\n if timestamp > now:\n logging.warning('timestamp %r (%r) from %r is in the future, now is %r', timestamp_string, time.mktime(timestamp), filename, time.mktime(now))\n if time.mktime(timestamp) - time.mktime(now) >= 60 * 60:\n logging.info('Resetting timestamp to now.')\n timestamp = now\n return timestamp", "docstring": "Return a timestamp from a file.\n\n The timestamp file format is a single line, containing a string in the\n ISO-8601 format YYYY-MM-DDThh:mm:ssZ (i.e. UTC time). We do not support\n all ISO-8601 formats for reasons of convenience in the code.\n\n Timestamps internal to nss_cache deliberately do not carry milliseconds.\n\nArgs:\n filename: A String naming the file to read from.\n\nReturns:\n A time.struct_time, or None if the timestamp file doesn't\n exist or has errors.", "source": "github_repos"} +{"code": "def variable_sync_on_read_context():\n try:\n _variable_sync_on_read_context.entered = True\n yield\n finally:\n _variable_sync_on_read_context.entered = False", "docstring": "A context that forces SyncOnReadVariable to aggregate upon reading.\n\n This context is useful if one wants to read the aggregated value out of a\n SyncOnReadVariable in replica context. By default the aggregation is turned\n off per the definition of SyncOnReadVariable.\n\n When reading a SyncOnReadVariable in cross-replica context, aggregation is\n always turned on so there is no need for such context.\n\n By reading a SyncOnReadVariable, we mean:\n 1. Convert the variable to a tensor using `convert_to_tensor`.\n 2. Calling `variable.value()` or `variable.read_value()`.\n\n Example usage:\n\n ```\n strategy = tf.distribute.MirroredStrategy(devices=[\"GPU:0\", \"GPU:1\"])\n with strategy.scope():\n v = tf.Variable(1.0, synchronization=tf.VariableSynchronization.ON_READ,\n aggregation=tf.VariableAggregation.SUM)\n\n def replica_fn():\n return v + 10.0\n\n non_aggregated = strategy.run(replica_fn)\n print(non_aggregated) # PerReplica: {0: 11.0, 1: 11.0}\n\n def replica_fn():\n with variable_sync_on_read_context():\n return v + 10.0\n\n aggregated = strategy.run(replica_fn)\n print(aggregated) # PerReplica: {0: 12.0, 1: 12.0}\n ```\n\nYields:\n Context manager for aggregating SyncOnReadVariable upon reading.", "source": "github_repos"} +{"code": "def convert_nested_time_distributed(weights):\n return preprocess_weights_for_loading(layer.layer, weights, original_keras_version, original_backend)", "docstring": "Converts layers nested in `TimeDistributed` wrapper.\n\n This function uses `preprocess_weights_for_loading()` for converting nested\n layers.\n\nArgs:\n weights: List of weights values (Numpy arrays).\n\nReturns:\n A list of weights values (Numpy arrays).", "source": "github_repos"} +{"code": "def _orthogonal_kernel(self, ksize, cin, cout):\n if cin > cout:\n raise ValueError(f'The number of input channels (cin={cin}) cannot exceed the number of output channels (cout={cout}).')\n orth = self._orthogonal_matrix(cout)[0:cin, :]\n if ksize == 1:\n return array_ops.expand_dims(array_ops.expand_dims(array_ops.expand_dims(orth, 0), 0), 0)\n p = self._block_orth(self._symmetric_projection(cout), self._symmetric_projection(cout), self._symmetric_projection(cout))\n for _ in range(ksize - 2):\n temp = self._block_orth(self._symmetric_projection(cout), self._symmetric_projection(cout), self._symmetric_projection(cout))\n p = self._matrix_conv(p, temp)\n for i in range(ksize):\n for j in range(ksize):\n for k in range(ksize):\n p[i, j, k] = math_ops.matmul(orth, p[i, j, k])\n return self._dict_to_tensor(p, ksize, ksize, ksize)", "docstring": "Construct orthogonal kernel for convolution.\n\nArgs:\n ksize: Kernel size.\n cin: Number of input channels.\n cout: Number of output channels.\n\nReturns:\n An [ksize, ksize, ksize, cin, cout] orthogonal kernel.\n\nRaises:\n ValueError: If cin > cout.", "source": "github_repos"} +{"code": "def _unary_assert_doc(sym, sym_name):\n\n def _decorator(func):\n \"\"\"Generated decorator that adds the appropriate docstring to the function for symbol `sym`.\n\n Args:\n func: Function for a TensorFlow op\n\n Returns:\n Version of `func` with documentation attached.\n \"\"\"\n opname = func.__name__\n cap_sym_name = sym_name.capitalize()\n func.__doc__ = '\\n Assert the condition `x {sym}` holds element-wise.\\n\\n When running in graph mode, you should add a dependency on this operation\\n to ensure that it runs. Example of adding a dependency to an operation:\\n\\n ```python\\n with tf.control_dependencies([tf.debugging.{opname}(x, y)]):\\n output = tf.reduce_sum(x)\\n ```\\n\\n {sym_name} means, for every element `x[i]` of `x`, we have `x[i] {sym}`.\\n If `x` is empty this is trivially satisfied.\\n\\n Args:\\n x: Numeric `Tensor`.\\n data: The tensors to print out if the condition is False. Defaults to\\n error message and first few entries of `x`.\\n summarize: Print this many entries of each tensor.\\n message: A string to prefix to the default message.\\n name: A name for this operation (optional). Defaults to \"{opname}\".\\n\\n Returns:\\n Op that raises `InvalidArgumentError` if `x {sym}` is False.\\n @compatibility(eager)\\n returns None\\n @end_compatibility\\n\\n Raises:\\n InvalidArgumentError: if the check can be performed immediately and\\n `x {sym}` is False. The check can be performed immediately during\\n eager execution or if `x` is statically known.\\n '.format(sym=sym, sym_name=cap_sym_name, opname=opname)\n return func\n return _decorator", "docstring": "Common docstring for assert_* ops that evaluate a unary predicate over every element of a tensor.\n\nArgs:\n sym: Mathematical symbol for the check performed on each element, i.e. \"> 0\"\n sym_name: English-language name for the op described by sym\n\nReturns:\n Decorator that adds the appropriate docstring to the function for symbol\n `sym`.", "source": "github_repos"} +{"code": "def _as_serialized_graph(self, allow_stateful=None, strip_device_assignment=None, external_state_policy=options_lib.ExternalStatePolicy.WARN):\n if external_state_policy:\n policy = external_state_policy.value\n return gen_dataset_ops.dataset_to_graph_v2(self._variant_tensor, external_state_policy=policy, strip_device_assignment=strip_device_assignment)\n if strip_device_assignment:\n return gen_dataset_ops.dataset_to_graph(self._variant_tensor, allow_stateful=allow_stateful, strip_device_assignment=strip_device_assignment)\n return gen_dataset_ops.dataset_to_graph(self._variant_tensor, allow_stateful=allow_stateful)", "docstring": "Produces serialized graph representation of the dataset.\n\nArgs:\n allow_stateful: If true, we allow stateful ops to be present in the graph\n def. In that case, the state in these ops would be thrown away.\n strip_device_assignment: If true, non-local (i.e. job and task) device\n assignment is stripped from ops in the serialized graph.\n external_state_policy: The ExternalStatePolicy enum that determines how we\n handle input pipelines that depend on external state. By default, its\n set to WARN.\n\nReturns:\n A scalar `tf.Tensor` of `tf.string` type, representing this dataset as a\n serialized graph.", "source": "github_repos"} +{"code": "def get_polynomial_decay_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, lr_end=1e-07, power=1.0, last_epoch=-1):\n lr_init = optimizer.defaults['lr']\n if not lr_init > lr_end:\n raise ValueError(f'lr_end ({lr_end}) must be smaller than initial lr ({lr_init})')\n lr_lambda = partial(_get_polynomial_decay_schedule_with_warmup_lr_lambda, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, lr_end=lr_end, power=power, lr_init=lr_init)\n return LambdaLR(optimizer, lr_lambda, last_epoch)", "docstring": "Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the\n optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the\n initial lr set in the optimizer.\n\nArgs:\n optimizer ([`~torch.optim.Optimizer`]):\n The optimizer for which to schedule the learning rate.\n num_warmup_steps (`int`):\n The number of steps for the warmup phase.\n num_training_steps (`int`):\n The total number of training steps.\n lr_end (`float`, *optional*, defaults to 1e-7):\n The end LR.\n power (`float`, *optional*, defaults to 1.0):\n Power factor.\n last_epoch (`int`, *optional*, defaults to -1):\n The index of the last epoch when resuming training.\n\n Note: *power* defaults to 1.0 as in the fairseq implementation, which in turn is based on the original BERT\n implementation at\n https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/optimization.py#L37\n\nReturns:\n `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.", "source": "github_repos"} +{"code": "def unpack(self, dtensor: Any) -> Sequence[Any]:\n if not context.executing_eagerly():\n raise RuntimeError('`unpack` must be called eagerly.')\n try:\n tensors = _pywrap_dtensor_device.Unpack(context.context()._handle, dtensor, self._device_info)\n except core._NotOkStatusException as e:\n raise core._status_to_exception(e) from None\n is_sparse = _pywrap_dtensor_device.IsSparseDTensor(context.context()._handle, dtensor, self._device_info)\n if is_sparse:\n result = []\n for i in range(len(tensors) // 3):\n result.append(sparse_tensor.SparseTensor(tensors[i], tensors[i + len(tensors) // 3], tensors[i + 2 * len(tensors) // 3]))\n return result\n else:\n return tensors", "docstring": "Unpacks a DTensor handle on this DTensor device.\n\n Packing and unpacking are inverse operations:\n\n ```\n * unpack(pack(tensors)) == tensors\n * pack(unpack(dtensor)) == dtensor\n ```\n\n Refer to `dtensor.unpack` for more information.\n\nArgs:\n dtensor: The DTensor to unpack.\n\nReturns:\n The raw underlying tensor components of the DTensor.\n\nRaises:\n RuntimeError: When not called eagerly.", "source": "github_repos"} +{"code": "def pad_image(self, image: np.ndarray, pad_size: Optional[Dict[str, int]]=None, constant_values: Union[float, Iterable[float]]=0, pad_mode: PaddingMode=PaddingMode.CONSTANT, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs):\n height, width = get_image_size(image, channel_dim=input_data_format)\n max_height = pad_size.get('height', height)\n max_width = pad_size.get('width', width)\n pad_right, pad_bottom = (max_width - width, max_height - height)\n if pad_right < 0 or pad_bottom < 0:\n raise ValueError('The padding size must be greater than image size')\n padding = ((0, pad_bottom), (0, pad_right))\n padded_image = pad(image, padding, mode=pad_mode, constant_values=constant_values, data_format=data_format, input_data_format=input_data_format)\n return padded_image", "docstring": "Pad an image with zeros to the given size.\n\nArgs:\n image (`np.ndarray`):\n Image to pad.\n pad_size (`Dict[str, int]`)\n Size of the output image with pad.\n constant_values (`Union[float, Iterable[float]]`)\n The fill value to use when padding the image.\n pad_mode (`PaddingMode`)\n The pad mode, default to PaddingMode.CONSTANT\n data_format (`ChannelDimension` or `str`, *optional*)\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.", "source": "github_repos"} +{"code": "def parse_args():\n parser = argparse.ArgumentParser()\n parser.register('type', 'bool', lambda v: v.lower() == 'true')\n parser.add_argument('--max_steps', type=int, default=10, help='Number of steps to run trainer.')\n parser.add_argument('--train_batch_size', type=int, default=100, help='Batch size used during training.')\n parser.add_argument('--learning_rate', type=float, default=0.025, help='Initial learning rate.')\n parser.add_argument('--data_dir', type=str, default='/tmp/mnist_data', help='Directory for storing data')\n parser.add_argument('--ui_type', type=str, default='readline', help='Command-line user interface type (only readline is supported)')\n parser.add_argument('--fake_data', type='bool', nargs='?', const=True, default=False, help='Use fake MNIST data for unit testing')\n parser.add_argument('--debug', type='bool', nargs='?', const=True, default=False, help='Use debugger to track down bad values during training. Mutually exclusive with the --tensorboard_debug_address flag.')\n parser.add_argument('--tensorboard_debug_address', type=str, default=None, help='Connect to the TensorBoard Debugger Plugin backend specified by the gRPC address (e.g., localhost:1234). Mutually exclusive with the --debug flag.')\n parser.add_argument('--use_random_config_path', type='bool', nargs='?', const=True, default=False, help='If set, set config file path to a random file in the temporary\\n directory.')\n return parser.parse_known_args()", "docstring": "Parses commandline arguments.\n\nReturns:\n A tuple (parsed, unparsed) of the parsed object and a group of unparsed\n arguments that did not match the parser.", "source": "github_repos"} +{"code": "def num_accumulated(self, name=None):\n if name is None:\n name = '%s_NumAccumulated' % self._name\n return gen_data_flow_ops.accumulator_num_accumulated(self._accumulator_ref, name=name)", "docstring": "Number of gradients that have currently been aggregated in accumulator.\n\nArgs:\n name: Optional name for the operation.\n\nReturns:\n Number of accumulated gradients currently in accumulator.", "source": "github_repos"} +{"code": "def WriteMap(self, map_data=None, force_write=False):\n if map_data is None:\n writable_map = self.data\n else:\n writable_map = map_data\n entries_written = self.Write(writable_map)\n if entries_written is None:\n self.log.warning('cache write failed, exiting')\n return 1\n if force_write or self.Verify(entries_written):\n self._Commit()\n self.WriteIndex()\n return 0\n self.log.warning('verification failed, exiting')\n return 1", "docstring": "Write a map to disk.\n\nArgs:\n map_data: optional Map object to overwrite our current data with.\n force_write: optional flag to indicate verification checks can be\n ignored.\n\nReturns:\n 0 if succesful, 1 if not", "source": "github_repos"} +{"code": "def emit_obj_create(self, category: str, name: str, timestamp: int, pid: int, tid: int, object_id: int) -> None:\n event = self._create_event('N', category, name, pid, tid, timestamp)\n event['id'] = object_id\n self._events.append(event)", "docstring": "Adds an object creation event to the trace.\n\nArgs:\n category: The event category as a string.\n name: The event name as a string.\n timestamp: The timestamp of this event as a long integer.\n pid: Identifier of the process generating this event as an integer.\n tid: Identifier of the thread generating this event as an integer.\n object_id: Identifier of the object as an integer.", "source": "github_repos"} +{"code": "def report_files(config, auth, account, report_id):\n account_id, advertiser_id = parse_account(config, auth, account)\n is_superuser, profile_id = get_profile_for_api(config, auth, account_id)\n kwargs = {'profileId': profile_id, 'accountId': account_id} if is_superuser else {'profileId': profile_id}\n kwargs['reportId'] = report_id\n for report_file in API_DCM(config, auth, iterate=True, internal=is_superuser).reports().files().list(**kwargs).execute():\n yield report_file", "docstring": "Lists all the files available for a given DCM report configuration.\n\n Bulletproofing:\n https://developers.google.com/doubleclick-advertisers/v3.2/files/list\n\nArgs:\n * auth: (string) Either user or service.\n * account: (string) [account:advertiser@profile] token.\n * report_id: (int) DCM report identifier.\n\nReturns:\n * Iterator of JSONs.", "source": "github_repos"} +{"code": "def _create_beam_sdk(sdk_remote_location, temp_dir) -> List[beam_runner_api_pb2.ArtifactInformation]:\n sdk_remote_parsed = urlparse(sdk_remote_location)\n sdk_remote_filename = os.path.basename(sdk_remote_parsed.path)\n local_download_file = os.path.join(temp_dir, sdk_remote_filename)\n Stager._download_file(sdk_remote_location, local_download_file)\n staged_name = Stager._desired_sdk_filename_in_staging_location(local_download_file)\n _LOGGER.info('Staging Beam SDK from %s', sdk_remote_location)\n return [Stager._create_file_stage_to_artifact(local_download_file, staged_name)]", "docstring": "Creates a Beam SDK file with the appropriate version.\n\nArgs:\n sdk_remote_location: A URL from which the file can be downloaded or a\n remote file location. The SDK file can be a tarball or a wheel.\n temp_dir: path to temporary location where the file should be\n downloaded.\n\nReturns:\n A list of ArtifactInformation of local files path and SDK files that\n will be staged to the staging location.\n\nRaises:\n RuntimeError: if staging was not successful.", "source": "github_repos"} +{"code": "def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:\n size = get_size_dict(size, default_to_square=False)\n output_size = get_resize_output_image_size(image, size=(size['height'], size['width']), default_to_square=False, input_data_format=input_data_format)\n return resize(image, size=output_size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs)", "docstring": "Resize an image. The shortest edge of the image is resized to size[\"shortest_edge\"], with the longest edge\n resized to keep the input aspect ratio.\n\nArgs:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred from the input\n image.", "source": "github_repos"} +{"code": "def lookup(self, keys, name=None):\n key_tensor = keys\n if isinstance(keys, (sparse_tensor.SparseTensor, internal.RaggedTensor)):\n key_tensor = keys.values\n if keys.dtype.base_dtype != self._key_dtype:\n raise TypeError(f'Dtype of argument `keys` must be {self._key_dtype}, received: {keys.dtype}')\n with ops.name_scope(name, '%s_Lookup' % self.name, (self.resource_handle, key_tensor, self._default_value)):\n values = gen_lookup_ops.lookup_table_find_v2(self.resource_handle, key_tensor, self._default_value)\n values.set_shape(key_tensor.get_shape())\n if isinstance(keys, sparse_tensor.SparseTensor):\n return sparse_tensor.SparseTensor(keys.indices, values, keys.dense_shape)\n elif isinstance(keys, internal.RaggedTensor):\n return keys.with_values(values)\n else:\n return values", "docstring": "Looks up `keys` in a table, outputs the corresponding values.\n\n The `default_value` is used for keys not present in the table.\n\nArgs:\n keys: Keys to look up. May be either a `SparseTensor` or dense `Tensor`.\n name: A name for the operation (optional).\n\nReturns:\n A `SparseTensor` if keys are sparse, a `RaggedTensor` if keys are ragged,\n otherwise a dense `Tensor`.\n\nRaises:\n TypeError: when `keys` or `default_value` doesn't match the table data\n types.", "source": "github_repos"} +{"code": "def BuildParamsWithMask(self, graph_fn, dtype, input_shapes, output_shapes, input_mask, output_mask, extra_inputs, extra_outputs):\n\n def _ValidateShapes(shapes):\n for shape in shapes:\n assert all(shape), f'Shape unspecified: {shape}'\n _ValidateShapes(input_shapes)\n _ValidateShapes(output_shapes)\n assert len(input_mask) == len(input_shapes), f'Inconsistent input_mask and input_shapes: len({input_mask}) != len({input_shapes}).'\n assert len(output_mask) == len(output_shapes), f'Inconsistent output_mask and output_shapes: len({output_mask}) != len({output_shapes}).'\n for extra_in_shape, extra_out_shape in zip(extra_inputs, extra_outputs):\n assert len(input_shapes) == len(extra_in_shape), f'Inconsistent input_shapes and extra_in_shape: len({input_shapes}) != len({extra_in_shape}).'\n assert len(output_shapes) == len(extra_out_shape), f'Inconsistent output_shapes and extra_out_shape: len({output_shapes}) != len({extra_out_shape}).'\n return TfTrtIntegrationTestParams(graph_fn=graph_fn, input_specs=[self._GetTensorSpec(shape, mask, dtype, 'input_%d' % i) for i, (shape, mask) in enumerate(zip(input_shapes, input_mask))], output_specs=[self._GetTensorSpec(shape, mask, dtype, 'output_%d' % i) for i, (shape, mask) in enumerate(zip(output_shapes, output_mask))], input_dims=[input_shapes] + extra_inputs, expected_output_dims=[output_shapes] + extra_outputs)", "docstring": "Build test parameters with static or dynamic input shapes.\n\n To define dynamic shapes give a boolean mask that describes which\n dimensions to treat as known. The values in input_mask are interpreted the\n following way:\n - True: known dim (use the corresponding value from input_shapes)\n - False: unknown dim (replace the corresponding value from input_shapes\n with None)\n For example, to define the first two dimension with unknown size use\n input_shapes=[[1,2,1,8]], input_mask=[[False, False, True, True]].\n\nArgs:\n graph_fn: The function to build the graph.\n dtype: The element type.\n input_shapes: The input shapes.\n output_shapes: The output shapes.\n input_mask: The input shape masks.\n output_mask: the output shape masks.\n extra_inputs: list of additional input shapes\n extra_outputs: list of additional outputs shapes\n\nReturns:\n The test parameters.", "source": "github_repos"} +{"code": "def colored_block(text: str, block_start: str, block_end: str, color: Optional[str]=None, background: Optional[str]=None, styles: Optional[List[str]]=None) -> str:\n if not color and (not background) and (not styles):\n return text\n s = []\n start_index = 0\n end_index = 0\n previous_color = None\n\n def write_nonblock_text(text: str, previous_color: Optional[str]):\n if previous_color:\n s.append(previous_color)\n s.append(text)\n while start_index < len(text):\n start_index = text.find(block_start, end_index)\n if start_index == -1:\n write_nonblock_text(text[end_index:], previous_color)\n break\n since_last_block = text[end_index:start_index]\n write_nonblock_text(since_last_block, previous_color)\n colors = re.findall(_ANSI_COLOR_REGEX, since_last_block)\n if colors:\n previous_color = colors[-1]\n end_index = text.find(block_end, start_index + len(block_start))\n if end_index == -1:\n write_nonblock_text(text[start_index:], previous_color)\n break\n end_index += len(block_end)\n block = text[start_index:end_index]\n block = colored(block, color=color, background=background, styles=styles)\n s.append(block)\n return ''.join(s)", "docstring": "Apply colors to text blocks.\n\nArgs:\n text: A string that may or may not already has ANSI color characters.\n block_start: A string that signals the start of a block. E.g. '{{'\n block_end: A string that signals the end of a block. E.g. '}}'.\n color: A string for text colors. Applicable values are:\n 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'.\n background: A string for background colors. Applicable values are:\n 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'.\n styles: A list of strings for applying styles on the text.\n Applicable values are:\n 'bold', 'dark', 'underline', 'blink', 'reverse', 'concealed'.\n\nReturns:\n A string with ANSI color characters embracing the matched text blocks.", "source": "github_repos"} +{"code": "def moses_pipeline(self, text: str) -> List[str]:\n text = self.moses_punct_norm(text)\n text = self.moses_tokenize(text)\n text = tokenize_numbers(text)\n return text", "docstring": "Does basic tokenization using [`sacremoses.MosesPunctNormalizer`] and [`sacremoses.MosesTokenizer`] with\n *aggressive_dash_splits=True* (see [`sacremoses.tokenize.MosesTokenizer.tokenize`]). Additionally, large\n comma-separated numbers and floating point values are split. E.g. \"23,000 people are 1.80m tall\" -> \"23 @,@ 000\n people are 1 @.@ 80m tall\"\n\nArgs:\n text: Text to be tokenize\n\nReturns:\n A list of tokenized string\n\nExample:\n ```python\n >>> tokenizer = TransfoXLTokenizer.from_pretrained(\"transfo-xl/transfo-xl-wt103\")\n >>> tokenizer.moses_pipeline(\"23,000 people are 1.80 m tall\")\n ['23', '@,@', '000', 'people', 'are', '1', '@.@', '80', 'm', 'tall']\n ```", "source": "github_repos"} +{"code": "def _resource_apply_sparse_duplicate_indices(self, grad, handle, indices, **kwargs):\n summed_grad, unique_indices = _deduplicate_indexed_slices(values=grad, indices=indices)\n return self._resource_apply_sparse(summed_grad, handle, unique_indices, **kwargs)", "docstring": "Add ops to apply sparse gradients to `handle`, with repeated indices.\n\n Optimizers which override this method must deal with repeated indices. See\n the docstring of `_apply_sparse_duplicate_indices` for details. By default\n the correct behavior, to sum non-unique indices and their associated\n gradients, is enforced by first pre-processing `grad` and `indices` and\n passing them on to `_resource_apply_sparse`. Optimizers which deal correctly\n with duplicate indices may instead override this method to avoid the\n overhead of summing.\n\nArgs:\n grad: a `Tensor` representing the gradient for the affected indices.\n handle: a `Tensor` of dtype `resource` which points to the variable to be\n updated.\n indices: a `Tensor` of integral type representing the indices for which\n the gradient is nonzero. Indices may be repeated.\n **kwargs: May optionally contain `apply_state`\n\nReturns:\n An `Operation` which updates the value of the variable.", "source": "github_repos"} +{"code": "def __init__(self, proto_cls: Type[_T], handler: primitive_handler.PrimitiveHandler, resource_time_zone: str) -> None:\n self.proto_cls = proto_cls\n self.handler = handler\n self.resource_time_zone = resource_time_zone\n self.resources_by_uri: Dict[str, Union[Optional[_T], Dict[str, Any]]] = {}", "docstring": "A collection of FHIR resources of a given type.\n\nAttributes:\n archive_file: The zip or tar file path or a function returning a file-like\n proto_cls: The class of the proto this collection contains.\n handler: The FHIR primitive handler used for resource parsing.\n resource_time_zone: The time zone code to parse resource dates into.\n resources_by_uri: A map between URIs and the resource for that URI. Elements\n begin as JSON and are replaced with protos of type _T as they are\n accessed. For resources inside bundles, the JSON will be the bundle's JSON\n rather than the resource itself.", "source": "github_repos"} +{"code": "def isinf(x):\n if any_symbolic_tensors((x,)):\n return Isinf().symbolic_call(x)\n return backend.numpy.isinf(x)", "docstring": "Test element-wise for positive or negative infinity.\n\nArgs:\n x: Input tensor.\n\nReturns:\n Output boolean tensor.", "source": "github_repos"} +{"code": "def get_doc_dicts(self, doc_ids: np.ndarray) -> List[dict]:\n raise NotImplementedError", "docstring": "Returns a list of dictionaries, containing titles and text of the retrieved documents.\n\nArgs:\n doc_ids (`np.ndarray` of shape `(batch_size, n_docs)`):\n A tensor of document indices.", "source": "github_repos"} +{"code": "def __init__(self, trans, output_vertex, error_vertex):\n self.transition = trans\n self.output_vertex = output_vertex\n self.error_vertex = error_vertex", "docstring": "An edge of 2 graph.StateVertex's in state transition graph.\n\nAttributes:\n transition: state.Transition in state transition spec.\n output_vertext: graph.StateVertex matching with |transition|'s post_states.\n error_vertext: graph.StateVertex matching with |transition|'s error_states.", "source": "github_repos"} +{"code": "def list_children(self, obj, save_type=base.SaveType.CHECKPOINT, **kwargs):\n children = []\n for name, ref in super(ObjectGraphView, self).children(obj, save_type, **kwargs).items():\n children.append(base.TrackableReference(name, ref))\n if obj is self.root and self._attached_dependencies:\n children.extend(self._attached_dependencies)\n return children", "docstring": "Returns list of all child trackables attached to obj.\n\nArgs:\n obj: A `Trackable` object.\n save_type: A string, can be 'savedmodel' or 'checkpoint'.\n **kwargs: kwargs to use when retrieving the object's children.\n\nReturns:\n List of all children attached to the object.", "source": "github_repos"} +{"code": "def _get_stats(self):\n return _pywrap_dtensor_device.GetStats(context.context()._handle, self._device_info)", "docstring": "Returns the number of cache hit and miss for function compilation.\n\nReturns:\n A dictionary.\n 'miss': number of cache misses;\n 'hit': number of cache hits; and\n 'size': size of cache;\n miss count.", "source": "github_repos"} +{"code": "def resize_position_embeddings(self, new_num_position_embeddings: int):\n self.config.max_position_embeddings = new_num_position_embeddings\n self.model.decoder.resize_position_embeddings(new_num_position_embeddings)", "docstring": "Resizes position embeddings matrix of the model if `new_num_position_embeddings !=\n config.max_position_embeddings`.\n\nArgs:\n new_num_position_embeddings (`int`):\n The number of new position embeddings. If position embeddings are learned, increasing the size will add\n newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If\n position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will\n add correct vectors at the end following the position encoding algorithm, whereas reducing the size\n will remove vectors from the end.", "source": "github_repos"} +{"code": "def get_watermarks(self, applied_ptransform: AppliedPTransform) -> '_TransformWatermarks':\n while applied_ptransform.parts:\n applied_ptransform = applied_ptransform.parts[-1]\n return self._transform_to_watermarks[applied_ptransform]", "docstring": "Gets the input and output watermarks for an AppliedPTransform.\n\n If the applied_ptransform has not processed any elements, return a\n watermark with minimum value.\n\nArgs:\n applied_ptransform: AppliedPTransform to get the watermarks for.\n\nReturns:\n A snapshot (TransformWatermarks) of the input watermark and output\n watermark for the provided transform.", "source": "github_repos"} +{"code": "def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):\n\n def rotate_half_codec(x):\n x = x.reshape(*x.shape[:-1], -1, 2)\n x1, x2 = x.unbind(dim=-1)\n x = torch.stack((-x2, x1), dim=-1)\n return x.reshape(*x.shape[:-2], -1)\n cos = cos.unsqueeze(unsqueeze_dim)\n sin = sin.unsqueeze(unsqueeze_dim)\n q_embed = q * cos + rotate_half_codec(q) * sin\n k_embed = k * cos + rotate_half_codec(k) * sin\n return (q_embed, k_embed)", "docstring": "Applies Rotary Position Embedding to the query and key tensors.\n\nArgs:\n q (`torch.Tensor`): The query tensor.\n k (`torch.Tensor`): The key tensor.\n cos (`torch.Tensor`): The cosine part of the rotary embedding.\n sin (`torch.Tensor`): The sine part of the rotary embedding.\n position_ids (`torch.Tensor`, *optional*):\n Deprecated and unused.\n unsqueeze_dim (`int`, *optional*, defaults to 1):\n The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and\n sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note\n that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and\n k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes\n cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have\n the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.\n\nReturns:\n `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.", "source": "github_repos"} +{"code": "def get_setter(proto):\n _, type_registrations = _REVIVED_TYPE_REGISTRY.get(proto.identifier, (None, None))\n if type_registrations is not None:\n for type_registration in type_registrations:\n if type_registration.should_load(proto):\n return type_registration.setter\n return None", "docstring": "Gets the registered setter function for the SavedUserObject proto.\n\n See VersionedTypeRegistration for info about the setter function.\n\nArgs:\n proto: SavedUserObject proto\n\nReturns:\n setter function", "source": "github_repos"} +{"code": "def test_correctness_2_factor_hull_white_consistency(self, valuation_method, error_tol):\n dtype = tf.float64\n expiries = np.array([1.0])\n fixed_leg_payment_times = np.array([1.25, 1.5, 1.75, 2.0])\n fixed_leg_daycount_fractions = 0.25 * np.ones_like(fixed_leg_payment_times)\n fixed_leg_coupon = 0.011 * np.ones_like(fixed_leg_payment_times)\n zero_rate_fn = lambda x: 0.01 * tf.ones_like(x, dtype=dtype)\n mu = 0.03\n vol1 = 0.02\n vol2 = 0.01\n eff_vol = np.sqrt(vol1 ** 2 + vol2 ** 2)\n hjm_price = tff.models.hjm.swaption_price(expiries=expiries, fixed_leg_payment_times=fixed_leg_payment_times, fixed_leg_daycount_fractions=fixed_leg_daycount_fractions, fixed_leg_coupon=fixed_leg_coupon, reference_rate_fn=zero_rate_fn, notional=100.0, num_hjm_factors=2, mean_reversion=[mu, mu], volatility=[vol1, vol2], num_samples=25000, valuation_method=valuation_method, time_step_finite_difference=0.05, num_grid_points_finite_difference=251, time_step=0.1, random_type=tff.math.random.RandomType.STATELESS_ANTITHETIC, seed=[1, 2], dtype=dtype)\n hjm_price = self.evaluate(hjm_price)\n hw_price = tff.models.hull_white.swaption_price(expiries=expiries, floating_leg_start_times=[0], floating_leg_end_times=[0], floating_leg_daycount_fractions=[0], fixed_leg_payment_times=fixed_leg_payment_times, fixed_leg_daycount_fractions=fixed_leg_daycount_fractions, fixed_leg_coupon=fixed_leg_coupon, reference_rate_fn=zero_rate_fn, notional=100.0, mean_reversion=[mu], volatility=[eff_vol], use_analytic_pricing=True, dtype=dtype)\n hw_price = self.evaluate(hw_price)\n self.assertNear(hjm_price, hw_price, error_tol)", "docstring": "Test that under certain conditions HJM matches analytic HW results.\n\nArgs:\n valuation_method: The valuation method used.\n error_tol: Test error tolerance.\n\n For the two factor model, when both mean reversions are equivalent, then\n the HJM model matches that of a HW one-factor model with the same mean\n reversion, and effective volatility:\n eff_vol = sqrt(vol1^2 + vol2^2 + 2 rho(vol1 * vol2)\n where rho is the cross correlation between the two factors. In this\n specific test, we assume rho = 0.0.", "source": "github_repos"} +{"code": "def double(self, count=0):\n return 2 * count", "docstring": "Returns the input multiplied by 2.\n\nArgs:\n count: Input number that you want to double.\n\nReturns:\n A number that is the double of count.", "source": "github_repos"} +{"code": "def __init__(self, maximum_iterations=None, parallel_iterations=10, back_prop=True, swap_memory=False, name='while_context', grad_state=None, context_def=None, import_scope=None):\n if context_def:\n self._init_from_proto(context_def, import_scope=import_scope)\n else:\n ControlFlowContext.__init__(self)\n self._init_from_args(maximum_iterations, parallel_iterations, back_prop, swap_memory, name)\n self._grad_state = grad_state", "docstring": "\"Creates a `WhileContext`.\n\nArgs:\n maximum_iterations: Optional upper bound on number of loop iterations.\n parallel_iterations: The number of iterations allowed to run in parallel.\n back_prop: Whether backprop is enabled for this while loop.\n swap_memory: Whether GPU-CPU memory swap is enabled for this loop.\n name: Optional name prefix for the returned tensors.\n grad_state: The gradient loop state.\n context_def: Optional `WhileContextDef` protocol buffer to initialize the\n `Whilecontext` python object from.\n import_scope: Optional `string`. Name scope to add. Only used when\n initialing from protocol buffer.", "source": "github_repos"} +{"code": "def _check_input_partition_dims(self, tensor, dims):\n if dims is None:\n return\n dims = np.array(dims)\n if (dims < 1).any():\n raise ValueError('All input partition dims must be >= 1.')\n if dims.prod() == 1:\n return\n if dims.prod() != self._device_assignment.num_cores_per_replica:\n raise ValueError('The product of each input partition dim should equal to num_cores_per_replica. (dim = {}, num_cores_per_replica = {})'.format(dims, self._device_assignment.num_cores_per_replica))\n if dims.shape[0] != tensor.shape.ndims:\n raise ValueError('Input partition dims must have the same number of dimensions as the `Tensor` to be partitioned. (tensor shape = {}, input partition dims = {}).'.format(tensor.shape.as_list(), dims))\n tensor.shape.assert_is_fully_defined()", "docstring": "Checks that input partition dims are valid for the `Tensor`.\n\nArgs:\n tensor: Input tensor for partitioning.\n dims: A list of integer describes how to partition the input tensor.\n\nRaises:\n ValueError: If the tensor can't be partitioned by dims or the\n num_cores_per_replica doesn't match the number of\n partitions(dims.prod()).", "source": "github_repos"} +{"code": "def __init__(self, database_config: VectorDatabaseWriteConfig):\n if not isinstance(database_config, VectorDatabaseWriteConfig):\n raise TypeError(f'database_config must be VectorDatabaseWriteConfig, got {type(database_config)}')\n self.database_config = database_config", "docstring": "Initialize transform with database config.\n\nArgs:\n database_config: Configuration for target vector database.", "source": "github_repos"} +{"code": "def on_execution(self, execution_index, execution):", "docstring": "Monitor method for top-level execution events.\n\n Return values (if any) are ignored by the associated DebugDataReader.\n\nArgs:\n execution_index: The index of the top-level execution event, as an int.\n execution: An Execution data object, for a top-level op or function\n execution event.", "source": "github_repos"} +{"code": "def stage_job_resources(self, resources: List[Tuple[str, str, str]], staging_location: Optional[str]=None):\n if staging_location is None:\n raise RuntimeError('The staging_location must be specified.')\n staged_resources = []\n for file_path, staged_path, sha256 in resources:\n self.stage_artifact(file_path, FileSystems.join(staging_location, staged_path), sha256)\n staged_resources.append(staged_path)\n return staged_resources", "docstring": "For internal use only; no backwards-compatibility guarantees.\n\n Stages job resources to staging_location.\n\nArgs:\n resources: A list of tuples of local file paths and file names (no\n paths) to be used for staging resources.\n staging_location: Location to stage the file.\n\nReturns:\n A list of file names (no paths) for the resources staged. All the\n files are assumed to be staged at staging_location.\n\nRaises:\n RuntimeError: If files specified are not found or error encountered\n while trying to create the resources (e.g., build a setup package).", "source": "github_repos"} +{"code": "def __rdiv__(self, other):\n raise TypeError(\"unsupported operand type(s) for /: '{}' and 'Dimension', please use // instead\".format(type(other).__name__))", "docstring": "Use `__floordiv__` via `x // y` instead.\n\n This function exists only to have a better error message. Instead of:\n `TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'`,\n this function will explicitly call for usage of `//` instead.\n\nArgs:\n other: Another `Dimension`.\n\nRaises:\n TypeError.", "source": "github_repos"} +{"code": "def _make_dense_default(self, key, shape, dtype):\n default_value = self.dense_defaults.get(key)\n if shape.ndims is not None and shape.ndims > 0 and (shape.dims[0].value is None):\n if default_value is None:\n default_value = ops.convert_to_tensor('' if dtype == dtypes.string else 0, dtype=dtype)\n else:\n key_name = 'padding_' + re.sub('[^A-Za-z0-9_.\\\\-/]', '_', key)\n default_value = ops.convert_to_tensor(default_value, dtype=dtype, name=key_name)\n default_value = array_ops.reshape(default_value, [])\n elif default_value is None:\n default_value = constant_op.constant([], dtype=dtype)\n elif not isinstance(default_value, tensor.Tensor):\n key_name = 'key_' + re.sub('[^A-Za-z0-9_.\\\\-/]', '_', key)\n default_value = ops.convert_to_tensor(default_value, dtype=dtype, name=key_name)\n default_value = array_ops.reshape(default_value, shape)\n return default_value", "docstring": "Construct the default value tensor for a specified dense feature.\n\nArgs:\n key: The key string identifying the dense feature.\n shape: The dense feature's shape.\n dtype: The dense feature's dtype.\n\nReturns:\n A Tensor.", "source": "github_repos"} +{"code": "def __init__(self, sess, coord, stop_grace_period_secs=120):\n _WrappedSession.__init__(self, sess)\n self._coord = coord\n self._stop_grace_period_secs = stop_grace_period_secs", "docstring": "Create a new `_CoordinatedSession`.\n\nArgs:\n sess: A `tf.compat.v1.Session` object. The wrapped session.\n coord: A `tf.train.Coordinator` object.\n stop_grace_period_secs: Number of seconds given to threads to stop after\n `close()` has been called.", "source": "github_repos"} +{"code": "def replace_method_name(self, signature_key, method_name, tags=None):\n if not signature_key:\n raise ValueError('`signature_key` must be defined.')\n if not method_name:\n raise ValueError('`method_name` must be defined.')\n if tags is not None and (not isinstance(tags, list)):\n tags = [tags]\n found_match = False\n for meta_graph_def in self._saved_model.meta_graphs:\n if tags is None or set(tags) == set(meta_graph_def.meta_info_def.tags):\n if signature_key not in meta_graph_def.signature_def:\n raise ValueError(f\"MetaGraphDef associated with tags {tags} does not have a signature_def with key: '{signature_key}'. This means either you specified the wrong signature key or forgot to put the signature_def with the corresponding key in your SavedModel.\")\n meta_graph_def.signature_def[signature_key].method_name = method_name\n found_match = True\n if not found_match:\n raise ValueError(f'MetaGraphDef associated with tags {tags} could not be found in SavedModel. This means either you specified invalid tags or your SavedModel does not have a MetaGraphDef with the specified tags.')", "docstring": "Replaces the method_name in the specified signature_def.\n\n This will match and replace multiple sig defs iff tags is None (i.e when\n multiple `MetaGraph`s have a signature_def with the same key).\n If tags is not None, this will only replace a single signature_def in the\n `MetaGraph` with matching tags.\n\nArgs:\n signature_key: Key of the signature_def to be updated.\n method_name: new method_name to replace the existing one.\n tags: A tag or sequence of tags identifying the `MetaGraph` to update. If\n None, all meta graphs will be updated.\n\nRaises:\n ValueError: if signature_key or method_name are not defined or\n if no metagraphs were found with the associated tags or\n if no meta graph has a signature_def that matches signature_key.", "source": "github_repos"} +{"code": "def _align_output_features_output_indices(out_features: Optional[list[str]], out_indices: Optional[Union[list[int], tuple[int]]], stage_names: list[str]):\n if out_indices is None and out_features is None:\n out_indices = [len(stage_names) - 1]\n out_features = [stage_names[-1]]\n elif out_indices is None and out_features is not None:\n out_indices = [stage_names.index(layer) for layer in out_features]\n elif out_features is None and out_indices is not None:\n out_features = [stage_names[idx] for idx in out_indices]\n return (out_features, out_indices)", "docstring": "Finds the corresponding `out_features` and `out_indices` for the given `stage_names`.\n\n The logic is as follows:\n - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the\n `out_indices`.\n - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the\n `out_features`.\n - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.\n - `out_indices` and `out_features` set: input `out_indices` and `out_features` are returned.\n\nArgs:\n out_features (`List[str]`): The names of the features for the backbone to output.\n out_indices (`List[int]` or `Tuple[int]`): The indices of the features for the backbone to output.\n stage_names (`List[str]`): The names of the stages of the backbone.", "source": "github_repos"} +{"code": "def forward(self, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Zamba2HybridDynamicCache]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, cache_position: Optional[torch.LongTensor]=None, logits_to_keep: Union[int, torch.Tensor]=0, **loss_kwargs) -> Union[Tuple, CausalLMOutputWithPast]:\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, return_dict=return_dict)\n hidden_states = outputs[0]\n slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep\n logits = self.lm_head(hidden_states[:, slice_indices, :])\n loss = None\n if labels is not None:\n loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\nExample:\n ```python\n >>> from transformers import AutoTokenizer, Zamba2ForCausalLM\n\n >>> model = Zamba2ForCausalLM.from_pretrained(\"Zyphra/Zamba2-7B-v1\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"Zyphra/Zamba2-7B-v1\")\n\n >>> prompt = \"Hey, are you conscious? Can you talk to me?\"\n >>> inputs = tokenizer(prompt, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"Hey, are you conscious? Can you talk to me?\\nI'm not conscious, but I can talk to you.\"\n ```", "source": "github_repos"} +{"code": "def post_process_object_detection(self, outputs: 'GroundingDinoObjectDetectionOutput', threshold: float=0.1, target_sizes: Optional[Union[TensorType, List[Tuple]]]=None):\n batch_logits, batch_boxes = (outputs.logits, outputs.pred_boxes)\n batch_size = len(batch_logits)\n if target_sizes is not None and len(target_sizes) != batch_size:\n raise ValueError('Make sure that you pass in as many target sizes as images')\n batch_class_logits = torch.max(batch_logits, dim=-1)\n batch_scores = torch.sigmoid(batch_class_logits.values)\n batch_labels = batch_class_logits.indices\n batch_boxes = center_to_corners_format(batch_boxes)\n if target_sizes is not None:\n batch_boxes = _scale_boxes(batch_boxes, target_sizes)\n results = []\n for scores, labels, boxes in zip(batch_scores, batch_labels, batch_boxes):\n keep = scores > threshold\n scores = scores[keep]\n labels = labels[keep]\n boxes = boxes[keep]\n results.append({'scores': scores, 'labels': labels, 'boxes': boxes})\n return results", "docstring": "Converts the raw output of [`GroundingDinoForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,\n bottom_right_x, bottom_right_y) format.\n\nArgs:\n outputs ([`GroundingDinoObjectDetectionOutput`]):\n Raw outputs of the model.\n threshold (`float`, *optional*, defaults to 0.1):\n Score threshold to keep object detection predictions.\n target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):\n Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size\n `(height, width)` of each image in the batch. If unset, predictions will not be resized.\n\nReturns:\n `List[Dict]`: A list of dictionaries, each dictionary containing the following keys:\n - \"scores\": The confidence scores for each predicted box on the image.\n - \"labels\": Indexes of the classes predicted by the model on the image.\n - \"boxes\": Image bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format.", "source": "github_repos"} +{"code": "def _internal_operation_seed(self):\n return self._rng.randint(0, _MAXINT32)", "docstring": "Returns a fake operation seed.\n\n In eager mode, user shouldn't set or depend on operation seed.\n Here, we generate a random seed based on global seed to make\n operation's randomness different and depend on the global seed.\n\nReturns:\n A fake operation seed based on global seed.", "source": "github_repos"} +{"code": "def create_constructor_args(cls, proto_list: List[american_option_pb2.AmericanEquityOption], config: AmericanOptionConfig=None) -> Dict[str, Any]:\n am_option_data = proto_utils.from_protos(proto_list, config)\n res = {}\n for key in am_option_data:\n tensor_repr = proto_utils.tensor_repr(am_option_data[key])\n res[key] = tensor_repr\n return res", "docstring": "Creates a dictionary to initialize AmericanEquityOption.\n\n The output dictionary is such that the instruments can be initialized\n as follows:\n ```\n initializer = create_constructor_args(proto_list, config)\n american_options = [AmericanEquityOption(**data)\n for data in initializer.values()]\n ```\n\n The keys of the output dictionary are unique identifiers of the batched\n instruments. This is useful for identifying an existing graph that could be\n reused for the instruments without the need of rebuilding the graph.\n\nArgs:\n proto_list: A list of protos for which the initialization arguments are\n constructed.\n config: An instance of `AmericanOptionConfig`.\n\nReturns:\n A possibly nested dictionary such that each value provides initialization\n arguments for the AmericanEquityOption.", "source": "github_repos"} +{"code": "def __init__(self, name, state_callback, restore_callback):\n\n def _state_callback_wrapper():\n with ops.init_scope():\n return state_callback()\n self._state_callback = _state_callback_wrapper\n self._restore_callback = restore_callback\n with ops.device('/cpu:0'):\n self._save_string = constant_op.constant('', dtype=dtypes.string)\n spec = saveable_object.SaveSpec(self._save_string, '', name, dtype=dtypes.string)\n super(_PythonStringStateSaveable, self).__init__(self._save_string, [spec], name)", "docstring": "Configure saving.\n\nArgs:\n name: The checkpoint key to write to.\n state_callback: A function taking no arguments which returns a string.\n This function is run every time a checkpoint is written.\n restore_callback: A function taking a Python string, used to restore\n state.", "source": "github_repos"} +{"code": "def generate(self, pixel_values: torch.FloatTensor, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.LongTensor]=None, interpolate_pos_encoding: bool=False, **generate_kwargs) -> torch.LongTensor:\n if hasattr(self, 'hf_device_map'):\n self._preprocess_accelerate()\n batch_size = pixel_values.shape[0]\n image_embeds = self.vision_model(pixel_values, return_dict=True, interpolate_pos_encoding=interpolate_pos_encoding).last_hidden_state\n image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)\n query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)\n query_outputs = self.qformer(query_embeds=query_tokens, encoder_hidden_states=image_embeds, encoder_attention_mask=image_attention_mask, return_dict=True)\n query_output = query_outputs.last_hidden_state\n if query_output.dtype != image_embeds.dtype:\n query_output = query_output.to(image_embeds.dtype)\n language_model_inputs = self.language_projection(query_output)\n language_attention_mask = torch.ones(language_model_inputs.size()[:-1], dtype=torch.long, device=language_model_inputs.device)\n if input_ids is None:\n start_tokens = [self.config.text_config.bos_token_id]\n if getattr(self.config, 'image_token_id', None) is not None:\n start_tokens = [self.config.image_token_id] * self.config.num_query_tokens + start_tokens\n input_ids = torch.tensor([start_tokens], dtype=torch.long, device=image_embeds.device)\n input_ids = input_ids.repeat(batch_size, 1)\n inputs_embeds = self.get_input_embeddings()(input_ids)\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if getattr(self.config, 'image_token_id', None) is not None:\n special_image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)\n inputs_embeds[special_image_mask] = language_model_inputs.flatten()\n else:\n logger.warning_once('Expanding inputs for image tokens in BLIP-2 should be done in processing. Please follow instruction here (https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042) to update your BLIP-2 model. Using processors without these attributes in the config is deprecated and will throw an error in v4.50.')\n inputs_embeds = torch.cat([language_model_inputs, inputs_embeds.to(language_model_inputs.device)], dim=1)\n attention_mask = torch.cat([language_attention_mask, attention_mask.to(language_attention_mask.device)], dim=1)\n if not self.language_model.config.is_encoder_decoder:\n generate_kwargs['max_length'] = generate_kwargs.get('max_length', 20) + language_model_inputs.shape[1] - 1\n generate_kwargs['min_length'] = generate_kwargs.get('min_length', 0) + language_model_inputs.shape[1]\n inputs = {'inputs_embeds': inputs_embeds, 'attention_mask': attention_mask}\n if not self.language_model.config.is_encoder_decoder:\n inputs['input_ids'] = input_ids\n outputs = self.language_model.generate(**inputs, **generate_kwargs)\n return outputs", "docstring": "Overrides `generate` function to be able to use the model as a conditional generator.\n\nArgs:\n pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):\n Input images to be processed.\n input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n The sequence used as a prompt for the generation.\n attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):\n Mask to avoid performing attention on padding token indices\n\nReturns:\n captions (list): A list of strings of length batch_size * num_captions.", "source": "github_repos"} +{"code": "def on_graph_execution_trace(self, graph_execution_trace_index, graph_execution_trace):", "docstring": "Monitor method for intra-graph execution events.\n\n Return values (if any) are ignored by the associated DebugDataReader.\n\nArgs:\n graph_execution_trace_index: The index of the intra-graph execution\n event, as an int.\n graph_execution_trace: A GraphExecutionTrace data object, for an\n intra-graph tensor event.", "source": "github_repos"} +{"code": "def logsumexp(x, axis=None, keepdims=None):\n return tf_np.asarray(math_ops.reduce_logsumexp(input_tensor=x, axis=axis, keepdims=keepdims))", "docstring": "Computes log(sum(exp(elements across dimensions of a tensor))).\n\n Reduces `x` along the dimensions given in `axis`.\n Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each\n entry in `axis`. If `keepdims` is true, the reduced dimensions\n are retained with length 1.\n If `axis` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n This function is more numerically stable than log(sum(exp(input))). It avoids\n overflows caused by taking the exp of large inputs and underflows caused by\n taking the log of small inputs.\n\nArgs:\n x: The tensor to reduce. Should have numeric type.\n axis: The dimensions to reduce. If `None` (the default), reduces all\n dimensions. Must be in the range `[-rank(x), rank(x))`.\n keepdims: If true, retains reduced dimensions with length 1.\n\nReturns:\n The reduced tensor.", "source": "github_repos"} +{"code": "def _compute_posterior(self, likelihoods_watermarked: torch.Tensor, likelihoods_unwatermarked: torch.Tensor, mask: torch.Tensor, prior: float) -> torch.Tensor:\n mask = torch.unsqueeze(mask, dim=-1)\n prior = torch.clamp(prior, min=1e-05, max=1 - 1e-05)\n log_likelihoods_watermarked = torch.log(torch.clamp(likelihoods_watermarked, min=1e-30, max=float('inf')))\n log_likelihoods_unwatermarked = torch.log(torch.clamp(likelihoods_unwatermarked, min=1e-30, max=float('inf')))\n log_odds = log_likelihoods_watermarked - log_likelihoods_unwatermarked\n relative_surprisal_likelihood = torch.einsum('i...->i', log_odds * mask)\n relative_surprisal_prior = torch.log(prior) - torch.log(1 - prior)\n relative_surprisal = relative_surprisal_prior + relative_surprisal_likelihood\n return torch.sigmoid(relative_surprisal)", "docstring": "Compute posterior P(w|g) given likelihoods, mask and prior.\n\nArgs:\n likelihoods_watermarked (`torch.Tensor` of shape `(batch, length, depth)`):\n Likelihoods P(g_values|watermarked) of g-values under watermarked model.\n likelihoods_unwatermarked (`torch.Tensor` of shape `(batch, length, depth)`):\n Likelihoods P(g_values|unwatermarked) of g-values under unwatermarked model.\n mask (`torch.Tensor` of shape `(batch, length)`):\n A binary array indicating which g-values should be used. g-values with mask value 0 are discarded.\n prior (`float`):\n the prior probability P(w) that the text is watermarked.\n\nReturns:\n Posterior probability P(watermarked|g_values), shape [batch].", "source": "github_repos"} +{"code": "def _create_pseudo_names(tensors, prefix):\n\n def one_index(ele):\n if isinstance(ele, int):\n return ele + 1\n return ele\n flat_paths = list(nest.yield_flat_paths(tensors))\n flat_paths = nest.map_structure(one_index, flat_paths)\n names = []\n for path in flat_paths:\n if not path:\n name = prefix + '1'\n else:\n name = '_'.join((str(p) for p in path))\n if isinstance(path[0], int):\n name = prefix + name\n names.append(name)\n return names", "docstring": "Creates pseudo {input | output} names for subclassed Models.\n\n Warning: this function should only be used to define default\n names for `Metics` and `SavedModel`. No other use cases should\n rely on a `Model`'s input or output names.\n\n Example with dict:\n\n `{'a': [x1, x2], 'b': x3}` becomes:\n `['a_1', 'a_2', 'b']`\n\n Example with list:\n\n `[x, y]` becomes:\n `['output_1', 'output_2']`\n\nArgs:\n tensors: `Model`'s outputs or inputs.\n prefix: 'output_' for outputs, 'input_' for inputs.\n\nReturns:\n Flattened list of pseudo names.", "source": "github_repos"} +{"code": "def run_tac(model_path, targets, output_path):\n if not model_path:\n raise ValueError('Invalid model_path.')\n if not targets:\n raise ValueError('Targets are not specified.')\n if not output_path:\n raise ValueError('Invalid output_path.')\n return _pywrap_tac_wrapper.run_tac(model_path, targets, output_path)", "docstring": "Run target aware conversion for the given tflite model file.\n\nArgs:\n model_path: Path to the tflite model file.\n targets: A list of string of the desired targets. E.g., ['GPU', 'CPU'].\n output_path: The output path.\n\nReturns:\n Whether the optimization succeeded.\n\nRaises:\n ValueError:\n Invalid model_path.\n Targets are not specified.\n Invalid output_path.", "source": "github_repos"} +{"code": "def from_list(index, queues):\n if not queues or not isinstance(queues, list) or (not all((isinstance(x, QueueBase) for x in queues))):\n raise TypeError('A list of queues expected')\n dtypes = queues[0].dtypes\n if not all((dtypes == q.dtypes for q in queues[1:])):\n raise TypeError('Queues do not have matching component dtypes.')\n names = queues[0].names\n if not all((names == q.names for q in queues[1:])):\n raise TypeError('Queues do not have matching component names.')\n queue_shapes = [q.shapes for q in queues]\n reduced_shapes = [functools.reduce(_shape_common, s) for s in zip(*queue_shapes)]\n queue_refs = array_ops_stack.stack([x.queue_ref for x in queues])\n selected_queue = array_ops.gather(queue_refs, index)\n return QueueBase(dtypes=dtypes, shapes=reduced_shapes, names=names, queue_ref=selected_queue)", "docstring": "Create a queue using the queue reference from `queues[index]`.\n\nArgs:\n index: An integer scalar tensor that determines the input that gets\n selected.\n queues: A list of `QueueBase` objects.\n\nReturns:\n A `QueueBase` object.\n\nRaises:\n TypeError: When `queues` is not a list of `QueueBase` objects,\n or when the data types of `queues` are not all the same.", "source": "github_repos"} +{"code": "def AddBackpropLoopCounter(self, count, outer_grad_state):\n in_separate_functions = count.graph is not ops.get_default_graph()\n if in_separate_functions:\n count = array_ops.identity(count)\n else:\n one = constant_op.constant(1, name='b_count')\n self.Enter()\n self.AddName(count.name)\n enter_count = _Enter(count, self._name, is_constant=False, parallel_iterations=self._parallel_iterations, name='b_count')\n self.loop_enters.append(enter_count)\n merge_count = merge([enter_count, enter_count])[0]\n self._pivot_for_pred = merge_count\n if in_separate_functions:\n one = constant_op.constant(1, name='b_count')\n pred = math_ops.greater_equal(merge_count, one)\n self._pivot = loop_cond(pred, name='b_count')\n switch_count = switch(merge_count, self._pivot)\n index = math_ops.subtract(switch_count[1], one)\n self._pivot_for_body = index\n next_count = _NextIteration(index)\n merge_count.op._update_input(1, next_count)\n final_zero = exit(switch_count[0], name='b_count')\n self.loop_exits.append(final_zero)\n if outer_grad_state is not None:\n outer_grad_state.grad_sync._add_control_input(final_zero.op)\n self.ExitResult([final_zero])\n self.Exit()\n return next_count", "docstring": "Add the backprop loop that controls the iterations.\n\n This is added to the backprop loop. It is used to control the loop\n termination of the backprop loop. Called in the outer context of\n this grad context.\n\n The pseudocode is:\n `n = count; while (n >= 1) { n--; }`\n\n Note that a control dependency is added to `final_zero` to ensure the\n correct execution order of stack pop ops.\n\nArgs:\n count: The number of iterations for backprop.\n outer_grad_state: The outer grad state. None if not nested.\n\nReturns:\n The loop index.", "source": "github_repos"} +{"code": "def __init__(self) -> None:\n self.errors: List[str] = []\n self.warnings: List[str] = []", "docstring": "A delegate for FHIRPath encoding errors.\n\n Errors are logged to the corresponding `logging` context (e.g. \"warning\" or\n \"error\") and any encountered messages are stored in the corresponding\n attribute (`warnings` and `errors`, respectively). These can then be retrieved\n by the caller within the context of the larger system.\n\nAttributes:\n errors: A list of error messages encountered.\n warnings: A list of warning messages encountered.", "source": "github_repos"} +{"code": "def _segment_reduce(values, index, segment_reduce_fn, name):\n flat_index = flatten(index)\n vector_shape = values.size()[len(index.indices.size()):]\n flattened_shape = torch.cat([torch.as_tensor([-1], dtype=torch.long), torch.as_tensor(vector_shape, dtype=torch.long)], dim=0)\n flat_values = values.reshape(flattened_shape.tolist())\n out = torch.zeros(int(flat_index.num_segments), dtype=torch.float, device=flat_values.device)\n segment_means = out.scatter_reduce(dim=0, index=flat_index.indices.long(), src=flat_values.float(), reduce=segment_reduce_fn, include_self=False)\n device = index.num_segments.device\n new_shape = torch.cat([torch.as_tensor(index.batch_shape(), dtype=torch.long, device=device), torch.as_tensor([index.num_segments], dtype=torch.long, device=device), torch.as_tensor(vector_shape, dtype=torch.long, device=device)], dim=0)\n output_values = segment_means.clone().view(new_shape.tolist()).to(values.dtype)\n output_index = range_index_map(index.batch_shape(), index.num_segments)\n return (output_values, output_index)", "docstring": "Applies a segment reduction segment-wise.\n\nArgs:\n values (`torch.Tensor`):\n Tensor with segment values.\n index (`IndexMap`):\n IndexMap.\n segment_reduce_fn (`str`):\n Name for the reduce operation. One of \"sum\", \"mean\", \"max\" or \"min\".\n name (`str`):\n Name for the operation. Currently not used\n\nReturns:\n (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).", "source": "github_repos"} +{"code": "def _Commands(component, depth=3):\n if inspect.isroutine(component) or inspect.isclass(component):\n for completion in Completions(component, verbose=False):\n yield (completion,)\n if inspect.isroutine(component):\n return\n if depth < 1:\n return\n for member_name, member in VisibleMembers(component, class_attrs={}, verbose=False):\n member_name = _FormatForCommand(member_name)\n yield (member_name,)\n for command in _Commands(member, depth - 1):\n yield ((member_name,) + command)", "docstring": "Yields tuples representing commands.\n\n To use the command from Python, insert '.' between each element of the tuple.\n To use the command from the command line, insert ' ' between each element of\n the tuple.\n\nArgs:\n component: The component considered to be the root of the yielded commands.\n depth: The maximum depth with which to traverse the member DAG for commands.\n\nYields:\n Tuples, each tuple representing one possible command for this CLI.\n Only traverses the member DAG up to a depth of depth.", "source": "github_repos"} +{"code": "def __init__(self, config):\n super().__init__()\n self.config = config\n self.layers = nn.ModuleList()\n for channels, factor in zip(config.neck_hidden_sizes, config.reassemble_factors):\n self.layers.append(PromptDepthAnythingReassembleLayer(config, channels=channels, factor=factor))", "docstring": "This class reassembles the hidden states of the backbone into image-like feature representations at various\n resolutions.\n\n This happens in 3 stages:\n 1. Take the patch embeddings and reshape them to image-like feature representations.\n 2. Project the channel dimension of the hidden states according to `config.neck_hidden_sizes`.\n 3. Resizing the spatial dimensions (height, width).\n\nArgs:\n config (`[PromptDepthAnythingConfig]`):\n Model configuration class defining the model architecture.", "source": "github_repos"} +{"code": "def use_wrapped_call(layer, call_fn, default_training_value=None, return_method=False):\n expects_training_arg = layer_uses_training_bool(layer)\n if hasattr(call_fn, 'original_layer_call'):\n original_call = call_fn.original_layer_call\n call_fn = call_fn.__call__\n else:\n original_call = call_fn\n fn, arg_spec = maybe_add_training_arg(original_call, call_fn, expects_training_arg, default_training_value)\n\n def return_outputs_and_add_losses(*args, **kwargs):\n \"\"\"Returns the outputs from the layer call function, and adds the losses.\"\"\"\n if return_method:\n args = args[1:]\n outputs, losses = fn(*args, **kwargs)\n layer.add_loss(losses, inputs=True)\n if context.executing_eagerly():\n for i in layer._flatten_layers():\n if i is not layer:\n i._eager_losses = [base_layer_utils.REVIVED_LOSS_PLACEHOLDER]\n return outputs\n decorated = tf_decorator.make_decorator(target=call_fn, decorator_func=return_outputs_and_add_losses, decorator_argspec=arg_spec)\n if return_method:\n return types.MethodType(decorated, layer)\n else:\n return decorated", "docstring": "Creates fn that adds the losses returned by call_fn & returns the outputs.\n\nArgs:\n layer: A Keras layer object\n call_fn: tf.function that takes layer inputs (and possibly a training arg),\n and returns a tuple of (outputs, list of losses).\n default_training_value: Default value of the training kwarg. If `None`, the\n default is `K.learning_phase()`.\n return_method: Whether to return a method bound to the layer.\n\nReturns:\n function that calls call_fn and returns the outputs. Losses returned by\n call_fn are added to the layer losses.", "source": "github_repos"} +{"code": "def auto_cast_partition_dtype():\n return False", "docstring": "Whether incompatible row-partitioning dtypes should be auto-converted.\n\n If true, then operations that combine RaggedTensors but have different\n row-partitioning tensor dtypes will be automatically cast to a\n compatible dtype (`tf.int64`). If false, then such operations will result\n in an error.\n\nReturns:\n `bool`", "source": "github_repos"} +{"code": "def scatter(indices, values, shape):\n if any_symbolic_tensors((indices, values)):\n return Scatter(shape=shape).symbolic_call(indices, values)\n return backend.core.scatter(indices, values, shape)", "docstring": "Returns a tensor of shape `shape` where `indices` are set to `values`.\n\n At a high level, this operation does `zeros[indices] = updates` and\n returns the output. It is equivalent to:\n\n ```python\n zeros = keras.ops.zeros(shape)\n output = keras.ops.scatter_update(zeros, indices, values)\n ```\n\nArgs:\n indices: A tensor or list/tuple specifying\n indices for the values in `values`.\n values: A tensor, the values to be set at `indices`.\n shape: Shape of the output tensor.\n\nExample:\n >>> indices = [[0, 1], [1, 1]]\n >>> values = np.array([1., 1.])\n >>> keras.ops.scatter(indices, values, shape=(2, 2))\n array([[0., 1.],\n [0., 1.]])", "source": "github_repos"} +{"code": "def forward(self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor]=None, pos_emb: Optional[torch.Tensor]=None, output_attentions: Optional[torch.Tensor]=False) -> Tuple[torch.Tensor, torch.Tensor]:\n bsz, q_len, _ = hidden_states.size()\n query_states = self.linear_q(hidden_states).view(bsz, -1, self.num_heads, self.head_dim)\n key_states = self.linear_k(hidden_states).view(bsz, -1, self.num_heads, self.head_dim)\n value_states = self.linear_v(hidden_states).view(bsz, -1, self.num_heads, self.head_dim)\n bsz_pos = pos_emb.size(0)\n pos_encoding = self.linear_pos(pos_emb).view(bsz_pos, -1, self.num_heads, self.head_dim)\n query_with_bias_u = (query_states + self.pos_bias_u).transpose(1, 2)\n query_with_bias_v = (query_states + self.pos_bias_v).transpose(1, 2)\n matrix_ac = torch.matmul(query_with_bias_u, key_states.permute(0, 2, 3, 1))\n matrix_bd = torch.matmul(query_with_bias_v, pos_encoding.permute(0, 2, 3, 1))\n matrix_bd = self.shift_relative_position_tensor(matrix_bd)\n scores = (matrix_ac + matrix_bd) / math.sqrt(self.dim_key)\n if attention_mask is not None:\n expected_size = (bsz, 1, q_len)\n if attention_mask.size() != expected_size:\n raise ValueError(f'Attention mask should be of size {expected_size}, but is {attention_mask.size()}')\n attention_mask = attention_mask.unsqueeze(1).eq(0)\n min_value = float(torch.finfo(scores.dtype).min)\n scores = scores.masked_fill(attention_mask, min_value)\n attn_weights = torch.softmax(scores, dim=-1).masked_fill(attention_mask, 0.0)\n else:\n attn_weights = torch.softmax(scores, dim=-1)\n attn_weights = self.dropout(attn_weights)\n attn_output = torch.matmul(attn_weights, value_states.transpose(1, 2))\n attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, q_len, -1)\n attn_output = self.linear_out(attn_output)\n if not output_attentions:\n attn_weights = None\n return (attn_output, attn_weights)", "docstring": "Compute 'Scaled Dot Product Attention' with rel. positional encoding.\n\nArgs:\n hidden_states (`torch.Tensor` of shape `(batch, time2, size)`): Values of the hidden states\n attention_mask (`torch.Tensor` of shape `(batch, time1, time2)`): Mask tensor.\n pos_emb (`torch.Tensor` of shape `(batch, 2*time1-1, size)`): Positional embedding tensor.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n\nReturns:\n `torch.Tensor`: Output tensor of shape `(batch, time1, d_model)`.", "source": "github_repos"} +{"code": "def convert(self):\n if not _jit:\n raise ImportError('Cannot import jit from jax.')\n if not self._serving_funcs:\n raise ValueError('No serving func is specified.')\n if not self._inputs:\n raise ValueError('Input tensors are not specified.')\n if len(self._inputs) != len(self._serving_funcs):\n msg = 'Input tensor mapping len {} does not match serving func len {}.'.format(len(self._inputs), len(self._serving_funcs))\n raise ValueError(msg)\n if not isinstance(self._inputs, (tuple, list)):\n raise ValueError('Input tensors should be pass in a tuple list wrapped in an array.')\n if len(self._serving_funcs) > 1:\n raise ValueError('Currently only support single serving function.')\n if not isinstance(self._inputs[0], (tuple, list)):\n raise ValueError('The input placeholders are not a dictionary.')\n input_names = []\n ordered_inputs = []\n for input_name, tensor in self._inputs[0]:\n input_names.append(input_name)\n ordered_inputs.append(tensor)\n try:\n hlo_proto = _jit(self._serving_funcs[0]).trace(*ordered_inputs).lower(lowering_platforms=('cpu',)).compiler_ir('hlo').as_serialized_hlo_module_proto()\n except Exception:\n raise ValueError('Failed to convert the given Jax function to hlo.')\n converter_kwargs = {'input_content': hlo_proto, 'input_names': input_names, 'is_proto_format': True}\n converter_kwargs.update(self._get_base_converter_args())\n quant_mode = QuantizationMode(self.optimizations, self.target_spec, self.representative_dataset, None, experimental_qdq_annotation=self._experimental_strict_qdq)\n self._validate_inference_input_output_types(quant_mode)\n converter_kwargs.update(quant_mode.converter_flags())\n result = _convert_jax_hlo(**converter_kwargs)\n return self._optimize_tflite_model(result, quant_mode, _build_conversion_flags(**converter_kwargs).debug_options, quant_io=self.experimental_new_quantizer)", "docstring": "Converts a Jax serving func based on instance variables.\n\nReturns:\n The converted data in serialized format.\n\nRaises:\n ImportError:\n If cannot import the jit from jax.\n ValueError:\n No serving function is specified.\n Input tensors are not specified.\n The truth value of an array with more than one element is ambiguous.\n Failed to convert the given Jax function to hlo.", "source": "github_repos"} +{"code": "def __init__(self, config: JetMoeConfig):\n super(JetMoeMoE, self).__init__()\n self.input_size = config.hidden_size\n self.hidden_size = config.intermediate_size\n self.activation = ACT2FN[config.activation_function]\n self.bias = torch.nn.Parameter(torch.empty(self.input_size))\n self.input_linear = JetMoeParallelExperts(config.num_local_experts, self.input_size, self.hidden_size * 2)\n self.output_linear = JetMoeParallelExperts(config.num_local_experts, self.hidden_size, self.input_size)\n self.router = JetMoeTopKGating(input_size=self.input_size, num_experts=config.num_local_experts, top_k=config.num_experts_per_tok)", "docstring": "A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.\n\nArgs:\n config:\n Configuration object with model hyperparameters.", "source": "github_repos"} +{"code": "def _render_node_traceback(self, node_name):\n lines = [RL(''), RL(''), RL('Traceback of node construction:', 'bold')]\n try:\n node_stack = self._debug_dump.node_traceback(node_name)\n for depth, (file_path, line, function_name, text) in enumerate(node_stack):\n lines.append('%d: %s' % (depth, file_path))\n attribute = debugger_cli_common.MenuItem('', 'ps %s -b %d' % (file_path, line)) if text else None\n line_number_line = RL(' ')\n line_number_line += RL('Line: %d' % line, attribute)\n lines.append(line_number_line)\n lines.append(' Function: %s' % function_name)\n lines.append(' Text: ' + ('\"%s\"' % text if text else 'None'))\n lines.append('')\n except KeyError:\n lines.append('(Node unavailable in the loaded Python graph)')\n except LookupError:\n lines.append('(Unavailable because no Python graph has been loaded)')\n return debugger_cli_common.rich_text_lines_from_rich_line_list(lines)", "docstring": "Render traceback of a node's creation in Python, if available.\n\nArgs:\n node_name: (str) name of the node.\n\nReturns:\n A RichTextLines object containing the stack trace of the node's\n construction.", "source": "github_repos"} +{"code": "def generate(arglist, git_tag_override=None):\n spec, head_symlink, _, dest_file = arglist\n data = json.load(open(spec))\n git_version = None\n if not data['git']:\n git_version = b'unknown'\n else:\n old_branch = data['branch']\n new_branch = parse_branch_ref(head_symlink)\n if new_branch != old_branch:\n raise RuntimeError(\"Run ./configure again, branch was '%s' but is now '%s'\" % (old_branch, new_branch))\n git_version = get_git_version(data['path'], git_tag_override)\n write_version_info(dest_file, git_version)", "docstring": "Generate version_info.cc as given `destination_file`.\n\nArgs:\n arglist: should be a sequence that contains\n spec, head_symlink, ref_symlink, destination_file.\n\n `destination_file` is the filename where version_info.cc will be written\n\n `spec` is a filename where the file contains a JSON dictionary\n 'git' bool that is true if the source is in a git repo\n 'path' base path of the source code\n 'branch' the name of the ref specification of the current branch/tag\n\n `head_symlink` is a filename to HEAD that is cross-referenced against\n what is contained in the json branch designation.\n\n `ref_symlink` is unused in this script but passed, because the build\n system uses that file to detect when commits happen.\n\n git_tag_override: Override the value for the git tag. This is useful for\n releases where we want to build the release before the git tag is\n created.\n\nRaises:\n RuntimeError: If ./configure needs to be run, RuntimeError will be raised.", "source": "github_repos"} +{"code": "def symbolic_trace(model: 'PreTrainedModel', input_names: Optional[list[str]]=None, disable_check: bool=False, tracer_cls: type[HFTracer]=HFTracer) -> GraphModule:\n if input_names is None:\n input_names = model.dummy_inputs.keys()\n input_names = list(input_names)\n concrete_args = get_concrete_args(model, input_names)\n if not disable_check:\n check_if_model_is_supported(model)\n if 'past_key_values' in input_names and (not getattr(model.config, 'use_cache', False)):\n logger.warning('`past_key_values` were specified as input names, but model.config.use_cache = False, this might lead to unexpected behavior.')\n if 'past_key_values' not in input_names and getattr(model.config, 'use_cache', False):\n logger.warning('`past_key_values` were not specified as input names, but model.config.use_cache = True. Setting model.config.use_cache = False.')\n model.config.use_cache = False\n tracer = tracer_cls()\n traced_graph = tracer.trace(model, concrete_args=concrete_args)\n traced = torch.fx.GraphModule(model, traced_graph)\n traced.config = model.config\n traced.class_for_deserialization = model.__class__\n traced.device = model.device\n return traced", "docstring": "Performs symbolic tracing on the model.\n\nArgs:\n model ([`PretrainedModel`]):\n The model to trace.\n input_names (`List[str]`, *optional*):\n The names of the inputs of the traced model. If unset, model.dummy_inputs.keys() are used instead.\n disable_check (`bool`, *optional*, defaults to `False`):\n If `True`, no check is done before trying to trace the model, this is mostly usesul for debugging purposes.\n tracer_cls (`Type[HFTracer]`, *optional*, defaults to `HFTracer`):\n The tracer class to use for instantiating the tracer. If unset, `HFTracer` is used instead.\n\nReturns:\n `torch.fx.GraphModule`: A GraphModule constructed by recording operations seen while tracing the model.\n\nExample:\n ```python\n from transformers.utils.fx import symbolic_trace\n\n traced_model = symbolic_trace(model, input_names=[\"input_ids\", \"attention_mask\", \"token_type_ids\"])\n ```", "source": "github_repos"} +{"code": "def _merge_call(self, fn, args, kwargs):\n t = threading.current_thread()\n assert isinstance(t, _MirroredReplicaThread)\n t.merge_fn = fn\n t.merge_args = args\n t.merge_kwargs = kwargs\n t.captured_name_scope = t.graph.get_name_scope()\n if t.captured_name_scope:\n t.captured_name_scope += '/'\n t.captured_var_scope = variable_scope.get_variable_scope()\n t.captured_control_deps = t.graph._current_control_dependencies()\n t.merge_call_entered_in_eager = context.context().executing_eagerly()\n if ops.get_default_graph() != t.graph:\n raise RuntimeError('`merge_call` called while defining a new graph or a tf.function. This can often happen if the function `fn` passed to `strategy.run()` contains a nested `@tf.function`, and the nested `@tf.function` contains a synchronization point, such as aggregating gradients (e.g, optimizer.apply_gradients), or if the function `fn` uses a control flow statement which contains a synchronization point in the body. Such behaviors are not yet supported. Instead, please avoid nested `tf.function`s or control flow statements that may potentially cross a synchronization boundary, for example, wrap the `fn` passed to `strategy.run` or the entire `strategy.run` inside a `tf.function` or move the control flow out of `fn`. If you are subclassing a `tf.keras.Model`, please avoid decorating overridden methods `test_step` and `train_step` in `tf.function`.')\n t.has_paused.set()\n t.should_run.wait()\n t.should_run.clear()\n if t.coord.should_stop():\n raise _RequestedStop()\n t.merge_call_entered_in_eager = None\n return t.merge_result", "docstring": "`merge_call()` implementation for synchronized replica.\n\n This pauses the current replica thread and passes `fn` and its arguments to\n the main thread. The main thread will wait until all replicas pause, then\n invoke `fn` with grouped arguments. The current replica thread will continue\n after `fn` completes.\n\n See `_call_for_each_replica` for the logic in the main thread.\n\nArgs:\n fn: a function that is called in cross replica context with grouped\n arguments from each replica. `fn` should returns grouped values.\n args: positional arguments to `fn`.\n kwargs: keyword arguments to `fn`.\n\nReturns:\n Return value of `fn` for the current replica.\n\nRaises:\n RuntimeError: when merge_call happens in a different graph, e.g. in a\n different tf.function, which is not supported now.\n _RequestedStop: when stop is requested.", "source": "github_repos"} +{"code": "def count_up_to(ref, limit, name=None):\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.count_up_to(ref, limit=limit, name=name)\n return gen_state_ops.resource_count_up_to(ref.handle, limit, T=ref.dtype, name=name)", "docstring": "Increments 'ref' until it reaches 'limit'.\n\nArgs:\n ref: A Variable. Must be one of the following types: `int32`, `int64`.\n Should be from a scalar `Variable` node.\n limit: An `int`.\n If incrementing ref would bring it above limit, instead generates an\n 'OutOfRange' error.\n name: A name for the operation (optional).\n\nReturns:\n A `Tensor`. Has the same type as `ref`.\n A copy of the input before increment. If nothing else modifies the\n input, the values produced will all be distinct.", "source": "github_repos"} +{"code": "def byte_swap_tflite_buffer(tflite_model, from_endiness, to_endiness):\n if tflite_model is None:\n return None\n model = convert_bytearray_to_object(tflite_model)\n byte_swap_tflite_model_obj(model, from_endiness, to_endiness)\n return convert_object_to_bytearray(model)", "docstring": "Generates a new model byte array after byte swapping its buffers field.\n\nArgs:\n tflite_model: TFLite flatbuffer in a byte array.\n from_endiness: The original endianness format of the buffers in\n tflite_model.\n to_endiness: The destined endianness format of the buffers in tflite_model.\n\nReturns:\n TFLite flatbuffer in a byte array, after being byte swapped to to_endiness\n format.", "source": "github_repos"} +{"code": "def from_dict(cls, feature_extractor_dict: dict[str, Any], **kwargs) -> PreTrainedFeatureExtractor:\n return_unused_kwargs = kwargs.pop('return_unused_kwargs', False)\n to_remove = []\n for key, value in kwargs.items():\n if key in feature_extractor_dict:\n feature_extractor_dict[key] = value\n to_remove.append(key)\n for key in to_remove:\n kwargs.pop(key, None)\n feature_extractor = cls(**feature_extractor_dict)\n logger.info(f'Feature extractor {feature_extractor}')\n if return_unused_kwargs:\n return (feature_extractor, kwargs)\n else:\n return feature_extractor", "docstring": "Instantiates a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a Python dictionary of\n parameters.\n\nArgs:\n feature_extractor_dict (`Dict[str, Any]`):\n Dictionary that will be used to instantiate the feature extractor object. Such a dictionary can be\n retrieved from a pretrained checkpoint by leveraging the\n [`~feature_extraction_utils.FeatureExtractionMixin.to_dict`] method.\n kwargs (`Dict[str, Any]`):\n Additional parameters from which to initialize the feature extractor object.\n\nReturns:\n [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature extractor object instantiated from those\n parameters.", "source": "github_repos"} +{"code": "def get_image_features(self, pixel_values: torch.FloatTensor, vision_feature_layer: Optional[Union[int, List[int]]]=None, vision_feature_select_strategy: Optional[str]=None, **kwargs):\n vision_feature_layer = vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer\n vision_feature_select_strategy = vision_feature_select_strategy if vision_feature_select_strategy is not None else self.config.vision_feature_select_strategy\n downsample_ratio = self.config.downsample_ratio\n if vision_feature_layer == -1:\n vision_features = self.vision_tower(pixel_values=pixel_values).last_hidden_state\n else:\n vision_features = self.vision_model(pixel_values=pixel_values).hidden_states[vision_feature_layer]\n if vision_feature_select_strategy == 'default':\n vision_features = vision_features[:, 1:, :]\n channels = vision_features.shape[1]\n feature_size = int(channels ** 0.5)\n batch_size = vision_features.shape[0]\n vision_features = vision_features.reshape(batch_size, feature_size, feature_size, -1)\n vision_features = self.pixel_shuffle(vision_features, scale_factor=downsample_ratio)\n vision_features = vision_features.reshape(batch_size, -1, vision_features.shape[-1])\n vision_features = self.multi_modal_projector(vision_features)\n return vision_features", "docstring": "Obtains image last hidden states from the vision tower and apply multimodal projection.\n\nArgs:\n pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)\n The tensors corresponding to the input images.\n vision_feature_layer (`int` or `List[int]`):\n Layer index or list of layer indices to extract features from.\n\nReturns:\n vision_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`.", "source": "github_repos"} +{"code": "def load_supported_categories(categories_path: str):\n global _load_supported_categories\n if _load_supported_categories:\n return\n with open(categories_path, encoding='utf-8') as supported_categories:\n yaml_object = yaml.load(supported_categories.read(), Loader=yaml.SafeLoader)\n Tag.Config.supported_categories = yaml_object[TagFields.categories]\n _load_supported_categories = True", "docstring": "Load the list of supported categories from categories_path file\n into Tag model config\n\nArgs:\n categories_path: path to the file with categories.", "source": "github_repos"} +{"code": "def debug(msg: str, *args, **kwargs) -> None:\n _DEFAULT_LOGGER.debug(msg, *args, **kwargs)", "docstring": "Logs debug message.\n\nArgs:\n msg: Message with possible format string.\n *args: Values for variables in the format string.\n **kwargs: Keyword arguments for the logger.", "source": "github_repos"} +{"code": "def from_control_flow_context_def(context_def, import_scope=None):\n if context_def.HasField('cond_ctxt'):\n return CondContext.from_proto(context_def.cond_ctxt, import_scope=import_scope)\n if context_def.HasField('while_ctxt'):\n return WhileContext.from_proto(context_def.while_ctxt, import_scope=import_scope)\n raise NotImplementedError('Unknown ControlFlowContextDef field: %s' % context_def.WhichOneof('ctxt'))", "docstring": "Deserializes `context_def` into the appropriate ControlFlowContext.\n\nArgs:\n context_def: ControlFlowContextDef proto\n import_scope: Optional `string`. Name scope to add.\n\nReturns:\n A ControlFlowContext subclass", "source": "github_repos"} +{"code": "def clean_up_tokenization(out_string: str) -> str:\n out_string = out_string.replace(' .', '.').replace(' ?', '?').replace(' !', '!').replace(' ,', ',').replace(\" ' \", \"'\").replace(\" n't\", \"n't\").replace(\" 'm\", \"'m\").replace(\" 's\", \"'s\").replace(\" 've\", \"'ve\").replace(\" 're\", \"'re\")\n return out_string", "docstring": "Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms.\n\nArgs:\n out_string (`str`): The text to clean up.\n\nReturns:\n `str`: The cleaned-up string.", "source": "github_repos"} +{"code": "def insert(self, keys, values, name=None):\n with ops.name_scope(name, '%s_lookup_table_insert' % self.name, [self.resource_handle, keys, values]):\n keys = ops.convert_to_tensor(keys, self._key_dtype, name='keys')\n values = ops.convert_to_tensor(values, self._value_dtype, name='values')\n with ops.colocate_with(self.resource_handle):\n op = gen_lookup_ops.lookup_table_insert_v2(self.resource_handle, keys, values)\n return op", "docstring": "Associates `keys` with `values`.\n\nArgs:\n keys: Keys to insert. Can be a tensor of any shape. Must match the table's\n key type.\n values: Values to be associated with keys. Must be a tensor of the same\n shape as `keys` and match the table's value type.\n name: A name for the operation (optional).\n\nReturns:\n The created Operation.\n\nRaises:\n TypeError: when `keys` or `values` doesn't match the table data\n types.", "source": "github_repos"} +{"code": "def _html_tree_view_render(self, *, view: 'HtmlTreeView', name: Optional[str]=None, parent: Any=None, root_path: Optional[KeyPath]=None, **kwargs) -> Html:\n return self._html_tree_view(view=view, name=name, parent=parent, root_path=root_path, **view.get_kwargs(kwargs, self._html_tree_view_config(), root_path or KeyPath())).add_style(*self._html_tree_view_css_styles())", "docstring": "The entrypoint of rendering the subtree represented by this extension.\n\nArgs:\n view: The view to render the object.\n name: The name of the object.\n parent: The parent of the object.\n root_path: The key path of the object relative to the root.\n **kwargs: kwargs to pass to `view.render()` on this extension.\n\nReturns:\n The rendered HTML.", "source": "github_repos"} +{"code": "def with_hot_key_fanout(self, fanout):\n from apache_beam.transforms.combiners import curry_combine_fn\n if fanout is None:\n return self\n else:\n return _CombinePerKeyWithHotKeyFanout(curry_combine_fn(self.fn, self.args, self.kwargs), fanout)", "docstring": "A per-key combine operation like self but with two levels of aggregation.\n\n If a given key is produced by too many upstream bundles, the final\n reduction can become a bottleneck despite partial combining being lifted\n pre-GroupByKey. In these cases it can be helpful to perform intermediate\n partial aggregations in parallel and then re-group to peform a final\n (per-key) combine. This is also useful for high-volume keys in streaming\n where combiners are not generally lifted for latency reasons.\n\n Note that a fanout greater than 1 requires the data to be sent through\n two GroupByKeys, and a high fanout can also result in more shuffle data\n due to less per-bundle combining. Setting the fanout for a key at 1 or less\n places values on the \"cold key\" path that skip the intermediate level of\n aggregation.\n\nArgs:\n fanout: either None, for no fanout, an int, for a constant-degree fanout,\n or a callable mapping keys to a key-specific degree of fanout.\n\nReturns:\n A per-key combining PTransform with the specified fanout.", "source": "github_repos"} +{"code": "def __init__(self, project, throttle_rampup=True, hint_num_workers=_Mutate._DEFAULT_HINT_NUM_WORKERS):\n mutate_fn = DeleteFromDatastore._DatastoreDeleteFn(project)\n super().__init__(mutate_fn, throttle_rampup, hint_num_workers)", "docstring": "Initialize the `DeleteFromDatastore` transform.\n\nArgs:\n project: (:class:`str`) The ID of the project from which the entities will\n be deleted.\n throttle_rampup: Whether to enforce a gradual ramp-up.\n hint_num_workers: A hint for the expected number of workers, used to\n estimate appropriate limits during ramp-up throttling.", "source": "github_repos"} +{"code": "def _transform_features_v2(features, feature_columns, state_manager):\n feature_columns = _normalize_feature_columns(feature_columns)\n outputs = {}\n with ops.name_scope(None, default_name='transform_features', values=features.values()):\n transformation_cache = FeatureTransformationCache(features)\n for column in feature_columns:\n with ops.name_scope(None, default_name=_sanitize_column_name_for_variable_scope(column.name)):\n outputs[column] = transformation_cache.get(column, state_manager)\n return outputs", "docstring": "Returns transformed features based on features columns passed in.\n\n Please note that most probably you would not need to use this function. Please\n check `input_layer` and `linear_model` to see whether they will\n satisfy your use case or not.\n\nExample:\n ```python\n # Define features and transformations\n crosses_a_x_b = crossed_column(\n columns=[\"sparse_feature_a\", \"sparse_feature_b\"], hash_bucket_size=10000)\n price_buckets = bucketized_column(\n source_column=numeric_column(\"price\"), boundaries=[...])\n\n columns = [crosses_a_x_b, price_buckets]\n features = tf.io.parse_example(..., features=make_parse_example_spec(columns))\n transformed = transform_features(features=features, feature_columns=columns)\n\n assertCountEqual(columns, transformed.keys())\n ```\n\nArgs:\n features: A mapping from key to tensors. `FeatureColumn`s look up via these\n keys. For example `numeric_column('price')` will look at 'price' key in\n this dict. Values can be a `SparseTensor` or a `Tensor` depends on\n corresponding `FeatureColumn`.\n feature_columns: An iterable containing all the `FeatureColumn`s.\n state_manager: A StateManager object that holds the FeatureColumn state.\n\nReturns:\n A `dict` mapping `FeatureColumn` to `Tensor` and `SparseTensor` values.", "source": "github_repos"} +{"code": "def _maybe_truncate_traceback(traceback):\n if len(traceback) > MAX_TRACEBACK_LENGTH:\n return traceback[:MAX_TRACEBACK_LENGTH - 2] + [_ELLIPSIS, traceback[-1]]\n else:\n return traceback", "docstring": "Truncate the traceback if it is too long.\n\nArgs:\n traceback: A list representing an error's traceback. There should be one\n list item per entry in the traceback (in the right order); beyond that,\n this function does not care about the item types.\n\nReturns:\n The traceback, possibly with some items removed and an _ELLIPSIS inserted.\n Guaranteed to be no longer than MAX_TRACEBACK_LENGTH.", "source": "github_repos"} +{"code": "def load_default_japanese_parser() -> Parser:\n with open(os.path.join(MODEL_DIR, 'ja.json'), encoding='utf-8') as f:\n model = json.load(f)\n return Parser(model)", "docstring": "Loads a parser equipped with the default Japanese model.\n\nReturns:\n A parser (:obj:`budoux.Parser`).", "source": "github_repos"} +{"code": "def _spanner_io_read_test_preprocessor(test_spec: dict, expected: List[str], env: TestEnvironment):\n if (pipeline := test_spec.get('pipeline', None)):\n for transform in pipeline.get('transforms', []):\n if transform.get('type', '').startswith('ReadFromSpanner'):\n config = transform['config']\n instance, database = (config['instance_id'], config['database_id'])\n if (table := (config.get('table', None) is None)):\n table = config.get('query', '').split('FROM')[-1].strip()\n transform['type'] = 'Create'\n transform['config'] = {k: v for k, v in config.items() if k.startswith('__')}\n elements = INPUT_TABLES[str(instance), str(database), str(table)]\n if config.get('query', None):\n config['query'].replace('select ', 'SELECT ').replace(' from ', ' FROM ')\n columns = set(''.join(config['query'].split('SELECT ')[1:]).split(' FROM', maxsplit=1)[0].split(', '))\n if columns != {'*'}:\n elements = [{column: element[column] for column in element if column in columns} for element in elements]\n transform['config']['elements'] = elements\n return test_spec", "docstring": "Preprocessor for tests that involve reading from Spanner.\n\n This preprocessor replaces any ReadFromSpanner transform with a Create\n transform that reads from a predefined in-memory dictionary. This allows\n the test to verify the pipeline's correctness without relying on external\n Spanner instances.\n\nArgs:\n test_spec: The dictionary representation of the YAML pipeline specification.\n expected: A list of strings representing the expected output of the\n pipeline.\n env: The TestEnvironment object providing utilities for creating temporary\n files.\n\nReturns:\n The modified test_spec dictionary with ReadFromSpanner transforms replaced.", "source": "github_repos"} +{"code": "def GetShadowMap(self, since=None):\n return ShadowUpdateGetter().GetUpdates(self._GetClient(), self.conf['bucket'], self.conf['shadow_object'], since)", "docstring": "Return the shadow map from this source.\n\nArgs:\n since: Get data only changed since this timestamp (inclusive) or None\n for all data.\n\nReturns:\n instance of shadow.ShadowMap", "source": "github_repos"} +{"code": "def _eval_indexed_slices(a):\n if isinstance(a, indexed_slices.IndexedSlices) and context.executing_eagerly():\n return indexed_slices.IndexedSlicesValue(indices=[x.numpy() for x in a.indices], values=[x.numpy() for x in a.values], dense_shape=a.dense_shape)\n return a", "docstring": "Converts IndexedSlices to IndexedSlicesValue with numpy indices/values.\n\n When eager execution is enabled, converts IndexedSlices\n to IndexedSlicesValue with numpy indices/values.\n\nArgs:\n a: any value.\n\nReturns:\n If a is IndexedSlices and eager execution is enabled, calls numpy() on a's\n fields. Otherwise returns a unchanged.", "source": "github_repos"} +{"code": "def _overload_operator(cls, tensor_class, operator):\n tensor_oper = getattr(tensor_class, operator)\n tensor_oper = getattr(tensor_oper, '__func__', tensor_oper)\n setattr(cls, operator, tensor_oper)", "docstring": "Overload an operator with the same implementation as a base Tensor class.\n\n We pull the operator out of the class dynamically to avoid ordering issues.\n\nArgs:\n tensor_class: The (Composite)Tensor to get the method from.\n operator: string. The operator name.", "source": "github_repos"} +{"code": "def _strip_blank_lines(lines):\n start = 0\n num_lines = len(lines)\n while lines and start < num_lines and _is_blank(lines[start]):\n start += 1\n lines = lines[start:]\n while lines and _is_blank(lines[-1]):\n lines.pop()\n return lines", "docstring": "Removes lines containing only blank characters before and after the text.\n\nArgs:\n lines: A list of lines.\n\nReturns:\n A list of lines without trailing or leading blank lines.", "source": "github_repos"} +{"code": "def __init__(self, output_bit, quant_mode=False, force_dequant='none'):\n super().__init__()\n self.output_bit = output_bit\n self.max_bit = 32\n self.quant_mode = quant_mode\n if force_dequant in ['nonlinear', 'softmax']:\n logger.info('Force dequantize softmax')\n self.quant_mode = False\n self.act = QuantAct(16, quant_mode=self.quant_mode)\n self.x0 = -0.6931\n self.const = 30\n self.coef = [0.35815147, 0.96963238, 1.0]\n self.coef[1] /= self.coef[0]\n self.coef[2] /= self.coef[0]", "docstring": "Quantized version of `torch.nn.Softmax`. Adds quantization-specific arguments on top of `torch.nn.Softmax`.\n\nArgs:\n output_bit (`int`):\n Bitwidth for the layer output activation.\n quant_mode (`bool`, *optional*, defaults to `False`):\n Whether or not the layer is quantized.\n force_dequant (`str`, *optional*, defaults to `\"none\"`):\n Force dequantize the layer if either \"softmax\" or \"nonlinear\" is given.", "source": "github_repos"} +{"code": "def recipe_drive_copy(config, auth_read, source, destination):\n drive(config, {'auth': auth_read, 'copy': {'source': source, 'destination': destination}})", "docstring": "Copy a drive document.\n\nArgs:\n auth_read (authentication) - Credentials used for reading data.\n source (string) - Name or URL of document to copy from.\n destination (string) - Name document to copy to.", "source": "github_repos"} +{"code": "def flat_values(self):\n rt_values = self.values\n while isinstance(rt_values, RaggedTensor):\n rt_values = rt_values.values\n return rt_values", "docstring": "The innermost `values` tensor for this ragged tensor.\n\n Concretely, if `rt.values` is a `Tensor`, then `rt.flat_values` is\n `rt.values`; otherwise, `rt.flat_values` is `rt.values.flat_values`.\n\n Conceptually, `flat_values` is the tensor formed by flattening the\n outermost dimension and all of the ragged dimensions into a single\n dimension.\n\n `rt.flat_values.shape = [nvals] + rt.shape[rt.ragged_rank + 1:]`\n (where `nvals` is the number of items in the flattened dimensions).\n\nReturns:\n A `Tensor`.\n\n #### Example:\n\n >>> rt = tf.ragged.constant([[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]])\n >>> print(rt.flat_values)\n tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32)", "source": "github_repos"} +{"code": "def _single_column_cell_selection_loss(token_logits, column_logits, labels, cell_index, col_index, cell_mask):\n labels_per_column, _ = reduce_sum(tf.cast(labels, tf.float32), col_index)\n column_label = tf.argmax(labels_per_column, axis=-1, output_type=tf.int32)\n no_cell_selected = tf.equal(tf.reduce_max(labels_per_column, axis=-1), 0)\n column_label = tf.where(no_cell_selected, tf.zeros_like(column_label), column_label)\n column_dist = tfp.distributions.Categorical(logits=column_logits)\n column_loss_per_example = -column_dist.log_prob(column_label)\n logits_per_cell, _ = reduce_mean(token_logits, cell_index)\n labels_per_cell, labels_index = reduce_max(tf.cast(labels, tf.int32), cell_index)\n column_id_for_cells = cell_index.project_inner(labels_index).indices\n column_mask = tf.cast(tf.equal(column_id_for_cells, tf.expand_dims(column_label, axis=1)), tf.float32)\n cell_dist = tfp.distributions.Bernoulli(logits=logits_per_cell)\n cell_log_prob = cell_dist.log_prob(labels_per_cell)\n cell_loss = -tf.reduce_sum(cell_log_prob * column_mask * cell_mask, axis=1)\n cell_loss /= tf.reduce_sum(column_mask * cell_mask, axis=1) + EPSILON_ZERO_DIVISION\n selection_loss_per_example = column_loss_per_example\n selection_loss_per_example += tf.where(no_cell_selected, tf.zeros_like(selection_loss_per_example), cell_loss)\n selected_column_id = tf.argmax(column_logits, axis=-1, output_type=tf.int32)\n selected_column_mask = tf.cast(tf.equal(column_id_for_cells, tf.expand_dims(selected_column_id, axis=-1)), tf.float32)\n selected_column_mask = tf.where(tf.equal(column_id_for_cells, 0), tf.zeros_like(selected_column_mask), selected_column_mask)\n logits_per_cell += CLOSE_ENOUGH_TO_LOG_ZERO * (1.0 - cell_mask * selected_column_mask)\n logits = gather(logits_per_cell, cell_index)\n return (selection_loss_per_example, logits)", "docstring": "Computes the loss for cell selection constrained to a single column. The loss is a hierarchical log-likelihood. The\n model first predicts a column and then selects cells within that column (conditioned on the column). Cells outside\n the selected column are never selected.\n\nArgs:\n token_logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):\n Tensor containing the logits per token.\n column_logits (`tf.Tensor` of shape `(batch_size, max_num_cols)`):\n Tensor containing the logits per column.\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`):\n Labels per token.\n cell_index (`ProductIndexMap`):\n Index that groups tokens into cells.\n col_index (`IndexMap`):\n Index that groups tokens into columns.\n cell_mask (`tf.Tensor` of shape `(batch_size, max_num_rows * max_num_cols)`):\n Mask for cells that exist in the table (i.e. that are not padding).\n\nReturns:\n selection_loss_per_example (`tf.Tensor` of shape `(batch_size,)`): Loss for each example. logits (`tf.Tensor`\n of shape `(batch_size, sequence_length)`): New logits which are only allowed to select cells in a single\n column. Logits outside of the most likely column according to *column_logits* will be set to a very low value\n (such that the probabilities are 0).", "source": "github_repos"} +{"code": "def with_metadata_spec(self, column_name: str='metadata', python_type: Type=str, convert_fn: Optional[Callable[[Dict[str, Any]], Any]]=None, sql_typecast: Optional[str]='::jsonb') -> 'ColumnSpecsBuilder':\n\n def value_fn(chunk: Chunk) -> Any:\n if convert_fn:\n return convert_fn(chunk.metadata)\n return json.dumps(chunk.metadata) if python_type == str else chunk.metadata\n self._specs.append(ColumnSpec(column_name=column_name, python_type=python_type, value_fn=value_fn, sql_typecast=sql_typecast))\n return self", "docstring": "Add metadata :class:`.ColumnSpec` with optional type and conversion.\n\nArgs:\n column_name: Name for the metadata column (defaults to \"metadata\")\n python_type: Python type for the column (defaults to str)\n convert_fn: Optional function to convert the metadata dictionary\n If None and python_type is str, converts to JSON string\n sql_typecast: Optional SQL type cast (defaults to \"::jsonb\")\n\nReturns:\n Self for method chaining\n\nExample:\n >>> builder.with_metadata_spec(\n ... column_name=\"meta_tags\",\n ... python_type=list,\n ... convert_fn=lambda meta: list(meta.keys()),\n ... sql_typecast=\"::text[]\"\n ... )", "source": "github_repos"} +{"code": "def __init__(self, resource_handle, create_op, name):\n stamp_token, serialized = gen_boosted_trees_ops.boosted_trees_serialize_ensemble(resource_handle)\n slice_spec = ''\n specs = [saver.BaseSaverBuilder.SaveSpec(stamp_token, slice_spec, name + '_stamp'), saver.BaseSaverBuilder.SaveSpec(serialized, slice_spec, name + '_serialized')]\n super(_TreeEnsembleSavable, self).__init__(resource_handle, specs, name)\n self.resource_handle = resource_handle\n self._create_op = create_op", "docstring": "Creates a _TreeEnsembleSavable object.\n\nArgs:\n resource_handle: handle to the decision tree ensemble variable.\n create_op: the op to initialize the variable.\n name: the name to save the tree ensemble variable under.", "source": "github_repos"} +{"code": "def basis(sample_paths, time_index):\n sample_paths = tf.convert_to_tensor(sample_paths, name='sample_paths')\n if sample_paths.shape.rank == 3:\n sample_paths = tf.expand_dims(sample_paths, axis=0)\n shape = tf.shape(sample_paths)\n num_samples = shape[1]\n batch_size = shape[0]\n dim = sample_paths.shape[-1]\n slice_samples = tf.slice(sample_paths, [0, 0, time_index, 0], [batch_size, num_samples, 1, dim])\n samples_centered = slice_samples - tf.math.reduce_mean(slice_samples, axis=1, keepdims=True)\n grid = tf.range(degree + 1, dtype=samples_centered.dtype)\n grid = tf.meshgrid(*dim * [grid])\n grid = tf.reshape(tf.stack(grid, -1), [-1, dim])\n basis_expansion = tf.reduce_prod(samples_centered ** grid, axis=-1)\n return tf.transpose(basis_expansion, [0, 2, 1])", "docstring": "Computes polynomial basis expansion at the given sample points.\n\nArgs:\n sample_paths: A `Tensor` of either `flaot32` or `float64` dtype and of\n either shape `[num_samples, num_times, dim]` or\n `[batch_size, num_samples, num_times, dim]`.\n time_index: An integer scalar `Tensor` that corresponds to the time\n coordinate at which the basis function is computed.\n\nReturns:\n A `Tensor`s of shape `[batch_size, (degree + 1)**dim, num_samples]`.", "source": "github_repos"} +{"code": "def _find_max_under_constraint(self, constrained, dependent, predicate):\n feasible = array_ops.where_v2(predicate(constrained, self.value))\n feasible_exists = math_ops.greater(array_ops.size(feasible), 0)\n max_dependent = math_ops.reduce_max(array_ops.gather(dependent, feasible))\n return array_ops.where_v2(feasible_exists, max_dependent, 0.0)", "docstring": "Returns the maximum of dependent_statistic that satisfies the constraint.\n\nArgs:\n constrained: Over these values the constraint\n is specified. A rank-1 tensor.\n dependent: From these values the maximum that satiesfies the\n constraint is selected. Values in this tensor and in\n `constrained` are linked by having the same threshold at each\n position, hence this tensor must have the same shape.\n predicate: A binary boolean functor to be applied to arguments\n `constrained` and `self.value`, e.g. `tf.greater`.\n\n Returns maximal dependent value, if no value satiesfies the constraint 0.0.", "source": "github_repos"} +{"code": "def contains_saved_model(export_dir):\n if isinstance(export_dir, os.PathLike):\n export_dir = os.fspath(export_dir)\n return maybe_saved_model_directory(export_dir)", "docstring": "Checks whether the provided export directory could contain a SavedModel.\n\n Note that the method does not load any data by itself. If the method returns\n `false`, the export directory definitely does not contain a SavedModel. If the\n method returns `true`, the export directory may contain a SavedModel but\n provides no guarantee that it can be loaded.\n\nArgs:\n export_dir: Absolute path to possible export location. For example,\n '/my/foo/model'.\n\nReturns:\n True if the export directory contains SavedModel files, False otherwise.", "source": "github_repos"} +{"code": "def check_annotation_type_mismatch(self, node, name, typ, value, stack, allow_none, details=None):\n if not typ or not value:\n return\n if value.data == [self.convert.ellipsis] or (allow_none and value.data == [self.convert.none]):\n return\n contained_type = abstract_utils.match_type_container(typ, ('typing.ClassVar', 'dataclasses.InitVar'))\n if contained_type:\n typ = contained_type\n bad = self.matcher(node).compute_one_match(value, typ).bad_matches\n for match in bad:\n self.errorlog.annotation_type_mismatch(stack, match.expected.typ, match.actual_binding, name, match.error_details, details)", "docstring": "Checks for a mismatch between a variable's annotation and value.\n\nArgs:\n node: node\n name: variable name\n typ: variable annotation\n value: variable value\n stack: a frame stack for error reporting\n allow_none: whether a value of None is allowed for any type\n details: any additional details to add to the error message", "source": "github_repos"} +{"code": "def update_shapes_dict_for_target_fn(target_fn, shapes_dict, call_spec, class_name):\n if utils.is_default(target_fn):\n return None\n sig = inspect.signature(target_fn)\n expected_names = []\n for name, param in sig.parameters.items():\n if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY, param.KEYWORD_ONLY):\n expected_names.append(name)\n if len(expected_names) == 1:\n key = expected_names[0]\n values = tuple(shapes_dict.values())\n if values:\n input_shape = values[0]\n else:\n input_shape = None\n return {key: input_shape}\n kwargs = {}\n for name in expected_names:\n method_name = target_fn.__name__\n error_preamble = f'For a `{method_name}()` method with more than one argument, all arguments should have a `_shape` suffix and match an argument from `call()`. E.g. `{method_name}(self, foo_shape, bar_shape)` '\n if not name.endswith('_shape'):\n raise ValueError(f\"{error_preamble} For layer '{class_name}', Received `{method_name}()` argument `{name}`, which does not end in `_shape`.\")\n expected_call_arg = utils.removesuffix(name, '_shape')\n if expected_call_arg not in call_spec.arguments_dict:\n raise ValueError(f\"{error_preamble} For layer '{class_name}', received `{method_name}()` argument `{name}`, but `call()` does not have argument `{expected_call_arg}`.\")\n if name in shapes_dict:\n kwargs[name] = shapes_dict[name]\n return kwargs", "docstring": "Updates a `shapes_dict` for `build()` or `compute_output_shape()`.\n\n This function will align a dictionary of the shapes of all tensor\n passed to `call`, with the signatures of `build()` or\n `compute_output_shape()`.\n\n The alignment is a follows:\n\n - If `build()` or `compute_output_shape()` accept only one argument,\n forward the shape of the first positional argument from call without\n checking any argument names.\n - If `build()` or `compute_output_shape()` accept multiple arguments,\n enforce that all argument names match a call argument name, e.g.\n `foo_shape` would match call argument `foo`.\n\nReturns:\n An updated `shapes_dict` that can be used to invoke\n `target_fn(**shapes_dict)`.", "source": "github_repos"} +{"code": "def get_traverse_shallow_structure(traverse_fn, structure, expand_composites=False):\n is_nested_fn = _is_nested_or_composite if expand_composites else is_nested\n to_traverse = traverse_fn(structure)\n if not is_nested_fn(structure):\n if not isinstance(to_traverse, bool):\n raise TypeError('traverse_fn returned structure: %s for non-structure: %s' % (to_traverse, structure))\n return to_traverse\n level_traverse = []\n if isinstance(to_traverse, bool):\n if not to_traverse:\n return False\n else:\n for branch in nest_util.yield_value(nest_util.Modality.CORE, structure):\n level_traverse.append(get_traverse_shallow_structure(traverse_fn, branch, expand_composites=expand_composites))\n elif not is_nested_fn(to_traverse):\n raise TypeError('traverse_fn returned a non-bool scalar: %s for input: %s' % (to_traverse, structure))\n else:\n assert_shallow_structure(to_traverse, structure, expand_composites=expand_composites)\n for t, branch in zip(nest_util.yield_value(nest_util.Modality.CORE, to_traverse), nest_util.yield_value(nest_util.Modality.CORE, structure)):\n if not isinstance(t, bool):\n raise TypeError(\"traverse_fn didn't return a depth=1 structure of bools. saw: %s for structure: %s\" % (to_traverse, structure))\n if t:\n level_traverse.append(get_traverse_shallow_structure(traverse_fn, branch))\n else:\n level_traverse.append(False)\n return nest_util.sequence_like(structure, level_traverse)", "docstring": "Generates a shallow structure from a `traverse_fn` and `structure`.\n\n `traverse_fn` must accept any possible subtree of `structure` and return\n a depth=1 structure containing `True` or `False` values, describing which\n of the top-level subtrees may be traversed. It may also\n return scalar `True` or `False` \"traversal is OK / not OK for all subtrees.\"\n\n Examples are available in the unit tests (nest_test.py).\n\nArgs:\n traverse_fn: Function taking a substructure and returning either a scalar\n `bool` (whether to traverse that substructure or not) or a depth=1\n shallow structure of the same type, describing which parts of the\n substructure to traverse.\n structure: The structure to traverse.\n expand_composites: If true, then composite tensors such as\n `tf.sparse.SparseTensor` and `tf.RaggedTensor` are expanded into their\n component tensors.\n\nReturns:\n A shallow structure containing python bools, which can be passed to\n `map_structure_up_to` and `flatten_up_to`.\n\nRaises:\n TypeError: if `traverse_fn` returns a nested structure for an atom input.\n or a structure with depth higher than 1 for a nested structure input,\n or if any leaf values in the returned structure or scalar are not type\n `bool`.", "source": "github_repos"} +{"code": "def get_bq_tableschema(schema):\n if isinstance(schema, (bigquery.TableSchema, value_provider.ValueProvider)) or callable(schema) or schema is None:\n return schema\n elif isinstance(schema, str):\n return get_table_schema_from_string(schema)\n elif isinstance(schema, dict):\n schema_string = json.dumps(schema)\n return parse_table_schema_from_json(schema_string)\n else:\n raise TypeError('Unexpected schema argument: %s.' % schema)", "docstring": "Convert the table schema to a TableSchema object.\n\nArgs:\n schema (str, dict, ~apache_beam.io.gcp.internal.clients.bigquery.bigquery_v2_messages.TableSchema):\n The schema to be used if the BigQuery table to write has to be created.\n This can either be a dict or string or in the TableSchema format.\n\nReturns:\n ~apache_beam.io.gcp.internal.clients.bigquery.bigquery_v2_messages.TableSchema: The schema as a TableSchema object.", "source": "github_repos"} +{"code": "def _assert_sparse_compatible(sparse_tensors):\n checks = []\n first = sparse_tensors[0]\n for t in sparse_tensors[1:]:\n checks.append(check_ops.assert_equal(first.dense_shape, t.dense_shape, message='Mismatched shapes!'))\n checks.append(check_ops.assert_equal(first.indices, t.indices, message='Mismatched indices!'))\n return checks", "docstring": "Check that all of `sparse_tensors` have same `indices` and `dense_shape`.\n\nArgs:\n sparse_tensors: A list of sparse tensors.\n\nReturns:\n An op to be used as a control dependency.", "source": "github_repos"} +{"code": "def nested_value_rowids(self, name=None):\n with ops.name_scope(name, 'RaggedNestedValueRowIds', [self]):\n rt_nested_ids = [self.value_rowids()]\n rt_values = self.values\n while isinstance(rt_values, RaggedTensor):\n rt_nested_ids.append(rt_values.value_rowids())\n rt_values = rt_values.values\n return tuple(rt_nested_ids)", "docstring": "Returns a tuple containing the value_rowids for all ragged dimensions.\n\n `rt.nested_value_rowids` is a tuple containing the `value_rowids` tensors\n for\n all ragged dimensions in `rt`, ordered from outermost to innermost. In\n particular, `rt.nested_value_rowids = (rt.value_rowids(),) + value_ids`\n where:\n\n * `value_ids = ()` if `rt.values` is a `Tensor`.\n * `value_ids = rt.values.nested_value_rowids` otherwise.\n\nArgs:\n name: A name prefix for the returned tensors (optional).\n\nReturns:\n A `tuple` of 1-D integer `Tensor`s.\n\n #### Example:\n\n >>> rt = tf.ragged.constant(\n ... [[[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]]])\n >>> for i, ids in enumerate(rt.nested_value_rowids()):\n ... print('row ids for dimension %d: %s' % (i+1, ids.numpy()))\n row ids for dimension 1: [0 0 0]\n row ids for dimension 2: [0 0 0 2 2]\n row ids for dimension 3: [0 0 0 0 2 2 2 3]", "source": "github_repos"} +{"code": "def rfft(x, fft_length=None):\n if any_symbolic_tensors((x,)):\n return RFFT(fft_length).symbolic_call(x)\n return backend.math.rfft(x, fft_length)", "docstring": "Real-valued Fast Fourier Transform along the last axis of the input.\n\n Computes the 1D Discrete Fourier Transform of a real-valued signal over the\n inner-most dimension of input.\n\n Since the Discrete Fourier Transform of a real-valued signal is\n Hermitian-symmetric, RFFT only returns the `fft_length / 2 + 1` unique\n components of the FFT: the zero-frequency term, followed by the\n `fft_length / 2` positive-frequency terms.\n\n Along the axis RFFT is computed on, if `fft_length` is smaller than the\n corresponding dimension of the input, the dimension is cropped. If it is\n larger, the dimension is padded with zeros.\n\nArgs:\n x: Input tensor.\n fft_length: An integer representing the number of the fft length. If not\n specified, it is inferred from the length of the last axis of `x`.\n Defaults to `None`.\n\nReturns:\n A tuple containing two tensors - the real and imaginary parts of the\n output.\n\nExample:\n >>> x = keras.ops.convert_to_tensor([0.0, 1.0, 2.0, 3.0, 4.0])\n >>> rfft(x)\n (array([10.0, -2.5, -2.5]), array([0.0, 3.4409548, 0.81229924]))\n\n >>> rfft(x, 3)\n (array([3.0, -1.5]), array([0.0, 0.8660254]))", "source": "github_repos"} +{"code": "def isnan(x):\n if any_symbolic_tensors((x,)):\n return Isnan().symbolic_call(x)\n return backend.numpy.isnan(x)", "docstring": "Test element-wise for NaN and return result as a boolean tensor.\n\nArgs:\n x: Input tensor.\n\nReturns:\n Output boolean tensor.", "source": "github_repos"} +{"code": "def __init__(self, namespace: Optional[str], name: Optional[str], urn: Optional[str]=None, labels: Optional[Dict[str, str]]=None) -> None:\n if not urn:\n if not namespace:\n raise ValueError('Metric namespace must be non-empty')\n if not name:\n raise ValueError('Metric name must be non-empty')\n self.namespace = namespace\n self.name = name\n self.urn = urn\n self.labels = labels if labels else {}", "docstring": "Initializes ``MetricName``.\n\n Note: namespace and name should be set for user metrics,\n urn and labels should be set for an arbitrary metric to package into a\n MonitoringInfo.\n\nArgs:\n namespace: A string with the namespace of a metric.\n name: A string with the name of a metric.\n urn: URN to populate on a MonitoringInfo, when sending to RunnerHarness.\n labels: Labels to populate on a MonitoringInfo", "source": "github_repos"} +{"code": "def _sequence_like(instance, args):\n return nest_util.sequence_like(instance, args)", "docstring": "Converts the sequence `args` to the same type as `instance`.\n\nArgs:\n instance: an instance of `tuple`, `list`, `namedtuple`, `dict`,\n `collections.OrderedDict`, or `composite_tensor.Composite_Tensor`\n or `type_spec.TypeSpec`.\n args: items to be converted to the `instance` type.\n\nReturns:\n `args` with the type of `instance`.", "source": "github_repos"} +{"code": "def solvevec(self, rhs, adjoint=False, name='solve'):\n with self._name_scope(name):\n rhs = tensor_conversion.convert_to_tensor_v2_with_dispatch(rhs, name='rhs')\n self._check_input_dtype(rhs)\n self_dim = -1 if adjoint else -2\n tensor_shape.dimension_at_index(self.shape, self_dim).assert_is_compatible_with(rhs.shape[-1])\n return self._solvevec(rhs, adjoint=adjoint)", "docstring": "Solve single equation with best effort: `A X = rhs`.\n\n The returned `Tensor` will be close to an exact solution if `A` is well\n conditioned. Otherwise closeness will vary. See class docstring for details.\n\nExample:\n ```python\n # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N]\n operator = LinearOperator(...)\n operator.shape = [..., M, N]\n\n # Solve one linear system for every member of the batch.\n RHS = ... # shape [..., M]\n\n X = operator.solvevec(RHS)\n # X is the solution to the linear system\n # sum_j A[..., :, j] X[..., j] = RHS[..., :]\n\n operator.matvec(X)\n ==> RHS\n ```\n\nArgs:\n rhs: `Tensor` with same `dtype` as this operator.\n `rhs` is treated like a [batch] vector meaning for every set of leading\n dimensions, the last dimension defines a vector. See class docstring\n for definition of compatibility regarding batch dimensions.\n adjoint: Python `bool`. If `True`, solve the system involving the adjoint\n of this `LinearOperator`: `A^H X = rhs`.\n name: A name scope to use for ops added by this method.\n\nReturns:\n `Tensor` with shape `[...,N]` and same `dtype` as `rhs`.\n\nRaises:\n NotImplementedError: If `self.is_non_singular` or `is_square` is False.", "source": "github_repos"} +{"code": "def function(inputs, outputs, updates=None, name=None, **kwargs):\n if ops.executing_eagerly_outside_functions():\n if kwargs:\n raise ValueError('Session keyword arguments are not supported during eager execution. You passed: %s' % (kwargs,))\n if updates:\n raise ValueError('`updates` argument is not supported during eager execution. You passed: %s' % (updates,))\n from tensorflow.python.keras import models\n from tensorflow.python.keras.utils import tf_utils\n model = models.Model(inputs=inputs, outputs=outputs)\n wrap_outputs = isinstance(outputs, list) and len(outputs) == 1\n\n def func(model_inputs):\n outs = model(model_inputs)\n if wrap_outputs:\n outs = [outs]\n return tf_utils.sync_to_numpy_or_python_type(outs)\n return func\n if kwargs:\n for key in kwargs:\n if key not in tf_inspect.getfullargspec(session_module.Session.run)[0] and key not in ['inputs', 'outputs', 'updates', 'name']:\n msg = 'Invalid argument \"%s\" passed to K.function with TensorFlow backend' % key\n raise ValueError(msg)\n return GraphExecutionFunction(inputs, outputs, updates=updates, name=name, **kwargs)", "docstring": "Instantiates a Keras function.\n\nArgs:\n inputs: List of placeholder tensors.\n outputs: List of output tensors.\n updates: List of update ops.\n name: String, name of function.\n **kwargs: Passed to `tf.Session.run`.\n\nReturns:\n Output values as Numpy arrays.\n\nRaises:\n ValueError: if invalid kwargs are passed in or if in eager execution.", "source": "github_repos"} +{"code": "def check_line_split(code_line):\n return re.search('\\\\\\\\\\\\s*\\\\n$', code_line)", "docstring": "Checks if a line was split with `\\`.\n\nArgs:\n code_line: A line of Python code\n\nReturns:\n If the line was split with `\\`\n\n >>> skip_magic(\"!gcloud ml-engine models create ${MODEL} \\\\\\n\")\n True", "source": "github_repos"} +{"code": "def preprocess_input_examples_arg_string(input_examples_str):\n input_dict = preprocess_input_exprs_arg_string(input_examples_str)\n for input_key, example_list in input_dict.items():\n if not isinstance(example_list, list):\n raise ValueError('tf.Example input must be a list of dictionaries, but \"%s\" is %s' % (example_list, type(example_list)))\n input_dict[input_key] = [_create_example_string(example) for example in example_list]\n return input_dict", "docstring": "Parses input into dict that maps input keys to lists of tf.Example.\n\n Parses input string in the format of 'input_key1=[{feature_name:\n feature_list}];input_key2=[{feature_name:feature_list}];' into a dictionary\n that maps each input_key to its list of serialized tf.Example.\n\nArgs:\n input_examples_str: A string that specifies a list of dictionaries of\n feature_names and their feature_lists for each input.\n Each input is separated by semicolon. For each input key:\n 'input=[{feature_name1: feature_list1, feature_name2:feature_list2}]'\n items in feature_list can be the type of float, int, long or str.\n\nReturns:\n A dictionary that maps input keys to lists of serialized tf.Example.\n\nRaises:\n ValueError: An error when the given tf.Example is not a list.", "source": "github_repos"} +{"code": "def matches_any(patterns: List[Pattern[str]], line: str) -> bool:\n stripped_line = line.strip()\n for pattern in patterns:\n if pattern.match(stripped_line):\n return True\n return False", "docstring": "Checks if the line matches any of the given patterns.\n\nArgs:\n patterns: A list of compiled regular expression patterns.\n line: The line to check for matches.\n\nReturns:\n True if the line matches any of the patterns, False otherwise.", "source": "github_repos"} +{"code": "def _channel_flatten_input(x, data_format):\n graph = ops.get_default_graph()\n cache_key = (graph, x.ref(), data_format)\n if cache_key not in _channel_flatten_input_cache:\n x_shape = array_ops.shape(x)\n neg_ones = constant_op.constant([-1], dtype=x_shape.dtype)\n if data_format == b'NCHW':\n order = [1, 0, 2, 3, 4]\n shape = array_ops.concat([x_shape[1:2], neg_ones, x_shape[3:]], axis=0)\n reverse_order = order\n else:\n order = [1, 2, 3, 0, 4]\n shape = array_ops.concat([x_shape[1:4], neg_ones], axis=0)\n reverse_order = [3, 0, 1, 2, 4]\n x = array_ops.transpose(x, order)\n reverse_shape = array_ops.shape(x)\n x = array_ops.reshape(x, shape)\n outputs = (x, reverse_order, reverse_shape)\n _channel_flatten_input_cache[cache_key] = outputs\n else:\n outputs = _channel_flatten_input_cache[cache_key]\n return outputs", "docstring": "Merge the stack dimension with the channel dimension.\n\n If S is pfor's stacking dimension, then,\n - for SNCHW, we transpose to NSCHW. If N dimension has size 1, the transpose\n should be cheap.\n - for SNHWC, we transpose to NHWSC.\n We then merge the S and C dimension.\n\nArgs:\n x: tensor_lib.Tensor to transform.\n data_format: \"NCHW\" or \"NHWC\".\n\nReturns:\n A 3-element tuple with the transformed value, along with the shape for\n reshape and order for transpose required to transform back.", "source": "github_repos"} +{"code": "def extrapolation_step():\n\n def step_fn(time, next_time, coord_grid, value_grid, boundary_conditions, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, num_steps_performed, dtype=None, name=None):\n \"\"\"Performs the step.\"\"\"\n del num_steps_performed\n name = name or 'extrapolation_step'\n return parabolic_equation_step(time, next_time, coord_grid, value_grid, boundary_conditions, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, time_marching_scheme=extrapolation_scheme, dtype=dtype, name=name)\n return step_fn", "docstring": "Creates a stepper function with Extrapolation time marching scheme.\n\n Extrapolation scheme combines two half-steps and the full time step to obtain\n desirable properties. See more details below in `extrapolation_scheme`.\n\n It is slower than Crank-Nicolson scheme, but deals better with value grids\n that have discontinuities. Consider also `oscillation_damped_crank_nicolson`,\n an efficient combination of Crank-Nicolson and Extrapolation schemes.\n\nReturns:\n Callable to be used in finite-difference PDE solvers (see fd_solvers.py).", "source": "github_repos"} +{"code": "def multiply_no_nan(x, y, name=None):\n with ops.name_scope(name, 'multiply_no_nan', [x, y]) as name:\n x = ops.convert_to_tensor(x, name='x')\n y = ops.convert_to_tensor(y, name='y', dtype=x.dtype.base_dtype)\n x_dtype = x.dtype.base_dtype\n y_dtype = y.dtype.base_dtype\n if x_dtype != y_dtype:\n raise TypeError(f'`x` and `y` must have the same dtype, got {x_dtype!r} != {y_dtype!r}')\n return gen_math_ops.mul_no_nan(x, y, name=name)", "docstring": "Computes the product of x and y and returns 0 if the y is zero, even if x is NaN or infinite.\n\n Note this is noncommutative: if y is NaN or infinite and x is 0, the result\n will be NaN.\n\nArgs:\n x: A `Tensor`. Must be one of the following types: `float32`, `float64`.\n y: A `Tensor` whose dtype is compatible with `x`.\n name: A name for the operation (optional).\n\nReturns:\n The element-wise value of the x times y.", "source": "github_repos"} +{"code": "def __init__(self, image_processor=None, tokenizer=None, **kwargs):\n feature_extractor = None\n if 'feature_extractor' in kwargs:\n warnings.warn('The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor` instead.', FutureWarning)\n feature_extractor = kwargs.pop('feature_extractor')\n image_processor = image_processor if image_processor is not None else feature_extractor\n if image_processor is None:\n raise ValueError('You need to specify an `image_processor`.')\n if tokenizer is None:\n raise ValueError('You need to specify a `tokenizer`.')\n super().__init__(image_processor, tokenizer)\n self.current_processor = self.image_processor", "docstring": "Constructs a FLAVA processor which wraps a FLAVA image processor and a FLAVA tokenizer into a single processor.\n\n [`FlavaProcessor`] offers all the functionalities of [`FlavaImageProcessor`] and [`BertTokenizerFast`]. See the\n [`~FlavaProcessor.__call__`] and [`~FlavaProcessor.decode`] for more information.\n\nArgs:\n image_processor ([`FlavaImageProcessor`], *optional*): The image processor is a required input.\n tokenizer ([`BertTokenizerFast`], *optional*): The tokenizer is a required input.", "source": "github_repos"} +{"code": "def to_struct(self, from_api: dict=None, from_json: dict=None, indent: int=2) -> str:\n if from_api:\n from_json = self.to_json(from_api=from_api)\n fields = []\n spaces = ' ' * indent\n for key, value in from_json.items():\n if not isinstance(value, dict):\n continue\n if value.get('type', 'record') == 'record':\n fields.append('%sSTRUCT(\\n%s\\n%s) AS %s' % (spaces, self.to_struct(from_json=value, indent=indent + 2), spaces, key))\n elif value['type'] == 'array':\n if 'enum' in value['items']:\n fields.append('%s[%s\\n%s] AS %s' % (spaces, 'STRING', spaces, key))\n else:\n fields.append('%s[STRUCT(\\n%s\\n%s)] AS %s' % (spaces, self.to_struct(from_json=value['items'], indent=indent + 2), spaces, key))\n else:\n fields.append('%s%s AS %s' % (spaces, value['type'].upper(), key))\n return ',\\n'.join(fields)", "docstring": "Translates a Discovery API Document schema to a BigQuery STRUCT.\n\n Recursively crawls the discovery document reference tree to build struct.\n Leverages recursion depth passed in constructor to stop if necessary.\n\nArgs:\n from_api: the api schema to extrapolate\n from_json: new object with references replaced, not passed by caller\n parents: used to track recursion depth for a specific schema branch\n\nReturns:\n A BigQuery STRUCT object that can be pasted into a query.", "source": "github_repos"} +{"code": "def constant_value(pred):\n if isinstance(pred, tensor.Tensor):\n return tensor_util.constant_value(pred)\n if pred in {0, 1}:\n return bool(pred)\n if isinstance(pred, bool):\n return pred\n if isinstance(pred, variables.Variable):\n return None\n raise TypeError('`pred` must be a Tensor, or a Python bool, or 1 or 0. Found instead: %s' % type(pred))", "docstring": "Return the bool value for `pred`, or None if `pred` had a dynamic value.\n\nArgs:\n pred: A scalar, either a Python bool or a TensorFlow boolean variable\n or tensor, or the Python integer 1 or 0.\n\nReturns:\n True or False if `pred` has a constant boolean value, None otherwise.\n\nRaises:\n TypeError: If `pred` is not a Variable, Tensor or bool, or Python\n integer 1 or 0.", "source": "github_repos"} +{"code": "def WorkerMessages(self, request, global_params=None):\n config = self.GetMethodConfig('WorkerMessages')\n return self._RunMethod(config, request, global_params=global_params)", "docstring": "Send a worker_message to the service.\n\nArgs:\n request: (DataflowProjectsWorkerMessagesRequest) input message\n global_params: (StandardQueryParameters, default: None) global arguments\n\nReturns:\n (SendWorkerMessagesResponse) The response message.", "source": "github_repos"} +{"code": "def coerce(lhs: FhirPathDataType, rhs: FhirPathDataType) -> FhirPathDataType:\n if not is_coercible(lhs, rhs):\n raise TypeError(f'Unsupported Standard SQL coercion between {lhs} and {rhs}.')\n if isinstance(rhs, _Any) or isinstance(lhs, _Any):\n return _Any\n if rhs in lhs.supported_coercion:\n return rhs\n else:\n return lhs", "docstring": "Performs implicit type coercion between two datatypes.\n\n See more at: https://hl7.org/fhirpath/#conversion.\n\nArgs:\n lhs: The left operand.\n rhs: The right operand.\n\nReturns:\n The resulting coerced datatype, if successful.\n\nRaises:\n TypeError: In the event that coercion is not supported.\n ValueError: In the event that a coercion cycle is detected.", "source": "github_repos"} +{"code": "def embedding_feature(self):\n return HardwareFeature._embedding_feature_proto_to_string(self.tpu_hardware_feature_proto.embedding_feature)", "docstring": "TPU embedding feature.\n\nReturns:\n An EmbeddingFeature enum.", "source": "github_repos"} +{"code": "def __init__(self, initializer, num_oov_buckets, lookup_key_dtype=None, name=None, experimental_is_anonymous=False):\n if num_oov_buckets <= 0:\n raise ValueError('`num_oov_buckets` must be > 0; use StaticHashTable.')\n if name:\n name = name.rstrip('/')\n if initializer:\n if lookup_key_dtype is None:\n lookup_key_dtype = initializer.key_dtype\n supported_table_key_dtypes = (dtypes.int64, dtypes.string)\n if initializer.key_dtype not in supported_table_key_dtypes:\n raise TypeError('Invalid `key_dtype`, expected one of %s, but got %s.' % (supported_table_key_dtypes, initializer.key_dtype))\n if initializer.key_dtype.is_integer != lookup_key_dtype.is_integer:\n raise TypeError('Invalid `key_dtype`, expected %s but got %s.' % ('integer' if lookup_key_dtype.is_integer else 'non-integer', initializer.key_dtype))\n if initializer.value_dtype != dtypes.int64:\n raise TypeError('Invalid `value_dtype`, expected %s but got %s.' % (dtypes.int64, initializer.value_dtype))\n if isinstance(initializer, trackable_base.Trackable):\n self._initializer = self._track_trackable(initializer, '_initializer')\n self._table = HashTable(initializer, default_value=-1, experimental_is_anonymous=experimental_is_anonymous)\n name = name or self._table.name\n else:\n lookup_key_dtype = dtypes.string\n self._table = None\n name = name or 'hash_bucket'\n if not lookup_key_dtype.is_integer and dtypes.string != lookup_key_dtype:\n raise TypeError(f'Invalid `key_dtype`, expected integer or string, got {lookup_key_dtype}')\n self._num_oov_buckets = num_oov_buckets\n self._table_name = None\n if name is not None:\n self._table_name = name.split('/')[-1]\n super(StaticVocabularyTable, self).__init__(lookup_key_dtype, dtypes.int64)", "docstring": "Construct a `StaticVocabularyTable` object.\n\nArgs:\n initializer: A `TableInitializerBase` object that contains the data used\n to initialize the table. If None, then we only use out-of-vocab buckets.\n num_oov_buckets: Number of buckets to use for out-of-vocabulary keys. Must\n be greater than zero. If out-of-vocab buckets are not required, use\n `StaticHashTable` instead.\n lookup_key_dtype: Data type of keys passed to `lookup`. Defaults to\n `initializer.key_dtype` if `initializer` is specified, otherwise\n `tf.string`. Must be string or integer, and must be castable to\n `initializer.key_dtype`.\n name: A name for the operation (optional).\n experimental_is_anonymous: Whether to use anonymous mode for the\n table (default is False). In anonymous mode, the table\n resource can only be accessed via a resource handle. It can't\n be looked up by a name. When all resource handles pointing to\n that resource are gone, the resource will be deleted\n automatically.\n\nRaises:\n ValueError: when `num_oov_buckets` is not positive.\n TypeError: when lookup_key_dtype or initializer.key_dtype are not\n integer or string. Also when initializer.value_dtype != int64.", "source": "github_repos"} +{"code": "def non_serializable():\n\n def _apply_fn(dataset):\n \"\"\"Function from `Dataset` to `Dataset` that applies the transformation.\"\"\"\n return _NonSerializableDataset(dataset)\n return _apply_fn", "docstring": "A non-serializable identity transformation.\n\nReturns:\n A `Dataset` transformation function, which can be passed to\n `tf.data.Dataset.apply`.", "source": "github_repos"} +{"code": "def get_int(self, min_int=_MIN_INT, max_int=_MAX_INT):\n return self.fdp.ConsumeIntInRange(min_int, max_int)", "docstring": "Consume a signed integer with given constraints.\n\nArgs:\n min_int: Minimum allowed integer.\n max_int: Maximum allowed integer.\n\nReturns:\n Consumed integer based on input bytes and constraints.", "source": "github_repos"} +{"code": "def run_schedule(inputs: Dict[EventSetNode, EventSet], schedule: Schedule, verbose: int, check_execution: bool, force_garbage_collector_interval: Optional[float]=10) -> Dict[EventSetNode, EventSet]:\n data = {**inputs}\n gc_begin_time = time.time()\n num_steps = len(schedule.steps)\n for step_idx, step in enumerate(schedule.steps):\n operator_def = step.op.definition\n implementation_cls = implementation_lib.get_implementation_class(operator_def.key)\n implementation = implementation_cls(step.op)\n if verbose == 1:\n print(f' {step_idx + 1} / {num_steps}: {step.op.operator_key()}', file=sys.stderr, end='', flush=True)\n elif verbose >= 2:\n print('=============================', file=sys.stderr)\n print(f'{step_idx + 1} / {num_steps}: Run {step.op}', file=sys.stderr, flush=True)\n operator_inputs = {input_key: data[input_node] for input_key, input_node in step.op.inputs.items()}\n if verbose >= 2:\n print(f'Inputs:\\n{operator_inputs}\\n', file=sys.stderr, flush=True)\n begin_time = time.perf_counter()\n if check_execution:\n operator_outputs = implementation.call(**operator_inputs)\n else:\n operator_outputs = implementation(**operator_inputs)\n end_time = time.perf_counter()\n if verbose == 1:\n print(f' [{end_time - begin_time:.5f} s]', file=sys.stderr, flush=True)\n elif verbose >= 2:\n print(f'Outputs:\\n{operator_outputs}\\n', file=sys.stderr)\n print(f'Duration: {end_time - begin_time} s', file=sys.stderr, flush=True)\n for output_key, output_node in step.op.outputs.items():\n output_evset = operator_outputs[output_key]\n output_evset._internal_node = output_node\n data[output_node] = output_evset\n for node in step.released_nodes:\n assert node in data\n del data[node]\n if force_garbage_collector_interval is not None and time.time() - gc_begin_time >= force_garbage_collector_interval:\n begin_gc = time.time()\n if verbose >= 2:\n print('Garbage collection', file=sys.stderr, flush=True, end='')\n gc.collect()\n gc_begin_time = time.time()\n if verbose >= 2:\n print(f' [{gc_begin_time - begin_gc:.5f} s]', file=sys.stderr, flush=True)\n return data", "docstring": "Evaluates a schedule on a dictionary of input\n [`EventSets`][temporian.EventSet].\n\nArgs:\n inputs: Mapping of EventSetNodes to materialized EventSets.\n schedule: Sequence of operators to apply on the data.\n verbose: If >0, prints details about the execution on the standard error\n output. The larger the number, the more information is displayed.\n check_execution: If `True`, data of the intermediate results of the\n operators is checked against its expected structure and raises if\n it differs.\n force_garbage_collector_interval: If set, triggers the garbage\n collection every \"force_garbage_collector_interval\" seconds.", "source": "github_repos"} +{"code": "def __init__(self, name='hinge', dtype=None):\n super().__init__(fn=hinge, name=name, dtype=dtype)\n self._direction = 'down'", "docstring": "Computes the hinge metric between `y_true` and `y_pred`.\n\n `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are\n provided we will convert them to -1 or 1.\n\nArgs:\n name: (Optional) string name of the metric instance.\n dtype: (Optional) data type of the metric result.\n\nExample:\n >>> m = keras.metrics.Hinge()\n >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])\n >>> m.result()\n 1.3\n >>> m.reset_state()\n >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],\n ... sample_weight=[1, 0])\n >>> m.result()\n 1.1", "source": "github_repos"} +{"code": "def minutes(value: Union[int, float]) -> Duration:\n return float(value * 60)", "docstring": "Converts input value from minutes to a `Duration` in seconds.\n\nExample:\n ```python\n >>> timestamps = [tp.duration.minutes(i) for i in [5, 10, 30]]\n >>> timestamps\n [300.0, 600.0, 1800.0]\n\n >>> # Usage in a window operation\n >>> a = tp.event_set(timestamps=timestamps, features={\"f1\": [1, 5, -5]})\n >>> a.moving_sum(window_length=tp.duration.minutes(6))\n indexes: ...\n timestamps: [ 300. 600. 1800.]\n 'f1': [ 1 6 -5]\n ...\n\n ```\n\nArgs:\n value: Number of minutes.\n\nReturns:\n Equivalent number of seconds.", "source": "github_repos"} +{"code": "def _VerifyValues(self, image, ksizes, strides, rates, padding, patches):\n ksizes = [1] + ksizes + [1]\n strides = [1] + strides + [1]\n rates = [1] + rates + [1]\n for dtype in [np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype]:\n out_tensor = array_ops.extract_image_patches(constant_op.constant(image, dtype=dtype), ksizes=ksizes, strides=strides, rates=rates, padding=padding, name='im2col')\n self.assertAllClose(np.array(patches, dtype=dtype), self.evaluate(out_tensor))", "docstring": "Tests input-output pairs for the ExtractImagePatches op.\n\nArgs:\n image: Input tensor with shape: [batch, in_rows, in_cols, depth].\n ksizes: Patch size specified as: [ksize_rows, ksize_cols].\n strides: Output strides, specified as [stride_rows, stride_cols].\n rates: Atrous rates, specified as [rate_rows, rate_cols].\n padding: Padding type.\n patches: Expected output.", "source": "github_repos"} +{"code": "def initial_value(self):\n raise NotImplementedError", "docstring": "Returns the Tensor used as the initial value for the variable.\n\n Note that this is different from `initialized_value()` which runs\n the op that initializes the variable before returning its value.\n This method returns the tensor that is used by the op that initializes\n the variable.\n\nReturns:\n A `Tensor`.", "source": "github_repos"} +{"code": "def from_seed(cls, seed, alg=None):\n if alg is None:\n alg = DEFAULT_ALGORITHM\n alg = random_ops_util.convert_alg_to_int(alg)\n state = create_rng_state(seed, alg)\n return cls(state=state, alg=alg)", "docstring": "Creates a generator from a seed.\n\n A seed is a 1024-bit unsigned integer represented either as a Python\n integer or a vector of integers. Seeds shorter than 1024-bit will be\n padded. The padding, the internal structure of a seed and the way a seed\n is converted to a state are all opaque (unspecified). The only semantics\n specification of seeds is that two different seeds are likely to produce\n two independent generators (but no guarantee).\n\nArgs:\n seed: the seed for the RNG.\n alg: (optional) the RNG algorithm. If None, it will be auto-selected. See\n `__init__` for its possible values.\n\nReturns:\n The new generator.", "source": "github_repos"} +{"code": "def __init__(self, dataset, coordinator):\n if isinstance(dataset, input_lib.DistributedDataset):\n original_dataset = dataset._original_dataset\n serialized = serialize_dataset_to_graph(original_dataset)\n\n def dataset_fn():\n deserialized = deserialize_dataset_from_graph(serialized, original_dataset.element_spec)\n dataset.build(dataset_to_replace=deserialized)\n return dataset\n elif isinstance(dataset, input_lib.DistributedDatasetsFromFunction):\n\n def dataset_fn():\n dataset.build()\n return dataset\n elif isinstance(dataset, dataset_ops.Dataset):\n serialized = serialize_dataset_to_graph(dataset)\n\n def dataset_fn():\n return deserialize_dataset_from_graph(serialized, dataset.element_spec)\n else:\n raise ValueError('Unexpected dataset type!')\n super(PerWorkerDatasetFromDataset, self).__init__(dataset_fn, coordinator)", "docstring": "Makes an iterable from datasets created by the given dataset.\n\n It creates a dataset_fn which deserializes a dataset from a graph under the\n hood.\n\nArgs:\n dataset: A tf.data.Dataset, a DistributedDataset or a\n DistributedDatasetsFromFunction\n coordinator: a `ClusterCoordinator` object, used to create dataset\n resources.", "source": "github_repos"} +{"code": "def iterate_nested(nd: NestedDict, previous_keys: Optional[KeyList]=None) -> Iterator[Tuple[KeyList, LeafType]]:\n if previous_keys is None:\n previous_keys = []\n for k, v in nd.items():\n keys = previous_keys + [k]\n if not _is_nested(v):\n yield (keys, v)\n else:\n as_dict = dataclasses.asdict(v) if dataclasses.is_dataclass(v) else v\n for val in iterate_nested(as_dict, keys):\n yield val", "docstring": "Creates an iterator over every leaf value in depth first order.\n\n Iterates over a nested dictionary in depth first order. The order in which\n the peer keys are traversed is not guaranteed (same as for the keys of a\n dictionary).\n\n ```Example\n nested_dict = {'a': 1, 'b': [2, 3, 4], 'c': {'d': 8}}\n for k, v in iterate_nested(nested_dict):\n print('_'.join(k), v)\n # Prints out:\n # a: 1\n # b: [2, 3, 4]\n # c_d: 8\n ```\n\nArgs:\n nd: The dictionary to be traversed.\n previous_keys: If supplied, the computed key list will be a join of the\n previous_keys and the current keys.\n\nYields:\n A tuple of the key path and the value for each leaf node.", "source": "github_repos"} +{"code": "def get_c_function(self, name):\n self.ensure_initialized()\n return c_api_util.ScopedTFFunction(pywrap_tfe.TFE_ContextGetFunction(self._handle, name), name)", "docstring": "Get a C API TF_Function from the context.\n\nArgs:\n name: Name of the function to get.\n\nReturns:\n A ScopedTFFunction wrapping the C API TF_Function.", "source": "github_repos"} +{"code": "def add_update(self, updates, inputs=None):\n if inputs is not None:\n tf_logging.warning('`add_update` `inputs` kwarg has been deprecated. You no longer need to pass a value to `inputs` as it is being automatically inferred.')\n call_context = base_layer_utils.call_context()\n if call_context.in_keras_graph:\n return\n if not call_context.frozen:\n for update in nest.flatten(updates):\n if callable(update):\n update()", "docstring": "Add update op(s), potentially dependent on layer inputs.\n\n Weight updates (for instance, the updates of the moving mean and variance\n in a BatchNormalization layer) may be dependent on the inputs passed\n when calling a layer. Hence, when reusing the same layer on\n different inputs `a` and `b`, some entries in `layer.updates` may be\n dependent on `a` and some on `b`. This method automatically keeps track\n of dependencies.\n\n This call is ignored when eager execution is enabled (in that case, variable\n updates are run on the fly and thus do not need to be tracked for later\n execution).\n\nArgs:\n updates: Update op, or list/tuple of update ops, or zero-arg callable\n that returns an update op. A zero-arg callable should be passed in\n order to disable running the updates by setting `trainable=False`\n on this Layer, when executing in Eager mode.\n inputs: Deprecated, will be automatically inferred.", "source": "github_repos"} +{"code": "def wait_at_barrier(self, barrier_id, timeout_in_ms):\n ensure_initialized()\n pywrap_tfe.TFE_WaitAtBarrier(self._context_handle, barrier_id, timeout_in_ms)", "docstring": "Blocks until all coordinated tasks are at the barrier.\n\n The barrier may fail if it times out or if one of the tasks is unhealthy.\n\nArgs:\n barrier_id: Unique string identifying the barrier.\n timeout_in_ms: Duration before the barrier times out and fails.", "source": "github_repos"} +{"code": "def param_static_shapes(cls, sample_shape):\n if isinstance(sample_shape, tensor_shape.TensorShape):\n if not sample_shape.is_fully_defined():\n raise ValueError('TensorShape sample_shape must be fully defined')\n sample_shape = sample_shape.as_list()\n params = cls.param_shapes(sample_shape)\n static_params = {}\n for name, shape in params.items():\n static_shape = tensor_util.constant_value(shape)\n if static_shape is None:\n raise ValueError('sample_shape must be a fully-defined TensorShape or list/tuple')\n static_params[name] = tensor_shape.TensorShape(static_shape)\n return static_params", "docstring": "param_shapes with static (i.e. `TensorShape`) shapes.\n\n This is a class method that describes what key/value arguments are required\n to instantiate the given `Distribution` so that a particular shape is\n returned for that instance's call to `sample()`. Assumes that the sample's\n shape is known statically.\n\n Subclasses should override class method `_param_shapes` to return\n constant-valued tensors when constant values are fed.\n\nArgs:\n sample_shape: `TensorShape` or python list/tuple. Desired shape of a call\n to `sample()`.\n\nReturns:\n `dict` of parameter name to `TensorShape`.\n\nRaises:\n ValueError: if `sample_shape` is a `TensorShape` and is not fully defined.", "source": "github_repos"} +{"code": "def stop(save=True):\n global _profiler\n with _profiler_lock:\n if _profiler is None:\n raise errors.UnavailableError(None, None, 'Cannot export profiling results. No profiler is running.')\n if save:\n try:\n _profiler.export_to_tb()\n except Exception:\n _profiler = None\n raise\n _profiler = None", "docstring": "Stops the current profiling session.\n\n The profiler session will be stopped and profile results can be saved.\n\nArgs:\n save: An optional variable to save the results to TensorBoard. Default True.\n\nRaises:\n UnavailableError: If there is no active profiling session.", "source": "github_repos"} +{"code": "def _is_framework_filename(filename):\n for pattern in _EXTERNAL_FILENAME_PATTERNS:\n if pattern.search(filename):\n return False\n for pattern in _FRAMEWORK_FILENAME_PATTERNS:\n if pattern.search(filename):\n return True\n for prefix in _FRAMEWORK_PATH_PREFIXES:\n if filename.startswith(prefix):\n return True\n return False", "docstring": "Returns whether a filename should be considered a part of the framework.\n\n A file is part of the framework if it does not match a pattern in\n _EXTERNAL_FILENAME_PATTERNS and it either matches a pattern in\n _FRAMEWORK_FILENAME_PATTERNS or starts with a _FRAMEWORK_PATH_PREFIXES prefix.\n\nArgs:\n filename: A filename string.\n\nReturns:\n Whether the filename should be considered to be internal to the\n TensorFlow framework for the purposes of reporting errors.", "source": "github_repos"} +{"code": "def recipe_bucket(config, auth_write, bucket_bucket, bucket_emails, bucket_groups):\n bucket(config, {'auth': auth_write, 'bucket': bucket_bucket, 'emails': bucket_emails, 'groups': bucket_groups})", "docstring": "Create and permission a bucket in Storage.\n\nArgs:\n auth_write (authentication) - Credentials used for writing data.\n bucket_bucket (string) - Name of Google Cloud Bucket to create.\n bucket_emails (string_list) - Comma separated emails.\n bucket_groups (string_list) - Comma separated groups.", "source": "github_repos"} +{"code": "def transform_feature(self, transformation_cache, state_manager):\n pass", "docstring": "Returns intermediate representation (usually a `Tensor`).\n\n Uses `transformation_cache` to create an intermediate representation\n (usually a `Tensor`) that other feature columns can use.\n\n Example usage of `transformation_cache`:\n Let's say a Feature column depends on raw feature ('raw') and another\n `FeatureColumn` (input_fc). To access corresponding `Tensor`s,\n transformation_cache will be used as follows:\n\n ```python\n raw_tensor = transformation_cache.get('raw', state_manager)\n fc_tensor = transformation_cache.get(input_fc, state_manager)\n ```\n\nArgs:\n transformation_cache: A `FeatureTransformationCache` object to access\n features.\n state_manager: A `StateManager` to create / access resources such as\n lookup tables.\n\nReturns:\n Transformed feature `Tensor`.", "source": "github_repos"} +{"code": "def __init__(self, tensor, slice_spec, name, dtype=None, device=None):\n self._tensor = tensor\n self.slice_spec = slice_spec\n self.name = name\n if callable(self._tensor):\n if dtype is None or device is None:\n raise AssertionError('When passing a callable `tensor` to a SaveSpec, an explicit dtype and device must be provided.')\n self.dtype = dtype\n self.device = device\n else:\n self.dtype = tensor.dtype\n if device is not None:\n self.device = device\n else:\n self.device = tensor.device", "docstring": "Creates a `SaveSpec` object.\n\nArgs:\n tensor: the tensor to save or callable that produces a tensor to save.\n If the value is `None`, the `SaveSpec` is ignored.\n slice_spec: the slice to be saved. See `Variable.SaveSliceInfo`.\n name: the name to save the tensor under.\n dtype: The data type of the Tensor. Required if `tensor` is callable.\n Used for error checking in the restore op.\n device: The device generating and consuming this tensor. Required if\n `tensor` is callable. Used to group objects to save by device.", "source": "github_repos"} +{"code": "def split(tensor, split_dimension, num_devices, assign_tuple_sharding=False, use_sharding_op=False, input_shape=None):\n return Sharding.split(tensor, split_dimension, num_devices, input_shape).apply_to_tensor(tensor, assign_tuple_sharding=assign_tuple_sharding, use_sharding_op=use_sharding_op)", "docstring": "Returns a tensor that is split along the given dimension.\n\nArgs:\n tensor: A tf.Tensor to split.\n split_dimension: The dimension to split.\n num_devices: The number of devices to partition the dimension.\n assign_tuple_sharding: If the sharding type should be a tuple.\n use_sharding_op: If true, adds a sharding op to set the sharding.\n input_shape: The full shape of the input tensor.", "source": "github_repos"} +{"code": "def toInteger(self) -> 'Builder':\n return self._to_builder(_evaluation.ToIntegerFunction(self.node.context, self.node, []))", "docstring": "The FHIRPath toInteger() function.\n\n Casts its operand to an integer.\n Returns an empty collection if the operand can not be coerced to an integer.\n Raises a ValueError if the operand collection contains more than one\n element.\n\nReturns:\n An integer representation of its operand.", "source": "github_repos"} +{"code": "def _set_graph_parents(self, graph_parents):\n graph_parents = [] if graph_parents is None else graph_parents\n for i, t in enumerate(graph_parents):\n if t is None or not (linear_operator_util.is_ref(t) or tensor_util.is_tf_type(t)):\n raise ValueError('Graph parent item %d is not a Tensor; %s.' % (i, t))\n self._graph_parents = graph_parents", "docstring": "Set self._graph_parents. Called during derived class init.\n\n This method allows derived classes to set graph_parents, without triggering\n a deprecation warning (which is invoked if `graph_parents` is passed during\n `__init__`.\n\nArgs:\n graph_parents: Iterable over Tensors.", "source": "github_repos"} +{"code": "def _create_vocab_table_lookup_model_tf1(self, sess: session.Session) -> Tuple[core.Tensor, core.Tensor, core.Tensor]:\n asset_dir = self.create_tempdir('assets').full_path\n asset_file = os.path.join(asset_dir, 'vocab_file.txt')\n file_io.write_string_to_file(filename=asset_file, file_content='hello,model,quantization\\n')\n vocab_file = asset.Asset(asset_file)\n raw_vocab = io_ops.read_file(vocab_file)\n vocabs = ragged_string_ops.string_split_v2(string_ops.string_strip(raw_vocab), sep=',')\n kv_init = lookup_ops.KeyValueTensorInitializer(keys=vocabs, values=np.array([0, 1, 2]), value_dtype=dtypes.int64)\n table = lookup_ops.StaticVocabularyTable(kv_init, num_oov_buckets=5)\n input_vocabs_placeholder = array_ops.placeholder(dtypes.string, shape=(None,), name='input_vocabs')\n lookup_vals = math_ops.cast(table.lookup(input_vocabs_placeholder), dtypes.float32)\n matmul_input = array_ops_stack.stack([lookup_vals, lookup_vals])\n weight_row = array_ops.ones(shape=array_ops.shape(input_vocabs_placeholder), dtype=dtypes.float32)\n weight = array_ops.transpose_v2(array_ops_stack.stack([weight_row, weight_row]))\n output_tensor = math_ops.matmul(matmul_input, weight)\n return (input_vocabs_placeholder, lookup_vals, output_tensor)", "docstring": "Creates a simple model that initializes and lookups a vocab table.\n\n This model creates an asset file at \"vocab_file.txt\" containing\n comma-separated vocabularies. It also initializes a `StaticVocabularyTable`\n and performs a lookup with the input vocabs, which is a 1D tensor of\n strings.\n\nArgs:\n sess: Tensorflow Session to create the model in.\n\nReturns:\n (input_vocabs_placeholder, lookup_vals, output_tensor), where\n * input_vocabs_placeholder is a placeholder tensor of 1D strings\n * lookup_vals is an output tensor that is a direct result of table lookup\n * output_tensor is a float 2x2 matrix", "source": "github_repos"} +{"code": "def binary_crossentropy(target, output, from_logits=False):\n target = tf.convert_to_tensor(target)\n output = tf.convert_to_tensor(output)\n if len(target.shape) != len(output.shape):\n raise ValueError(f'Arguments `target` and `output` must have the same rank (ndim). Received: target.shape={target.shape}, output.shape={output.shape}')\n for e1, e2 in zip(target.shape, output.shape):\n if e1 is not None and e2 is not None and (e1 != e2):\n raise ValueError(f'Arguments `target` and `output` must have the same shape. Received: target.shape={target.shape}, output.shape={output.shape}')\n output, from_logits = _get_logits(output, from_logits, 'Sigmoid', 'binary_crossentropy')\n if from_logits:\n return tf.nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)\n output = tf.clip_by_value(output, backend.epsilon(), 1.0 - backend.epsilon())\n bce = target * tf.math.log(output)\n bce += (1 - target) * tf.math.log(1 - output)\n return -bce", "docstring": "Binary crossentropy between an output tensor and a target tensor.\n\nArgs:\n target: A tensor with the same shape as `output`.\n output: A tensor.\n from_logits: Whether `output` is expected to be a logits tensor.\n By default, we consider that `output`\n encodes a probability distribution.\n\nReturns:\n A tensor.", "source": "github_repos"} +{"code": "def _build_shuffle_scatter(reduced_shards, dst_devices):\n num_devices = len(dst_devices)\n out_tensors = []\n for d in range(0, num_devices):\n with ops.device(dst_devices[d]):\n out_tensors.append(array_ops.concat(reduced_shards, 0))\n return out_tensors", "docstring": "Build the scatter phase of shuffle all-reduce.\n\nArgs:\n reduced_shards: list of `tf.Tensor` fully reduced shards\n dst_devices: list of names of devices at which the fully-reduced value\n should be reconstituted.\n\nReturns:\n list of `tf.Tensor` scattered tensors.", "source": "github_repos"} +{"code": "def _pad_for_batching(self, pixel_values: List[np.ndarray], image_sizes: List[List[int]], data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None):\n max_shape = (max([size[0] for size in image_sizes]), max([size[1] for size in image_sizes]))\n pixel_values = [pad(image, padding=((0, max_shape[0] - size[0]), (0, max_shape[1] - size[1])), data_format=data_format, input_data_format=input_data_format) for image, size in zip(pixel_values, image_sizes)]\n return pixel_values", "docstring": "Pads images on the `num_of_patches` dimension with zeros to form a batch of same number of patches.\n\nArgs:\n pixel_values (`List[np.ndarray]`):\n An array of pixel values of each images of shape (`batch_size`, `num_patches`, `image_in_3D`)\n image_sizes (`List[List[int]]`):\n A list of sizes for each image in `pixel_values` in (height, width) format.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format for the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use the inferred format of the input image.\n\nReturns:\n List[`np.ndarray`]: The padded images.", "source": "github_repos"} +{"code": "def compiler_ir_generator(stage='hlo', device_name=None, platform_name=None):\n if device_name is not None:\n if platform_name is not None:\n raise ValueError('device_name and platform_name cannot be provided at the same time.')\n warnings.warn('device_name is being deprecated. Use platform_name.')\n device_name = maybe_get_device_name(device_name)\n res_bytes = context.context().get_compiler_ir(device_name=device_name, platform_name=platform_name, function_name=fn_name, flat_args=filtered_flat_specs, captured_inputs=concrete_fn.captured_inputs, stage=stage)\n if stage in ('stablehlo_serialized', 'hlo_serialized', 'optimized_hlo_serialized', 'optimized_hlo_proto_serialized'):\n return res_bytes\n else:\n return res_bytes.decode('utf-8')", "docstring": "Gets the compiler IR bytes.\n\nArgs:\n stage: The exported stage for the given function.\n device_name: The name of the device with the form as\n \"/job:localhost/replica:0/task:0/device:CPU:0\", \"/device:TPU:0\" etc.\n When this is used, actual device is needed for getting the compiler IR.\n platform_name: The name of the platform, e.g. \"TPU\". See the comment in\n `get_compiler_ir` in `context.py`.\n\nReturns:\n The compiler IR bytes.", "source": "github_repos"} +{"code": "def mlir_sparsify(input_data_str):\n return wrap_converter.wrapped_experimental_mlir_sparsify(input_data_str)", "docstring": "Sparsify `input_data_str` to encode sparse tensor with proper format.\n\nArgs:\n input_data_str: Input data in serialized form (e.g. a TFLITE model).\n\nReturns:\n Sparsified model in serialized form (e.g. a TFLITE model).", "source": "github_repos"} +{"code": "def make_initializer(self, dataset, name=None):\n with ops.name_scope(name, 'make_initializer') as name:\n dataset_output_types = nest.map_structure(lambda component_spec: component_spec._to_legacy_output_types(), dataset.element_spec)\n dataset_output_shapes = nest.map_structure(lambda component_spec: component_spec._to_legacy_output_shapes(), dataset.element_spec)\n dataset_output_classes = nest.map_structure(lambda component_spec: component_spec._to_legacy_output_classes(), dataset.element_spec)\n nest.assert_same_structure(self.output_types, dataset_output_types)\n nest.assert_same_structure(self.output_shapes, dataset_output_shapes)\n for iterator_class, dataset_class in zip(nest.flatten(self.output_classes), nest.flatten(dataset_output_classes)):\n if iterator_class is not dataset_class:\n raise TypeError(f'Expected output classes {self.output_classes!r} but got dataset with output classes {dataset_output_classes!r}.')\n for iterator_dtype, dataset_dtype in zip(nest.flatten(self.output_types), nest.flatten(dataset_output_types)):\n if iterator_dtype != dataset_dtype:\n raise TypeError(f'Expected output types {self.output_types!r} but got dataset with output types {dataset_output_types!r}.')\n for iterator_shape, dataset_shape in zip(nest.flatten(self.output_shapes), nest.flatten(dataset_output_shapes)):\n if not iterator_shape.is_compatible_with(dataset_shape):\n raise TypeError(f'Expected output shapes compatible with {self.output_shapes!r} but got dataset with output shapes {dataset_output_shapes!r}.')\n with ops.colocate_with(self._iterator_resource):\n return gen_dataset_ops.make_iterator(dataset._variant_tensor, self._iterator_resource, name=name)", "docstring": "Returns a `tf.Operation` that initializes this iterator on `dataset`.\n\nArgs:\n dataset: A `Dataset` whose `element_spec` if compatible with this\n iterator.\n name: (Optional.) A name for the created operation.\n\nReturns:\n A `tf.Operation` that can be run to initialize this iterator on the given\n `dataset`.\n\nRaises:\n TypeError: If `dataset` and this iterator do not have a compatible\n `element_spec`.", "source": "github_repos"} +{"code": "def test_noninlined_funcdef(self, mode):\n self._maybe_skip(mode)\n with ops.device(_get_device(mode)):\n random_seed.set_random_seed(0)\n x = _input([8, 8])\n y = _matmul_act(x)\n y = _example_noninlined_funcdef(y)\n optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=0.01)\n g = optimizer.compute_gradients(y, [x])\n output = (g, y)\n output_val_ref, output_val, cost_graph = self._run(mode, output)\n node_map = _build_node_map(cost_graph.node)\n self._assert_output_f16(mode, node_map, 'MatMul')\n tol = 0.01 if mode == 'mkl' else 0.001\n atol = 0.01 if test.is_built_with_rocm() else tol\n self.assertAllClose(output_val_ref, output_val, atol=atol, rtol=tol)", "docstring": "Test graph with non-inlined function subgraph.\n\n This requires the grappler pass to handle an OpDef that only appears in the\n graph's function registry instead of the global op registry.\n\nArgs:\n mode: Either 'cuda' or 'mkl'.", "source": "github_repos"} +{"code": "def resize(self, images: 'torch.Tensor', size: SizeDict, interpolation: Optional['F.InterpolationMode']=None, size_divisor: Optional[int]=None) -> 'torch.Tensor':\n if interpolation is None:\n interpolation = self.resample\n shorter = size.shortest_edge\n longer = int(MAX_LONGER_EDGE / MAX_SHORTER_EDGE * shorter)\n heights = images.shape[-2]\n widths = images.shape[-1]\n if heights < widths:\n new_heights = shorter\n new_widths = widths * (shorter / heights)\n else:\n new_heights = heights * (shorter / widths)\n new_widths = shorter\n if max(new_heights, new_widths) > longer:\n scale = longer / max(new_heights, new_widths)\n new_heights = new_heights * scale\n new_widths = new_widths * scale\n new_heights = int(new_heights + 0.5)\n new_widths = int(new_widths + 0.5)\n if size_divisor is not None:\n new_heights = new_heights // size_divisor * size_divisor\n new_widths = new_widths // size_divisor * size_divisor\n return F.resize(images, [new_heights, new_widths], interpolation=interpolation)", "docstring": "Resize an image or batch of images to specified size.\n\nArgs:\n images (`torch.Tensor`): Image or batch of images to resize.\n size (`Dict[str, int]`): Size dictionary with shortest_edge key.\n interpolation (`F.InterpolationMode`, *optional*): Interpolation method to use.\n size_divisor (`int`, *optional*): Value to ensure height/width are divisible by.\n\nReturns:\n `torch.Tensor`: Resized image or batch of images.", "source": "github_repos"} +{"code": "def report_file(config, auth, account, report_id=None, name=None, timeout=60, chunksize=DCM_CHUNK_SIZE):\n account_id, advertiser_id = parse_account(config, auth, account)\n file_json = report_fetch(config, auth, account, report_id, name, timeout)\n if file_json == False:\n return (None, None)\n elif file_json == True:\n return ('report_running.csv', None)\n else:\n filename = '%s_%s.csv' % (file_json['fileName'], file_json['dateRange']['endDate'].replace('-', ''))\n if chunksize:\n return (filename, media_download(API_DCM(config, auth).files().get_media(reportId=file_json['reportId'], fileId=file_json['id']).execute(False), chunksize, 'utf-8'))\n else:\n return (filename, StringIO(API_DCM(config, auth).files().get_media(reportId=file_json['reportId'], fileId=file_json['id']).execute().decode('utf-8')))", "docstring": "Retrieves most recent DCM file by name or ID, if in progress, waits for it to complete.\n\n Bulletproofing:\n https://developers.google.com/doubleclick-advertisers/v3.2/files/get\n\n Timeout is in minutes ( retries will happen at 1 minute interval, default\n total time is 60 minutes )\n If chunksize is set to 0 then the whole file is downloaded at once.\n\nArgs:\n * auth: (string) Either user or service.\n * account: (string) [account:advertiser@profile] token.\n * report_id: (int) ID of DCm report to fetch ( either or name ).\n * name: (string) Name of report to fetch ( either or report_id ).\n * timeout: (int) Minutes to wait for in progress report before giving up.\n * chunksize: (int) number of bytes to download at a time, for memory\n constrained systems.\n\nReturns:\n * (filename, iterator) if file exists and is ready to download in chunks.\n * (filename, file) if file exists and chunking is off.\n * ('report_running.csv', None) if report is in progress.\n * (None, None) if file does not exist.", "source": "github_repos"} +{"code": "def populate_conversion_metadata(model_object, metadata):\n try:\n metadata_builder = flatbuffers.Builder(0)\n metadata_builder.Finish(metadata.Pack(metadata_builder))\n buffer_field = schema_fb.BufferT()\n buffer_field.data = metadata_builder.Output()\n if not model_object.metadata:\n model_object.metadata = []\n else:\n for meta in model_object.metadata:\n if meta.name.decode('utf-8') == CONVERSION_METADATA_FIELD_NAME:\n model_object.buffers[meta.buffer] = buffer_field\n return model_object\n if not model_object.buffers:\n model_object.buffers = []\n model_object.buffers.append(buffer_field)\n metadata_field = schema_fb.MetadataT()\n metadata_field.name = CONVERSION_METADATA_FIELD_NAME\n metadata_field.buffer = len(model_object.buffers) - 1\n model_object.metadata.append(metadata_field)\n return model_object\n except Exception:\n return model_object", "docstring": "Add or update conversion metadata to a tflite model.\n\nArgs:\n model_object: A tflite model in object form.\n metadata: The conversion metadata.\n\nReturns:\n A tflite model object with embedded conversion metadata.", "source": "github_repos"} +{"code": "def map_structure(func, *structure, **check_types_dict):\n return nest_util.map_structure(nest_util.Modality.DATA, func, *structure, **check_types_dict)", "docstring": "Applies `func` to each entry in `structure` and returns a new structure.\n\n Applies `func(x[0], x[1], ...)` where x[i] is an entry in\n `structure[i]`. All structures in `structure` must have the same arity,\n and the return value will contain the results in the same structure.\n\nArgs:\n func: A callable that accepts as many arguments are there are structures.\n *structure: scalar, or tuple or list of constructed scalars and/or other\n tuples/lists, or scalars. Note: numpy arrays are considered scalars.\n **check_types_dict: only valid keyword argument is `check_types`. If set to\n `True` (default) the types of iterables within the structures have to be\n same (e.g. `map_structure(func, [1], (1,))` raises a `TypeError`\n exception). To allow this set this argument to `False`.\n\nReturns:\n A new structure with the same arity as `structure`, whose values correspond\n to `func(x[0], x[1], ...)` where `x[i]` is a value in the corresponding\n location in `structure[i]`. If there are different sequence types and\n `check_types` is `False` the sequence types of the first structure will be\n used.\n\nRaises:\n TypeError: If `func` is not callable or if the structures do not match\n each other by depth tree.\n ValueError: If no structure is provided or if the structures do not match\n each other by type.\n ValueError: If wrong keyword arguments are provided.", "source": "github_repos"} +{"code": "def binary_accuracy(y_true, y_pred, threshold=0.5):\n y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred)\n threshold = math_ops.cast(threshold, y_pred.dtype)\n y_pred = math_ops.cast(y_pred > threshold, y_pred.dtype)\n return backend.mean(math_ops.equal(y_true, y_pred), axis=-1)", "docstring": "Calculates how often predictions match binary labels.\n\n Standalone usage:\n >>> y_true = [[1], [1], [0], [0]]\n >>> y_pred = [[1], [1], [0], [0]]\n >>> m = tf.keras.metrics.binary_accuracy(y_true, y_pred)\n >>> assert m.shape == (4,)\n >>> m.numpy()\n array([1., 1., 1., 1.], dtype=float32)\n\nArgs:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n threshold: (Optional) Float representing the threshold for deciding whether\n prediction values are 1 or 0.\n\nReturns:\n Binary accuracy values. shape = `[batch_size, d0, .. dN-1]`", "source": "github_repos"} +{"code": "def __init__(self, gain=1.0):\n self.gain = gain", "docstring": "Initializer that generates the identity matrix.\n\n Only usable for generating 2D matrices.\n\nExample:\n >>> # Standalone usage:\n >>> initializer = Identity()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = Identity()\n >>> layer = Dense(3, kernel_initializer=initializer)\n\nArgs:\n gain: Multiplicative factor to apply to the identity matrix.", "source": "github_repos"} +{"code": "def save_pcoder(self, pcoder, *labels):\n raise NotImplementedError", "docstring": "Saves pcoder for given PCollection.\n\n Correct reading of PCollection from Cache requires PCoder to be known.\n This method saves desired PCoder for PCollection that will subsequently\n be used by sink(...), source(...), and, most importantly, read(...) method.\n The latter must be able to read a PCollection written by Beam using\n non-Beam IO.\n\nArgs:\n pcoder: A PCoder to be used for reading and writing a PCollection.\n *labels: List of labels for PCollection instance.", "source": "github_repos"} +{"code": "def __init__(self, mask_value=0.0, **kwargs):\n super().__init__(**kwargs)\n if isinstance(mask_value, dict) and mask_value.get('config', None):\n mask_value = deserialize_keras_object(mask_value)\n self.mask_value = mask_value\n self.supports_masking = True\n self._build_at_init()", "docstring": "Masks a sequence by using a mask value to skip timesteps.\n\n For each timestep in the input tensor (dimension #1 in the tensor),\n if all values in the input tensor at that timestep\n are equal to `mask_value`, then the timestep will be masked (skipped)\n in all downstream layers (as long as they support masking).\n\n If any downstream layer does not support masking yet receives such\n an input mask, an exception will be raised.\n\nExample:\n Consider a NumPy data array `x` of shape `(samples, timesteps, features)`,\n to be fed to an LSTM layer. You want to mask timestep #3 and #5 because you\n lack data for these timesteps. You can:\n\n - Set `x[:, 3, :] = 0.` and `x[:, 5, :] = 0.`\n - Insert a `Masking` layer with `mask_value=0.` before the LSTM layer:\n\n ```python\n samples, timesteps, features = 32, 10, 8\n inputs = np.random.random([samples, timesteps, features]).astype(np.float32)\n inputs[:, 3, :] = 0.\n inputs[:, 5, :] = 0.\n\n model = keras.models.Sequential()\n model.add(keras.layers.Masking(mask_value=0.0))\n model.add(keras.layers.LSTM(32))\n output = model(inputs)\n # The time step 3 and 5 will be skipped from LSTM calculation.\n ```\n\n Note: in the Keras masking convention, a masked timestep is denoted by\n a mask value of `False`, while a non-masked (i.e. usable) timestep\n is denoted by a mask value of `True`.", "source": "github_repos"} +{"code": "def get_bool(self):\n return self.fdp.ConsumeBool()", "docstring": "Consume a bool.\n\nReturns:\n Consumed a bool based on input bytes and constraints.", "source": "github_repos"} +{"code": "def value(self, row, col, device_name_filter=None, node_name_filter=None, op_type_filter=None):\n menu_item = None\n if col == 0:\n text = self._profile_datum_list[row].node_exec_stats.node_name\n elif col == 1:\n text = self._profile_datum_list[row].op_type\n elif col == 2:\n text = str(self.formatted_start_time[row])\n elif col == 3:\n text = str(self.formatted_op_time[row])\n elif col == 4:\n text = str(self.formatted_exec_time[row])\n elif col == 5:\n command = 'ps'\n if device_name_filter:\n command += ' --%s %s' % (_DEVICE_NAME_FILTER_FLAG, device_name_filter)\n if node_name_filter:\n command += ' --%s %s' % (_NODE_NAME_FILTER_FLAG, node_name_filter)\n if op_type_filter:\n command += ' --%s %s' % (_OP_TYPE_FILTER_FLAG, op_type_filter)\n command += ' %s --init_line %d' % (self._profile_datum_list[row].file_path, self._profile_datum_list[row].line_number)\n menu_item = debugger_cli_common.MenuItem(None, command)\n text = self._profile_datum_list[row].file_line_func\n else:\n raise IndexError('Invalid column index %d.' % col)\n return RL(text, font_attr=menu_item)", "docstring": "Get the content of a cell of the table.\n\nArgs:\n row: (int) row index.\n col: (int) column index.\n device_name_filter: Regular expression to filter by device name.\n node_name_filter: Regular expression to filter by node name.\n op_type_filter: Regular expression to filter by op type.\n\nReturns:\n A debuggre_cli_common.RichLine object representing the content of the\n cell, potentially with a clickable MenuItem.\n\nRaises:\n IndexError: if row index is out of range.", "source": "github_repos"} +{"code": "def forward(self, pixel_values: torch.FloatTensor, audio_values: torch.FloatTensor, pixel_mask: Optional[torch.FloatTensor]=None, audio_mask: Optional[torch.FloatTensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, labels: Optional[torch.LongTensor]=None) -> Union[Tuple[torch.FloatTensor], SequenceClassifierOutput]:\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n outputs = self.tvlt(pixel_values, audio_values, pixel_mask=pixel_mask, audio_mask=audio_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)\n sequence_output = outputs[0][:, 0]\n logits = self.classifier(sequence_output)\n loss = None\n if labels is not None:\n if self.config.loss_type == 'regression':\n loss_fct = MSELoss()\n loss = loss_fct(logits, labels)\n elif self.config.loss_type == 'classification':\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits, labels)\n if not return_dict:\n output = (logits,) + outputs[4:]\n return (loss,) + output if loss is not None else output\n return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)", "docstring": "labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):\n Labels for computing the audiovisual loss. Indices should be in `[0, ..., num_classes-1]` where num_classes\n refers to the number of classes in audiovisual tasks.\n\nReturns:\n\nExample:\n ```python\n >>> from transformers import TvltProcessor, TvltForAudioVisualClassification\n >>> import numpy as np\n >>> import torch\n\n >>> num_frames = 8\n >>> images = list(np.random.randn(num_frames, 3, 224, 224))\n >>> audio = list(np.random.randn(10000))\n >>> processor = TvltProcessor.from_pretrained(\"ZinengTang/tvlt-base\")\n >>> model = TvltForAudioVisualClassification.from_pretrained(\"ZinengTang/tvlt-base\")\n >>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors=\"pt\")\n\n >>> outputs = model(**input_dict)\n >>> loss = outputs.loss\n ```", "source": "github_repos"} +{"code": "def to(self, device: Union[str, 'torch.device'], *, non_blocking: bool=False) -> 'BatchEncoding':\n requires_backends(self, ['torch'])\n import torch\n if isinstance(device, str) or is_torch_device(device) or isinstance(device, int):\n self.data = {k: v.to(device=device, non_blocking=non_blocking) if isinstance(v, torch.Tensor) else v for k, v in self.data.items()}\n else:\n logger.warning(f'Attempting to cast a BatchEncoding to type {str(device)}. This is not supported.')\n return self", "docstring": "Send all values to device by calling `v.to(device, non_blocking=non_blocking)` (PyTorch only).\n\nArgs:\n device (`str` or `torch.device`): The device to put the tensors on.\n non_blocking (`bool`): Whether to perform the copy asynchronously.\n\nReturns:\n [`BatchEncoding`]: The same instance after modification.", "source": "github_repos"} +{"code": "def get_libstdcpp_version():\n key = 'libstdcpp_ver'\n out, err = run_shell_cmd(cmds_all[PLATFORM.lower()][key])\n if err and FLAGS.debug:\n print('Error in detecting libstdc++ version:\\n %s' % str(err))\n ver = out.split(b'_')[-1].replace(b'\\n', b'')\n return ver", "docstring": "Retrieves version of libstdc++ detected.\n\nReturns:\n String that is the version of libstdc++.\n e.g. '3.4.25'", "source": "github_repos"} +{"code": "def write(tag, tensor, step=None, metadata=None, name=None):\n with ops.name_scope(name, 'write_summary') as scope:\n if _summary_state.writer is None:\n return constant_op.constant(False)\n if step is None:\n step = get_step()\n if metadata is None:\n serialized_metadata = b''\n elif hasattr(metadata, 'SerializeToString'):\n serialized_metadata = metadata.SerializeToString()\n else:\n serialized_metadata = metadata\n\n def record():\n \"\"\"Record the actual summary and return True.\"\"\"\n if step is None:\n raise ValueError('No step set. Please specify one either through the `step` argument or through tf.summary.experimental.set_step()')\n with ops.device('cpu:0'):\n summary_tensor = tensor() if callable(tensor) else array_ops.identity(tensor)\n writer = _summary_state.writer\n summary_value = _maybe_convert_tensor_to_dtensor(writer, summary_tensor)\n step_value = _maybe_convert_tensor_to_dtensor(writer, step)\n write_summary_op = gen_summary_ops.write_summary(writer._resource, step_value, summary_value, tag, serialized_metadata, name=scope)\n with ops.control_dependencies([write_summary_op]):\n return constant_op.constant(True)\n op = smart_cond.smart_cond(should_record_summaries(), record, _nothing, name='summary_cond')\n if not context.executing_eagerly():\n ops.add_to_collection(ops.GraphKeys._SUMMARY_COLLECTION, op)\n return op", "docstring": "Writes a generic summary to the default SummaryWriter if one exists.\n\n This exists primarily to support the definition of type-specific summary ops\n like scalar() and image(), and is not intended for direct use unless defining\n a new type-specific summary op.\n\nArgs:\n tag: string tag used to identify the summary (e.g. in TensorBoard), usually\n generated with `tf.summary.summary_scope`\n tensor: the Tensor holding the summary data to write or a callable that\n returns this Tensor. If a callable is passed, it will only be called when\n a default SummaryWriter exists and the recording condition specified by\n `record_if()` is met.\n step: Explicit `int64`-castable monotonic step value for this summary. If\n omitted, this defaults to `tf.summary.experimental.get_step()`, which must\n not be None.\n metadata: Optional SummaryMetadata, as a proto or serialized bytes\n name: Optional string name for this op.\n\nReturns:\n True on success, or false if no summary was written because no default\n summary writer was available.\n\nRaises:\n ValueError: if a default writer exists, but no step was provided and\n `tf.summary.experimental.get_step()` is None.", "source": "github_repos"} +{"code": "def conv2d(x, kernel, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1)):\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format: ' + str(data_format))\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n x = nn.convolution(input=x, filter=kernel, dilation_rate=dilation_rate, strides=strides, padding=padding, data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = array_ops.transpose(x, (0, 3, 1, 2))\n return x", "docstring": "2D convolution.\n\nArgs:\n x: Tensor or variable.\n kernel: kernel tensor.\n strides: strides tuple.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: `\"channels_last\"` or `\"channels_first\"`.\n dilation_rate: tuple of 2 integers.\n\nReturns:\n A tensor, result of 2D convolution.\n\nRaises:\n ValueError: if `data_format` is neither `channels_last` or\n `channels_first`.", "source": "github_repos"} +{"code": "def _TensorArraySplitGrad(op: ops.Operation, flow):\n handle = op.inputs[0]\n dtype = op.get_attr('T')\n grad_source = _GetGradSource(flow)\n flow_out = array_ops.identity(op.outputs[0], 'flow_out')\n with ops.control_dependencies([flow_out]):\n flow = array_ops.identity(flow, 'write_barrier')\n g = tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow, colocate_with_first_write_call=False).grad(source=grad_source, flow=flow)\n grad = g.concat()\n return [None, grad, None, flow]", "docstring": "Gradient for TensorArraySplit.\n\nArgs:\n op: Forward TensorArraySplit op.\n flow: Gradient `Tensor` flow to TensorArraySplit.\n\nReturns:\n A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad.", "source": "github_repos"} +{"code": "def as_graph_element(self, obj, allow_tensor=True, allow_operation=True) -> Union[tensor_lib.Tensor, 'Operation']:\n if self._finalized:\n return self._as_graph_element_locked(obj, allow_tensor, allow_operation)\n with self._lock:\n return self._as_graph_element_locked(obj, allow_tensor, allow_operation)", "docstring": "Returns the object referred to by `obj`, as an `Operation` or `Tensor`.\n\n This function validates that `obj` represents an element of this\n graph, and gives an informative error message if it is not.\n\n This function is the canonical way to get/validate an object of\n one of the allowed types from an external argument reference in the\n Session API.\n\n This method may be called concurrently from multiple threads.\n\nArgs:\n obj: A `Tensor`, an `Operation`, or the name of a tensor or operation. Can\n also be any object with an `_as_graph_element()` method that returns a\n value of one of these types. Note: `_as_graph_element` will be called\n inside the graph's lock and so may not modify the graph.\n allow_tensor: If true, `obj` may refer to a `Tensor`.\n allow_operation: If true, `obj` may refer to an `Operation`.\n\nReturns:\n The `Tensor` or `Operation` in the Graph corresponding to `obj`.\n\nRaises:\n TypeError: If `obj` is not a type we support attempting to convert\n to types.\n ValueError: If `obj` is of an appropriate type but invalid. For\n example, an invalid string.\n KeyError: If `obj` is not an object in the graph.", "source": "github_repos"} +{"code": "def infer_return_type(c, input_types, debug=False, depth=5):\n try:\n if hashable(c) and c in known_return_types:\n return known_return_types[c]\n elif isinstance(c, types.FunctionType):\n return infer_return_type_func(c, input_types, debug, depth)\n elif isinstance(c, types.MethodType):\n if c.__self__ is not None:\n input_types = [Const(c.__self__)] + input_types\n return infer_return_type_func(c.__func__, input_types, debug, depth)\n elif isinstance(c, BoundMethod):\n input_types = [c.type] + input_types\n return infer_return_type_func(c.func, input_types, debug, depth)\n elif inspect.isclass(c):\n if c in typehints.DISALLOWED_PRIMITIVE_TYPES:\n return {list: typehints.List[Any], set: typehints.Set[Any], frozenset: typehints.FrozenSet[Any], tuple: typehints.Tuple[Any, ...], dict: typehints.Dict[Any, Any]}[c]\n return c\n elif c == getattr and len(input_types) == 2 and isinstance(input_types[1], Const):\n from apache_beam.typehints import opcodes\n return opcodes._getattr(input_types[0], input_types[1].value)\n elif isinstance(c, python_callable.PythonCallableWithSource):\n return infer_return_type(c._callable, input_types, debug, depth)\n else:\n return Any\n except TypeInferenceError:\n if debug:\n traceback.print_exc()\n return Any\n except Exception:\n if debug:\n sys.stdout.flush()\n raise\n else:\n return Any", "docstring": "Analyses a callable to deduce its return type.\n\nArgs:\n c: A Python callable to infer the return type of.\n input_types: A sequence of inputs corresponding to the input types.\n debug: Whether to print verbose debugging information.\n depth: Maximum inspection depth during type inference.\n\nReturns:\n A TypeConstraint that that the return value of this function will (likely)\n satisfy given the specified inputs.", "source": "github_repos"} +{"code": "def _CanDelete(self, cls):\n if not self._processed_count[cls.name]:\n return False\n return self._processed_count[cls.name] == self._total_count[cls.name]", "docstring": "Checks whether this class can be deleted.\n\n Returns whether all occurrences of this class as a type were due to\n constants we removed.\n\nArgs:\n cls: A pytd.Class.\n\nReturns:\n True if we can delete this class.", "source": "github_repos"} +{"code": "def _neg(x, name=None):\n return negative(x, name)", "docstring": "Computes numerical negative value element-wise.\n\n I.e., \\(y = -x\\).\n\nArgs:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`,\n `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.\n name: A name for the operation (optional).\n\nReturns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.", "source": "github_repos"} +{"code": "def _sub_entity_map(self, assignments, item, campaign):\n for assignment in assignments:\n placement = self._placement_dao.get(assignment, required=True)\n event_tag = self._event_tag_dao.get(assignment, required=True)\n creative = self._creative_dao.get(assignment, required=True)\n landing_page = None\n if assignment.get(FieldMap.AD_LANDING_PAGE_ID, '') != 'CAMPAIGN_DEFAULT':\n landing_page = self._landing_page_dao.get(assignment, required=True)\n if landing_page:\n assignment[FieldMap.AD_LANDING_PAGE_ID] = landing_page['id']\n if item:\n assignment[FieldMap.AD_ID] = item['id']\n assignment[FieldMap.AD_NAME] = item['name']\n if campaign:\n assignment[FieldMap.CAMPAIGN_ID] = campaign['id']\n assignment[FieldMap.CAMPAIGN_NAME] = campaign['name']\n if placement:\n assignment[FieldMap.PLACEMENT_ID] = placement['id']\n assignment[FieldMap.PLACEMENT_NAME] = placement['name']\n if creative:\n assignment[FieldMap.CREATIVE_ID] = creative['id']\n assignment[FieldMap.CREATIVE_NAME] = creative['name']\n if event_tag:\n assignment[FieldMap.EVENT_TAG_ID] = event_tag['id']\n assignment[FieldMap.EVENT_TAG_NAME] = event_tag['name']", "docstring": "Maps ids and names of sub entities so they can be updated in the Bulkdozer feed.\n\n When Bulkdozer is done processing an item, it writes back the updated names\n and ids of related objects, this method makes sure those are updated in the\n ad feed.\n\nArgs:\n assignments: List of child feeds to map.\n item: The DCM ad object that was updated or created.\n campaign: The campaign object associated with the ad.", "source": "github_repos"} +{"code": "def __init__(self, output_size: Union[int, Iterable[int]], reduce_function: Callable=tf.reduce_mean, data_format: Optional[str]=None, **kwargs) -> None:\n self.data_format = normalize_data_format(data_format)\n self.reduce_function = reduce_function\n self.output_size = (output_size,) if isinstance(output_size, int) else tuple(output_size)\n super().__init__(**kwargs)", "docstring": "Args:\n Average 1D Pooling with adaptive kernel size.\n output_size: An integer or tuple/list of a single integer, specifying pooled_features.\n The new size of output channels.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape `(batch, steps, channels)` while `channels_first` corresponds\n to inputs with shape `(batch, channels, steps)`.\n Input shape:\n - If `data_format='channels_last'`: 3D tensor with shape `(batch, steps, channels)`.\n - If `data_format='channels_first'`: 3D tensor with shape `(batch, channels, steps)`.\n Output shape:\n - If `data_format='channels_last'`: 3D tensor with shape `(batch_size, pooled_steps, channels)`.\n - If `data_format='channels_first'`: 3D tensor with shape `(batch_size, channels, pooled_steps)`.\n\n Adapted from [tensorflow-addon's adaptive pooling.py](\n https://github.com/tensorflow/addons/blob/8cec33fcaaf1cf90aec7bdd55a0fcdbb251ce5c2/tensorflow_addons/layers/adaptive_pooling.py#L90-L120\n )", "source": "github_repos"} +{"code": "def _subsample_labels(self, label):\n pos_idx, neg_idx = subsample_labels(label, self.batch_size_per_image, self.positive_fraction, 0)\n label.fill_(-1)\n label.scatter_(0, pos_idx, 1)\n label.scatter_(0, neg_idx, 0)\n return label", "docstring": "Randomly sample a subset of positive and negative examples, and overwrite the label vector to the ignore value\n (-1) for all elements that are not included in the sample.\n\nArgs:\n labels (Tensor): a vector of -1, 0, 1. Will be modified in-place and returned.", "source": "github_repos"} +{"code": "def transform_and_print_file(self, file_path: str, transformation: Optional[Callable[[Iterator[str]], Iterator[str]]]=None, output_stream: io.TextIOBase=cast(io.TextIOBase, sys.stdout)) -> None:\n if transformation is None:\n transformation = self.annotate_test_file\n if file_path == _STANDARD_IO_STREAMS:\n output_stream.writelines(transformation(sys.stdin))\n else:\n with open(file_path, 'r') as file_contents:\n output_stream.writelines(transformation(file_contents))", "docstring": "Reads from `file_path`, applies a transformation, and prints to `stdout`.\n\nArgs:\n file_path: The path to the input file. If this is equal to the constant\n `_STANDARD_IO_STREAMS` (i.e. the string \"-\"), the input will come from\n `stdin`.\n transformation: A function that takes an iterator over the lines of an HLO\n file and returns an iterator over the lines of the transformed file. If\n this is left as `None`, `self.annotate_test_file` will be used.\n output_stream: The stream to which the transformed file should be written.\n Defaults to `stdout`.", "source": "github_repos"} +{"code": "def affine_transform(boxes, angle, translate_x, translate_y, scale, shear_x, shear_y, height, width, center_x=None, center_y=None, bounding_box_format='xyxy'):\n if bounding_box_format != 'xyxy':\n raise NotImplementedError\n box_utils = BoundingBox()\n if backend_utils.in_tf_graph():\n box_utils.backend.set_backend('tensorflow')\n boxes = box_utils.affine(boxes, angle, translate_x, translate_y, scale, shear_x, shear_y, height, width, center_x=center_x, center_y=center_y)\n box_utils.backend.reset()\n return boxes", "docstring": "Applies an affine transformation to the bounding boxes.\n\n The `height` and `width` parameters are used to normalize the\n translation and scaling factors.\n\nArgs:\n boxes: The bounding boxes to transform, a tensor/array of shape\n `(N, 4)` or `(batch_size, N, 4)`.\n angle: Rotation angle in degrees.\n translate_x: Horizontal translation fraction.\n translate_y: Vertical translation fraction.\n scale: Scaling factor.\n shear_x: Shear angle in x-direction (degrees).\n shear_y: Shear angle in y-direction (degrees).\n height: Height of the image/data.\n width: Width of the image/data.\n center_x: x-coordinate of the transformation center (fraction).\n center_y: y-coordinate of the transformation center (fraction).\n bounding_box_format: The format of the input bounding boxes. Defaults to\n `\"xyxy\"`.\n\nReturns:\n The transformed bounding boxes, a tensor/array with the same shape\n as the input `boxes`.", "source": "github_repos"} +{"code": "def verbosity_from(options):\n level = logging.getLogger().getEffectiveLevel()\n _set_verbosity(options.verbosity, options.timestamp_logs, options.debug_logs)\n try:\n yield\n finally:\n logging.getLogger().setLevel(level)", "docstring": "Sets the logging level to options.verbosity and restores it afterwards.\n\n If you directly call any of pytype's internal methods,\n like analyze.infer_types, use this contextmanager to set the logging\n verbosity. Consider using one of the top-level methods in pytype.io instead,\n which take care of this detail for you.\n\nArgs:\n options: A config.Options object.\n\nYields:\n Nothing.", "source": "github_repos"} +{"code": "def _assert_sparse_indices_are_ragged_right(indices):\n index_prefix = indices[:, :-1]\n index_suffix = indices[:, -1]\n index_prefix_changed = math_ops.reduce_any(math_ops.not_equal(index_prefix[1:], index_prefix[:-1]), axis=1)\n index_ok = array_ops.where(index_prefix_changed, math_ops.equal(index_suffix[1:], 0), math_ops.equal(index_suffix[1:], index_suffix[:-1] + 1))\n sparse_indices_are_ragged_right = math_ops.logical_and(math_ops.reduce_all(math_ops.equal(index_suffix[:1], 0)), math_ops.reduce_all(index_ok))\n message = ['SparseTensor is not right-ragged', 'SparseTensor.indices =', indices]\n return [control_flow_assert.Assert(sparse_indices_are_ragged_right, message)]", "docstring": "Checks that the given SparseTensor.indices tensor is ragged-right.\n\n Example: `indices = [[0, 0], [0, 1], [2, 0], [3, 1]]` is not ragged right\n because the entry `[3, 1]` skips a cell.\n\nArgs:\n indices: The SparseTensor indices to check.\n\nReturns:\n A list of control dependency op tensors.", "source": "github_repos"} +{"code": "def _validate_alias_file_path(alias_file_path):\n\n if not os.path.exists(alias_file_path):\n raise CLIError(ALIAS_FILE_NOT_FOUND_ERROR)\n\n if os.path.isdir(alias_file_path):\n raise CLIError(ALIAS_FILE_DIR_ERROR.format(alias_file_path))", "docstring": "Make sure the alias file path is neither non-existant nor a directory\n\nArgs:\n The alias file path to import aliases from.", "source": "juraj_google_style"} +{"code": "def get_learning_rate(self, iter):\n\n return self.init_lr * ((math.cos(iter * 1.0 / (self.max_iter) * math.pi) + 1.0) * 0.5)", "docstring": "Get learning rate with cosine decay based on current iteration.\n\nArgs:\n iter (int): Current iteration (starting with 0).\n\nReturns:\n float: Learning rate", "source": "juraj_google_style"} +{"code": "def ParseFileObject(self, parser_mediator, file_object):\n\n esedb_file = pyesedb.file()\n\n try:\n esedb_file.open_file_object(file_object)\n except IOError as exception:\n parser_mediator.ProduceExtractionWarning(\n 'unable to open file with error: {0!s}'.format(exception))\n return\n\n # Compare the list of available plugin objects.\n cache = ESEDBCache()\n try:\n table_names = frozenset(self._GetTableNames(esedb_file))\n\n for plugin in self._plugins:\n if parser_mediator.abort:\n break\n\n if not plugin.required_tables.issubset(table_names):\n continue\n\n try:\n plugin.UpdateChainAndProcess(\n parser_mediator, cache=cache, database=esedb_file)\n\n except Exception as exception: # pylint: disable=broad-except\n parser_mediator.ProduceExtractionWarning((\n 'plugin: {0:s} unable to parse ESE database with error: '\n '{1!s}').format(plugin.NAME, exception))\n\n finally:\n # TODO: explicitly clean up cache.\n\n esedb_file.close()", "docstring": "Parses an ESE database file-like object.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n file_object (dfvfs.FileIO): file-like object.", "source": "juraj_google_style"} +{"code": "def __init__(self, dataframe, map_info):\n\n self.df = dataframe\n self.map_info = map_info", "docstring": "Reads genotypes from a pandas DataFrame.\n\nArgs:\n dataframe (pandas.DataFrame): The data.\n map_info (pandas.DataFrame): The mapping information.\n\n Note\n ====\n The index of the dataframe should be the sample IDs. The index of\n the map_info should be the variant name, and there should be\n columns named chrom and pos.", "source": "juraj_google_style"} +{"code": "def info_qry(tickers, flds) -> str:\n\n full_list = '\\n'.join([f'tickers: {tickers[:8]}'] + [\n f' {tickers[n:(n + 8)]}' for n in range(8, len(tickers), 8)\n ])\n return f'{full_list}\\nfields: {flds}'", "docstring": "Logging info for given tickers and fields\n\nArgs:\n tickers: tickers\n flds: fields\n\nReturns:\n str\n\nExample:\n >>> print(info_qry(\n ... tickers=['NVDA US Equity'], flds=['Name', 'Security_Name']\n ... ))\n tickers: ['NVDA US Equity']\n fields: ['Name', 'Security_Name']", "source": "juraj_google_style"} +{"code": "def __init__(self, pos=(0, 0, 0, -100), branches=None, sigma=(0, 0)):\n\n self.pos = pos\n self.length = sqrt((pos[2]-pos[0])**2+(pos[3]-pos[1])**2)\n self.branches = branches\n self.sigma = sigma\n\n self.comp = len(self.branches)\n self.age = 0\n\n self.nodes = [\n [Node(pos[2:])]\n ]", "docstring": "The contructor.\n\nArgs:\n pos (tupel): A tupel, holding the start and end point of the tree. (x1, y1, x2, y2)\n branches (tupel/array): Holding array/s with scale and angle for every branch.\n sigma (tuple): Holding the branch and angle sigma. e.g.(0.1, 0.2)", "source": "juraj_google_style"} +{"code": "def _build_kernel(self, kernel_source, compile_flags=()):\n\n return cl.Program(self._cl_context, kernel_source).build(' '.join(compile_flags))", "docstring": "Convenience function for building the kernel for this worker.\n\nArgs:\n kernel_source (str): the kernel source to use for building the kernel\n\nReturns:\n cl.Program: a compiled CL kernel", "source": "juraj_google_style"} +{"code": "def start_proc_mask_signal(proc):\n\n if not isinstance(proc, list):\n proc = [proc]\n\n with mask_sigint():\n for p in proc:\n if isinstance(p, mp.Process):\n if sys.version_info < (3, 4) or mp.get_start_method() == 'fork':\n log_once(\n\"Starting a process with 'fork' method is not safe and may consume unnecessary extra memory.\"\n\" Use 'forkserver' method (available after Py3.4) instead if you run into any issues. \"\n\"See https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods\",\n'warn') # noqa\n p.start()", "docstring": "Start process(es) with SIGINT ignored.\n\nArgs:\n proc: (mp.Process or list)\n\nNote:\n The signal mask is only applied when called from main thread.", "source": "juraj_google_style"} +{"code": "def load_many(self, fobjs=None):\n\n if fobjs is not None:\n # tolerance\n if not hasattr(fobjs, \"__iter__\"):\n fobjs = [fobjs]\n\n for index, (fobj, page) in enumerate(zip(fobjs, self.pages)):\n if fobj is None:\n continue\n elif isinstance(fobj, ft.DataFile):\n self.load(fobj, index)\n elif isinstance(fobj, str):\n self.load_filename(fobj, index)\n else:\n raise TypeError(\"Invalid object of class '{}'\".format(fobj.__class__.__name__))", "docstring": "Loads as many files as the number of pages\n\nArgs:\n fobjs: [filename or DataFile obj, ...]", "source": "juraj_google_style"} +{"code": "def __init__(self, grr_worker=None):\n\n self.grr_worker = grr_worker\n self.response_id = INITIAL_RESPONSE_ID\n self.cpu_used = None\n self.nanny_controller = None\n self.status = rdf_flows.GrrStatus(\n status=rdf_flows.GrrStatus.ReturnedStatus.OK)\n self._last_gc_run = rdfvalue.RDFDatetime.Now()\n self._gc_frequency = config.CONFIG[\"Client.gc_frequency\"]\n self.proc = psutil.Process()\n self.cpu_start = self.proc.cpu_times()\n self.cpu_limit = rdf_flows.GrrMessage().cpu_limit", "docstring": "Initializes the action plugin.\n\nArgs:\n grr_worker: The grr client worker object which may be used to e.g. send\n new actions on.", "source": "juraj_google_style"} +{"code": "def get_numeric_features_to_observed_range(examples):\n\n observed_features = collections.defaultdict(list) # name -> [value, ]\n for example in examples:\n for feature_name in get_numeric_feature_names(example):\n original_feature = parse_original_feature_from_example(\n example, feature_name)\n observed_features[feature_name].extend(original_feature.original_value)\n return {\n feature_name: {\n 'observedMin': min(feature_values),\n 'observedMax': max(feature_values),\n }\n for feature_name, feature_values in iteritems(observed_features)\n }", "docstring": "Returns numerical features and their observed ranges.\n\nArgs:\n examples: Examples to read to get ranges.\n\nReturns:\n A dict mapping feature_name -> {'observedMin': 'observedMax': } dicts,\n with a key for each numerical feature.", "source": "juraj_google_style"} +{"code": "def register_event(self, direction, verb, child_fn, priority=10):\n\n if verb not in self._event_handlers:\n self._event_handlers[verb] = []\n\n self._event_handlers[verb].append({\n 'handler': child_fn,\n 'direction': direction,\n 'priority': priority,\n })\n\n for name, server in self.servers.items():\n server.register_event(direction, verb, child_fn, priority=priority)", "docstring": "Register an event with all servers.\n\nArgs:\n direction (str): `in`, `out`, `both`, `raw`.\n verb (str): Event name.\n child_fn (function): Handler function.\n priority (int): Handler priority (lower priority executes first).", "source": "juraj_google_style"} +{"code": "def range(self, start_row=0, max_rows=None):\n\n fetcher = self._get_row_fetcher(start_row=start_row, max_rows=max_rows)\n return iter(datalab.utils.Iterator(fetcher))", "docstring": "Get an iterator to iterate through a set of table rows.\n\nArgs:\n start_row: the row of the table at which to start the iteration (default 0)\n max_rows: an upper limit on the number of rows to iterate through (default None)\n\nReturns:\n A row iterator.", "source": "juraj_google_style"} +{"code": "def add_droplets(self, droplet_ids):\n\n return self.get_data(\n \"load_balancers/%s/droplets/\" % self.id,\n type=POST,\n params={\"droplet_ids\": droplet_ids}\n )", "docstring": "Assign a LoadBalancer to a Droplet.\n\nArgs:\n droplet_ids (obj:`list` of `int`): A list of Droplet IDs", "source": "juraj_google_style"} +{"code": "def reset_spent_time(self, **kwargs):\n\n path = '%s/%s/reset_spent_time' % (self.manager.path, self.get_id())\n return self.manager.gitlab.http_post(path, **kwargs)", "docstring": "Resets the time spent working on the object.\n\nArgs:\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabTimeTrackingError: If the time tracking update cannot be done", "source": "juraj_google_style"} +{"code": "def env_or_default(var, default=None):\n\n if var in os.environ:\n return os.environ[var]\n return default", "docstring": "Get environment variable or provide default.\n\nArgs:\n var (str): environment variable to search for\n default (optional(str)): default to return", "source": "juraj_google_style"} +{"code": "def _force_disconnect_action(self, action):\n\n\n conn_key = action.data['id']\n if self._get_connection_state(conn_key) == self.Disconnected:\n return\n\n data = self._get_connection(conn_key)\n\n # If there are any operations in progress, cancel them cleanly\n if data['state'] == self.Connecting:\n callback = data['action'].data['callback']\n callback(data['connection_id'], self.id, False, 'Unexpected disconnection')\n elif data['state'] == self.Disconnecting:\n callback = data['action'].data['callback']\n callback(data['connection_id'], self.id, True, None)\n elif data['state'] == self.InProgress:\n callback = data['action'].data['callback']\n if data['microstate'] == 'rpc':\n callback(False, 'Unexpected disconnection', 0xFF, None)\n elif data['microstate'] == 'open_interface':\n callback(False, 'Unexpected disconnection')\n elif data['microstate'] == 'close_interface':\n callback(False, 'Unexpected disconnection')\n\n connection_id = data['connection_id']\n internal_id = data['internal_id']\n del self._connections[connection_id]\n del self._int_connections[internal_id]", "docstring": "Forcibly disconnect a device.\n\nArgs:\n action (ConnectionAction): the action object describing what we are\n forcibly disconnecting", "source": "juraj_google_style"} +{"code": "def __init__(self, pub_key=None):\n\n if pub_key is not None and type(pub_key) is not EllipticCurve.ECPoint:\n raise Exception(\"Pubkey must be ECPoint Instance\")\n\n self.PublicKey = pub_key", "docstring": "Create an instance.\n\nArgs:\n pub_key (EllipticCurve.ECPoint):\n\nRaises:\n Exception: if `pub_key` is not a valid ECPoint.", "source": "juraj_google_style"} +{"code": "def calculate_bv_sum_unordered(site, nn_list, scale_factor=1):\n\n # If the site \"site\" has N partial occupations as : f_{site}_0,\n # f_{site}_1, ... f_{site}_N of elements\n # X_{site}_0, X_{site}_1, ... X_{site}_N, and each neighbors nn_i in nn\n # has N_{nn_i} partial occupations as :\n # f_{nn_i}_0, f_{nn_i}_1, ..., f_{nn_i}_{N_{nn_i}}, then the bv sum of\n # site \"site\" is obtained as :\n # \\sum_{nn} \\sum_j^N \\sum_k^{N_{nn}} f_{site}_j f_{nn_i}_k vij_full\n # where vij_full is the valence bond of the fully occupied bond\n bvsum = 0\n for specie1, occu1 in site.species.items():\n el1 = Element(specie1.symbol)\n for (nn, dist) in nn_list:\n for specie2, occu2 in nn.species.items():\n el2 = Element(specie2.symbol)\n if (el1 in ELECTRONEG or el2 in ELECTRONEG) and el1 != el2:\n r1 = BV_PARAMS[el1][\"r\"]\n r2 = BV_PARAMS[el2][\"r\"]\n c1 = BV_PARAMS[el1][\"c\"]\n c2 = BV_PARAMS[el2][\"c\"]\n R = r1 + r2 - r1 * r2 * (sqrt(c1) - sqrt(c2)) ** 2 / \\\n (c1 * r1 + c2 * r2)\n vij = exp((R - dist * scale_factor) / 0.31)\n bvsum += occu1 * occu2 * vij * (1 if el1.X < el2.X else -1)\n return bvsum", "docstring": "Calculates the BV sum of a site for unordered structures.\n\nArgs:\n site:\n The site\n nn_list:\n List of nearest neighbors in the format [(nn_site, dist), ...].\n scale_factor:\n A scale factor to be applied. This is useful for scaling distance,\n esp in the case of calculation-relaxed structures which may tend\n to under (GGA) or over bind (LDA).", "source": "juraj_google_style"} +{"code": "def pairwise_alignment_stats(reference_seq_aln, other_seq_aln):\n\n if len(reference_seq_aln) != len(other_seq_aln):\n raise ValueError('Sequence lengths not equal - was an alignment run?')\n\n reference_seq_aln = ssbio.protein.sequence.utils.cast_to_str(reference_seq_aln)\n other_seq_aln = ssbio.protein.sequence.utils.cast_to_str(other_seq_aln)\n\n infodict = {}\n\n # Percent identity to the reference sequence\n stats_percent_ident = get_percent_identity(a_aln_seq=reference_seq_aln, b_aln_seq=other_seq_aln)\n infodict['percent_identity'] = stats_percent_ident\n\n # Other alignment results\n aln_df = get_alignment_df(a_aln_seq=reference_seq_aln, b_aln_seq=other_seq_aln)\n infodict['deletions'] = get_deletions(aln_df)\n infodict['insertions'] = get_insertions(aln_df)\n infodict['mutations'] = get_mutations(aln_df)\n infodict['unresolved'] = get_unresolved(aln_df)\n\n return infodict", "docstring": "Get a report of a pairwise alignment.\n\nArgs:\n reference_seq_aln (str, Seq, SeqRecord): Reference sequence, alignment form\n other_seq_aln (str, Seq, SeqRecord): Other sequence, alignment form\n\nReturns:\n dict: Dictionary of information on mutations, insertions, sequence identity, etc.", "source": "juraj_google_style"} +{"code": "def run(self, dag):\n\n self.layout = self.layout or self.property_set['layout']\n\n if self.layout is None:\n raise TranspilerError(\"EnlargeWithAncilla requires property_set[\\\"layout\\\"] or\"\n \" \\\"layout\\\" parameter to run\")\n\n layout_virtual_qubits = self.layout.get_virtual_bits().keys()\n new_qregs = set(virtual_qubit[0] for virtual_qubit in layout_virtual_qubits\n if virtual_qubit not in dag.wires)\n\n for qreg in new_qregs:\n dag.add_qreg(qreg)\n\n return dag", "docstring": "Extends dag with virtual qubits that are in layout but not in the circuit yet.\n\nArgs:\n dag (DAGCircuit): DAG to extend.\n\nReturns:\n DAGCircuit: An extended DAG.\n\nRaises:\n TranspilerError: If there is not layout in the property set or not set at init time.", "source": "juraj_google_style"} +{"code": "def to_title_caps(underscore_case):\n r\n words = underscore_case.split('_')\n words2 = [\n word[0].upper() + word[1:]\n for count, word in enumerate(words)\n ]\n title_str = ' '.join(words2)\n return title_str", "docstring": "r\"\"\"\n\nArgs:\n underscore_case (?):\n\nReturns:\n str: title_str\n\n CommandLine:\n python -m utool.util_str --exec-to_title_caps\n\nExample:\n >>> # DISABLE_DOCTEST\n >>> from utool.util_str import * # NOQA\n >>> underscore_case = 'the_foo_bar_func'\n >>> title_str = to_title_caps(underscore_case)\n >>> result = ('title_str = %s' % (str(title_str),))\n >>> print(result)\n title_str = The Foo Bar Func", "source": "juraj_google_style"} +{"code": "def get_ytvideos(query, ilogger):\n\n\n queue = []\n\n # Search YouTube\n search_result = ytdiscoveryapi.search().list(\n q=query,\n part=\"id,snippet\",\n maxResults=1,\n type=\"video,playlist\"\n ).execute()\n\n if not search_result[\"items\"]:\n return []\n\n # Get video/playlist title\n title = search_result[\"items\"][0][\"snippet\"][\"title\"]\n ilogger.info(\"Queueing {}\".format(title))\n\n # Queue video if video\n if search_result[\"items\"][0][\"id\"][\"kind\"] == \"youtube#video\":\n # Get ID of video\n videoid = search_result[\"items\"][0][\"id\"][\"videoId\"]\n\n # Append video to queue\n queue.append([\"https://www.youtube.com/watch?v={}\".format(videoid), title])\n\n # Queue playlist if playlist\n elif search_result[\"items\"][0][\"id\"][\"kind\"] == \"youtube#playlist\":\n queue = get_queue_from_playlist(search_result[\"items\"][0][\"id\"][\"playlistId\"])\n\n return queue", "docstring": "Gets either a list of videos from a playlist or a single video, using the\n first result of a YouTube search\n\nArgs:\n query (str): The YouTube search query\n ilogger (logging.logger): The logger to log API calls to\n\nReturns:\n queue (list): The items obtained from the YouTube search", "source": "juraj_google_style"} +{"code": "def label_TM_tmhmm_residue_numbers_and_leaflets(tmhmm_seq):\n\n\n TM_number_dict = {}\n T_index = []\n T_residue = []\n\n residue_count = 1\n for residue_label in tmhmm_seq:\n if residue_label == 'T':\n T_residue.append(residue_count)\n\n residue_count = residue_count + 1\n TM_number_dict.update({'T_residue': T_residue})\n\n # finding the TM boundaries\n T_residue_list = TM_number_dict['T_residue']\n\n count = 0\n max_count = len(T_residue_list) - 1\n TM_helix_count = 0\n TM_boundary_dict = {}\n\n while count <= max_count:\n # first residue = TM start\n if count == 0:\n TM_start = T_residue_list[count]\n count = count + 1\n continue\n # Last residue = TM end\n elif count == max_count:\n TM_end = T_residue_list[count]\n TM_helix_count = TM_helix_count + 1\n TM_boundary_dict.update({'TM_helix_' + str(TM_helix_count): [TM_start, TM_end]})\n break\n # middle residues need to be start or end\n elif T_residue_list[count] != T_residue_list[count + 1] - 1:\n TM_end = T_residue_list[count]\n TM_helix_count = TM_helix_count + 1\n TM_boundary_dict.update({'TM_helix_' + str(TM_helix_count): [TM_start, TM_end]})\n # new TM_start\n TM_start = T_residue_list[count + 1]\n count = count + 1\n # assign leaflet to proper TM residues O or I\n leaflet_dict = {}\n for leaflet in ['O', 'I']:\n leaflet_list = []\n for TM_helix, TM_residues in TM_boundary_dict.items():\n for residue_num in TM_residues:\n tmhmm_seq_index = residue_num - 1\n previous_residue = tmhmm_seq_index - 1\n next_residue = tmhmm_seq_index + 1\n # identify if the previous or next residue closest to the TM helix start/end is the proper leaflet\n if tmhmm_seq[previous_residue] == leaflet or tmhmm_seq[next_residue] == leaflet:\n leaflet_list.append(residue_num)\n leaflet_dict.update({'tmhmm_leaflet_' + leaflet: leaflet_list})\n\n return TM_boundary_dict, leaflet_dict", "docstring": "Determine the residue numbers of the TM-helix residues that cross the membrane and label them by leaflet.\n\nArgs:\n tmhmm_seq: g.protein.representative_sequence.seq_record.letter_annotations['TM-tmhmm']\n\nReturns:\n leaflet_dict: a dictionary with leaflet_variable : [residue list] where the variable is inside or outside\n TM_boundary dict: outputs a dictionar with : TM helix number : [TM helix residue start , TM helix residue end]\n\n TODO:\n untested method!", "source": "juraj_google_style"} +{"code": "def insert(self, iterable, index=0, data=None, weight=1.0):\n\n if index == len(iterable):\n self.is_terminal = True\n self.key = iterable\n self.weight = weight\n if data:\n self.data.add(data)\n else:\n if iterable[index] not in self.children:\n self.children[iterable[index]] = TrieNode()\n self.children[iterable[index]].insert(iterable, index + 1, data)", "docstring": "Insert new node into tree\n\nArgs:\n iterable(hashable): key used to find in the future.\n data(object): data associated with the key\n index(int): an index used for insertion.\n weight(float): the wait given for the item added.", "source": "juraj_google_style"} +{"code": "def __init__(self, arm_id_list):\n\n [self.__beta_dist_dict.setdefault(key, BetaDist()) for key in arm_id_list]", "docstring": "Initialization\n\nArgs:\n arm_id_list: List of arms Master id.", "source": "juraj_google_style"} +{"code": "def _complete_batch(self, batch, error, base_offset, timestamp_ms=None):\n\n # Standardize no-error to None\n if error is Errors.NoError:\n error = None\n\n if error is not None and self._can_retry(batch, error):\n # retry\n log.warning(\"Got error produce response on topic-partition %s,\"\n \" retrying (%d attempts left). Error: %s\",\n batch.topic_partition,\n self.config['retries'] - batch.attempts - 1,\n error)\n self._accumulator.reenqueue(batch)\n self._sensors.record_retries(batch.topic_partition.topic, batch.record_count)\n else:\n if error is Errors.TopicAuthorizationFailedError:\n error = error(batch.topic_partition.topic)\n\n # tell the user the result of their request\n batch.done(base_offset, timestamp_ms, error)\n self._accumulator.deallocate(batch)\n if error is not None:\n self._sensors.record_errors(batch.topic_partition.topic, batch.record_count)\n\n if getattr(error, 'invalid_metadata', False):\n self._metadata.request_update()\n\n # Unmute the completed partition.\n if self.config['guarantee_message_order']:\n self._accumulator.muted.remove(batch.topic_partition)", "docstring": "Complete or retry the given batch of records.\n\nArgs:\n batch (RecordBatch): The record batch\n error (Exception): The error (or None if none)\n base_offset (int): The base offset assigned to the records if successful\n timestamp_ms (int, optional): The timestamp returned by the broker for this batch", "source": "juraj_google_style"} +{"code": "def _model_to_dict(model, ignore):\n\n return {attr: value for attr, value in model.__dict__.items()\n if not attr.startswith('_') and attr not in ignore}", "docstring": "Convert OSS model to dict.\n\nArgs:\n model (oss2.models.RequestResult): Model.\n ignore (tuple of str): Keys to not insert to dict.\n\nReturns:\n dict: Model dict version.", "source": "juraj_google_style"} +{"code": "def get_iterator_type(script_settings, subscripts={}):\n\n\n if 'iterator_type' in script_settings:\n # figure out the iterator type\n if script_settings['iterator_type'] == 'Loop':\n iterator_type = 'loop'\n elif script_settings['iterator_type'] == 'Parameter Sweep':\n iterator_type = 'sweep'\n else:\n raise TypeError('unknown iterator type')\n else:\n # asign the correct iterator script type\n if 'sweep_param' in script_settings:\n iterator_type = 'sweep'\n elif 'num_loops' in script_settings:\n iterator_type = 'loop'\n else:\n raise TypeError('unknown iterator type')\n\n return iterator_type", "docstring": "figures out the iterator type based on the script settings and (optionally) subscripts\n\nArgs:\n script_settings: iterator_type\n subscripts: subscripts\n Returns:", "source": "juraj_google_style"} +{"code": "def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name):\n\n self._set_grid_info('y', y_low, y_high, num_y, yscale, yval_name)\n return", "docstring": "Set the grid values for y.\n\n Create information for the grid of y values.\n\nArgs:\n num_y (int): Number of points on axis.\n y_low/y_high (float): Lowest/highest value for the axis.\n yscale (str): Scale of the axis. Choices are 'log' or 'lin'.\n yval_name (str): Name representing the axis. See GenerateContainer documentation\n for options for the name.", "source": "juraj_google_style"} +{"code": "def _SimpleEncoder(wire_type, encode_value, compute_value_size):\n\n\n def SpecificEncoder(field_number, is_repeated, is_packed):\n if is_packed:\n tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n def EncodePackedField(write, value):\n write(tag_bytes)\n size = 0\n for element in value:\n size += compute_value_size(element)\n local_EncodeVarint(write, size)\n for element in value:\n encode_value(write, element)\n return EncodePackedField\n elif is_repeated:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeRepeatedField(write, value):\n for element in value:\n write(tag_bytes)\n encode_value(write, element)\n return EncodeRepeatedField\n else:\n tag_bytes = TagBytes(field_number, wire_type)\n def EncodeField(write, value):\n write(tag_bytes)\n return encode_value(write, value)\n return EncodeField\n\n return SpecificEncoder", "docstring": "Return a constructor for an encoder for fields of a particular type.\n\nArgs:\n wire_type: The field's wire type, for encoding tags.\n encode_value: A function which encodes an individual value, e.g.\n _EncodeVarint().\n compute_value_size: A function which computes the size of an individual\n value, e.g. _VarintSize().", "source": "juraj_google_style"} +{"code": "def valid_paths(self, *args):\n\n for i, path in enumerate(args, start=0):\n cp = list(args)\n current = cp.pop(i)\n if current in cp:\n raise SettingsInvalidError(\"Multiple occurences finded for \"\n \"path: {}\".format(current))\n\n return True", "docstring": "Validate that given paths are not the same.\n\nArgs:\n (string): Path to validate.\n\nRaises:\n boussole.exceptions.SettingsInvalidError: If there is more than one\n occurence of the same path.\n\nReturns:\n bool: ``True`` if paths are validated.", "source": "juraj_google_style"} +{"code": "def image_format(value):\n\n\n if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS:\n raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)", "docstring": "Confirms that the uploaded image is of supported format.\n\nArgs:\n value (File): The file with an `image` property containing the image\n\nRaises:\n django.forms.ValidationError", "source": "juraj_google_style"} +{"code": "def _get_object_from_python_path(python_path):\n\n # Dissect the path\n python_path = python_path.split('.')\n module_path = python_path[:-1]\n object_class = python_path[-1]\n\n if isinstance(module_path, list):\n module_path = '.'.join(module_path)\n\n # Grab the object\n module = import_module(module_path)\n schema = getattr(module, object_class)\n\n if isclass(schema):\n schema = schema()\n\n return schema", "docstring": "Method that will fetch a Marshmallow schema from a path to it.\n\nArgs:\n python_path (str): The string path to the Marshmallow schema.\n\nReturns:\n marshmallow.Schema: The schema matching the provided path.\n\nRaises:\n TypeError: This is raised if the specified object isn't\n a Marshmallow schema.", "source": "juraj_google_style"} +{"code": "def _parse_authors(details):\n\n authors = details.find(\n \"tr\",\n {\"id\": \"ctl00_ContentPlaceHolder1_tblRowAutor\"}\n )\n\n if not authors:\n return [] # book with unspecified authors\n\n # parse authors from HTML and convert them to Author objects\n author_list = []\n for author in authors[0].find(\"a\"):\n author_obj = Author(author.getContent())\n\n if \"href\" in author.params:\n author_obj.URL = author.params[\"href\"]\n\n author_list.append(author_obj)\n\n return author_list", "docstring": "Parse authors of the book.\n\nArgs:\n details (obj): HTMLElement containing slice of the page with details.\n\nReturns:\n list: List of :class:`structures.Author` objects. Blank if no author \\\n found.", "source": "juraj_google_style"} +{"code": "def note_versions(self, updater_id=None, post_id=None, note_id=None):\n\n params = {\n 'search[updater_id]': updater_id,\n 'search[post_id]': post_id,\n 'search[note_id]': note_id\n }\n return self._get('note_versions.json', params)", "docstring": "Get list of note versions.\n\n Parameters:\n updater_id (int):\n post_id (int):\n note_id (int):", "source": "juraj_google_style"} +{"code": "def add(self, aspect, ifpresent=\"error\"):\n\n\n # If aspect is a contextualization, it is trated separately\n if isinstance(aspect, contextualize):\n self.contextualize.update(aspect)\n return True\n\n classification = [(network, self.networks), (system, self.systems), (ansible, self.ansible_hosts),\n (deploy, self.deploys), (configure, self.configures)]\n aspect_list = [l for t, l in classification if isinstance(aspect, t)]\n assert len(aspect_list) == 1, \"Unexpected aspect for RADL.\"\n aspect_list = aspect_list[0]\n\n old_aspect = [a for a in aspect_list if a.getId() == aspect.getId()]\n if old_aspect:\n # If some aspect with the same id is found\n if ifpresent == \"error\":\n raise Exception(\"Aspect with the same id was found.\")\n elif ifpresent == \"replace\":\n for i, elem in enumerate(aspect_list):\n if elem.getId() == old_aspect[0].getId():\n del aspect_list[i]\n break\n aspect_list.append(aspect)\n return True\n elif ifpresent == \"ignore\":\n return False\n else:\n raise ValueError\n else:\n # Otherwise add aspect\n aspect_list.append(aspect)\n return True", "docstring": "Add a network, ansible_host, system, deploy, configure or contextualize.\n\nArgs:\n - aspect(network, system, deploy, configure or contextualize): thing to add.\n - ifpresent(str): if it has been defined, do:\n\n - ``\"ignore\"``: not add the aspect.\n - ``\"replace\"``: replace by the old defined.\n - ``\"error\"``: raise an error.\n\n Return(bool): True if aspect was added.", "source": "juraj_google_style"} +{"code": "def delete_metadata(self, resource, keys):\n\n self.metadata_service.set_auth(self._token_metadata)\n self.metadata_service.delete(resource, keys)", "docstring": "Deletes the given key-value pairs associated with the given resource.\n\n Will attempt to delete all key-value pairs even if some fail.\n\nArgs:\n resource (intern.resource.boss.BossResource)\n keys (list)\n\nRaises:\n HTTPErrorList on failure.", "source": "juraj_google_style"} +{"code": "def full_url(self):\n\n if self.link == '':\n return None\n else:\n return Note._expand_url(self.link, self.subreddit)", "docstring": "Return the full reddit URL associated with the usernote.\n\nArgs:\n subreddit: the subreddit name for the note (PRAW Subreddit object)", "source": "juraj_google_style"} +{"code": "def get_lambda_alias_arn(app, account, region):\n\n session = boto3.Session(profile_name=account, region_name=region)\n lambda_client = session.client('lambda')\n\n lambda_aliases = lambda_client.list_aliases(FunctionName=app)\n\n matched_alias = None\n for alias in lambda_aliases['Aliases']:\n if alias['Name'] == account:\n lambda_alias_arn = alias['AliasArn']\n LOG.info('Found ARN for alias %s for function %s', account, app)\n matched_alias = lambda_alias_arn\n break\n else:\n fatal_message = 'Lambda alias {0} of function {1} not found'.format(account, app)\n LOG.fatal(fatal_message)\n raise LambdaAliasDoesNotExist(fatal_message)\n return matched_alias", "docstring": "Get lambda alias ARN. Assumes that account name is equal to alias name.\n\nArgs:\n account (str): AWS account name.\n region (str): Region name, e.g. us-east-1\n app (str): Lambda function name\n\nReturns:\n str: ARN for requested lambda alias", "source": "juraj_google_style"} +{"code": "def getContextsForTerm(self, term, getFingerprint=None, startIndex=0, maxResults=5):\n\n return self._terms.getContextsForTerm(self._retina, term, getFingerprint, startIndex, maxResults)", "docstring": "Get the contexts for a given term\n\nArgs:\n term, str: A term in the retina (required)\n getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional)\n startIndex, int: The start-index for pagination (optional)\n maxResults, int: Max results per page (optional)\n\nReturns:\n list of Context\n\nRaises:\n CorticalioException: if the request was not successful", "source": "juraj_google_style"} +{"code": "def properties(self, var_or_nodeid, as_list=False):\n\n props = []\n if var_or_nodeid in self._vars:\n props = self._vars[var_or_nodeid]['props']\n elif var_or_nodeid in self._eps:\n var = self._eps[var_or_nodeid][3].get(IVARG_ROLE)\n props = self._vars.get(var, {}).get('props', [])\n else:\n raise KeyError(var_or_nodeid)\n if not as_list:\n props = dict(props)\n return props", "docstring": "Return a dictionary of variable properties for *var_or_nodeid*.\n\nArgs:\n var_or_nodeid: if a variable, return the properties\n associated with the variable; if a nodeid, return the\n properties associated with the intrinsic variable of the\n predication given by the nodeid", "source": "juraj_google_style"} +{"code": "def convert_convtranspose(params, w_name, scope_name, inputs, layers, weights, names):\n\n print('Converting transposed convolution ...')\n\n if names == 'short':\n tf_name = 'C' + random_string(7)\n elif names == 'keep':\n tf_name = w_name\n else:\n tf_name = w_name + str(random.random())\n\n bias_name = '{0}.bias'.format(w_name)\n weights_name = '{0}.weight'.format(w_name)\n\n if len(weights[weights_name].numpy().shape) == 4:\n W = weights[weights_name].numpy().transpose(2, 3, 1, 0)\n height, width, n_filters, channels = W.shape\n\n n_groups = params['group']\n if n_groups > 1:\n raise AssertionError('Cannot convert conv1d with groups != 1')\n\n if params['dilations'][0] > 1:\n raise AssertionError('Cannot convert conv1d with dilation_rate != 1')\n\n if bias_name in weights:\n biases = weights[bias_name].numpy()\n has_bias = True\n else:\n biases = None\n has_bias = False\n\n input_name = inputs[0]\n\n if has_bias:\n weights = [W, biases]\n else:\n weights = [W]\n\n conv = keras.layers.Conv2DTranspose(\n filters=n_filters,\n kernel_size=(height, width),\n strides=(params['strides'][0], params['strides'][1]),\n padding='valid',\n output_padding=0,\n weights=weights,\n use_bias=has_bias,\n activation=None,\n dilation_rate=params['dilations'][0],\n bias_initializer='zeros', kernel_initializer='zeros',\n name=tf_name\n )\n\n layers[scope_name] = conv(layers[input_name])\n\n # Magic ad-hoc.\n # See the Keras issue: https://github.com/keras-team/keras/issues/6777\n layers[scope_name].set_shape(layers[scope_name]._keras_shape)\n\n pads = params['pads']\n if pads[0] > 0:\n assert(len(pads) == 2 or (pads[2] == pads[0] and pads[3] == pads[1]))\n\n crop = keras.layers.Cropping2D(\n pads[:2],\n name=tf_name + '_crop'\n )\n layers[scope_name] = crop(layers[scope_name])\n else:\n raise AssertionError('Layer is not supported for now')", "docstring": "Convert transposed convolution layer.\n\nArgs:\n params: dictionary with layer parameters\n w_name: name prefix in state_dict\n scope_name: pytorch scope name\n inputs: pytorch node inputs\n layers: dictionary with keras tensors\n weights: pytorch state_dict\n names: use short names for keras layers", "source": "juraj_google_style"} +{"code": "def _create_datadict(cls, internal_name):\n\n if internal_name == \"LOCATION\":\n return Location()\n if internal_name == \"DESIGN CONDITIONS\":\n return DesignConditions()\n if internal_name == \"TYPICAL/EXTREME PERIODS\":\n return TypicalOrExtremePeriods()\n if internal_name == \"GROUND TEMPERATURES\":\n return GroundTemperatures()\n if internal_name == \"HOLIDAYS/DAYLIGHT SAVINGS\":\n return HolidaysOrDaylightSavings()\n if internal_name == \"COMMENTS 1\":\n return Comments1()\n if internal_name == \"COMMENTS 2\":\n return Comments2()\n if internal_name == \"DATA PERIODS\":\n return DataPeriods()\n raise ValueError(\n \"No DataDictionary known for {}\".format(internal_name))", "docstring": "Creates an object depending on `internal_name`\n\nArgs:\n internal_name (str): IDD name\n\nRaises:\n ValueError: if `internal_name` cannot be matched to a data dictionary object", "source": "juraj_google_style"} +{"code": "def __init__(self, meter_id=Meter.OFPM_ALL):\n\n super().__init__()\n self.meter_id = meter_id", "docstring": "Create a MeterMultipartRequest with the optional parameters below.\n\nArgs:\n meter_id(Meter): Meter Indentify.The value Meter.OFPM_ALL is used\n to refer to all Meters on the switch.", "source": "juraj_google_style"} +{"code": "def assert_key_has_value(self, key, caller):\n\n assert key, (\"key parameter must be specified.\")\n self.assert_key_exists(key, caller)\n\n if self[key] is None:\n raise KeyInContextHasNoValueError(\n f\"context['{key}'] must have a value for {caller}.\")", "docstring": "Assert that context contains key which also has a value.\n\nArgs:\n key: validate this key exists in context AND has a value that isn't\n None.\n caller: string. calling function name - this used to construct\n error messages\n\nRaises:\n KeyNotInContextError: Key doesn't exist\n KeyInContextHasNoValueError: context[key] is None\n AssertionError: if key is None", "source": "juraj_google_style"} +{"code": "def DEFINE_alias(name, original_name, flag_values=FLAGS, module_name=None): # pylint: disable=g-bad-name\n\n if original_name not in flag_values:\n raise UnrecognizedFlagError(original_name)\n flag = flag_values[original_name]\n\n class _Parser(ArgumentParser):\n\n\n def parse(self, argument):\n flag.parse(argument)\n return flag.value\n\n class _FlagAlias(Flag):\n\n\n @property\n def value(self):\n return flag.value\n\n @value.setter\n def value(self, value):\n flag.value = value\n\n help_msg = 'Alias for --%s.' % flag.name\n # If alias_name has been used, gflags.DuplicatedFlag will be raised.\n DEFINE_flag(_FlagAlias(_Parser(), flag.serializer, name, flag.default,\n help_msg, boolean=flag.boolean),\n flag_values, module_name)", "docstring": "Defines an alias flag for an existing one.\n\nArgs:\n name: A string, name of the alias flag.\n original_name: A string, name of the original flag.\n flag_values: FlagValues object with which the flag will be registered.\n module_name: A string, the name of the module that defines this flag.\n\nRaises:\n gflags.FlagError:\n UnrecognizedFlagError: if the referenced flag doesn't exist.\n DuplicateFlagError: if the alias name has been used by some existing flag.", "source": "juraj_google_style"} +{"code": "def _buckets_nearly_equal(a_dist, b_dist):\n\n a_type, a_buckets = _detect_bucket_option(a_dist)\n b_type, b_buckets = _detect_bucket_option(b_dist)\n if a_type != b_type:\n return False\n elif a_type == u'linearBuckets':\n return _linear_buckets_nearly_equal(a_buckets, b_buckets)\n elif a_type == u'exponentialBuckets':\n return _exponential_buckets_nearly_equal(a_buckets, b_buckets)\n elif a_type == u'explicitBuckets':\n return _explicit_buckets_nearly_equal(a_buckets, b_buckets)\n else:\n return False", "docstring": "Determines whether two `Distributions` are nearly equal.\n\nArgs:\n a_dist (:class:`Distribution`): an instance\n b_dist (:class:`Distribution`): another instance\n\nReturns:\n boolean: `True` if the two instances are approximately equal, otherwise\n False", "source": "juraj_google_style"} +{"code": "def is_commutable(expr1, expr2, eps=0.00000001):\n\n return sum((x * x.conjugate()).real for x in commutator(expr1, expr2).coeffs()) < eps", "docstring": "Test whether expr1 and expr2 are commutable.\n\nArgs:\n expr1 (Expr, Term or Pauli operator): Pauli's expression.\n expr2 (Expr, Term or Pauli operator): Pauli's expression.\n eps (float, optional): Machine epsilon.\n If |[expr1, expr2]| < eps, consider it is commutable.\n\nReturns:\n bool: if expr1 and expr2 are commutable, returns True, otherwise False.", "source": "juraj_google_style"} +{"code": "def GetSoapXMLForComplexType(self, type_name, value):\n\n element = self.schema.get_element(\n '{%s}%s' % (self._namespace_override, type_name))\n result_element = self._element_maker(element.qname.localname)\n element_value = element(**value)\n element.type.render(result_element, element_value)\n data = lxml.etree.tostring(result_element).strip()\n return data", "docstring": "Return an XML string representing a SOAP complex type.\n\nArgs:\n type_name: The name of the type with namespace prefix if necessary.\n value: A python dictionary to hydrate the type instance with.\n\nReturns:\n A string containing the SOAP XML for the type.", "source": "juraj_google_style"} +{"code": "def nr_cases(self, snv_cases=None, sv_cases=None):\n\n query = {}\n\n if snv_cases:\n query = {'vcf_path': {'$exists':True}}\n if sv_cases:\n query = {'vcf_sv_path': {'$exists':True}}\n if snv_cases and sv_cases:\n query = None\n\n return self.db.case.count_documents(query)", "docstring": "Return the number of cases in the database\n\nArgs:\n snv_cases(bool): If only snv cases should be searched\n sv_cases(bool): If only snv cases should be searched\n\nReturns:\n cases (Iterable(Case)): A iterable with mongo cases", "source": "juraj_google_style"} +{"code": "def send(self, response):\n\n self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid),\n pickle.dumps(response))", "docstring": "Send a response back to the client that issued a request.\n\nArgs:\n response (Response): Reference to the response object that should be sent.", "source": "juraj_google_style"} +{"code": "def _ParseFieldsMetadata(self, structure):\n\n fields = structure.fields.split(' ')\n\n log_line_structure = pyparsing.Empty()\n if fields[0] == 'date' and fields[1] == 'time':\n log_line_structure += self.DATE_TIME.setResultsName('date_time')\n fields = fields[2:]\n\n for member in fields:\n log_line_structure += self._LOG_LINE_STRUCTURES.get(member, self.URI)\n\n updated_structures = []\n for line_structure in self._line_structures:\n if line_structure[0] != 'logline':\n updated_structures.append(line_structure)\n updated_structures.append(('logline', log_line_structure))\n # TODO: self._line_structures is a work-around and this needs\n # a structural fix.\n self._line_structures = updated_structures", "docstring": "Parses the fields metadata and updates the log line definition to match.\n\nArgs:\n structure (pyparsing.ParseResults): structure parsed from the log file.", "source": "juraj_google_style"} +{"code": "def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n\n super(RevokeRequestPayload, self).read(\n istream,\n kmip_version=kmip_version\n )\n tstream = BytearrayStream(istream.read(self.length))\n\n self.unique_identifier = attributes.UniqueIdentifier()\n self.unique_identifier.read(tstream, kmip_version=kmip_version)\n\n self.revocation_reason = objects.RevocationReason()\n self.revocation_reason.read(tstream, kmip_version=kmip_version)\n\n if self.is_tag_next(enums.Tags.COMPROMISE_OCCURRENCE_DATE, tstream):\n self.compromise_occurrence_date = primitives.DateTime(\n tag=enums.Tags.COMPROMISE_OCCURRENCE_DATE)\n self.compromise_occurrence_date.read(\n tstream,\n kmip_version=kmip_version\n )\n\n self.is_oversized(tstream)\n self.validate()", "docstring": "Read the data encoding the RevokeRequestPayload object and decode it\n into its constituent parts.\n\nArgs:\n istream (Stream): A data stream containing encoded object data,\n supporting a read method; usually a BytearrayStream object.\n kmip_version (KMIPVersion): An enumeration defining the KMIP\n version with which the object will be decoded. Optional,\n defaults to KMIP 1.0.", "source": "juraj_google_style"} +{"code": "def __init__(self, data_type_definition):\n\n super(PaddingMap, self).__init__(data_type_definition)\n self.byte_size = None", "docstring": "Initializes a padding data type map.\n\nArgs:\n data_type_definition (DataTypeDefinition): data type definition.\n\nRaises:\n FormatError: if the data type map cannot be determined from the data\n type definition.", "source": "juraj_google_style"} +{"code": "def from_api_repr(cls, resource):\n\n version = resource.get(\"version\")\n etag = resource.get(\"etag\")\n policy = cls(etag, version)\n for binding in resource.get(\"bindings\", ()):\n role = binding[\"role\"]\n members = sorted(binding[\"members\"])\n policy[role] = members\n return policy", "docstring": "Factory: create a policy from a JSON resource.\n\nArgs:\n resource (dict): policy resource returned by ``getIamPolicy`` API.\n\nReturns:\n :class:`Policy`: the parsed policy", "source": "juraj_google_style"} +{"code": "def _get_create_query(partition, tablename, include=None):\n\n TYPE_MAP = {\n 'int': 'INTEGER',\n 'float': 'REAL',\n six.binary_type.__name__: 'TEXT',\n six.text_type.__name__: 'TEXT',\n 'date': 'DATE',\n 'datetime': 'TIMESTAMP WITHOUT TIME ZONE'\n }\n columns_types = []\n if not include:\n include = []\n for column in sorted(partition.datafile.reader.columns, key=lambda x: x['pos']):\n if include and column['name'] not in include:\n continue\n sqlite_type = TYPE_MAP.get(column['type'])\n if not sqlite_type:\n raise Exception('Do not know how to convert {} to sql column.'.format(column['type']))\n columns_types.append(' \"{}\" {}'.format(column['name'], sqlite_type))\n columns_types_str = ',\\n'.join(columns_types)\n query = 'CREATE TABLE IF NOT EXISTS {}(\\n{})'.format(tablename, columns_types_str)\n return query", "docstring": "Creates and returns `CREATE TABLE ...` sql statement for given mprows.\n\nArgs:\n partition (orm.Partition):\n tablename (str): name of the table in the return create query.\n include (list of str, optional): list of columns to include to query.\n\nReturns:\n str: create table query.", "source": "juraj_google_style"} +{"code": "def record_value(self, value, count=1):\n\n if value < 0:\n return False\n counts_index = self._counts_index_for(value)\n if (counts_index < 0) or (self.counts_len <= counts_index):\n return False\n self.counts[counts_index] += count\n self.total_count += count\n self.min_value = min(self.min_value, value)\n self.max_value = max(self.max_value, value)\n return True", "docstring": "Record a new value into the histogram\n\nArgs:\n value: the value to record (must be in the valid range)\n count: incremental count (defaults to 1)", "source": "juraj_google_style"} +{"code": "def vcf_records(self, format_tags=None, qualified=False):\n\n if qualified:\n sample_names = self.qualified_sample_names\n else:\n sample_names = self.sample_names\n\n for line in self._file_reader.read_lines():\n if line.startswith(\"#\"):\n continue\n vcf_record = vcf.VcfRecord.parse_record(line, sample_names)\n if format_tags:\n vcf_record = self.modify_format_tag(vcf_record, format_tags)\n yield vcf_record", "docstring": "Generates parsed VcfRecord objects.\n\n Typically called in a for loop to process each vcf record in a\n VcfReader. VcfReader must be opened in advanced and closed when\n complete. Skips all headers.\n\nArgs:\n qualified: When True, sample names are prefixed with file name\n\nReturns:\n Parsed VcfRecord\n\nRaises:\n StopIteration: when reader is exhausted.\n TypeError: if reader is closed.", "source": "juraj_google_style"} +{"code": "def matches(self, node, value):\n\n\n if self.skip(value):\n return True\n\n if not self._valid_value(value):\n msg = \"Invalid value {value} passed to filter {name} - \".format(\n value=repr(value),\n name=self.name)\n\n if self.default is not None:\n warn(msg + \"defaulting to {}\".format(self.default))\n value = self.default\n else:\n warn(msg + \"skipping\")\n return True\n\n return self.func(node, value)", "docstring": "Returns whether the given node matches the filter rule with the given value.\n\nArgs:\n node (Element): The node to filter.\n value (object): The desired value with which the node should be evaluated.\n\nReturns:\n bool: Whether the given node matches.", "source": "juraj_google_style"} +{"code": "def generate_data(self, data_dir, tmp_dir, task_id=-1):\n\n tf.logging.info(\"generate_data task_id=%s\" % task_id)\n encoder = self.get_or_create_vocab(data_dir, tmp_dir)\n assert task_id >= 0 and task_id < self.num_generate_tasks\n if task_id < self.num_train_shards:\n out_file = self.training_filepaths(\n data_dir, self.num_train_shards, shuffled=False)[task_id]\n else:\n out_file = self.dev_filepaths(\n data_dir, self.num_dev_shards,\n shuffled=False)[task_id - self.num_train_shards]\n generator_utils.generate_files(\n self.example_generator(encoder, tmp_dir, task_id), [out_file])\n generator_utils.shuffle_dataset([out_file])", "docstring": "Generates training/dev data.\n\nArgs:\n data_dir: a string\n tmp_dir: a string\n task_id: an optional integer\n\nReturns:\n shard or shards for which data was generated.", "source": "juraj_google_style"} +{"code": "def from_input(cls, input, workdir=None, manager=None):\n\n return cls(input, workdir=workdir, manager=manager)", "docstring": "Create an instance of `AbinitTask` from an ABINIT input.\n\nArgs:\n ainput: `AbinitInput` object.\n workdir: Path to the working directory.\n manager: :class:`TaskManager` object.", "source": "juraj_google_style"} +{"code": "def validate(self, *args, **kwargs): # pylint: disable=arguments-differ\n\n return super(ParameterValidator, self)._validate(*args, **kwargs)", "docstring": "Validate a parameter dict against a parameter schema from an ocrd-tool.json\n\nArgs:\n obj (dict):\n schema (dict):", "source": "juraj_google_style"} +{"code": "def top3_reduced(votes):\n\n res = np.zeros(16)\n for vote in votes:\n # the top ranked alternative is in vote[0][0], second in vote[1][0]\n if vote[0][0] == 0: # i.e. the first alt is ranked first\n res[0] += 1\n if vote[1][0] == 2:\n res[4] += 1\n elif vote[1][0] == 3:\n res[5] += 1\n elif vote[1][0] == 1 and vote[2][0] == 2:\n res[14] += 1\n elif vote[0][0] == 1:\n res[1] += 1\n if vote[1][0] == 0:\n res[6] += 1\n elif vote[1][0] == 3:\n res[7] += 1\n elif vote[1][0] == 2 and vote[2][0] == 3:\n res[15] += 1\n elif vote[0][0] == 2:\n res[2] += 1\n if vote[1][0] == 0:\n res[8] += 1\n elif vote[1][0] == 1:\n res[9] += 1\n elif vote[1][0] == 3 and vote[2][0] == 0:\n res[12] += 1\n elif vote[0][0] == 3:\n res[3] += 1\n if vote[1][0] == 1:\n res[10] += 1\n elif vote[1][0] == 2:\n res[11] += 1\n elif vote[1][0] == 0 and vote[2][0] == 1:\n res[13] += 1\n res /= len(votes)\n return res", "docstring": "Description:\n Top 3 alternatives 16 moment conditions values calculation\n Parameters:\n votes: ordinal preference data (numpy ndarray of integers)", "source": "juraj_google_style"} +{"code": "def mock(self, slot, rpc_id, value):\n\n\n address = slot.address\n\n if address not in self.mock_rpcs:\n self.mock_rpcs[address] = {}\n\n self.mock_rpcs[address][rpc_id] = value", "docstring": "Store a mock return value for an RPC\n\nArgs:\n slot (SlotIdentifier): The slot we are mocking\n rpc_id (int): The rpc we are mocking\n value (int): The value that should be returned\n when the RPC is called.", "source": "juraj_google_style"} +{"code": "def _ParseRecordLogline(self, parser_mediator, structure):\n\n date_time = dfdatetime_time_elements.TimeElementsInMilliseconds()\n\n try:\n datetime_iso8601 = self._GetISO8601String(structure.date_time)\n date_time.CopyFromStringISO8601(datetime_iso8601)\n except ValueError:\n parser_mediator.ProduceExtractionWarning(\n 'invalid date time value: {0!s}'.format(structure.date_time))\n return\n\n event_data = GoogleDriveSyncLogEventData()\n event_data.log_level = structure.log_level\n event_data.pid = structure.pid\n event_data.thread = structure.thread\n event_data.source_code = structure.source_code\n # Replace newlines with spaces in structure.message to preserve output.\n event_data.message = structure.message.replace('\\n', ' ')\n\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_ADDED)\n\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a logline record structure and produces events.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n structure (pyparsing.ParseResults): structure of tokens derived from\n a line of a text file.", "source": "juraj_google_style"} +{"code": "def _kl_laplace_laplace(a, b, name=None):\n\n with tf.name_scope(name or \"kl_laplace_laplace\"):\n # Consistent with\n # http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 38\n distance = tf.abs(a.loc - b.loc)\n ratio = a.scale / b.scale\n\n return (-tf.math.log(ratio) - 1 + distance / b.scale +\n ratio * tf.exp(-distance / a.scale))", "docstring": "Calculate the batched KL divergence KL(a || b) with a and b Laplace.\n\nArgs:\n a: instance of a Laplace distribution object.\n b: instance of a Laplace distribution object.\n name: (optional) Name to use for created operations.\n default is \"kl_laplace_laplace\".\n\nReturns:\n Batchwise KL(a || b)", "source": "juraj_google_style"} +{"code": "def xarrayfunc(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if any(isinstance(arg, xr.DataArray) for arg in args):\n newargs = []\n for arg in args:\n if isinstance(arg, xr.DataArray):\n newargs.append(arg.values)\n else:\n newargs.append(arg)\n\n return dc.full_like(args[0], func(*newargs, **kwargs))\n else:\n return func(*args, **kwargs)\n\n return wrapper", "docstring": "Make a function compatible with xarray.DataArray.\n\n This function is intended to be used as a decorator like::\n\n >>> @dc.xarrayfunc\n >>> def func(array):\n ... # do something\n ... return newarray\n >>>\n >>> result = func(array)\n\nArgs:\n func (function): Function to be wrapped. The first argument\n of the function must be an array to be processed.\n\nReturns:\n wrapper (function): Wrapped function.", "source": "juraj_google_style"} +{"code": "def find(pattern, path=os.path.curdir, recursive=False):\n\n root = realpath(path)\n\n Finder = lambda item: regex.is_regex(pattern) \\\n and pattern.match(item) or (pattern == item)\n\n if recursive:\n for base, dirs, files in os.walk(root, topdown=True):\n for segment in itertools.chain(filter(Finder, files), filter(Finder, dirs)):\n yield FS(os.path.join(base, segment))\n\n else:\n for segment in filter(Finder, os.listdir(root)):\n yield(os.path.join(root, segment))", "docstring": "Find absolute file/folder paths with the given ``re`` pattern.\n\nArgs:\n * pattern: search pattern, support both string (exact match) and `re` pattern.\n * path: root path to start searching, default is current working directory.\n * recursive: whether to recursively find the matched items from `path`, False by default\n\nReturns:\n Generator of the matched items of Files/Folders.", "source": "juraj_google_style"} +{"code": "def write_eval_records(bt_table, game_data, last_game):\n\n eval_num = last_game\n\n # Each column counts as a mutation so max rows is ~10000\n GAMES_PER_COMMIT = 2000\n for games in grouper(tqdm(game_data), GAMES_PER_COMMIT):\n assert bt_table.read_row(EVAL_PREFIX.format(eval_num)), \"Prev row doesn't exists\"\n assert bt_table.read_row(EVAL_PREFIX.format(eval_num+1)) is None, \"Row already exists\"\n\n rows = []\n for i, metadata in enumerate(games):\n eval_num += 1\n row_name = EVAL_PREFIX.format(eval_num)\n row = bt_table.row(row_name)\n for column, value in metadata:\n row.set_cell(METADATA, column, value)\n rows.append(row)\n # For each batch of games print a couple of the rows being added.\n if i < 5 or i + 5 > len(games):\n print(\"\\t\", i, row_name, metadata[6][1])\n\n if eval_num == last_game + len(games):\n test = input(\"Commit ('y'/'yes' required): \")\n if test.lower() not in ('y', 'yes'):\n break\n\n # TODO(derek): Figure out how to condition on atomic counter update.\n # Condition all updates on the current value of last_game\n\n game_num_update = bt_table.row(TABLE_STATE)\n game_num_update.set_cell(METADATA, EVAL_GAME_COUNTER, eval_num)\n print(TABLE_STATE, eval_num)\n\n response = bt_table.mutate_rows(rows)\n\n # validate that all rows written successfully\n any_bad = False\n for i, status in enumerate(response):\n if status.code is not 0:\n print(\"Row number {} failed to write {}\".format(i, status))\n any_bad = True\n if any_bad:\n break\n\n game_num_update.commit()", "docstring": "Write all eval_records to eval_table\n\n In addition to writing new rows table_state must be updated in\n row `table_state` columns `metadata:eval_game_counter`\n\nArgs:\n bt_table: bigtable table to add rows to.\n game_data: metadata pairs (column name, value) for each eval record.\n last_game: last_game in metadata:table_state", "source": "juraj_google_style"} +{"code": "def __init__(self, item_type=None, min_length=None, max_length=None, empty=True):\n\n super(ListTypeChecker, self).__init__(\n iter_type=list, item_type=item_type, min_length=min_length, max_length=max_length, empty=empty\n )", "docstring": "Initialization method.\n\nArgs:\n item_type (type): the type of the items inside the list.\n min_length (int): minimum length of the list (included).\n max_length (int): maximum length of the list (included).\n empty (bool): whether empty list is allowed.", "source": "juraj_google_style"} +{"code": "def Write2000256List(self, arr):\n\n for item in arr:\n ba = bytearray(binascii.unhexlify(item))\n ba.reverse()\n self.WriteBytes(ba)", "docstring": "Write an array of 64 byte items to the stream.\n\nArgs:\n arr (list): a list of 2000 items of 64 bytes in size.", "source": "juraj_google_style"} +{"code": "def disease_terms(self, hgnc_id=None):\n\n query = {}\n if hgnc_id:\n LOG.debug(\"Fetching all diseases for gene %s\", hgnc_id)\n query['genes'] = hgnc_id\n else:\n LOG.info(\"Fetching all disease terms\")\n\n return list(self.disease_term_collection.find(query))", "docstring": "Return all disease terms that overlaps a gene\n\n If no gene, return all disease terms\n\nArgs:\n hgnc_id(int)\n\nReturns:\n iterable(dict): A list with all disease terms that match", "source": "juraj_google_style"} +{"code": "def put(self, name, base):\n\n async def fini():\n if self.base_by_name.get(name) is base:\n self.base_by_name.pop(name, None)\n\n # Remove myself from BaseRef when I fini\n base.onfini(fini)\n self.base_by_name[name] = base", "docstring": "Add a Base (or sub-class) to the BaseRef by name.\n\nArgs:\n name (str): The name/iden of the Base\n base (Base): The Base instance\n\nReturns:\n (None)", "source": "juraj_google_style"} +{"code": "def load_hpo_terms(adapter, hpo_lines=None, hpo_gene_lines=None, alias_genes=None):\n\n\n # Store the hpo terms\n hpo_terms = {}\n\n # Fetch the hpo terms if no file\n if not hpo_lines:\n hpo_lines = fetch_hpo_terms()\n\n # Fetch the hpo gene information if no file\n if not hpo_gene_lines:\n hpo_gene_lines = fetch_hpo_to_genes()\n\n # Parse the terms\n # This will yield dictionaries with information about the terms\n LOG.info(\"Parsing hpo terms\")\n for term in parse_hpo_obo(hpo_lines):\n hpo_terms[term['hpo_id']] = term\n\n # Get a map with hgnc symbols to hgnc ids from scout\n if not alias_genes:\n alias_genes = adapter.genes_by_alias()\n\n LOG.info(\"Adding gene information to hpo terms ...\")\n for hpo_to_symbol in parse_hpo_to_genes(hpo_gene_lines):\n hgnc_symbol = hpo_to_symbol['hgnc_symbol']\n hpo_id = hpo_to_symbol['hpo_id']\n\n # Fetch gene info to get correct hgnc id\n gene_info = alias_genes.get(hgnc_symbol)\n if not gene_info:\n continue\n\n hgnc_id = gene_info['true']\n\n if hpo_id not in hpo_terms:\n continue\n\n hpo_term = hpo_terms[hpo_id]\n\n if not 'genes' in hpo_term:\n hpo_term['genes'] = set()\n\n hpo_term['genes'].add(hgnc_id)\n\n start_time = datetime.now()\n\n LOG.info(\"Loading the hpo terms...\")\n nr_terms = len(hpo_terms)\n hpo_bulk = []\n with progressbar(hpo_terms.values(), label=\"Loading hpo terms\", length=nr_terms) as bar:\n\n for hpo_info in bar:\n hpo_bulk.append(build_hpo_term(hpo_info))\n\n if len(hpo_bulk) > 10000:\n adapter.load_hpo_bulk(hpo_bulk)\n hpo_bulk = []\n\n if hpo_bulk:\n adapter.load_hpo_bulk(hpo_bulk)\n\n LOG.info(\"Loading done. Nr of terms loaded {0}\".format(nr_terms))\n LOG.info(\"Time to load terms: {0}\".format(datetime.now() - start_time))", "docstring": "Load the hpo terms into the database\n\n Parse the hpo lines, build the objects and add them to the database\n\nArgs:\n adapter(MongoAdapter)\n hpo_lines(iterable(str))\n hpo_gene_lines(iterable(str))", "source": "juraj_google_style"} +{"code": "def __init__(self, *args):\n\n if len(args) == 1:\n args = args[0]\n try:\n extent = list(map(float, args))\n except (TypeError, ValueError) as exc:\n exc.args = ('Cannot create Envelope from \"%s\"' % repr(args),)\n raise\n try:\n self.min_x, self.max_x = sorted(extent[::2])\n self.min_y, self.max_y = sorted(extent[1::2])\n except ValueError as exc:\n exc.args = ('Sequence length should be \"4\", not \"%d\"' % len(args),)\n raise", "docstring": "Creates an envelope from lower-left and upper-right coordinates.\n\nArgs:\n args -- min_x, min_y, max_x, max_y or a four-tuple", "source": "juraj_google_style"} +{"code": "def adapt(self, d, x):\n\n self.update_memory_x(x)\n m_d, m_x = self.read_memory()\n # estimate\n y = np.dot(self.w, x-m_x) + m_d\n e = d - y\n nu = self.mu / (self.eps + np.dot(x-m_x, x-m_x))\n dw = nu * e * (x-m_x)\n self.w += dw\n self.update_memory_d(d)", "docstring": "Adapt weights according one desired value and its input.\n\nArgs:\n * `d` : desired value (float)\n\n * `x` : input array (1-dimensional array)", "source": "juraj_google_style"} +{"code": "def save(self, savefile):\n\n with open(str(savefile), 'wb') as f:\n self.write_to_fp(f)\n log.debug(\"Saved to %s\", savefile)", "docstring": "Do the TTS API request and write result to file.\n\nArgs:\n savefile (string): The path and file name to save the ``mp3`` to.\n\nRaises:\n :class:`gTTSError`: When there's an error with the API request.", "source": "juraj_google_style"} +{"code": "def _predict_one(self, document, encoding=None, return_blocks=False):\n\n # blockify\n blocks = self.blockifier.blockify(document, encoding=encoding)\n # get features\n try:\n features = self.features.transform(blocks)\n except ValueError: # Can't make features, predict no content\n preds = np.zeros((len(blocks)))\n # make predictions\n else:\n if self.prob_threshold is None:\n preds = self.model.predict(features)\n else:\n self._positive_idx = (\n self._positive_idx or list(self.model.classes_).index(1))\n preds = self.model.predict_proba(features) > self.prob_threshold\n preds = preds[:, self._positive_idx].astype(int)\n\n if return_blocks:\n return preds, blocks\n else:\n return preds", "docstring": "Predict class (content=1 or not-content=0) of each block in an HTML\n document.\n\nArgs:\n documents (str): HTML document\n\nReturns:\n ``np.ndarray``: array of binary predictions for content (1) or\n not-content (0).", "source": "juraj_google_style"} +{"code": "def getSet(self, name):\n\n return lock_and_call(\n lambda: Set(self._impl.getSet(name)),\n self._lock\n )", "docstring": "Get the set with the corresponding name.\n\nArgs:\n name: Name of the set to be found.\n\nRaises:\n TypeError: if the specified set does not exist.", "source": "juraj_google_style"} +{"code": "def expand_dims(self, axis):\n\n if axis == -1:\n axis = self.ndim\n if axis <= self._distaxis:\n subaxis = axis\n new_distaxis = self._distaxis + 1\n else:\n subaxis = axis - 1\n new_distaxis = self._distaxis\n new_subarrays = [expand_dims(ra, subaxis) for ra in self._subarrays]\n return DistArray(new_subarrays, new_distaxis)", "docstring": "Insert a new axis, at a given position in the array shape\n\nArgs:\n axis (int): Position (amongst axes) where new axis is to be inserted.", "source": "juraj_google_style"} +{"code": "def __init__(self, name, lim_low=85., lim_high=95., **kwargs):\n\n self.lim_low = lim_low\n self.lim_high = lim_high\n super(DayNightCompositor, self).__init__(name, **kwargs)", "docstring": "Collect custom configuration values.\n\nArgs:\n lim_low (float): lower limit of Sun zenith angle for the\n blending of the given channels\n lim_high (float): upper limit of Sun zenith angle for the\n blending of the given channels", "source": "juraj_google_style"} +{"code": "def _run_dnb_normalization(self, dnb_data, sza_data):\n\n # convert dask arrays to DataArray objects\n dnb_data = xr.DataArray(dnb_data, dims=('y', 'x'))\n sza_data = xr.DataArray(sza_data, dims=('y', 'x'))\n\n good_mask = ~(dnb_data.isnull() | sza_data.isnull())\n # good_mask = ~(dnb_data.mask | sza_data.mask)\n output_dataset = dnb_data.where(good_mask)\n # we only need the numpy array\n output_dataset = output_dataset.values.copy()\n dnb_data = dnb_data.values\n sza_data = sza_data.values\n\n day_mask, mixed_mask, night_mask = make_day_night_masks(\n sza_data,\n good_mask.values,\n self.high_angle_cutoff,\n self.low_angle_cutoff,\n stepsDegrees=self.mixed_degree_step)\n\n did_equalize = False\n has_multi_times = len(mixed_mask) > 0\n if day_mask.any():\n did_equalize = True\n if self.adaptive_day == \"always\" or (\n has_multi_times and self.adaptive_day == \"multiple\"):\n LOG.debug(\"Adaptive histogram equalizing DNB day data...\")\n local_histogram_equalization(\n dnb_data,\n day_mask,\n valid_data_mask=good_mask.values,\n local_radius_px=self.day_radius_pixels,\n out=output_dataset)\n else:\n LOG.debug(\"Histogram equalizing DNB day data...\")\n histogram_equalization(dnb_data,\n day_mask,\n out=output_dataset)\n if mixed_mask:\n for mask in mixed_mask:\n if mask.any():\n did_equalize = True\n if self.adaptive_mixed == \"always\" or (\n has_multi_times and\n self.adaptive_mixed == \"multiple\"):\n LOG.debug(\n \"Adaptive histogram equalizing DNB mixed data...\")\n local_histogram_equalization(\n dnb_data,\n mask,\n valid_data_mask=good_mask.values,\n local_radius_px=self.mixed_radius_pixels,\n out=output_dataset)\n else:\n LOG.debug(\"Histogram equalizing DNB mixed data...\")\n histogram_equalization(dnb_data,\n day_mask,\n out=output_dataset)\n if night_mask.any():\n did_equalize = True\n if self.adaptive_night == \"always\" or (\n has_multi_times and self.adaptive_night == \"multiple\"):\n LOG.debug(\"Adaptive histogram equalizing DNB night data...\")\n local_histogram_equalization(\n dnb_data,\n night_mask,\n valid_data_mask=good_mask.values,\n local_radius_px=self.night_radius_pixels,\n out=output_dataset)\n else:\n LOG.debug(\"Histogram equalizing DNB night data...\")\n histogram_equalization(dnb_data,\n night_mask,\n out=output_dataset)\n\n if not did_equalize:\n raise RuntimeError(\"No valid data found to histogram equalize\")\n\n return output_dataset", "docstring": "Scale the DNB data using a adaptive histogram equalization method.\n\nArgs:\n dnb_data (ndarray): Day/Night Band data array\n sza_data (ndarray): Solar Zenith Angle data array", "source": "juraj_google_style"} +{"code": "def __init__(self, access_token, user_agent, revoke_uri=None):\n\n super(AccessTokenCredentials, self).__init__(\n access_token,\n None,\n None,\n None,\n None,\n None,\n user_agent,\n revoke_uri=revoke_uri)", "docstring": "Create an instance of OAuth2Credentials\n\n This is one of the few types if Credentials that you should contrust,\n Credentials objects are usually instantiated by a Flow.\n\nArgs:\n access_token: string, access token.\n user_agent: string, The HTTP User-Agent to provide for this\n application.\n revoke_uri: string, URI for revoke endpoint. Defaults to None; a\n token can't be revoked if this is None.", "source": "juraj_google_style"} +{"code": "def divide(x1, x2, output_shape=None, name=None):\n\n output_shape = convert_to_shape(output_shape)\n if not isinstance(x2, Tensor):\n return ScalarMultiplyOperation(x1, 1.0 / x2).outputs[0]\n with tf.name_scope(name, default_name=\"divide\"):\n x1, x2 = binary_arguments_to_tensors(x1, x2)\n return multiply(x1, reciprocal(x2), output_shape=output_shape)", "docstring": "Binary division with broadcasting.\n\nArgs:\n x1: a Tensor\n x2: a Tensor\n output_shape: an optional Shape\n name: an optional string\n\nReturns:\n a Tensor", "source": "juraj_google_style"} +{"code": "def from_json(self, js, groups: Iterable[Group]):\n\n self.index = js[\"index\"]\n self.groupIndex = js[\"groupIndex\"]\n self.label = js[\"label\"]\n self.functionalChannelType = FunctionalChannelType.from_str(\n js[\"functionalChannelType\"], js[\"functionalChannelType\"]\n )\n self.groups = []\n for id in js[\"groups\"]:\n for g in groups:\n if g.id == id:\n self.groups.append(g)\n break", "docstring": "this function will load the functional channel object\n from a json object and the given groups\n\nArgs:\n js(dict): the json object\n groups(Iterable[Group]): the groups for referencing", "source": "juraj_google_style"} +{"code": "def comment_update(self, comment_id, body):\n\n params = {'comment[body]': body}\n return self._get('comments/{0}.json'.format(comment_id), params, 'PUT',\n auth=True)", "docstring": "Function to update a comment (Requires login).\n\n Parameters:\n comment_id (int):\n body (str):", "source": "juraj_google_style"} +{"code": "def compute_bleu(reference_corpus, translation_corpus, max_order=4,\n use_bp=True):\n\n reference_length = 0\n translation_length = 0\n bp = 1.0\n geo_mean = 0\n\n matches_by_order = [0] * max_order\n possible_matches_by_order = [0] * max_order\n precisions = []\n\n for (references, translations) in zip(reference_corpus, translation_corpus):\n reference_length += len(references)\n translation_length += len(translations)\n ref_ngram_counts = _get_ngrams_with_counter(references, max_order)\n translation_ngram_counts = _get_ngrams_with_counter(translations, max_order)\n\n overlap = dict((ngram,\n min(count, translation_ngram_counts[ngram]))\n for ngram, count in ref_ngram_counts.items())\n\n for ngram in overlap:\n matches_by_order[len(ngram) - 1] += overlap[ngram]\n for ngram in translation_ngram_counts:\n possible_matches_by_order[len(ngram) - 1] += translation_ngram_counts[\n ngram]\n\n precisions = [0] * max_order\n smooth = 1.0\n\n for i in xrange(0, max_order):\n if possible_matches_by_order[i] > 0:\n precisions[i] = float(matches_by_order[i]) / possible_matches_by_order[i]\n if matches_by_order[i] > 0:\n precisions[i] = float(matches_by_order[i]) / possible_matches_by_order[\n i]\n else:\n smooth *= 2\n precisions[i] = 1.0 / (smooth * possible_matches_by_order[i])\n else:\n precisions[i] = 0.0\n\n if max(precisions) > 0:\n p_log_sum = sum(math.log(p) for p in precisions if p)\n geo_mean = math.exp(p_log_sum / max_order)\n\n if use_bp:\n ratio = translation_length / reference_length\n bp = math.exp(1 - 1. / ratio) if ratio < 1.0 else 1.0\n bleu = geo_mean * bp\n return np.float32(bleu)", "docstring": "Computes BLEU score of translated segments against one or more references.\n\nArgs:\n reference_corpus: list of references for each translation. Each\n reference should be tokenized into a list of tokens.\n translation_corpus: list of translations to score. Each translation\n should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n use_bp: boolean, whether to apply brevity penalty.\n\nReturns:\n BLEU score.", "source": "juraj_google_style"} +{"code": "def list_tasks(target=None):\n\n from os import getcwd, chdir\n from glob import glob\n original = getcwd()\n if target is None:# pragma: no cover\n target = _dbdir()\n\n chdir(target)\n result = {}\n for filename in glob(\"*.*.json\"):\n project, task = filename.split('.')[0:2]\n if project not in result:\n result[project] = []\n result[project].append(task)\n\n #Set the working directory back to what it was.\n chdir(original)\n\n return result", "docstring": "Returns a list of all the projects and tasks available in the `acorn`\n database directory.\n\nArgs:\n target (str): directory to list the projects for. Defaults to the configured\n database directory.\n\nReturns:\n dict: keys are project names; values are lists of tasks associated with the\n project.", "source": "juraj_google_style"} +{"code": "def __send_ses_email(self, recipients, subject, body_html, body_text):\n\n source_arn = dbconfig.get('source_arn', NS_EMAIL)\n return_arn = dbconfig.get('return_path_arn', NS_EMAIL)\n\n session = get_local_aws_session()\n ses = session.client('ses', region_name=dbconfig.get('ses_region', NS_EMAIL, 'us-west-2'))\n\n body = {}\n if body_html:\n body['Html'] = {\n 'Data': body_html\n }\n if body_text:\n body['Text'] = {\n 'Data': body_text\n }\n\n ses_options = {\n 'Source': self.sender,\n 'Destination': {\n 'ToAddresses': recipients\n },\n 'Message': {\n 'Subject': {\n 'Data': subject\n },\n 'Body': body\n }\n }\n\n # Set SES options if needed\n if source_arn and return_arn:\n ses_options.update({\n 'SourceArn': source_arn,\n 'ReturnPathArn': return_arn\n })\n\n ses.send_email(**ses_options)", "docstring": "Send an email using SES\n\nArgs:\n recipients (`1ist` of `str`): List of recipient email addresses\n subject (str): Subject of the email\n body_html (str): HTML body of the email\n body_text (str): Text body of the email\n\nReturns:\n `None`", "source": "juraj_google_style"} +{"code": "def recall(truth, recommend, k=None):\n\n if len(truth) == 0:\n if len(recommend) == 0:\n return 1.\n return 0.\n\n if k is None:\n k = len(recommend)\n return count_true_positive(truth, recommend[:k]) / float(truth.size)", "docstring": "Recall@k.\n\nArgs:\n truth (numpy 1d array): Set of truth samples.\n recommend (numpy 1d array): Ordered set of recommended samples.\n k (int): Top-k items in `recommend` will be recommended.\n\nReturns:\n float: Recall@k.", "source": "juraj_google_style"} +{"code": "def is_artifact_optional(chain, task_id, path):\n\n upstream_artifacts = chain.task['payload'].get('upstreamArtifacts', [])\n optional_artifacts_per_task_id = get_optional_artifacts_per_task_id(upstream_artifacts)\n return path in optional_artifacts_per_task_id.get(task_id, [])", "docstring": "Tells whether an artifact is flagged as optional or not.\n\nArgs:\n chain (ChainOfTrust): the chain of trust object\n task_id (str): the id of the aforementioned task\n\nReturns:\n bool: True if artifact is optional", "source": "juraj_google_style"} +{"code": "def get_descriptor_defaults(self, api_info, hostname=None):\n\n if self.__request:\n hostname = self.__request.reconstruct_hostname()\n protocol = self.__request.url_scheme\n else:\n hostname = (hostname or util.get_app_hostname() or\n api_info.hostname)\n protocol = 'http' if ((hostname and hostname.startswith('localhost')) or\n util.is_running_on_devserver()) else 'https'\n full_base_path = '{0}{1}/{2}/'.format(api_info.base_path,\n api_info.name,\n api_info.path_version)\n base_url = '{0}://{1}{2}'.format(protocol, hostname, full_base_path)\n root_url = '{0}://{1}{2}'.format(protocol, hostname, api_info.base_path)\n defaults = {\n 'kind': 'discovery#restDescription',\n 'discoveryVersion': 'v1',\n 'id': '{0}:{1}'.format(api_info.name, api_info.path_version),\n 'name': api_info.name,\n 'version': api_info.api_version,\n 'icons': {\n 'x16': 'https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png',\n 'x32': 'https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png'\n },\n 'protocol': 'rest',\n 'servicePath': '{0}/{1}/'.format(api_info.name, api_info.path_version),\n 'batchPath': 'batch',\n 'basePath': full_base_path,\n 'rootUrl': root_url,\n 'baseUrl': base_url,\n 'description': 'This is an API',\n }\n if api_info.description:\n defaults['description'] = api_info.description\n if api_info.title:\n defaults['title'] = api_info.title\n if api_info.documentation:\n defaults['documentationLink'] = api_info.documentation\n if api_info.canonical_name:\n defaults['canonicalName'] = api_info.canonical_name\n\n return defaults", "docstring": "Gets a default configuration for a service.\n\nArgs:\n api_info: _ApiInfo object for this service.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to None.\n\nReturns:\n A dictionary with the default configuration.", "source": "juraj_google_style"} +{"code": "def put_char(\n self,\n x: int,\n y: int,\n ch: int,\n bg_blend: int = tcod.constants.BKGND_DEFAULT,\n ) -> None:\n\n lib.TCOD_console_put_char(self.console_c, x, y, ch, bg_blend)", "docstring": "Draw the character c at x,y using the default colors and a blend mode.\n\nArgs:\n x (int): The x coordinate from the left.\n y (int): The y coordinate from the top.\n ch (int): Character code to draw. Must be in integer form.\n bg_blend (int): Blending mode to use, defaults to BKGND_DEFAULT.", "source": "juraj_google_style"} +{"code": "def __init__(self, file_pattern, action_function):\n\n super(GeneratorAction, self).__init__()\n self.__file_pattern = file_pattern\n self.__action_function = action_function", "docstring": "Container to store an \"action\".\n\n Every file(s) generation is considered as an action.\n\nArgs:\n file_pattern: fnmatch pattern.\n action_function: Callback without argument. See documentation.", "source": "juraj_google_style"} +{"code": "def is_special_unitary(\n matrix: np.ndarray,\n *,\n rtol: float = 1e-5,\n atol: float = 1e-8) -> bool:\n\n return (is_unitary(matrix, rtol=rtol, atol=atol) and\n (matrix.shape[0] == 0 or\n np.allclose(np.linalg.det(matrix), 1, rtol=rtol, atol=atol)))", "docstring": "Determines if a matrix is approximately unitary with unit determinant.\n\n A matrix is special-unitary if it is square and its adjoint is its inverse\n and its determinant is one.\n\nArgs:\n matrix: The matrix to check.\n rtol: The per-matrix-entry relative tolerance on equality.\n atol: The per-matrix-entry absolute tolerance on equality.\n\nReturns:\n Whether the matrix is unitary with unit determinant within the given\n tolerance.", "source": "juraj_google_style"} +{"code": "def smooth(self, noise, strategy=INVERSE_STRATEGY):\n\n if strategy is INVERSE_STRATEGY:\n self.points = with_inverse(self.points, noise)\n elif strategy is EXTRAPOLATE_STRATEGY:\n self.points = with_extrapolation(self.points, noise, 30)\n elif strategy is NO_STRATEGY:\n self.points = with_no_strategy(self.points, noise)\n return self", "docstring": "In-place smoothing\n\n See smooth_segment function\n\nArgs:\n noise (float): Noise expected\n strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY\n or smooth.EXTRAPOLATE_STRATEGY\n\nReturns:\n :obj:`Segment`", "source": "juraj_google_style"} +{"code": "def debug(self, status=None, nids=None):\n\n nrows, ncols = get_terminal_size()\n\n # Test for scheduler exceptions first.\n sched_excfile = os.path.join(self.workdir, \"_exceptions\")\n if os.path.exists(sched_excfile):\n with open(sched_excfile, \"r\") as fh:\n cprint(\"Found exceptions raised by the scheduler\", \"red\")\n cprint(fh.read(), color=\"red\")\n return\n\n if status is not None:\n tasks = list(self.iflat_tasks(status=status, nids=nids))\n else:\n errors = list(self.iflat_tasks(status=self.S_ERROR, nids=nids))\n qcriticals = list(self.iflat_tasks(status=self.S_QCRITICAL, nids=nids))\n abicriticals = list(self.iflat_tasks(status=self.S_ABICRITICAL, nids=nids))\n tasks = errors + qcriticals + abicriticals\n\n # For each task selected:\n # 1) Check the error files of the task. If not empty, print the content to stdout and we are done.\n # 2) If error files are empty, look at the master log file for possible errors\n # 3) If also this check failes, scan all the process log files.\n # TODO: This check is not needed if we introduce a new __abinit_error__ file\n # that is created by the first MPI process that invokes MPI abort!\n #\n ntasks = 0\n for task in tasks:\n print(make_banner(str(task), width=ncols, mark=\"=\"))\n ntasks += 1\n\n # Start with error files.\n for efname in [\"qerr_file\", \"stderr_file\",]:\n err_file = getattr(task, efname)\n if err_file.exists:\n s = err_file.read()\n if not s: continue\n print(make_banner(str(err_file), width=ncols, mark=\"=\"))\n cprint(s, color=\"red\")\n #count += 1\n\n # Check main log file.\n try:\n report = task.get_event_report()\n if report and report.num_errors:\n print(make_banner(os.path.basename(report.filename), width=ncols, mark=\"=\"))\n s = \"\\n\".join(str(e) for e in report.errors)\n else:\n s = None\n except Exception as exc:\n s = str(exc)\n\n count = 0 # count > 0 means we found some useful info that could explain the failures.\n if s is not None:\n cprint(s, color=\"red\")\n count += 1\n\n if not count:\n # Inspect all log files produced by the other nodes.\n log_files = task.tmpdir.list_filepaths(wildcard=\"*LOG_*\")\n if not log_files:\n cprint(\"No *LOG_* file in tmpdir. This usually happens if you are running with many CPUs\", color=\"magenta\")\n\n for log_file in log_files:\n try:\n report = EventsParser().parse(log_file)\n if report.errors:\n print(report)\n count += 1\n break\n except Exception as exc:\n cprint(str(exc), color=\"red\")\n count += 1\n break\n\n if not count:\n cprint(\"Houston, we could not find any error message that can explain the problem\", color=\"magenta\")\n\n print(\"Number of tasks analyzed: %d\" % ntasks)", "docstring": "This method is usually used when the flow didn't completed succesfully\n It analyzes the files produced the tasks to facilitate debugging.\n Info are printed to stdout.\n\nArgs:\n status: If not None, only the tasks with this status are selected\n nids: optional list of node identifiers used to filter the tasks.", "source": "juraj_google_style"} +{"code": "def _build_zmat(self, construction_table):\n\n c_table = construction_table\n default_cols = ['atom', 'b', 'bond', 'a', 'angle', 'd', 'dihedral']\n optional_cols = list(set(self.columns) - {'atom', 'x', 'y', 'z'})\n\n zmat_frame = pd.DataFrame(columns=default_cols + optional_cols,\n dtype='float', index=c_table.index)\n\n zmat_frame.loc[:, optional_cols] = self.loc[c_table.index,\n optional_cols]\n\n zmat_frame.loc[:, 'atom'] = self.loc[c_table.index, 'atom']\n zmat_frame.loc[:, ['b', 'a', 'd']] = c_table\n\n zmat_values = self._calculate_zmat_values(c_table)\n zmat_frame.loc[:, ['bond', 'angle', 'dihedral']] = zmat_values\n\n zmatrix = Zmat(zmat_frame, metadata=self.metadata,\n _metadata={'last_valid_cartesian': self.copy()})\n return zmatrix", "docstring": "Create the Zmatrix from a construction table.\n\nArgs:\n Construction table (pd.DataFrame):\n\nReturns:\n Zmat: A new instance of :class:`Zmat`.", "source": "juraj_google_style"} +{"code": "def element(self, using, value):\n\n return self._execute(Command.FIND_CHILD_ELEMENT, {\n 'using': using,\n 'value': value\n })", "docstring": "find an element in the current element.\n\n Support:\n Android iOS Web(WebView)\n\nArgs:\n using(str): The element location strategy.\n value(str): The value of the location strategy.\n\nReturns:\n WebElement Object.\n\nRaises:\n WebDriverException.", "source": "juraj_google_style"} +{"code": "def update_subscription(self, *, subscription_id, credit_card_token):\n\n payload = {\n \"creditCardToken\": credit_card_token\n }\n fmt = 'subscriptions/{}'.format(subscription_id)\n return self.client._put(self.url + fmt, json=payload, headers=self.get_headers())", "docstring": "Update information associated with the specified subscription. At the moment it is only possible\n to update the token of the credit card to which the charge of the subscription is made.\n\nArgs:\n subscription_id: Identification of the subscription.\n credit_card_token:\n\n Returns:", "source": "juraj_google_style"} +{"code": "def add_column(self, column_name, column_values):\n\n # Sanity checks.\n if isinstance(column_values, list) and isinstance(column_values[0], list):\n raise ValueError('\"column_values\" must be a flat list, but we detected '\n 'that its first entry is a list')\n\n if isinstance(column_values, np.ndarray) and column_values.ndim != 1:\n raise ValueError('\"column_values\" should be of rank 1, '\n 'but is of rank %d' % column_values.ndim)\n if len(column_values) != self.num_points:\n raise ValueError('\"column_values\" should be of length %d, but is of '\n 'length %d' % (self.num_points, len(column_values)))\n if column_name in self.name_to_values:\n raise ValueError('The column name \"%s\" is already used' % column_name)\n\n self.column_names.append(column_name)\n self.name_to_values[column_name] = column_values", "docstring": "Adds a named column of metadata values.\n\nArgs:\n column_name: Name of the column.\n column_values: 1D array/list/iterable holding the column values. Must be\n of length `num_points`. The i-th value corresponds to the i-th point.\n\nRaises:\n ValueError: If `column_values` is not 1D array, or of length `num_points`,\n or the `name` is already used.", "source": "juraj_google_style"} +{"code": "def corpus_page_generator(corpus_files, tmp_dir, max_page_size_exp):\n\n for remote_filepath in corpus_files:\n\n filepath = maybe_copy_file_to_directory(remote_filepath, tmp_dir)\n tf.logging.info(\"Reading from \" + filepath)\n\n command = [\"7z\", \"x\", \"-so\", filepath]\n tf.logging.info(\"Running command: %s\", command)\n\n p = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=-1)\n\n for page in file_page_generator(p.stdout, 2**max_page_size_exp):\n yield page", "docstring": "Generate pages from a list of .7z encoded history dumps.\n\nArgs:\n corpus_files: a list of strings\n tmp_dir: a string\n max_page_size_exp: an integer\n\nYields:\n strings", "source": "juraj_google_style"} +{"code": "def check_the_end_flag(self, state_key):\n\n # As a rule, the learning can not be stopped.\n x, y = state_key\n end_point_tuple = np.where(self.__map_arr == self.__end_point_label)\n end_point_x_arr, end_point_y_arr = end_point_tuple\n if x == end_point_x_arr[0] and y == end_point_y_arr[0]:\n return True\n else:\n return False", "docstring": "Check the end flag.\n\n If this return value is `True`, the learning is end.\n\nArgs:\n state_key: The key of state in `self.t`.\n\nReturns:\n bool", "source": "juraj_google_style"} +{"code": "def GetSystemConfigurationArtifact(self, session_identifier=CURRENT_SESSION):\n\n system_configuration = artifacts.SystemConfigurationArtifact()\n\n system_configuration.code_page = self.GetValue(\n 'codepage', default_value=self._codepage)\n\n system_configuration.hostname = self._hostnames.get(\n session_identifier, None)\n\n system_configuration.keyboard_layout = self.GetValue('keyboard_layout')\n system_configuration.operating_system = self.GetValue('operating_system')\n system_configuration.operating_system_product = self.GetValue(\n 'operating_system_product')\n system_configuration.operating_system_version = self.GetValue(\n 'operating_system_version')\n\n date_time = datetime.datetime(2017, 1, 1)\n time_zone = self._time_zone.tzname(date_time)\n\n if time_zone and isinstance(time_zone, py2to3.BYTES_TYPE):\n time_zone = time_zone.decode('ascii')\n\n system_configuration.time_zone = time_zone\n\n user_accounts = self._user_accounts.get(session_identifier, {})\n # In Python 3 dict.values() returns a type dict_values, which will cause\n # the JSON serializer to raise a TypeError.\n system_configuration.user_accounts = list(user_accounts.values())\n\n return system_configuration", "docstring": "Retrieves the knowledge base as a system configuration artifact.\n\nArgs:\n session_identifier (Optional[str])): session identifier, where\n CURRENT_SESSION represents the active session.\n\nReturns:\n SystemConfigurationArtifact: system configuration artifact.", "source": "juraj_google_style"} +{"code": "def Decrypt(self, encrypted_data):\n\n decrypted_data = self._rc4_cipher.decrypt(encrypted_data)\n return decrypted_data, b''", "docstring": "Decrypts the encrypted data.\n\nArgs:\n encrypted_data (bytes): encrypted data.\n\nReturns:\n tuple[bytes,bytes]: decrypted data and remaining encrypted data.", "source": "juraj_google_style"} +{"code": "def GetEnvironmentVariable(self, name):\n\n name = name.upper()\n return self._environment_variables.get(name, None)", "docstring": "Retrieves an environment variable.\n\nArgs:\n name (str): name of the environment variable.\n\nReturns:\n EnvironmentVariableArtifact: environment variable artifact or None\n if there was no value set for the given name.", "source": "juraj_google_style"} +{"code": "def get_params_from_sqlalchemy_url(db_url):\n # type: (str) -> Dict[str,Any]\n\n result = urlsplit(db_url)\n return {'database': result.path[1:], 'host': result.hostname, 'port': result.port,\n 'username': result.username, 'password': result.password, 'driver': result.scheme}", "docstring": "Gets PostgreSQL database connection parameters from SQLAlchemy url\n\nArgs:\n db_url (str): SQLAlchemy url\n\nReturns:\n Dict[str,Any]: Dictionary of database connection parameters", "source": "juraj_google_style"} +{"code": "def set(self, key, value):\n\n\n match = self._get_match(key=key)\n\n if not match:\n self._log.info('\"%s\" does not exist, so it will be added.', key)\n\n if isinstance(value, str):\n self._log.info('\"%s\" will be added as a PHP string value.',\n key)\n value_str = '\\'{}\\''.format(value)\n else:\n self._log.info('\"%s\" will be added as a PHP object value.',\n key)\n value_str = str(value).lower()\n\n new = 'define(\\'{key}\\', {value});'.format(\n key=key,\n value=value_str)\n\n self._log.info('\"%s\" will be added as: %s', key, new)\n\n replace_this = '>> x,y = cp.variable(2)\n >>> P = cp.Poly([x-1, y])\n >>> Q = cp.Poly([x+1, x*y])\n >>> print(cp.inner(P, Q))\n q0^2+q0q1^2-1\n >>> x = numpy.arange(4)\n >>> print(cp.inner(x, x))\n 14", "source": "juraj_google_style"} +{"code": "def GetUsernameByIdentifier(\n self, user_identifier, session_identifier=CURRENT_SESSION):\n\n user_accounts = self._user_accounts.get(session_identifier, {})\n user_account = user_accounts.get(user_identifier, None)\n if not user_account:\n return ''\n\n return user_account.username or ''", "docstring": "Retrieves the username based on an user identifier.\n\nArgs:\n user_identifier (str): user identifier, either a UID or SID.\n session_identifier (Optional[str])): session identifier, where\n CURRENT_SESSION represents the active session.\n\nReturns:\n str: username.", "source": "juraj_google_style"} +{"code": "def blocksearch(block, name):\n\n if hasattr(block, 'tokens'):\n for b in block.tokens[1]:\n b = (b if hasattr(b, 'raw') and b.raw() == name else blocksearch(\n b, name))\n if b:\n return b\n return False", "docstring": "Recursive search for name in block (inner blocks)\n\nArgs:\n name (str): search term\n\nReturns:\n Block OR False", "source": "juraj_google_style"} +{"code": "def get_properties(properties_file='raw.properties.json', env=None, region=None):\n\n with open(properties_file, 'rt') as file_handle:\n properties = json.load(file_handle)\n\n env_properties = properties.get(env, properties)\n contents = env_properties.get(region, env_properties)\n LOG.debug('Found properties for %s:\\n%s', env, contents)\n return contents", "docstring": "Get contents of _properties_file_ for the _env_.\n\nArgs:\n properties_file (str): File name of `create-configs` JSON output.\n env (str): Environment to read optionally.\n region (str): Region to get specific configs for.\n\nReturns:\n dict: JSON loaded Application properties for _env_.\n None: Given _env_ was not found in `create-configs` JSON output.", "source": "juraj_google_style"} +{"code": "def __init__(self, context):\n\n self._logdir = context.logdir\n self._multiplexer = context.multiplexer\n self._plugin_name_to_instance = context.plugin_name_to_instance", "docstring": "Instantiates ScalarsPlugin via TensorBoard core.\n\nArgs:\n context: A base_plugin.TBContext instance.", "source": "juraj_google_style"} +{"code": "def _RunScript(self, metadata_key, metadata_script):\n\n process = subprocess.Popen(\n metadata_script, shell=True,\n executable=self.default_shell,\n stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n while True:\n for line in iter(process.stdout.readline, b''):\n message = line.decode('utf-8', 'replace').rstrip('\\n')\n if message:\n self.logger.info('%s: %s', metadata_key, message)\n if process.poll() is not None:\n break\n self.logger.info('%s: Return code %s.', metadata_key, process.returncode)", "docstring": "Run a script and log the streamed script output.\n\nArgs:\n metadata_key: string, the key specifing the metadata script.\n metadata_script: string, the file location of an executable script.", "source": "juraj_google_style"} +{"code": "def _layer_to_path_gen(layer):\n\n draw = False\n for x, y in zip(*layer):\n if np.isnan(x) or np.isnan(y):\n draw = False\n elif not draw:\n yield 'M {} {}'.format(x, y)\n draw = True\n else:\n yield 'L {} {}'.format(x, y)", "docstring": "Generates an SVG path from a given layer.\n\nArgs:\n layer (layer): the layer to convert\n\nYields:\n str: the next component of the path", "source": "juraj_google_style"} +{"code": "def __init__(self, name, path, dsm=None, package=None):\n\n super().__init__()\n self.name = name\n self.path = path\n self.package = package\n self.dsm = dsm\n self.dependencies = []", "docstring": "Initialization method.\n\nArgs:\n name (str): name of the module.\n path (str): path to the module.\n dsm (DSM): parent DSM.\n package (Package): parent Package.", "source": "juraj_google_style"} +{"code": "def receiveds_parsing(receiveds):\n\n\n parsed = []\n receiveds = [re.sub(JUNK_PATTERN, \" \", i).strip() for i in receiveds]\n n = len(receiveds)\n log.debug(\"Nr. of receiveds. {}\".format(n))\n\n for idx, received in enumerate(receiveds):\n log.debug(\"Parsing received {}/{}\".format(idx + 1, n))\n log.debug(\"Try to parse {!r}\".format(received))\n try:\n # try to parse the current received header...\n values_by_clause = parse_received(received)\n except MailParserReceivedParsingError:\n # if we can't, let's append the raw\n parsed.append({'raw': received})\n else:\n # otherwise append the full values_by_clause dict\n parsed.append(values_by_clause)\n\n log.debug(\"len(receiveds) %s, len(parsed) %s\" % (\n len(receiveds), len(parsed)))\n\n if len(receiveds) != len(parsed):\n # something really bad happened,\n # so just return raw receiveds with hop indices\n log.error(\"len(receiveds): %s, len(parsed): %s, receiveds: %s, \\\n parsed: %s\" % (len(receiveds), len(parsed), receiveds, parsed))\n return receiveds_not_parsed(receiveds)\n\n else:\n # all's good! we have parsed or raw receiveds for each received header\n return receiveds_format(parsed)", "docstring": "This function parses the receiveds headers.\n\nArgs:\n receiveds (list): list of raw receiveds headers\n\nReturns:\n a list of parsed receiveds headers with first hop in first position", "source": "juraj_google_style"} +{"code": "def read(self, nodes=None, **kwargs):\n\n if nodes is None:\n required_nodes = self.wishlist - set(self.datasets.keys())\n nodes = self.dep_tree.leaves(nodes=required_nodes)\n return self._read_datasets(nodes, **kwargs)", "docstring": "Load datasets from the necessary reader.\n\nArgs:\n nodes (iterable): DependencyTree Node objects\n **kwargs: Keyword arguments to pass to the reader's `load` method.\n\nReturns:\n DatasetDict of loaded datasets", "source": "juraj_google_style"} +{"code": "def serve(self, model_dir, environment):\n\n logger.info(\"serving\")\n\n self.container_root = self._create_tmp_folder()\n logger.info('creating hosting dir in {}'.format(self.container_root))\n\n volumes = self._prepare_serving_volumes(model_dir)\n\n # If the user script was passed as a file:// mount it to the container.\n if sagemaker.estimator.DIR_PARAM_NAME.upper() in environment:\n script_dir = environment[sagemaker.estimator.DIR_PARAM_NAME.upper()]\n parsed_uri = urlparse(script_dir)\n if parsed_uri.scheme == 'file':\n volumes.append(_Volume(parsed_uri.path, '/opt/ml/code'))\n # Update path to mount location\n environment = environment.copy()\n environment[sagemaker.estimator.DIR_PARAM_NAME.upper()] = '/opt/ml/code'\n\n if _ecr_login_if_needed(self.sagemaker_session.boto_session, self.image):\n _pull_image(self.image)\n\n self._generate_compose_file('serve',\n additional_env_vars=environment,\n additional_volumes=volumes)\n compose_command = self._compose()\n self.container = _HostingContainer(compose_command)\n self.container.start()", "docstring": "Host a local endpoint using docker-compose.\n\nArgs:\n primary_container (dict): dictionary containing the container runtime settings\n for serving. Expected keys:\n - 'ModelDataUrl' pointing to a file or s3:// location.\n - 'Environment' a dictionary of environment variables to be passed to the hosting container.", "source": "juraj_google_style"} +{"code": "def _AddsAnalysisProcessStatusTableRow(self, process_status, table_view):\n\n used_memory = self._FormatSizeInUnitsOf1024(process_status.used_memory)\n\n events = ''\n if (process_status.number_of_consumed_events is not None and\n process_status.number_of_consumed_events_delta is not None):\n events = '{0:d} ({1:d})'.format(\n process_status.number_of_consumed_events,\n process_status.number_of_consumed_events_delta)\n\n event_tags = ''\n if (process_status.number_of_produced_event_tags is not None and\n process_status.number_of_produced_event_tags_delta is not None):\n event_tags = '{0:d} ({1:d})'.format(\n process_status.number_of_produced_event_tags,\n process_status.number_of_produced_event_tags_delta)\n\n reports = ''\n if (process_status.number_of_produced_reports is not None and\n process_status.number_of_produced_reports_delta is not None):\n reports = '{0:d} ({1:d})'.format(\n process_status.number_of_produced_reports,\n process_status.number_of_produced_reports_delta)\n\n table_view.AddRow([\n process_status.identifier, process_status.pid, process_status.status,\n used_memory, events, event_tags, reports])", "docstring": "Adds an analysis process status table row.\n\nArgs:\n process_status (ProcessStatus): processing status.\n table_view (CLITabularTableView): table view.", "source": "juraj_google_style"} +{"code": "def update_dns_zone_record(env, zone_id, **kwargs):\n\n client = boto3.Session(profile_name=env).client('route53')\n response = {}\n\n hosted_zone_info = client.get_hosted_zone(Id=zone_id)\n zone_name = hosted_zone_info['HostedZone']['Name'].rstrip('.')\n dns_name = kwargs.get('dns_name')\n\n if dns_name and dns_name.endswith(zone_name):\n dns_name_aws = kwargs.get('dns_name_aws')\n # This is what will be added to DNS\n dns_json = get_template(template_file='infrastructure/dns_upsert.json.j2', **kwargs)\n LOG.info('Attempting to create DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id,\n zone_name)\n try:\n response = client.change_resource_record_sets(\n HostedZoneId=zone_id,\n ChangeBatch=json.loads(dns_json), )\n LOG.info('Upserted DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id, zone_name)\n except botocore.exceptions.ClientError as error:\n LOG.info('Error creating DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id,\n zone_name)\n LOG.debug(error)\n else:\n LOG.info('Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)', dns_name, zone_id, zone_name)\n\n LOG.debug('Route53 JSON Response: \\n%s', pformat(response))", "docstring": "Create a Route53 CNAME record in _env_ zone.\n\nArgs:\n env (str): Deployment environment.\n zone_id (str): Route53 zone id.\n\n Keyword Args:\n dns_name (str): FQDN of application's dns entry to add/update.\n dns_name_aws (str): FQDN of AWS resource\n dns_ttl (int): DNS time-to-live (ttl)", "source": "juraj_google_style"} +{"code": "def set_cookie(self, name, value, attrs={}):\n\n cookie = http.cookies.SimpleCookie()\n cookie[name] = value\n for key, value in attrs.items():\n cookie[name][key] = value\n self.add_header('Set-Cookie', cookie[name].OutputString())", "docstring": "Add a Set-Cookie header to response object.\n\n For a description about cookie attribute values, see\n https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel.\n\nArgs:\n name (str): Name of the cookie\n value (str): Value of the cookie\n attrs (dict): Dicitionary with cookie attribute keys and\n values.", "source": "juraj_google_style"} +{"code": "def FindMessageTypeByName(self, full_name):\n\n\n full_name = _NormalizeFullyQualifiedName(full_name)\n if full_name not in self._descriptors:\n self._FindFileContainingSymbolInDb(full_name)\n return self._descriptors[full_name]", "docstring": "Loads the named descriptor from the pool.\n\nArgs:\n full_name: The full name of the descriptor to load.\n\nReturns:\n The descriptor for the named type.\n\nRaises:\n KeyError: if the message cannot be found in the pool.", "source": "juraj_google_style"} +{"code": "def imflip(img, direction='horizontal'):\n\n assert direction in ['horizontal', 'vertical']\n if direction == 'horizontal':\n return np.flip(img, axis=1)\n else:\n return np.flip(img, axis=0)", "docstring": "Flip an image horizontally or vertically.\n\nArgs:\n img (ndarray): Image to be flipped.\n direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\nReturns:\n ndarray: The flipped image.", "source": "juraj_google_style"} +{"code": "def encode_varint_1(num):\n\n # Shift sign to the end of number\n num = (num << 1) ^ (num >> 63)\n # Max 10 bytes. We assert those are allocated\n buf = bytearray(10)\n\n for i in range(10):\n # 7 lowest bits from the number and set 8th if we still have pending\n # bits left to encode\n buf[i] = num & 0x7f | (0x80 if num > 0x7f else 0)\n num = num >> 7\n if num == 0:\n break\n else:\n # Max size of endcoded double is 10 bytes for unsigned values\n raise ValueError(\"Out of double range\")\n return buf[:i + 1]", "docstring": "Encode an integer to a varint presentation. See\n https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints\n on how those can be produced.\n\nArgs:\n num (int): Value to encode\n\nReturns:\n bytearray: Encoded presentation of integer with length from 1 to 10\n bytes", "source": "juraj_google_style"} +{"code": "def stations(self, station, limit=10):\n\n query = {\n 'start': 1,\n 'S': station + '?',\n 'REQ0JourneyStopsB': limit\n }\n rsp = requests.get('http://reiseauskunft.bahn.de/bin/ajax-getstop.exe/dn', params=query)\n return parse_stations(rsp.text)", "docstring": "Find stations for given queries\n\nArgs:\n station (str): search query\n limit (int): limit number of results", "source": "juraj_google_style"} +{"code": "def _detect_encoding(data=None):\n\n import locale\n enc_list = ['utf-8', 'latin-1', 'iso8859-1', 'iso8859-2',\n 'utf-16', 'cp720']\n code = locale.getpreferredencoding(False)\n if data is None:\n return code\n if code.lower() not in enc_list:\n enc_list.insert(0, code.lower())\n for c in enc_list:\n try:\n for line in data:\n line.decode(c)\n except (UnicodeDecodeError, UnicodeError, AttributeError):\n continue\n return c\n print(\"Encoding not detected. Please pass encoding value manually\")", "docstring": "Return the default system encoding. If data is passed, try\n to decode the data with the default system encoding or from a short\n list of encoding types to test.\n\nArgs:\n data - list of lists\n\nReturns:\n enc - system encoding", "source": "juraj_google_style"} +{"code": "def __init__(self, input_dim, minval, maxval, **kwargs):\n\n super(NGram, self).__init__(**kwargs)\n self.input_dim = input_dim\n self.minval = minval\n self.maxval = maxval", "docstring": "Constructs layer.\n\nArgs:\n input_dim: int > 0. Size of the vocabulary, i.e. maximum integer index +\n 1.\n minval: Lowest inclusive value of n for computing n-grams. For example,\n setting it to 1 will compute starting from unigrams.\n maxval: Highest non-inclusive value of n for computing n-grams. For\n example, setting it to 3 will compute at most bigrams.\n **kwargs: kwargs of parent class.", "source": "juraj_google_style"} +{"code": "def char_matches(s1, s2, n=3):\n\n return __matches(s1, s2, char_ngrams, n=n)", "docstring": "Character-level n-grams that match between two strings\n\nArgs:\n s1: a string\n s2: another string\n n: an int for the n in n-gram\n\nReturns:\n set: the n-grams found in both strings", "source": "juraj_google_style"} +{"code": "def load(self, code, setup='', teardown=''):\n\n self._setup = textwrap.dedent(setup).splitlines()\n self._code = code\n self._teardown = textwrap.dedent(teardown).splitlines()", "docstring": "Prepares a set of setup, test, and teardown code to be\n run in the console.\n\n PARAMETERS:\n code -- list; processed lines of code. Elements in the list are\n either strings (input) or CodeAnswer objects (output)\n setup -- str; raw setup code\n teardown -- str; raw teardown code", "source": "juraj_google_style"} +{"code": "def create_config(config_path=\"scriptworker.yaml\"):\n\n if not os.path.exists(config_path):\n print(\"{} doesn't exist! Exiting...\".format(config_path), file=sys.stderr)\n sys.exit(1)\n with open(config_path, \"r\", encoding=\"utf-8\") as fh:\n secrets = safe_load(fh)\n config = dict(deepcopy(DEFAULT_CONFIG))\n if not secrets.get(\"credentials\"):\n secrets['credentials'] = read_worker_creds()\n config.update(secrets)\n apply_product_config(config)\n messages = check_config(config, config_path)\n if messages:\n print('\\n'.join(messages), file=sys.stderr)\n print(\"Exiting...\", file=sys.stderr)\n sys.exit(1)\n credentials = get_frozen_copy(secrets['credentials'])\n del(config['credentials'])\n config = get_frozen_copy(config)\n return config, credentials", "docstring": "Create a config from DEFAULT_CONFIG, arguments, and config file.\n\n Then validate it and freeze it.\n\nArgs:\n config_path (str, optional): the path to the config file. Defaults to\n \"scriptworker.yaml\"\n\nReturns:\n tuple: (config frozendict, credentials dict)\n\nRaises:\n SystemExit: on failure", "source": "juraj_google_style"} +{"code": "def _tuple_of_big_endian_int(bit_groups: Tuple[np.ndarray, ...]\n ) -> Tuple[int, ...]:\n\n return tuple(_big_endian_int(bits) for bits in bit_groups)", "docstring": "Returns the big-endian integers specified by groups of bits.\n\nArgs:\n bit_groups: Groups of descending bits, each specifying a big endian\n integer with the 1s bit at the end.\n\nReturns:\n A tuple containing the integer for each group.", "source": "juraj_google_style"} +{"code": "def drag_and_drop(self, source_selector, destination_selector, **kwargs):\n\n self.info_log(\n \"Drag and drop: source (%s); destination (%s)\" %\n (source_selector, destination_selector)\n )\n\n use_javascript_dnd = kwargs.get(\n \"use_javascript_dnd\",\n \"proxy_driver:use_javascript_dnd\"\n )\n\n source_el = self.find(source_selector)\n destination_el = self.find(destination_selector)\n\n if use_javascript_dnd:\n try:\n dnd_script = [\n \"function simulate(f,c,d,e){var b,a=null;for(b in eventMatchers)if(eventMatchers[b].test(c)){a=b;break}if(!a)return!1;document.createEvent?(b=document.createEvent(a),a=='HTMLEvents'?b.initEvent(c,!0,!0):b.initMouseEvent(c,!0,!0,document.defaultView,0,d,e,d,e,!1,!1,!1,!1,0,null),f.dispatchEvent(b)):(a=document.createEventObject(),a.detail=0,a.screenX=d,a.screenY=e,a.clientX=d,a.clientY=e,a.ctrlKey=!1,a.altKey=!1,a.shiftKey=!1,a.metaKey=!1,a.button=1,f.fireEvent('on'+c,a));return!0} var eventMatchers={HTMLEvents:/^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,MouseEvents:/^(?:click|dblclick|mouse(?:down|up|over|move|out))$/};\", # noqa\n \"var source = arguments[0],destination = arguments[1];\",\n \"simulate(source, 'mousedown', 0, 0);\",\n \"simulate(source, 'mousemove', destination.offsetLeft, destination.offsetTop);\", # noqa\n \"simulate(source, 'mouseup', destination.offsetLeft, destination.offsetTop);\" # noqa\n ]\n self._driver.execute_script(\n '\\n'.join(dnd_script),\n source_el._element,\n destination_el._element\n )\n\n except Exception as e:\n self.error_log(u'drag_and_drop exception: %s' % str(e))\n raise\n else:\n try:\n ActionChains(self._driver).drag_and_drop(\n source_el,\n destination_el\n ).perform()\n except Exception as e:\n self.error_log(u'drag_and_drop exception: %s' % str(e))\n raise", "docstring": "Drag and drop\n\nArgs:\n source_selector: (str)\n destination_selector: (str)\n\n Kwargs:\n use_javascript_dnd: bool; default:\n config proxy_driver:use_javascript_dnd", "source": "juraj_google_style"} +{"code": "def _get_genes(self, variant):\n\n transcripts = variant['transcripts']\n ensembl_ids = [transcript['ensembl_id'] for transcript in\n transcripts if transcript['ensembl_id']]\n hgnc_symbols = [transcript['hgnc_symbol'] for transcript in\n transcripts if transcript['hgnc_symbol']]\n genes = get_gene_info(ensembl_ids, hgnc_symbols)\n return genes", "docstring": "Add the genes for a variant\n\n Get the hgnc symbols from all transcripts and add them\n to the variant.\n\nArgs:\n variant (dict): A variant dictionary\n\nReturns:\n genes (list): A list of Genes", "source": "juraj_google_style"} +{"code": "def check_mailfy(self, query, kwargs={}):\n\n data = self.launchQueryForMode(query=query, mode=\"mailfy\")\n if self._somethingFound(data, mode=\"mailfy\"):\n return data\n return None", "docstring": "Verifying a mailfy query in this platform.\n\n This might be redefined in any class inheriting from Platform. The only\n condition is that any of this should return a dictionary as defined.\n\nArgs:\n -----\n query: The element to be searched.\n kwargs: Dictionary with extra parameters. Just in case.\n\nReturns:\n -------\n Returns the collected data if exists or None if not.", "source": "juraj_google_style"} +{"code": "def preds(self, nodeids=None):\n\n if nodeids is None: nodeids = self._nodeids\n _eps = self._eps\n return [_eps[nid][1] for nid in nodeids]", "docstring": "Return the Pred objects for *nodeids*, or all Preds.\n\nArgs:\n nodeids: an iterable of nodeids of predications to return\n Preds from; if `None`, return all Preds", "source": "juraj_google_style"} +{"code": "def main(catalog):\n\n res = validate_catalog(catalog, only_errors=True, fmt=\"list\",\n export_path=None, validator=None)\n print(\"\")\n print(\"=== Errores a nivel de CATALOGO ===\")\n pprint(res[\"catalog\"])\n\n print(\"\")\n print(\"=== Errores a nivel de DATASET ===\")\n pprint(res[\"dataset\"])", "docstring": "Permite validar un catálogo por línea de comandos.\n\nArgs:\n catalog (str): Path local o URL a un catálogo.", "source": "juraj_google_style"} +{"code": "def which(self, path, mode=\"r\"):\n # type: (Text, Text) -> Tuple[Optional[Text], Optional[FS]]\n\n if check_writable(mode):\n return self._write_fs_name, self.write_fs\n for name, fs in self.iterate_fs():\n if fs.exists(path):\n return name, fs\n return None, None", "docstring": "Get a tuple of (name, fs) that the given path would map to.\n\nArgs:\n path (str): A path on the filesystem.\n mode (str): An `io.open` mode.", "source": "juraj_google_style"} +{"code": "def create(self, msgtype, *args, **kwargs):\n\n if msgtype not in self._messages:\n raise ProtocolError(\"Unknown message type %r for protocol version %s\" % (msgtype, self._version))\n return self._messages[msgtype].create(*args, **kwargs)", "docstring": "Create a new Message instance for the given type.\n\nArgs:\n msgtype (str) :", "source": "juraj_google_style"} +{"code": "def attention_mask_autoregressive(query_pos, dtype=tf.float32):\n\n memory_pos = rename_length_to_memory_length(query_pos)\n return mtf.cast(mtf.less(query_pos, memory_pos), dtype) * -1e9", "docstring": "Bias for self-attention where attention to the right is disallowed.\n\nArgs:\n query_pos: a mtf.Tensor with shape [..., length_dim]\n dtype: a tf.dtype\n\nReturns:\n a mtf.Tensor with shape [..., length_dim, memory_length_dim]", "source": "juraj_google_style"} +{"code": "def end_log_task(task, logger=logging, level='info'):\n\n getattr(logger, level)(END_TASK_TRIGGER_MSG % task)", "docstring": "Ends a log task\n\nArgs:\n task (str): name of the log task to end\n logger (logging.Logger): logger to use\n level (str): log level to use\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def _sync_call(self, func):\n\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n if self._start_msg:\n self._start_print()\n result = func(*args, **kwargs)\n if self._end_msg:\n print(self._end_msg)\n return result\n\n setattr(wrapper, ANNOTATED, True)\n return wrapper", "docstring": "__call__ function for regular synchronous functions.\n\nArgs:\n func: The annotated function.\n args: Arguments for func.\n kwargs: Keyword arguments for func.", "source": "juraj_google_style"} +{"code": "def move_gain(mapping, node_id, old_id, new_id, weight_dict, match_num):\n\n # new node mapping after moving\n new_mapping = (node_id, new_id)\n # node mapping before moving\n old_mapping = (node_id, old_id)\n # new nodes mapping list (all node pairs)\n new_mapping_list = mapping[:]\n new_mapping_list[node_id] = new_id\n # if this mapping is already been investigated, use saved one to avoid duplicate computing\n if tuple(new_mapping_list) in match_triple_dict:\n return match_triple_dict[tuple(new_mapping_list)] - match_num\n gain = 0\n # add the triple match incurred by new_mapping to gain\n if new_mapping in weight_dict:\n for key in weight_dict[new_mapping]:\n if key == -1:\n # instance/attribute triple match\n gain += weight_dict[new_mapping][-1]\n elif new_mapping_list[key[0]] == key[1]:\n # relation gain incurred by new_mapping and another node pair in new_mapping_list\n gain += weight_dict[new_mapping][key]\n # deduct the triple match incurred by old_mapping from gain\n if old_mapping in weight_dict:\n for k in weight_dict[old_mapping]:\n if k == -1:\n gain -= weight_dict[old_mapping][-1]\n elif mapping[k[0]] == k[1]:\n gain -= weight_dict[old_mapping][k]\n # update match number dictionary\n match_triple_dict[tuple(new_mapping_list)] = match_num + gain\n return gain", "docstring": "Compute the triple match number gain from the move operation\n\nArgs:\n mapping: current node mapping\n node_id: remapped node in AMR 1\n old_id: original node id in AMR 2 to which node_id is mapped\n new_id: new node in to which node_id is mapped\n weight_dict: weight dictionary\n match_num: the original triple matching number\n\nReturns:\n the triple match gain number (might be negative)", "source": "juraj_google_style"} +{"code": "def __init__(self, device, logger):\n\n self._serial = pyserial.Serial(device, 115200)\n\n logger.info(\"Clearing buffers\")\n self._serial.write(b\"@b\")\n ret = self._serial.read(1)\n if ret != b\"k\":\n raise RuntimeError(\"Error while clearing buffers\")\n\n # ensure pending operations are terminated (eg: @r, @l)\n self._serial.write(b\"@c\")\n ret = self._serial.read()\n if ret != b\"k\":\n raise RuntimeError(\"Error while cancelling pending operations\")\n\n logger.info(\"Enabling ASCII mode\")\n self._serial.write(b\"@MA\")\n ret = self._serial.read(1)\n if ret != b\"k\":\n raise RuntimeError(\"Error while enabling ASCII mode\")\n\n logger.info(\"Filter Ack messages\")\n self._serial.write(b\"@F2\")\n ret = self._serial.read(1)\n if ret != b\"k\":\n raise RuntimeError(\"Error while setting filter\")", "docstring": "Initialize the class\n\nArgs:\n device: string containing the serial device allocated to SCSGate\n logger: instance of logging", "source": "juraj_google_style"} +{"code": "def switch_to_frame(self, frame):\n\n\n if isinstance(frame, Element):\n self.driver.switch_to_frame(frame)\n self._scopes.append(\"frame\")\n elif frame == \"parent\":\n if self._scopes[-1] != \"frame\":\n raise ScopeError(\"`switch_to_frame(\\\"parent\\\")` cannot be called \"\n \"from inside a descendant frame's `scope` context.\")\n self._scopes.pop()\n self.driver.switch_to_frame(\"parent\")\n elif frame == \"top\":\n if \"frame\" in self._scopes:\n idx = self._scopes.index(\"frame\")\n if any([scope not in [\"frame\", None] for scope in self._scopes[idx:]]):\n raise ScopeError(\"`switch_to_frame(\\\"top\\\")` cannot be called \"\n \"from inside a descendant frame's `scope` context.\")\n self._scopes = self._scopes[:idx]\n self.driver.switch_to_frame(\"top\")\n else:\n raise ValueError(\n \"You must provide a frame element, \\\"parent\\\", or \\\"top\\\" \"\n \"when calling switch_to_frame\")", "docstring": "Switch to the given frame.\n\n If you use this method you are responsible for making sure you switch back to the parent\n frame when done in the frame changed to. :meth:`frame` is preferred over this method and\n should be used when possible. May not be supported by all drivers.\n\nArgs:\n frame (Element | str): The iframe/frame element to switch to.", "source": "juraj_google_style"} +{"code": "def phase_histogram(dts, times=None, nbins=30, colormap=mpl.cm.Blues):\n\n if times is None:\n times = np.linspace(dts.tspan[0], dts.tspan[-1], num=4)\n elif isinstance(times, numbers.Number):\n times = np.array([times], dtype=np.float64)\n indices = distob.gather(dts.tspan.searchsorted(times))\n if indices[-1] == len(dts.tspan):\n indices[-1] -= 1\n nplots = len(indices)\n fig = plt.figure()\n n = np.zeros((nbins, nplots))\n for i in range(nplots):\n index = indices[i]\n time = dts.tspan[index]\n phases = distob.gather(dts.mod2pi()[index, 0, :])\n ax = fig.add_subplot(1, nplots, i + 1, projection='polar')\n n[:,i], bins, patches = ax.hist(phases, nbins, (-np.pi, np.pi), \n density=True, histtype='bar')\n ax.set_title('time = %d s' % time)\n ax.set_xticklabels(['0', r'$\\frac{\\pi}{4}$', r'$\\frac{\\pi}{2}$', \n r'$\\frac{3\\pi}{4}$', r'$\\pi$', r'$\\frac{-3\\pi}{4}$',\n r'$\\frac{-\\pi}{2}$', r'$\\frac{-\\pi}{4}$'])\n nmin, nmax = n.min(), n.max()\n #TODO should make a custom colormap instead of reducing color dynamic range:\n norm = mpl.colors.Normalize(1.2*nmin - 0.2*nmax, \n 0.6*nmin + 0.4*nmax, clip=True)\n for i in range(nplots):\n ax = fig.get_axes()[i]\n ax.set_ylim(0, nmax)\n for this_n, thispatch in zip(n[:,i], ax.patches):\n color = colormap(norm(this_n))\n thispatch.set_facecolor(color)\n thispatch.set_edgecolor(color)\n fig.show()", "docstring": "Plot a polar histogram of a phase variable's probability distribution\n\nArgs:\n dts: DistTimeseries with axis 2 ranging over separate instances of an\n oscillator (time series values are assumed to represent an angle)\n times (float or sequence of floats): The target times at which\n to plot the distribution\n nbins (int): number of histogram bins\n colormap", "source": "juraj_google_style"} +{"code": "def __init__(self,\n name,\n numCorticalColumns=1,\n inputSize=1024,\n numInputBits=20,\n externalInputSize=1024,\n numExternalInputBits=20,\n L2Overrides=None,\n networkType = \"L4L2TMColumn\",\n L4Overrides=None,\n seed=42,\n logCalls=False,\n objectNamesAreIndices=False,\n TMOverrides=None,\n ):\n\n\n # Handle logging - this has to be done first\n self.logCalls = logCalls\n\n registerAllResearchRegions()\n self.name = name\n\n self.numLearningPoints = 1\n self.numColumns = numCorticalColumns\n self.inputSize = inputSize\n self.externalInputSize = externalInputSize\n self.numInputBits = numInputBits\n self.objectNamesAreIndices = objectNamesAreIndices\n\n # seed\n self.seed = seed\n random.seed(seed)\n\n # update parameters with overrides\n self.config = {\n \"networkType\": networkType,\n \"numCorticalColumns\": numCorticalColumns,\n \"externalInputSize\": externalInputSize,\n \"sensorInputSize\": inputSize,\n \"enableFeedback\": False,\n \"L4Params\": self.getDefaultL4Params(inputSize, numExternalInputBits),\n \"L2Params\": self.getDefaultL2Params(inputSize, numInputBits),\n \"TMParams\": self.getDefaultTMParams(self.inputSize, self.numInputBits),\n }\n\n\n if L2Overrides is not None:\n self.config[\"L2Params\"].update(L2Overrides)\n\n if L4Overrides is not None:\n self.config[\"L4Params\"].update(L4Overrides)\n\n if TMOverrides is not None:\n self.config[\"TMParams\"].update(TMOverrides)\n\n # Recreate network including TM parameters\n self.network = createNetwork(self.config)\n self.sensorInputs = []\n self.externalInputs = []\n self.L4Regions = []\n self.L2Regions = []\n self.TMRegions = []\n\n for i in xrange(self.numColumns):\n self.sensorInputs.append(\n self.network.regions[\"sensorInput_\" + str(i)].getSelf()\n )\n self.externalInputs.append(\n self.network.regions[\"externalInput_\" + str(i)].getSelf()\n )\n self.L4Regions.append(\n self.network.regions[\"L4Column_\" + str(i)]\n )\n self.L2Regions.append(\n self.network.regions[\"L2Column_\" + str(i)]\n )\n self.TMRegions.append(\n self.network.regions[\"TMColumn_\" + str(i)]\n )\n\n self.L4Columns = [region.getSelf() for region in self.L4Regions]\n self.L2Columns = [region.getSelf() for region in self.L2Regions]\n self.TMColumns = [region.getSelf() for region in self.TMRegions]\n\n # will be populated during training\n self.objectL2Representations = {}\n self.objectL2RepresentationsMatrices = [\n SparseMatrix(0, self.config[\"L2Params\"][\"cellCount\"])\n for _ in xrange(self.numColumns)]\n self.objectNameToIndex = {}\n self.statistics = []\n\n # Create classifier to hold supposedly unique TM states\n self.classifier = KNNClassifier(distanceMethod=\"rawOverlap\")\n self.numTMCells = (self.TMColumns[0].cellsPerColumn *\n self.TMColumns[0].columnCount)", "docstring": "Creates the network.\n\n Parameters:\n ----------------------------\n @param TMOverrides (dict)\n Parameters to override in the TM region", "source": "juraj_google_style"} +{"code": "def extract_tendency_grid(self, model_grid):\n\n var_name = model_grid.variable + \"-tendency\"\n self.attributes[var_name] = []\n timesteps = np.arange(self.start_time, self.end_time + 1)\n for ti, t in enumerate(timesteps):\n t_index = t - model_grid.start_hour\n self.attributes[var_name].append(\n model_grid.data[t_index, self.i[ti], self.j[ti]] - model_grid.data[t_index - 1, self.i[ti], self.j[ti]]\n )", "docstring": "Extracts the difference in model outputs\n\nArgs:\n model_grid: ModelOutput or ModelGrid object.", "source": "juraj_google_style"} +{"code": "def _CanSkipDataStream(self, file_entry, data_stream):\n\n if file_entry.IsFile():\n return False\n\n if data_stream.IsDefault():\n return True\n\n return False", "docstring": "Determines if analysis and extraction of a data stream can be skipped.\n\n This is used to prevent Plaso trying to run analyzers or extract content\n from a pipe or socket it encounters while processing a mounted filesystem.\n\nArgs:\n file_entry (dfvfs.FileEntry): file entry to consider for skipping.\n data_stream (dfvfs.DataStream): data stream to consider for skipping.\n\nReturns:\n bool: True if the data stream can be skipped.", "source": "juraj_google_style"} +{"code": "def inspect_file(self, commit, path):\n\n req = proto.InspectFileRequest(file=proto.File(commit=commit_from(commit), path=path))\n res = self.stub.InspectFile(req, metadata=self.metadata)\n return res", "docstring": "Returns info about a specific file.\n\n Params:\n * commit: A tuple, string, or Commit object representing the commit.\n * path: Path to file.", "source": "juraj_google_style"} +{"code": "def reverse_axis(self, axis_to_reverse):\n\n if axis_to_reverse.lower() == 'x':\n self.general.reverse_x_axis = True\n if axis_to_reverse.lower() == 'y':\n self.general.reverse_y_axis = True\n if axis_to_reverse.lower() != 'x' or axis_to_reverse.lower() != 'y':\n raise ValueError('Axis for reversing needs to be either x or y.')\n return", "docstring": "Reverse an axis in all figure plots.\n\n This will reverse the tick marks on an axis for each plot in the figure.\n It can be overridden in SinglePlot class.\n\nArgs:\n axis_to_reverse (str): Axis to reverse. Supports `x` and `y`.\n\nRaises:\n ValueError: The string representing the axis to reverse is not `x` or `y`.", "source": "juraj_google_style"} +{"code": "def hstack(tup):\n\n # Follow numpy.hstack behavior for 1D arrays:\n if all(ar.ndim is 1 for ar in tup):\n return concatenate(tup, axis=0)\n else:\n return concatenate(tup, axis=1)", "docstring": "Stack arrays in sequence horizontally (column wise),\n handling ``RemoteArray`` and ``DistArray`` without moving data.\n\nArgs:\n tup (sequence of array_like)\n\nReturns:\n res: `ndarray`, if inputs were all local\n `RemoteArray`, if inputs were all on the same remote engine\n `DistArray`, if inputs were already scattered on different engines", "source": "juraj_google_style"} +{"code": "def parse_options(cls, options):\n\n d = {}\n for filename_check, dictionary in cls.filename_checks.items():\n # retrieve the marks from the passed options\n filename_data = getattr(options, filename_check)\n if len(filename_data) != 0:\n parsed_params = {}\n for single_line in filename_data:\n a = [s.strip() for s in single_line.split('=')]\n # whitelist the acceptable params\n if a[0] in ['filter_regex', 'filename_regex']:\n parsed_params[a[0]] = a[1]\n d[filename_check] = parsed_params\n cls.filename_checks.update(d)\n # delete any empty rules\n cls.filename_checks = {x: y for x, y in cls.filename_checks.items() if len(y) > 0}", "docstring": "Required by flake8\n parse the options, called after add_options\n\nArgs:\n options (dict): options to be parsed", "source": "juraj_google_style"} +{"code": "def _set_bearer_user_vars(allowed_client_ids, scopes):\n\n all_scopes, sufficient_scopes = _process_scopes(scopes)\n try:\n authorized_scopes = oauth.get_authorized_scopes(sorted(all_scopes))\n except oauth.Error:\n _logger.debug('Unable to get authorized scopes.', exc_info=True)\n return\n if not _are_scopes_sufficient(authorized_scopes, sufficient_scopes):\n _logger.warning('Authorized scopes did not satisfy scope requirements.')\n return\n client_id = oauth.get_client_id(authorized_scopes)\n\n # The client ID must be in allowed_client_ids. If allowed_client_ids is\n # empty, don't allow any client ID. If allowed_client_ids is set to\n # SKIP_CLIENT_ID_CHECK, all client IDs will be allowed.\n if (list(allowed_client_ids) != SKIP_CLIENT_ID_CHECK and\n client_id not in allowed_client_ids):\n _logger.warning('Client ID is not allowed: %s', client_id)\n return\n\n os.environ[_ENV_USE_OAUTH_SCOPE] = ' '.join(authorized_scopes)\n _logger.debug('get_current_user() will return user from matched oauth_user.')", "docstring": "Validate the oauth bearer token and set endpoints auth user variables.\n\n If the bearer token is valid, this sets ENDPOINTS_USE_OAUTH_SCOPE. This\n provides enough information that our endpoints.get_current_user() function\n can get the user.\n\nArgs:\n allowed_client_ids: List of client IDs that are acceptable.\n scopes: List of acceptable scopes.", "source": "juraj_google_style"} +{"code": "def generate_rpcs(self, address):\n\n\n rpc_list = []\n\n for offset in range(2, len(self.data), 16):\n rpc = (address, rpcs.SET_CONFIG_VARIABLE, self.var_id, offset - 2, self.data[offset:offset + 16])\n rpc_list.append(rpc)\n\n return rpc_list", "docstring": "Generate the RPCs needed to stream this config variable to a tile.\n\nArgs:\n address (int): The address of the tile that we should stream to.\n\nReturns:\n list of tuples: A list of argument tuples for each RPC.\n\n These tuples can be passed to EmulatedDevice.rpc to actually make\n the RPCs.", "source": "juraj_google_style"} +{"code": "def RetryUpload(self, job, job_id, error):\n\n if self.IsErrorRetryable(error):\n retry_count = 0\n sleep_interval = config.CONFIG[\"BigQuery.retry_interval\"]\n while retry_count < config.CONFIG[\"BigQuery.retry_max_attempts\"]:\n\n time.sleep(sleep_interval.seconds)\n logging.info(\"Retrying job_id: %s\", job_id)\n retry_count += 1\n\n try:\n response = job.execute()\n return response\n except errors.HttpError as e:\n if self.IsErrorRetryable(e):\n sleep_interval *= config.CONFIG[\"BigQuery.retry_multiplier\"]\n logging.exception(\"Error with job: %s, will retry in %s\", job_id,\n sleep_interval)\n else:\n raise BigQueryJobUploadError(\n \"Can't retry error code %s. Giving up\"\n \" on job: %s.\" % (e.resp.status, job_id))\n else:\n raise BigQueryJobUploadError(\"Can't retry error code %s. Giving up on \"\n \"job: %s.\" % (error.resp.status, job_id))\n\n raise BigQueryJobUploadError(\n \"Giving up on job:%s after %s retries.\" % (job_id, retry_count))", "docstring": "Retry the BigQuery upload job.\n\n Using the same job id protects us from duplicating data on the server. If we\n fail all of our retries we raise.\n\nArgs:\n job: BigQuery job object\n job_id: ID string for this upload job\n error: errors.HttpError object from the first error\n\nReturns:\n API response object on success, None on failure\n\nRaises:\n BigQueryJobUploadError: if we can't get the bigquery job started after\n retry_max_attempts", "source": "juraj_google_style"} +{"code": "def __init__(self, host, folder, event_loop=None, timeout=15):\n\n self.host = host\n self.folder = folder\n self.logger = logger.getChild('HttpProtocol {}'.format(id(self)))\n self.logger.debug('Instantiated HttpProtocol')\n self._loop = event_loop or asyncio.get_event_loop()\n self._timeout = timeout\n self._timeout_handle = None", "docstring": "Initialise a new instance.\n\nArgs:\n host: the host to serve\n folder: the folder to serve files from", "source": "juraj_google_style"} +{"code": "def parse_query(query_str):\n\n def _generate_match_all_fields_query():\n # Strip colon character (special character for ES)\n stripped_query_str = ' '.join(query_str.replace(':', ' ').split())\n return {'multi_match': {'query': stripped_query_str, 'fields': ['_all'], 'zero_terms_query': 'all'}}\n\n if not isinstance(query_str, six.text_type):\n query_str = six.text_type(query_str.decode('utf-8'))\n\n logger.info('Parsing: \"' + query_str + '\\\".')\n\n parser = StatefulParser()\n rst_visitor = RestructuringVisitor()\n es_visitor = ElasticSearchVisitor()\n\n try:\n unrecognized_text, parse_tree = parser.parse(query_str, Query)\n\n if unrecognized_text: # Usually, should never happen.\n msg = 'Parser returned unrecognized text: \"' + unrecognized_text + \\\n '\" for query: \"' + query_str + '\".'\n\n if query_str == unrecognized_text and parse_tree is None:\n # Didn't recognize anything.\n logger.warn(msg)\n return _generate_match_all_fields_query()\n else:\n msg += 'Continuing with recognized parse tree.'\n logger.warn(msg)\n\n except SyntaxError as e:\n logger.warn('Parser syntax error (' + six.text_type(e) + ') with query: \"' + query_str +\n '\". Continuing with a match_all with the given query.')\n return _generate_match_all_fields_query()\n\n # Try-Catch-all exceptions for visitors, so that search functionality never fails for the user.\n try:\n restructured_parse_tree = parse_tree.accept(rst_visitor)\n logger.debug('Parse tree: \\n' + emit_tree_format(restructured_parse_tree))\n\n except Exception as e:\n logger.exception(\n RestructuringVisitor.__name__ + \" crashed\" + (\": \" + six.text_type(e) + \".\") if six.text_type(e) else '.'\n )\n return _generate_match_all_fields_query()\n\n try:\n es_query = restructured_parse_tree.accept(es_visitor)\n except Exception as e:\n logger.exception(\n ElasticSearchVisitor.__name__ + \" crashed\" + (\": \" + six.text_type(e) + \".\") if six.text_type(e) else '.'\n )\n return _generate_match_all_fields_query()\n\n if not es_query:\n # Case where an empty query was generated (i.e. date query with malformed date, e.g. \"d < 200\").\n return _generate_match_all_fields_query()\n\n return es_query", "docstring": "Drives the whole logic, by parsing, restructuring and finally, generating an ElasticSearch query.\n\nArgs:\n query_str (six.text_types): the given query to be translated to an ElasticSearch query\n\nReturns:\n six.text_types: Return an ElasticSearch query.\n\nNote:\n In case there's an error, an ElasticSearch `multi_match` query is generated with its `query` value, being the\n query_str argument.", "source": "juraj_google_style"} +{"code": "def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):\n\n if boundaries:\n sval = fsed.ahocorasick.boundary_transform(sval)\n if slow:\n sval = trie.replace(sval)\n else:\n sval = trie.greedy_replace(sval)\n if boundaries:\n sval = ''.join(fsed.ahocorasick.boundary_untransform(sval))\n return sval", "docstring": "Rewrites a string using the given trie object.\n\nArgs:\n - `sval`:\n - `trie`:\n - `boundaries`:\n - `slow`:", "source": "juraj_google_style"} +{"code": "def _countdown(self, waitTime=0, printString=\"Waiting %*d seconds...\", verbose=True):\n\n if waitTime <= 0:\n waitTime = self.__retryDelay\n for remaining in range(waitTime, 0, -1):\n _vPrint(verbose, \"\\r\" + printString % (len(str(waitTime)), remaining), end=\"\", flush=True)\n time.sleep(1)\n if verbose:\n _vPrint(verbose, \"\\r\" + printString % (len(str(waitTime)), 0))", "docstring": "Makes a pretty countdown.\n\nArgs:\n gitquery (str): The query or endpoint itself.\n\nExample:\n query: 'query { viewer { login } }'\n endpoint: '/user'\n printString (Optional[str]): A counter message to display.\n Defaults to 'Waiting %*d seconds...'\n verbose (Optional[bool]): If False, all extra printouts will be\n suppressed. Defaults to True.", "source": "juraj_google_style"} +{"code": "def _calc(cls, **kwargs):\n\n zenith = 90.833333 # offical value\n\n jd = kwargs.get(\"jd\", None)\n lat = kwargs.get(\"lat\", None)\n lon = kwargs.get(\"lon\", None)\n stage = kwargs.get(\"stage\", None)\n if jd is None or stage is None or lat is None or lon is None:\n raise ValueError(\"Must supply an 'jd', 'lat, 'lon', and 'stage' parameter\")\n\n if stage != SunCycles.RISING and stage != SunCycles.SETTING:\n raise ValueError(\"'stage' parameter must be %s or %s\" % (SunCycles.RISING, SunCycles.SETTING))\n\n longhr = lon / 15.\n if stage == SunCycles.RISING:\n apx = jd + ( (6 - longhr) / 24 )\n elif stage == SunCycles.SETTING:\n apx = jd + ( (18 - longhr) / 24 )\n\n sun_mean_anom = ( 0.9856 * apx ) - 3.289 # sun's mean anomaly\n #sun's longitude\n sun_lon = sun_mean_anom + (1.916 * np.sin( np.radians(sun_mean_anom) )) \\\n + (0.02 * np.sin( np.radians(2 * sun_mean_anom) )) + 282.634\n\n if sun_lon > 360:\n sun_lon = sun_lon - 360\n elif sun_lon < 0:\n sun_lon = sun_lon + 360\n\n right_ascension = np.degrees(np.arctan( 0.91764 * np.tan( np.radians(sun_lon) ) )) # sun's right ascension\n\n if right_ascension > 360:\n right_ascension = right_ascension - 360\n elif right_ascension < 0:\n right_ascension = right_ascension + 360\n\n # put sun's right ascension value in the same quadrant as the sun's\n # true longitude\n lQuad = 90. * np.floor(sun_lon / 90.)\n raQuad = 90. * np.floor(right_ascension / 90.)\n right_ascension = right_ascension + ( lQuad - raQuad)\n right_ascension = right_ascension / 15. # Convert to hours\n\n # Sun's declination\n sinDecl = 0.39782 * np.sin( np.radians(sun_lon) )\n cosDecl = np.cos( np.arcsin( sinDecl ) )\n\n # Sun's local hour angle\n cosHr = (np.cos( np.radians(zenith) ) - ( sinDecl * np.sin(np.radians(lat)) )) \\\n / ( cosDecl * np.cos( np.radians(lat) ) )\n\n if cosHr > 1: # Sun doesnt rise on this loc on this date\n return -1, -1\n elif cosHr < -1: # Sun doesnt set on this location on this date\n return -1, -1\n elif stage == SunCycles.RISING: # Sunrise\n hr = 360 - np.degrees(np.arccos(cosHr))\n elif stage == SunCycles.SETTING: # Sunset\n hr = np.degrees(np.arccos(cosHr))\n\n hr = hr / 15. # Convert angle to hours\n\n localTime = hr + right_ascension - ( 0.06571 * apx ) - 6.622# local meantime of rise/set\n\n UTtime = localTime - longhr # adjust to UTC\n\n if UTtime < 0:\n UTtime = UTtime + 24\n elif UTtime > 24:\n UTtime = UTtime - 24\n\n hour = np.floor(UTtime)\n\n minute = (UTtime - hour) * 60\n if minute == 60:\n hour = hour + 1\n minute = 0\n\n return hour, minute", "docstring": "Calculate sunrise or sunset based on:\n Parameters:\n jd: Julian Day\n lat: latitude\n lon: longitude\n stage: sunrise or sunset", "source": "juraj_google_style"} +{"code": "def prepare_adiabatic_limit(slh, k=None):\n\n if k is None:\n k = symbols('k', positive=True)\n Ld = slh.L.dag()\n LdL = (Ld * slh.L)[0, 0]\n K = (-LdL / 2 + I * slh.H).expand().simplify_scalar()\n N = slh.S.dag()\n B, A, Y = K.series_expand(k, 0, 2)\n G, F = Ld.series_expand(k, 0, 1)\n\n return Y, A, B, F, G, N", "docstring": "Prepare the adiabatic elimination on an SLH object\n\nArgs:\n slh: The SLH object to take the limit for\n k: The scaling parameter $k \\rightarrow \\infty$. The default is a\n positive symbol 'k'\n\nReturns:\n tuple: The objects ``Y, A, B, F, G, N``\n necessary to compute the limiting system.", "source": "juraj_google_style"} +{"code": "def __getattr__(self, item):\n\n if item in self.METHOD_NO_PROXY:\n return super(AuthProxy, self).__getattr__(item)\n attr = getattr(self.proxy_class, item)\n if callable(attr):\n return self.auth_proxy(attr)", "docstring": "Override attribute getter to act as a proxy for``proxy_class``.\n\n If ``item`` is contained in ``METHOD_NO_PROXY``, it will not be\n proxied to the ``proxy_class`` and will instead return the attribute\n on this object.\n\nArgs:\n item (str): Name of attribute to get.", "source": "juraj_google_style"} +{"code": "def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None:\n # noqa\n for old_key, new_key in renames.items():\n if new_key == old_key:\n continue\n if old_key in d:\n if new_key in d:\n raise ValueError(\n \"rename_keys_in_dict: renaming {} -> {} but new key \"\n \"already exists\".format(repr(old_key), repr(new_key)))\n d[new_key] = d.pop(old_key)", "docstring": "Renames, IN PLACE, the keys in ``d`` according to the mapping in\n ``renames``.\n\nArgs:\n d: a dictionary to modify\n renames: a dictionary of the format ``{old_key_name: new_key_name}``\n\n See\n https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary.", "source": "juraj_google_style"} +{"code": "def matches(self, desc):\n\n desc_value_type = desc.valueType or ValueType.STRING # default not parsed\n return (self.label_name == desc.key and\n self.value_type == desc_value_type)", "docstring": "Determines if a given label descriptor matches this enum instance\n\nArgs:\n desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):\n the instance to test\n\nReturns:\n `True` if desc is supported, otherwise `False`", "source": "juraj_google_style"} +{"code": "def __group_data__(self, data, **kwargs):\n\n # strip all of the rdf_type triples and merge\n\n class_types = self._merge_classtypes(self.__get_classtypes__(data))\n self.subj_list = list([item[self.smap] for item in class_types])\n # get non defined classes\n self.non_defined = self._get_non_defined(data, class_types)\n return class_types", "docstring": "processes the data in to groups prior to loading into the\n dataset\n\nArgs:\n data: a list of triples", "source": "juraj_google_style"} +{"code": "def __fetch_route53_zone_records(self, zone_id):\n\n route53 = self.session.client('route53')\n\n done = False\n nextName = nextType = None\n records = {}\n\n try:\n while not done:\n if nextName and nextType:\n response = route53.list_resource_record_sets(\n HostedZoneId=zone_id,\n StartRecordName=nextName,\n StartRecordType=nextType\n )\n else:\n response = route53.list_resource_record_sets(HostedZoneId=zone_id)\n\n if response['IsTruncated']:\n nextName = response['NextRecordName']\n nextType = response['NextRecordType']\n else:\n done = True\n\n if 'ResourceRecordSets' in response:\n for record in response['ResourceRecordSets']:\n # Cannot make this a list, due to a race-condition in the AWS api that might return the same\n # record more than once, so we use a dict instead to ensure that if we get duplicate records\n # we simply just overwrite the one already there with the same info.\n record_id = self._get_resource_hash(zone_id, record)\n if 'AliasTarget' in record:\n value = record['AliasTarget']['DNSName']\n records[record_id] = {\n 'id': record_id,\n 'name': record['Name'].rstrip('.'),\n 'type': 'ALIAS',\n 'ttl': 0,\n 'value': [value]\n }\n else:\n value = [y['Value'] for y in record['ResourceRecords']]\n records[record_id] = {\n 'id': record_id,\n 'name': record['Name'].rstrip('.'),\n 'type': record['Type'],\n 'ttl': record['TTL'],\n 'value': value\n }\n\n return list(records.values())\n finally:\n del route53", "docstring": "Return all resource records for a specific Route53 zone\n\nArgs:\n zone_id (`str`): Name / ID of the hosted zone\n\nReturns:\n `dict`", "source": "juraj_google_style"} +{"code": "def add_node(self, node_descriptor):\n\n\n if self._max_nodes is not None and len(self.nodes) >= self._max_nodes:\n raise ResourceUsageError(\"Maximum number of nodes exceeded\", max_nodes=self._max_nodes)\n\n node, inputs, processor = parse_node_descriptor(node_descriptor, self.model)\n\n in_root = False\n\n for i, input_data in enumerate(inputs):\n selector, trigger = input_data\n\n walker = self.sensor_log.create_walker(selector)\n\n # Constant walkers begin life initialized to 0 so they always read correctly\n if walker.selector.inexhaustible:\n walker.reading = IOTileReading(0xFFFFFFFF, walker.selector.as_stream(), 0)\n\n node.connect_input(i, walker, trigger)\n\n if selector.input and not in_root:\n self.roots.append(node)\n in_root = True # Make sure we only add to root list once\n else:\n found = False\n for other in self.nodes:\n if selector.matches(other.stream):\n other.connect_output(node)\n found = True\n\n if not found and selector.buffered:\n raise NodeConnectionError(\"Node has input that refers to another node that has not been created yet\", node_descriptor=node_descriptor, input_selector=str(selector), input_index=i)\n\n # Also make sure we add this node's output to any other existing node's inputs\n # this is important for constant nodes that may be written from multiple places\n # FIXME: Make sure when we emit nodes, they are topologically sorted\n for other_node in self.nodes:\n for selector, trigger in other_node.inputs:\n if selector.matches(node.stream):\n node.connect_output(other_node)\n\n # Find and load the processing function for this node\n func = self.find_processing_function(processor)\n if func is None:\n raise ProcessingFunctionError(\"Could not find processing function in installed packages\", func_name=processor)\n\n node.set_func(processor, func)\n self.nodes.append(node)", "docstring": "Add a node to the sensor graph based on the description given.\n\n The node_descriptor must follow the sensor graph DSL and describe\n a node whose input nodes already exist.\n\nArgs:\n node_descriptor (str): A description of the node to be added\n including its inputs, triggering conditions, processing function\n and output stream.", "source": "juraj_google_style"} +{"code": "def print_res(data):\n\n print('===================================')\n main_part = data['data']\n print(main_part['word_name'])\n symbols = main_part['symbols'][0]\n print(\"美式音标:[\" + symbols['ph_am'] + \"]\")\n print(\"英式音标:[\" + symbols['ph_en'] + \"]\")\n print('-----------------------------------')\n parts = symbols['parts']\n for part in parts:\n print(part['part'])\n for mean in part['means']:\n print(\" \", mean)\n print('===================================')", "docstring": "Print translate result in a better format\n\nArgs:\n data(str): result", "source": "juraj_google_style"} +{"code": "def __init__(self, option_strings, dest, help, metavar, flag_instance): # pylint: disable=redefined-builtin\n\n del dest\n self._flag_instance = flag_instance\n super(_FlagAction, self).__init__(\n option_strings=option_strings,\n dest=argparse.SUPPRESS,\n help=help,\n metavar=metavar)", "docstring": "Initializes _FlagAction.\n\nArgs:\n option_strings: See argparse.Action.\n dest: Ignored. The flag is always defined with dest=argparse.SUPPRESS.\n help: See argparse.Action.\n metavar: See argparse.Action.\n flag_instance: absl.flags.Flag, the absl flag instance.", "source": "juraj_google_style"} +{"code": "def remove_room_alias(self, room_alias):\n\n try:\n self.api.remove_room_alias(room_alias)\n return True\n except MatrixRequestError:\n return False", "docstring": "Remove mapping of an alias\n\nArgs:\n room_alias(str): The alias to be removed.\n\nReturns:\n bool: True if the alias is removed, False otherwise.", "source": "juraj_google_style"} +{"code": "def sort_resources(cls, request, resources, fail_enum, header_proto=None):\n\n if not request.sorting:\n return resources\n\n value_handlers = cls._get_handler_set(request, fail_enum, header_proto)\n\n def sorter(resource_a, resource_b):\n for handler in value_handlers:\n val_a, val_b = handler.get_sort_values(resource_a, resource_b)\n\n if val_a < val_b:\n return handler.xform_result(-1)\n if val_a > val_b:\n return handler.xform_result(1)\n\n return 0\n\n return sorted(resources, key=cmp_to_key(sorter))", "docstring": "Sorts a list of resources based on a list of sort controls\n\nArgs:\n request (object): The parsed protobuf request object\n resources (list of objects): The resources to be sorted\n fail_enum (int, enum): The enum status to raise with invalid keys\n header_proto(class): Class to decode a resources header\n\nReturns:\n list: The sorted list of resources", "source": "juraj_google_style"} +{"code": "def generate_defect_structure(self, supercell=(1, 1, 1)):\n\n defect_structure = self.bulk_structure.copy()\n defect_structure.make_supercell(supercell)\n\n #create a trivial defect structure to find where supercell transformation moves the lattice\n struct_for_defect_site = Structure( self.bulk_structure.copy().lattice,\n [self.site.specie],\n [self.site.frac_coords],\n to_unit_cell=True)\n struct_for_defect_site.make_supercell(supercell)\n defect_site = struct_for_defect_site[0]\n\n poss_deflist = sorted(\n defect_structure.get_sites_in_sphere(defect_site.coords, 2, include_index=True), key=lambda x: x[1])\n defindex = poss_deflist[0][2]\n defect_structure.remove_sites([defindex])\n defect_structure.set_charge(self.charge)\n return defect_structure", "docstring": "Returns Defective Vacancy structure, decorated with charge\n\nArgs:\n supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix", "source": "juraj_google_style"} +{"code": "def ReadResponsesForRequestId(self, session_id, request_id, timestamp=None):\n\n request = rdf_flow_runner.RequestState(id=request_id, session_id=session_id)\n for _, responses in self.ReadResponses([request], timestamp=timestamp):\n return responses", "docstring": "Reads responses for one request.\n\nArgs:\n session_id: The session id to use.\n request_id: The id of the request.\n timestamp: A timestamp as used in the data store.\n\nYields:\n fetched responses for the request", "source": "juraj_google_style"} +{"code": "def idcode(msg):\n\n\n if df(msg) not in [5, 21]:\n raise RuntimeError(\"Message must be Downlink Format 5 or 21.\")\n\n mbin = hex2bin(msg)\n\n C1 = mbin[19]\n A1 = mbin[20]\n C2 = mbin[21]\n A2 = mbin[22]\n C4 = mbin[23]\n A4 = mbin[24]\n # _ = mbin[25]\n B1 = mbin[26]\n D1 = mbin[27]\n B2 = mbin[28]\n D2 = mbin[29]\n B4 = mbin[30]\n D4 = mbin[31]\n\n byte1 = int(A4+A2+A1, 2)\n byte2 = int(B4+B2+B1, 2)\n byte3 = int(C4+C2+C1, 2)\n byte4 = int(D4+D2+D1, 2)\n\n return str(byte1) + str(byte2) + str(byte3) + str(byte4)", "docstring": "Computes identity (squawk code) from DF5 or DF21 message, bit 20-32.\n credit: @fbyrkjeland\n\nArgs:\n msg (String): 28 bytes hexadecimal message string\n\nReturns:\n string: squawk code", "source": "juraj_google_style"} +{"code": "def CheckForHeaderGuard(filename, clean_lines, error):\n\n\n # Don't check for header guards if there are error suppression\n # comments somewhere in this file.\n #\n # Because this is silencing a warning for a nonexistent line, we\n # only support the very specific NOLINT(build/header_guard) syntax,\n # and not the general NOLINT or NOLINT(*) syntax.\n raw_lines = clean_lines.lines_without_raw_strings\n for i in raw_lines:\n if Search(r'//\\s*NOLINT\\(build/header_guard\\)', i):\n return\n\n # Allow pragma once instead of header guards\n for i in raw_lines:\n if Search(r'^\\s*#pragma\\s+once', i):\n return\n\n cppvar = GetHeaderGuardCPPVariable(filename)\n\n ifndef = ''\n ifndef_linenum = 0\n define = ''\n endif = ''\n endif_linenum = 0\n for linenum, line in enumerate(raw_lines):\n linesplit = line.split()\n if len(linesplit) >= 2:\n # find the first occurrence of #ifndef and #define, save arg\n if not ifndef and linesplit[0] == '#ifndef':\n # set ifndef to the header guard presented on the #ifndef line.\n ifndef = linesplit[1]\n ifndef_linenum = linenum\n if not define and linesplit[0] == '#define':\n define = linesplit[1]\n # find the last occurrence of #endif, save entire line\n if line.startswith('#endif'):\n endif = line\n endif_linenum = linenum\n\n if not ifndef or not define or ifndef != define:\n error(filename, 0, 'build/header_guard', 5,\n 'No #ifndef header guard found, suggested CPP variable is: %s' %\n cppvar)\n return\n\n # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__\n # for backward compatibility.\n if ifndef != cppvar:\n error_level = 0\n if ifndef != cppvar + '_':\n error_level = 5\n\n ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,\n error)\n error(filename, ifndef_linenum, 'build/header_guard', error_level,\n '#ifndef header guard has wrong style, please use: %s' % cppvar)\n\n # Check for \"//\" comments on endif line.\n ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,\n error)\n match = Match(r'#endif\\s*//\\s*' + cppvar + r'(_)?\\b', endif)\n if match:\n if match.group(1) == '_':\n # Issue low severity warning for deprecated double trailing underscore\n error(filename, endif_linenum, 'build/header_guard', 0,\n '#endif line should be \"#endif // %s\"' % cppvar)\n return\n\n # Didn't find the corresponding \"//\" comment. If this file does not\n # contain any \"//\" comments at all, it could be that the compiler\n # only wants \"/**/\" comments, look for those instead.\n no_single_line_comments = True\n for i in xrange(1, len(raw_lines) - 1):\n line = raw_lines[i]\n if Match(r'^(?:(?:\\'(?:\\.|[^\\'])*\\')|(?:\"(?:\\.|[^\"])*\")|[^\\'\"])*//', line):\n no_single_line_comments = False\n break\n\n if no_single_line_comments:\n match = Match(r'#endif\\s*/\\*\\s*' + cppvar + r'(_)?\\s*\\*/', endif)\n if match:\n if match.group(1) == '_':\n # Low severity warning for double trailing underscore\n error(filename, endif_linenum, 'build/header_guard', 0,\n '#endif line should be \"#endif /* %s */\"' % cppvar)\n return\n\n # Didn't find anything\n error(filename, endif_linenum, 'build/header_guard', 5,\n '#endif line should be \"#endif // %s\"' % cppvar)", "docstring": "Checks that the file contains a header guard.\n\n Logs an error if no #ifndef header guard is present. For other\n headers, checks that the full pathname is used.\n\nArgs:\n filename: The name of the C++ header file.\n clean_lines: A CleansedLines instance containing the file.\n error: The function to call with any errors found.", "source": "juraj_google_style"} +{"code": "def delta_E( self ):\n\n site_delta_E = self.final_site.energy - self.initial_site.energy\n if self.nearest_neighbour_energy:\n site_delta_E += self.nearest_neighbour_delta_E()\n if self.coordination_number_energy:\n site_delta_E += self.coordination_number_delta_E()\n return site_delta_E", "docstring": "The change in system energy if this jump were accepted.\n\nArgs:\n None\n\nReturns:\n (Float): delta E", "source": "juraj_google_style"} +{"code": "def _Open(self, path_spec, mode='rb'):\n\n if not path_spec.HasParent():\n raise errors.PathSpecError(\n 'Unsupported path specification without parent.')\n\n resolver.Resolver.key_chain.ExtractCredentialsFromPathSpec(path_spec)\n\n bde_volume = pybde.volume()\n file_object = resolver.Resolver.OpenFileObject(\n path_spec.parent, resolver_context=self._resolver_context)\n\n try:\n bde.BDEVolumeOpen(\n bde_volume, path_spec, file_object, resolver.Resolver.key_chain)\n except:\n file_object.close()\n raise\n\n self._bde_volume = bde_volume\n self._file_object = file_object", "docstring": "Opens the file system defined by path specification.\n\nArgs:\n path_spec (PathSpec): path specification.\n mode (Optional[str]): file access mode. The default is 'rb'\n read-only binary.\n\nRaises:\n AccessError: if the access to open the file was denied.\n IOError: if the file system could not be opened.\n PathSpecError: if the path specification is incorrect.\n ValueError: if the path specification is invalid.", "source": "juraj_google_style"} +{"code": "def group_id(self, resource_id):\n\n if self._name != 'group':\n self._request_uri = '{}/{}'.format(self._api_uri, resource_id)", "docstring": "Update the request URI to include the Group ID for specific group retrieval.\n\nArgs:\n resource_id (string): The group id.", "source": "juraj_google_style"} +{"code": "def get_gain(data, attr, class_attr,\n method=DEFAULT_DISCRETE_METRIC,\n only_sub=0, prefer_fewer_values=False, entropy_func=None):\n\n entropy_func = entropy_func or entropy\n val_freq = defaultdict(float)\n subset_entropy = 0.0\n\n # Calculate the frequency of each of the values in the target attribute\n for record in data:\n val_freq[record.get(attr)] += 1.0\n\n # Calculate the sum of the entropy for each subset of records weighted\n # by their probability of occuring in the training set.\n for val in val_freq.keys():\n val_prob = val_freq[val] / sum(val_freq.values())\n data_subset = [record for record in data if record.get(attr) == val]\n e = entropy_func(data_subset, class_attr, method=method)\n subset_entropy += val_prob * e\n\n if only_sub:\n return subset_entropy\n\n # Subtract the entropy of the chosen attribute from the entropy of the\n # whole data set with respect to the target attribute (and return it)\n main_entropy = entropy_func(data, class_attr, method=method)\n\n # Prefer gains on attributes with fewer values.\n if prefer_fewer_values:\n# n = len(val_freq)\n# w = (n+1)/float(n)/2\n #return (main_entropy - subset_entropy)*w\n return ((main_entropy - subset_entropy), 1./len(val_freq))\n else:\n return (main_entropy - subset_entropy)", "docstring": "Calculates the information gain (reduction in entropy) that would\n result by splitting the data on the chosen attribute (attr).\n\n Parameters:\n\n prefer_fewer_values := Weights the gain by the count of the attribute's\n unique values. If multiple attributes have the same gain, but one has\n slightly fewer attributes, this will cause the one with fewer\n attributes to be preferred.", "source": "juraj_google_style"} +{"code": "def get(cls, issue_type):\n\n if isinstance(issue_type, str):\n obj = getattr(db, cls.__name__).find_one(cls.issue_type == issue_type)\n\n elif isinstance(issue_type, int):\n obj = getattr(db, cls.__name__).find_one(cls.issue_type_id == issue_type)\n\n elif isinstance(issue_type, cls):\n return issue_type\n\n else:\n obj = None\n\n if not obj:\n obj = cls()\n obj.issue_type = issue_type\n\n db.session.add(obj)\n db.session.commit()\n db.session.refresh(obj)\n\n return obj", "docstring": "Returns the IssueType object for `issue_type`. If no existing object was found, a new type will\n be created in the database and returned\n\nArgs:\n issue_type (str,int,IssueType): Issue type name, id or class\n\nReturns:\n :obj:`IssueType`", "source": "juraj_google_style"} +{"code": "def update_course_runs(self, course_runs, enterprise_customer, enterprise_context):\n\n updated_course_runs = []\n for course_run in course_runs:\n track_selection_url = utils.get_course_track_selection_url(\n course_run=course_run,\n query_parameters=dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer)),\n )\n\n enrollment_url = enterprise_customer.get_course_run_enrollment_url(course_run.get('key'))\n\n course_run.update({\n 'enrollment_url': enrollment_url,\n 'track_selection_url': track_selection_url,\n })\n\n # Update marketing urls in course metadata to include enterprise related info.\n marketing_url = course_run.get('marketing_url')\n if marketing_url:\n query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))\n course_run.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})\n\n # Add updated course run to the list.\n updated_course_runs.append(course_run)\n return updated_course_runs", "docstring": "Update Marketing urls in course metadata and return updated course.\n\nArgs:\n course_runs (list): List of course runs.\n enterprise_customer (EnterpriseCustomer): enterprise customer instance.\n enterprise_context (dict): The context to inject into URLs.\n\nReturns:\n (dict): Dictionary containing updated course metadata.", "source": "juraj_google_style"} +{"code": "def insert_infocontent_data(germanet_db):\n\n gnet = germanet.GermaNet(germanet_db)\n # use add one smoothing\n gn_counts = defaultdict(lambda: 1.)\n total_count = 1\n input_file = gzip.open(os.path.join(os.path.dirname(__file__),\n WORD_COUNT_FILE))\n num_lines_read = 0\n num_lines = 0\n for line in input_file:\n line = line.decode('utf-8').strip().split('\\t')\n num_lines += 1\n if len(line) != 3:\n continue\n count, pos, word = line\n num_lines_read += 1\n count = int(count)\n synsets = set(gnet.synsets(word, pos))\n if not synsets:\n continue\n # Although Resnik (1995) suggests dividing count by the number\n # of synsets, Patwardhan et al (2003) argue against doing\n # this.\n count = float(count) / len(synsets)\n for synset in synsets:\n total_count += count\n paths = synset.hypernym_paths\n scount = float(count) / len(paths)\n for path in paths:\n for ss in path:\n gn_counts[ss._id] += scount\n print('Read {0} of {1} lines from count file.'.format(num_lines_read,\n num_lines))\n print('Recorded counts for {0} synsets.'.format(len(gn_counts)))\n print('Total count is {0}'.format(total_count))\n input_file.close()\n # update all the synset records in GermaNet\n num_updates = 0\n for synset in germanet_db.synsets.find():\n synset['infocont'] = gn_counts[synset['_id']] / total_count\n germanet_db.synsets.save(synset)\n num_updates += 1\n print('Updated {0} synsets.'.format(num_updates))", "docstring": "For every synset in GermaNet, inserts count information derived\n from SDEWAC.\n\nArgs:\n - `germanet_db`: a pymongo.database.Database object", "source": "juraj_google_style"} +{"code": "def initialize(self, map_arr, start_point_label=\"S\", end_point_label=\"G\", wall_label=\"#\", agent_label=\"@\"):\n\n np.set_printoptions(threshold=np.inf)\n\n self.__agent_label = agent_label\n self.__map_arr = map_arr\n self.__start_point_label = start_point_label\n start_arr_tuple = np.where(self.__map_arr == self.__start_point_label)\n x_arr, y_arr = start_arr_tuple\n self.__start_point_tuple = (x_arr[0], y_arr[0])\n end_arr_tuple = np.where(self.__map_arr == self.__end_point_label)\n x_arr, y_arr = end_arr_tuple\n self.__end_point_tuple = (x_arr[0], y_arr[0])\n self.__wall_label = wall_label\n\n for x in range(self.__map_arr.shape[1]):\n for y in range(self.__map_arr.shape[0]):\n if (x, y) == self.__start_point_tuple or (x, y) == self.__end_point_tuple:\n continue\n arr_value = self.__map_arr[y][x]\n if arr_value == self.__wall_label:\n continue\n\n self.save_r_df((x, y), float(arr_value))", "docstring": "Initialize map of maze and setup reward value.\n\nArgs:\n map_arr: Map. the 2d- `np.ndarray`.\n start_point_label: Label of start point.\n end_point_label: Label of end point.\n wall_label: Label of wall.\n agent_label: Label of agent.", "source": "juraj_google_style"} +{"code": "def configs_for_writer(writer=None, ppp_config_dir=None):\n\n search_paths = (ppp_config_dir,) if ppp_config_dir else tuple()\n if writer is not None:\n if not isinstance(writer, (list, tuple)):\n writer = [writer]\n # given a config filename or writer name\n config_files = [w if w.endswith('.yaml') else w + '.yaml' for w in writer]\n else:\n writer_configs = glob_config(os.path.join('writers', '*.yaml'),\n *search_paths)\n config_files = set(writer_configs)\n\n for config_file in config_files:\n config_basename = os.path.basename(config_file)\n writer_configs = config_search_paths(\n os.path.join(\"writers\", config_basename), *search_paths)\n\n if not writer_configs:\n LOG.warning(\"No writer configs found for '%s'\", writer)\n continue\n\n yield writer_configs", "docstring": "Generator of writer configuration files for one or more writers\n\nArgs:\n writer (Optional[str]): Yield configs only for this writer\n ppp_config_dir (Optional[str]): Additional configuration directory\n to search for writer configuration files.\n\n Returns: Generator of lists of configuration files", "source": "juraj_google_style"} +{"code": "def new(self, length, fp, manage_fp, offset):\n # type: (int, BinaryIO, bool, int) -> None\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('Inode is already initialized')\n\n self.data_length = length\n\n self.data_fp = fp\n self.manage_fp = manage_fp\n self.fp_offset = offset\n self.original_data_location = self.DATA_IN_EXTERNAL_FP\n\n self._initialized = True", "docstring": "Initialize a new Inode.\n\n Parameters:\n None.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def needkwargs(*argnames):\n\n required = set(argnames)\n\n def decorator(func):\n def inner(*args, **kwargs):\n missing = required - set(kwargs)\n if missing:\n err = \"%s kwargs are missing.\" % list(missing)\n raise ValueError(err)\n return func(*args, **kwargs)\n return inner\n return decorator", "docstring": "Function decorator which checks that the decorated function is called\n with a set of required kwargs.\n\nArgs:\n *argnames: String keyword argument names.\n\nRaises:\n ValueError: If a required kwarg is missing in the decorated function\n call.", "source": "juraj_google_style"} +{"code": "def __init__(self, editor):\n\n self.editor = editor\n self.timer = QTimer(self.editor)\n self.timer.setSingleShot(True)\n self.timer.timeout.connect(self.do_autosave)\n self._enabled = False # Can't use setter here\n self._interval = self.DEFAULT_AUTOSAVE_INTERVAL", "docstring": "Constructor.\n\n Autosave is disabled after construction and needs to be enabled\n explicitly if required.\n\nArgs:\n editor (Editor): editor plugin.", "source": "juraj_google_style"} +{"code": "def _activation_summary(x):\n\n # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training\n # session. This helps the clarity of presentation on tensorboard.\n tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)\n tf.summary.histogram(tensor_name + '/activations', x)\n tf.summary.scalar(tensor_name + '/sparsity',\n tf.nn.zero_fraction(x))", "docstring": "Helper to create summaries for activations.\n\n Creates a summary that provides a histogram of activations.\n Creates a summary that measures the sparsity of activations.\n\nArgs:\n x: Tensor\n\nReturns:\n nothing", "source": "juraj_google_style"} +{"code": "def check_runtime_errors(cmd_derived_from_alias, pos_args_table):\n\n for placeholder, value in pos_args_table.items():\n exec('{} = \"{}\"'.format(placeholder, value)) # pylint: disable=exec-used\n\n expressions = get_placeholders(cmd_derived_from_alias)\n for expression in expressions:\n try:\n exec(expression) # pylint: disable=exec-used\n except Exception as exception: # pylint: disable=broad-except\n error_msg = PLACEHOLDER_EVAL_ERROR.format(expression, exception)\n raise CLIError(error_msg)", "docstring": "Validate placeholders and their expressions in cmd_derived_from_alias to make sure\n that there is no runtime error (such as index out of range).\n\nArgs:\n cmd_derived_from_alias: The command derived from the alias\n (include any positional argument placehodlers)\n pos_args_table: The positional argument table.", "source": "juraj_google_style"} +{"code": "def __init__(self, prefix, section, filename=None):\n\n options = dict(prefix=prefix, section=section, filename=filename)\n\n super(Settings, self).__init__(**options)", "docstring": "Will try to read configuration from environment variables and ini\n files, if no value found in either of those ``None`` is\n returned.\n\nArgs:\n prefix: The environment variable prefix.\n section: The ini file section this configuration is scoped to\n filename: The path to the ini file to use", "source": "juraj_google_style"} +{"code": "def has_all_nonzero_section_lengths(neuron, threshold=0.0):\n\n bad_ids = [s.id for s in _nf.iter_sections(neuron.neurites)\n if section_length(s.points) <= threshold]\n\n return CheckResult(len(bad_ids) == 0, bad_ids)", "docstring": "Check presence of neuron sections with length not above threshold\n\nArgs:\n neuron(Neuron): The neuron object to test\n threshold(float): value above which a section length is considered\n to be non-zero\n\nReturns:\n CheckResult with result including list of ids of bad sections", "source": "juraj_google_style"} +{"code": "def ConfigureLogging(\n debug_output=False, filename=None, mode='w', quiet_mode=False):\n\n # Remove all possible log handlers. The log handlers cannot be reconfigured\n # and therefore must be recreated.\n for handler in logging.root.handlers:\n logging.root.removeHandler(handler)\n\n logger = logging.getLogger()\n\n if filename and filename.endswith('.gz'):\n handler = CompressedFileHandler(filename, mode=mode)\n elif filename:\n handler = logging.FileHandler(filename, mode=mode)\n else:\n handler = logging.StreamHandler()\n\n format_string = (\n '%(asctime)s [%(levelname)s] (%(processName)-10s) PID:%(process)d '\n '<%(module)s> %(message)s')\n\n formatter = logging.Formatter(format_string)\n handler.setFormatter(formatter)\n\n if debug_output:\n level = logging.DEBUG\n elif quiet_mode:\n level = logging.WARNING\n else:\n level = logging.INFO\n\n logger.setLevel(level)\n handler.setLevel(level)\n\n logger.addHandler(handler)", "docstring": "Configures the logging root logger.\n\nArgs:\n debug_output (Optional[bool]): True if the logging should include debug\n output.\n filename (Optional[str]): log filename.\n mode (Optional[str]): log file access mode.\n quiet_mode (Optional[bool]): True if the logging should not include\n information output. Note that debug_output takes precedence over\n quiet_mode.", "source": "juraj_google_style"} +{"code": "def normalise(self, to_currency):\n\n out = Money(currency=to_currency)\n for money in self._money_obs:\n out += converter.convert(money, to_currency)\n return Balance([out])", "docstring": "Normalise this balance into a single currency\n\nArgs:\n to_currency (str): Destination currency\n\nReturns:\n (Balance): A new balance object containing a single Money value in the specified currency", "source": "juraj_google_style"} +{"code": "def delete_namespace(self, name, ignore_errors=False):\n\n if self.has_namespace(name):\n del self.namespaces[name]\n return True\n elif ignore_errors:\n return True\n else:\n raise RuntimeError(\"namespace '%s' does not exist\" % name)", "docstring": "deletes a namespace\n\nArgs:\n name: the name of the namespace\n ignore_errors(bool): Will ignore if a namespace doesn not exist or\n there is an error deleting the namespace\n\nReturns:\n True if deleted\n False if not deleted\n error if namespace already exists", "source": "juraj_google_style"} +{"code": "def _GetPathSegmentIndexForSimilarityWeights(\n self, similarity_weights, occurrence_weights, value_weights):\n\n largest_weight = similarity_weights.GetLargestWeight()\n\n if largest_weight > 0:\n similarity_weight_indexes = similarity_weights.GetIndexesForWeight(\n largest_weight)\n number_of_similarity_indexes = len(similarity_weight_indexes)\n else:\n number_of_similarity_indexes = 0\n\n path_segment_index = None\n if number_of_similarity_indexes == 0:\n path_segment_index = self._GetPathSegmentIndexForOccurrenceWeights(\n occurrence_weights, value_weights)\n\n elif number_of_similarity_indexes == 1:\n path_segment_index = similarity_weight_indexes[0]\n\n else:\n largest_weight = 0\n largest_value_weight = 0\n\n for similarity_index in similarity_weight_indexes:\n occurrence_weight = occurrence_weights.GetWeightForIndex(\n similarity_index)\n\n if largest_weight > 0 and largest_weight == occurrence_weight:\n value_weight = value_weights.GetWeightForIndex(similarity_index)\n\n if largest_value_weight < value_weight:\n largest_weight = 0\n\n if not path_segment_index or largest_weight < occurrence_weight:\n largest_weight = occurrence_weight\n path_segment_index = similarity_index\n\n largest_value_weight = value_weights.GetWeightForIndex(\n similarity_index)\n\n return path_segment_index", "docstring": "Retrieves the index of the path segment based on similarity weights.\n\nArgs:\n similarity_weights: the similarity weights object (instance of\n _PathSegmentWeights).\n occurrence_weights: the occurrence weights object (instance of\n _PathSegmentWeights).\n value_weights: the value weights object (instance of _PathSegmentWeights).\n\nReturns:\n An integer containing the path segment index.", "source": "juraj_google_style"} +{"code": "def to_add_skip_model(self, start_id, end_id):\n\n self.operation_history.append((\"to_add_skip_model\", start_id, end_id))\n filters_end = self.layer_list[end_id].output.shape[-1]\n filters_start = self.layer_list[start_id].output.shape[-1]\n start_node_id = self.layer_id_to_output_node_ids[start_id][0]\n\n pre_end_node_id = self.layer_id_to_input_node_ids[end_id][0]\n end_node_id = self.layer_id_to_output_node_ids[end_id][0]\n\n skip_output_id = self._insert_pooling_layer_chain(start_node_id, end_node_id)\n\n # Add the conv layer\n new_conv_layer = get_conv_class(self.n_dim)(filters_start, filters_end, 1)\n skip_output_id = self.add_layer(new_conv_layer, skip_output_id)\n\n # Add the add layer.\n add_input_node_id = self._add_node(deepcopy(self.node_list[end_node_id]))\n add_layer = StubAdd()\n\n self._redirect_edge(pre_end_node_id, end_node_id, add_input_node_id)\n self._add_edge(add_layer, add_input_node_id, end_node_id)\n self._add_edge(add_layer, skip_output_id, end_node_id)\n add_layer.input = [\n self.node_list[add_input_node_id],\n self.node_list[skip_output_id],\n ]\n add_layer.output = self.node_list[end_node_id]\n self.node_list[end_node_id].shape = add_layer.output_shape\n\n # Set weights to the additional conv layer.\n if self.weighted:\n filter_shape = (1,) * self.n_dim\n weights = np.zeros((filters_end, filters_start) + filter_shape)\n bias = np.zeros(filters_end)\n new_conv_layer.set_weights(\n (add_noise(weights, np.array([0, 1])), add_noise(bias, np.array([0, 1])))\n )", "docstring": "Add a weighted add skip-connection from after start node to end node.\n\nArgs:\n start_id: The convolutional layer ID, after which to start the skip-connection.\n end_id: The convolutional layer ID, after which to end the skip-connection.", "source": "juraj_google_style"} +{"code": "def crcMeterRead(self, raw_read, def_buf):\n\n try:\n if len(raw_read) == 0:\n ekm_log(\"(\" + self.m_context + \") Empty return read.\")\n return False\n sent_crc = self.calc_crc16(raw_read[1:-2])\n logstr = \"(\" + self.m_context + \")CRC sent = \" + str(def_buf[\"crc16\"][MeterData.StringValue])\n logstr += \" CRC calc = \" + sent_crc\n ekm_log(logstr)\n if int(def_buf[\"crc16\"][MeterData.StringValue], 16) == int(sent_crc, 16):\n return True\n\n # A cross simple test lines on a USB serial adapter, these occur every\n # 1000 to 2000 reads, and they show up here as a bad unpack or\n # a bad crc type call. In either case, we suppress them a log will\n # become quite large. ekmcrc errors come through as type errors.\n # Failures of int type conversion in 16 bit conversion occur as value\n # errors.\n except struct.error:\n ekm_log(str(sys.exc_info()))\n for frame in traceback.extract_tb(sys.exc_info()[2]):\n fname, lineno, fn, text = frame\n ekm_log(\"Error in %s on line %d\" % (fname, lineno))\n return False\n\n except TypeError:\n ekm_log(str(sys.exc_info()))\n for frame in traceback.extract_tb(sys.exc_info()[2]):\n fname, lineno, fn, text = frame\n ekm_log(\"Error in %s on line %d\" % (fname, lineno))\n return False\n\n except ValueError:\n ekm_log(str(sys.exc_info()))\n for frame in traceback.extract_tb(sys.exc_info()[2]):\n fname, lineno, fn, text = frame\n ekm_log(\"Error in %s on line %d\" % (fname, lineno))\n return False\n\n return False", "docstring": "Internal read CRC wrapper.\n\nArgs:\n raw_read (str): Bytes with implicit string cast from serial read\n def_buf (SerialBlock): Populated read buffer.\n\nReturns:\n bool: True if passed CRC equals calculated CRC.", "source": "juraj_google_style"} +{"code": "def dfa(self, ttab: TransitionTable, init: int = 0) -> int:\n\n state = init\n while True:\n disp = ttab[state]\n ch = self.peek()\n state = disp.get(ch, disp[\"\"])()\n if state < 0:\n return state\n self.offset += 1", "docstring": "Run a DFA and return the final (negative) state.\n\nArgs:\n ttab: Transition table (with possible side-effects).\n init: Initial state.\n\nRaises:\n EndOfInput: If past the end of `self.input`.", "source": "juraj_google_style"} +{"code": "def _get_resource_view(self, resource_view):\n # type: (Union[ResourceView,Dict]) -> ResourceView\n\n if isinstance(resource_view, dict):\n resource_view = ResourceView(resource_view, configuration=self.configuration)\n if isinstance(resource_view, ResourceView):\n return resource_view\n raise HDXError('Type %s is not a valid resource view!' % type(resource_view).__name__)", "docstring": "Get resource view id\n\nArgs:\n resource_view (Union[ResourceView,Dict]): ResourceView metadata from a ResourceView object or dictionary\n\nReturns:\n ResourceView: ResourceView object", "source": "juraj_google_style"} +{"code": "def GetRequestXML(self, method, *args):\n\n self.suds_client.set_options(nosend=True)\n service_request = (getattr(self, method))(*args).envelope\n self.suds_client.set_options(nosend=False)\n return lxml.etree.fromstring(service_request)", "docstring": "Get the raw SOAP XML for a request.\n\nArgs:\n method: The method name.\n *args: A list of arguments to be passed to the method.\n\nReturns:\n An element containing the raw XML that would be sent as the request.", "source": "juraj_google_style"} +{"code": "def __eq__(self, other):\n\n res = False\n if type(self) is type(other) and \\\n self.name == other.name and \\\n self.size == other.size:\n res = True\n return res", "docstring": "Two Registers are the same if they are of the same type\n (i.e. quantum/classical), and have the same name and size.\n\nArgs:\n other (Register): other Register\n\nReturns:\n bool: are self and other equal.", "source": "juraj_google_style"} +{"code": "def remove(self, path, dir_fd=None):\n\n path = self._path_with_dir_fd(path, self.remove, dir_fd)\n self.filesystem.remove(path)", "docstring": "Remove the FakeFile object at the specified file path.\n\nArgs:\n path: Path to file to be removed.\n dir_fd: If not `None`, the file descriptor of a directory,\n with `path` being relative to this directory.\n New in Python 3.3.\n\nRaises:\n OSError: if path points to a directory.\n OSError: if path does not exist.\n OSError: if removal failed.", "source": "juraj_google_style"} +{"code": "def sum(x, axis=None, keepdims=False):\n\n from .function_bases import sum as sum_base\n if axis is None:\n axis = range(x.ndim)\n elif not hasattr(axis, '__iter__'):\n axis = [axis]\n return sum_base(x, axis, keepdims)", "docstring": "Reduction along axes with sum operation.\n\nArgs:\n x (Variable): An input variable.\n axis (None, int or tuple of ints): Axis or axes along which the sum is\n calculated. Passing the default value `None` will reduce all dimensions.\n keepdims (bool): Flag whether the reduced axes are kept as a dimension with 1 element.\n\nReturns:\n ~nnabla.Variable: N-D array.", "source": "juraj_google_style"} +{"code": "def attribute(*args, **kw):\n\n return operator(kind=Operator.Type.ATTRIBUTE, *args, **kw)", "docstring": "Registers a new attribute only operator function in the test engine.\n\nArgs:\n *args: variadic arguments.\n **kw: variadic keyword arguments.\n\nReturns:\n function", "source": "juraj_google_style"} +{"code": "def peersDF(symbol, token='', version=''):\n\n p = peers(symbol, token, version)\n df = _peersToDF(p)\n return df", "docstring": "Peers of ticker\n\n https://iexcloud.io/docs/api/#peers\n 8am UTC daily\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n DataFrame: result", "source": "juraj_google_style"} +{"code": "def post(self, request, enterprise_customer_uuid):\n\n transmit_courses_metadata_form = TransmitEnterpriseCoursesForm(request.POST)\n\n # check that form data is well-formed\n if transmit_courses_metadata_form.is_valid():\n channel_worker_username = transmit_courses_metadata_form.cleaned_data['channel_worker_username']\n\n # call `transmit_content_metadata` management command to trigger\n # transmission of enterprise courses metadata\n call_command(\n 'transmit_content_metadata',\n '--catalog_user', channel_worker_username,\n enterprise_customer=enterprise_customer_uuid\n )\n\n # Redirect to GET\n return HttpResponseRedirect('')\n\n context = self._build_context(request, enterprise_customer_uuid)\n context.update({self.ContextParameters.TRANSMIT_COURSES_METADATA_FORM: transmit_courses_metadata_form})\n return render(request, self.template, context)", "docstring": "Handle POST request - handle form submissions.\n\nArgs:\n request (django.http.request.HttpRequest): Request instance\n enterprise_customer_uuid (str): Enterprise Customer UUID", "source": "juraj_google_style"} +{"code": "def start_app(self, bundle_id):\n\n # if self._session is not None:\n # self.stop_app()\n self._bundle_id = bundle_id\n self._session = self._wda.session(bundle_id)\n return self._session", "docstring": "Start an application\n\nArgs:\n - bundle_id: (string) apk bundle ID\n\nReturns:\n WDA session object", "source": "juraj_google_style"} +{"code": "def _remove_hidden_parts(projected_surface):\n\n surface = np.copy(projected_surface)\n surface[~_make_occlusion_mask(projected_surface)] = np.nan\n return surface", "docstring": "Removes parts of a projected surface that are not visible.\n\nArgs:\n projected_surface (surface): the surface to use\n\nReturns:\n surface: A projected surface.", "source": "juraj_google_style"} +{"code": "def safe_call(request: Request, methods: Methods, *, debug: bool) -> Response:\n\n with handle_exceptions(request, debug) as handler:\n result = call(methods.items[request.method], *request.args, **request.kwargs)\n handler.response = SuccessResponse(result=result, id=request.id)\n return handler.response", "docstring": "Call a Request, catching exceptions to ensure we always return a Response.\n\nArgs:\n request: The Request object.\n methods: The list of methods that can be called.\n debug: Include more information in error responses.\n\nReturns:\n A Response object.", "source": "juraj_google_style"} +{"code": "def create_bmi_config_file(self, filename: str = \"bmi_config.txt\") -> None:\n\n s0 = self.construct_default_initial_state()\n s0.to_csv(filename, index_label=\"variable\")", "docstring": "Create a BMI config file to initialize the model.\n\nArgs:\n filename: The filename with which the config file should be saved.", "source": "juraj_google_style"} +{"code": "def __init__(self, _args):\n\n super(TcExInit, self).__init__(_args)\n\n # properties\n self.base_url = (\n 'https://raw.githubusercontent.com/ThreatConnect-Inc/tcex/{}/app_init/'\n ).format(self.args.branch)", "docstring": "Initialize Class properties.\n\nArgs:\n _args (namespace): The argparser args Namespace.", "source": "juraj_google_style"} +{"code": "def l2_loss(tensor, weight=1.0, scope=None):\n\n with tf.name_scope(scope, 'L2Loss', [tensor]):\n weight = tf.convert_to_tensor(weight,\n dtype=tensor.dtype.base_dtype,\n name='loss_weight')\n loss = tf.multiply(weight, tf.nn.l2_loss(tensor), name='value')\n tf.add_to_collection(LOSSES_COLLECTION, loss)\n return loss", "docstring": "Define a L2Loss, useful for regularize, i.e. weight decay.\n\nArgs:\n tensor: tensor to regularize.\n weight: an optional weight to modulate the loss.\n scope: Optional scope for name_scope.\n\nReturns:\n the L2 loss op.", "source": "juraj_google_style"} +{"code": "def gene_filter(self, query, mongo_query):\n\n LOG.debug('Adding panel and genes-related parameters to the query')\n\n gene_query = []\n\n if query.get('hgnc_symbols') and query.get('gene_panels'):\n gene_query.append({'hgnc_symbols': {'$in': query['hgnc_symbols']}})\n gene_query.append({'panels': {'$in': query['gene_panels']}})\n mongo_query['$or']=gene_query\n else:\n if query.get('hgnc_symbols'):\n hgnc_symbols = query['hgnc_symbols']\n mongo_query['hgnc_symbols'] = {'$in': hgnc_symbols}\n LOG.debug(\"Adding hgnc_symbols: %s to query\" %\n ', '.join(hgnc_symbols))\n\n if query.get('gene_panels'):\n gene_panels = query['gene_panels']\n mongo_query['panels'] = {'$in': gene_panels}\n\n return gene_query", "docstring": "Adds gene-related filters to the query object\n\nArgs:\n query(dict): a dictionary of query filters specified by the users\n mongo_query(dict): the query that is going to be submitted to the database\n\nReturns:\n mongo_query(dict): returned object contains gene and panel-related filters", "source": "juraj_google_style"} +{"code": "def register(self, token, regexp):\n\n self._tokens.append((token, re.compile(regexp)))", "docstring": "Register a token.\n\nArgs:\n token (Token): the token class to register\n regexp (str): the regexp for that token", "source": "juraj_google_style"} +{"code": "def _process_rules(self, rules):\n\n cidr = []\n non_cidr = []\n\n for rule in rules:\n if '.' in rule['app']:\n self.log.debug('Custom CIDR rule: %s', rule)\n self._validate_cidr(rule)\n cidr.append(rule)\n else:\n self.log.debug('SG reference rule: %s', rule)\n non_cidr.append(rule)\n\n self.log.debug('Custom CIDR rules: %s', cidr)\n self.log.debug('SG reference rules: %s', non_cidr)\n return non_cidr, cidr", "docstring": "Process rules into cidr and non-cidr lists.\n\nArgs:\n rules (list): Allowed Security Group ports and protocols.\n\nReturns:\n (list, list): Security Group reference rules and custom CIDR rules.", "source": "juraj_google_style"} +{"code": "def cols_strip(df,col_list, dest = False):\n\n if not dest:\n return _pd.DataFrame({col_name:col_strip(df,col_name) for col_name in col_list})\n for col_name in col_list:\n col_strip(df,col_name,dest)", "docstring": "Performs str.strip() a column of a DataFrame\n Parameters:\n df - DataFrame\n DataFrame to operate on\n col_list - list of strings\n names of columns to strip\n dest - bool, default False\n Whether to apply the result to the DataFrame or return it.\n True is apply, False is return.", "source": "juraj_google_style"} +{"code": "def deserialize_pem(cert_pem):\n\n if isinstance(cert_pem, str):\n cert_pem = cert_pem.encode(\"utf-8\")\n return cryptography.x509.load_pem_x509_certificate(\n data=cert_pem, backend=cryptography.hazmat.backends.default_backend()\n )", "docstring": "Deserialize PEM (Base64) encoded X.509 v3 certificate.\n\nArgs:\n cert_pem: str or bytes\n PEM (Base64) encoded X.509 v3 certificate\n\nReturns:\n cert_obj: cryptography.Certificate", "source": "juraj_google_style"} +{"code": "def _get_record(self, model_class, record_id):\n\n url = '{host}/{namespace}/{model}/{id}'.format(\n host=self._host,\n namespace=self._namespace,\n model=self._translate_name(model_class.__name__),\n id=record_id\n )\n data = self._get_json(url)['data']\n fresh_model = model_class(data['attributes'])\n fresh_model.id = data['id']\n fresh_model.validate()\n if self._cache is not None:\n self._cache.set_record(model_class.__name__, fresh_model.id, fresh_model)\n return fresh_model", "docstring": "Get a single record from the API.\n\nArgs:\n model_class (:class:`cinder_data.model.CinderModel`): A subclass of\n :class:`cinder_data.model.CinderModel` of your chosen model.\n record_id (int): The id of the record requested.\n\nReturns:\n :class:`cinder_data.model.CinderModel`: An instance of model_class or None.", "source": "juraj_google_style"} +{"code": "def set_timezone(self, timezone: str):\n\n data = {\"timezoneId\": timezone}\n return self._restCall(\"home/setTimezone\", body=json.dumps(data))", "docstring": "sets the timezone for the AP. e.g. \"Europe/Berlin\"\n\nArgs:\n timezone(str): the new timezone", "source": "juraj_google_style"} +{"code": "def length(ext_id, ext_des, ext_src):\n # type: (bytes, bytes, bytes) -> int\n\n return 8 + len(ext_id) + len(ext_des) + len(ext_src)", "docstring": "Static method to return the length of the Rock Ridge Extensions Reference\n record.\n\n Parameters:\n ext_id - The extension identifier to use.\n ext_des - The extension descriptor to use.\n ext_src - The extension specification source to use.\n\nReturns:\n The length of this record in bytes.", "source": "juraj_google_style"} +{"code": "def GetMessages(self, formatter_mediator, event):\n\n if self.DATA_TYPE != event.data_type:\n raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(\n event.data_type))\n\n event_values = event.CopyToDict()\n\n document_type = event_values.get('document_type', None)\n if document_type:\n event_values['document_type'] = self._DOC_TYPES.get(\n document_type, 'UNKNOWN')\n\n shared = event_values.get('shared', False)\n if shared:\n event_values['shared'] = 'Shared'\n else:\n event_values['shared'] = 'Private'\n\n return self._ConditionalFormatMessages(event_values)", "docstring": "Determines the formatted message strings for an event object.\n\nArgs:\n formatter_mediator (FormatterMediator): mediates the interactions\n between formatters and other components, such as storage and Windows\n EventLog resources.\n event (EventObject): event.\n\nReturns:\n tuple(str, str): formatted message string and short message string.\n\nRaises:\n WrongFormatter: if the event object cannot be formatted by the formatter.", "source": "juraj_google_style"} +{"code": "def read(self, size=None):\n\n if not self._is_open:\n raise IOError('Not opened.')\n\n if self._current_offset < 0:\n raise IOError(\n 'Invalid current offset: {0:d} value less than zero.'.format(\n self._current_offset))\n\n if self._decrypted_stream_size is None:\n self._decrypted_stream_size = self._GetDecryptedStreamSize()\n\n if self._decrypted_stream_size < 0:\n raise IOError('Invalid decrypted stream size.')\n\n if self._current_offset >= self._decrypted_stream_size:\n return b''\n\n if self._realign_offset:\n self._AlignDecryptedDataOffset(self._current_offset)\n self._realign_offset = False\n\n if size is None:\n size = self._decrypted_stream_size\n if self._current_offset + size > self._decrypted_stream_size:\n size = self._decrypted_stream_size - self._current_offset\n\n decrypted_data = b''\n\n if size == 0:\n return decrypted_data\n\n while size > self._decrypted_data_size:\n decrypted_data = b''.join([\n decrypted_data,\n self._decrypted_data[self._decrypted_data_offset:]])\n\n remaining_decrypted_data_size = (\n self._decrypted_data_size - self._decrypted_data_offset)\n\n self._current_offset += remaining_decrypted_data_size\n size -= remaining_decrypted_data_size\n\n if self._current_offset >= self._decrypted_stream_size:\n break\n\n read_count = self._ReadEncryptedData(self._ENCRYPTED_DATA_BUFFER_SIZE)\n self._decrypted_data_offset = 0\n if read_count == 0:\n break\n\n if size > 0:\n slice_start_offset = self._decrypted_data_offset\n slice_end_offset = slice_start_offset + size\n\n decrypted_data = b''.join([\n decrypted_data,\n self._decrypted_data[slice_start_offset:slice_end_offset]])\n\n self._decrypted_data_offset += size\n self._current_offset += size\n\n return decrypted_data", "docstring": "Reads a byte string from the file-like object at the current offset.\n\n The function will read a byte string of the specified size or\n all of the remaining data if no size was specified.\n\nArgs:\n size (Optional[int]): number of bytes to read, where None is all\n remaining data.\n\nReturns:\n bytes: data read.\n\nRaises:\n IOError: if the read failed.\n OSError: if the read failed.", "source": "juraj_google_style"} +{"code": "def uniprot_ec(uniprot_id):\n\n r = requests.post('http://www.uniprot.org/uniprot/?query=%s&columns=ec&format=tab' % uniprot_id)\n ec = r.content.decode('utf-8').splitlines()[1]\n\n if len(ec) == 0:\n ec = None\n\n return ec", "docstring": "Retrieve the EC number annotation for a UniProt ID.\n\nArgs:\n uniprot_id: Valid UniProt ID\n\n Returns:", "source": "juraj_google_style"} +{"code": "def italic(self, action):\n\n if action =='on':\n action = '4'\n elif action=='off':\n action = '5'\n else:\n raise RuntimeError('Invalid action for function italic. Options are on and off')\n self.send(chr(27)+action)", "docstring": "Enable/cancel italic printing\n\nArgs:\n action: Enable or disable italic printing. Options are 'on' and 'off'\n\nReturns:\n None\n\nRaises:\n RuntimeError: Invalid action.", "source": "juraj_google_style"} +{"code": "def pairwise_intersection(boxlist1, boxlist2):\n\n x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1)\n x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1)\n all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))\n all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))\n intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)\n all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))\n all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2))\n intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)\n return intersect_heights * intersect_widths", "docstring": "Compute pairwise intersection areas between boxes.\n\nArgs:\n boxlist1: Nx4 floatbox\n boxlist2: Mx4\n\nReturns:\n a tensor with shape [N, M] representing pairwise intersections", "source": "juraj_google_style"} +{"code": "def Match(self, registry_key):\n\n value_names = frozenset([\n registry_value.name for registry_value in registry_key.GetValues()])\n\n return self._value_names.issubset(value_names)", "docstring": "Determines if a Windows Registry key matches the filter.\n\nArgs:\n registry_key (dfwinreg.WinRegistryKey): Windows Registry key.\n\nReturns:\n bool: True if the keys match.", "source": "juraj_google_style"} +{"code": "def WriteSessionCompletion(self, aborted=False):\n\n self._RaiseIfNotWritable()\n\n if self._storage_type != definitions.STORAGE_TYPE_SESSION:\n raise IOError('Unsupported storage type.')\n\n self._session.aborted = aborted\n session_completion = self._session.CreateSessionCompletion()\n self._storage_file.WriteSessionCompletion(session_completion)", "docstring": "Writes session completion information.\n\nArgs:\n aborted (Optional[bool]): True if the session was aborted.\n\nRaises:\n IOError: if the storage type is not supported or\n when the storage writer is closed.\n OSError: if the storage type is not supported or\n when the storage writer is closed.", "source": "juraj_google_style"} +{"code": "def fetch_ensembl_exons(build='37'):\n\n LOG.info(\"Fetching ensembl exons build %s ...\", build)\n if build == '37':\n url = 'http://grch37.ensembl.org'\n else:\n url = 'http://www.ensembl.org'\n\n dataset_name = 'hsapiens_gene_ensembl'\n\n dataset = pybiomart.Dataset(name=dataset_name, host=url)\n\n attributes = [\n 'chromosome_name',\n 'ensembl_gene_id',\n 'ensembl_transcript_id',\n 'ensembl_exon_id',\n 'exon_chrom_start',\n 'exon_chrom_end',\n '5_utr_start',\n '5_utr_end',\n '3_utr_start',\n '3_utr_end',\n 'strand',\n 'rank'\n ]\n\n filters = {\n 'chromosome_name': CHROMOSOMES,\n }\n\n result = dataset.query(\n attributes = attributes,\n filters = filters\n )\n\n return result", "docstring": "Fetch the ensembl genes\n\nArgs:\n build(str): ['37', '38']", "source": "juraj_google_style"} +{"code": "def swo_speed_info(self):\n\n info = structs.JLinkSWOSpeedInfo()\n res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_SPEED_INFO,\n ctypes.byref(info))\n if res < 0:\n raise errors.JLinkException(res)\n\n return info", "docstring": "Retrieves information about the supported SWO speeds.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n A ``JLinkSWOSpeedInfo`` instance describing the target's supported\n SWO speeds.\n\nRaises:\n JLinkException: on error", "source": "juraj_google_style"} +{"code": "def saveRecords(self, path='myOutput'):\n\n numRecords = self.fields[0].numRecords\n assert (all(field.numRecords==numRecords for field in self.fields))\n\n import csv\n with open(path+'.csv', 'wb') as f:\n writer = csv.writer(f)\n writer.writerow(self.getAllFieldNames())\n writer.writerow(self.getAllDataTypes())\n writer.writerow(self.getAllFlags())\n writer.writerows(self.getAllRecords())\n if self.verbosity>0:\n print '******', numRecords,'records exported in numenta format to file:',\\\n path,'******\\n'", "docstring": "Export all the records into a csv file in numenta format.\n\n Example header format:\n fieldName1 fieldName2 fieldName3\n date string float\n T S\n\n Parameters:\n --------------------------------------------------------------------\n path: Relative path of the file to which the records are to be exported", "source": "juraj_google_style"} +{"code": "def write_message(self, message, timeout):\n\n with self._writer_lock:\n self._transport.write(message.header, timeout.remaining_ms)\n\n # Use any remaining time to send the data. Note that if we get this far,\n # we always at least try to send the data (with a minimum of 10ms timeout)\n # because we don't want the remote end to get out of sync because we sent\n # a header but no data.\n if timeout.has_expired():\n _LOG.warning('Timed out between AdbMessage header and data, sending '\n 'data anyway with 10ms timeout')\n timeout = timeouts.PolledTimeout.from_millis(10)\n self._transport.write(message.data, timeout.remaining_ms)", "docstring": "Send the given message over this transport.\n\nArgs:\n message: The AdbMessage to send.\n timeout: Use this timeout for the entire write operation, it should be an\n instance of timeouts.PolledTimeout.", "source": "juraj_google_style"} +{"code": "def localopt(self, forcefield='mmff94', steps=500):\n\n pbmol = pb.Molecule(self._obmol)\n pbmol.localopt(forcefield=forcefield, steps=steps)\n self._obmol = pbmol.OBMol", "docstring": "A wrapper to pybel's localopt method to optimize a Molecule.\n\nArgs:\n forcefield: Default is mmff94. Options are 'gaff', 'ghemical',\n 'mmff94', 'mmff94s', and 'uff'.\n steps: Default is 500.", "source": "juraj_google_style"} +{"code": "def proto_refactor_files(dest_dir, namespace, namespace_path):\n\n for dn, dns, fns in os.walk(dest_dir):\n for fn in fns:\n fn = os.path.join(dn, fn)\n if fnmatch.fnmatch(fn, '*.proto'):\n data = proto_refactor(fn, namespace, namespace_path)\n with open(fn, 'w') as f:\n f.write(data)", "docstring": "This method runs the refactoring on all the Protobuf files in the\n Dropsonde repo.\n\nArgs:\n dest_dir (str): directory where the Protobuf files lives.\n namespace (str): the desired package name (i.e. \"dropsonde.py2\")\n namespace_path (str): the desired path corresponding to the package\n name (i.e. \"dropsonde/py2\")", "source": "juraj_google_style"} +{"code": "def add_child(self, key, value):\n\n if type(value) in (list, tuple, dict):\n if type(value)==dict:\n for k in value.keys():\n self.add_child(k, value[k])\n return\n i = 0\n for child in value:\n self.add_child(key[i], child)\n i = i + 1\n return\n\n if hasattr(value, 'attributes'):\n value.attributes['data-parent-widget'] = self.identifier\n value._parent = self\n\n if key in self.children:\n self._render_children_list.remove(key)\n self._render_children_list.append(key)\n\n self.children[key] = value", "docstring": "Adds a child to the Tag\n\n To retrieve the child call get_child or access to the Tag.children[key] dictionary.\n\nArgs:\n key (str): Unique child's identifier, or iterable of keys\n value (Tag, str): can be a Tag, an iterable of Tag or a str. In case of iterable\n of Tag is a dict, each item's key is set as 'key' param", "source": "juraj_google_style"} +{"code": "def _RunAction(self, rule, client_id):\n\n actions_count = 0\n\n try:\n if self._CheckIfHuntTaskWasAssigned(client_id, rule.hunt_id):\n logging.info(\n \"Foreman: ignoring hunt %s on client %s: was started \"\n \"here before\", client_id, rule.hunt_id)\n else:\n logging.info(\"Foreman: Starting hunt %s on client %s.\", rule.hunt_id,\n client_id)\n\n # hunt_name is only used for legacy hunts.\n if rule.hunt_name:\n flow_cls = registry.AFF4FlowRegistry.FlowClassByName(rule.hunt_name)\n hunt_urn = rdfvalue.RDFURN(\"aff4:/hunts/%s\" % rule.hunt_id)\n flow_cls.StartClients(hunt_urn, [client_id])\n else:\n hunt.StartHuntFlowOnClient(client_id, rule.hunt_id)\n\n actions_count += 1\n\n # There could be all kinds of errors we don't know about when starting the\n # hunt so we catch everything here.\n except Exception as e: # pylint: disable=broad-except\n logging.exception(\"Failure running foreman action on client %s: %s\",\n rule.hunt_id, e)\n\n return actions_count", "docstring": "Run all the actions specified in the rule.\n\nArgs:\n rule: Rule which actions are to be executed.\n client_id: Id of a client where rule's actions are to be executed.\n\nReturns:\n Number of actions started.", "source": "juraj_google_style"} +{"code": "def comment_delete(self, comment_id):\n\n return self._get('comments/{0}.json'.format(comment_id),\n method='DELETE', auth=True)", "docstring": "Remove a specific comment (Requires login).\n\n Parameters:\n comment_id (int): The id number of the comment to remove.", "source": "juraj_google_style"} +{"code": "def print_debug(*args, **kwargs):\n\n if WTF_CONFIG_READER.get(\"debug\", False) == True:\n print(*args, **kwargs)", "docstring": "Print if and only if the debug flag is set true in the config.yaml file.\n\nArgs:\n args : var args of print arguments.", "source": "juraj_google_style"} +{"code": "def get(self, s):\n\n ret = []\n search_by_expression = self._valid_search(s)\n for l in self.lines:\n if search_by_expression(l):\n ret.append(self._parse_line(l))\n return ret", "docstring": "Returns all lines that contain `s` anywhere and wrap them in a list of\n dictionaries. `s` can be either a single string or a string list. For\n list, all keywords in the list must be found in each line.\n\n Parameters:\n s(str or list): one or more strings to search for.\n\nReturns:\n (list): list of dictionaries corresponding to the parsed lines\n contain the `s`.", "source": "juraj_google_style"} +{"code": "def FlagCxx11Features(filename, clean_lines, linenum, error):\n\n line = clean_lines.elided[linenum]\n\n # Flag unapproved C++11 headers.\n include = Match(r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]', line)\n if include and include.group(1) in ('cfenv',\n 'condition_variable',\n 'fenv.h',\n 'future',\n 'mutex',\n 'thread',\n 'chrono',\n 'ratio',\n 'regex',\n 'system_error',\n ):\n error(filename, linenum, 'build/c++11', 5,\n ('<%s> is an unapproved C++11 header.') % include.group(1))\n\n # The only place where we need to worry about C++11 keywords and library\n # features in preprocessor directives is in macro definitions.\n if Match(r'\\s*#', line) and not Match(r'\\s*#\\s*define\\b', line): return\n\n # These are classes and free functions. The classes are always\n # mentioned as std::*, but we only catch the free functions if\n # they're not found by ADL. They're alphabetical by header.\n for top_name in (\n # type_traits\n 'alignment_of',\n 'aligned_union',\n ):\n if Search(r'\\bstd::%s\\b' % top_name, line):\n error(filename, linenum, 'build/c++11', 5,\n ('std::%s is an unapproved C++11 class or function. Send c-style '\n 'an example of where it would make your code more readable, and '\n 'they may let you use it.') % top_name)", "docstring": "Flag those c++11 features that we only allow in certain places.\n\nArgs:\n filename: The name of the current file.\n clean_lines: A CleansedLines instance containing the file.\n linenum: The number of the line to check.\n error: The function to call with any errors found.", "source": "juraj_google_style"} +{"code": "def fit_transform(self, X, y=None):\n\n\n self.label_encoders = [None] * X.shape[1]\n self.label_maxes = [None] * X.shape[1]\n\n for i, col in enumerate(X.columns):\n self.label_encoders[i], self.label_maxes[i] = \\\n self._get_label_encoder_and_max(X[col])\n\n X.loc[:, col] = X[col].fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)\n\n return X", "docstring": "Encode categorical columns into label encoded columns\n\nArgs:\n X (pandas.DataFrame): categorical columns to encode\n\nReturns:\n X (pandas.DataFrame): label encoded columns", "source": "juraj_google_style"} +{"code": "def strip_errors(obj):\n\n rtn_obj = copy.deepcopy(obj)\n try:\n del rtn_obj[\"__error_keys__\"]\n except KeyError:\n pass\n for key in obj.get('__error_keys__', []):\n rtn_obj[key] = rtn_obj[key]['value']\n return rtn_obj", "docstring": "Reads through and error object and replaces the error dict with the\n value\n\nArgs:\n obj: the error object/dictionary", "source": "juraj_google_style"} +{"code": "def link(target, link_to):\n\n assert isinstance(target, str)\n assert os.path.exists(target)\n assert isinstance(link_to, str)\n\n # Create the path to the link if it does not exists\n abs_path = os.path.dirname(os.path.abspath(link_to))\n if not os.path.isdir(abs_path):\n os.makedirs(abs_path)\n\n # Make sure the file or folder recursively has the good mode\n chmod(target)\n\n # Create the link to target\n os.symlink(target, link_to)", "docstring": "Create a link to a target file or a folder.\n\n For simplicity sake, both target and link_to must be absolute path and must\n include the filename of the file or folder.\n Also do not include any trailing slash.\n\n e.g. link('/path/to/file', '/path/to/link')\n\n But not: link('/path/to/file', 'path/to/')\n or link('/path/to/folder/', '/path/to/link')\n\nArgs:\n target (str): file or folder the link will point to\n link_to (str): Link to create", "source": "juraj_google_style"} +{"code": "def verify(self, obj):\n\n\n if obj != self._literal:\n raise ValidationError(\"Object is not equal to literal\",\n reason='%s is not equal to %s' % (str(obj), str(self._literal)), object=obj)\n\n return obj", "docstring": "Verify that the object conforms to this verifier's schema\n\nArgs:\n obj (object): A python object to verify\n\nRaises:\n ValidationError: If there is a problem verifying the dictionary, a\n ValidationError is thrown with at least the reason key set indicating\n the reason for the lack of validation.", "source": "juraj_google_style"} +{"code": "def write_log(self, message):\n\n if self._is_write_log and self.log_file and not self.log_file.closed:\n self.log_file.write(message + '\\n')", "docstring": "Write a line to the VM instruction log file.\n\nArgs:\n message (str): string message to write to file.", "source": "juraj_google_style"} +{"code": "def dataset(self, mode, hparams=None, global_step=None, **kwargs):\n\n datasets = [p.dataset(mode, **kwargs) for p in self.problems]\n datasets = [\n d.map(lambda x, i=j: self.normalize_example( # pylint: disable=g-long-lambda\n dict(x, problem_id=tf.constant([i])), hparams))\n for j, d in enumerate(datasets) # Tag examples with a problem_id.\n ]\n if mode is problem.DatasetSplit.TRAIN:\n if global_step is None:\n global_step = tf.train.get_or_create_global_step()\n pmf = get_schedule_distribution(self.schedule, global_step)\n return get_multi_dataset(datasets, pmf)\n elif self.only_eval_first_problem:\n return datasets[0]\n else:\n datasets = [d.repeat() for d in datasets]\n return tf.data.Dataset.zip(tuple(datasets)).flat_map(\n lambda *x: functools.reduce( # pylint: disable=g-long-lambda\n tf.data.Dataset.concatenate,\n map(tf.data.Dataset.from_tensors, x)))", "docstring": "Returns a dataset containing examples from multiple problems.\n\nArgs:\n mode: A member of problem.DatasetSplit.\n hparams: A tf.HParams object, the model hparams.\n global_step: A scalar tensor used to compute the sampling distribution.\n If global_step is None, we call tf.train.get_or_create_global_step by\n default.\n **kwargs: Keywords for problem.Problem.Dataset.\n\nReturns:\n A dataset containing examples from multiple problems.", "source": "juraj_google_style"} +{"code": "def _map_across_full_axis_select_indices(\n self, axis, func, indices, keep_remaining=False\n ):\n\n return self.data.apply_func_to_select_indices_along_full_axis(\n axis, func, indices, keep_remaining\n )", "docstring": "Maps function to select indices along full axis.\n\nArgs:\n axis: 0 for columns and 1 for rows.\n func: Callable mapping function over the BlockParitions.\n indices: indices along axis to map over.\n keep_remaining: True if keep indices where function was not applied.\n\nReturns:\n BaseFrameManager containing the result of mapping func over axis on indices.", "source": "juraj_google_style"} +{"code": "def reciprocal_lattice_from_outcar( filename ): # from https://github.com/MaterialsDiscovery/PyChemia\n\n outcar = open(filename, \"r\").read()\n # just keeping the last component\n recLat = re.findall(r\"reciprocal\\s*lattice\\s*vectors\\s*([-.\\s\\d]*)\",\n outcar)[-1]\n recLat = recLat.split()\n recLat = np.array(recLat, dtype=float)\n # up to now I have, both direct and rec. lattices (3+3=6 columns)\n recLat.shape = (3, 6)\n recLat = recLat[:, 3:]\n return recLat", "docstring": "Finds and returns the reciprocal lattice vectors, if more than\n one set present, it just returns the last one.\n\nArgs:\n filename (Str): The name of the outcar file to be read\n\nReturns:\n List(Float): The reciprocal lattice vectors.", "source": "juraj_google_style"} +{"code": "def cooccurrences(self, domains):\n\n api_name = 'opendns-cooccurrences'\n fmt_url_path = u'recommendations/name/{0}.json'\n return self._multi_get(api_name, fmt_url_path, domains)", "docstring": "Get the domains related to input domains.\n\nArgs:\n domains: an enumerable of strings domain names\n\nReturns:\n An enumerable of string domain names", "source": "juraj_google_style"} +{"code": "def add_profile_variants(self, profile_variants):\n\n\n\n results = self.db.profile_variant.insert_many(profile_variants)\n\n return results", "docstring": "Add several variants to the profile_variant collection in the\n database\n\nArgs:\n profile_variants(list(models.ProfileVariant))", "source": "juraj_google_style"} +{"code": "def __init__(self, parent):\n\n\n super(ModuleFrame, self).__init__(parent)\n logger.debug(\"Initialising module tabs\")\n\n # Setup styles\n style = ttk.Style()\n style.configure(\"Module.TFrame\", background=\"white\")\n\n self.module_buttons = {}\n self.current_button = None\n\n # Module view\n self.module_list = ttk.Frame(self, width=150, style=\"Module.TFrame\")\n self.module_list.grid(column=0, row=0, padx=0, pady=0, sticky=\"W E N S\")\n self.module_list.columnconfigure(0, weight=1)\n self.module_list.rowconfigure(0, weight=0)\n self.module_list.rowconfigure(1, weight=1)\n # Header\n header = tk.Label(self.module_list, text=\"Modules\", bg=\"white\", fg=\"#484848\")\n header.grid(column=0, row=0, padx=0, pady=0, sticky=\"W E N\")\n # Module selection list\n self.module_selection = ttk.Frame(self.module_list, style=\"Module.TFrame\")\n self.module_selection.grid(column=0, row=1, padx=0, pady=0, sticky=\"W E N S\")\n self.module_selection.columnconfigure(0, weight=1)\n # Module UI view\n self.module_ui = ttk.Frame(self)\n self.module_ui.grid(column=1, row=0, padx=0, pady=0, sticky=\"W E N S\")\n self.module_ui.columnconfigure(0, weight=1)\n self.module_ui.rowconfigure(0, weight=1)\n\n self.clear_modules()\n\n # Configure stretch ratios\n self.columnconfigure(0, minsize=150)\n self.columnconfigure(1, weight=1)\n self.rowconfigure(0, weight=1)", "docstring": "Create a new module frame and add it to the given parent.\n\nArgs:\n parent: A tk or ttk object", "source": "juraj_google_style"} +{"code": "def _cumprod(l):\n\n ret = [1]\n for item in l:\n ret.append(ret[-1] * item)\n return ret", "docstring": "Cumulative product of a list.\n\nArgs:\n l: a list of integers\n\nReturns:\n a list with one more element (starting with 1)", "source": "juraj_google_style"} +{"code": "def _enum_from_direction(direction):\n\n if isinstance(direction, int):\n return direction\n\n if direction == Query.ASCENDING:\n return enums.StructuredQuery.Direction.ASCENDING\n elif direction == Query.DESCENDING:\n return enums.StructuredQuery.Direction.DESCENDING\n else:\n msg = _BAD_DIR_STRING.format(direction, Query.ASCENDING, Query.DESCENDING)\n raise ValueError(msg)", "docstring": "Convert a string representation of a direction to an enum.\n\nArgs:\n direction (str): A direction to order by. Must be one of\n :attr:`~.firestore.Query.ASCENDING` or\n :attr:`~.firestore.Query.DESCENDING`.\n\nReturns:\n int: The enum corresponding to ``direction``.\n\nRaises:\n ValueError: If ``direction`` is not a valid direction.", "source": "juraj_google_style"} +{"code": "def _GetEnableOsLoginValue(self, metadata_dict):\n\n instance_data, project_data = self._GetInstanceAndProjectAttributes(\n metadata_dict)\n instance_value = instance_data.get('enable-oslogin')\n project_value = project_data.get('enable-oslogin')\n value = instance_value or project_value or ''\n\n return value.lower() == 'true'", "docstring": "Get the value of the enable-oslogin metadata key.\n\nArgs:\n metadata_dict: json, the deserialized contents of the metadata server.\n\nReturns:\n bool, True if OS Login is enabled for VM access.", "source": "juraj_google_style"} +{"code": "def process_data(data, number_to_keep):\n\n\n result = dict()\n\n if number_to_keep != 0:\n data_temp = dict(Counter(data).most_common(number_to_keep))\n data_temp['rest'] = sum(data.values()) - sum(data_temp.values())\n data = data_temp\n\n labels = data\n values = np.array([data[key] for key in labels], dtype=float)\n pvalues = values / sum(values)\n for position, label in enumerate(labels):\n result[label] = round(pvalues[position], 5)\n\n return result", "docstring": "Prepare received data for representation.\n\nArgs:\n data (dict): values to represent (ex. {'001' : 130})\n number_to_keep (int): number of elements to show individually.\n\nReturns:\n dict: processed data to show.", "source": "juraj_google_style"} +{"code": "def get_item(dictionary, tuple_key, default_value):\n\n u, v = tuple_key\n\n # Grab tuple-values from dictionary\n tuple1 = dictionary.get((u, v), None)\n tuple2 = dictionary.get((v, u), None)\n\n # Return the first value that is not {None, 0, False}\n return tuple1 or tuple2 or default_value", "docstring": "Grab values from a dictionary using an unordered tuple as a key.\n\n Dictionary should not contain None, 0, or False as dictionary values.\n\nArgs:\n dictionary: Dictionary that uses two-element tuple as keys\n tuple_key: Unordered tuple of two elements\n default_value: Value that is returned when the tuple_key is not found in the dictionary", "source": "juraj_google_style"} +{"code": "def num_nodes(self, leaves=True, internal=True):\n\n if not isinstance(leaves, bool):\n raise TypeError(\"leaves must be a bool\")\n if not isinstance(internal, bool):\n raise TypeError(\"internal must be a bool\")\n num = 0\n for node in self.traverse_preorder():\n if (leaves and node.is_leaf()) or (internal and not node.is_leaf()):\n num += 1\n return num", "docstring": "Compute the total number of selected nodes in this ``Tree``\n\nArgs:\n ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``\n\n ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``\n\nReturns:\n ``int``: The total number of selected nodes in this ``Tree``", "source": "juraj_google_style"} +{"code": "def refresh(self, refresh_binary=True):\n\n\n\n\t\tupdated_self = self.repo.get_resource(self.uri)\n\n\t\t# if resource type of updated_self != self, raise exception\n\t\tif not isinstance(self, type(updated_self)):\n\t\t\traise Exception('Instantiated %s, but repository reports this resource is %s' % (type(updated_self), type(self)) )\n\n\t\tif updated_self:\n\n\t\t\t# update attributes\n\t\t\tself.status_code = updated_self.status_code\n\t\t\tself.rdf.data = updated_self.rdf.data\n\t\t\tself.headers = updated_self.headers\n\t\t\tself.exists = updated_self.exists\n\n\t\t\t# update graph if RDFSource\n\t\t\tif type(self) != NonRDFSource:\n\t\t\t\tself._parse_graph()\n\n\t\t\t# empty versions\n\t\t\tself.versions = SimpleNamespace()\n\n\t\t\t# if NonRDF, set binary attributes\n\t\t\tif type(updated_self) == NonRDFSource and refresh_binary:\n\t\t\t\tself.binary.refresh(updated_self)\n\n\t\t\t# fire resource._post_create hook if exists\n\t\t\tif hasattr(self,'_post_refresh'):\n\t\t\t\tself._post_refresh()\n\n\t\t\t# cleanup\n\t\t\tdel(updated_self)\n\n\t\telse:\n\t\t\tlogger.debug('resource %s not found, dumping values')\n\t\t\tself._empty_resource_attributes()", "docstring": "Performs GET request and refreshes RDF information for resource.\n\nArgs:\n None\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def view_structure(self, only_chains=None, opacity=1.0, recolor=False, gui=False):\n\n # TODO: show_structure_file does not work for MMTF files - need to check for that and load accordingly\n\n if ssbio.utils.is_ipynb():\n import nglview as nv\n else:\n raise EnvironmentError('Unable to display structure - not running in a Jupyter notebook environment')\n\n if not self.structure_file:\n raise ValueError(\"Structure file not loaded\")\n\n only_chains = ssbio.utils.force_list(only_chains)\n to_show_chains = '( '\n for c in only_chains:\n to_show_chains += ':{} or'.format(c)\n to_show_chains = to_show_chains.strip(' or ')\n to_show_chains += ' )'\n\n if self.file_type == 'mmtf' or self.file_type == 'mmtf.gz':\n view = nv.NGLWidget()\n view.add_component(self.structure_path)\n else:\n view = nv.show_structure_file(self.structure_path, gui=gui)\n\n if recolor:\n view.clear_representations()\n if only_chains:\n view.add_cartoon(selection='{} and (not hydrogen)'.format(to_show_chains), color='silver', opacity=opacity)\n else:\n view.add_cartoon(selection='protein', color='silver', opacity=opacity)\n elif only_chains:\n view.clear_representations()\n view.add_cartoon(selection='{} and (not hydrogen)'.format(to_show_chains), color='silver', opacity=opacity)\n\n return view", "docstring": "Use NGLviewer to display a structure in a Jupyter notebook\n\nArgs:\n only_chains (str, list): Chain ID or IDs to display\n opacity (float): Opacity of the structure\n recolor (bool): If structure should be cleaned and recolored to silver\n gui (bool): If the NGLview GUI should show up\n\nReturns:\n NGLviewer object", "source": "juraj_google_style"} +{"code": "def set_key_color(self, color: Tuple[int, int, int]) -> None:\n\n lib.TCOD_image_set_key_color(self.image_c, color)", "docstring": "Set a color to be transparent during blitting functions.\n\nArgs:\n color (Union[Tuple[int, int, int], Sequence[int]]):\n An (r, g, b) sequence or Color instance.", "source": "juraj_google_style"} +{"code": "def get_box_threads(self, box_key):\n\n\t\turi = '/'.join([\n\t\t\t\t\t\tself.api_uri,\n\t\t\t\t\t\tself.boxes_suffix,\n\t\t\t\t\t\tbox_key,\n\t\t\t\t\t\tself.threads_suffix\n\t\t\t\t\t\t])\n\t\treturn self._req('get', uri)", "docstring": "Gets all threads in a specified box\n\nArgs:\n box_key \t\tbox to look in\n returns \t\ta list of thread dicts", "source": "juraj_google_style"} +{"code": "def download_as_pem(\n base_url=d1_common.const.URL_DATAONE_ROOT,\n timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT,\n):\n\n return ssl.DER_cert_to_PEM_cert(download_as_der(base_url, timeout_sec))", "docstring": "Download public certificate from a TLS/SSL web server as PEM encoded string.\n\n Also see download_as_der().\n\nArgs:\n base_url : str\n A full URL to a DataONE service endpoint or a server hostname\n timeout_sec : int or float\n Timeout for the SSL socket operations\n\nReturns:\n str: The certificate as a PEM encoded string.", "source": "juraj_google_style"} +{"code": "def write_version(name=None, path=None):\n\n # Written like this for coverage purposes.\n # http://stackoverflow.com/questions/5850268/how-to-test-or-mock-if-name-main-contents/27084447#27084447\n if name in (None, '__main__'):\n path = path or os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),\n \"version.json\")\n contents = {\n 'version': __version__,\n 'version_string': __version_string__,\n }\n with open(path, 'w') as filehandle:\n filehandle.write(json.dumps(contents, sort_keys=True, indent=4))", "docstring": "Write the version info to ../version.json, for setup.py.\n\nArgs:\n name (Optional[str]): this is for the ``write_version(name=__name__)``\n below. That's one way to both follow the\n ``if __name__ == '__main__':`` convention but also allow for full\n coverage without ignoring parts of the file.\n\n path (Optional[str]): the path to write the version json to. Defaults\n to ../version.json", "source": "juraj_google_style"} +{"code": "def ParseEnum(field, value):\n\n enum_descriptor = field.enum_type\n try:\n number = int(value, 0)\n except ValueError:\n # Identifier.\n enum_value = enum_descriptor.values_by_name.get(value, None)\n if enum_value is None:\n raise ValueError('Enum type \"%s\" has no value named %s.' %\n (enum_descriptor.full_name, value))\n else:\n # Numeric value.\n enum_value = enum_descriptor.values_by_number.get(number, None)\n if enum_value is None:\n raise ValueError('Enum type \"%s\" has no value with number %d.' %\n (enum_descriptor.full_name, number))\n return enum_value.number", "docstring": "Parse an enum value.\n\n The value can be specified by a number (the enum value), or by\n a string literal (the enum name).\n\nArgs:\n field: Enum field descriptor.\n value: String value.\n\nReturns:\n Enum value number.\n\nRaises:\n ValueError: If the enum value could not be parsed.", "source": "juraj_google_style"} +{"code": "def dispatch(self, inp):\n\n inp = tf.reshape(inp, [self._batch * self._length, -1])\n # [batch, num_experts, expert_capacity, depth]\n ret = tf.gather(inp, self._flat_indices)\n return ret", "docstring": "Send the inputs to the experts.\n\nArgs:\n inp: a `Tensor` of shape \"[batch, length, depth]`\n\nReturns:\n a tensor with shape [batch, num_experts, expert_capacity, depth]", "source": "juraj_google_style"} +{"code": "def _verify_required_claims_exist(jwt_claims):\n\n for claim_name in [u\"aud\", u\"exp\", u\"iss\", u\"sub\"]:\n if claim_name not in jwt_claims:\n raise suppliers.UnauthenticatedException(u'Missing \"%s\" claim' % claim_name)", "docstring": "Verifies that the required claims exist.\n\nArgs:\n jwt_claims: the JWT claims to be verified.\n\nRaises:\n UnauthenticatedException: if some claim doesn't exist.", "source": "juraj_google_style"} +{"code": "def get_groups(self, **kwargs):\n\n # Endpoint parameters\n params = {\n 'cultureInfo': util.language_code(kwargs.get('lang'))\n }\n\n # Request\n result = self.make_request('geo', 'get_groups', **params)\n\n if not util.check_result(result):\n return False, result.get('resultDescription', 'UNKNOWN ERROR')\n\n # Parse\n values = util.response_list(result, 'resultValues')\n return True, [emtype.GeoGroupItem(**a) for a in values]", "docstring": "Obtain line types and details.\n\nArgs:\n lang (str): Language code (*es* or *en*).\n\nReturns:\n Status boolean and parsed response (list[GeoGroupItem]), or message\n string in case of error.", "source": "juraj_google_style"} +{"code": "def initialize_environments(self, batch_size=1):\n\n assert batch_size >= 1\n self._batch_size = batch_size\n\n self._envs = [gym.make(self.base_env_name) for _ in range(batch_size)]\n if self._env_wrapper_fn is not None:\n self._envs = list(map(self._env_wrapper_fn, self._envs))\n\n # If self.observation_space and self.action_space aren't None, then it means\n # that this is a re-initialization of this class, in that case make sure\n # that this matches our previous behaviour.\n if self._observation_space:\n assert str(self._observation_space) == str(\n self._envs[0].observation_space)\n else:\n # This means that we are initializing this class for the first time.\n #\n # We set this equal to the first env's observation space, later on we'll\n # verify that all envs have the same observation space.\n self._observation_space = self._envs[0].observation_space\n\n # Similarly for action_space\n if self._action_space:\n assert str(self._action_space) == str(self._envs[0].action_space)\n else:\n self._action_space = self._envs[0].action_space\n\n self._verify_same_spaces()\n\n # If self.reward_range is None, i.e. this means that we should take the\n # reward range of the env.\n if self.reward_range is None:\n self._reward_range = self._envs[0].reward_range\n\n # This data structure stores the history of each env.\n #\n # NOTE: Even if the env is a NN and can step in all batches concurrently, it\n # is still valuable to store the trajectories separately.\n self._trajectories = trajectory.BatchTrajectory(batch_size=batch_size)", "docstring": "Initializes the environments and trajectories.\n\n Subclasses can override this if they don't want a default implementation\n which initializes `batch_size` environments, but must take care to\n initialize self._trajectories (this is checked in __init__ anyways).\n\nArgs:\n batch_size: (int) Number of `self.base_env_name` envs to initialize.", "source": "juraj_google_style"} +{"code": "def encode_fetch_request(cls, payloads=(), max_wait_time=100, min_bytes=4096):\n\n return kafka.protocol.fetch.FetchRequest[0](\n replica_id=-1,\n max_wait_time=max_wait_time,\n min_bytes=min_bytes,\n topics=[(\n topic,\n [(\n partition,\n payload.offset,\n payload.max_bytes)\n for partition, payload in topic_payloads.items()])\n for topic, topic_payloads in group_by_topic_and_partition(payloads).items()])", "docstring": "Encodes a FetchRequest struct\n\nArgs:\n payloads: list of FetchRequestPayload\n max_wait_time (int, optional): ms to block waiting for min_bytes\n data. Defaults to 100.\n min_bytes (int, optional): minimum bytes required to return before\n max_wait_time. Defaults to 4096.\n\n Return: FetchRequest", "source": "juraj_google_style"} +{"code": "def start_naive_bayes(automated_run, session, path):\n\n module = functions.import_string_code_as_module(automated_run.source)\n random_state = 8 if not hasattr(module, 'random_state') else module.random_state\n assert module.metric_to_optimize in automated_run.base_learner_origin.metric_generators\n\n # get non-searchable parameters\n base_estimator = automated_run.base_learner_origin.return_estimator()\n base_estimator.set_params(**module.default_params)\n default_params = functions.make_serializable(base_estimator.get_params())\n non_searchable_params = dict((key, val) for key, val in iteritems(default_params)\n if key not in module.pbounds)\n\n # get already calculated base learners in search space\n existing_base_learners = []\n for base_learner in automated_run.base_learner_origin.base_learners:\n if not base_learner.job_status == 'finished':\n continue\n in_search_space = True\n for key, val in iteritems(non_searchable_params):\n if base_learner.hyperparameters[key] != val:\n in_search_space = False\n break # If no match, move on to the next base learner\n if in_search_space:\n existing_base_learners.append(base_learner)\n\n # build initialize dictionary\n target = []\n initialization_dict = dict((key, list()) for key in module.pbounds.keys())\n for base_learner in existing_base_learners:\n # check if base learner's searchable hyperparameters are all numerical\n all_numerical = True\n for key in module.pbounds.keys():\n if not isinstance(base_learner.hyperparameters[key], numbers.Number):\n all_numerical = False\n break\n if not all_numerical:\n continue # if there is a non-numerical hyperparameter, skip this.\n\n for key in module.pbounds.keys():\n initialization_dict[key].append(base_learner.hyperparameters[key])\n target.append(base_learner.individual_score[module.metric_to_optimize])\n initialization_dict['target'] = target if not module.invert_metric \\\n else list(map(lambda x: -x, target))\n print('{} existing in initialization dictionary'.\n format(len(initialization_dict['target'])))\n\n # Create function to be optimized\n func_to_optimize = return_func_to_optimize(\n path, session, automated_run.base_learner_origin, module.default_params,\n module.metric_to_optimize, module.invert_metric, set(module.integers)\n )\n\n # Create Bayes object\n bo = BayesianOptimization(func_to_optimize, module.pbounds)\n\n bo.initialize(initialization_dict)\n\n np.random.seed(random_state)\n\n bo.maximize(**module.maximize_config)", "docstring": "Starts naive bayes automated run\n\nArgs:\n automated_run (xcessiv.models.AutomatedRun): Automated run object\n\n session: Valid SQLAlchemy session\n\n path (str, unicode): Path to project folder", "source": "juraj_google_style"} +{"code": "def yiq_to_rgb(y, i=None, q=None):\n\n if type(y) in [list,tuple]:\n y, i, q = y\n r = y + (i * 0.9562) + (q * 0.6210)\n g = y - (i * 0.2717) - (q * 0.6485)\n b = y - (i * 1.1053) + (q * 1.7020)\n return (r, g, b)", "docstring": "Convert the color from YIQ coordinates to RGB.\n\n Parameters:\n :y:\n Tte Y component value [0...1]\n :i:\n The I component value [0...1]\n :q:\n The Q component value [0...1]\n\nReturns:\n The color as an (r, g, b) tuple in the range:\n r[0...1],\n g[0...1],\n b[0...1]\n\n >>> '({}, {}, {})'.format(*[round(v, 6) for v in yiq_to_rgb(0.592263, 0.458874, -0.0499818)])\n '(1.0, 0.5, 1e-06)'", "source": "juraj_google_style"} +{"code": "def set_video_pos(self, x1, y1, x2, y2):\n\n position = \"%s %s %s %s\" % (str(x1),str(y1),str(x2),str(y2))\n self._player_interface.VideoPos(ObjectPath('/not/used'), String(position))", "docstring": "Set the video position on the screen\n\nArgs:\n x1 (int): Top left x coordinate (px)\n y1 (int): Top left y coordinate (px)\n x2 (int): Bottom right x coordinate (px)\n y2 (int): Bottom right y coordinate (px)", "source": "juraj_google_style"} +{"code": "def upsert_variant(self, variant_obj):\n\n LOG.debug(\"Upserting variant %s\", variant_obj['_id'])\n try:\n result = self.variant_collection.insert_one(variant_obj)\n except DuplicateKeyError as err:\n LOG.debug(\"Variant %s already exists in database\", variant_obj['_id'])\n result = self.variant_collection.find_one_and_update(\n {'_id': variant_obj['_id']},\n {\n '$set': {\n 'compounds': variant_obj.get('compounds',[])\n }\n }\n )\n variant = self.variant_collection.find_one({'_id': variant_obj['_id']})\n return result", "docstring": "Load a variant object, if the object already exists update compounds.\n\nArgs:\n variant_obj(dict)\n\nReturns:\n result", "source": "juraj_google_style"} +{"code": "def make_lda_variational(activation, num_topics, layer_sizes):\n\n encoder_net = tf.keras.Sequential()\n for num_hidden_units in layer_sizes:\n encoder_net.add(\n tf.keras.layers.Dense(\n num_hidden_units,\n activation=activation,\n kernel_initializer=tf.compat.v1.glorot_normal_initializer()))\n encoder_net.add(\n tf.keras.layers.Dense(\n num_topics,\n activation=tf.nn.softplus,\n kernel_initializer=tf.compat.v1.glorot_normal_initializer()))\n\n def lda_variational(bag_of_words):\n concentration = _clip_dirichlet_parameters(encoder_net(bag_of_words))\n return ed.Dirichlet(concentration=concentration, name=\"topics_posterior\")\n\n return lda_variational", "docstring": "Creates the variational distribution for LDA.\n\nArgs:\n activation: Activation function to use.\n num_topics: The number of topics.\n layer_sizes: The number of hidden units per layer in the encoder.\n\nReturns:\n lda_variational: A function that takes a bag-of-words Tensor as\n input and returns a distribution over topics.", "source": "juraj_google_style"} +{"code": "def compare(expr, value, regex_expr=False):\n\n # Strict equality comparison\n if expr == value:\n return True\n\n # Infer negate expression to match, if needed\n negate = False\n if isinstance(expr, str):\n negate = expr.startswith(NEGATE)\n expr = strip_negate(expr) if negate else expr\n\n try:\n # RegExp or strict equality comparison\n test(expr, value, regex_expr=regex_expr)\n except Exception as err:\n if negate:\n return True\n else:\n raise err\n\n return True", "docstring": "Compares an string or regular expression againast a given value.\n\nArgs:\n expr (str|regex): string or regular expression value to compare.\n value (str): value to compare against to.\n regex_expr (bool, optional): enables string based regex matching.\n\nRaises:\n AssertionError: in case of assertion error.\n\nReturns:\n bool", "source": "juraj_google_style"} +{"code": "def _kl_half_normal_half_normal(a, b, name=None):\n\n with tf.name_scope(name or \"kl_half_normal_half_normal\"):\n # Consistent with\n # http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 119\n return (tf.math.log(b.scale) - tf.math.log(a.scale) +\n (a.scale**2 - b.scale**2) / (2 * b.scale**2))", "docstring": "Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.\n\nArgs:\n a: Instance of a `HalfNormal` distribution object.\n b: Instance of a `HalfNormal` distribution object.\n name: (optional) Name to use for created operations.\n default is \"kl_half_normal_half_normal\".\n\nReturns:\n Batchwise KL(a || b)", "source": "juraj_google_style"} +{"code": "def __init__(self, conv_sizes, dense_sizes, scope='cnn-baseline', summary_labels=()):\n\n\n network = []\n for size in conv_sizes:\n network.append(dict(type='conv2d', size=size))\n\n # First layer has a larger window.\n network[0]['window'] = 5\n\n network.append(dict(type='flatten')) # TODO: change to max pooling!\n for size in dense_sizes:\n network.append(dict(type='dense', size=size))\n\n super(CNNBaseline, self).__init__(network=network, scope=scope, summary_labels=summary_labels)", "docstring": "CNN baseline.\n\nArgs:\n conv_sizes: List of convolutional layer sizes\n dense_sizes: List of dense layer sizes", "source": "juraj_google_style"} +{"code": "def extremum_icohpvalue(self, summed_spin_channels=True, spin=Spin.up):\n\n if not self._are_coops:\n extremum = sys.float_info.max\n else:\n extremum = -sys.float_info.max\n\n if not self._is_spin_polarized:\n if spin == Spin.down:\n warnings.warn(\"This spin channel does not exist. I am switching to Spin.up\")\n spin = Spin.up\n\n for value in self._icohplist.values():\n if not value.is_spin_polarized or not summed_spin_channels:\n if not self._are_coops:\n if value.icohpvalue(spin) < extremum:\n extremum = value.icohpvalue(spin)\n # print(extremum)\n else:\n if value.icohpvalue(spin) > extremum:\n extremum = value.icohpvalue(spin)\n # print(extremum)\n else:\n if not self._are_coops:\n if value.summed_icohp < extremum:\n extremum = value.summed_icohp\n # print(extremum)\n else:\n if value.summed_icohp > extremum:\n extremum = value.summed_icohp\n # print(extremum)\n return extremum", "docstring": "get ICOHP/ICOOP of strongest bond\n\nArgs:\n summed_spin_channels: Boolean to indicate whether the ICOHPs/ICOOPs of both spin channels should be summed\n\n spin: if summed_spin_channels is equal to False, this spin indicates which spin channel should be returned\n\nReturns:\n lowest ICOHP/largest ICOOP value (i.e. ICOHP/ICOOP value of strongest bond)", "source": "juraj_google_style"} +{"code": "def _base_query(self, session):\n\n return session.query(ORMTargetMarker) \\\n .filter(ORMTargetMarker.name == self.name) \\\n .filter(ORMTargetMarker.params == self.params)", "docstring": "Base query for a target.\n\nArgs:\n session: database session to query in", "source": "juraj_google_style"} +{"code": "def entry(bucket, key):\n\n if key is None:\n return urlsafe_base64_encode('{0}'.format(bucket))\n else:\n return urlsafe_base64_encode('{0}:{1}'.format(bucket, key))", "docstring": "计算七牛API中的数据格式:\n\n entry规格参考 https://developer.qiniu.com/kodo/api/1276/data-format\n\nArgs:\n bucket: 待操作的空间名\n key: 待操作的文件名\n\nReturns:\n 符合七牛API规格的数据格式", "source": "juraj_google_style"} +{"code": "def flp_nonlinear_soco(I,J,d,M,f,c):\n\n model = Model(\"nonlinear flp -- soco formulation\")\n\n x,X,u = {},{},{}\n for j in J:\n X[j] = model.addVar(ub=M[j], vtype=\"C\", name=\"X(%s)\"%j) # for sum_i x_ij\n u[j] = model.addVar(vtype=\"C\", name=\"u(%s)\"%j) # for replacing sqrt sum_i x_ij in soco\n for i in I:\n x[i,j] = model.addVar(vtype=\"B\", name=\"x(%s,%s)\"%(i,j)) # i's demand satisfied from j\n\n # constraints for customer's demand satisfaction\n for i in I:\n model.addCons(quicksum(x[i,j] for j in J) == 1, \"Demand(%s)\"%i)\n\n for j in J:\n model.addCons(quicksum(d[i]*x[i,j] for i in I) == X[j], \"Capacity(%s)\"%j)\n model.addQConstr(quicksum(f[j]**2*d[i]*x[i,j]*x[i,j] for i in I) <= u[j]*u[j], \"SOC(%s)\"%j)\n\n model.setObjective(quicksum(u[j] for j in J) +\\\n quicksum(c[i,j]*d[i]*x[i,j] for j in J for i in I),\\\n \"minimize\")\n\n model.data = x,u\n return model", "docstring": "flp_nonlinear_soco -- use\n Parameters:\n - I: set of customers\n - J: set of facilities\n - d[i]: demand for product i\n - M[j]: capacity of facility j\n - f[j]: fixed cost for using a facility in point j\n - c[i,j]: unit cost of servicing demand point i from facility j\n Returns a model, ready to be solved.", "source": "juraj_google_style"} +{"code": "def StatEntryFromStat(stat,\n pathspec,\n ext_attrs = True):\n\n result = rdf_client_fs.StatEntry(pathspec=pathspec)\n\n for attr in _STAT_ATTRS:\n value = getattr(stat.GetRaw(), attr, None)\n if value is None:\n continue\n\n # TODO(hanuszczak): Why are we doing this?\n value = int(value)\n if value < 0:\n value &= 0xFFFFFFFF\n\n setattr(result, attr, value)\n\n result.st_flags_linux = stat.GetLinuxFlags()\n result.st_flags_osx = stat.GetOsxFlags()\n if ext_attrs:\n # TODO(hanuszczak): Can we somehow incorporate extended attribute getter to\n # the `Stat` class? That would make the code a lot prettier but would force\n # `utils` to depend on `xattrs`.\n result.ext_attrs = list(GetExtAttrs(stat.GetPath()))\n\n return result", "docstring": "Build a stat entry object from a given stat object.\n\nArgs:\n stat: A `Stat` object.\n pathspec: A `PathSpec` from which `stat` was obtained.\n ext_attrs: Whether to include extended file attributes in the result.\n\nReturns:\n `StatEntry` object.", "source": "juraj_google_style"} +{"code": "def show_inputs(self, varnames=None, nids=None, wslice=None, stream=sys.stdout):\n\n if varnames is not None:\n # Build dictionary varname --> [(task1, value), (task2, value), ...]\n varnames = [s.strip() for s in list_strings(varnames)]\n dlist = collections.defaultdict(list)\n for task in self.select_tasks(nids=nids, wslice=wslice):\n dstruct = task.input.structure.as_dict(fmt=\"abivars\")\n\n for vname in varnames:\n value = task.input.get(vname, None)\n if value is None: # maybe in structure?\n value = dstruct.get(vname, None)\n if value is not None:\n dlist[vname].append((task, value))\n\n for vname in varnames:\n tv_list = dlist[vname]\n if not tv_list:\n stream.write(\"[%s]: Found 0 tasks with this variable\\n\" % vname)\n else:\n stream.write(\"[%s]: Found %s tasks with this variable\\n\" % (vname, len(tv_list)))\n for i, (task, value) in enumerate(tv_list):\n stream.write(\" %s --> %s\\n\" % (str(value), task))\n stream.write(\"\\n\")\n\n else:\n lines = []\n for task in self.select_tasks(nids=nids, wslice=wslice):\n s = task.make_input(with_header=True)\n\n # Add info on dependencies.\n if task.deps:\n s += \"\\n\\nDependencies:\\n\" + \"\\n\".join(str(dep) for dep in task.deps)\n else:\n s += \"\\n\\nDependencies: None\"\n\n lines.append(2*\"\\n\" + 80 * \"=\" + \"\\n\" + s + 2*\"\\n\")\n\n stream.writelines(lines)", "docstring": "Print the input of the tasks to the given stream.\n\nArgs:\n varnames:\n List of Abinit variables. If not None, only the variable in varnames\n are selected and printed.\n nids:\n List of node identifiers. By defaults all nodes are shown\n wslice:\n Slice object used to select works.\n stream:\n File-like object, Default: sys.stdout", "source": "juraj_google_style"} +{"code": "def QA_SU_save_index_min(engine, client=DATABASE):\n\n\n engine = select_save_engine(engine)\n engine.QA_SU_save_index_min(client=client)", "docstring": "save index_min\n\nArgs:\n engine {[type]} -- [description]\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})", "source": "juraj_google_style"} +{"code": "def _slice_single_param(param, param_event_ndims, slices, dist_batch_shape):\n\n # Extend param shape with ones on the left to match dist_batch_shape.\n param_shape = tf.shape(input=param)\n insert_ones = tf.ones(\n [tf.size(input=dist_batch_shape) + param_event_ndims - tf.rank(param)],\n dtype=param_shape.dtype)\n new_param_shape = tf.concat([insert_ones, param_shape], axis=0)\n full_batch_param = tf.reshape(param, new_param_shape)\n param_slices = []\n # We separately track the batch axis from the parameter axis because we want\n # them to align for positive indexing, and be offset by param_event_ndims for\n # negative indexing.\n param_dim_idx = 0\n batch_dim_idx = 0\n for slc in slices:\n if slc is tf.newaxis:\n param_slices.append(slc)\n continue\n if slc is Ellipsis:\n if batch_dim_idx < 0:\n raise ValueError('Found multiple `...` in slices {}'.format(slices))\n param_slices.append(slc)\n # Switch over to negative indexing for the broadcast check.\n num_remaining_non_newaxis_slices = sum(\n [s is not tf.newaxis for s in slices[slices.index(Ellipsis) + 1:]])\n batch_dim_idx = -num_remaining_non_newaxis_slices\n param_dim_idx = batch_dim_idx - param_event_ndims\n continue\n # Find the batch dimension sizes for both parameter and distribution.\n param_dim_size = new_param_shape[param_dim_idx]\n batch_dim_size = dist_batch_shape[batch_dim_idx]\n is_broadcast = batch_dim_size > param_dim_size\n # Slices are denoted by start:stop:step.\n if isinstance(slc, slice):\n start, stop, step = slc.start, slc.stop, slc.step\n if start is not None:\n start = tf.where(is_broadcast, 0, start)\n if stop is not None:\n stop = tf.where(is_broadcast, 1, stop)\n if step is not None:\n step = tf.where(is_broadcast, 1, step)\n param_slices.append(slice(start, stop, step))\n else: # int, or int Tensor, e.g. d[d.batch_shape_tensor()[0] // 2]\n param_slices.append(tf.where(is_broadcast, 0, slc))\n param_dim_idx += 1\n batch_dim_idx += 1\n param_slices.extend([ALL_SLICE] * param_event_ndims)\n return full_batch_param.__getitem__(param_slices)", "docstring": "Slices a single parameter of a distribution.\n\nArgs:\n param: A `Tensor`, the original parameter to slice.\n param_event_ndims: `int` event parameterization rank for this parameter.\n slices: A `tuple` of normalized slices.\n dist_batch_shape: The distribution's batch shape `Tensor`.\n\nReturns:\n new_param: A `Tensor`, batch-sliced according to slices.", "source": "juraj_google_style"} +{"code": "def bbox_scaling(bboxes, scale, clip_shape=None):\n\n if float(scale) == 1.0:\n scaled_bboxes = bboxes.copy()\n else:\n w = bboxes[..., 2] - bboxes[..., 0] + 1\n h = bboxes[..., 3] - bboxes[..., 1] + 1\n dw = (w * (scale - 1)) * 0.5\n dh = (h * (scale - 1)) * 0.5\n scaled_bboxes = bboxes + np.stack((-dw, -dh, dw, dh), axis=-1)\n if clip_shape is not None:\n return bbox_clip(scaled_bboxes, clip_shape)\n else:\n return scaled_bboxes", "docstring": "Scaling bboxes w.r.t the box center.\n\nArgs:\n bboxes (ndarray): Shape(..., 4).\n scale (float): Scaling factor.\n clip_shape (tuple, optional): If specified, bboxes that exceed the\n boundary will be clipped according to the given shape (h, w).\n\nReturns:\n ndarray: Scaled bboxes.", "source": "juraj_google_style"} +{"code": "def unique_list(seq: Iterable[Any]) -> List[Any]:\n # noqa\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]", "docstring": "Returns a list of all the unique elements in the input list.\n\nArgs:\n seq: input list\n\nReturns:\n list of unique elements\n\n As per\n http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order", "source": "juraj_google_style"} +{"code": "def update_with_result(self, result):\n\n\n assert isinstance(result, dict), \"%s is not a dictionary\" % result\n\n for type in (\"instance\", \"plugin\"):\n id = (result[type] or {}).get(\"id\")\n\n is_context = not id\n if is_context:\n item = self.instances[0]\n else:\n item = self.items.get(id)\n\n if item is None:\n # If an item isn't there yet\n # no worries. It's probably because\n # reset is still running and the\n # item in question is a new instance\n # not yet added to the model.\n continue\n\n item.isProcessing = False\n item.currentProgress = 1\n item.processed = True\n item.hasWarning = item.hasWarning or any([\n record[\"levelno\"] == logging.WARNING\n for record in result[\"records\"]\n ])\n\n if result.get(\"error\"):\n item.hasError = True\n item.amountFailed += 1\n\n else:\n item.succeeded = True\n item.amountPassed += 1\n\n item.duration += result[\"duration\"]\n item.finishedAt = time.time()\n\n if item.itemType == \"plugin\" and not item.actionsIconVisible:\n\n actions = list(item.actions)\n\n # Context specific actions\n for action in list(actions):\n if action[\"on\"] == \"failed\" and not item.hasError:\n actions.remove(action)\n if action[\"on\"] == \"succeeded\" and not item.succeeded:\n actions.remove(action)\n if action[\"on\"] == \"processed\" and not item.processed:\n actions.remove(action)\n\n if actions:\n item.actionsIconVisible = True\n\n # Update section item\n class DummySection(object):\n hasWarning = False\n hasError = False\n succeeded = False\n\n section_item = DummySection()\n for section in self.sections:\n if item.itemType == \"plugin\" and section.name == item.verb:\n section_item = section\n if (item.itemType == \"instance\" and\n section.name == item.category):\n section_item = section\n\n section_item.hasWarning = (\n section_item.hasWarning or item.hasWarning\n )\n section_item.hasError = section_item.hasError or item.hasError\n section_item.succeeded = section_item.succeeded or item.succeeded\n section_item.isProcessing = False", "docstring": "Update item-model with result from host\n\n State is sent from host after processing had taken place\n and represents the events that took place; including\n log messages and completion status.\n\nArgs:\n result (dict): Dictionary following the Result schema", "source": "juraj_google_style"} +{"code": "def _validate_first_message(cls, msg):\n\n data = cls._unpack_message(msg)\n logger.debug(data)\n if data != cls.RTM_HANDSHAKE:\n raise SlackApiError('Unexpected response: {!r}'.format(data))\n logger.info('Joined real-time messaging.')", "docstring": "Check the first message matches the expected handshake.\n\nNote:\n The handshake is provided as :py:attr:`RTM_HANDSHAKE`.\n\nArgs:\n msg (:py:class:`aiohttp.Message`): The message to validate.\n\nRaises:\n :py:class:`SlackApiError`: If the data doesn't match the\n expected handshake.", "source": "juraj_google_style"} +{"code": "def multiply(self, other):\n\n if not isinstance(other, Number):\n raise QiskitError(\"other is not a number\")\n return Chi(other * self._data, self._input_dims, self._output_dims)", "docstring": "Return the QuantumChannel self + other.\n\nArgs:\n other (complex): a complex number.\n\nReturns:\n Chi: the scalar multiplication other * self as a Chi object.\n\nRaises:\n QiskitError: if other is not a valid scalar.", "source": "juraj_google_style"} +{"code": "def get_forced_variation(self, experiment_key, user_id):\n\n\n if user_id not in self.forced_variation_map:\n self.logger.debug('User \"%s\" is not in the forced variation map.' % user_id)\n return None\n\n experiment = self.get_experiment_from_key(experiment_key)\n if not experiment:\n # The invalid experiment key will be logged inside this call.\n return None\n\n experiment_to_variation_map = self.forced_variation_map.get(user_id)\n\n if not experiment_to_variation_map:\n self.logger.debug('No experiment \"%s\" mapped to user \"%s\" in the forced variation map.' % (\n experiment_key,\n user_id\n ))\n return None\n\n variation_id = experiment_to_variation_map.get(experiment.id)\n if variation_id is None:\n self.logger.debug(\n 'No variation mapped to experiment \"%s\" in the forced variation map.' % experiment_key\n )\n return None\n\n variation = self.get_variation_from_id(experiment_key, variation_id)\n\n self.logger.debug('Variation \"%s\" is mapped to experiment \"%s\" and user \"%s\" in the forced variation map' % (\n variation.key,\n experiment_key,\n user_id\n ))\n return variation", "docstring": "Gets the forced variation key for the given user and experiment.\n\nArgs:\n experiment_key: Key for experiment.\n user_id: The user ID.\n\nReturns:\n The variation which the given user and experiment should be forced into.", "source": "juraj_google_style"} +{"code": "def apply_mutation(module_path, operator, occurrence):\n\n module_ast = get_ast(module_path, python_version=operator.python_version)\n original_code = module_ast.get_code()\n visitor = MutationVisitor(occurrence, operator)\n mutated_ast = visitor.walk(module_ast)\n\n mutated_code = None\n if visitor.mutation_applied:\n mutated_code = mutated_ast.get_code()\n with module_path.open(mode='wt', encoding='utf-8') as handle:\n handle.write(mutated_code)\n handle.flush()\n\n return original_code, mutated_code", "docstring": "Apply a specific mutation to a file on disk.\n\nArgs:\n module_path: The path to the module to mutate.\n operator: The `operator` instance to use.\n occurrence: The occurrence of the operator to apply.\n\n Returns: A `(unmutated-code, mutated-code)` tuple to the with-block. If there was\n no mutation performed, the `mutated-code` is `None`.", "source": "juraj_google_style"} +{"code": "def is_github_task(task):\n\n return any((\n # XXX Cron tasks don't usually define 'taskcluster-github' as their schedulerId as they\n # are scheduled within another Taskcluster task.\n task.get('schedulerId') == 'taskcluster-github',\n # XXX Same here, cron tasks don't start with github\n task.get('extra', {}).get('tasks_for', '').startswith('github-'),\n is_github_url(task.get('metadata', {}).get('source', '')),\n ))", "docstring": "Determine if a task is related to GitHub.\n\n This function currently looks into the ``schedulerId``, ``extra.tasks_for``, and\n ``metadata.source``.\n\nArgs:\n task (dict): the task definition to check.\n\nReturns:\n bool: True if a piece of data refers to GitHub", "source": "juraj_google_style"} +{"code": "def state_province_region(self, value=None):\n\n if value is not None:\n try:\n value = str(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type str '\n 'for field `state_province_region`'.format(value))\n if ',' in value:\n raise ValueError('value should not contain a comma '\n 'for field `state_province_region`')\n\n self._state_province_region = value", "docstring": "Corresponds to IDD Field `state_province_region`\n\nArgs:\n value (str): value for IDD Field `state_province_region`\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def from_str(cls, label: str) -> int:\n\n label_norm = label.replace('1', 'one').upper()\n if label_norm in cls.__members__:\n return DecayType[label_norm]\n else:\n raise NotImplementedError", "docstring": "Convert given string label of decay type to special index\n\nArgs:\n label: name of decay type.\n Set of values: `\"linear\"`, `\"cosine\"`, `\"exponential\"`,\n `\"onecycle\"`, `\"trapezoid\"`, `[\"polynomial\", K]`, where K is a polynomial power\n\nReturns:\n index of decay type", "source": "juraj_google_style"} +{"code": "def is_spontaneous(gene, custom_id=None):\n\n\n spont = re.compile(\"[Ss](_|)0001\")\n if spont.match(gene.id):\n return True\n elif gene.id == custom_id:\n return True\n else:\n return False", "docstring": "Input a COBRApy Gene object and check if the ID matches a spontaneous ID regex.\n\nArgs:\n gene (Gene): COBRApy Gene\n custom_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``\n\nReturns:\n bool: If gene ID matches spontaneous ID", "source": "juraj_google_style"} +{"code": "def reverse_taskname(name: str) -> str:\n\n components = name.split('.')\n assert len(components) <= 3\n return '.'.join(components[::-1])", "docstring": "Reverses components in the name of task. Reversed convention is used for filenames since\n it groups log/scratch files of related tasks together\n\n 0.somejob.somerun -> somerun.somejob.0\n 0.somejob -> somejob.0\n somename -> somename\n\nArgs:\n name: name of task", "source": "juraj_google_style"} +{"code": "def _on_write_request(self, request):\n\n if request['connection_handle'] != self._connection_handle:\n return False\n\n attribute_handle = request['attribute_handle']\n\n # If write to configure notification\n config_handles = [\n ReceiveHeaderChar.config_handle,\n ReceivePayloadChar.config_handle,\n StreamingChar.config_handle,\n TracingChar.config_handle\n ]\n if attribute_handle in config_handles:\n notification_enabled, _ = struct.unpack(' str:\n\n if isinstance(auth, Mapping):\n # Validate the JSON format only.\n if \"identitytoken\" in auth:\n pass\n elif \"auth\" in auth:\n return compose_auth_header(auth[\"auth\"], registry_addr)\n else:\n if registry_addr:\n auth[\"serveraddress\"] = registry_addr\n auth_json = json.dumps(auth).encode(\"utf-8\")\n elif isinstance(auth, (str, bytes)):\n # Parse simple \"username:password\"-formatted strings\n # and attach the server address specified.\n if isinstance(auth, bytes):\n auth = auth.decode(\"utf-8\")\n s = base64.b64decode(auth)\n username, passwd = s.split(b\":\", 1)\n config = {\n \"username\": username.decode(\"utf-8\"),\n \"password\": passwd.decode(\"utf-8\"),\n \"email\": None,\n \"serveraddress\": registry_addr,\n }\n auth_json = json.dumps(config).encode(\"utf-8\")\n else:\n raise TypeError(\"auth must be base64 encoded string/bytes or a dictionary\")\n auth = base64.b64encode(auth_json).decode(\"ascii\")\n return auth", "docstring": "Validate and compose base64-encoded authentication header\n with an optional support for parsing legacy-style \"user:password\"\n strings.\n\nArgs:\n auth: Authentication information\n registry_addr: An address of the registry server\n\nReturns:\n A base64-encoded X-Registry-Auth header value", "source": "juraj_google_style"} +{"code": "def passthrough_context_definition(context_params):\n\n\n check.inst_param(context_params, 'context', ExecutionContext)\n context_definition = PipelineContextDefinition(context_fn=lambda *_args: context_params)\n return {DEFAULT_CONTEXT_NAME: context_definition}", "docstring": "Create a context definition from a pre-existing context. This can be useful\n in testing contexts where you may want to create a context manually and then\n pass it into a one-off PipelineDefinition\n\nArgs:\n context (ExecutionContext): The context that will provided to the pipeline.\n\nReturns:\n PipelineContextDefinition: The passthrough context definition.", "source": "juraj_google_style"} +{"code": "def reduce(x, op='sum'):\n\n import warnings\n warnings.warn(\n \"Deprecated API. Use ``sum`` or ``mean`` instead.\", DeprecationWarning)\n from .function_bases import reduce_sum, reduce_mean\n if op == 'sum':\n return reduce_sum(x)\n elif op == 'mean':\n return reduce_mean(x)\n raise ValueError()", "docstring": "Reduction function with given operation.\n\nArgs:\n x (Variable): An input.\n op (str): 'sum' or 'mean'.\n\nNote:\n This is deprecated. Use ``mean`` or ``sum`` instead.", "source": "juraj_google_style"} +{"code": "def usergroups_users_update(\n self, *, usergroup: str, users: List[str], **kwargs\n ) -> SlackResponse:\n\n self._validate_xoxp_token()\n kwargs.update({\"usergroup\": usergroup, \"users\": users})\n return self.api_call(\"usergroups.users.update\", json=kwargs)", "docstring": "Update the list of users for a User Group\n\nArgs:\n usergroup (str): The encoded ID of the User Group to update.\n e.g. 'S0604QSJC'\n users (list): A list user IDs that represent the entire list of\n users for the User Group. e.g. ['U060R4BJ4', 'U060RNRCZ']", "source": "juraj_google_style"} +{"code": "def _validate_observation_data(\n kernel, observation_index_points, observations):\n\n # Check that observation index points and observation counts broadcast.\n ndims = kernel.feature_ndims\n if (tensorshape_util.is_fully_defined(\n observation_index_points.shape[:-ndims]) and\n tensorshape_util.is_fully_defined(observations.shape)):\n index_point_count = observation_index_points.shape[:-ndims]\n observation_count = observations.shape\n try:\n tf.broadcast_static_shape(index_point_count, observation_count)\n except ValueError:\n # Re-raise with our own more contextual error message.\n raise ValueError(\n 'Observation index point and observation counts are not '\n 'broadcastable: {} and {}, respectively.'.format(\n index_point_count, observation_count))", "docstring": "Ensure that observation data and locations have consistent shapes.\n\n This basically means that the batch shapes are broadcastable. We can only\n ensure this when those shapes are fully statically defined.\n\nArgs:\n kernel: The GP kernel.\n observation_index_points: the observation data locations in the index set.\n observations: the observation data.\n\nRaises:\n ValueError: if the observations' batch shapes are not broadcastable.", "source": "juraj_google_style"} +{"code": "def GetServicePeriodsActiveEachDate(self, date_start, date_end):\n\n date_it = date_start\n one_day = datetime.timedelta(days=1)\n date_service_period_list = []\n while date_it < date_end:\n periods_today = []\n date_it_string = date_it.strftime(\"%Y%m%d\")\n for service in self.GetServicePeriodList():\n if service.IsActiveOn(date_it_string, date_it):\n periods_today.append(service)\n date_service_period_list.append((date_it, periods_today))\n date_it += one_day\n return date_service_period_list", "docstring": "Return a list of tuples (date, [period1, period2, ...]).\n\n For each date in the range [date_start, date_end) make list of each\n ServicePeriod object which is active.\n\nArgs:\n date_start: The first date in the list, a date object\n date_end: The first date after the list, a date object\n\nReturns:\n A list of tuples. Each tuple contains a date object and a list of zero or\n more ServicePeriod objects.", "source": "juraj_google_style"} +{"code": "def note_list(self, body_matches=None, post_id=None, post_tags_match=None,\n creator_name=None, creator_id=None, is_active=None):\n\n params = {\n 'search[body_matches]': body_matches,\n 'search[post_id]': post_id,\n 'search[post_tags_match]': post_tags_match,\n 'search[creator_name]': creator_name,\n 'search[creator_id]': creator_id,\n 'search[is_active]': is_active\n }\n return self._get('notes.json', params)", "docstring": "Return list of notes.\n\n Parameters:\n body_matches (str): The note's body matches the given terms.\n post_id (int): A specific post.\n post_tags_match (str): The note's post's tags match the given terms.\n creator_name (str): The creator's name. Exact match.\n creator_id (int): The creator's user id.\n is_active (bool): Can be: True, False.", "source": "juraj_google_style"} +{"code": "def unset(entity, *types):\n\n if not types:\n types = (TypedField,)\n\n fields = list(entity._fields.keys())\n remove = (x for x in fields if isinstance(x, types))\n\n for field in remove:\n del entity._fields[field]", "docstring": "Unset the TypedFields on the input `entity`.\n\nArgs:\n entity: A mixbox.Entity object.\n *types: A variable-length list of TypedField subclasses. If not\n provided, defaults to TypedField.", "source": "juraj_google_style"} +{"code": "def warn(what, string, pos):\n\n\n\n\tpos = position(string, pos)\n\n\twarnings.warn(\"{0} at position {1}!\".format(what, pos), Warning)", "docstring": "Combines a warning with a call to errors.position().\n\n Simple convenience function.\n\nArgs:\n string (str): The string being parsed.\n pos (int): The index of the character that caused trouble.", "source": "juraj_google_style"} +{"code": "def shuffle_dataset(filenames, extra_fn=None):\n\n if outputs_exist(filenames):\n tf.logging.info(\"Skipping shuffle because output files exist\")\n return\n tf.logging.info(\"Shuffling data...\")\n for filename in filenames:\n _shuffle_single(filename, extra_fn=extra_fn)\n tf.logging.info(\"Data shuffled.\")", "docstring": "Shuffles the dataset.\n\nArgs:\n filenames: a list of strings\n extra_fn: an optional function from list of records to list of records\n to be called after shuffling a file.", "source": "juraj_google_style"} +{"code": "def pickupSearch(self):\n\n self.__searchJob = self.loadSavedHyperSearchJob(\n permWorkDir=self._options[\"permWorkDir\"],\n outputLabel=self._options[\"outputLabel\"])\n\n\n self.monitorSearchJob()", "docstring": "Pick up the latest search from a saved jobID and monitor it to completion\n Parameters:\n ----------------------------------------------------------------------\n retval: nothing", "source": "juraj_google_style"} +{"code": "def insert(self, loc, column, value):\n\n if is_list_like(value):\n # TODO make work with another querycompiler object as `value`.\n # This will require aligning the indices with a `reindex` and ensuring that\n # the data is partitioned identically.\n if isinstance(value, pandas.Series):\n value = value.reindex(self.index)\n value = list(value)\n\n def insert(df, internal_indices=[]):\n internal_idx = int(internal_indices[0])\n old_index = df.index\n df.index = pandas.RangeIndex(len(df.index))\n df.insert(internal_idx, internal_idx, value, allow_duplicates=True)\n df.columns = pandas.RangeIndex(len(df.columns))\n df.index = old_index\n return df\n\n new_data = self.data.apply_func_to_select_indices_along_full_axis(\n 0, insert, loc, keep_remaining=True\n )\n new_columns = self.columns.insert(loc, column)\n return self.__constructor__(new_data, self.index, new_columns)", "docstring": "Insert new column data.\n\nArgs:\n loc: Insertion index.\n column: Column labels to insert.\n value: Dtype object values to insert.\n\nReturns:\n A new PandasQueryCompiler with new data inserted.", "source": "juraj_google_style"} +{"code": "def read_file_offset(self, id, offset, limit, path=\"/\"):\n\n params = {\n \"path\": path,\n \"offset\": offset,\n \"limit\": limit\n }\n return self.request(id, params=params, method=\"get\").text", "docstring": "Read contents of a file in an allocation directory.\n\n https://www.nomadproject.io/docs/http/client-fs-cat.html\n\nArgs:\n - id: (str) allocation_id required\n - offset: (int) required\n - limit: (int) required\n - path: (str) optional\n returns: (str) text\n\nRaises:\n - nomad.api.exceptions.BaseNomadException\n - nomad.api.exceptions.BadRequestNomadException", "source": "juraj_google_style"} +{"code": "def parse(self, scope):\n\n name = ''.join(self.tokens[0])\n parsed = self.process(self.tokens[1:], scope)\n\n if name == '%(':\n name = 'sformat'\n elif name in ('~', 'e'):\n name = 'escape'\n color = Color.Color()\n args = [\n t for t in parsed\n if not isinstance(t, string_types) or t not in '(),'\n ]\n if hasattr(self, name):\n try:\n return getattr(self, name)(*args)\n except ValueError:\n pass\n\n if hasattr(color, name):\n try:\n result = getattr(color, name)(*args)\n try:\n return result + ' '\n except TypeError:\n return result\n except ValueError:\n pass\n return name + ''.join([p for p in parsed])", "docstring": "Parse Node within scope.\n the functions ~( and e( map to self.escape\n and %( maps to self.sformat\n\nArgs:\n scope (Scope): Current scope", "source": "juraj_google_style"} +{"code": "def dump_migration_session_state(raw):\n\n class BlockStyle(str): pass\n class SessionDumper(yaml.SafeDumper): pass\n def str_block_formatter(dumper, data):\n return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')\n SessionDumper.add_representer(BlockStyle, str_block_formatter)\n\n raw = deepcopy(raw)\n for step in raw:\n step['output'] = BlockStyle(step['output'])\n step['traceback'] = BlockStyle(step['traceback'])\n return yaml.dump(raw, Dumper=SessionDumper)", "docstring": "Serialize a migration session state to yaml using nicer formatting\n\nArgs:\n raw: object to serialize\n Returns: string (of yaml)\n\n Specifically, this forces the \"output\" member of state step dicts (e.g.\n state[0]['output']) to use block formatting. For example, rather than this:\n\n - migration: [app, migration_name]\n output: \"line 1\\nline2\\nline3\"\n\n You get this:\n\n - migration: [app, migration_name]\n output: |\n line 1\n line 2\n line 3", "source": "juraj_google_style"} +{"code": "def __init__(self, path, encoding='utf-8'):\n\n super(FileOutputWriter, self).__init__(encoding=encoding)\n self._file_object = None\n self._path = path", "docstring": "Initializes an output writer.\n\nArgs:\n path (str): name of the path.\n encoding (Optional[str]): input encoding.", "source": "juraj_google_style"} +{"code": "def load_data_split(proc_data_dir):\n\n ds_train = Dataset.load(path.join(proc_data_dir, 'train.bin'))\n ds_val = Dataset.load(path.join(proc_data_dir, 'val.bin'))\n ds_test = Dataset.load(path.join(proc_data_dir, 'test.bin'))\n return ds_train, ds_val, ds_test", "docstring": "Loads a split dataset\n\nArgs:\n proc_data_dir: Directory with the split and processed data\n\nReturns:\n (Training Data, Validation Data, Test Data)", "source": "juraj_google_style"} +{"code": "def __init__(self, module_to_name, members, filename_to_library_map,\n path_prefix):\n\n self._module_to_name = module_to_name\n self._members = members\n self._filename_to_library_map = filename_to_library_map\n self._path_prefix = path_prefix", "docstring": "Creates a new Index.\n\nArgs:\n module_to_name: Dictionary mapping modules to short names.\n members: Dictionary mapping member name to (fullname, member).\n filename_to_library_map: A list of (filename, Library) pairs. The order\n corresponds to the order in which the libraries appear in the index.\n path_prefix: Prefix to add to links in the index.", "source": "juraj_google_style"} +{"code": "def snyder_ac(self, structure):\n\n nsites = structure.num_sites\n volume = structure.volume\n natoms = structure.composition.num_atoms\n num_density = 1e30 * nsites / volume\n tot_mass = sum([e.atomic_mass for e in structure.species])\n avg_mass = 1.6605e-27 * tot_mass / natoms\n return 0.38483*avg_mass * \\\n ((self.long_v(structure) + 2.*self.trans_v(structure))/3.) ** 3.\\\n / (300.*num_density ** (-2./3.) * nsites ** (1./3.))", "docstring": "Calculates Snyder's acoustic sound velocity (in SI units)\n\nArgs:\n structure: pymatgen structure object\n\n Returns: Snyder's acoustic sound velocity (in SI units)", "source": "juraj_google_style"} +{"code": "def setLoggedMetrics(self, metricNames):\n\n if metricNames is None:\n self.__metricNames = set([])\n else:\n self.__metricNames = set(metricNames)", "docstring": "Tell the writer which metrics should be written\n\n Parameters:\n -----------------------------------------------------------------------\n metricsNames: A list of metric lables to be written", "source": "juraj_google_style"} +{"code": "def reviews(self, packageName, filterByDevice=False, sort=2,\n nb_results=None, offset=None):\n\n # TODO: select the number of reviews to return\n path = REVIEWS_URL + \"?doc={}&sort={}\".format(requests.utils.quote(packageName), sort)\n if nb_results is not None:\n path += \"&n={}\".format(nb_results)\n if offset is not None:\n path += \"&o={}\".format(offset)\n if filterByDevice:\n path += \"&dfil=1\"\n data = self.executeRequestApi2(path)\n output = []\n for review in data.payload.reviewResponse.getResponse.review:\n output.append(utils.parseProtobufObj(review))\n return output", "docstring": "Browse reviews for an application\n\nArgs:\n packageName (str): app unique ID.\n filterByDevice (bool): filter results for current device\n sort (int): sorting criteria (values are unknown)\n nb_results (int): max number of reviews to return\n offset (int): return reviews starting from an offset value\n\nReturns:\n dict object containing all the protobuf data returned from\n the api", "source": "juraj_google_style"} +{"code": "def form_to_params(fn=None, return_json=True):\n\n def forms_to_params_decorator(fn):\n @handle_type_error\n @wraps(fn)\n def forms_to_params_wrapper(*args, **kwargs):\n kwargs.update(\n dict(request.forms)\n )\n\n if not return_json:\n return fn(*args, **kwargs)\n\n return encode_json_body(\n fn(*args, **kwargs)\n )\n\n return forms_to_params_wrapper\n\n if fn: # python decorator with optional parameters bukkake\n return forms_to_params_decorator(fn)\n\n return forms_to_params_decorator", "docstring": "Convert bottle forms request to parameters for the wrapped function.\n\nArgs:\n return_json (bool, default True): Should the decorator automatically\n convert returned value to JSON?", "source": "juraj_google_style"} +{"code": "def Write(self, output_writer):\n\n # Round up the column sizes to the nearest tab.\n for column_index, column_size in enumerate(self._column_sizes):\n column_size, _ = divmod(column_size, self._NUMBER_OF_SPACES_IN_TAB)\n column_size = (column_size + 1) * self._NUMBER_OF_SPACES_IN_TAB\n self._column_sizes[column_index] = column_size\n\n if self._columns:\n self._WriteRow(output_writer, self._columns, in_bold=True)\n\n for values in self._rows:\n self._WriteRow(output_writer, values)", "docstring": "Writes the table to output writer.\n\nArgs:\n output_writer (CLIOutputWriter): output writer.", "source": "juraj_google_style"} +{"code": "def get_completed_task(self, task, timeout=-1):\n\n self.__wait_task_completion(task, timeout)\n\n return self.get(task)", "docstring": "Waits until the task is completed and returns the task resource.\n\nArgs:\n task: TaskResource\n timeout: Timeout in seconds\n\nReturns:\n dict: TaskResource", "source": "juraj_google_style"} +{"code": "def predict(self, X):\n\n return collections.deque(self.iter_predict(X), maxlen=1).pop()", "docstring": "Returns the predictions for ``X``.\n\n Under the hood this method simply goes through the outputs of ``iter_predict`` and returns\n the final one.\n\nArgs:\n X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.\n Sparse matrices are accepted only if they are supported by the weak model.\n\nReturns:\n array of shape (n_samples,) containing the predicted values.", "source": "juraj_google_style"} +{"code": "def save_state_regularly(self, fname, frequency=600):\n\n self.save_state(fname)\n loop = asyncio.get_event_loop()\n self.save_state_loop = loop.call_later(frequency,\n self.save_state_regularly,\n fname,\n frequency)", "docstring": "Save the state of node with a given regularity to the given\n filename.\n\nArgs:\n fname: File name to save retularly to\n frequency: Frequency in seconds that the state should be saved.\n By default, 10 minutes.", "source": "juraj_google_style"} +{"code": "def stack_call(self, *args):\n\n self.pipelined_args.append(args)\n self.number_of_stacked_calls = self.number_of_stacked_calls + 1", "docstring": "Stacks a redis command inside the object.\n\n The syntax is the same than the call() method a Client class.\n\nArgs:\n *args: full redis command as variable length argument list.\n\nExample:\n >>> pipeline = Pipeline()\n >>> pipeline.stack_call(\"HSET\", \"key\", \"field\", \"value\")\n >>> pipeline.stack_call(\"PING\")\n >>> pipeline.stack_call(\"INCR\", \"key2\")", "source": "juraj_google_style"} +{"code": "def __eq__(self, other) -> bool:\n\n if self.timeslots == other.timeslots:\n return True\n return False", "docstring": "Two time-slot collections are the same if they have the same time-slots.\n\nArgs:\n other (TimeslotCollection): other TimeslotCollection", "source": "juraj_google_style"} +{"code": "def download(timestamp, dataset, path=None, products=None,\n levels=None, offset=0):\n\n if path is None:\n path = DATA_PATH\n closest = timestamp.hour//6*6\n filename = dataset(closest, offset)\n gfs_timestamp = '%s%02d' % (timestamp.strftime('%Y%m%d'), closest)\n\n url = baseurl(gfs_timestamp, filename)\n index = url + '.idx'\n messages = message_index(index)\n segments = _filter_messages(messages, products, levels)\n dl_path = path + '/%s/' % gfs_timestamp\n _verify_path(dl_path)\n _download_segments(path + filename, url, segments)", "docstring": "save GFS grib file to DATA_PATH.\n\nArgs:\n dataset(function): naming convention function. eg. pgrb2\n timestamp(datetime): ???\n path(str): if None defaults to DATA_PATH\n products(list): TMP, etc. if None downloads all.\n layers(list): surface, etc. if None downloads all.\n offset(int): should be multiple of 3", "source": "juraj_google_style"} +{"code": "def bdp_bds_cache(func, tickers, flds, **kwargs) -> ToQuery:\n\n cache_data = []\n log_level = kwargs.get('log', logs.LOG_LEVEL)\n logger = logs.get_logger(bdp_bds_cache, level=log_level)\n kwargs['has_date'] = kwargs.pop('has_date', func == 'bds')\n kwargs['cache'] = kwargs.get('cache', True)\n\n tickers = utils.flatten(tickers)\n flds = utils.flatten(flds)\n loaded = pd.DataFrame(data=0, index=tickers, columns=flds)\n\n for ticker, fld in product(tickers, flds):\n data_file = storage.ref_file(\n ticker=ticker, fld=fld, ext='pkl', **{\n k: v for k, v in kwargs.items() if k not in EXC_COLS\n }\n )\n if not files.exists(data_file): continue\n logger.debug(f'reading from {data_file} ...')\n cache_data.append(pd.read_pickle(data_file))\n loaded.loc[ticker, fld] = 1\n\n to_qry = loaded.where(loaded == 0)\\\n .dropna(how='all', axis=1).dropna(how='all', axis=0)\n\n return ToQuery(\n tickers=to_qry.index.tolist(), flds=to_qry.columns.tolist(),\n cached_data=cache_data\n )", "docstring": "Find cached `BDP` / `BDS` queries\n\nArgs:\n func: function name - bdp or bds\n tickers: tickers\n flds: fields\n **kwargs: other kwargs\n\nReturns:\n ToQuery(ticker, flds, kwargs)", "source": "juraj_google_style"} +{"code": "def sg_int(tensor, opt):\n r\n return tf.cast(tensor, tf.sg_intx, name=opt.name)", "docstring": "r\"\"\"Casts a tensor to intx.\n\n See `tf.cast()` in tensorflow.\n\nArgs:\n tensor: A `Tensor` or `SparseTensor` (automatically given by chain).\n opt:\n name: If provided, it replaces current tensor's name.\n\nReturns:\n A `Tensor` or `SparseTensor` with same shape as `tensor`.", "source": "juraj_google_style"} +{"code": "def __init__(self, username, **kwargs):\n # type: (str, **Any) -> None\n\n super(ProfileLooter, self).__init__(**kwargs)\n self._username = username\n self._owner_id = None", "docstring": "Create a new profile looter.\n\nArgs:\n username (str): the username of the profile.\n\n See `InstaLooter.__init__` for more details about accepted\n keyword arguments.", "source": "juraj_google_style"} +{"code": "def getfileversion(self):\n\n\n status, major_v, minor_v, release, info = _C.Hgetfileversion(self._id)\n _checkErr('getfileversion', status, \"cannot get file version\")\n return major_v, minor_v, release, info", "docstring": "Get file version info.\n\nArgs:\n no argument\n\nReturns:\n 4-element tuple with the following components:\n -major version number (int)\n -minor version number (int)\n -complete library version number (int)\n -additional information (string)\n\n C library equivalent : Hgetlibversion", "source": "juraj_google_style"} +{"code": "def destroy_unit(self, unit):\n\n\n # if we are given an object, grab it's name property\n # otherwise, convert to unicode\n if isinstance(unit, Unit):\n unit = unit.name\n else:\n unit = str(unit)\n\n self._single_request('Units.Delete', unitName=unit)\n return True", "docstring": "Delete a unit from the cluster\n\nArgs:\n unit (str, Unit): The Unit, or name of the unit to delete\n\nReturns:\n True: The unit was deleted\n\nRaises:\n fleet.v1.errors.APIError: Fleet returned a response code >= 400", "source": "juraj_google_style"} +{"code": "def ParseFileObject(self, parser_mediator, file_object):\n\n self._last_charset_attribute = 'ascii'\n\n self._ParseHeader(parser_mediator, file_object)\n\n data_dict = {}\n time_dict = {}\n\n try:\n for name, value in self._ParseAttributesGroup(file_object):\n name = self._ATTRIBUTE_NAME_TRANSLATION.get(name, name)\n\n if name in self._DATE_TIME_VALUE_NAMES:\n time_dict.setdefault(name, []).append(value)\n else:\n data_dict.setdefault(name, []).append(value)\n\n except (ValueError, errors.ParseError) as exception:\n parser_mediator.ProduceExtractionWarning(\n 'unable to parse attributes with error: {0!s}'.format(exception))\n return\n\n event_data = CupsIppEventData()\n event_data.application = self._GetStringValue(data_dict, 'application')\n event_data.computer_name = self._GetStringValue(data_dict, 'computer_name')\n event_data.copies = data_dict.get('copies', [0])[0]\n event_data.data_dict = data_dict\n event_data.doc_type = self._GetStringValue(data_dict, 'doc_type')\n event_data.job_id = self._GetStringValue(data_dict, 'job_id')\n event_data.job_name = self._GetStringValue(data_dict, 'job_name')\n event_data.user = self._GetStringValue(data_dict, 'user')\n event_data.owner = self._GetStringValue(data_dict, 'owner')\n event_data.printer_id = self._GetStringValue(data_dict, 'printer_id')\n event_data.uri = self._GetStringValue(data_dict, 'uri')\n\n for name, usage in iter(self._DATE_TIME_VALUES.items()):\n for date_time in time_dict.get(name, []):\n event = time_events.DateTimeValuesEvent(date_time, usage)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n for name, usage in iter(self._POSIX_TIME_VALUES.items()):\n for time_value in time_dict.get(name, []):\n date_time = dfdatetime_posix_time.PosixTime(timestamp=time_value)\n event = time_events.DateTimeValuesEvent(date_time, usage)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a CUPS IPP file-like object.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n file_object (dfvfs.FileIO): file-like object.\n\nRaises:\n UnableToParseFile: when the file cannot be parsed.", "source": "juraj_google_style"} +{"code": "def __init__(self, value):\n\n super().__init__(duration=0)\n\n if abs(value) > 1:\n raise PulseError(\"Absolute value of PV amplitude exceeds 1.\")\n\n self._value = complex(value)", "docstring": "create new persistent value command.\n\nArgs:\n value (complex): Complex value to apply, bounded by an absolute value of 1.\n The allowable precision is device specific.\n\nRaises:\n PulseError: when input value exceed 1.", "source": "juraj_google_style"} +{"code": "def get_list_index(lst, index_or_name):\n\n if isinstance(index_or_name, six.integer_types):\n return index_or_name\n\n return lst.index(index_or_name)", "docstring": "Return the index of an element in the list.\n\nArgs:\n lst (list): The list.\n index_or_name (int or str): The value of the reference element, or directly its numeric index.\n\nReturns:\n (int) The index of the element in the list.", "source": "juraj_google_style"} +{"code": "def cppn(\n width,\n batch=1,\n num_output_channels=3,\n num_hidden_channels=24,\n num_layers=8,\n activation_func=_composite_activation,\n normalize=False,\n):\n\n r = 3.0 ** 0.5 # std(coord_range) == 1.0\n coord_range = tf.linspace(-r, r, width)\n y, x = tf.meshgrid(coord_range, coord_range, indexing=\"ij\")\n net = tf.stack([tf.stack([x, y], -1)] * batch, 0)\n\n with slim.arg_scope(\n [slim.conv2d],\n kernel_size=[1, 1],\n activation_fn=None,\n weights_initializer=tf.initializers.variance_scaling(),\n biases_initializer=tf.initializers.random_normal(0.0, 0.1),\n ):\n for i in range(num_layers):\n x = slim.conv2d(net, num_hidden_channels)\n if normalize:\n x = slim.instance_norm(x)\n net = activation_func(x)\n rgb = slim.conv2d(\n net,\n num_output_channels,\n activation_fn=tf.nn.sigmoid,\n weights_initializer=tf.zeros_initializer(),\n )\n return rgb", "docstring": "Compositional Pattern Producing Network\n\nArgs:\n width: width of resulting image, equals height\n batch: batch dimension of output, note that all params share the same weights!\n num_output_channels:\n num_hidden_channels:\n num_layers:\n activation_func:\n normalize:\n\nReturns:\n The collapsed shape, represented as a list.", "source": "juraj_google_style"} +{"code": "def hue(self, color, *args):\n\n if color:\n h, l, s = self._hextohls(color)\n return utility.convergent_round(h * 360.0, 3)\n raise ValueError('Illegal color values')", "docstring": "Return the hue value of a color\n\nArgs:\n color (str): color\n\nRaises:\n ValueError\n\nReturns:\n float", "source": "juraj_google_style"} +{"code": "def list_workflow_outputs(self):\n\n workflow_outputs = []\n for task in self.tasks:\n for output_port_name in task.outputs._portnames:\n if task.outputs.__getattribute__(output_port_name).persist:\n workflow_outputs.append(task.name + ':' + output_port_name)\n\n return workflow_outputs", "docstring": "Get a list of outputs from the workflow that are saved to S3. To get resolved locations call workflow status.\n\nArgs:\n None\n\nReturns:\n list", "source": "juraj_google_style"} +{"code": "def pandas_dataframe(self, start, stop, ncol, **kwargs):\n\n try:\n int(start)\n int(stop)\n except TypeError:\n print('start and stop must be ints')\n try:\n ncol = int(ncol)\n return pd.read_csv(six.StringIO('\\n'.join(self[start:stop])), delim_whitespace=True, names=range(ncol), **kwargs)\n except TypeError:\n try:\n ncol = list(ncol)\n return pd.read_csv(six.StringIO('\\n'.join(self[start:stop])), delim_whitespace=True, names=ncol, **kwargs)\n except TypeError:\n print('Cannot pandas_dataframe if ncol is {}, must be int or list'.format(type(ncol)))", "docstring": "Returns the result of tab-separated pandas.read_csv on\n a subset of the file.\n\nArgs:\n start (int): line number where structured data starts\n stop (int): line number where structured data stops\n ncol (int or list): the number of columns in the structured\n data or a list of that length with column names\n\nReturns:\n pd.DataFrame: structured data", "source": "juraj_google_style"} +{"code": "def backfill_previous_messages(self, reverse=False, limit=10):\n\n res = self.client.api.get_room_messages(self.room_id, self.prev_batch,\n direction=\"b\", limit=limit)\n events = res[\"chunk\"]\n if not reverse:\n events = reversed(events)\n for event in events:\n self._put_event(event)", "docstring": "Backfill handling of previous messages.\n\nArgs:\n reverse (bool): When false messages will be backfilled in their original\n order (old to new), otherwise the order will be reversed (new to old).\n limit (int): Number of messages to go back.", "source": "juraj_google_style"} +{"code": "def Open(self, file_object, ascii_codepage='cp1252'):\n\n registry_file = dfwinreg_regf.REGFWinRegistryFile(\n ascii_codepage=ascii_codepage)\n\n # We don't catch any IOErrors here since we want to produce a parse error\n # from the parser if this happens.\n registry_file.Open(file_object)\n\n return registry_file", "docstring": "Opens a Windows Registry file-like object.\n\nArgs:\n file_object (dfvfs.FileIO): Windows Registry file-like object.\n ascii_codepage (Optional[str]): ASCII string codepage.\n\nReturns:\n WinRegistryFile: Windows Registry file or None.", "source": "juraj_google_style"} +{"code": "def from_dict(event_dict):\n\n return SnippetEvent(\n callback_id=event_dict['callbackId'],\n name=event_dict['name'],\n creation_time=event_dict['time'],\n data=event_dict['data'])", "docstring": "Create a SnippetEvent object from a dictionary.\n\nArgs:\n event_dict: a dictionary representing an event.\n\nReturns:\n A SnippetEvent object.", "source": "juraj_google_style"} +{"code": "def get_cmd_out(command):\n\n\n\tif isinstance(command, list):\n\t\tresult = sp.check_output(command)\n\telse:\n\t\tresult = sp.check_output(command, shell=True)\n\n\treturn result.decode('utf-8').rstrip()", "docstring": "Get the output of a command.\n\n Gets a nice Unicode no-extra-whitespace string of the ``stdout`` of a given command.\n\nArgs:\n command (str or list): A string of the command, or a list of the arguments (as would be used in :class:`subprocess.Popen`).\n\nNote:\n If ``command`` is a ``str``, it will be evaluated with ``shell=True`` i.e. in the default shell (for example, bash).\n\nReturns:\n str: The ``stdout`` of the command.", "source": "juraj_google_style"} +{"code": "def _add_open_file(self, file_obj):\n\n if self._free_fd_heap:\n open_fd = heapq.heappop(self._free_fd_heap)\n self.open_files[open_fd] = [file_obj]\n return open_fd\n\n self.open_files.append([file_obj])\n return len(self.open_files) - 1", "docstring": "Add file_obj to the list of open files on the filesystem.\n Used internally to manage open files.\n\n The position in the open_files array is the file descriptor number.\n\nArgs:\n file_obj: File object to be added to open files list.\n\nReturns:\n File descriptor number for the file object.", "source": "juraj_google_style"} +{"code": "def __init__(self, subdomain, username, password, ssl=False, currentUser=None):\n\n self.base_url = \"http%s://%s.campfirenow.com\" % (\"s\" if ssl else \"\", subdomain)\n self._settings = {\n \"subdomain\": subdomain,\n \"username\": username,\n \"password\": password,\n \"ssl\": ssl\n }\n self._user = currentUser\n self._users = {}\n self._rooms = {}\n\n if not self._user:\n _connection = Connection(url=\"%s/users/me\" % self.base_url, user=username, password=password)\n user = _connection.get(key=\"user\")\n\n self._connection = Connection(\n base_url=self.base_url, \n user=self._user.token if self._user else user[\"api_auth_token\"], \n password=\"x\"\n )\n\n if self._user:\n self._user.set_connection(self._connection)\n else:\n self._user = User(self, user[\"id\"], current=True)\n self._user.token = user[\"api_auth_token\"]", "docstring": "Initialize.\n\nArgs:\n subdomain (str): Campfire subdomain\n username (str): User\n password (str): pasword\n\n Kwargs:\n ssl (bool): enabled status of SSL\n currentUser (:class:`User`): If specified, don't auto load current user, use this one instead", "source": "juraj_google_style"} +{"code": "def autobuild_release(family=None):\n\n\n if family is None:\n family = utilities.get_family('module_settings.json')\n\n env = Environment(tools=[])\n env['TILE'] = family.tile\n\n target = env.Command(['#build/output/module_settings.json'], ['#module_settings.json'],\n action=env.Action(create_release_settings_action, \"Creating release manifest\"))\n env.AlwaysBuild(target)\n\n # Copy over release notes if they exist\n if os.path.exists('RELEASE.md'):\n env.Command(['build/output/RELEASE.md'], ['RELEASE.md'], Copy(\"$TARGET\", \"$SOURCE\"))\n\n # Now copy across the build products that are not copied automatically\n copy_include_dirs(family.tile)\n copy_tilebus_definitions(family.tile)\n copy_dependency_docs(family.tile)\n copy_linker_scripts(family.tile)\n\n # Allow users to specify a hide_dependency_images flag that does not copy over all firmware images\n if not family.tile.settings.get('hide_dependency_images', False):\n copy_dependency_images(family.tile)\n\n copy_extra_files(family.tile)\n build_python_distribution(family.tile)", "docstring": "Copy necessary files into build/output so that this component can be used by others\n\nArgs:\n family (ArchitectureGroup): The architecture group that we are targeting. If not\n provided, it is assumed that we are building in the current directory and the\n module_settings.json file is read to create an ArchitectureGroup", "source": "juraj_google_style"} +{"code": "def AddEnumDescriptor(self, enum_desc):\n\n\n if not isinstance(enum_desc, descriptor.EnumDescriptor):\n raise TypeError('Expected instance of descriptor.EnumDescriptor.')\n\n self._enum_descriptors[enum_desc.full_name] = enum_desc\n self.AddFileDescriptor(enum_desc.file)", "docstring": "Adds an EnumDescriptor to the pool.\n\n This method also registers the FileDescriptor associated with the message.\n\nArgs:\n enum_desc: An EnumDescriptor.", "source": "juraj_google_style"} +{"code": "def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):\n\n return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]", "docstring": "Convert a list of bounding boxes from the format used by albumentations to a format, specified\n in `target_format`.\n\nArgs:\n bboxes (list): List of bounding box with coordinates in the format used by albumentations\n target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'.\n rows (int): image height\n cols (int): image width\n check_validity (bool): check if all boxes are valid boxes", "source": "juraj_google_style"} +{"code": "def __init__(self, application, authenticator):\n\n if not isinstance(authenticator, tokens.Authenticator):\n raise ValueError(u\"Invalid authenticator\")\n\n self._application = application\n self._authenticator = authenticator", "docstring": "Initializes an authentication middleware instance.\n\nArgs:\n application: a WSGI application to be wrapped\n authenticator (:class:`google.auth.tokens.Authenticator`): an\n authenticator that authenticates incoming requests", "source": "juraj_google_style"} +{"code": "def FromJsonString(self, value):\n\n if len(value) < 1 or value[-1] != 's':\n raise ParseError(\n 'Duration must end with letter \"s\": {0}.'.format(value))\n try:\n pos = value.find('.')\n if pos == -1:\n self.seconds = int(value[:-1])\n self.nanos = 0\n else:\n self.seconds = int(value[:pos])\n if value[0] == '-':\n self.nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9))\n else:\n self.nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9))\n except ValueError:\n raise ParseError(\n 'Couldn\\'t parse duration: {0}.'.format(value))", "docstring": "Converts a string to Duration.\n\nArgs:\n value: A string to be converted. The string must end with 's'. Any\n fractional digits (or none) are accepted as long as they fit into\n precision. For example: \"1s\", \"1.01s\", \"1.0000001s\", \"-3.100s\n\nRaises:\n ParseError: On parsing problems.", "source": "juraj_google_style"} +{"code": "def _get_db_fields(self, obj):\n\n for field in obj.indexes:\n yield field, self._zeo_key(field)", "docstring": "Return list of database dictionaries, which are used as indexes for\n each attributes.\n\nArgs:\n cached (bool, default True): Use cached connection to database.\n\nReturns:\n list: List of OOBTree's for each item in :attr:`.COMMON_FIELDS`.", "source": "juraj_google_style"} +{"code": "def replace(self, **kw):\n\n if \"tzinfo\" in kw:\n if kw[\"tzinfo\"] is None:\n raise TypeError(\"Can not remove the timezone use asdatetime()\")\n else:\n tzinfo = kw[\"tzinfo\"]\n del kw[\"tzinfo\"]\n else:\n tzinfo = None\n\n is_dst = None\n if \"is_dst\" in kw:\n is_dst = kw[\"is_dst\"]\n del kw[\"is_dst\"]\n else:\n # Use our own DST setting..\n is_dst = self.is_dst\n\n replaced = self.asdatetime().replace(**kw)\n\n return type(self)(\n replaced, tzinfo=tzinfo or self.tzinfo.zone, is_dst=is_dst)", "docstring": "Return datetime with new specified fields given as arguments.\n\n For example, dt.replace(days=4) would return a new datetime_tz object with\n exactly the same as dt but with the days attribute equal to 4.\n\n Any attribute can be replaced, but tzinfo can not be set to None.\n\nArgs:\n Any datetime_tz attribute.\n\nReturns:\n A datetime_tz object with the attributes replaced.\n\nRaises:\n TypeError: If the given replacement is invalid.", "source": "juraj_google_style"} +{"code": "def prefixed_name(self, unprefixed_name, max_length=0):\n\n if max_length == 0:\n prefixed_name = '%s-%s' % (self.uuid[:8], unprefixed_name)\n else:\n if max_length < 6:\n raise RuntimeError(\n \"Can't prefix with less than 6 chars (%s)\" %\n unprefixed_name\n )\n if max_length < 16:\n _uuid = self.uuid[:4]\n else:\n _uuid = self.uuid[:8]\n\n name_max_length = max_length - len(_uuid) - 1\n\n if name_max_length < len(unprefixed_name):\n hashed_name = hashlib.sha1(unprefixed_name).hexdigest()\n unprefixed_name = hashed_name[:name_max_length]\n\n prefixed_name = '%s-%s' % (_uuid, unprefixed_name)\n\n return prefixed_name", "docstring": "Returns a uuid pefixed identifier\n\nArgs:\n unprefixed_name(str): Name to add a prefix to\n max_length(int): maximum length of the resultant prefixed name,\n will adapt the given name and the length of the uuid ot fit it\n\nReturns:\n str: prefixed identifier for the given unprefixed name", "source": "juraj_google_style"} +{"code": "def normalize_name(decl):\n\n if decl.cache.normalized_name is None:\n decl.cache.normalized_name = normalize(decl.name)\n return decl.cache.normalized_name", "docstring": "Cached variant of normalize\n\nArgs:\n decl (declaration.declaration_t): the declaration\n\nReturns:\n str: normalized name", "source": "juraj_google_style"} +{"code": "def robust_zscore(mat, ctrl_mat=None, min_mad=0.1):\n\n\n # If optional df exists, calc medians and mads from it\n if ctrl_mat is not None:\n medians = ctrl_mat.median(axis=1)\n median_devs = abs(ctrl_mat.subtract(medians, axis=0))\n\n # Else just use plate medians\n else:\n medians = mat.median(axis=1)\n median_devs = abs(mat.subtract(medians, axis=0))\n\n sub = mat.subtract(medians, axis='index')\n mads = median_devs.median(axis=1)\n\n # Threshold mads\n mads = mads.clip(lower=min_mad)\n\n # Must multiply values by 1.4826 to make MAD comparable to SD\n # (https://en.wikipedia.org/wiki/Median_absolute_deviation)\n zscore_df = sub.divide(mads * 1.4826, axis='index')\n\n return zscore_df.round(rounding_precision)", "docstring": "Robustly z-score a pandas df along the rows.\n\nArgs:\n mat (pandas df): Matrix of data that z-scoring will be applied to\n ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs\n (e.g. vehicle control)\n min_mad (float): Minimum MAD to threshold to; tiny MAD values will cause\n z-scores to blow up\n\nReturns:\n zscore_df (pandas_df): z-scored data", "source": "juraj_google_style"} +{"code": "def _build_graph(self, tags):\n\n graph = SimpleGraph()\n for tag_index in xrange(len(tags)):\n for entity_index in xrange(len(tags[tag_index].get('entities'))):\n a_entity_name = graph_key_from_tag(tags[tag_index], entity_index)\n tokens = self.tokenizer.tokenize(tags[tag_index].get('entities', [])[entity_index].get('match'))\n for tag in tags[tag_index + 1:]:\n start_token = tag.get('start_token')\n if start_token >= tags[tag_index].get('start_token') + len(tokens):\n for b_entity_index in xrange(len(tag.get('entities'))):\n b_entity_name = graph_key_from_tag(tag, b_entity_index)\n graph.add_edge(a_entity_name, b_entity_name)\n\n return graph", "docstring": "Builds a graph from the entities included in the tags.\n Note this is used internally.\n\nArgs:\n tags (list): A list of the tags to include in graph\n\nReturns:\n graph : this is the resulting graph of the tagged entities.", "source": "juraj_google_style"} +{"code": "def _prepare_sample_data(self, submission_type):\n\n # write images\n images = np.random.randint(0, 256,\n size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)\n for i in range(BATCH_SIZE):\n Image.fromarray(images[i, :, :, :]).save(\n os.path.join(self._sample_input_dir, IMAGE_NAME_PATTERN.format(i)))\n # write target class for targeted attacks\n if submission_type == 'targeted_attack':\n target_classes = np.random.randint(1, 1001, size=[BATCH_SIZE])\n target_class_filename = os.path.join(self._sample_input_dir,\n 'target_class.csv')\n with open(target_class_filename, 'w') as f:\n for i in range(BATCH_SIZE):\n f.write((IMAGE_NAME_PATTERN + ',{1}\\n').format(i, target_classes[i]))", "docstring": "Prepares sample data for the submission.\n\nArgs:\n submission_type: type of the submission.", "source": "juraj_google_style"} +{"code": "def marshal_json(\n obj,\n types=JSON_TYPES,\n fields=None,\n):\n\n return marshal_dict(\n obj,\n types,\n fields=fields,\n )", "docstring": "Recursively marshal a Python object to a JSON-compatible dict\n that can be passed to json.{dump,dumps}, a web client,\n or a web server, etc...\n\nArgs:\n obj: object, It's members can be nested Python\n objects which will be converted to dictionaries\n types: tuple-of-types, The JSON primitive types, typically\n you would not change this\n fields: None-list-of-str, Explicitly marshal only these fields\n\nReturns:\n dict", "source": "juraj_google_style"} +{"code": "def _create_topk_unique(inputs, k):\n\n height = inputs.shape[0]\n width = inputs.shape[1]\n neg_inf_r0 = tf.constant(-np.inf, dtype=tf.float32)\n ones = tf.ones([height, width], dtype=tf.float32)\n neg_inf_r2 = ones * neg_inf_r0\n inputs = tf.where(tf.is_nan(inputs), neg_inf_r2, inputs)\n\n # Select the current largest value k times and keep them in topk_r2. The\n # selected largest values are marked as the smallest value to avoid being\n # selected again.\n tmp = inputs\n topk_r2 = tf.zeros([height, k], dtype=tf.float32)\n for i in range(k):\n kth_order_statistic = tf.reduce_max(tmp, axis=1, keepdims=True)\n k_mask = tf.tile(tf.expand_dims(tf.equal(tf.range(k), tf.fill([k], i)), 0),\n [height, 1])\n topk_r2 = tf.where(k_mask, tf.tile(kth_order_statistic, [1, k]), topk_r2)\n ge_r2 = tf.greater_equal(inputs, tf.tile(kth_order_statistic, [1, width]))\n tmp = tf.where(ge_r2, neg_inf_r2, inputs)\n\n log2_ceiling = int(math.ceil(math.log(float(int(width)), 2)))\n next_power_of_two = 1 << log2_ceiling\n count_mask = next_power_of_two - 1\n mask_r0 = tf.constant(count_mask)\n mask_r2 = tf.fill([height, k], mask_r0)\n topk_r2_s32 = tf.bitcast(topk_r2, tf.int32)\n topk_indices_r2 = tf.bitwise.bitwise_and(topk_r2_s32, mask_r2)\n return topk_r2, topk_indices_r2", "docstring": "Creates the top k values in sorted order with indices.\n\nArgs:\n inputs: A tensor with rank of 2. [batch_size, original_size].\n k: An integer, number of top elements to select.\n\nReturns:\n topk_r2: A tensor, the k largest elements. [batch_size, k].\n topk_indices_r2: A tensor, indices of the top k values. [batch_size, k].", "source": "juraj_google_style"} +{"code": "def _MergeEntities(self, a, b):\n\n if a.shape_id != b.shape_id:\n raise MergeError('shape_id must be the same')\n\n distance = max(ApproximateDistanceBetweenPoints(a.points[0][:2],\n b.points[0][:2]),\n ApproximateDistanceBetweenPoints(a.points[-1][:2],\n b.points[-1][:2]))\n if distance > self.largest_shape_distance:\n raise MergeError('The shape endpoints are too far away: %.1fm '\n '(largest_shape_distance is %.1fm)' %\n (distance, self.largest_shape_distance))\n\n return self._Migrate(b, self.feed_merger.b_schedule, False)", "docstring": "Merges the shapes by taking the new shape.\n\nArgs:\n a: The first transitfeed.Shape instance.\n b: The second transitfeed.Shape instance.\n\nReturns:\n The merged shape.\n\nRaises:\n MergeError: If the ids are different or if the endpoints are further\n than largest_shape_distance apart.", "source": "juraj_google_style"} +{"code": "def return_handler(\n self,\n call_node,\n function_nodes,\n saved_function_call_index,\n first_node\n ):\n\n if any(isinstance(node, YieldNode) for node in function_nodes):\n # Presence of a `YieldNode` means that the function is a generator\n rhs_prefix = 'yld_'\n elif any(isinstance(node, ConnectToExitNode) for node in function_nodes):\n # Only `Return`s and `Raise`s can be of type ConnectToExitNode\n rhs_prefix = 'ret_'\n else:\n return # No return value\n\n # Create e.g. ~call_1 = ret_func_foo RestoreNode\n LHS = CALL_IDENTIFIER + 'call_' + str(saved_function_call_index)\n RHS = rhs_prefix + get_call_names_as_string(call_node.func)\n return_node = RestoreNode(\n LHS + ' = ' + RHS,\n LHS,\n [RHS],\n line_number=call_node.lineno,\n path=self.filenames[-1]\n )\n return_node.first_node = first_node\n self.nodes[-1].connect(return_node)\n self.nodes.append(return_node)", "docstring": "Handle the return from a function during a function call.\n\nArgs:\n call_node(ast.Call) : The node that calls the definition.\n function_nodes(list[Node]): List of nodes of the function being called.\n saved_function_call_index(int): Unique number for each call.\n first_node(EntryOrExitNode or RestoreNode): Used to connect previous statements to this function.", "source": "juraj_google_style"} +{"code": "def readall(self):\n # type: () -> bytes\n\n if not self._open:\n raise pycdlibexception.PyCdlibInvalidInput('I/O operation on closed file.')\n\n readsize = self._length - self._offset\n if readsize > 0:\n data = self._fp.read(readsize)\n self._offset += readsize\n else:\n data = b''\n\n return data", "docstring": "A method to read and return the remaining bytes in the file.\n\n Parameters:\n None.\n\nReturns:\n The rest of the data left in the file. If the file is at or past EOF,\n returns an empty bytestring.", "source": "juraj_google_style"} +{"code": "def __init__(self, latitude, longitude, name=None, description=None,\n elevation=None, time=None):\n\n super(_GpxElem, self).__init__(latitude, longitude, time=time)\n self.name = name\n self.description = description\n self.elevation = elevation", "docstring": "Initialise a new ``_GpxElem`` object.\n\nArgs:\n latitude (float): Element's latitude\n longitude (float): Element's longitude\n name (str): Name for Element\n description (str): Element's description\n elevation (float): Element's elevation\n time (utils.Timestamp): Time the data was generated", "source": "juraj_google_style"} +{"code": "def bind(self, prefix, namespace, *args, **kwargs):\n\n # RdfNamespace(prefix, namespace, **kwargs)\n setattr(self, prefix, RdfNamespace(prefix, namespace, **kwargs))\n if kwargs.pop('calc', True):\n self.__make_dicts__", "docstring": "Extends the function to add an attribute to the class for each\n added namespace to allow for use of dot notation. All prefixes are\n converted to lowercase\n\nArgs:\n prefix: string of namespace name\n namespace: rdflib.namespace instance\n\n kwargs:\n calc: whether or not create the lookup reference dictionaries\n\n Example usage:\n RdfNsManager.rdf.type =>\n http://www.w3.org/1999/02/22-rdf-syntax-ns#type", "source": "juraj_google_style"} +{"code": "def reqTickByTickData(\n self, contract: Contract, tickType: str,\n numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker:\n\n reqId = self.client.getReqId()\n ticker = self.wrapper.startTicker(reqId, contract, tickType)\n self.client.reqTickByTickData(\n reqId, contract, tickType, numberOfTicks, ignoreSize)\n return ticker", "docstring": "Subscribe to tick-by-tick data and return the Ticker that\n holds the ticks in ticker.tickByTicks.\n\n https://interactivebrokers.github.io/tws-api/tick_data.html\n\nArgs:\n contract: Contract of interest.\n tickType: One of 'Last', 'AllLast', 'BidAsk' or 'MidPoint'.\n numberOfTicks: Number of ticks or 0 for unlimited.\n ignoreSize: Ignore bid/ask ticks that only update the size.", "source": "juraj_google_style"} +{"code": "def sia_bipartitions(nodes, node_labels=None):\n\n if config.CUT_ONE_APPROXIMATION:\n bipartitions = directed_bipartition_of_one(nodes)\n else:\n # Don't consider trivial partitions where one part is empty\n bipartitions = directed_bipartition(nodes, nontrivial=True)\n\n return [Cut(bipartition[0], bipartition[1], node_labels)\n for bipartition in bipartitions]", "docstring": "Return all |big_phi| cuts for the given nodes.\n\n This value changes based on :const:`config.CUT_ONE_APPROXIMATION`.\n\nArgs:\n nodes (tuple[int]): The node indices to partition.\n\nReturns:\n list[Cut]: All unidirectional partitions.", "source": "juraj_google_style"} +{"code": "def dict2str(self, d: Dict, joiner: str) -> str:\n\n result = str()\n for key in d:\n result = result + str(key) + \" : \"\n if isinstance(d[key], list):\n result = result + self.list2str(d[key], joiner) + joiner\n elif isinstance(d[key], dict):\n result = result + self.dict2str(d[key], joiner) + joiner\n elif d[key]:\n result = result + str(d[key]) + joiner\n return result", "docstring": "Convert dict to str as input for tokenizer\n\nArgs:\n d (dict): dict for converting\n joiner (str): join the elements using this string to separate them.\n\n Returns: the value of the dict as a string", "source": "juraj_google_style"} +{"code": "def _add_ce_record(self, curr_dr_len, thislen):\n # type: (int, int) -> int\n\n if self.dr_entries.ce_record is None:\n self.dr_entries.ce_record = RRCERecord()\n self.dr_entries.ce_record.new()\n curr_dr_len += RRCERecord.length()\n self.dr_entries.ce_record.add_record(thislen)\n return curr_dr_len", "docstring": "An internal method to add a new length to a Continuation Entry. If the\n Continuation Entry does not yet exist, this method creates it.\n\n Parameters:\n curr_dr_len - The current Directory Record length.\n thislen - The new length to add to the Continuation Entry.\n\nReturns:\n An integer representing the current directory record length after\n adding the Continuation Entry.", "source": "juraj_google_style"} +{"code": "def record(self):\n # type: () -> bytes\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('This Eltorito Boot Info Table not yet initialized')\n\n return struct.pack('=LLLL', self.vd.extent_location(),\n self.inode.extent_location(), self.orig_len,\n self.csum) + b'\\x00' * 40", "docstring": "A method to generate a string representing this boot info table.\n\n Parameters:\n None.\n\nReturns:\n A string representing this boot info table.", "source": "juraj_google_style"} +{"code": "def get_config_string_option(parser: ConfigParser,\n section: str,\n option: str,\n default: str = None) -> str:\n\n if not parser.has_section(section):\n raise ValueError(\"config missing section: \" + section)\n return parser.get(section, option, fallback=default)", "docstring": "Retrieves a string value from a parser.\n\nArgs:\n parser: instance of :class:`ConfigParser`\n section: section name within config file\n option: option (variable) name within that section\n default: value to return if option is absent\n\nReturns:\n string value\n\nRaises:\n ValueError: if the section is absent", "source": "juraj_google_style"} +{"code": "def goto_step(self, inst: InstanceNode) -> InstanceNode:\n\n try:\n return inst._entry(\n inst.value.index(self.parse_value(inst.schema_node)))\n except ValueError:\n raise NonexistentInstance(inst.json_pointer(),\n f\"entry '{self.value!s}'\") from None", "docstring": "Return member instance of `inst` addressed by the receiver.\n\nArgs:\n inst: Current instance.", "source": "juraj_google_style"} +{"code": "def get_bounds(changeset):\n\n try:\n return Polygon([\n (float(changeset.get('min_lon')), float(changeset.get('min_lat'))),\n (float(changeset.get('max_lon')), float(changeset.get('min_lat'))),\n (float(changeset.get('max_lon')), float(changeset.get('max_lat'))),\n (float(changeset.get('min_lon')), float(changeset.get('max_lat'))),\n (float(changeset.get('min_lon')), float(changeset.get('min_lat'))),\n ])\n except TypeError:\n return Polygon()", "docstring": "Get the bounds of the changeset and return it as a Polygon object. If\n the changeset has not coordinates (case of the changesets that deal only\n with relations), it returns an empty Polygon.\n\nArgs:\n changeset: the XML string of the changeset.", "source": "juraj_google_style"} +{"code": "def delete_field(self, field_name):\n\n self._whoosh.remove_field(field_name.strip())\n return self._whoosh.schema", "docstring": "This function deletes one determined field using the command MODEL.pw.delete_field(FIELD)\n\nArgs:\n field_name (string): This argument let you delete some field for some model registered in the index.\n\nReturns:\n (WhooshSchema): The new schema after deleted is returned.", "source": "juraj_google_style"} +{"code": "def SerializeUnsigned(self, writer):\n\n writer.WriteUInt32(self.Version)\n writer.WriteUInt256(self.PrevHash)\n writer.WriteUInt256(self.MerkleRoot)\n writer.WriteUInt32(self.Timestamp)\n writer.WriteUInt32(self.Index)\n writer.WriteUInt64(self.ConsensusData)\n writer.WriteUInt160(self.NextConsensus)", "docstring": "Serialize unsigned data only.\n\nArgs:\n writer (neo.IO.BinaryWriter):", "source": "juraj_google_style"} +{"code": "def add_affiliation(self, value, curated_relation=None, record=None):\n\n if value:\n affiliation = {\n 'value': value\n }\n if record:\n affiliation['record'] = record\n if curated_relation is not None:\n affiliation['curated_relation'] = curated_relation\n self._ensure_list_field('affiliations', affiliation)", "docstring": "Add an affiliation.\n\nArgs:\n value (string): affiliation value\n curated_relation (bool): is relation curated\n record (dict): affiliation JSON reference", "source": "juraj_google_style"} +{"code": "def is_http_running_on(port):\n\n try:\n conn = httplib.HTTPConnection('127.0.0.1:' + str(port))\n conn.connect()\n conn.close()\n return True\n except Exception:\n return False", "docstring": "Check if an http server runs on a given port.\n\nArgs:\n The port to check.\n\nReturns:\n True if it is used by an http server. False otherwise.", "source": "juraj_google_style"} +{"code": "def trimpath(attributes):\n\n if 'pathdepth' in attributes:\n if attributes['pathdepth'] != 'full':\n pathelements = []\n remainder = attributes['file']\n limit = int(attributes['pathdepth'])\n while len(pathelements) < limit and remainder:\n remainder, pe = os.path.split(remainder)\n pathelements.insert(0, pe)\n return os.path.join(*pathelements)\n return attributes['file']\n return os.path.basename(attributes['file'])", "docstring": "Simplifies the given path.\n\n If pathdepth is in attributes, the last pathdepth elements will be\n returned. If pathdepth is \"full\", the full path will be returned.\n Otherwise the filename only will be returned.\n\nArgs:\n attributes: The element attributes.\n\nReturns:\n The trimmed path.", "source": "juraj_google_style"} +{"code": "def __init__(self, dimensions, dimension=3, epsilon=None):\n\n self.dimensions = dimensions\n self.dimension = dimension\n\n if epsilon is None:\n self.epsilon = self.DEFAULT_EPSILON\n else:\n self.epsilon = epsilon", "docstring": "The only key parameter is the list (or tuple) of dimensions, which can be\n of any size as long as its length is equal to the \"dimension\" parameter.\n\n Parameters:\n ----------------------------\n @param dimensions (list(int))\n List of the box's dimensions.\n\n @param dimension (int)\n Space dimension. Typically 3.\n\n @param epsilon (float)\n Object resolution. Defaults to self.DEFAULT_EPSILON", "source": "juraj_google_style"} +{"code": "def _embedding_dim(vocab_size):\n\n if not vocab_size or (vocab_size <= 0):\n raise ValueError(\"Invalid vocab_size %g.\" % vocab_size)\n return int(round(6.0 * math.sqrt(math.sqrt(vocab_size))))", "docstring": "Calculate a reasonable embedding size for a vocabulary.\n\n Rule of thumb is 6 * 4th root of vocab_size.\n\nArgs:\n vocab_size: Size of the input vocabulary.\n\nReturns:\n The embedding size to use.\n\nRaises:\n ValueError: if `vocab_size` is invalid.", "source": "juraj_google_style"} +{"code": "def tryload(self, cfgstr=None, on_error='raise'):\n\n cfgstr = self._rectify_cfgstr(cfgstr)\n if self.enabled:\n try:\n if self.verbose > 1:\n self.log('[cacher] tryload fname={}'.format(self.fname))\n return self.load(cfgstr)\n except IOError:\n if self.verbose > 0:\n self.log('[cacher] ... {} cache miss'.format(self.fname))\n except Exception:\n if self.verbose > 0:\n self.log('[cacher] ... failed to load')\n if on_error == 'raise':\n raise\n elif on_error == 'clear':\n self.clear(cfgstr)\n return None\n else:\n raise KeyError('Unknown method on_error={}'.format(on_error))\n else:\n if self.verbose > 1:\n self.log('[cacher] ... cache disabled: fname={}'.format(self.fname))\n return None", "docstring": "Like load, but returns None if the load fails due to a cache miss.\n\nArgs:\n on_error (str): How to handle non-io errors errors. Either raise,\n which re-raises the exception, or clear which deletes the cache\n and returns None.", "source": "juraj_google_style"} +{"code": "def __init__(self, output_mediator):\n\n super(DynamicOutputModule, self).__init__(output_mediator)\n self._dynamic_fields_helper = DynamicFieldsHelper(output_mediator)\n self._field_delimiter = self._DEFAULT_FIELD_DELIMITER\n self._fields = self._DEFAULT_FIELDS", "docstring": "Initializes an output module object.\n\nArgs:\n output_mediator (OutputMediator): an output mediator.", "source": "juraj_google_style"} +{"code": "def __init__(self, sdat):\n\n self.sdat = sdat\n super().__init__('Stagnant lid regime for {}'.format(sdat))", "docstring": "Initialization of instances:\n\nArgs:\n sdat (:class:`~stagpy.stagyydata.StagyyData`): the StagyyData\n instance for which a stagnant lid regime was found.\n\nAttributes:\n sdat (:class:`~stagpy.stagyydata.StagyyData`): the StagyyData\n instance for which a stagnant lid regime was found.", "source": "juraj_google_style"} +{"code": "def update_panel(store, panel_name, csv_lines, option):\n\n new_genes= []\n panel_obj = store.gene_panel(panel_name)\n if panel_obj is None:\n return None\n try:\n new_genes = parse_genes(csv_lines) # a list of gene dictionaries containing gene info\n except SyntaxError as error:\n flash(error.args[0], 'danger')\n return None\n\n # if existing genes are to be replaced by those in csv_lines\n if option == 'replace':\n # all existing genes should be deleted\n for gene in panel_obj['genes']:\n #create extra key to use in pending actions:\n gene['hgnc_symbol'] = gene['symbol']\n store.add_pending(panel_obj, gene, action='delete', info=None)\n\n for new_gene in new_genes:\n if not new_gene['hgnc_id']:\n flash(\"gene missing hgnc id: {}\".format(new_gene['hgnc_symbol']),'danger')\n continue\n gene_obj = store.hgnc_gene(new_gene['hgnc_id'])\n if gene_obj is None:\n flash(\"gene not found: {} - {}\".format(new_gene['hgnc_id'], new_gene['hgnc_symbol']),'danger')\n continue\n if new_gene['hgnc_symbol'] and gene_obj['hgnc_symbol'] != new_gene['hgnc_symbol']:\n flash(\"symbol mis-match: {0} | {1}\".format(\n gene_obj['hgnc_symbol'], new_gene['hgnc_symbol']), 'warning')\n\n info_data = {\n 'disease_associated_transcripts': new_gene['transcripts'],\n 'reduced_penetrance': new_gene['reduced_penetrance'],\n 'mosaicism': new_gene['mosaicism'],\n 'inheritance_models': new_gene['inheritance_models'],\n 'database_entry_version': new_gene['database_entry_version'],\n }\n if option == 'replace': # there will be no existing genes for sure, because we're replacing them all\n action = 'add'\n else: # add option. Add if genes is not existing. otherwise edit it\n existing_genes = {gene['hgnc_id'] for gene in panel_obj['genes']}\n action = 'edit' if gene_obj['hgnc_id'] in existing_genes else 'add'\n store.add_pending(panel_obj, gene_obj, action=action, info=info_data)\n\n return panel_obj", "docstring": "Update an existing gene panel with genes.\n\nArgs:\n store(scout.adapter.MongoAdapter)\n panel_name(str)\n csv_lines(iterable(str)): Stream with genes\n option(str): 'add' or 'replace'\n\nReturns:\n panel_obj(dict)", "source": "juraj_google_style"} +{"code": "def parse(self, string, strict=True):\n\n if isinstance(string, bytes):\n errors = 'strict' if strict else 'replace'\n string = string.decode(self.encoding, errors=errors)\n\n if not self.raw:\n self.raw = string\n else:\n self.raw += string\n\n lines = unfold_lines(string).splitlines()\n for line in lines:\n if line:\n if ':' not in line:\n if strict:\n raise ValueError('Field missing colon.')\n else:\n continue\n\n name, value = line.split(':', 1)\n name = name.strip()\n value = value.strip()\n self.add(name, value)", "docstring": "Parse the string or bytes.\n\nArgs:\n strict (bool): If True, errors will not be ignored\n\nRaises:\n :class:`ValueError` if the record is malformed.", "source": "juraj_google_style"} +{"code": "def play(self, **kwargs):\n\n path = '%s/%s/play' % (self.manager.path, self.get_id())\n self.manager.gitlab.http_post(path)", "docstring": "Trigger a job explicitly.\n\nArgs:\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabJobPlayError: If the job could not be triggered", "source": "juraj_google_style"} +{"code": "def search_features(self, search):\n\n if isinstance(search, string_types):\n search = [search]\n search = [s.replace('*', '.*') for s in search]\n cols = list(self.data.columns)\n results = []\n for s in search:\n results.extend([f for f in cols if re.match(s + '$', f)])\n return list(set(results))", "docstring": "Returns all features that match any of the elements in the input\n list.\n\nArgs:\n search (str, list): A string or list of strings defining the query.\n\nReturns:\n A list of matching feature names.", "source": "juraj_google_style"} +{"code": "def get_entity(namespace, workspace, etype, ename):\n\n uri = \"workspaces/{0}/{1}/entities/{2}/{3}\".format(namespace,\n workspace, etype, ename)\n return __get(uri)", "docstring": "Request entity information.\n\n Gets entity metadata and attributes.\n\nArgs:\n namespace (str): project to which workspace belongs\n workspace (str): Workspace name\n etype (str): Entity type\n ename (str): The entity's unique id\n\n Swagger:\n https://api.firecloud.org/#!/Entities/getEntity", "source": "juraj_google_style"} +{"code": "def validate_string(string, options=None):\n\n output.info(\"Performing JSON schema validation on input string: \" + string)\n stream = io.StringIO(string)\n return validate(stream, options)", "docstring": "Validate the input `string` according to the options passed in.\n\n If any exceptions are raised during validation, no further validation\n will take place.\n\nArgs:\n string: The string containing the JSON to be validated.\n options: An instance of ``ValidationOptions``.\n\nReturns:\n An ObjectValidationResults instance, or a list of such.", "source": "juraj_google_style"} +{"code": "def raise_for_api_error(headers: MutableMapping, data: MutableMapping) -> None:\n\n\n if not data[\"ok\"]:\n raise exceptions.SlackAPIError(data.get(\"error\", \"unknow_error\"), headers, data)\n\n if \"warning\" in data:\n LOG.warning(\"Slack API WARNING: %s\", data[\"warning\"])", "docstring": "Check request response for Slack API error\n\nArgs:\n headers: Response headers\n data: Response data\n\nRaises:\n :class:`slack.exceptions.SlackAPIError`", "source": "juraj_google_style"} +{"code": "def generate_visualizations(methods, data, true_labels, base_dir = 'visualizations',\n figsize=(18,10), **scatter_options):\n\n plt.figure(figsize=figsize)\n for method in methods:\n preproc= method[0]\n if isinstance(preproc, Preprocess):\n preprocessed, ll = preproc.run(data)\n output_names = preproc.output_names\n else:\n # if the input is a list, only use the first preproc result\n p1 = data\n output_names = ['']\n for p in preproc:\n p1, ll = p.run(p1)\n p1 = p1[0]\n output_names[0] = output_names[0] + p.output_names[0]\n preprocessed = [p1]\n for r, name in zip(preprocessed, output_names):\n # TODO: cluster labels\n print(name)\n # if it's 2d, just display it... else, do tsne to reduce to 2d\n if r.shape[0]==2:\n r_dim_red = r\n else:\n # sometimes the data is too big to do tsne... (for sklearn)\n if sparse.issparse(r) and r.shape[0] > 100:\n name = 'tsvd_' + name\n tsvd = TruncatedSVD(50)\n r_dim_red = tsvd.fit_transform(r.T)\n try:\n tsne = TSNE(2)\n r_dim_red = tsne.fit_transform(r_dim_red).T\n name = 'tsne_' + name\n except:\n tsvd2 = TruncatedSVD(2)\n r_dim_red = tsvd2.fit_transform(r_dim_red).T\n else:\n name = 'tsne_' + name\n tsne = TSNE(2)\n r_dim_red = tsne.fit_transform(r.T).T\n if isinstance(method[1], list):\n for clustering_method in method[1]:\n try:\n cluster_labels = clustering_method.run(r)\n except:\n print('clustering failed')\n continue\n output_path = base_dir + '/{0}_{1}_labels.png'.format(name, clustering_method.name)\n visualize_dim_red(r_dim_red, cluster_labels, output_path, **scatter_options)\n else:\n clustering_method = method[1]\n try:\n cluster_labels = clustering_method.run(r)\n except:\n print('clustering failed')\n continue\n output_path = base_dir + '/{0}_{1}_labels.png'.format(name, clustering_method.name)\n visualize_dim_red(r_dim_red, cluster_labels, output_path, **scatter_options)\n output_path = base_dir + '/{0}_true_labels.png'.format(name)\n visualize_dim_red(r_dim_red, true_labels, output_path, **scatter_options)", "docstring": "Generates visualization scatters for all the methods.\n\nArgs:\n methods: follows same format as run_experiments. List of tuples.\n data: genes x cells\n true_labels: array of integers\n base_dir: base directory to save all the plots\n figsize: tuple of ints representing size of figure\n scatter_options: options for plt.scatter", "source": "juraj_google_style"} +{"code": "def _generate_examples(self, file_path):\n\n\n with tf.io.gfile.GFile(file_path) as f:\n raw_data = csv.DictReader(f)\n for row in raw_data:\n survive_val = row.pop(\"survived\")\n yield {\n \"survived\": convert_to_label(survive_val, _SURVIVED_DICT),\n \"features\": {\n name: FEATURE_DICT[name][1](value)\n for name, value in row.items()\n }\n }", "docstring": "Generate features and target given the directory path.\n\nArgs:\n file_path: path where the csv file is stored\n\nYields:\n The features and the target", "source": "juraj_google_style"} +{"code": "def attach(self, engine, log_handler, event_name):\n\n if event_name not in State.event_to_attr:\n raise RuntimeError(\"Unknown event name '{}'\".format(event_name))\n\n engine.add_event_handler(event_name, log_handler, self, event_name)", "docstring": "Attach the logger to the engine and execute `log_handler` function at `event_name` events.\n\nArgs:\n engine (Engine): engine object.\n log_handler (callable): a logging handler to execute\n event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine.Events`\n or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.", "source": "juraj_google_style"} +{"code": "def _maybe_download_corpora(tmp_dir, dataset_split):\n\n cnn_filename = \"cnn_stories.tgz\"\n cnn_finalpath = os.path.join(tmp_dir, \"cnn/stories/\")\n dailymail_filename = \"dailymail_stories.tgz\"\n dailymail_finalpath = os.path.join(tmp_dir, \"dailymail/stories/\")\n if not tf.gfile.Exists(cnn_finalpath):\n cnn_file = generator_utils.maybe_download_from_drive(\n tmp_dir, cnn_filename, _CNN_STORIES_DRIVE_URL)\n with tarfile.open(cnn_file, \"r:gz\") as cnn_tar:\n cnn_tar.extractall(tmp_dir)\n if not tf.gfile.Exists(dailymail_finalpath):\n dailymail_file = generator_utils.maybe_download_from_drive(\n tmp_dir, dailymail_filename, _DAILYMAIL_STORIES_DRIVE_URL)\n with tarfile.open(dailymail_file, \"r:gz\") as dailymail_tar:\n dailymail_tar.extractall(tmp_dir)\n\n cnn_files = tf.gfile.Glob(cnn_finalpath + \"*\")\n dailymail_files = tf.gfile.Glob(dailymail_finalpath + \"*\")\n all_files = cnn_files + dailymail_files\n\n if dataset_split == problem.DatasetSplit.TRAIN:\n urls_path = generator_utils.maybe_download(tmp_dir, \"all_train.txt\",\n _TRAIN_URLS)\n elif dataset_split == problem.DatasetSplit.EVAL:\n urls_path = generator_utils.maybe_download(tmp_dir, \"all_val.txt\",\n _DEV_URLS)\n else:\n urls_path = generator_utils.maybe_download(tmp_dir, \"all_test.txt\",\n _TEST_URLS)\n\n return all_files, urls_path", "docstring": "Download corpora if necessary and unzip them.\n\nArgs:\n tmp_dir: directory containing dataset.\n dataset_split: whether we're in train/dev/test mode.\n\nReturns:\n List of all files generated and path to file containing\n train/dev/test split info.", "source": "juraj_google_style"} +{"code": "def join(self, other):\n\n if self.contains(other):\n return True\n\n if other.contains(self):\n self.x = other.x\n self.y = other.y\n self.width = other.width\n self.height = other.height\n return True\n\n if not self.intersects(other, edges=True):\n return False\n\n # Other rectangle is Up/Down from this\n if self.left == other.left and self.width == other.width:\n y_min = min(self.bottom, other.bottom)\n y_max = max(self.top, other.top) \n self.y = y_min\n self.height = y_max-y_min\n return True\n\n # Other rectangle is Right/Left from this\n if self.bottom == other.bottom and self.height == other.height:\n x_min = min(self.left, other.left)\n x_max = max(self.right, other.right)\n self.x = x_min\n self.width = x_max-x_min\n return True\n\n return False", "docstring": "Try to join a rectangle to this one, if the result is also a rectangle\n and the operation is successful and this rectangle is modified to the union.\n\nArgs:\n other (Rectangle): Rectangle to join\n\nReturns:\n bool: True when successfully joined, False otherwise", "source": "juraj_google_style"} +{"code": "def pool_function(domain, launchWhois=False):\n\n is_valid = True\n try:\n ipv4 = socket.gethostbyname(domain[\"domain\"])\n\n # Check if this ipv4 normally throws false positives\n if isBlackListed(ipv4):\n return {\"platform\" : str(domain), \"status\": \"ERROR\", \"data\": {}}\n\n #If we arrive here... The domain exists!!\n aux = {}\n aux[\"type\"] = \"i3visio.result\"\n aux[\"value\"] = \"Domain Info - \" + domain[\"domain\"]\n aux[\"attributes\"] = []\n\n # Performing whois info and adding if necessary\n try:\n if domain[\"type\"] != \"global\" and launchWhois:\n aux[\"attributes\"] = getWhoisInfo(domain[\"domain\"])\n except Exception as e:\n # If something happened... Well, we'll return an empty attributes array.\n pass\n\n tmp = {}\n tmp[\"type\"] = \"i3visio.domain\"\n tmp[\"value\"] = domain[\"domain\"]\n tmp[\"attributes\"] = []\n\n aux[\"attributes\"].append(tmp)\n\n tmp = {}\n tmp[\"type\"] = \"i3visio.tld_type\"\n tmp[\"value\"] = domain[\"type\"]\n tmp[\"attributes\"] = []\n\n aux[\"attributes\"].append(tmp)\n\n tmp = {}\n tmp[\"type\"] = \"i3visio.ipv4\"\n tmp[\"value\"] = ipv4\n tmp[\"attributes\"] = []\n\n aux[\"attributes\"].append(tmp)\n\n return {\"platform\" : str(domain), \"status\": \"DONE\", \"data\": aux}\n except Exception as e:\n return {\"platform\" : str(domain), \"status\": \"ERROR\", \"data\": {}}", "docstring": "Wrapper for being able to launch all the threads of getPageWrapper.\n\nArgs:\n -----\n domain: We receive the parameters as a dictionary.\n ```\n {\n \"domain\" : \".com\",\n \"type\" : \"global\"\n }\n ```\n launchWhois: Whether the whois info will be launched.\n\nReturns:\n --------\n dict: A dictionary containing the following values:\n `{\"platform\" : str(domain), \"status\": \"DONE\", \"data\": aux}`", "source": "juraj_google_style"} +{"code": "def inspect_plugin(self, name):\n\n url = self._url('/plugins/{0}/json', name)\n return self._result(self._get(url), True)", "docstring": "Retrieve plugin metadata.\n\nArgs:\n name (string): The name of the plugin. The ``:latest`` tag is\n optional, and is the default if omitted.\n\nReturns:\n A dict containing plugin info", "source": "juraj_google_style"} +{"code": "def isdir(path):\n\n system = get_instance(path)\n\n # User may use directory path without trailing '/'\n # like on standard file systems\n return system.isdir(system.ensure_dir_path(path))", "docstring": "Return True if path is an existing directory.\n\n Equivalent to \"os.path.isdir\".\n\nArgs:\n path (path-like object): Path or URL.\n\nReturns:\n bool: True if directory exists.", "source": "juraj_google_style"} +{"code": "def gcs(line, cell=None):\n\n parser = google.datalab.utils.commands.CommandParser(prog='%gcs', description=)\n\n # TODO(gram): consider adding a move command too. I did try this already using the\n # objects.patch API to change the object name but that fails with an error:\n #\n # Value 'newname' in content does not agree with value 'oldname'. This can happen when a value\n # set through a parameter is inconsistent with a value set in the request.\n #\n # This is despite 'name' being identified as writable in the storage API docs.\n # The alternative would be to use a copy/delete.\n copy_parser = parser.subcommand('copy', 'Copy one or more Google Cloud Storage objects to a '\n 'different location.')\n copy_parser.add_argument('-s', '--source', help='The name of the object(s) to copy', nargs='+')\n copy_parser.add_argument('-d', '--destination', required=True,\n help='The copy destination. For multiple source objects this must be a '\n 'bucket.')\n copy_parser.set_defaults(func=_gcs_copy)\n\n create_parser = parser.subcommand('create', 'Create one or more Google Cloud Storage buckets.')\n create_parser.add_argument('-p', '--project', help='The project associated with the objects')\n create_parser.add_argument('-b', '--bucket', help='The name of the bucket(s) to create',\n nargs='+')\n create_parser.set_defaults(func=_gcs_create)\n\n delete_parser = parser.subcommand('delete', 'Delete one or more Google Cloud Storage buckets or '\n 'objects.')\n delete_parser.add_argument('-b', '--bucket', nargs='*',\n help='The name of the bucket(s) to remove')\n delete_parser.add_argument('-o', '--object', nargs='*',\n help='The name of the object(s) to remove')\n delete_parser.set_defaults(func=_gcs_delete)\n\n list_parser = parser.subcommand('list', 'List buckets in a project, or contents of a bucket.')\n list_parser.add_argument('-p', '--project', help='The project associated with the objects')\n list_parser.add_argument('-o', '--objects',\n help='List objects under the given Google Cloud Storage path',\n nargs='?')\n list_parser.set_defaults(func=_gcs_list)\n\n read_parser = parser.subcommand('read', 'Read the contents of a Google Cloud Storage object into '\n 'a Python variable.')\n read_parser.add_argument('-o', '--object', help='The name of the object to read',\n required=True)\n read_parser.add_argument('-v', '--variable', required=True,\n help='The name of the Python variable to set')\n read_parser.set_defaults(func=_gcs_read)\n\n view_parser = parser.subcommand('view', 'View the contents of a Google Cloud Storage object.')\n view_parser.add_argument('-n', '--head', type=int, default=20,\n help='The number of initial lines to view')\n view_parser.add_argument('-t', '--tail', type=int, default=20,\n help='The number of lines from end to view')\n view_parser.add_argument('-o', '--object', help='The name of the object to view',\n required=True)\n view_parser.set_defaults(func=_gcs_view)\n\n write_parser = parser.subcommand('write', 'Write the value of a Python variable to a Google '\n 'Cloud Storage object.')\n write_parser.add_argument('-v', '--variable', help='The name of the source Python variable',\n required=True)\n write_parser.add_argument('-o', '--object', required=True,\n help='The name of the destination Google Cloud Storage object to write')\n write_parser.add_argument('-c', '--content_type', help='MIME type', default='text/plain')\n write_parser.set_defaults(func=_gcs_write)\n\n return google.datalab.utils.commands.handle_magic_line(line, cell, parser)", "docstring": "Implements the gcs cell magic for ipython notebooks.\n\nArgs:\n line: the contents of the gcs line.\n\nReturns:\n The results of executing the cell.", "source": "juraj_google_style"} +{"code": "def __init__(self, offset):\n\n super(TimeZoneOffset, self).__init__()\n if isinstance(offset, datetime.timedelta):\n offset = total_seconds(offset) / 60\n self.__offset = offset", "docstring": "Initialize a time zone offset.\n\nArgs:\n offset: Integer or timedelta time zone offset, in minutes from UTC.\n This can be negative.", "source": "juraj_google_style"} +{"code": "def __init__(self, args=None, cmd=None):\n\n if args is None or cmd is None:\n raise errors.FormatError('Missing args or cmd value.')\n\n super(CommandSourceType, self).__init__()\n self.args = args\n self.cmd = cmd", "docstring": "Initializes a source type.\n\nArgs:\n args (list[str]): arguments to the command to run.\n cmd (str): command to run.\n\nRaises:\n FormatError: when args or cmd is not set.", "source": "juraj_google_style"} +{"code": "def _ConvertMapFieldValue(self, value, message, field):\n\n if not isinstance(value, dict):\n raise ParseError(\n 'Map field {0} must be in a dict which is {1}.'.format(\n field.name, value))\n key_field = field.message_type.fields_by_name['key']\n value_field = field.message_type.fields_by_name['value']\n for key in value:\n key_value = _ConvertScalarFieldValue(key, key_field, True)\n if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:\n self.ConvertMessage(value[key], getattr(\n message, field.name)[key_value])\n else:\n getattr(message, field.name)[key_value] = _ConvertScalarFieldValue(\n value[key], value_field)", "docstring": "Convert map field value for a message map field.\n\nArgs:\n value: A JSON object to convert the map field value.\n message: A protocol message to record the converted data.\n field: The descriptor of the map field to be converted.\n\nRaises:\n ParseError: In case of convert problems.", "source": "juraj_google_style"} +{"code": "def bounds(self, thr=0, lower_index=0, upper_index=-1):\n\n points = self.points[lower_index:upper_index]\n\n min_lat = float(\"inf\")\n min_lon = float(\"inf\")\n max_lat = -float(\"inf\")\n max_lon = -float(\"inf\")\n\n for point in points:\n min_lat = min(min_lat, point.lat)\n min_lon = min(min_lon, point.lon)\n max_lat = max(max_lat, point.lat)\n max_lon = max(max_lon, point.lon)\n\n return (min_lat - thr, min_lon - thr, max_lat + thr, max_lon + thr)", "docstring": "Computes the bounds of the segment, or part of it\n\nArgs:\n lower_index (int, optional): Start index. Defaults to 0\n upper_index (int, optional): End index. Defaults to 0\n\nReturns:\n :obj:`tuple` of :obj:`float`: Bounds of the (sub)segment, such that\n (min_lat, min_lon, max_lat, max_lon)", "source": "juraj_google_style"} +{"code": "def is_periodic_image(self, other, tolerance=1e-8, check_lattice=True):\n\n if check_lattice and self.lattice != other.lattice:\n return False\n if self.species != other.species:\n return False\n\n frac_diff = pbc_diff(self.frac_coords, other.frac_coords)\n return np.allclose(frac_diff, [0, 0, 0], atol=tolerance)", "docstring": "Returns True if sites are periodic images of each other.\n\nArgs:\n other (PeriodicSite): Other site\n tolerance (float): Tolerance to compare fractional coordinates\n check_lattice (bool): Whether to check if the two sites have the\n same lattice.\n\nReturns:\n bool: True if sites are periodic images of each other.", "source": "juraj_google_style"} +{"code": "def team_pitching_bref(team, start_season, end_season=None):\n\n if start_season is None:\n raise ValueError(\"You need to provide at least one season to collect data for. Try team_pitching_bref(season) or team_pitching_bref(start_season, end_season).\")\n if end_season is None:\n end_season = start_season\n\n url = \"https://www.baseball-reference.com/teams/{}\".format(team)\n\n data = []\n headings = None\n for season in range(start_season, end_season+1):\n print(\"Getting Pitching Data: {} {}\".format(season, team))\n stats_url = \"{}/{}.shtml\".format(url, season)\n response = requests.get(stats_url)\n soup = BeautifulSoup(response.content, 'html.parser')\n\n table = soup.find_all('table', {'id': 'team_pitching'})[0]\n\n if headings is None:\n headings = [row.text.strip() for row in table.find_all('th')[1:34]]\n\n rows = table.find_all('tr')\n for row in rows:\n cols = row.find_all('td')\n cols = [ele.text.strip() for ele in cols]\n cols = [col.replace('*', '').replace('#', '') for col in cols] # Removes '*' and '#' from some names\n cols = [col for col in cols if 'Totals' not in col and 'NL teams' not in col and 'AL teams' not in col] # Removes Team Totals and other rows\n cols.insert(2, season)\n data.append([ele for ele in cols[0:]])\n\n headings.insert(2, \"Year\")\n data = pd.DataFrame(data=data, columns=headings) # [:-5] # -5 to remove Team Totals and other rows (didn't work in multi-year queries)\n data = data.dropna() # Removes Row of All Nones\n\n return data", "docstring": "Get season-level Pitching Statistics for Specific Team (from Baseball-Reference)\n\nArgs:\n team : str : The Team Abbreviation (i.e. 'NYY' for Yankees) of the Team you want data for\n start_season : int : first season you want data for (or the only season if you do not specify an end_season)\n end_season : int : final season you want data for", "source": "juraj_google_style"} +{"code": "def get_kinds(start=None, end=None):\n\n q = Kind.query()\n if start is not None and start != '':\n q = q.filter(Kind.key >= Kind.key_for_kind(start))\n if end is not None:\n if end == '':\n return []\n q = q.filter(Kind.key < Kind.key_for_kind(end))\n\n return [x.kind_name for x in q]", "docstring": "Return all kinds in the specified range, for the current namespace.\n\nArgs:\n start: only return kinds >= start if start is not None.\n end: only return kinds < end if end is not None.\n\nReturns:\n A list of kind names between the (optional) start and end values.", "source": "juraj_google_style"} +{"code": "def to_bytesize(value, default_unit=None, base=DEFAULT_BASE):\n\n if isinstance(value, (int, float)):\n return unitized(value, default_unit, base)\n\n if value is None:\n return None\n\n try:\n if value[-1].lower() == \"b\":\n # Accept notations such as \"1mb\", as they get used out of habit\n value = value[:-1]\n\n unit = value[-1:].lower()\n if unit.isdigit():\n unit = default_unit\n\n else:\n value = value[:-1]\n\n return unitized(to_number(float, value), unit, base)\n\n except (IndexError, TypeError, ValueError):\n return None", "docstring": "Convert `value` to bytes, accepts notations such as \"4k\" to mean 4096 bytes\n\nArgs:\n value (str | unicode | int | None): Number of bytes optionally suffixed by a char from UNITS\n default_unit (str | unicode | None): Default unit to use for unqualified values\n base (int): Base to use (usually 1024)\n\nReturns:\n (int | None): Deduced bytesize value, if possible", "source": "juraj_google_style"} +{"code": "def apply_cut(self, cut):\n\n # TODO: is the MICE cache reusable?\n return MacroSubsystem(\n self.network,\n self.network_state,\n self.micro_node_indices,\n cut=cut,\n time_scale=self.time_scale,\n blackbox=self.blackbox,\n coarse_grain=self.coarse_grain)", "docstring": "Return a cut version of this |MacroSubsystem|.\n\nArgs:\n cut (Cut): The cut to apply to this |MacroSubsystem|.\n\nReturns:\n MacroSubsystem: The cut version of this |MacroSubsystem|.", "source": "juraj_google_style"} +{"code": "def AddEventData(self, event_data):\n\n self._RaiseIfNotWritable()\n\n self._AddAttributeContainer(self._CONTAINER_TYPE_EVENT_DATA, event_data)", "docstring": "Adds event data.\n\nArgs:\n event_data (EventData): event data.\n\nRaises:\n IOError: when the storage file is closed or read-only.\n OSError: when the storage file is closed or read-only.", "source": "juraj_google_style"} +{"code": "def with_row(self, row):\n\n self = self.copy()\n self.append(row)\n return self", "docstring": "Return a table with an additional row.\n\nArgs:\n ``row`` (sequence): A value for each column.\n\nRaises:\n ``ValueError``: If the row length differs from the column count.\n\n >>> tiles = Table(make_array('letter', 'count', 'points'))\n >>> tiles.with_row(['c', 2, 3]).with_row(['d', 4, 2])\n letter | count | points\n c | 2 | 3\n d | 4 | 2", "source": "juraj_google_style"} +{"code": "def build_subresource_uri(self, resource_id_or_uri=None, subresource_id_or_uri=None, subresource_path=''):\n\n if subresource_id_or_uri and \"/\" in subresource_id_or_uri:\n return subresource_id_or_uri\n else:\n if not resource_id_or_uri:\n raise exceptions.HPOneViewValueError(RESOURCE_ID_OR_URI_REQUIRED)\n\n resource_uri = self.build_uri(resource_id_or_uri)\n\n uri = \"{}/{}/{}\".format(resource_uri, subresource_path, str(subresource_id_or_uri or ''))\n uri = uri.replace(\"//\", \"/\")\n\n if uri.endswith(\"/\"):\n uri = uri[:-1]\n\n return uri", "docstring": "Helps to build a URI with resource path and its sub resource path.\n\nArgs:\n resoure_id_or_uri: ID/URI of the main resource.\n subresource_id__or_uri: ID/URI of the sub resource.\n subresource_path: Sub resource path to be added with the URI.\n\nReturns:\n Returns URI", "source": "juraj_google_style"} +{"code": "def cancel(\n self,\n accountID,\n orderSpecifier,\n **kwargs\n ):\n\n\n request = Request(\n 'PUT',\n '/v3/accounts/{accountID}/orders/{orderSpecifier}/cancel'\n )\n\n request.set_path_param(\n 'accountID',\n accountID\n )\n\n request.set_path_param(\n 'orderSpecifier',\n orderSpecifier\n )\n\n response = self.ctx.request(request)\n\n\n if response.content_type is None:\n return response\n\n if not response.content_type.startswith(\"application/json\"):\n return response\n\n jbody = json.loads(response.raw_body)\n\n parsed_body = {}\n\n #\n # Parse responses as defined by the API specification\n #\n if str(response.status) == \"200\":\n if jbody.get('orderCancelTransaction') is not None:\n parsed_body['orderCancelTransaction'] = \\\n self.ctx.transaction.OrderCancelTransaction.from_dict(\n jbody['orderCancelTransaction'],\n self.ctx\n )\n\n if jbody.get('relatedTransactionIDs') is not None:\n parsed_body['relatedTransactionIDs'] = \\\n jbody.get('relatedTransactionIDs')\n\n if jbody.get('lastTransactionID') is not None:\n parsed_body['lastTransactionID'] = \\\n jbody.get('lastTransactionID')\n\n elif str(response.status) == \"401\":\n if jbody.get('errorCode') is not None:\n parsed_body['errorCode'] = \\\n jbody.get('errorCode')\n\n if jbody.get('errorMessage') is not None:\n parsed_body['errorMessage'] = \\\n jbody.get('errorMessage')\n\n elif str(response.status) == \"404\":\n if jbody.get('orderCancelRejectTransaction') is not None:\n parsed_body['orderCancelRejectTransaction'] = \\\n self.ctx.transaction.OrderCancelRejectTransaction.from_dict(\n jbody['orderCancelRejectTransaction'],\n self.ctx\n )\n\n if jbody.get('relatedTransactionIDs') is not None:\n parsed_body['relatedTransactionIDs'] = \\\n jbody.get('relatedTransactionIDs')\n\n if jbody.get('lastTransactionID') is not None:\n parsed_body['lastTransactionID'] = \\\n jbody.get('lastTransactionID')\n\n if jbody.get('errorCode') is not None:\n parsed_body['errorCode'] = \\\n jbody.get('errorCode')\n\n if jbody.get('errorMessage') is not None:\n parsed_body['errorMessage'] = \\\n jbody.get('errorMessage')\n\n elif str(response.status) == \"405\":\n if jbody.get('errorCode') is not None:\n parsed_body['errorCode'] = \\\n jbody.get('errorCode')\n\n if jbody.get('errorMessage') is not None:\n parsed_body['errorMessage'] = \\\n jbody.get('errorMessage')\n\n #\n # Unexpected response status\n #\n else:\n parsed_body = jbody\n\n response.body = parsed_body\n\n return response", "docstring": "Cancel a pending Order in an Account\n\nArgs:\n accountID:\n Account Identifier\n orderSpecifier:\n The Order Specifier\n\nReturns:\n v20.response.Response containing the results from submitting the\n request", "source": "juraj_google_style"} +{"code": "def path_size(p: tcod.path.AStar) -> int:\n\n return int(lib.TCOD_path_size(p._path_c))", "docstring": "Return the current length of the computed path.\n\nArgs:\n p (AStar): An AStar instance.\n\nReturns:\n int: Length of the path.", "source": "juraj_google_style"} +{"code": "def read_ckan_catalog(portal_url):\n\n portal = RemoteCKAN(portal_url)\n try:\n status = portal.call_action(\n 'status_show', requests_kwargs={\"verify\": False})\n packages_list = portal.call_action(\n 'package_list', requests_kwargs={\"verify\": False})\n groups_list = portal.call_action(\n 'group_list', requests_kwargs={\"verify\": False})\n\n # itera leyendo todos los datasets del portal\n packages = []\n num_packages = len(packages_list)\n for index, pkg in enumerate(packages_list):\n # progreso (necesario cuando son muchos)\n msg = \"Leyendo dataset {} de {}\".format(index + 1, num_packages)\n logger.info(msg)\n\n # agrega un nuevo dataset a la lista\n packages.append(portal.call_action(\n 'package_show', {'id': pkg},\n requests_kwargs={\"verify\": False}\n ))\n\n # tiempo de espera padra evitar baneos\n time.sleep(0.2)\n\n # itera leyendo todos los temas del portal\n groups = [portal.call_action(\n 'group_show', {'id': grp},\n requests_kwargs={\"verify\": False})\n for grp in groups_list]\n\n catalog = map_status_to_catalog(status)\n catalog[\"dataset\"] = map_packages_to_datasets(\n packages, portal_url)\n catalog[\"themeTaxonomy\"] = map_groups_to_themes(groups)\n\n except (CKANAPIError, RequestException) as e:\n logger.exception(\n 'Error al procesar el portal %s', portal_url, exc_info=True)\n raise NonParseableCatalog(portal_url, e)\n\n return catalog", "docstring": "Convierte los metadatos de un portal disponibilizados por la Action API\n v3 de CKAN al estándar data.json.\n\nArgs:\n portal_url (str): URL de un portal de datos CKAN que soporte la API v3.\n\nReturns:\n dict: Representación interna de un catálogo para uso en las funciones\n de esta librería.", "source": "juraj_google_style"} +{"code": "def timestamp_any(value):\n\n return int(calendar.timegm(dateutil.parser.parse(value).utctimetuple()))", "docstring": "Convert timestamp string to time in seconds since epoch.\n\n Most timestamps strings are supported in fact this wraps the\n dateutil.parser.parse() method. This is SLOW use the other timestamp_*()\n functions if possible.\n\nArgs:\n value: A timestamp string.\n\nReturns:\n The time in seconds since epoch as an integer.", "source": "juraj_google_style"} +{"code": "def parse(self, text):\n\n tokens = self.lex(text)\n parser = Parser(tokens)\n return parser.parse()", "docstring": "Parse self.text.\n\nArgs:\n text (str): the text to lex\n\nReturns:\n object: a node representing the current rule.", "source": "juraj_google_style"} +{"code": "def add_dict_to_hash(a_hash, a_dict):\n\n if a_dict is None:\n return\n for k, v in a_dict.items():\n a_hash.update(b'\\x00' + k.encode('utf-8') + b'\\x00' + v.encode('utf-8'))", "docstring": "Adds `a_dict` to `a_hash`\n\nArgs:\n a_hash (`Hash`): the secure hash, e.g created by hashlib.md5\n a_dict (dict[string, [string]]): the dictionary to add to the hash", "source": "juraj_google_style"} +{"code": "def dotd(A, B, out=None):\n r\n A = asarray(A, float)\n B = asarray(B, float)\n if A.ndim == 1 and B.ndim == 1:\n if out is None:\n return dot(A, B)\n return dot(A, B, out)\n if out is None:\n out = empty((A.shape[0],), float)\n return einsum(\"ij,ji->i\", A, B, out=out)", "docstring": "r\"\"\"Diagonal of :math:`\\mathrm A\\mathrm B^\\intercal`.\n\n If ``A`` is :math:`n\\times p` and ``B`` is :math:`p\\times n`, it is done in\n :math:`O(pn)`.\n\nArgs:\n A (array_like): Left matrix.\n B (array_like): Right matrix.\n out (:class:`numpy.ndarray`, optional): copy result to.\n\nReturns:\n :class:`numpy.ndarray`: Resulting diagonal.", "source": "juraj_google_style"} +{"code": "def _GetEventData(\n self, parser_mediator, record_index, evt_record, recovered=False):\n\n event_data = WinEvtRecordEventData()\n\n try:\n event_data.record_number = evt_record.identifier\n except OverflowError as exception:\n parser_mediator.ProduceExtractionWarning((\n 'unable to read record identifier from event record: {0:d} '\n 'with error: {1!s}').format(record_index, exception))\n\n try:\n event_identifier = evt_record.event_identifier\n except OverflowError as exception:\n parser_mediator.ProduceExtractionWarning((\n 'unable to read event identifier from event record: {0:d} '\n 'with error: {1!s}').format(record_index, exception))\n\n event_identifier = None\n\n event_data.offset = evt_record.offset\n event_data.recovered = recovered\n\n # We want the event identifier to match the behavior of that of the EVTX\n # event records.\n if event_identifier is not None:\n event_data.event_identifier = event_identifier & 0xffff\n event_data.facility = (event_identifier >> 16) & 0x0fff\n event_data.severity = event_identifier >> 30\n event_data.message_identifier = event_identifier\n\n event_data.event_type = evt_record.event_type\n event_data.event_category = evt_record.event_category\n event_data.source_name = evt_record.source_name\n\n # Computer name is the value stored in the event record and does not\n # necessarily corresponds with the actual hostname.\n event_data.computer_name = evt_record.computer_name\n event_data.user_sid = evt_record.user_security_identifier\n\n event_data.strings = list(evt_record.strings)\n\n return event_data", "docstring": "Retrieves event data from the Windows EventLog (EVT) record.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n record_index (int): event record index.\n evt_record (pyevt.record): event record.\n recovered (Optional[bool]): True if the record was recovered.\n\nReturns:\n WinEvtRecordEventData: event data.", "source": "juraj_google_style"} +{"code": "def rgb_to_hex(color):\n\n rgb = eval(color.replace('rgb', ''))\n # return '#'+''.join(map(chr, rgb)).encode('hex')\n return '#' + ''.join(['{0:02x}'.format(x).upper() for x in rgb])", "docstring": "Converts from rgb to hex\n\n Parameters:\n -----------\n color : string\n Color representation on hex or rgb\n\nExample:\n rgb_to_hex('rgb(23,25,24)')", "source": "juraj_google_style"} +{"code": "def clean(df,error_rate = 0):\n\n df = df.copy()\n\n # Change colnames\n basics.clean_colnames(df)\n # Eventually use a more advanced function to clean colnames\n print('Changed colnames to {}'.format(df.columns))\n\n # Remove extra whitespace\n obj_col_list = df.select_dtypes(include = 'object').columns\n for col_name in obj_col_list:\n df[col_name] = basics.col_strip(df,col_name)\n print(\"Stripped extra whitespace from '{}'\".format(col_name))\n\n # Coerce columns if possible\n for col_name in obj_col_list:\n new_dtype = coerce_col(df,col_name,error_rate)\n if new_dtype is not None:\n print(\"Coerced '{}' to datatype '{}'\".format(col_name, new_dtype))\n\n # Scrub columns\n obj_col_list = df.select_dtypes(include = 'object').columns\n for col_name in obj_col_list:\n scrubf, scrubb = smart_scrub(df,col_name,1-error_rate)\n if scrubf is not None or scrubb is not None:\n print(\"Scrubbed '{}' from the front and '{}' from the back of column '{}'\" \\\n .format(scrubf,scrubb,col_name))\n\n # Coerice columns if possible\n for col_name in obj_col_list:\n new_dtype = coerce_col(df,col_name,error_rate)\n if new_dtype is not None:\n print(\"Coerced '{}' to datatype '{}'\".format(col_name, new_dtype)) \n return df", "docstring": "Superficially cleans data, i.e. changing simple things about formatting.\n Parameters:\n df - DataFrame\n DataFrame to clean\n error_rate - float {0 <= error_rate <= 1}, default 0\n Maximum amount of errors/inconsistencies caused explicitly by cleaning, expressed\n as a percentage of total dataframe rows (0 = 0%, .5 = 50%, etc.)\n Ex: na values from coercing a column of data to numeric", "source": "juraj_google_style"} +{"code": "def set_page_artid(self, page_start=None, page_end=None, artid=None):\n\n if page_end and not page_start:\n raise ValueError('End_page provided without start_page')\n\n self._ensure_reference_field('publication_info', {})\n publication_info = self.obj['reference']['publication_info']\n if page_start:\n publication_info['page_start'] = page_start\n if page_end:\n publication_info['page_end'] = page_end\n if artid:\n publication_info['artid'] = artid", "docstring": "Add artid, start, end pages to publication info of a reference.\n\nArgs:\n page_start(Optional[string]): value for the field page_start\n page_end(Optional[string]): value for the field page_end\n artid(Optional[string]): value for the field artid\n\nRaises:\n ValueError: when no start_page given for an end_page", "source": "juraj_google_style"} +{"code": "def recursive_chmod(path, mode=0755):\n\n passwd_reader.set_permissions(path, mode=mode)\n if os.path.isfile(path):\n return\n\n # recursively change mode of all subdirectories\n for root, dirs, files in os.walk(path):\n for fn in files + dirs:\n passwd_reader.set_permissions(os.path.join(root, fn), mode=mode)", "docstring": "Recursively change ``mode`` for given ``path``. Same as ``chmod -R mode``.\n\nArgs:\n path (str): Path of the directory/file.\n mode (octal int, default 0755): New mode of the file.\n\n Warning:\n Don't forget to add ``0`` at the beginning of the numbers of `mode`, or\n `Unspeakable hOrRoRs` will be awaken from their unholy sleep outside of\n the reality and they WILL eat your soul (and your files).", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.CompleteQuery = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.Completion/CompleteQuery\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_completion__service__pb2.CompleteQueryRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_completion__service__pb2.CompleteQueryResponse.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def __init__(self, context, name, task_id=None):\n\n self.name = name\n self.context = context\n self.task_id = task_id or get_task_id(context.claim_task)\n self.task = context.task\n self.task_type = guess_task_type(name, self.task)\n self.worker_impl = guess_worker_impl(self) # this should be scriptworker\n self.decision_task_id = get_decision_task_id(self.task)\n self.parent_task_id = get_parent_task_id(self.task)\n self.links = []", "docstring": "Initialize ChainOfTrust.\n\nArgs:\n context (scriptworker.context.Context): the scriptworker context\n name (str): the name of the task (e.g., signing)\n task_id (str, optional): the task_id of the task. If None, use\n ``get_task_id(context.claim_task)``. Defaults to None.", "source": "juraj_google_style"} +{"code": "def _circuit_as_layers(circuit: circuits.Circuit,\n grouping: _QubitGrouping) -> List[_TransformsThenCzs]:\n\n frontier = {q: 0 for q in circuit.all_qubits()}\n\n layers = []\n while True:\n # Pull within-group operations into per-group matrices.\n any_group_matrices = False\n group_matrices = []\n for g in grouping.groups:\n # Scan for reachable operations contained within the group qubits.\n start_frontier = {q: frontier[q] for q in g}\n end_frontier = circuit.reachable_frontier_from(start_frontier)\n mergeable_ops = circuit.findall_operations_between(start_frontier,\n end_frontier)\n\n # Advance frontier.\n for q, v in end_frontier.items():\n frontier[q] = v\n\n # Fold reachable operations into a single group matrix.\n group_matrix = np.eye(1 << len(g)).reshape((2, 2) * len(g))\n if mergeable_ops:\n any_group_matrices = True\n for _, op in mergeable_ops:\n group_matrix = linalg.targeted_left_multiply(\n left_matrix=protocols.unitary(op).reshape(\n (2, 2) * len(op.qubits)),\n right_target=group_matrix,\n target_axes=[grouping.loc(q)[1] for q in op.qubits])\n group_matrices.append(np.transpose(group_matrix.reshape(\n 1 << len(g), 1 << len(g))))\n\n # Scan for reachable CZ operations between groups.\n end_frontier = circuit.reachable_frontier_from(\n frontier,\n is_blocker=lambda op: grouping.all_in_same_group(*op.qubits))\n cz_ops = circuit.findall_operations_between(frontier, end_frontier)\n\n # Advance frontier.\n frontier = end_frontier\n\n # List out qubit index pairs for each CZ.\n cz_indices = []\n for _, cz in cz_ops:\n a, b = cz.qubits\n assert cz == ops.CZ(a, b)\n cz_indices.append((grouping.ind(a), grouping.ind(b)))\n\n # Combine group and CZ operations into a simulation layer.\n if not any_group_matrices and not cz_indices:\n break\n layer = _TransformsThenCzs(group_matrices=group_matrices,\n cz_indices=cz_indices)\n layers.append(layer)\n\n # We should have processed the whole circuit.\n assert frontier == {q: len(circuit) for q in circuit.all_qubits()}\n\n return layers", "docstring": "Transforms a circuit into a series of GroupMatrix+CZ layers.\n\nArgs:\n circuit: The circuit to transform.\n grouping: How the circuit's qubits are combined into groups.\n\nReturns:\n A list of layers. Each layer has a matrix to apply to each group of\n qubits, and a list of CZs to apply to pairs of qubits crossing\n between groups.", "source": "juraj_google_style"} +{"code": "def is_valid_bibtex(reference):\n\n # str is necessary since pybtex seems to have an issue with unicode. The\n # filter expression removes all non-ASCII characters.\n sio = StringIO(remove_non_ascii(reference))\n parser = bibtex.Parser()\n errors.set_strict_mode(False)\n bib_data = parser.parse_stream(sio)\n return len(bib_data.entries) > 0", "docstring": "Use pybtex to validate that a reference is in proper BibTeX format\n\nArgs:\n reference: A String reference in BibTeX format.\n\nReturns:\n Boolean indicating if reference is valid bibtex.", "source": "juraj_google_style"} +{"code": "def match(self, message) -> bool:\n\n if self.to and message.to != self.to:\n return False\n\n if self.sender and message.sender != self.sender:\n return False\n\n if self.body and message.body != self.body:\n return False\n\n if self.thread and message.thread != self.thread:\n return False\n\n for key, value in self.metadata.items():\n if message.get_metadata(key) != value:\n return False\n\n logger.debug(f\"message matched {self} == {message}\")\n return True", "docstring": "Returns wether a message matches with this message or not.\n The message can be a Message object or a Template object.\n\nArgs:\n message (spade.message.Message): the message to match to\n\nReturns:\n bool: wether the message matches or not", "source": "juraj_google_style"} +{"code": "def str2dict_values(str_in):\n\n tmp_dict = str2dict(str_in)\n if tmp_dict is None:\n return None\n return [tmp_dict[key] for key in sorted(k for k in tmp_dict)]", "docstring": "Extracts the values from a string that represents a dict and returns them\n sorted by key.\n\nArgs:\n str_in (string) that contains python dict\n\nReturns:\n (list) with values or None if no valid dict was found\n\nRaises:\n -", "source": "juraj_google_style"} +{"code": "def getSchedulesBuffer(self, period_group):\n\n empty_return = SerialBlock()\n if period_group == ReadSchedules.Schedules_1_To_4:\n return self.m_schd_1_to_4\n elif period_group == ReadSchedules.Schedules_5_To_6:\n return self.m_schd_5_to_6\n else:\n return empty_return", "docstring": "Return the requested tariff schedule :class:`~ekmmeters.SerialBlock` for meter.\n\nArgs:\n period_group (int): A :class:`~ekmmeters.ReadSchedules` value.\n\nReturns:\n SerialBlock: The requested tariff schedules for meter.", "source": "juraj_google_style"} +{"code": "def check_hours(tickers, tz_exch, tz_loc=DEFAULT_TZ) -> pd.DataFrame:\n\n cols = ['Trading_Day_Start_Time_EOD', 'Trading_Day_End_Time_EOD']\n con, _ = create_connection()\n hours = con.ref(tickers=tickers, flds=cols)\n cur_dt = pd.Timestamp('today').strftime('%Y-%m-%d ')\n hours.loc[:, 'local'] = hours.value.astype(str).str[:-3]\n hours.loc[:, 'exch'] = pd.DatetimeIndex(\n cur_dt + hours.value.astype(str)\n ).tz_localize(tz_loc).tz_convert(tz_exch).strftime('%H:%M')\n\n hours = pd.concat([\n hours.set_index(['ticker', 'field']).exch.unstack().loc[:, cols],\n hours.set_index(['ticker', 'field']).local.unstack().loc[:, cols],\n ], axis=1)\n hours.columns = ['Exch_Start', 'Exch_End', 'Local_Start', 'Local_End']\n\n return hours", "docstring": "Check exchange hours vs local hours\n\nArgs:\n tickers: list of tickers\n tz_exch: exchange timezone\n tz_loc: local timezone\n\nReturns:\n Local and exchange hours", "source": "juraj_google_style"} +{"code": "def splat(f: Callable[..., A]) -> Callable[[Iterable], A]:\n\n\n def splatted(args):\n return f(*args)\n\n return splatted", "docstring": "Convert a function taking multiple arguments into a function taking a single iterable argument.\n\nArgs:\n f: Any function\n\nReturns:\n A function that accepts a single iterable argument. Each element of this iterable argument is passed as an\n argument to ``f``.\n\nExample:\n $ def f(a, b, c):\n $ return a + b + c\n $\n $ f(1, 2, 3) # 6\n $ g = splat(f)\n $ g([1, 2, 3]) # 6", "source": "juraj_google_style"} +{"code": "def _ParseDistributedTrackingIdentifier(\n self, parser_mediator, uuid_object, origin):\n\n if uuid_object.version == 1:\n event_data = windows_events.WindowsDistributedLinkTrackingEventData(\n uuid_object, origin)\n date_time = dfdatetime_uuid_time.UUIDTime(timestamp=uuid_object.time)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_CREATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n return '{{{0!s}}}'.format(uuid_object)", "docstring": "Extracts data from a Distributed Tracking identifier.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n uuid_object (uuid.UUID): UUID of the Distributed Tracking identifier.\n origin (str): origin of the event (event source).\n\nReturns:\n str: UUID string of the Distributed Tracking identifier.", "source": "juraj_google_style"} +{"code": "def add_jpeg_decoding(module_spec):\n\n input_height, input_width = hub.get_expected_image_size(module_spec)\n input_depth = hub.get_num_image_channels(module_spec)\n jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput')\n decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)\n # Convert from full range of uint8 to range [0,1] of float32.\n decoded_image_as_float = tf.image.convert_image_dtype(decoded_image,\n tf.float32)\n decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)\n resize_shape = tf.stack([input_height, input_width])\n resize_shape_as_int = tf.cast(resize_shape, dtype=tf.int32)\n resized_image = tf.image.resize_bilinear(decoded_image_4d,\n resize_shape_as_int)\n return jpeg_data, resized_image", "docstring": "Adds operations that perform JPEG decoding and resizing to the graph..\n\nArgs:\n module_spec: The hub.ModuleSpec for the image module being used.\n\nReturns:\n Tensors for the node to feed JPEG data into, and the output of the\n preprocessing steps.", "source": "juraj_google_style"} +{"code": "def filter_list_by_indices(lst, indices):\n\n return [x for i, x in enumerate(lst) if i in indices]", "docstring": "Return a modified list containing only the indices indicated.\n\nArgs:\n lst: Original list of values\n indices: List of indices to keep from the original list\n\nReturns:\n list: Filtered list of values", "source": "juraj_google_style"} +{"code": "def format(self, *args, **kwargs):\n\n inplace = kwargs.pop(\"inplace\", False)\n if not inplace:\n return str(self).format(*args, **kwargs)\n self._lines = str(self).format(*args, **kwargs).splitlines()", "docstring": "Format the string representation of the editor.\n\nArgs:\n inplace (bool): If True, overwrite editor's contents with formatted contents", "source": "juraj_google_style"} +{"code": "def _add_sv_coordinates(self, variant):\n\n variant.stop_chrom = variant.CHROM\n variant.start = int(variant.POS)\n\n # If we have a translocation:\n if ':' in variant.ALT:\n other_coordinates = variant.ALT.strip('ACGTN[]').split(':')\n variant.stop_chrom = other_coordinates[0].lstrip('chrCHR')\n other_position = other_coordinates[1]\n # variant.stop = other_position\n\n #Set 'infinity' to length if translocation\n variant.sv_len = float('inf')\n variant.sv_type = 'BND'\n else:\n variant.sv_len = variant.stop - variant.start\n\n variant['cytoband_start'] = get_cytoband_coord(\n chrom=variant.CHROM,\n pos=variant.start\n )\n\n variant['cytoband_stop'] = get_cytoband_coord(\n chrom=variant.stop_chrom,\n pos=variant.stop\n )", "docstring": "Add the neccesary sv coordinates for a variant\n\nArgs:\n variant (puzzle.models.variant)", "source": "juraj_google_style"} +{"code": "def bearer_auth():\n\n authorization = request.headers.get(\"Authorization\")\n if not (authorization and authorization.startswith(\"Bearer \")):\n response = app.make_response(\"\")\n response.headers[\"WWW-Authenticate\"] = \"Bearer\"\n response.status_code = 401\n return response\n slice_start = len(\"Bearer \")\n token = authorization[slice_start:]\n\n return jsonify(authenticated=True, token=token)", "docstring": "Prompts the user for authorization using bearer authentication.\n ---\n tags:\n - Auth\n parameters:\n - in: header\n name: Authorization\n schema:\n type: string\n produces:\n - application/json\n responses:\n 200:\n description: Sucessful authentication.\n 401:\n description: Unsuccessful authentication.", "source": "juraj_google_style"} +{"code": "def remove_father(self, father):\n\n self._fathers = [x for x in self._fathers if x.node_id != father.node_id]", "docstring": "Remove the father node. Do nothing if the node is not a father\n\nArgs:\n fathers: list of fathers to add", "source": "juraj_google_style"} +{"code": "def calculate_columns(sequence):\n\n columns = {}\n\n for row in sequence:\n for key in row.keys():\n if key not in columns:\n columns[key] = len(key)\n\n value_length = len(str(row[key]))\n if value_length > columns[key]:\n columns[key] = value_length\n\n return columns", "docstring": "Find all row names and the maximum column widths.\n\nArgs:\n columns (dict): the keys are the column name and the value the max length.\n\nReturns:\n dict: column names (key) and widths (value).", "source": "juraj_google_style"} +{"code": "def getmtime(self, path=None, client_kwargs=None, header=None):\n\n return self._getmtime_from_header(\n self.head(path, client_kwargs, header))", "docstring": "Return the time of last access of path.\n\nArgs:\n path (str): File path or URL.\n client_kwargs (dict): Client arguments.\n header (dict): Object header.\n\nReturns:\n float: The number of seconds since the epoch\n (see the time module).", "source": "juraj_google_style"} +{"code": "def get_directorship_heads(self, val):\n\n\n __ldap_group_ou__ = \"cn=groups,cn=accounts,dc=csh,dc=rit,dc=edu\"\n\n res = self.__con__.search_s(\n __ldap_group_ou__,\n ldap.SCOPE_SUBTREE,\n \"(cn=eboard-%s)\" % val,\n ['member'])\n\n ret = []\n for member in res[0][1]['member']:\n try:\n ret.append(member.decode('utf-8'))\n except UnicodeDecodeError:\n ret.append(member)\n except KeyError:\n continue\n\n return [CSHMember(self,\n dn.split('=')[1].split(',')[0],\n True)\n for dn in ret]", "docstring": "Get the head of a directorship\n\nArgs:\n val -- the cn of the directorship", "source": "juraj_google_style"} +{"code": "def run(self, dag):\n\n if self.layout is None:\n if self.property_set[\"layout\"]:\n self.layout = self.property_set[\"layout\"]\n else:\n self.layout = Layout.generate_trivial_layout(*dag.qregs.values())\n\n self.property_set['is_direction_mapped'] = True\n edges = self.coupling_map.get_edges()\n\n for gate in dag.twoQ_gates():\n physical_q0 = self.layout[gate.qargs[0]]\n physical_q1 = self.layout[gate.qargs[1]]\n\n if isinstance(gate.op, (CXBase, CnotGate)) and (\n physical_q0, physical_q1) not in edges:\n self.property_set['is_direction_mapped'] = False\n return", "docstring": "If `dag` is mapped and the direction is correct the property\n `is_direction_mapped` is set to True (or to False otherwise).\n\nArgs:\n dag (DAGCircuit): DAG to check.", "source": "juraj_google_style"} +{"code": "def add_info_to_exception(err: Exception, info: Dict) -> None:\n # noqa\n if not err.args:\n err.args = ('', )\n err.args += (info, )", "docstring": "Adds an information dictionary to an exception.\n\n See\n http://stackoverflow.com/questions/9157210/how-do-i-raise-the-same-exception-with-a-custom-message-in-python\n\nArgs:\n err: the exception to be modified\n info: the information to add", "source": "juraj_google_style"} +{"code": "def sk_log_loss(y_true: Union[List[List[float]], List[List[int]], np.ndarray],\n y_predicted: Union[List[List[float]], List[List[int]], np.ndarray]) -> float:\n\n return log_loss(y_true, y_predicted)", "docstring": "Calculates log loss.\n\nArgs:\n y_true: list or array of true values\n y_predicted: list or array of predicted values\n\nReturns:\n Log loss", "source": "juraj_google_style"} +{"code": "def gibbs_binding_energy(self, eads=False):\n\n\n n = self.get_unit_primitive_area\n Nads = self.Nads_in_slab\n\n BE = (self.energy - n * self.clean_entry.energy) / Nads - \\\n sum([ads.energy_per_atom for ads in self.adsorbates])\n return BE * Nads if eads else BE", "docstring": "Returns the adsorption energy or Gibb's binding energy\n of an adsorbate on a surface\n\nArgs:\n eads (bool): Whether to calculate the adsorption energy\n (True) or the binding energy (False) which is just\n adsorption energy normalized by number of adsorbates.", "source": "juraj_google_style"} +{"code": "def pnl(self, account='', modelCode='') -> List[PnL]:\n\n return [v for v in self.wrapper.pnls.values() if\n (not account or v.account == account) and\n (not modelCode or v.modelCode == modelCode)]", "docstring": "List of subscribed :class:`.PnL` objects (profit and loss),\n optionally filtered by account and/or modelCode.\n\n The :class:`.PnL` objects are kept live updated.\n\nArgs:\n account: If specified, filter for this account name.\n modelCode: If specified, filter for this account model.", "source": "juraj_google_style"} +{"code": "def data_period_name_or_description(self, value=None):\n\n if value is not None:\n try:\n value = str(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type str '\n 'for field `data_period_name_or_description`'.format(value))\n if ',' in value:\n raise ValueError('value should not contain a comma '\n 'for field `data_period_name_or_description`')\n\n self._data_period_name_or_description = value", "docstring": "Corresponds to IDD Field `data_period_name_or_description`\n\nArgs:\n value (str): value for IDD Field `data_period_name_or_description`\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def setModelData(self, editor, model, index):\n\n model.setData(index, editor.itemText(editor.currentIndex()))", "docstring": "Updates the model after changing data in the editor.\n\nArgs:\n editor (QtGui.QComboBox): The current editor for the item. Should be\n a `QtGui.QComboBox` as defined in `createEditor`.\n model (ColumnDtypeModel): The model which holds the displayed data.\n index (QtCore.QModelIndex): The index of the current item of the model.", "source": "juraj_google_style"} +{"code": "def from_int(i):\n\n point = ECPointAffine.from_int(bitcoin_curve, i)\n return PublicKey.from_point(point)", "docstring": "Generates a public key object from an integer.\n\nNote:\n This assumes that the upper 32 bytes of the integer\n are the x component of the public key point and the\n lower 32 bytes are the y component.\n\nArgs:\n i (Bignum): A 512-bit integer representing the public\n key point on the secp256k1 curve.\n\nReturns:\n PublicKey: A PublicKey object.", "source": "juraj_google_style"} +{"code": "def validate_and_decode(jwt_bu64, cert_obj):\n\n try:\n return jwt.decode(\n jwt_bu64.strip(), cert_obj.public_key(), algorithms=['RS256'], verify=True\n )\n except jwt.InvalidTokenError as e:\n raise JwtException('Signature is invalid. error=\"{}\"'.format(str(e)))", "docstring": "Validate the JWT and return as a dict.\n\n - JWTs contain a set of values serialized to a JSON dict. This decodes the JWT and\n returns it as a dict.\n\nArgs:\n jwt_bu64: bytes\n The JWT encoded using a a URL safe flavor of Base64.\n\n cert_obj: cryptography.Certificate\n Public certificate used for signing the JWT (typically the CN cert).\n\nRaises:\n JwtException: If validation fails.\n\nReturns:\n dict: Values embedded in the JWT.", "source": "juraj_google_style"} +{"code": "def GetFileObject(self, data_stream_name=''):\n\n if data_stream_name:\n return None\n\n return resolver.Resolver.OpenFileObject(\n self.path_spec, resolver_context=self._resolver_context)", "docstring": "Retrieves the file-like object.\n\nArgs:\n data_stream_name (Optional[str]): name of the data stream, where an empty\n string represents the default data stream.\n\nReturns:\n FileIO: a file-like object or None if not available.", "source": "juraj_google_style"} +{"code": "def encode_message(self, message):\n\n message.check_initialized()\n\n return json.dumps(message, cls=MessageJSONEncoder,\n protojson_protocol=self)", "docstring": "Encode Message instance to JSON string.\n\nArgs:\n Message instance to encode in to JSON string.\n\nReturns:\n String encoding of Message instance in protocol JSON format.\n\nRaises:\n messages.ValidationError if message is not initialized.", "source": "juraj_google_style"} +{"code": "def decode(self, encoded):\n\n encoded = super().decode(encoded)\n tokens = [self.itos[index] for index in encoded]\n return self.detokenize(tokens)", "docstring": "Decodes a tensor into a sequence.\n\nArgs:\n encoded (torch.Tensor): Encoded sequence.\n\nReturns:\n str: Sequence decoded from ``encoded``.", "source": "juraj_google_style"} +{"code": "def absolute_magnitude(self, richness=1, steps=1e4):\n\n # Using the SDSS g,r -> V from Jester 2005 [astro-ph/0506022]\n # for stars with R-I < 1.15\n # V = g_sdss - 0.59*(g_sdss - r_sdss) - 0.01\n\n # Create a copy of the isochrone in the SDSS system\n params = {k:v.value for k,v in self._params.items()}\n params.update(band_1='g',band_2='r',survey='sdss')\n iso = self.__class__(**params)\n\n # g, r are absolute magnitude\n mass_init, mass_pdf, mass_act, sdss_g, sdss_r = iso.sample(mass_steps=steps)\n V = jester_mag_v(sdss_g,sdss_r)\n\n # Sum the V-band absolute magnitudes\n return sum_mags(V,weights=mass_pdf*richness)", "docstring": "Calculate the absolute visual magnitude (Mv) from the richness\n by transforming the isochrone in the SDSS system and using the\n g,r -> V transform equations from Jester 2005\n [astro-ph/0506022].\n\n\n Parameters:\n -----------\n richness : isochrone normalization parameter\n steps : number of isochrone sampling steps\n\nReturns:\n --------\n abs_mag : Absolute magnitude (Mv)", "source": "juraj_google_style"} +{"code": "def _print_task_data(self, task):\n\n print(' {0:s} ({1:s})'.format(task['name'], task['id']))\n paths = task.get('saved_paths', [])\n if not paths:\n return\n for path in paths:\n if path.endswith('worker-log.txt'):\n continue\n if path.endswith('{0:s}.log'.format(task.get('id'))):\n continue\n if path.startswith('/'):\n continue\n print(' ' + path)", "docstring": "Pretty-prints task data.\n\nArgs:\n task: Task dict generated by Turbinia.", "source": "juraj_google_style"} +{"code": "def create_schema(host):\n\n connection = create_blocking_connection(host)\n channel = connection.channel()\n\n exchange = settings.get_amqp_settings()[host][\"exchange\"]\n channel.exchange_declare(\n exchange=exchange,\n exchange_type=\"topic\",\n durable=True\n )\n print \"Created exchange '%s'.\" % exchange\n print \"Creating queues:\"\n\n queues = settings.get_amqp_settings()[host][\"queues\"]\n for queue in queues.keys():\n channel.queue_declare(\n queue=queue,\n durable=True,\n # arguments={'x-message-ttl': int(1000 * 60 * 60 * 24)} # :S\n )\n print \"\\tCreated durable queue '%s'.\" % queue\n\n print\n print \"Routing exchanges using routing key to queues:\"\n\n for queue in queues.keys():\n channel.queue_bind(\n queue=queue,\n exchange=exchange,\n routing_key=queues[queue]\n )\n\n print \"\\tRouting exchange %s['%s'] -> '%s'.\" % (\n exchange,\n queues[queue],\n queue\n )", "docstring": "Create exchanges, queues and route them.\n\nArgs:\n host (str): One of the possible hosts.", "source": "juraj_google_style"} +{"code": "def unique_everseen(iterable, key=None):\n\n\n seen = set()\n seen_add = seen.add\n\n if key is None:\n\n for element in filterfalse(seen.__contains__, iterable):\n\n seen_add(element)\n yield element\n\n else:\n\n for element in iterable:\n\n k = key(element)\n\n if k not in seen:\n\n seen_add(k)\n yield element", "docstring": "The generator to list unique elements, preserving the order. Remember all\n elements ever seen. This was taken from the itertools recipes.\n\nArgs:\n iterable (:obj:`iter`): An iterable to process.\n key (:obj:`callable`): Optional function to run when checking\n elements (e.g., str.lower)\n\nYields:\n The next unique element found.", "source": "juraj_google_style"} +{"code": "def delete(self, task_name):\n\n r = self.gbdx_connection.delete(self._base_url + '/' + task_name)\n raise_for_status(r)\n\n return r.text", "docstring": "Deletes a GBDX task.\n\nArgs:\n task_name (str): Task name.\n\nReturns:\n Response (str).", "source": "juraj_google_style"} +{"code": "def setup(self,\n hosts, files, use_tsk,\n reason, grr_server_url, grr_username, grr_password, approvers=None,\n verify=True):\n\n super(GRRFileCollector, self).setup(\n reason, grr_server_url, grr_username, grr_password,\n approvers=approvers, verify=verify)\n\n if files is not None:\n self.files = [item.strip() for item in files.strip().split(',')]\n\n self.hostnames = [item.strip() for item in hosts.strip().split(',')]\n self.use_tsk = use_tsk", "docstring": "Initializes a GRR file collector.\n\nArgs:\n hosts: Comma-separated list of hostnames to launch the flow on.\n files: list of file paths.\n use_tsk: toggle for use_tsk flag on GRR flow.\n reason: justification for GRR access.\n grr_server_url: GRR server URL.\n grr_username: GRR username.\n grr_password: GRR password.\n approvers: list of GRR approval recipients.\n verify: boolean, whether to verify the GRR server's x509 certificate.", "source": "juraj_google_style"} +{"code": "def run(self):\n\n while self.should_run:\n try:\n self.logger.debug('Sending heartbeat, seq ' + last_sequence)\n self.ws.send(json.dumps({\n 'op': 1,\n 'd': last_sequence\n }))\n except Exception as e:\n self.logger.error(f'Got error in heartbeat: {str(e)}')\n finally:\n elapsed = 0.0\n while elapsed < self.interval and self.should_run:\n time.sleep(self.TICK_INTERVAL)\n elapsed += self.TICK_INTERVAL", "docstring": "Runs the thread\n\n This method handles sending the heartbeat to the Discord websocket server, so the connection\n can remain open and the bot remain online for those commands that require it to be.\n\nArgs:\n None", "source": "juraj_google_style"} +{"code": "def get_aws_unique_id(timeout=DEFAULT_AWS_TIMEOUT):\n\n try:\n resp = requests.get(AWS_ID_URL, timeout=timeout).json()\n except requests.exceptions.ConnectTimeout:\n _logger.warning('Connection timeout when determining AWS unique '\n 'ID. Not using AWS unique ID.')\n return None\n else:\n aws_id = \"{0}_{1}_{2}\".format(resp['instanceId'], resp['region'],\n resp['accountId'])\n _logger.debug('Using AWS unique ID %s.', aws_id)\n return aws_id", "docstring": "Determine the current AWS unique ID\n\nArgs:\n timeout (int): How long to wait for a response from AWS metadata IP", "source": "juraj_google_style"} +{"code": "def write_bashrc(_path):\n\n cfg_mounts = CFG[\"container\"][\"mounts\"].value\n cfg_prefix = CFG[\"container\"][\"prefixes\"].value\n\n path.mkfile_uchroot(\"/etc/portage/bashrc\")\n mounts = uchroot.mounts(\"mnt\", cfg_mounts)\n p_paths, p_libs = uchroot.env(cfg_prefix)\n paths, libs = uchroot.env(mounts)\n\n paths = paths + p_paths\n libs = libs + p_libs\n\n with open(_path, 'w') as bashrc:\n lines = .format(path.list_to_path(paths), path.list_to_path(libs))\n\n bashrc.write(lines)", "docstring": "Write a valid gentoo bashrc file to :path:.\n\nArgs:\n path - The output path of the make.conf", "source": "juraj_google_style"} +{"code": "def __init__(self, webhook_obj, alert_recipient=None): # pragma: no cover\n\n logging.Handler.__init__(self)\n self.webhook_obj = webhook_obj\n if not self.webhook_obj: # test if it's configured\n raise Exception('Webhook not configured.')\n\n self.api_url = webhook_obj.webhook_url\n self.alert_recipient = alert_recipient\n self.alert_length = 0\n if self.alert_recipient:\n self.alert_length = len(self.alert_recipient)", "docstring": "HackyDiscordHandler init\n\nArgs:\n webhook_obj (:obj:`DiscordWebhook`): discord webhook has all the info for connection\n alert_recipients (`str`:<@int>, optional): user/group to notify", "source": "juraj_google_style"} +{"code": "def random_restore(\n rnd: Optional[tcod.random.Random], backup: tcod.random.Random\n) -> None:\n\n lib.TCOD_random_restore(rnd.random_c if rnd else ffi.NULL, backup.random_c)", "docstring": "Restore a random number generator from a backed up copy.\n\nArgs:\n rnd (Optional[Random]): A Random instance, or None to use the default.\n backup (Random): The Random instance which was used as a backup.\n\n .. deprecated:: 8.4\n You can use the standard library copy and pickle modules to save a\n random state.", "source": "juraj_google_style"} +{"code": "def update(field, value, db, collection, match=None):\n\n c = db[collection]\n match = match if match is not None else {}\n # check MongoDB version to use appropriate update command\n if db.client.server_info()['version'].startswith('2'):\n c.update(match, {'$set': {field: value}}, multi=True)\n else:\n c.update_many(match, {'$set': {field: value}})", "docstring": "Updates MongoDB documents.\n\n Sets ``field`` equal to ``value`` for all documents that\n meet ``match`` criteria.\n\nArgs:\n field (str): Field to update.\n\n value (str): Update value.\n\n db (Database): A pymongo Database object.\n\n collection (str): Collection name.\n\n match (dict): A dictionary containing the match criteria, for example::\n\n {'seq_id': {'$in': ['a', 'b', 'c']}, 'cdr3_len': {'$gte': 18}}", "source": "juraj_google_style"} +{"code": "def apply(self, data, path=None, applicator=None):\n\n\n if applicator:\n applicator.pset = self\n else:\n applicator = Applicator(self)\n\n return applicator.apply(data, path=path)", "docstring": "Apply permissions in this set to the provided data, effectively\n removing all keys from it are not permissioned to be viewed\n\nArgs:\n data -- dict of data\n\nReturns:\n Cleaned data", "source": "juraj_google_style"} +{"code": "def ParseBookmarkRow(\n self, parser_mediator, query, row, **unused_kwargs):\n\n query_hash = hash(query)\n\n rev_host = self._GetRowValue(query_hash, row, 'rev_host')\n bookmark_type = self._GetRowValue(query_hash, row, 'type')\n\n event_data = FirefoxPlacesBookmarkEventData()\n event_data.host = rev_host or 'N/A'\n event_data.offset = self._GetRowValue(query_hash, row, 'id')\n event_data.places_title = self._GetRowValue(query_hash, row, 'places_title')\n event_data.query = query\n event_data.title = self._GetRowValue(query_hash, row, 'bookmark_title')\n event_data.type = self._BOOKMARK_TYPES.get(bookmark_type, 'N/A')\n event_data.url = self._GetRowValue(query_hash, row, 'url')\n event_data.visit_count = self._GetRowValue(query_hash, row, 'visit_count')\n\n timestamp = self._GetRowValue(query_hash, row, 'dateAdded')\n if timestamp:\n date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(\n timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_ADDED)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = self._GetRowValue(query_hash, row, 'lastModified')\n if timestamp:\n date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(\n timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_MODIFICATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a bookmark row.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n query (str): query that created the row.\n row (sqlite3.Row): row.", "source": "juraj_google_style"} +{"code": "def get_filelikeobject(filename: str = None,\n blob: bytes = None) -> BinaryIO:\n\n if not filename and not blob:\n raise ValueError(\"no filename and no blob\")\n if filename and blob:\n raise ValueError(\"specify either filename or blob\")\n if filename:\n return open(filename, 'rb')\n else:\n return io.BytesIO(blob)", "docstring": "Open a file-like object.\n\n Guard the use of this function with ``with``.\n\nArgs:\n filename: for specifying via a filename\n blob: for specifying via an in-memory ``bytes`` object\n\nReturns:\n a :class:`BinaryIO` object", "source": "juraj_google_style"} +{"code": "def from_dict(cls, fields, mapping):\n\n iterable = [None] * len(fields)\n for key, value in mapping.items():\n try:\n index = fields.index(key)\n except KeyError:\n raise ItsdbError('Invalid field name(s): ' + key)\n iterable[index] = value\n return cls(fields, iterable)", "docstring": "Create a Record from a dictionary of field mappings.\n\n The *fields* object is used to determine the column indices\n of fields in the mapping.\n\nArgs:\n fields: the Relation schema for the table of this record\n mapping: a dictionary or other mapping from field names to\n column values\n\nReturns:\n a :class:`Record` object", "source": "juraj_google_style"} +{"code": "def handle_message(self, ch, method, properties, body):\n\n input = {}\n headers = {}\n try:\n self.sessid = method.routing_key\n\n input = json_decode(body)\n data = input['data']\n\n # since this comes as \"path\" we dont know if it's view or workflow yet\n # TODO: just a workaround till we modify ui to\n if 'path' in data:\n if data['path'] in VIEW_METHODS:\n data['view'] = data['path']\n else:\n data['wf'] = data['path']\n session = Session(self.sessid)\n\n headers = {'remote_ip': input['_zops_remote_ip'],\n 'source': input['_zops_source']}\n\n if 'wf' in data:\n output = self._handle_workflow(session, data, headers)\n elif 'job' in data:\n\n self._handle_job(session, data, headers)\n return\n else:\n output = self._handle_view(session, data, headers)\n\n except HTTPError as e:\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n output = {\"cmd\": \"error\", \"error\": self._prepare_error_msg(e.message), \"code\": e.code}\n log.exception(\"Http error occurred\")\n except:\n self.current = Current(session=session, input=data)\n self.current.headers = headers\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n err = traceback.format_exc()\n output = {\"cmd\": \"error\", \"error\": self._prepare_error_msg(err), \"code\": 500}\n log.exception(\"Worker error occurred with messsage body:\\n%s\" % body)\n if 'callbackID' in input:\n output['callbackID'] = input['callbackID']\n log.info(\"OUTPUT for %s: %s\" % (self.sessid, output))\n output['reply_timestamp'] = time()\n self.send_output(output)", "docstring": "this is a pika.basic_consumer callback\n handles client inputs, runs appropriate workflows and views\n\nArgs:\n ch: amqp channel\n method: amqp method\n properties:\n body: message body", "source": "juraj_google_style"} +{"code": "def is_valid_nhs_number(n: int) -> bool:\n # noqa\n if not isinstance(n, int):\n log.debug(\"is_valid_nhs_number: parameter was not of integer type\")\n return False\n\n s = str(n)\n # Not 10 digits long?\n if len(s) != 10:\n log.debug(\"is_valid_nhs_number: not 10 digits\")\n return False\n\n main_digits = [int(s[i]) for i in range(9)]\n actual_check_digit = int(s[9]) # tenth digit\n expected_check_digit = nhs_check_digit(main_digits)\n if expected_check_digit == 10:\n log.debug(\"is_valid_nhs_number: calculated check digit invalid\")\n return False\n if expected_check_digit != actual_check_digit:\n log.debug(\"is_valid_nhs_number: check digit mismatch\")\n return False\n # Hooray!\n return True", "docstring": "Validates an integer as an NHS number.\n\nArgs:\n n: NHS number\n\nReturns:\n valid?\n\n Checksum details are at\n http://www.datadictionary.nhs.uk/version2/data_dictionary/data_field_notes/n/nhs_number_de.asp", "source": "juraj_google_style"} +{"code": "def delete_all(self, filter=None, timeout=-1):\n\n return self._client.delete_all(filter=filter, timeout=timeout)", "docstring": "Delete an SNMPv3 User based on User name specified in filter. The user will be deleted only if it has no associated destinations.\n\nArgs:\n username: ID or URI of SNMPv3 user.\n filter: A general filter/query string to narrow the list of items returned.\n The default is no filter - all resources are returned.\n\nReturns:\n bool: Indicates if the resource was successfully deleted.", "source": "juraj_google_style"} +{"code": "def find_all_by_mapreduce_state(cls, mapreduce_state):\n\n keys = cls.calculate_keys_by_mapreduce_state(mapreduce_state)\n i = 0\n while i < len(keys):\n @db.non_transactional\n def no_tx_get(i):\n return db.get(keys[i:i+cls._MAX_STATES_IN_MEMORY])\n # We need a separate function to so that we can mix non-transactional and\n # use be a generator\n states = no_tx_get(i)\n for s in states:\n i += 1\n if s is not None:\n yield s", "docstring": "Find all shard states for given mapreduce.\n\nArgs:\n mapreduce_state: MapreduceState instance\n\nYields:\n shard states sorted by shard id.", "source": "juraj_google_style"} +{"code": "def relevant(symbol, token='', version=''):\n\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/relevant', token, version)", "docstring": "Same as peers\n\n https://iexcloud.io/docs/api/#relevant\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n dict: result", "source": "juraj_google_style"} +{"code": "def serialize_example(transformed_json_data, features, feature_indices, target_name):\n\n import six\n import tensorflow as tf\n from trainer import feature_transforms\n\n line = str(transformed_json_data[target_name][0])\n for name, info in feature_indices:\n if features[name]['transform'] in [feature_transforms.IDENTITY_TRANSFORM,\n feature_transforms.SCALE_TRANSFORM]:\n line += ' %d:%s' % (info['index_start'], str(transformed_json_data[name][0]))\n elif features[name]['transform'] in [feature_transforms.ONE_HOT_TRANSFORM,\n feature_transforms.MULTI_HOT_TRANSFORM]:\n for i in range(info['size']):\n if i in transformed_json_data[name]:\n line += ' %d:1' % (info['index_start'] + i)\n elif features[name]['transform'] in [feature_transforms.IMAGE_TRANSFORM]:\n for i in range(info['size']):\n line += ' %d:%s' % (info['index_start'] + i, str(transformed_json_data[name][i]))\n\n return line", "docstring": "Makes an instance of data in libsvm format.\n\nArgs:\n transformed_json_data: dict of transformed data.\n features: features config.\n feature_indices: output of feature_transforms.get_transformed_feature_indices()\n\nReturns:\n The text line representation of an instance in libsvm format.", "source": "juraj_google_style"} +{"code": "def set_heat_pump_feature(self, device_label, feature):\n\n response = None\n try:\n response = requests.put(\n urls.set_heatpump_feature(self._giid, device_label, feature),\n headers={\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Cookie': 'vid={}'.format(self._vid)})\n except requests.exceptions.RequestException as ex:\n raise RequestError(ex)\n _validate_response(response)\n return json.loads(response.text)", "docstring": "Set heatpump mode\n\nArgs:\n feature: 'QUIET', 'ECONAVI', or 'POWERFUL'", "source": "juraj_google_style"} +{"code": "def GetMessages(self, files):\n\n result = {}\n for file_name in files:\n file_desc = self.pool.FindFileByName(file_name)\n for name, msg in file_desc.message_types_by_name.items():\n if file_desc.package:\n full_name = '.'.join([file_desc.package, name])\n else:\n full_name = msg.name\n result[full_name] = self.GetPrototype(\n self.pool.FindMessageTypeByName(full_name))\n\n # While the extension FieldDescriptors are created by the descriptor pool,\n # the python classes created in the factory need them to be registered\n # explicitly, which is done below.\n #\n # The call to RegisterExtension will specifically check if the\n # extension was already registered on the object and either\n # ignore the registration if the original was the same, or raise\n # an error if they were different.\n\n for name, extension in file_desc.extensions_by_name.items():\n if extension.containing_type.full_name not in self._classes:\n self.GetPrototype(extension.containing_type)\n extended_class = self._classes[extension.containing_type.full_name]\n extended_class.RegisterExtension(extension)\n return result", "docstring": "Gets all the messages from a specified file.\n\n This will find and resolve dependencies, failing if the descriptor\n pool cannot satisfy them.\n\nArgs:\n files: The file names to extract messages from.\n\nReturns:\n A dictionary mapping proto names to the message classes. This will include\n any dependent messages as well as any messages defined in the same file as\n a specified message.", "source": "juraj_google_style"} +{"code": "def enter_diff_mode(self, context_model=None):\n\n assert not self.diff_mode\n self.diff_mode = True\n\n if context_model is None:\n self.diff_from_source = True\n self.diff_context_model = self.context_model.copy()\n else:\n self.diff_from_source = False\n self.diff_context_model = context_model\n\n self.clear()\n self.setColumnCount(5)\n self.refresh()", "docstring": "Enter diff mode.\n\nArgs:\n context_model (`ContextModel`): Context to diff against. If None, a\n copy of the current context is used.", "source": "juraj_google_style"} +{"code": "def split(s, posix=True):\n\n if isinstance(s, six.binary_type):\n s = s.decode(\"utf-8\")\n return shlex.split(s, posix=posix)", "docstring": "Split the string s using shell-like syntax.\n\nArgs:\n s (str): String to split\n posix (bool): Use posix split\n\nReturns:\n list of str: List of string parts", "source": "juraj_google_style"} +{"code": "def find_runner(program):\n\n if os.path.isfile(program) and not os.access(program, os.X_OK):\n # program is a path to a non-executable file\n try:\n opened = open(program)\n except PermissionError:\n return None\n first_line = opened.readline().strip()\n if first_line.startswith('#!'):\n return shlex.split(first_line[2:])\n if program.endswith('.py'):\n return [sys.executable]\n return None", "docstring": "Return a command that will run program.\n\nArgs:\n program: The string name of the program to try to run.\n\nReturns:\n commandline list of strings to run the program (eg. with subprocess.call()) or None", "source": "juraj_google_style"} +{"code": "def _ParseVValueString(\n self, parser_mediator, data, user_information_descriptor):\n\n data_start_offset = (\n user_information_descriptor.offset + self._V_VALUE_STRINGS_OFFSET)\n data_end_offset = data_start_offset + user_information_descriptor.size\n descriptor_data = data[data_start_offset:data_end_offset]\n\n try:\n username = descriptor_data.decode('utf-16-le')\n except (UnicodeDecodeError, UnicodeEncodeError) as exception:\n username = descriptor_data.decode('utf-16-le', errors='replace')\n parser_mediator.ProduceExtractionWarning((\n 'unable to decode V value string with error: {0!s}. Characters '\n 'that cannot be decoded will be replaced with \"?\" or '\n '\"\\\\ufffd\".').format(exception))\n\n return username", "docstring": "Parses a V value string.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n data (bytes): Windows Registry V value data.\n user_information_descriptor (user_information_descriptor): V value\n user information descriptor.\n\nReturns:\n str: string value stored in the Windows Registry V value data.", "source": "juraj_google_style"} +{"code": "def generate_text(self, generation_type='markov'):\n\n assert generation_type in ['markov', 'hmm', 'hmm_past']\n if generation_type == \"markov\":\n return self._text_generator(next_token=self._generate_next_token)\n elif generation_type == \"hmm\":\n return self._text_generator(next_token=self._generate_next_token_hmm, emit=self._emitHMM)\n elif generation_type == \"hmm_past\":\n return self._text_generator(next_token=self._generate_next_token_hmm, emit=self._emitHMM_with_past)", "docstring": "Generates sentences from a given corpus\n\nArgs:\n generation_type: 'markov' | 'hmm' | 'hmm_past'\n\nReturns:\n Properly formatted string of generated sentences", "source": "juraj_google_style"} +{"code": "def __init__(self, structure_matcher=StructureMatcher(\n comparator=ElementComparator()), symprec=None):\n\n self.symprec = symprec\n self.structure_list = defaultdict(list)\n if isinstance(structure_matcher, dict):\n self.structure_matcher = StructureMatcher.from_dict(structure_matcher)\n else:\n self.structure_matcher = structure_matcher", "docstring": "Remove duplicate structures based on the structure matcher\n and symmetry (if symprec is given).\n\nArgs:\n structure_matcher: Provides a structure matcher to be used for\n structure comparison.\n symprec: The precision in the symmetry finder algorithm if None (\n default value), no symmetry check is performed and only the\n structure matcher is used. A recommended value is 1e-5.", "source": "juraj_google_style"} +{"code": "def load(self, source, pause=False):\n\n self._source = source\n self._load_source(source)\n if pause:\n time.sleep(0.5) # Wait for the DBus interface to be initialised\n self.pause()", "docstring": "Loads a new source (as a file) from ``source`` (a file path or URL)\n by killing the current ``omxplayer`` process and forking a new one.\n\nArgs:\n source (string): Path to the file to play or URL", "source": "juraj_google_style"} +{"code": "def track_event(self, name, properties=None, measurements=None):\n\n data = channel.contracts.EventData()\n data.name = name or NULL_CONSTANT_STRING\n if properties:\n data.properties = properties\n if measurements:\n data.measurements = measurements\n\n self.track(data, self._context)", "docstring": "Send information about a single event that has occurred in the context of the application.\n\nArgs:\n name (str). the data to associate to this event.\\n\n properties (dict). the set of custom properties the client wants attached to this data item. (defaults to: None)\\n\n measurements (dict). the set of custom measurements the client wants to attach to this data item. (defaults to: None)", "source": "juraj_google_style"} +{"code": "def ProcessNewBlock(self, block):\n\n added = set()\n changed = set()\n deleted = set()\n\n try:\n # go through the list of transactions in the block and enumerate\n # over their outputs\n for tx in block.FullTransactions:\n\n for index, output in enumerate(tx.outputs):\n\n # check to see if the outputs in the tx are in this wallet\n state = self.CheckAddressState(output.ScriptHash)\n\n if state & AddressState.InWallet > 0:\n\n # if it's in the wallet, check to see if the coin exists yet\n key = CoinReference(tx.Hash, index)\n\n # if it exists, update it, otherwise create a new one\n if key in self._coins.keys():\n coin = self._coins[key]\n coin.State |= CoinState.Confirmed\n changed.add(coin)\n else:\n newcoin = Coin.CoinFromRef(coin_ref=key, tx_output=output, state=CoinState.Confirmed, transaction=tx)\n self._coins[key] = newcoin\n added.add(newcoin)\n\n if state & AddressState.WatchOnly > 0:\n self._coins[key].State |= CoinState.WatchOnly\n changed.add(self._coins[key])\n\n # now iterate over the inputs of the tx and do the same\n for tx in block.FullTransactions:\n\n for input in tx.inputs:\n\n if input in self._coins.keys():\n if self._coins[input].Output.AssetId == Blockchain.SystemShare().Hash:\n coin = self._coins[input]\n coin.State |= CoinState.Spent | CoinState.Confirmed\n changed.add(coin)\n\n else:\n deleted.add(self._coins[input])\n del self._coins[input]\n\n for claimTx in [tx for tx in block.Transactions if tx.Type == TransactionType.ClaimTransaction]:\n\n for ref in claimTx.Claims:\n if ref in self._coins.keys():\n deleted.add(self._coins[ref])\n del self._coins[ref]\n\n # update the current height of the wallet\n self._current_height += 1\n\n # in the case that another wallet implementation needs to do something\n # with the coins that have been changed ( ie persist to db ) this\n # method is called\n self.OnProcessNewBlock(block, added, changed, deleted)\n\n # this is not necessary at the moment, but any outside process\n # that wants to subscribe to the balance changed event could do\n # so from the BalanceChanged method\n if len(added) + len(deleted) + len(changed) > 0:\n self.BalanceChanged()\n\n except Exception as e:\n traceback.print_stack()\n traceback.print_exc()\n logger.error(\"could not process %s \" % e)", "docstring": "Processes a block on the blockchain. This should be done in a sequential order, ie block 4 should be\n only processed after block 3.\n\nArgs:\n block: (neo.Core.Block) a block on the blockchain.", "source": "juraj_google_style"} +{"code": "def post(self, url, data=None, files=None, headers=None, get_json=True):\n\n\n if self.debug:\n print(\"POST: %s, headers=%s\" % (url, headers))\n\n self.headers = self._get_default_headers()\n if headers is not None:\n self.headers.update(headers)\n\n response = requests.post(url, headers=self.headers, data=data, auth=self.auth, files=files, verify=self.verify_ssl)\n json_response = self._process_json_response(response)\n\n return json_response if get_json is True else response", "docstring": "Make POST request to a url\n\nArgs:\n url (str): URL to send the request to\n data (dict, optional): Data to send\n files (dict, optional): Files to send with the request\n headers (str, optional): custom headers\n\nReturns:\n A JSON object of the returned response if `get_json` is True,\n Requests' response object otherwise", "source": "juraj_google_style"} +{"code": "def __init__(self, dimensions):\n\n super(LearnableMultivariateNormalDiag, self).__init__()\n with tf.compat.v1.name_scope(self._name):\n self.dimensions = dimensions\n self._mean = tf.compat.v2.Variable(\n tf.random.normal([dimensions], stddev=0.1), name=\"mean\")\n # Initialize the std dev such that it will be close to 1 after a softplus\n # function.\n self._untransformed_stddev = tf.compat.v2.Variable(\n tf.random.normal([dimensions], mean=0.55, stddev=0.1),\n name=\"untransformed_stddev\")", "docstring": "Constructs a learnable multivariate diagonal normal model.\n\nArgs:\n dimensions: An integer corresponding to the dimensionality of the\n distribution.", "source": "juraj_google_style"} +{"code": "def HandleGetDataMessageReceived(self, payload):\n\n inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.InvPayload.InvPayload')\n if not inventory:\n return\n\n for hash in inventory.Hashes:\n hash = hash.encode('utf-8')\n\n item = None\n # try to get the inventory to send from relay cache\n\n if hash in self.leader.RelayCache.keys():\n item = self.leader.RelayCache[hash]\n\n if inventory.Type == InventoryType.TXInt:\n if not item:\n item, index = BC.Default().GetTransaction(hash)\n if not item:\n item = self.leader.GetTransaction(hash)\n if item:\n message = Message(command='tx', payload=item, print_payload=False)\n self.SendSerializedMessage(message)\n\n elif inventory.Type == InventoryType.BlockInt:\n if not item:\n item = BC.Default().GetBlock(hash)\n if item:\n message = Message(command='block', payload=item, print_payload=False)\n self.SendSerializedMessage(message)\n\n elif inventory.Type == InventoryType.ConsensusInt:\n if item:\n self.SendSerializedMessage(Message(command='consensus', payload=item, print_payload=False))", "docstring": "Process a InvPayload payload.\n\nArgs:\n payload (neo.Network.Inventory):", "source": "juraj_google_style"} +{"code": "def add_triangle(self, neighbors, color, center=None, opacity=0.4,\n draw_edges=False, edges_color=[0.0, 0.0, 0.0],\n edges_linewidth=2):\n\n points = vtk.vtkPoints()\n triangle = vtk.vtkTriangle()\n for ii in range(3):\n points.InsertNextPoint(neighbors[ii].x, neighbors[ii].y,\n neighbors[ii].z)\n triangle.GetPointIds().SetId(ii, ii)\n triangles = vtk.vtkCellArray()\n triangles.InsertNextCell(triangle)\n\n # polydata object\n trianglePolyData = vtk.vtkPolyData()\n trianglePolyData.SetPoints( points )\n trianglePolyData.SetPolys( triangles )\n\n # mapper\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInput(trianglePolyData)\n\n ac = vtk.vtkActor()\n ac.SetMapper(mapper)\n ac.GetProperty().SetOpacity(opacity)\n if color == 'element':\n if center is None:\n raise ValueError(\n 'Color should be chosen according to the central atom, '\n 'and central atom is not provided')\n # If partial occupations are involved, the color of the specie with\n # the highest occupation is used\n myoccu = 0.0\n for specie, occu in center.species.items():\n if occu > myoccu:\n myspecie = specie\n myoccu = occu\n color = [i / 255 for i in self.el_color_mapping[myspecie.symbol]]\n ac.GetProperty().SetColor(color)\n else:\n ac.GetProperty().SetColor(color)\n if draw_edges:\n ac.GetProperty().SetEdgeColor(edges_color)\n ac.GetProperty().SetLineWidth(edges_linewidth)\n ac.GetProperty().EdgeVisibilityOn()\n self.ren.AddActor(ac)", "docstring": "Adds a triangular surface between three atoms.\n\nArgs:\n atoms: Atoms between which a triangle will be drawn.\n color: Color for triangle as RGB.\n center: The \"central atom\" of the triangle\n opacity: opacity of the triangle\n draw_edges: If set to True, the a line will be drawn at each edge\n edges_color: Color of the line for the edges\n edges_linewidth: Width of the line drawn for the edges", "source": "juraj_google_style"} +{"code": "def CleanseRawStrings(raw_lines):\n\n\n delimiter = None\n lines_without_raw_strings = []\n for line in raw_lines:\n if delimiter:\n # Inside a raw string, look for the end\n end = line.find(delimiter)\n if end >= 0:\n # Found the end of the string, match leading space for this\n # line and resume copying the original lines, and also insert\n # a \"\" on the last line.\n leading_space = Match(r'^(\\s*)\\S', line)\n line = leading_space.group(1) + '\"\"' + line[end + len(delimiter):]\n delimiter = None\n else:\n # Haven't found the end yet, append a blank line.\n line = '\"\"'\n\n # Look for beginning of a raw string, and replace them with\n # empty strings. This is done in a loop to handle multiple raw\n # strings on the same line.\n while delimiter is None:\n # Look for beginning of a raw string.\n # See 2.14.15 [lex.string] for syntax.\n #\n # Once we have matched a raw string, we check the prefix of the\n # line to make sure that the line is not part of a single line\n # comment. It's done this way because we remove raw strings\n # before removing comments as opposed to removing comments\n # before removing raw strings. This is because there are some\n # cpplint checks that requires the comments to be preserved, but\n # we don't want to check comments that are inside raw strings.\n matched = Match(r'^(.*?)\\b(?:R|u8R|uR|UR|LR)\"([^\\s\\\\()]*)\\((.*)$', line)\n if (matched and\n not Match(r'^([^\\'\"]|\\'(\\\\.|[^\\'])*\\'|\"(\\\\.|[^\"])*\")*//',\n matched.group(1))):\n delimiter = ')' + matched.group(2) + '\"'\n\n end = matched.group(3).find(delimiter)\n if end >= 0:\n # Raw string ended on same line\n line = (matched.group(1) + '\"\"' +\n matched.group(3)[end + len(delimiter):])\n delimiter = None\n else:\n # Start of a multi-line raw string\n line = matched.group(1) + '\"\"'\n else:\n break\n\n lines_without_raw_strings.append(line)\n\n # TODO(unknown): if delimiter is not None here, we might want to\n # emit a warning for unterminated string.\n return lines_without_raw_strings", "docstring": "Removes C++11 raw strings from lines.\n\n Before:\n static const char kData[] = R\"(\n multi-line string\n )\";\n\n After:\n static const char kData[] = \"\"\n (replaced by blank line)\n \"\";\n\nArgs:\n raw_lines: list of raw lines.\n\nReturns:\n list of lines with C++11 raw strings replaced by empty strings.", "source": "juraj_google_style"} +{"code": "def print_inplace(*args, **kwargs):\n\n kwargs.setdefault('file', sys.stdout)\n kwargs.setdefault('end', '')\n pos_save(file=kwargs['file'])\n delay = None\n with suppress(KeyError):\n delay = kwargs.pop('delay')\n if delay is None:\n print(*args, **kwargs)\n else:\n for c in kwargs.get('sep', ' ').join(str(a) for a in args):\n kwargs['file'].write(c)\n kwargs['file'].flush()\n sleep(delay)\n if kwargs['end']:\n kwargs['file'].write(kwargs['end'])\n pos_restore(file=kwargs['file'])\n # Must flush to see changes.\n kwargs['file'].flush()", "docstring": "Save cursor position, write some text, and then restore the position.\n\nArgs:\n Same as `print()`.\n\n Keyword Arguments:\n Same as `print()`, except `end` defaults to '' (empty str),\n and these:\n delay : Time in seconds between character writes.", "source": "juraj_google_style"} +{"code": "def data_string_compare(db_data, user_data):\n\n db_data = ''.join(db_data.split())\n user_data = ''.join(user_data.split())\n if operator.eq(db_data, user_data):\n return True\n return False", "docstring": "Validate string removing all white space before comparison.\n\nArgs:\n db_data (str): The data store in Redis.\n user_data (str): The user provided data.\n\nReturns:\n bool: True if the data passed validation.", "source": "juraj_google_style"} +{"code": "def __init__(self, datafile, logger, error_handler):\n\n\n config = json.loads(datafile)\n self.logger = logger\n self.error_handler = error_handler\n self.version = config.get('version')\n if self.version not in SUPPORTED_VERSIONS:\n raise exceptions.UnsupportedDatafileVersionException(\n enums.Errors.UNSUPPORTED_DATAFILE_VERSION.format(self.version)\n )\n\n self.account_id = config.get('accountId')\n self.project_id = config.get('projectId')\n self.revision = config.get('revision')\n self.groups = config.get('groups', [])\n self.experiments = config.get('experiments', [])\n self.events = config.get('events', [])\n self.attributes = config.get('attributes', [])\n self.audiences = config.get('audiences', [])\n self.typed_audiences = config.get('typedAudiences', [])\n self.feature_flags = config.get('featureFlags', [])\n self.rollouts = config.get('rollouts', [])\n self.anonymize_ip = config.get('anonymizeIP', False)\n self.bot_filtering = config.get('botFiltering', None)\n\n # Utility maps for quick lookup\n self.group_id_map = self._generate_key_map(self.groups, 'id', entities.Group)\n self.experiment_key_map = self._generate_key_map(self.experiments, 'key', entities.Experiment)\n self.event_key_map = self._generate_key_map(self.events, 'key', entities.Event)\n self.attribute_key_map = self._generate_key_map(self.attributes, 'key', entities.Attribute)\n\n self.audience_id_map = self._generate_key_map(self.audiences, 'id', entities.Audience)\n\n # Conditions of audiences in typedAudiences are not expected\n # to be string-encoded as they are in audiences.\n for typed_audience in self.typed_audiences:\n typed_audience['conditions'] = json.dumps(typed_audience['conditions'])\n typed_audience_id_map = self._generate_key_map(self.typed_audiences, 'id', entities.Audience)\n self.audience_id_map.update(typed_audience_id_map)\n\n self.rollout_id_map = self._generate_key_map(self.rollouts, 'id', entities.Layer)\n for layer in self.rollout_id_map.values():\n for experiment in layer.experiments:\n self.experiment_key_map[experiment['key']] = entities.Experiment(**experiment)\n\n self.audience_id_map = self._deserialize_audience(self.audience_id_map)\n for group in self.group_id_map.values():\n experiments_in_group_key_map = self._generate_key_map(group.experiments, 'key', entities.Experiment)\n for experiment in experiments_in_group_key_map.values():\n experiment.__dict__.update({\n 'groupId': group.id,\n 'groupPolicy': group.policy\n })\n self.experiment_key_map.update(experiments_in_group_key_map)\n\n self.experiment_id_map = {}\n self.variation_key_map = {}\n self.variation_id_map = {}\n self.variation_variable_usage_map = {}\n for experiment in self.experiment_key_map.values():\n self.experiment_id_map[experiment.id] = experiment\n self.variation_key_map[experiment.key] = self._generate_key_map(\n experiment.variations, 'key', entities.Variation\n )\n self.variation_id_map[experiment.key] = {}\n for variation in self.variation_key_map.get(experiment.key).values():\n self.variation_id_map[experiment.key][variation.id] = variation\n self.variation_variable_usage_map[variation.id] = self._generate_key_map(\n variation.variables, 'id', entities.Variation.VariableUsage\n )\n\n self.feature_key_map = self._generate_key_map(self.feature_flags, 'key', entities.FeatureFlag)\n\n # Dict containing map of experiment ID to feature ID.\n # for checking that experiment is a feature experiment or not.\n self.experiment_feature_map = {}\n for feature in self.feature_key_map.values():\n feature.variables = self._generate_key_map(feature.variables, 'key', entities.Variable)\n\n for exp_id in feature.experimentIds:\n # Add this experiment in experiment-feature map.\n self.experiment_feature_map[exp_id] = [feature.id]\n\n experiment_in_feature = self.experiment_id_map[exp_id]\n # Check if any of the experiments are in a group and add the group id for faster bucketing later on\n if experiment_in_feature.groupId:\n feature.groupId = experiment_in_feature.groupId\n # Experiments in feature can only belong to one mutex group\n break\n\n # Map of user IDs to another map of experiments to variations.\n # This contains all the forced variations set by the user\n # by calling set_forced_variation (it is not the same as the\n # whitelisting forcedVariations data structure).\n self.forced_variation_map = {}", "docstring": "ProjectConfig init method to load and set project config data.\n\nArgs:\n datafile: JSON string representing the project.\n logger: Provides a log message to send log messages to.\n error_handler: Provides a handle_error method to handle exceptions.", "source": "juraj_google_style"} +{"code": "def encipher_shift(plaintext, plain_vocab, shift):\n\n ciphertext = []\n cipher = ShiftEncryptionLayer(plain_vocab, shift)\n\n for _, sentence in enumerate(plaintext):\n cipher_sentence = []\n for _, character in enumerate(sentence):\n encrypted_char = cipher.encrypt_character(character)\n cipher_sentence.append(encrypted_char)\n ciphertext.append(cipher_sentence)\n\n return ciphertext", "docstring": "Encrypt plain text with a single shift layer.\n\nArgs:\n plaintext (list of list of Strings): a list of plain text to encrypt.\n plain_vocab (list of Integer): unique vocabularies being used.\n shift (Integer): number of shift, shift to the right if shift is positive.\n\nReturns:\n ciphertext (list of Strings): encrypted plain text.", "source": "juraj_google_style"} +{"code": "def col_mod(df,col_name,func,*args,**kwargs):\n\n backup = df[col_name].copy()\n try:\n return_val = func(df,col_name,*args,**kwargs)\n if return_val is not None:\n set_col(df,col_name,return_val)\n except:\n df[col_name] = backup", "docstring": "Changes a column of a DataFrame according to a given function\n Parameters:\n df - DataFrame\n DataFrame to operate on\n col_name - string\n Name of column to modify\n func - function\n The function to use to modify the column", "source": "juraj_google_style"} +{"code": "def fit_gaussian(samples, ddof=0):\n\n if len(samples.shape) == 1:\n return np.mean(samples), np.std(samples, ddof=ddof)\n return np.mean(samples, axis=1), np.std(samples, axis=1, ddof=ddof)", "docstring": "Calculates the mean and the standard deviation of the given samples.\n\nArgs:\n samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all\n values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension.\n ddof (int): the difference degrees of freedom in the std calculation. See numpy.", "source": "juraj_google_style"} +{"code": "def init_app(self, app):\n\n app.url_rule_class = partial(NavigationRule, copilot=self)\n app.context_processor(self.inject_context)", "docstring": "Register the extension with the application.\n\nArgs:\n app (flask.Flask): The application to register with.", "source": "juraj_google_style"} +{"code": "def _prepare_for_training(self, records, mini_batch_size=None, job_name=None):\n\n num_records = None\n if isinstance(records, list):\n for record in records:\n if record.channel == 'train':\n num_records = record.num_records\n break\n if num_records is None:\n raise ValueError('Must provide train channel.')\n else:\n num_records = records.num_records\n\n # mini_batch_size is a required parameter\n default_mini_batch_size = min(self.DEFAULT_MINI_BATCH_SIZE,\n max(1, int(num_records / self.train_instance_count)))\n use_mini_batch_size = mini_batch_size or default_mini_batch_size\n\n super(PCA, self)._prepare_for_training(records=records, mini_batch_size=use_mini_batch_size, job_name=job_name)", "docstring": "Set hyperparameters needed for training.\n\nArgs:\n * records (:class:`~RecordSet`): The records to train this ``Estimator`` on.\n * mini_batch_size (int or None): The size of each mini-batch to use when training. If ``None``, a\n default value will be used.\n * job_name (str): Name of the training job to be created. If not specified, one is generated,\n using the base name given to the constructor if applicable.", "source": "juraj_google_style"} +{"code": "def _print_download_progress_msg(self, msg, flush=False):\n\n if self._interactive_mode():\n # Print progress message to console overwriting previous progress\n # message.\n self._max_prog_str = max(self._max_prog_str, len(msg))\n sys.stdout.write(\"\\r%-{}s\".format(self._max_prog_str) % msg)\n sys.stdout.flush()\n if flush:\n print(\"\\n\")\n else:\n # Interactive progress tracking is disabled. Print progress to the\n # standard TF log.\n logging.info(msg)", "docstring": "Prints a message about download progress either to the console or TF log.\n\nArgs:\n msg: Message to print.\n flush: Indicates whether to flush the output (only used in interactive\n mode).", "source": "juraj_google_style"} +{"code": "def remove_hairs_decorator(fn=None, hairs=HAIRS):\n\n def decorator_wrapper(fn):\n @wraps(fn)\n def decorator(*args, **kwargs):\n out = fn(*args, **kwargs)\n\n return remove_hairs(out, hairs)\n\n return decorator\n\n if fn:\n return decorator_wrapper(fn)\n\n return decorator_wrapper", "docstring": "Parametrized decorator wrapping the :func:`remove_hairs` function.\n\nArgs:\n hairs (str, default HAIRS): List of characters which should be removed.\n See :attr:`HAIRS` for details.", "source": "juraj_google_style"} +{"code": "def uniquify(seq):\n\n\n seen = set()\n seen_add = seen.add\n return [x for x in seq if x not in seen and not seen_add(x)]", "docstring": "Return unique values in a list in the original order. See: \\\n http://www.peterbe.com/plog/uniqifiers-benchmark\n\nArgs:\n seq (list): original list.\n\nReturns:\n list: list without duplicates preserving original order.", "source": "juraj_google_style"} +{"code": "def get_workflow_outputs(namespace, workspace, submission_id, workflow_id):\n\n uri = \"workspaces/{0}/{1}/\".format(namespace, workspace)\n uri += \"submissions/{0}/workflows/{1}/outputs\".format(submission_id,\n workflow_id)\n return __get(uri)", "docstring": "Request the outputs for a workflow in a submission.\n\nArgs:\n namespace (str): project to which workspace belongs\n workspace (str): Workspace name\n submission_id (str): Submission's unique identifier\n workflow_id (str): Workflow's unique identifier.\n\n Swagger:\n https://api.firecloud.org/#!/Submissions/workflowOutputsInSubmission", "source": "juraj_google_style"} +{"code": "def in_labelset(xmrs, nodeids, label=None):\n\n nodeids = set(nodeids)\n if label is None:\n label = xmrs.ep(next(iter(nodeids))).label\n return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])", "docstring": "Test if all nodeids share a label.\n\nArgs:\n nodeids: iterable of nodeids\n label (str, optional): the label that all nodeids must share\n\nReturns:\n bool: `True` if all nodeids share a label, otherwise `False`", "source": "juraj_google_style"} +{"code": "def delete(adapter, case_obj, update=False, existing_case=False):\n\n # This will overwrite the updated case with the previous one\n if update:\n adapter.add_case(existing_case)\n else:\n adapter.delete_case(case_obj)\n\n for file_type in ['vcf_path','vcf_sv_path']:\n if not case_obj.get(file_type):\n continue\n variant_file = case_obj[file_type]\n # Get a cyvcf2.VCF object\n vcf_obj = get_vcf(variant_file)\n\n delete_variants(\n adapter=adapter,\n vcf_obj=vcf_obj,\n case_obj=case_obj,\n )", "docstring": "Delete a case and all of it's variants from the database.\n\nArgs:\n adapter: Connection to database\n case_obj(models.Case)\n update(bool): If we are in the middle of an update\n existing_case(models.Case): If something failed during an update we need to revert\n to the original case", "source": "juraj_google_style"} +{"code": "def from_dict(cls, copula_dict):\n\n instance = cls(copula_dict['copula_type'])\n instance.theta = copula_dict['theta']\n instance.tau = copula_dict['tau']\n return instance", "docstring": "Create a new instance from the given parameters.\n\nArgs:\n copula_dict: `dict` with the parameters to replicate the copula.\n Like the output of `Bivariate.to_dict`\n\nReturns:\n Bivariate: Instance of the copula defined on the parameters.", "source": "juraj_google_style"} +{"code": "def delete_additional_charge(self, recurring_billing_id):\n\n fmt = 'recurringBillItems/{}'.format(recurring_billing_id)\n return self.client._delete(self.url + fmt, headers=self.get_headers())", "docstring": "Remove an extra charge from an invoice.\n\nArgs:\n recurring_billing_id: Identifier of the additional charge.\n\n Returns:", "source": "juraj_google_style"} +{"code": "def _best_subset(self, n_qubits):\n\n if n_qubits == 1:\n return np.array([0])\n\n device_qubits = self.coupling_map.size()\n\n cmap = np.asarray(self.coupling_map.get_edges())\n data = np.ones_like(cmap[:, 0])\n sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),\n shape=(device_qubits, device_qubits)).tocsr()\n best = 0\n best_map = None\n # do bfs with each node as starting point\n for k in range(sp_cmap.shape[0]):\n bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,\n return_predecessors=False)\n\n connection_count = 0\n sub_graph = []\n for i in range(n_qubits):\n node_idx = bfs[i]\n for j in range(sp_cmap.indptr[node_idx],\n sp_cmap.indptr[node_idx + 1]):\n node = sp_cmap.indices[j]\n for counter in range(n_qubits):\n if node == bfs[counter]:\n connection_count += 1\n sub_graph.append([node_idx, node])\n break\n\n if connection_count > best:\n best = connection_count\n best_map = bfs[0:n_qubits]\n # Return a best mapping that has reduced bandwidth\n mapping = {}\n for edge in range(best_map.shape[0]):\n mapping[best_map[edge]] = edge\n new_cmap = [[mapping[c[0]], mapping[c[1]]] for c in sub_graph]\n rows = [edge[0] for edge in new_cmap]\n cols = [edge[1] for edge in new_cmap]\n data = [1]*len(rows)\n sp_sub_graph = sp.coo_matrix((data, (rows, cols)),\n shape=(n_qubits, n_qubits)).tocsr()\n perm = cs.reverse_cuthill_mckee(sp_sub_graph)\n best_map = best_map[perm]\n return best_map", "docstring": "Computes the qubit mapping with the best connectivity.\n\nArgs:\n n_qubits (int): Number of subset qubits to consider.\n\nReturns:\n ndarray: Array of qubits to use for best connectivity mapping.", "source": "juraj_google_style"} +{"code": "def line(p1, p2):\n\n A = (p1[1] - p2[1])\n B = (p2[0] - p1[0])\n C = (p1[0]*p2[1] - p2[0]*p1[1])\n return A, B, -C", "docstring": "Creates a line from two points\n\n From http://stackoverflow.com/a/20679579\n\nArgs:\n p1 ([float, float]): x and y coordinates\n p2 ([float, float]): x and y coordinates\n\nReturns:\n (float, float, float): x, y and _", "source": "juraj_google_style"} +{"code": "def glob(*args):\n\n if len(args) is 1 and isinstance(args[0], list):\n args = args[0]\n matches = []\n for pattern in args:\n for item in glob2.glob(pattern):\n if not os.path.isdir(item):\n matches.append(item)\n return matches", "docstring": "Returns list of paths matching one or more wildcard patterns.\n\nArgs:\n include_dirs: Include directories in the output", "source": "juraj_google_style"} +{"code": "def call(self, x):\n\n with tf.name_scope(\"embedding\"):\n embeddings = tf.gather(self.shared_weights, x)\n\n # Scale embedding by the sqrt of the hidden size\n embeddings *= self.hidden_size ** 0.5\n\n # Create binary array of size [batch_size, length]\n # where 1 = padding, 0 = not padding\n padding = model_utils.get_padding(x)\n\n # Set all padding embedding values to 0\n embeddings *= tf.expand_dims(1 - padding, -1)\n return embeddings", "docstring": "Get token embeddings of x.\n\nArgs:\n x: An int64 tensor with shape [batch_size, length]\n\nReturns:\n embeddings: float32 tensor with shape [batch_size, length, embedding_size]\n padding: float32 tensor with shape [batch_size, length] indicating the\n locations of the padding tokens in x.", "source": "juraj_google_style"} +{"code": "def is_mobile(user_agent):\n\n if user_agent:\n b = reg_b.search(user_agent)\n v = reg_v.search(user_agent[0:4])\n return b or v\n return False", "docstring": "Checks if the user browser from the given user agent is mobile.\n\nArgs:\n user_agent: A given user agent.\n\n Returns: True if the browser from the user agent is mobile.", "source": "juraj_google_style"} +{"code": "def execute(self, triple_map, output, **kwargs):\n\n subjects = []\n found_elements = self.source.xpath(\n str(triple_map.logicalSource.iterator),\n namespaces=self.xml_ns)\n for element in found_elements:\n subject = self.generate_term(term_map=triple_map.subjectMap,\n element=element,\n **kwargs)\n start = len(output)\n for row in triple_map.predicateObjectMap:\n predicate = row.predicate\n if row.template is not None:\n obj_ = self.generate_term(term_map=row, **kwargs)\n output.add((subject, predicate, obj_))\n if row.parentTriplesMap is not None:\n self.__handle_parents__(\n output,\n parent_map=row.parentTriplesMap,\n subject=subject,\n predicate=predicate,\n **kwargs)\n new_subjects = self.__reference_handler__(\n output,\n predicate_obj_map=row,\n element=element,\n subject=subject)\n subjects.extend(new_subjects)\n if row.constant is not None:\n output.add((subject, predicate, row.constant))\n if start < len(output):\n if triple_map.subjectMap.class_ is not None:\n output.add((subject,\n NS_MGR.rdf.type.rdflib,\n triple_map.subjectMap.class_))\n subjects.append(subject)\n return subjects", "docstring": "Method executes mapping between source\n\nArgs:\n -----\n triple_map: SimpleNamespace, Triple Map", "source": "juraj_google_style"} +{"code": "def get_total_mass(self):\n\n try:\n mass = self.loc[:, 'mass'].sum()\n except KeyError:\n mass_molecule = self.add_data('mass')\n mass = mass_molecule.loc[:, 'mass'].sum()\n return mass", "docstring": "Returns the total mass in g/mol.\n\nArgs:\n None\n\nReturns:\n float:", "source": "juraj_google_style"} +{"code": "def _get_mpr_table(self, connection, partition):\n\n # TODO: This is the first candidate for optimization. Add field to partition\n # with table name and update it while table creation.\n # Optimized version.\n #\n # return partition.mpr_table or raise exception\n\n # Not optimized version.\n #\n # first check either partition has readonly table.\n virtual_table = partition.vid\n table = '{}_v'.format(virtual_table)\n logger.debug(\n 'Looking for materialized table of the partition.\\n partition: {}'.format(partition.name))\n table_exists = self._relation_exists(connection, table)\n if table_exists:\n logger.debug(\n 'Materialized table of the partition found.\\n partition: {}, table: {}'\n .format(partition.name, table))\n return table\n\n # now check for virtual table\n logger.debug(\n 'Looking for a virtual table of the partition.\\n partition: {}'.format(partition.name))\n virtual_exists = self._relation_exists(connection, virtual_table)\n if virtual_exists:\n logger.debug(\n 'Virtual table of the partition found.\\n partition: {}, table: {}'\n .format(partition.name, table))\n return virtual_table\n raise MissingTableError('sqlite database does not have table for mpr of {} partition.'\n .format(partition.vid))", "docstring": "Returns name of the sqlite table who stores mpr data.\n\nArgs:\n connection (apsw.Connection): connection to sqlite database who stores mpr data.\n partition (orm.Partition):\n\nReturns:\n str:\n\nRaises:\n MissingTableError: if partition table not found in the db.", "source": "juraj_google_style"} +{"code": "def get_victim_social_asset(self, main_type, sub_type, unique_id, asset_id, params=None):\n\n params = params or {}\n\n return self.victim_social_asset(main_type, sub_type, unique_id, asset_id, params=params)", "docstring": "Args:\n main_type:\n sub_type:\n unique_id:\n asset_id:\n params:\n\n Return:", "source": "juraj_google_style"} +{"code": "def forward(self, x):\n\n head_outputs = [None] * self.t\n\n # Execute input layer\n if isinstance(self.input_layer, list): # One input_module per task\n input_outputs = [mod(x) for mod, x in zip(self.input_layer, x)]\n x = torch.stack(input_outputs, dim=1)\n\n # Execute level-0 task heads from their respective input modules\n for t in self.task_map[0]:\n head = self.heads[t]\n head_outputs[t] = head(input_outputs[t])\n else: # One input_module for all tasks\n x = self.input_layer(x)\n\n # Execute level-0 task heads from the single input module\n for t in self.task_map[0]:\n head = self.heads[t]\n head_outputs[t] = head(x)\n\n # Execute middle layers\n for i, layer in enumerate(self.middle_layers, start=1):\n x = layer(x)\n\n # Attach level-i task heads from the ith middle module\n for t in self.task_map[i]:\n head = self.heads[t]\n # Optionally include as input the predictions of parent tasks\n if self.config[\"pass_predictions\"] and bool(self.task_graph.parents[t]):\n task_input = [x]\n for p in self.task_graph.parents[t]:\n task_input.append(head_outputs[p])\n task_input = torch.stack(task_input, dim=1)\n else:\n task_input = x\n head_outputs[t] = head(task_input)\n return head_outputs", "docstring": "Returns a list of outputs for tasks 0,...t-1\n\nArgs:\n x: a [batch_size, ...] batch from X", "source": "juraj_google_style"} +{"code": "def greater_than_evaluator(self, index):\n\n condition_name = self.condition_data[index][0]\n condition_value = self.condition_data[index][1]\n user_value = self.attributes.get(condition_name)\n\n if not validator.is_finite_number(condition_value):\n self.logger.warning(audience_logs.UNKNOWN_CONDITION_VALUE.format(\n self._get_condition_json(index)\n ))\n return None\n\n if not self.is_value_a_number(user_value):\n self.logger.warning(audience_logs.UNEXPECTED_TYPE.format(\n self._get_condition_json(index),\n type(user_value),\n condition_name\n ))\n return None\n\n if not validator.is_finite_number(user_value):\n self.logger.warning(audience_logs.INFINITE_ATTRIBUTE_VALUE.format(\n self._get_condition_json(index),\n condition_name\n ))\n return None\n\n return user_value > condition_value", "docstring": "Evaluate the given greater than match condition for the user attributes.\n\nArgs:\n index: Index of the condition to be evaluated.\n\nReturns:\n Boolean:\n - True if the user attribute value is greater than the condition value.\n - False if the user attribute value is less than or equal to the condition value.\n None: if the condition value isn't finite or the user attribute value isn't finite.", "source": "juraj_google_style"} +{"code": "def _parse_list(cls, args):\n\n argparser = ArgumentParser(prog=\"cluster list\")\n\n group = argparser.add_mutually_exclusive_group()\n\n group.add_argument(\"--id\", dest=\"cluster_id\",\n help=\"show cluster with this id\")\n\n group.add_argument(\"--label\", dest=\"label\",\n help=\"show cluster with this label\")\n\n group.add_argument(\"--state\", dest=\"state\", action=\"store\",\n choices=['up', 'down', 'pending', 'terminating'],\n help=\"list only clusters in the given state\")\n pagination_group = group.add_argument_group()\n pagination_group.add_argument(\"--page\", dest=\"page\", action=\"store\", type=int,\n help=\"page number\")\n pagination_group.add_argument(\"--per-page\", dest=\"per_page\", action=\"store\", type=int,\n help=\"number of clusters to be retrieved per page\")\n\n arguments = argparser.parse_args(args)\n return vars(arguments)", "docstring": "Parse command line arguments to construct a dictionary of cluster\n parameters that can be used to determine which clusters to list.\n\nArgs:\n `args`: sequence of arguments\n\nReturns:\n Dictionary that can be used to determine which clusters to list", "source": "juraj_google_style"} +{"code": "def list_permissions(self, group_name=None, resource=None):\n\n self.project_service.set_auth(self._token_project)\n return self.project_service.list_permissions(group_name, resource)", "docstring": "List permission sets associated filtering by group and/or resource.\n\nArgs:\n group_name (string): Name of group.\n resource (intern.resource.boss.Resource): Identifies which data\n model object to operate on.\n\nReturns:\n (list): List of permissions.\n\nRaises:\n requests.HTTPError on failure.", "source": "juraj_google_style"} +{"code": "def create_server(self, server_name, *args, **kwargs):\n\n server = ServerConnection(name=server_name, reactor=self)\n\n if args or kwargs:\n server.set_connect_info(*args, **kwargs)\n\n # register cached events\n for verb, infos in self._event_handlers.items():\n for info in infos:\n server.register_event(info['direction'], verb, info['handler'],\n priority=info['priority'])\n\n self.servers[server_name] = server\n\n return server", "docstring": "Create an IRC server connection slot.\n\n The server will actually be connected to when\n :meth:`girc.client.ServerConnection.connect` is called later.\n\nArgs:\n server_name (str): Name of the server, to be used for functions and accessing the\n server later through the reactor.\n\nReturns:\n server (girc.client.ServerConnection): A not-yet-connected server.", "source": "juraj_google_style"} +{"code": "def SvelteComponent(name, path):\n\n if path[-3:] == \".js\":\n js_path = path\n elif path[-5:] == \".html\":\n print(\"Trying to build svelte component from html...\")\n js_path = build_svelte(path)\n js_content = read(js_path, mode='r')\n def inner(data):\n id_str = js_id(name)\n html = _template \\\n .replace(\"$js\", js_content) \\\n .replace(\"$name\", name) \\\n .replace(\"$data\", json.dumps(data)) \\\n .replace(\"$id\", id_str)\n _display_html(html)\n return inner", "docstring": "Display svelte components in iPython.\n\nArgs:\n name: name of svelte component (must match component filename when built)\n path: path to compile svelte .js file or source svelte .html file.\n (If html file, we try to call svelte and build the file.)\n\nReturns:\n A function mapping data to a rendered svelte component in ipython.", "source": "juraj_google_style"} +{"code": "def HasIndex(self, index):\n\n for i in self.Items:\n if i.index == index:\n return True\n return False", "docstring": "Flag indicating the index exists in any of the spent coin items.\n\nArgs:\n index (int):\n\n Returns:", "source": "juraj_google_style"} +{"code": "def _add_encoded(self, encoded):\n\n if self.public_key != encoded.public_key:\n raise ValueError(\"Attempted to add numbers encoded against \"\n \"different public keys!\")\n\n # In order to add two numbers, their exponents must match.\n a, b = self, encoded\n if a.exponent > b.exponent:\n a = self.decrease_exponent_to(b.exponent)\n elif a.exponent < b.exponent:\n b = b.decrease_exponent_to(a.exponent)\n\n # Don't bother to salt/obfuscate in a basic operation, do it\n # just before leaving the computer.\n encrypted_scalar = a.public_key.raw_encrypt(b.encoding, 1)\n\n sum_ciphertext = a._raw_add(a.ciphertext(False), encrypted_scalar)\n return EncryptedNumber(a.public_key, sum_ciphertext, a.exponent)", "docstring": "Returns E(a + b), given self=E(a) and b.\n\nArgs:\n encoded (EncodedNumber): an :class:`EncodedNumber` to be added\n to `self`.\n\nReturns:\n EncryptedNumber: E(a + b), calculated by encrypting b and\n taking the product of E(a) and E(b) modulo\n :attr:`~PaillierPublicKey.n` ** 2.\n\nRaises:\n ValueError: if scalar is out of range or precision.", "source": "juraj_google_style"} +{"code": "def unsplat(f: Callable[[Iterable], A]) -> Callable[..., A]:\n\n\n def unsplatted(*args):\n return f(args)\n\n return unsplatted", "docstring": "Convert a function taking a single iterable argument into a function taking multiple arguments.\n\nArgs:\n f: Any function taking a single iterable argument\n\nReturns:\n A function that accepts multiple arguments. Each argument of this function is passed as an element of an\n iterable to ``f``.\n\nExample:\n $ def f(a):\n $ return a[0] + a[1] + a[2]\n $\n $ f([1, 2, 3]) # 6\n $ g = unsplat(f)\n $ g(1, 2, 3) # 6", "source": "juraj_google_style"} +{"code": "def register_with_password(self, username, password):\n\n response = self.api.register(\n auth_body={\"type\": \"m.login.dummy\"},\n kind='user',\n username=username,\n password=password,\n )\n return self._post_registration(response)", "docstring": "Register for a new account on this HS.\n\nArgs:\n username (str): Account username\n password (str): Account password\n\nReturns:\n str: Access Token\n\nRaises:\n MatrixRequestError", "source": "juraj_google_style"} +{"code": "def color_string(self, x):\n\n diff_str = \"\"\n color = \"black\"\n\n if len(x) == 2 and self.compare_file is not None:\n difference = x[0] - x[1]\n if difference:\n color, sign = ('green', '-') if difference < 0 else ('red', '+')\n diff_str = '{}{}'.format(sign, self.format_measure(difference))\n return [self.format_measure(x[0]), [diff_str, color]]", "docstring": "Return a string formatted delta for the values in x.\n\nArgs:\n x: 2-item list of integers (representing number of calls) or\n 2-item list of floats (representing seconds of runtime).\n\nReturns:\n A list with [formatted x[0], [color, formatted delta]], where\n color reflects whether x[1] is lower, greater, or the same as\n x[0].", "source": "juraj_google_style"} +{"code": "def add_argument_to(self, parser):\n\n from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory\n if isinstance(self.kwargs.get('action', ''), list):\n # see documentation of DefaultIffUsedActionFactory to see why this is necessary\n if self.kwargs['action'][0] == 'default_iff_used':\n self.kwargs['action'] = DefaultIffUsedActionFactory.generate_action(\n self.kwargs['action'][1])\n # In cli 'preserved' is not supported.\n # It needs to be removed because it is unknown for argparse.\n self.kwargs.pop('preserved', None)\n try:\n parser.add_argument(*self.flags, **self.kwargs)\n except Exception as ex:\n problem = \"Error while adding argument '{name}': {error}\".\\\n format(name=self.name, error=repr(ex))\n raise exceptions.ExecutionException(problem)", "docstring": "Used by cli to add this as an argument to argparse parser.\n\nArgs:\n parser: parser to add this argument to", "source": "juraj_google_style"} +{"code": "def __init__(self, device, configs=None):\n\n self._device = device\n self._configs = configs", "docstring": "Constructor of the class.\n\n The constructor is the only place to pass in a config. If you need to\n change the config later, you should unregister the service instance\n from `ServiceManager` and register again with the new config.\n\nArgs:\n device: the device object this service is associated with.\n config: optional configuration defined by the author of the service\n class.", "source": "juraj_google_style"} +{"code": "def new_root(self, vd, seqnum, log_block_size):\n # type: (headervd.PrimaryOrSupplementaryVD, int, int) -> None\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('Directory Record already initialized')\n\n self._new(vd, b'\\x00', None, seqnum, True, log_block_size, False)", "docstring": "Create a new root Directory Record.\n\n Parameters:\n vd - The Volume Descriptor this record is part of.\n seqnum - The sequence number for this directory record.\n log_block_size - The logical block size to use.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def map(self, op: Callable[[T], U]) -> 'Union[Result[U, E], Result[T, E]]':\n\n return self._type.Ok(op(cast(T, self._val))) if self._is_ok else self", "docstring": "Applies a function to the contained :meth:`Result.Ok` value.\n\nArgs:\n op: The function to apply to the :meth:`Result.Ok` value.\n\nReturns:\n A :class:`Result` with its success value as the function result\n if `self` is an :meth:`Result.Ok` value, otherwise returns\n `self`.\n\nExample:\n >>> Ok(1).map(lambda x: x * 2)\n Ok(2)\n >>> Err(1).map(lambda x: x * 2)\n Err(1)", "source": "juraj_google_style"} +{"code": "def report_line(zipfilename: str, contentsfilename: str, line: str,\n show_inner_file: bool) -> None:\n\n if show_inner_file:\n print(\"{} [{}]: {}\".format(zipfilename, contentsfilename, line))\n else:\n print(\"{}: {}\".format(zipfilename, line))", "docstring": "Prints a line from a file, with the ``.zip`` filename and optionally also\n the inner filename.\n\nArgs:\n zipfilename: filename of the ``.zip`` file\n contentsfilename: filename of the inner file\n line: the line from the inner file\n show_inner_file: if ``True``, show both filenames; if ``False``, show\n just the ``.zip`` filename", "source": "juraj_google_style"} +{"code": "def GetAdGroups(self, client_customer_id, campaign_id):\n\n self.client.SetClientCustomerId(client_customer_id)\n selector = {\n 'fields': ['Id', 'Name', 'Status'],\n 'predicates': [\n {\n 'field': 'CampaignId',\n 'operator': 'EQUALS',\n 'values': [campaign_id]\n },\n {\n 'field': 'Status',\n 'operator': 'NOT_EQUALS',\n 'values': ['REMOVED']\n }\n ]\n }\n adgroups = self.client.GetService('AdGroupService').get(selector)\n\n if int(adgroups['totalNumEntries']) > 0:\n return adgroups['entries']\n else:\n return None", "docstring": "Retrieves all AdGroups for the given campaign that haven't been removed.\n\nArgs:\n client_customer_id: str Client Customer Id being used in API request.\n campaign_id: str id of the campaign for which to fetch ad groups.\n\nReturns:\n list List of AdGroup data objects.", "source": "juraj_google_style"} +{"code": "def __init__(self, label, ast_node, *, line_number=None, path):\n\n self.label = label\n self.ast_node = ast_node\n if line_number:\n self.line_number = line_number\n elif ast_node:\n self.line_number = ast_node.lineno\n else:\n self.line_number = None\n self.path = path\n self.ingoing = list()\n self.outgoing = list()", "docstring": "Create a Node that can be used in a CFG.\n\nArgs:\n label(str): The label of the node, describing its expression.\n line_number(Optional[int]): The line of the expression of the Node.", "source": "juraj_google_style"} +{"code": "def slice(self, start, size):\n\n return SeriesWeld(\n grizzly_impl.slice(\n self.expr,\n start,\n size,\n self.weld_type\n ),\n self.weld_type,\n self.df,\n self.column_name\n )", "docstring": "Summary\n\nArgs:\n start (TYPE): Description\n size (TYPE): Description\n\nReturns:\n TYPE: Description", "source": "juraj_google_style"} +{"code": "def whoami(self) -> dict:\n\n if not self.access_token:\n return {}\n self._try_refresh_access_token()\n return self.session.get(self.WHOAMI_URL).json()", "docstring": "Returns the basic information about the authenticated character.\n\n Obviously doesn't do anything if this Preston instance is not\n authenticated, so it returns an empty dict.\n\nArgs:\n None\n\nReturns:\n character info if authenticated, otherwise an empty dict", "source": "juraj_google_style"} +{"code": "def unblock_by_identifier(self, identifier):\n\n\n params = {'identifier': identifier}\n\n return self.client.delete(self._url(), params=params)", "docstring": "Unblocks by identifier\n\nArgs:\n identifier (str): Should be any of: username, phone_number, email.\n\n See: https://auth0.com/docs/api/management/v2#!/User_Blocks/delete_user_blocks", "source": "juraj_google_style"} +{"code": "def date_proc(func):\n\n\t@wraps(func)\n\tdef wrapped(request, *args, **kwargs):\n\t\tif 'date' in request.GET and request.GET['date'] == '':\n\t\t\traise Http404(\"api does not exist\")\n\t\telif 'date' not in request.GET:\n\t\t\tdate = datetime.today()\n\t\t\treturn func(request, date)\n\t\telse:\n\t\t\tdate = tuple(int(intValue) for intValue in request.GET['date'].split('-'))\n\t\t\tif len(date) == 3:\n\t\t\t\tdate = datetime(*date)\n\t\t\telif len(date) == 2:\n\t\t\t\tdate = datetime(*date, day = 1)\n\t\t\telse:\n\t\t\t\tdate = datetime(*date, month = 1, day = 1)\n\t\t\treturn func(request, date)\n\treturn wrapped", "docstring": "An decorator checking whether date parameter is passing in or not. If not, default date value is all PTT data.\n Else, return PTT data with right date.\n\nArgs:\n func: function you want to decorate.\n request: WSGI request parameter getten from django.\n\nReturns:\n date:\n a datetime variable, you can only give year, year + month or year + month + day, three type.\n The missing part would be assigned default value 1 (for month is Jan, for day is 1).", "source": "juraj_google_style"} +{"code": "def create_with_claims(self, claims):\n\n new_kwargs = dict(self._kwargs)\n new_kwargs.update(claims)\n result = self.__class__(self._service_account_email,\n self._signer,\n scopes=self._scopes,\n private_key_id=self._private_key_id,\n client_id=self.client_id,\n user_agent=self._user_agent,\n **new_kwargs)\n result.token_uri = self.token_uri\n result.revoke_uri = self.revoke_uri\n result._private_key_pkcs8_pem = self._private_key_pkcs8_pem\n result._private_key_pkcs12 = self._private_key_pkcs12\n result._private_key_password = self._private_key_password\n return result", "docstring": "Create credentials that specify additional claims.\n\nArgs:\n claims: dict, key-value pairs for claims.\n\nReturns:\n ServiceAccountCredentials, a copy of the current service account\n credentials with updated claims to use when obtaining access\n tokens.", "source": "juraj_google_style"} +{"code": "def query(self, query, archiver=\"\", timeout=DEFAULT_TIMEOUT):\n\n if archiver == \"\":\n archiver = self.archivers[0]\n\n nonce = random.randint(0, 2**32)\n ev = threading.Event()\n response = {}\n def _handleresult(msg):\n # decode, throw away if not correct nonce\n got_response = False\n error = getError(nonce, msg)\n if error is not None:\n got_response = True\n response[\"error\"] = error\n\n metadata = getMetadata(nonce, msg)\n if metadata is not None:\n got_response = True\n response[\"metadata\"] = metadata\n\n timeseries = getTimeseries(nonce, msg)\n if timeseries is not None:\n got_response = True\n response[\"timeseries\"] = timeseries\n\n if got_response:\n ev.set()\n\n vk = self.vk[:-1] # remove last part of VK because archiver doesn't expect it\n\n # set up receiving\n self.c.subscribe(\"{0}/s.giles/_/i.archiver/signal/{1},queries\".format(archiver, vk), _handleresult)\n\n # execute query\n q_struct = msgpack.packb({\"Query\": query, \"Nonce\": nonce})\n po = PayloadObject((2,0,8,1), None, q_struct)\n self.c.publish(\"{0}/s.giles/_/i.archiver/slot/query\".format(archiver), payload_objects=(po,))\n\n ev.wait(timeout)\n if len(response) == 0: # no results\n raise TimeoutException(\"Query of {0} timed out\".format(query))\n return response", "docstring": "Runs the given pundat query and returns the results as a Python object.\n\nArgs:\n [query]: the query string\n [archiver]: if specified, this is the archiver to use. Else, it will run on the first archiver passed\n into the constructor for the client\n [timeout]: time in seconds to wait for a response from the archiver", "source": "juraj_google_style"} +{"code": "def __init__(self, method, stop_if_false=False):\n\n self.method = method\n self.stopped = threading.Event()\n self.thread = None\n self.stop_if_false = stop_if_false", "docstring": "Initializes the Interval.\n\nArgs:\n method: A callable to execute, it should take no arguments.\n stop_if_false: If True, the interval will exit if the method returns\n False.", "source": "juraj_google_style"} +{"code": "def get_execution_info(self, driver_id, function_descriptor):\n\n if self._worker.load_code_from_local:\n # Load function from local code.\n # Currently, we don't support isolating code by drivers,\n # thus always set driver ID to NIL here.\n driver_id = ray.DriverID.nil()\n if not function_descriptor.is_actor_method():\n self._load_function_from_local(driver_id, function_descriptor)\n else:\n # Load function from GCS.\n # Wait until the function to be executed has actually been\n # registered on this worker. We will push warnings to the user if\n # we spend too long in this loop.\n # The driver function may not be found in sys.path. Try to load\n # the function from GCS.\n with profiling.profile(\"wait_for_function\"):\n self._wait_for_function(function_descriptor, driver_id)\n try:\n function_id = function_descriptor.function_id\n info = self._function_execution_info[driver_id][function_id]\n except KeyError as e:\n message = (\"Error occurs in get_execution_info: \"\n \"driver_id: %s, function_descriptor: %s. Message: %s\" %\n (driver_id, function_descriptor, e))\n raise KeyError(message)\n return info", "docstring": "Get the FunctionExecutionInfo of a remote function.\n\nArgs:\n driver_id: ID of the driver that the function belongs to.\n function_descriptor: The FunctionDescriptor of the function to get.\n\nReturns:\n A FunctionExecutionInfo object.", "source": "juraj_google_style"} +{"code": "def query_phenomizer(usr, pwd, *hpo_terms):\n\n base_string = 'http://compbio.charite.de/phenomizer/phenomizer/PhenomizerServiceURI'\n questions = {'mobilequery':'true', 'terms':','.join(hpo_terms), 'username':usr, 'password':pwd}\n try:\n r = requests.get(base_string, params=questions, timeout=10)\n except requests.exceptions.Timeout:\n raise RuntimeError(\"The request timed out.\")\n\n if not r.status_code == requests.codes.ok:\n raise RuntimeError(\"Phenomizer returned a bad status code: %s\" % r.status_code)\n\n r.encoding = 'utf-8'\n\n return r", "docstring": "Query the phenomizer web tool\n\nArgs:\n usr (str): A username for phenomizer\n pwd (str): A password for phenomizer\n hpo_terms (list): A list with hpo terms\n\nReturns:\n raw_answer : The raw result from phenomizer", "source": "juraj_google_style"} +{"code": "def get(self, key=None):\n\n\n if key:\n key = ub_to_str(key)\n if settings.ENABLE_CACHING:\n return self.get_from_cache(key) or self.set_to_cache(self._get_from_riak(key))\n\n else:\n return self._get_from_riak(key)\n\n else:\n self._exec_query()\n if not self._solr_cache['docs']:\n raise ObjectDoesNotExist(\"%s %s\" % (self.index_name, self.compiled_query))\n\n if self.count() > 1:\n raise MultipleObjectsReturned(\n \"%s objects returned for %s\" % (self.count(),\n self._model_class.__name__))\n\n return self._get_from_riak(self._solr_cache['docs'][0]['_yz_rk'])", "docstring": "If key is not None, tries to get obj from cache first. If not\n found, tries to get from riak and sets to cache.\n\n If key is None, then execute solr query and checks result. Returns\n obj data and key tuple or raises exception ObjectDoesNotExist or\n MultipleObjectsReturned.\n\nArgs:\n key(str): obj key\n\nReturns:\n (tuple): obj data dict, obj key", "source": "juraj_google_style"} +{"code": "def GetVShadowStoreByPathSpec(self, path_spec):\n\n store_index = vshadow.VShadowPathSpecGetStoreIndex(path_spec)\n if store_index is None:\n return None\n\n return self._vshadow_volume.get_store(store_index)", "docstring": "Retrieves a VSS store for a path specification.\n\nArgs:\n path_spec (PathSpec): path specification.\n\nReturns:\n pyvshadow.store: a VSS store or None if not available.", "source": "juraj_google_style"} +{"code": "def create_zone(server, token, domain, identifier, dtype, master=None):\n\n method = 'PUT'\n uri = 'https://' + server + '/zone'\n\n obj = JSONConverter(domain)\n obj.generate_zone(domain, identifier, dtype, master)\n connect.tonicdns_client(uri, method, token, obj.zone)", "docstring": "Create zone records.\n\nArgs:\n server: TonicDNS API server\n token: TonicDNS API authentication token\n domain: Specify domain name\n identifier: Template ID\n dtype: MASTER|SLAVE|NATIVE (default: MASTER)\n master: master server ip address when dtype is SLAVE\n (default: None)\n\n ContentType: application/json\n x-authentication-token: token", "source": "juraj_google_style"} +{"code": "def get_decomposition_energy(self, entry, pH, V):\n\n # Find representative multientry\n if self._multielement and not isinstance(entry, MultiEntry):\n possible_entries = self._generate_multielement_entries(\n self._filtered_entries, forced_include=[entry])\n\n # Filter to only include materials where the entry is only solid\n if entry.phase_type == \"solid\":\n possible_entries = [e for e in possible_entries\n if e.phase_type.count(\"Solid\") == 1]\n possible_energies = [e.normalized_energy_at_conditions(pH, V)\n for e in possible_entries]\n else:\n possible_energies = [entry.normalized_energy_at_conditions(pH, V)]\n\n min_energy = np.min(possible_energies, axis=0)\n\n # Find entry and take the difference\n hull = self.get_hull_energy(pH, V)\n return min_energy - hull", "docstring": "Finds decomposition to most stable entry\n\nArgs:\n entry (PourbaixEntry): PourbaixEntry corresponding to\n compound to find the decomposition for\n pH (float): pH at which to find the decomposition\n V (float): voltage at which to find the decomposition\n\nReturns:\n reaction corresponding to the decomposition", "source": "juraj_google_style"} +{"code": "def __init__(self, rate=None, burst_size=None):\n\n super().__init__(MeterBandType.OFPMBT_DROP, rate, burst_size)", "docstring": "Create a MeterBandDrop with the optional parameters below.\n\nArgs:\n rate (int): Rate for dropping packets.\n burst_size (int): Size of bursts.", "source": "juraj_google_style"} +{"code": "def from_list(cls, vals: List[Value] = [], reverse: bool = False) -> \"LinkedList\":\n\n res = EmptyList()\n for v in (vals if reverse else vals[::-1]):\n res = cls(v, res)\n return res", "docstring": "Create an instance from a standard list.\n\nArgs:\n vals: Python list of instance values.", "source": "juraj_google_style"} +{"code": "def convert_attribute_tag_to_name(value):\n\n if not isinstance(value, Tags):\n raise ValueError(\"The attribute tag must be a Tags enumeration.\")\n\n for entry in attribute_name_tag_table:\n if value == entry[1]:\n return entry[0]\n\n raise ValueError(\"Unrecognized attribute tag: {}\".format(value))", "docstring": "A utility function that converts an attribute tag into the corresponding\n attribute name string.\n\n For example: enums.Tags.STATE -> 'State'\n\nArgs:\n value (enum): The Tags enumeration value of the attribute.\n\nReturns:\n string: The attribute name string that corresponds to the attribute\n tag.\n\nRaises:\n ValueError: if the attribute tag is not a Tags enumeration or if it\n is unrecognized attribute tag", "source": "juraj_google_style"} +{"code": "def available_writers(as_dict=False):\n\n writers = []\n for writer_configs in configs_for_writer():\n try:\n writer_info = read_writer_config(writer_configs)\n except (KeyError, IOError, yaml.YAMLError):\n LOG.warning(\"Could not import writer config from: %s\", writer_configs)\n LOG.debug(\"Error loading YAML\", exc_info=True)\n continue\n writers.append(writer_info if as_dict else writer_info['name'])\n return writers", "docstring": "Available writers based on current configuration.\n\nArgs:\n as_dict (bool): Optionally return writer information as a dictionary.\n Default: False\n\n Returns: List of available writer names. If `as_dict` is `True` then\n a list of dictionaries including additionally writer information\n is returned.", "source": "juraj_google_style"} +{"code": "def create_model_package_from_algorithm(self, name, description, algorithm_arn, model_data):\n\n request = {\n 'ModelPackageName': name,\n 'ModelPackageDescription': description,\n 'SourceAlgorithmSpecification': {\n 'SourceAlgorithms': [\n {\n 'AlgorithmName': algorithm_arn,\n 'ModelDataUrl': model_data\n }\n ]\n }\n }\n try:\n LOGGER.info('Creating model package with name: {}'.format(name))\n self.sagemaker_client.create_model_package(**request)\n except ClientError as e:\n error_code = e.response['Error']['Code']\n message = e.response['Error']['Message']\n\n if (\n error_code == 'ValidationException'\n and 'ModelPackage already exists' in message\n ):\n LOGGER.warning('Using already existing model package: {}'.format(name))\n else:\n raise", "docstring": "Create a SageMaker Model Package from the results of training with an Algorithm Package\n\nArgs:\n name (str): ModelPackage name\n description (str): Model Package description\n algorithm_arn (str): arn or name of the algorithm used for training.\n model_data (str): s3 URI to the model artifacts produced by training", "source": "juraj_google_style"} +{"code": "def AddEventTag(self, event_tag):\n\n self._RaiseIfNotWritable()\n\n event_identifier = event_tag.GetEventIdentifier()\n if not isinstance(event_identifier, identifiers.SQLTableIdentifier):\n raise IOError('Unsupported event identifier type: {0:s}'.format(\n type(event_identifier)))\n\n event_tag.event_row_identifier = event_identifier.row_identifier\n\n self._AddAttributeContainer(self._CONTAINER_TYPE_EVENT_TAG, event_tag)", "docstring": "Adds an event tag.\n\nArgs:\n event_tag (EventTag): event tag.\n\nRaises:\n IOError: when the storage file is closed or read-only or\n if the event identifier type is not supported.\n OSError: when the storage file is closed or read-only or\n if the event identifier type is not supported.", "source": "juraj_google_style"} +{"code": "def _x_open(self):\n\n if self.is_open:\n return\n\n args = AMQPWriter()\n args.write_shortstr('') # out_of_band: deprecated\n self._send_method((20, 10), args)\n return self.wait(allowed_methods=[\n (20, 11), # Channel.open_ok\n ])", "docstring": "Open a channel for use\n\n This method opens a virtual connection (a channel).\n\n RULE:\n\n This method MUST NOT be called when the channel is already\n open.\n\n PARAMETERS:\n out_of_band: shortstr (DEPRECATED)\n\n out-of-band settings\n\n Configures out-of-band transfers on this channel. The\n syntax and meaning of this field will be formally\n defined at a later date.", "source": "juraj_google_style"} +{"code": "def JoinPath(self, path_segments):\n\n # This is an optimized way to combine the path segments into a single path\n # and combine multiple successive path separators to one.\n\n # Split all the path segments based on the path (segment) separator.\n path_segments = [\n segment.split(self.PATH_SEPARATOR) for segment in path_segments]\n\n # Flatten the sublists into one list.\n path_segments = [\n element for sublist in path_segments for element in sublist]\n\n # Remove empty path segments.\n path_segments = list(filter(None, path_segments))\n\n return '{0:s}{1:s}'.format(\n self.PATH_SEPARATOR, self.PATH_SEPARATOR.join(path_segments))", "docstring": "Joins the path segments into a path.\n\nArgs:\n path_segments (list[str]): path segments.\n\nReturns:\n str: joined path segments prefixed with the path separator.", "source": "juraj_google_style"} +{"code": "def __init__(self, module, dropout, weights=['weight_hh_l0']):\n\n super().__init__()\n self.module,self.weights,self.dropout = module,weights,dropout\n self._setup()", "docstring": "Default constructor for the WeightDrop module\n\nArgs:\n module (torch.nn.Module): A pytorch layer being wrapped\n dropout (float): a dropout value to apply\n weights (list(str)): the parameters of the wrapped **module**\n which should be fractionally dropped.", "source": "juraj_google_style"} +{"code": "def __init__(self, ea=UseCurrentAddress, name=None, index=None, segment_t=None):\n\n if sum((ea not in (self.UseCurrentAddress, None), name is not None, index is not None,\n segment_t is not None,)) > 1:\n raise ValueError((\n \"Expected only one (ea, name, index or segment_t).\"\n \" Got (ea={!r}, name={!r}, index={!r}, segment_t={!r})\"\n ).format(ea,\n name,\n index,\n segment_t))\n\n\n elif segment_t is not None:\n seg = segment_t\n\n elif name is not None:\n seg = idaapi.get_segm_by_name(name)\n\n elif index is not None:\n seg = idaapi.getnseg(index)\n\n elif ea == self.UseCurrentAddress:\n seg = idaapi.getseg(idc.here())\n\n elif ea is None:\n raise ValueError(\"`None` is not a valid address. To use the current screen ea, \"\n \"use `Function(ea=Function.UseCurrentAddress)` or supply no `ea`.\")\n\n else:\n seg = idaapi.getseg(ea)\n\n self._segment = seg", "docstring": "Wrapper around IDA segments.\n\n There are 3 ways to get a segment - by name, ea or index. Only use one.\n\nArgs:\n ea - address in the segment\n name - name of the segment\n index - index of the segment", "source": "juraj_google_style"} +{"code": "def add_arguments(self, parser, bootstrap=False):\n\n [item.add_argument(parser, bootstrap)\n for item in self._get_items(bootstrap=False)]", "docstring": "Adds all items to the parser passed in.\n\nArgs:\n parser (argparse.ArgumentParser): The parser to add all items to.\n bootstrap (bool): Flag to indicate whether you only want to mark\n bootstrapped items as required on the command-line.", "source": "juraj_google_style"} +{"code": "def guess_content_type_and_encoding(path):\n\n for ext, content_type in _EXTENSION_TO_MIME_TYPE.items():\n if path.endswith(ext):\n return content_type\n\n content_type, encoding = mimetypes.guess_type(path)\n content_type = content_type or \"application/binary\"\n return content_type, encoding", "docstring": "Guess the content type of a path, using ``mimetypes``.\n\n Falls back to \"application/binary\" if no content type is found.\n\nArgs:\n path (str): the path to guess the mimetype of\n\nReturns:\n str: the content type of the file", "source": "juraj_google_style"} +{"code": "def make_iterable(value):\n\n if sys.version_info <= (3, 0):\n # Convert unicode values to strings for Python 2\n if isinstance(value, unicode):\n value = str(value)\n if isinstance(value, str) or isinstance(value, dict):\n value = [value]\n\n if not isinstance(value, collections.Iterable):\n raise TypeError('value must be an iterable object')\n\n return value", "docstring": "Converts the supplied value to a list object\n\n This function will inspect the supplied value and return an\n iterable in the form of a list.\n\nArgs:\n value (object): An valid Python object\n\nReturns:\n An iterable object of type list", "source": "juraj_google_style"} +{"code": "def __init__(self, path_segment_index):\n\n super(PathFilterScanTreeNode, self).__init__()\n self._path_segments = {}\n self.default_value = None\n self.parent = None\n self.path_segment_index = path_segment_index", "docstring": "Initializes a path filter scan tree node.\n\nArgs:\n path_segment_index: an integer containing the path segment index.", "source": "juraj_google_style"} +{"code": "def get_site_energy(self, site_index):\n\n if self._charged:\n warn('Per atom energies for charged structures not supported in EwaldSummation')\n return np.sum(self._recip[:,site_index]) + np.sum(self._real[:,site_index]) \\\n + self._point[site_index]", "docstring": "Compute the energy for a single site in the structure\n\nArgs:\n site_index (int): Index of site\n\nReturns:\n (float) - Energy of that site", "source": "juraj_google_style"} +{"code": "def add_enum(name=None, index=None, flags=idaapi.hexflag(), bitfield=False):\n\n if name is not None:\n with ignored(exceptions.EnumNotFound):\n _get_enum(name)\n raise exceptions.EnumAlreadyExists()\n\n if index is None or index < 0:\n index = idaapi.get_enum_qty()\n\n eid = idaapi.add_enum(index, name, flags)\n\n if eid == idaapi.BADADDR:\n raise exceptions.EnumCreationFailed('Failed creating enum \"{}\"'.format(name))\n\n if bitfield:\n idaapi.set_enum_bf(eid, bitfield)\n\n return Enum(eid=eid)", "docstring": "Create a new enum.\n\nArgs:\n name: Name of the enum to create.\n index: The index of the enum. Leave at default to append the enum as the last enum.\n flags: Enum type flags.\n bitfield: Is the enum a bitfield.\n\nReturns:\n An `Enum` object.", "source": "juraj_google_style"} +{"code": "def cardinal(self, to):\n\n return sum(m.cardinal(to) for m in self.submodules)", "docstring": "Return the number of dependencies of this package to the given node.\n\nArgs:\n to (Package/Module): target node.\n\nReturns:\n int: number of dependencies.", "source": "juraj_google_style"} +{"code": "def save_users(users, path=settings.LOGIN_FILE):\n\n with open(path, \"w\") as fh:\n for username, data in users.items():\n pass_line = username + \":\" + \":\".join([\n data[\"pass_hash\"],\n data[\"uid\"],\n data[\"gid\"],\n data[\"full_name\"],\n data[\"home\"],\n data[\"shell\"]\n ])\n\n fh.write(pass_line + \"\\n\")", "docstring": "Save dictionary with user data to passwd file (default\n :attr:`ftp.settings.LOGIN_FILE`).\n\nArgs:\n users (dict): dictionary with user data. For details look at dict\n returned from :func:`load_users`.\n path (str, default settings.LOGIN_FILE): path of the file, where the\n data will be stored (default :attr:`ftp.settings.LOGIN_FILE`).", "source": "juraj_google_style"} +{"code": "def get(self, key, default) -> Union[Uniform, UniformBlock, Subroutine, Attribute, Varying]:\n\n\n return self._members.get(key, default)", "docstring": "Returns a Uniform, UniformBlock, Subroutine, Attribute or Varying.\n\nArgs:\n default: This is the value to be returned in case key does not exist.\n\nReturns:\n :py:class:`Uniform`, :py:class:`UniformBlock`, :py:class:`Subroutine`,\n :py:class:`Attribute` or :py:class:`Varying`", "source": "juraj_google_style"} +{"code": "def blend(self, other, percent=0.5):\n\n dest = 1.0 - percent\n rgb = tuple(((u * percent) + (v * dest) for u, v in zip(self.__rgb, other.__rgb)))\n a = (self.__a * percent) + (other.__a * dest)\n return Color(rgb, 'rgb', a, self.__wref)", "docstring": "blend this color with the other one.\n\nArgs:\n :other:\n the grapefruit.Color to blend with this one.\n\nReturns:\n A grapefruit.Color instance which is the result of blending\n this color on the other one.\n\n >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2)\n >>> c2 = Color.from_rgb(1, 1, 1, 0.6)\n >>> c3 = c1.blend(c2)\n >>> c3\n Color(1.0, 0.75, 0.5, 0.4)", "source": "juraj_google_style"} +{"code": "def _scandir_generator(is_bytes, scandir_path, system):\n\n with handle_os_exceptions():\n for name, header in system.list_objects(scandir_path, first_level=True):\n yield DirEntry(\n scandir_path=scandir_path, system=system, name=name,\n header=header, bytes_path=is_bytes)", "docstring": "scandir generator\n\nArgs:\n is_bytes (bool): True if DirEntry must handle path as bytes.\n scandir_path (str): Path.\n system (pycosio._core.io_system.SystemBase subclass):\n Storage system.\n\nYields:\n DirEntry: Directory entries", "source": "juraj_google_style"} +{"code": "def _preprocess_sqlite_index(asql_query, library, backend, connection):\n\n\n new_query = None\n\n if asql_query.strip().lower().startswith('index'):\n\n logger.debug(\n '_preprocess_index: create index query found.\\n asql query: {}'\n .format(asql_query))\n\n index = parse_index(asql_query)\n partition = library.partition(index.source)\n table = backend.install(connection, partition, materialize=True)\n index_name = '{}_{}_ind'.format(partition.vid, '_'.join(index.columns))\n new_query = 'CREATE INDEX IF NOT EXISTS {index} ON {table} ({columns});'.format(\n index=index_name, table=table, columns=','.join(index.columns))\n\n logger.debug(\n '_preprocess_index: preprocess finished.\\n asql query: {}\\n new query: {}'\n .format(asql_query, new_query))\n\n return new_query or asql_query", "docstring": "Creates materialized view for each indexed partition found in the query.\n\nArgs:\n asql_query (str): asql query\n library (ambry.Library):\n backend (SQLiteBackend):\n connection (apsw.Connection):\n\nReturns:\n str: converted asql if it contains index query. If not, returns asql_query as is.", "source": "juraj_google_style"} +{"code": "def match(self, f, *args):\n\n try:\n match = f(self.tokenizer, *args)\n except StopIteration:\n # The grammar function might have tried to access more tokens than\n # are available. That's not really an error, it just means it didn't\n # match.\n return\n\n if match is None:\n return\n\n if not isinstance(match, grammar.TokenMatch):\n raise TypeError(\"Invalid grammar function %r returned %r.\"\n % (f, match))\n\n self.matched = match\n return match", "docstring": "Match grammar function 'f' against next token and set 'self.matched'.\n\nArgs:\n f: A grammar function - see efilter.parsers.common.grammar. Must\n return TokenMatch or None.\n args: Passed to 'f', if any.\n\nReturns:\n Instance of efilter.parsers.common.grammar.TokenMatch or None.\n\n Comment:\n If a match is returned, it will also be stored in self.matched.", "source": "juraj_google_style"} +{"code": "def multi_get(self, urls, query_params=None, to_json=True):\n\n return self._multi_request(\n MultiRequest._VERB_GET, urls, query_params,\n data=None, to_json=to_json,\n )", "docstring": "Issue multiple GET requests.\n\nArgs:\n urls - A string URL or list of string URLs\n query_params - None, a dict, or a list of dicts representing the query params\n to_json - A boolean, should the responses be returned as JSON blobs\n\nReturns:\n a list of dicts if to_json is set of requests.response otherwise.\n\nRaises:\n InvalidRequestError - Can not decide how many requests to issue.", "source": "juraj_google_style"} +{"code": "def _CountStoredAttributeContainers(self, container_type):\n\n if not container_type in self._CONTAINER_TYPES:\n raise ValueError('Attribute container type {0:s} is not supported'.format(\n container_type))\n\n if not self._HasTable(container_type):\n return 0\n\n # Note that this is SQLite specific, and will give inaccurate results if\n # there are DELETE commands run on the table. The Plaso SQLite storage\n # implementation does not run any DELETE commands.\n query = 'SELECT MAX(_ROWID_) FROM {0:s} LIMIT 1'.format(container_type)\n self._cursor.execute(query)\n row = self._cursor.fetchone()\n if not row:\n return 0\n\n return row[0] or 0", "docstring": "Counts the number of attribute containers of the given type.\n\nArgs:\n container_type (str): attribute container type.\n\nReturns:\n int: number of attribute containers of the given type.\n\nRaises:\n ValueError: if an unsupported container_type is provided.", "source": "juraj_google_style"} +{"code": "def _get_non_string_match(self, key):\n\n\n expression = r'(?:\\s*)'.join([\n '^',\n 'define',\n r'\\(',\n '\\'{}\\''.format(key),\n ',',\n r'(.*)',\n r'\\)',\n ';'\n ])\n\n pattern = re.compile(expression, re.MULTILINE)\n return pattern.search(self._content)", "docstring": "Gets a MatchObject for the given key, assuming a non-string value.\n\nArgs:\n key (str): Key of the property to look-up.\n\nReturns:\n MatchObject: The discovered match.", "source": "juraj_google_style"} +{"code": "def _expand_terms(self, terms):\n\n ret = {\n 'keywords': list(),\n 'doc': list(),\n 'from': None,\n 'to': None}\n\n if not isinstance(terms, dict):\n stp = SearchTermParser()\n terms = stp.parse(terms, term_join=self.backend._and_join)\n\n if 'about' in terms:\n ret['doc'].append(terms['about'])\n\n if 'with' in terms:\n ret['doc'].append(terms['with'])\n\n if 'in' in terms:\n place_vids = self._expand_place_ids(terms['in'])\n ret['keywords'].append(place_vids)\n\n if 'by' in terms:\n ret['keywords'].append(terms['by'])\n ret['from'] = terms.get('from', None)\n ret['to'] = terms.get('to', None)\n return ret", "docstring": "Expands partition terms to the appropriate fields.\n\nArgs:\n terms (dict or str):\n\nReturns:\n dict: keys are field names, values are query strings", "source": "juraj_google_style"} +{"code": "def setRightsHolder(self, pid, userId, serialVersion, vendorSpecific=None):\n\n response = self.setRightsHolderResponse(\n pid, userId, serialVersion, vendorSpecific\n )\n return self._read_boolean_response(response)", "docstring": "See Also: setRightsHolderResponse()\n\nArgs:\n pid:\n userId:\n serialVersion:\n vendorSpecific:\n\n Returns:", "source": "juraj_google_style"} +{"code": "def in_coord_list(coord_list, coord, atol=1e-8):\n\n return len(find_in_coord_list(coord_list, coord, atol=atol)) > 0", "docstring": "Tests if a particular coord is within a coord_list.\n\nArgs:\n coord_list: List of coords to test\n coord: Specific coordinates\n atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and\n array.\n\nReturns:\n True if coord is in the coord list.", "source": "juraj_google_style"} +{"code": "def has_namespace(self, namespace):\n\n result = requests.get(self._make_url(namespace))\n if result.status_code == 200:\n return True\n elif result.status_code == 404:\n return False", "docstring": "tests to see if the namespace exists\n\nArgs:\n namespace: the name of the namespace", "source": "juraj_google_style"} +{"code": "def setChannel(self, channel=11):\n\n print '%s call setChannel' % self.port\n print channel\n try:\n cmd = 'channel %s' % channel\n datasetCmd = 'dataset channel %s' % channel\n self.hasActiveDatasetToCommit = True\n return self.__sendCommand(cmd)[0] == 'Done' and self.__sendCommand(datasetCmd)[0] == 'Done'\n except Exception, e:\n ModuleHelper.WriteIntoDebugLogger(\"setChannel() Error: \" + str(e))", "docstring": "set channel of Thread device operates on.\n\nArgs:\n channel:\n (0 - 10: Reserved)\n (11 - 26: 2.4GHz channels)\n (27 - 65535: Reserved)\n\nReturns:\n True: successful to set the channel\n False: fail to set the channel", "source": "juraj_google_style"} +{"code": "def get_imap_capabilities(server):\n\n\n capabilities = list(map(str, list(server.capabilities())))\n for i in range(len(capabilities)):\n capabilities[i] = str(capabilities[i]).replace(\"b'\",\n \"\").replace(\"'\",\n \"\")\n logger.debug(\"IMAP server supports: {0}\".format(capabilities))\n\n return capabilities", "docstring": "Returns a list of an IMAP server's capabilities\n\nArgs:\n server (imapclient.IMAPClient): An instance of imapclient.IMAPClient\n\n Returns (list): A list of capabilities", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.AnnotateVideo = channel.unary_unary(\n \"/google.cloud.videointelligence.v1beta1.VideoIntelligenceService/AnnotateVideo\",\n request_serializer=google_dot_cloud_dot_videointelligence__v1beta1_dot_proto_dot_video__intelligence__pb2.AnnotateVideoRequest.SerializeToString,\n response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def forward(self, X):\n\n return self.W(X).sum(dim=1) + self.b", "docstring": "Execute sparse linear layer\n\nArgs:\n X: an [n, h] torch.LongTensor containing up to h indices of features\n whose weights should be looked up and used in a sparse linear\n multiplication.", "source": "juraj_google_style"} +{"code": "def get_processes(sort_by_name=True):\n\n if sort_by_name:\n return sorted(\n _list_processes(),\n key=cmp_to_key(\n lambda p1, p2: (cmp(p1.name, p2.name) or cmp(p1.pid, p2.pid))\n ),\n )\n else:\n return sorted(\n _list_processes(),\n key=cmp_to_key(\n lambda p1, p2: (cmp(p1.pid, p2.pid) or cmp(p1.name, p2.name))\n ),\n )", "docstring": "Retrieve a list of processes sorted by name.\n\nArgs:\n sort_by_name (bool): Sort the list by name or by process ID's.\n\nReturns:\n list of (int, str) or list of (int, str, str): List of process id,\n process name and optional cmdline tuples.", "source": "juraj_google_style"} +{"code": "def _restore_and_log_checkpoint(self, actor):\n\n actor_id = self._worker.actor_id\n try:\n checkpoints = ray.actor.get_checkpoints_for_actor(actor_id)\n if len(checkpoints) > 0:\n # If we found previously saved checkpoints for this actor,\n # call the `load_checkpoint` callback.\n checkpoint_id = actor.load_checkpoint(actor_id, checkpoints)\n if checkpoint_id is not None:\n # Check that the returned checkpoint id is in the\n # `available_checkpoints` list.\n msg = (\n \"`load_checkpoint` must return a checkpoint id that \" +\n \"exists in the `available_checkpoints` list, or eone.\")\n assert any(checkpoint_id == checkpoint.checkpoint_id\n for checkpoint in checkpoints), msg\n # Notify raylet that this actor has been resumed from\n # a checkpoint.\n (self._worker.raylet_client.\n notify_actor_resumed_from_checkpoint(\n actor_id, checkpoint_id))\n except Exception:\n # Checkpoint save or reload failed. Notify the driver.\n traceback_str = ray.utils.format_error_message(\n traceback.format_exc())\n ray.utils.push_error_to_driver(\n self._worker,\n ray_constants.CHECKPOINT_PUSH_ERROR,\n traceback_str,\n driver_id=self._worker.task_driver_id)", "docstring": "Restore an actor from a checkpoint if available and log any errors.\n\n This should only be called on workers that have just executed an actor\n creation task.\n\nArgs:\n actor: The actor to restore from a checkpoint.", "source": "juraj_google_style"} +{"code": "def upload_list(self, uploader_id=None, uploader_name=None, source=None):\n\n params = {\n 'search[uploader_id]': uploader_id,\n 'search[uploader_name]': uploader_name,\n 'search[source]': source\n }\n return self._get('uploads.json', params, auth=True)", "docstring": "Search and return an uploads list (Requires login).\n\n Parameters:\n uploader_id (int): The id of the uploader.\n uploader_name (str): The name of the uploader.\n source (str): The source of the upload (exact string match).", "source": "juraj_google_style"} +{"code": "def imfrombytes(content, flag='color'):\n\n img_np = np.frombuffer(content, np.uint8)\n flag = imread_flags[flag] if is_str(flag) else flag\n img = cv2.imdecode(img_np, flag)\n return img", "docstring": "Read an image from bytes.\n\nArgs:\n content (bytes): Image bytes got from files or other streams.\n flag (str): Same as :func:`imread`.\n\nReturns:\n ndarray: Loaded image array.", "source": "juraj_google_style"} +{"code": "def prepare_cql_query(self, query, compression):\n\n self._seqid += 1\n d = self._reqs[self._seqid] = defer.Deferred()\n self.send_prepare_cql_query(query, compression)\n return d", "docstring": "Prepare a CQL (Cassandra Query Language) statement by compiling and returning\n - the type of CQL statement\n - an id token of the compiled CQL stored on the server side.\n - a count of the discovered bound markers in the statement\n\n Parameters:\n - query\n - compression", "source": "juraj_google_style"} +{"code": "def load_with_vocab(fin, vocab, dtype=np.float32):\n\n arr = None\n for line in fin:\n try:\n token, v = _parse_line(line, dtype)\n except (ValueError, IndexError):\n raise ParseError(b'Parsing error in line: ' + line)\n if token in vocab:\n if arr is None:\n arr = np.empty((len(vocab), len(v)), dtype=dtype)\n arr.fill(np.NaN)\n elif arr.shape[1] != len(v):\n raise ParseError(b'Vector size did not match in line: ' + line)\n arr[vocab[token], :] = np.array(v, dtype=dtype).reshape(1, -1)\n return arr", "docstring": "Load word embedding file with predefined vocabulary\n\nArgs:\n fin (File): File object to read. File should be open for reading ascii.\n vocab (dict): Mapping from words (``bytes``) to vector indices\n (``int``).\n dtype (numpy.dtype): Element data type to use for the array.\n\nReturns:\n numpy.ndarray: Word embedding representation vectors", "source": "juraj_google_style"} +{"code": "def disconnect_async(self, conn_id, callback):\n\n\n try:\n context = self.conns.get_context(conn_id)\n except ArgumentError:\n callback(conn_id, self.id, False, \"Could not find connection information\")\n return\n\n self.conns.begin_disconnection(conn_id, callback, self.get_config('default_timeout'))\n\n topics = context['topics']\n disconn_message = {'key': context['key'], 'client': self.name, 'type': 'command', 'operation': 'disconnect'}\n\n self.client.publish(topics.action, disconn_message)", "docstring": "Asynchronously disconnect from a device that has previously been connected\n\nArgs:\n conn_id (int): a unique identifier for this connection on the DeviceManager\n that owns this adapter.\n callback (callable): A function called as callback(conn_id, adapter_id, success, failure_reason)\n when the disconnection finishes. Disconnection can only either succeed or timeout.", "source": "juraj_google_style"} +{"code": "def display_upstream_structure(structure_dict):\n\n graph = _create_graph(structure_dict)\n plt = Image(graph.create_png())\n display(plt)", "docstring": "Displays pipeline structure in the jupyter notebook.\n\nArgs:\n structure_dict (dict): dict returned by\n :func:`~steppy.base.Step.upstream_structure`.", "source": "juraj_google_style"} +{"code": "def get_dimensions(js_dict, naming):\n\n\n dimensions = []\n dim_names = []\n if check_version_2(js_dict):\n dimension_dict = js_dict\n else:\n dimension_dict = js_dict['dimension']\n for dim in dimension_dict['id']:\n dim_name = js_dict['dimension'][dim]['label']\n if not dim_name:\n dim_name = dim\n if naming == 'label':\n dim_label = get_dim_label(js_dict, dim)\n dimensions.append(dim_label)\n dim_names.append(dim_name)\n else:\n dim_index = get_dim_index(js_dict, dim)\n dimensions.append(dim_index)\n dim_names.append(dim)\n return dimensions, dim_names", "docstring": "Get dimensions from input data.\n\nArgs:\n js_dict (dict): dictionary containing dataset data and metadata.\n naming (string, optional): dimension naming. Possible values: 'label' \\\n or 'id'.\n\nReturns:\n dimensions (list): list of pandas data frames with dimension \\\n category data.\n dim_names (list): list of strings with dimension names.", "source": "juraj_google_style"} +{"code": "def to_element(self, include_namespaces=False):\n\n elt_attrib = {}\n if include_namespaces:\n elt_attrib.update({\n 'xmlns': \"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\",\n 'xmlns:dc': \"http://purl.org/dc/elements/1.1/\",\n 'xmlns:upnp': \"urn:schemas-upnp-org:metadata-1-0/upnp/\",\n })\n elt_attrib.update({\n 'parentID': self.parent_id,\n 'restricted': 'true' if self.restricted else 'false',\n 'id': self.item_id\n })\n elt = XML.Element(self.tag, elt_attrib)\n\n # Add the title, which should always come first, according to the spec\n XML.SubElement(elt, 'dc:title').text = self.title\n\n # Add in any resources\n for resource in self.resources:\n elt.append(resource.to_element())\n\n # Add the rest of the metadata attributes (i.e all those listed in\n # _translation) as sub-elements of the item element.\n for key, value in self._translation.items():\n if hasattr(self, key):\n # Some attributes have a namespace of '', which means they\n # are in the default namespace. We need to handle those\n # carefully\n tag = \"%s:%s\" % value if value[0] else \"%s\" % value[1]\n XML.SubElement(elt, tag).text = (\"%s\" % getattr(self, key))\n # Now add in the item class\n XML.SubElement(elt, 'upnp:class').text = self.item_class\n\n # And the desc element\n desc_attrib = {'id': 'cdudn', 'nameSpace':\n 'urn:schemas-rinconnetworks-com:metadata-1-0/'}\n desc_elt = XML.SubElement(elt, 'desc', desc_attrib)\n desc_elt.text = self.desc\n\n return elt", "docstring": "Return an ElementTree Element representing this instance.\n\nArgs:\n include_namespaces (bool, optional): If True, include xml\n namespace attributes on the root element\n\nReturns:\n ~xml.etree.ElementTree.Element: an Element.", "source": "juraj_google_style"} +{"code": "def get_msms_df(model, pdb_id, outfile=None, outdir=None, outext='_msms.df', force_rerun=False):\n\n # XTODO: need to deal with temporary surface/vertex files in tmp directory when running on a large scale --\n # XTODO: will run into inode limits! Also, some valuable information is in these MSMS output files that we should save.\n\n # Create the output file name\n outfile = ssbio.utils.outfile_maker(inname=pdb_id, outname=outfile, outdir=outdir, outext=outext)\n\n if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):\n # Run MSMS with Biopython\n try:\n rd = PDB.ResidueDepth(model)\n except AssertionError:\n log.error('{}: unable to run MSMS'.format(pdb_id))\n return pd.DataFrame()\n\n # Reorganize the results into a csv file\n appender = []\n for k in rd.property_keys:\n x = rd.property_dict[k]\n chain = k[0]\n residue = k[1]\n het = residue[0]\n resnum = residue[1]\n icode = residue[2]\n resdepth = x[0]\n cadepth = x[1]\n appender.append((chain, resnum, icode, resdepth, cadepth))\n\n df = pd.DataFrame.from_records(appender, columns=['chain', 'resnum', 'icode', 'res_depth', 'ca_depth'])\n df.to_csv(outfile)\n else:\n log.debug('{}: already ran MSMS and force_rerun={}, loading results'.format(outfile, force_rerun))\n df = pd.read_csv(outfile, index_col=0)\n\n return df", "docstring": "Run MSMS (using Biopython) on a Biopython Structure Model.\n\n Depths are in units Angstroms. 1A = 10^-10 m = 1nm. Returns a dictionary of::\n\n {\n chain_id:{\n resnum1_id: (res_depth, ca_depth),\n resnum2_id: (res_depth, ca_depth)\n }\n }\n\nArgs:\n model: Biopython Structure Model\n\nReturns:\n Pandas DataFrame: ResidueDepth property_dict, reformatted", "source": "juraj_google_style"} +{"code": "def heightmap_get_interpolated_value(\n hm: np.ndarray, x: float, y: float\n) -> float:\n\n return float(\n lib.TCOD_heightmap_get_interpolated_value(_heightmap_cdata(hm), x, y)\n )", "docstring": "Return the interpolated height at non integer coordinates.\n\nArgs:\n hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.\n x (float): A floating point x coordinate.\n y (float): A floating point y coordinate.\n\nReturns:\n float: The value at ``x``, ``y``.", "source": "juraj_google_style"} +{"code": "def probability_density(self, X):\n\n self.check_fit()\n return norm.pdf(X, loc=self.mean, scale=self.std)", "docstring": "Compute probability density.\n\nArgs:\n X: `np.ndarray` of shape (n, 1).\n\nReturns:\n np.ndarray", "source": "juraj_google_style"} +{"code": "def time_estimate(self, duration, **kwargs):\n\n path = '%s/%s/time_estimate' % (self.manager.path, self.get_id())\n data = {'duration': duration}\n return self.manager.gitlab.http_post(path, post_data=data, **kwargs)", "docstring": "Set an estimated time of work for the object.\n\nArgs:\n duration (str): Duration in human format (e.g. 3h30)\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabTimeTrackingError: If the time tracking update cannot be done", "source": "juraj_google_style"} +{"code": "def _find_rr_record(self, rr_path):\n # type: (bytes) -> dr.DirectoryRecord\n\n if not utils.starts_with_slash(rr_path):\n raise pycdlibexception.PyCdlibInvalidInput('Must be a path starting with /')\n\n root_dir_record = self.pvd.root_directory_record()\n\n # If the path is just the slash, we just want the root directory, so\n # get the child there and quit.\n if rr_path == b'/':\n return root_dir_record\n\n # Split the path along the slashes\n splitpath = utils.split_path(rr_path)\n\n currpath = splitpath.pop(0).decode('utf-8').encode('utf-8')\n\n entry = root_dir_record\n\n while True:\n child = None\n\n thelist = entry.rr_children\n lo = 0\n hi = len(thelist)\n while lo < hi:\n mid = (lo + hi) // 2\n\n tmpchild = thelist[mid]\n\n if tmpchild.rock_ridge is None:\n raise pycdlibexception.PyCdlibInvalidInput('Record without Rock Ridge entry on Rock Ridge ISO')\n\n if tmpchild.rock_ridge.name() < currpath:\n lo = mid + 1\n else:\n hi = mid\n index = lo\n tmpchild = thelist[index]\n if index != len(thelist) and tmpchild.rock_ridge is not None and tmpchild.rock_ridge.name() == currpath:\n child = thelist[index]\n\n if child is None:\n # We failed to find this component of the path, so break out of the\n # loop and fail\n break\n\n if child.rock_ridge is not None and child.rock_ridge.child_link_record_exists():\n # Here, the rock ridge extension has a child link, so we\n # need to follow it.\n child = child.rock_ridge.cl_to_moved_dr\n if child is None:\n break\n\n # We found the child, and it is the last one we are looking for;\n # return it.\n if not splitpath:\n return child\n\n if not child.is_dir():\n break\n entry = child\n currpath = splitpath.pop(0).decode('utf-8').encode('utf-8')\n\n raise pycdlibexception.PyCdlibInvalidInput('Could not find path')", "docstring": "An internal method to find an directory record on the ISO given a Rock\n Ridge path. If the entry is found, it returns the directory record\n object corresponding to that entry. If the entry could not be found, a\n pycdlibexception.PyCdlibInvalidInput is raised.\n\n Parameters:\n rr_path - The Rock Ridge path to lookup.\n\nReturns:\n The directory record entry representing the entry on the ISO.", "source": "juraj_google_style"} +{"code": "def NewRow(self, value=\"\"):\n\n newrow = self.row_class()\n newrow.row = self.size + 1\n newrow.table = self\n headers = self._Header()\n for header in headers:\n newrow[header] = value\n return newrow", "docstring": "Fetches a new, empty row, with headers populated.\n\nArgs:\n value: Initial value to set each row entry to.\n\nReturns:\n A Row() object.", "source": "juraj_google_style"} +{"code": "def fetch_all_first_values(session: Session,\n select_statement: Select) -> List[Any]:\n\n rows = session.execute(select_statement) # type: ResultProxy\n try:\n return [row[0] for row in rows]\n except ValueError as e:\n raise MultipleResultsFound(str(e))", "docstring": "Returns a list of the first values in each row returned by a ``SELECT``\n query.\n\n A Core version of this sort of thing:\n http://xion.io/post/code/sqlalchemy-query-values.html\n\nArgs:\n session: SQLAlchemy :class:`Session` object\n select_statement: SQLAlchemy :class:`Select` object\n\nReturns:\n a list of the first value of each result row", "source": "juraj_google_style"} +{"code": "def ParseRow(self, parser_mediator, query, row, **unused_kwargs):\n\n query_hash = hash(query)\n\n event_data = AndroidWebViewCacheEventData()\n event_data.content_length = self._GetRowValue(\n query_hash, row, 'contentlength')\n event_data.query = query\n event_data.url = self._GetRowValue(query_hash, row, 'url')\n\n timestamp = self._GetRowValue(query_hash, row, 'expires')\n if timestamp is not None:\n date_time = dfdatetime_java_time.JavaTime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_EXPIRATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = self._GetRowValue(query_hash, row, 'lastmodify')\n if timestamp is not None:\n date_time = dfdatetime_java_time.JavaTime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_MODIFICATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a row from the database.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n query (str): query that created the row.\n row (sqlite3.Row): row.", "source": "juraj_google_style"} +{"code": "def retry_loop(self, context, step_method):\n\n logger.debug(\"starting\")\n\n context['retryCounter'] = 0\n\n sleep = context.get_formatted_as_type(self.sleep, out_type=float)\n if self.max:\n max = context.get_formatted_as_type(self.max, out_type=int)\n\n logger.info(f\"retry decorator will try {max} times at {sleep}s \"\n \"intervals.\")\n else:\n max = None\n logger.info(f\"retry decorator will try indefinitely at {sleep}s \"\n \"intervals.\")\n\n # this will never be false. because on counter == max,\n # exec_iteration raises an exception, breaking out of the loop.\n # pragma because cov doesn't know the implied else is impossible.\n # unit test cov is 100%, though.\n if poll.while_until_true(interval=sleep,\n max_attempts=max)(\n self.exec_iteration)(context=context,\n step_method=step_method\n ): # pragma: no cover\n logger.debug(\"retry loop complete, reporting success.\")\n\n logger.debug(\"retry loop done\")\n\n logger.debug(\"done\")", "docstring": "Run step inside a retry loop.\n\nArgs:\n context: (pypyr.context.Context) The pypyr context. This arg will\n mutate - after method execution will contain the new\n updated context.\n step_method: (method/function) This is the method/function that\n will execute on every loop iteration. Signature is:\n function(context)", "source": "juraj_google_style"} +{"code": "def __init__(self, email, password):\n\n self.email = email\n self.password = password\n self.token = None\n self.refresh_token = None\n self.last_api_call = None\n self.state = []\n # get a token\n self.authenticated = self._authenticate()", "docstring": "Create the EcoNet API interface object.\n\nArgs:\n email (str): EcoNet account email address.\n password (str): EcoNet account password.", "source": "juraj_google_style"} +{"code": "def _logsum_expbig_minus_expsmall(big, small):\n\n with tf.name_scope(\"logsum_expbig_minus_expsmall\"):\n return tf.math.log1p(-tf.exp(small - big)) + big", "docstring": "Stable evaluation of `Log[exp{big} - exp{small}]`.\n\n To work correctly, we should have the pointwise relation: `small <= big`.\n\nArgs:\n big: Floating-point `Tensor`\n small: Floating-point `Tensor` with same `dtype` as `big` and broadcastable\n shape.\n\nReturns:\n `Tensor` of same `dtype` of `big` and broadcast shape.", "source": "juraj_google_style"} +{"code": "def __getitem__(self, thing: Any) -> np.ndarray:\n\n\t\tif type(thing) is slice or type(thing) is np.ndarray or type(thing) is int:\n\t\t\tam = AttributeManager(None, axis=self.axis)\n\t\t\tfor key, val in self.items():\n\t\t\t\tam[key] = val[thing]\n\t\t\treturn am\n\t\telif type(thing) is tuple:\n\t\t\t# A tuple of strings giving alternative names for attributes\n\t\t\tresult: np.ndarray = None\n\t\t\tfor t in thing:\n\t\t\t\tif t in self.__dict__[\"storage\"]:\n\t\t\t\t\tif result is None:\n\t\t\t\t\t\tresult = self.__getattr__(t)\n\t\t\t\t\telse:\n\t\t\t\t\t\tvals = self.__getattr__(t)\n\t\t\t\t\t\tif vals.dtype != result.dtype:\n\t\t\t\t\t\t\traise AttributeError(f\"Cannot stack attributes of different types ({vals.dtype} and {result.dtype})\")\n\t\t\t\t\t\tresult = np.vstack((result, vals)).transpose()\n\t\t\tif result is None:\n\t\t\t\traise AttributeError(f\"'{type(self)}' object has no attribute {thing}\")\n\t\t\telse:\n\t\t\t\treturn result\n\t\telse:\n\t\t\treturn self.__getattr__(thing)", "docstring": "Return a named attribute, or a slice through all the attributes\n\nArgs:\n thing:\t\tif string, return the named attribute\n if slice, np.ndarray or int, return a slice through all the attributes", "source": "juraj_google_style"} +{"code": "def parse_genes(gene_lines):\n\n genes = []\n header = []\n hgnc_identifiers = set()\n delimiter = '\\t'\n # This can be '\\t' or ';'\n delimiters = ['\\t', ' ', ';']\n\n # There are files that have '#' to indicate headers\n # There are some files that start with a header line without\n # any special symbol\n for i,line in enumerate(gene_lines):\n line = line.rstrip()\n if not len(line) > 0:\n continue\n if line.startswith('#'):\n if not line.startswith('##'):\n # We need to try delimiters\n # We prefer ';' or '\\t' byt should accept ' '\n line_length = 0\n delimiter = None\n for alt in delimiters:\n head_line = line.split(alt)\n if len(head_line) > line_length:\n line_length = len(head_line)\n delimiter = alt\n\n header = [word.lower() for word in line[1:].split(delimiter)]\n else:\n # If no header symbol(#) assume first line is header\n if i == 0:\n line_length = 0\n for alt in delimiters:\n head_line = line.split(alt)\n if len(head_line) > line_length:\n line_length = len(head_line)\n delimiter = alt\n\n if ('hgnc' in line or 'HGNC' in line):\n header = [word.lower() for word in line.split(delimiter)]\n continue\n # If first line is not a header try to sniff what the first\n # columns holds\n if line.split(delimiter)[0].isdigit():\n header = ['hgnc_id']\n else:\n header = ['hgnc_symbol']\n\n splitted_line = line.split(delimiter)\n gene_info = dict(zip(header, splitted_line))\n\n # There are cases when excel exports empty lines that looks like\n # ;;;;;;;. This is a exception to handle these\n info_found = False\n for key in gene_info:\n if gene_info[key]:\n info_found = True\n break\n # If no info was found we skip that line\n if not info_found:\n continue\n\n try:\n gene = parse_gene(gene_info)\n except Exception as e:\n LOG.warning(e)\n raise SyntaxError(\"Line {0} is malformed\".format(i + 1))\n\n identifier = gene.pop('identifier')\n\n if not identifier in hgnc_identifiers:\n hgnc_identifiers.add(identifier)\n genes.append(gene)\n\n return genes", "docstring": "Parse a file with genes and return the hgnc ids\n\nArgs:\n gene_lines(iterable(str)): Stream with genes\n\nReturns:\n genes(list(dict)): Dictionaries with relevant gene info", "source": "juraj_google_style"} +{"code": "def last(symbols=None, token='', version=''):\n\n symbols = _strToList(symbols)\n if symbols:\n return _getJson('tops/last?symbols=' + ','.join(symbols) + '%2b', token, version)\n return _getJson('tops/last', token, version)", "docstring": "Last provides trade data for executions on IEX. It is a near real time, intraday API that provides IEX last sale price, size and time.\n Last is ideal for developers that need a lightweight stock quote.\n\n https://iexcloud.io/docs/api/#last\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n dict: result", "source": "juraj_google_style"} +{"code": "def __init__(self, use_zeromq=True):\n\n super(PsortMultiProcessEngine, self).__init__()\n self._analysis_plugins = {}\n self._completed_analysis_processes = set()\n self._data_location = None\n self._event_filter_expression = None\n self._event_queues = {}\n self._event_tag_index = event_tag_index.EventTagIndex()\n self._events_status = processing_status.EventsStatus()\n # The export event heap is used to make sure the events are sorted in\n # a deterministic way.\n self._export_event_heap = PsortEventHeap()\n self._export_event_timestamp = 0\n self._guppy_memory_profiler = None\n self._knowledge_base = None\n self._memory_profiler = None\n self._merge_task = None\n self._number_of_consumed_event_tags = 0\n self._number_of_consumed_events = 0\n self._number_of_consumed_reports = 0\n self._number_of_consumed_sources = 0\n self._number_of_consumed_warnings = 0\n self._number_of_produced_event_tags = 0\n self._number_of_produced_events = 0\n self._number_of_produced_reports = 0\n self._number_of_produced_sources = 0\n self._number_of_produced_warnings = 0\n self._processing_configuration = None\n self._processing_profiler = None\n self._serializers_profiler = None\n self._status = definitions.STATUS_INDICATOR_IDLE\n self._status_update_callback = None\n self._use_zeromq = use_zeromq\n self._worker_memory_limit = definitions.DEFAULT_WORKER_MEMORY_LIMIT", "docstring": "Initializes an engine object.\n\nArgs:\n use_zeromq (Optional[bool]): True if ZeroMQ should be used for queuing\n instead of Python's multiprocessing queue.", "source": "juraj_google_style"} +{"code": "def raw(self, query):\n\n clone = copy.deepcopy(self)\n clone.adapter._pre_compiled_query = query\n clone.adapter.compiled_query = query\n return clone", "docstring": "make a raw query\n\nArgs:\n query (str): solr query\n \\*\\*params: solr parameters", "source": "juraj_google_style"} +{"code": "def update_shared_file(self,\n sharekey=None,\n title=None,\n description=None):\n\n if not sharekey:\n raise Exception(\n \"You must specify a sharekey for the sharedfile\"\n \"you wish to update.\")\n\n if not (title or description):\n raise Exception(\"You must specify a title or description.\")\n\n post_data = {}\n\n if title:\n post_data['title'] = title\n if description:\n post_data['description'] = description\n\n endpoint = '/api/sharedfile/{0}'.format(sharekey)\n\n data = self._make_request('POST', endpoint=endpoint, data=post_data)\n\n return SharedFile.NewFromJSON(data)", "docstring": "Update the editable details (just the title and description) of a\n SharedFile.\n\nArgs:\n sharekey (str): Sharekey of the SharedFile to update.\n title (Optional[str]): Title of the SharedFile.\n description (Optional[str]): Description of the SharedFile\n\nReturns:\n SharedFile on success, 404 on Sharekey not found, 403 on\n unauthorized.", "source": "juraj_google_style"} +{"code": "def nr_profiles(arr, genomes):\n\n gs_collapse = []\n genome_idx_dict = {}\n indices = []\n patt_dict = {}\n for i, g in enumerate(genomes):\n p = arr[i, :].tostring()\n if p in patt_dict:\n parent = patt_dict[p]\n idx = genome_idx_dict[parent]\n gs_collapse[idx].append(g)\n else:\n indices.append(i)\n patt_dict[p] = g\n genome_idx_dict[g] = len(gs_collapse)\n gs_collapse.append([g])\n return arr[indices, :], gs_collapse", "docstring": "Get a condensed cgMLST pairwise distance matrix for specified Genomes_\n where condensed means redundant cgMLST profiles are only represented once in the distance matrix.\n\nArgs:\n user_name (list): List of Genome_ names to retrieve condensed distance matrix for\n\nReturns:\n (numpy.array, list): tuple of condensed cgMLST distance matrix and list of grouped Genomes_", "source": "juraj_google_style"} +{"code": "def iter_replace_strings(replacements):\n\n def function_iter_replace_strings(iterable_strings):\n\n for string in iterable_strings:\n yield reduce((lambda s, kv: s.replace(*kv)),\n replacements.items(),\n string)\n\n return function_iter_replace_strings", "docstring": "Create a function that uses replacement pairs to process a string.\n\n The returned function takes an iterator and yields on each processed\n line.\n\nArgs:\n replacements: Dict containing 'find_string': 'replace_string' pairs\n\nReturns:\n function with signature: iterator of strings = function(iterable)", "source": "juraj_google_style"} +{"code": "def get_model(self, opt_fn, emb_sz, n_hid, n_layers, **kwargs):\n\n m = get_language_model(self.nt, emb_sz, n_hid, n_layers, self.pad_idx, **kwargs)\n model = SingleModel(to_gpu(m))\n return RNN_Learner(self, model, opt_fn=opt_fn)", "docstring": "Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module.\n\nArgs:\n opt_fn (Optimizer): the torch optimizer function to use\n emb_sz (int): embedding size\n n_hid (int): number of hidden inputs\n n_layers (int): number of hidden layers\n kwargs: other arguments\n\nReturns:\n An instance of the RNN_Learner class.", "source": "juraj_google_style"} +{"code": "def _CreateImage(media_service, opener, url):\n\n # Note: The utf-8 decode is for 2to3 Python 3 compatibility.\n image_data = opener.open(url).read().decode('utf-8')\n image = {\n 'type': 'IMAGE',\n 'data': image_data,\n 'xsi_type': 'Image'\n }\n\n return media_service.upload(image)[0]", "docstring": "Creates an image and uploads it to the server.\n\nArgs:\n media_service: a SudsServiceProxy instance for AdWords's MediaService.\n opener: an OpenerDirector instance.\n url: a str URL used to load image data.\n\nReturns:\n The image that was successfully uploaded.", "source": "juraj_google_style"} +{"code": "def _add_task(cls,\n worker_task,\n mapreduce_spec,\n queue_name):\n\n if not _run_task_hook(mapreduce_spec.get_hooks(),\n \"enqueue_worker_task\",\n worker_task,\n queue_name):\n try:\n # Not adding transactionally because worker_task has name.\n # Named task is not allowed for transactional add.\n worker_task.add(queue_name)\n except (taskqueue.TombstonedTaskError,\n taskqueue.TaskAlreadyExistsError), e:\n logging.warning(\"Task %r already exists. %s: %s\",\n worker_task.name,\n e.__class__,\n e)", "docstring": "Schedule slice scanning by adding it to the task queue.\n\nArgs:\n worker_task: a model.HugeTask task for slice. This is NOT a taskqueue\n task.\n mapreduce_spec: an instance of model.MapreduceSpec.\n queue_name: Optional queue to run on; uses the current queue of\n execution or the default queue if unspecified.", "source": "juraj_google_style"} +{"code": "def read(cls, five9, external_id):\n\n results = cls.search(five9, {cls.__uid_field__: external_id})\n if not results:\n return None\n return results[0]", "docstring": "Return a record singleton for the ID.\n\nArgs:\n five9 (five9.Five9): The authenticated Five9 remote.\n external_id (mixed): The identified on Five9. This should be the\n value that is in the ``__uid_field__`` field on the record.\n\nReturns:\n BaseModel: The record, if found. Otherwise ``None``", "source": "juraj_google_style"} +{"code": "def __init__(self, app):\n\n\n self.app = app\n\n # Use the applications's SECRET_KEY if flask_secret_key is not specified.\n flask_secret_key = app.config.get('SECRET_KEY', None)\n if not flask_secret_key:\n raise ConfigError('Config setting SECRET_KEY is missing.')\n\n # Print a warning if SECRET_KEY is too short\n key = flask_secret_key.encode()\n if len(key)<32:\n print('WARNING: Flask-User TokenManager: SECRET_KEY is shorter than 32 bytes.')\n key = key + b' '*32 # Make sure the key is at least 32 bytes long\n\n key32 = key[:32]\n base64_key32 = base64.urlsafe_b64encode(key32)\n\n # Create a Fernet cypher to encrypt data -- basically AES128 in CBC mode,\n # Encrypt, timestamp, sign, and base64-encode\n from cryptography.fernet import Fernet\n self.fernet = Fernet(base64_key32)", "docstring": "Check config settings and initialize the Fernet encryption cypher.\n\n Fernet is basically AES128 in CBC mode, with a timestamp and a signature.\n\nArgs:\n app(Flask): The Flask application instance.", "source": "juraj_google_style"} +{"code": "def initialize_logger(debug):\n\n level = logging.DEBUG if debug else logging.INFO\n logger = logging.getLogger('cucco')\n logger.setLevel(level)\n formatter = logging.Formatter('%(asctime)s %(levelname).1s %(message)s')\n console_handler = logging.StreamHandler()\n console_handler.setLevel(level)\n console_handler.setFormatter(formatter)\n logger.addHandler(console_handler)\n\n return logger", "docstring": "Set up logger to be used by the library.\n\nArgs:\n debug: Wheter to use debug level or not.\n\nReturns:\n A logger ready to be used.", "source": "juraj_google_style"} +{"code": "def unarchive_user(self, user_id):\n\n url = self.record_url + \"/unarchive\"\n res = requests.patch(url=url, json={\"user_id\": user_id}, headers=HEADERS, verify=False)\n self.write_response_html_to_file(res,\"bob.html\")\n res.raise_for_status()", "docstring": "Unarchives the user with the specified user ID.\n\nArgs:\n user_id: `int`. The ID of the user to unarchive.\n\nReturns:\n `NoneType`: None.", "source": "juraj_google_style"} +{"code": "def _ProcessCompressedStreamTypes(self, mediator, path_spec, type_indicators):\n\n number_of_type_indicators = len(type_indicators)\n if number_of_type_indicators == 0:\n return\n\n self.processing_status = definitions.STATUS_INDICATOR_COLLECTING\n\n if number_of_type_indicators > 1:\n display_name = mediator.GetDisplayName()\n logger.debug((\n 'Found multiple format type indicators: {0:s} for '\n 'compressed stream file: {1:s}').format(\n type_indicators, display_name))\n\n for type_indicator in type_indicators:\n if type_indicator == dfvfs_definitions.TYPE_INDICATOR_BZIP2:\n compressed_stream_path_spec = path_spec_factory.Factory.NewPathSpec(\n dfvfs_definitions.TYPE_INDICATOR_COMPRESSED_STREAM,\n compression_method=dfvfs_definitions.COMPRESSION_METHOD_BZIP2,\n parent=path_spec)\n\n elif type_indicator == dfvfs_definitions.TYPE_INDICATOR_GZIP:\n compressed_stream_path_spec = path_spec_factory.Factory.NewPathSpec(\n dfvfs_definitions.TYPE_INDICATOR_GZIP, parent=path_spec)\n\n else:\n compressed_stream_path_spec = None\n\n warning_message = (\n 'unsupported compressed stream format type indicators: '\n '{0:s}').format(type_indicator)\n mediator.ProduceExtractionWarning(\n warning_message, path_spec=path_spec)\n\n if compressed_stream_path_spec:\n event_source = event_sources.FileEntryEventSource(\n path_spec=compressed_stream_path_spec)\n event_source.file_entry_type = dfvfs_definitions.FILE_ENTRY_TYPE_FILE\n mediator.ProduceEventSource(event_source)\n\n self.last_activity_timestamp = time.time()", "docstring": "Processes a data stream containing compressed stream types such as: bz2.\n\nArgs:\n mediator (ParserMediator): mediates the interactions between\n parsers and other components, such as storage and abort signals.\n path_spec (dfvfs.PathSpec): path specification.\n type_indicators(list[str]): dfVFS archive type indicators found in\n the data stream.", "source": "juraj_google_style"} +{"code": "def print_start_command(self, command):\n\n size = len(command)\n if size > 20:\n raise RuntimeError('Command too long')\n n1 = size/10\n n2 = size%10\n self.send('^PS'+chr(n1)+chr(n2)+command)", "docstring": "Set print command\n\nArgs:\n command: the type of command you desire.\n\nReturns:\n None\n\nRaises:\n RuntimeError: Command too long.", "source": "juraj_google_style"} +{"code": "def plot_average(sdat, lovs):\n\n steps_iter = iter(sdat.walk.filter(rprof=True))\n try:\n step = next(steps_iter)\n except StopIteration:\n return\n\n sovs = misc.set_of_vars(lovs)\n\n istart = step.istep\n nprofs = 1\n rprof_averaged = {}\n rads = {}\n metas = {}\n\n # assume constant z spacing for the moment\n for rvar in sovs:\n rprof_averaged[rvar], rad, metas[rvar] = get_rprof(step, rvar)\n if rad is not None:\n rads[rvar] = rad\n\n for step in steps_iter:\n nprofs += 1\n for rvar in sovs:\n rprof_averaged[rvar] += get_rprof(step, rvar)[0]\n\n ilast = step.istep\n for rvar in sovs:\n rprof_averaged[rvar] /= nprofs\n rcmb, rsurf = misc.get_rbounds(step)\n rprof_averaged['bounds'] = (step.sdat.scale(rcmb, 'm')[0],\n step.sdat.scale(rsurf, 'm')[0])\n rprof_averaged['r'] = get_rprof(step, 'r')[0] + rprof_averaged['bounds'][0]\n\n stepstr = '{}_{}'.format(istart, ilast)\n\n _plot_rprof_list(sdat, lovs, rprof_averaged, metas, stepstr, rads)", "docstring": "Plot time averaged profiles.\n\nArgs:\n sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.\n lovs (nested list of str): nested list of profile names such as\n the one produced by :func:`stagpy.misc.list_of_vars`.\n\n Other Parameters:\n conf.core.snapshots: the slice of snapshots.\n conf.conf.timesteps: the slice of timesteps.", "source": "juraj_google_style"} +{"code": "def intern(self, text):\n\n if self.table_type.is_shared:\n raise TypeError('Cannot intern on shared symbol table')\n if not isinstance(text, six.text_type):\n raise TypeError('Cannot intern non-Unicode sequence into symbol table: %r' % text)\n\n token = self.get(text)\n if token is None:\n token = self.__add_text(text)\n return token", "docstring": "Interns the given Unicode sequence into the symbol table.\n\nNote:\n This operation is only valid on local symbol tables.\n\nArgs:\n text (unicode): The target to intern.\n\nReturns:\n SymbolToken: The mapped symbol token which may already exist in the table.", "source": "juraj_google_style"} +{"code": "def delete_knowledge_base(project_id, knowledge_base_id):\n\n import dialogflow_v2beta1 as dialogflow\n client = dialogflow.KnowledgeBasesClient()\n knowledge_base_path = client.knowledge_base_path(\n project_id, knowledge_base_id)\n\n response = client.delete_knowledge_base(knowledge_base_path)\n\n print('Knowledge Base deleted.'.format(response))", "docstring": "Deletes a specific Knowledge base.\n\nArgs:\n project_id: The GCP project linked with the agent.\n knowledge_base_id: Id of the Knowledge base.", "source": "juraj_google_style"} +{"code": "def overlay(self, dimensions=None, **kwargs):\n\n if dimensions is None:\n dimensions = self.kdims\n else:\n if not isinstance(dimensions, (list, tuple)):\n dimensions = [dimensions]\n dimensions = [self.get_dimension(d, strict=True)\n for d in dimensions]\n dims = [d for d in self.kdims if d not in dimensions]\n return self.groupby(dims, group_type=NdOverlay)", "docstring": "Group by supplied dimension(s) and overlay each group\n\n Groups data by supplied dimension(s) overlaying the groups\n along the dimension(s).\n\nArgs:\n dimensions: Dimension(s) of dimensions to group by\n\nReturns:\n NdOverlay object(s) with supplied dimensions", "source": "juraj_google_style"} +{"code": "def create_ingress_rule(self, app, rule):\n\n if isinstance(rule, dict):\n # Advanced\n start_port = rule.get('start_port')\n end_port = rule.get('end_port')\n protocol = rule.get('protocol', 'tcp')\n\n requested_cross_account = rule.get('env', self.env)\n if self.env == requested_cross_account:\n # We are trying to use cross-account security group settings within the same account\n # We should not allow this.\n cross_account_env = None\n cross_account_vpc_id = None\n else:\n cross_account_env = requested_cross_account\n cross_account_vpc_id = get_vpc_id(cross_account_env, self.region)\n\n else:\n start_port = rule\n end_port = rule\n protocol = 'tcp'\n cross_account_env = None\n cross_account_vpc_id = None\n\n created_rule = {\n 'app': app,\n 'start_port': start_port,\n 'end_port': end_port,\n 'protocol': protocol,\n 'cross_account_env': cross_account_env,\n 'cross_account_vpc_id': cross_account_vpc_id\n }\n self.log.debug('Normalized ingress rule: %s', created_rule)\n return created_rule", "docstring": "Create a normalized ingress rule.\n\nArgs:\n app (str): Application name\n rule (dict or int): Allowed Security Group ports and protocols.\n\nReturns:\n dict: Contains app, start_port, end_port, protocol, cross_account_env and cross_account_vpc_id", "source": "juraj_google_style"} +{"code": "def __init__(self,\n make_distribution_fn,\n convert_to_tensor_fn=tfd.Distribution.sample,\n **kwargs):\n\n # TODO(b/120440642): See if something like this code block is needed.\n # if output_shape is None:\n # def default_output_shape(keras_input_shape):\n # output_shape = map(\n # _expand_rank_at_least_one,\n # [sample_shape, keras_input_shape[:-1], event_shape])\n # return tf.concat(output_shape, axis=0)\n # output_shape = default_output_shape\n\n if isinstance(make_distribution_fn, six.string_types):\n # We are being called from `from_config`, so need to un-pickle.\n make_distribution_fn = _deserialize_function(make_distribution_fn)\n\n convert_to_tensor_fn = _get_convert_to_tensor_fn(convert_to_tensor_fn)\n\n # If there is a 'function' keyword argument (e.g., because we are being\n # called from a `from_config` method), remove it. We pass a function to\n # `Lambda.__init__` below as the first positional argument.\n kwargs.pop('function', None)\n\n def _fn(*fargs, **fkwargs):\n\n d = make_distribution_fn(*fargs, **fkwargs)\n value_is_seq = isinstance(d.dtype, collections.Sequence)\n maybe_composite_convert_to_tensor_fn = (\n (lambda d: tensor_tuple.TensorTuple(convert_to_tensor_fn(d)))\n if value_is_seq else convert_to_tensor_fn)\n distribution = dtc._TensorCoercible( # pylint: disable=protected-access\n distribution=d,\n convert_to_tensor_fn=maybe_composite_convert_to_tensor_fn)\n\n # Calling `distrbution._value()` is equivalent to:\n # from tensorflow.python.framework import ops\n # value = ops.convert_to_tensor_or_composite(value=distribution)\n # We'd prefer to call ops.convert_to_tensor_or_composite but do not,\n # favoring our own non-public API over TF's.\n value = distribution._value() # pylint: disable=protected-access\n\n # TODO(b/126056144): Remove silent handle once we identify how/why Keras\n # is losing the distribution handle for activity_regularizer.\n value._tfp_distribution = distribution # pylint: disable=protected-access\n # TODO(b/120153609): Keras is incorrectly presuming everything is a\n # `tf.Tensor`. Closing this bug entails ensuring Keras only accesses\n # `tf.Tensor` properties after calling `tf.convert_to_tensor`.\n if value_is_seq:\n value.shape = value[-1].shape\n value.get_shape = value[-1].get_shape\n value.dtype = value[-1].dtype\n distribution.shape = value[-1].shape\n distribution.get_shape = value[-1].get_shape\n else:\n distribution.shape = value.shape\n distribution.get_shape = value.get_shape\n return distribution, value\n\n super(DistributionLambda, self).__init__(_fn, **kwargs)\n\n self._make_distribution_fn = make_distribution_fn\n self._convert_to_tensor_fn = convert_to_tensor_fn\n\n # We'll need to keep track of who's calling who since the functional\n # API has a different way of injecting `_keras_history` than the\n # `keras.Sequential` way.\n self._enter_dunder_call = False", "docstring": "Create a `DistributionLambda` Keras layer.\n\nArgs:\n make_distribution_fn: Python `callable` that takes previous layer outputs\n and returns a `tfd.Distribution` instance.\n convert_to_tensor_fn: Python `callable` that takes a `tfd.Distribution`\n instance and returns a `tf.Tensor`-like object. For examples, see\n `class` docstring.\n Default value: `tfd.Distribution.sample`.\n **kwargs: Additional keyword arguments passed to `tf.keras.Layer`.", "source": "juraj_google_style"} +{"code": "def _Open(self, path_spec, mode='rb'):\n\n if not path_spec.HasParent():\n raise errors.PathSpecError(\n 'Unsupported path specification without parent.')\n\n encoding_method = getattr(path_spec, 'encoding_method', None)\n if not encoding_method:\n raise errors.PathSpecError(\n 'Unsupported path specification without encoding method.')\n\n self._encoding_method = encoding_method", "docstring": "Opens the file system defined by path specification.\n\nArgs:\n path_spec (PathSpec): a path specification.\n mode (Optional[str]): file access mode. The default is 'rb' which\n represents read-only binary.\n\nRaises:\n AccessError: if the access to open the file was denied.\n IOError: if the file system could not be opened.\n PathSpecError: if the path specification is incorrect.\n ValueError: if the path specification is invalid.", "source": "juraj_google_style"} +{"code": "def fulfill_order(self, order_number, site_code=None, email_opt_in=False):\n\n max_fulfillment_retries = get_configuration('MAX_FULFILLMENT_RETRIES', site_code=site_code)\n api = get_ecommerce_client(site_code=site_code)\n try:\n logger.info('Requesting fulfillment of order [%s].', order_number)\n api.orders(order_number).fulfill.put(email_opt_in=email_opt_in)\n except exceptions.HttpClientError as exc:\n status_code = exc.response.status_code # pylint: disable=no-member\n if status_code == 406:\n # The order is not fulfillable. Therefore, it must be complete.\n logger.info('Order [%s] has already been fulfilled. Ignoring.', order_number)\n raise Ignore()\n else:\n # Unknown client error. Let's retry to resolve it.\n logger.warning(\n 'Fulfillment of order [%s] failed because of HttpClientError. Retrying',\n order_number,\n exc_info=True\n )\n _retry_order(self, exc, max_fulfillment_retries, order_number)\n\n except (exceptions.HttpServerError, exceptions.Timeout, SSLError) as exc:\n # Fulfillment failed, retry\n _retry_order(self, exc, max_fulfillment_retries, order_number)", "docstring": "Fulfills an order.\n\nArgs:\n order_number (str): Order number indicating which order to fulfill.\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def find_module_defining_flag(self, flagname, default=None):\n\n registered_flag = self._flags().get(flagname)\n if registered_flag is None:\n return default\n for module, flags in six.iteritems(self.flags_by_module_dict()):\n for flag in flags:\n # It must compare the flag with the one in _flags. This is because a\n # flag might be overridden only for its long name (or short name),\n # and only its short name (or long name) is considered registered.\n if (flag.name == registered_flag.name and\n flag.short_name == registered_flag.short_name):\n return module\n return default", "docstring": "Return the name of the module defining this flag, or default.\n\nArgs:\n flagname: str, name of the flag to lookup.\n default: Value to return if flagname is not defined. Defaults\n to None.\n\nReturns:\n The name of the module which registered the flag with this name.\n If no such module exists (i.e. no flag with this name exists),\n we return default.", "source": "juraj_google_style"} +{"code": "def get_self_attention_bias(x):\n\n\n x_shape = common_layers.shape_list(x)\n self_attention_bias = common_attention.attention_bias_lower_triangle(\n x_shape[1])\n return self_attention_bias", "docstring": "Creates masked self attention bias.\n\nArgs:\n x: A tensor of shape [batch, length, depth]\n\nReturns:\n self_attention_bias: A tensor of shape [length, length, 1]", "source": "juraj_google_style"} +{"code": "def angles( self ):\n\n ( a, b, c ) = [ row for row in self.matrix ]\n return [ angle( b, c ), angle( a, c ), angle( a, b ) ]", "docstring": "The cell angles (in degrees).\n\nArgs:\n None\n\nReturns:\n (list(alpha,beta,gamma)): The cell angles.", "source": "juraj_google_style"} +{"code": "def _write_move_counts(self, sess, h):\n\n def gen():\n for k, v in h.items():\n # The keys in the histogram may be of type 'bytes'\n k = str(k, 'utf-8')\n vs = str(v)\n yield (k.replace('g_', 'ct_') + '_%d' % v, vs)\n yield (k + '_m_000', vs)\n mc = tf.data.Dataset.from_generator(gen, (tf.string, tf.string))\n wr_op = self.tf_table.write(mc,\n column_families=[METADATA],\n columns=[MOVE_COUNT])\n sess.run(wr_op)", "docstring": "Add move counts from the given histogram to the table.\n\n Used to update the move counts in an existing table. Should\n not be needed except for backfill or repair.\n\nArgs:\n sess: TF session to use for doing a Bigtable write.\n tf_table: TF Cloud Bigtable to use for writing.\n h: a dictionary keyed by game row prefix (\"g_0023561\") whose values\n are the move counts for each game.", "source": "juraj_google_style"} +{"code": "def camel_to_underscore(string):\n\n string = FIRST_CAP_RE.sub(r'\\1_\\2', string)\n return ALL_CAP_RE.sub(r'\\1_\\2', string).lower()", "docstring": "Convert camelcase to lowercase and underscore.\n\n Recipe from http://stackoverflow.com/a/1176023\n\nArgs:\n string (str): The string to convert.\n\nReturns:\n str: The converted string.", "source": "juraj_google_style"} +{"code": "def display_task_progress(\n self, instance, project, region, request_id=None, user=None,\n poll_interval=60):\n\n total_completed = 0\n\n while True:\n task_results = self.client.get_task_data(\n instance, project, region, request_id=request_id, user=user)\n tasks = {task['id']: task for task in task_results}\n completed_tasks = set()\n pending_tasks = set()\n\n for task in tasks.values():\n if task.get('successful') is not None:\n completed_tasks.add(task['id'])\n else:\n pending_tasks.add(task['id'])\n\n if len(completed_tasks) > total_completed or not completed_tasks:\n total_completed = len(completed_tasks)\n\n print('Task status update (completed: {0:d} | pending: {1:d})'.format(\n len(completed_tasks), len(pending_tasks)))\n\n print('Completed tasks:')\n for task_id in completed_tasks:\n self._print_task_data(tasks[task_id])\n\n print('Pending tasks:')\n for task_id in pending_tasks:\n self._print_task_data(tasks[task_id])\n\n if len(completed_tasks) == len(task_results) and completed_tasks:\n print('All {0:d} Tasks completed'.format(len(task_results)))\n return\n\n time.sleep(poll_interval)", "docstring": "Displays the overall progress of tasks in a Turbinia job.\n\nArgs:\n instance (string): The name of the Turbinia instance\n project (string): The project containing the disk to process\n region (string): Region where turbinia is configured.\n request_id (string): The request ID provided by Turbinia.\n user (string): The username to filter tasks by.\n poll_interval (int): The interval at which to poll for new results.", "source": "juraj_google_style"} +{"code": "def __init__(self, message_type=None, length=None, xid=None):\n\n super().__init__()\n self.message_type = message_type\n self.length = length\n self.xid = xid", "docstring": "Create a Header with the optional parameters below.\n\nArgs:\n message_type (~pyof.v0x04.common.header.Type):\n One of the OFPT_* constants.\n length (int): Length including this ofp_header.\n xid (int): Transaction id associated with this packet. Replies use\n the same id as was in the request to facilitate pairing.", "source": "juraj_google_style"} +{"code": "def count_matching(self, selector, offset=0):\n\n\n if selector.output:\n data = self.streaming_data\n elif selector.buffered:\n data = self.storage_data\n else:\n raise ArgumentError(\"You can only pass a buffered selector to count_matching\", selector=selector)\n\n count = 0\n for i in range(offset, len(data)):\n reading = data[i]\n\n stream = DataStream.FromEncoded(reading.stream)\n if selector.matches(stream):\n count += 1\n\n return count", "docstring": "Count the number of readings matching selector.\n\nArgs:\n selector (DataStreamSelector): The selector that we want to\n count matching readings for.\n offset (int): The starting offset that we should begin counting at.\n\nReturns:\n int: The number of matching readings.", "source": "juraj_google_style"} +{"code": "def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,\n containing_type=None, scope=None):\n\n\n if package:\n enum_name = '.'.join((package, enum_proto.name))\n else:\n enum_name = enum_proto.name\n\n if file_desc is None:\n file_name = None\n else:\n file_name = file_desc.name\n\n values = [self._MakeEnumValueDescriptor(value, index)\n for index, value in enumerate(enum_proto.value)]\n desc = descriptor.EnumDescriptor(name=enum_proto.name,\n full_name=enum_name,\n filename=file_name,\n file=file_desc,\n values=values,\n containing_type=containing_type,\n options=enum_proto.options)\n scope['.%s' % enum_name] = desc\n self._enum_descriptors[enum_name] = desc\n return desc", "docstring": "Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.\n\nArgs:\n enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.\n package: Optional package name for the new message EnumDescriptor.\n file_desc: The file containing the enum descriptor.\n containing_type: The type containing this enum.\n scope: Scope containing available types.\n\nReturns:\n The added descriptor", "source": "juraj_google_style"} +{"code": "def _generate_examples(self, filepath):\n\n # Simultaneously iterating through the different data sets in the hdf5\n # file is >100x slower and the data set is small (26.7MB). Hence, we first\n # load everything into memory before yielding the samples.\n image_array, class_array, values_array = _load_data(filepath)\n for image, classes, values in moves.zip(image_array, class_array,\n values_array):\n yield dict(\n image=np.expand_dims(image, -1),\n label_shape=classes[1],\n label_scale=classes[2],\n label_orientation=classes[3],\n label_x_position=classes[4],\n label_y_position=classes[5],\n value_shape=values[1],\n value_scale=values[2],\n value_orientation=values[3],\n value_x_position=values[4],\n value_y_position=values[5])", "docstring": "Generates examples for the dSprites data set.\n\nArgs:\n filepath: path to the dSprites hdf5 file.\n\nYields:\n Dictionaries with images, latent classes, and latent values.", "source": "juraj_google_style"} +{"code": "def add_boot_info_table(self, boot_info_table):\n # type: (eltorito.EltoritoBootInfoTable) -> None\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('Inode is not yet initialized')\n\n self.boot_info_table = boot_info_table", "docstring": "A method to add a boot info table to this Inode.\n\n Parameters:\n boot_info_table - The Boot Info Table object to add to this Inode.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def compile_intermediate_cpfs(self,\n scope: Dict[str, TensorFluent],\n batch_size: Optional[int] = None,\n noise: Optional[Noise] = None) -> List[CPFPair]:\n\n interm_fluents = []\n\n with self.graph.as_default():\n with tf.name_scope('intermediate_cpfs'):\n\n for cpf in self.rddl.domain.intermediate_cpfs:\n cpf_noise = noise.get(cpf.name, None) if noise is not None else None\n\n name_scope = utils.identifier(cpf.name)\n with tf.name_scope(name_scope):\n t = self._compile_expression(cpf.expr, scope, batch_size, cpf_noise)\n\n interm_fluents.append((cpf.name, t))\n scope[cpf.name] = t\n\n return interm_fluents", "docstring": "Compiles the intermediate fluent CPFs given the current `state` and `action` scope.\n\nArgs:\n scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation.\n batch_size (Optional[int]): The batch size.\n\nReturns:\n A list of intermediate fluent CPFs compiled to :obj:`rddl2tf.fluent.TensorFluent`.", "source": "juraj_google_style"} +{"code": "def marketYesterdayDF(token='', version=''):\n\n x = marketYesterday(token, version)\n data = []\n for key in x:\n data.append(x[key])\n data[-1]['symbol'] = key\n df = pd.DataFrame(data)\n _toDatetime(df)\n _reindex(df, 'symbol')\n return df", "docstring": "This returns previous day adjusted price data for whole market\n\n https://iexcloud.io/docs/api/#previous-day-prices\n Available after 4am ET Tue-Sat\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n DataFrame: result", "source": "juraj_google_style"} +{"code": "def _project_TH3(self, hist: Hist) -> Any:\n\n # Axis length validation\n if len(self.projection_axes) < 1 or len(self.projection_axes) > 2:\n raise ValueError(len(self.projection_axes), \"Invalid number of axes\")\n\n # Need to concatenate the names of the axes together\n projection_axis_name = \"\"\n for axis in self.projection_axes:\n # Determine the axis name based on the name of the axis type.\n # [:1] returns just the first letter. For example, we could get \"xy\" if the first axis as\n # x_axis and the second was y_axis.\n # NOTE: Careful. This depends on the name of the enumerated values!!! Since this isn't terribly\n # safe, we then perform additional validation on the same to ensure that it is one of the\n # expected axis names.\n proj_axis_name = axis.axis_type.name[:1]\n if proj_axis_name not in [\"x\", \"y\", \"z\"]:\n raise ValueError(f\"Projection axis name {proj_axis_name} is not 'x', 'y', or 'z'. Please check your configuration.\")\n projection_axis_name += proj_axis_name\n\n # Handle ROOT Project3D quirk...\n # 2D projection are called as (y, x, options), so we should reverse the order so it performs\n # as expected.\n # NOTE: This isn't well documented in TH3. It is instead described in THnBase.Projection(...)\n if len(self.projection_axes) == 2:\n # Reverse the axes\n projection_axis_name = projection_axis_name[::-1]\n\n # Do the actual projection\n logger.info(f\"Projecting onto axes \\\"{projection_axis_name}\\\" from hist {hist.GetName()}\")\n projected_hist = hist.Project3D(projection_axis_name)\n\n return projected_hist", "docstring": "Perform the actual TH3 -> TH1 projection.\n\n This projection could be to 1D or 2D.\n\nArgs:\n hist (ROOT.TH3): Histogram from which the projections should be performed.\n\nReturns:\n ROOT.TH1: The projected histogram.", "source": "juraj_google_style"} +{"code": "def AddEventTags(self, event_tags):\n\n self._RaiseIfNotWritable()\n\n for event_tag in event_tags:\n self.AddEventTag(event_tag)", "docstring": "Adds event tags.\n\nArgs:\n event_tags (list[EventTag]): event tags.\n\nRaises:\n IOError: when the storage file is closed or read-only or\n if the event tags cannot be serialized.\n OSError: when the storage file is closed or read-only or\n if the event tags cannot be serialized.", "source": "juraj_google_style"} +{"code": "def _finalize_outputs(cls, mapreduce_spec, mapreduce_state):\n\n # Only finalize the output writers if the job is successful.\n if (mapreduce_spec.mapper.output_writer_class() and\n mapreduce_state.result_status == model.MapreduceState.RESULT_SUCCESS):\n mapreduce_spec.mapper.output_writer_class().finalize_job(mapreduce_state)", "docstring": "Finalize outputs.\n\nArgs:\n mapreduce_spec: an instance of MapreduceSpec.\n mapreduce_state: an instance of MapreduceState.", "source": "juraj_google_style"} +{"code": "def _checkMode(mode):\n\n\n if not isinstance(mode, str):\n raise TypeError('The {0} should be a string. Given: {1!r}'.format(\"mode\", mode))\n\n if mode not in [MODE_RTU, MODE_ASCII]:\n raise ValueError(\"Unreconized Modbus mode given. Must be 'rtu' or 'ascii' but {0!r} was given.\".format(mode))", "docstring": "Check that the Modbus mode is valie.\n\nArgs:\n mode (string): The Modbus mode (MODE_RTU or MODE_ASCII)\n\nRaises:\n TypeError, ValueError", "source": "juraj_google_style"} +{"code": "def extract_archive(archive_path, dest):\n\n # Make the dest folder if it does not exist\n if not os.path.isdir(dest):\n os.makedirs(dest)\n\n try:\n tmpfolder = None\n\n if (not tf.gfile.Exists(archive_path)) or tf.gfile.IsDirectory(archive_path):\n raise ValueError('archive path %s is not a file' % archive_path)\n\n if archive_path.startswith('gs://'):\n # Copy the file to a local temp folder\n tmpfolder = tempfile.mkdtemp()\n cmd_args = ['gsutil', 'cp', archive_path, tmpfolder]\n _shell_process.run_and_monitor(cmd_args, os.getpid())\n archive_path = os.path.join(tmpfolder, os.path.name(archive_path))\n\n if archive_path.lower().endswith('.tar.gz'):\n flags = '-xzf'\n elif archive_path.lower().endswith('.tar'):\n flags = '-xf'\n else:\n raise ValueError('Only tar.gz or tar.Z files are supported.')\n\n cmd_args = ['tar', flags, archive_path, '-C', dest]\n _shell_process.run_and_monitor(cmd_args, os.getpid())\n finally:\n if tmpfolder:\n shutil.rmtree(tmpfolder)", "docstring": "Extract a local or GCS archive file to a folder.\n\nArgs:\n archive_path: local or gcs path to a *.tar.gz or *.tar file\n dest: local folder the archive will be extracted to", "source": "juraj_google_style"} +{"code": "def register(self, username=\"\"):\n\n if not username:\n username = utils.mxid2localpart(self.identity)\n content = {\n \"type\": \"m.login.application_service\",\n \"username\": username,\n }\n return self._send(\"POST\", \"/register\", content,\n api_path=MATRIX_V2_API_PATH)", "docstring": "Performs /register with type: m.login.application_service\n\nArgs:\n username(str): Username to register.", "source": "juraj_google_style"} +{"code": "def provide(self, cls):\n\n support.verify_class_type(cls, 'cls')\n if not self._is_injectable_fn(cls):\n provide_loc = locations.get_back_frame_loc()\n raise errors.NonExplicitlyBoundClassError(provide_loc, cls)\n try:\n return self._obj_provider.provide_class(\n cls, self._injection_context_factory.new(cls.__init__),\n direct_init_pargs=[], direct_init_kwargs={})\n except errors.Error as e:\n if self._use_short_stack_traces:\n raise e\n else:\n raise", "docstring": "Provides an instance of the given class.\n\nArgs:\n cls: a class (not an instance)\n\nReturns:\n an instance of cls\n\nRaises:\n Error: an instance of cls is not providable", "source": "juraj_google_style"} +{"code": "def ints_to_rgb(r, g=None, b=None):\n\n if type(r) in [list,tuple]:\n r, g, b = r\n return tuple(float(v) / 255.0 for v in [r, g, b])", "docstring": "Convert ints in the [0...255] range to the standard [0...1] range.\n\n Parameters:\n :r:\n The Red component value [0...255]\n :g:\n The Green component value [0...255]\n :b:\n The Blue component value [0...255]\n\nReturns:\n The color as an (r, g, b) tuple in the range:\n r[0...1],\n g[0...1],\n b[0...1]\n\n >>> '(%g, %g, %g)' % ints_to_rgb((255, 128, 0))\n '(1, 0.501961, 0)'", "source": "juraj_google_style"} +{"code": "def scalar_input_map(func, input_):\n\n if util_iter.isiterable(input_):\n return list(map(func, input_))\n else:\n return func(input_)", "docstring": "Map like function\n\nArgs:\n func: function to apply\n input_ : either an iterable or scalar value\n\nReturns:\n If ``input_`` is iterable this function behaves like map\n otherwise applies func to ``input_``", "source": "juraj_google_style"} +{"code": "def get_by(self, field, value, uri=None):\n\n if not field:\n logger.exception(RESOURCE_CLIENT_INVALID_FIELD)\n raise ValueError(RESOURCE_CLIENT_INVALID_FIELD)\n\n if not uri:\n uri = self._uri\n self.__validate_resource_uri(uri)\n\n logger.debug('Get by (uri = %s, field = %s, value = %s)' %\n (uri, field, str(value)))\n\n filter = \"\\\"{0}='{1}'\\\"\".format(field, value)\n results = self.get_all(filter=filter, uri=uri)\n\n # Workaround when the OneView filter does not work, it will filter again\n if \".\" not in field:\n # This filter only work for the first level\n results = [item for item in results if str(item.get(field, '')).lower() == value.lower()]\n\n return results", "docstring": "This function uses get_all passing a filter.\n\n The search is case-insensitive.\n\nArgs:\n field: Field name to filter.\n value: Value to filter.\n uri: Resource uri.\n\nReturns:\n dict", "source": "juraj_google_style"} +{"code": "def populate_ast_nsarg_orthologs(ast, species):\n\n\n ortholog_namespace = \"EG\"\n\n if isinstance(ast, NSArg):\n if re.match(ortholog_namespace, ast.canonical):\n orthologs = bel.terms.orthologs.get_orthologs(\n ast.canonical, list(species.keys())\n )\n for species_id in species:\n if species_id in orthologs:\n orthologs[species_id][\"species_label\"] = species[species_id]\n\n ast.orthologs = copy.deepcopy(orthologs)\n\n # Recursively process every NSArg by processing BELAst and Functions\n if hasattr(ast, \"args\"):\n for arg in ast.args:\n populate_ast_nsarg_orthologs(arg, species)\n\n return ast", "docstring": "Recursively collect NSArg orthologs for BEL AST\n\n This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available\n\nArgs:\n ast: AST at recursive point in belobj\n species: dictionary of species ids vs labels for or", "source": "juraj_google_style"} +{"code": "def __init__(self, dims, multiples, name=\"tile_by_dim\"):\n\n super(TileByDim, self).__init__(name=name)\n self._dims = dims\n self._multiples = multiples\n if np.unique(dims).size != len(dims):\n raise ValueError(\"dims must not have any repeated integers.\")\n if len(multiples) != len(dims):\n raise ValueError(\n \"multiples must have the same length as dims: {}.\".format(len(dims)))", "docstring": "Constructs the `TileByDim` module.\n\nArgs:\n dims: The dimensions to tile along, as a list of unique integers.\n multiples: The multiple of the tiling, as a list of integers. Must\n be the same length as the `dims` list.\n name: The name of the module.\n\nRaises:\n ValueError: If `dims` has non-unique integers, or if the size of\n `multiples` is different from the size of `dims`.", "source": "juraj_google_style"} +{"code": "def desaturate(self, level):\n\n h, s, l = self.__hsl\n return Color((h, max(s - level, 0), l), 'hsl', self.__a, self.__wref)", "docstring": "Create a new instance based on this one but less saturated.\n\n Parameters:\n :level:\n The amount by which the color should be desaturated to produce\n the new one [0...1].\n\nReturns:\n A grapefruit.Color instance.\n\n >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25)\n Color(0.625, 0.5, 0.375, 1.0)\n >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25).hsl\n (30.0, 0.25, 0.5)", "source": "juraj_google_style"} +{"code": "def log_histogram(self, name, value, step=None):\n\n if isinstance(value, six.string_types):\n raise TypeError('\"value\" should be a number, got {}'\n .format(type(value)))\n\n self._check_step(step)\n tf_name = self._ensure_tf_name(name)\n\n summary = self._histogram_summary(tf_name, value, step=step)\n self._log_summary(tf_name, summary, value, step=step)", "docstring": "Log a histogram for given name on given step.\n\nArgs:\n name (str): name of the variable (it will be converted to a valid\n tensorflow summary name).\n value (tuple or list): either list of numbers\n to be summarized as a histogram, or a tuple of bin_edges and\n bincounts that directly define a histogram.\n step (int): non-negative integer used for visualization", "source": "juraj_google_style"} +{"code": "def _all_correct_list(array):\n\n if type(array) not in _ITERABLE_TYPES:\n return False\n\n for item in array:\n if not type(item) in _ITERABLE_TYPES:\n return False\n\n if len(item) != 2:\n return False\n\n return True", "docstring": "Make sure, that all items in `array` has good type and size.\n\nArgs:\n array (list): Array of python types.\n\nReturns:\n True/False", "source": "juraj_google_style"} +{"code": "def _prefix_exists_in_gcs(gcs_prefix, credentials=None):\n\n gcs_service = _get_storage_service(credentials)\n\n bucket_name, prefix = gcs_prefix[len('gs://'):].split('/', 1)\n # documentation in\n # https://cloud.google.com/storage/docs/json_api/v1/objects/list\n request = gcs_service.objects().list(\n bucket=bucket_name, prefix=prefix, maxResults=1)\n response = request.execute()\n return response.get('items', None)", "docstring": "Check whether there is a GCS object whose name starts with the prefix.\n\n Since GCS doesn't actually have folders, this is how we check instead.\n\nArgs:\n gcs_prefix: The path; should start with 'gs://'.\n credentials: Optional credential to be used to load the file from gcs.\n\nReturns:\n True if the prefix matches at least one object in GCS.\n\nRaises:\n errors.HttpError: if it can't talk to the server", "source": "juraj_google_style"} +{"code": "def stop_dag(self, name=None):\n\n return self._client.send(\n Request(\n action='stop_dag',\n payload={'name': name if name is not None else self._dag_name}\n )\n ).success", "docstring": "Send a stop signal to the specified dag or the dag that hosts this task.\n\nArgs:\n name str: The name of the dag that should be stopped. If no name is given the\n dag that hosts this task is stopped.\n\n Upon receiving the stop signal, the dag will not queue any new tasks and wait\n for running tasks to terminate.\n\nReturns:\n bool: True if the signal was sent successfully.", "source": "juraj_google_style"} +{"code": "def CreateDataTypeMap(self, definition_name):\n\n data_type_definition = self._definitions_registry.GetDefinitionByName(\n definition_name)\n if not data_type_definition:\n return None\n\n return DataTypeMapFactory.CreateDataTypeMapByType(data_type_definition)", "docstring": "Creates a specific data type map by name.\n\nArgs:\n definition_name (str): name of the data type definition.\n\nReturns:\n DataTypeMap: data type map or None if the date type definition\n is not available.", "source": "juraj_google_style"} +{"code": "def typical_or_extreme_period_name(self, value=None):\n\n if value is not None:\n try:\n value = str(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type str '\n 'for field `typical_or_extreme_period_name`'.format(value))\n if ',' in value:\n raise ValueError('value should not contain a comma '\n 'for field `typical_or_extreme_period_name`')\n\n self._typical_or_extreme_period_name = value", "docstring": "Corresponds to IDD Field `typical_or_extreme_period_name`\n\nArgs:\n value (str): value for IDD Field `typical_or_extreme_period_name`\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def get(cls, option, default_value=None):\n\n config = cls.__get_instance()\n for name in option.split(':'):\n if not name:\n raise Exception('Incorrect value in path (maybe double `:` or empty path)')\n if name not in config:\n return default_value\n config = config[name]\n return deepcopy(config)", "docstring": "Return value of given option.\n\n If option isn't found - return default_value (None by default).\n\nArgs:\n - option: string with path to option with `:` separator", "source": "juraj_google_style"} +{"code": "def tracers(tracersfile):\n\n if not tracersfile.is_file():\n return None\n tra = {}\n with tracersfile.open('rb') as fid:\n readbin = partial(_readbin, fid)\n magic = readbin()\n if magic > 8000: # 64 bits\n magic -= 8000\n readbin()\n readbin = partial(readbin, file64=True)\n if magic < 100:\n raise ParsingError(tracersfile,\n 'magic > 100 expected to get tracervar info')\n nblk = magic % 100\n readbin('f', 2) # aspect ratio\n readbin() # istep\n readbin('f') # time\n ninfo = readbin()\n ntra = readbin(nwords=nblk, unpack=False)\n readbin('f') # tracer ideal mass\n curv = readbin()\n if curv:\n readbin('f') # r_cmb\n infos = [] # list of info names\n for _ in range(ninfo):\n infos.append(b''.join(readbin('b', 16)).strip().decode())\n tra[infos[-1]] = []\n if magic > 200:\n ntrace_elt = readbin()\n if ntrace_elt > 0:\n readbin('f', ntrace_elt) # outgassed\n for ntrab in ntra: # blocks\n data = readbin('f', ntrab * ninfo)\n for idx, info in enumerate(infos):\n tra[info].append(data[idx::ninfo])\n return tra", "docstring": "Extract tracers data.\n\nArgs:\n tracersfile (:class:`pathlib.Path`): path of the binary tracers file.\n\nReturns:\n dict of list of numpy.array:\n Tracers data organized by attribute and block.", "source": "juraj_google_style"} +{"code": "def delete(self, key):\n\n try:\n del self._collection(key)[key]\n\n if len(self._collection(key)) == 0:\n del self._items[str(key.path)]\n except KeyError, e:\n pass", "docstring": "Removes the object named by `key`.\n\n Removes the object from the collection corresponding to ``key.path``.\n\nArgs:\n key: Key naming the object to remove.", "source": "juraj_google_style"} +{"code": "def get_vep_info(vep_string, vep_header):\n\n\n vep_annotations = [\n dict(zip(vep_header, vep_annotation.split('|'))) \n for vep_annotation in vep_string.split(',')\n ]\n\n return vep_annotations", "docstring": "Make the vep annotations into a dictionaries\n\n A vep dictionary will have the vep column names as keys and\n the vep annotations as values.\n The dictionaries are stored in a list\n\nArgs:\n vep_string (string): A string with the CSQ annotation\n vep_header (list): A list with the vep header\n\nReturns:\n vep_annotations (list): A list of vep dicts", "source": "juraj_google_style"} +{"code": "def select_qadapter(self, pconfs):\n\n # Order the list of configurations according to policy.\n policy, max_ncpus = self.policy, self.max_cores\n pconfs = pconfs.get_ordered_with_policy(policy, max_ncpus)\n\n if policy.precedence == \"qadapter\":\n\n # Try to run on the qadapter with the highest priority.\n for qadpos, qad in enumerate(self.qads):\n possible_pconfs = [pc for pc in pconfs if qad.can_run_pconf(pc)]\n\n if qad.allocation == \"nodes\":\n #if qad.allocation in [\"nodes\", \"force_nodes\"]:\n # Select the configuration divisible by nodes if possible.\n for pconf in possible_pconfs:\n if pconf.num_cores % qad.hw.cores_per_node == 0:\n return self._use_qadpos_pconf(qadpos, pconf)\n\n # Here we select the first one.\n if possible_pconfs:\n return self._use_qadpos_pconf(qadpos, possible_pconfs[0])\n\n elif policy.precedence == \"autoparal_conf\":\n # Try to run on the first pconf irrespectively of the priority of the qadapter.\n for pconf in pconfs:\n for qadpos, qad in enumerate(self.qads):\n\n if qad.allocation == \"nodes\" and not pconf.num_cores % qad.hw.cores_per_node == 0:\n continue # Ignore it. not very clean\n\n if qad.can_run_pconf(pconf):\n return self._use_qadpos_pconf(qadpos, pconf)\n\n else:\n raise ValueError(\"Wrong value of policy.precedence = %s\" % policy.precedence)\n\n # No qadapter could be found\n raise RuntimeError(\"Cannot find qadapter for this run!\")", "docstring": "Given a list of parallel configurations, pconfs, this method select an `optimal` configuration\n according to some criterion as well as the :class:`QueueAdapter` to use.\n\nArgs:\n pconfs: :class:`ParalHints` object with the list of parallel configurations\n\nReturns:\n :class:`ParallelConf` object with the `optimal` configuration.", "source": "juraj_google_style"} +{"code": "def _filterByPaddingNum(cls, iterable, num):\n\n _check = DISK_RE.match\n\n for item in iterable:\n # Add a filter for paths that don't match the frame\n # padding of a given number\n matches = _check(item)\n if not matches:\n if num <= 0:\n # Not a sequence pattern, but we were asked\n # to match on a zero padding\n yield item\n\n continue\n\n frame = matches.group(3) or ''\n\n if not frame:\n if num <= 0:\n # No frame value was parsed, but we were asked\n # to match on a zero padding\n yield item\n continue\n\n # We have a frame number\n\n if frame[0] == '0' or frame[:2] == '-0':\n if len(frame) == num:\n # A frame leading with '0' is explicitly\n # padded and can only be a match if its exactly\n # the target padding number\n yield item\n continue\n\n if len(frame) >= num:\n # A frame that does not lead with '0' can match\n # a padding width >= to the target padding number\n yield item\n continue", "docstring": "Yield only path elements from iterable which have a frame\n padding that matches the given target padding number\n\nArgs:\n iterable (collections.Iterable):\n num (int):\n\nYields:\n str:", "source": "juraj_google_style"} +{"code": "def package_and_copy(package_root_dir, setup_py, output_tar_path):\n\n if not output_tar_path.startswith('gs://'):\n raise ValueError('output_tar_path needs to be a GCS path.')\n if not os.path.isfile(setup_py):\n raise ValueError('Supplied file \"%s\" does not exist.' % setup_py)\n\n dest_setup_py = os.path.join(package_root_dir, 'setup.py')\n if dest_setup_py != setup_py:\n # setuptools requires a \"setup.py\" in the current dir, so copy setup.py there.\n # Also check if there is an existing setup.py. If so, back it up.\n if os.path.isfile(dest_setup_py):\n os.rename(dest_setup_py, dest_setup_py + '._bak_')\n shutil.copyfile(setup_py, dest_setup_py)\n\n tempdir = tempfile.mkdtemp()\n previous_cwd = os.getcwd()\n os.chdir(package_root_dir)\n try:\n # Repackage.\n sdist = ['python', dest_setup_py, 'sdist', '--format=gztar', '-d', tempdir]\n subprocess.check_call(sdist)\n\n # Copy to GCS.\n source = os.path.join(tempdir, '*.tar.gz')\n gscopy = ['gsutil', 'cp', source, output_tar_path]\n subprocess.check_call(gscopy)\n return\n finally:\n os.chdir(previous_cwd)\n if dest_setup_py != setup_py:\n os.remove(dest_setup_py)\n if os.path.isfile(dest_setup_py + '._bak_'):\n os.rename(dest_setup_py + '._bak_', dest_setup_py)\n shutil.rmtree(tempdir)", "docstring": "Repackage an CloudML package and copy it to a staging dir.\n\nArgs:\n package_root_dir: the root dir to install package from. Usually you can get the path\n from inside your module using a relative path to __file__.\n setup_py: the path to setup.py.\n output_tar_path: the GCS path of the output tarball package.\n\nRaises:\n ValueError if output_tar_path is not a GCS path, or setup_py does not exist.", "source": "juraj_google_style"} +{"code": "def learn_dfa(self, mma=None):\n\n logging.info('Initializing learning procedure.')\n if mma:\n self._init_table_from_dfa(mma)\n else:\n self._init_table()\n\n logging.info('Generating a closed and consistent observation table.')\n while True:\n\n closed = False\n # Make sure that the table is closed\n while not closed:\n logging.debug('Checking if table is closed.')\n closed, string = self.observation_table.is_closed()\n if not closed:\n logging.debug('Closing table.')\n self._ot_make_closed(string)\n else:\n logging.debug('Table closed.')\n\n # Create conjecture\n\n dfa = self.get_dfa_conjecture()\n\n logging.info('Generated conjecture machine with %d states.',len(list(dfa.states)))\n\n # _check correctness\n logging.debug('Running equivalence query.')\n found, counter_example = self._equivalence_query(dfa)\n\n # Are we done?\n if found:\n logging.info('No counterexample found. Hypothesis is correct!')\n break\n\n # Add the new experiments into the table to reiterate the\n # learning loop\n logging.info('Processing counterexample %s with length %d.', counter_example, len(counter_example))\n self._process_counter_example(dfa, counter_example)\n\n logging.info('Learning complete.')\n logging.info('Learned em_vector table is the following:')\n logging.info(self.observation_table.em_vector)\n return '', dfa", "docstring": "Implements the high level loop of the algorithm for learning a\n Mealy machine.\n\nArgs:\n mma (DFA): The input automaton\n\nReturns:\n MealyMachine: A string and a model for the Mealy machine to be learned.", "source": "juraj_google_style"} +{"code": "def FileEntryExistsByPathSpec(self, path_spec):\n\n tsk_vs_part, _ = tsk_partition.GetTSKVsPartByPathSpec(\n self._tsk_volume, path_spec)\n\n # The virtual root file has not corresponding TSK volume system part object\n # but should have a location.\n if tsk_vs_part is None:\n location = getattr(path_spec, 'location', None)\n return location is not None and location == self.LOCATION_ROOT\n\n return True", "docstring": "Determines if a file entry for a path specification exists.\n\nArgs:\n path_spec (PathSpec): a path specification.\n\nReturns:\n bool: True if the file entry exists or false otherwise.", "source": "juraj_google_style"} +{"code": "def _ReadPresetsFromFileObject(self, file_object):\n\n yaml_generator = yaml.safe_load_all(file_object)\n\n last_preset_definition = None\n for yaml_definition in yaml_generator:\n try:\n preset_definition = self._ReadParserPresetValues(yaml_definition)\n except errors.MalformedPresetError as exception:\n error_location = 'At start'\n if last_preset_definition:\n error_location = 'After: {0:s}'.format(last_preset_definition.name)\n\n raise errors.MalformedPresetError(\n '{0:s} {1!s}'.format(error_location, exception))\n\n yield preset_definition\n last_preset_definition = preset_definition", "docstring": "Reads parser and parser plugin presets from a file-like object.\n\nArgs:\n file_object (file): file-like object containing the parser and parser\n plugin presets definitions.\n\nYields:\n ParserPreset: a parser preset.\n\nRaises:\n MalformedPresetError: if one or more plugin preset definitions are\n malformed.", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.GetChanges = channel.unary_stream(\n '/pb.Data/GetChanges',\n request_serializer=lookout_dot_sdk_dot_service__data__pb2.ChangesRequest.SerializeToString,\n response_deserializer=lookout_dot_sdk_dot_service__data__pb2.Change.FromString,\n )\n self.GetFiles = channel.unary_stream(\n '/pb.Data/GetFiles',\n request_serializer=lookout_dot_sdk_dot_service__data__pb2.FilesRequest.SerializeToString,\n response_deserializer=lookout_dot_sdk_dot_service__data__pb2.File.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def devno_free(self, devno):\n\n devno_int = int(devno, 16)\n self._devno_pool.free(devno_int)", "docstring": "Free a device number allocated with :meth:`devno_alloc`.\n\n The device number must be allocated.\n\n Parameters:\n devno (string): The device number as four hexadecimal digits.\n\nRaises:\n ValueError: Device number not in pool range or not currently\n allocated.", "source": "juraj_google_style"} +{"code": "def brake_on(self):\n\n data = []\n data.append(0x0A)\n data.append(self.servoid)\n data.append(RAM_WRITE_REQ)\n data.append(TORQUE_CONTROL_RAM)\n data.append(0x01)\n data.append(0x40)\n send_data(data)", "docstring": "Set the Brakes of Herkulex\n\n In braked mode, position control and velocity control\n will not work, enable torque before that\n\nArgs:\n none", "source": "juraj_google_style"} +{"code": "def isubset(self, *keys):\n # type: (*Hashable) -> ww.g\n\n return ww.g((key, self[key]) for key in keys)", "docstring": "Return key, self[key] as generator for key in keys.\n\n Raise KeyError if a key does not exist\n\nArgs:\n keys: Iterable containing keys\n\nExample:\n >>> from ww import d\n >>> list(d({1: 1, 2: 2, 3: 3}).isubset(1, 3))\n [(1, 1), (3, 3)]", "source": "juraj_google_style"} +{"code": "def send_status_message(self, object_id, status):\n\n try:\n body = json.dumps({\n 'id': object_id,\n 'status': status\n })\n\n self.status_queue.send_message(\n MessageBody=body,\n MessageGroupId='job_status',\n MessageDeduplicationId=get_hash((object_id, status))\n )\n return True\n except Exception as ex:\n print(ex)\n return False", "docstring": "Send a message to the `status_queue` to update a job's status.\n\n Returns `True` if the message was sent, else `False`\n\nArgs:\n object_id (`str`): ID of the job that was executed\n status (:obj:`SchedulerStatus`): Status of the job\n\nReturns:\n `bool`", "source": "juraj_google_style"} +{"code": "def write(self, data):\n\n if not isinstance(data, (bytes, bytearray, list)):\n raise TypeError(\"Invalid data type, should be bytes, bytearray, or list.\")\n\n if isinstance(data, list):\n data = bytearray(data)\n\n try:\n return os.write(self._fd, data)\n except OSError as e:\n raise SerialError(e.errno, \"Writing serial port: \" + e.strerror)", "docstring": "Write `data` to the serial port and return the number of bytes\n written.\n\nArgs:\n data (bytes, bytearray, list): a byte array or list of 8-bit integers to write.\n\nReturns:\n int: number of bytes written.\n\nRaises:\n SerialError: if an I/O or OS error occurs.\n TypeError: if `data` type is invalid.\n ValueError: if data is not valid bytes.", "source": "juraj_google_style"} +{"code": "def mctransp(I,J,K,c,d,M):\n\n\n model = Model(\"multi-commodity transportation\")\n\n # Create variables\n x = {}\n\n for (i,j,k) in c:\n x[i,j,k] = model.addVar(vtype=\"C\", name=\"x(%s,%s,%s)\" % (i,j,k))\n\n # Demand constraints\n for i in I:\n for k in K:\n model.addCons(sum(x[i,j,k] for j in J if (i,j,k) in x) == d[i,k], \"Demand(%s,%s)\" % (i,k))\n\n # Capacity constraints\n for j in J:\n model.addCons(sum(x[i,j,k] for (i,j2,k) in x if j2 == j) <= M[j], \"Capacity(%s)\" % j)\n\n # Objective\n model.setObjective(quicksum(c[i,j,k]*x[i,j,k] for (i,j,k) in x), \"minimize\")\n\n model.data = x\n\n return model", "docstring": "mctransp -- model for solving the Multi-commodity Transportation Problem\n Parameters:\n - I: set of customers\n - J: set of facilities\n - K: set of commodities\n - c[i,j,k]: unit transportation cost on arc (i,j) for commodity k\n - d[i][k]: demand for commodity k at node i\n - M[j]: capacity\n Returns a model, ready to be solved.", "source": "juraj_google_style"} +{"code": "def ParseFileObject(self, parser_mediator, file_object):\n\n file_size = file_object.get_size()\n\n file_header_map = self._GetDataTypeMap('rp_log_file_header')\n\n try:\n file_header, _ = self._ReadStructureFromFileObject(\n file_object, 0, file_header_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.UnableToParseFile(\n 'Unable to parse file header with error: {0!s}'.format(\n exception))\n\n file_footer_map = self._GetDataTypeMap('rp_log_file_footer')\n\n file_footer_offset = file_size - file_footer_map.GetByteSize()\n\n try:\n file_footer, _ = self._ReadStructureFromFileObject(\n file_object, file_footer_offset, file_footer_map)\n except (ValueError, errors.ParseError) as exception:\n parser_mediator.ProduceExtractionWarning(\n 'unable to parse file footer with error: {0!s}'.format(exception))\n return\n\n # The description in the file header includes the end-of-string character\n # that we need to strip off.\n description = file_header.description.rstrip('\\0')\n\n if file_footer.creation_time == 0:\n date_time = dfdatetime_semantic_time.SemanticTime('Not set')\n else:\n date_time = dfdatetime_filetime.Filetime(\n timestamp=file_footer.creation_time)\n\n event_data = RestorePointEventData()\n event_data.description = description\n event_data.restore_point_event_type = file_header.event_type\n event_data.restore_point_type = file_header.restore_point_type\n event_data.sequence_number = file_header.sequence_number\n\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_CREATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a Windows Restore Point (rp.log) log file-like object.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n file_object (dfvfs.FileIO): file-like object.\n\nRaises:\n UnableToParseFile: when the file cannot be parsed.", "source": "juraj_google_style"} +{"code": "def add_dataset(self, task_name, dataset=None, *, aliases=None):\n\n self._datasets.append(dataset if dataset is not None else TaskData())\n last_index = len(self._datasets) - 1\n self._aliases[task_name] = last_index\n\n if aliases is not None:\n for alias in aliases:\n self._aliases[alias] = last_index\n\n if len(self._datasets) == 1:\n self._default_index = 0", "docstring": "Add a new dataset to the MultiTaskData.\n\nArgs:\n task_name (str): The name of the task from which the dataset was received.\n dataset (TaskData): The dataset that should be added.\n aliases (list): A list of aliases that should be registered with the dataset.", "source": "juraj_google_style"} +{"code": "def write_dict_to_new_file(file_name, localization_key_to_comment):\n\n output_file_descriptor = open_strings_file(file_name, \"w\")\n for entry_key, entry_comment in sorted(localization_key_to_comment.iteritems(), key=operator.itemgetter(1)):\n write_entry_to_file(output_file_descriptor, entry_comment, entry_key)\n output_file_descriptor.write(u'\\n')\n output_file_descriptor.close()", "docstring": "Writes dictionary of localization keys and comments to a file.\n\nArgs:\n localization_key_to_comment (dict): A mapping between localization keys and comments.\n file_name (str): The path of the file to append to.", "source": "juraj_google_style"} +{"code": "def extract_tree_with(self, labels, suppress_unifurcations=True):\n\n return self.extract_tree(labels, False, suppress_unifurcations)", "docstring": "Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels``\n\nArgs:\n ``leaves`` (``set``): Set of leaf labels to include.\n\n ``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``\n\nReturns:\n Tree: Copy of this Tree, including only the leaves labeled by the strings in ``labels``", "source": "juraj_google_style"} +{"code": "def wait_for_tuning_job(self, job, poll=5):\n\n desc = _wait_until(lambda: _tuning_job_status(self.sagemaker_client, job), poll)\n self._check_job_status(job, desc, 'HyperParameterTuningJobStatus')\n return desc", "docstring": "Wait for an Amazon SageMaker hyperparameter tuning job to complete.\n\nArgs:\n job (str): Name of the tuning job to wait for.\n poll (int): Polling interval in seconds (default: 5).\n\nReturns:\n (dict): Return value from the ``DescribeHyperParameterTuningJob`` API.\n\nRaises:\n ValueError: If the hyperparameter tuning job fails.", "source": "juraj_google_style"} +{"code": "def replace(cls, obj, field, value, state):\n\n if not hasattr(obj, field):\n raise ValidationError(\"Field '%s' does not exist, so it cannot be patched\" % field)\n setattr(obj, field, value)\n return True", "docstring": "This is method for replace operation. It is separated to provide a\n possibility to easily override it in your Parameters.\n\nArgs:\n obj (object): an instance to change.\n field (str): field name\n value (str): new value\n state (dict): inter-operations state storage\n\nReturns:\n processing_status (bool): True", "source": "juraj_google_style"} +{"code": "def padFrameRange(frange, zfill):\n\n def _do_pad(match):\n\n result = list(match.groups())\n result[1] = pad(result[1], zfill)\n if result[4]:\n result[4] = pad(result[4], zfill)\n return ''.join((i for i in result if i))\n return PAD_RE.sub(_do_pad, frange)", "docstring": "Return the zero-padded version of the frame range string.\n\nArgs:\n frange (str): a frame range to test\n zfill (int):\n\nReturns:\n str:", "source": "juraj_google_style"} +{"code": "def uri(self, value, strip_iri=True):\n\n\n return self.convert_to_uri(value, strip_iri=strip_iri)", "docstring": "Converts py_uri or ttl uri to a http://... full uri format\n\nArgs:\n value: the string to convert\n\nReturns:\n full uri of an abbreivated uri", "source": "juraj_google_style"} +{"code": "def write_top_half(f, row_metadata_df, col_metadata_df, metadata_null, filler_null):\n\n # Initialize the top half of the gct including the third line\n size_of_top_half_df = (1 + col_metadata_df.shape[1],\n 1 + row_metadata_df.shape[1] + col_metadata_df.shape[0])\n\n top_half_df = pd.DataFrame(np.full(size_of_top_half_df, filler_null, dtype=object))\n\n # Assemble the third line of the gct: \"id\", then rhds, then cids\n top_half_df.iloc[0, :] = np.hstack((\"id\", row_metadata_df.columns.values, col_metadata_df.index.values))\n\n # Insert the chds\n top_half_df.iloc[range(1, top_half_df.shape[0]), 0] = col_metadata_df.columns.values\n\n # Insert the column metadata, but first convert to strings and replace NaNs\n col_metadata_indices = (range(1, top_half_df.shape[0]),\n range(1 + row_metadata_df.shape[1], top_half_df.shape[1]))\n # pd.DataFrame.at to insert into dataframe(python3)\n top_half_df.at[col_metadata_indices[0], col_metadata_indices[1]] = (\n col_metadata_df.astype(str).replace(\"nan\", value=metadata_null).T.values)\n\n # Write top_half_df to file\n top_half_df.to_csv(f, header=False, index=False, sep=\"\\t\")", "docstring": "Write the top half of the gct file: top-left filler values, row metadata\n headers, and top-right column metadata.\n\nArgs:\n f (file handle): handle for output file\n row_metadata_df (pandas df)\n col_metadata_df (pandas df)\n metadata_null (string): how to represent missing values in the metadata\n filler_null (string): what value to fill the top-left filler block with\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def binfiles_set(self, isnap):\n\n possible_files = set(self.filename(fstem, isnap, force_legacy=True)\n for fstem in phyvars.FIELD_FILES)\n return possible_files & self.files", "docstring": "Set of existing binary files at a given snap.\n\nArgs:\n isnap (int): snapshot index.\n\nReturns:\n set of pathlib.Path: the set of output files available for this\n snapshot number.", "source": "juraj_google_style"} +{"code": "def lat_id(self, line):\n\n if self.grid == 'WAC':\n lat = ((1 + self.LINE_PROJECTION_OFFSET - line) *\n self.MAP_SCALE * 1e-3 / self.A_AXIS_RADIUS)\n return lat * 180 / np.pi\n else:\n lat = float(self.CENTER_LATITUDE) - \\\n (line - float(self.LINE_PROJECTION_OFFSET) - 1)\\\n / float(self.MAP_RESOLUTION)\n return lat", "docstring": "Return the corresponding latitude\n\nArgs:\n line (int): Line number\n\nReturns:\n Correponding latitude in degree", "source": "juraj_google_style"} +{"code": "def EnumerateAllConfigs(self, stats, file_objects):\n\n # Convert the stats & file_objects into a cache of a\n # simple path keyed dict of file contents.\n cache = {}\n for stat_obj, file_obj in zip(stats, file_objects):\n cache[stat_obj.pathspec.path] = utils.ReadFileBytesAsUnicode(file_obj)\n\n result = []\n external = []\n # Check to see if we have the old pam config file laying around.\n if self.OLD_PAMCONF_FILENAME in cache:\n # The PAM documentation says if it contains config data, then\n # it takes precedence over the rest of the config.\n # If it doesn't, the rest of the PAMDIR config counts.\n result, external = self.EnumerateConfig(None, self.OLD_PAMCONF_FILENAME,\n cache)\n if result:\n return result, external\n\n # If we made it here, there isn't a old-style pam.conf file worth\n # speaking of, so process everything!\n for path in cache:\n # PAM uses the basename as the 'service' id.\n service = os.path.basename(path)\n r, e = self.EnumerateConfig(service, path, cache)\n result.extend(r)\n external.extend(e)\n return result, external", "docstring": "Generate RDFs for the fully expanded configs.\n\nArgs:\n stats: A list of RDF StatEntries corresponding to the file_objects.\n file_objects: A list of file handles.\n\nReturns:\n A tuple of a list of RDFValue PamConfigEntries found & a list of strings\n which are the external config references found.", "source": "juraj_google_style"} +{"code": "def projects(self, term, field=None, **kwargs):\n\n params = kwargs\n params['q'] = term\n if field:\n params['f'] = self._FIELD_MAP[field]\n else:\n params['f'] = 'pro.t'\n baseuri = self._BASE_URI + 'projects'\n res = self.session.get(baseuri, params=params)\n self.handle_http_error(res)\n return res", "docstring": "Search for projects. Defaults to project_title. Other fields\n are:\n project_reference\n project_abstract\n\nArgs:\n term (str): Term to search for.\n kwargs (dict): additional keywords passed into\n requests.session.get params keyword.", "source": "juraj_google_style"} +{"code": "def fit(self, X):\n\n U, V = self.split_matrix(X)\n self.tau = stats.kendalltau(U, V)[0]\n self.theta = self.compute_theta()\n self.check_theta()", "docstring": "Fit a model to the data updating the parameters.\n\nArgs:\n X: `np.ndarray` of shape (,2).\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def groups_invite(self, *, channel: str, user: str, **kwargs) -> SlackResponse:\n\n self._validate_xoxp_token()\n kwargs.update({\"channel\": channel, \"user\": user})\n return self.api_call(\"groups.invite\", json=kwargs)", "docstring": "Invites a user to a private channel.\n\nArgs:\n channel (str): The group id. e.g. 'G1234567890'\n user (str): The user id. e.g. 'U1234567890'", "source": "juraj_google_style"} +{"code": "def create_assembly(self, did, wid, name='My Assembly'):\n\n\n payload = {\n 'name': name\n }\n\n return self._api.request('post', '/api/assemblies/d/' + did + '/w/' + wid, body=payload)", "docstring": "Creates a new assembly element in the specified document / workspace.\n\nArgs:\n - did (str): Document ID\n - wid (str): Workspace ID\n - name (str, default='My Assembly')\n\nReturns:\n - requests.Response: Onshape response data", "source": "juraj_google_style"} +{"code": "def PushEvent(self, event):\n\n event_string = event.GetAttributeValuesString()\n heap_values = (event.timestamp, event.timestamp_desc, event_string, event)\n heapq.heappush(self._heap, heap_values)", "docstring": "Pushes an event onto the heap.\n\nArgs:\n event (EventObject): event.", "source": "juraj_google_style"} +{"code": "def _parse_frange_part(frange):\n\n match = FRANGE_RE.match(frange)\n if not match:\n msg = 'Could not parse \"{0}\": did not match {1}'\n raise ParseException(msg.format(frange, FRANGE_RE.pattern))\n start, end, modifier, chunk = match.groups()\n start = int(start)\n end = int(end) if end is not None else start\n\n if end > start and chunk is not None and int(chunk) < 0:\n msg = 'Could not parse \"{0}: chunk can not be negative'\n raise ParseException(msg.format(frange))\n\n chunk = abs(int(chunk)) if chunk is not None else 1\n # a zero chunk is just plain illogical\n if chunk == 0:\n msg = 'Could not parse \"{0}\": chunk cannot be 0'\n raise ParseException(msg.format(frange))\n return start, end, modifier, chunk", "docstring": "Internal method: parse a discrete frame range part.\n\nArgs:\n frange (str): single part of a frame range as a string\n (ie \"1-100x5\")\n\nReturns:\n tuple: (start, end, modifier, chunk)\n\nRaises:\n :class:`.ParseException`: if the frame range can\n not be parsed", "source": "juraj_google_style"} +{"code": "def download_as_obj(\n base_url=d1_common.const.URL_DATAONE_ROOT,\n timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT,\n):\n\n return decode_der(download_as_der(base_url, timeout_sec))", "docstring": "Download public certificate from a TLS/SSL web server as Certificate object.\n\n Also see download_as_der().\n\nArgs:\n base_url : str\n A full URL to a DataONE service endpoint or a server hostname\n timeout_sec : int or float\n Timeout for the SSL socket operations\n\nReturns:\n cryptography.Certificate", "source": "juraj_google_style"} +{"code": "def __init__(self, force=False):\n\n self.colorize = force or sys.stdout.isatty() or os.environ.get('JPY_PARENT_PID', None)", "docstring": "Initialize the class.\n\nArgs:\n force (bool): If True, render colorizes output no matter where the output is (default: False).", "source": "juraj_google_style"} +{"code": "def _retrieve_info(self, request):\n\n info = _metadata.get_service_account_info(\n request,\n service_account=self._service_account_email)\n\n self._service_account_email = info['email']\n self._scopes = info['scopes']", "docstring": "Retrieve information about the service account.\n\n Updates the scopes and retrieves the full service account email.\n\nArgs:\n request (google.auth.transport.Request): The object used to make\n HTTP requests.", "source": "juraj_google_style"} +{"code": "def cancelTickByTickData(self, contract: Contract, tickType: str):\n\n ticker = self.ticker(contract)\n reqId = self.wrapper.endTicker(ticker, tickType)\n if reqId:\n self.client.cancelTickByTickData(reqId)\n else:\n self._logger.error(\n f'cancelMktData: No reqId found for contract {contract}')", "docstring": "Unsubscribe from tick-by-tick data\n\nArgs:\n contract: The exact contract object that was used to\n subscribe with.", "source": "juraj_google_style"} +{"code": "def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT):\n\n svg = plot_to_svg(plot, width, height, unit)\n with open(filename, 'w') as outfile:\n outfile.write(svg)", "docstring": "Writes a plot SVG to a file.\n\nArgs:\n plot (list): a list of layers to plot\n filename (str): the name of the file to write\n width (float): the width of the output SVG\n height (float): the height of the output SVG\n unit (str): the unit of the height and width", "source": "juraj_google_style"} +{"code": "def calc_timestep_statistic(self, statistic, time):\n\n ti = np.where(self.times == time)[0][0]\n ma = np.where(self.masks[ti].ravel() == 1)\n if statistic in ['mean', 'max', 'min', 'std', 'ptp']:\n stat_val = getattr(self.timesteps[ti].ravel()[ma], statistic)()\n elif statistic == 'median':\n stat_val = np.median(self.timesteps[ti].ravel()[ma])\n elif 'percentile' in statistic:\n per = int(statistic.split(\"_\")[1])\n stat_val = np.percentile(self.timesteps[ti].ravel()[ma], per)\n elif 'dt' in statistic:\n stat_name = statistic[:-3]\n if ti == 0:\n stat_val = 0\n else:\n stat_val = self.calc_timestep_statistic(stat_name, time) -\\\n self.calc_timestep_statistic(stat_name, time - 1)\n else:\n stat_val = np.nan\n return stat_val", "docstring": "Calculate statistics from the primary attribute of the StObject.\n\nArgs:\n statistic: statistic being calculated\n time: Timestep being investigated\n\nReturns:\n Value of the statistic", "source": "juraj_google_style"} +{"code": "def write_contents(self, filename, contents, directory=None):\n\n filepath = \"{}/{}\".format(directory.rstrip(\"/\"), filename) if directory else filename\n self._write_to_zipfile(filepath, contents)\n return filepath", "docstring": "write_contents: Write contents to filename in zip\n\nArgs:\n contents: (str) contents of file\n filename: (str) name of file in zip\n directory: (str) directory in zipfile to write file to (optional)\n Returns: path to file in zip", "source": "juraj_google_style"} +{"code": "def __init__(\n self, name, aliases=None, alignment_size=None, description=None,\n urls=None):\n\n super(PaddingDefinition, self).__init__(\n name, aliases=aliases, description=description, urls=urls)\n self.alignment_size = alignment_size", "docstring": "Initializes a padding data type definition.\n\nArgs:\n name (str): name.\n aliases (Optional[list[str]]): aliases.\n alignment_size (Optional[int]): alignment size.\n description (Optional[str]): description.\n urls (Optional[list[str]]): URLs.", "source": "juraj_google_style"} +{"code": "def get_help_datapacks(module_name, server_prefix):\n\n\n _dir = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\n module_dir = \"{}/../{}\".format(_dir, module_name, \"_help.json\")\n if os.path.isdir(module_dir):\n module_help_path = \"{}/{}\".format(module_dir, \"_help.json\")\n\n if os.path.isfile(module_help_path):\n return helptools.get_help_datapacks(module_help_path, server_prefix)\n else:\n return [(\"Help\", \"{} does not have a help.json file\".format(module_name), False)]\n else:\n return [(\"Help\", \"No module found called {}\".format(module_name), False)]", "docstring": "Get the help datapacks for a module\n\nArgs:\n module_name (str): The module to get help data for\n server_prefix (str): The command prefix for this server\n\nReturns:\n datapacks (list): The help datapacks for the module", "source": "juraj_google_style"} +{"code": "def __init__(self, rom_path):\n\n # create a ROM file from the ROM path\n rom = ROM(rom_path)\n # check that there is PRG ROM\n if rom.prg_rom_size == 0:\n raise ValueError('ROM has no PRG-ROM banks.')\n # ensure that there is no trainer\n if rom.has_trainer:\n raise ValueError('ROM has trainer. trainer is not supported.')\n # try to read the PRG ROM and raise a value error if it fails\n _ = rom.prg_rom\n # try to read the CHR ROM and raise a value error if it fails\n _ = rom.chr_rom\n # check the TV system\n if rom.is_pal:\n raise ValueError('ROM is PAL. PAL is not supported.')\n # check that the mapper is implemented\n elif rom.mapper not in {0, 1, 2, 3}:\n msg = 'ROM has an unsupported mapper number {}.'\n raise ValueError(msg.format(rom.mapper))\n # create a dedicated random number generator for the environment\n self.np_random = np.random.RandomState()\n # store the ROM path\n self._rom_path = rom_path\n # initialize the C++ object for running the environment\n self._env = _LIB.Initialize(self._rom_path)\n # setup a placeholder for a 'human' render mode viewer\n self.viewer = None\n # setup a placeholder for a pointer to a backup state\n self._has_backup = False\n # setup a done flag\n self.done = True\n # setup the controllers, screen, and RAM buffers\n self.controllers = [self._controller_buffer(port) for port in range(2)]\n self.screen = self._screen_buffer()\n self.ram = self._ram_buffer()", "docstring": "Create a new NES environment.\n\nArgs:\n rom_path (str): the path to the ROM for the environment\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def clean(self, value):\n\n\n\t\t# If the value is None and it's optional, return as is\n\t\tif value is None and self._optional:\n\t\t\treturn None\n\n\t\t# If the value is not a dict\n\t\tif not isinstance(value, dict):\n\t\t\traise ValueError('value')\n\n\t\t# Init the return value\n\t\tdRet = {}\n\n\t\t# Go through each value and clean it using the associated node\n\t\tfor k in value.keys():\n\t\t\ttry:\n\t\t\t\tdRet[k] = self._nodes[k].clean(value[k])\n\t\t\texcept KeyError:\n\t\t\t\traise ValueError('%s is not a valid node in the parent' % k)\n\n\t\t# Return the cleaned values\n\t\treturn dRet", "docstring": "Clean\n\n Goes through each of the values in the dict, cleans it, stores it, and\n returns a new dict\n\nArgs:\n value {dict} -- The value to clean\n\nReturns:\n dict", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.Ping = channel.unary_unary(\n '/processor.Processor/Ping',\n request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,\n response_deserializer=processor__pb2.Status.FromString,\n )\n self.Process = channel.unary_unary(\n '/processor.Processor/Process',\n request_serializer=message__pb2.Message.SerializeToString,\n response_deserializer=message__pb2.Message.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def _indicator(self, indicator_data):\n\n if isinstance(indicator_data, dict):\n # get xid from dict\n xid = indicator_data.get('xid')\n else:\n # get xid from object\n xid = indicator_data.xid\n\n if self.indicators.get(xid) is not None:\n # return existing indicator from memory\n indicator_data = self.indicators.get(xid)\n elif self.indicators_shelf.get(xid) is not None:\n # return existing indicator from shelf\n indicator_data = self.indicators_shelf.get(xid)\n else:\n # store new indicators\n self.indicators[xid] = indicator_data\n return indicator_data", "docstring": "Return previously stored indicator or new indicator.\n\nArgs:\n indicator_data (dict|obj): An Indicator dict or instance of Indicator object.\n\nReturns:\n dict|obj: The new Indicator dict/object or the previously stored dict/object.", "source": "juraj_google_style"} +{"code": "def set_hook_data(self, key, data):\n\n\n if not isinstance(data, collections.Mapping):\n raise ValueError(\"Hook (key: %s) data must be an instance of \"\n \"collections.Mapping (a dictionary for \"\n \"example).\" % key)\n\n if key in self.hook_data:\n raise KeyError(\"Hook data for key %s already exists, each hook \"\n \"must have a unique data_key.\", key)\n\n self.hook_data[key] = data", "docstring": "Set hook data for the given key.\n\nArgs:\n key(str): The key to store the hook data in.\n data(:class:`collections.Mapping`): A dictionary of data to store,\n as returned from a hook.", "source": "juraj_google_style"} +{"code": "def unit(n, d=None, j=None, tt_instance=True):\n\n if isinstance(n, int):\n if d is None:\n d = 1\n n = n * _np.ones(d, dtype=_np.int32)\n else:\n d = len(n)\n if j is None:\n j = 0\n rv = []\n\n j = _ind2sub(n, j)\n\n for k in xrange(d):\n rv.append(_np.zeros((1, n[k], 1)))\n rv[-1][0, j[k], 0] = 1\n if tt_instance:\n rv = _vector.vector.from_list(rv)\n return rv", "docstring": "Generates e_j _vector in tt.vector format\n ---------\n Parameters:\n n - modes (either integer or array)\n d - dimensionality (integer)\n j - position of 1 in full-format e_j (integer)\n tt_instance - if True, returns tt.vector;\n if False, returns tt cores as a list", "source": "juraj_google_style"} +{"code": "def sleep(self, seconds):\n\n until = time.time() + seconds\n try:\n while True:\n self._service_futures([], until)\n except TimeoutError:\n return", "docstring": "Services all futures while waiting\n\nArgs:\n seconds (float): Time to wait", "source": "juraj_google_style"} +{"code": "def write_version_and_dims(version, dims, f):\n\n f.write((\"#\" + version + \"\\n\"))\n f.write((dims[0] + \"\\t\" + dims[1] + \"\\t\" + dims[2] + \"\\t\" + dims[3] + \"\\n\"))", "docstring": "Write first two lines of gct file.\n\nArgs:\n version (string): 1.3 by default\n dims (list of strings): length = 4\n f (file handle): handle of output file\n\nReturns:\n nothing", "source": "juraj_google_style"} +{"code": "def __init__(self, name):\n\n super(MemberSectionDefinition, self).__init__()\n self.name = name\n self.members = []", "docstring": "Initializes a member section definition.\n\nArgs:\n name (str): name.", "source": "juraj_google_style"} +{"code": "def readinto(self, b):\n\n if not self._readable:\n raise UnsupportedOperation('read')\n\n with self._seek_lock:\n # Gets seek\n seek = self._seek\n\n # Initializes queue\n queue = self._read_queue\n if seek == 0:\n # Starts initial preloading on first call\n self._preload_range()\n\n # Initializes read data buffer\n size = len(b)\n if size:\n # Preallocated buffer:\n # Use memory view to avoid copies\n b_view = memoryview(b)\n size_left = size\n else:\n # Dynamic buffer:\n # Can't avoid copy, read until EOF\n b_view = b\n size_left = -1\n b_end = 0\n\n # Starts reading\n buffer_size = self._buffer_size\n while size_left > 0 or size_left == -1:\n\n # Finds buffer position in queue and buffer seek\n start = seek % buffer_size\n queue_index = seek - start\n\n # Gets preloaded buffer\n try:\n buffer = queue[queue_index]\n except KeyError:\n # EOF\n break\n\n # Get buffer from future\n with handle_os_exceptions():\n try:\n queue[queue_index] = buffer = buffer.result()\n\n # Already evaluated\n except AttributeError:\n pass\n buffer_view = memoryview(buffer)\n data_size = len(buffer)\n\n # Checks if end of file reached\n if not data_size:\n break\n\n # Gets theoretical range to copy\n if size_left != -1:\n end = start + size_left\n else:\n end = data_size - start\n\n # Checks for end of buffer\n if end >= data_size:\n # Adjusts range to copy\n end = data_size\n\n # Removes consumed buffer from queue\n del queue[queue_index]\n\n # Append another buffer preload at end of queue\n index = queue_index + buffer_size * self._max_buffers\n if index < self._size:\n queue[index] = self._workers.submit(\n self._read_range, index, index + buffer_size)\n\n # Gets read size, updates seek and updates size left\n read_size = end - start\n if size_left != -1:\n size_left -= read_size\n seek += read_size\n\n # Defines read buffer range\n b_start = b_end\n b_end = b_start + read_size\n\n # Copy data from preload buffer to read buffer\n b_view[b_start:b_end] = buffer_view[start:end]\n\n # Updates seek and sync raw\n self._seek = seek\n self._raw.seek(seek)\n\n # Returns read size\n return b_end", "docstring": "Read bytes into a pre-allocated, writable bytes-like object b,\n and return the number of bytes read.\n\nArgs:\n b (bytes-like object): buffer.\n\nReturns:\n int: number of bytes read", "source": "juraj_google_style"} +{"code": "def _log_every_n_to_logger(n, logger, level, message, *args): # pylint: disable=invalid-name\n\n logger = logger or logging.getLogger()\n def _gen(): # pylint: disable=missing-docstring\n while True:\n for _ in range(n):\n yield False\n logger.log(level, message, *args)\n yield True\n gen = _gen()\n return lambda: six.next(gen)", "docstring": "Logs the given message every n calls to a logger.\n\nArgs:\n n: Number of calls before logging.\n logger: The logger to which to log.\n level: The logging level (e.g. logging.INFO).\n message: A message to log\n *args: Any format args for the message.\n\nReturns:\n A method that logs and returns True every n calls.", "source": "juraj_google_style"} +{"code": "def driver_for_path(path, drivers=None):\n\n ext = (os.path.splitext(path)[1][1:] or path).lower()\n drivers = drivers or ImageDriver.registry if ext else {}\n for name, meta in drivers.items():\n if ext == meta.get('DMD_EXTENSION', '').lower():\n return ImageDriver(name)\n return None", "docstring": "Returns the gdal.Driver for a path or None based on the file extension.\n\nArgs:\n path -- file path as str with a GDAL supported file extension", "source": "juraj_google_style"} +{"code": "def AddWatchOnly(self, script_hash):\n\n if script_hash in self._contracts:\n logger.error(\"Address already in contracts\")\n return\n\n self._watch_only.append(script_hash)", "docstring": "Add a watch only address to the wallet.\n\nArgs:\n script_hash (UInt160): a bytearray (len 20) representing the public key.\n\nNote:\n Prints a warning to the console if the address already exists in the wallet.", "source": "juraj_google_style"} +{"code": "def extract_function_argument(text, f_name, f_argn, f_argt=asttypes.String):\n\n\n tree = parse(text)\n return list(filter_function_argument(tree, f_name, f_argn, f_argt))", "docstring": "Extract a specific argument from a specific function name.\n\nArgs:\n text\n The source text.\n f_name\n The name of the function\n f_argn\n The argument position\n f_argt\n The argument type from calmjs.parse.asttypes;\n default: calmjs.parse.asttypes.String", "source": "juraj_google_style"} +{"code": "def write_worksheets(workbook, data_list, result_info_key, identifier_keys):\n\n\n # we can use the first item to figure out the worksheet keys\n worksheet_keys = get_worksheet_keys(data_list[0], result_info_key)\n\n for key in worksheet_keys:\n\n title = key.split('/')[1]\n\n title = utilities.convert_snake_to_title_case(title)\n\n title = KEY_TO_WORKSHEET_MAP.get(title, title)\n\n if key == 'property/nod':\n # the property/nod endpoint needs to be split into two worksheets\n create_property_nod_worksheets(workbook, data_list, result_info_key, identifier_keys)\n else:\n # all other endpoints are written to a single worksheet\n\n # Maximum 31 characters allowed in sheet title\n worksheet = workbook.create_sheet(title=title[:31])\n\n processed_data = process_data(key, data_list, result_info_key, identifier_keys)\n\n write_data(worksheet, processed_data)\n\n # remove the first, unused empty sheet\n workbook.remove_sheet(workbook.active)", "docstring": "Writes rest of the worksheets to workbook.\n\nArgs:\n workbook: workbook to write into\n data_list: Analytics API data as a list of dicts\n result_info_key: the key in api_data dicts that contains the data results\n identifier_keys: the list of keys used as requested identifiers\n (address, zipcode, block_id, etc)", "source": "juraj_google_style"} +{"code": "def do_IDENT(self, service_name: str, source: list, *args, **kwargs) -> None:\n\n self.logger.info(' IDENT %s as %s', service_name, source)\n self.messaging._address_map[service_name] = source", "docstring": "Perform identification of a service to a binary representation.\n\nArgs:\n service_name: human readable name for service\n source: zmq representation for the socket source", "source": "juraj_google_style"} +{"code": "def unpack_message(buffer):\n\n hdr_size = Header().get_size()\n hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:]\n header = Header()\n header.unpack(hdr_buff)\n message = new_message_from_header(header)\n message.unpack(msg_buff)\n return message", "docstring": "Unpack the whole buffer, including header pack.\n\nArgs:\n buffer (bytes): Bytes representation of a openflow message.\n\nReturns:\n object: Instance of openflow message.", "source": "juraj_google_style"} +{"code": "def FindFirst(cls, setting_matcher, device_matcher=None, **kwargs):\n\n try:\n return next(cls.FindDevices(\n setting_matcher, device_matcher=device_matcher, **kwargs))\n except StopIteration:\n raise usb_exceptions.DeviceNotFoundError(\n 'No device available, or it is in the wrong configuration.')", "docstring": "Find and return the first matching device.\n\nArgs:\n setting_matcher: See cls.FindDevices.\n device_matcher: See cls.FindDevices.\n **kwargs: See cls.FindDevices.\n\nReturns:\n An instance of UsbHandle.\n\nRaises:\n DeviceNotFoundError: Raised if the device is not available.", "source": "juraj_google_style"} +{"code": "def Parse(self, conditions, host_data):\n\n result = CheckResult(check_id=self.check_id)\n methods = self.SelectChecks(conditions)\n result.ExtendAnomalies([m.Parse(conditions, host_data) for m in methods])\n return result", "docstring": "Runs methods that evaluate whether collected host_data has an issue.\n\nArgs:\n conditions: A list of conditions to determine which Methods to trigger.\n host_data: A map of artifacts and rdf data.\n\nReturns:\n A CheckResult populated with Anomalies if an issue exists.", "source": "juraj_google_style"} +{"code": "def anchored_pairs(self, anchor):\n\n\n\n pairs = OrderedDict()\n\n for term in self.keys:\n score = self.get_pair(anchor, term)\n if score: pairs[term] = score\n\n return utils.sort_dict(pairs)", "docstring": "Get distances between an anchor term and all other terms.\n\nArgs:\n anchor (str): The anchor term.\n\nReturns:\n OrderedDict: The distances, in descending order.", "source": "juraj_google_style"} +{"code": "def set_memcache_policy(self, func):\n\n if func is None:\n func = self.default_memcache_policy\n elif isinstance(func, bool):\n func = lambda unused_key, flag=func: flag\n self._memcache_policy = func", "docstring": "Set the memcache policy function.\n\nArgs:\n func: A function that accepts a Key instance as argument and returns\n a bool indicating if it should be cached. May be None.", "source": "juraj_google_style"} +{"code": "def __init__(self, prefs, g, divPressureValues, kappa=2.0, omega=0.5,\n beta=1.0, mu=1.0,omega2=0.0,\n freeparams=['kappa', 'omega', 'beta', 'mu', 'omega2']):\n\n _checkParam('omega2',omega2, self.PARAMLIMITS, self.PARAMTYPES)\n self.omega2 = omega2\n self.deltar = scipy.array(divPressureValues.copy())\n assert (max(scipy.absolute(self.deltar))) <= 1, (\n \"A scaled deltar value is > 1 or < -1.\")\n super(ExpCM_empirical_phi_divpressure, self).__init__(prefs, g,\n kappa=kappa, omega=omega, beta=beta, mu=mu,\n freeparams=freeparams)", "docstring": "Initialize an `ExpCM_empirical_phi_divpressure` object.\n\nArgs:\n `prefs`, `kappa`, `omega`, `beta`, `mu`, `g`, `freeparams`\n Same meaning as for an `ExpCM_empirical_phi`\n `divPressureValues`, `omega2`\n Meaning described in the main class doc string.", "source": "juraj_google_style"} +{"code": "def __init__(self, layer, named_tensors=None, scope='tf-layer', summary_labels=(), **kwargs):\n\n self.layer_spec = layer\n self.layer = util.get_object(obj=layer, predefined_objects=TFLayer.tf_layers, kwargs=kwargs)\n self.first_scope = None\n\n super(TFLayer, self).__init__(named_tensors=named_tensors, scope=scope, summary_labels=summary_labels)", "docstring": "Creates a new layer instance of a TensorFlow layer.\n\nArgs:\n name: The name of the layer, one of 'dense'.\n **kwargs: Additional arguments passed on to the TensorFlow layer constructor.", "source": "juraj_google_style"} +{"code": "def updateFeatureService(self, efs_config):\n\n if self.securityhandler is None:\n print (\"Security handler required\")\n return\n fsRes = None\n fst = None\n fURL = None\n resItm= None\n try:\n\n fsRes = []\n fst = featureservicetools.featureservicetools(securityinfo=self)\n\n\n if isinstance(efs_config, list):\n for ext_service in efs_config:\n fURL = None\n cs = 0\n try:\n if 'ChunkSize' in ext_service:\n if common.is_number(ext_service['ChunkSize']):\n cs = ext_service['ChunkSize']\n except Exception as e:\n pass\n resItm={\"DeleteDetails\": None,\"AddDetails\":None}\n if 'ItemId' in ext_service and 'LayerName' in ext_service:\n fs = fst.GetFeatureService(itemId=ext_service['ItemId'],returnURLOnly=False)\n if not fs is None:\n fURL = fst.GetLayerFromFeatureService(fs=fs,layerName=ext_service['LayerName'],returnURLOnly=True)\n if fURL is None and 'URL' in ext_service:\n\n fURL = ext_service['URL']\n if fURL is None:\n print(\"Item and layer not found or URL not in config\")\n continue\n\n if 'DeleteInfo' in ext_service:\n if str(ext_service['DeleteInfo']['Delete']).upper() == \"TRUE\":\n resItm['DeleteDetails'] = fst.DeleteFeaturesFromFeatureLayer(url=fURL, sql=ext_service['DeleteInfo']['DeleteSQL'],chunksize=cs)\n if not 'error' in resItm['DeleteDetails'] :\n print (\"Delete Successful: %s\" % fURL)\n else:\n print (str(resItm['DeleteDetails']))\n\n resItm['AddDetails'] = fst.AddFeaturesToFeatureLayer(url=fURL, pathToFeatureClass = ext_service['FeatureClass'],chunksize=cs)\n\n fsRes.append(resItm)\n\n if not 'error' in resItm['AddDetails']:\n print (\"Add Successful: %s \" % fURL)\n else:\n print (str(resItm['AddDetails']))\n\n else:\n resItm={\"DeleteDetails\": None,\"AddDetails\":None}\n fURL = efs_config['URL']\n cs = 0\n try:\n if 'ChunkSize' in efs_config:\n if common.is_number(efs_config['ChunkSize']):\n cs = efs_config['ChunkSize']\n except Exception as e:\n pass\n if 'ItemId' in efs_config and 'LayerName' in efs_config:\n fs = fst.GetFeatureService(itemId=efs_config['ItemId'],returnURLOnly=False)\n if not fs is None:\n fURL = fst.GetLayerFromFeatureService(fs=fs,layerName=efs_config['LayerName'],returnURLOnly=True)\n if fURL is None and 'URL' in efs_config:\n\n fURL = efs_config['URL']\n if fURL is None:\n print(\"Item and layer not found or URL not in config\")\n return None\n if 'DeleteInfo' in efs_config:\n if str(efs_config['DeleteInfo']['Delete']).upper() == \"TRUE\":\n resItm['DeleteDetails'] = fst.DeleteFeaturesFromFeatureLayer(url=fURL, sql=efs_config['DeleteInfo']['DeleteSQL'],chunksize=cs)\n if not 'error' in resItm['DeleteDetails'] :\n print (\" Delete Successful: %s\" % fURL)\n else:\n print (\" \" + str(resItm['DeleteDetails']))\n\n resItm['AddDetails'] = fst.AddFeaturesToFeatureLayer(url=fURL, pathToFeatureClass = efs_config['FeatureClass'],chunksize=cs)\n\n fsRes.append(resItm)\n\n if not 'error' in resItm['AddDetails']:\n print (\" Add Successful: %s \" % fURL)\n else:\n print (\" \" + str(resItm['AddDetails']))\n\n return fsRes\n\n except common.ArcRestHelperError as e:\n raise e\n except Exception as e:\n\n line, filename, synerror = trace()\n raise common.ArcRestHelperError({\n \"function\": \"updateFeatureService\",\n \"line\": line,\n \"filename\": filename,\n \"synerror\": synerror,\n })\n finally:\n fst = None\n fURL = None\n resItm= None\n\n del fst\n del fURL\n del resItm\n\n gc.collect()", "docstring": "Updates a feature service.\n\nArgs:\n efs_config (list): A list of JSON configuration feature service details to update.\n\nReturns:\n dict: A dictionary of results objects.", "source": "juraj_google_style"} +{"code": "def dim_reduce_data(data, d):\n\n genes, cells = data.shape\n distances = np.zeros((cells, cells))\n for i in range(cells):\n for j in range(cells):\n distances[i,j] = poisson_dist(data[:,i], data[:,j])\n # do MDS on the distance matrix (procedure from Wikipedia)\n proximity = distances**2\n J = np.eye(cells) - 1./cells\n B = -0.5*np.dot(J, np.dot(proximity, J))\n # B should be symmetric, so we can use eigh\n e_val, e_vec = np.linalg.eigh(B)\n # Note: lam should be ordered to be the largest eigenvalues\n lam = np.diag(e_val[-d:])[::-1]\n #lam = max_or_zero(lam)\n E = e_vec[:,-d:][::-1]\n X = np.dot(E, lam**0.5)\n return X", "docstring": "Does a MDS on the data directly, not on the means.\n\nArgs:\n data (array): genes x cells\n d (int): desired dimensionality\n\nReturns:\n X, a cells x d matrix", "source": "juraj_google_style"} +{"code": "def join_sources(source_module: DeploymentModule, contract_name: str):\n\n joined_file = Path(__file__).parent.joinpath('joined.sol')\n remapping = {module: str(path) for module, path in contracts_source_path().items()}\n command = [\n './utils/join-contracts.py',\n '--import-map',\n json.dumps(remapping),\n str(contracts_source_path_of_deployment_module(\n source_module,\n ).joinpath(contract_name + '.sol')),\n str(joined_file),\n ]\n working_dir = Path(__file__).parent.parent\n try:\n subprocess.check_call(command, cwd=working_dir)\n except subprocess.CalledProcessError as ex:\n print(f'cd {str(working_dir)}; {subprocess.list2cmdline(command)} failed.')\n raise ex\n\n return joined_file.read_text()", "docstring": "Use join-contracts.py to concatenate all imported Solidity files.\n\nArgs:\n source_module: a module name to look up contracts_source_path()\n contract_name: 'TokenNetworkRegistry', 'SecretRegistry' etc.", "source": "juraj_google_style"} +{"code": "def Add(self, path, age=None):\n\n if not isinstance(path, string_types):\n raise ValueError(\"Only strings should be added to a URN.\")\n\n result = rdfvalue.RDFURN(self.Copy(age))\n result.Update(path=utils.JoinPath(self._string_urn, path))\n\n return result", "docstring": "Add a relative stem to the current value and return a new RDFURN.\n\n Note that this returns an RDFURN, not a ClientURN since the resulting object\n would not pass validation.\n\nArgs:\n path: A string containing a relative path.\n age: The age of the object. If None set to current time.\n\nReturns:\n A new RDFURN that can be chained.\n\nRaises:\n ValueError: if the path component is not a string.", "source": "juraj_google_style"} +{"code": "def put(self, block_id, priority, pb_type='offline'):\n\n if pb_type not in ('offline', 'realtime'):\n raise ValueError('Invalid PB type.')\n\n with self._mutex:\n added_time = datetime.datetime.utcnow().isoformat()\n entry = (priority, sys.maxsize-self._index, block_id, pb_type,\n added_time)\n self._index += 1\n if self._block_map.get(block_id) is not None:\n raise KeyError('ERROR: Block id \"{}\" already exists in '\n 'PC PB queue!'.\n format(block_id))\n self._block_map[block_id] = entry\n LOG.debug(\"Adding PB %s to queue\", block_id)\n self._queue.append(entry)\n self._queue.sort() # Sort by priority followed by insertion order.\n self._queue.reverse()", "docstring": "Add a Processing Block to the queue.\n\n When a new entry it added, the queue is (re-)sorted by priority\n followed by insertion order (older blocks with equal priority are\n first).\n\nArgs:\n block_id (str): Processing Block Identifier\n priority (int): Processing Block scheduling priority\n (higher values = higher priority)\n pb_type (str): Processing Block type (offline, realtime)", "source": "juraj_google_style"} +{"code": "def __edit_distance_alt(self, words):\n\n words = [x.lower() for x in words]\n return [e2 for e1 in words for e2 in self.edit_distance_1(e1)]", "docstring": "Compute all strings that are 1 edits away from all the words using\n only the letters in the corpus\n\nArgs:\n words (list): The words for which to calculate the edit distance\n\nReturns:\n set: The set of strings that are edit distance two from the \\\n provided words", "source": "juraj_google_style"} +{"code": "def _create_query(node, context):\n\n visited_nodes = [node]\n output_columns = _get_output_columns(visited_nodes, context)\n filters = _get_filters(visited_nodes, context)\n selectable = sql_context_helpers.get_node_selectable(node, context)\n query = select(output_columns).select_from(selectable).where(and_(*filters))\n return query", "docstring": "Create a query from a SqlNode.\n\nArgs:\n node: SqlNode, the current node.\n context: CompilationContext, global compilation state and metadata.\n\nReturns:\n Selectable, selectable of the generated query.", "source": "juraj_google_style"} +{"code": "def _Scroll(self, lines=None):\n\n if lines is None:\n lines = self._cli_lines\n\n if lines < 0:\n self._displayed -= self._cli_lines\n self._displayed += lines\n if self._displayed < 0:\n self._displayed = 0\n self._lines_to_show = self._cli_lines\n else:\n self._lines_to_show = lines\n\n self._lastscroll = lines", "docstring": "Set attributes to scroll the buffer correctly.\n\nArgs:\n lines: An int, number of lines to scroll. If None, scrolls\n by the terminal length.", "source": "juraj_google_style"} +{"code": "def __init__(self, game, ui, visualize=False):\n\n self.game = game\n self.init_game = copy.deepcopy(self.game)\n self.ui = ui\n self.visualize = visualize\n\n first_obs, first_reward, _ = self.game.its_showtime()\n self._actions = DMPycolab.get_action_space(self.ui)\n self._states = DMPycolab.get_state_space(first_obs, self.ui._croppers)", "docstring": "Initialize Pycolab environment.\n\nArgs:\n game: Pycolab Game Engine object. See https://github.com/deepmind/pycolab/tree/master/pycolab/examples\n ui: Pycolab CursesUI object. See https://github.com/deepmind/pycolab/tree/master/pycolab/examples\n visualize: If set True, the program will visualize the trainings of Pycolab game # TODO", "source": "juraj_google_style"} +{"code": "def _prepare_headers(self, request, filter=None, order_by=None, group_by=[], page=None, page_size=None):\n\n\n if filter:\n request.set_header('X-Nuage-Filter', filter)\n\n if order_by:\n request.set_header('X-Nuage-OrderBy', order_by)\n\n if page is not None:\n request.set_header('X-Nuage-Page', str(page))\n\n if page_size:\n request.set_header('X-Nuage-PageSize', str(page_size))\n\n if len(group_by) > 0:\n header = \", \".join(group_by)\n request.set_header('X-Nuage-GroupBy', 'true')\n request.set_header('X-Nuage-Attributes', header)", "docstring": "Prepare headers for the given request\n\nArgs:\n request: the NURESTRequest to send\n filter: string\n order_by: string\n group_by: list of names\n page: int\n page_size: int", "source": "juraj_google_style"} +{"code": "def cleanup(context):\n\n for name in 'work_dir', 'artifact_dir', 'task_log_dir':\n path = context.config[name]\n if os.path.exists(path):\n log.debug(\"rm({})\".format(path))\n rm(path)\n makedirs(path)", "docstring": "Clean up the work_dir and artifact_dir between task runs, then recreate.\n\nArgs:\n context (scriptworker.context.Context): the scriptworker context.", "source": "juraj_google_style"} +{"code": "def like_shared_file(self, sharekey=None):\n\n\n if not sharekey:\n raise Exception(\n \"You must specify a sharekey of the file you\"\n \"want to 'like'.\")\n\n endpoint = '/api/sharedfile/{sharekey}/like'.format(sharekey=sharekey)\n data = self._make_request(\"POST\", endpoint=endpoint, data=None)\n\n try:\n sf = SharedFile.NewFromJSON(data)\n sf.liked = True\n return sf\n except:\n raise Exception(\"{0}\".format(data['error']))", "docstring": "'Like' a SharedFile. mlkshk doesn't allow you to unlike a\n sharedfile, so this is ~~permanent~~.\n\nArgs:\n sharekey (str): Sharekey for the file you want to 'like'.\n\nReturns:\n Either a SharedFile on success, or an exception on error.", "source": "juraj_google_style"} +{"code": "def compare_jsone_task_definition(parent_link, rebuilt_definitions):\n\n diffs = []\n for compare_definition in rebuilt_definitions['tasks']:\n # Rebuilt decision tasks have an extra `taskId`; remove\n if 'taskId' in compare_definition:\n del(compare_definition['taskId'])\n # remove key/value pairs where the value is empty, since json-e drops\n # them instead of keeping them with a None/{}/[] value.\n compare_definition = remove_empty_keys(compare_definition)\n runtime_definition = remove_empty_keys(parent_link.task)\n\n diff = list(dictdiffer.diff(compare_definition, runtime_definition))\n if diff:\n diffs.append(pprint.pformat(diff))\n continue\n log.info(\"{}: Good.\".format(parent_link.name))\n break\n else:\n error_msg = \"{} {}: the runtime task doesn't match any rebuilt definition!\\n{}\".format(\n parent_link.name, parent_link.task_id, pprint.pformat(diffs)\n )\n log.critical(error_msg)\n raise CoTError(error_msg)", "docstring": "Compare the json-e rebuilt task definition vs the runtime definition.\n\nArgs:\n parent_link (LinkOfTrust): the parent link to test.\n rebuilt_definitions (dict): the rebuilt task definitions.\n\nRaises:\n CoTError: on failure.", "source": "juraj_google_style"} +{"code": "def get_associated_resource(self, task):\n\n\n if not task:\n raise HPOneViewUnknownType(MSG_INVALID_TASK)\n\n if task['category'] != 'tasks' and task['category'] != 'backups':\n # it is an error if type is not in obj, so let the except flow\n raise HPOneViewUnknownType(MSG_UNKNOWN_OBJECT_TYPE)\n\n if task['type'] == 'TaskResourceV2':\n resource_uri = task['associatedResource']['resourceUri']\n\n if resource_uri and resource_uri.startswith(\"/rest/appliance/support-dumps/\"):\n # Specific for support dumps\n return task, resource_uri\n\n elif task['type'] == 'BACKUP':\n task = self._connection.get(task['taskUri'])\n resource_uri = task['uri']\n else:\n raise HPOneViewInvalidResource(MSG_TASK_TYPE_UNRECONIZED % task['type'])\n\n entity = {}\n\n if resource_uri:\n entity = self._connection.get(resource_uri)\n\n return task, entity", "docstring": "Retrieve a resource associated with a task.\n\nArgs:\n task: task dict\n\nReturns:\n tuple: task (updated), the entity found (dict)", "source": "juraj_google_style"} +{"code": "def _module_info_from_proto_safe(module_info_def, import_scope=None):\n\n try:\n return _module_info_from_proto(module_info_def, import_scope)\n except Exception as e: # pylint: disable=broad-except\n logging.warning(\n \"Error encountered when deserializing sonnet ModuleInfo:\\n%s\", str(e))\n return None", "docstring": "Deserializes the `module_info_def` proto without raising exceptions.\n\nArgs:\n module_info_def: An instance of `module_pb2.SonnetModule`.\n import_scope: Optional `string`. Name scope to use.\n\nReturns:\n An instance of `ModuleInfo`.", "source": "juraj_google_style"} +{"code": "def _make_request(self, url, method=\"get\", data=None, extra_headers=None):\n\n attempts = 0\n\n while attempts < 1:\n # Authenticate first if not authenticated already\n if not self._is_authenticated:\n self._authenticate()\n # Make the request and check for authentication errors\n # This allows us to catch session timeouts for long standing connections\n try:\n return self._send_request(url, method, data, extra_headers)\n except HTTPError as e:\n if e.response.status_code == 403:\n logger.info(\"Authenticated session against NetMRI timed out. Retrying.\")\n self._is_authenticated = False\n attempts += 1\n else:\n # re-raise other HTTP errors\n raise", "docstring": "Prepares the request, checks for authentication and retries in case of issues\n\nArgs:\n url (str): URL of the request\n method (str): Any of \"get\", \"post\", \"delete\"\n data (any): Possible extra data to send with the request\n extra_headers (dict): Possible extra headers to send along in the request\n\nReturns:\n dict", "source": "juraj_google_style"} +{"code": "def handleEvent(self, eventObj):\n\n\n if eventObj.type not in (MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN) or not self.visible:\n # The radioButton only cares bout mouse-related events (or no events, if it is invisible)\n return False\n\n if not self.isEnabled:\n return False\n\n clicked = False\n\n if (not self.mouseOverButton) and self.rect.collidepoint(eventObj.pos):\n # if mouse has entered the radioButton:\n self.mouseOverButton = True\n\n elif self.mouseOverButton and (not self.rect.collidepoint(eventObj.pos)):\n # if mouse has exited the radioButton:\n self.mouseOverButton = False\n\n if self.rect.collidepoint(eventObj.pos):\n\n if eventObj.type == MOUSEBUTTONDOWN:\n self.buttonDown = True\n self.lastMouseDownOverButton = True\n\n else:\n if eventObj.type in (MOUSEBUTTONUP, MOUSEBUTTONDOWN):\n # if an up/down happens off the radioButton, then the next up won't cause mouseClick()\n self.lastMouseDownOverButton = False\n\n if eventObj.type == MOUSEBUTTONDOWN:\n self.mouseIsDown = True\n\n # mouse up is handled whether or not it was over the radioButton\n doMouseClick = False\n if eventObj.type == MOUSEBUTTONUP:\n self.mouseIsDown = False\n if self.lastMouseDownOverButton:\n doMouseClick = True\n self.lastMouseDownOverButton = False\n\n if self.buttonDown:\n self.buttonDown = False\n\n if doMouseClick:\n self.buttonDown = False\n clicked = True\n\n # Turn all radio buttons in this group off\n for radioButton in PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group]:\n radioButton.setValue(False)\n self.setValue(True) # And turn the current one (the one that was clicked) on\n\n if self.playSoundOnClick:\n self.soundOnClick.play()\n\n if clicked:\n if self.callBack is not None:\n self.callBack(self.nickname)\n\n return clicked", "docstring": "This method should be called every time through the main loop.\n\n It handles showing the up, over, and down states of the button.\n\n Parameters:\n | eventObj - the event object obtained by calling pygame.event.get()\n\nReturns:\n | False most of the time\n | True when the user selects a radio button from the group", "source": "juraj_google_style"} +{"code": "def is_link(url, processed, files):\n\n if url not in processed:\n is_file = url.endswith(BAD_TYPES)\n if is_file:\n files.add(url)\n return False\n return True\n return False", "docstring": "Determine whether or not a link should be crawled\n A url should not be crawled if it\n - Is a file\n - Has already been crawled\n\nArgs:\n url: str Url to be processed\n processed: list[str] List of urls that have already been crawled\n\nReturns:\n bool If `url` should be crawled", "source": "juraj_google_style"} +{"code": "def decode_varint(buffer, pos=0):\n\n result = buffer[pos]\n if not (result & 0x81):\n return (result >> 1), pos + 1\n if not (result & 0x80):\n return (result >> 1) ^ (~0), pos + 1\n\n result &= 0x7f\n pos += 1\n shift = 7\n while 1:\n b = buffer[pos]\n result |= ((b & 0x7f) << shift)\n pos += 1\n if not (b & 0x80):\n return ((result >> 1) ^ -(result & 1), pos)\n shift += 7\n if shift >= 64:\n raise ValueError(\"Out of int64 range\")", "docstring": "Decode an integer from a varint presentation. See\n https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints\n on how those can be produced.\n\nArgs:\n buffer (bytearry): buffer to read from.\n pos (int): optional position to read from\n\nReturns:\n (int, int): Decoded int value and next read position", "source": "juraj_google_style"} +{"code": "def processor_coordinates_to_pnum(mesh_shape, coord):\n\n ret = 0\n multiplier = 1\n for c, d in zip(coord[::-1], mesh_shape.to_integer_list[::-1]):\n ret += multiplier * c\n multiplier *= d\n return ret", "docstring": "Inverse of pnum_to_processor_coordinates.\n\nArgs:\n mesh_shape: a Shape\n coord: a list of integers with length len(mesh_shape)\n\nReturns:\n an integer less than len(mesh_shape)", "source": "juraj_google_style"} +{"code": "def load(source, semi=None):\n\n if hasattr(source, 'read'):\n return _load(source, semi)\n else:\n with open(source, 'r') as fh:\n return _load(fh, semi)", "docstring": "Read a variable-property mapping from *source* and return the VPM.\n\nArgs:\n source: a filename or file-like object containing the VPM\n definitions\n semi (:class:`~delphin.mrs.semi.SemI`, optional): if provided,\n it is passed to the VPM constructor\n\nReturns:\n a :class:`VPM` instance", "source": "juraj_google_style"} +{"code": "def peak_signal_to_noise_ratio(true, pred):\n\n return 10.0 * tf.log(1.0 / mean_squared_error(true, pred)) / tf.log(10.0)", "docstring": "Image quality metric based on maximal signal power vs. power of the noise.\n\nArgs:\n true: the ground truth image.\n pred: the predicted image.\n\nReturns:\n peak signal to noise ratio (PSNR)", "source": "juraj_google_style"} +{"code": "def running(processid):\n\n try:\n # From kill(2)\n # If sig is 0 (the null signal), error checking is performed but no\n # signal is actually sent. The null signal can be used to check the\n # validity of pid\n os.kill(processid, 0)\n except OverflowError as exc:\n print(\"checking validity of pid ({p}) failed with: {e}\"\n .format(p=processid, e=exc))\n sys.exit(1)\n except OSError:\n return False\n else:\n return True", "docstring": "Check the validity of a process ID.\n\nArgs:\n processid (int): Process ID number.\n\nReturns:\n True if process ID is found otherwise False.", "source": "juraj_google_style"} +{"code": "def verify_permitted_to_read(gs_path):\n\n # TODO(qimingj): Storage APIs need to be modified to allow absence of project\n # or credential on Items. When that happens we can move the function\n # to Items class.\n from . import _bucket\n bucket, prefix = _bucket.parse_name(gs_path)\n credentials = None\n if datalab.context.Context.is_signed_in():\n credentials = datalab.context._utils.get_credentials()\n args = {\n 'maxResults': Api._MAX_RESULTS,\n 'projection': 'noAcl'\n }\n if prefix is not None:\n args['prefix'] = prefix\n url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, ''))\n try:\n datalab.utils.Http.request(url, args=args, credentials=credentials)\n except datalab.utils.RequestException as e:\n if e.status == 401:\n raise Exception('Not permitted to read from specified path. '\n 'Please sign in and make sure you have read access.')\n raise e", "docstring": "Check if the user has permissions to read from the given path.\n\nArgs:\n gs_path: the GCS path to check if user is permitted to read.\n\nRaises:\n Exception if user has no permissions to read.", "source": "juraj_google_style"} +{"code": "def save(self, recipe):\n\n # test if this is a create vs. an update\n if 'id' in recipe and recipe['id'] is not None:\n # update -> use put op\n self.logger.debug(\"Updating existing recipe: \" + json.dumps(recipe))\n url = '%(base_url)s/recipe/json/%(recipe_id)s' % {\n 'base_url': self.base_url, 'recipe_id': recipe['id']\n }\n r = self.gbdx_connection.put(url, json=recipe)\n try:\n r.raise_for_status()\n except:\n print(r.text)\n raise\n return recipe['id']\n else:\n # create -> use post op\n self.logger.debug(\"Creating new recipe: \" + json.dumps(recipe))\n url = '%(base_url)s/recipe/json' % {\n 'base_url': self.base_url\n }\n r = self.gbdx_connection.post(url, json=recipe)\n try:\n r.raise_for_status()\n except:\n print(r.text)\n raise\n recipe_json = r.json()\n return recipe_json['id']", "docstring": "Saves an AnswerFactory Recipe\n\nArgs:\n recipe (dict): Dictionary specifying a recipe\n\nReturns:\n AnswerFactory Recipe id", "source": "juraj_google_style"} +{"code": "def __parameter_enum(self, param):\n\n if isinstance(param, messages.EnumField):\n return [enum_entry[0] for enum_entry in sorted(\n param.type.to_dict().items(), key=lambda v: v[1])]", "docstring": "Returns enum descriptor of a parameter if it is an enum.\n\n An enum descriptor is a list of keys.\n\nArgs:\n param: A simple field.\n\nReturns:\n The enum descriptor for the field, if it's an enum descriptor, else\n returns None.", "source": "juraj_google_style"} +{"code": "def to_frame(self, **kwargs):\n r\n df = export.write_dataframe(self._values, **kwargs)\n df.name = self.title\n return df", "docstring": "r\"\"\"Return a pandas DataFrame loaded from the worksheet data.\n\nArgs:\n \\**kwargs: passed to ``pandas.read_csv()`` (e.g. ``header``, ``index_col``)\n\nReturns:\n pandas.DataFrame: new ``DataFrame`` instance", "source": "juraj_google_style"} +{"code": "def _ParseValueData(self, knowledge_base, value_data):\n\n if not isinstance(value_data, py2to3.UNICODE_TYPE):\n raise errors.PreProcessFail(\n 'Unsupported Windows Registry value type: {0:s} for '\n 'artifact: {1:s}.'.format(\n type(value_data), self.ARTIFACT_DEFINITION_NAME))\n\n # Map the Windows time zone name to a Python equivalent name.\n lookup_key = value_data.replace(' ', '')\n\n time_zone = time_zones.TIME_ZONES.get(lookup_key, value_data)\n # TODO: check if time zone is set in knowledge base.\n if time_zone:\n try:\n # Catch and warn about unsupported preprocessor plugin.\n knowledge_base.SetTimeZone(time_zone)\n except ValueError:\n # TODO: add and store preprocessing errors.\n time_zone = value_data\n logger.warning('Unable to map: \"{0:s}\" to time zone'.format(\n value_data))", "docstring": "Parses Windows Registry value data for a preprocessing attribute.\n\nArgs:\n knowledge_base (KnowledgeBase): to fill with preprocessing information.\n value_data (object): Windows Registry value data.\n\nRaises:\n errors.PreProcessFail: if the preprocessing fails.", "source": "juraj_google_style"} +{"code": "def del_rules(cls, *names, attr=None):\n\n if attr is None:\n attr = cls._rules_attr()\n if len(names) == 0:\n getattr(cls, attr) # raise AttributeError if wrong attr\n setattr(cls, attr, OrderedDict())\n else:\n for name in names:\n del getattr(cls, attr)[name]", "docstring": "Delete algebraic rules used by :meth:`create`\n\n Remove the rules with the given `names`, or all rules if no names are\n given\n\nArgs:\n names (str): Names of rules to delete\n attr (None or str): Name of the class attribute from which to\n delete the rules. Cf. :meth:`add_rule`.\n\nRaises:\n KeyError: If any rules in `names` does not exist\n AttributeError: If invalid `attr`", "source": "juraj_google_style"} +{"code": "def insert(self, index, item):\n\n if not self:\n list.append(self, item)\n elif item.__class__ == self[0].__class__:\n list.insert(self, index, item)\n else:\n raise exceptions.WrongListItemType(item.__class__.__name__,\n self[0].__class__.__name__)", "docstring": "Insert an item at the specified index.\n\nArgs:\n index (int): Position to insert the item.\n item: Item to be inserted.\n\nRaises:\n :exc:`~.exceptions.WrongListItemType`: If an item has a different\n type than the first item to be stored.", "source": "juraj_google_style"} +{"code": "def list_lb_nat_rules(access_token, subscription_id, resource_group, lb_name):\n\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourceGroups/', resource_group,\n '/providers/Microsoft.Network/loadBalancers/', lb_name,\n 'inboundNatRules?api-version=', NETWORK_API])\n return do_get(endpoint, access_token)", "docstring": "List the inbound NAT rules for a load balancer.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n resource_group (str): Azure resource group name.\n lb_name (str): Name of the load balancer.\n\nReturns:\n HTTP response. JSON body of load balancer NAT rules.", "source": "juraj_google_style"} +{"code": "def read_data_event(self, whence, complete=False, can_flush=False):\n\n return Transition(None, _read_data_handler(whence, self, complete, can_flush))", "docstring": "Creates a transition to a co-routine for retrieving data as bytes.\n\nArgs:\n whence (Coroutine): The co-routine to return to after the data is satisfied.\n complete (Optional[bool]): True if STREAM_END should be emitted if no bytes are read or\n available; False if INCOMPLETE should be emitted in that case.\n can_flush (Optional[bool]): True if NEXT may be requested after INCOMPLETE is emitted as a result of this\n data request.", "source": "juraj_google_style"} +{"code": "def bind_sockets(address, port):\n\n ss = netutil.bind_sockets(port=port or 0, address=address)\n assert len(ss)\n ports = {s.getsockname()[1] for s in ss}\n assert len(ports) == 1, \"Multiple ports assigned??\"\n actual_port = ports.pop()\n if port:\n assert actual_port == port\n return ss, actual_port", "docstring": "Bind a socket to a port on an address.\n\nArgs:\n address (str) :\n An address to bind a port on, e.g. ``\"localhost\"``\n\n port (int) :\n A port number to bind.\n\n Pass 0 to have the OS automatically choose a free port.\n\n This function returns a 2-tuple with the new socket as the first element,\n and the port that was bound as the second. (Useful when passing 0 as a port\n number to bind any free port.)\n\nReturns:\n (socket, port)", "source": "juraj_google_style"} +{"code": "def get_testcase_io(testcase):\n\n test_runner = testcase.runner\n variables = testcase.config.get(\"variables\", {})\n output_list = testcase.config.get(\"output\", [])\n output_mapping = test_runner.extract_output(output_list)\n\n return {\n \"in\": variables,\n \"out\": output_mapping\n }", "docstring": "get and print testcase input(variables) and output.\n\nArgs:\n testcase (unittest.suite.TestSuite): corresponding to one YAML/JSON file, it has been set two attributes:\n config: parsed config block\n runner: initialized runner.Runner() with config\n\nReturns:\n dict: input(variables) and output mapping.", "source": "juraj_google_style"} +{"code": "def _make_query_from_terms(self, terms):\n\n\n match_query = ''\n\n expanded_terms = self._expand_terms(terms)\n if expanded_terms['doc']:\n match_query = self.backend._and_join(expanded_terms['doc'])\n\n if expanded_terms['keywords']:\n if match_query:\n match_query = self.backend._and_join(\n [match_query, self.backend._join_keywords(expanded_terms['keywords'])])\n else:\n match_query = self.backend._join_keywords(expanded_terms['keywords'])\n\n if match_query:\n query = text()\n query_params = {\n 'match_query': match_query}\n else:\n query = text()\n query_params = {}\n\n return query, query_params", "docstring": "Creates a query for partition from decomposed search terms.\n\nArgs:\n terms (dict or unicode or string):\n\nReturns:\n tuple of (str, dict): First element is str with FTS query, second is parameters of the query.", "source": "juraj_google_style"} +{"code": "def _CreateLineString(self, parent, coordinate_list):\n\n if not coordinate_list:\n return None\n linestring = ET.SubElement(parent, 'LineString')\n tessellate = ET.SubElement(linestring, 'tessellate')\n tessellate.text = '1'\n if len(coordinate_list[0]) == 3:\n altitude_mode = ET.SubElement(linestring, 'altitudeMode')\n altitude_mode.text = 'absolute'\n coordinates = ET.SubElement(linestring, 'coordinates')\n if len(coordinate_list[0]) == 3:\n coordinate_str_list = ['%f,%f,%f' % t for t in coordinate_list]\n else:\n coordinate_str_list = ['%f,%f' % t for t in coordinate_list]\n coordinates.text = ' '.join(coordinate_str_list)\n return linestring", "docstring": "Create a KML LineString element.\n\n The points of the string are given in coordinate_list. Every element of\n coordinate_list should be one of a tuple (longitude, latitude) or a tuple\n (longitude, latitude, altitude).\n\nArgs:\n parent: The parent ElementTree.Element instance.\n coordinate_list: The list of coordinates.\n\nReturns:\n The LineString ElementTree.Element instance or None if coordinate_list is\n empty.", "source": "juraj_google_style"} +{"code": "def __init__(self, value, method=Method.PREFIX):\n\n self.value = value\n self.method = method", "docstring": "Init method.\n\nArgs:\n value (str): value to match.\n method (const): Method constant, matching method.", "source": "juraj_google_style"} +{"code": "def load_disease_term(self, disease_obj):\n\n LOG.debug(\"Loading disease term %s into database\", disease_obj['_id'])\n try:\n self.disease_term_collection.insert_one(disease_obj)\n except DuplicateKeyError as err:\n raise IntegrityError(\"Disease term %s already exists in database\".format(disease_obj['_id']))\n\n LOG.debug(\"Disease term saved\")", "docstring": "Load a disease term into the database\n\nArgs:\n disease_obj(dict)", "source": "juraj_google_style"} +{"code": "def observe_reward_value(self, state_key, action_key):\n\n reward_value = 0.0\n if state_key in self.__state_action_list_dict:\n if action_key in self.__state_action_list_dict[state_key]:\n reward_value = 1.0\n\n return reward_value", "docstring": "Compute the reward value.\n\nArgs:\n state_key: The key of state.\n action_key: The key of action.\n\nReturns:\n Reward value.", "source": "juraj_google_style"} +{"code": "def __init__(self, keys=None):\n\n if not keys:\n raise errors.FormatError('Missing keys value.')\n\n if not isinstance(keys, list):\n raise errors.FormatError('keys must be a list')\n\n for key in keys:\n self.ValidateKey(key)\n\n super(WindowsRegistryKeySourceType, self).__init__()\n self.keys = keys", "docstring": "Initializes a source type.\n\nArgs:\n keys (Optional[list[str]]): key paths relative to the root of\n the Windows Registry.\n\nRaises:\n FormatError: when keys is not set.", "source": "juraj_google_style"} +{"code": "def retry_api_check(exception):\n\n if isinstance(exception, apiclient.errors.HttpError):\n if exception.resp.status in TRANSIENT_HTTP_ERROR_CODES:\n _print_error('Retrying...')\n return True\n\n if isinstance(exception, socket.error):\n if exception.errno in TRANSIENT_SOCKET_ERROR_CODES:\n _print_error('Retrying...')\n return True\n\n if isinstance(exception, oauth2client.client.AccessTokenRefreshError):\n _print_error('Retrying...')\n return True\n\n # For a given installation, this could be a permanent error, but has only\n # been observed as transient.\n if isinstance(exception, SSLError):\n _print_error('Retrying...')\n return True\n\n # This has been observed as a transient error:\n # ServerNotFoundError: Unable to find the server at genomics.googleapis.com\n if isinstance(exception, ServerNotFoundError):\n _print_error('Retrying...')\n return True\n\n return False", "docstring": "Return True if we should retry. False otherwise.\n\nArgs:\n exception: An exception to test for transience.\n\nReturns:\n True if we should retry. False otherwise.", "source": "juraj_google_style"} +{"code": "def _attempt_shard_retry(self, shard_state, tstate):\n\n shard_attempts = shard_state.retries + 1\n\n if shard_attempts >= parameters.config.SHARD_MAX_ATTEMPTS:\n logging.warning(\n \"Shard attempt %s exceeded %s max attempts.\",\n shard_attempts, parameters.config.SHARD_MAX_ATTEMPTS)\n return self._TASK_DIRECTIVE.FAIL_TASK\n if tstate.output_writer and (\n not tstate.output_writer._supports_shard_retry(tstate)):\n logging.warning(\"Output writer %s does not support shard retry.\",\n tstate.output_writer.__class__.__name__)\n return self._TASK_DIRECTIVE.FAIL_TASK\n\n shard_state.reset_for_retry()\n logging.warning(\"Shard %s attempt %s failed with up to %s attempts.\",\n shard_state.shard_id,\n shard_state.retries,\n parameters.config.SHARD_MAX_ATTEMPTS)\n output_writer = None\n if tstate.output_writer:\n output_writer = tstate.output_writer.create(\n tstate.mapreduce_spec, shard_state.shard_number, shard_attempts + 1)\n tstate.reset_for_retry(output_writer)\n return self._TASK_DIRECTIVE.RETRY_SHARD", "docstring": "Whether to retry shard.\n\n This method may modify shard_state and tstate to prepare for retry or fail.\n\nArgs:\n shard_state: model.ShardState for current shard.\n tstate: model.TransientShardState for current shard.\n\nReturns:\n A _TASK_DIRECTIVE enum. RETRY_SHARD if shard should be retried.\n FAIL_TASK otherwise.", "source": "juraj_google_style"} +{"code": "def transform_qubits(self: TSelf_Operation,\n func: Callable[[Qid], Qid]) -> TSelf_Operation:\n\n return self.with_qubits(*(func(q) for q in self.qubits))", "docstring": "Returns the same operation, but with different qubits.\n\nArgs:\n func: The function to use to turn each current qubit into a desired\n new qubit.\n\nReturns:\n The receiving operation but with qubits transformed by the given\n function.", "source": "juraj_google_style"} +{"code": "def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,\n index):\n\n full_name = '.'.join((service_name, method_proto.name))\n input_type = self._GetTypeFromScope(\n package, method_proto.input_type, scope)\n output_type = self._GetTypeFromScope(\n package, method_proto.output_type, scope)\n return descriptor.MethodDescriptor(name=method_proto.name,\n full_name=full_name,\n index=index,\n containing_service=None,\n input_type=input_type,\n output_type=output_type,\n options=_OptionsOrNone(method_proto))", "docstring": "Creates a method descriptor from a MethodDescriptorProto.\n\nArgs:\n method_proto: The proto describing the method.\n service_name: The name of the containing service.\n package: Optional package name to look up for types.\n scope: Scope containing available types.\n index: Index of the method in the service.\n\nReturns:\n An initialized MethodDescriptor object.", "source": "juraj_google_style"} +{"code": "def CmyToCmyk(c, m, y):\n\n k = min(c, m, y)\n if k==1.0: return (0.0, 0.0, 0.0, 1.0)\n mk = 1-k\n return ((c-k) / mk, (m-k) / mk, (y-k) / mk, k)", "docstring": "Convert the color from CMY coordinates to CMYK.\n\n Parameters:\n :c:\n The Cyan component value [0...1]\n :m:\n The Magenta component value [0...1]\n :y:\n The Yellow component value [0...1]\n\nReturns:\n The color as an (c, m, y, k) tuple in the range:\n c[0...1],\n m[0...1],\n y[0...1],\n k[0...1]\n\n >>> '(%g, %g, %g, %g)' % Color.CmyToCmyk(1, 0.66, 0.5)\n '(1, 0.32, 0, 0.5)'", "source": "juraj_google_style"} +{"code": "def __getitem__(self, key):\n\n if key in self.patterns:\n return ScreenPattern(self.patterns[key], self.field_registry)\n for shorter in range(key, 0, -1):\n if shorter in self.min_patterns:\n pattern = self.min_patterns[shorter]\n\n # Try to vertically center the pattern\n prefix = [''] * (key - shorter / 2)\n return ScreenPattern(prefix + pattern, self.field_registry)\n return ScreenPattern([], self.field_registry)", "docstring": "Retrieve the best pattern for a given size.\n\n The algorithm is:\n - If a pattern is registered for the size, use it\n - Otherwise, find the longest registered pattern shorter thant size, add\n some blank lines before, and return it\n - If no shorter pattern exist, return a blank pattern.\n\nArgs:\n key (int): the target size\n\nReturns:\n ScreenPattern: the best pattern available for that size", "source": "juraj_google_style"} +{"code": "def apply_activation(\n books,\n x,\n activation,\n activation_args=(),\n activation_kwargs=None):\n\n if activation is None:\n return x\n if activation_kwargs is None:\n activation_kwargs = {}\n y = activation(x, *activation_args, **activation_kwargs)\n if activation in (tf.nn.relu, functions.leaky_relu, functions.softplus):\n books.add_scalar_summary(\n tf.reduce_mean(tf.cast(tf.less(x, 0.0), tf.float32)),\n '%s/zeros' % y.op.name)\n elif activation is tf.nn.relu6:\n books.add_scalar_summary(\n tf.reduce_mean(tf.cast(tf.less(x, 0.0), tf.float32)),\n '%s/zeros' % y.op.name)\n books.add_scalar_summary(\n tf.reduce_mean(tf.cast(tf.greater(x, 6.0), tf.float32)),\n '%s/sixes' % y.op.name)\n elif activation in (functions.l2_normalize, tf.nn.l2_normalize,\n functions.l1_normalize):\n books.add_scalar_summary(\n tf.reduce_mean(tf.sqrt(tf.reduce_sum(\n tf.square(x), 1))), '%s/length' % y.op.name)\n return y", "docstring": "Returns activation(x, *activation_args, **activation_kwargs).\n\n This applies the given activation and adds useful summaries specific to the\n activation.\n\nArgs:\n books: The bookkeeper.\n x: The tensor to apply activation to.\n activation: An activation function.\n activation_args: Optional additional arguments for the activation.\n activation_kwargs: Optional keyword args for activation.\n\nReturns:\n A tensor with activation applied to x.", "source": "juraj_google_style"} +{"code": "def create_checksum_object_from_bytes(\n b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM\n):\n\n checksum_str = calculate_checksum_on_bytes(b, algorithm)\n checksum_pyxb = d1_common.types.dataoneTypes.checksum(checksum_str)\n checksum_pyxb.algorithm = algorithm\n return checksum_pyxb", "docstring": "Calculate the checksum of ``bytes``.\n\n Warning:\n This method requires the entire object to be buffered in (virtual) memory, which\n should normally be avoided in production code.\n\nArgs:\n b: bytes\n Raw bytes\n\n algorithm: str\n Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.\n\nReturns:\n Populated PyXB Checksum object.", "source": "juraj_google_style"} +{"code": "def expand_tile(units, axis):\n\n assert axis in (1, 2)\n n_time_steps = tf.shape(units)[1]\n repetitions = [1, 1, 1, 1]\n repetitions[axis] = n_time_steps\n return tf.tile(tf.expand_dims(units, axis), repetitions)", "docstring": "Expand and tile tensor along given axis\n\nArgs:\n units: tf tensor with dimensions [batch_size, time_steps, n_input_features]\n axis: axis along which expand and tile. Must be 1 or 2", "source": "juraj_google_style"} +{"code": "def url(self, url):\n\n self._request.url = url\n self.add_matcher(matcher('URLMatcher', url))", "docstring": "Defines the mock URL to match.\n It can be a full URL with path and query params.\n\n Protocol schema is optional, defaults to ``http://``.\n\nArgs:\n url (str): mock URL to match. E.g: ``server.com/api``.\n\nReturns:\n self: current Mock instance.", "source": "juraj_google_style"} +{"code": "def __init__(self,\n application,\n project_id,\n control_client,\n next_operation_id=_next_operation_uuid,\n timer=datetime.utcnow):\n\n self._application = application\n self._project_id = project_id\n self._control_client = control_client\n self._next_operation_id = next_operation_id\n self._timer = timer", "docstring": "Initializes a new Middleware instance.\n\nArgs:\n application: the wrapped wsgi application\n project_id: the project_id thats providing service control support\n control_client: the service control client instance\n next_operation_id (func): produces the next operation\n timer (func[[datetime.datetime]]): a func that obtains the current time", "source": "juraj_google_style"} +{"code": "def get_logger(name):\n\n logger = logging.getLogger(name)\n logger.addHandler(logging.NullHandler())\n return logger", "docstring": "Gets a logger\n\nArgs:\n name - the name you wish to log as\n\nReturns:\n A logger!", "source": "juraj_google_style"} +{"code": "def from_path(cls, path):\n\n stat_res = os.stat(path)\n return cls.from_int(stat.S_IMODE(stat_res.st_mode))", "docstring": "Make a new :class:`FilePerms` object based on the permissions\n assigned to the file or directory at *path*.\n\nArgs:\n path (str): Filesystem path of the target file.\n\n >>> from os.path import expanduser\n >>> 'r' in FilePerms.from_path(expanduser('~')).user # probably\n True", "source": "juraj_google_style"} +{"code": "def load(self, steps_dir=None, step_file=None, step_list=None):\n\n self._closed()\n\n self.steps_library.load(steps_dir=steps_dir, step_file=step_file,\n step_list=step_list)", "docstring": "Load CWL steps into the WorkflowGenerator's steps library.\n\n Adds steps (command line tools and workflows) to the\n ``WorkflowGenerator``'s steps library. These steps can be used to\n create workflows.\n\nArgs:\n steps_dir (str): path to directory containing CWL files. All CWL in\n the directory are loaded.\n step_file (str): path to a file containing a CWL step that will be\n added to the steps library.", "source": "juraj_google_style"} +{"code": "def WriteSignedBinaryBlobs(binary_urn,\n blobs,\n token = None):\n\n if _ShouldUseLegacyDatastore():\n aff4.FACTORY.Delete(binary_urn, token=token)\n with data_store.DB.GetMutationPool() as mutation_pool:\n with aff4.FACTORY.Create(\n binary_urn,\n collects.GRRSignedBlob,\n mode=\"w\",\n mutation_pool=mutation_pool,\n token=token) as fd:\n for blob in blobs:\n fd.Add(blob, mutation_pool=mutation_pool)\n\n if data_store.RelationalDBEnabled():\n blob_references = rdf_objects.BlobReferences()\n current_offset = 0\n for blob in blobs:\n blob_id = data_store.BLOBS.WriteBlobWithUnknownHash(\n blob.SerializeToString())\n blob_references.items.Append(\n rdf_objects.BlobReference(\n offset=current_offset, size=len(blob.data), blob_id=blob_id))\n current_offset += len(blob.data)\n data_store.REL_DB.WriteSignedBinaryReferences(\n _SignedBinaryIDFromURN(binary_urn), blob_references)", "docstring": "Saves signed blobs to the datastore.\n\n If a signed binary with the given URN already exists, its contents will get\n overwritten.\n\nArgs:\n binary_urn: RDFURN that should serve as a unique identifier for the binary.\n blobs: An Iterable of signed blobs to write to the datastore.\n token: ACL token to use with the legacy (non-relational) datastore.", "source": "juraj_google_style"} +{"code": "def parse_lammps_dumps(file_pattern):\n\n files = glob.glob(file_pattern)\n if len(files) > 1:\n pattern = r\"%s\" % file_pattern.replace(\"*\", \"([0-9]+)\")\n pattern = pattern.replace(\"\\\\\", \"\\\\\\\\\")\n files = sorted(files,\n key=lambda f: int(re.match(pattern, f).group(1)))\n\n for fname in files:\n with zopen(fname, \"rt\") as f:\n dump_cache = []\n for line in f:\n if line.startswith(\"ITEM: TIMESTEP\"):\n if len(dump_cache) > 0:\n yield LammpsDump.from_string(\"\".join(dump_cache))\n dump_cache = [line]\n else:\n dump_cache.append(line)\n yield LammpsDump.from_string(\"\".join(dump_cache))", "docstring": "Generator that parses dump file(s).\n\nArgs:\n file_pattern (str): Filename to parse. The timestep wildcard\n (e.g., dump.atom.'*') is supported and the files are parsed\n in the sequence of timestep.\n\nYields:\n LammpsDump for each available snapshot.", "source": "juraj_google_style"} +{"code": "def ParseArguments(args):\n\n try:\n (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',\n 'counting=',\n 'filter=',\n 'root=',\n 'repository=',\n 'linelength=',\n 'extensions=',\n 'exclude=',\n 'headers=',\n 'quiet',\n 'recursive'])\n except getopt.GetoptError:\n PrintUsage('Invalid arguments.')\n\n verbosity = _VerboseLevel()\n output_format = _OutputFormat()\n filters = ''\n counting_style = ''\n recursive = False\n\n for (opt, val) in opts:\n if opt == '--help':\n PrintUsage(None)\n elif opt == '--output':\n if val not in ('emacs', 'vs7', 'eclipse', 'junit'):\n PrintUsage('The only allowed output formats are emacs, vs7, eclipse '\n 'and junit.')\n output_format = val\n elif opt == '--verbose':\n verbosity = int(val)\n elif opt == '--filter':\n filters = val\n if not filters:\n PrintCategories()\n elif opt == '--counting':\n if val not in ('total', 'toplevel', 'detailed'):\n PrintUsage('Valid counting options are total, toplevel, and detailed')\n counting_style = val\n elif opt == '--root':\n global _root\n _root = val\n elif opt == '--repository':\n global _repository\n _repository = val\n elif opt == '--linelength':\n global _line_length\n try:\n _line_length = int(val)\n except ValueError:\n PrintUsage('Line length must be digits.')\n elif opt == '--exclude':\n global _excludes\n if not _excludes:\n _excludes = set()\n _excludes.update(glob.glob(val))\n elif opt == '--extensions':\n global _valid_extensions\n try:\n _valid_extensions = set(val.split(','))\n except ValueError:\n PrintUsage('Extensions must be comma seperated list.')\n elif opt == '--headers':\n global _header_extensions\n try:\n _header_extensions = set(val.split(','))\n except ValueError:\n PrintUsage('Extensions must be comma seperated list.')\n elif opt == '--recursive':\n recursive = True\n elif opt == '--quiet':\n global _quiet\n _quiet = True\n\n if not filenames:\n PrintUsage('No files were specified.')\n\n if recursive:\n filenames = _ExpandDirectories(filenames)\n\n if _excludes:\n filenames = _FilterExcludedFiles(filenames)\n\n _SetOutputFormat(output_format)\n _SetVerboseLevel(verbosity)\n _SetFilters(filters)\n _SetCountingStyle(counting_style)\n\n return filenames", "docstring": "Parses the command line arguments.\n\n This may set the output format and verbosity level as side-effects.\n\nArgs:\n args: The command line arguments:\n\nReturns:\n The list of filenames to lint.", "source": "juraj_google_style"} +{"code": "def FromDictionary(cls, msg_dict):\n\n\n level = msg_dict.get('level')\n msg = msg_dict.get('message')\n now = msg_dict.get('now_time')\n created = msg_dict.get('created_time')\n count = msg_dict.get('count', 1)\n msg_id = msg_dict.get('id', 0)\n\n new_msg = ServiceMessage(level, msg, msg_id, created, now)\n if count > 1:\n new_msg.count = count\n\n return new_msg", "docstring": "Create from a dictionary with kv pairs.\n\nArgs:\n msg_dict (dict): A dictionary with information as created by to_dict()\n\nReturns:\n ServiceMessage: the converted message", "source": "juraj_google_style"} +{"code": "def output(self, stream, value):\n\n if stream not in self.outputs:\n raise ValueError(\"Stream is not an output of this operator.\")\n e = self.expression(value)\n e._stream = stream\n return e", "docstring": "SPL output port assignment expression.\n\nArgs:\n stream(Stream): Output stream the assignment is for.\n value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.\n\nReturns:\n Expression: Output assignment expression that is valid as a the context of this operator.", "source": "juraj_google_style"} +{"code": "def ub_to_str(string):\n\n if not isinstance(string, str):\n if six.PY2:\n return str(string)\n else:\n return string.decode()\n return string", "docstring": "converts py2 unicode / py3 bytestring into str\n\nArgs:\n string (unicode, byte_string): string to be converted\n\nReturns:\n (str)", "source": "juraj_google_style"} +{"code": "def expand_docstring(**kwargs):\n\n def _fn_wrapped(fn):\n\n doc = inspect.cleandoc(fn.__doc__)\n for k, v in six.iteritems(kwargs):\n # Capture each ${k} reference to replace with v.\n # We wrap the replacement in a function so no backslash escapes\n # are processed.\n pattern = r'\\$\\{' + str(k) + r'\\}'\n doc = re.sub(pattern, lambda match: v, doc) # pylint: disable=cell-var-from-loop\n fn.__doc__ = doc\n return fn\n return _fn_wrapped", "docstring": "Decorator to programmatically expand the docstring.\n\nArgs:\n **kwargs: Keyword arguments to set. For each key-value pair `k` and `v`,\n the key is found as `${k}` in the docstring and replaced with `v`.\n\nReturns:\n Decorated function.", "source": "juraj_google_style"} +{"code": "def get_iso3_country_code(cls, country, use_live=True, exception=None):\n # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]\n\n countriesdata = cls.countriesdata(use_live=use_live)\n countryupper = country.upper()\n len_countryupper = len(countryupper)\n if len_countryupper == 3:\n if countryupper in countriesdata['countries']:\n return countryupper\n elif len_countryupper == 2:\n iso3 = countriesdata['iso2iso3'].get(countryupper)\n if iso3 is not None:\n return iso3\n\n iso3 = countriesdata['countrynames2iso3'].get(countryupper)\n if iso3 is not None:\n return iso3\n\n for candidate in cls.expand_countryname_abbrevs(countryupper):\n iso3 = countriesdata['countrynames2iso3'].get(candidate)\n if iso3 is not None:\n return iso3\n\n if exception is not None:\n raise exception\n return None", "docstring": "Get ISO3 code for cls. Only exact matches or None are returned.\n\nArgs:\n country (str): Country for which to get ISO3 code\n use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.\n\nReturns:\n Optional[str]: ISO3 country code or None", "source": "juraj_google_style"} +{"code": "def get_size(self, value=None):\n\n if value is None:\n if not self:\n # If this is a empty list, then returns zero\n return 0\n elif issubclass(type(self[0]), GenericType):\n # If the type of the elements is GenericType, then returns the\n # length of the list multiplied by the size of the GenericType.\n return len(self) * self[0].get_size()\n\n # Otherwise iter over the list accumulating the sizes.\n return sum(item.get_size() for item in self)\n\n return type(self)(value).get_size()", "docstring": "Return the size in bytes.\n\nArgs:\n value: In structs, the user can assign other value instead of\n this class' instance. Here, in such cases, ``self`` is a class\n attribute of the struct.\n\nReturns:\n int: The size in bytes.", "source": "juraj_google_style"} +{"code": "def service_registry(self, sr):\n\n if type(sr) is not EFServiceRegistry:\n raise TypeError(\"sr value must be type 'EFServiceRegistry'\")\n self._service_registry = sr", "docstring": "Sets service registry object in context, doesn't check it\n\nArgs:\n sr: EFServiceRegistry object", "source": "juraj_google_style"} +{"code": "def remove_all_logger_handlers(logger: logging.Logger) -> None:\n\n while logger.handlers:\n h = logger.handlers[0]\n logger.removeHandler(h)", "docstring": "Remove all handlers from a logger.\n\nArgs:\n logger: logger to modify", "source": "juraj_google_style"} +{"code": "def with_organisation(self, organisation):\n\n if organisation is None:\n organisation = ''\n organisation = slugify(organisation)\n self._validate_organisation(organisation)\n self.organisation = organisation\n return self", "docstring": "Add an organisation segment.\n\nArgs:\n organisation (str): Official name of an administrative body\n holding an election.\n\nReturns:\n IdBuilder\n\nRaises:\n ValueError", "source": "juraj_google_style"} +{"code": "def get_dirty_items(item_list, flag_list):\n\n assert len(item_list) == len(flag_list)\n dirty_items = [item for (item, flag) in\n zip(item_list, flag_list)\n if not flag]\n #print('num_dirty_items = %r' % len(dirty_items))\n #print('item_list = %r' % (item_list,))\n #print('flag_list = %r' % (flag_list,))\n return dirty_items", "docstring": "Returns each item in item_list where not flag in flag_list\n\nArgs:\n item_list (list):\n flag_list (list):\n\nReturns:\n dirty_items", "source": "juraj_google_style"} +{"code": "def get_items(self, page=1, order_by=None, filters=None):\n\n start = (page-1)*self.per_page\n query = self.get_query()\n if order_by is not None:\n query = query.order_by(self._get_field(order_by))\n if filters is not None:\n query = self._filter(query, filters)\n return query.offset(start).limit(self.per_page), self.count(query)", "docstring": "Fetch database for items matching.\n\nArgs:\n page (int):\n which page will be sliced\n slice size is ``self.per_page``.\n order_by (str):\n a field name to order query by.\n filters (dict):\n a ``filter name``: ``value`` dict.\n\nReturns:\n tuple with:\n items, sliced by page*self.per_page\n total items without slice", "source": "juraj_google_style"} +{"code": "def __init__(self, enterprise_configuration, client=SAPSuccessFactorsAPIClient):\n\n self.enterprise_configuration = enterprise_configuration\n self.client = client(enterprise_configuration) if client else None", "docstring": "Use the ``SAPSuccessFactorsAPIClient`` for content metadata transmission to SAPSF.\n\nArgs:\n enterprise_configuration (required): SAPSF configuration connecting an enterprise to an integrated channel.\n client: The REST API client that will fetch data from integrated channel.", "source": "juraj_google_style"} +{"code": "def call_for_each_tower(\n towers, func, devices=None, use_vs=None):\n\n\n ret = []\n if devices is not None:\n assert len(devices) == len(towers)\n if use_vs is not None:\n assert len(use_vs) == len(towers)\n\n tower_names = ['tower{}'.format(idx) for idx in range(len(towers))]\n\n for idx, t in enumerate(towers):\n device = devices[idx] if devices is not None else '/gpu:{}'.format(t)\n usevs = use_vs[idx] if use_vs is not None else False\n reuse = not usevs and idx > 0\n with tfv1.device(device), _maybe_reuse_vs(reuse), TrainTowerContext(\n tower_names[idx],\n vs_name=tower_names[idx] if usevs else '',\n index=idx, total=len(towers)):\n if len(str(device)) < 10: # a device function doesn't have good string description\n logger.info(\"Building graph for training tower {} on device {} ...\".format(idx, device))\n else:\n logger.info(\"Building graph for training tower {} ...\".format(idx))\n\n # When use_vs is True, use LOCAL_VARIABLES,\n # so these duplicated variables won't be saved by default.\n with override_to_local_variable(enable=usevs):\n ret.append(func())\n return ret", "docstring": "Run `func` on all GPUs (towers) and return the results.\n\nArgs:\n towers (list[int]): a list of GPU id.\n func: a lambda to be called inside each tower\n devices: a list of devices to be used. By default will use '/gpu:{tower}'\n use_vs (list[bool]): list of use_vs to passed to TowerContext\n\nReturns:\n List of outputs of ``func``, evaluated on each tower.", "source": "juraj_google_style"} +{"code": "def Columns(iterable):\n\n columns = sorted(iterable)\n return \"({})\".format(\", \".join(\"`{}`\".format(col) for col in columns))", "docstring": "Returns a string of column names for MySQL INSERTs.\n\n To account for Iterables with undefined order (dicts before Python 3.6),\n this function sorts column names.\n\nExample:\n >>> Columns({\"password\": \"foo\", \"name\": \"bar\"})\n u'(`name`, `password`)'\n\nArgs:\n iterable: The iterable of strings to be used as column names.\n Returns: A string containing a tuple of sorted comma-separated column names.", "source": "juraj_google_style"} +{"code": "def ssh(cmd=''):\n\n with settings(warn_only=True):\n local('ssh -A -o StrictHostKeyChecking=no -i \"%s\" %s@%s \"%s\"' % (\n env.key_filename, env.user, env.host, cmd))", "docstring": "SSH into the server(s) (sequentially if more than one)\n\nArgs:\n cmd (str) ='': Command to run on the server", "source": "juraj_google_style"} +{"code": "def set_processed_counts(self, shards_processed, shards_status):\n\n chart = google_chart_api.BarChart()\n\n def filter_status(status_to_filter):\n return [count if status == status_to_filter else 0\n for count, status in zip(shards_processed, shards_status)]\n\n if shards_status:\n # Each index will have only one non-zero count, so stack them to color-\n # code the bars by status\n # These status values are computed in _update_state_from_shard_states,\n # in mapreduce/handlers.py.\n chart.stacked = True\n chart.AddBars(filter_status(\"unknown\"), color=\"404040\")\n chart.AddBars(filter_status(\"success\"), color=\"00ac42\")\n chart.AddBars(filter_status(\"running\"), color=\"3636a9\")\n chart.AddBars(filter_status(\"aborted\"), color=\"e29e24\")\n chart.AddBars(filter_status(\"failed\"), color=\"f6350f\")\n else:\n chart.AddBars(shards_processed)\n\n shard_count = len(shards_processed)\n\n if shard_count > 95:\n # Auto-spacing does not work for large numbers of shards.\n pixels_per_shard = 700.0 / shard_count\n bar_thickness = int(pixels_per_shard * .9)\n\n chart.style = bar_chart.BarChartStyle(bar_thickness=bar_thickness,\n bar_gap=0.1, use_fractional_gap_spacing=True)\n\n if shards_processed and shard_count <= 95:\n # Adding labels puts us in danger of exceeding the URL length, only\n # do it when we have a small amount of data to plot.\n # Only 16 labels on the whole chart.\n stride_length = max(1, shard_count / 16)\n chart.bottom.labels = []\n for x in xrange(shard_count):\n if (x % stride_length == 0 or\n x == shard_count - 1):\n chart.bottom.labels.append(x)\n else:\n chart.bottom.labels.append(\"\")\n chart.left.labels = [\"0\", str(max(shards_processed))]\n chart.left.min = 0\n\n self.chart_width = min(700, max(300, shard_count * 20))\n self.chart_url = chart.display.Url(self.chart_width, 200)", "docstring": "Updates a chart url to display processed count for each shard.\n\nArgs:\n shards_processed: list of integers with number of processed entities in\n each shard", "source": "juraj_google_style"} +{"code": "def list_filepaths(self, wildcard=None):\n\n # Select the files in the directory.\n fnames = [f for f in os.listdir(self.path)]\n filepaths = filter(os.path.isfile, [os.path.join(self.path, f) for f in fnames])\n\n # Filter using the shell patterns.\n if wildcard is not None:\n filepaths = WildCard(wildcard).filter(filepaths)\n\n return filepaths", "docstring": "Return the list of absolute filepaths in the directory.\n\nArgs:\n wildcard: String of tokens separated by \"|\". Each token represents a pattern.\n If wildcard is not None, we return only those files that match the given shell pattern (uses fnmatch).\n\nExample:\n wildcard=\"*.nc|*.pdf\" selects only those files that end with .nc or .pdf", "source": "juraj_google_style"} +{"code": "def fit(self, X):\n\n\n self.constant_value = self._get_constant_value(X)\n\n if self.constant_value is None:\n self.model = scipy.stats.gaussian_kde(X)\n\n else:\n self._replace_constant_methods()\n\n self.fitted = True", "docstring": "Fit Kernel density estimation to an list of values.\n\nArgs:\n X: 1-d `np.ndarray` or `pd.Series` or `list` datapoints to be estimated from.\n\n This function will fit a gaussian_kde model to a list of datapoints\n and store it as a class attribute.", "source": "juraj_google_style"} +{"code": "def add_chapter(self, c):\n\n try:\n assert type(c) == chapter.Chapter\n except AssertionError:\n raise TypeError('chapter must be of type Chapter')\n chapter_file_output = os.path.join(self.OEBPS_DIR, self.current_chapter_path)\n c._replace_images_in_chapter(self.OEBPS_DIR)\n c.write(chapter_file_output)\n self._increase_current_chapter_number()\n self.chapters.append(c)", "docstring": "Add a Chapter to your epub.\n\nArgs:\n c (Chapter): A Chapter object representing your chapter.\n\nRaises:\n TypeError: Raised if a Chapter object isn't supplied to this\n method.", "source": "juraj_google_style"} +{"code": "def direct_normal_radiation(self, value=9999.0):\n\n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type float '\n 'for field `direct_normal_radiation`'.format(value))\n if value < 0.0:\n raise ValueError('value need to be greater or equal 0.0 '\n 'for field `direct_normal_radiation`')\n\n self._direct_normal_radiation = value", "docstring": "Corresponds to IDD Field `direct_normal_radiation`\n\nArgs:\n value (float): value for IDD Field `direct_normal_radiation`\n Unit: Wh/m2\n value >= 0.0\n Missing value: 9999.0\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def list_directories_in_directory(full_directory_path):\n\n directories = list()\n for directory_name in __os.listdir(full_directory_path):\n if __os.path.isdir(__os.path.join(full_directory_path, directory_name)):\n directories.append(directory_name)\n return directories", "docstring": "List the directories in a specified directory\n\nArgs:\n full_directory_path: The full directory path to check, derive from the os module\n\n Returns: returns a list of directories", "source": "juraj_google_style"} +{"code": "def call_plugins(self, step):\n\n for plugin in self.plugins:\n try:\n getattr(plugin, step)()\n except AttributeError:\n self.logger.debug(\"{} doesn't exist on plugin {}\".format(step, plugin))\n except TypeError:\n self.logger.debug(\"{} on plugin {} is not callable\".format(step, plugin))", "docstring": "For each plugins, check if a \"step\" method exist on it, and call it\n\nArgs:\n step (str): The method to search and call on each plugin", "source": "juraj_google_style"} +{"code": "def QA_SU_save_stock_list(engine, client=DATABASE):\n\n\n engine = select_save_engine(engine)\n engine.QA_SU_save_stock_list(client=client)", "docstring": "save stock_list\n\nArgs:\n engine {[type]} -- [description]\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})", "source": "juraj_google_style"} +{"code": "def depth_september_average_ground_temperature(self, value=None):\n\n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type float '\n 'for field `depth_september_average_ground_temperature`'.format(value))\n\n self._depth_september_average_ground_temperature = value", "docstring": "Corresponds to IDD Field\n `depth_september_average_ground_temperature`\n\nArgs:\n value (float): value for IDD Field `depth_september_average_ground_temperature`\n Unit: C\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def __add__(self, other):\n\n sum_rel = DistributedReliability(self.thresholds, self.obs_threshold)\n sum_rel.frequencies = self.frequencies + other.frequencies\n return sum_rel", "docstring": "Add two DistributedReliability objects together and combine their values.\n\nArgs:\n other: a DistributedReliability object\n\nReturns:\n A DistributedReliability Object", "source": "juraj_google_style"} +{"code": "def precipitable_water(self, value=999.0):\n\n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type float '\n 'for field `precipitable_water`'.format(value))\n\n self._precipitable_water = value", "docstring": "Corresponds to IDD Field `precipitable_water`\n\nArgs:\n value (float): value for IDD Field `precipitable_water`\n Unit: mm\n Missing value: 999.0\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def _compute_nfps_real(counts, sizes):\n\n nfps = np.zeros((len(sizes), len(sizes)))\n # All u an l are inclusive bounds for intervals.\n # Compute p = 1, the NFPs\n for l in range(len(sizes)):\n for u in range(l, len(sizes)):\n nfps[l, u] = _compute_nfp_real(l, u, counts, sizes)\n return nfps", "docstring": "Computes the matrix of expected false positives for all possible\n sub-intervals of the complete domain of set sizes.\n\nArgs:\n counts: the complete distribution of set sizes.\n sizes: the complete domain of set sizes.\n\n Return (np.array): the 2-D array of expected number of false positives\n for every pair of [l, u] interval, where l is axis-0 and u is\n axis-1.", "source": "juraj_google_style"} +{"code": "def modelAdoptNextOrphan(self, jobId, maxUpdateInterval):\n\n\n @g_retrySQL\n def findCandidateModelWithRetries():\n modelID = None\n with ConnectionFactory.get() as conn:\n # TODO: may need a table index on job_id/status for speed\n query = 'SELECT model_id FROM %s ' \\\n ' WHERE status=%%s ' \\\n ' AND job_id=%%s ' \\\n ' AND TIMESTAMPDIFF(SECOND, ' \\\n ' _eng_last_update_time, ' \\\n ' UTC_TIMESTAMP()) > %%s ' \\\n ' LIMIT 1 ' \\\n % (self.modelsTableName,)\n sqlParams = [self.STATUS_RUNNING, jobId, maxUpdateInterval]\n numRows = conn.cursor.execute(query, sqlParams)\n rows = conn.cursor.fetchall()\n\n assert numRows <= 1, \"Unexpected numRows: %r\" % numRows\n if numRows == 1:\n (modelID,) = rows[0]\n\n return modelID\n\n @g_retrySQL\n def adoptModelWithRetries(modelID):\n adopted = False\n with ConnectionFactory.get() as conn:\n query = 'UPDATE %s SET _eng_worker_conn_id=%%s, ' \\\n ' _eng_last_update_time=UTC_TIMESTAMP() ' \\\n ' WHERE model_id=%%s ' \\\n ' AND status=%%s' \\\n ' AND TIMESTAMPDIFF(SECOND, ' \\\n ' _eng_last_update_time, ' \\\n ' UTC_TIMESTAMP()) > %%s ' \\\n ' LIMIT 1 ' \\\n % (self.modelsTableName,)\n sqlParams = [self._connectionID, modelID, self.STATUS_RUNNING,\n maxUpdateInterval]\n numRowsAffected = conn.cursor.execute(query, sqlParams)\n\n assert numRowsAffected <= 1, 'Unexpected numRowsAffected=%r' % (\n numRowsAffected,)\n\n if numRowsAffected == 1:\n adopted = True\n else:\n # Discern between transient failure during update and someone else\n # claiming this model\n (status, connectionID) = self._getOneMatchingRowNoRetries(\n self._models, conn, {'model_id':modelID},\n ['status', '_eng_worker_conn_id'])\n adopted = (status == self.STATUS_RUNNING and\n connectionID == self._connectionID)\n return adopted\n\n\n adoptedModelID = None\n while True:\n modelID = findCandidateModelWithRetries()\n if modelID is None:\n break\n if adoptModelWithRetries(modelID):\n adoptedModelID = modelID\n break\n\n return adoptedModelID", "docstring": "Look through the models table for an orphaned model, which is a model\n that is not completed yet, whose _eng_last_update_time is more than\n maxUpdateInterval seconds ago.\n\n If one is found, change its _eng_worker_conn_id to the current worker's\n and return the model id.\n\n Parameters:\n ----------------------------------------------------------------\n retval: modelId of the model we adopted, or None if none found", "source": "juraj_google_style"} +{"code": "def coarse_graining(network, state, internal_indices):\n\n max_phi = float('-inf')\n max_coarse_grain = CoarseGrain((), ())\n\n for coarse_grain in all_coarse_grains(internal_indices):\n try:\n subsystem = MacroSubsystem(network, state, internal_indices,\n coarse_grain=coarse_grain)\n except ConditionallyDependentError:\n continue\n\n phi = compute.phi(subsystem)\n if (phi - max_phi) > constants.EPSILON:\n max_phi = phi\n max_coarse_grain = coarse_grain\n\n return (max_phi, max_coarse_grain)", "docstring": "Find the maximal coarse-graining of a micro-system.\n\nArgs:\n network (Network): The network in question.\n state (tuple[int]): The state of the network.\n internal_indices (tuple[int]): Nodes in the micro-system.\n\nReturns:\n tuple[int, CoarseGrain]: The phi-value of the maximal |CoarseGrain|.", "source": "juraj_google_style"} +{"code": "def HashFilePath(self, path, byte_count):\n\n with open(path, \"rb\") as fd:\n self.HashFile(fd, byte_count)", "docstring": "Updates underlying hashers with file on a given path.\n\nArgs:\n path: A path to the file that is going to be fed to the hashers.\n byte_count: A maximum numbers of bytes that are going to be processed.", "source": "juraj_google_style"} +{"code": "def from_dict(cls, pwinput_dict):\n\n pwinput = cls(structure=Structure.from_dict(pwinput_dict['structure']),\n pseudo=pwinput_dict['pseudo'],\n control=pwinput_dict['sections']['control'],\n system=pwinput_dict['sections']['system'],\n electrons=pwinput_dict['sections']['electrons'],\n ions=pwinput_dict['sections']['ions'],\n cell=pwinput_dict['sections']['cell'],\n kpoints_mode=pwinput_dict['kpoints_mode'],\n kpoints_grid=pwinput_dict['kpoints_grid'],\n kpoints_shift=pwinput_dict['kpoints_shift'])\n return pwinput", "docstring": "Load a PWInput object from a dictionary.\n\nArgs:\n pwinput_dict (dict): dictionary with PWInput data\n\nReturns:\n PWInput object", "source": "juraj_google_style"} +{"code": "def convert_args_to_laid_out_tensors(xs):\n\n ret = []\n for x in xs:\n if hasattr(x, \"to_laid_out_tensor\"):\n ret.append(x.to_laid_out_tensor())\n else:\n ret.append(x)\n return ret", "docstring": "Convert list elements to laid-out-tensors when possible.\n\nArgs:\n xs: a list\n\nReturns:\n a list", "source": "juraj_google_style"} +{"code": "def split_vector_ctype(ctype):\n\n if not is_vector_ctype(ctype):\n raise ValueError('The given ctype is not a vector type.')\n for vector_length in [2, 3, 4, 8, 16]:\n if ctype.endswith(str(vector_length)):\n vector_str_len = len(str(vector_length))\n return ctype[:-vector_str_len], int(ctype[-vector_str_len:])", "docstring": "Split a vector ctype into a raw ctype and the vector length.\n\n If the given ctype is not a vector type, we raise an error. I\n\nArgs:\n ctype (str): the ctype to possibly split into a raw ctype and the vector length\n\nReturns:\n tuple: the raw ctype and the vector length", "source": "juraj_google_style"} +{"code": "def decode_list(cls, obj, element_type):\n # type: (List[Any], ConjureTypeType) -> List[Any]\n\n if not isinstance(obj, list):\n raise Exception(\"expected a python list\")\n\n return list(map(lambda x: cls.do_decode(x, element_type), obj))", "docstring": "Decodes json into a list, handling conversion of the elements.\n\nArgs:\n obj: the json object to decode\n element_type: a class object which is the conjure type of\n the elements in this list.\n\nReturns:\n A python list where the elements are instances of type\n element_type.", "source": "juraj_google_style"} +{"code": "def merge_and_fit(self, track, pairings):\n\n\n for (self_seg_index, track_seg_index, _) in pairings:\n self_s = self.segments[self_seg_index]\n ss_start = self_s.points[0]\n track_s = track.segments[track_seg_index]\n tt_start = track_s.points[0]\n tt_end = track_s.points[-1]\n\n d_start = ss_start.distance(tt_start)\n d_end = ss_start.distance(tt_end)\n\n if d_start > d_end:\n track_s = track_s.copy()\n track_s.points = list(reversed(track_s.points))\n\n self_s.merge_and_fit(track_s)\n return self", "docstring": "Merges another track with this one, ordering the points based on a\n distance heuristic\n\nArgs:\n track (:obj:`Track`): Track to merge with\n pairings\n\nReturns:\n :obj:`Segment`: self", "source": "juraj_google_style"} +{"code": "def _mouseUp(x, y, button):\n\n if button == 'left':\n try:\n _sendMouseEvent(MOUSEEVENTF_LEFTUP, x, y)\n except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60\n pass\n elif button == 'middle':\n try:\n _sendMouseEvent(MOUSEEVENTF_MIDDLEUP, x, y)\n except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60\n pass\n elif button == 'right':\n try:\n _sendMouseEvent(MOUSEEVENTF_RIGHTUP, x, y)\n except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60\n pass\n else:\n assert False, \"button argument not in ('left', 'middle', 'right')\"", "docstring": "Send the mouse up event to Windows by calling the mouse_event() win32\n function.\n\nArgs:\n x (int): The x position of the mouse event.\n y (int): The y position of the mouse event.\n button (str): The mouse button, either 'left', 'middle', or 'right'\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def download(self, resource_id):\n\n self.resource_id(str(resource_id))\n self._request_uri = '{}/download'.format(self._request_uri)", "docstring": "Update the request URI to download the document for this resource.\n\nArgs:\n resource_id (integer): The group id.", "source": "juraj_google_style"} +{"code": "def __Util__delete_device(self, klass_name, device_name):\n\n\n db = self.get_database()\n device_name = __simplify_device_name(device_name)\n device_exists = True\n try:\n db.import_device(device_name)\n except DevFailed as df:\n device_exists = not df.args[0].reason == \"DB_DeviceNotDefined\"\n\n # 1 - Make sure device name exists in the database\n if not device_exists:\n Except.throw_exception(\"PyAPI_DeviceNotDefined\",\n \"The device %s is not defined in the database\" % device_name,\n \"Util.delete_device\")\n\n # 2 - Make sure device name is defined in this server\n class_device_name = \"%s::%s\" % (klass_name, device_name)\n ds = self.get_dserver_device()\n dev_names = ds.query_device()\n device_exists = False\n for dev_name in dev_names:\n p = dev_name.index(\"::\")\n dev_name = dev_name[:p] + dev_name[p:].lower()\n if dev_name == class_device_name:\n device_exists = True\n break\n if not device_exists:\n Except.throw_exception(\"PyAPI_DeviceNotDefinedInServer\",\n \"The device %s is not defined in this server\" % class_device_name,\n \"Util.delete_device\")\n\n db.delete_device(device_name)\n\n dimpl = self.get_device_by_name(device_name)\n\n dc = dimpl.get_device_class()\n dc.device_destroyer(device_name)", "docstring": "delete_device(self, klass_name, device_name) -> None\n\n Deletes an existing device from the database and from this running\n server\n\n Throws tango.DevFailed:\n - the device name doesn't exist in the database\n - the device name doesn't exist in this DS.\n\n New in PyTango 7.1.2\n\n Parameters :\n - klass_name : (str) the device class name\n - device_name : (str) the device name\n\n Return : None", "source": "juraj_google_style"} +{"code": "def QA_util_future_to_tradedatetime(real_datetime):\n\n if len(str(real_datetime)) >= 19:\n dt = datetime.datetime.strptime(\n str(real_datetime)[0:19],\n '%Y-%m-%d %H:%M:%S'\n )\n return dt if dt.time(\n ) < datetime.time(21,\n 0) else QA_util_get_next_datetime(dt,\n 1)\n elif len(str(real_datetime)) == 16:\n dt = datetime.datetime.strptime(\n str(real_datetime)[0:16],\n '%Y-%m-%d %H:%M'\n )\n return dt if dt.time(\n ) < datetime.time(21,\n 0) else QA_util_get_next_datetime(dt,\n 1)", "docstring": "输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换\n\nArgs:\n real_datetime {[type]} -- [description]\n\nReturns:\n [type] -- [description]", "source": "juraj_google_style"} +{"code": "def _format_batch_statuses(statuses, batch_ids, tracker):\n\n proto_statuses = []\n\n for batch_id in batch_ids:\n if statuses[batch_id] == \\\n client_batch_submit_pb2.ClientBatchStatus.INVALID:\n invalid_txns = tracker.get_invalid_txn_info(batch_id)\n for txn_info in invalid_txns:\n try:\n txn_info['transaction_id'] = txn_info.pop('id')\n except KeyError as e:\n LOGGER.debug(e)\n else:\n invalid_txns = None\n\n proto_statuses.append(\n client_batch_submit_pb2.ClientBatchStatus(\n batch_id=batch_id,\n status=statuses[batch_id],\n invalid_transactions=invalid_txns))\n\n return proto_statuses", "docstring": "Takes a statuses dict and formats it for transmission with Protobuf and\n ZMQ.\n\nArgs:\n statuses (dict of int): Dict with batch ids as the key, status as value\n batch_ids (list of str): The batch ids in their original order\n tracker (BatchTracker): A batch tracker with access to invalid info", "source": "juraj_google_style"} +{"code": "def init(self, address, hard_reset=False):\n\n self.address = address\n\n if hard_reset:\n # TODO (needs more work to be usable)\n # if not Dongle._hard_reset(address):\n # return False\n # time.sleep(2.0)\n pass\n\n # TODO timeout not working if opened on valid, non Bluegiga port\n for i in range(Dongle.PORT_RETRIES):\n try:\n logger.debug('Setting up BGAPI, attempt {}/{}'.format(i + 1, Dongle.PORT_RETRIES))\n self.api = BlueGigaAPI(port=self.address, callbacks=self, baud=Dongle.BAUDRATE, timeout=DEF_TIMEOUT)\n self.api.start_daemon()\n break\n except serial.serialutil.SerialException as e:\n logger.debug('Failed to init BlueGigaAPI: {}, attempt {}/{}'.format(e, i + 1, Dongle.PORT_RETRIES))\n time.sleep(0.1)\n\n if self.api is None:\n return False\n\n time.sleep(0.5) # TODO\n self.get_supported_connections()\n logger.info('Dongle supports {} connections'.format(self.supported_connections))\n if self.supported_connections == -1:\n logger.error('Failed to retrieve number of supported connections from the dongle! (try reinserting it)')\n return False\n\n self.conn_state = {x: self._STATE_IDLE for x in range(self.supported_connections)}\n self.reset()\n\n self._cbthread = threading.Thread(target=self._cbthreadfunc)\n self._cbthread.setDaemon(True)\n self._cbthread_q = Queue()\n self._cbthread.start()\n return True", "docstring": "Open the serial connection to a dongle at the supplied address.\n\nArgs:\n address (str): the serial port address of the BLED112 dongle, e.g. 'COM5'\n hard_reset (bool): not currently used\n\nReturns:\n True if a connection with the dongle was established, False otherwise.", "source": "juraj_google_style"} +{"code": "def set_log_block_num(self, bl):\n # type: (int) -> None\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('PL record not yet initialized!')\n\n self.parent_log_block_num = bl", "docstring": "Set the logical block number for the parent.\n\n Parameters:\n bl - Logical block number of the parent.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def wait(self, timeout_ms=None):\n\n closed = timeouts.loop_until_timeout_or_true(\n timeouts.PolledTimeout.from_millis(timeout_ms),\n self.stream.is_closed, .1)\n if closed:\n if hasattr(self.stdout, 'getvalue'):\n return self.stdout.getvalue()\n return True\n return None", "docstring": "Block until this command has completed.\n\nArgs:\n timeout_ms: Timeout, in milliseconds, to wait.\n\nReturns:\n Output of the command if it complete and self.stdout is a StringIO\n object or was passed in as None. Returns True if the command completed but\n stdout was provided (and was not a StringIO object). Returns None if the\n timeout expired before the command completed. Be careful to check the\n return value explicitly for None, as the output may be ''.", "source": "juraj_google_style"} +{"code": "def incomeStatement(symbol, token='', version=''):\n\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/income', token, version)", "docstring": "Pulls income statement data. Available quarterly (4 quarters) or annually (4 years).\n\n https://iexcloud.io/docs/api/#income-statement\n Updates at 8am, 9am UTC daily\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n dict: result", "source": "juraj_google_style"} +{"code": "def _prep_binary_content(self):\n\n\n\n\t\t# nothing present\n\t\tif not self.data and not self.location and 'Content-Location' not in self.resource.headers.keys():\n\t\t\traise Exception('creating/updating NonRDFSource requires content from self.binary.data, self.binary.location, or the Content-Location header')\n\n\t\telif 'Content-Location' in self.resource.headers.keys():\n\t\t\tlogger.debug('Content-Location header found, using')\n\t\t\tself.delivery = 'header'\n\n\t\t# if Content-Location is not set, look for self.data_location then self.data\n\t\telif 'Content-Location' not in self.resource.headers.keys():\n\n\t\t\t# data_location set, trumps Content self.data\n\t\t\tif self.location:\n\t\t\t\t# set appropriate header\n\t\t\t\tself.resource.headers['Content-Location'] = self.location\n\t\t\t\tself.delivery = 'header'\n\n\t\t\t# data attribute is plain text, binary, or file-like object\n\t\t\telif self.data:\n\n\t\t\t\t# if file-like object, set flag for api.http_request\n\t\t\t\tif isinstance(self.data, io.BufferedIOBase):\n\t\t\t\t\tlogger.debug('detected file-like object')\n\t\t\t\t\tself.delivery = 'payload'\n\n\t\t\t\t# else, just bytes\n\t\t\t\telse:\n\t\t\t\t\tlogger.debug('detected bytes')\n\t\t\t\t\tself.delivery = 'payload'", "docstring": "Sets delivery method of either payload or header\n Favors Content-Location header if set\n\nArgs:\n None\n\nReturns:\n None: sets attributes in self.binary and headers", "source": "juraj_google_style"} +{"code": "def rouge_2_fscore(logits, labels):\n\n predictions = tf.to_int32(tf.argmax(logits, axis=-1))\n # TODO: Look into removing use of py_func\n rouge_2_f_score = tf.py_func(rouge_n, (predictions, labels), tf.float32)\n return rouge_2_f_score, tf.constant(1.0)", "docstring": "ROUGE-2 F1 score computation between labels and predictions.\n\n This is an approximate ROUGE scoring method since we do not glue word pieces\n or decode the ids and tokenize the output.\n\nArgs:\n logits: tensor, model predictions\n labels: tensor, gold output.\n\nReturns:\n rouge2_fscore: approx rouge-2 f1 score.", "source": "juraj_google_style"} +{"code": "def ffn_expert_fn(input_size,\n hidden_sizes,\n output_size,\n hidden_activation=tf.nn.relu):\n\n def my_fn(x):\n layer_sizes = [input_size] + hidden_sizes + [output_size]\n for i in range(1 + len(hidden_sizes)):\n w = tf.get_variable(\"w_%d\" % i, layer_sizes[i:i+2], tf.float32)\n x = tf.matmul(x, w)\n if i < len(hidden_sizes):\n x = hidden_activation(x)\n if layer_sizes[i] != input_size:\n x *= (layer_sizes[i] / float(input_size))**-0.5\n return x\n return my_fn", "docstring": "Returns a function that creates a feed-forward network.\n\n Use this function to create the expert_fn argument to distributed_moe.\n\nArgs:\n input_size: an integer\n hidden_sizes: a list of integers\n output_size: an integer\n hidden_activation: a unary function.\n\nReturns:\n a unary function", "source": "juraj_google_style"} +{"code": "def _get_package_name(prefix=settings.TEMP_DIR, book_id=None):\n\n if book_id is None:\n book_id = str(uuid.uuid4())\n\n return os.path.join(prefix, book_id)", "docstring": "Return package path. Use uuid to generate package's directory name.\n\nArgs:\n book_id (str, default None): UUID of the book.\n prefix (str, default settings.TEMP_DIR): Where the package will be\n stored. Default :attr:`settings.TEMP_DIR`.\n\nReturns:\n str: Path to the root directory.", "source": "juraj_google_style"} +{"code": "def disconnect_sync(self, conn_id):\n\n\n done = threading.Event()\n result = {}\n\n def disconnect_done(conn_id, adapter_id, status, reason):\n result['success'] = status\n result['failure_reason'] = reason\n done.set()\n\n self.disconnect_async(conn_id, disconnect_done)\n done.wait()\n\n return result", "docstring": "Synchronously disconnect from a connected device\n\nArgs:\n conn_id (int): A unique identifier that will refer to this connection\n\nReturns:\n dict: A dictionary with two elements\n 'success': a bool with the result of the connection attempt\n 'failure_reason': a string with the reason for the failure if we failed", "source": "juraj_google_style"} +{"code": "def _server_response_handler(self, response: Dict[str, Any]):\n\n code = response.get(\"CODE\")\n if code == 100:\n if self.debug:\n print(\"auth succeed\")\n self._login_fut.set_result(response)\n if code == 101:\n if self.debug:\n print('pong')\n return True", "docstring": "处理100~199段状态码,针对不同的服务响应进行操作.\n\n Parameters:\n (response): - 响应的python字典形式数据\n\nReturns:\n (bool): - 准确地说没有错误就会返回True", "source": "juraj_google_style"} +{"code": "def f0(E, fermi, T):\n\n return 1. / (1. + np.exp((E - fermi) / (_cd(\"Boltzmann constant in eV/K\") * T)))", "docstring": "Returns the equilibrium fermi-dirac.\n\nArgs:\n E (float): energy in eV\n fermi (float): the fermi level in eV\n T (float): the temperature in kelvin", "source": "juraj_google_style"} +{"code": "def rpm_name(self, name, python_version=None, pkg_name=False):\n\n if pkg_name:\n return super(DandifiedNameConvertor, self).rpm_name(\n name, python_version)\n original_name = name\n converted = super(DandifiedNameConvertor, self).rpm_name(\n name, python_version)\n python_query = self.query.filter(name__substr=[\n 'python', 'py', original_name, canonical_form(original_name)])\n if converted in [pkg.name for pkg in python_query]:\n logger.debug(\"Converted name exists\")\n return converted\n\n logger.debug(\"Converted name not found, searches for correct form\")\n\n not_versioned_name = NameVariants(self.base_name(original_name), '')\n versioned_name = NameVariants(self.base_name(original_name),\n python_version)\n\n if self.base_name(original_name).startswith(\"py\"):\n nonpy_name = NameVariants(self.base_name(\n original_name)[2:], python_version)\n\n for pkg in python_query:\n versioned_name.find_match(pkg.name)\n not_versioned_name.find_match(pkg.name)\n if 'nonpy_name' in locals():\n nonpy_name.find_match(pkg.name)\n\n if 'nonpy_name' in locals():\n versioned_name = versioned_name.merge(nonpy_name)\n\n correct_form = versioned_name.merge(not_versioned_name).best_matching\n logger.debug(\"Most likely correct form of the name {0}.\".format(\n correct_form))\n return correct_form or converted", "docstring": "Checks if name converted using superclass rpm_name_method match name\n of package in the query. Searches for correct name if it doesn't.\n\nArgs:\n name: name to convert\n python_version: python version for which to retrieve the name of\n the package\n pkg_name: flag to perform conversion of rpm package name\n (foo -> python-foo)", "source": "juraj_google_style"} +{"code": "def get_sample(self, md5):\n\n\n # Support 'short' md5s but don't waste performance if the full md5 is provided\n if len(md5) < 32:\n md5 = self.get_full_md5(md5, self.sample_collection)\n\n # Grab the sample\n sample_info = self.database[self.sample_collection].find_one({'md5': md5})\n if not sample_info:\n return None\n\n # Get the raw bytes from GridFS (note: this could fail)\n try:\n grid_fs_id = sample_info['__grid_fs']\n sample_info = self.clean_for_serialization(sample_info)\n sample_info.update({'raw_bytes':self.gridfs_handle.get(grid_fs_id).read()})\n return sample_info\n except gridfs.errors.CorruptGridFile:\n # If we don't have the gridfs files, delete the entry from samples\n self.database[self.sample_collection].update({'md5': md5}, {'md5': None})\n return None", "docstring": "Get the sample from the data store.\n\n This method first fetches the data from datastore, then cleans it for serialization\n and then updates it with 'raw_bytes' item.\n\nArgs:\n md5: The md5 digest of the sample to be fetched from datastore.\n\nReturns:\n The sample dictionary or None", "source": "juraj_google_style"} +{"code": "def _add_scalar(self, scalar):\n\n encoded = EncodedNumber.encode(self.public_key, scalar,\n max_exponent=self.exponent)\n\n return self._add_encoded(encoded)", "docstring": "Returns E(a + b), given self=E(a) and b.\n\nArgs:\n scalar: an int or float b, to be added to `self`.\n\nReturns:\n EncryptedNumber: E(a + b), calculated by encrypting b and\n taking the product of E(a) and E(b) modulo\n :attr:`~PaillierPublicKey.n` ** 2.\n\nRaises:\n ValueError: if scalar is out of range or precision.", "source": "juraj_google_style"} +{"code": "def countriesdata(cls, use_live=True):\n # type: (bool) -> List[Dict[Dict]]\n\n if cls._countriesdata is None:\n countries = None\n if use_live:\n try:\n countries = hxl.data(cls._ochaurl)\n except IOError:\n logger.exception('Download from OCHA feed failed! Falling back to stored file.')\n if countries is None:\n countries = hxl.data(\n script_dir_plus_file('Countries & Territories Taxonomy MVP - C&T Taxonomy with HXL Tags.csv',\n Country), allow_local=True)\n cls.set_countriesdata(countries)\n return cls._countriesdata", "docstring": "Read countries data from OCHA countries feed (falling back to file)\n\nArgs:\n use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n\nReturns:\n List[Dict[Dict]]: Countries dictionaries", "source": "juraj_google_style"} +{"code": "def emit(self, signal, message, analysis_id):\n\n\n log.debug('kernel {} zmq send ({}): {}'\n ''.format(analysis_id, signal, message))\n self.zmq_publish.send(json.dumps({\n 'analysis_id': analysis_id,\n 'frame': {'signal': signal, 'load': message},\n }, default=json_encoder_default).encode('utf-8'))", "docstring": "Emit signal to main.\n\nArgs:\n signal: Name of the signal to be emitted.\n message: Message to be sent.\n analysis_id: Identifies the instance of this analysis.", "source": "juraj_google_style"} +{"code": "def _CompositeMapByteStream(\n self, byte_stream, byte_offset=0, context=None, **unused_kwargs):\n\n context_state = getattr(context, 'state', {})\n\n attribute_index = context_state.get('attribute_index', 0)\n mapped_values = context_state.get('mapped_values', None)\n subcontext = context_state.get('context', None)\n\n if not mapped_values:\n mapped_values = self._structure_values_class()\n if not subcontext:\n subcontext = DataTypeMapContext(values={\n type(mapped_values).__name__: mapped_values})\n\n members_data_size = 0\n\n for attribute_index in range(attribute_index, self._number_of_attributes):\n attribute_name = self._attribute_names[attribute_index]\n data_type_map = self._data_type_maps[attribute_index]\n member_definition = self._data_type_definition.members[attribute_index]\n\n condition = getattr(member_definition, 'condition', None)\n if condition:\n namespace = dict(subcontext.values)\n # Make sure __builtins__ contains an empty dictionary.\n namespace['__builtins__'] = {}\n\n try:\n condition_result = eval(condition, namespace) # pylint: disable=eval-used\n except Exception as exception:\n raise errors.MappingError(\n 'Unable to evaluate condition with error: {0!s}'.format(\n exception))\n\n if not isinstance(condition_result, bool):\n raise errors.MappingError(\n 'Condition does not result in a boolean value')\n\n if not condition_result:\n continue\n\n if isinstance(member_definition, data_types.PaddingDefinition):\n _, byte_size = divmod(\n members_data_size, member_definition.alignment_size)\n if byte_size > 0:\n byte_size = member_definition.alignment_size - byte_size\n\n data_type_map.byte_size = byte_size\n\n try:\n value = data_type_map.MapByteStream(\n byte_stream, byte_offset=byte_offset, context=subcontext)\n setattr(mapped_values, attribute_name, value)\n\n except errors.ByteStreamTooSmallError as exception:\n context_state['attribute_index'] = attribute_index\n context_state['context'] = subcontext\n context_state['mapped_values'] = mapped_values\n raise errors.ByteStreamTooSmallError(exception)\n\n except Exception as exception:\n raise errors.MappingError(exception)\n\n supported_values = getattr(member_definition, 'values', None)\n if supported_values and value not in supported_values:\n raise errors.MappingError(\n 'Value: {0!s} not in supported values: {1:s}'.format(\n value, ', '.join([\n '{0!s}'.format(value) for value in supported_values])))\n\n byte_offset += subcontext.byte_size\n members_data_size += subcontext.byte_size\n\n if attribute_index != (self._number_of_attributes - 1):\n context_state['attribute_index'] = attribute_index\n context_state['context'] = subcontext\n context_state['mapped_values'] = mapped_values\n\n error_string = (\n 'Unable to read: {0:s} from byte stream at offset: {1:d} '\n 'with error: missing attribute: {2:d}').format(\n self._data_type_definition.name, byte_offset, attribute_index)\n raise errors.ByteStreamTooSmallError(error_string)\n\n if context:\n context.byte_size = members_data_size\n context.state = {}\n\n return mapped_values", "docstring": "Maps a sequence of composite data types on a byte stream.\n\nArgs:\n byte_stream (bytes): byte stream.\n byte_offset (Optional[int]): offset into the byte stream where to start.\n context (Optional[DataTypeMapContext]): data type map context.\n\nReturns:\n object: mapped value.\n\nRaises:\n MappingError: if the data type definition cannot be mapped on\n the byte stream.", "source": "juraj_google_style"} +{"code": "def point_line_distance(point, start, end):\n\n if start == end:\n return distance(point, start)\n else:\n un_dist = abs(\n (end.lat-start.lat)*(start.lon-point.lon) - (start.lat-point.lat)*(end.lon-start.lon)\n )\n n_dist = sqrt(\n (end.lat-start.lat)**2 + (end.lon-start.lon)**2\n )\n if n_dist == 0:\n return 0\n else:\n return un_dist / n_dist", "docstring": "Distance from a point to a line, formed by two points\n\nArgs:\n point (:obj:`Point`)\n start (:obj:`Point`): line point\n end (:obj:`Point`): line point\n\nReturns:\n float: distance to line, in degrees", "source": "juraj_google_style"} +{"code": "def __init__(self, config, default=None):\n\n self.update(self._load(default))\n self.update(self._load(config))\n\n self._formatFilepaths()\n\n # For back-compatibility...\n self.params = self\n\n # Run some basic validation\n # ADW: This should be run after creating filenames\n self._validate()\n\n # Filenames from this config (masked by existence) \n # ADW: We should not recreate filenames if they already exist\n # in the input config\n if not hasattr(self,'filenames'):\n try:\n self.filenames = self._createFilenames()\n except:\n exc_type,exc_value,exc_traceback = sys.exc_info()\n logger.warning(\"%s %s\"%(exc_type,exc_value))\n logger.warning(\"Filenames could not be created for config.\")", "docstring": "Initialize a configuration object from a filename or a dictionary.\n Provides functionality to merge with a default configuration.\n\n Parameters:\n config: filename, dict, or Config object (deep copied)\n default: default configuration to merge\n\nReturns:\n config", "source": "juraj_google_style"} +{"code": "def register_many(self, *args):\n\n params = []\n for name in args:\n params.append(self.register(name))\n\n return params", "docstring": "Register many configuration names.\n\nArgs:\n *args: Config names as strings.\n\nReturns:\n list: List of registered configs.", "source": "juraj_google_style"} +{"code": "def getCmdOpts(self, text):\n\n off = 0\n\n _, off = s_syntax.nom(text, off, s_syntax.whites)\n\n name, off = s_syntax.meh(text, off, s_syntax.whites)\n\n _, off = s_syntax.nom(text, off, s_syntax.whites)\n\n opts = {}\n\n args = collections.deque([synt for synt in self._cmd_syntax if not synt[0].startswith('-')])\n\n switches = {synt[0]: synt for synt in self._cmd_syntax if synt[0].startswith('-')}\n\n # populate defaults and lists\n for synt in self._cmd_syntax:\n snam = synt[0].strip('-')\n\n defval = synt[1].get('defval')\n if defval is not None:\n opts[snam] = defval\n\n if synt[1].get('type') in ('list', 'kwlist'):\n opts[snam] = []\n\n def atswitch(t, o):\n # check if we are at a recognized switch. if not\n # assume the data is part of regular arguments.\n if not text.startswith('-', o):\n return None, o\n\n name, x = s_syntax.meh(t, o, s_syntax.whites)\n swit = switches.get(name)\n if swit is None:\n return None, o\n\n return swit, x\n\n while off < len(text):\n\n _, off = s_syntax.nom(text, off, s_syntax.whites)\n\n swit, off = atswitch(text, off)\n if swit is not None:\n\n styp = swit[1].get('type', 'flag')\n snam = swit[0].strip('-')\n\n if styp == 'valu':\n valu, off = s_syntax.parse_cmd_string(text, off)\n opts[snam] = valu\n\n elif styp == 'list':\n valu, off = s_syntax.parse_cmd_string(text, off)\n if not isinstance(valu, list):\n valu = valu.split(',')\n opts[snam].extend(valu)\n\n elif styp == 'enum':\n vals = swit[1].get('enum:vals')\n valu, off = s_syntax.parse_cmd_string(text, off)\n if valu not in vals:\n raise s_exc.BadSyntax(mesg='%s (%s)' % (swit[0], '|'.join(vals)),\n text=text)\n\n opts[snam] = valu\n\n else:\n opts[snam] = True\n\n continue\n\n if not args:\n raise s_exc.BadSyntax(mesg='trailing text: [%s]' % (text[off:],),\n text=text)\n\n synt = args.popleft()\n styp = synt[1].get('type', 'valu')\n\n # a glob type eats the remainder of the string\n if styp == 'glob':\n opts[synt[0]] = text[off:]\n break\n\n # eat the remainder of the string as separate vals\n if styp == 'list':\n valu = []\n\n while off < len(text):\n item, off = s_syntax.parse_cmd_string(text, off)\n valu.append(item)\n\n opts[synt[0]] = valu\n break\n\n if styp == 'kwlist':\n kwlist, off = s_syntax.parse_cmd_kwlist(text, off)\n opts[snam] = kwlist\n break\n\n valu, off = s_syntax.parse_cmd_string(text, off)\n opts[synt[0]] = valu\n\n return opts", "docstring": "Use the _cmd_syntax def to split/parse/normalize the cmd line.\n\nArgs:\n text (str): Command to process.\n\nNote:\n This is implemented independent of argparse (et al) due to the\n need for syntax aware argument splitting. Also, allows different\n split per command type\n\nReturns:\n dict: An opts dictionary.", "source": "juraj_google_style"} +{"code": "def fit(self, x_tr, y_tr, epochs=50, batchsize=32,\n learning_rate=0.01, verbose=None, device=None):\n\n if batchsize > len(x_tr):\n batchsize = len(x_tr)\n verbose, device = SETTINGS.get_default(('verbose', verbose),\n ('device', device))\n self.model = NCC_model()\n opt = th.optim.Adam(self.model.parameters(), lr=learning_rate)\n criterion = th.nn.BCEWithLogitsLoss()\n y = y_tr.values if isinstance(y_tr, pd.DataFrame) else y_tr\n y = th.Tensor(y)/2 + .5\n # print(y)\n self.model = self.model.to(device)\n y = y.to(device)\n dataset = []\n for i, (idx, row) in enumerate(x_tr.iterrows()):\n\n a = row['A'].reshape((len(row['A']), 1))\n b = row['B'].reshape((len(row['B']), 1))\n m = np.hstack((a, b))\n m = m.astype('float32')\n m = th.from_numpy(m).t().unsqueeze(0)\n dataset.append(m)\n dataset = [m.to(device) for m in dataset]\n acc = [0]\n da = th.utils.data.DataLoader(Dataset(dataset, y), batch_size=batchsize,\n shuffle=True)\n data_per_epoch = (len(dataset) // batchsize)\n with trange(epochs, desc=\"Epochs\", disable=not verbose) as te:\n for epoch in te:\n with trange(data_per_epoch, desc=\"Batches of {}\".format(batchsize),\n disable=not (verbose and batchsize == len(dataset))) as t:\n output = []\n labels = []\n for (batch, label), i in zip(da, t):\n opt.zero_grad()\n # print(batch.shape, labels.shape)\n out = th.stack([self.model(m) for m in batch], 0).squeeze(2)\n loss = criterion(out, label)\n loss.backward()\n t.set_postfix(loss=loss.item())\n opt.step()\n output.append(out)\n labels.append(label)\n acc = th.where(th.cat(output, 0) > .5,\n th.ones(len(output)),\n th.zeros(len(output))) - th.cat(labels, 0)\n te.set_postfix(Acc=1-acc.abs().mean().item())", "docstring": "Fit the NCC model.\n\nArgs:\n x_tr (pd.DataFrame): CEPC format dataframe containing the pairs\n y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs\n epochs (int): number of train epochs\n learning_rate (float): learning rate of Adam\n verbose (bool): verbosity (defaults to ``cdt.SETTINGS.verbose``)\n device (str): cuda or cpu device (defaults to ``cdt.SETTINGS.default_device``)", "source": "juraj_google_style"} +{"code": "def _rm_udf_file_ident(self, parent, fi):\n # type: (udfmod.UDFFileEntry, bytes) -> int\n\n logical_block_size = self.pvd.logical_block_size()\n num_extents_to_remove = parent.remove_file_ident_desc_by_name(fi,\n logical_block_size)\n self.udf_logical_volume_integrity.logical_volume_impl_use.num_files -= 1\n\n self._find_udf_record.cache_clear() # pylint: disable=no-member\n\n return num_extents_to_remove * logical_block_size", "docstring": "An internal method to remove a UDF File Identifier from the parent\n and remove any space from the Logical Volume as necessary.\n\n Parameters:\n parent - The parent entry to remove the UDF File Identifier from.\n fi - The file identifier to remove.\n\nReturns:\n The number of bytes to remove from the ISO.", "source": "juraj_google_style"} +{"code": "def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n\n tstream = BytearrayStream()\n\n self.extension_name.write(tstream, kmip_version=kmip_version)\n\n if self.extension_tag is not None:\n self.extension_tag.write(tstream, kmip_version=kmip_version)\n if self.extension_type is not None:\n self.extension_type.write(tstream, kmip_version=kmip_version)\n\n self.length = tstream.length()\n super(ExtensionInformation, self).write(\n ostream,\n kmip_version=kmip_version\n )\n ostream.write(tstream.buffer)", "docstring": "Write the data encoding the ExtensionInformation object to a stream.\n\nArgs:\n ostream (Stream): A data stream in which to encode object data,\n supporting a write method; usually a BytearrayStream object.\n kmip_version (KMIPVersion): An enumeration defining the KMIP\n version with which the object will be encoded. Optional,\n defaults to KMIP 1.0.", "source": "juraj_google_style"} +{"code": "def save(nifti_filename, numpy_data):\n\n # Expand filename to be absolute\n nifti_filename = os.path.expanduser(nifti_filename)\n\n try:\n nifti_img = nib.Nifti1Image(numpy_data, numpy.eye(4))\n nib.save(nifti_img, nifti_filename)\n\n except Exception as e:\n raise ValueError(\"Could not save file {0}.\".format(nifti_filename))\n return nifti_filename", "docstring": "Export a numpy array to a nifti file. TODO: currently using dummy\n headers and identity matrix affine transform. This can be expanded.\n\nArgs:\n nifti_filename (str): A filename to which to save the nifti data\n numpy_data (numpy.ndarray): The numpy array to save to nifti\n\nReturns:\n String. The expanded filename that now holds the nifti data", "source": "juraj_google_style"} +{"code": "def setup_callbacks(self, callbacks, monitors):\n\n assert isinstance(callbacks, list), callbacks\n assert isinstance(monitors, list), monitors\n describe_trainable_vars() # TODO weird\n\n self.register_callback(MaintainStepCounter())\n for cb in callbacks:\n self.register_callback(cb)\n for cb in self._callbacks:\n assert not isinstance(cb, MonitorBase), \"Monitor cannot be pre-registered for now!\"\n registered_monitors = []\n for m in monitors:\n if self.register_callback(m):\n registered_monitors.append(m)\n self.monitors = Monitors(registered_monitors)\n self.register_callback(self.monitors) # monitors is also a callback\n\n # some final operations that might modify the graph\n logger.info(\"Setup callbacks graph ...\")\n self._callbacks = Callbacks(self._callbacks)\n self._callbacks.setup_graph(weakref.proxy(self))", "docstring": "Setup callbacks and monitors. Must be called after the main graph is built.\n\nArgs:\n callbacks ([Callback]):\n monitors ([MonitorBase]):", "source": "juraj_google_style"} +{"code": "def AddArguments(cls, argument_group):\n\n argument_group.add_argument(\n '--append', dest='append', action='store_true', default=False,\n required=cls._DEFAULT_APPEND, help=(\n 'Defines whether the intention is to append to an already '\n 'existing database or overwrite it. Defaults to overwrite.'))\n argument_group.add_argument(\n '--evidence', dest='evidence', type=str,\n default=cls._DEFAULT_EVIDENCE, action='store', required=False,\n help='Set the evidence field to a specific value, defaults to empty.')\n argument_group.add_argument(\n '--fields', dest='fields', type=str, action='store',\n default=cls._DEFAULT_FIELDS, help=(\n 'Defines which fields should be indexed in the database.'))\n argument_group.add_argument(\n '--additional_fields', dest='additional_fields', type=str,\n action='store', default='', help=(\n 'Defines extra fields to be included in the output, in addition to'\n ' the default fields, which are {0:s}.'.format(\n cls._DEFAULT_FIELDS)))", "docstring": "Adds command line arguments the helper supports to an argument group.\n\n This function takes an argument parser or an argument group object and adds\n to it all the command line arguments this helper supports.\n\nArgs:\n argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):\n argparse group.", "source": "juraj_google_style"} +{"code": "def _CheckStorageMetadata(cls, metadata_values, check_readable_only=False):\n\n format_version = metadata_values.get('format_version', None)\n\n if not format_version:\n raise IOError('Missing format version.')\n\n try:\n format_version = int(format_version, 10)\n except (TypeError, ValueError):\n raise IOError('Invalid format version: {0!s}.'.format(format_version))\n\n if not check_readable_only and format_version != cls._FORMAT_VERSION:\n raise IOError('Format version: {0:d} is not supported.'.format(\n format_version))\n\n if format_version < cls._COMPATIBLE_FORMAT_VERSION:\n raise IOError(\n 'Format version: {0:d} is too old and no longer supported.'.format(\n format_version))\n\n if format_version > cls._FORMAT_VERSION:\n raise IOError(\n 'Format version: {0:d} is too new and not yet supported.'.format(\n format_version))\n\n metadata_values['format_version'] = format_version\n\n compression_format = metadata_values.get('compression_format', None)\n if compression_format not in definitions.COMPRESSION_FORMATS:\n raise IOError('Unsupported compression format: {0:s}'.format(\n compression_format))\n\n serialization_format = metadata_values.get('serialization_format', None)\n if serialization_format != definitions.SERIALIZER_FORMAT_JSON:\n raise IOError('Unsupported serialization format: {0:s}'.format(\n serialization_format))\n\n storage_type = metadata_values.get('storage_type', None)\n if storage_type not in definitions.STORAGE_TYPES:\n raise IOError('Unsupported storage type: {0:s}'.format(\n storage_type))", "docstring": "Checks the storage metadata.\n\nArgs:\n metadata_values (dict[str, str]): metadata values per key.\n check_readable_only (Optional[bool]): whether the store should only be\n checked to see if it can be read. If False, the store will be checked\n to see if it can be read and written to.\n\nRaises:\n IOError: if the format version or the serializer format is not supported.\n OSError: if the format version or the serializer format is not supported.", "source": "juraj_google_style"} +{"code": "def securityEvent(symbol=None, token='', version=''):\n\n _raiseIfNotStr(symbol)\n if symbol:\n return _getJson('deep/security-event?symbols=' + symbol, token, version)\n return _getJson('deep/security-event', token, version)", "docstring": "The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs\n\n https://iexcloud.io/docs/api/#deep-security-event\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n dict: result", "source": "juraj_google_style"} +{"code": "def __call__(self, parser, namespace, value, option_string=None, **kwargs):\n\n\n handle = copen(value, mode=self.mode, **self.kwargs)\n\n setattr(namespace, self.dest, handle)", "docstring": "Detects and opens compressed files\n\nArgs:\n parser (ArgumentParser): parser used to generate values\n\n namespace (Namespace): namespace to set values for\n\n value (str): actual value specified by user\n\n option_string (str): argument flag used to call this function\n\n **kwargs (various): optional arguments later passed to the\n compression algorithm", "source": "juraj_google_style"} +{"code": "def get_sequence_sliding_window_properties(self, scale, window, representative_only=True):\n\n if representative_only:\n # Check if a representative sequence was set\n if not self.representative_sequence:\n log.warning('{}: no representative sequence set, cannot get sequence properties'.format(self.id))\n return\n\n # Also need to check if a sequence has been stored\n if not self.representative_sequence.seq:\n log.warning('{}: representative sequence {} set, but no sequence stored. '\n 'Cannot get sequence properties.'.format(self.id, self.representative_sequence.id))\n return\n\n self.representative_sequence.get_sliding_window_properties(scale=scale, window=window)\n\n if not representative_only:\n for s in self.sequences:\n # Need to check if a sequence has been stored\n if not s.seq:\n log.warning('{}: no sequence stored. '\n 'Cannot get sequence properties.'.format(s.id))\n continue\n\n else:\n s.get_sliding_window_properties(scale=scale, window=window)", "docstring": "Run Biopython ProteinAnalysis with a sliding window to calculate a given property.\n Results are stored in the protein's respective SeqProp objects at ``.letter_annotations``\n\nArgs:\n scale (str): Scale name\n window (int): Sliding window size\n representative_only (bool): If analysis should only be run on the representative sequence", "source": "juraj_google_style"} +{"code": "def user(self, user: str) -> \"ChildHTTPAPI\":\n\n if self.is_real_user:\n raise ValueError(\"Can't get child of real user\")\n\n try:\n return self.children[user]\n except KeyError:\n child = ChildHTTPAPI(user, self)\n self.children[user] = child\n return child", "docstring": "Get a child HTTPAPI instance.\n\nArgs:\n user: The Matrix ID of the user whose API to get.\n\nReturns:\n A HTTPAPI instance that always uses the given Matrix ID.", "source": "juraj_google_style"} +{"code": "def simulate_values(cls, num_events, lr_scheduler, **kwargs):\n\n # This scheduler uses `torch.optim.lr_scheduler._LRScheduler` which\n # should be replicated in order to simulate LR values and\n # not perturb original scheduler.\n copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler)\n values = []\n scheduler = cls(save_history=False, lr_scheduler=copy_lr_scheduler)\n for i in range(num_events):\n scheduler(engine=None)\n values.append([i, scheduler.optimizer_param_groups[0][scheduler.param_name]])\n\n return values", "docstring": "Method to simulate scheduled values during num_events events.\n\nArgs:\n num_events (int): number of events during the simulation.\n lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap.\n\nReturns:\n list of pairs: [event_index, value]", "source": "juraj_google_style"} +{"code": "def default(self, obj):\n\n if isinstance(obj, datetime):\n return obj.isoformat()\n\n if issubclass(obj.__class__, Enum.__class__):\n return obj.value\n\n to_json = getattr(obj, 'to_json', None)\n if to_json:\n out = obj.to_json()\n if issubclass(obj.__class__, Model):\n out.update({'__type': obj.__class__.__name__})\n\n return out\n\n return JSONEncoder.default(self, obj)", "docstring": "Default object encoder function\n\nArgs:\n obj (:obj:`Any`): Object to be serialized\n\nReturns:\n JSON string", "source": "juraj_google_style"} +{"code": "def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }):\n\n\n if isinstance(path_cfg, str):\n return _expand_str(path_cfg, alias_dict, overriding_kargs)\n\n if isinstance(path_cfg, dict):\n return _expand_dict(path_cfg, alias_dict)\n\n # assume tuple or list\n return _expand_tuple(path_cfg, alias_dict, overriding_kargs)", "docstring": "expand a path config\n\nArgs:\n path_cfg (str, tuple, dict): a config for path\n alias_dict (dict): a dict for aliases\n overriding_kargs (dict): to be used for recursive call", "source": "juraj_google_style"} +{"code": "def _generate_legacy_type_checks(types=()):\n\n types = dict(types)\n\n def gen_type_check(pytypes):\n pytypes = _utils.flatten(pytypes)\n\n def type_check(checker, instance):\n if isinstance(instance, bool):\n if bool not in pytypes:\n return False\n return isinstance(instance, pytypes)\n\n return type_check\n\n definitions = {}\n for typename, pytypes in iteritems(types):\n definitions[typename] = gen_type_check(pytypes)\n\n return definitions", "docstring": "Generate newer-style type checks out of JSON-type-name-to-type mappings.\n\nArgs:\n types (dict):\n\n A mapping of type names to their Python types\n\nReturns:\n A dictionary of definitions to pass to `TypeChecker`", "source": "juraj_google_style"} +{"code": "def create(self, value):\n\n\n # Explicitly check with len such that non-sequence types throw.\n if self._optional and (value is None or len(value) == 0):\n return None\n\n if hasattr(self._type, 'resource_type'):\n # Our type is a resource, so ensure we have a dict of title to\n # parameters\n if not isinstance(value, dict):\n raise ValueError(\"Resources must be specified as a dict of \"\n \"title to parameters\")\n if not self._many and len(value) > 1:\n raise ValueError(\"Only one resource can be provided for this \"\n \"TroposphereType variable\")\n\n result = [\n self._type.from_dict(title, v) for title, v in value.items()\n ]\n else:\n # Our type is for properties, not a resource, so don't use\n # titles\n if self._many:\n result = [self._type.from_dict(None, v) for v in value]\n elif not isinstance(value, dict):\n raise ValueError(\"TroposphereType for a single non-resource\"\n \"type must be specified as a dict of \"\n \"parameters\")\n else:\n result = [self._type.from_dict(None, value)]\n\n if self._validate:\n for v in result:\n v._validate_props()\n\n return result[0] if not self._many else result", "docstring": "Create the troposphere type from the value.\n\nArgs:\n value (Union[dict, list]): A dictionary or list of dictionaries\n (see class documentation for details) to use as parameters to\n create the Troposphere type instance.\n Each dictionary will be passed to the `from_dict` method of the\n type.\n\nReturns:\n Union[list, type]: Returns the value converted to the troposphere\n type", "source": "juraj_google_style"} +{"code": "def write_image(self, stream, image_format=\"svg\", **kwargs):\n\n plt = self.get_plot(**kwargs)\n\n f = plt.gcf()\n f.set_size_inches((12, 10))\n\n plt.savefig(stream, format=image_format)", "docstring": "Writes the phase diagram to an image in a stream.\n\nArgs:\n stream:\n stream to write to. Can be a file stream or a StringIO stream.\n image_format\n format for image. Can be any of matplotlib supported formats.\n Defaults to svg for best results for vector graphics.\n \\\\*\\\\*kwargs: Pass through to get_plot functino.", "source": "juraj_google_style"} +{"code": "def has_types(self, types, all_=True):\n\n func = all if all_ else any\n return func([self.get_stim(t) for t in listify(types)])", "docstring": "Check whether the current component list matches all Stim types\n in the types argument.\n\nArgs:\n types (Stim, list): a Stim class or iterable of Stim classes.\n all_ (bool): if True, all input types must match; if False, at\n least one input type must match.\n\nReturns:\n True if all passed types match at least one Stim in the component\n list, otherwise False.", "source": "juraj_google_style"} +{"code": "def macro_state(self, micro_state):\n\n assert len(micro_state) == len(self.micro_indices)\n\n reindexed = self.reindex()\n return utils.state_of(reindexed.output_indices, micro_state)", "docstring": "Compute the macro-state of this blackbox.\n\n This is just the state of the blackbox's output indices.\n\nArgs:\n micro_state (tuple[int]): The state of the micro-elements in the\n blackbox.\n\nReturns:\n tuple[int]: The state of the output indices.", "source": "juraj_google_style"} +{"code": "def _parse_parameters(val_type, val):\n\n if val_type == \"logical\":\n return val == \"T\"\n elif val_type == \"int\":\n return int(val)\n elif val_type == \"string\":\n return val.strip()\n else:\n return float(val)", "docstring": "Helper function to convert a Vasprun parameter into the proper type.\n Boolean, int and float types are converted.\n\nArgs:\n val_type: Value type parsed from vasprun.xml.\n val: Actual string value parsed for vasprun.xml.", "source": "juraj_google_style"} +{"code": "def __init__(self, *compressed_files, **kwargs):\n\n self._files = []\n self._prefixes = defaultdict(lambda: set(['']))\n self._extract = kwargs.get('extract', False)\n self._supersede = kwargs.get('supersede', False)\n self._match_version = kwargs.get('_match_version', True)\n self._local_warned = False\n\n for f in compressed_files:\n if isinstance(f, zipfile.ZipFile):\n bin_package = any(n.endswith('.so') or n.endswith('.pxd') or n.endswith('.dylib')\n for n in f.namelist())\n need_extract = True\n elif isinstance(f, tarfile.TarFile):\n bin_package = any(m.name.endswith('.so') or m.name.endswith('.pxd') or m.name.endswith('.dylib')\n for m in f.getmembers())\n need_extract = True\n elif isinstance(f, dict):\n bin_package = any(name.endswith('.so') or name.endswith('.pxd') or name.endswith('.dylib')\n for name in iterkeys(f))\n need_extract = False\n elif isinstance(f, list):\n bin_package = any(name.endswith('.so') or name.endswith('.pxd') or name.endswith('.dylib')\n for name in f)\n need_extract = False\n else:\n raise TypeError('Compressed file can only be zipfile.ZipFile or tarfile.TarFile')\n\n if bin_package:\n if not ALLOW_BINARY:\n raise SystemError('Cannot load binary package. It is quite possible that you are using an old '\n 'MaxCompute service which does not support binary packages. If this is '\n 'not true, please set `odps.isolation.session.enable` to True or ask your '\n 'project owner to change project-level configuration.')\n if need_extract:\n f = self._extract_archive(f)\n\n prefixes = set([''])\n dir_prefixes = set()\n if isinstance(f, zipfile.ZipFile):\n for name in f.namelist():\n name = name if name.endswith('/') else (name.rsplit('/', 1)[0] + '/')\n if name in prefixes:\n continue\n try:\n f.getinfo(name + '__init__.py')\n except KeyError:\n prefixes.add(name)\n elif isinstance(f, tarfile.TarFile):\n for member in f.getmembers():\n name = member.name if member.isdir() else member.name.rsplit('/', 1)[0]\n if name in prefixes:\n continue\n try:\n f.getmember(name + '/__init__.py')\n except KeyError:\n prefixes.add(name + '/')\n elif isinstance(f, (list, dict)):\n # Force ArchiveResource to run under binary mode to resolve manually\n # opening __file__ paths in pure-python code.\n if ALLOW_BINARY:\n bin_package = True\n\n rendered_names = set()\n for name in f:\n name = name.replace(os.sep, '/')\n rendered_names.add(name)\n\n for name in rendered_names:\n name = name if name.endswith('/') else (name.rsplit('/', 1)[0] + '/')\n if name in prefixes or '/tests/' in name:\n continue\n if name + '__init__.py' not in rendered_names:\n prefixes.add(name)\n dir_prefixes.add(name)\n else:\n if '/' in name.rstrip('/'):\n ppath = name.rstrip('/').rsplit('/', 1)[0]\n else:\n ppath = ''\n prefixes.add(ppath)\n dir_prefixes.add(ppath)\n\n if bin_package:\n path_patch = []\n for p in sorted(dir_prefixes):\n if p in sys.path:\n continue\n parent_exist = False\n for pp in path_patch:\n if p[:len(pp)] == pp:\n parent_exist = True\n break\n if parent_exist:\n continue\n path_patch.append(p)\n if self._supersede:\n sys.path = path_patch + sys.path\n else:\n sys.path = sys.path + path_patch\n else:\n self._files.append(f)\n if prefixes:\n self._prefixes[id(f)] = sorted(prefixes)", "docstring": "Constructor.\n\nArgs:\n compressed_files zipfile.ZipFile or tarfile.TarFile", "source": "juraj_google_style"} +{"code": "def create_pipeline(url, auth, json_payload, verify_ssl):\n\n title = json_payload['pipelineConfig']['title']\n description = json_payload['pipelineConfig']['description']\n params = {'description':description, 'autoGeneratePipelineId':True}\n logging.info('No destination pipeline ID provided. Creating a new pipeline: ' + title)\n put_result = requests.put(url + '/' + title, params=params, headers=X_REQ_BY, auth=auth, verify=verify_ssl)\n put_result.raise_for_status()\n create_json = put_result.json()\n logging.debug(create_json)\n logging.info('Pipeline creation successful.')\n return create_json", "docstring": "Create a new pipeline.\n\nArgs:\n url (str): the host url in the form 'http://host:port/'.\n auth (tuple): a tuple of username, and password.\n json_payload (dict): the exported json paylod as a dictionary.\n verify_ssl (bool): whether to verify ssl certificates\n\nReturns:\n dict: the response json", "source": "juraj_google_style"} +{"code": "def sibling(self, name: InstanceName) -> \"ObjectMember\":\n\n ssn = self.parinst._member_schema_node(name)\n try:\n sibs = self.siblings.copy()\n newval = sibs.pop(name)\n sibs[self.name] = self.value\n return ObjectMember(name, sibs, newval, self.parinst,\n ssn, self.timestamp)\n except KeyError:\n raise NonexistentInstance(self.json_pointer(),\n f\"member '{name}'\") from None", "docstring": "Return an instance node corresponding to a sibling member.\n\nArgs:\n name: Instance name of the sibling member.\n\nRaises:\n NonexistentSchemaNode: If member `name` is not permitted by the\n schema.\n NonexistentInstance: If sibling member `name` doesn't exist.", "source": "juraj_google_style"} +{"code": "def get_package_hashes(filename):\n\n log.debug('Getting package hashes')\n filename = os.path.abspath(filename)\n with open(filename, 'rb') as f:\n data = f.read()\n\n _hash = hashlib.sha256(data).hexdigest()\n log.debug('Hash for file %s: %s', filename, _hash)\n return _hash", "docstring": "Provides hash of given filename.\n\nArgs:\n filename (str): Name of file to hash\n\nReturns:\n (str): sha256 hash", "source": "juraj_google_style"} +{"code": "def eigenvalues(df):\n\n corr = np.corrcoef(df, rowvar=0)\n eigvals = np.linalg.eigvals(corr)\n return pd.Series(eigvals, df.columns, name='Eigenvalue')", "docstring": "Returns a pandas Series with eigenvalues of the correlation matrix.\n\nArgs:\n df: pandas DataFrame with columns to run diagnostics on", "source": "juraj_google_style"} +{"code": "def __init__(self, instrumentation_key, *args, **kwargs):\n\n if not instrumentation_key:\n raise Exception('Instrumentation key was required but not provided')\n telemetry_channel = kwargs.get('telemetry_channel')\n if 'telemetry_channel' in kwargs:\n del kwargs['telemetry_channel']\n self.client = applicationinsights.TelemetryClient(instrumentation_key, telemetry_channel)\n super(LoggingHandler, self).__init__(*args, **kwargs)", "docstring": "Initialize a new instance of the class.\n\nArgs:\n instrumentation_key (str). the instrumentation key to use while sending telemetry to the service.", "source": "juraj_google_style"} +{"code": "def dump_logs(json_data, project_mapping, tag_name):\n\n pwd_dir_path, dump_file_name = _prepare_dump_info(project_mapping, tag_name)\n dump_json_file(json_data, pwd_dir_path, dump_file_name)", "docstring": "dump tests data to json file.\n the dumped file is located in PWD/logs folder.\n\nArgs:\n json_data (list/dict): json data to dump\n project_mapping (dict): project info\n tag_name (str): tag name, loaded/parsed/summary", "source": "juraj_google_style"} +{"code": "def add_case(self, case_obj, vtype='snv', mode='vcf', ped_svg=None):\n\n new_case = Case(case_id=case_obj.case_id,\n name=case_obj.name,\n variant_source=case_obj.variant_source,\n variant_type=vtype,\n variant_mode=mode,\n pedigree=ped_svg,\n compressed=case_obj.compressed,\n tabix_index=case_obj.tabix_index)\n\n # build individuals\n inds = [Individual(\n ind_id=ind.ind_id,\n name=ind.name,\n mother=ind.mother,\n father=ind.father,\n sex=ind.sex,\n phenotype=ind.phenotype,\n ind_index=ind.ind_index,\n variant_source=ind.variant_source,\n bam_path=ind.bam_path,\n ) for ind in case_obj.individuals]\n new_case.individuals = inds\n\n if self.case(new_case.case_id):\n logger.warning(\"Case already exists in database!\")\n else:\n self.session.add(new_case)\n self.save()\n return new_case", "docstring": "Load a case with individuals.\n\nArgs:\n case_obj (puzzle.models.Case): initialized case model", "source": "juraj_google_style"} +{"code": "def __register_class(self, parsed_config):\n\n methods = parsed_config.get('methods')\n if not methods:\n return\n\n # Determine the name of the class that implements this configuration.\n service_classes = set()\n for method in methods.itervalues():\n rosy_method = method.get('rosyMethod')\n if rosy_method and '.' in rosy_method:\n method_class = rosy_method.split('.', 1)[0]\n service_classes.add(method_class)\n\n for service_class in service_classes:\n if service_class in self.__registered_classes:\n raise api_exceptions.ApiConfigurationError(\n 'API class %s has already been registered.' % service_class)\n self.__registered_classes.add(service_class)", "docstring": "Register the class implementing this config, so we only add it once.\n\nArgs:\n parsed_config: The JSON object with the API configuration being added.\n\nRaises:\n ApiConfigurationError: If the class has already been registered.", "source": "juraj_google_style"} +{"code": "def get_artifact_filename(self, package_name, artifact_name):\n\n\n project_name = self.packages.normalize(package_name)\n return self.records.get((project_name, artifact_name))", "docstring": "Similar to pkg_resources.resource_filename, however this works\n with the information cached in this registry instance, and\n arguments are not quite the same.\n\nArgs:\n package_name\n The name of the package to get the artifact from\n artifact_name\n The exact name of the artifact.\n\n Returns the path of where the artifact should be if it has been\n declared, otherwise None.", "source": "juraj_google_style"} +{"code": "def _build_command(self, python_executable, lib_dir_fq, proxy_enabled):\n\n exe_command = [\n os.path.expanduser(python_executable),\n '-m',\n 'pip',\n 'install',\n '-r',\n self.requirements_file,\n '--ignore-installed',\n '--quiet',\n '--target',\n lib_dir_fq,\n ]\n if self.args.no_cache_dir:\n exe_command.append('--no-cache-dir')\n\n if proxy_enabled:\n # trust the pypi hosts to avoid ssl errors\n trusted_hosts = ['pypi.org', 'pypi.python.org', 'files.pythonhosted.org']\n\n for host in trusted_hosts:\n exe_command.append('--trusted-host')\n exe_command.append(host)\n\n return exe_command", "docstring": "Build the pip command for installing dependencies.\n\nArgs:\n python_executable (str): The fully qualified path of the Python executable.\n lib_dir_fq (str): The fully qualified path of the lib directory.\n\nReturns:\n list: The Python pip command with all required args.", "source": "juraj_google_style"} +{"code": "def rh45(msg):\n\n d = hex2bin(data(msg))\n if d[38] == '0':\n return None\n rh = bin2int(d[39:51]) * 16\n return rh", "docstring": "Radio height.\n\nArgs:\n msg (String): 28 bytes hexadecimal message string\n\nReturns:\n int: radio height in ft", "source": "juraj_google_style"} +{"code": "def _count_tokens(files, file_byte_limit=1e6):\n\n token_counts = collections.defaultdict(int)\n\n for filepath in files:\n with tf.gfile.Open(filepath, mode=\"r\") as reader:\n file_byte_budget = file_byte_limit\n counter = 0\n lines_to_skip = int(reader.size() / (file_byte_budget * 2))\n for line in reader:\n if counter < lines_to_skip:\n counter += 1\n else:\n if file_byte_budget < 0:\n break\n line = line.strip()\n file_byte_budget -= len(line)\n counter = 0\n\n # Add words to token counts\n for token in _split_string_to_tokens(_native_to_unicode(line)):\n token_counts[token] += 1\n return token_counts", "docstring": "Return token counts of words in the files.\n\n Samples file_byte_limit bytes from each file, and counts the words that appear\n in the samples. The samples are semi-evenly distributed across the file.\n\nArgs:\n files: List of filepaths\n file_byte_limit: Max number of bytes that will be read from each file.\n\nReturns:\n Dictionary mapping tokens to the number of times they appear in the sampled\n lines from the files.", "source": "juraj_google_style"} +{"code": "def default_datastore_policy(key):\n\n flag = None\n if key is not None:\n modelclass = model.Model._kind_map.get(key.kind())\n if modelclass is not None:\n policy = getattr(modelclass, '_use_datastore', None)\n if policy is not None:\n if isinstance(policy, bool):\n flag = policy\n else:\n flag = policy(key)\n return flag", "docstring": "Default datastore policy.\n\n This defers to _use_datastore on the Model class.\n\nArgs:\n key: Key instance.\n\nReturns:\n A bool or None.", "source": "juraj_google_style"} +{"code": "def _ConvertListToObject(cls, json_list):\n\n list_value = []\n for json_list_element in json_list:\n if isinstance(json_list_element, dict):\n list_value.append(cls._ConvertDictToObject(json_list_element))\n\n elif isinstance(json_list_element, list):\n list_value.append(cls._ConvertListToObject(json_list_element))\n\n else:\n list_value.append(json_list_element)\n\n return list_value", "docstring": "Converts a JSON list into an object.\n\nArgs:\n json_list (list[object]): JSON serialized objects.\n\nReturns:\n list[object]: a deserialized list.", "source": "juraj_google_style"} +{"code": "def wait_until_page_ready(page_object, timeout=WTF_TIMEOUT_MANAGER.NORMAL):\n\n try:\n do_until(lambda: page_object.webdriver.execute_script(\"return document.readyState\").lower()\n == 'complete', timeout)\n except wait_utils.OperationTimeoutError:\n raise PageUtilOperationTimeoutError(\n \"Timeout occurred while waiting for page to be ready.\")", "docstring": "Waits until document.readyState == Complete (e.g. ready to execute javascript commands)\n\nArgs:\n page_object (PageObject) : PageObject class\n\n Kwargs:\n timeout (number) : timeout period", "source": "juraj_google_style"} +{"code": "def tail(self, n):\n\n # See head for an explanation of the transposed behavior\n if n < 0:\n n = max(0, len(self.index) + n)\n if self._is_transposed:\n result = self.__constructor__(\n self.data.transpose().take(1, -n).transpose(),\n self.index[-n:],\n self.columns,\n self._dtype_cache,\n )\n result._is_transposed = True\n else:\n result = self.__constructor__(\n self.data.take(0, -n), self.index[-n:], self.columns, self._dtype_cache\n )\n return result", "docstring": "Returns the last n rows.\n\nArgs:\n n: Integer containing the number of rows to return.\n\nReturns:\n DataManager containing the last n rows of the original DataManager.", "source": "juraj_google_style"} +{"code": "def parse_individuals(samples):\n\n individuals = []\n if len(samples) == 0:\n raise PedigreeError(\"No samples could be found\")\n\n ind_ids = set()\n for sample_info in samples:\n parsed_ind = parse_individual(sample_info)\n individuals.append(parsed_ind)\n ind_ids.add(parsed_ind['individual_id'])\n\n # Check if relations are correct\n for parsed_ind in individuals:\n father = parsed_ind['father']\n if (father and father != '0'):\n if father not in ind_ids:\n raise PedigreeError('father %s does not exist in family' % father)\n mother = parsed_ind['mother']\n if (mother and mother != '0'):\n if mother not in ind_ids:\n raise PedigreeError('mother %s does not exist in family' % mother)\n\n return individuals", "docstring": "Parse the individual information\n\n Reformat sample information to proper individuals\n\nArgs:\n samples(list(dict))\n\nReturns:\n individuals(list(dict))", "source": "juraj_google_style"} +{"code": "def is_element_in_database(element='', database='ENDF_VII'):\n\n if element == '':\n return False\n\n list_entry_from_database = get_list_element_from_database(database=database)\n if element in list_entry_from_database:\n return True\n return False", "docstring": "will try to find the element in the folder (database) specified\n\n Parameters:\n ==========\n element: string. Name of the element. Not case sensitive\n database: string (default is 'ENDF_VII'). Name of folder that has the list of elements\n\nReturns:\n =======\n bool: True if element was found in the database\n False if element could not be found", "source": "juraj_google_style"} +{"code": "def draw_mask(im, mask, alpha=0.5, color=None):\n\n if color is None:\n color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]\n im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2),\n im * (1 - alpha) + color * alpha, im)\n im = im.astype('uint8')\n return im", "docstring": "Overlay a mask on top of the image.\n\nArgs:\n im: a 3-channel uint8 image in BGR\n mask: a binary 1-channel image of the same size\n color: if None, will choose automatically", "source": "juraj_google_style"} +{"code": "def heightmap_clamp(hm: np.ndarray, mi: float, ma: float) -> None:\n\n hm.clip(mi, ma)", "docstring": "Clamp all values on this heightmap between ``mi`` and ``ma``\n\nArgs:\n hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.\n mi (float): The lower bound to clamp to.\n ma (float): The upper bound to clamp to.\n\n .. deprecated:: 2.0\n Do ``hm.clip(mi, ma)`` instead.", "source": "juraj_google_style"} +{"code": "def propagate(self, date):\n\n\n if self.propagator.orbit is not self:\n self.propagator.orbit = self\n\n return self.propagator.propagate(date)", "docstring": "Propagate the orbit to a new date\n\nArgs:\n date (Date)\n\nReturns:\n Orbit", "source": "juraj_google_style"} +{"code": "def _head(self, client_kwargs):\n\n with _handle_client_exception():\n # Object\n if 'obj' in client_kwargs:\n return self.client.head_object(**client_kwargs)\n\n # Container\n return self.client.head_container(**client_kwargs)", "docstring": "Returns object HTTP header.\n\nArgs:\n client_kwargs (dict): Client arguments.\n\nReturns:\n dict: HTTP header.", "source": "juraj_google_style"} +{"code": "def delete_handler(Model, name=None, **kwds):\n\n # necessary imports\n from nautilus.database import db\n\n async def action_handler(service, action_type, payload, props, notify=True, **kwds):\n # if the payload represents a new instance of `model`\n if action_type == get_crud_action('delete', name or Model):\n try:\n # the props of the message\n message_props = {}\n # if there was a correlation id in the request\n if 'correlation_id' in props:\n # make sure it ends up in the reply\n message_props['correlation_id'] = props['correlation_id']\n # the id in the payload representing the record to delete\n record_id = payload['id'] if 'id' in payload else payload['pk']\n # get the model matching the payload\n try:\n model_query = Model.select().where(Model.primary_key() == record_id)\n except KeyError:\n raise RuntimeError(\"Could not find appropriate id to remove service record.\")\n # remove the model instance\n model_query.get().delete_instance()\n # if we need to tell someone about what happened\n if notify:\n # publish the success event\n await service.event_broker.send(\n payload='{\"status\":\"ok\"}',\n action_type=change_action_status(action_type, success_status()),\n **message_props\n )\n\n # if something goes wrong\n except Exception as err:\n # if we need to tell someone about what happened\n if notify:\n # publish the error as an event\n await service.event_broker.send(\n payload=str(err),\n action_type=change_action_status(action_type, error_status()),\n **message_props\n )\n # otherwise we aren't supposed to notify\n else:\n # raise the exception normally\n raise err\n\n\n # return the handler\n return action_handler", "docstring": "This factory returns an action handler that deletes a new instance of\n the specified model when a delete action is recieved, assuming the\n action follows nautilus convetions.\n\nArgs:\n Model (nautilus.BaseModel): The model to delete when the action\n received.\n\nReturns:\n function(type, payload): The action handler for this model", "source": "juraj_google_style"} +{"code": "def download_listing(self, file: Optional[IO],\n duration_timeout: Optional[float]=None) -> \\\n ListingResponse:\n\n if self._session_state != SessionState.directory_request_sent:\n raise RuntimeError('File request not sent')\n\n self._session_state = SessionState.file_request_sent\n\n yield from self.download(file=file, rewind=False,\n duration_timeout=duration_timeout)\n\n try:\n if self._response.body.tell() == 0:\n listings = ()\n elif self._listing_type == 'mlsd':\n self._response.body.seek(0)\n\n machine_listings = wpull.protocol.ftp.util.parse_machine_listing(\n self._response.body.read().decode('utf-8',\n errors='surrogateescape'),\n convert=True, strict=False\n )\n listings = list(\n wpull.protocol.ftp.util.machine_listings_to_file_entries(\n machine_listings\n ))\n else:\n self._response.body.seek(0)\n\n file = io.TextIOWrapper(self._response.body, encoding='utf-8',\n errors='surrogateescape')\n\n listing_parser = ListingParser(file=file)\n\n listings = list(listing_parser.parse_input())\n\n _logger.debug('Listing detected as %s', listing_parser.type)\n\n # We don't want the file to be closed when exiting this function\n file.detach()\n\n except (ListingError, ValueError) as error:\n raise ProtocolError(*error.args) from error\n\n self._response.files = listings\n\n self._response.body.seek(0)\n\n self._session_state = SessionState.response_received\n\n return self._response", "docstring": "Read file listings.\n\nArgs:\n file: A file object or asyncio stream.\n duration_timeout: Maximum time in seconds of which the\n entire file must be read.\n\nReturns:\n A Response populated the file listings\n\n Be sure to call :meth:`start_file_listing` first.\n\n Coroutine.", "source": "juraj_google_style"} +{"code": "def get_attr_value(self, attr_key, el_idx=0):\n\n return self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key]", "docstring": "Return the value of the selected attribute in the selected element.\n\nArgs:\n attr_key : str\n Name of attribute for which to search\n\n el_idx : int\n Index of element to use in the event that there are multiple sibling\n elements with the same name.\n\nReturns:\n str : Value of the selected attribute in the selected element.", "source": "juraj_google_style"} +{"code": "def getpexts(lsp):\n\n lines=lsp.split('\\n');\n #unfortunately regex doesn't work here\n lns,planens = zip(\n *[ (i,int(re.search('^ *extract *([0-9]+)',line).group(1)))\n for i,line in enumerate(lines)\n if re.search('^ *extract *[0-9]+', line)]);\n if len(lns) == 0: return [];\n end = lns[-1];\n\n for i,line in enumerate(lines[end+1:]):\n if re.match(' *\\[',line): break;\n end += i;\n lineranges = zip(lns,(lns+(end,))[1:]);\n planes=dict()\n for (i,end),plane in zip(lineranges,planens):\n d=dict();\n labels = [\n 'species',\n 'direction',\n 'position',];\n datarx = [\n '^ *species *([0-9]+)',\n '^ *direction *([xXyYzZ])',\n '^ *at *(.*)',];\n convs = [\n lambda s: int(s),\n lambda i: i,\n lambda s: np.array(\n map(float,s.split(' '))),\n ];\n for line in lines[i:end]:\n for label,rx,conv in zip(labels,datarx,convs):\n if re.match(rx,line):\n d[label]=conv(re.match(rx,line).group(1));\n pass\n pass\n planes[plane] = d;\n return planes;", "docstring": "Get information from pext planes. This might or might not work, use with\n caution!\n\n Parameters:\n -----------\n\n lsp : .lsp string\n\n Returns a list of dicts with information for all pext planes", "source": "juraj_google_style"} +{"code": "def _create_metric_extractor(metric_name):\n\n def extractor_fn(session_or_group):\n metric_value = _find_metric_value(session_or_group,\n metric_name)\n return metric_value.value if metric_value else None\n\n return extractor_fn", "docstring": "Returns function that extracts a metric from a session group or a session.\n\nArgs:\n metric_name: tensorboard.hparams.MetricName protobuffer. Identifies the\n metric to extract from the session group.\n\nReturns:\n A function that takes a tensorboard.hparams.SessionGroup or\n tensorborad.hparams.Session protobuffer and returns the value of the metric\n identified by 'metric_name' or None if the value doesn't exist.", "source": "juraj_google_style"} +{"code": "def __init__(self, while_definition):\n\n logger.debug(\"starting\")\n\n if isinstance(while_definition, dict):\n # errorOnMax: optional. defaults False\n self.error_on_max = while_definition.get('errorOnMax', False)\n\n # max: optional. defaults None.\n self.max = while_definition.get('max', None)\n\n # sleep: optional. defaults 0.\n self.sleep = while_definition.get('sleep', 0)\n\n # stop: optional. defaults None.\n self.stop = while_definition.get('stop', None)\n\n if self.stop is None and self.max is None:\n logger.error(f\"while decorator missing both max and stop.\")\n raise PipelineDefinitionError(\"the while decorator must have \"\n \"either max or stop, or both. \"\n \"But not neither. Note that \"\n \"setting stop: False with no \"\n \"max is an infinite loop. If \"\n \"an infinite loop is really \"\n \"what you want, set stop: False\")\n else:\n # if it isn't a dict, pipeline configuration is wrong.\n logger.error(f\"while decorator definition incorrect.\")\n raise PipelineDefinitionError(\"while decorator must be a dict \"\n \"(i.e a map) type.\")\n\n logger.debug(\"done\")", "docstring": "Initialize the class. No duh, huh.\n\n You can happily expect the initializer to initialize all\n member attributes.\n\nArgs:\n while_definition: dict. This is the actual while definition as it\n exists in the pipeline yaml.", "source": "juraj_google_style"} +{"code": "def rename(blocks, scope, stype):\n\n for p in blocks:\n if isinstance(p, stype):\n p.tokens[0].parse(scope)\n if p.tokens[1]:\n scope.push()\n scope.current = p.tokens[0]\n rename(p.tokens[1], scope, stype)\n scope.pop()", "docstring": "Rename all sub-blocks moved under another\n block. (mixins)\n\nArgs:\n lst (list): block list\n scope (object): Scope object", "source": "juraj_google_style"} +{"code": "def min(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':\n\n return cls._binary_op(x, y, tf.minimum, tf.float32)", "docstring": "Returns a TensorFluent for the minimum function.\n\nArgs:\n x: The first operand.\n y: The second operand.\n\nReturns:\n A TensorFluent wrapping the minimum function.", "source": "juraj_google_style"} +{"code": "def convert_reduce_sum(params, w_name, scope_name, inputs, layers, weights, names):\n\n print('Converting reduce_sum ...')\n\n keepdims = params['keepdims'] > 0\n axis = params['axes']\n\n def target_layer(x, keepdims=keepdims, axis=axis):\n import keras.backend as K\n return K.sum(x, keepdims=keepdims, axis=axis)\n\n lambda_layer = keras.layers.Lambda(target_layer)\n layers[scope_name] = lambda_layer(layers[inputs[0]])", "docstring": "Convert reduce_sum layer.\n\nArgs:\n params: dictionary with layer parameters\n w_name: name prefix in state_dict\n scope_name: pytorch scope name\n inputs: pytorch node inputs\n layers: dictionary with keras tensors\n weights: pytorch state_dict\n names: use short names for keras layers", "source": "juraj_google_style"} +{"code": "def pad(self, file, size=6):\n\n buffer = ''\n for element in self.splitter.split(file):\n if _payload_size_within_limit(buffer + element, size):\n buffer += element\n else:\n tmp = buffer\n buffer = element\n yield tmp\n if _validate_payload_size(buffer, size):\n yield buffer", "docstring": "Group together as many records as possible to fit in the specified size\n\nArgs:\n file (str): file path to read the records from.\n size (int): maximum size in MB that each group of records will be fitted to.\n passing 0 means unlimited size.\n\nReturns:\n generator of records", "source": "juraj_google_style"} +{"code": "def sample_with_temperature(x, dim, temperature=1.0, dtype=tf.int32, name=None):\n\n dim = convert_to_dimension(dim)\n with tf.name_scope(name, default_name=\"sample_with_temperature\"):\n if temperature != 0.0:\n # gumbel trick.\n # Note: we don't want to generate 0 or 1 because:\n # * -log(-log(0)) is -infinity\n # * -log(-log(1)) is +infinity.\n # np.finfo(x.dtype.as_numpy_dtype).tiny doesn't work on bfloat16\n tiny_val = 1e-9\n g = -log(-log(\n random_uniform(\n x.mesh,\n x.shape,\n minval=tiny_val,\n maxval=1.,\n dtype=x.dtype)))\n x += g * temperature\n return argmax(x, dim, dtype, name)", "docstring": "Either argmax or random sampling.\n\nArgs:\n x: a Tensor.\n dim: a Dimension in x.shape.dims\n temperature: a float 0.0=argmax 1.0=random\n dtype: a tf.dtype (for the output)\n name: an optional string\n\nReturns:\n a Tensor with type dtype.", "source": "juraj_google_style"} +{"code": "def tag_versions(repo_path):\n\n repo = dulwich.repo.Repo(repo_path)\n tags = get_tags(repo)\n maj_version = 0\n feat_version = 0\n fix_version = 0\n last_maj_version = 0\n last_feat_version = 0\n result = []\n\n for commit_sha, children in reversed(\n get_children_per_first_parent(repo_path).items()\n ):\n commit = get_repo_object(repo, commit_sha)\n maj_version, feat_version, fix_version = get_version(\n commit=commit,\n tags=tags,\n maj_version=maj_version,\n feat_version=feat_version,\n fix_version=fix_version,\n children=children,\n )\n if (\n last_maj_version != maj_version or\n last_feat_version != feat_version\n ):\n last_maj_version = maj_version\n last_feat_version = feat_version\n tag_name = 'refs/tags/v%d.%d' % (maj_version, feat_version)\n if ON_PYTHON3:\n repo[str.encode(tag_name)] = commit\n else:\n repo[tag_name] = commit\n\n result.append(\n 'v%d.%d -> %s' % (maj_version, feat_version, commit_sha)\n )\n\n return '\\n'.join(result)", "docstring": "Given a repo will add a tag for each major version.\n\nArgs:\n repo_path(str): path to the git repository to tag.", "source": "juraj_google_style"} +{"code": "def smart_open(filepath):\n\n if filepath[-2:] == \"gz\":\n mode = \"rt\"\n fopen = gzip.open\n else:\n mode = \"r\"\n fopen = open\n if sys.version_info[0] < 3:\n fh = fopen(filepath, mode)\n else:\n fh = fopen(filepath, mode, errors=\"ignore\")\n try:\n yield fh\n except IOError:\n fh.close()\n finally:\n fh.close()", "docstring": "Open file intelligently depending on the source and python version.\n\nArgs:\n filepath (:obj:`str`): Path to the file.\n\nYields:\n Context manager for file handle.", "source": "juraj_google_style"} +{"code": "def overlay_boxes(self, image, predictions):\n\n labels = predictions.get_field(\"labels\")\n boxes = predictions.bbox\n\n colors = self.compute_colors_for_labels(labels).tolist()\n\n for box, color in zip(boxes, colors):\n box = box.to(torch.int64)\n top_left, bottom_right = box[:2].tolist(), box[2:].tolist()\n image = cv2.rectangle(\n image, tuple(top_left), tuple(bottom_right), tuple(color), 1\n )\n\n return image", "docstring": "Adds the predicted boxes on top of the image\n\nArgs:\n image (np.ndarray): an image as returned by OpenCV\n predictions (BoxList): the result of the computation by the model.\n It should contain the field `labels`.", "source": "juraj_google_style"} +{"code": "def save(self, path):\n\n with open(path, 'w') as f:\n f.write(self.contents())", "docstring": "Save svg as file(.svg)\n\nArgs:\n path (str): destination to save file", "source": "juraj_google_style"} +{"code": "def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir,\n epsilon):\n\n dataset_images = [f for f in os.listdir(dataset_batch_dir)\n if f.endswith('.png')]\n image_hashes = {}\n resize_warning = False\n for img_name in dataset_images:\n if not os.path.exists(os.path.join(adv_dir, img_name)):\n logging.warning('Image %s not found in the output', img_name)\n continue\n image = np.array(\n Image.open(os.path.join(dataset_batch_dir, img_name)).convert('RGB'))\n image = image.astype('int32')\n image_max_clip = np.clip(image + epsilon, 0, 255).astype('uint8')\n image_min_clip = np.clip(image - epsilon, 0, 255).astype('uint8')\n # load and resize adversarial image if needed\n adv_image = Image.open(os.path.join(adv_dir, img_name)).convert('RGB')\n # Image.size is reversed compared to np.array.shape\n if adv_image.size[::-1] != image.shape[:2]:\n resize_warning = True\n adv_image = adv_image.resize((image.shape[1], image.shape[0]),\n Image.BICUBIC)\n adv_image = np.array(adv_image)\n clipped_adv_image = np.clip(adv_image,\n image_min_clip,\n image_max_clip)\n Image.fromarray(clipped_adv_image).save(os.path.join(output_dir, img_name))\n # compute hash\n image_hashes[img_name[:-4]] = hashlib.sha1(\n clipped_adv_image.view(np.uint8)).hexdigest()\n if resize_warning:\n logging.warning('One or more adversarial images had incorrect size')\n return image_hashes", "docstring": "Enforces size of perturbation on images, and compute hashes for all images.\n\nArgs:\n dataset_batch_dir: directory with the images of specific dataset batch\n adv_dir: directory with generated adversarial images\n output_dir: directory where to copy result\n epsilon: size of perturbation\n\nReturns:\n dictionary with mapping form image ID to hash.", "source": "juraj_google_style"} +{"code": "def _ParseEntryObject(self, file_object, file_offset):\n\n entry_object_map = self._GetDataTypeMap('systemd_journal_entry_object')\n\n try:\n entry_object, _ = self._ReadStructureFromFileObject(\n file_object, file_offset, entry_object_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError((\n 'Unable to parse entry object at offset: 0x{0:08x} with error: '\n '{1!s}').format(file_offset, exception))\n\n if entry_object.object_type != self._OBJECT_TYPE_ENTRY:\n raise errors.ParseError('Unsupported object type: {0:d}.'.format(\n entry_object.object_type))\n\n if entry_object.object_flags != 0:\n raise errors.ParseError('Unsupported object flags: 0x{0:02x}.'.format(\n entry_object.object_flags))\n\n return entry_object", "docstring": "Parses an entry object.\n\nArgs:\n file_object (dfvfs.FileIO): a file-like object.\n file_offset (int): offset of the entry object relative to the start\n of the file-like object.\n\nReturns:\n systemd_journal_entry_object: entry object.\n\nRaises:\n ParseError: if the entry object cannot be parsed.", "source": "juraj_google_style"} +{"code": "def register_domain(self, domain=0, tokenizer=None, trie=None):\n\n self.domains[domain] = IntentDeterminationEngine(\n tokenizer=tokenizer, trie=trie)", "docstring": "Register a domain with the intent engine.\n\nArgs:\n tokenizer(tokenizer): The tokenizer you wish to use.\n trie(Trie): the Trie() you wish to use.\n domain(str): a string representing the domain you wish to add", "source": "juraj_google_style"} +{"code": "def _get_fbeta_score(true_positives, selected, relevant, beta=1):\n\n precision = 1\n if selected > 0:\n precision = true_positives / selected\n if beta == 0:\n return precision\n recall = 1\n if relevant > 0:\n recall = true_positives / relevant\n if precision > 0 and recall > 0:\n beta2 = beta * beta\n return (1 + beta2) * precision * recall / (beta2 * precision + recall)\n else:\n return 0", "docstring": "Compute Fbeta score.\n\nArgs:\n true_positives: Number of true positive ngrams.\n selected: Number of selected ngrams.\n relevant: Number of relevant ngrams.\n beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only.\n\nReturns:\n Fbeta score.", "source": "juraj_google_style"} +{"code": "def merge_sketches(outdir, sketch_paths):\n\n merge_sketch_path = os.path.join(outdir, 'sistr.msh')\n args = ['mash', 'paste', merge_sketch_path]\n for x in sketch_paths:\n args.append(x)\n args.append(MASH_SKETCH_FILE)\n logging.info('Running Mash paste with command: %s', ' '.join(args))\n p = Popen(args)\n p.wait()\n assert os.path.exists(merge_sketch_path), 'Merged sketch was not created at {}'.format(merge_sketch_path)\n return merge_sketch_path", "docstring": "Merge new Mash sketches with current Mash sketches\n\nArgs:\n outdir (str): output directory to write merged Mash sketch file\n sketch_paths (list of str): Mash sketch file paths for input fasta files\n\nReturns:\n str: output path for Mash sketch file with new and old sketches", "source": "juraj_google_style"} +{"code": "def __init__(self, *args, **kwargs):\n\n super(StateTransaction, self).__init__(*args, **kwargs)\n\n self.Type = TransactionType.StateTransaction", "docstring": "Create an instance.\n\nArgs:\n *args:\n **kwargs:", "source": "juraj_google_style"} +{"code": "def webhook(self, webhook_url):\n\n if not webhook_url:\n raise Exception('Url can not be None')\n\n matcher = re.match(self.__webhook_url_format, webhook_url)\n if not matcher:\n raise Exception('Invalid url format, looking for: ' + self.__webhook_url_format)\n\n self.api_keys(int(matcher.group(1)), matcher.group(2))", "docstring": "Load object with webhook_url\n\nArgs:\n webhook_url (str): full webhook url given by Discord 'create webhook' func", "source": "juraj_google_style"} +{"code": "def render_html(root, options=0, extensions=None):\n\n if extensions is None:\n extensions = _cmark.ffi.NULL\n\n raw_result = _cmark.lib.cmark_render_html(\n root, options, extensions)\n\n return _cmark.ffi.string(raw_result).decode('utf-8')", "docstring": "Render a given syntax tree as HTML.\n\nArgs:\n root (Any): The reference to the root node of the syntax tree.\n options (int): The cmark options.\n extensions (Any): The reference to the syntax extensions, generally\n from :func:`parser_get_syntax_extensions`\n\nReturns:\n str: The rendered HTML.", "source": "juraj_google_style"} +{"code": "def dot_product(p1, p2, o=(0, 0)):\n\n v1 = vector(o, p1)\n v2 = vector(o, p2)\n return v1[0] * v2[0] + v1[1] * v2[1]", "docstring": "Returns dot product\n\nArgs:\n p1, p2: point (x, y)\n o: origin", "source": "juraj_google_style"} +{"code": "def delete_credit_card(self, *, customer_id, credit_card_id):\n\n fmt = 'customers/{}/creditCards/{}'.format(customer_id, credit_card_id)\n return self.client._delete(self.url + fmt, headers=self.get_headers())", "docstring": "Delete a credit card (Token) associated with a user.\n\nArgs:\n customer_id: Identifier of the client of whom you are going to delete the token.\n credit_card_id: Identifier of the token to be deleted.\n\n Returns:", "source": "juraj_google_style"} +{"code": "def _get_mpr_table(self, connection, partition):\n\n # TODO: This is the first candidate for optimization. Add field to partition\n # with table name and update it while table creation.\n # Optimized version.\n #\n # return partition.mpr_table or raise exception\n\n # Not optimized version.\n #\n # first check either partition has materialized view.\n logger.debug(\n 'Looking for materialized view of the partition.\\n partition: {}'.format(partition.name))\n foreign_table = partition.vid\n view_table = '{}_v'.format(foreign_table)\n view_exists = self._relation_exists(connection, view_table)\n if view_exists:\n logger.debug(\n 'Materialized view of the partition found.\\n partition: {}, view: {}'\n .format(partition.name, view_table))\n return view_table\n\n # now check for fdw/virtual table\n logger.debug(\n 'Looking for foreign table of the partition.\\n partition: {}'.format(partition.name))\n foreign_exists = self._relation_exists(connection, foreign_table)\n if foreign_exists:\n logger.debug(\n 'Foreign table of the partition found.\\n partition: {}, foreign table: {}'\n .format(partition.name, foreign_table))\n return foreign_table\n raise MissingTableError('postgres database does not have table for {} partition.'\n .format(partition.vid))", "docstring": "Returns name of the postgres table who stores mpr data.\n\nArgs:\n connection: connection to postgres db who stores mpr data.\n partition (orm.Partition):\n\nReturns:\n str:\n\nRaises:\n MissingTableError: if partition table not found in the db.", "source": "juraj_google_style"} +{"code": "def add_workflow_definitions(sbi_config: dict):\n\n registered_workflows = []\n for i in range(len(sbi_config['processing_blocks'])):\n workflow_config = sbi_config['processing_blocks'][i]['workflow']\n workflow_name = '{}:{}'.format(workflow_config['id'],\n workflow_config['version'])\n if workflow_name in registered_workflows:\n continue\n workflow_definition = dict(\n id=workflow_config['id'],\n version=workflow_config['version'],\n stages=[]\n )\n key = \"workflow_definitions:{}:{}\".format(workflow_config['id'],\n workflow_config['version'])\n DB.save_dict(key, workflow_definition, hierarchical=False)\n registered_workflows.append(workflow_name)", "docstring": "Add any missing SBI workflow definitions as placeholders.\n\n This is a utility function used in testing and adds mock / test workflow\n definitions to the database for workflows defined in the specified\n SBI config.\n\nArgs:\n sbi_config (dict): SBI configuration dictionary.", "source": "juraj_google_style"} +{"code": "def __init__(self, source, lineno, target, what=None):\n\n self.source = source\n self.lineno = lineno\n self.target = target\n self.what = what", "docstring": "Initialization method.\n\nArgs:\n source (Module): source Module.\n lineno (int): number of line at which import statement occurs.\n target (str/Module/Package): the target node.\n what (str): what is imported (optional).", "source": "juraj_google_style"} +{"code": "def run(self, data_loaders, workflow, max_epochs, **kwargs):\n\n assert isinstance(data_loaders, list)\n assert mmcv.is_list_of(workflow, tuple)\n assert len(data_loaders) == len(workflow)\n\n self._max_epochs = max_epochs\n work_dir = self.work_dir if self.work_dir is not None else 'NONE'\n self.logger.info('Start running, host: %s, work_dir: %s',\n get_host_info(), work_dir)\n self.logger.info('workflow: %s, max: %d epochs', workflow, max_epochs)\n self.call_hook('before_run')\n\n while self.epoch < max_epochs:\n for i, flow in enumerate(workflow):\n mode, epochs = flow\n if isinstance(mode, str): # self.train()\n if not hasattr(self, mode):\n raise ValueError(\n 'runner has no method named \"{}\" to run an epoch'.\n format(mode))\n epoch_runner = getattr(self, mode)\n elif callable(mode): # custom train()\n epoch_runner = mode\n else:\n raise TypeError('mode in workflow must be a str or '\n 'callable function, not {}'.format(\n type(mode)))\n for _ in range(epochs):\n if mode == 'train' and self.epoch >= max_epochs:\n return\n epoch_runner(data_loaders[i], **kwargs)\n\n time.sleep(1) # wait for some hooks like loggers to finish\n self.call_hook('after_run')", "docstring": "Start running.\n\nArgs:\n data_loaders (list[:obj:`DataLoader`]): Dataloaders for training\n and validation.\n workflow (list[tuple]): A list of (phase, epochs) to specify the\n running order and epochs. E.g, [('train', 2), ('val', 1)] means\n running 2 epochs for training and 1 epoch for validation,\n iteratively.\n max_epochs (int): Total training epochs.", "source": "juraj_google_style"} +{"code": "def warn_if_element_not_of_class(element, class_suffix, special_ui_components_prefix):\n\n valid_class_names = [\"%s%s\" % (DEFAULT_UI_COMPONENTS_PREFIX, class_suffix)]\n if special_ui_components_prefix is not None:\n valid_class_names.append(\"%s%s\" % (special_ui_components_prefix, class_suffix))\n\n if (not element.hasAttribute('customClass')) or element.attributes['customClass'].value not in valid_class_names:\n logging.warn(\"WARNING: %s is internationalized but isn't one of %s\",\n extract_element_internationalized_comment(element), valid_class_names)", "docstring": "Log a warning if the element is not of the given type (indicating that it is not internationalized).\n\nArgs:\n element: The xib's XML element.\n class_name: The type the element should be, but is missing.\n special_ui_components_prefix: If provided, will not warn about class with this prefix (default is only 'JT')", "source": "juraj_google_style"} +{"code": "def plot_accuracy(data, output_dir_path='.', output_filename='accuracy.png',\n width=10, height=8):\n\n output_path = os.path.join(output_dir_path, output_filename)\n\n max_val_data = get_epoch_max_val_acc(data)\n max_val_label = round(max_val_data['acc'].values[0], 4)\n\n # max_val_epoch = max_val_data['epoch'].values[0]\n max_epoch_data = data[data['epoch'] == data['epoch'].max()]\n\n plot = ggplot(data, aes('epoch', 'acc', color='factor(data)')) + \\\n geom_line(size=1, show_legend=False) + \\\n geom_vline(aes(xintercept='epoch', color='data'),\n data=max_val_data, alpha=0.5, show_legend=False) + \\\n geom_label(aes('epoch', 'acc'), data=max_val_data,\n label=max_val_label, nudge_y=-0.02, va='top', label_size=0,\n show_legend=False) + \\\n geom_text(aes('epoch', 'acc', label='data'), data=max_epoch_data,\n nudge_x=2, ha='center', show_legend=False) + \\\n geom_point(aes('epoch', 'acc'), data=max_val_data,\n show_legend=False) + \\\n labs(y='Accuracy', x='Epochs') + \\\n theme_bw(base_family='Arial', base_size=15) + \\\n scale_color_manual(['#ef8a62', '#67a9cf', \"#f7f7f7\"])\n\n plot.save(output_path, width=width, height=height)", "docstring": "Plot accuracy.\n\nArgs:\n data: Panda dataframe in *the* format.", "source": "juraj_google_style"} +{"code": "def submit(self, job):\n\n self._check_job(job)\n\n if job.workingdir is None:\n job.workingdir = self.default_wdir\n job.imageid = du.create_provisioned_image(self.client, job.image,\n job.workingdir, job.inputs)\n\n container_args = self._generate_container_args(job)\n\n job.rundata.container = self.client.create_container(job.imageid, **container_args)\n self.client.start(job.rundata.container)\n job.rundata.containerid = job.rundata.container['Id']\n job.jobid = job.rundata.containerid", "docstring": "Submit job to the engine\n\nArgs:\n job (pyccc.job.Job): Job to submit", "source": "juraj_google_style"} +{"code": "def join(self, other, **kwargs):\n\n if not isinstance(other, list):\n other = [other]\n return self._join_list_of_managers(other, **kwargs)", "docstring": "Joins a list or two objects together.\n\nArgs:\n other: The other object(s) to join on.\n\nReturns:\n Joined objects.", "source": "juraj_google_style"} +{"code": "def get_object(tree):\n\n if isinstance(tree, Tree):\n if tree.label() == 'DT' or tree.label() == 'POS':\n return ''\n words = []\n for child in tree:\n words.append(get_object(child))\n return ' '.join([_f for _f in words if _f])\n else:\n return tree", "docstring": "Get the object in the tree object.\n\n Method should remove unnecessary letters and words::\n\n the\n a/an\n 's\n\nArgs:\n tree (Tree): Parsed tree structure\n\nReturns:\n Resulting string of tree ``(Ex: \"red car\")``", "source": "juraj_google_style"} +{"code": "def registration_info_request(self, registration_id):\n\n return self.requests_session.get(\n self.INFO_END_POINT + registration_id,\n params={'details': 'true'}\n )", "docstring": "Makes a request for registration info and returns the response object\n\nArgs:\n registration_id: id to be checked\n\nReturns:\n response of registration info request", "source": "juraj_google_style"} +{"code": "def unsubscribe(self, subscription, max=None):\n\n if max is None:\n self._send('UNSUB %d' % subscription.sid)\n self._subscriptions.pop(subscription.sid)\n else:\n subscription.max = max\n self._send('UNSUB %d %s' % (subscription.sid, max))", "docstring": "Unsubscribe will remove interest in the given subject. If max is\n provided an automatic Unsubscribe that is processed by the server\n when max messages have been received\n\nArgs:\n subscription (pynats.Subscription): a Subscription object\n max (int=None): number of messages", "source": "juraj_google_style"} +{"code": "def generate_code(meta, prefix=None, node=False, min=False):\n\n if isinstance(meta, dict):\n url_prefix, auth_header, resources = parse_meta(meta)\n else:\n url_prefix, auth_header, resources = meta\n if prefix is not None:\n url_prefix = prefix\n core = render_core(url_prefix, auth_header, resources)\n if min:\n filename = 'res.web.min.js'\n else:\n filename = 'res.web.js'\n if node:\n filename = 'res.node.js'\n base = read_file(filename)\n return base.replace('\"#res.core.js#\"', core)", "docstring": "Generate res.js\n\nArgs:\n meta: tuple(url_prefix, auth_header, resources) or metadata of API\n\nReturns:\n res.js source code", "source": "juraj_google_style"} +{"code": "def sync_job_info(self, job_name):\n\n job_path = os.path.join(self._logdir, job_name)\n\n if job_name not in self._monitored_jobs:\n self._create_job_info(job_path)\n self._monitored_jobs.add(job_name)\n else:\n self._update_job_info(job_path)\n\n expr_dirs = filter(lambda d: os.path.isdir(os.path.join(job_path, d)),\n os.listdir(job_path))\n\n for expr_dir_name in expr_dirs:\n self.sync_trial_info(job_path, expr_dir_name)\n\n self._update_job_info(job_path)", "docstring": "Load information of the job with the given job name.\n\n 1. Traverse each experiment sub-directory and sync information\n for each trial.\n 2. Create or update the job information, together with the job\n meta file.\n\nArgs:\n job_name (str) name of the Tune experiment", "source": "juraj_google_style"} +{"code": "def as_dtype(type_value):\n\n if isinstance(type_value, DType):\n return type_value\n\n try:\n return _INTERN_TABLE[type_value]\n except KeyError:\n pass\n\n try:\n return _STRING_TO_TF[type_value]\n except KeyError:\n pass\n\n try:\n return _PYTHON_TO_TF[type_value]\n except KeyError:\n pass\n\n if isinstance(type_value, np.dtype):\n # The numpy dtype for strings is variable length. We can not compare\n # dtype with a single constant (np.string does not exist) to decide\n # dtype is a \"string\" type. We need to compare the dtype.type to be\n # sure it's a string type.\n if type_value.type == np.string_ or type_value.type == np.unicode_:\n return string\n\n if isinstance(type_value, (type, np.dtype)):\n for key, val in _NP_TO_TF:\n try:\n if key == type_value:\n return val\n except TypeError as e:\n raise TypeError(\n \"Cannot convert {} to a dtype. {}\".format(type_value, e)\n )\n\n raise TypeError(\"Cannot convert value %r to a TensorFlow DType.\" % type_value)", "docstring": "Converts the given `type_value` to a `DType`.\n\nArgs:\n type_value: A value that can be converted to a `tf.DType` object. This may\n currently be a `tf.DType` object, a [`DataType`\n enum](https://www.tensorflow.org/code/tensorflow/core/framework/types.proto),\n a string type name, or a `numpy.dtype`.\n\nReturns:\n A `DType` corresponding to `type_value`.\n\nRaises:\n TypeError: If `type_value` cannot be converted to a `DType`.", "source": "juraj_google_style"} +{"code": "def ExamineEvent(self, mediator, event):\n\n # TODO: Handle event log entries here also (ie, event id 4697).\n event_data_type = getattr(event, 'data_type', '')\n if event_data_type == 'windows:registry:service':\n # Create and store the service.\n service = WindowsService.FromEvent(event)\n self._service_collection.AddService(service)", "docstring": "Analyzes an event and creates Windows Services as required.\n\n At present, this method only handles events extracted from the Registry.\n\nArgs:\n mediator (AnalysisMediator): mediates interactions between analysis\n plugins and other components, such as storage and dfvfs.\n event (EventObject): event to examine.", "source": "juraj_google_style"} +{"code": "def BuildAdGroupCriterionOperations(adgroup_id):\n\n criterion_operations = [\n {\n # You must specify the xsi_type of operations run by the\n # BatchJobService.\n 'xsi_type': 'AdGroupCriterionOperation',\n 'operand': {\n 'xsi_type': 'BiddableAdGroupCriterion',\n 'adGroupId': adgroup_id,\n 'criterion': {\n 'xsi_type': 'Keyword',\n # Make 10% of keywords invalid to demonstrate error handling.\n 'text': 'mars%s%s' % (uuid.uuid4(),\n '!!!' if i % 10 == 0 else ''),\n 'matchType': 'BROAD'\n }\n },\n 'operator': 'ADD'\n }\n for i in range(KEYWORD_COUNT)]\n\n return criterion_operations", "docstring": "Builds the operations adding a Keyword Criterion to each AdGroup.\n\nArgs:\n adgroup_id: an integer identifying an AdGroup to associate the keywords\n with.\n\nReturns:\n a list containing the operations that will create a new Keyword Criterion\n associated with each provided AdGroup.", "source": "juraj_google_style"} +{"code": "def assignees(self, assignee=None, resource_id=None):\n\n if resource_id is not None:\n self.resource_id(resource_id)\n self._request_uri = '{}/assignees'.format(self._request_uri)\n if assignee is not None:\n self._request_uri = '{}/{}'.format(self._request_uri, assignee)", "docstring": "Add an assignee to a Task\n\n GET: /v2/tasks/{uniqueId}/assignees\n GET: /v2/tasks/{uniqueId}/assignees/{assigneeId}\n POST: /v2/tasks/{uniqueId}/assignees/{assigneeId}\n DELETE: /v2/tasks/{uniqueId}/assignees/{assigneeId}\n\nArgs:\n assignee (Optional [string]): The assignee name.\n resource_id (Optional [string]): The task ID.", "source": "juraj_google_style"} +{"code": "def fetcher_with_object(cls, parent_object, relationship=\"child\"):\n\n\n fetcher = cls()\n fetcher.parent_object = parent_object\n fetcher.relationship = relationship\n\n rest_name = cls.managed_object_rest_name()\n parent_object.register_fetcher(fetcher, rest_name)\n\n return fetcher", "docstring": "Register the fetcher for a served object.\n\n This method will fill the fetcher with `managed_class` instances\n\nArgs:\n parent_object: the instance of the parent object to serve\n\nReturns:\n It returns the fetcher instance.", "source": "juraj_google_style"} +{"code": "def _new_open_bin(self, remaining_rect):\n\n factories_to_delete = set() #\n new_bin = None\n\n for key, binfac in self._empty_bins.items():\n\n # Only return the new bin if at least one of the remaining \n # rectangles fit inside.\n a_rectangle_fits = False\n for _, rect in remaining_rect.items():\n if binfac.fits_inside(rect[0], rect[1]):\n a_rectangle_fits = True\n break\n\n if not a_rectangle_fits:\n factories_to_delete.add(key)\n continue\n\n # Create bin and add to open_bins\n new_bin = binfac.new_bin()\n if new_bin is None:\n continue\n self._open_bins.append(new_bin)\n\n # If the factory was depleted mark for deletion\n if binfac.is_empty():\n factories_to_delete.add(key)\n\n break\n\n # Delete marked factories\n for f in factories_to_delete:\n del self._empty_bins[f]\n\n return new_bin", "docstring": "Extract the next bin where at least one of the rectangles in\n rem\n\nArgs:\n remaining_rect (dict): rectangles not placed yet\n\nReturns:\n PackingAlgorithm: Initialized empty packing bin.\n None: No bin big enough for the rectangle was found", "source": "juraj_google_style"} +{"code": "def decode_bu64(b):\n\n s = b\n s = s.replace(b'-', b'+')\n s = s.replace(b'_', b'/')\n p = len(s) % 4\n if p == 0:\n pass\n elif p == 2:\n s += b'=='\n elif p == 3:\n s += b'='\n else:\n raise ValueError('Illegal Base64url string')\n return base64.standard_b64decode(s)", "docstring": "Encode bytes to a URL safe flavor of Base64 used by JWTs.\n\n - Reverse of encode_bu64().\n\nArgs:\n b: bytes\n URL safe Base64 encoded bytes to encode.\n\nReturns:\n bytes: Decoded bytes.", "source": "juraj_google_style"} +{"code": "def process_streamer(self, streamer, callback=None):\n\n\n index = streamer.index\n\n if index in self._in_progress_streamers:\n raise InternalError(\"You cannot add a streamer again until it has finished streaming.\")\n\n queue_item = QueuedStreamer(streamer, callback)\n self._in_progress_streamers.add(index)\n\n self._logger.debug(\"Streamer %d: queued to send %d readings\", index, queue_item.initial_count)\n self._queue.put_nowait(queue_item)", "docstring": "Start streaming a streamer.\n\nArgs:\n streamer (DataStreamer): The streamer itself.\n callback (callable): An optional callable that will be called as:\n callable(index, success, highest_id_received_from_other_side)", "source": "juraj_google_style"} +{"code": "def __delitem__(self, keyword):\n\n status = False\n if keyword:\n if not self.case_sensitive:\n keyword = keyword.lower()\n current_dict = self.keyword_trie_dict\n character_trie_list = []\n for letter in keyword:\n if letter in current_dict:\n character_trie_list.append((letter, current_dict))\n current_dict = current_dict[letter]\n else:\n # if character is not found, break out of the loop\n current_dict = None\n break\n # remove the characters from trie dict if there are no other keywords with them\n if current_dict and self._keyword in current_dict:\n # we found a complete match for input keyword.\n character_trie_list.append((self._keyword, current_dict))\n character_trie_list.reverse()\n\n for key_to_remove, dict_pointer in character_trie_list:\n if len(dict_pointer.keys()) == 1:\n dict_pointer.pop(key_to_remove)\n else:\n # more than one key means more than 1 path.\n # Delete not required path and keep the other\n dict_pointer.pop(key_to_remove)\n break\n # successfully removed keyword\n status = True\n self._terms_in_trie -= 1\n return status", "docstring": "To remove keyword from the dictionary\n pass the keyword and the clean name it maps to.\n\nArgs:\n keyword : string\n keyword that you want to remove if it's present\n\nExample:\n >>> keyword_processor.add_keyword('Big Apple')\n >>> del keyword_processor['Big Apple']", "source": "juraj_google_style"} +{"code": "def forecast(self, throughputs, backlog_size, num_simulations=10000, max_periods=10000, seed=None):\n\n self._check_throughputs(throughputs)\n results = []\n\n if seed is not None:\n random.seed(seed)\n\n for i in range(0, num_simulations):\n simulated_backlog = backlog_size\n time_unit_count = 0\n while simulated_backlog > 0:\n simulated_backlog -= random.choice(throughputs)\n time_unit_count += 1\n if time_unit_count > max_periods:\n raise ValueError(\"More than {} periods calculated\".format(max_periods))\n results.append(time_unit_count)\n\n return Results(results)", "docstring": "Forecasts how long a backlog will take to complete given the historical values provided.\n\nArgs:\n throughputs(List[int]): Number of units completed per unit of time (stories per week, story points per month, etc.)\n backlog_size(int): Units in the backlog (stories, points, etc.)\n\nReturns:\n results\n Exceptions:\n ValueError: If there aren't any positive throughputs, or the simulation takes too long.", "source": "juraj_google_style"} +{"code": "def _handle_captcha(captcha_data, message=''): # pylint:disable=unused-argument\n\n from tempfile import NamedTemporaryFile\n tmpf = NamedTemporaryFile(suffix='.png')\n tmpf.write(captcha_data)\n tmpf.flush()\n captcha_text = input('Please take a look at the captcha image \"%s\" and provide the code:' % tmpf.name)\n tmpf.close()\n return captcha_text", "docstring": "Called when a captcha must be solved\n Writes the image to a temporary file and asks the user to enter the code.\n\nArgs:\n captcha_data: Bytestring of the PNG captcha image.\n message: Optional. A message from Steam service.\n\nReturns:\n A string containing the solved captcha code.", "source": "juraj_google_style"} +{"code": "def weights_to_cpu(state_dict):\n\n state_dict_cpu = OrderedDict()\n for key, val in state_dict.items():\n state_dict_cpu[key] = val.cpu()\n return state_dict_cpu", "docstring": "Copy a model state_dict to cpu.\n\nArgs:\n state_dict (OrderedDict): Model weights on GPU.\n\nReturns:\n OrderedDict: Model weights on GPU.", "source": "juraj_google_style"} +{"code": "def _or_join(self, terms):\n\n from six import text_type\n\n if isinstance(terms, (tuple, list)):\n if len(terms) > 1:\n return ' | '.join(text_type(t) for t in terms)\n else:\n return terms[0]\n else:\n return terms", "docstring": "Joins terms using OR operator.\n\nArgs:\n terms (list): terms to join\n\nExample:\n self._or_join(['term1', 'term2']) -> 'term1 | term2'\n\nReturns:\n str", "source": "juraj_google_style"} +{"code": "def _load_chunk(dat_path, cat_path, info_path):\n\n dat_array = read_binary_matrix(dat_path)\n # Even if the image is gray scale, we need to add an extra channel dimension\n # to be compatible with tfds.features.Image.\n dat_array = np.expand_dims(dat_array, -1)\n\n cat_array = read_binary_matrix(cat_path)\n\n info_array = read_binary_matrix(info_path)\n info_array = np.copy(info_array) # Make read-only buffer array writable.\n # Azimuth values are 0, 2, 4, .., 34. We divide by 2 to get proper labels.\n info_array[:, 2] = info_array[:, 2] / 2\n\n return dat_array, cat_array, info_array", "docstring": "Loads a data chunk as specified by the paths.\n\nArgs:\n dat_path: Path to dat file of the chunk.\n cat_path: Path to cat file of the chunk.\n info_path: Path to info file of the chunk.\n\nReturns:\n Tuple with the dat, cat, info_arrays.", "source": "juraj_google_style"} +{"code": "def getQueryEngineDescription(self, queryEngine, **kwargs):\n\n response = self.getQueryEngineDescriptionResponse(queryEngine, **kwargs)\n return self._read_dataone_type_response(response, 'QueryEngineDescription')", "docstring": "See Also: getQueryEngineDescriptionResponse()\n\nArgs:\n queryEngine:\n **kwargs:\n\n Returns:", "source": "juraj_google_style"} +{"code": "def save(self, projects):\n\n\n base_path = os.path.expanduser(self.path)\n\n if not os.path.isdir(base_path):\n return\n\n logger.debug(\"Save projects config to %s\", base_path)\n\n for name, data in list(projects.items()):\n project_file_path = self.get_project_config_path(name)\n with open(project_file_path, \"w\") as f:\n yaml.dump(data, stream = f, default_flow_style = False)\n logger.debug(\"Project '%s' config has been writed to '%s'\", name, project_file_path)", "docstring": "Save the projects configs to local path\n\nArgs:\n projects (dict): project_name -> project_data", "source": "juraj_google_style"} +{"code": "def _GetSpecificationStore(cls, format_category):\n\n specification_store = specification.FormatSpecificationStore()\n remainder_list = []\n\n for analyzer_helper in iter(cls._analyzer_helpers.values()):\n if not analyzer_helper.IsEnabled():\n continue\n\n if format_category in analyzer_helper.format_categories:\n format_specification = analyzer_helper.GetFormatSpecification()\n\n if format_specification is not None:\n specification_store.AddSpecification(format_specification)\n else:\n remainder_list.append(analyzer_helper)\n\n return specification_store, remainder_list", "docstring": "Retrieves the specification store for specified format category.\n\nArgs:\n format_category (str): format category.\n\nReturns:\n tuple[FormatSpecificationStore, list[AnalyzerHelper]]: a format\n specification store and remaining analyzer helpers that do not have\n a format specification.", "source": "juraj_google_style"} +{"code": "def replace_variables(self, text):\n\n variables = {\n 'python-executable': str(self._venv_path / 'bin' / 'python')\n }\n return text.format(**variables)", "docstring": "Replace variable placeholders in `text` with values from the virtual env.\n\n The variables are:\n - {python-executable}\n\nArgs:\n text: The text to do replacment int.\n\n Returns: The text after replacement.", "source": "juraj_google_style"} +{"code": "def __init__(self, structure, transformations=None, history=None,\n other_parameters=None):\n\n self.final_structure = structure\n self.history = history or []\n self.other_parameters = other_parameters or {}\n self._undone = []\n\n transformations = transformations or []\n for t in transformations:\n self.append_transformation(t)", "docstring": "Initializes a transformed structure from a structure.\n\nArgs:\n structure (Structure): Input structure\n transformations ([Transformations]): List of transformations to\n apply.\n history (list): Previous history.\n other_parameters (dict): Additional parameters to be added.", "source": "juraj_google_style"} +{"code": "def note_revert(self, note_id, version_id):\n\n return self._get('notes/{0}/revert.json'.format(note_id),\n {'version_id': version_id}, method='PUT', auth=True)", "docstring": "Function to revert a specific note (Requires login) (UNTESTED).\n\n Parameters:\n note_id (int): Where note_id is the note id.\n version_id (int): The note version id to revert to.", "source": "juraj_google_style"} +{"code": "def ikey(self, value):\n\n if value == self._defaults['iKey'] and 'iKey' in self._values:\n del self._values['iKey']\n else:\n self._values['iKey'] = value", "docstring": "The ikey property.\n\nArgs:\n value (string). the property value.", "source": "juraj_google_style"} +{"code": "def updateEnterpriseUser(self, username, idpUsername):\n\n params = {\n \"f\" : \"json\",\n \"username\" : username,\n \"idpUsername\" : idpUsername\n }\n url = self._url + \"/users/updateEnterpriseUser\"\n return self._post(url=url,\n param_dict=params,\n proxy_url=self._proxy_url,\n proxy_port=self._proxy_port)", "docstring": "This operation allows an administrator to update the idpUsername\n for an enterprise user in the portal. This is used when migrating\n from accounts used with web-tier authentication to SAML\n authentication.\n\n Parameters:\n username - username of the enterprise account\n idpUsername - username used by the SAML identity provider", "source": "juraj_google_style"} +{"code": "def auctionDF(symbol=None, token='', version=''):\n\n df = pd.io.json.json_normalize(auction(symbol, token, version))\n _toDatetime(df)\n return df", "docstring": "DEEP broadcasts an Auction Information Message every one second between the Lock-in Time and the auction match for Opening and Closing Auctions,\n and during the Display Only Period for IPO, Halt, and Volatility Auctions. Only IEX listed securities are eligible for IEX Auctions.\n\n https://iexcloud.io/docs/api/#deep-auction\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n DataFrame: result", "source": "juraj_google_style"} +{"code": "def load(self, data):\n\n resp = self.client.api.load_image(data)\n images = []\n for chunk in resp:\n if 'stream' in chunk:\n match = re.search(\n r'(^Loaded image ID: |^Loaded image: )(.+)$',\n chunk['stream']\n )\n if match:\n image_id = match.group(2)\n images.append(image_id)\n if 'error' in chunk:\n raise ImageLoadError(chunk['error'])\n\n return [self.get(i) for i in images]", "docstring": "Load an image that was previously saved using\n :py:meth:`~docker.models.images.Image.save` (or ``docker save``).\n Similar to ``docker load``.\n\nArgs:\n data (binary): Image data to be loaded.\n\nReturns:\n (list of :py:class:`Image`): The images.\n\nRaises:\n :py:class:`docker.errors.APIError`\n If the server returns an error.", "source": "juraj_google_style"} +{"code": "def _protobuf_value_to_string(value):\n\n value_in_json = json_format.MessageToJson(value)\n if value.HasField(\"string_value\"):\n # Remove the quotations.\n return value_in_json[1:-1]\n return value_in_json", "docstring": "Returns a string representation of given google.protobuf.Value message.\n\nArgs:\n value: google.protobuf.Value message. Assumed to be of type 'number',\n 'string' or 'bool'.", "source": "juraj_google_style"} +{"code": "def vmstat(stat):\n\n out = subprocess.check_output([\"vmstat\", \"-s\"])\n stat = stat.encode(\"ascii\")\n for line in out.split(b\"\\n\"):\n line = line.strip()\n if stat in line:\n return int(line.split(b\" \")[0])\n raise ValueError(\"Can't find {} in 'vmstat' output.\".format(stat))", "docstring": "Run vmstat and get a particular statistic.\n\nArgs:\n stat: The statistic that we are interested in retrieving.\n\nReturns:\n The parsed output.", "source": "juraj_google_style"} +{"code": "def __init__(self, owner, repo_name, token=''):\n\n self._github_repository = GitHub(token=token).repository(owner, repo_name)", "docstring": "Build the GitHub API URL which points to the definition of the repository.\n\nArgs:\n owner (str): the owner's GitHub username\n repo_name (str): the name of the repository\n token (str): the GitHub API token\n\nReturns:\n dict: a representation of the repo definition", "source": "juraj_google_style"} +{"code": "def __gt__(self, other):\n\n if other.__class__ is not self.__class__:\n return NotImplemented\n return not self <= other", "docstring": "Test if self is greater than an object of the same class.\n\nArgs:\n other: The object to compare against.\n\nReturns:\n True if self is greater than other; else False.\n\nRaises:\n TypeError: Raised if the objects are not of the same class.", "source": "juraj_google_style"} +{"code": "def get_ref(profile, ref):\n\n resource = \"/refs/\" + ref\n data = api.get_request(profile, resource)\n return prepare(data)", "docstring": "Fetch a ref.\n\nArgs:\n profile\n A profile generated from ``simplygithub.authentication.profile``.\n Such profiles tell this module (i) the ``repo`` to connect to,\n and (ii) the ``token`` to connect with.\n\n ref\n The ref to fetch, e.g., ``heads/my-feature-branch``.\n\n Returns\n A dict with data about the ref.", "source": "juraj_google_style"} +{"code": "def GetMessages(self, formatter_mediator, event):\n\n if self.DATA_TYPE != event.data_type:\n raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(\n event.data_type))\n\n event_values = event.CopyToDict()\n\n regvalue = event_values.get('regvalue', {})\n string_parts = []\n for key, value in sorted(regvalue.items()):\n string_parts.append('{0:s}: {1!s}'.format(key, value))\n event_values['text'] = ' '.join(string_parts)\n\n urls = event_values.get('urls', [])\n if urls:\n event_values['urls'] = ' - '.join(urls)\n\n if 'key_path' in event_values:\n format_string = self.FORMAT_STRING\n else:\n format_string = self.FORMAT_STRING_ALTERNATIVE\n\n return self._FormatMessages(\n format_string, self.FORMAT_STRING_SHORT, event_values)", "docstring": "Determines the formatted message strings for an event object.\n\nArgs:\n formatter_mediator (FormatterMediator): mediates the interactions\n between formatters and other components, such as storage and Windows\n EventLog resources.\n event (EventObject): event.\n\nReturns:\n tuple(str, str): formatted message string and short message string.\n\nRaises:\n WrongFormatter: if the event object cannot be formatted by the formatter.", "source": "juraj_google_style"} +{"code": "def _mean_of_runs(stats, key='runs'):\n\n\n num_runs = len(stats[key])\n first = stats[key][0]\n\n mean = {}\n for stat_key in first:\n # Skip non numberic attributes\n if isinstance(first[stat_key], numbers.Number):\n mean[stat_key] = sum(run[stat_key]\n for run in stats[key]) / float(num_runs)\n\n return mean", "docstring": "Obtain the mean of stats.\n\nArgs:\n stats: dict; A set of stats, structured as above.\n key: str; Optional key to determine where list of runs is found in stats", "source": "juraj_google_style"} +{"code": "def confusion_matrix(\n gold, pred, null_pred=False, null_gold=False, normalize=False, pretty_print=True\n):\n\n conf = ConfusionMatrix(null_pred=null_pred, null_gold=null_gold)\n gold = arraylike_to_numpy(gold)\n pred = arraylike_to_numpy(pred)\n conf.add(gold, pred)\n mat = conf.compile()\n\n if normalize:\n mat = mat / len(gold)\n\n if pretty_print:\n conf.display(normalize=normalize)\n\n return mat", "docstring": "A shortcut method for building a confusion matrix all at once.\n\nArgs:\n gold: an array-like of gold labels (ints)\n pred: an array-like of predictions (ints)\n null_pred: If True, include the row corresponding to null predictions\n null_gold: If True, include the col corresponding to null gold labels\n normalize: if True, divide counts by the total number of items\n pretty_print: if True, pretty-print the matrix before returning", "source": "juraj_google_style"} +{"code": "def is_common(schema):\n\n if isinstance(schema, StreamSchema):\n return schema.schema() in _SCHEMA_COMMON\n if isinstance(schema, CommonSchema):\n return True\n if isinstance(schema, basestring):\n return is_common(StreamSchema(schema))\n return False", "docstring": "Is `schema` an common schema.\n\nArgs:\n schema: Scheme to test.\n\nReturns:\n bool: ``True`` if schema is a common schema, otherwise ``False``.", "source": "juraj_google_style"} +{"code": "def urlToIds(url):\n\n urlId = url.split(\"/\")[-1]\n convUrl = \"https://join.skype.com/api/v2/conversation/\"\n json = SkypeConnection.externalCall(\"POST\", convUrl, json={\"shortId\": urlId, \"type\": \"wl\"}).json()\n return {\"id\": json.get(\"Resource\"),\n \"long\": json.get(\"Id\"),\n \"blob\": json.get(\"ChatBlob\")}", "docstring": "Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.\n\nArgs:\n url (str): public join URL, or identifier from it\n\nReturns:\n dict: related conversation's identifiers -- keys: ``id``, ``long``, ``blob``", "source": "juraj_google_style"} +{"code": "def OSXEnumerateRunningServicesFromClient(args):\n\n del args # Unused.\n osx_version = client_utils_osx.OSXVersion()\n version_array = osx_version.VersionAsMajorMinor()\n\n if version_array[:2] < [10, 6]:\n raise UnsupportedOSVersionError(\n \"ServiceManagement API unsupported on < 10.6. This client is %s\" %\n osx_version.VersionString())\n\n launchd_list = GetRunningLaunchDaemons()\n\n parser = osx_launchd.OSXLaunchdJobDict(launchd_list)\n for job in parser.Parse():\n response = CreateServiceProto(job)\n yield response", "docstring": "Get running launchd jobs.\n\nArgs:\n args: Unused.\n\nYields:\n `rdf_client.OSXServiceInformation` instances.\n\nRaises:\n UnsupportedOSVersionError: for OS X earlier than 10.6.", "source": "juraj_google_style"} +{"code": "def create_clusters(provider, context, **kwargs):\n\n conn = get_session(provider.region).client('ecs')\n\n try:\n clusters = kwargs[\"clusters\"]\n except KeyError:\n logger.error(\"setup_clusters hook missing \\\"clusters\\\" argument\")\n return False\n\n if isinstance(clusters, basestring):\n clusters = [clusters]\n\n cluster_info = {}\n for cluster in clusters:\n logger.debug(\"Creating ECS cluster: %s\", cluster)\n r = conn.create_cluster(clusterName=cluster)\n cluster_info[r[\"cluster\"][\"clusterName\"]] = r\n return {\"clusters\": cluster_info}", "docstring": "Creates ECS clusters.\n\n Expects a \"clusters\" argument, which should contain a list of cluster\n names to create.\n\nArgs:\n provider (:class:`stacker.providers.base.BaseProvider`): provider\n instance\n context (:class:`stacker.context.Context`): context instance\n\n Returns: boolean for whether or not the hook succeeded.", "source": "juraj_google_style"} +{"code": "def _finish_add(self, num_bytes_to_add, num_partition_bytes_to_add):\n # type: (int, int) -> None\n\n for pvd in self.pvds:\n pvd.add_to_space_size(num_bytes_to_add + num_partition_bytes_to_add)\n if self.joliet_vd is not None:\n self.joliet_vd.add_to_space_size(num_bytes_to_add + num_partition_bytes_to_add)\n\n if self.enhanced_vd is not None:\n self.enhanced_vd.copy_sizes(self.pvd)\n\n if self.udf_root is not None:\n num_extents_to_add = utils.ceiling_div(num_partition_bytes_to_add,\n self.pvd.logical_block_size())\n\n self.udf_main_descs.partition.part_length += num_extents_to_add\n self.udf_reserve_descs.partition.part_length += num_extents_to_add\n self.udf_logical_volume_integrity.size_table += num_extents_to_add\n\n if self._always_consistent:\n self._reshuffle_extents()\n else:\n self._needs_reshuffle = True", "docstring": "An internal method to do all of the accounting needed whenever\n something is added to the ISO. This method should only be called by\n public API implementations.\n\n Parameters:\n num_bytes_to_add - The number of additional bytes to add to all\n descriptors.\n num_partition_bytes_to_add - The number of additional bytes to add to\n the partition if this is a UDF file.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def set_colors(self, fg=None, bg=None):\n\n if fg is not None:\n self._fg = _format_color(fg, self._fg)\n if bg is not None:\n self._bg = _format_color(bg, self._bg)", "docstring": "Sets the colors to be used with the L{print_str} and draw_* methods.\n\n Values of None will only leave the current values unchanged.\n\nArgs:\n fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])\n bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])\n .. seealso:: :any:`move`, :any:`print_str`", "source": "juraj_google_style"} +{"code": "def ip_prefixes_sanity_check(config, bird_configuration):\n\n for ip_version in bird_configuration:\n modify_ip_prefixes(config,\n bird_configuration[ip_version]['config_file'],\n bird_configuration[ip_version]['variable_name'],\n bird_configuration[ip_version]['dummy_ip_prefix'],\n bird_configuration[ip_version]['reconfigure_cmd'],\n bird_configuration[ip_version]['keep_changes'],\n bird_configuration[ip_version]['changes_counter'],\n ip_version)", "docstring": "Sanity check on IP prefixes.\n\nArgs:\n config (obg): A configparser object which holds our configuration.\n bird_configuration (dict): A dictionary, which holds Bird configuration\n per IP protocol version.", "source": "juraj_google_style"} +{"code": "def available_readers(as_dict=False):\n\n readers = []\n for reader_configs in configs_for_reader():\n try:\n reader_info = read_reader_config(reader_configs)\n except (KeyError, IOError, yaml.YAMLError):\n LOG.warning(\"Could not import reader config from: %s\", reader_configs)\n LOG.debug(\"Error loading YAML\", exc_info=True)\n continue\n readers.append(reader_info if as_dict else reader_info['name'])\n return readers", "docstring": "Available readers based on current configuration.\n\nArgs:\n as_dict (bool): Optionally return reader information as a dictionary.\n Default: False\n\n Returns: List of available reader names. If `as_dict` is `True` then\n a list of dictionaries including additionally reader information\n is returned.", "source": "juraj_google_style"} +{"code": "def lookup_rest_method(self, orig_request):\n\n method_name, method, params = self.config_manager.lookup_rest_method(\n orig_request.path, orig_request.request_uri, orig_request.http_method)\n orig_request.method_name = method_name\n return method, params", "docstring": "Looks up and returns rest method for the currently-pending request.\n\nArgs:\n orig_request: An ApiRequest, the original request from the user.\n\nReturns:\n A tuple of (method descriptor, parameters), or (None, None) if no method\n was found for the current request.", "source": "juraj_google_style"} +{"code": "def poke(exposes):\n\n def _poke(store, objname, obj, container, visited=None, _stack=None):\n try:\n sub_container = store.newContainer(objname, obj, container)\n except (SystemExit, KeyboardInterrupt):\n raise\n except:\n raise ValueError('generic poke not supported by store')\n #_stack = _add_to_stack(_stack, objname)\n for iobjname in exposes:\n try:\n iobj = getattr(obj, iobjname)\n except AttributeError:\n pass\n else:\n store.poke(iobjname, iobj, sub_container, visited=visited, \\\n _stack=_stack)\n return _poke", "docstring": "Default serializer factory.\n\nArgs:\n exposes (iterable): attributes to serialized.\n\nReturns:\n callable: serializer (`poke` routine).", "source": "juraj_google_style"} +{"code": "def release_port(upnp, external_port):\n\n mapping = upnp.getspecificportmapping(external_port, 'UDP')\n\n if mapping is None:\n log.error('could not find a port mapping', external=external_port)\n return False\n else:\n log.debug('found existing port mapping', mapping=mapping)\n\n if upnp.deleteportmapping(external_port, 'UDP'):\n log.info('successfully released port mapping', external=external_port)\n return True\n\n log.warning(\n 'could not release port mapping, check your router for stale mappings',\n )\n return False", "docstring": "Try to release the port mapping for `external_port`.\n\nArgs:\n external_port (int): the port that was previously forwarded to.\n\nReturns:\n success (boolean): if the release was successful.", "source": "juraj_google_style"} +{"code": "def hugepage_support(user, group='hugetlb', nr_hugepages=256,\n max_map_count=65536, mnt_point='/run/hugepages/kvm',\n pagesize='2MB', mount=True, set_shmmax=False):\n\n group_info = add_group(group)\n gid = group_info.gr_gid\n add_user_to_group(user, group)\n if max_map_count < 2 * nr_hugepages:\n max_map_count = 2 * nr_hugepages\n sysctl_settings = {\n 'vm.nr_hugepages': nr_hugepages,\n 'vm.max_map_count': max_map_count,\n 'vm.hugetlb_shm_group': gid,\n }\n if set_shmmax:\n shmmax_current = int(check_output(['sysctl', '-n', 'kernel.shmmax']))\n shmmax_minsize = bytes_from_string(pagesize) * nr_hugepages\n if shmmax_minsize > shmmax_current:\n sysctl_settings['kernel.shmmax'] = shmmax_minsize\n sysctl.create(yaml.dump(sysctl_settings), '/etc/sysctl.d/10-hugepage.conf')\n mkdir(mnt_point, owner='root', group='root', perms=0o755, force=False)\n lfstab = fstab.Fstab()\n fstab_entry = lfstab.get_entry_by_attr('mountpoint', mnt_point)\n if fstab_entry:\n lfstab.remove_entry(fstab_entry)\n entry = lfstab.Entry('nodev', mnt_point, 'hugetlbfs',\n 'mode=1770,gid={},pagesize={}'.format(gid, pagesize), 0, 0)\n lfstab.add_entry(entry)\n if mount:\n fstab_mount(mnt_point)", "docstring": "Enable hugepages on system.\n\nArgs:\n user (str) -- Username to allow access to hugepages to\n group (str) -- Group name to own hugepages\n nr_hugepages (int) -- Number of pages to reserve\n max_map_count (int) -- Number of Virtual Memory Areas a process can own\n mnt_point (str) -- Directory to mount hugepages on\n pagesize (str) -- Size of hugepages\n mount (bool) -- Whether to Mount hugepages", "source": "juraj_google_style"} +{"code": "def set(self, name, permission):\n\n assert isinstance(permission, BasePermission), 'Only permission instances can be added to the set'\n\n self._permissions[name] = permission", "docstring": "Adds permission with the given name to the set. Permission with the same name will be overridden.\n\nArgs:\n name: name of the permission\n permission: permission instance", "source": "juraj_google_style"} +{"code": "def render_latex(latex: str) -> PIL.Image: # pragma: no cover\n\n tmpfilename = 'circ'\n with tempfile.TemporaryDirectory() as tmpdirname:\n tmppath = os.path.join(tmpdirname, tmpfilename)\n with open(tmppath + '.tex', 'w') as latex_file:\n latex_file.write(latex)\n\n subprocess.run([\"pdflatex\",\n \"-halt-on-error\",\n \"-output-directory={}\".format(tmpdirname),\n \"{}\".format(tmpfilename+'.tex')],\n stdout=subprocess.PIPE,\n stderr=subprocess.DEVNULL,\n check=True)\n\n subprocess.run(['pdftocairo',\n '-singlefile',\n '-png',\n '-q',\n tmppath + '.pdf',\n tmppath])\n img = PIL.Image.open(tmppath + '.png')\n\n return img", "docstring": "Convert a single page LaTeX document into an image.\n\n To display the returned image, `img.show()`\n\n\n Required external dependencies: `pdflatex` (with `qcircuit` package),\n and `poppler` (for `pdftocairo`).\n\nArgs:\n A LaTeX document as a string.\n\nReturns:\n A PIL Image\n\nRaises:\n OSError: If an external dependency is not installed.", "source": "juraj_google_style"} +{"code": "def _patch_expand_paths(self, settings, name, value):\n\n return [self._patch_expand_path(settings, name, item)\n for item in value]", "docstring": "Apply ``SettingsPostProcessor._patch_expand_path`` to each element in\n list.\n\nArgs:\n settings (dict): Current settings.\n name (str): Setting name.\n value (list): List of paths to patch.\n\nReturns:\n list: Patched path list to an absolute path.", "source": "juraj_google_style"} +{"code": "def __init__(self, obj):\n\n if distob.engine is None:\n setup_engines()\n if isinstance(obj, Ref):\n self._ref = obj\n self.is_local = (self._ref.id.engine is distob.engine.eid)\n else:\n self._ref = Ref(obj)\n self.is_local = True\n if self.is_local:\n self._dv = None\n self._obcache = distob.engine[self._ref.id]\n self._obcache_current = True\n else:\n self._dv = distob.engine._client[self._ref.id.engine]\n self._dv.use_dill()\n self._obcache = None\n self._obcache_current = False\n self._id = self._ref.id\n # preference setting: whether to give cached local results if available\n self.prefer_local = True \n #Add proxy controllers for any instance-specific methods/attributes:\n instance_methods, instance_attribs, size = call(\n _scan_instance, self, self.__class__._include_underscore,\n self.__class__._exclude, prefer_local=False)\n for name, doc in instance_methods:\n setattr(self, name, _make_proxy_method(name, doc))\n for name, doc in instance_attribs:\n setattr(self.__class__, name, _make_proxy_property(name, doc))\n self.__engine_affinity__ = (self._ref.id.engine, size)", "docstring": "Set up the Remote* proxy object to access an already-existing object,\n which may be local or remote.\n\nArgs:\n obj (Ref or object): either a Ref reference to the (possibly remote)\n object to be controlled, or else an actual (local) object to be\n controlled.", "source": "juraj_google_style"} +{"code": "def _check_load_existing_object(self, object_type, id_field_name, operation='update'):\n # type: (str, str, str) -> None\n\n self._check_existing_object(object_type, id_field_name)\n if not self._load_from_hdx(object_type, self.data[id_field_name]):\n raise HDXError('No existing %s to %s!' % (object_type, operation))", "docstring": "Check metadata exists and contains HDX object identifier, and if so load HDX object\n\nArgs:\n object_type (str): Description of HDX object type (for messages)\n id_field_name (str): Name of field containing HDX object identifier\n operation (str): Operation to report if error. Defaults to update.\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def releases(self, **kwargs):\n\n path = self._get_id_path('releases')\n\n response = self._GET(path, kwargs)\n self._set_attrs_to_values(response)\n return response", "docstring": "Get the release date and certification information by country for a\n specific movie id.\n\nArgs:\n append_to_response: (optional) Comma separated, any movie method.\n\nReturns:\n A dict representation of the JSON returned from the API.", "source": "juraj_google_style"} +{"code": "def WriteScanNode(self, scan_context, scan_node, indentation=''):\n\n if not scan_node:\n return\n\n values = []\n\n part_index = getattr(scan_node.path_spec, 'part_index', None)\n if part_index is not None:\n values.append('{0:d}'.format(part_index))\n\n store_index = getattr(scan_node.path_spec, 'store_index', None)\n if store_index is not None:\n values.append('{0:d}'.format(store_index))\n\n start_offset = getattr(scan_node.path_spec, 'start_offset', None)\n if start_offset is not None:\n values.append('start offset: {0:d} (0x{0:08x})'.format(start_offset))\n\n location = getattr(scan_node.path_spec, 'location', None)\n if location is not None:\n values.append('location: {0:s}'.format(location))\n\n values = ', '.join(values)\n\n flags = ''\n if scan_node in scan_context.locked_scan_nodes:\n flags = ' [LOCKED]'\n\n print('{0:s}{1:s}: {2:s}{3:s}'.format(\n indentation, scan_node.path_spec.type_indicator, values, flags))\n\n indentation = ' {0:s}'.format(indentation)\n for sub_scan_node in scan_node.sub_nodes:\n self.WriteScanNode(scan_context, sub_scan_node, indentation=indentation)", "docstring": "Writes the source scanner node to stdout.\n\nArgs:\n scan_context (SourceScannerContext): the source scanner context.\n scan_node (SourceScanNode): the scan node.\n indentation (Optional[str]): indentation.", "source": "juraj_google_style"} +{"code": "def _build_vocab(filename, vocab_path, vocab_size):\n\n data = _read_words(filename)\n counter = collections.Counter(data)\n count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))\n words, _ = list(zip(*count_pairs))\n words = words[:vocab_size]\n with open(vocab_path, \"w\") as f:\n f.write(\"\\n\".join(words))", "docstring": "Reads a file to build a vocabulary of `vocab_size` most common words.\n\n The vocabulary is sorted by occurrence count and has one word per line.\n Originally from:\n https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py\n\nArgs:\n filename: file to read list of words from.\n vocab_path: path where to save the vocabulary.\n vocab_size: size of the vocabulary to generate.", "source": "juraj_google_style"} +{"code": "def _getClassInstance(path, args=None):\n\n\t\tif not path.endswith(\".py\"):\n\t\t\treturn None\n\n\t\tif args is None:\n\t\t\targs = {}\n\n\t\tclassname = AtomShieldsScanner._getClassName(path)\n\t\tbasename = os.path.basename(path).replace(\".py\", \"\")\n\t\tsys.path.append(os.path.dirname(path))\n\t\ttry:\n\t\t\tmod = __import__(basename, globals(), locals(), [classname], -1)\n\t\t\tclass_ = getattr(mod, classname)\n\t\t\tinstance = class_(**args)\n\t\texcept Exception as e:\n\t\t\tAtomShieldsScanner._debug(\"[!] %s\" % e)\n\t\t\treturn None\n\t\tfinally:\n\t\t\tsys.path.remove(os.path.dirname(path))\n\t\treturn instance", "docstring": "Returns a class instance from a .py file.\n\nArgs:\n path (str): Absolute path to .py file\n args (dict): Arguments passed via class constructor\n\nReturns:\n object: Class instance or None", "source": "juraj_google_style"} +{"code": "def regex_findall_variables(content):\n\n try:\n vars_list = []\n for var_tuple in variable_regex_compile.findall(content):\n vars_list.append(\n var_tuple[0] or var_tuple[1]\n )\n return vars_list\n except TypeError:\n return []", "docstring": "extract all variable names from content, which is in format $variable\n\nArgs:\n content (str): string content\n\nReturns:\n list: variables list extracted from string content\n\nExample:\n >>> regex_findall_variables(\"$variable\")\n [\"variable\"]\n\n >>> regex_findall_variables(\"/blog/$postid\")\n [\"postid\"]\n\n >>> regex_findall_variables(\"/$var1/$var2\")\n [\"var1\", \"var2\"]\n\n >>> regex_findall_variables(\"abc\")\n []", "source": "juraj_google_style"} +{"code": "def add_arguments(self, parser):\n\n parser.add_argument('name', nargs=1, choices=['kinetis'],\n help='name of MCU to unlock')\n return self.add_common_arguments(parser, True)", "docstring": "Adds the unlock command arguments to the parser.\n\nArgs:\n self (UnlockCommand): the ``UnlockCommand`` instance\n parser (argparse.ArgumentParser): the parser to add the arguments to\n\nReturns:\n ``None``", "source": "juraj_google_style"} +{"code": "def on_click(self, handler):\n\n self.on_change('active', lambda attr, old, new: handler(new))", "docstring": "Set up a handler for button state changes (clicks).\n\nArgs:\n handler (func) : handler function to call when button is toggled.\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def _bisect(self, begin, end, listener):\n\n\n step = (end.date - begin.date) / 2\n\n while abs(step) >= self._eps_bisect:\n date = begin.date + step\n if self.SPEAKER_MODE == \"global\":\n orb = self.propagate(date)\n else:\n orb = begin.propagate(date)\n if listener(begin) * listener(orb) > 0:\n begin = orb\n else:\n end = orb\n step = (end.date - begin.date) / 2\n else:\n end.event = listener.info(end)\n return end", "docstring": "This method search for the zero-crossing of the watched parameter\n\nArgs:\n begin (Orbit):\n end (Orbit)\n listener (Listener)\n Return\n Return", "source": "juraj_google_style"} +{"code": "def get_object(cls, api_token, id):\n\n load_balancer = cls(token=api_token, id=id)\n load_balancer.load()\n return load_balancer", "docstring": "Class method that will return a LoadBalancer object by its ID.\n\nArgs:\n api_token (str): DigitalOcean API token\n id (str): Load Balancer ID", "source": "juraj_google_style"} +{"code": "def unique(ar):\n r\n\n import dask.array as da\n\n if isinstance(ar, da.core.Array):\n return da.unique(ar)\n\n return _unique(ar)", "docstring": "r\"\"\"Find the unique elements of an array.\n\n It uses ``dask.array.unique`` if necessary.\n\nArgs:\n ar (array_like): Input array.\n\nReturns:\n array_like: the sorted unique elements.", "source": "juraj_google_style"} +{"code": "def parse(self, datestr):\n # type: (bytes) -> None\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('This Volume Descriptor Date object is already initialized')\n\n if len(datestr) != 17:\n raise pycdlibexception.PyCdlibInvalidISO('Invalid ISO9660 date string')\n\n timestruct = string_to_timestruct(datestr[:-3])\n self.year = timestruct.tm_year\n self.month = timestruct.tm_mon\n self.dayofmonth = timestruct.tm_mday\n self.hour = timestruct.tm_hour\n self.minute = timestruct.tm_min\n self.second = timestruct.tm_sec\n if timestruct.tm_year == 0 and timestruct.tm_mon == 0 and timestruct.tm_mday == 0 and timestruct.tm_hour == 0 and timestruct.tm_min == 0 and timestruct.tm_sec == 0:\n self.hundredthsofsecond = 0\n self.gmtoffset = 0\n self.date_str = self.EMPTY_STRING\n else:\n self.hundredthsofsecond = int(datestr[14:15])\n self.gmtoffset, = struct.unpack_from('=b', datestr, 16)\n self.date_str = datestr\n\n self._initialized = True", "docstring": "Parse a Volume Descriptor Date out of a string. A string of all zeros\n is valid, which means that the date in this field was not specified.\n\n Parameters:\n datestr - string to be parsed\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def save_json(obj, filename, **kwargs):\n\n\n with open(filename, 'w', encoding='utf-8') as f:\n json.dump(obj, f, **kwargs)", "docstring": "Save an object as a JSON file.\n\nArgs:\n obj: The object to save. Must be JSON-serializable.\n filename: Path to the output file.\n **kwargs: Additional arguments to `json.dump`.", "source": "juraj_google_style"} +{"code": "def wiki_list(self, title=None, creator_id=None, body_matches=None,\n other_names_match=None, creator_name=None, hide_deleted=None,\n other_names_present=None, order=None):\n\n params = {\n 'search[title]': title,\n 'search[creator_id]': creator_id,\n 'search[body_matches]': body_matches,\n 'search[other_names_match]': other_names_match,\n 'search[creator_name]': creator_name,\n 'search[hide_deleted]': hide_deleted,\n 'search[other_names_present]': other_names_present,\n 'search[order]': order\n }\n return self._get('wiki_pages.json', params)", "docstring": "Function to retrieves a list of every wiki page.\n\n Parameters:\n title (str): Page title.\n creator_id (int): Creator id.\n body_matches (str): Page content.\n other_names_match (str): Other names.\n creator_name (str): Creator name.\n hide_deleted (str): Can be: yes, no.\n other_names_present (str): Can be: yes, no.\n order (str): Can be: date, title.", "source": "juraj_google_style"} +{"code": "def __init__(self, *args, **kwargs):\n\n self.command = list(args)\n self.directory = kwargs['directory'] if 'directory' in kwargs else None\n self.env_vars = kwargs['env_vars'] if 'env_vars' in kwargs else None", "docstring": "Define a subcommand.\n\nArgs:\n *args (str): Sequence of program arguments needed to run the command.\n directory (Optional[str]): Directory the command is run in.\n env_vars (Optional[dict]): Environment variable to feed to the subcommand.", "source": "juraj_google_style"} +{"code": "def add_primitives_path(path):\n\n if path not in _PRIMITIVES_PATHS:\n if not os.path.isdir(path):\n raise ValueError('Invalid path: {}'.format(path))\n\n LOGGER.debug('Adding new primitives path %s', path)\n _PRIMITIVES_PATHS.insert(0, os.path.abspath(path))", "docstring": "Add a new path to look for primitives.\n\n The new path will be inserted in the first place of the list,\n so any primitive found in this new folder will take precedence\n over any other primitive with the same name that existed in the\n system before.\n\nArgs:\n path (str): path to add\n\nRaises:\n ValueError: A `ValueError` will be raised if the path is not valid.", "source": "juraj_google_style"} +{"code": "def connect(self, inbox):\n\n if self.started:\n self.log.error('Piper %s is started and cannot connect to %s.' % \\\n (self, inbox))\n raise PiperError('Piper %s is started and cannot connect to %s.' % \\\n (self, inbox))\n elif self.connected:\n self.log.error('Piper %s is connected and cannot connect to %s.' % \\\n (self, inbox))\n raise PiperError('Piper %s is connected and cannot connect to %s.' % \\\n (self, inbox))\n elif hasattr(self.imap, '_started') and self.imap._started.isSet():\n self.log.error('Piper %s cannot connect (NuMap is started).' % \\\n self)\n raise PiperError('Piper %s cannot connect (NuMap is started).' % \\\n self)\n else:\n # not started and not connected and NuMap not started\n self.log.debug('Piper %s connects to %s' % (self, inbox))\n # determine the stride with which result will be consumed from the\n # input.\n stride = self.imap.stride if hasattr(self.imap, 'stride') else 1\n\n # Tee input iterators. The idea is to create a promise object for a\n # tee. The actual teed iterator will be created on start. Each tee\n # is protected with a seperate lock the reasons for this are:\n # - tee objects are as a collection not thread safe\n # - tee objects might be next'ed from different threads, a single\n # lock will not guarantee that a thread might be allowed to finish\n # it's stride. (How it works that a thread releases the next \n # thread only if it finished a stride\n teed = []\n for piper in inbox:\n if hasattr(piper, '_iter'): # isinstance Piper?\n piper.tee_num += 1\n tee_lock = Lock()\n tee_lock.acquire()\n piper.tee_locks.append(tee_lock)\n piper = _TeePiper(piper, piper.tee_num - 1, stride)\n teed.append(_InputIterator(piper, self))\n\n # set how much to consume from input iterators.\n self.inbox = _Zip(*teed) if self.consume == 1 else\\\n _Consume(_Zip(*teed), n=self.consume, stride=stride)\n\n # set how much to \n for i in xrange(self.spawn):\n self.imap_tasks.append(\\\n self.imap(self.worker, self.inbox) \\\n if self.imap is imap else \\\n self.imap(self.worker, self.inbox, timeout=self.timeout, \\\n track=self.track))\n # chain the results together.\n outbox = _Chain(self.imap_tasks, stride=stride)\n # Make output\n #prd = ProduceFromSequence if self.produce_from_sequence else Produce\n if self.produce == 1:\n self.outbox = outbox\n elif self.repeat:\n self.outbox = _Repeat(outbox, n=self.produce, stride=stride)\n else:\n self.outbox = _Produce(outbox, n=self.produce, stride=stride)\n self.connected = True\n\n return self", "docstring": "Connects the ``Piper`` instance to its upstream ``Pipers`` that should\n be given as a sequence. This connects this ``Piper.inbox`` with the\n upstream ``Piper.outbox`` respecting any \"consume\", \"spawn\" and\n \"produce\" arguments.\n\nArgs:\n - inbox(sequence) sequence of ``Piper`` instances.", "source": "juraj_google_style"} +{"code": "def add_exac_info(genes, alias_genes, exac_lines):\n\n LOG.info(\"Add exac pli scores\")\n for exac_gene in parse_exac_genes(exac_lines):\n hgnc_symbol = exac_gene['hgnc_symbol'].upper()\n pli_score = exac_gene['pli_score']\n\n for hgnc_id in get_correct_ids(hgnc_symbol, alias_genes):\n genes[hgnc_id]['pli_score'] = pli_score", "docstring": "Add information from the exac genes\n\n Currently we only add the pLi score on gene level\n\n The exac resource only use HGNC symbol to identify genes so we need\n our alias mapping.\n\nArgs:\n genes(dict): Dictionary with all genes\n alias_genes(dict): Genes mapped to all aliases\n ensembl_lines(iteable): Iteable with raw ensembl info", "source": "juraj_google_style"} +{"code": "def load_hpo(adapter, disease_lines, hpo_disease_lines=None, hpo_lines=None, hpo_gene_lines=None):\n\n # Create a map from gene aliases to gene objects\n alias_genes = adapter.genes_by_alias()\n\n # Fetch the hpo terms if no file\n if not hpo_lines:\n hpo_lines = fetch_hpo_terms()\n\n # Fetch the hpo gene information if no file\n if not hpo_gene_lines:\n hpo_gene_lines = fetch_hpo_to_genes()\n\n # Fetch the hpo phenotype information if no file\n if not hpo_disease_lines:\n hpo_disease_lines = fetch_hpo_phenotype_to_terms()\n\n load_hpo_terms(adapter, hpo_lines, hpo_gene_lines, alias_genes)\n\n load_disease_terms(adapter, disease_lines, alias_genes, hpo_disease_lines)", "docstring": "Load the hpo terms and hpo diseases into database\n\nArgs:\n adapter(MongoAdapter)\n disease_lines(iterable(str)): These are the omim genemap2 information\n hpo_lines(iterable(str))\n disease_lines(iterable(str))\n hpo_gene_lines(iterable(str))", "source": "juraj_google_style"} +{"code": "def binary_n(total_N, min_n=50):\n\n max_exp = np.log2(1.0 * total_N / min_n)\n max_exp = int(np.floor(max_exp))\n return [int(np.floor(1.0 * total_N / (2**i))) for i in range(1, max_exp + 1)]", "docstring": "Creates a list of values by successively halving the total length total_N\n until the resulting value is less than min_n.\n\n Non-integer results are rounded down.\n\nArgs:\n total_N (int):\n total length\n Kwargs:\n min_n (int):\n minimal length after division\n\nReturns:\n list of integers:\n total_N/2, total_N/4, total_N/8, ... until total_N/2^i < min_n", "source": "juraj_google_style"} +{"code": "def _string_from_ip_int(self, ip_int):\n\n octets = []\n for _ in xrange(4):\n octets.insert(0, str(ip_int & 0xFF))\n ip_int >>= 8\n return '.'.join(octets)", "docstring": "Turns a 32-bit integer into dotted decimal notation.\n\nArgs:\n ip_int: An integer, the IP address.\n\nReturns:\n The IP address as a string in dotted decimal notation.", "source": "juraj_google_style"} +{"code": "def new(self, sector_count, load_seg, media_name, system_type, bootable):\n # type: (int, int, str, int, bool) -> None\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('El Torito Entry already initialized')\n\n if media_name == 'noemul':\n media_type = self.MEDIA_NO_EMUL\n elif media_name == 'floppy':\n if sector_count == 2400:\n media_type = self.MEDIA_12FLOPPY\n elif sector_count == 2880:\n media_type = self.MEDIA_144FLOPPY\n elif sector_count == 5760:\n media_type = self.MEDIA_288FLOPPY\n else:\n raise pycdlibexception.PyCdlibInvalidInput('Invalid sector count for floppy media type; must be 2400, 2880, or 5760')\n # With floppy booting, the sector_count always ends up being 1\n sector_count = 1\n elif media_name == 'hdemul':\n media_type = self.MEDIA_HD_EMUL\n # With HD emul booting, the sector_count always ends up being 1\n sector_count = 1\n else:\n raise pycdlibexception.PyCdlibInvalidInput(\"Invalid media name '%s'\" % (media_name))\n\n if bootable:\n self.boot_indicator = 0x88\n else:\n self.boot_indicator = 0\n self.boot_media_type = media_type\n self.load_segment = load_seg\n self.system_type = system_type\n self.sector_count = sector_count\n self.load_rba = 0 # This will get set later\n self.selection_criteria_type = 0 # FIXME: allow the user to set this\n self.selection_criteria = b''.ljust(19, b'\\x00')\n\n self._initialized = True", "docstring": "A method to create a new El Torito Entry.\n\n Parameters:\n sector_count - The number of sectors to assign to this El Torito Entry.\n load_seg - The load segment address of the boot image.\n media_name - The name of the media type, one of 'noemul', 'floppy', or 'hdemul'.\n system_type - The partition type to assign to the entry.\n bootable - Whether this entry is bootable.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def get_userid_from_botid(self, botid):\n\n botinfo = self.slack_client.api_call('bots.info', bot=botid)\n if botinfo['ok'] is True:\n return botinfo['bot'].get('user_id')\n else:\n return botid", "docstring": "Perform a lookup of bots.info to resolve a botid to a userid\n\nArgs:\n botid (string): Slack botid to lookup.\n\nReturns:\n string: userid value", "source": "juraj_google_style"} +{"code": "def __init__(self, inqueue, size, num_passes):\n\n self.inqueue = inqueue\n self.size = size\n self.max_ttl = num_passes\n self.cur_max_ttl = 1 # ramp up slowly to better mix the input data\n self.buffers = [None] * size\n self.ttl = [0] * size\n self.idx = 0", "docstring": "Initialize a minibatch buffer.\n\nArgs:\n inqueue: Queue to populate the internal ring buffer from.\n size: Max number of data items to buffer.\n num_passes: Max num times each data item should be emitted.", "source": "juraj_google_style"} +{"code": "def compute_mask_offsets(shard_id2num_examples):\n\n total_num_examples = sum(shard_id2num_examples)\n\n mask_offsets = []\n total_num_examples = 0\n for num_examples_in_shard in shard_id2num_examples:\n # The offset (nb of examples to skip in the next shard) correspond to the\n # number of examples remaining in the current shard\n mask_offsets.append(total_num_examples % 100)\n total_num_examples += num_examples_in_shard\n\n return mask_offsets", "docstring": "Return the list of offsets associated with each shards.\n\nArgs:\n shard_id2num_examples: `list[int]`, mapping shard_id=>num_examples\n\nReturns:\n mask_offsets: `list[int]`, offset to skip for each of the shard", "source": "juraj_google_style"} +{"code": "def HandleNetworkInterfaces(self, result):\n\n network_interfaces = self._ExtractInterfaceMetadata(result)\n\n if self.network_setup_enabled:\n self.network_setup.EnableNetworkInterfaces(\n [interface.name for interface in network_interfaces[1:]])\n\n for interface in network_interfaces:\n if self.ip_forwarding_enabled:\n self.ip_forwarding.HandleForwardedIps(\n interface.name, interface.forwarded_ips, interface.ip)", "docstring": "Called when network interface metadata changes.\n\nArgs:\n result: dict, the metadata response with the network interfaces.", "source": "juraj_google_style"} +{"code": "def generate_mix2pl_dataset(n, m, useDirichlet=True):\n\n\n alpha = np.random.rand()\n gamma1 = None\n gamma2 = None\n\n if useDirichlet:\n gamma1 = np.random.dirichlet(np.ones(m))\n gamma2 = np.random.dirichlet(np.ones(m))\n else:\n gamma1 = np.random.rand(m)\n gamma1 /= np.sum(gamma1) # normalize sum to 1.0 (not needed for Dirichlet)\n gamma2 = np.random.rand(m)\n gamma2 /= np.sum(gamma1)\n\n votes = []\n\n for i in range(n):\n vote = None\n draw = np.random.rand()\n if draw <= alpha:\n vote = draw_pl_vote(m, gamma1)\n else: # draw > alpha\n vote = draw_pl_vote(m, gamma2)\n votes.append(vote)\n params = np.hstack((alpha, gamma1, gamma2))\n return (params, votes)", "docstring": "Description:\n Generate a mixture of 2 Plackett-Luce models dataset\n and return the parameters and votes.\n Parameters:\n n: number of votes to generate\n m: number of alternatives\n useDirichlet: boolean flag to use the Dirichlet distribution", "source": "juraj_google_style"} +{"code": "def get_site_dos(self, site):\n\n site_dos = functools.reduce(add_densities, self.pdos[site].values())\n return Dos(self.efermi, self.energies, site_dos)", "docstring": "Get the total Dos for a site (all orbitals).\n\nArgs:\n site: Site in Structure associated with CompleteDos.\n\nReturns:\n Dos containing summed orbital densities for site.", "source": "juraj_google_style"} +{"code": "def download(url, output_file=None, open_file=True, allow_overwrite=False):\n\n filename = url.split('/')[-1]\n if output_file is None:\n cache = os.path.join(get_data_home(), filename)\n else:\n cache = output_file\n if os.path.exists(cache) and not allow_overwrite:\n logger.info(\"> {} already exists.\".format(cache))\n logger.info(\"> If you have any issue when using this file, \")\n logger.info(\"> manually remove the file and try download again.\")\n else:\n r = request.urlopen(url)\n try:\n if six.PY2:\n content_length = int(r.info().dict['content-length'])\n elif six.PY3:\n content_length = int(r.info()['Content-Length'])\n except:\n content_length = 0\n unit = 1000000\n content = b''\n with tqdm(total=content_length, desc=filename, unit='B', unit_scale=True, unit_divisor=1024) as t:\n while True:\n data = r.read(unit)\n l = len(data)\n t.update(l)\n if l == 0:\n break\n content += data\n with open(cache, 'wb') as f:\n f.write(content)\n if not open_file:\n return\n return open(cache, 'rb')", "docstring": "Download a file from URL.\n\nArgs:\n url (str): URL.\n output_file (str, optional): If given, the downloaded file is written to the given path.\n open_file (bool): If True, it returns an opened file stream of the downloaded file.\n allow_overwrite (bool): If True, it overwrites an existing file.\n\nReturns:\n Returns file object if open_file is True, otherwise None.", "source": "juraj_google_style"} +{"code": "def _generate_bucket_value(self, bucketing_id):\n\n\n ratio = float(self._generate_unsigned_hash_code_32_bit(bucketing_id)) / MAX_HASH_VALUE\n return math.floor(ratio * MAX_TRAFFIC_VALUE)", "docstring": "Helper function to generate bucket value in half-closed interval [0, MAX_TRAFFIC_VALUE).\n\nArgs:\n bucketing_id: ID for bucketing.\n\nReturns:\n Bucket value corresponding to the provided bucketing ID.", "source": "juraj_google_style"} +{"code": "def _closeElements(childs, HTMLElement):\n\n out = []\n\n # close all unclosed pair tags\n for e in childs:\n if not e.isTag():\n out.append(e)\n continue\n\n if not e.isNonPairTag() and not e.isEndTag() and not e.isComment() \\\n and e.endtag is None:\n e.childs = _closeElements(e.childs, HTMLElement)\n\n out.append(e)\n out.append(HTMLElement(\"\"))\n\n # join opener and endtag\n e.endtag = out[-1]\n out[-1].openertag = e\n else:\n out.append(e)\n\n return out", "docstring": "Create `endtags` to elements which looks like openers, but doesn't have\n proper :attr:`HTMLElement.endtag`.\n\nArgs:\n childs (list): List of childs (:class:`HTMLElement` obj) - typically\n from :attr:`HTMLElement.childs` property.\n\nReturns:\n list: List of closed elements.", "source": "juraj_google_style"} +{"code": "def create_list(self, **kwargs):\n\n path = self._get_path('create_list')\n kwargs.update({'session_id': self.session_id})\n\n payload = {\n 'name': kwargs.pop('name', None), \n 'description': kwargs.pop('description', None),\n }\n if 'language' in kwargs:\n payload['language'] = kwargs['language']\n\n response = self._POST(path, kwargs, payload)\n self._set_attrs_to_values(response)\n return response", "docstring": "Create a new list.\n\n A valid session id is required.\n\nArgs:\n name: Name of the list.\n description: Description of the list.\n language: (optional) ISO 639-1 code.\n\nReturns:\n A dict respresentation of the JSON returned from the API.", "source": "juraj_google_style"} +{"code": "def get_ip_address_info(ip_address, cache=None, nameservers=None,\n timeout=2.0, parallel=False):\n\n ip_address = ip_address.lower()\n if cache:\n info = cache.get(ip_address, None)\n if info:\n return info\n info = OrderedDict()\n info[\"ip_address\"] = ip_address\n reverse_dns = get_reverse_dns(ip_address,\n nameservers=nameservers,\n timeout=timeout)\n country = get_ip_address_country(ip_address, parallel=parallel)\n info[\"country\"] = country\n info[\"reverse_dns\"] = reverse_dns\n info[\"base_domain\"] = None\n if reverse_dns is not None:\n base_domain = get_base_domain(reverse_dns)\n info[\"base_domain\"] = base_domain\n\n return info", "docstring": "Returns reverse DNS and country information for the given IP address\n\nArgs:\n ip_address (str): The IP address to check\n cache (ExpiringDict): Cache storage\n nameservers (list): A list of one or more nameservers to use\n (Cloudflare's public DNS resolvers by default)\n timeout (float): Sets the DNS timeout in seconds\n parallel (bool): parallel processing\n\nReturns:\n OrderedDict: ``ip_address``, ``reverse_dns``", "source": "juraj_google_style"} +{"code": "def starts_with_prefix_in_list(text, prefixes):\n\n for prefix in prefixes:\n if text.startswith(prefix):\n return True\n return False", "docstring": "Return True if the given string starts with one of the prefixes in the given list, otherwise\n return False.\n\nArgs:\n text (str): Text to check for prefixes.\n prefixes (list): List of prefixes to check for.\n\nReturns:\n bool: True if the given text starts with any of the given prefixes, otherwise False.", "source": "juraj_google_style"} +{"code": "def __init__(self, n=65, radius=1, port_distance_from_surface=.07):\n\n super(Sphere, self).__init__()\n particle = mb.Particle(name='np')\n particle.add(mb.Port(anchor=particle), label='out')\n\n # Generate 65 points on the surface of a unit sphere.\n pattern = mb.SpherePattern(n)\n # Magnify the unit sphere by the provided radius.\n pattern.scale(radius)\n\n particles = pattern.apply(particle, orientation='normal', compound_port='out')\n self.add(particles, label='np_[$]')\n\n # Create particles and Ports at pattern positions.\n for i, pos in enumerate(pattern.points):\n particle = mb.Particle(name=\"np\", pos=pos)\n self.add(particle, \"np_{}\".format(i))\n port = mb.Port(anchor=particle)\n self.add(port, \"port_{}\".format(i))\n\n # Make the top of the port point toward the positive x axis.\n port.spin(-pi/2, [0, 0, 1])\n # Raise up (or down) the top of the port in the z direction.\n port.spin(-arcsin(pos[2]/radius), [0, 1, 0])\n # Rotate the Port along the z axis.\n port.spin(arctan2(pos[1], pos[0]), [0, 0, 1])\n # Move the Port a bit away from the surface of the Sphere.\n port.translate(pos/radius * port_distance_from_surface)", "docstring": "Initialize a Sphere object.\n\nArgs:\n n (int): Number of points used to construct the Sphere.\n radius (float): Radius of the Sphere.\n port_distance_from_surface (float): Distance of Ports from Sphere.", "source": "juraj_google_style"} +{"code": "def parse_genes(transcripts):\n\n # Dictionary to group the transcripts by hgnc_id\n genes_to_transcripts = {}\n\n # List with all genes and there transcripts\n genes = []\n\n hgvs_identifier = None\n canonical_transcript = None\n exon = None\n # Group all transcripts by gene\n for transcript in transcripts:\n # Check what hgnc_id a transcript belongs to\n hgnc_id = transcript['hgnc_id']\n hgnc_symbol = transcript['hgnc_symbol']\n\n if (transcript['is_canonical'] and transcript.get('coding_sequence_name')):\n hgvs_identifier = transcript.get('coding_sequence_name')\n canonical_transcript = transcript['transcript_id']\n exon = transcript['exon']\n\n # If there is a identifier we group the transcripts under gene\n if hgnc_id:\n if hgnc_id in genes_to_transcripts:\n genes_to_transcripts[hgnc_id].append(transcript)\n else:\n genes_to_transcripts[hgnc_id] = [transcript]\n else:\n if hgnc_symbol:\n if hgnc_symbol in genes_to_transcripts:\n genes_to_transcripts[hgnc_symbol].append(transcript)\n else:\n genes_to_transcripts[hgnc_symbol] = [transcript]\n\n # We need to find out the most severe consequence in all transcripts\n # and save in what transcript we found it\n\n # Loop over all genes\n for gene_id in genes_to_transcripts:\n # Get the transcripts for a gene\n gene_transcripts = genes_to_transcripts[gene_id]\n # This will be a consequece from SO_TERMS\n most_severe_consequence = None\n # Set the most severe score to infinity\n most_severe_rank = float('inf')\n # The most_severe_transcript is a dict\n most_severe_transcript = None\n\n most_severe_region = None\n\n most_severe_sift = None\n most_severe_polyphen = None\n\n # Loop over all transcripts for a gene to check which is most severe\n for transcript in gene_transcripts:\n hgnc_id = transcript['hgnc_id']\n hgnc_symbol = transcript['hgnc_symbol']\n # Loop over the consequences for a transcript\n for consequence in transcript['functional_annotations']:\n # Get the rank based on SO_TERM\n # Lower rank is worse\n new_rank = SO_TERMS[consequence]['rank']\n\n if new_rank < most_severe_rank:\n # If a worse consequence is found, update the parameters\n most_severe_rank = new_rank\n most_severe_consequence = consequence\n most_severe_transcript = transcript\n most_severe_sift = transcript['sift_prediction']\n most_severe_polyphen = transcript['polyphen_prediction']\n most_severe_region = SO_TERMS[consequence]['region']\n\n gene = {\n 'transcripts': gene_transcripts,\n 'most_severe_transcript': most_severe_transcript,\n 'most_severe_consequence': most_severe_consequence,\n 'most_severe_sift': most_severe_sift,\n 'most_severe_polyphen': most_severe_polyphen,\n 'hgnc_id': hgnc_id,\n 'hgnc_symbol': hgnc_symbol,\n 'region_annotation': most_severe_region,\n 'hgvs_identifier': transcript['coding_sequence_name'],\n 'canonical_transcript': transcript['transcript_id'],\n 'exon': transcript['exon'],\n }\n genes.append(gene) \n\n return genes", "docstring": "Parse transcript information and get the gene information from there.\n\n Use hgnc_id as identifier for genes and ensembl transcript id to identify transcripts\n\nArgs:\n transcripts(iterable(dict))\n\nReturns:\n genes (list(dict)): A list with dictionaries that represents genes", "source": "juraj_google_style"} +{"code": "def _TrimNode(node, index, depth, flags):\n\n if depth == 1 or node.LeftChild is None:\n return\n\n if depth == 2:\n if not flags[index * 2] and not flags[index * 2 + 1]:\n node.LeftChild = None\n node.RightChild = None\n\n else:\n\n MerkleTree._TrimNode(node.LeftChild, index * 2, depth - 1, flags)\n MerkleTree._TrimNode(node.RightChild, index * 2, depth - 1, flags)\n\n if node.LeftChild.LeftChild is None and node.RightChild.RightChild is None:\n node.LeftChild = None\n node.RightChild = None", "docstring": "Internal helper method to trim a node.\n\nArgs:\n node (MerkleTreeNode):\n index (int): flag index.\n depth (int): node tree depth to start trim from.\n flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node.\n 00 to erase, 11 to keep. Will keep the node if either left or right is not-0", "source": "juraj_google_style"} +{"code": "def get_size(fileobj):\n\n\n old_pos = fileobj.tell()\n try:\n fileobj.seek(0, 2)\n return fileobj.tell()\n finally:\n fileobj.seek(old_pos, 0)", "docstring": "Returns the size of the file.\n The position when passed in will be preserved if no error occurs.\n\nArgs:\n fileobj (fileobj)\n\nReturns:\n int: The size of the file\n\nRaises:\n IOError", "source": "juraj_google_style"} +{"code": "def distorted_inputs(data_dir, batch_size):\n\n filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i)\n for i in xrange(1, 6)]\n for f in filenames:\n if not tf.gfile.Exists(f):\n raise ValueError('Failed to find file: ' + f)\n\n # Create a queue that produces the filenames to read.\n filename_queue = tf.train.string_input_producer(filenames)\n\n # Read examples from files in the filename queue.\n read_input = read_cifar10(filename_queue)\n reshaped_image = tf.cast(read_input.uint8image, tf.float32)\n\n height = IMAGE_SIZE\n width = IMAGE_SIZE\n\n # Image processing for training the network. Note the many random\n # distortions applied to the image.\n\n # Randomly crop a [height, width] section of the image.\n distorted_image = tf.random_crop(reshaped_image, [height, width, 3])\n\n # Randomly flip the image horizontally.\n distorted_image = tf.image.random_flip_left_right(distorted_image)\n\n # Because these operations are not commutative, consider randomizing\n # the order their operation.\n distorted_image = tf.image.random_brightness(distorted_image,\n max_delta=63)\n distorted_image = tf.image.random_contrast(distorted_image,\n lower=0.2, upper=1.8)\n\n # Subtract off the mean and divide by the variance of the pixels.\n float_image = tf.image.per_image_standardization(distorted_image)\n\n # Set the shapes of tensors.\n float_image.set_shape([height, width, 3])\n read_input.label.set_shape([1])\n\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *\n min_fraction_of_examples_in_queue)\n print ('Filling queue with %d CIFAR images before starting to train. '\n 'This will take a few minutes.' % min_queue_examples)\n\n # Generate a batch of images and labels by building up a queue of examples.\n return _generate_image_and_label_batch(float_image, read_input.label,\n min_queue_examples, batch_size,\n shuffle=True)", "docstring": "Construct distorted input for CIFAR training using the Reader ops.\n\nArgs:\n data_dir: Path to the CIFAR-10 data directory.\n batch_size: Number of images per batch.\n\nReturns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.", "source": "juraj_google_style"} +{"code": "def Extract(self, components):\n\n\n rundll_index = -1\n for index, component in enumerate(components):\n if component.lower().endswith(\"rundll32.exe\"):\n rundll_index = index\n\n if rundll_index == -1:\n return []\n\n components = components[(rundll_index + 1):]\n\n # We expect components after \"rundll32.exe\" to point at a DLL and a\n # function. For example:\n # rundll32.exe \"C:\\Windows\\system32\\advpack.dll\",DelNodeRunDLL32\n last_component = components[-1].rsplit(\",\", 1)[0]\n\n extracted_path = \" \".join(components[0:-1] + [last_component])\n return [extracted_path]", "docstring": "Extracts interesting paths from a given path.\n\nArgs:\n components: Source string represented as a list of components.\n\nReturns:\n A list of extracted paths (as strings).", "source": "juraj_google_style"} +{"code": "def _ReadCompressedData(self, read_size):\n\n compressed_data = self._file_object.read(read_size)\n\n read_count = len(compressed_data)\n\n self._compressed_data = b''.join([self._compressed_data, compressed_data])\n\n self._uncompressed_data, self._compressed_data = (\n self._decompressor.Decompress(self._compressed_data))\n\n self._uncompressed_data_size = len(self._uncompressed_data)\n\n return read_count", "docstring": "Reads compressed data from the file-like object.\n\nArgs:\n read_size (int): number of bytes of compressed data to read.\n\nReturns:\n int: number of bytes of compressed data read.", "source": "juraj_google_style"} +{"code": "def _UpdateYear(self, mediator, month):\n\n if not self._year_use:\n self._year_use = mediator.GetEstimatedYear()\n if not self._maximum_year:\n self._maximum_year = mediator.GetLatestYear()\n\n if not self._last_month:\n self._last_month = month\n return\n\n # Some syslog daemons allow out-of-order sequences, so allow some leeway\n # to not cause Apr->May->Apr to cause the year to increment.\n # See http://bugzilla.adiscon.com/show_bug.cgi?id=527\n if self._last_month > (month + 1):\n if self._year_use != self._maximum_year:\n self._year_use += 1\n self._last_month = month", "docstring": "Updates the year to use for events, based on last observed month.\n\nArgs:\n mediator (ParserMediator): mediates the interactions between\n parsers and other components, such as storage and abort signals.\n month (int): month observed by the parser, where January is 1.", "source": "juraj_google_style"} +{"code": "def screenrecord(self, bit_rate: int = 5000000, time_limit: int = 180, filename: _PATH = '/sdcard/demo.mp4') -> None:\n\n self._execute('-s', self.device_sn, 'shell',\n 'screenrecord', '--bit-rate', str(bit_rate), '--time-limit', str(time_limit), filename)", "docstring": "Recording the display of devices running Android 4.4 (API level 19) and higher.\n\nArgs:\n bit_rate:You can increase the bit rate to improve video quality, but doing so results in larger movie files.\n time_limit: Sets the maximum recording time, in seconds, and the maximum value is 180 (3 minutes).", "source": "juraj_google_style"} +{"code": "def run_docker(self, commands):\n\n try:\n import docker\n except ImportError:\n print(\n '{}{}Could not import docker module (try \"pip install docker\").'.format(\n c.Style.BRIGHT, c.Fore.RED\n )\n )\n sys.exit(1)\n\n # app_args = self.profile.get('profile_args').standard\n app_args_data = self.profile.get('profile_args').data\n install_json = self.profile.get('install_json')\n\n # client\n client = docker.from_env()\n\n # app data\n app_dir = os.getcwd()\n # app_path = '{}/{}'.format(app_dir, program_main)\n\n # ports\n ports = {}\n if self.args.vscd:\n ports = {'{}/tcp'.format(self.args.vscd_port): self.args.vscd_port}\n\n # volumes\n volumes = {}\n in_path = '{}/{}'.format(app_dir, app_args_data.get('tc_in_path'))\n if app_args_data.get('tc_in_path') is not None:\n volumes[in_path] = {'bind': in_path}\n log_path = '{}/{}'.format(app_dir, app_args_data.get('tc_log_path'))\n if app_args_data.get('tc_log_path') is not None:\n volumes[log_path] = {'bind': log_path}\n out_path = '{}/{}'.format(app_dir, app_args_data.get('tc_out_path'))\n if app_args_data.get('tc_out_path') is not None:\n volumes[out_path] = {'bind': out_path}\n temp_path = '{}/{}'.format(app_dir, app_args_data.get('tc_temp_path'))\n if app_args_data.get('tc_temp_path') is not None:\n volumes[temp_path] = {'bind': temp_path}\n volumes[app_dir] = {'bind': app_dir}\n\n if self.args.docker_image is not None:\n # user docker image from cli as an override.\n docker_image = self.args.docker_image\n else:\n # docker image from install.json can be overridden by docker image in profile. if no\n # image is defined in either file use the default image define as self.docker_image.\n docker_image = self.profile.get(\n 'dockerImage', install_json.get('dockerImage', self.docker_image)\n )\n\n status_code = 1\n try:\n self.container = client.containers.run(\n docker_image,\n entrypoint=commands.get('cli_command'),\n environment=['PYTHONPATH={}/lib_latest'.format(app_dir)],\n detach=True,\n # network_mode=install_json.get('docker_host', 'host'),\n ports=ports,\n remove=True,\n volumes=volumes,\n working_dir=app_dir,\n )\n results = self.container.wait()\n status_code = results.get('StatusCode')\n error = results.get('Error')\n if error:\n print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, error))\n except Exception as e:\n print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, e))\n sys.exit()\n\n # Exit Code\n return self.run_exit_code(status_code)", "docstring": "Run App in Docker Container.\n\nArgs:\n commands (dict): A dictionary of the CLI commands.\n\nReturns:\n int: The exit code of the subprocess command.", "source": "juraj_google_style"} +{"code": "def __getHyperSearchJobIDFilePath(cls, permWorkDir, outputLabel):\n\n # Get the base path and figure out the path of the report file.\n basePath = permWorkDir\n\n # Form the name of the output csv file that will contain all the results\n filename = \"%s_HyperSearchJobID.pkl\" % (outputLabel,)\n filepath = os.path.join(basePath, filename)\n\n return filepath", "docstring": "Returns filepath where to store HyperSearch JobID\n\n Parameters:\n ----------------------------------------------------------------------\n permWorkDir: Directory path for saved jobID file\n outputLabel: Label string for incorporating into file name for saved jobID\n retval: Filepath where to store HyperSearch JobID", "source": "juraj_google_style"} +{"code": "def AddEventAttribute(self, attribute_name, attribute_value):\n\n if attribute_name in self._extra_event_attributes:\n raise KeyError('Event attribute {0:s} already set'.format(\n attribute_name))\n\n self._extra_event_attributes[attribute_name] = attribute_value", "docstring": "Adds an attribute that will be set on all events produced.\n\n Setting attributes using this method will cause events produced via this\n mediator to have an attribute with the provided name set with the\n provided value.\n\nArgs:\n attribute_name (str): name of the attribute to add.\n attribute_value (str): value of the attribute to add.\n\nRaises:\n KeyError: if the event attribute is already set.", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.StreamingAnnotateVideo = channel.stream_stream(\n \"/google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService/StreamingAnnotateVideo\",\n request_serializer=google_dot_cloud_dot_videointelligence__v1p3beta1_dot_proto_dot_video__intelligence__pb2.StreamingAnnotateVideoRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_videointelligence__v1p3beta1_dot_proto_dot_video__intelligence__pb2.StreamingAnnotateVideoResponse.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def receive(self, sequence, args):\n\n\n # If we are told to ignore sequence numbers, just pass the packet on\n if not self._reorder:\n self._callback(*args)\n return\n\n # If this packet is in the past, drop it\n if self._next_expected is not None and sequence < self._next_expected:\n print(\"Dropping out of order packet, seq=%d\" % sequence)\n return\n\n self._out_of_order.append((sequence, args))\n self._out_of_order.sort(key=lambda x: x[0])\n\n # If we have received packets, attempt to process them in order\n while len(self._out_of_order) > 0:\n seq, args = self._out_of_order[0]\n\n if self._next_expected is not None and seq != self._next_expected:\n return\n\n self._callback(*args)\n self._out_of_order.pop(0)\n self._next_expected = seq+1", "docstring": "Receive one packet\n\n If the sequence number is one we've already seen before, it is dropped.\n\n If it is not the next expected sequence number, it is put into the\n _out_of_order queue to be processed once the holes in sequence number\n are filled in.\n\nArgs:\n sequence (int): The sequence number of the received packet\n args (list): The list of packet contents that will be passed to callback\n as callback(*args)", "source": "juraj_google_style"} +{"code": "def __init__(self, min_obs=10):\n\n\n self.min_obs = min_obs\n self.label_encoder = LabelEncoder(min_obs)", "docstring": "Initialize the OneHotEncoder class object.\n\nArgs:\n min_obs (int): minimum number of observation to create a dummy variable\n label_encoder (LabelEncoder): LabelEncoder that transofrm", "source": "juraj_google_style"} +{"code": "def __call__(self, data):\n\n # For inputs which represent multiple \"rows\", the result should be newline-separated CSV rows\n if _is_mutable_sequence_like(data) and len(data) > 0 and _is_sequence_like(data[0]):\n return '\\n'.join([_CsvSerializer._serialize_row(row) for row in data])\n return _CsvSerializer._serialize_row(data)", "docstring": "Take data of various data formats and serialize them into CSV.\n\nArgs:\n data (object): Data to be serialized.\n\nReturns:\n object: Sequence of bytes to be used for the request body.", "source": "juraj_google_style"} +{"code": "def _WebSafeComponent(c, alt=False):\n\n # This sucks, but floating point between 0 and 1 is quite fuzzy...\n # So we just change the scale a while to make the equality tests\n # work, otherwise it gets wrong at some decimal far to the right.\n sc = c * 100.0\n\n # If the color is already safe, return it straight away\n d = sc % 20\n if d==0: return c\n\n # Get the lower and upper safe values\n l = sc - d\n u = l + 20\n\n # Return the 'closest' value according to the alt flag\n if alt:\n if (sc-l) >= (u-sc): return l/100.0\n else: return u/100.0\n else:\n if (sc-l) >= (u-sc): return u/100.0\n else: return l/100.0", "docstring": "Convert a color component to its web safe equivalent.\n\n Parameters:\n :c:\n The component value [0...1]\n :alt:\n If True, return the alternative value instead of the nearest one.\n\nReturns:\n The web safe equivalent of the component value.", "source": "juraj_google_style"} +{"code": "def GetForwardedIps(self, interface, interface_ip=None):\n\n try:\n ips = netifaces.ifaddresses(interface)\n ips = ips[netifaces.AF_INET]\n except (ValueError, IndexError):\n return []\n forwarded_ips = []\n for ip in ips:\n if ip['addr'] != interface_ip:\n full_addr = '%s/%d' % (ip['addr'], netaddr.IPAddress(ip['netmask']).netmask_bits())\n forwarded_ips.append(full_addr)\n return self.ParseForwardedIps(forwarded_ips)", "docstring": "Retrieve the list of configured forwarded IP addresses.\n\nArgs:\n interface: string, the output device to query.\n interface_ip: string, current interface ip address.\n\nReturns:\n list, the IP address strings.", "source": "juraj_google_style"} +{"code": "def GetArtifactsForCollection(os_name, artifact_list):\n\n artifact_arranger = ArtifactArranger(os_name, artifact_list)\n artifact_names = artifact_arranger.GetArtifactsInProperOrder()\n return artifact_names", "docstring": "Wrapper for the ArtifactArranger.\n\n Extend the artifact list by dependencies and sort the artifacts to resolve the\n dependencies.\n\nArgs:\n os_name: String specifying the OS name.\n artifact_list: List of requested artifact names.\n\nReturns:\n A list of artifacts such that if they are collected in the given order\n their dependencies are resolved.", "source": "juraj_google_style"} +{"code": "def data_group_association(self, xid):\n\n groups = []\n group_data = None\n\n # get group data from one of the arrays\n if self.groups.get(xid) is not None:\n group_data = self.groups.get(xid)\n del self.groups[xid]\n elif self.groups_shelf.get(xid) is not None:\n group_data = self.groups_shelf.get(xid)\n del self.groups_shelf[xid]\n\n if group_data is not None:\n # convert any obj into dict and process file data\n group_data = self.data_group_type(group_data)\n groups.append(group_data)\n\n # recursively get associations\n for assoc_xid in group_data.get('associatedGroupXid', []):\n groups.extend(self.data_group_association(assoc_xid))\n\n return groups", "docstring": "Return group dict array following all associations.\n\nArgs:\n xid (str): The xid of the group to retrieve associations.\n\nReturns:\n list: A list of group dicts.", "source": "juraj_google_style"} +{"code": "def decode_varint_1(buffer, pos=0):\n\n value = 0\n shift = 0\n memview = memoryview(buffer)\n for i in range(pos, pos + 10):\n try:\n byte = _read_byte(memview, i)\n except IndexError:\n raise ValueError(\"End of byte stream\")\n if byte & 0x80 != 0:\n value |= (byte & 0x7f) << shift\n shift += 7\n else:\n value |= byte << shift\n break\n else:\n # Max size of endcoded double is 10 bytes for unsigned values\n raise ValueError(\"Out of double range\")\n # Normalize sign\n return (value >> 1) ^ -(value & 1), i + 1", "docstring": "Decode an integer from a varint presentation. See\n https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints\n on how those can be produced.\n\nArgs:\n buffer (bytes-like): any object acceptable by ``memoryview``\n pos (int): optional position to read from\n\nReturns:\n (int, int): Decoded int value and next read position", "source": "juraj_google_style"} +{"code": "def suggest_filename(metadata):\n\n\n\tif 'title' in metadata and 'track_number' in metadata: # Music Manager.\n\t\tsuggested_filename = f\"{metadata['track_number']:0>2} {metadata['title']}\"\n\telif 'title' in metadata and 'trackNumber' in metadata: # Mobile.\n\t\tsuggested_filename = f\"{metadata['trackNumber']:0>2} {metadata['title']}\"\n\telif 'title' in metadata and 'tracknumber' in metadata: # audio-metadata/mutagen.\n\t\ttrack_number = _split_number_field(\n\t\t\tlist_to_single_value(\n\t\t\t\tmetadata['tracknumber']\n\t\t\t)\n\t\t)\n\t\ttitle = list_to_single_value(metadata['title'])\n\n\t\tsuggested_filename = f\"{track_number:0>2} {title}\"\n\telse:\n\t\tsuggested_filename = f\"00 {list_to_single_value(metadata.get('title', ['']))}\"\n\n\treturn _replace_invalid_characters(suggested_filename)", "docstring": "Generate a filename like Google for a song based on metadata.\n\n Parameters:\n metadata (~collections.abc.Mapping): A metadata dict.\n\nReturns:\n str: A filename string without an extension.", "source": "juraj_google_style"} +{"code": "def __init__(self, key_path=''):\n\n super(WinRegistryKey, self).__init__()\n self._key_path = key_paths.JoinKeyPath([key_path])", "docstring": "Initializes a Windows Registry key.\n\nArgs:\n key_path (Optional[str]): Windows Registry key path.", "source": "juraj_google_style"} +{"code": "def oxide_type(structure, relative_cutoff=1.1, return_nbonds=False):\n\n\n ox_obj = OxideType(structure, relative_cutoff)\n if return_nbonds:\n return ox_obj.oxide_type, ox_obj.nbonds\n else:\n return ox_obj.oxide_type", "docstring": "Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide\n\nArgs:\n structure (Structure): Input structure.\n relative_cutoff (float): Relative_cutoff * act. cutoff stipulates the\n max distance two O atoms must be from each other.\n return_nbonds (bool): Should number of bonds be requested?", "source": "juraj_google_style"} +{"code": "def update_defaults(self, new_defaults, respect_none=False):\n\n for key, value in six.iteritems(new_defaults):\n item = self.get_item(key)\n if item is None:\n raise YapconfItemNotFound(\"Cannot update default for {0}, \"\n \"there is no config item by the \"\n \"name of {1}\".format(key, key), None)\n\n item.update_default(value, respect_none)", "docstring": "Update items defaults to the values in the new_defaults dict.\n\nArgs:\n new_defaults (dict): A key-value pair of new defaults to be\n applied.\n respect_none (bool): Flag to indicate if ``None`` values should\n constitute an update to the default.", "source": "juraj_google_style"} +{"code": "def assemble_buffer(self, buf_header, buf_payload):\n\n if self.header.get('num_buffers', 0) <= len(self._buffers):\n raise ProtocolError(\"too many buffers received expecting \" + str(self.header['num_buffers']))\n self._buffers.append((buf_header, buf_payload))", "docstring": "Add a buffer header and payload that we read from the socket.\n\n This differs from add_buffer() because we're validating vs.\n the header's num_buffers, instead of filling in the header.\n\nArgs:\n buf_header (``JSON``) : a buffer header\n buf_payload (``JSON`` or bytes) : a buffer payload\n\nReturns:\n None\n\nRaises:\n ProtocolError", "source": "juraj_google_style"} +{"code": "def postings(self, quarter, stats_counter=None):\n\n logging.info('Finding postings for %s', quarter)\n for posting in self._iter_postings(quarter):\n transformed = self._transform(posting)\n transformed['id'] = '{}_{}'.format(\n self.partner_id,\n self._id(posting)\n )\n if stats_counter:\n stats_counter.track(\n input_document=posting,\n output_document=transformed\n )\n yield transformed", "docstring": "Yield job postings in common schema format\n\nArgs:\n quarter (str) The quarter, in format '2015Q1'\n stats_counter (object, optional) A counter that can track both\n input and output documents using a 'track' method.", "source": "juraj_google_style"} +{"code": "def set_column_count(self, count):\n\n current_row_count = self.row_count()\n current_column_count = self.column_count()\n if count > current_column_count:\n cl = TableEditableItem if self._editable else TableItem\n for r_key in self.children.keys():\n row = self.children[r_key]\n for i in range(current_column_count, count):\n row.append(cl(), str(i))\n if self._editable:\n row.children[str(i)].onchange.connect(\n self.on_item_changed, int(r_key), int(i))\n self._update_first_row()\n elif count < current_column_count:\n for row in self.children.values():\n for i in range(count, current_column_count):\n row.remove_child(row.children[str(i)])\n self._column_count = count", "docstring": "Sets the table column count.\n\nArgs:\n count (int): column of rows", "source": "juraj_google_style"} +{"code": "def get_plot(self, width=8, height=8):\n\n plt = pretty_plot(width, height)\n for label, electrode in self._electrodes.items():\n (x, y) = self.get_plot_data(electrode)\n plt.plot(x, y, '-', linewidth=2, label=label)\n\n plt.legend()\n if self.xaxis == \"capacity\":\n plt.xlabel('Capacity (mAh/g)')\n else:\n plt.xlabel('Fraction')\n plt.ylabel('Voltage (V)')\n plt.tight_layout()\n return plt", "docstring": "Returns a plot object.\n\nArgs:\n width: Width of the plot. Defaults to 8 in.\n height: Height of the plot. Defaults to 6 in.\n\nReturns:\n A matplotlib plot object.", "source": "juraj_google_style"} +{"code": "def main(argv=None):\n\n\n if argv is None:\n argv = sys.argv[1:]\n\n parser = build_args()\n args = parser.parse_args(args=argv)\n verbosity = args.verbose\n\n root = logging.getLogger()\n\n formatter = logging.Formatter('%(levelname).6s %(name)s %(message)s')\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n\n loglevels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]\n if verbosity >= len(loglevels):\n verbosity = len(loglevels) - 1\n\n level = loglevels[verbosity]\n root.setLevel(level)\n root.addHandler(handler)\n else:\n root.addHandler(logging.NullHandler())\n\n try:\n with open(args.script, \"rb\") as infile:\n binary_script = infile.read()\n except IOError as exc:\n print(\"ERROR: Unable to read script file: %s\" % str(exc))\n return 1\n\n try:\n script = UpdateScript.FromBinary(binary_script, allow_unknown=args.allow_unknown, show_rpcs=args.show_rpcs)\n except ArgumentError as err:\n print(\"ERROR: ArgumentError: could not parse script\")\n print(str(err))\n return 3\n except DataError as err:\n print(\"ERROR: DataError: could not parse script\")\n print(str(err))\n return 4\n\n if args.format != 'text':\n print(\"ERROR: only text format is currently supported\")\n return 2\n\n if args.format == 'text':\n print(\"\\nUpdate Script\")\n print(\"-------------\")\n print(\"Path: %s\" % args.script)\n print(\"Record Count: %d\" % len(script.records))\n print(\"Total length: %d bytes\" % len(binary_script))\n\n print(\"\\nActions\")\n print(\"-------\")\n\n for i, record in enumerate(script.records):\n print(\"%02d: %s\" % (i + 1, str(record)))\n\n print(\"\")\n\n return 0", "docstring": "Main script entry point.\n\nArgs:\n argv (list): The command line arguments, defaults to sys.argv if not passed.\n\nReturns:\n int: The return value of the script.", "source": "juraj_google_style"} +{"code": "def delete(self, personId):\n\n check_type(personId, basestring, may_be_none=False)\n\n # API request\n self._session.delete(API_ENDPOINT + '/' + personId)", "docstring": "Remove a person from the system.\n\n Only an admin can remove a person.\n\nArgs:\n personId(basestring): The ID of the person to be deleted.\n\nRaises:\n TypeError: If the parameter types are incorrect.\n ApiError: If the Webex Teams cloud returns an error.", "source": "juraj_google_style"} +{"code": "def __init__(\n self, name, aliases=None, description=None, false_value=0, urls=None):\n\n super(BooleanDefinition, self).__init__(\n name, aliases=aliases, description=description, urls=urls)\n self.false_value = false_value\n self.true_value = None", "docstring": "Initializes a boolean data type definition.\n\nArgs:\n name (str): name.\n aliases (Optional[list[str]]): aliases.\n description (Optional[str]): description.\n false_value (Optional[int]): value that represents false.\n urls (Optional[list[str]]): URLs.", "source": "juraj_google_style"} +{"code": "def show_edit_form(obj, attrs=None, title=\"\", toolTips=None):\n\n\n if attrs is None:\n if hasattr(obj, \"keys\"):\n attrs = list(obj.keys())\n else:\n raise RuntimeError(\"attrs is None and cannot determine it from obj\")\n\n specs = []\n for i, name in enumerate(attrs):\n # Tries as attribute, then as key\n try:\n value = obj.__getattribute__(name)\n except AttributeError:\n value = obj[name]\n\n if value is None:\n value = \"\" # None becomes str\n\n dict_ = {\"value\": value}\n\n if toolTips is not None:\n dict_[\"toolTip\"] = toolTips[i]\n dict_[\"tooltip\"] = toolTips[i]\n\n specs.append((name, dict_))\n form = XParametersEditor(specs=specs, title=title)\n r = form.exec_()\n return r, form", "docstring": "Shows parameters editor modal form.\n\nArgs:\n obj: object to extract attribute values from, or a dict-like\n attrs: list of attribute names\n title:\n toolTips:", "source": "juraj_google_style"} +{"code": "def when(self, key):\n\n ctx = Context(key, self)\n self.context.append(ctx)\n return ctx", "docstring": "Specify context, i.e. condition that must be met.\n\nArgs:\n key (str): Name of the context whose value you want to query.\n\nReturns:\n Context:", "source": "juraj_google_style"} +{"code": "def extract_cluster(self, target_sites, **kwargs):\n\n cluster = list(target_sites)\n others = [site for site in self if site not in cluster]\n size = 0\n while len(cluster) > size:\n size = len(cluster)\n new_others = []\n for site in others:\n for site2 in cluster:\n if CovalentBond.is_bonded(site, site2, **kwargs):\n cluster.append(site)\n break\n else:\n new_others.append(site)\n others = new_others\n return cluster", "docstring": "Extracts a cluster of atoms based on bond lengths\n\nArgs:\n target_sites ([Site]): List of initial sites to nucleate cluster.\n \\\\*\\\\*kwargs: kwargs passed through to CovalentBond.is_bonded.\n\nReturns:\n [Site/PeriodicSite] Cluster of atoms.", "source": "juraj_google_style"} +{"code": "def _write_session(self):\n\n base_name = \"%ssession\" % self._product_accronym.lower()\n filename = \"%s%s.py\" % (self._class_prefix.lower(), base_name)\n override_content = self._extract_override_content(base_name)\n\n self.write(destination=self.output_directory, filename=filename, template_name=\"session.py.tpl\",\n version=self.api_version,\n product_accronym=self._product_accronym,\n class_prefix=self._class_prefix,\n root_api=self.api_root,\n api_prefix=self.api_prefix,\n override_content=override_content,\n header=self.header_content)", "docstring": "Write SDK session file\n\nArgs:\n version (str): the version of the server", "source": "juraj_google_style"} +{"code": "def flatten_zip_dataset(*args):\n\n flattened = tf.data.Dataset.from_tensors(args[0])\n for ex in args[1:]:\n flattened = flattened.concatenate(tf.data.Dataset.from_tensors(ex))\n return flattened", "docstring": "A list of examples to a dataset containing mixed examples.\n\n Given a list of `n` dataset examples, flatten them by converting\n each element into a dataset and concatenating them to convert into a\n single dataset.\n\nArgs:\n *args: A list containing one example each from `n` different datasets.\n\nReturns:\n flattened: A new dataset containing the examples from the list as part\n of a single dataset.", "source": "juraj_google_style"} +{"code": "def __init__(self,\n max_entity_count=MAX_ENTITY_COUNT,\n mapreduce_spec=None):\n\n self.max_entity_count = max_entity_count\n params = mapreduce_spec.params if mapreduce_spec is not None else {}\n self.force_writes = bool(params.get(\"force_ops_writes\", False))\n self.puts = _ItemList(max_entity_count,\n self._flush_puts,\n repr_function=self._db_repr)\n self.deletes = _ItemList(max_entity_count,\n self._flush_deletes)\n self.ndb_puts = _ItemList(max_entity_count,\n self._flush_ndb_puts,\n repr_function=self._ndb_repr)\n self.ndb_deletes = _ItemList(max_entity_count,\n self._flush_ndb_deletes)", "docstring": "Constructor.\n\nArgs:\n max_entity_count: maximum number of entities before flushing it to db.\n mapreduce_spec: An optional instance of MapperSpec.", "source": "juraj_google_style"} +{"code": "def dataframe(self, force_refresh=False):\n\n if force_refresh:\n self.clear_cache()\n if self._dataframe is None:\n self._dataframe = self._fetch_dataframe()\n return self._dataframe", "docstring": "A pandas dataframe with lots of interesting results about this object.\n Created by calling SageMaker List and Describe APIs and converting them into\n a convenient tabular summary.\n\nArgs:\n force_refresh (bool): Set to True to fetch the latest data from SageMaker API.", "source": "juraj_google_style"} +{"code": "def update_location_centroid(point, cluster, max_distance, min_samples):\n\n cluster.append(point)\n points = [p.gen2arr() for p in cluster]\n\n # Estimates the epsilon\n eps = estimate_meters_to_deg(max_distance, precision=6)\n\n p_cluster = DBSCAN(eps=eps, min_samples=min_samples)\n p_cluster.fit(points)\n\n clusters = {}\n for i, label in enumerate(p_cluster.labels_):\n if label in clusters.keys():\n clusters[label].append(points[i])\n else:\n clusters[label] = [points[i]]\n\n centroids = []\n biggest_centroid_l = -float(\"inf\")\n biggest_centroid = None\n\n for label, n_cluster in clusters.items():\n centroid = compute_centroid(n_cluster)\n centroids.append(centroid)\n\n if label >= 0 and len(n_cluster) >= biggest_centroid_l:\n biggest_centroid_l = len(n_cluster)\n biggest_centroid = centroid\n\n if biggest_centroid is None:\n biggest_centroid = compute_centroid(points)\n\n return biggest_centroid, cluster", "docstring": "Updates the centroid of a location cluster with another point\n\nArgs:\n point (:obj:`Point`): Point to add to the cluster\n cluster (:obj:`list` of :obj:`Point`): Location cluster\n max_distance (float): Max neighbour distance\n min_samples (int): Minimum number of samples\n\nReturns:\n (:obj:`Point`, :obj:`list` of :obj:`Point`): Tuple with the location centroid\n and new point cluster (given cluster + given point)", "source": "juraj_google_style"} +{"code": "def do_reset_ids(concatenated_meta_df, data_df, concat_direction):\n\n if concat_direction == \"horiz\":\n\n # Make sure cids agree between data_df and concatenated_meta_df\n assert concatenated_meta_df.index.equals(data_df.columns), (\n \"cids in concatenated_meta_df do not agree with cids in data_df.\")\n\n # Reset cids in concatenated_meta_df\n reset_ids_in_meta_df(concatenated_meta_df)\n\n # Replace cids in data_df with the new ones from concatenated_meta_df\n # (just an array of unique integers, zero-indexed)\n data_df.columns = pd.Index(concatenated_meta_df.index.values)\n\n elif concat_direction == \"vert\":\n\n # Make sure rids agree between data_df and concatenated_meta_df\n assert concatenated_meta_df.index.equals(data_df.index), (\n \"rids in concatenated_meta_df do not agree with rids in data_df.\")\n\n # Reset rids in concatenated_meta_df\n reset_ids_in_meta_df(concatenated_meta_df)\n\n # Replace rids in data_df with the new ones from concatenated_meta_df\n # (just an array of unique integers, zero-indexed)\n data_df.index = pd.Index(concatenated_meta_df.index.values)", "docstring": "Reset ids in concatenated metadata and data dfs to unique integers and\n save the old ids in a metadata column.\n\n Note that the dataframes are modified in-place.\n\nArgs:\n concatenated_meta_df (pandas df)\n data_df (pandas df)\n concat_direction (string): 'horiz' or 'vert'\n\nReturns:\n None (dfs modified in-place)", "source": "juraj_google_style"} +{"code": "def _FindLargestIdPostfixNumber(self, schedule):\n\n postfix_number_re = re.compile('(\\d+)$')\n\n def ExtractPostfixNumber(entity_id):\n\n if entity_id is None:\n return 0\n match = postfix_number_re.search(entity_id)\n if match is not None:\n return int(match.group(1))\n else:\n return 0\n\n id_data_sets = {'agency_id': schedule.GetAgencyList(),\n 'stop_id': schedule.GetStopList(),\n 'route_id': schedule.GetRouteList(),\n 'trip_id': schedule.GetTripList(),\n 'service_id': schedule.GetServicePeriodList(),\n 'fare_id': schedule.GetFareAttributeList(),\n 'shape_id': schedule.GetShapeList()}\n\n max_postfix_number = 0\n for id_name, entity_list in id_data_sets.items():\n for entity in entity_list:\n entity_id = getattr(entity, id_name)\n postfix_number = ExtractPostfixNumber(entity_id)\n max_postfix_number = max(max_postfix_number, postfix_number)\n return max_postfix_number", "docstring": "Finds the largest integer used as the ending of an id in the schedule.\n\nArgs:\n schedule: The schedule to check.\n\nReturns:\n The maximum integer used as an ending for an id.", "source": "juraj_google_style"} +{"code": "def start(self, attempts=5, timeout=2):\n\n\n if not self.alive():\n with LogTask('Create network %s' % self.name()):\n net = self.libvirt_con.networkCreateXML(self._libvirt_xml())\n if net is None:\n raise RuntimeError(\n 'failed to create network, XML: %s' %\n (self._libvirt_xml())\n )\n for _ in range(attempts):\n if net.isActive():\n return\n LOGGER.debug(\n 'waiting for network %s to become active', net.name()\n )\n time.sleep(timeout)\n raise RuntimeError(\n 'failed to verify network %s is active' % net.name()\n )", "docstring": "Start the network, will check if the network is active ``attempts``\n times, waiting ``timeout`` between each attempt.\n\nArgs:\n attempts (int): number of attempts to check the network is active\n timeout (int): timeout for each attempt\n\nReturns:\n None\n\nRaises:\n RuntimeError: if network creation failed, or failed to verify it is\n active.", "source": "juraj_google_style"} +{"code": "def encode(self, object_):\n\n if self.enforce_reversible:\n self.enforce_reversible = False\n if self.decode(self.encode(object_)) != object_:\n raise ValueError('Encoding is not reversible for \"%s\"' % object_)\n self.enforce_reversible = True\n\n return object_", "docstring": "Encodes an object.\n\nArgs:\n object_ (object): Object to encode.\n\nReturns:\n object: Encoding of the object.", "source": "juraj_google_style"} +{"code": "def __init__(self,\n segments=None,\n\n id=DEFAULT_ID,\n confidence=DEFAULT_CONFIDENCE,\n kvpairs=DEFAULT_DYNAMIC_METADATA,\n status=DEFAULT_STATUS,\n author=DEFAULT_AUTHOR):\n\n self.segments = segments\n\n RAMONBase.__init__(self,\n id=id,\n confidence=confidence,\n kvpairs=kvpairs,\n status=status,\n author=author)", "docstring": "Initialize a new `RAMONNeuron`. Neurons take all of the arguments of\n `RAMONBase`.\n\nArgs:\n segments (int[]: None): A list of RAMON IDs that make up the neuron", "source": "juraj_google_style"} +{"code": "def changes(self, target_version=None, nodes=None, labels=None):\n\n if nodes is None:\n nodes = []\n if labels is None:\n labels = []\n\n current_time = time.time()\n\n params = {\n 'nodes': nodes,\n 'clientTimestamp': _node.NodeTimestamps.int_to_str(current_time),\n 'requestHeader': {\n 'clientSessionId': self._session_id,\n 'clientPlatform': 'ANDROID',\n 'clientVersion': {\n 'major': '9',\n 'minor': '9',\n 'build': '9',\n 'revision': '9'\n },\n 'capabilities': [\n {'type': 'NC'}, # Color support (Send note color)\n {'type': 'PI'}, # Pinned support (Send note pinned)\n {'type': 'LB'}, # Labels support (Send note labels)\n {'type': 'AN'}, # Annotations support (Send annotations)\n {'type': 'SH'}, # Sharing support\n {'type': 'DR'}, # Drawing support\n {'type': 'TR'}, # Trash support (Stop setting the delete timestamp)\n {'type': 'IN'}, # Indentation support (Send listitem parent)\n\n {'type': 'SNB'}, # Allows modification of shared notes?\n {'type': 'MI'}, # Concise blob info?\n {'type': 'CO'}, # VSS_SUCCEEDED when off?\n\n # TODO: Figure out what these do:\n # {'type': 'EC'}, # ???\n # {'type': 'RB'}, # Rollback?\n # {'type': 'EX'}, # ???\n ]\n },\n }\n if target_version is not None:\n params['targetVersion'] = target_version\n\n if labels:\n params['userInfo'] = {\n 'labels': labels\n }\n\n logger.debug('Syncing %d labels and %d nodes', len(labels), len(nodes))\n\n return self.send(\n url=self._base_url + 'changes',\n method='POST',\n json=params\n )", "docstring": "Sync up (and down) all changes.\n\nArgs:\n target_version (str): The local change version.\n nodes (List[dict]): A list of nodes to sync up to the server.\n labels (List[dict]): A list of labels to sync up to the server.\n\nReturns:\n dict: Description of all changes.\n\nRaises:\n APIException: If the server returns an error.", "source": "juraj_google_style"} +{"code": "def numeric_task_id(task_id):\n\n\n # This function exists to support the legacy \"task-id\" format in the \"google\"\n # provider. Google labels originally could not be numeric. When the google\n # provider is completely replaced by the google-v2 provider, this function can\n # go away.\n\n if task_id is not None:\n if task_id.startswith('task-'):\n return int(task_id[len('task-'):])\n else:\n return int(task_id)", "docstring": "Converts a task-id to the numeric task-id.\n\nArgs:\n task_id: task-id in either task-n or n format\n\nReturns:\n n", "source": "juraj_google_style"} +{"code": "def add_connection(self, connection_id, internal_id, context):\n\n # Make sure we are not reusing an id that is currently connected to something\n if self._get_connection_state(connection_id) != self.Disconnected:\n return\n if self._get_connection_state(internal_id) != self.Disconnected:\n return\n\n conn_data = {\n 'state': self.Idle,\n 'microstate': None,\n 'connection_id': connection_id,\n 'internal_id': internal_id,\n 'context': context\n }\n\n self._connections[connection_id] = conn_data\n self._int_connections[internal_id] = conn_data", "docstring": "Add an already created connection. Used to register devices connected before starting the device adapter.\n\nArgs:\n connection_id (int): The external connection id\n internal_id (string): An internal identifier for the connection\n context (dict): Additional information to associate with this context", "source": "juraj_google_style"} +{"code": "def from_file(feff_inp_file='feff.inp', ldos_file='ldos'):\n\n header_str = Header.header_string_from_file(feff_inp_file)\n header = Header.from_string(header_str)\n structure = header.struct\n nsites = structure.num_sites\n parameters = Tags.from_file(feff_inp_file)\n\n if \"RECIPROCAL\" in parameters:\n pot_dict = dict()\n pot_readstart = re.compile('.*iz.*lmaxsc.*xnatph.*xion.*folp.*')\n pot_readend = re.compile('.*ExternalPot.*switch.*')\n pot_inp = re.sub(r'feff.inp', r'pot.inp', feff_inp_file)\n dos_index = 1\n begin = 0\n\n with zopen(pot_inp, \"r\") as potfile:\n for line in potfile:\n if len(pot_readend.findall(line)) > 0:\n break\n\n if begin == 1:\n begin += 1\n continue\n\n if begin == 2:\n z_number = int(line.strip().split()[0])\n ele_name = Element.from_Z(z_number).name\n if ele_name not in pot_dict:\n pot_dict[ele_name] = dos_index\n else:\n pot_dict[ele_name] = min(dos_index, pot_dict[ele_name])\n dos_index += 1\n\n if len(pot_readstart.findall(line)) > 0:\n begin = 1\n else:\n pot_string = Potential.pot_string_from_file(feff_inp_file)\n dicts = Potential.pot_dict_from_string(pot_string)\n pot_dict = dicts[0]\n\n with zopen(ldos_file + \"00.dat\", \"r\") as fobject:\n f = fobject.readlines()\n efermi = float(f[0].split()[4])\n\n dos_energies = []\n ldos = {}\n\n for i in range(1, len(pot_dict) + 1):\n if len(str(i)) == 1:\n ldos[i] = np.loadtxt(\"{}0{}.dat\".format(ldos_file, i))\n else:\n ldos[i] = np.loadtxt(\"{}{}.dat\".format(ldos_file, i))\n\n for i in range(0, len(ldos[1])):\n dos_energies.append(ldos[1][i][0])\n\n all_pdos = []\n vorb = {\"s\": Orbital.s, \"p\": Orbital.py, \"d\": Orbital.dxy,\n \"f\": Orbital.f0}\n forb = {\"s\": 0, \"p\": 1, \"d\": 2, \"f\": 3}\n\n dlength = len(ldos[1])\n\n for i in range(nsites):\n pot_index = pot_dict[structure.species[i].symbol]\n all_pdos.append(defaultdict(dict))\n for k, v in vorb.items():\n density = [ldos[pot_index][j][forb[k] + 1]\n for j in range(dlength)]\n updos = density\n downdos = None\n if downdos:\n all_pdos[-1][v] = {Spin.up: updos, Spin.down: downdos}\n else:\n all_pdos[-1][v] = {Spin.up: updos}\n\n pdos = all_pdos\n vorb2 = {0: Orbital.s, 1: Orbital.py, 2: Orbital.dxy, 3: Orbital.f0}\n pdoss = {structure[i]: {v: pdos[i][v]\n for v in vorb2.values()}\n for i in range(len(pdos))}\n\n forb = {\"s\": 0, \"p\": 1, \"d\": 2, \"f\": 3}\n\n tdos = [0] * dlength\n for i in range(nsites):\n pot_index = pot_dict[structure.species[i].symbol]\n for v in forb.values():\n density = [ldos[pot_index][j][v + 1] for j in range(dlength)]\n for j in range(dlength):\n tdos[j] = tdos[j] + density[j]\n tdos = {Spin.up: tdos}\n\n dos = Dos(efermi, dos_energies, tdos)\n complete_dos = CompleteDos(structure, dos, pdoss)\n charge_transfer = LDos.charge_transfer_from_file(feff_inp_file,\n ldos_file)\n return LDos(complete_dos, charge_transfer)", "docstring": "Creates LDos object from raw Feff ldos files by\n by assuming they are numbered consecutively, i.e. ldos01.dat\n ldos02.dat...\n\nArgs:\n feff_inp_file (str): input file of run to obtain structure\n ldos_file (str): output ldos file of run to obtain dos info, etc.", "source": "juraj_google_style"} +{"code": "def __init__(self, attribute_values_hash):\n\n super(FakeIdentifier, self).__init__()\n self.attribute_values_hash = attribute_values_hash", "docstring": "Initializes a fake attribute container identifier.\n\nArgs:\n attribute_values_hash (int): hash value of the attribute values.", "source": "juraj_google_style"} +{"code": "def get_user_info(self, token):\n\n\n url = self.get_user_info_url()\n\n try:\n headers = {'Authorization': 'Bearer {}'.format(token)}\n response = requests.get(url, headers=headers)\n except requests.RequestException:\n logger.exception('Failed to retrieve user info due to a request exception.')\n raise UserInfoRetrievalFailed\n\n if response.status_code == 200:\n return self.process_user_info_response(response.json())\n else:\n msg = 'Failed to retrieve user info. Server [{server}] responded with status [{status}].'.format(\n server=url,\n status=response.status_code\n )\n raise UserInfoRetrievalFailed(msg)", "docstring": "Retrieves the user info from the OAuth provider.\n\nArgs:\n token (str): OAuth2 access token.\n\nReturns:\n dict\n\nRaises:\n UserInfoRetrievalFailed: Retrieval of user info from the remote server failed.", "source": "juraj_google_style"} +{"code": "def spawn_agent(self, agent_definition, location):\n\n self._should_write_to_command_buffer = True\n self._add_agents(agent_definition)\n command_to_send = SpawnAgentCommand(location, agent_definition.name, agent_definition.type)\n self._commands.add_command(command_to_send)", "docstring": "Queues a spawn agent command. It will be applied when `tick` or `step` is called next.\n The agent won't be able to be used until the next frame.\n\nArgs:\n agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn.\n location (np.ndarray or list): The position to spawn the agent in the world, in XYZ coordinates (in meters).", "source": "juraj_google_style"} +{"code": "def mrc_to_marc(mrc):\n\n # ignore blank lines\n lines = [\n line\n for line in mrc.splitlines()\n if line.strip()\n ]\n\n def split_to_parts(lines):\n for line in lines:\n first_part, second_part = line.split(\" L \", 1)\n\n yield line, first_part, second_part.lstrip()\n\n control_lines = []\n data_lines = []\n for line, first_part, second_part in split_to_parts(lines):\n if second_part.startswith(\"$\"):\n data_lines.append(line)\n else:\n control_lines.append(line)\n\n # convert controlfield lines\n record = MARCXMLRecord()\n record.oai_marc = True\n for line, descr, content in split_to_parts(control_lines):\n record.controlfields[descr.strip()[:3]] = content\n\n def get_subfield_dict(line):\n fields = (\n (field[0], field[1:])\n for field in line.split(\"$$\")[1:]\n )\n\n fields_dict = defaultdict(list)\n for key, val in fields:\n fields_dict[key].append(val)\n\n return fields_dict\n\n # convert datafield lines\n for line, descr, content_line in split_to_parts(data_lines):\n name = descr[:3]\n i1 = descr[3]\n i2 = descr[4]\n\n record.add_data_field(\n name,\n i1,\n i2,\n get_subfield_dict(content_line)\n )\n\n return record.to_XML()", "docstring": "Convert MRC data format to MARC XML.\n\nArgs:\n mrc (str): MRC as string.\n\nReturns:\n str: XML with MARC.", "source": "juraj_google_style"} +{"code": "def series_with_permutation(self, other):\n\n combined_permutation = tuple([self.permutation[p]\n for p in other.permutation])\n return CPermutation.create(combined_permutation)", "docstring": "Compute the series product with another channel permutation circuit\n\nArgs:\n other (CPermutation):\n\nReturns:\n Circuit: The composite permutation circuit (could also be the\n identity circuit for n channels)", "source": "juraj_google_style"} +{"code": "def register_instance(self, instance: Any, allow_dotted_names: bool=False):\n\n if self.instance:\n raise RuntimeError(\"can only register one instance\")\n self.instance = instance\n self.allow_dotted_names = allow_dotted_names\n return True", "docstring": "注册一个实例用于执行,注意只能注册一个.\n\n Parameters:\n instance (Any): - 将一个类的实例注册到rpc\n allow_dotted_names (bool): 是否允许带`.`号的名字", "source": "juraj_google_style"} +{"code": "def get_or_set_section(\n self,\n config,\n section,\n option,\n DEFAULT_VALUE,\n method='get'\n ):\n\n\n try:\n if isinstance(DEFAULT_VALUE, str):\n val = DEFAULT_VALUE\n else:\n val = json.dumps(DEFAULT_VALUE)\n if method == 'get':\n return self.get_config(section, option)\n else:\n self.set_config(section, option, val)\n return val\n\n except:\n self.set_config(section, option, val)\n return val", "docstring": "[summary]\n\nArgs:\n config {[type]} -- [description]\n section {[type]} -- [description]\n option {[type]} -- [description]\n DEFAULT_VALUE {[type]} -- [description]\n\n Keyword Arguments:\n method {str} -- [description] (default: {'get'})\n\nReturns:\n [type] -- [description]", "source": "juraj_google_style"} +{"code": "def limit_replace(self, accountID, orderID, **kwargs):\n\n return self.replace(\n accountID,\n orderID,\n order=LimitOrderRequest(**kwargs)\n )", "docstring": "Shortcut to replace a pending Limit Order in an Account\n\nArgs:\n accountID : The ID of the Account\n orderID : The ID of the Limit Order to replace\n kwargs : The arguments to create a LimitOrderRequest\n\nReturns:\n v20.response.Response containing the results from submitting\n the request", "source": "juraj_google_style"} +{"code": "def _prefix_from_ip_string(self, ip_str):\n\n # Parse the netmask/hostmask like an IP address.\n try:\n ip_int = self._ip_int_from_string(ip_str)\n except AddressValueError:\n self._report_invalid_netmask(ip_str)\n\n # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).\n # Note that the two ambiguous cases (all-ones and all-zeroes) are\n # treated as netmasks.\n try:\n return self._prefix_from_ip_int(ip_int)\n except ValueError:\n pass\n\n # Invert the bits, and try matching a /0+1+/ hostmask instead.\n ip_int ^= self._ALL_ONES\n try:\n return self._prefix_from_ip_int(ip_int)\n except ValueError:\n self._report_invalid_netmask(ip_str)", "docstring": "Turn a netmask/hostmask string into a prefix length\n\nArgs:\n ip_str: The netmask/hostmask to be converted\n\nReturns:\n An integer, the prefix length.\n\nRaises:\n NetmaskValueError: If the input is not a valid netmask/hostmask", "source": "juraj_google_style"} +{"code": "def CalculateForecastStats(matched, available, possible=None):\n\n if matched > 0:\n available_percent = (float(available) / matched) * 100.\n else:\n available_percent = 0\n\n if possible is not None:\n if matched > 0:\n possible_percent = (possible/float(matched)) * 100.\n else:\n possible_percent = 0\n else:\n possible_percent = None\n\n return available_percent, possible_percent", "docstring": "Calculate forecast percentage stats.\n\nArgs:\n matched: The number of matched impressions.\n available: The number of available impressions.\n possible: The optional number of possible impressions.\n\nReturns:\n The percentage of impressions that are available and possible.", "source": "juraj_google_style"} +{"code": "def make_node(cls, lineno, operator, operand, func=None, type_=None):\n\n assert type_ is None or isinstance(type_, SymbolTYPE)\n\n if func is not None: # Try constant-folding\n if is_number(operand): # e.g. ABS(-5)\n return SymbolNUMBER(func(operand.value), lineno=lineno)\n elif is_string(operand): # e.g. LEN(\"a\")\n return SymbolSTRING(func(operand.text), lineno=lineno)\n\n if type_ is None:\n type_ = operand.type_\n\n if operator == 'MINUS':\n if not type_.is_signed:\n type_ = type_.to_signed()\n operand = SymbolTYPECAST.make_node(type_, operand, lineno)\n elif operator == 'NOT':\n type_ = TYPE.ubyte\n\n return cls(operator, operand, lineno, type_)", "docstring": "Creates a node for a unary operation. E.g. -x or LEN(a$)\n\n Parameters:\n -func: lambda function used on constant folding when possible\n -type_: the resulting type (by default, the same as the argument).\n For example, for LEN (str$), result type is 'u16'\n and arg type is 'string'", "source": "juraj_google_style"} +{"code": "def _SimpleDecoder(wire_type, decode_value):\n\n\n def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default):\n if is_packed:\n local_DecodeVarint = _DecodeVarint\n def DecodePackedField(buffer, pos, end, message, field_dict):\n value = field_dict.get(key)\n if value is None:\n value = field_dict.setdefault(key, new_default(message))\n (endpoint, pos) = local_DecodeVarint(buffer, pos)\n endpoint += pos\n if endpoint > end:\n raise _DecodeError('Truncated message.')\n while pos < endpoint:\n (element, pos) = decode_value(buffer, pos)\n value.append(element)\n if pos > endpoint:\n del value[-1] # Discard corrupt value.\n raise _DecodeError('Packed element was truncated.')\n return pos\n return DecodePackedField\n elif is_repeated:\n tag_bytes = encoder.TagBytes(field_number, wire_type)\n tag_len = len(tag_bytes)\n def DecodeRepeatedField(buffer, pos, end, message, field_dict):\n value = field_dict.get(key)\n if value is None:\n value = field_dict.setdefault(key, new_default(message))\n while 1:\n (element, new_pos) = decode_value(buffer, pos)\n value.append(element)\n # Predict that the next tag is another copy of the same repeated\n # field.\n pos = new_pos + tag_len\n if buffer[new_pos:pos] != tag_bytes or new_pos >= end:\n # Prediction failed. Return.\n if new_pos > end:\n raise _DecodeError('Truncated message.')\n return new_pos\n return DecodeRepeatedField\n else:\n def DecodeField(buffer, pos, end, message, field_dict):\n (field_dict[key], pos) = decode_value(buffer, pos)\n if pos > end:\n del field_dict[key] # Discard corrupt value.\n raise _DecodeError('Truncated message.')\n return pos\n return DecodeField\n\n return SpecificDecoder", "docstring": "Return a constructor for a decoder for fields of a particular type.\n\nArgs:\n wire_type: The field's wire type.\n decode_value: A function which decodes an individual value, e.g.\n _DecodeVarint()", "source": "juraj_google_style"} +{"code": "def __init__(self, basecache=None):\n\n self._data = {}\n\n if basecache is not None:\n for key,val in basecache.items():\n self._data[key] = val", "docstring": "Create a new transient cache.\n\n Optionally supports populating the cache with values of an\n existing cache.\n\nArgs:\n basecache (TransientCache, optional): Cache to populate this new\n cache with.", "source": "juraj_google_style"} +{"code": "def users_setPhoto(self, *, image: Union[str, IOBase], **kwargs) -> SlackResponse:\n\n self._validate_xoxp_token()\n return self.api_call(\"users.setPhoto\", files={\"image\": image}, data=kwargs)", "docstring": "Set the user profile photo\n\nArgs:\n image (str): Supply the path of the image you'd like to upload.\n e.g. 'myimage.png'", "source": "juraj_google_style"} +{"code": "def generate_timing_stats(file_list, var_list):\n\n timing_result = dict()\n timing_summary = dict()\n for file in file_list:\n timing_result[file] = functions.parse_gptl(file, var_list)\n for var in var_list:\n var_time = []\n for f, data in timing_result.items():\n try:\n var_time.append(data[var])\n except:\n continue\n if len(var_time):\n timing_summary[var] = {'mean': np.mean(var_time),\n 'max': np.max(var_time),\n 'min': np.min(var_time),\n 'std': np.std(var_time)}\n return timing_summary", "docstring": "Parse all of the timing files, and generate some statistics\n about the run.\n\nArgs:\n file_list: A list of timing files to parse\n var_list: A list of variables to look for in the timing file\n\nReturns:\n A dict containing values that have the form:\n [mean, min, max, mean, standard deviation]", "source": "juraj_google_style"} +{"code": "def download(cls, root, check=None):\n\n path = os.path.join(root, cls.name)\n check = path if check is None else check\n if not os.path.isdir(check):\n for url in cls.urls:\n if isinstance(url, tuple):\n url, filename = url\n else:\n filename = os.path.basename(url)\n zpath = os.path.join(path, filename)\n if not os.path.isfile(zpath):\n if not os.path.exists(os.path.dirname(zpath)):\n os.makedirs(os.path.dirname(zpath))\n print('downloading {}'.format(filename))\n download_from_url(url, zpath)\n zroot, ext = os.path.splitext(zpath)\n _, ext_inner = os.path.splitext(zroot)\n if ext == '.zip':\n with zipfile.ZipFile(zpath, 'r') as zfile:\n print('extracting')\n zfile.extractall(path)\n # tarfile cannot handle bare .gz files\n elif ext == '.tgz' or ext == '.gz' and ext_inner == '.tar':\n with tarfile.open(zpath, 'r:gz') as tar:\n dirs = [member for member in tar.getmembers()]\n tar.extractall(path=path, members=dirs)\n elif ext == '.gz':\n with gzip.open(zpath, 'rb') as gz:\n with open(zroot, 'wb') as uncompressed:\n shutil.copyfileobj(gz, uncompressed)\n\n return os.path.join(path, cls.dirname)", "docstring": "Download and unzip an online archive (.zip, .gz, or .tgz).\n\nArgs:\n root (str): Folder to download data to.\n check (str or None): Folder whose existence indicates\n that the dataset has already been downloaded, or\n None to check the existence of root/{cls.name}.\n\nReturns:\n str: Path to extracted dataset.", "source": "juraj_google_style"} +{"code": "def _extract_datasets_to_harvest(cls, report):\n\n assert isinstance(report, string_types + (list,))\n\n # Si `report` es una lista de tuplas con longitud 2, asumimos que es un\n # reporte procesado para extraer los datasets a harvestear. Se devuelve\n # intacta.\n if (isinstance(report, list) and all([isinstance(x, tuple) and\n len(x) == 2 for x in report])):\n return report\n\n table = readers.read_table(report)\n table_keys = table[0].keys()\n expected_keys = [\"catalog_metadata_url\", \"dataset_title\",\n \"dataset_accrualPeriodicity\"]\n\n # Verifico la presencia de las claves básicas de un config de harvester\n for key in expected_keys:\n if key not in table_keys:\n raise KeyError(.format(key))\n\n if \"harvest\" in table_keys:\n # El archivo es un reporte de datasets.\n datasets_to_harvest = [\n (row[\"catalog_metadata_url\"], row[\"dataset_title\"]) for row in\n table if int(row[\"harvest\"])]\n else:\n # El archivo es un config de harvester.\n datasets_to_harvest = [\n (row[\"catalog_metadata_url\"], row[\"dataset_title\"]) for row in\n table]\n\n return datasets_to_harvest", "docstring": "Extrae de un reporte los datos necesarios para reconocer qué\n datasets marcar para cosecha en cualquier generador.\n\nArgs:\n report (str o list): Reporte (lista de dicts) o path a uno.\n\nReturns:\n list: Lista de tuplas con los títulos de catálogo y dataset de cada\n reporte extraído.", "source": "juraj_google_style"} +{"code": "def wait_for_endpoint(self, endpoint, poll=5):\n\n desc = _wait_until(lambda: _deploy_done(self.sagemaker_client, endpoint), poll)\n status = desc['EndpointStatus']\n\n if status != 'InService':\n reason = desc.get('FailureReason', None)\n raise ValueError('Error hosting endpoint {}: {} Reason: {}'.format(endpoint, status, reason))\n return desc", "docstring": "Wait for an Amazon SageMaker endpoint deployment to complete.\n\nArgs:\n endpoint (str): Name of the ``Endpoint`` to wait for.\n poll (int): Polling interval in seconds (default: 5).\n\nReturns:\n dict: Return value from the ``DescribeEndpoint`` API.", "source": "juraj_google_style"} +{"code": "def get_structures(self, primitive=True):\n\n structures = []\n for d in self._cif.data.values():\n try:\n s = self._get_structure(d, primitive)\n if s:\n structures.append(s)\n except (KeyError, ValueError) as exc:\n # Warn the user (Errors should never pass silently)\n # A user reported a problem with cif files produced by Avogadro\n # in which the atomic coordinates are in Cartesian coords.\n self.errors.append(str(exc))\n warnings.warn(str(exc))\n if self.errors:\n warnings.warn(\"Issues encountered while parsing CIF:\")\n for error in self.errors:\n warnings.warn(error)\n if len(structures) == 0:\n raise ValueError(\"Invalid cif file with no structures!\")\n return structures", "docstring": "Return list of structures in CIF file. primitive boolean sets whether a\n conventional cell structure or primitive cell structure is returned.\n\nArgs:\n primitive (bool): Set to False to return conventional unit cells.\n Defaults to True. With magnetic CIF files, will return primitive\n magnetic cell which may be larger than nuclear primitive cell.\n\nReturns:\n List of Structures.", "source": "juraj_google_style"} +{"code": "def _augment_observation(self, ob, reward, cumulative_reward):\n\n img = PIL_Image().new(\"RGB\",\n (ob.shape[1], self.HEADER_HEIGHT,))\n draw = PIL_ImageDraw().Draw(img)\n draw.text(\n (1, 0), \"c:{:3}, r:{:3}\".format(int(cumulative_reward), int(reward)),\n fill=(255, 0, 0)\n )\n draw.text(\n (1, 15), \"fc:{:3}\".format(int(self._frame_counter)),\n fill=(255, 0, 0)\n )\n header = np.asarray(img)\n del img\n header.setflags(write=1)\n # Top row color indicates if WAIT MODE is on.\n if self._wait:\n pixel_fill = (0, 255, 0)\n else:\n pixel_fill = (255, 0, 0)\n header[0, :, :] = pixel_fill\n return np.concatenate([header, ob], axis=0)", "docstring": "Expand observation array with additional information header (top rows).\n\nArgs:\n ob: observation\n reward: reward to be included in header.\n cumulative_reward: total cumulated reward to be included in header.\n\nReturns:\n Expanded observation array.", "source": "juraj_google_style"} +{"code": "def finish_directory_parse(self):\n # type: () -> None\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('UDF File Entry not initialized')\n\n if self.icb_tag.file_type != 4:\n raise pycdlibexception.PyCdlibInternalError('Can only finish_directory for a directory')", "docstring": "A method to finish up the parsing of this UDF File Entry directory.\n In particular, this method checks to see if it is in sorted order for\n future use.\n\n Parameters:\n None.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def deep_diff(self, db_data, user_data):\n\n # NOTE: tcex does include the deepdiff library as a dependencies since it is only\n # required for local testing.\n try:\n from deepdiff import DeepDiff\n except ImportError:\n print('Could not import DeepDiff module (try \"pip install deepdiff\").')\n sys.exit(1)\n\n try:\n ddiff = DeepDiff(db_data, user_data, ignore_order=True)\n except KeyError:\n return False\n except NameError:\n return False\n if ddiff:\n self.tcex.log.info(u'[validate] Diff : {}'.format(ddiff))\n return False\n return True", "docstring": "Validate data in user data.\n\nArgs:\n db_data (dict|str|list): The data store in Redis.\n user_data (dict|str|list): The user provided data.\n\nReturns:\n bool: True if the data passed validation.", "source": "juraj_google_style"} +{"code": "def RemoveProcessedTaskStorage(self, task):\n\n if self._storage_type != definitions.STORAGE_TYPE_SESSION:\n raise IOError('Unsupported storage type.')\n\n processed_storage_file_path = self._GetProcessedStorageFilePath(task)\n\n try:\n os.remove(processed_storage_file_path)\n except OSError as exception:\n raise IOError((\n 'Unable to remove task storage file: {0:s} with error: '\n '{1!s}').format(processed_storage_file_path, exception))", "docstring": "Removes a processed task storage.\n\nArgs:\n task (Task): task.\n\nRaises:\n IOError: if the storage type is not supported or\n if the storage file cannot be removed.\n OSError: if the storage type is not supported or\n if the storage file cannot be removed.", "source": "juraj_google_style"} +{"code": "def not_storable(_type):\n\n return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type)))", "docstring": "Helper for tagging unserializable types.\n\nArgs:\n _type (type): type to be ignored.\n\nReturns:\n Storable: storable instance that does not poke.", "source": "juraj_google_style"} +{"code": "def stage_signature(vcs, signature):\n\n evidence_path = _get_staged_history_path(vcs)\n staged = get_staged_signatures(vcs)\n if signature in staged:\n raise AlreadyStagedError\n staged.append(signature)\n string = '\\n'.join(staged)\n with open(evidence_path, 'w') as f:\n f.write(string)", "docstring": "Add `signature` to the list of staged signatures\n\nArgs:\n vcs (easyci.vcs.base.Vcs)\n signature (basestring)\n\nRaises:\n AlreadyStagedError", "source": "juraj_google_style"} +{"code": "def __init__(self, flow, **kwargs):\n\n self.flow = flow\n self.max_njobs_inqueue = kwargs.get(\"max_njobs_inqueue\", 200)", "docstring": "Initialize the object\n\nArgs:\n flow: :class:`Flow` object\n max_njobs_inqueue: The launcher will stop submitting jobs when the\n number of jobs in the queue is >= Max number of jobs", "source": "juraj_google_style"} +{"code": "def parse_mmtf_header(infile):\n\n infodict = {}\n\n mmtf_decoder = mmtf.parse(infile)\n infodict['date'] = mmtf_decoder.deposition_date\n infodict['release_date'] = mmtf_decoder.release_date\n try:\n infodict['experimental_method'] = [x.decode() for x in mmtf_decoder.experimental_methods]\n except AttributeError:\n infodict['experimental_method'] = [x for x in mmtf_decoder.experimental_methods]\n infodict['resolution'] = mmtf_decoder.resolution\n infodict['description'] = mmtf_decoder.title\n\n group_name_exclude = ['HOH']\n chem_comp_type_exclude = ['l-peptide linking', 'peptide linking']\n chemicals = list(set([mmtf_decoder.group_list[idx]['groupName'] for idx in mmtf_decoder.group_type_list if mmtf_decoder.group_list[idx]['chemCompType'].lower() not in chem_comp_type_exclude and mmtf_decoder.group_list[idx]['groupName'] not in group_name_exclude]))\n infodict['chemicals'] = chemicals\n return infodict", "docstring": "Parse an MMTF file and return basic header-like information.\n\nArgs:\n infile (str): Path to MMTF file\n\nReturns:\n dict: Dictionary of parsed header\n\n Todo:\n - Can this be sped up by not parsing the 3D coordinate info somehow?\n - OR just store the sequences when this happens since it is already being parsed.", "source": "juraj_google_style"} +{"code": "def WriteTaskCompletion(self, aborted=False):\n\n self._RaiseIfNotWritable()\n\n if self._storage_type != definitions.STORAGE_TYPE_TASK:\n raise IOError('Unsupported storage type.')\n\n self._task.aborted = aborted\n task_completion = self._task.CreateTaskCompletion()\n self._storage_file.WriteTaskCompletion(task_completion)", "docstring": "Writes task completion information.\n\nArgs:\n aborted (Optional[bool]): True if the session was aborted.\n\nRaises:\n IOError: if the storage type is not supported or\n when the storage writer is closed.\n OSError: if the storage type is not supported or\n when the storage writer is closed.", "source": "juraj_google_style"} +{"code": "def ParseOptions(cls, options, configuration_object):\n\n if not isinstance(configuration_object, tools.CLITool):\n raise errors.BadConfigObject(\n 'Configuration object is not an instance of CLITool')\n\n yara_rules_string = None\n\n path = getattr(options, 'yara_rules_path', None)\n if path:\n try:\n with io.open(path, 'rt', encoding='utf-8') as rules_file:\n yara_rules_string = rules_file.read()\n\n except IOError as exception:\n raise errors.BadConfigObject(\n 'Unable to read Yara rules file: {0:s} with error: {1!s}'.format(\n path, exception))\n\n try:\n # We try to parse the rules here, to check that the definitions are\n # valid. We then pass the string definitions along to the workers, so\n # that they don't need read access to the rules file.\n yara.compile(source=yara_rules_string)\n\n except yara.Error as exception:\n raise errors.BadConfigObject(\n 'Unable to parse Yara rules in: {0:s} with error: {1!s}'.format(\n path, exception))\n\n setattr(configuration_object, '_yara_rules_string', yara_rules_string)", "docstring": "Parses and validates options.\n\nArgs:\n options (argparse.Namespace): parser options.\n configuration_object (CLITool): object to be configured by the argument\n helper.\n\nRaises:\n BadConfigObject: when the configuration object is of the wrong type.", "source": "juraj_google_style"} +{"code": "def _einsum_equation(input_shapes, output_shape):\n\n ret = []\n next_letter = ord(\"a\")\n dim_to_letter = {}\n for shape_num, shape in enumerate(input_shapes + [output_shape]):\n if shape_num == len(input_shapes):\n ret.append(\"->\")\n elif shape_num > 0:\n ret.append(\",\")\n for d in shape.dims:\n if d not in dim_to_letter:\n dim_to_letter[d] = chr(next_letter)\n next_letter += 1\n ret.append(dim_to_letter[d])\n\n return \"\".join(ret)", "docstring": "Turn shapes into an einsum equation.\n\n e.g. \"ij,jk->ik\"\n\nArgs:\n input_shapes: a list of Shapes\n output_shape: a Shape\n\nReturns:\n a string", "source": "juraj_google_style"} +{"code": "def dmail_list(self, message_matches=None, to_name=None, to_id=None,\n from_name=None, from_id=None, read=None):\n\n params = {\n 'search[message_matches]': message_matches,\n 'search[to_name]': to_name,\n 'search[to_id]': to_id,\n 'search[from_name]': from_name,\n 'search[from_id]': from_id,\n 'search[read]': read\n }\n return self._get('dmails.json', params, auth=True)", "docstring": "Return list of Dmails. You can only view dmails you own\n (Requires login).\n\n Parameters:\n message_matches (str): The message body contains the given terms.\n to_name (str): The recipient's name.\n to_id (int): The recipient's user id.\n from_name (str): The sender's name.\n from_id (int): The sender's user id.\n read (bool): Can be: true, false.", "source": "juraj_google_style"} +{"code": "def process_actions(self, actions):\n\n notices = {}\n notification_contacts = {}\n for action in actions:\n resource = action['resource']\n action_status = ActionStatus.SUCCEED\n\n try:\n if action['action'] == AuditActions.REMOVE:\n action_status = self.process_action(\n resource,\n AuditActions.REMOVE\n )\n if action_status == ActionStatus.SUCCEED:\n db.session.delete(action['issue'].issue)\n\n elif action['action'] == AuditActions.STOP:\n action_status = self.process_action(\n resource,\n AuditActions.STOP\n )\n if action_status == ActionStatus.SUCCEED:\n action['issue'].update({\n 'missing_tags': action['missing_tags'],\n 'notes': action['notes'],\n 'last_alert': action['last_alert'],\n 'state': action['action']\n })\n\n elif action['action'] == AuditActions.FIXED:\n db.session.delete(action['issue'].issue)\n\n elif action['action'] == AuditActions.ALERT:\n action['issue'].update({\n 'missing_tags': action['missing_tags'],\n 'notes': action['notes'],\n 'last_alert': action['last_alert'],\n 'state': action['action']\n })\n\n db.session.commit()\n\n if action_status == ActionStatus.SUCCEED:\n for owner in [\n dict(t) for t in {tuple(d.items()) for d in (action['owners'] + self.permanent_emails)}\n ]:\n if owner['value'] not in notification_contacts:\n contact = NotificationContact(type=owner['type'], value=owner['value'])\n notification_contacts[owner['value']] = contact\n notices[contact] = {\n 'fixed': [],\n 'not_fixed': []\n }\n else:\n contact = notification_contacts[owner['value']]\n\n if action['action'] == AuditActions.FIXED:\n notices[contact]['fixed'].append(action)\n else:\n notices[contact]['not_fixed'].append(action)\n except Exception as ex:\n self.log.exception('Unexpected error while processing resource {}/{}/{}/{}'.format(\n action['resource'].account.account_name,\n action['resource'].id,\n action['resource'],\n ex\n ))\n\n return notices", "docstring": "Process the actions we want to take\n\nArgs:\n actions (`list`): List of actions we want to take\n\nReturns:\n `list` of notifications", "source": "juraj_google_style"} +{"code": "def _build_udf(name, code, return_type, params, language, imports):\n\n\n params = ','.join(['%s %s' % named_param for named_param in params])\n imports = ','.join(['library=\"%s\"' % i for i in imports])\n\n if language.lower() == 'sql':\n udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\\n' + \\\n 'RETURNS {return_type}\\n' + \\\n 'AS (\\n' + \\\n '{code}\\n' + \\\n ');'\n else:\n udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\\n' +\\\n 'RETURNS {return_type}\\n' + \\\n 'LANGUAGE {language}\\n' + \\\n 'AS \\n' +\\\n 'OPTIONS (\\n' +\\\n '{imports}\\n' +\\\n ');'\n return udf.format(name=name, params=params, return_type=return_type,\n language=language, code=code, imports=imports)", "docstring": "Creates the UDF part of a BigQuery query using its pieces\n\nArgs:\n name: the name of the javascript function\n code: function body implementing the logic.\n return_type: BigQuery data type of the function return. See supported data types in\n the BigQuery docs\n params: dictionary of parameter names and types\n language: see list of supported languages in the BigQuery docs\n imports: a list of GCS paths containing further support code.", "source": "juraj_google_style"} +{"code": "def __trim_grave_accent(self, href):\n\n\n if href.startswith(\"`\"):\n href = href[1:]\n\n if href.endswith(\"`\"):\n href = href[:-1]\n\n return href", "docstring": "Trim grave accents manually (because BeautifulSoup doesn\"t support it).\n\nArgs:\n href (str): The BeautifulSoup href value.\n\nReturns:\n str: The BeautifulSoup href value without grave accents.", "source": "juraj_google_style"} +{"code": "def _sparse_or_dense_matmul_onehot(sparse_or_dense_matrix, col_index):\n\n if isinstance(sparse_or_dense_matrix,\n (tf.SparseTensor, tf.compat.v1.SparseTensorValue)):\n # TODO(b/111924846): Implement better (ideally in a way that allows us to\n # eliminate the `num_rows` arg, if possible).\n num_rows = _get_shape(sparse_or_dense_matrix)[-2]\n batch_shape = _get_shape(sparse_or_dense_matrix)[:-2]\n slice_start = tf.concat([tf.zeros_like(batch_shape), [0, col_index]],\n axis=0)\n slice_size = tf.concat([batch_shape, [num_rows, 1]], axis=0)\n # We momentarily lose static shape information in tf.sparse_slice. However\n # we regain it in the following tf.reshape.\n sparse_slice = tf.sparse.slice(sparse_or_dense_matrix,\n tf.cast(slice_start, tf.int64),\n tf.cast(slice_size, tf.int64))\n\n output_shape = tf.concat([batch_shape, [num_rows]], axis=0)\n return tf.reshape(tf.sparse.to_dense(sparse_slice), output_shape)\n else:\n return tf.gather(sparse_or_dense_matrix, col_index, axis=-1)", "docstring": "Returns a (dense) column of a Tensor or SparseTensor.\n\nArgs:\n sparse_or_dense_matrix: matrix-shaped, `float` `Tensor` or `SparseTensor`.\n col_index: scalar, `int` `Tensor` representing the index of the desired\n column.\n\nReturns:\n column: vector-shaped, `float` `Tensor` with the same dtype as\n `sparse_or_dense_matrix`, representing the `col_index`th column of\n `sparse_or_dense_matrix`.", "source": "juraj_google_style"} +{"code": "def _init_boto3_clients(self, profile, region):\n\n try:\n session = None\n if profile and region:\n session = boto3.session.Session(profile_name=profile, region_name=region)\n elif profile:\n session = boto3.session.Session(profile_name=profile)\n elif region:\n session = boto3.session.Session(region_name=region)\n else:\n session = boto3.session.Session()\n\n self._cloud_formation = session.client('cloudformation')\n return True\n except Exception as wtf:\n logging.error(wtf, exc_info=True)\n return False", "docstring": "The utililty requires boto3 clients to CloudFormation.\n\nArgs:\n None\n\nReturns:\n Good or Bad; True or False", "source": "juraj_google_style"} +{"code": "def VerifyGitkitToken(self, jwt):\n\n certs = self.rpc_helper.GetPublicCert()\n crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 # 30 days\n parsed = None\n for aud in filter(lambda x: x is not None, [self.project_id, self.client_id]):\n try:\n parsed = crypt.verify_signed_jwt_with_certs(jwt, certs, aud)\n except crypt.AppIdentityError as e:\n if \"Wrong recipient\" not in e.message:\n return None\n if parsed:\n return GitkitUser.FromToken(parsed)\n return None", "docstring": "Verifies a Gitkit token string.\n\nArgs:\n jwt: string, the token to be checked\n\nReturns:\n GitkitUser, if the token is valid. None otherwise.", "source": "juraj_google_style"} +{"code": "def get(self, url, headers=None, parameters=None, get_json=True):\n\n\n if self.debug:\n print(\"GET: %s, headers=%s\" % (url, headers))\n\n self.headers = self._get_default_headers()\n get_parameters = self.parameters\n if get_parameters is None:\n # In case self.parameters is still empty\n get_parameters = {}\n if headers is not None:\n self.headers.update(headers)\n if parameters is not None:\n get_parameters.update(parameters)\n\n response = requests.get(url, headers=self.headers, params=get_parameters, auth=self.auth, verify=self.verify_ssl)\n json_response = self._process_json_response(response)\n\n return json_response if get_json is True else response", "docstring": "Send a GET request with custome headers and parameters\n\nArgs:\n url (str): URL to send the request to\n headers (str, optional): custom headers\n parameters (str, optional): optional parameters\n\nReturns:\n A JSON object of the returned response if `get_json` is True,\n Requests' response object otherwise", "source": "juraj_google_style"} +{"code": "def calculate_sun_from_hoy(self, hoy, is_solar_time=False):\n\n datetime = DateTime.from_hoy(hoy, self.is_leap_year)\n return self.calculate_sun_from_date_time(datetime, is_solar_time)", "docstring": "Get Sun data for an hour of the year.\n\nArgs:\n datetime: Ladybug datetime\n is_solar_time: A boolean to indicate if the input hour is solar time\n (Default: False).\n\nReturns:\n A sun object for this particular time", "source": "juraj_google_style"} +{"code": "def export_model(model_path):\n\n estimator = tf.estimator.Estimator(model_fn, model_dir=FLAGS.work_dir,\n params=FLAGS.flag_values_dict())\n latest_checkpoint = estimator.latest_checkpoint()\n all_checkpoint_files = tf.gfile.Glob(latest_checkpoint + '*')\n for filename in all_checkpoint_files:\n suffix = filename.partition(latest_checkpoint)[2]\n destination_path = model_path + suffix\n print(\"Copying {} to {}\".format(filename, destination_path))\n tf.gfile.Copy(filename, destination_path)", "docstring": "Take the latest checkpoint and copy it to model_path.\n\n Assumes that all relevant model files are prefixed by the same name.\n (For example, foo.index, foo.meta and foo.data-00000-of-00001).\n\nArgs:\n model_path: The path (can be a gs:// path) to export model", "source": "juraj_google_style"} +{"code": "def __rmtree(path):\n\n logger.info(\"rmtree: %s\" % path)\n try:\n shutil.rmtree(path)\n return True\n except Exception as e:\n logger.error(\"rmtree: %s failed! Error: %s\" % (path, e))\n return False", "docstring": "Recursively delete a directory tree.\n\nArgs:\n path (str): Path to the directory that needs to be deleted.\n\nReturns:\n bool: True if the operation is successful, False otherwise.", "source": "juraj_google_style"} +{"code": "def add_entry(self, path_object):\n\n if (not is_root() and not self.st_mode & PERM_WRITE and\n not self.filesystem.is_windows_fs):\n exception = IOError if IS_PY2 else OSError\n raise exception(errno.EACCES, 'Permission Denied', self.path)\n\n if path_object.name in self.contents:\n self.filesystem.raise_os_error(errno.EEXIST, self.path)\n\n self.contents[path_object.name] = path_object\n path_object.parent_dir = self\n self.st_nlink += 1\n path_object.st_nlink += 1\n path_object.st_dev = self.st_dev\n if path_object.st_nlink == 1:\n self.filesystem.change_disk_usage(\n path_object.size, path_object.name, self.st_dev)", "docstring": "Adds a child FakeFile to this directory.\n\nArgs:\n path_object: FakeFile instance to add as a child of this directory.\n\nRaises:\n OSError: if the directory has no write permission (Posix only)\n OSError: if the file or directory to be added already exists", "source": "juraj_google_style"} +{"code": "def calc_digest(origin, algorithm=\"sha1\", block_size=None):\n\n try:\n hashM = hashlib.new(algorithm)\n except ValueError:\n raise ValueError('hash algorithm not supported by the underlying platform: \"{0}\"'.format(algorithm))\n\n while True:\n chunk = origin.read(block_size) if block_size else origin.read()\n if not chunk:\n break\n hashM.update(chunk)\n return hashM.hexdigest()", "docstring": "Calculate digest of a readable object\n\nArgs:\n origin -- a readable object for which calculate digest\n algorithn -- the algorithm to use. See ``hashlib.algorithms_available`` for supported algorithms.\n block_size -- the size of the block to read at each iteration", "source": "juraj_google_style"} +{"code": "def signature(array):\n\n length = len(array)\n index = _NUM_SIGNATURE_BYTES if length > _NUM_SIGNATURE_BYTES else length\n\n return array[:index]", "docstring": "Returns the first 262 bytes of the given bytearray\n as part of the file header signature.\n\nArgs:\n array: bytearray to extract the header signature.\n\nReturns:\n First 262 bytes of the file content as bytearray type.", "source": "juraj_google_style"} +{"code": "def _handle_singular(cls, enterprise_customer, manage_learners_form):\n\n form_field_value = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.EMAIL_OR_USERNAME]\n email = email_or_username__to__email(form_field_value)\n try:\n validate_email_to_link(email, form_field_value, ValidationMessages.INVALID_EMAIL_OR_USERNAME, True)\n except ValidationError as exc:\n manage_learners_form.add_error(ManageLearnersForm.Fields.EMAIL_OR_USERNAME, exc)\n else:\n EnterpriseCustomerUser.objects.link_user(enterprise_customer, email)\n return [email]", "docstring": "Link single user by email or username.\n\nArgs:\n enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance\n manage_learners_form (ManageLearnersForm): bound ManageLearners form instance", "source": "juraj_google_style"} +{"code": "def _on_connection_finished(self, result):\n\n\n success, retval, context = self._parse_return(result)\n conn_id = context['connection_id']\n callback = context['callback']\n\n if success is False:\n callback(conn_id, self.id, False, 'Timeout opening connection')\n\n with self.count_lock:\n self.connecting_count -= 1\n return\n\n handle = retval['handle']\n context['disconnect_handler'] = self._on_connection_failed\n context['connect_time'] = time.time()\n context['state'] = 'preparing'\n self._connections[handle] = context\n\n self.probe_services(handle, conn_id, self._probe_services_finished)", "docstring": "Callback when the connection attempt to a BLE device has finished\n\n This function if called when a new connection is successfully completed\n\nArgs:\n event (BGAPIPacket): Connection event", "source": "juraj_google_style"} +{"code": "def rgb_to_greyscale(r, g=None, b=None):\n\n if type(r) in [list,tuple]:\n r, g, b = r\n v = (r + g + b) / 3.0\n return (v, v, v)", "docstring": "Convert the color from RGB to its greyscale equivalent\n\n Parameters:\n :r:\n The Red component value [0...1]\n :g:\n The Green component value [0...1]\n :b:\n The Blue component value [0...1]\n\nReturns:\n The color as an (r, g, b) tuple in the range:\n the range:\n r[0...1],\n g[0...1],\n b[0...1]\n\n >>> '(%g, %g, %g)' % rgb_to_greyscale(1, 0.8, 0)\n '(0.6, 0.6, 0.6)'", "source": "juraj_google_style"} +{"code": "def mac_app_exists(app):\n\n\n\tAPP_CHECK_APPLESCRIPT = \n\n\twith open('/tmp/app_check.AppleScript', 'w') as f:\n\t\tf.write(APP_CHECK_APPLESCRIPT % app)\n\n\tapp_check_proc = sp.Popen(\n\t\t['osascript', '-e', '/tmp/app_check.AppleScript'])\n\n\tif app_check_proc.wait() != 0:\n\t\treturn False\n\n\telse:\n\t\treturn True", "docstring": "Check if 'app' is installed (OS X).\n\n Check if the given applications is installed on this OS X system.\n\nArgs:\n app (str): The application name.\n\nReturns:\n bool: Is the app installed or not?", "source": "juraj_google_style"} +{"code": "def delete(self, *names: str, pipeline=False):\n\n if pipeline:\n self._pipeline.delete(*names)\n else:\n self._db.delete(*names)", "docstring": "Delete one or more keys specified by names.\n\nArgs:\n names (str): Names of keys to delete\n pipeline (bool): True, start a transaction block. Default false.", "source": "juraj_google_style"} +{"code": "def _xysxy2(date):\n\n\n planets = _planets(date)\n x_tab, y_tab, s_tab = _tab('X'), _tab('Y'), _tab('s')\n\n ttt = date.change_scale('TT').julian_century\n\n # Units: micro-arcsecond\n X = -16616.99 + 2004191742.88 * ttt - 427219.05 * ttt ** 2 - 198620.54 * ttt ** 3\\\n - 46.05 * ttt ** 4 + 5.98 * ttt ** 5\n\n Y = -6950.78 - 25381.99 * ttt - 22407250.99 * ttt ** 2 + 1842.28 * ttt ** 3\\\n + 1113.06 * ttt ** 4 + 0.99 * ttt ** 5\n\n s_xy2 = 94.0 + 3808.65 * ttt - 122.68 * ttt ** 2 - 72574.11 * ttt ** 3\\\n + 27.98 * ttt ** 4 + 15.62 * ttt ** 5\n\n for j in range(5):\n\n _x, _y, _s = 0, 0, 0\n for i in range(len(x_tab[j])):\n Axs, Axc, *p_coefs = x_tab[j][i]\n ax_p = np.dot(p_coefs, planets)\n _x += Axs * np.sin(ax_p) + Axc * np.cos(ax_p)\n\n for i in range(len(y_tab[j])):\n Ays, Ayc, *p_coefs = y_tab[j][i]\n ay_p = np.dot(p_coefs, planets)\n _y += Ays * np.sin(ay_p) + Ayc * np.cos(ay_p)\n\n for i in range(len(s_tab[j])):\n Ass, Asc, *p_coefs = s_tab[j][i]\n as_p = np.dot(p_coefs, planets)\n _s += Ass * np.sin(as_p) + Asc * np.cos(as_p)\n\n X += _x * ttt ** j\n Y += _y * ttt ** j\n s_xy2 += _s * ttt ** j\n\n # Conversion to arcsecond\n return X * 1e-6, Y * 1e-6, s_xy2 * 1e-6", "docstring": "Here we deviate from what has been done everywhere else. Instead of taking the formulas\n available in the Vallado, we take those described in the files tab5.2{a,b,d}.txt.\n\n The result should be equivalent, but they are the last iteration of the IAU2000A as of June 2016\n\nArgs:\n date (Date)\n\nReturns:\n 3-tuple of float: Values of X, Y, s + XY/2 in arcsecond", "source": "juraj_google_style"} +{"code": "def sg_restore(sess, save_path, category=''):\n r\n # to list\n if not isinstance(category, (tuple, list)):\n category = [category]\n\n # make variable list to load\n var_list = {}\n for cat in category:\n for t in tf.global_variables():\n if t.name.startswith(cat):\n var_list[t.name[:-2]] = t\n\n # restore parameters\n saver = tf.train.Saver(var_list)\n saver.restore(sess, save_path)", "docstring": "r\"\"\" Restores previously saved variables.\n\nArgs:\n sess: A `Session` to use to restore the parameters.\n save_path: Path where parameters were previously saved.\n category: A `String` to filter variables starts with given category.\n\n Returns:", "source": "juraj_google_style"} +{"code": "def get_fastq_dxfile_objects(self,barcode=None):\n\n fq_ext_glob = \"*{}\".format(self.FQEXT)\n name = fq_ext_glob\n if barcode:\n name = \"*_{barcode}_*{FQEXT}\".format(barcode=barcode, FQEXT=self.FQEXT)\n fastqs= dxpy.find_data_objects(project=self.dx_project_id,folder=self.DX_FASTQ_FOLDER,name=name,name_mode=\"glob\")\n if not fastqs:\n # Then look for them in all folders:\n fastqs= dxpy.find_data_objects(project=self.dx_project_id,name=name,name_mode=\"glob\")\n\n if not fastqs:\n msg = \"No FASTQ files found for run {run} \".format(run=proj_name)\n if barcode:\n msg += \"and barcode {barcode}.\".format(barcode=barcode)\n raise FastqNotFound(msg)\n fastqs = [dxpy.DXFile(project=x[\"project\"],dxid=x[\"id\"]) for x in fastqs]\n return fastqs", "docstring": "Retrieves all the FASTQ files in project self.dx_project_name as DXFile objects.\n\nArgs:\n barcode: `str`. If set, then only FASTQ file properties for FASTQ files having the specified barcode are returned.\n\nReturns:\n `list` of DXFile objects representing FASTQ files.\n\nRaises:\n `dnanexus_utils.FastqNotFound`: No FASTQ files were found.", "source": "juraj_google_style"} +{"code": "def chmod_r(root: str, permission: int) -> None:\n\n os.chmod(root, permission)\n for dirpath, dirnames, filenames in os.walk(root):\n for d in dirnames:\n os.chmod(os.path.join(dirpath, d), permission)\n for f in filenames:\n os.chmod(os.path.join(dirpath, f), permission)", "docstring": "Recursive ``chmod``.\n\nArgs:\n root: directory to walk down\n permission: e.g. ``e.g. stat.S_IWUSR``", "source": "juraj_google_style"} +{"code": "def _load_image_set_index(self, shuffle):\n\n assert os.path.exists(self.list_file), 'Path does not exists: {}'.format(self.list_file)\n with open(self.list_file, 'r') as f:\n image_set_index = [x.strip() for x in f.readlines()]\n if shuffle:\n np.random.shuffle(image_set_index)\n return image_set_index", "docstring": "find out which indexes correspond to given image set (train or val)\n\n Parameters:\n ----------\n shuffle : boolean\n whether to shuffle the image list\n\nReturns:\n ----------\n entire list of images specified in the setting", "source": "juraj_google_style"} +{"code": "def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids,\n platform_restrictions=None):\n\n campaign_extension_setting_service = client.GetService(\n 'CampaignExtensionSettingService', 'v201809')\n\n extension_feed_items = [{\n CreateSitelinkFeedItem(feed_items, feed_item_id)\n } for feed_item_id in feed_item_ids]\n\n extension_setting = {\n 'extensions': extension_feed_items\n }\n\n if platform_restrictions:\n extension_setting['platformRestrictions'] = platform_restrictions\n\n campaign_extension_setting = {\n 'campaignId': campaign_feed['campaignId'],\n 'extensionType': 'SITELINK',\n 'extensionSetting': extension_setting\n }\n\n operation = {\n 'operand': campaign_extension_setting,\n 'operator': 'ADD'\n }\n\n campaign_extension_setting_service.mutate([operation])", "docstring": "Creates the extension setting for a list of Feed Items.\n\nArgs:\n client: an AdWordsClient instance.\n feed_items: the list of all Feed Items.\n campaign_feed: the original Campaign Feed.\n feed_item_ids: the Ids of the feed items for which extension settings should\n be created.\n platform_restrictions: an optional Platform Restriction for the Feed items.", "source": "juraj_google_style"} +{"code": "def cache():\n\n is_conditional = request.headers.get(\"If-Modified-Since\") or request.headers.get(\n \"If-None-Match\"\n )\n\n if is_conditional is None:\n response = view_get()\n response.headers[\"Last-Modified\"] = http_date()\n response.headers[\"ETag\"] = uuid.uuid4().hex\n return response\n else:\n return status_code(304)", "docstring": "Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise.\n ---\n tags:\n - Response inspection\n parameters:\n - in: header\n name: If-Modified-Since\n - in: header\n name: If-None-Match\n produces:\n - application/json\n responses:\n 200:\n description: Cached response\n 304:\n description: Modified", "source": "juraj_google_style"} +{"code": "def ExtractEvents(self, parser_mediator, registry_key, **kwargs):\n\n for subkey in registry_key.GetSubkeys():\n values_dict = {}\n values_dict['subkey_name'] = subkey.name\n\n name_values = subkey.name.split('&')\n number_of_name_values = len(name_values)\n\n # Normally we expect 4 fields here however that is not always the case.\n if number_of_name_values != 4:\n logger.warning(\n 'Expected 4 &-separated values in: {0:s}'.format(subkey.name))\n\n if number_of_name_values >= 1:\n values_dict['device_type'] = name_values[0]\n if number_of_name_values >= 2:\n values_dict['vendor'] = name_values[1]\n if number_of_name_values >= 3:\n values_dict['product'] = name_values[2]\n if number_of_name_values >= 4:\n values_dict['revision'] = name_values[3]\n\n event_data = windows_events.WindowsRegistryEventData()\n event_data.key_path = registry_key.path\n event_data.offset = registry_key.offset\n event_data.regvalue = values_dict\n event_data.source_append = self._SOURCE_APPEND\n\n if subkey.number_of_subkeys == 0:\n # Time last USB device of this class was first inserted.\n event = time_events.DateTimeValuesEvent(\n subkey.last_written_time, definitions.TIME_DESCRIPTION_WRITTEN)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n continue\n\n for device_key in subkey.GetSubkeys():\n values_dict['serial'] = device_key.name\n\n friendly_name_value = device_key.GetValueByName('FriendlyName')\n if friendly_name_value:\n values_dict['friendly_name'] = friendly_name_value.GetDataAsObject()\n else:\n values_dict.pop('friendly_name', None)\n\n # ParentIdPrefix applies to Windows XP Only.\n parent_id_prefix_value = device_key.GetValueByName('ParentIdPrefix')\n if parent_id_prefix_value:\n values_dict['parent_id_prefix'] = (\n parent_id_prefix_value.GetDataAsObject())\n else:\n values_dict.pop('parent_id_prefix', None)\n\n # Time last USB device of this class was first inserted.\n event = time_events.DateTimeValuesEvent(\n subkey.last_written_time, definitions.TIME_DESCRIPTION_WRITTEN)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n # Win7 - Last Connection.\n # Vista/XP - Time of an insert.\n event = time_events.DateTimeValuesEvent(\n device_key.last_written_time, definitions.TIME_DESCRIPTION_WRITTEN)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n device_parameter_key = device_key.GetSubkeyByName('Device Parameters')\n if device_parameter_key:\n event = time_events.DateTimeValuesEvent(\n device_parameter_key.last_written_time,\n definitions.TIME_DESCRIPTION_WRITTEN)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n log_configuration_key = device_key.GetSubkeyByName('LogConf')\n if log_configuration_key:\n event = time_events.DateTimeValuesEvent(\n log_configuration_key.last_written_time,\n definitions.TIME_DESCRIPTION_WRITTEN)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n properties_key = device_key.GetSubkeyByName('Properties')\n if properties_key:\n event = time_events.DateTimeValuesEvent(\n properties_key.last_written_time,\n definitions.TIME_DESCRIPTION_WRITTEN)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Extracts events from a Windows Registry key.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n registry_key (dfwinreg.WinRegistryKey): Windows Registry key.", "source": "juraj_google_style"} +{"code": "def call_servo(examples, serving_bundle):\n\n parsed_url = urlparse('http://' + serving_bundle.inference_address)\n channel = implementations.insecure_channel(parsed_url.hostname,\n parsed_url.port)\n stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)\n\n if serving_bundle.use_predict:\n request = predict_pb2.PredictRequest()\n elif serving_bundle.model_type == 'classification':\n request = classification_pb2.ClassificationRequest()\n else:\n request = regression_pb2.RegressionRequest()\n request.model_spec.name = serving_bundle.model_name\n if serving_bundle.model_version is not None:\n request.model_spec.version.value = serving_bundle.model_version\n if serving_bundle.signature is not None:\n request.model_spec.signature_name = serving_bundle.signature\n\n if serving_bundle.use_predict:\n # tf.compat.v1 API used here to convert tf.example into proto. This\n # utility file is bundled in the witwidget pip package which has a dep\n # on TensorFlow.\n request.inputs[serving_bundle.predict_input_tensor].CopyFrom(\n tf.compat.v1.make_tensor_proto(\n values=[ex.SerializeToString() for ex in examples],\n dtype=types_pb2.DT_STRING))\n else:\n request.input.example_list.examples.extend(examples)\n\n if serving_bundle.use_predict:\n return common_utils.convert_predict_response(\n stub.Predict(request, 30.0), serving_bundle) # 30 secs timeout\n elif serving_bundle.model_type == 'classification':\n return stub.Classify(request, 30.0) # 30 secs timeout\n else:\n return stub.Regress(request, 30.0)", "docstring": "Send an RPC request to the Servomatic prediction service.\n\nArgs:\n examples: A list of examples that matches the model spec.\n serving_bundle: A `ServingBundle` object that contains the information to\n make the serving request.\n\nReturns:\n A ClassificationResponse or RegressionResponse proto.", "source": "juraj_google_style"} +{"code": "def __get_distribution_tags(self, client, arn):\n\n return {\n t['Key']: t['Value'] for t in client.list_tags_for_resource(\n Resource=arn\n )['Tags']['Items']\n }", "docstring": "Returns a dict containing the tags for a CloudFront distribution\n\nArgs:\n client (botocore.client.CloudFront): Boto3 CloudFront client object\n arn (str): ARN of the distribution to get tags for\n\nReturns:\n `dict`", "source": "juraj_google_style"} +{"code": "def _render_timestep(self,\n t: int,\n s: Fluents, a: Fluents, f: Fluents,\n r: np.float32) -> None:\n\n print(\"============================\")\n print(\"TIME = {}\".format(t))\n print(\"============================\")\n fluent_variables = self._compiler.rddl.action_fluent_variables\n self._render_fluent_timestep('action', a, fluent_variables)\n fluent_variables = self._compiler.rddl.interm_fluent_variables\n self._render_fluent_timestep('interms', f, fluent_variables)\n fluent_variables = self._compiler.rddl.state_fluent_variables\n self._render_fluent_timestep('states', s, fluent_variables)\n self._render_reward(r)", "docstring": "Prints fluents and rewards for the given timestep `t`.\n\nArgs:\n t (int): timestep\n s (Sequence[Tuple[str], np.array]: State fluents.\n a (Sequence[Tuple[str], np.array]: Action fluents.\n f (Sequence[Tuple[str], np.array]: Interm state fluents.\n r (np.float32): Reward.", "source": "juraj_google_style"} +{"code": "def sed(regexpr, repl, force=False, recursive=False, dpath_list=None,\n fpath_list=None, verbose=None, include_patterns=None,\n exclude_patterns=[]):\n\n #_grep(r, [repl], dpath_list=dpath_list, recursive=recursive)\n if include_patterns is None:\n include_patterns = ['*.py', '*.pyx', '*.pxi', '*.cxx', '*.cpp', '*.hxx', '*.hpp', '*.c', '*.h', '*.html', '*.tex']\n if dpath_list is None:\n dpath_list = [os.getcwd()]\n if verbose is None:\n verbose = ut.NOT_QUIET\n if fpath_list is None:\n greater_exclude_dirs = get_standard_exclude_dnames()\n exclude_dirs = []\n fpath_generator = matching_fpaths(\n dpath_list, include_patterns, exclude_dirs,\n greater_exclude_dirs=greater_exclude_dirs,\n recursive=recursive, exclude_patterns=exclude_patterns)\n else:\n fpath_generator = fpath_list\n if verbose:\n print('sed-ing %r' % (dpath_list,))\n print(' * regular expression : %r' % (regexpr,))\n print(' * replacement : %r' % (repl,))\n print(' * include_patterns : %r' % (include_patterns,))\n print(' * recursive: %r' % (recursive,))\n print(' * force: %r' % (force,))\n from utool import util_str\n print(' * fpath_list: %s' % (util_str.repr3(fpath_list),))\n regexpr = extend_regex(regexpr)\n #if '\\x08' in regexpr:\n # print('Remember \\\\x08 != \\\\b')\n # print('subsituting for you for you')\n # regexpr = regexpr.replace('\\x08', '\\\\b')\n # print(' * regular expression : %r' % (regexpr,))\n\n # Walk through each directory recursively\n num_changed = 0\n num_files_checked = 0\n fpaths_changed = []\n for fpath in fpath_generator:\n num_files_checked += 1\n changed_lines = sedfile(fpath, regexpr, repl, force, verbose=verbose)\n if changed_lines is not None:\n fpaths_changed.append(fpath)\n num_changed += len(changed_lines)\n import utool as ut\n print('num_files_checked = %r' % (num_files_checked,))\n print('fpaths_changed = %s' % (ut.repr3(sorted(fpaths_changed)),))\n print('total lines changed = %r' % (num_changed,))", "docstring": "Python implementation of sed. NOT FINISHED\n\n searches and replaces text in files\n\nArgs:\n regexpr (str): regx patterns to find\n repl (str): text to replace\n force (bool):\n recursive (bool):\n dpath_list (list): directories to search (defaults to cwd)", "source": "juraj_google_style"} +{"code": "def ProduceEventTag(self, event_tag):\n\n self._storage_writer.AddEventTag(event_tag)\n\n self.number_of_produced_event_tags += 1\n\n self.last_activity_timestamp = time.time()", "docstring": "Produces an event tag.\n\nArgs:\n event_tag (EventTag): event tag.", "source": "juraj_google_style"} +{"code": "def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0):\n\n\n batch_size = shape_list(mu)[0]\n prior_distribution = tfp.distributions.Normal(\n mu_p, tf.exp(tf.multiply(0.5, log_var_p)))\n posterior_distribution = tfp.distributions.Normal(\n mu, tf.exp(tf.multiply(0.5, log_var)))\n kld = tfp.distributions.kl_divergence(posterior_distribution,\n prior_distribution)\n return tf.reduce_sum(kld) / to_float(batch_size)", "docstring": "KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).\n\nArgs:\n mu: mu parameter of the distribution.\n log_var: log(var) parameter of the distribution.\n mu_p: optional mu from a learned prior distribution\n log_var_p: optional log(var) from a learned prior distribution\n\nReturns:\n the KL loss.", "source": "juraj_google_style"} +{"code": "def resolves_for(self, node):\n\n\n self.actual_title = normalize_text(node.title)\n return bool(self.search_regexp.search(self.actual_title))", "docstring": "Resolves this query relative to the given node.\n\nArgs:\n node (node.Document): The node to be evaluated.\n\nReturns:\n bool: Whether the given node matches this query.", "source": "juraj_google_style"} +{"code": "def bool(name, default=None, allow_none=False, fallback=None):\n\n value = read(name, default, allow_none, fallback=fallback)\n if isinstance(value, builtins.bool):\n return value\n elif isinstance(value, builtins.int):\n return True if value > 0 else False\n elif value is None and allow_none:\n return None\n else:\n value_str = builtins.str(value).lower().strip()\n return _strtobool(value_str)", "docstring": "Get a boolean based environment value or the default.\n\nArgs:\n name: The environment variable name\n default: The default value to use if no environment variable is found\n allow_none: If the return value can be `None` (i.e. optional)", "source": "juraj_google_style"} +{"code": "def summarize_mean_in_nats_and_bits(inputs, units, name,\n nats_name_scope=\"nats\",\n bits_name_scope=\"bits_per_dim\"):\n\n mean = tf.reduce_mean(input_tensor=inputs)\n with tf.compat.v1.name_scope(nats_name_scope):\n tf.compat.v2.summary.scalar(\n name,\n mean,\n step=tf.compat.v1.train.get_or_create_global_step())\n with tf.compat.v1.name_scope(bits_name_scope):\n tf.compat.v2.summary.scalar(\n name,\n mean / units / tf.math.log(2.),\n step=tf.compat.v1.train.get_or_create_global_step())", "docstring": "Summarize the mean of a tensor in nats and bits per unit.\n\nArgs:\n inputs: A tensor of values measured in nats.\n units: The units of the tensor with which to compute the mean bits\n per unit.\n name: The name of the tensor.\n nats_name_scope: The name scope of the nats summary.\n bits_name_scope: The name scope of the bits summary.", "source": "juraj_google_style"} +{"code": "def jaccard(self, other):\n\n if other.seed != self.seed:\n raise ValueError(\"Cannot compute Jaccard given WeightedMinHash objects with\\\n different seeds\")\n if len(self) != len(other):\n raise ValueError(\"Cannot compute Jaccard given WeightedMinHash objects with\\\n different numbers of hash values\")\n # Check how many pairs of (k, t) hashvalues are equal\n intersection = 0\n for this, that in zip(self.hashvalues, other.hashvalues):\n if np.array_equal(this, that):\n intersection += 1\n return float(intersection) / float(len(self))", "docstring": "Estimate the `weighted Jaccard similarity`_ between the\n multi-sets represented by this weighted MinHash and the other.\n\nArgs:\n other (datasketch.WeightedMinHash): The other weighted MinHash.\n\nReturns:\n float: The weighted Jaccard similarity between 0.0 and 1.0.\n\n .. _`weighted Jaccard similarity`: http://mathoverflow.net/questions/123339/weighted-jaccard-similarity", "source": "juraj_google_style"} +{"code": "def WriteArtifactsFile(self, artifacts, filename):\n\n with open(filename, 'w') as file_object:\n file_object.write(self.FormatArtifacts(artifacts))", "docstring": "Writes artifact definitions to a file.\n\nArgs:\n artifacts (list[ArtifactDefinition]): artifact definitions to be written.\n filename (str): name of the file to write artifacts to.", "source": "juraj_google_style"} +{"code": "def __call__(self, environ, start_response):\n\n path = environ['PATH_INFO'] or '/'\n for p, app in self.apps:\n # The apps list should be sorted by length, descending.\n if path.startswith(p + '/') or path == p:\n environ = environ.copy()\n environ['SCRIPT_NAME'] = environ.get('SCRIPT_NAME', '') + p\n environ['PATH_INFO'] = path[len(p):]\n return app(environ, start_response)\n\n start_response(\n '404 Not Found', [\n ('Content-Type', 'text/plain'),\n ('Content-Length', '0'),\n ],\n )\n return ['']", "docstring": "Process incoming WSGI request.\n\n Ref: :pep:`3333`\n\nArgs:\n environ (Mapping): a dict containing WSGI environment variables\n start_response (callable): function, which sets response\n status and headers\n\nReturns:\n list[bytes]: iterable containing bytes to be returned in\n HTTP response body", "source": "juraj_google_style"} +{"code": "def data(item=None, show_doc=False):\n\n\n if item:\n try:\n if show_doc:\n __print_item_docs(item)\n return\n\n df = __read_csv(item)\n return df\n except KeyError:\n find_similar(item)\n else:\n return __datasets_desc()", "docstring": "loads a datasaet (from in-modules datasets) in a dataframe data structure.\n\nArgs:\n item (str) : name of the dataset to load.\n show_doc (bool) : to show the dataset's documentation.\n\nExample:\n >>> iris = data('iris')\n\n\n >>> data('titanic', show_doc=True)\n : returns the dataset's documentation.\n\n >>> data()\n : like help(), returns a dataframe [Item, Title]\n for a list of the available datasets.", "source": "juraj_google_style"} +{"code": "def launch(self, task, **kwargs):\n\n if task.status == task.S_LOCKED:\n raise ValueError(\"You shall not submit a locked task!\")\n\n # Build the task\n task.build()\n\n # Pass information on the time limit to Abinit (we always assume ndtset == 1)\n if isinstance(task, AbinitTask):\n args = kwargs.get(\"exec_args\", [])\n if args is None: args = []\n args = args[:]\n args.append(\"--timelimit %s\" % qu.time2slurm(self.qadapter.timelimit))\n kwargs[\"exec_args\"] = args\n\n # Write the submission script\n script_file = self.write_jobfile(task, **kwargs)\n\n # Submit the task and save the queue id.\n try:\n qjob, process = self.qadapter.submit_to_queue(script_file)\n task.set_status(task.S_SUB, msg='Submitted to queue')\n task.set_qjob(qjob)\n return process\n\n except self.qadapter.MaxNumLaunchesError as exc:\n # TODO: Here we should try to switch to another qadapter\n # 1) Find a new parallel configuration in those stored in task.pconfs\n # 2) Change the input file.\n # 3) Regenerate the submission script\n # 4) Relaunch\n task.set_status(task.S_ERROR, msg=\"max_num_launches reached: %s\" % str(exc))\n raise", "docstring": "Build the input files and submit the task via the :class:`Qadapter`\n\nArgs:\n task: :class:`TaskObject`\n\nReturns:\n Process object.", "source": "juraj_google_style"} +{"code": "def anim(host, seq, anim, d):\n\n at(host, 'ANIM', seq, [anim, d])", "docstring": "Makes the drone execute a predefined movement (animation).\n\n Parameters:\n seq -- sequcence number\n anim -- Integer: animation to play\n d -- Integer: total duration in seconds of the animation", "source": "juraj_google_style"} +{"code": "def parse_hgnc_genes(lines):\n\n header = []\n logger.info(\"Parsing hgnc genes...\")\n for index, line in enumerate(lines):\n if index == 0:\n header = line.split('\\t')\n elif len(line) > 1:\n hgnc_gene = parse_hgnc_line(line=line, header=header)\n if hgnc_gene:\n yield hgnc_gene", "docstring": "Parse lines with hgnc formated genes\n\n This is designed to take a dump with genes from HGNC.\n This is downloaded from:\n ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt\n\nArgs:\n lines(iterable(str)): An iterable with HGNC formated genes\n\nYields:\n hgnc_gene(dict): A dictionary with the relevant information", "source": "juraj_google_style"} +{"code": "def _RegisterDebuggee(self, service):\n\n try:\n request = {'debuggee': self._GetDebuggee()}\n\n try:\n response = service.debuggees().register(body=request).execute()\n\n # self._project_number will refer to the project id on initialization if\n # the project number is not available. The project field in the debuggee\n # will always refer to the project number. Update so the server will not\n # have to do id->number translations in the future.\n project_number = response['debuggee'].get('project')\n self._project_number = project_number or self._project_number\n\n self._debuggee_id = response['debuggee']['id']\n native.LogInfo('Debuggee registered successfully, ID: %s' % (\n self._debuggee_id))\n self.register_backoff.Succeeded()\n return (False, 0) # Proceed immediately to list active breakpoints.\n except BaseException:\n native.LogInfo('Failed to register debuggee: %s, %s' %\n (request, traceback.format_exc()))\n except BaseException:\n native.LogWarning('Debuggee information not available: ' +\n traceback.format_exc())\n\n return (True, self.register_backoff.Failed())", "docstring": "Single attempt to register the debuggee.\n\n If the registration succeeds, sets self._debuggee_id to the registered\n debuggee ID.\n\nArgs:\n service: client to use for API calls\n\nReturns:\n (registration_required, delay) tuple", "source": "juraj_google_style"} +{"code": "def _do_pass(self, pass_, dag, options):\n\n\n # First, do the requires of pass_\n if not options[\"ignore_requires\"]:\n for required_pass in pass_.requires:\n dag = self._do_pass(required_pass, dag, options)\n\n # Run the pass itself, if not already run\n if pass_ not in self.valid_passes:\n if pass_.is_transformation_pass:\n pass_.property_set = self.fenced_property_set\n new_dag = pass_.run(dag)\n if not isinstance(new_dag, DAGCircuit):\n raise TranspilerError(\"Transformation passes should return a transformed dag.\"\n \"The pass %s is returning a %s\" % (type(pass_).__name__,\n type(new_dag)))\n dag = new_dag\n elif pass_.is_analysis_pass:\n pass_.property_set = self.property_set\n pass_.run(FencedDAGCircuit(dag))\n else:\n raise TranspilerError(\"I dont know how to handle this type of pass\")\n\n # update the valid_passes property\n self._update_valid_passes(pass_, options['ignore_preserves'])\n\n return dag", "docstring": "Do a pass and its \"requires\".\n\nArgs:\n pass_ (BasePass): Pass to do.\n dag (DAGCircuit): The dag on which the pass is ran.\n options (dict): PassManager options.\n\nReturns:\n DAGCircuit: The transformed dag in case of a transformation pass.\n The same input dag in case of an analysis pass.\n\nRaises:\n TranspilerError: If the pass is not a proper pass instance.", "source": "juraj_google_style"} +{"code": "def log_deprecated(name=\"\", text=\"\", eos=\"\"):\n\n assert name or text\n if eos:\n eos = \"after \" + datetime(*map(int, eos.split(\"-\"))).strftime(\"%d %b\")\n if name:\n if eos:\n warn_msg = \"%s will be deprecated %s. %s\" % (name, eos, text)\n else:\n warn_msg = \"%s was deprecated. %s\" % (name, text)\n else:\n warn_msg = text\n if eos:\n warn_msg += \" Legacy period ends %s\" % eos\n logger.warn(\"[Deprecated] \" + warn_msg)", "docstring": "Log deprecation warning.\n\nArgs:\n name (str): name of the deprecated item.\n text (str, optional): information about the deprecation.\n eos (str, optional): end of service date such as \"YYYY-MM-DD\".", "source": "juraj_google_style"} +{"code": "def _ParseCachedEntryXP(self, value_data, cached_entry_offset):\n\n try:\n cached_entry = self._ReadStructureFromByteStream(\n value_data[cached_entry_offset:], cached_entry_offset,\n self._cached_entry_data_type_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError(\n 'Unable to parse cached entry value with error: {0!s}'.format(\n exception))\n\n # TODO: have dtFabric handle string conversion.\n string_size = 0\n for string_index in range(0, 528, 2):\n if (cached_entry.path[string_index] == 0 and\n cached_entry.path[string_index + 1] == 0):\n break\n string_size += 2\n\n try:\n path = bytearray(cached_entry.path[0:string_size]).decode('utf-16-le')\n except UnicodeDecodeError:\n raise errors.ParseError('Unable to decode cached entry path to string')\n\n cached_entry_object = AppCompatCacheCachedEntry()\n cached_entry_object.cached_entry_size = (\n self._cached_entry_data_type_map.GetByteSize())\n cached_entry_object.file_size = cached_entry.file_size\n cached_entry_object.last_modification_time = (\n cached_entry.last_modification_time)\n cached_entry_object.last_update_time = cached_entry.last_update_time\n cached_entry_object.path = path\n\n return cached_entry_object", "docstring": "Parses a Windows XP cached entry.\n\nArgs:\n value_data (bytes): value data.\n cached_entry_offset (int): offset of the first cached entry data\n relative to the start of the value data.\n\nReturns:\n AppCompatCacheCachedEntry: cached entry.\n\nRaises:\n ParseError: if the value data could not be parsed.", "source": "juraj_google_style"} +{"code": "def install(package_name):\n\n holodeck_path = util.get_holodeck_path()\n binary_website = \"https://s3.amazonaws.com/holodeckworlds/\"\n\n if package_name not in packages:\n raise HolodeckException(\"Unknown package name \" + package_name)\n package_url = packages[package_name]\n\n print(\"Installing \" + package_name + \" at \" + holodeck_path)\n install_path = os.path.join(holodeck_path, \"worlds\")\n binary_url = binary_website + util.get_os_key() + \"_\" + package_url\n _download_binary(binary_url, install_path)\n if os.name == \"posix\":\n _make_binary_excecutable(package_name, install_path)", "docstring": "Installs a holodeck package.\n\nArgs:\n package_name (str): The name of the package to install", "source": "juraj_google_style"} +{"code": "def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None):\n\n egg_project_name = pkg_resources.to_filename(project_name)\n req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name)\n if subdir:\n req += '&subdirectory={}'.format(subdir)\n\n return req", "docstring": "Return the URL for a VCS requirement.\n\nArgs:\n repo_url: the remote VCS url, with any needed VCS prefix (e.g. \"git+\").\n project_name: the (unescaped) project name.", "source": "juraj_google_style"} +{"code": "def MakeTokenRegex(meta_left, meta_right):\n\n key = meta_left, meta_right\n if key not in _token_re_cache:\n # - Need () grouping for re.split\n # - The first character must be a non-space. This allows us to ignore\n # literals like function() { return 1; } when\n # - There must be at least one (non-space) character inside {}\n _token_re_cache[key] = re.compile(\n r'(' +\n re.escape(meta_left) +\n r'\\S.*?' +\n re.escape(meta_right) +\n r')')\n return _token_re_cache[key]", "docstring": "Return a (compiled) regular expression for tokenization.\n\nArgs:\n meta_left, meta_right: e.g. '{' and '}'\n\n - The regular expressions are memoized.\n - This function is public so the syntax highlighter can use it.", "source": "juraj_google_style"} +{"code": "def forum_topic_delete(self, topic_id):\n\n return self._get('forum_topics/{0}.json'.format(topic_id),\n method='DELETE', auth=True)", "docstring": "Delete a topic (Login Requires) (Moderator+) (UNTESTED).\n\n Parameters:\n topic_id (int): Where topic_id is the topic id.", "source": "juraj_google_style"} +{"code": "def has_entry(self, name):\n # type: (str) -> bool\n\n return getattr(self.dr_entries, name) or getattr(self.ce_entries, name)", "docstring": "An internal method to tell if we have already parsed an entry of the\n named type.\n\n Parameters:\n name - The name of the entry to check.\n\nReturns:\n True if we have already parsed an entry of the named type, False otherwise.", "source": "juraj_google_style"} +{"code": "def _ParseFile(self, file_obj, line_parser):\n\n lines = [\n l.strip() for l in utils.ReadFileBytesAsUnicode(file_obj).splitlines()\n ]\n try:\n for index, line in enumerate(lines):\n if line:\n line_parser(line)\n except (IndexError, KeyError) as e:\n raise parser.ParseError(\"Invalid file at line %d: %s\" % (index + 1, e))", "docstring": "Process a file line by line.\n\nArgs:\n file_obj: The file to parse.\n line_parser: The parser method used to process and store line content.\n\nRaises:\n parser.ParseError if the parser is unable to process the line.", "source": "juraj_google_style"} +{"code": "def receive(self,message_type):\n\n topic = None\n message = None\n if message_type == RAW:\n message = self._sock.recv(flags=zmq.NOBLOCK)\n elif message_type == PYOBJ:\n message = self._sock.recv_pyobj(flags=zmq.NOBLOCK)\n elif message_type == JSON:\n message = self._sock.recv_json(flags=zmq.NOBLOCK)\n elif message_type == MULTIPART:\n data = self._sock.recv_multipart(flags=zmq.NOBLOCK)\n message = data[1]\n topic = data[0]\n elif message_type == STRING:\n message = self._sock.recv_string(flags=zmq.NOBLOCK)\n elif message_type == UNICODE:\n message = self._sock.recv_unicode(flags=zmq.NOBLOCK)\n else:\n raise Exception(\"Unknown message type %s\"%(self._message_type,))\n\n return (topic, message)", "docstring": "Receive the message of the specified type and retun\n\nArgs:\n - message_type: the type of the message to receive\n\nReturns:\n - the topic of the message\n - the message received from the socket", "source": "juraj_google_style"} +{"code": "def __init__(self, api_key=None, endpoint=None, dtype=None, verbose=None, debug=None):\n\n self.api_key = api_key if api_key else os.environ['MPDS_KEY']\n\n self.network = httplib2.Http()\n\n self.endpoint = endpoint or self.endpoint\n self.dtype = dtype or MPDSDataTypes.PEER_REVIEWED\n self.verbose = verbose if verbose is not None else self.verbose\n self.debug = debug or self.debug", "docstring": "MPDS API consumer constructor\n\nArgs:\n api_key: (str) The MPDS API key, or None if the MPDS_KEY envvar is set\n endpoint: (str) MPDS API gateway URL\n\n Returns: None", "source": "juraj_google_style"} +{"code": "def md5sum( string ):\n\n h = hashlib.new( 'md5' )\n h.update( string.encode( 'utf-8' ) )\n return h.hexdigest()", "docstring": "Generate the md5 checksum for a string\n\nArgs:\n string (Str): The string to be checksummed.\n\nReturns:\n (Str): The hex checksum.", "source": "juraj_google_style"} +{"code": "def in_flight_request_count(self, node_id=None):\n\n if node_id is not None:\n conn = self._conns.get(node_id)\n if conn is None:\n return 0\n return len(conn.in_flight_requests)\n else:\n return sum([len(conn.in_flight_requests)\n for conn in list(self._conns.values())])", "docstring": "Get the number of in-flight requests for a node or all nodes.\n\nArgs:\n node_id (int, optional): a specific node to check. If unspecified,\n return the total for all nodes\n\nReturns:\n int: pending in-flight requests for the node, or all nodes if None", "source": "juraj_google_style"} +{"code": "def __update_cleanup_paths(new_path):\n\n cleanup_dirs = settings.CFG[\"cleanup_paths\"].value\n cleanup_dirs = set(cleanup_dirs)\n cleanup_dirs.add(new_path)\n cleanup_dirs = list(cleanup_dirs)\n settings.CFG[\"cleanup_paths\"] = cleanup_dirs", "docstring": "Add the new path to the list of paths to clean up afterwards.\n\nArgs:\n new_path: Path to the directory that need to be cleaned up.", "source": "juraj_google_style"} +{"code": "def getctime(self, path=None, client_kwargs=None, header=None):\n\n return self._getctime_from_header(\n self.head(path, client_kwargs, header))", "docstring": "Return the creation time of path.\n\nArgs:\n path (str): File path or URL.\n client_kwargs (dict): Client arguments.\n header (dict): Object header.\n\nReturns:\n float: The number of seconds since the epoch\n (see the time module).", "source": "juraj_google_style"} +{"code": "def compute_backoff(attempts, *, factor=5, jitter=True, max_backoff=2000, max_exponent=32):\n\n exponent = min(attempts, max_exponent)\n backoff = min(factor * 2 ** exponent, max_backoff)\n if jitter:\n backoff /= 2\n backoff = int(backoff + uniform(0, backoff))\n return attempts + 1, backoff", "docstring": "Compute an exponential backoff value based on some number of attempts.\n\n Parameters:\n attempts(int): The number of attempts there have been so far.\n factor(int): The number of milliseconds to multiply each backoff by.\n max_backoff(int): The max number of milliseconds to backoff by.\n max_exponent(int): The maximum backoff exponent.\n\nReturns:\n tuple: The new number of attempts and the backoff in milliseconds.", "source": "juraj_google_style"} +{"code": "def record(self, value=1.0, time_ms=None):\n\n if time_ms is None:\n time_ms = time.time() * 1000\n self._last_record_time = time_ms\n with self._lock: # XXX high volume, might be performance issue\n # increment all the stats\n for stat in self._stats:\n stat.record(self._config, value, time_ms)\n self._check_quotas(time_ms)\n for parent in self._parents:\n parent.record(value, time_ms)", "docstring": "Record a value at a known time.\n\nArgs:\n value (double): The value we are recording\n time_ms (int): A POSIX timestamp in milliseconds.\n Default: The time when record() is evaluated (now)\n\nRaises:\n QuotaViolationException: if recording this value moves a\n metric beyond its configured maximum or minimum bound", "source": "juraj_google_style"} +{"code": "def pose_inv(pose):\n\n\n # Note, the inverse of a pose matrix is the following\n # [R t; 0 1]^-1 = [R.T -R.T*t; 0 1]\n\n # Intuitively, this makes sense.\n # The original pose matrix translates by t, then rotates by R.\n # We just invert the rotation by applying R-1 = R.T, and also translate back.\n # Since we apply translation first before rotation, we need to translate by\n # -t in the original frame, which is -R-1*t in the new frame, and then rotate back by\n # R-1 to align the axis again.\n\n pose_inv = np.zeros((4, 4))\n pose_inv[:3, :3] = pose[:3, :3].T\n pose_inv[:3, 3] = -pose_inv[:3, :3].dot(pose[:3, 3])\n pose_inv[3, 3] = 1.0\n return pose_inv", "docstring": "Computes the inverse of a homogenous matrix corresponding to the pose of some\n frame B in frame A. The inverse is the pose of frame A in frame B.\n\nArgs:\n pose: numpy array of shape (4,4) for the pose to inverse\n\nReturns:\n numpy array of shape (4,4) for the inverse pose", "source": "juraj_google_style"} +{"code": "def traverse_ancestors(self, include_self=True):\n\n if not isinstance(include_self, bool):\n raise TypeError(\"include_self must be a bool\")\n if include_self:\n c = self\n else:\n c = self.parent\n while c is not None:\n yield c; c = c.parent", "docstring": "Traverse over the ancestors of this ``Node``\n\nArgs:\n ``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False``", "source": "juraj_google_style"} +{"code": "def segmentation_to_mask(polys, height, width):\n\n polys = [p.flatten().tolist() for p in polys]\n assert len(polys) > 0, \"Polygons are empty!\"\n\n import pycocotools.mask as cocomask\n rles = cocomask.frPyObjects(polys, height, width)\n rle = cocomask.merge(rles)\n return cocomask.decode(rle)", "docstring": "Convert polygons to binary masks.\n\nArgs:\n polys: a list of nx2 float array. Each array contains many (x, y) coordinates.\n\nReturns:\n a binary matrix of (height, width)", "source": "juraj_google_style"} +{"code": "def _ParseOriginalFilename(self, file_object, format_version):\n\n file_offset = file_object.tell()\n\n if format_version == 1:\n data_type_map = self._GetDataTypeMap(\n 'recycle_bin_metadata_utf16le_string')\n else:\n data_type_map = self._GetDataTypeMap(\n 'recycle_bin_metadata_utf16le_string_with_size')\n\n try:\n original_filename, _ = self._ReadStructureFromFileObject(\n file_object, file_offset, data_type_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError(\n 'Unable to parse original filename with error: {0!s}'.format(\n exception))\n\n if format_version == 1:\n return original_filename.rstrip('\\x00')\n\n return original_filename.string.rstrip('\\x00')", "docstring": "Parses the original filename.\n\nArgs:\n file_object (FileIO): file-like object.\n format_version (int): format version.\n\nReturns:\n str: filename or None on error.\n\nRaises:\n ParseError: if the original filename cannot be read.", "source": "juraj_google_style"} +{"code": "def get_unresolved(aln_df):\n\n unresolved_df = aln_df[aln_df['type'] == 'unresolved']\n unresolved = []\n if not unresolved_df.empty:\n unresolved_df['id_a_pos'] = unresolved_df['id_a_pos'].astype(int)\n unresolved = unresolved_df.id_a_pos.tolist()\n return unresolved", "docstring": "Get a list of residue numbers (in the original sequence's numbering) that are unresolved\n\nArgs:\n aln_df (DataFrame): Alignment DataFrame\n\nReturns:\n list: Residue numbers that are mutated", "source": "juraj_google_style"} +{"code": "def GetMerger(self, cls):\n\n for merger in self._mergers:\n if isinstance(merger, cls):\n return merger\n raise LookupError('No matching DataSetMerger found')", "docstring": "Looks for an added DataSetMerger derived from the given class.\n\nArgs:\n cls: A class derived from DataSetMerger.\n\nReturns:\n The matching DataSetMerger instance.\n\nRaises:\n LookupError: No matching DataSetMerger has been added.", "source": "juraj_google_style"} +{"code": "def get_current_and_head_revision(\n database_url: str,\n alembic_config_filename: str,\n alembic_base_dir: str = None,\n version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]:\n\n # Where we are\n head_revision = get_head_revision_from_alembic(\n alembic_config_filename=alembic_config_filename,\n alembic_base_dir=alembic_base_dir,\n version_table=version_table\n )\n log.info(\"Intended database version: {}\", head_revision)\n\n # Where we want to be\n current_revision = get_current_revision(\n database_url=database_url,\n version_table=version_table\n )\n log.info(\"Current database version: {}\", current_revision)\n\n # Are we where we want to be?\n return current_revision, head_revision", "docstring": "Returns a tuple of ``(current_revision, head_revision)``; see\n :func:`get_current_revision` and :func:`get_head_revision_from_alembic`.\n\nArgs:\n database_url: SQLAlchemy URL for the database\n alembic_config_filename: config filename\n alembic_base_dir: directory to start in, so relative paths in the\n config file work.\n version_table: table name for Alembic versions", "source": "juraj_google_style"} +{"code": "def plot_legend(ax, no_legend=True, legend_arg=None):\n\n legend_arg = dict_if_none(legend_arg)\n\n if not no_legend:\n ax.legend(**legend_arg)", "docstring": "Function that defines the legend options\n of a matplotlib plot.\n\nArgs:\n ax: matplotlib axes\n no_legend (bool): Defines the presence of a legend in the figure\n legend_arg (dict): Addition arguments for matplotlib.legend() call", "source": "juraj_google_style"} +{"code": "def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config):\n\n oauth2_kwargs = {\n 'proxy_config': proxy_config\n }\n\n if all(config in product_data for config in _OAUTH2_INSTALLED_APP_KEYS):\n oauth2_args = [\n product_data['client_id'], product_data['client_secret'],\n product_data['refresh_token']\n ]\n oauth2_client = googleads.oauth2.GoogleRefreshTokenClient\n for key in _OAUTH2_INSTALLED_APP_KEYS:\n del product_data[key]\n elif all(config in product_data for config in _OAUTH2_SERVICE_ACCT_KEYS):\n oauth2_args = [\n product_data['path_to_private_key_file'],\n googleads.oauth2.GetAPIScope(product_yaml_key),\n ]\n oauth2_kwargs.update({\n 'sub': product_data.get('delegated_account')\n })\n oauth2_client = googleads.oauth2.GoogleServiceAccountClient\n for key in _OAUTH2_SERVICE_ACCT_KEYS:\n del product_data[key]\n for optional_key in _OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL:\n if optional_key in product_data:\n del product_data[optional_key]\n else:\n raise googleads.errors.GoogleAdsValueError(\n 'Your yaml file is incorrectly configured for OAuth2. You need to '\n 'specify credentials for either the installed application flow (%s) '\n 'or service account flow (%s).' %\n (_OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS))\n\n return oauth2_client(*oauth2_args, **oauth2_kwargs)", "docstring": "Generates an GoogleOAuth2Client subclass using the given product_data.\n\nArgs:\n product_yaml_key: a string key identifying the product being configured.\n product_data: a dict containing the configurations for a given product.\n proxy_config: a ProxyConfig instance.\n\nReturns:\n An instantiated GoogleOAuth2Client subclass.\n\nRaises:\n A GoogleAdsValueError if the OAuth2 configuration for the given product is\n misconfigured.", "source": "juraj_google_style"} +{"code": "def replace_drive_enclosure(self, information):\n\n\n uri = \"{}/replaceDriveEnclosure\".format(self.data[\"uri\"])\n result = self._helper.create(information, uri)\n self.refresh()\n\n return result", "docstring": "When a drive enclosure has been physically replaced, initiate the replacement operation that enables the\n new drive enclosure to take over as a replacement for the prior drive enclosure. The request requires\n specification of both the serial numbers of the original drive enclosure and its replacement to be provided.\n\nArgs:\n information: Options to replace the drive enclosure.\n\nReturns:\n dict: SAS Logical Interconnect.", "source": "juraj_google_style"} +{"code": "def __saveHyperSearchJobID(cls, permWorkDir, outputLabel, hyperSearchJob):\n\n jobID = hyperSearchJob.getJobID()\n filePath = cls.__getHyperSearchJobIDFilePath(permWorkDir=permWorkDir,\n outputLabel=outputLabel)\n\n if os.path.exists(filePath):\n _backupFile(filePath)\n\n d = dict(hyperSearchJobID = jobID)\n\n with open(filePath, \"wb\") as jobIdPickleFile:\n pickle.dump(d, jobIdPickleFile)", "docstring": "Saves the given _HyperSearchJob instance's jobID to file\n\n Parameters:\n ----------------------------------------------------------------------\n permWorkDir: Directory path for saved jobID file\n outputLabel: Label string for incorporating into file name for saved jobID\n hyperSearchJob: _HyperSearchJob instance\n retval: nothing", "source": "juraj_google_style"} +{"code": "def cast_to_str(obj):\n\n\n if isinstance(obj, str):\n return obj\n if isinstance(obj, Seq):\n return str(obj)\n if isinstance(obj, SeqRecord):\n return str(obj.seq)\n else:\n raise ValueError('Must provide a string, Seq, or SeqRecord object.')", "docstring": "Return a string representation of a Seq or SeqRecord.\n\nArgs:\n obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord\n\nReturns:\n str: String representation of the sequence", "source": "juraj_google_style"} +{"code": "def _refresh_grpc(operations_stub, operation_name):\n\n request_pb = operations_pb2.GetOperationRequest(name=operation_name)\n return operations_stub.GetOperation(request_pb)", "docstring": "Refresh an operation using a gRPC client.\n\nArgs:\n operations_stub (google.longrunning.operations_pb2.OperationsStub):\n The gRPC operations stub.\n operation_name (str): The name of the operation.\n\nReturns:\n google.longrunning.operations_pb2.Operation: The operation.", "source": "juraj_google_style"} +{"code": "def download_url(url, root, filename=None, md5=None):\n\n from six.moves import urllib\n\n root = os.path.expanduser(root)\n if not filename:\n filename = os.path.basename(url)\n fpath = os.path.join(root, filename)\n\n makedir_exist_ok(root)\n\n # downloads file\n if os.path.isfile(fpath) and check_integrity(fpath, md5):\n print('Using downloaded and verified file: ' + fpath)\n else:\n try:\n print('Downloading ' + url + ' to ' + fpath)\n urllib.request.urlretrieve(\n url, fpath,\n reporthook=gen_bar_updater()\n )\n except OSError:\n if url[:5] == 'https':\n url = url.replace('https:', 'http:')\n print('Failed download. Trying https -> http instead.'\n ' Downloading ' + url + ' to ' + fpath)\n urllib.request.urlretrieve(\n url, fpath,\n reporthook=gen_bar_updater()\n )", "docstring": "Download a file from a url and place it in root.\n\nArgs:\n url (str): URL to download file from\n root (str): Directory to place downloaded file in\n filename (str, optional): Name to save the file under. If None, use the basename of the URL\n md5 (str, optional): MD5 checksum of the download. If None, do not check", "source": "juraj_google_style"} +{"code": "def load(cls, path: str, password: str = None) -> 'Account':\n\n with open(path) as f:\n keystore = json.load(f)\n if not check_keystore_json(keystore):\n raise ValueError('Invalid keystore file')\n return Account(keystore, password, path=path)", "docstring": "Load an account from a keystore file.\n\nArgs:\n path: full path to the keyfile\n password: the password to decrypt the key file or `None` to leave it encrypted", "source": "juraj_google_style"} +{"code": "def exclude(self, **filters):\n\n exclude = {'-%s' % key: value for key, value in filters.items()}\n return self.filter(**exclude)", "docstring": "Applies query filters for excluding matching records from result set.\n\nArgs:\n **filters: Query filters as keyword arguments.\n\nReturns:\n Self. Queryset object.\n\nExample:\n >>> Person.objects.exclude(age=None)\n >>> Person.objects.filter(name__startswith='jo').exclude(age__lte=16)", "source": "juraj_google_style"} +{"code": "def _index_to_ansi_values(self, index):\n\n if self.__class__.__name__[0] == 'F': # Foreground\n if index < 8:\n index += ANSI_FG_LO_BASE\n else:\n index += (ANSI_FG_HI_BASE - 8) # 82\n else: # Background\n if index < 8:\n index += ANSI_BG_LO_BASE\n else:\n index += (ANSI_BG_HI_BASE - 8) # 92\n return [str(index)]", "docstring": "Converts an palette index to the corresponding ANSI color.\n\nArgs:\n index - an int (from 0-15)\n\nReturns:\n index as str in a list for compatibility with values.", "source": "juraj_google_style"} +{"code": "def removeRouter(self, xRouterId):\n\n print '%s call removeRouter' % self.port\n print xRouterId\n routerId = ''\n routerId = self.__convertRlocToRouterId(xRouterId)\n print routerId\n\n if routerId == None:\n print 'no matched xRouterId'\n return False\n\n try:\n cmd = 'releaserouterid %s' % routerId\n return self.__sendCommand(cmd)[0] != 'Fail'\n except Exception, e:\n ModuleHelper.WriteIntoDebugLogger('removeRouter() Error: ' + str(e))", "docstring": "kick router with a given router id from the Thread Network\n\nArgs:\n xRouterId: a given router id in hex format\n\nReturns:\n True: successful to remove the router from the Thread Network\n False: fail to remove the router from the Thread Network", "source": "juraj_google_style"} +{"code": "def get_likelihood(self, uni_matrix):\n\n uni_dim = uni_matrix.shape[1]\n num_edge = len(self.edges)\n values = np.zeros([1, num_edge])\n new_uni_matrix = np.empty([uni_dim, uni_dim])\n\n for i in range(num_edge):\n edge = self.edges[i]\n value, left_u, right_u = edge.get_likelihood(uni_matrix)\n new_uni_matrix[edge.L, edge.R] = left_u\n new_uni_matrix[edge.R, edge.L] = right_u\n values[0, i] = np.log(value)\n\n return np.sum(values), new_uni_matrix", "docstring": "Compute likelihood of the tree given an U matrix.\n\nArgs:\n uni_matrix(numpy.array): univariate matrix to evaluate likelihood on.\n\nReturns:\n tuple[float, numpy.array]:\n likelihood of the current tree, next level conditional univariate matrix", "source": "juraj_google_style"} +{"code": "def from_tushare(dataframe, dtype='day'):\n\n\n if dtype in ['day']:\n return QA_DataStruct_Stock_day(\n dataframe.assign(date=pd.to_datetime(dataframe.date)\n ).set_index(['date',\n 'code'],\n drop=False),\n dtype='stock_day'\n )\n elif dtype in ['min']:\n return QA_DataStruct_Stock_min(\n dataframe.assign(datetime=pd.to_datetime(dataframe.datetime)\n ).set_index(['datetime',\n 'code'],\n drop=False),\n dtype='stock_min'\n )", "docstring": "dataframe from tushare\n\nArgs:\n dataframe {[type]} -- [description]\n\nReturns:\n [type] -- [description]", "source": "juraj_google_style"} +{"code": "def prefixlen_to_mask(prefixlen):\n\n prefixlen = prefixlen or '32'\n addr = '0.0.0.0/%s' % prefixlen\n return str(netaddr.IPNetwork(addr).netmask)", "docstring": "Converts a prefix length to a dotted decimal subnet mask\n\nArgs:\n prefixlen (str): The prefix length value to convert\n\nReturns:\n str: The subt mask as a dotted decimal string", "source": "juraj_google_style"} +{"code": "def _add_unitary_two(self, gate, qubit0, qubit1):\n\n\n # Convert to complex rank-4 tensor\n gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2])\n\n # Compute einsum index string for 2-qubit matrix multiplication\n indexes = einsum_matmul_index([qubit0, qubit1], self._number_of_qubits)\n\n # Apply matrix multiplication\n self._unitary = np.einsum(indexes, gate_tensor, self._unitary,\n dtype=complex, casting='no')", "docstring": "Apply a two-qubit unitary matrix.\n\nArgs:\n gate (matrix_like): a the two-qubit gate matrix\n qubit0 (int): gate qubit-0\n qubit1 (int): gate qubit-1", "source": "juraj_google_style"} +{"code": "def delete_token(self,\n token_name,\n project_name,\n dataset_name):\n\n url = self.url() + \"/nd/resource/dataset/{}\".format(dataset_name)\\\n + \"/project/{}\".format(project_name)\\\n + \"/token/{}/\".format(token_name)\n req = self.remote_utils.delete_url(url)\n\n if req.status_code is not 204:\n raise RemoteDataUploadError(\"Could not delete {}\".format(req.text))\n if req.content == \"\" or req.content == b'':\n return True\n else:\n return False", "docstring": "Delete a token with the given parameters.\n\nArgs:\n project_name (str): Project name\n dataset_name (str): Dataset name project is based on\n token_name (str): Token name\n channel_name (str): Channel name project is based on\n\nReturns:\n bool: True if project deleted, false if not deleted.", "source": "juraj_google_style"} +{"code": "def learn(self, initial_state_key, limit=1000, game_n=1):\n\n end_flag_list = [False] * len(self.q_learning_list)\n for game in range(game_n):\n state_key = copy.copy(initial_state_key)\n self.t = 1\n while self.t <= limit:\n for i in range(len(self.q_learning_list)):\n if game + 1 == game_n:\n self.state_key_list.append((i, copy.copy(state_key)))\n self.q_learning_list[i].t = self.t\n next_action_list = self.q_learning_list[i].extract_possible_actions(state_key)\n\n if len(next_action_list):\n action_key = self.q_learning_list[i].select_action(\n state_key=state_key,\n next_action_list=next_action_list\n )\n reward_value = self.q_learning_list[i].observe_reward_value(state_key, action_key)\n\n # Check.\n if self.q_learning_list[i].check_the_end_flag(state_key) is True:\n end_flag_list[i] = True\n\n # Max-Q-Value in next action time.\n next_state_key = self.q_learning_list[i].update_state(\n state_key=state_key,\n action_key=action_key\n )\n next_next_action_list = self.q_learning_list[i].extract_possible_actions(next_state_key)\n if len(next_next_action_list):\n next_action_key = self.q_learning_list[i].predict_next_action(\n next_state_key,\n next_next_action_list\n )\n next_max_q = self.q_learning_list[i].extract_q_df(next_state_key, next_action_key)\n\n # Update Q-Value.\n self.q_learning_list[i].update_q(\n state_key=state_key,\n action_key=action_key,\n reward_value=reward_value,\n next_max_q=next_max_q\n )\n\n # Update State.\n state_key = next_state_key\n\n # Epsode.\n self.t += 1\n self.q_learning_list[i].t = self.t\n if False not in end_flag_list:\n break", "docstring": "Multi-Agent Learning.\n\n Override.\n\nArgs:\n initial_state_key: Initial state.\n limit: Limit of the number of learning.\n game_n: The number of games.", "source": "juraj_google_style"} +{"code": "def apply_region_configs(env_config):\n\n new_config = env_config.copy()\n for region in env_config.get('regions', REGIONS):\n if isinstance(env_config.get('regions'), dict):\n region_specific_config = env_config['regions'][region]\n new_config[region] = dict(DeepChainMap(region_specific_config, env_config))\n else:\n new_config[region] = env_config.copy()\n LOG.debug('Region Specific Config:\\n%s', new_config)\n return new_config", "docstring": "Override default env configs with region specific configs and nest\n all values under a region\n\nArgs:\n env_config (dict): The environment specific config.\n\nReturns:\n dict: Newly updated dictionary with region overrides applied.", "source": "juraj_google_style"} +{"code": "def get_course_modes(self, course_id):\n\n details = self.get_course_details(course_id)\n modes = details.get('course_modes', [])\n return self._sort_course_modes([mode for mode in modes if mode['slug'] not in EXCLUDED_COURSE_MODES])", "docstring": "Query the Enrollment API for the specific course modes that are available for the given course_id.\n\nArgs:\n course_id (str): The string value of the course's unique identifier\n\nReturns:\n list: A list of course mode dictionaries.", "source": "juraj_google_style"} +{"code": "def address(self, num):\n\n url_root = \"company/{}/registered-office-address\"\n baseuri = self._BASE_URI + url_root.format(num)\n res = self.session.get(baseuri)\n self.handle_http_error(res)\n return res", "docstring": "Search for company addresses by company number.\n\nArgs:\n num (str): Company number to search on.", "source": "juraj_google_style"} +{"code": "def _get_args_name_from_parser(parser):\n\n # Retrieve the 'action' destination of the method parser i.e. its\n # argument name. The HelpAction is ignored.\n return [action.dest for action in parser._actions if not\n isinstance(action, argparse._HelpAction)]", "docstring": "Retrieve the name of the function argument linked to the given parser.\n\nArgs:\n parser: a function parser", "source": "juraj_google_style"} +{"code": "def get_artist_location(self, cache=True):\n\n if not (cache and ('artist_location' in self.cache)):\n response = self.get_attribute('profile', bucket='artist_location')\n self.cache['artist_location'] = response['songs'][0]['artist_location']\n return self.cache['artist_location']", "docstring": "Get the location of a song's artist.\n\nArgs:\n cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.\n\nReturns:\n An artist location object.\n\nExample:\n >>> s = song.Song('SOQKVPH12A58A7AF4D')\n >>> s.artist_location\n {u'latitude': 34.053489999999996, u'location': u'Los Angeles, CA', u'longitude': -118.24532000000001}\n >>>", "source": "juraj_google_style"} +{"code": "def get_parser(parser):\n\n parser.description = textwrap.dedent(.strip())\n parser.add_argument(\"locale\", nargs=\"+\", help=\"a locale to segment\")", "docstring": "Grabs the parser.\n\nArgs:\n parser: The parser", "source": "juraj_google_style"} +{"code": "def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None):\n\n\n # Use cid if provided\n if cid is not None:\n assert type(cid) == list, \"cid must be a list. cid: {}\".format(cid)\n\n cols_to_keep = [gctoo_col for gctoo_col in gctoo.data_df.columns if gctoo_col in cid]\n\n # Tell user if some cids not found\n num_missing_cids = len(cid) - len(cols_to_keep)\n if num_missing_cids != 0:\n logger.info(\"{} cids were not found in the GCT.\".format(num_missing_cids))\n\n # Use col_bool if provided\n elif col_bool is not None:\n\n assert len(col_bool) == gctoo.data_df.shape[1], (\n \"col_bool must have length equal to gctoo.data_df.shape[1]. \" +\n \"len(col_bool): {}, gctoo.data_df.shape[1]: {}\".format(\n len(col_bool), gctoo.data_df.shape[1]))\n cols_to_keep = gctoo.data_df.columns[col_bool].values\n\n # Use cidx if provided\n elif cidx is not None:\n\n assert type(cidx[0]) is int, (\n \"cidx must be a list of integers. cidx[0]: {}, \" +\n \"type(cidx[0]): {}\").format(cidx[0], type(cidx[0]))\n\n assert max(cidx) <= gctoo.data_df.shape[1], (\n \"cidx contains an integer larger than the number of columns in \" +\n \"the GCToo. max(cidx): {}, gctoo.data_df.shape[1]: {}\").format(\n max(cidx), gctoo.data_df.shape[1])\n\n cols_to_keep = gctoo.data_df.columns[cidx].values\n\n # If cid, col_bool, and cidx are all None, return all columns\n else:\n cols_to_keep = gctoo.data_df.columns.values\n\n # Use exclude_cid if provided\n if exclude_cid is not None:\n\n # Keep only those columns that are not in exclude_cid\n cols_to_keep = [col_to_keep for col_to_keep in cols_to_keep if col_to_keep not in exclude_cid]\n\n return cols_to_keep", "docstring": "Figure out based on the possible columns inputs which columns to keep.\n\nArgs:\n gctoo (GCToo object):\n cid (list of strings):\n col_bool (boolean array):\n cidx (list of integers):\n exclude_cid (list of strings):\n\nReturns:\n cols_to_keep (list of strings): col ids to be kept", "source": "juraj_google_style"} +{"code": "def set_colour(self, r, g, b):\n\n if not 0 <= r <= 255:\n raise ValueError(\"The value for red needs to be between 0 and 255.\")\n if not 0 <= g <= 255:\n raise ValueError(\"The value for green needs to be between 0 and 255.\")\n if not 0 <= b <= 255:\n raise ValueError(\"The value for blue needs to be between 0 and 255.\")\n\n #print(BulbDevice)\n hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b)\n\n payload = self.generate_payload(SET, {\n self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR,\n self.DPS_INDEX_COLOUR: hexvalue})\n data = self._send_receive(payload)\n return data", "docstring": "Set colour of an rgb bulb.\n\nArgs:\n r(int): Value for the colour red as int from 0-255.\n g(int): Value for the colour green as int from 0-255.\n b(int): Value for the colour blue as int from 0-255.", "source": "juraj_google_style"} +{"code": "def _scrub_method_name(self, method_name):\n\n if method_name not in self._scrubbed_method_names:\n self._scrubbed_method_names[method_name] = (\n scrub_method_name(method_name))\n\n return self._scrubbed_method_names[method_name]", "docstring": "Scrubs a method name, returning result from local cache if available.\n\n This method wraps fitparse.utils.scrub_method_name and memoizes results,\n as scrubbing a method name is expensive.\n\nArgs:\n method_name: Method name to scrub.\n\nReturns:\n Scrubbed method name.", "source": "juraj_google_style"} +{"code": "def __init__(self, word_count=None):\n\n\n if isinstance(word_count, dict):\n word_count = iteritems(word_count)\n sorted_counts = list(sorted(word_count, key=lambda wc: wc[1], reverse=True))\n words = [w for w,c in sorted_counts]\n super(CountedVocabulary, self).__init__(words=words)\n self.word_count = dict(sorted_counts)", "docstring": "Build attributes word_id and id_word from input.\n\nArgs:\n word_count (dictionary): A dictionary of the type word:count or\n list of tuples of the type (word, count).", "source": "juraj_google_style"} +{"code": "def jump(self, selected_number: int) -> None:\n\n self._verify_entrypoint_selected()\n if selected_number < 1 or selected_number > len(self.trace_tuples):\n raise UserError(\n \"Trace frame number out of bounds \"\n f\"(expected 1-{len(self.trace_tuples)} but got {selected_number}).\"\n )\n\n self.current_trace_frame_index = selected_number - 1\n self.trace()", "docstring": "Jump to a specific trace frame in a trace.\n\n Parameters:\n selected_number: int the trace frame number from trace output", "source": "juraj_google_style"} +{"code": "def parse(cls, buf: memoryview, params: Params) \\\n -> Tuple[Parseable, memoryview]:\n\n for data_type in params.expected:\n try:\n return data_type.parse(buf, params)\n except NotParseable:\n pass\n raise UnexpectedType(buf)", "docstring": "Parses the given buffer by attempting to parse the list of\n :attr:`~Params.expected` types until one of them succeeds,\n then returns the parsed object.\n\nArgs:\n buf: The bytes containing the data to be parsed.\n params: The parameters used by some parseable types.", "source": "juraj_google_style"} +{"code": "def UpdateChainAndProcess(self, parser_mediator, registry_key, **kwargs):\n\n parser_mediator.AppendToParserChain(self)\n try:\n self.Process(parser_mediator, registry_key, **kwargs)\n finally:\n parser_mediator.PopFromParserChain()", "docstring": "Updates the parser chain and processes a Windows Registry key or value.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n registry_key (dfwinreg.WinRegistryKey): Windows Registry key.\n\nRaises:\n ValueError: If the Windows Registry key is not set.", "source": "juraj_google_style"} +{"code": "def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool:\n\n if len(self.sites) == 1:\n return True\n all_dists = self.distance_matrix[np.triu_indices(len(self), 1)]\n return bool(np.min(all_dists) > tol)", "docstring": "True if SiteCollection does not contain atoms that are too close\n together. Note that the distance definition is based on type of\n SiteCollection. Cartesian distances are used for non-periodic\n Molecules, while PBC is taken into account for periodic structures.\n\nArgs:\n tol (float): Distance tolerance. Default is 0.5A.\n\nReturns:\n (bool) True if SiteCollection does not contain atoms that are too\n close together.", "source": "juraj_google_style"} +{"code": "def export(self, template_file_name, output_file_name,\n sort=\"public\", data=None, limit=0):\n\n exportedData = {}\n exportedUsers = self.getSortedUsers()\n template = self.__getTemplate(template_file_name)\n position = 1\n\n if not limit:\n exportedData[\"users\"] = exportedUsers\n else:\n exportedData[\"users\"] = exportedUsers[:limit]\n\n for u in exportedData[\"users\"]:\n u[\"position\"] = position\n u[\"comma\"] = position < len(exportedData[\"users\"])\n position += 1\n\n exportedData[\"extraData\"] = data\n\n renderer = Renderer()\n output = renderer.render(template, exportedData)\n\n with open(output_file_name, \"w\") as text_file:\n text_file.write(output)", "docstring": "Export ranking to a file.\n\nArgs:\n template_file_name (str): where is the template\n (moustache template)\n output_file_name (str): where create the file with the ranking\n sort (str): field to sort the users", "source": "juraj_google_style"} +{"code": "def get_conv_out_grad(net, image, class_id=None, conv_layer_name=None):\n\n return _get_grad(net, image, class_id, conv_layer_name, image_grad=False)", "docstring": "Get the output and gradients of output of a convolutional layer.\n\n Parameters:\n ----------\n net: Block\n Network to use for visualization.\n image: NDArray\n Preprocessed image to use for visualization.\n class_id: int\n Category ID this image belongs to. If not provided,\n network's prediction will be used.\n conv_layer_name: str\n Name of the convolutional layer whose output and output's gradients need to be acptured.", "source": "juraj_google_style"} +{"code": "def _check_validity(cls, text):\n\n\n if not text[0].lstrip().startswith('1 ') or not text[1].lstrip().startswith('2 '):\n raise ValueError(\"Line number check failed\")\n\n for line in text:\n line = line.strip()\n if str(cls._checksum(line)) != line[-1]:\n raise ValueError(\"Checksum validation failed\")", "docstring": "Check the validity of a TLE\n\nArgs:\n text (tuple of str)\n\nRaises:\n ValueError", "source": "juraj_google_style"} +{"code": "def stream_sample(self, md5, kwargs=None):\n\n\n # Get the max_rows if specified\n max_rows = kwargs.get('max_rows', None) if kwargs else None\n\n # Grab the sample and it's raw bytes\n sample = self.get_sample(md5)['sample']\n raw_bytes = sample['raw_bytes']\n\n # Figure out the type of file to be streamed\n type_tag = sample['type_tag']\n if type_tag == 'bro':\n bro_log = bro_log_reader.BroLogReader(convert_datetimes=False)\n mem_file = StringIO(raw_bytes)\n generator = bro_log.read_log(mem_file)\n return generator\n elif type_tag == 'els_query':\n els_log = json.loads(raw_bytes)\n # Try to determine a couple of different types of ELS query results\n if 'fields' in els_log['hits']['hits'][0]:\n generator = (row['fields'] for row in els_log['hits']['hits'][:max_rows])\n else:\n generator = (row['_source'] for row in els_log['hits']['hits'][:max_rows])\n return generator\n elif type_tag == 'log':\n generator = ({'row':row} for row in raw_bytes.split('\\n')[:max_rows])\n return generator\n elif type_tag == 'json':\n generator = (row for row in json.loads(raw_bytes)[:max_rows])\n return generator\n else:\n raise RuntimeError('Cannot stream file %s with type_tag:%s' % (md5, type_tag))", "docstring": "Stream the sample by giving back a generator, typically used on 'logs'.\n\nArgs:\n md5: the md5 of the sample\n kwargs: a way of specifying subsets of samples (None for all)\n max_rows: the maximum number of rows to return\n\nReturns:\n A generator that yields rows of the file/log", "source": "juraj_google_style"} +{"code": "def setMaxDemandPeriod(self, period, password=\"00000000\"):\n\n result = False\n self.setContext(\"setMaxDemandPeriod\")\n try:\n if period < 1 or period > 3:\n self.writeCmdMsg(\"Correct parameter: 1 = 15 minute, 2 = 30 minute, 3 = hour\")\n self.setContext(\"\")\n return result\n\n if not self.request(False):\n self.writeCmdMsg(\"Bad read CRC on setting\")\n else:\n if not self.serialCmdPwdAuth(password):\n self.writeCmdMsg(\"Password failure\")\n else:\n req_str = \"015731023030353028\" + binascii.hexlify(str(period)).zfill(2) + \"2903\"\n req_str += self.calc_crc16(req_str[2:].decode(\"hex\"))\n self.m_serial_port.write(req_str.decode(\"hex\"))\n if self.m_serial_port.getResponse(self.getContext()).encode(\"hex\") == \"06\":\n self.writeCmdMsg(\"Success(setMaxDemandPeriod): 06 returned.\")\n result = True\n self.serialPostEnd()\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n\n self.setContext(\"\")\n return result", "docstring": "Serial call to set max demand period.\n\nArgs:\n period (int): : as int.\n password (str): Optional password.\n\nReturns:\n bool: True on completion with ACK.", "source": "juraj_google_style"} +{"code": "def get_data_csv(file_name, encoding='utf-8', file_contents=None, on_demand=False):\n\n def yield_csv(csv_contents, csv_file):\n try:\n for line in csv_contents:\n yield line\n finally:\n try:\n csv_file.close()\n except:\n pass\n\n def process_csv(csv_contents, csv_file):\n return [line for line in yield_csv(csv_contents, csv_file)]\n\n if file_contents:\n csv_file = BytesIO(file_contents)\n else:\n # Don't use 'open as' format, as on_demand loads shouldn't close the file early\n csv_file = open(file_name, 'rb')\n reader = csv.reader(csv_file, dialect=csv.excel, encoding=encoding)\n\n if on_demand:\n table = yield_csv(reader, csv_file)\n else:\n table = process_csv(reader, csv_file)\n\n return [table]", "docstring": "Gets good old csv data from a file.\n\nArgs:\n file_name: The name of the local file, or the holder for the\n extension type when the file_contents are supplied.\n encoding: Loads the file with the specified cell encoding.\n file_contents: The file-like object holding contents of file_name.\n If left as None, then file_name is directly loaded.\n on_demand: Requests that a yielder be used in place of a full data\n copy.", "source": "juraj_google_style"} +{"code": "def fillup_layer(layer, first_clbit):\n\n for nones in [i for i, x in enumerate(layer) if x is None]:\n layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')\n return layer", "docstring": "Given a layer, replace the Nones in it with EmptyWire elements.\n\nArgs:\n layer (list): The layer that contains Nones.\n first_clbit (int): The first wire that is classic.\n\nReturns:\n list: The new layer, with no Nones.", "source": "juraj_google_style"} +{"code": "def match(path, glob):\n\n path_len = len(path)\n glob_len = len(glob)\n\n ss = -1\n ss_glob = glob\n if '**' in glob:\n ss = glob.index('**')\n if '**' in glob[ss + 1:]:\n raise dpath.exceptions.InvalidGlob(\"Invalid glob. Only one '**' is permitted per glob.\")\n\n if path_len >= glob_len:\n # Just right or more stars.\n more_stars = ['*'] * (path_len - glob_len + 1)\n ss_glob = glob[:ss] + more_stars + glob[ss + 1:]\n elif path_len == glob_len - 1:\n # Need one less star.\n ss_glob = glob[:ss] + glob[ss + 1:]\n\n if path_len == len(ss_glob):\n # Python 3 support\n if PY3:\n return all(map(fnmatch.fnmatch, list(map(str, paths_only(path))), list(map(str, ss_glob))))\n else: # Default to Python 2\n return all(map(fnmatch.fnmatch, map(str, paths_only(path)), map(str, ss_glob)))\n\n return False", "docstring": "Match the path with the glob.\n\nArgs:\n path -- A list of keys representing the path.\n glob -- A list of globs to match against the path.", "source": "juraj_google_style"} +{"code": "def lstsq(A, b):\n r\n A = asarray(A, float)\n b = asarray(b, float)\n\n if A.ndim == 1:\n A = A[:, newaxis]\n\n if A.shape[1] == 1:\n return dot(A.T, b) / squeeze(dot(A.T, A))\n\n rcond = finfo(double).eps * max(*A.shape)\n return npy_lstsq(A, b, rcond=rcond)[0]", "docstring": "r\"\"\"Return the least-squares solution to a linear matrix equation.\n\nArgs:\n A (array_like): Coefficient matrix.\n b (array_like): Ordinate values.\n\nReturns:\n :class:`numpy.ndarray`: Least-squares solution.", "source": "juraj_google_style"} +{"code": "def spliceext(filepath, s):\n\n root, ext = os.path.splitext(safepath(filepath))\n return root + s + ext", "docstring": "Add s into filepath before the extension\n\nArgs:\n filepath (str, path): file path\n s (str): string to splice\n\nReturns:\n str", "source": "juraj_google_style"} +{"code": "def get_first_model_with_resource_name(cls, resource_name):\n\n\n models = cls.get_models_with_resource_name(resource_name)\n\n if len(models) > 0:\n return models[0]\n\n return None", "docstring": "Get the first model corresponding to a resource_name\n\nArgs:\n resource_name: the resource name", "source": "juraj_google_style"} +{"code": "def _generate_altered_sql_dependencies(self, dep_changed_keys):\n\n for key, removed_deps, added_deps in dep_changed_keys:\n app_label, sql_name = key\n operation = AlterSQLState(sql_name, add_dependencies=tuple(added_deps),\n remove_dependencies=tuple(removed_deps))\n sql_deps = [key]\n self.add_sql_operation(app_label, sql_name, operation, sql_deps)", "docstring": "Generate forward operations for changing/creating SQL item dependencies.\n\n Dependencies are only in-memory and should be reflecting database dependencies, so\n changing them in SQL config does not alter database. Such actions are persisted in separate\n type operation - `AlterSQLState`.\n\nArgs:\n dep_changed_keys (list): Data about keys, that have their dependencies changed.\n List of tuples (key, removed depndencies, added_dependencies).", "source": "juraj_google_style"} +{"code": "def _determine_hpp_url(self, platform, action):\n\n base_uri = settings.BASE_HPP_URL.format(platform)\n service = action + '.shtml'\n result = '/'.join([base_uri, service])\n return result", "docstring": "This returns the Adyen HPP endpoint based on the provided platform,\n and action.\n\nArgs:\n platform (str): Adyen platform, ie 'live' or 'test'.\n action (str): the HPP action to perform.\n possible actions: select, pay, skipDetails, directory", "source": "juraj_google_style"} +{"code": "def write_log_file(namespace, document):\n\n log_timestamp = asctime(gmtime(document[TS]))\n with open(\"{}{}.{}.log\".format(LOG_DIR, namespace, DAY_STRING), \"a\") as f:\n log_string = dumps({\n \"datetime\": log_timestamp.upper(),\n \"namespace\": namespace,\n \"log\": document[LOG_KEY]\n })\n f.write(\"{}\\n\".format(log_string))", "docstring": "Writes a line to a log file\n\nArgs:\n namespace {str} -- namespace of document\n document {dict} -- document to write to the logs", "source": "juraj_google_style"} +{"code": "def run_pod(self, pod, startup_timeout=120, get_logs=True):\n # type: (Pod, int, bool) -> Tuple[State, Optional[str]]\n\n resp = self.run_pod_async(pod)\n curr_time = dt.now()\n if resp.status.start_time is None:\n while self.pod_not_started(pod):\n delta = dt.now() - curr_time\n if delta.seconds >= startup_timeout:\n raise AirflowException(\"Pod took too long to start\")\n time.sleep(1)\n self.log.debug('Pod not yet started')\n\n return self._monitor_pod(pod, get_logs)", "docstring": "Launches the pod synchronously and waits for completion.\n\nArgs:\n pod (Pod):\n startup_timeout (int): Timeout for startup of the pod (if pod is pending for\n too long, considers task a failure", "source": "juraj_google_style"} +{"code": "def request(self, subject, callback, msg=None):\n\n inbox = self._build_inbox()\n s = self.subscribe(inbox, callback)\n self.unsubscribe(s, 1)\n self.publish(subject, msg, inbox)\n\n return s", "docstring": "ublish a message with an implicit inbox listener as the reply.\n Message is optional.\n\nArgs:\n subject (string): a string with the subject\n callback (function): callback to be called\n msg (string=None): payload string", "source": "juraj_google_style"} +{"code": "def get_top_pairs(fsym, limit=5):\n\n\n\t# load data\n\turl = build_url('pairs', fsym=fsym, limit=limit)\n\tdata = load_data(url)\n\n\treturn data['Data']", "docstring": "Get top trading pairs by 24 hour aggregated volume for a currency.\n\nArgs:\n fsym: FROM symbol.\n limit: Number of results. Default value returns top 5 pairs.\n\nReturns:\n Function returns a list containing a dictionary for each result:\n\n [{'exchange': ..., 'fromSymbol': ..., 'toSymbol': ..., 'volume24h': ...,\n 'volume24hTo': ...},\n {...},\n ...]\n\n The list is ordered based on the volume of the FROM currency starting\n with the highest value.", "source": "juraj_google_style"} +{"code": "def gallery_section(images, title):\n\n # pull all images\n imgs = []\n while True:\n img = yield marv.pull(images)\n if img is None:\n break\n imgs.append({'src': img.relpath})\n if not imgs:\n return\n\n # create gallery widget and section containing it\n widget = {'title': images.title, 'gallery': {'images': imgs}}\n section = {'title': title, 'widgets': [widget]}\n yield marv.push(section)", "docstring": "Create detail section with gallery.\n\nArgs:\n title (str): Title to be displayed for detail section.\n images: stream of marv image files\n\n Returns\n One detail section.", "source": "juraj_google_style"} +{"code": "def outputZip(self,figtype='png'):\n\n from zipfile import ZipFile\n with ZipFile(self.outfile+'.zip', 'w') as zipcontainer:\n zipcontainer.writestr(\n 'summary.txt',\n '# {}\\n\\n{}\\n{}'.format(\n self.title,\n self.p,\n ('\\n## Conclusion\\n' if self.conclusion else '')+self.conclusion\n ).encode()\n )\n c = count(1)\n for section in self.sections:\n section.sectionOutZip(zipcontainer,'s{}_{}/'.format(next(c),section.title.replace(' ','_')),\n figtype=figtype)", "docstring": "Outputs the report in a zip container.\n Figs and tabs as pngs and excells.\n\nArgs:\n figtype (str): Figure type of images in the zip folder.", "source": "juraj_google_style"} +{"code": "def add_activation_summary(x, types=None, name=None, collections=None):\n\n ndim = x.get_shape().ndims\n if ndim < 2:\n logger.warn(\"Cannot summarize scalar activation {}\".format(x.name))\n return\n if types is None:\n types = ['sparsity', 'rms', 'histogram']\n with cached_name_scope('activation-summary'):\n add_tensor_summary(x, types, name=name, collections=collections)", "docstring": "Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope.\n This function is a no-op if not calling from main training tower.\n\nArgs:\n x (tf.Tensor): the tensor to summary.\n types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``.\n name (str): if is None, use x.name.\n collections (list[str]): collections of the summary ops.", "source": "juraj_google_style"} +{"code": "def key_swap(\n d,\n cls,\n marshal\n):\n\n dname = '_{}marshal_key_swap'.format(\"\" if marshal else \"un\")\n if hasattr(cls, dname):\n key_swap = getattr(cls, dname)\n return {\n key_swap[k] if k in key_swap else k: v\n for k, v in d.items()\n }\n else:\n return d", "docstring": "Swap the keys in a dictionary\n\nArgs:\n d: dict, The dict to swap keys in\n cls: class, If the class has a staticly defined\n _marshal_key_swap and/or _unmarshal_key_swap dict,\n the keys will be swapped.\n Otherwise @d is returned\n marshal: bool, True if marshalling class to JSON,\n False if unmarshalling JSON to class\n\nReturns:\n dict", "source": "juraj_google_style"} +{"code": "def remove_by_threshold(self, threshold=5):\n\n keys = [x for x in self._dictionary.keys()]\n for key in keys:\n if self._dictionary[key] <= threshold:\n self._dictionary.pop(key)\n self._update_dictionary()", "docstring": "Remove all words at, or below, the provided threshold\n\nArgs:\n threshold (int): The threshold at which a word is to be \\\n removed", "source": "juraj_google_style"} +{"code": "def is_closed(self):\n\n old_training_data = self.training_data\n self.training_data = {x: [] for x in self.sm_vector}\n for t in self.smi_vector:\n src_state = t[:-1]\n symbol = t[-1:]\n found = False\n for dst_state in self.sm_vector:\n if self.observation_table[dst_state] == self.observation_table[t]:\n self._add_training_data(src_state, dst_state, symbol)\n found = True\n break\n if not found:\n return False, t\n\n assert self.training_data != old_training_data, \\\n \"No update happened from previous round. The algo will loop infinetely\"\n return True, None", "docstring": "_check if the observation table is closed.\n\nArgs:\n None\n\nReturns:\n tuple (bool, str): True if the observation table is closed and false otherwise.\n If the table is not closed the escaping string is returned.", "source": "juraj_google_style"} +{"code": "def read(self, size=-1):\n\n self._check_open()\n if not self._remaining():\n return ''\n\n data_list = []\n while True:\n remaining = self._buffer.remaining()\n if size >= 0 and size < remaining:\n data_list.append(self._buffer.read(size))\n self._offset += size\n break\n else:\n size -= remaining\n self._offset += remaining\n data_list.append(self._buffer.read())\n\n if self._buffer_future is None:\n if size < 0 or size >= self._remaining():\n needs = self._remaining()\n else:\n needs = size\n data_list.extend(self._get_segments(self._offset, needs))\n self._offset += needs\n break\n\n if self._buffer_future:\n self._buffer.reset(self._buffer_future.get_result())\n self._buffer_future = None\n\n if self._buffer_future is None:\n self._request_next_buffer()\n return ''.join(data_list)", "docstring": "Read data from RAW file.\n\nArgs:\n size: Number of bytes to read as integer. Actual number of bytes\n read is always equal to size unless EOF is reached. If size is\n negative or unspecified, read the entire file.\n\nReturns:\n data read as str.\n\nRaises:\n IOError: When this buffer is closed.", "source": "juraj_google_style"} +{"code": "def has_course_mode(self, course_run_id, mode):\n\n course_modes = self.get_course_modes(course_run_id)\n return any(course_mode for course_mode in course_modes if course_mode['slug'] == mode)", "docstring": "Query the Enrollment API to see whether a course run has a given course mode available.\n\nArgs:\n course_run_id (str): The string value of the course run's unique identifier\n\nReturns:\n bool: Whether the course run has the given mode avaialble for enrollment.", "source": "juraj_google_style"} +{"code": "def get_enricher(config, metrics, **kwargs):\n\n builder = enricher.GCEEnricherBuilder(\n config, metrics, **kwargs)\n return builder.build_enricher()", "docstring": "Get a GCEEnricher client.\n\n A factory function that validates configuration and returns an\n enricher client (:interface:`gordon.interfaces.IMessageHandler`)\n provider.\n\nArgs:\n config (dict): Google Compute Engine API related configuration.\n metrics (obj): :interface:`IMetricRelay` implementation.\n kwargs (dict): Additional keyword arguments to pass to the\n enricher.\n\nReturns:\n A :class:`GCEEnricher` instance.", "source": "juraj_google_style"} +{"code": "def set_display_name(self, display_name):\n\n self.displayname = display_name\n return self.api.set_display_name(self.user_id, display_name)", "docstring": "Set this users display name.\n\nArgs:\n display_name (str): Display Name", "source": "juraj_google_style"} +{"code": "def find(self, name):\n\n collectors = self.get_collectors()\n\n for collector in collectors:\n if name.lower() == collector['name'].lower():\n self.collector_id = collector['id']\n return collector\n\n return {'status': 'No results found.'}", "docstring": "Returns a dict of collector's details if found.\n\nArgs:\n name (str): name of collector searching for", "source": "juraj_google_style"} +{"code": "def get_image_grad(net, image, class_id=None):\n\n return _get_grad(net, image, class_id, image_grad=True)", "docstring": "Get the gradients of the image.\n\n Parameters:\n ----------\n net: Block\n Network to use for visualization.\n image: NDArray\n Preprocessed image to use for visualization.\n class_id: int\n Category ID this image belongs to. If not provided,\n network's prediction will be used.", "source": "juraj_google_style"} +{"code": "def _build_colocation_attr_map(input_map, absolute_import_scope):\n\n colocation_attr_map = collections.defaultdict(_ConsistentValue)\n used_outputs_of_imported_ops = collections.defaultdict(set)\n # Collect mappings from the input_map.\n for imported_tensor_name, mapped_tensor in input_map.items():\n imported_tensor_name = absolute_import_scope + \"/\" + imported_tensor_name\n imported_op_name, imported_index = _split_tensor_name(imported_tensor_name)\n key = tf.compat.as_bytes(\"loc:@\" + imported_op_name)\n colocation_attr_map[key].Set(\n mapped_tensor.op.colocation_groups(),\n {\"reason\": \"input '%s' is substituted by '%s'\" % (\n imported_tensor_name, mapped_tensor.name)})\n used_outputs_of_imported_ops[imported_op_name].add(imported_index)\n # Add unchanged mappings for additional, non-remapped outputs of ops touched\n # by the input_map. For now, these just signal inconsistency when used.\n for imported_op_name, used_outputs in used_outputs_of_imported_ops.items():\n imported_op = tf_v1.get_default_graph().get_operation_by_name(\n imported_op_name)\n unused_outputs = set(range(len(imported_op.outputs))) - used_outputs\n if not unused_outputs: continue\n key = tf.compat.as_bytes(\"loc:@\" + imported_op_name)\n if imported_op.colocation_groups() != [key]:\n # This should never happen: state nodes are remapped fully, input nodes\n # are prevented from having colocation attributes.\n raise ValueError(\n \"Internal error: tensors from op '%s' are partially remapped in \"\n \"import but op.colocation_groups=%s cannot be captured in a \"\n \"simple rewrite rule.\" %\n (imported_op_name, imported_op.colocation_groups()))\n colocation_attr_map[key].Set(\n [key],\n {\"reason\": \"tensor '%s:%s' is not substituted by inputs\" % (\n imported_op_name,\n \",\".join(str(i) for i in sorted(unused_outputs)))})\n\n return colocation_attr_map", "docstring": "Returns a dict mapping from pre-import to post-import colocation attrs.\n\nArgs:\n input_map: as for fix_colocation_after_import.\n absolute_import_scope: as for fix_colocation_after_import.\n\nReturns:\n A dict that maps bytes `\"loc:@\" + absolute_import_scope + \"/foo\"`\n to _ConsistentValues set to the lists of bytes `[\"loc:@...\", ...]`\n according to the rewriting scheme of fix_colocation_after_import.\n In case of an inconsistent rewriting, _ConsistentValue.has_error is true.", "source": "juraj_google_style"} +{"code": "def delete(self, model_name):\n\n full_name = model_name\n if not model_name.startswith('projects/'):\n full_name = ('projects/%s/models/%s' % (self._project_id, model_name))\n response = self._api.projects().models().delete(name=full_name).execute()\n if 'name' not in response:\n raise Exception('Invalid response from service. \"name\" is not found.')\n _util.wait_for_long_running_operation(response['name'])", "docstring": "Delete a model.\n\nArgs:\n model_name: the name of the model. It can be a model full name\n (\"projects/[project_id]/models/[model_name]\") or just [model_name].", "source": "juraj_google_style"} +{"code": "def object_hook(obj):\n\n try:\n if '__type' in obj:\n obj_type = obj['__type']\n cls = getattr(cloud_inquisitor.schema, obj_type)\n if hasattr(cls, 'from_json'):\n return cls.from_json(obj)\n\n key, value = next(iter(obj.items()))\n if key == ' t':\n return tuple(value)\n elif key == ' u':\n return uuid.UUID(value)\n elif key == ' b':\n return b64decode(value)\n elif key == ' m':\n return Markup(value)\n elif key == ' d':\n return parse_date(value)\n\n return obj\n except Exception:\n log.exception('Error during data deserialization')", "docstring": "Checks to see if the `__type`-hinting field is available in the object being de-serialized. If present, and\n the class referenced has a `from_json` function it will return the generated object, else a standard dic\n will be returned\n\nArgs:\n obj: Object to be deserialized\n\nReturns:\n Deserialized object or regular python objec", "source": "juraj_google_style"} +{"code": "def check_semidefinite_positiveness(A):\n\n B = empty_like(A)\n B[:] = A\n B[diag_indices_from(B)] += sqrt(finfo(float).eps)\n try:\n cholesky(B)\n except LinAlgError:\n return False\n return True", "docstring": "Check if ``A`` is a semi-definite positive matrix.\n\nArgs:\n A (array_like): Matrix.\n\nReturns:\n bool: ``True`` if ``A`` is definite positive; ``False`` otherwise.", "source": "juraj_google_style"} +{"code": "def yaml_to_ordered_dict(stream, loader=yaml.SafeLoader):\n\n class OrderedUniqueLoader(loader):\n\n\n # keys which require no duplicate siblings.\n NO_DUPE_SIBLINGS = [\"stacks\", \"class_path\"]\n # keys which require no duplicate children keys.\n NO_DUPE_CHILDREN = [\"stacks\"]\n\n def _error_mapping_on_dupe(self, node, node_name):\n\n if isinstance(node, MappingNode):\n mapping = {}\n for n in node.value:\n a = n[0]\n b = mapping.get(a.value, None)\n if b:\n msg = \"{} mapping cannot have duplicate keys {} {}\"\n raise ConstructorError(\n msg.format(node_name, b.start_mark, a.start_mark)\n )\n mapping[a.value] = a\n\n def _validate_mapping(self, node, deep=False):\n if not isinstance(node, MappingNode):\n raise ConstructorError(\n None, None,\n \"expected a mapping node, but found %s\" % node.id,\n node.start_mark)\n mapping = OrderedDict()\n for key_node, value_node in node.value:\n key = self.construct_object(key_node, deep=deep)\n try:\n hash(key)\n except TypeError as exc:\n raise ConstructorError(\n \"while constructing a mapping\", node.start_mark,\n \"found unhashable key (%s)\" % exc, key_node.start_mark\n )\n # prevent duplicate sibling keys for certain \"keywords\".\n if key in mapping and key in self.NO_DUPE_SIBLINGS:\n msg = \"{} key cannot have duplicate siblings {} {}\"\n raise ConstructorError(\n msg.format(key, node.start_mark, key_node.start_mark)\n )\n if key in self.NO_DUPE_CHILDREN:\n # prevent duplicate children keys for this mapping.\n self._error_mapping_on_dupe(value_node, key_node.value)\n value = self.construct_object(value_node, deep=deep)\n mapping[key] = value\n return mapping\n\n def construct_mapping(self, node, deep=False):\n\n if isinstance(node, MappingNode):\n self.flatten_mapping(node)\n return self._validate_mapping(node, deep=deep)\n\n def construct_yaml_map(self, node):\n data = OrderedDict()\n yield data\n value = self.construct_mapping(node)\n data.update(value)\n\n OrderedUniqueLoader.add_constructor(\n u'tag:yaml.org,2002:map', OrderedUniqueLoader.construct_yaml_map,\n )\n return yaml.load(stream, OrderedUniqueLoader)", "docstring": "Provides yaml.load alternative with preserved dictionary order.\n\nArgs:\n stream (string): YAML string to load.\n loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe\n load.\n\nReturns:\n OrderedDict: Parsed YAML.", "source": "juraj_google_style"} +{"code": "def power(self, n):\n\n # NOTE: if a subclass can have negative or non-integer powers\n # this method should be overriden in that class.\n if not isinstance(n, (int, np.integer)) or n < 1:\n raise QiskitError(\"Can only power with positive integer powers.\")\n if self._input_dim != self._output_dim:\n raise QiskitError(\"Can only power with input_dim = output_dim.\")\n ret = self.copy()\n for _ in range(1, n):\n ret = ret.compose(self)\n return ret", "docstring": "Return the compose of a operator with itself n times.\n\nArgs:\n n (int): the number of times to compose with self (n>0).\n\nReturns:\n BaseOperator: the n-times composed operator.\n\nRaises:\n QiskitError: if the input and output dimensions of the operator\n are not equal, or the power is not a positive integer.", "source": "juraj_google_style"} +{"code": "def set_columns(self, types):\n\n if self._types:\n raise wandb.Error('TypedTable.set_columns called more than once.')\n try:\n for key, type_ in types:\n if type_ not in TYPE_TO_TYPESTRING:\n raise wandb.Error('TypedTable.set_columns received invalid type ({}) for key \"{}\".\\n Valid types: {}'.format(\n type_, key, '[%s]' % ', '.join(VALID_TYPE_NAMES)))\n except TypeError:\n raise wandb.Error(\n 'TypedTable.set_columns requires iterable of (column_name, type) pairs.')\n self._types = dict(types)\n self._output.add({\n 'typemap': {k: TYPE_TO_TYPESTRING[type_] for k, type_ in types},\n 'columns': [t[0] for t in types]})", "docstring": "Set the column types\n\nArgs:\n types: iterable of (column_name, type) pairs.", "source": "juraj_google_style"} +{"code": "def output_sector_csv(self,csv_path,file_dict_key,out_path):\n\n csv_file = csv_path + \"{0}_{1}_{2}_{3}.csv\".format(\n file_dict_key,\n self.ensemble_name,\n self.member,\n self.run_date.strftime(self.date_format))\n if exists(csv_file):\n csv_data = pd.read_csv(csv_file)\n\n if self.inds is None:\n lon_obj = csv_data.loc[:,\"Centroid_Lon\"]\n lat_obj = csv_data.loc[:,\"Centroid_Lat\"]\n\n self.inds = np.where((self.ne_lat>=lat_obj)&(self.sw_lat<=lat_obj)\\\n &(self.ne_lon>=lon_obj)&(self.sw_lon<=lon_obj))[0]\n\n if np.shape(self.inds)[0] > 0:\n csv_data = csv_data.reindex(np.array(self.inds)) \n sector_csv_filename = out_path + \"{0}_{1}_{2}_{3}.csv\".format(\n file_dict_key,\n self.ensemble_name,\n self.member,\n self.run_date.strftime(self.date_format))\n print(\"Output sector csv file \" + sector_csv_filename)\n csv_data.to_csv(sector_csv_filename,\n na_rep=\"nan\",\n float_format=\"%0.5f\",\n index=False)\n os.chmod(sector_csv_filename, 0o666)\n else:\n print('No {0} {1} sector data found'.format(self.member,\n self.run_date.strftime(\"%Y%m%d\")))\n\n else:\n print('No {0} {1} csv file found'.format(self.member,\n self.run_date.strftime(\"%Y%m%d\")))\n return", "docstring": "Segment forecast tracks to only output data contined within a\n region in the CONUS, as defined by the mapfile.\n\nArgs:\n csv_path(str): Path to the full CONUS csv file.\n file_dict_key(str): Dictionary key for the csv files,\n currently either 'track_step' or 'track_total'\n out_path (str): Path to output new segmented csv files.\n\nReturns:\n Segmented forecast tracks in a csv file.", "source": "juraj_google_style"} +{"code": "def date_to_delorean(year, month, day):\n\n return Delorean(datetime=dt(year, month, day), timezone='UTC')", "docstring": "Converts date arguments to a Delorean instance in UTC\n\nArgs:\n year: int between 1 and 9999.\n month: int between 1 and 12.\n day: int between 1 and 31.\n\nReturns:\n Delorean instance in UTC of date.", "source": "juraj_google_style"} +{"code": "def image_channel_compress_top(body_output, targets, model_hparams, vocab_size):\n\n del targets # unused arg\n with tf.variable_scope(\"image_channel_compress_modality\"):\n hidden_size = model_hparams.hidden_size\n img_len = model_hparams.img_len\n channels = 3 # RGB\n batch = common_layers.shape_list(body_output)[0]\n x = tf.layers.conv2d(\n body_output,\n hidden_size * channels,\n kernel_size=(1, 1),\n strides=(1, 1),\n padding=\"VALID\",\n activation=tf.nn.relu,\n name=\"decompress_conv\")\n x = tf.reshape(x, [batch, img_len, img_len * channels, hidden_size])\n x = common_layers.layer_preprocess(x, model_hparams)\n x = tf.layers.dense(x,\n vocab_size,\n use_bias=True,\n activation=None,\n name=\"output_conv\")\n x = tf.reshape(\n x, [batch, img_len, img_len, channels, vocab_size])\n return x", "docstring": "Transforms body output to return logits.\n\nArgs:\n body_output: Tensor of shape [batch, img_len, img_len, depth].\n targets:\n model_hparams: HParams, model hyperparmeters.\n vocab_size: int, vocabulary size.\n\nReturns:\n Tensor of shape [batch, img_len, img_len, channels, vocab_size].", "source": "juraj_google_style"} +{"code": "def FileEntryExistsByPathSpec(self, path_spec):\n\n location = getattr(path_spec, 'location', None)\n\n if (location is None or\n not location.startswith(self.LOCATION_ROOT)):\n return False\n\n if len(location) == 1:\n return True\n\n try:\n self._tar_file.getmember(location[1:])\n return True\n except KeyError:\n pass\n\n # Check if location could be a virtual directory.\n for name in iter(self._tar_file.getnames()):\n # The TAR info name does not have the leading path separator as\n # the location string does.\n if name.startswith(location[1:]):\n return True\n\n return False", "docstring": "Determines if a file entry for a path specification exists.\n\nArgs:\n path_spec (PathSpec): path specification.\n\nReturns:\n bool: True if the file entry exists.", "source": "juraj_google_style"} +{"code": "def _txn_is_in_valid_batch(self, txn_id):\n\n\n batch = self._batches_by_txn_id[txn_id]\n\n # Return whether every transaction in the batch with a\n # transaction result is valid\n return all(\n self._txn_results[sig].is_valid\n for sig in set(self._txn_results).intersection(\n (txn.header_signature for txn in batch.transactions)))", "docstring": "Returns whether the transaction is in a valid batch.\n\nArgs:\n txn_id (str): The transaction header signature.\n\nReturns:\n (bool): True if the txn's batch is valid, False otherwise.", "source": "juraj_google_style"} +{"code": "def predict(self, x, add_intercept=False):\n\n # sanity check\n if x.min() < self.start:\n raise Warning(\"x.min() < self.start\")\n if x.max() > self.end:\n raise Warning(\"x.max() > self.end\")\n\n return get_X_spline(x=x,\n knots=self.knots,\n n_bases=self.n_bases,\n spline_order=self.spline_order,\n add_intercept=add_intercept)", "docstring": "For some x, predict the bn(x) for each base\n\nArgs:\n x: np.array; Vector of dimension 1\n add_intercept: bool; should we add the intercept to the final array\n\nReturns:\n np.array, of shape (len(x), n_bases + (add_intercept))", "source": "juraj_google_style"} +{"code": "def compare_files(path1, path2):\n # type: (str, str) -> List[str]\n\n diff = difflib.ndiff(open(path1).readlines(), open(path2).readlines())\n return [x for x in diff if x[0] in ['-', '+', '?']]", "docstring": "Returns the delta between two files using -, ?, + format excluding\n lines that are the same\n\nArgs:\n path1 (str): Path to first file\n path2 (str): Path to second file\n\nReturns:\n List[str]: Delta between the two files", "source": "juraj_google_style"} +{"code": "def path_compute(\n p: tcod.path.AStar, ox: int, oy: int, dx: int, dy: int\n) -> bool:\n\n return bool(lib.TCOD_path_compute(p._path_c, ox, oy, dx, dy))", "docstring": "Find a path from (ox, oy) to (dx, dy). Return True if path is found.\n\nArgs:\n p (AStar): An AStar instance.\n ox (int): Starting x position.\n oy (int): Starting y position.\n dx (int): Destination x position.\n dy (int): Destination y position.\n\nReturns:\n bool: True if a valid path was found. Otherwise False.", "source": "juraj_google_style"} +{"code": "def update(self, **kwargs):\n\n kwargs = self._preprocess_params(kwargs)\n kwargs = self.preprocess_kwargs_before_update(kwargs)\n for key, value in kwargs.iteritems():\n cls = type(self)\n if not hasattr(cls, key) or isinstance(getattr(cls, key), property):\n continue\n if key not in self._no_overwrite_:\n setattr(self, key, value)\n if isinstance(getattr(self, key), OrderingList):\n getattr(self, key).reorder()\n elif isinstance(getattr(cls, key), AssociationProxyInstance):\n target_name = getattr(cls, key).target_collection\n target_rel = getattr(self, target_name)\n if isinstance(target_rel, OrderingList):\n target_rel.reorder()\n try:\n self.session.commit()\n return self\n except Exception as e:\n self.session.rollback()\n raise e", "docstring": "Updates an instance.\n\nArgs:\n **kwargs : Arbitrary keyword arguments. Column names are\n keywords and their new values are the values.\n\nExample:\n >>> customer.update(email=\"newemail@x.com\", name=\"new\")", "source": "juraj_google_style"} +{"code": "def request(self, command, **kwargs):\n\n payload = {\n \"command\": command,\n \"params\": dict()\n }\n for item in kwargs.keys():\n payload[\"params\"][item] = kwargs.get(item)\n\n if self.access_token:\n payload[\"params\"][\"protection_access_token\"] = self.access_token\n\n return self.send(payload)", "docstring": "Function that builds the request and returns the response from\n oxd-server\n\n Parameters:\n * **command (str):** The command that has to be sent to the oxd-server\n * ** **kwargs:** The parameters that should accompany the request\n\nReturns:\n **dict:** the returned response from oxd-server as a dictionary", "source": "juraj_google_style"} +{"code": "def to_grid_locator(latitude, longitude, precision='square'):\n\n if precision not in ('square', 'subsquare', 'extsquare'):\n raise ValueError('Unsupported precision value %r' % precision)\n\n if not -90 <= latitude <= 90:\n raise ValueError('Invalid latitude value %r' % latitude)\n if not -180 <= longitude <= 180:\n raise ValueError('Invalid longitude value %r' % longitude)\n\n latitude += 90.0\n longitude += 180.0\n\n locator = []\n\n field = int(longitude / LONGITUDE_FIELD)\n locator.append(chr(field + 65))\n longitude -= field * LONGITUDE_FIELD\n\n field = int(latitude / LATITUDE_FIELD)\n locator.append(chr(field + 65))\n latitude -= field * LATITUDE_FIELD\n\n square = int(longitude / LONGITUDE_SQUARE)\n locator.append(str(square))\n longitude -= square * LONGITUDE_SQUARE\n\n square = int(latitude / LATITUDE_SQUARE)\n locator.append(str(square))\n latitude -= square * LATITUDE_SQUARE\n\n if precision in ('subsquare', 'extsquare'):\n subsquare = int(longitude / LONGITUDE_SUBSQUARE)\n locator.append(chr(subsquare + 97))\n longitude -= subsquare * LONGITUDE_SUBSQUARE\n\n subsquare = int(latitude / LATITUDE_SUBSQUARE)\n locator.append(chr(subsquare + 97))\n latitude -= subsquare * LATITUDE_SUBSQUARE\n\n if precision == 'extsquare':\n extsquare = int(longitude / LONGITUDE_EXTSQUARE)\n locator.append(str(extsquare))\n\n extsquare = int(latitude / LATITUDE_EXTSQUARE)\n locator.append(str(extsquare))\n\n return ''.join(locator)", "docstring": "Calculate Maidenhead locator from latitude and longitude.\n\nArgs:\n latitude (float): Position's latitude\n longitude (float): Position's longitude\n precision (str): Precision with which generate locator string\n\nReturns:\n str: Maidenhead locator for latitude and longitude\n\nRaises:\n ValueError: Invalid precision identifier\n ValueError: Invalid latitude or longitude value", "source": "juraj_google_style"} +{"code": "def document(self, document_id=None):\n\n if document_id is None:\n document_id = _auto_id()\n\n child_path = self._path + (document_id,)\n return self._client.document(*child_path)", "docstring": "Create a sub-document underneath the current collection.\n\nArgs:\n document_id (Optional[str]): The document identifier\n within the current collection. If not provided, will default\n to a random 20 character string composed of digits,\n uppercase and lowercase and letters.\n\nReturns:\n ~.firestore_v1beta1.document.DocumentReference: The child\n document.", "source": "juraj_google_style"} +{"code": "def __cloudflare_list_zone_records(self, *, account, zoneID, **kwargs):\n\n done = False\n records = {}\n page = 1\n\n while not done:\n kwargs['page'] = page\n response = self.__cloudflare_request(\n account=account,\n path='/zones/{}/dns_records'.format(zoneID),\n args=kwargs\n )\n info = response['result_info']\n\n # Check if we have received all records, and if not iterate over the result set\n if 'total_pages' not in info or page >= info['total_pages']:\n done = True\n else:\n page += 1\n\n for record in response['result']:\n if record['name'] in records:\n records[record['name']]['value'] = sorted(records[record['name']]['value'] + [record['content']])\n else:\n records[record['name']] = {\n 'name': record['name'],\n 'value': sorted([record['content']]),\n 'type': record['type']\n }\n\n return list(records.values())", "docstring": "Helper function to list all records on a CloudFlare DNS Zone. Returns a `dict` containing the records and\n their information.\n\nArgs:\n account (:obj:`CloudFlareAccount`): A CloudFlare Account object\n zoneID (`int`): Internal CloudFlare ID of the DNS zone\n **kwargs (`dict`): Additional arguments to be consumed by the API endpoint\n\nReturns:\n :obj:`dict` of `str`: `dict`", "source": "juraj_google_style"} +{"code": "def _subtoken_to_tokens(self, subtokens):\n\n concatenated = \"\".join(subtokens)\n split = concatenated.split(\"_\")\n return [_unescape_token(t + \"_\") for t in split if t]", "docstring": "Converts a list of subtoken to a list of tokens.\n\nArgs:\n subtokens: a list of integers in the range [0, vocab_size)\n\nReturns:\n a list of strings.", "source": "juraj_google_style"} +{"code": "def from_file(xmu_dat_file=\"xmu.dat\", feff_inp_file=\"feff.inp\"):\n\n data = np.loadtxt(xmu_dat_file)\n header = Header.from_file(feff_inp_file)\n parameters = Tags.from_file(feff_inp_file)\n pots = Potential.pot_string_from_file(feff_inp_file)\n # site index (Note: in feff it starts from 1)\n if \"RECIPROCAL\" in parameters:\n absorbing_atom = parameters[\"TARGET\"]\n # species symbol\n else:\n absorbing_atom = pots.splitlines()[3].split()[2]\n return Xmu(header, parameters, absorbing_atom, data)", "docstring": "Get Xmu from file.\n\nArgs:\n xmu_dat_file (str): filename and path for xmu.dat\n feff_inp_file (str): filename and path of feff.inp input file\n\nReturns:\n Xmu object", "source": "juraj_google_style"} +{"code": "def set_boolean(self, option, value):\n\n if not isinstance(value, bool):\n raise TypeError(\"%s must be a boolean\" % option)\n\n self.options[option] = str(value).lower()", "docstring": "Set a boolean option.\n\nArgs:\n option (str): name of option.\n value (bool): value of the option.\n\nRaises:\n TypeError: Value must be a boolean.", "source": "juraj_google_style"} +{"code": "def OpenAndRead(relative_path='debugger-blacklist.yaml'):\n\n\n # Note: This logic follows the convention established by source-context.json\n try:\n with open(os.path.join(sys.path[0], relative_path), 'r') as f:\n return Read(f)\n except IOError:\n return None", "docstring": "Attempts to find the yaml configuration file, then read it.\n\nArgs:\n relative_path: Optional relative path override.\n\nReturns:\n A Config object if the open and read were successful, None if the file\n does not exist (which is not considered an error).\n\nRaises:\n Error (some subclass): As thrown by the called Read() function.", "source": "juraj_google_style"} +{"code": "def getVarianceCompStdErrors(self,univariance=False):\n\n RV=sp.zeros((self.P,self.n_randEffs))\n for term_i in range(self.n_randEffs):\n #RV[:,term_i] = self.getTraitCovarStdErrors(term_i).diagonal()\n RV[:,term_i] = self.getTraitCovarStdErrors(term_i)\n var = self.getVarianceComps()\n if univariance:\n RV /= var.sum(1)[:,sp.newaxis]\n return RV", "docstring": "Return the standard errors on the estimated variance components (for variance component estimates \\see getVarianceComps)\n\nArgs:\n univariance: Boolean indicator, if True variance components are normalized to sum up to 1 for each trait\n\nReturns:\n standard errors on variance components [P, n_randEffs matrix]", "source": "juraj_google_style"} +{"code": "def set_x_grid_info(self, x_low, x_high, num_x, xscale, xval_name):\n\n self._set_grid_info('x', x_low, x_high, num_x, xscale, xval_name)\n return", "docstring": "Set the grid values for x.\n\n Create information for the grid of x values.\n\nArgs:\n num_x (int): Number of points on axis.\n x_low/x_high (float): Lowest/highest value for the axis.\n xscale (str): Scale of the axis. Choices are 'log' or 'lin'.\n xval_name (str): Name representing the axis. See GenerateContainer documentation\n for options for the name.", "source": "juraj_google_style"} +{"code": "def delete_edge(self, ind_node, dep_node):\n\n graph = self.graph\n if dep_node not in graph.get(ind_node, []):\n raise KeyError(\n \"No edge exists between %s and %s.\" % (ind_node, dep_node)\n )\n graph[ind_node].remove(dep_node)", "docstring": "Delete an edge from the graph.\n\nArgs:\n ind_node (str): The independent node to delete an edge from.\n dep_node (str): The dependent node that has a dependency on the\n ind_node.\n\nRaises:\n KeyError: Raised when the edge doesn't already exist.", "source": "juraj_google_style"} +{"code": "def show_history(self, status=None, nids=None, full_history=False, metadata=False):\n\n nrows, ncols = get_terminal_size()\n\n works_done = []\n # Loop on the tasks and show the history of the work is not in works_done\n for task in self.iflat_tasks(status=status, nids=nids):\n work = task.work\n\n if work not in works_done:\n works_done.append(work)\n if work.history or full_history:\n cprint(make_banner(str(work), width=ncols, mark=\"=\"), **work.status.color_opts)\n print(work.history.to_string(metadata=metadata))\n\n if task.history or full_history:\n cprint(make_banner(str(task), width=ncols, mark=\"=\"), **task.status.color_opts)\n print(task.history.to_string(metadata=metadata))\n\n # Print the history of the flow.\n if self.history or full_history:\n cprint(make_banner(str(self), width=ncols, mark=\"=\"), **self.status.color_opts)\n print(self.history.to_string(metadata=metadata))", "docstring": "Print the history of the flow to stdout.\n\nArgs:\n status: if not None, only the tasks with this status are select\n full_history: Print full info set, including nodes with an empty history.\n nids: optional list of node identifiers used to filter the tasks.\n metadata: print history metadata (experimental)", "source": "juraj_google_style"} +{"code": "def create_sas_locator(access_token, asset_id, accesspolicy_id):\n\n path = '/Locators'\n endpoint = ''.join([ams_rest_endpoint, path])\n body = '{ \\\n\t\t\"AccessPolicyId\":\"' + accesspolicy_id + '\", \\\n\t\t\"AssetId\":\"' + asset_id + '\", \\\n\t\t\"Type\":1 \\\n\t}'\n return do_ams_post(endpoint, path, body, access_token)", "docstring": "Create Media Service SAS Locator.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n asset_id (str): Media Service Asset ID.\n accesspolicy_id (str): Media Service Access Policy ID.\n\nReturns:\n HTTP response. JSON body.", "source": "juraj_google_style"} +{"code": "def dump(self, content, filepath, indent=4):\n\n with open(filepath, 'w') as fp:\n json.dump(content, fp, indent=indent)", "docstring": "Dump settings content to filepath.\n\nArgs:\n content (str): Settings content.\n filepath (str): Settings file location.", "source": "juraj_google_style"} +{"code": "def score(self, y_true, y_pred):\n\n score = f1_score(y_true, y_pred)\n print(' - f1: {:04.2f}'.format(score * 100))\n print(classification_report(y_true, y_pred, digits=4))\n return score", "docstring": "Calculate f1 score.\n\nArgs:\n y_true (list): true sequences.\n y_pred (list): predicted sequences.\n\nReturns:\n score: f1 score.", "source": "juraj_google_style"} +{"code": "def _parse_outgoing_mail(sender, to, msgstring):\n\n global OUTBOX\n OUTBOX.append(email.message_from_string(msgstring))\n return", "docstring": "Parse an outgoing mail and put it into the OUTBOX.\n\nArgs:\n - `sender`: str\n - `to`: str\n - `msgstring`: str\n\n Return: None\n Exceptions: None", "source": "juraj_google_style"} +{"code": "def check_config(config):\n\n for section, expected_section_keys in SECTION_KEYS.items():\n section_content = config.get(section)\n if not section_content:\n raise ConfigurationError(\"Config file badly formed! Section {} is missing.\"\n .format(section))\n elif not _section_is_healthy(section_content, expected_section_keys):\n raise ConfigurationError(\"The {} section of the configuration file is badly formed!\"\n .format(section))", "docstring": "Check that all sections of the config contain the keys that they should.\n\nArgs:\n config (defaultdict): A defaultdict.\n\nRaises:\n ConfigurationError", "source": "juraj_google_style"} +{"code": "def get_catch_vars(catch):\n\n catch_re = re.compile(r'catch\\s+(\\${?\\S+}?),\\s*(\\${?\\S+}?)')\n res = catch_re.match(catch)\n if res is None:\n err = 'Catch must have format \"catch $x, $y\", got \"{0}\"'.format(catch)\n raise exceptions.YamlSyntaxError(err)\n return get_var_name(res.group(1)), get_var_name(res.group(2))", "docstring": "Returns 2-tuple with names of catch control vars, e.g. for \"catch $was_exc, $exc\"\n it returns ('was_exc', 'err').\n\nArgs:\n catch: the whole catch line\n\nReturns:\n 2-tuple with names of catch control variables\n\nRaises:\n exceptions.YamlSyntaxError if the catch line is malformed", "source": "juraj_google_style"} +{"code": "def send(self, request, stem=None):\n\n if stem is not None:\n request.url = request.url + \"/\" + stem.lstrip(\"/\")\n\n prepped = self.session.prepare_request(request)\n settings = self.session.merge_environment_settings(url=prepped.url,\n proxies={},\n stream=None,\n verify=None,\n cert=None)\n\n return self.session.send(prepped, **settings)", "docstring": "Prepare and send a request\n\nArgs:\n request: a Request object that is not yet prepared\n stem: a path to append to the root URL\n\nReturns:\n The response to the request", "source": "juraj_google_style"} +{"code": "def update_compatibility_decorators(binding, decorators):\n\n\n def _widgetDecorator(some_function):\n def wrapper(*args, **kwargs):\n ret = some_function(*args, **kwargs)\n # Modifies the returned value so we can test that the\n # decorator works.\n return \"Test: {}\".format(ret)\n # preserve docstring and name of original function\n wrapper.__doc__ = some_function.__doc__\n wrapper.__name__ = some_function.__name__\n return wrapper\n\n # Assign a different decorator for the same method name on each class\n def _mainWindowDecorator(some_function):\n def wrapper(*args, **kwargs):\n ret = some_function(*args, **kwargs)\n # Modifies the returned value so we can test that the\n # decorator works.\n return \"QMainWindow Test: {}\".format(ret)\n # preserve docstring and name of original function\n wrapper.__doc__ = some_function.__doc__\n wrapper.__name__ = some_function.__name__\n return wrapper\n decorators.setdefault(\"QWidget\", {})[\"windowTitleDecorator\"] = (\n _widgetDecorator\n )\n decorators.setdefault(\"QMainWindow\", {})[\"windowTitleDecorator\"] = (\n _mainWindowDecorator\n )", "docstring": "This optional function is called by Qt.py to modify the decorators\n applied to QtCompat namespace objects.\n\nArgs:\n binding (str): The Qt binding being wrapped by Qt.py\n decorators (dict): Maps specific decorator functions to\n QtCompat namespace methods. See Qt._build_compatibility_members\n for more info.", "source": "juraj_google_style"} +{"code": "def extraterrestrial_horizontal_radiation(self, value=9999.0):\n\n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type float '\n 'for field `extraterrestrial_horizontal_radiation`'.format(value))\n if value < 0.0:\n raise ValueError(\n 'value need to be greater or equal 0.0 '\n 'for field `extraterrestrial_horizontal_radiation`')\n\n self._extraterrestrial_horizontal_radiation = value", "docstring": "Corresponds to IDD Field `extraterrestrial_horizontal_radiation`\n\nArgs:\n value (float): value for IDD Field `extraterrestrial_horizontal_radiation`\n Unit: Wh/m2\n value >= 0.0\n Missing value: 9999.0\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def discriminator(self, x, is_training, reuse=False):\n\n hparams = self.hparams\n with tf.variable_scope(\n \"discriminator\", reuse=reuse,\n initializer=tf.random_normal_initializer(stddev=0.02)):\n batch_size, height, width = common_layers.shape_list(x)[:3]\n # Mapping x from [bs, h, w, c] to [bs, 1]\n net = tf.layers.conv2d(x, 64, (4, 4), strides=(2, 2),\n padding=\"SAME\", name=\"d_conv1\")\n # [bs, h/2, w/2, 64]\n net = lrelu(net)\n net = tf.layers.conv2d(net, 128, (4, 4), strides=(2, 2),\n padding=\"SAME\", name=\"d_conv2\")\n # [bs, h/4, w/4, 128]\n if hparams.discriminator_batchnorm:\n net = tf.layers.batch_normalization(net, training=is_training,\n momentum=0.999, name=\"d_bn2\")\n net = lrelu(net)\n size = height * width\n net = tf.reshape(net, [batch_size, size * 8]) # [bs, h * w * 8]\n net = tf.layers.dense(net, 1024, name=\"d_fc3\") # [bs, 1024]\n if hparams.discriminator_batchnorm:\n net = tf.layers.batch_normalization(net, training=is_training,\n momentum=0.999, name=\"d_bn3\")\n net = lrelu(net)\n return net", "docstring": "Discriminator architecture based on InfoGAN.\n\nArgs:\n x: input images, shape [bs, h, w, channels]\n is_training: boolean, are we in train or eval model.\n reuse: boolean, should params be re-used.\n\nReturns:\n out_logit: the output logits (before sigmoid).", "source": "juraj_google_style"} +{"code": "def top_stories(self, raw=False, limit=None):\n\n top_stories = self._get_stories('topstories', limit)\n if raw:\n top_stories = [story.raw for story in top_stories]\n return top_stories", "docstring": "Returns list of item ids of current top stories\n\nArgs:\n limit (int): specifies the number of stories to be returned.\n raw (bool): Flag to indicate whether to represent all\n objects in raw json.\n\nReturns:\n `list` object containing ids of top stories.", "source": "juraj_google_style"} +{"code": "def __call__(self, *args, **kwargs):\n\n # Update kwargs in the app definition with ones passed in at calltime\n self.kwargs.update(kwargs)\n\n if self.data_flow_kernel is None:\n dfk = DataFlowKernelLoader.dfk()\n else:\n dfk = self.data_flow_kernel\n\n app_fut = dfk.submit(wrap_error(remote_side_bash_executor), self.func, *args,\n executors=self.executors,\n fn_hash=self.func_hash,\n cache=self.cache,\n **self.kwargs)\n\n out_futs = [DataFuture(app_fut, o, tid=app_fut.tid)\n for o in kwargs.get('outputs', [])]\n app_fut._outputs = out_futs\n\n return app_fut", "docstring": "Handle the call to a Bash app.\n\nArgs:\n - Arbitrary\n\n Kwargs:\n - Arbitrary\n\nReturns:\n If outputs=[...] was a kwarg then:\n App_fut, [Data_Futures...]\n else:\n App_fut", "source": "juraj_google_style"} +{"code": "def __init__(self, resolver_context, encoding='utf-8'):\n\n super(CPIOFileSystem, self).__init__(resolver_context)\n self._cpio_archive_file = None\n self._file_object = None\n self.encoding = encoding", "docstring": "Initializes a CPIO archive file system.\n\nArgs:\n resolver_context (Context): resolver context.\n encoding (Optional[str]): file entry name encoding.", "source": "juraj_google_style"} +{"code": "def pop(self, key, default=None):\n\n return self._dictionary.pop(key.lower(), default)", "docstring": "Remove the key and return the associated value or default if not\n found\n\nArgs:\n key (str): The key to remove\n default (obj): The value to return if key is not present", "source": "juraj_google_style"} +{"code": "def add_to_file_links(self):\n # type: () -> None\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not yet initialized')\n\n if self.dr_entries.px_record is None:\n if self.ce_entries.px_record is None:\n raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')\n self.ce_entries.px_record.posix_file_links += 1\n else:\n self.dr_entries.px_record.posix_file_links += 1", "docstring": "Increment the number of POSIX file links on this entry by one.\n\n Parameters:\n None.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def event_stream(self, from_token, timeout=30000):\n\n warnings.warn(\"event_stream is deprecated. Use sync instead.\",\n DeprecationWarning)\n path = \"/events\"\n return self._send(\n \"GET\", path, query_params={\n \"timeout\": timeout,\n \"from\": from_token\n }\n )", "docstring": "Deprecated. Use sync instead.\n Performs /events\n\nArgs:\n from_token (str): The 'from' query parameter.\n timeout (int): Optional. The 'timeout' query parameter.", "source": "juraj_google_style"} +{"code": "def env_valid(env):\n\n if env not in EFConfig.ENV_LIST:\n raise ValueError(\"unknown env: {}; env must be one of: \".format(env) + \", \".join(EFConfig.ENV_LIST))\n return True", "docstring": "Given an env, determine if it's valid\n\nArgs:\n env: the env to check\n\nReturns:\n True if the env is valid\n\nRaises:\n ValueError with message if the env is not valid", "source": "juraj_google_style"} +{"code": "def updateHistory(self, activeCells, forceOutput=False):\n\n self._activeCellsHistory.append(activeCells)\n if len(self._activeCellsHistory) > self._historyLength:\n self._activeCellsHistory.pop(0)\n\n self._unionSDR = numpy.zeros(shape=(self._numInputs,))\n if (len(self._activeCellsHistory) >= self._minHistory) or forceOutput:\n for i in self._activeCellsHistory:\n self._unionSDR[i] = 1\n\n return self._unionSDR", "docstring": "Computes one cycle of the Union Pooler algorithm. Return the union SDR\n Parameters:\n ----------------------------\n @param activeCells: A list that stores indices of active cells\n\n @param forceOutput: if True, a union will be created without regard to\n minHistory", "source": "juraj_google_style"} +{"code": "def with_rank_at_most(self, rank):\n\n if self.ndims is not None and self.ndims > rank:\n raise ValueError(\"Shape %s must have rank at most %d\" % (self, rank))\n else:\n return self", "docstring": "Returns a shape based on `self` with at most the given rank.\n\nArgs:\n rank: An integer.\n\nReturns:\n A shape that is at least as specific as `self` with at most the given\n rank.\n\nRaises:\n ValueError: If `self` does not represent a shape with at most the given\n `rank`.", "source": "juraj_google_style"} +{"code": "def __init__(self, **kwargs) -> 'PygalleBaseClass': # pylint: disable=unused-argument\n\n self.options = kwargs\n self.init_properties() \\\n .set_uid() \\\n .set_class_name() \\\n .set_category()", "docstring": "Create a new instance of :class:`PygalleBaseClass`\n\n # Arguments\n\nArgs:\n kwargs:\n\n # Returns:\n PygalleBaseClass: An instance of :class:`PygalleBaseClass`", "source": "juraj_google_style"} +{"code": "def col_dtypes(df): # Does some work to reduce possibility of errors and stuff\n\n test_list = [col_isobj,col_isnum,col_isbool,col_isdt,col_iscat,col_istdelt,col_isdtz]\n deque_list = [(deque(col_method(df)),name) \\\n for col_method,name in zip(test_list,_globals.__dtype_names) if len(col_method(df))]\n type_dict = {}\n for que, name in deque_list:\n while len(que):\n type_dict[que.popleft()] = name\n return type_dict", "docstring": "Returns dictionary of datatypes in a DataFrame (uses string representation)\n Parameters:\n df - DataFrame\n The DataFrame to return the object types of\n\n Pandas datatypes are as follows:\n object,number,bool,datetime,category,timedelta,datetimetz\n This method uses queues and iterates over the columns in linear time.\n It does extra steps to ensure that no further work with numpy datatypes needs\n to be done.", "source": "juraj_google_style"} +{"code": "def retrieve_pwd_from_config(msg, cfg):\n\n msg_type = msg.__class__.__name__.lower()\n key_fmt = msg.profile + \"_\" + msg_type\n pwd = cfg.pwd[key_fmt].split(\" :: \")\n if len(pwd) == 1:\n msg.auth = pwd[0]\n else:\n msg.auth = tuple(pwd)", "docstring": "Retrieve auth from profile configuration and set in msg.auth attr.\n\nArgs:\n :msg: (Message class) an instance of a message class.\n :cfg: (jsonconfig.Config) config instance.", "source": "juraj_google_style"} +{"code": "def gremove(pattern):\n\n for item in glob.glob(pattern):\n if not remove(item):\n return False\n return True", "docstring": "Remove all file found by glob.glob(pattern).\n\nArgs:\n pattern (str): Pattern of files to remove\n\nReturns:\n bool: True if the operation is successful, False otherwise.", "source": "juraj_google_style"} +{"code": "def alt40fms(msg):\n\n d = hex2bin(data(msg))\n\n if d[13] == '0':\n return None\n\n alt = bin2int(d[14:26]) * 16 # ft\n return alt", "docstring": "Selected altitude, FMS\n\nArgs:\n msg (String): 28 bytes hexadecimal message (BDS40) string\n\nReturns:\n int: altitude in feet", "source": "juraj_google_style"} +{"code": "def CheckSupportedFormat(cls, path, check_readable_only=False):\n\n try:\n connection = sqlite3.connect(\n path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)\n\n cursor = connection.cursor()\n\n query = 'SELECT * FROM metadata'\n cursor.execute(query)\n\n metadata_values = {row[0]: row[1] for row in cursor.fetchall()}\n\n cls._CheckStorageMetadata(\n metadata_values, check_readable_only=check_readable_only)\n\n connection.close()\n result = True\n\n except (IOError, sqlite3.DatabaseError):\n result = False\n\n return result", "docstring": "Checks if the storage file format is supported.\n\nArgs:\n path (str): path to the storage file.\n check_readable_only (Optional[bool]): whether the store should only be\n checked to see if it can be read. If False, the store will be checked\n to see if it can be read and written to.\n\nReturns:\n bool: True if the format is supported.", "source": "juraj_google_style"} +{"code": "def create_bird_config_files(bird_configuration):\n\n for ip_version in bird_configuration:\n # This creates the file if it doesn't exist.\n config_file = bird_configuration[ip_version]['config_file']\n try:\n touch(config_file)\n except OSError as exc:\n raise ValueError(\"failed to create {f}:{e}\"\n .format(f=config_file, e=exc))\n if bird_configuration[ip_version]['keep_changes']:\n history_dir = os.path.join(os.path.dirname(config_file), 'history')\n try:\n os.mkdir(history_dir)\n except FileExistsError:\n pass\n except OSError as exc:\n raise ValueError(\"failed to make directory {d} for keeping a \"\n \"history of changes for {b}:{e}\"\n .format(d=history_dir, b=config_file, e=exc))\n else:\n print(\"{d} is created\".format(d=history_dir))", "docstring": "Create bird configuration files per IP version.\n\n Creates bird configuration files if they don't exist. It also creates the\n directories where we store the history of changes, if this functionality is\n enabled.\n\nArgs:\n bird_configuration (dict): A dictionary with settings for bird.\n\nReturns:\n None\n\nRaises:\n ValueError if we can't create bird configuration files and the\n directory to store the history of changes in bird configuration file.", "source": "juraj_google_style"} +{"code": "def choose_template(self, template):\n\n n1 = int(template)/10\n n2 = int(template)%10\n self.send('^TS'+'0'+str(n1)+str(n2))", "docstring": "Choose a template\n\nArgs:\n template: String, choose which template you would like.\n\nReturns:\n None\n\nRaises:\n None", "source": "juraj_google_style"} +{"code": "def parse_individual(sample):\n\n ind_info = {}\n if 'sample_id' not in sample:\n raise PedigreeError(\"One sample is missing 'sample_id'\")\n sample_id = sample['sample_id']\n # Check the sex\n if 'sex' not in sample:\n raise PedigreeError(\"Sample %s is missing 'sex'\" % sample_id)\n sex = sample['sex']\n if sex not in REV_SEX_MAP:\n log.warning(\"'sex' is only allowed to have values from {}\"\n .format(', '.join(list(REV_SEX_MAP.keys()))))\n raise PedigreeError(\"Individual %s has wrong formated sex\" % sample_id)\n\n # Check the phenotype\n if 'phenotype' not in sample:\n raise PedigreeError(\"Sample %s is missing 'phenotype'\"\n % sample_id)\n phenotype = sample['phenotype']\n if phenotype not in REV_PHENOTYPE_MAP:\n log.warning(\"'phenotype' is only allowed to have values from {}\"\n .format(', '.join(list(REV_PHENOTYPE_MAP.keys()))))\n raise PedigreeError(\"Individual %s has wrong formated phenotype\" % sample_id)\n\n ind_info['individual_id'] = sample_id\n ind_info['display_name'] = sample.get('sample_name', sample['sample_id'])\n\n ind_info['sex'] = sex\n ind_info['phenotype'] = phenotype\n\n ind_info['father'] = sample.get('father')\n ind_info['mother'] = sample.get('mother')\n\n ind_info['confirmed_parent'] = sample.get('confirmed_parent')\n ind_info['confirmed_sex'] = sample.get('confirmed_sex')\n ind_info['predicted_ancestry'] = sample.get('predicted_ancestry')\n\n bam_file = sample.get('bam_path')\n if bam_file:\n ind_info['bam_file'] = bam_file\n\n mt_bam = sample.get('mt_bam')\n if mt_bam:\n ind_info['mt_bam'] = mt_bam\n\n analysis_type = sample.get('analysis_type')\n if analysis_type:\n ind_info['analysis_type'] = analysis_type\n\n ind_info['capture_kits'] = ([sample.get('capture_kit')]\n if 'capture_kit' in sample else [])\n\n # Path to downloadable vcf2cytosure file\n vcf2cytosure = sample.get('vcf2cytosure')\n if vcf2cytosure:\n ind_info['vcf2cytosure'] = vcf2cytosure\n\n # Cancer specific values\n tumor_type = sample.get('tumor_type')\n if tumor_type:\n ind_info['tumor_type'] = tumor_type\n\n tumor_mutational_burden = sample.get('tmb')\n if tumor_mutational_burden:\n ind_info['tmb'] = tumor_mutational_burden\n\n msi = sample.get('msi')\n if msi:\n ind_info['msi'] = msi\n\n tumor_purity = sample.get('tumor_purity')\n if tumor_purity:\n ind_info['tumor_purity'] = tumor_purity\n\n return ind_info", "docstring": "Parse individual information\n\nArgs:\n sample (dict)\n\nReturns:\n {\n 'individual_id': str,\n 'father': str,\n 'mother': str,\n 'display_name': str,\n 'sex': str,\n 'phenotype': str,\n 'bam_file': str,\n 'vcf2cytosure': str,\n 'analysis_type': str,\n 'capture_kits': list(str),\n }", "source": "juraj_google_style"} +{"code": "def set_title(title, mode=0):\n\n if os.name == 'nt':\n from .windows import set_title\n return set_title(title)\n else:\n if _CHOSEN_PALETTE:\n text = f'{OSC}{_title_mode_map.get(mode, mode)};{title}{BEL}'\n _write(text)\n return text", "docstring": "Set the title of the terminal window/tab/icon.\n\nArgs:\n title: str\n mode: | 0 | 'both' - Set icon/taskbar and window/tab title\n | 1 | 'icon' - Set only icon/taskbar title\n | 2 | 'title' - Set only window/tab title", "source": "juraj_google_style"} +{"code": "def execute_edit(args, root_dir=None):\n\n # Get editor\n EDITOR = os.environ.get('EDITOR', 'vim')\n # Get command from server\n key = args['key']\n status = command_factory('status')({}, root_dir=root_dir)\n\n # Check if queue is not empty, the entry exists and is queued or stashed\n if not isinstance(status['data'], str) and key in status['data']:\n if status['data'][key]['status'] in ['queued', 'stashed']:\n command = status['data'][key]['command']\n else:\n print(\"Entry is not 'queued' or 'stashed'\")\n sys.exit(1)\n else:\n print('No entry with this key')\n sys.exit(1)\n\n with tempfile.NamedTemporaryFile(suffix=\".tmp\") as tf:\n tf.write(command.encode('utf-8'))\n tf.flush()\n call([EDITOR, tf.name])\n\n # do the parsing with `tf` using regular File operations.\n # for instance:\n tf.seek(0)\n edited_command = tf.read().decode('utf-8')\n\n print_command_factory('edit')({\n 'key': key,\n 'command': edited_command,\n }, root_dir=root_dir)", "docstring": "Edit a existing queue command in the daemon.\n\nArgs:\n args['key'] int: The key of the queue entry to be edited\n root_dir (string): The path to the root directory the daemon is running in.", "source": "juraj_google_style"} +{"code": "def send_message(self, message):\n\n try:\n if _message_test_port is not None:\n _message_test_port.sent.append(message)\n yield message.send(self)\n except (WebSocketClosedError, StreamClosedError): # Tornado 4.x may raise StreamClosedError\n # on_close() is / will be called anyway\n log.warning(\"Failed sending message as connection was closed\")\n raise gen.Return(None)", "docstring": "Send a Bokeh Server protocol message to the connected client.\n\nArgs:\n message (Message) : a message to send", "source": "juraj_google_style"} +{"code": "def subscribe(self, devices_to_bind=[]):\n\n if self.entity_api_key == \"\":\n return {'status': 'failure', 'response': 'No API key found in request'}\n self.bind(devices_to_bind)\n loop = asyncio.new_event_loop()\n t1 = threading.Thread(target=self.start_subscribe_worker, args=(loop,))\n t1.daemon = True\n t1.start()", "docstring": "This function allows an entity to subscribe for data from the devices specified in the bind operation. It\n creates a thread with an event loop to manager the tasks created in start_subscribe_worker.\n\nArgs:\n devices_to_bind (list): an array of devices to listen to", "source": "juraj_google_style"} +{"code": "def cherry_pick(self, branch, **kwargs):\n\n path = '%s/%s/cherry_pick' % (self.manager.path, self.get_id())\n post_data = {'branch': branch}\n self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)", "docstring": "Cherry-pick a commit into a branch.\n\nArgs:\n branch (str): Name of target branch\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabCherryPickError: If the cherry-pick could not be performed", "source": "juraj_google_style"} +{"code": "def restore_state(self, state):\n\n\n state_name = state.get('state_name')\n state_version = state.get('state_version')\n\n if state_name != self.STATE_NAME or state_version != self.STATE_VERSION:\n raise ArgumentError(\"Invalid emulated device state name or version\", found=(state_name, state_version),\n expected=(self.STATE_NAME, self.STATE_VERSION))\n\n def _background_restore():\n # Restore the state of all of the tiles\n super(ReferenceDevice, self).restore_state(state)\n\n self.reset_count = state.get('reset_count', 0)\n self.script = base64.b64decode(state.get('received_script'))\n\n self.synchronize_task(_background_restore)", "docstring": "Restore the current state of this emulated device.\n\n Note that restore_state happens synchronously in the emulation thread\n to avoid any race conditions with accessing data members and ensure a\n consistent atomic restoration process.\n\n This method will block while the background restore happens.\n\nArgs:\n state (dict): A previously dumped state produced by dump_state.", "source": "juraj_google_style"} +{"code": "def get_graph(self, run_key, device_name, debug=False):\n\n return self.get_graphs(run_key, debug=debug).get(device_name, None)", "docstring": "Get the runtime GraphDef proto associated with a run key and a device.\n\nArgs:\n run_key: A Session.run kay.\n device_name: Name of the device in question.\n debug: Whether the debugger-decoratedgraph is to be retrieved.\n\nReturns:\n A `GraphDef` proto.", "source": "juraj_google_style"} +{"code": "def _process_counter_example(self, mma, w_string):\n\n if len(w_string) == 1:\n self.observation_table.smi_vector.append(w_string)\n for exp in self.observation_table.em_vector:\n self._fill_table_entry(w_string, exp)\n\n diff = len(w_string)\n same = 0\n membership_answer = self._membership_query(w_string)\n while True:\n i = (same + diff) / 2\n access_string = self._run_in_hypothesis(mma, w_string, i)\n if membership_answer != self._membership_query(access_string + w_string[i:]):\n diff = i\n else:\n same = i\n if diff - same == 1:\n break\n\n # First check if the transition is part of our training data.\n access_string = self._run_in_hypothesis(mma, w_string, diff - 1)\n wrong_transition = access_string + w_string[diff - 1]\n if wrong_transition not in self.observation_table.smi_vector:\n # If transition is not part of our training data add s_ib to Smi and\n # return to checking table closedness.\n self.observation_table.smi_vector.append(wrong_transition)\n for exp in self.observation_table.em_vector:\n self._fill_table_entry(wrong_transition, exp)\n return\n\n # This point presents a tradeoff between equivalence and membership\n # queries. If the transition in the counterexample'input_string breakpoint is not\n # part of our current training data (i.e. s_ib is not part of our Smi\n # set), then we assume a wrong transition and return to checking table\n # closure by adding s_ib to our training data. This saves a number of\n # membership queries since we don't add a row in our table unless\n # absolutely necessary. Notice that even if Equivalence queries are\n # expensive in general caching the result will be able to discover that\n # this iteration required a new state in the next equivalence query.\n\n exp = w_string[diff:]\n self.observation_table.em_vector.append(exp)\n for row in self.observation_table.sm_vector + self.observation_table.smi_vector:\n self._fill_table_entry(row, exp)", "docstring": "Process a counterexample in the Rivest-Schapire way.\n\nArgs:\n mma (DFA): The hypothesis automaton\n w_string (str): The examined string to be consumed\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def docx_text_from_xml_node(node: ElementTree.Element,\n level: int,\n config: TextProcessingConfig) -> str:\n\n text = ''\n # log.debug(\"Level {}, tag {}\", level, node.tag)\n if node.tag == DOCX_TEXT:\n text += node.text or ''\n elif node.tag == DOCX_TAB:\n text += '\\t'\n elif node.tag in DOCX_NEWLINES:\n text += '\\n'\n elif node.tag == DOCX_NEWPARA:\n text += '\\n\\n'\n\n if node.tag == DOCX_TABLE:\n text += '\\n\\n' + docx_table_from_xml_node(node, level, config)\n else:\n for child in node:\n text += docx_text_from_xml_node(child, level + 1, config)\n return text", "docstring": "Returns text from an XML node within a DOCX file.\n\nArgs:\n node: an XML node\n level: current level in XML hierarchy (used for recursion; start level\n is 0)\n config: :class:`TextProcessingConfig` control object\n\nReturns:\n contents as a string", "source": "juraj_google_style"} +{"code": "def idle(self, stop_signals: tuple = (SIGINT, SIGTERM, SIGABRT)):\n\n\n def signal_handler(*args):\n self.is_idle = False\n\n for s in stop_signals:\n signal(s, signal_handler)\n\n self.is_idle = True\n\n while self.is_idle:\n time.sleep(1)\n\n self.stop()", "docstring": "Blocks the program execution until one of the signals are received,\n then gently stop the Client by closing the underlying connection.\n\nArgs:\n stop_signals (``tuple``, *optional*):\n Iterable containing signals the signal handler will listen to.\n Defaults to (SIGINT, SIGTERM, SIGABRT).", "source": "juraj_google_style"} +{"code": "def validate_source_dir(script, directory):\n\n if directory:\n if not os.path.isfile(os.path.join(directory, script)):\n raise ValueError('No file named \"{}\" was found in directory \"{}\".'.format(script, directory))\n\n return True", "docstring": "Validate that the source directory exists and it contains the user script\n\nArgs:\n script (str): Script filename.\n directory (str): Directory containing the source file.\n\nRaises:\n ValueError: If ``directory`` does not exist, is not a directory, or does not contain ``script``.", "source": "juraj_google_style"} +{"code": "def compute_cyclomatic_complexity(function):\n\n # from https://en.wikipedia.org/wiki/Cyclomatic_complexity\n # M = E - N + 2P\n # where M is the complexity\n # E number of edges\n # N number of nodes\n # P number of connected components\n\n E = compute_number_edges(function)\n N = len(function.nodes)\n P = len(compute_strongly_connected_components(function))\n return E - N + 2 * P", "docstring": "Compute the cyclomatic complexity of a function\n\nArgs:\n function (core.declarations.function.Function)\n\nReturns:\n int", "source": "juraj_google_style"} +{"code": "def __init__(self, validate_args=False, name=\"absolute_value\"):\n\n self._graph_parents = []\n self._name = name\n\n with self._name_scope(\"init\"):\n super(AbsoluteValue, self).__init__(\n forward_min_event_ndims=0,\n validate_args=validate_args,\n name=name)", "docstring": "Instantiates the `AbsoluteValue` bijector.\n\nArgs:\n validate_args: Python `bool` indicating whether arguments should be\n checked for correctness, in particular whether inputs to `inverse` and\n `inverse_log_det_jacobian` are non-negative.\n name: Python `str` name given to ops managed by this object.", "source": "juraj_google_style"} +{"code": "def merge(self, workdir, gswfk_file, dfpt_files, gkk_files, out_gkk, binascii=0):\n\n raise NotImplementedError(\"This method should be tested\")\n #out_gkk = out_gkk if cwd is None else os.path.join(os.path.abspath(cwd), out_gkk)\n\n # We work with absolute paths.\n gswfk_file = os.path.absath(gswfk_file)\n dfpt_files = [os.path.abspath(s) for s in list_strings(dfpt_files)]\n gkk_files = [os.path.abspath(s) for s in list_strings(gkk_files)]\n\n print(\"Will merge %d 1WF files, %d GKK file in output %s\" %\n (len(dfpt_files), len(gkk_files), out_gkk))\n\n if self.verbose:\n for i, f in enumerate(dfpt_files): print(\" [%d] 1WF %s\" % (i, f))\n for i, f in enumerate(gkk_files): print(\" [%d] GKK %s\" % (i, f))\n\n self.stdin_fname, self.stdout_fname, self.stderr_fname = \\\n map(os.path.join, 3 * [workdir], [\"mrggkk.stdin\", \"mrggkk.stdout\", \"mrggkk.stderr\"])\n\n inp = StringIO()\n inp.write(out_gkk + \"\\n\") # Name of the output file\n inp.write(str(binascii) + \"\\n\") # Integer flag: 0 --> binary output, 1 --> ascii formatted output\n inp.write(gswfk_file + \"\\n\") # Name of the groud state wavefunction file WF\n\n #dims = len(dfpt_files, gkk_files, ?)\n dims = \" \".join([str(d) for d in dims])\n inp.write(dims + \"\\n\") # Number of 1WF, of GKK files, and number of 1WF files in all the GKK files\n\n # Names of the 1WF files...\n for fname in dfpt_files:\n inp.write(fname + \"\\n\")\n\n # Names of the GKK files...\n for fname in gkk_files:\n inp.write(fname + \"\\n\")\n\n self.stdin_data = [s for s in inp.getvalue()]\n\n with open(self.stdin_fname, \"w\") as fh:\n fh.writelines(self.stdin_data)\n # Force OS to write data to disk.\n fh.flush()\n os.fsync(fh.fileno())\n\n self.execute(workdir)\n\n return out_gkk", "docstring": "Merge GGK files, return the absolute path of the new database.\n\nArgs:\n gswfk_file: Ground-state WFK filename\n dfpt_files: List of 1WFK files to merge.\n gkk_files: List of GKK files to merge.\n out_gkk: Name of the output GKK file\n binascii: Integer flat. 0 --> binary output, 1 --> ascii formatted output", "source": "juraj_google_style"} +{"code": "def init_config_json(config_file):\n\n json_data = None\n try:\n if os.path.exists(config_file):\n #Load the config file\n\n with open(config_file) as json_file:\n json_data = json.load(json_file)\n return unicode_convert(json_data)\n else:\n return None\n except:\n line, filename, synerror = trace()\n raise ArcRestHelperError({\n \"function\": \"init_config_json\",\n \"line\": line,\n \"filename\": filename,\n \"synerror\": synerror,\n }\n )\n finally:\n json_data = None\n\n del json_data\n\n gc.collect()", "docstring": "Deserializes a JSON configuration file.\n\nArgs:\n config_file (str): The path to the JSON file.\n\nReturns:\n dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.", "source": "juraj_google_style"} +{"code": "def get_frame(self, index=None, onset=None):\n\n if onset:\n index = int(onset * self.fps)\n\n return super(VideoStim, self).get_frame(index)", "docstring": "Overrides the default behavior by giving access to the onset\n argument.\n\nArgs:\n index (int): Positional index of the desired frame.\n onset (float): Onset (in seconds) of the desired frame.", "source": "juraj_google_style"} +{"code": "def get_scan_plot(self, coords=None):\n\n from pymatgen.util.plotting import pretty_plot\n\n plt = pretty_plot(12, 8)\n\n d = self.read_scan()\n\n if coords and coords in d[\"coords\"]:\n x = d[\"coords\"][coords]\n plt.xlabel(coords)\n else:\n x = range(len(d[\"energies\"]))\n plt.xlabel(\"points\")\n\n plt.ylabel(\"Energy (eV)\")\n\n e_min = min(d[\"energies\"])\n y = [(e - e_min) * Ha_to_eV for e in d[\"energies\"]]\n\n plt.plot(x, y, \"ro--\")\n return plt", "docstring": "Get a matplotlib plot of the potential energy surface.\n\nArgs:\n coords: internal coordinate name to use as abcissa.", "source": "juraj_google_style"} +{"code": "def get(self, block_id):\n\n\n pool = current_app.config['bigchain_pool']\n\n with pool() as bigchain:\n block = bigchain.get_block(block_id=block_id)\n\n if not block:\n return make_error(404)\n\n return block", "docstring": "API endpoint to get details about a block.\n\nArgs:\n block_id (str): the id of the block.\n\nReturns:\n A JSON string containing the data about the block.", "source": "juraj_google_style"} +{"code": "def AddBlob(self, blob_id, length):\n\n if self.finalized and length > 0:\n raise IOError(\"Can't add blobs to finalized BlobImage\")\n\n self.content_dirty = True\n self.index.seek(0, 2)\n self.index.write(blob_id.AsBytes())\n self.size += length\n\n if length < self.chunksize:\n self.finalized = True", "docstring": "Add another blob to this image using its hash.\n\n Once a blob is added that is smaller than the chunksize we finalize the\n file, since handling adding more blobs makes the code much more complex.\n\nArgs:\n blob_id: rdf_objects.BlobID object.\n length: int length of blob\n\nRaises:\n IOError: if blob has been finalized.", "source": "juraj_google_style"} +{"code": "def facade(projectmainfn, **kwargs):\n # (Callable[[None], None], Any) -> None\n\n\n #\n # Setting up configuration\n #\n site_url = Configuration._create(**kwargs)\n\n logger.info('--------------------------------------------------')\n logger.info('> Using HDX Python API Library %s' % Configuration.apiversion)\n logger.info('> HDX Site: %s' % site_url)\n\n UserAgent.user_agent = Configuration.read().user_agent\n\n projectmainfn()", "docstring": "Facade to simplify project setup that calls project main function\n\nArgs:\n projectmainfn ((None) -> None): main function of project\n **kwargs: configuration parameters to pass to HDX Configuration class\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def _log(self, utterance: Any, direction: str, dialog_id: Optional[Hashable]=None):\n\n if isinstance(utterance, str):\n pass\n elif isinstance(utterance, RichMessage):\n utterance = utterance.json()\n elif isinstance(utterance, (list, dict)):\n utterance = jsonify_data(utterance)\n else:\n utterance = str(utterance)\n\n dialog_id = str(dialog_id) if not isinstance(dialog_id, str) else dialog_id\n\n if self.log_file.tell() >= self.log_max_size * 1024:\n self.log_file.close()\n self.log_file = self._get_log_file()\n else:\n try:\n log_msg = {}\n log_msg['timestamp'] = self._get_timestamp_utc_str()\n log_msg['dialog_id'] = dialog_id\n log_msg['direction'] = direction\n log_msg['message'] = utterance\n log_str = json.dumps(log_msg, ensure_ascii=self.config['ensure_ascii'])\n self.log_file.write(f'{log_str}\\n')\n except IOError:\n log.error('Failed to write dialog log.')", "docstring": "Logs single dialog utterance to current dialog log file.\n\nArgs:\n utterance: Dialog utterance.\n direction: 'in' or 'out' utterance direction.\n dialog_id: Dialog ID.", "source": "juraj_google_style"} +{"code": "def load_data_table(table_name, meta_file, meta):\n\n for table in meta['tables']:\n if table['name'] == table_name:\n prefix = os.path.dirname(meta_file)\n relative_path = os.path.join(prefix, meta['path'], table['path'])\n return pd.read_csv(relative_path), table", "docstring": "Return the contents and metadata of a given table.\n\nArgs:\n table_name(str): Name of the table.\n meta_file(str): Path to the meta.json file.\n meta(dict): Contents of meta.json.\n\nReturns:\n tuple(pandas.DataFrame, dict)", "source": "juraj_google_style"} +{"code": "def add_layer(self, formula='', thickness=np.NaN, density=np.NaN):\n\n if formula == '':\n return\n\n _new_stack = _utilities.formula_to_dictionary(formula=formula,\n thickness=thickness,\n density=density,\n database=self.database)\n # check if density has been defined\n self.__lock_density_if_defined(stack=_new_stack)\n\n new_stack = self.__update_stack_with_isotopes_infos(stack=_new_stack)\n self.stack = {**self.stack, **new_stack}\n\n # calculate stack_sigma, layer density, atoms_per_cm3 ...\n self.__math_on_stack()", "docstring": "provide another way to define the layers (stack)\n\n Parameters:\n ===========\n formula: string\n ex: 'CoAg2'\n ex: 'Al'\n thickness: float (in mm)\n density: float (g/cm3)", "source": "juraj_google_style"} +{"code": "def compress_pdf(filepath, output_path, ghostscript_binary):\n\n if not filepath.endswith(PDF_EXTENSION):\n raise ValueError(\"Filename must end with .pdf!\\n%s does not.\" % filepath)\n try:\n file_size = os.stat(filepath).st_size\n if file_size < FILE_SIZE_LOWER_LIMIT:\n LOGGER.info(NOT_COMPRESSING.format(filepath, file_size, FILE_SIZE_LOWER_LIMIT))\n process = subprocess.Popen(['cp', filepath, output_path])\n else:\n LOGGER.info(COMPRESSING.format(filepath))\n process = subprocess.Popen(\n [ghostscript_binary, \"-sDEVICE=pdfwrite\",\n \"-dCompatabilityLevel=1.4\", \"-dPDFSETTINGS=/ebook\",\n \"-dNOPAUSE\", \"-dQUIET\", \"-dBATCH\",\n \"-sOutputFile=%s\" % output_path, filepath]\n )\n except FileNotFoundError:\n msg = GS_NOT_INSTALLED.format(ghostscript_binary)\n raise FileNotFoundError(msg)\n process.communicate()\n LOGGER.info(FILE_DONE.format(output_path))", "docstring": "Compress a single PDF file.\n\nArgs:\n filepath (str): Path to the PDF file.\n output_path (str): Output path.\n ghostscript_binary (str): Name/alias of the Ghostscript binary.\n\nRaises:\n ValueError\n FileNotFoundError", "source": "juraj_google_style"} +{"code": "def __init__(self, hsObj):\n\n self._hsObj = hsObj\n\n # This list holds all the results we have so far on every model. In\n # addition, we maintain mutliple other data structures which provide\n # faster access into portions of this list\n self._allResults = []\n\n # Models that completed with errors and all completed.\n # These are used to determine when we should abort because of too many\n # errors\n self._errModels = set()\n self._numErrModels = 0\n self._completedModels = set()\n self._numCompletedModels = 0\n\n # Map of the model ID to index of result in _allResults\n self._modelIDToIdx = dict()\n\n # The global best result on the optimize metric so far, and the model ID\n self._bestResult = numpy.inf\n self._bestModelID = None\n\n # This is a dict of dicts. The top level dict has the swarmId as the key.\n # Each entry is a dict of genIdx: (modelId, errScore) entries.\n self._swarmBestOverall = dict()\n\n # For each swarm, we keep track of how many particles we have per generation\n # The key is the swarmId, the value is a list of the number of particles\n # at each generation\n self._swarmNumParticlesPerGeneration = dict()\n\n # The following variables are used to support the\n # getMaturedSwarmGenerations() call.\n #\n # The _modifiedSwarmGens set contains the set of (swarmId, genIdx) tuples\n # that have had results reported to them since the last time\n # getMaturedSwarmGenerations() was called.\n #\n # The maturedSwarmGens contains (swarmId,genIdx) tuples, one for each\n # swarm generation index which we have already detected has matured. This\n # insures that if by chance we get a rogue report from a model in a swarm\n # generation index which we have already assumed was matured that we won't\n # report on it again.\n self._modifiedSwarmGens = set()\n self._maturedSwarmGens = set()\n\n # For each particle, we keep track of it's best score (across all\n # generations) and the position it was at when it got that score. The keys\n # in this dict are the particleId, the values are (bestResult, position),\n # where position is a dict with varName:position items in it.\n self._particleBest = dict()\n\n # For each particle, we keep track of it's latest generation index.\n self._particleLatestGenIdx = dict()\n\n # For each swarm, we keep track of which models are in it. The key\n # is the swarmId, the value is a list of indexes into self._allResults.\n self._swarmIdToIndexes = dict()\n\n # ParamsHash to index mapping\n self._paramsHashToIndexes = dict()", "docstring": "Instantiate our results database\n\n Parameters:\n --------------------------------------------------------------------\n hsObj: Reference to the HypersearchV2 instance", "source": "juraj_google_style"} +{"code": "def _wrap_result(self, response):\n\n if isinstance(response, int):\n response = self._wrap_response(response)\n\n return HandlerResult(\n status=HandlerStatus.RETURN,\n message_out=self._response_proto(**response),\n message_type=self._response_type)", "docstring": "Wraps child's response in a HandlerResult to be sent back to client.\n\nArgs:\n response (enum or dict): Either an integer status enum, or a dict\n of attributes to be added to the protobuf response.", "source": "juraj_google_style"} +{"code": "def minute(self, value=None):\n\n if value is not None:\n try:\n value = int(value)\n except ValueError:\n raise ValueError('value {} need to be of type int '\n 'for field `minute`'.format(value))\n if value < 0:\n raise ValueError('value need to be greater or equal 0 '\n 'for field `minute`')\n if value > 60:\n raise ValueError('value need to be smaller 60 '\n 'for field `minute`')\n\n self._minute = value", "docstring": "Corresponds to IDD Field `minute`\n\nArgs:\n value (int): value for IDD Field `minute`\n value >= 0\n value <= 60\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def lex(self, text):\n\n pos = 0\n while text:\n token_class, match = self.tokens.get_token(text)\n if token_class is not None:\n matched_text = text[match.start():match.end()]\n yield token_class(matched_text)\n text = text[match.end():]\n pos += match.end()\n elif text[0] in self.blank_chars:\n text = text[1:]\n pos += 1\n else:\n raise LexerError(\n 'Invalid character %s in %s' % (text[0], text),\n position=pos)\n\n yield self.end_token()", "docstring": "Split self.text into a list of tokens.\n\nArgs:\n text (str): text to parse\n\nYields:\n Token: the tokens generated from the given text.", "source": "juraj_google_style"} +{"code": "def event(self, name, owner=None, **kwargs):\n\n return Event(self.tcex, name, owner=owner, **kwargs)", "docstring": "Create the Event TI object.\n\nArgs:\n name:\n **kwargs:\n\n Return:", "source": "juraj_google_style"} +{"code": "def sia(transition, direction=Direction.BIDIRECTIONAL):\n\n validate.direction(direction, allow_bi=True)\n log.info(\"Calculating big-alpha for %s...\", transition)\n\n if not transition:\n log.info('Transition %s is empty; returning null SIA '\n 'immediately.', transition)\n return _null_ac_sia(transition, direction)\n\n if not connectivity.is_weak(transition.network.cm,\n transition.node_indices):\n log.info('%s is not strongly/weakly connected; returning null SIA '\n 'immediately.', transition)\n return _null_ac_sia(transition, direction)\n\n log.debug(\"Finding unpartitioned account...\")\n unpartitioned_account = account(transition, direction)\n log.debug(\"Found unpartitioned account.\")\n\n if not unpartitioned_account:\n log.info('Empty unpartitioned account; returning null AC SIA '\n 'immediately.')\n return _null_ac_sia(transition, direction)\n\n cuts = _get_cuts(transition, direction)\n engine = ComputeACSystemIrreducibility(\n cuts, transition, direction, unpartitioned_account)\n result = engine.run_sequential()\n log.info(\"Finished calculating big-ac-phi data for %s.\", transition)\n log.debug(\"RESULT: \\n%s\", result)\n return result", "docstring": "Return the minimal information partition of a transition in a specific\n direction.\n\nArgs:\n transition (Transition): The candidate system.\n\nReturns:\n AcSystemIrreducibilityAnalysis: A nested structure containing all the\n data from the intermediate calculations. The top level contains the\n basic irreducibility information for the given subsystem.", "source": "juraj_google_style"} +{"code": "def put(self, key, value):\n\n key = self._service_key(key)\n self._service_ops['put'](key, value)", "docstring": "Stores the object `value` named by `key` in `service`.\n\nArgs:\n key: Key naming `value`.\n value: the object to store.", "source": "juraj_google_style"} +{"code": "def validate_term(usr, pwd, hpo_term):\n\n\n result = True\n try:\n for line in query(usr, pwd, hpo_term):\n pass\n except RuntimeError as err:\n raise err\n\n return result", "docstring": "Validate if the HPO term exists.\n\n Check if there are any result when querying phenomizer.\n\nArgs:\n usr (str): A username for phenomizer\n pwd (str): A password for phenomizer\n hpo_term (string): Represents the hpo term\n\nReturns:\n result (boolean): True if term exists, False otherwise", "source": "juraj_google_style"} +{"code": "def wait_for_conns(self, timeout=60, start_delay=0, interval=5, **kwargs):\n\n log.setLevel(kwargs.get('log_level',self.log_level))\n timestamp = time.time()\n last_check = time.time() + start_delay - interval\n last_delay_notification = time.time() - interval\n timeout += 1\n failing = True\n up_conns = {}\n # loop until the server is up or the timeout is reached\n while((time.time()-timestamp) < timeout) and failing:\n # if delaying, the start of the check, print waiting to start\n if start_delay > 0 and time.time() - timestamp < start_delay \\\n and (time.time()-last_delay_notification) > 5:\n print(\"Delaying server status check until %ss. Current time: %ss\" \\\n % (start_delay, int(time.time() - timestamp)))\n last_delay_notification = time.time()\n # check status at the specified 'interval' until the server is up\n first_check = True\n while ((time.time()-last_check) > interval) and failing:\n msg = [\"\\tChecked status of servers at %ss\" % \\\n int((time.time()-timestamp)),\n \"\\t** CONNECTION STATUS:\"]\n last_check = time.time()\n failing = self.failing\n new_up = (self.active.keys() - failing.keys()) - \\\n up_conns.keys()\n msg += [\"\\t\\t UP - %s: %s\" % (key, self.conns[key])\n for key in new_up]\n up_conns.update({key: self.conns[key] for key in new_up})\n msg.append(\"\\t*** '%s' connection(s) up\" % len(up_conns))\n msg += [\"\\t\\t FAILING - %s: %s\" % (key, self.conns[key])\n for key in failing]\n log.info(\"** CONNECTION STATUS:\\n%s\", \"\\n\".join(msg))\n if not failing:\n log.info(\"**** Servers up at %ss\" % \\\n int((time.time()-timestamp)))\n break\n if failing:\n raise RuntimeError(\"Unable to establish connection(s): \",\n failing)\n for conn in up_conns.values():\n conn.delay_check_pass()\n return not failing", "docstring": "delays unitil all connections are working\n\nArgs:\n timeout: number of seconds to try to connecting. Error out when\n timeout is reached\n start_delay: number of seconds to wait before checking status\n interval: number of seconds to wait between checks", "source": "juraj_google_style"} +{"code": "def mpim_history(self, *, channel: str, **kwargs) -> SlackResponse:\n\n kwargs.update({\"channel\": channel})\n return self.api_call(\"mpim.history\", http_verb=\"GET\", params=kwargs)", "docstring": "Fetches history of messages and events from a multiparty direct message.\n\nArgs:\n channel (str): Multiparty direct message to fetch history for. e.g. 'G1234567890'", "source": "juraj_google_style"} +{"code": "def __init__(self, *args, resampling_rate = 0.5, min_samples_advance = 1, **kwargs):\n\n\t\tself.resampling_rate = resampling_rate\n\t\tself.min_samples_advance = min_samples_advance", "docstring": "Iteration class to resample new configurations along side keeping the good ones\n in SuccessiveHalving.\n\n Parameters:\n -----------\n resampling_rate: float\n fraction of configurations that are resampled at each stage\n min_samples_advance:int\n number of samples that are guaranteed to proceed to the next\n stage regardless of the fraction.", "source": "juraj_google_style"} +{"code": "def stop(self, accountID, **kwargs):\n\n return self.create(\n accountID,\n order=StopOrderRequest(**kwargs)\n )", "docstring": "Shortcut to create a Stop Order in an Account\n\nArgs:\n accountID : The ID of the Account\n kwargs : The arguments to create a StopOrderRequest\n\nReturns:\n v20.response.Response containing the results from submitting\n the request", "source": "juraj_google_style"} +{"code": "def create_server(settings, log_config=None, bigchaindb_factory=None):\n\n\n settings = copy.deepcopy(settings)\n\n if not settings.get('workers'):\n settings['workers'] = (multiprocessing.cpu_count() * 2) + 1\n\n if not settings.get('threads'):\n # Note: Threading is not recommended currently, as the frontend workload\n # is largely CPU bound and parallisation across Python threads makes it\n # slower.\n settings['threads'] = 1\n\n settings['custom_log_config'] = log_config\n app = create_app(debug=settings.get('debug', False),\n threads=settings['threads'],\n bigchaindb_factory=bigchaindb_factory)\n standalone = StandaloneApplication(app, options=settings)\n return standalone", "docstring": "Wrap and return an application ready to be run.\n\nArgs:\n settings (dict): a dictionary containing the settings, more info\n here http://docs.gunicorn.org/en/latest/settings.html\n\nReturns:\n an initialized instance of the application.", "source": "juraj_google_style"} +{"code": "def prepare_soap_body(self, method, parameters, namespace):\n\n\n tags = []\n for name, value in parameters:\n tag = \"<{name}>{value}\".format(\n name=name, value=escape(\"%s\" % value, {'\"': \""\"}))\n # % converts to unicode because we are using unicode literals.\n # Avoids use of 'unicode' function which does not exist in python 3\n tags.append(tag)\n\n wrapped_params = \"\".join(tags)\n # Prepare the SOAP Body\n if namespace is not None:\n soap_body = (\n '<{method} xmlns=\"{namespace}\">'\n '{params}'\n ''.format(\n method=method, params=wrapped_params,\n namespace=namespace\n ))\n else:\n soap_body = (\n '<{method}>'\n '{params}'\n ''.format(\n method=method, params=wrapped_params\n ))\n\n return soap_body", "docstring": "Prepare the SOAP message body for sending.\n\nArgs:\n method (str): The name of the method to call.\n parameters (list): A list of (name, value) tuples containing\n the parameters to pass to the method.\n namespace (str): tThe XML namespace to use for the method.\n\nReturns:\n str: A properly formatted SOAP Body.", "source": "juraj_google_style"} +{"code": "def load(self, filename, offset):\n\n self.offset = offset\n self.filename = filename\n\n self.bootsector = BootSector(\n filename=filename,\n length=NTFS_BOOTSECTOR_SIZE,\n offset=self.offset)\n\n self.mft_table = MftTable(\n mft_entry_size=self.bootsector.mft_record_size,\n filename=self.filename,\n offset=self.mft_table_offset\n )\n\n self.mft_table.preload_entries(NUM_SYSTEM_ENTRIES)\n\n self._load_volume_information()", "docstring": "Loads NTFS volume information\n\nArgs:\n filename (str): Path to file/device to read the volume \\\n information from.\n offset (uint): Valid NTFS partition offset from the beginning \\\n of the file/device.\n\nRaises:\n IOError: If source file/device does not exist or is not readable", "source": "juraj_google_style"} +{"code": "def _get_account_xml(soco):\n\n # It is likely that the same information is available over UPnP as well\n # via a call to\n # systemProperties.GetStringX([('VariableName','R_SvcAccounts')]))\n # This returns an encrypted string, and, so far, we cannot decrypt it\n device = soco or discovery.any_soco()\n log.debug(\"Fetching account data from %s\", device)\n settings_url = \"http://{}:1400/status/accounts\".format(\n device.ip_address)\n result = requests.get(settings_url).content\n log.debug(\"Account data: %s\", result)\n return result", "docstring": "Fetch the account data from a Sonos device.\n\nArgs:\n soco (SoCo): a SoCo instance to query. If soco is `None`, a\n random device will be used.\n\nReturns:\n str: a byte string containing the account data xml", "source": "juraj_google_style"} +{"code": "def diff(self, order=1):\n\n order = int(order)\n if order < 0:\n raise ValueError(\"order must be >= 0, got %d\" % (order))\n\n if order == 0:\n return self.__call__\n\n if order > self.p: # identically zero, but force the same output format as in the general case\n dummy = self.__call__(0.) # get number of basis functions and output dtype\n nbasis = dummy.shape[0]\n return lambda x: np.zeros( (nbasis,), dtype=dummy.dtype ) # accept but ignore input x\n\n # At each differentiation, each term maps into two new terms.\n # The number of terms in the result will be 2**order.\n #\n # This will cause an exponential explosion in the number of terms for high derivative orders,\n # but for the first few orders (practical usage; >3 is rarely needed) the approach works.\n #\n terms = [ (1.,self) ]\n for k in range(order):\n tmp = []\n for Ci,Bi in terms:\n tmp.extend( (Ci*cn, Bn) for cn,Bn in Bi.__diff_internal() ) # NOTE: also propagate Ci\n terms = tmp\n\n # perform final summation at call time\n return lambda x: sum( ci*Bi(x) for ci,Bi in terms )", "docstring": "Differentiate a B-spline `order` number of times.\n\n Parameters:\n order:\n int, >= 0\n\nReturns:\n **lambda** `x`: ... that evaluates the `order`-th derivative of `B` at the point `x`.\n The returned function internally uses __call__, which is 'memoized' for speed.", "source": "juraj_google_style"} +{"code": "def _convert_to_example(filename, image_buffer, label, text, height, width):\n\n\n colorspace = 'RGB'\n channels = 3\n image_format = 'JPEG'\n\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': _int64_feature(height),\n 'image/width': _int64_feature(width),\n 'image/colorspace': _bytes_feature(tf.compat.as_bytes(colorspace)),\n 'image/channels': _int64_feature(channels),\n 'image/class/label': _int64_feature(label),\n 'image/class/text': _bytes_feature(tf.compat.as_bytes(text)),\n 'image/format': _bytes_feature(tf.compat.as_bytes(image_format)),\n 'image/filename': _bytes_feature(tf.compat.as_bytes(os.path.basename(filename))),\n 'image/encoded': _bytes_feature(tf.compat.as_bytes(image_buffer))}))\n return example", "docstring": "Build an Example proto for an example.\n\nArgs:\n filename: string, path to an image file, e.g., '/path/to/example.JPG'\n image_buffer: string, JPEG encoding of RGB image\n label: integer, identifier for the ground truth for the network\n text: string, unique human-readable, e.g. 'dog'\n height: integer, image height in pixels\n width: integer, image width in pixels\n\nReturns:\n Example proto", "source": "juraj_google_style"} +{"code": "def __init__(self, regex: str, option_suffix: str):\n\n super().__init__(option_suffix)\n self._regex = self._build_matcher(regex)", "docstring": "Create a new instance.\n\nArgs:\n regex:\n The regular expression describing the entry line to match. The\n first matching line is selected. The expression must contain a\n single capture group that contains the data to return.\n option_suffix:\n Suffix for each configuration option", "source": "juraj_google_style"} +{"code": "def replace_list(items, match, replacement):\n\n return [replace(item, match, replacement) for item in items]", "docstring": "Replaces occurrences of a match string in a given list of strings and returns\n a list of new strings. The match string can be a regex expression.\n\nArgs:\n items (list): the list of strings to modify.\n match (str): the search expression.\n replacement (str): the string to replace with.", "source": "juraj_google_style"} +{"code": "def Reset(\n self,\n Channel):\n\n\n try:\n res = self.__m_dllBasic.CAN_Reset(Channel)\n return TPCANStatus(res)\n except:\n logger.error(\"Exception on PCANBasic.Reset\")\n raise", "docstring": "Resets the receive and transmit queues of the PCAN Channel\n\n Remarks:\n A reset of the CAN controller is not performed\n\n Parameters:\n Channel : A TPCANHandle representing a PCAN Channel\n\nReturns:\n A TPCANStatus error code", "source": "juraj_google_style"} +{"code": "def darken(self, color, diff, *args):\n\n if color and diff:\n return self._ophsl(color, diff, 1, operator.sub)\n raise ValueError('Illegal color values')", "docstring": "Darken a color\n\nArgs:\n color (str): color\n diff (str): percentage\n\nReturns:\n str", "source": "juraj_google_style"} +{"code": "def get_variables(self, include_submodules=False, include_nontrainable=False):\n\n if include_nontrainable:\n model_variables = [self.all_variables[key] for key in sorted(self.all_variables)]\n\n states_preprocessing_variables = [\n variable for name in sorted(self.states_preprocessing)\n for variable in self.states_preprocessing[name].get_variables()\n ]\n model_variables += states_preprocessing_variables\n\n actions_exploration_variables = [\n variable for name in sorted(self.actions_exploration)\n for variable in self.actions_exploration[name].get_variables()\n ]\n model_variables += actions_exploration_variables\n\n if self.reward_preprocessing is not None:\n reward_preprocessing_variables = self.reward_preprocessing.get_variables()\n model_variables += reward_preprocessing_variables\n\n else:\n model_variables = [self.variables[key] for key in sorted(self.variables)]\n\n return model_variables", "docstring": "Returns the TensorFlow variables used by the model.\n\nArgs:\n include_submodules: Includes variables of submodules (e.g. baseline, target network)\n if true.\n include_nontrainable: Includes non-trainable variables if true.\n\nReturns:\n List of variables.", "source": "juraj_google_style"} +{"code": "def from_hyperplane(basis, origin, point, internal = True):\n\n basis = np.array(basis)\n assert basis.shape[0] + 1 == basis.shape[1]\n\n big_basis = np.zeros((basis.shape[1], basis.shape[1]))\n big_basis[:basis.shape[0],:basis.shape[1]] = basis\n\n u, s, vh = np.linalg.svd(big_basis)\n null_mask = (s <= 1e-8)\n normal = np.compress(null_mask, vh, axis=0)[0]\n\n if np.inner(np.array(point)-np.array(origin), normal) > 0:\n if internal:\n normal *= -1\n else:\n if not internal:\n normal *= -1\n offset = -np.dot(origin, normal)\n return Halfspace(normal, offset)", "docstring": "Returns a Halfspace defined by a list of vectors parallel to the\n bounding hyperplane.\n\nArgs:\n basis: basis for the hyperplane (array with vector rows)\n origin: point on the hyperplane\n point: point not on the hyperplane\n internal: whether point is inside the halfspace", "source": "juraj_google_style"} +{"code": "def get_chromosomes(self, sv=False):\n\n if sv:\n res = self.db.structural_variant.distinct('chrom')\n else:\n res = self.db.variant.distinct('chrom')\n\n return res", "docstring": "Return a list of all chromosomes found in database\n\nArgs:\n sv(bool): if sv variants should be choosen\n\nReturns:\n res(iterable(str)): An iterable with all chromosomes in the database", "source": "juraj_google_style"} +{"code": "def gt(self, other, axis=\"columns\", level=None):\n\n return self._binary_op(\"gt\", other, axis=axis, level=level)", "docstring": "Checks element-wise that this is greater than other.\n\nArgs:\n other: A DataFrame or Series or scalar to compare to.\n axis: The axis to perform the gt over.\n level: The Multilevel index level to apply gt over.\n\nReturns:\n A new DataFrame filled with Booleans.", "source": "juraj_google_style"} +{"code": "def listdir(*paths, glob=None):\n\n path = genpath(*paths)\n\n names = os.listdir(path)\n if glob is not None:\n names = fnmatch.filter(names, glob)\n\n retn = [os.path.join(path, name) for name in names]\n return retn", "docstring": "List the (optionally glob filtered) full paths from a dir.\n\nArgs:\n *paths ([str,...]): A list of path elements\n glob (str): An optional fnmatch glob str", "source": "juraj_google_style"} +{"code": "def ApplyPluginToTypedCollection(plugin, type_names, fetch_fn):\n\n for chunk in plugin.Start():\n yield chunk\n\n def GetValues(tn):\n for v in fetch_fn(tn):\n yield v\n\n for type_name in sorted(type_names):\n stored_cls = rdfvalue.RDFValue.classes[type_name]\n\n for chunk in plugin.ProcessValues(stored_cls,\n functools.partial(GetValues, type_name)):\n yield chunk\n\n for chunk in plugin.Finish():\n yield chunk", "docstring": "Applies instant output plugin to a collection of results.\n\nArgs:\n plugin: InstantOutputPlugin instance.\n type_names: List of type names (strings) to be processed.\n fetch_fn: Function that takes a type name as an argument and returns\n available items (FlowResult) corresponding to this type. Items are\n returned as a generator\n\nYields:\n Bytes chunks, as generated by the plugin.", "source": "juraj_google_style"} +{"code": "def tag(self, main_type, sub_type, unique_id, tag, action='GET', owner=None, params=None):\n\n params = params or {}\n\n if owner:\n params['owner'] = owner\n\n action = action.upper()\n if sub_type:\n url = '/v2/{}/{}/{}/tags/{}'.format(main_type, sub_type, unique_id, quote(tag))\n else:\n url = '/v2/{}/{}/tags/{}'.format(main_type, unique_id, quote(tag))\n response = None\n if action == 'ADD':\n response = self.tcex.session.post(url, params=params)\n elif action == 'DELETE':\n response = self.tcex.session.delete(url, params=params)\n elif action == 'GET':\n response = self.tcex.session.get(url, params=params)\n else:\n self.tcex.log.error('_tags error')\n return response", "docstring": "Args:\n owner:\n main_type:\n sub_type:\n unique_id:\n tag:\n action:\n params:\n\n Return:", "source": "juraj_google_style"} +{"code": "def referrer_uri(self, value):\n\n if value == self._defaults['referrerUri'] and 'referrerUri' in self._values:\n del self._values['referrerUri']\n else:\n self._values['referrerUri'] = value", "docstring": "The referrer_uri property.\n\nArgs:\n value (string). the property value.", "source": "juraj_google_style"} +{"code": "def run_dumper(self, dumper):\n\n\n logging.debug(\"start dumper::\")\n dumper(\n experiments=self.experiments,\n farms=self.farms,\n barn=self.barn,\n engine=self.current_engine,\n )\n logging.debug(\"::dumper ended\")", "docstring": "run dumber (once pr. engine)\n\nArgs:\n dumper: dumper to run (function or method).\n\n The dumper takes the attributes experiments, farms, and barn as input.\n It does not return anything. But can, if the dumper designer feels in\n a bad and nasty mood, modify the input objects\n (for example experiments).", "source": "juraj_google_style"} +{"code": "def _layer_stack(mp,\n inputs,\n self_attention_bias,\n layers,\n hparams,\n encoder_output=None,\n encoder_decoder_attention_bias=None):\n\n layers = layers.strip(\",\").split(\",\")\n\n # scaled_dot_product_attention_with_projections uses a 3d attention bias\n # (no heads), where multihead_attention uses 4d attention bias.\n self_attention_bias_3d = mp(tf.squeeze, self_attention_bias, 1)\n if encoder_decoder_attention_bias is not None:\n encoder_decoder_attention_bias_3d = mp(\n tf.squeeze, encoder_decoder_attention_bias, 1)\n relu_dropout_broadcast_dims = (\n common_layers.comma_separated_string_to_integer_list(\n getattr(hparams, \"relu_dropout_broadcast_dims\", \"\")))\n mix_size = int(hparams.mix_fraction * hparams.hidden_size)\n accumulator = inputs\n x = inputs\n for layer_num, layer_type in enumerate(layers):\n with tf.variable_scope(\"%s_%d\" % (layer_type, layer_num)):\n tf.logging.info(\"%s_%d\" % (layer_type, layer_num))\n if layer_type == \"a\":\n # accumulate\n accumulator = mp(tf.add, x, accumulator)\n x = accumulator\n elif layer_type == \"n\":\n # normalize\n x = mp(common_layers.apply_norm,\n x, hparams.norm_type, hparams.hidden_size, hparams.norm_epsilon)\n elif layer_type == \"d\":\n # dropout\n x = mp(tf.nn.dropout, x, 1.0 - hparams.layer_prepostprocess_dropout)\n elif layer_type == \"m\":\n if mix_size > 0:\n # mix across shards\n def _split(t):\n return tuple(tf.split(\n t, [mix_size, hparams.hidden_size - mix_size], 2))\n to_mix, to_keep = mp(_split, x)\n mixed = expert_utils.all_reduce_ring(to_mix, mp)\n mixed = mp(tf.multiply, mixed, mp.n ** -0.5)\n x = mp(lambda a, b: tf.concat([a, b], 2), mixed, to_keep)\n elif layer_type == \"att\":\n # single-head attention\n q = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False,\n name=\"q_transform\")\n x = mp(\n common_attention.scaled_dot_product_attention_simple,\n q, x, x, self_attention_bias_3d)\n x = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False,\n name=\"o_transform\")\n elif layer_type == \"enc-att\":\n # single-head attention over encoder\n q = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False,\n name=\"q_transform\")\n assert encoder_output is not None\n x = mp(\n common_attention.scaled_dot_product_attention_simple,\n q, encoder_output, encoder_output,\n encoder_decoder_attention_bias_3d)\n x = mp(tf.layers.dense, x, hparams.hidden_size, use_bias=False,\n name=\"o_transform\")\n elif layer_type == \"multihead-att\":\n # multi-head attention\n x = mp(\n common_attention.multihead_attention,\n x,\n None,\n self_attention_bias, # bias\n hparams.multihead_attention_key_channels or hparams.hidden_size,\n hparams.multihead_attention_value_channels or hparams.hidden_size,\n hparams.hidden_size,\n hparams.multihead_attention_num_heads,\n hparams.attention_dropout)\n elif layer_type == \"enc-multihead-att\":\n # multi-head attention\n x = mp(\n common_attention.multihead_attention,\n x,\n encoder_output,\n encoder_decoder_attention_bias, # bias\n hparams.multihead_attention_key_channels or hparams.hidden_size,\n hparams.multihead_attention_value_channels or hparams.hidden_size,\n hparams.hidden_size,\n hparams.multihead_attention_num_heads,\n hparams.attention_dropout)\n elif layer_type == \"ffn\":\n x = mp(\n common_layers.dense_relu_dense, x,\n hparams.filter_size, hparams.hidden_size,\n dropout=hparams.relu_dropout,\n dropout_broadcast_dims=[relu_dropout_broadcast_dims] * mp.n)\n else:\n assert False, \"unknown sublayer %s\" % layer_type\n return x", "docstring": "A stack of layers.\n\nArgs:\n mp: a Parallelism object\n inputs: a list of Tensors\n self_attention_bias: list of bias Tensor for self-attention\n (see common_attention.attention_bias())\n layers: a string\n hparams: hyperparameters for model\n encoder_output: optional list of tensors\n encoder_decoder_attention_bias: optional list of tensors\n\nReturns:\n y: a list of Tensors", "source": "juraj_google_style"} +{"code": "def _LogForwardedIpChanges(\n self, configured, desired, to_add, to_remove, interface):\n\n if not to_add and not to_remove:\n return\n self.logger.info(\n 'Changing %s IPs from %s to %s by adding %s and removing %s.',\n interface, configured or None, desired or None, to_add or None,\n to_remove or None)", "docstring": "Log the planned IP address changes.\n\nArgs:\n configured: list, the IP address strings already configured.\n desired: list, the IP address strings that will be configured.\n to_add: list, the forwarded IP address strings to configure.\n to_remove: list, the forwarded IP address strings to delete.\n interface: string, the output device to modify.", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.ListSinks = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/ListSinks\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.ListSinksRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.ListSinksResponse.FromString,\n )\n self.GetSink = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/GetSink\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.GetSinkRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.LogSink.FromString,\n )\n self.CreateSink = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/CreateSink\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.CreateSinkRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.LogSink.FromString,\n )\n self.UpdateSink = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/UpdateSink\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.UpdateSinkRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.LogSink.FromString,\n )\n self.DeleteSink = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/DeleteSink\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.DeleteSinkRequest.SerializeToString,\n response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,\n )\n self.ListExclusions = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/ListExclusions\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.ListExclusionsRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.ListExclusionsResponse.FromString,\n )\n self.GetExclusion = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/GetExclusion\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.GetExclusionRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.LogExclusion.FromString,\n )\n self.CreateExclusion = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/CreateExclusion\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.CreateExclusionRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.LogExclusion.FromString,\n )\n self.UpdateExclusion = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/UpdateExclusion\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.UpdateExclusionRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.LogExclusion.FromString,\n )\n self.DeleteExclusion = channel.unary_unary(\n \"/google.logging.v2.ConfigServiceV2/DeleteExclusion\",\n request_serializer=google_dot_cloud_dot_logging__v2_dot_proto_dot_logging__config__pb2.DeleteExclusionRequest.SerializeToString,\n response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def get(self, name):\n\n return self.prepare_model(self.client.api.inspect_plugin(name))", "docstring": "Gets a plugin.\n\nArgs:\n name (str): The name of the plugin.\n\nReturns:\n (:py:class:`Plugin`): The plugin.\n\nRaises:\n :py:class:`docker.errors.NotFound` If the plugin does not\n exist.\n :py:class:`docker.errors.APIError`\n If the server returns an error.", "source": "juraj_google_style"} +{"code": "def set_membership(self, room_id, user_id, membership, reason=\"\", profile=None,\n timestamp=None):\n\n if profile is None:\n profile = {}\n body = {\n \"membership\": membership,\n \"reason\": reason\n }\n if 'displayname' in profile:\n body[\"displayname\"] = profile[\"displayname\"]\n if 'avatar_url' in profile:\n body[\"avatar_url\"] = profile[\"avatar_url\"]\n\n return self.send_state_event(room_id, \"m.room.member\", body, state_key=user_id,\n timestamp=timestamp)", "docstring": "Perform PUT /rooms/$room_id/state/m.room.member/$user_id\n\nArgs:\n room_id (str): The room ID\n user_id (str): The user ID\n membership (str): New membership value\n reason (str): The reason\n timestamp (int): Set origin_server_ts (For application services only)", "source": "juraj_google_style"} +{"code": "def unpack(self, buff=None, offset=0):\n\n instruction_type = UBInt16(enum_ref=InstructionType)\n instruction_type.unpack(buff, offset)\n self.__class__ = InstructionType(instruction_type.value).find_class()\n\n length = UBInt16()\n length.unpack(buff, offset=offset+2)\n\n super().unpack(buff[:offset+length.value], offset)", "docstring": "Unpack *buff* into this object.\n\n This method will convert a binary data into a readable value according\n to the attribute format.\n\nArgs:\n buff (bytes): Binary buffer.\n offset (int): Where to begin unpacking.\n\nRaises:\n :exc:`~.exceptions.UnpackException`: If unpack fails.", "source": "juraj_google_style"} +{"code": "def find(format):\n\n try:\n serializer = SERIALIZERS[format]\n except KeyError:\n raise UnknownSerializer('No serializer found for %s' % format.acronym)\n\n return serializer", "docstring": "Find and return a serializer for the given format.\n\nArgs:\n format -- A Format instance.", "source": "juraj_google_style"} +{"code": "def _CopyDateFromString(self, date_string):\n\n date_string_length = len(date_string)\n\n # The date string should at least contain 'YYYY-MM-DD'.\n if date_string_length < 10:\n raise ValueError('Date string too short.')\n\n if date_string[4] != '-' or date_string[7] != '-':\n raise ValueError('Invalid date string.')\n\n try:\n year = int(date_string[0:4], 10)\n except ValueError:\n raise ValueError('Unable to parse year.')\n\n try:\n month = int(date_string[5:7], 10)\n except ValueError:\n raise ValueError('Unable to parse month.')\n\n try:\n day_of_month = int(date_string[8:10], 10)\n except ValueError:\n raise ValueError('Unable to parse day of month.')\n\n days_per_month = self._GetDaysPerMonth(year, month)\n if day_of_month < 1 or day_of_month > days_per_month:\n raise ValueError('Day of month value out of bounds.')\n\n return year, month, day_of_month", "docstring": "Copies a date from a string.\n\nArgs:\n date_string (str): date value formatted as: YYYY-MM-DD\n\nReturns:\n tuple[int, int, int]: year, month, day of month.\n\nRaises:\n ValueError: if the date string is invalid or not supported.", "source": "juraj_google_style"} +{"code": "def dedent(self, node, dirty=True):\n\n if node.id not in self._subitems:\n return\n\n del self._subitems[node.id]\n node.super_list_item_id = None\n node.parent_item = None\n if dirty:\n node.touch(True)", "docstring": "Dedent an item. Does nothing if the target is not indented under this item.\n\nArgs:\n node (gkeepapi.node.ListItem): Item to dedent.\n dirty (bool): Whether this node should be marked dirty.", "source": "juraj_google_style"} +{"code": "def conv_to_float(indata, inf_str=''):\n\n if indata.strip() == inf_str:\n outdata = float('Inf')\n else:\n try:\n outdata = float(indata)\n except:\n raise ValueError('Unable to convert {} to float'.format(indata))\n\n return outdata", "docstring": "Try to convert an arbitrary string to a float. Specify what will be replaced with \"Inf\".\n\nArgs:\n indata (str): String which contains a float\n inf_str (str): If string contains something other than a float, and you want to replace it with float(\"Inf\"),\n specify that string here.\n\nReturns:\n float: Converted string representation", "source": "juraj_google_style"} +{"code": "def external_ids(self, **kwargs):\n\n path = self._get_id_path('external_ids')\n\n response = self._GET(path, kwargs)\n self._set_attrs_to_values(response)\n return response", "docstring": "Get the external ids for a specific movie id.\n\nArgs:\n language: (optional) ISO 639-1 code.\n append_to_response: (optional) Comma separated, any movie method.\n\nReturns:\n A dict representation of the JSON returned from the API.", "source": "juraj_google_style"} +{"code": "def import_users(self, connection_id, file_obj, upsert=False):\n\n return self.client.file_post(self._url('users-imports'),\n data={'connection_id': connection_id, 'upsert': str(upsert).lower()},\n files={'users': file_obj})", "docstring": "Imports users to a connection from a file.\n\nArgs:\n connection_id (str): The connection id of the connection to which\n users will be inserted.\n\n file_obj (file): A file-like object to upload. The format for\n this file is explained in: https://auth0.com/docs/bulk-import\n\n See: https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports", "source": "juraj_google_style"} +{"code": "def __init__(self,env_id,visualize=False):\n\n\t\tenvs = [Arm2DEnv,L2RunEnv,ProstheticsEnv]\n\t\tself.env = envs[env_id](visualize=visualize)\n\n\t\tself.state_shape = len(self.env.reset())\n\t\tself.num_actions = len(self.env.action_space.sample())", "docstring": "Initialize OpenSimulator environment.\n\nArgs:\n visualize: render enviroment\n env: environment id to use ([0:Arm2DEnv, 1:L2RunEnv, 2:ProstheticsEnv])", "source": "juraj_google_style"} +{"code": "def jpeg_compression(x, severity=1):\n\n c = [25, 18, 15, 10, 7][severity - 1]\n x = tfds.core.lazy_imports.PIL_Image.fromarray(x.astype(np.uint8))\n output = io.BytesIO()\n x.save(output, 'JPEG', quality=c)\n output.seek(0)\n x = tfds.core.lazy_imports.PIL_Image.open(output)\n return np.asarray(x)", "docstring": "Conduct jpeg compression to images.\n\nArgs:\n x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n severity: integer, severity of corruption.\n\nReturns:\n numpy array, image with uint8 pixels in [0,255]. Applied jpeg compression.", "source": "juraj_google_style"} +{"code": "def fit_size_models(self, model_names,\n model_objs,\n input_columns,\n output_column=\"Hail_Size\",\n output_start=5,\n output_step=5,\n output_stop=100):\n\n print(\"Fitting size models\")\n groups = self.data[\"train\"][\"member\"][self.group_col].unique()\n output_start = int(output_start)\n output_step = int(output_step)\n output_stop = int(output_stop)\n for group in groups:\n group_data = self.data[\"train\"][\"combo\"].loc[self.data[\"train\"][\"combo\"][self.group_col] == group]\n group_data.dropna(inplace=True)\n group_data = group_data[group_data[output_column] >= output_start]\n output_data = group_data[output_column].values.astype(int)\n output_data[output_data > output_stop] = output_stop\n discrete_data = ((output_data - output_start) // output_step) * output_step + output_start\n self.size_models[group] = {}\n self.size_models[group][\"outputvalues\"] = np.arange(output_start, output_stop + output_step, output_step,\n dtype=int)\n for m, model_name in enumerate(model_names):\n print(\"{0} {1}\".format(group, model_name))\n self.size_models[group][model_name] = deepcopy(model_objs[m])\n self.size_models[group][model_name].fit(group_data[input_columns], discrete_data)", "docstring": "Fit size models to produce discrete pdfs of forecast hail sizes.\n\nArgs:\n model_names: List of model names\n model_objs: List of model objects\n input_columns: List of input variables\n output_column: Output variable name\n output_start: Hail size bin start\n output_step: hail size bin step\n output_stop: hail size bin stop", "source": "juraj_google_style"} +{"code": "def append_with_data(url, data):\n\n\n if data is None:\n return url\n\n url_parts = list(urlparse(url))\n\n query = OrderedDict(parse_qsl(url_parts[4], keep_blank_values=True))\n query.update(data)\n\n url_parts[4] = URLHelper.query_dict_to_string(query)\n\n return urlunparse(url_parts)", "docstring": "Append the given URL with the given data OrderedDict.\n\nArgs:\n url (str): The URL to append.\n data (obj): The key value OrderedDict to append to the URL.\n\nReturns:\n str: The new URL.", "source": "juraj_google_style"} +{"code": "def _SetAllFieldTypes(self, package, desc_proto, scope):\n\n\n package = _PrefixWithDot(package)\n\n main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)\n\n if package == '.':\n nested_package = _PrefixWithDot(desc_proto.name)\n else:\n nested_package = '.'.join([package, desc_proto.name])\n\n for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):\n self._SetFieldType(field_proto, field_desc, nested_package, scope)\n\n for extension_proto, extension_desc in (\n zip(desc_proto.extension, main_desc.extensions)):\n extension_desc.containing_type = self._GetTypeFromScope(\n nested_package, extension_proto.extendee, scope)\n self._SetFieldType(extension_proto, extension_desc, nested_package, scope)\n\n for nested_type in desc_proto.nested_type:\n self._SetAllFieldTypes(nested_package, nested_type, scope)", "docstring": "Sets all the descriptor's fields's types.\n\n This method also sets the containing types on any extensions.\n\nArgs:\n package: The current package of desc_proto.\n desc_proto: The message descriptor to update.\n scope: Enclosing scope of available types.", "source": "juraj_google_style"} +{"code": "def mapIdentity(self, primarySubject, secondarySubject, vendorSpecific=None):\n\n response = self.mapIdentityResponse(\n primarySubject, secondarySubject, vendorSpecific\n )\n return self._read_boolean_response(response)", "docstring": "See Also: mapIdentityResponse()\n\nArgs:\n primarySubject:\n secondarySubject:\n vendorSpecific:\n\n Returns:", "source": "juraj_google_style"} +{"code": "def __call__(self, utterances_batch: list, history_batch: list) -> list:\n\n return [[True] * len(utterances_batch)] * self.size", "docstring": "Returns skills-utterances application matrix.\n\n Generates skills-utterances application matrix with all True\n elements.\n\nArgs:\n utterances_batch: A batch of utterances of any type.\n history_batch: Not used.\n\nReturns:\n response: Skills-utterances application matrix with all True\n elements.", "source": "juraj_google_style"} +{"code": "def add_meta_line(self, key, value):\n\n meta_line = '##{0}={1}'.format(\n key, value\n )\n logger.info(\"Adding meta line to vcf: {0}\".format(meta_line))\n self.parse_meta_data(meta_line)\n return", "docstring": "Adds an arbitrary metadata line to the header.\n\n This must be a key value pair\n\nArgs:\n key (str): The key of the metadata line\n value (str): The value of the metadata line", "source": "juraj_google_style"} +{"code": "def __new__(cls, *args, **kwargs):\n\n instance = super(_AutoFinalizedObjectBase, cls).__new__(cls)\n instance._finalize_called = False\n return instance", "docstring": "Creates a new object instance and adds the private finalizer\n attributes to it.\n\n Returns: new object instance\n\nArgs:\n * *args, **kwargs -- ignored", "source": "juraj_google_style"} +{"code": "def get_timestamp(self, cycle=None, dataset_number=None,\n in_minutes=False, full=True):\n\n\n dataset_number = self._validate_dataset_number(dataset_number)\n if dataset_number is None:\n self._report_empty_dataset()\n return\n cycle_index_header = self.headers_normal.cycle_index_txt\n timestamp_header = self.headers_normal.test_time_txt\n\n v = pd.Series()\n test = self.datasets[dataset_number].dfdata\n if cycle:\n c = test[(test[cycle_index_header] == cycle)]\n if not self.is_empty(c):\n v = c[timestamp_header]\n\n else:\n if not full:\n self.logger.debug(\"getting timestapm for all cycles\")\n v = []\n no_cycles = np.amax(test[cycle_index_header])\n for j in range(1, no_cycles + 1):\n txt = \"Cycle %i: \" % j\n self.logger.debug(txt)\n c = test[(test[cycle_index_header] == j)]\n v.append(c[timestamp_header])\n else:\n self.logger.debug(\"returning full timestamp col\")\n v = test[timestamp_header]\n if in_minutes and v is not None:\n v /= 60.0\n if in_minutes and v is not None:\n v /= 60.0\n return v", "docstring": "Returns timestamps (in sec or minutes (if in_minutes==True)).\n\nArgs:\n cycle: cycle number (all if None)\n dataset_number: first dataset if None\n in_minutes: return values in minutes instead of seconds if True\n full: valid only for cycle=None (i.e. all cycles), returns the full\n pandas.Series if True, else a list of pandas.Series\n\nReturns:\n pandas.Series (or list of pandas.Series if cycle=None og full=False)", "source": "juraj_google_style"} +{"code": "def load_from_dict(self, conf_dict=None):\n\n self.set_to_default()\n self._update_dict(self._config, conf_dict)\n self._update_python_paths()", "docstring": "Load the configuration from a dictionary.\n\nArgs:\n conf_dict (dict): Dictionary with the configuration.", "source": "juraj_google_style"} +{"code": "def parameterized_codec(raw, b64):\n\n\n if isinstance(raw, bytes):\n raw = raw.decode('utf-8')\n\n result = _parameterize_string(raw)\n\n # Note, since we want a raw JSON object (not a string) output in the\n # template, we wrap the result in GenericHelperFn (not needed if we're\n # using Base64)\n return Base64(result.data) if b64 else result", "docstring": "Parameterize a string, possibly encoding it as Base64 afterwards\n\nArgs:\n raw (`str` | `bytes`): String to be processed. Byte strings will be\n interpreted as UTF-8.\n b64 (`bool`): Whether to wrap the output in a Base64 CloudFormation\n call\n\nReturns:\n :class:`troposphere.AWSHelperFn`: output to be included in a\n CloudFormation template.", "source": "juraj_google_style"} +{"code": "def get_variant_dict(variant_line, header_line=None):\n\n if not header_line:\n logger.debug(\"No header line, use only first 8 mandatory fields\")\n header_line = ['CHROM','POS','ID','REF','ALT','QUAL','FILTER','INFO']\n\n logger.debug(\"Building variant dict from variant line {0} and header\"\\\n \" line {1}\".format(variant_line, '\\t'.join(header_line)))\n\n splitted_line = variant_line.rstrip().split('\\t')\n if len(splitted_line) < len(header_line):\n logger.info('\\t'.join(header_line))\n logger.info('\\t'.join(splitted_line))\n raise SyntaxError(\"Length of variant line differs from length of\"\\\n \" header line\")\n\n return dict(zip(header_line, splitted_line))", "docstring": "Parse a variant line\n\n Split a variant line and map the fields on the header columns\n\nArgs:\n variant_line (str): A vcf variant line\n header_line (list): A list with the header columns\n\nReturns:\n variant_dict (dict): A variant dictionary", "source": "juraj_google_style"} +{"code": "def get_revision_sha(self, dest, rev):\n\n # Pass rev to pre-filter the list.\n output = self.run_command(['show-ref', rev], cwd=dest,\n show_stdout=False, on_returncode='ignore')\n refs = {}\n for line in output.strip().splitlines():\n try:\n sha, ref = line.split()\n except ValueError:\n # Include the offending line to simplify troubleshooting if\n # this error ever occurs.\n raise ValueError('unexpected show-ref line: {!r}'.format(line))\n\n refs[ref] = sha\n\n branch_ref = 'refs/remotes/origin/{}'.format(rev)\n tag_ref = 'refs/tags/{}'.format(rev)\n\n sha = refs.get(branch_ref)\n if sha is not None:\n return (sha, True)\n\n sha = refs.get(tag_ref)\n\n return (sha, False)", "docstring": "Return (sha_or_none, is_branch), where sha_or_none is a commit hash\n if the revision names a remote branch or tag, otherwise None.\n\nArgs:\n dest: the repository directory.\n rev: the revision name.", "source": "juraj_google_style"} +{"code": "def __init__(self, baselines, scope='aggregated-baseline', summary_labels=()):\n\n\n self.baselines = dict()\n for name in sorted(baselines):\n self.baselines[name] = Baseline.from_spec(\n spec=baselines[name],\n kwargs=dict(summary_labels=summary_labels))\n\n self.linear = Linear(size=1, bias=0.0, scope='prediction', summary_labels=summary_labels)\n\n super(AggregatedBaseline, self).__init__(scope, summary_labels)", "docstring": "Aggregated baseline.\n\nArgs:\n baselines: Dict of per-state baseline specification dicts", "source": "juraj_google_style"} +{"code": "def __init__(self, namespace=None):\n\n assert namespace != DEFAULT_REQUEST_CACHE_NAMESPACE,\\\n 'Optional namespace can not be {}.'.format(DEFAULT_REQUEST_CACHE_NAMESPACE)\n self.namespace = namespace or DEFAULT_REQUEST_CACHE_NAMESPACE", "docstring": "Creates a request cache with the provided namespace.\n\nArgs:\n namespace (string): (optional) uses 'default' if not provided.", "source": "juraj_google_style"} +{"code": "def __init__(self, graph: IGraph):\n\n super(IGraphWrapper, self).__init__(self._create_memory_database_interface())\n\n if not isinstance(graph, IGraph):\n raise ValueError(\"Invalid graph instance provided to IGraphWrapper\")\n\n self._wrapped_graph: IGraph = graph\n", "docstring": "Initialization.\n\nArgs:\n graph (IGraph): The igraph `Graph` object to wrap.", "source": "juraj_google_style"} +{"code": "def onTagAdd(self, name, func):\n\n # TODO allow name wild cards\n if '*' in name:\n self.ontagaddglobs.add(name, func)\n else:\n self.ontagadds[name].append(func)", "docstring": "Register a callback for tag addition.\n\nArgs:\n name (str): The name of the tag or tag glob.\n func (function): The callback func(node, tagname, tagval).", "source": "juraj_google_style"} +{"code": "def clear(self, size=-1, *, offset=0, chunk=None) -> None:\n\n\n self.mglo.clear(size, offset, chunk)", "docstring": "Clear the content.\n\nArgs:\n size (int): The size. Value ``-1`` means all.\n\n Keyword Args:\n offset (int): The offset.\n chunk (bytes): The chunk to use repeatedly.", "source": "juraj_google_style"} +{"code": "def fail_deployment(self, id):\n\n fail_json = {\"DeploymentID\": id}\n return self.request(\"fail\", id, json=fail_json, method=\"post\").json()", "docstring": "This endpoint is used to mark a deployment as failed. This should be done to force the scheduler to stop\n creating allocations as part of the deployment or to cause a rollback to a previous job version.\n\n https://www.nomadproject.io/docs/http/deployments.html\n\nArgs:\n - id\n returns: dict\n\nRaises:\n - nomad.api.exceptions.BaseNomadException\n - nomad.api.exceptions.URLNotFoundNomadException", "source": "juraj_google_style"} +{"code": "def get_padding_bias(x):\n\n with tf.name_scope(\"attention_bias\"):\n padding = get_padding(x)\n attention_bias = padding * _NEG_INF\n attention_bias = tf.expand_dims(\n tf.expand_dims(attention_bias, axis=1), axis=1)\n return attention_bias", "docstring": "Calculate bias tensor from padding values in tensor.\n\n Bias tensor that is added to the pre-softmax multi-headed attention logits,\n which has shape [batch_size, num_heads, length, length]. The tensor is zero at\n non-padding locations, and -1e9 (negative infinity) at padding locations.\n\nArgs:\n x: int tensor with shape [batch_size, length]\n\nReturns:\n Attention bias tensor of shape [batch_size, 1, 1, length].", "source": "juraj_google_style"} +{"code": "def put(self, key, value):\n\n if value is None:\n self.delete(key)\n else:\n self._collection(key)[key] = value", "docstring": "Stores the object `value` named by `key`.\n\n Stores the object in the collection corresponding to ``key.path``.\n\nArgs:\n key: Key naming `value`\n value: the object to store.", "source": "juraj_google_style"} +{"code": "def __init__(self, structure, element):\n\n self.structure = structure\n self.element = element\n\n # Find equivalent site list\n sga = SpacegroupAnalyzer(self.structure)\n self.symm_structure = sga.get_symmetrized_structure()\n\n self.equiv_sub = []\n for equiv_site_set in list(self.symm_structure.equivalent_sites):\n vac_site = equiv_site_set[0]\n if isinstance(element, str): # make sure you compare with specie symbol or Element type\n vac_specie = vac_site.specie.symbol\n else:\n vac_specie = vac_site.specie\n if element != vac_specie:\n defect_site = PeriodicSite(element, vac_site.coords, structure.lattice, coords_are_cartesian=True)\n sub = Substitution(structure, defect_site)\n self.equiv_sub.append(sub)", "docstring": "Initializes a Substitution Generator\n note: an Antisite is considered a type of substitution\n\nArgs:\n structure(Structure): pymatgen structure object\n element (str or Element or Specie): element for the substitution", "source": "juraj_google_style"} +{"code": "def process_result_value(self, value, dialect):\n\n masks = list()\n if value:\n for e in enums.CryptographicUsageMask:\n if e.value & value:\n masks.append(e)\n return masks", "docstring": "Returns a new list of enums.CryptographicUsageMask Enums. This converts\n the integer value into the list of enums.\n\nArgs:\n value(int): The integer value stored in the database that is used\n to create the list of enums.CryptographicUsageMask Enums.\n dialect(string): SQL dialect", "source": "juraj_google_style"} +{"code": "def mash_dist_trusted(fasta_path):\n\n args = [MASH_BIN,\n 'dist',\n MASH_SKETCH_FILE,\n fasta_path]\n p = Popen(args, stderr=PIPE, stdout=PIPE)\n (stdout, stderr) = p.communicate()\n retcode = p.returncode\n if retcode != 0:\n raise Exception('Could not run Mash dist {}'.format(stderr))\n\n return stdout", "docstring": "Compute Mash distances of sketch file of genome fasta to RefSeq sketch DB.\n\nArgs:\n mash_bin (str): Mash binary path\n\nReturns:\n (str): Mash STDOUT string", "source": "juraj_google_style"} +{"code": "def normalize(code):\n\n if len(code) == 3:\n return code\n\n normalized = translate(code)\n\n if normalized:\n return normalized\n\n country = countries.get(code, None)\n\n if country:\n return country.alpha3.lower()\n\n return code", "docstring": "Normalize language codes to ISO 639-2. If all conversions fails, return the\n `code` as it was given.\n\nArgs:\n code (str): Language / country code.\n\nReturns:\n str: ISO 639-2 country code.", "source": "juraj_google_style"} +{"code": "def overwrite_workspace_config(namespace, workspace, cnamespace, configname, body):\n\n headers = _fiss_agent_header({\"Content-type\": \"application/json\"})\n uri = \"workspaces/{0}/{1}/method_configs/{2}/{3}\".format(namespace,\n workspace, cnamespace, configname)\n return __put(uri, headers=headers, json=body)", "docstring": "Add or overwrite method configuration in workspace.\n\nArgs:\n namespace (str): project to which workspace belongs\n workspace (str): Workspace name\n cnamespace (str): Configuration namespace\n configname (str): Configuration name\n body (json): new body (definition) of the method config\n\n Swagger:\n https://api.firecloud.org/#!/Method_Configurations/overwriteWorkspaceMethodConfig", "source": "juraj_google_style"} +{"code": "def get_supervisor(func: types.AnyFunction) -> types.Supervisor:\n\n if not callable(func):\n raise TypeError(\"func is not callable\")\n if asyncio.iscoroutinefunction(func):\n supervisor = _async_supervisor\n else:\n supervisor = _sync_supervisor\n return functools.partial(supervisor, func)", "docstring": "Get the appropriate supervisor to use and pre-apply the function.\n\nArgs:\n func: A function.", "source": "juraj_google_style"} +{"code": "def Readdir(self, path, fh=None):\n\n if self.DataRefreshRequired(path):\n self._RunAndWaitForVFSFileUpdate(path)\n\n return super(GRRFuse, self).Readdir(path, fh=None)", "docstring": "Updates the directory listing from the client.\n\nArgs:\n path: The path to the directory to update. Client is inferred from this.\n fh: A file handler. Not used.\n\nReturns:\n A list of filenames.", "source": "juraj_google_style"} +{"code": "def _scalar_to_vector(self, m):\n\n if not isinstance(m.y0, numbers.Number):\n return m\n else:\n m = copy.deepcopy(m)\n t0 = 0.0\n if isinstance(m.y0, numbers.Integral):\n numtype = np.float64\n else:\n numtype = type(m.y0)\n y0_orig = m.y0\n m.y0 = np.array([m.y0], dtype=numtype)\n def make_vector_fn(fn):\n def newfn(y, t):\n return np.array([fn(y[0], t)], dtype=numtype)\n newfn.__name__ = fn.__name__\n return newfn\n def make_matrix_fn(fn):\n def newfn(y, t):\n return np.array([[fn(y[0], t)]], dtype=numtype)\n newfn.__name__ = fn.__name__\n return newfn\n def make_coupling_fn(fn):\n def newfn(source_y, target_y, weight):\n return np.array([fn(source_y[0], target_y[0], weight)])\n newfn.__name__ = fn.__name__\n return newfn\n if isinstance(m.f(y0_orig, t0), numbers.Number):\n m.f = make_vector_fn(m.f)\n if hasattr(m, 'G') and isinstance(m.G(y0_orig,t0), numbers.Number):\n m.G = make_matrix_fn(m.G)\n if (hasattr(m, 'coupling') and\n isinstance(m.coupling(y0_orig, y0_orig, 0.5),\n numbers.Number)):\n m.coupling = make_coupling_fn(m.coupling)\n return m", "docstring": "Allow submodels with scalar equations. Convert to 1D vector systems.\n\nArgs:\n m (Model)", "source": "juraj_google_style"} +{"code": "def port(self, value):\n\n\n self._port = value\n # If port is None we remove the element and don't write it to XML\n if value is None:\n try:\n del self._connectionXML.attrib['port']\n except KeyError:\n pass\n else:\n self._connectionXML.set('port', value)", "docstring": "Set the connection's port property.\n\nArgs:\n value: New port value. String.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def pyrdf2(value, class_type=None, datatype=None, lang=None, **kwargs):\n\n try:\n\n if isinstance(value, dict):\n # test to see if the type is a literal, a literal will have a another\n # dictionary key call datatype. Feed the datatype to the lookup to\n # return the value else convert it to a XsdString\n if value.get('type') == \"literal\":\n if not value.get(\"datatype\"):\n return XsdString(value['value'])\n else:\n try:\n if value.get(\"lang\"):\n # The lang keyword only applies to XsdString types\n return DT_LOOKUP[value['datatype']](value['value'],\n lang=value.get(\"lang\"))\n else:\n return DT_LOOKUP[value['datatype']](value['value'])\n except:\n rtn_val = BaseRdfDataType(value['value'])\n rtn_val.datatype = Uri(value['datatype'])\n return rtn_val\n else:\n return DT_LOOKUP[value['type']](value['value'])\n elif isinstance(value, BaseRdfDataType):\n return value\n else:\n return DT_LOOKUP[type(value)](value)\n except:\n pdb.set_trace()\n pass", "docstring": "Coverts an input to one of the rdfdatatypes classes\n\nArgs:\n value: any rdfdatatype, json dict or vlaue\n class_type: \"literal\", \"uri\" or \"blanknode\"\n datatype: \"xsd:string\", \"xsd:int\" , etc", "source": "juraj_google_style"} +{"code": "def update_factor(self, name, body):\n\n url = self._url('factors/{}'.format(name))\n return self.client.put(url, data=body)", "docstring": "Update Guardian factor\n Useful to enable / disable factor\n\nArgs:\n name (str): Either push-notification or sms\n body (dict): Attributes to modify.\n See: https://auth0.com/docs/api/management/v2#!/Guardian/put_factors_by_name", "source": "juraj_google_style"} +{"code": "def find_contacts(self, geoms_1, geoms_2):\n\n for contact in self.sim.data.contact[0 : self.sim.data.ncon]:\n # check contact geom in geoms\n c1_in_g1 = self.sim.model.geom_id2name(contact.geom1) in geoms_1\n c2_in_g2 = self.sim.model.geom_id2name(contact.geom2) in geoms_2\n # check contact geom in geoms (flipped)\n c2_in_g1 = self.sim.model.geom_id2name(contact.geom2) in geoms_1\n c1_in_g2 = self.sim.model.geom_id2name(contact.geom1) in geoms_2\n if (c1_in_g1 and c2_in_g2) or (c1_in_g2 and c2_in_g1):\n yield contact", "docstring": "Finds contact between two geom groups.\n\nArgs:\n geoms_1: a list of geom names (string)\n geoms_2: another list of geom names (string)\n\nReturns:\n iterator of all contacts between @geoms_1 and @geoms_2", "source": "juraj_google_style"} +{"code": "def image_path_from_index(self, index):\n\n assert self.image_set_index is not None, \"Dataset not initialized\"\n name = self.image_set_index[index]\n image_file = os.path.join(self.image_dir, 'images', name)\n assert os.path.isfile(image_file), 'Path does not exist: {}'.format(image_file)\n return image_file", "docstring": "given image index, find out full path\n\n Parameters:\n ----------\n index: int\n index of a specific image\n\nReturns:\n ----------\n full path of this image", "source": "juraj_google_style"} +{"code": "def product_name(self):\n\n buf = (ctypes.c_char * self.MAX_BUF_SIZE)()\n self._dll.JLINKARM_EMU_GetProductName(buf, self.MAX_BUF_SIZE)\n return ctypes.string_at(buf).decode()", "docstring": "Returns the product name of the connected J-Link.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n Product name.", "source": "juraj_google_style"} +{"code": "def _execute(self, request):\n\n if self._rate_limiter:\n # Since the ratelimiter library only exposes a context manager\n # interface the code has to be duplicated to handle the case where\n # no rate limiter is defined.\n with self._rate_limiter:\n return request.execute(http=self.http,\n num_retries=self._num_retries)\n return request.execute(http=self.http,\n num_retries=self._num_retries)", "docstring": "Run execute with retries and rate limiting.\n\nArgs:\n request (object): The HttpRequest object to execute.\n\nReturns:\n dict: The response from the API.", "source": "juraj_google_style"} +{"code": "def getbalance(self, user_id=\"\", as_decimal=True):\n\n balance = unicode(self.rpc.call(\"getbalance\", user_id))\n self.logger.debug(\"\\\"\" + user_id + \"\\\"\", self.coin, \"balance:\", balance)\n if as_decimal:\n return Decimal(balance)\n else:\n return balance", "docstring": "Calculate the total balance in all addresses belonging to this user.\n\nArgs:\n user_id (str): this user's unique identifier\n as_decimal (bool): balance is returned as a Decimal if True (default)\n or a string if False\n\nReturns:\n str or Decimal: this account's total coin balance", "source": "juraj_google_style"} +{"code": "def update_box_field(self, box_key, field):\n\n\t\t#does not work\n\t\tself._raise_unimplemented_error()\n\n\t\turi = '/'.join([self.api_uri,\n\t\t\t\t\t\tself.boxes_suffix,\n\t\t\t\t\t\tbox_key,\n\t\t\t\t\t\tself.fields_suffix\n\t\t\t\t\t\t])\n\t\treturn self._update_field(uri, field)", "docstring": "Upates box field as specified\n\nArgs:\n box_key\t\tkey for pipeline where the fields lives\n field \t\t\t\tStreakField object with fresh data\n returns\t\t\t\t(status code, updated field dict)", "source": "juraj_google_style"} +{"code": "def __init__(\n self,\n routes,\n ):\n\n self.routes = type_assert_iter(\n routes,\n Route,\n )\n check_dups(routes)", "docstring": "desc: Contains the URIs for this service\n\nArgs:\n - name: routes\n type: list\n subtypes: [Route]\n desc: a mapping of URIs to Route instances\n ctor: pymarshal.api_docs.routes.Route.__init__", "source": "juraj_google_style"} +{"code": "def __init__(self, base, analysis_function, time_limit=5.0):\n\n self._base = base\n self._analysis_function = analysis_function\n self._tile_images = self._create_tile_images()\n self._analyze_start_time = None\n self.time_limit = time_limit\n self.summaries = None\n self._parts = self._setup_parts(self._base)", "docstring": "Setup the common UI elements and behavior for a PQ Game UI.\n\nArgs:\n - base: a tkinter base element in which to create parts", "source": "juraj_google_style"} +{"code": "def __init__(self, client, base_path):\n\n self._client = client\n self._base_path = base_path\n self._queue_path = posixpath.join(self._base_path, 'queue', '')\n self._counter_path = posixpath.join(self._queue_path, 'counter')\n self._ensure_counter()\n self._ensure_queue()", "docstring": "Initialise the class.\n\nArgs:\n client (:class:`consulate.Consul`): A :class:`consulate.Consul` instance.\n base_path (str): the base path to use in Consul.", "source": "juraj_google_style"} +{"code": "def abort_expired_batches(self, request_timeout_ms, cluster):\n\n expired_batches = []\n to_remove = []\n count = 0\n for tp in list(self._batches.keys()):\n assert tp in self._tp_locks, 'TopicPartition not in locks dict'\n\n # We only check if the batch should be expired if the partition\n # does not have a batch in flight. This is to avoid the later\n # batches get expired when an earlier batch is still in progress.\n # This protection only takes effect when user sets\n # max.in.flight.request.per.connection=1. Otherwise the expiration\n # order is not guranteed.\n if tp in self.muted:\n continue\n\n with self._tp_locks[tp]:\n # iterate over the batches and expire them if they have stayed\n # in accumulator for more than request_timeout_ms\n dq = self._batches[tp]\n for batch in dq:\n is_full = bool(bool(batch != dq[-1]) or batch.records.is_full())\n # check if the batch is expired\n if batch.maybe_expire(request_timeout_ms,\n self.config['retry_backoff_ms'],\n self.config['linger_ms'],\n is_full):\n expired_batches.append(batch)\n to_remove.append(batch)\n count += 1\n self.deallocate(batch)\n else:\n # Stop at the first batch that has not expired.\n break\n\n # Python does not allow us to mutate the dq during iteration\n # Assuming expired batches are infrequent, this is better than\n # creating a new copy of the deque for iteration on every loop\n if to_remove:\n for batch in to_remove:\n dq.remove(batch)\n to_remove = []\n\n if expired_batches:\n log.warning(\"Expired %d batches in accumulator\", count) # trace\n\n return expired_batches", "docstring": "Abort the batches that have been sitting in RecordAccumulator for\n more than the configured request_timeout due to metadata being\n unavailable.\n\nArgs:\n request_timeout_ms (int): milliseconds to timeout\n cluster (ClusterMetadata): current metadata for kafka cluster\n\nReturns:\n list of ProducerBatch that were expired", "source": "juraj_google_style"} +{"code": "def console_set_char_background(\n con: tcod.console.Console,\n x: int,\n y: int,\n col: Tuple[int, int, int],\n flag: int = BKGND_SET,\n) -> None:\n\n lib.TCOD_console_set_char_background(_console(con), x, y, col, flag)", "docstring": "Change the background color of x,y to col using a blend mode.\n\nArgs:\n con (Console): Any Console instance.\n x (int): Character x position from the left.\n y (int): Character y position from the top.\n col (Union[Tuple[int, int, int], Sequence[int]]):\n An (r, g, b) sequence or Color instance.\n flag (int): Blending mode to use, defaults to BKGND_SET.", "source": "juraj_google_style"} +{"code": "def hpo_term(self, hpo_id):\n\n LOG.debug(\"Fetching hpo term %s\", hpo_id)\n\n return self.hpo_term_collection.find_one({'_id': hpo_id})", "docstring": "Fetch a hpo term\n\nArgs:\n hpo_id(str)\n\nReturns:\n hpo_obj(dict)", "source": "juraj_google_style"} +{"code": "def DOMDebugger_removeInstrumentationBreakpoint(self, eventName):\n\n\t\tassert isinstance(eventName, (str,)\n\t\t ), \"Argument 'eventName' must be of type '['str']'. Received type: '%s'\" % type(\n\t\t eventName)\n\t\tsubdom_funcs = self.synchronous_command(\n\t\t 'DOMDebugger.removeInstrumentationBreakpoint', eventName=eventName)\n\t\treturn subdom_funcs", "docstring": "Function path: DOMDebugger.removeInstrumentationBreakpoint\n Domain: DOMDebugger\n Method name: removeInstrumentationBreakpoint\n\n WARNING: This function is marked 'Experimental'!\n\n Parameters:\n Required arguments:\n 'eventName' (type: string) -> Instrumentation name to stop on.\n No return value.\n\n Description: Removes breakpoint on particular native event.", "source": "juraj_google_style"} +{"code": "def _ReadTable(self, tables, file_object, table_offset):\n\n table_header = self._ReadTableHeader(file_object, table_offset)\n\n for record_offset in table_header.record_offsets:\n if record_offset == 0:\n continue\n\n record_offset += table_offset\n\n if table_header.record_type == self._RECORD_TYPE_CSSM_DL_DB_SCHEMA_INFO:\n self._ReadRecordSchemaInformation(tables, file_object, record_offset)\n elif table_header.record_type == (\n self._RECORD_TYPE_CSSM_DL_DB_SCHEMA_INDEXES):\n self._ReadRecordSchemaIndexes(tables, file_object, record_offset)\n elif table_header.record_type == (\n self._RECORD_TYPE_CSSM_DL_DB_SCHEMA_ATTRIBUTES):\n self._ReadRecordSchemaAttributes(tables, file_object, record_offset)\n else:\n self._ReadRecord(\n tables, file_object, record_offset, table_header.record_type)", "docstring": "Reads the table.\n\nArgs:\n tables (dict[int, KeychainDatabaseTable]): tables per identifier.\n file_object (file): file-like object.\n table_offset (int): offset of the table relative to the start of\n the file.\n\nRaises:\n ParseError: if the table cannot be read.", "source": "juraj_google_style"} +{"code": "def __init__(self, name, data=None, package_cls=None):\n\n super(PackageMaker, self).__init__(data)\n self.name = name\n self.package_cls = package_cls or Package\n\n # set by `make_package`\n self.installed_variants = []\n self.skipped_variants = []", "docstring": "Create a package maker.\n\nArgs:\n name (str): Package name.", "source": "juraj_google_style"} +{"code": "def get_forecast_errors(y_hat,\n y_true,\n window_size=5,\n batch_size=30,\n smoothing_percent=0.05,\n smoothed=True):\n\n errors = [abs(y_h - y_t) for y_h, y_t in zip(y_hat, y_true)]\n\n if not smoothed:\n return errors\n\n historical_error_window = int(window_size * batch_size * smoothing_percent)\n moving_avg = []\n for i in range(len(errors)):\n left_window = i - historical_error_window\n right_window = i + historical_error_window + 1\n if left_window < 0:\n left_window = 0\n\n if right_window > len(errors):\n right_window = len(errors)\n\n moving_avg.append(np.mean(errors[left_window:right_window]))\n\n return moving_avg", "docstring": "Calculates the forecasting error for two arrays of data. If smoothed errors desired,\n runs EWMA.\n\nArgs:\n y_hat (list): forecasted values. len(y_hat)==len(y_true).\n y_true (list): true values. len(y_hat)==len(y_true).\n window_size (int):\n batch_size (int):\n smoothing_percent (float):\n smoothed (bool): whether the returned errors should be smoothed with EWMA.\n\nReturns:\n (list): error residuals. Smoothed if specified by user.", "source": "juraj_google_style"} +{"code": "def create_finance_metrics(metrics: list, pronacs: list):\n\n missing = missing_metrics(metrics, pronacs)\n print(f\"There are {len(missing)} missing metrics!\")\n\n processors = mp.cpu_count()\n print(f\"Using {processors} processors to calculate metrics!\")\n\n indicators_qs = FinancialIndicator.objects.filter(\n project_id__in=[p for p, _ in missing]\n )\n indicators = {i.project_id: i for i in indicators_qs}\n\n pool = mp.Pool(processors)\n results = [\n pool.apply_async(create_metric, args=(indicators, metric_name, pronac))\n for pronac, metric_name in missing\n ]\n\n calculated_metrics = [p.get() for p in results]\n if calculated_metrics:\n Metric.objects.bulk_create(calculated_metrics)\n print(\"Bulk completed\")\n\n for indicator in indicators.values():\n indicator.fetch_weighted_complexity()\n\n print(\"Finished update indicators!\")\n\n pool.close()\n print(\"Finished metrics calculation!\")", "docstring": "Creates metrics, creating an Indicator if it doesn't already exists\n Metrics are created for projects that are in pronacs and saved in\n database.\n\nArgs:\n metrics: list of names of metrics that will be calculated\n pronacs: pronacs in dataset that is used to calculate those metrics", "source": "juraj_google_style"} +{"code": "def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):\n\n from modelx.core.cells import shareable_parameters\n\n if len(args):\n indexes = shareable_parameters(cellsiter)\n else:\n indexes = get_all_params(cellsiter.values())\n\n result = None\n\n for cells in cellsiter.values():\n df = cells_to_dataframe(cells, args)\n\n if drop_allna and df.isnull().all().all():\n continue # Ignore all NA or empty\n\n if df.index.names != [None]:\n if isinstance(df.index, pd.MultiIndex):\n if _pd_ver < (0, 20):\n df = _reset_naindex(df)\n\n df = df.reset_index()\n\n missing_params = set(indexes) - set(df)\n\n for params in missing_params:\n df[params] = np.nan\n\n if result is None:\n result = df\n else:\n try:\n result = pd.merge(result, df, how=\"outer\")\n except MergeError:\n # When no common column exists, i.e. all cells are scalars.\n result = pd.concat([result, df], axis=1)\n except ValueError:\n # When common columns are not coercible (numeric vs object),\n # Make the numeric column object type\n cols = set(result.columns) & set(df.columns)\n for col in cols:\n\n # When only either of them has object dtype\n if (\n len(\n [\n str(frame[col].dtype)\n for frame in (result, df)\n if str(frame[col].dtype) == \"object\"\n ]\n )\n == 1\n ):\n\n if str(result[col].dtype) == \"object\":\n frame = df\n else:\n frame = result\n frame[[col]] = frame[col].astype(\"object\")\n\n # Try again\n result = pd.merge(result, df, how=\"outer\")\n\n if result is None:\n return pd.DataFrame()\n else:\n return result.set_index(indexes) if indexes else result", "docstring": "Convert multiple cells to a frame.\n\n If args is an empty sequence, all values are included.\n If args is specified, cellsiter must have shareable parameters.\n\nArgs:\n cellsiter: A mapping from cells names to CellsImpl objects.\n args: A sequence of arguments", "source": "juraj_google_style"} +{"code": "def create(self, project_id=None):\n\n if not self.exists():\n if project_id is None:\n project_id = self._api.project_id\n try:\n self._info = self._api.buckets_insert(self._name, project_id=project_id)\n except Exception as e:\n raise e\n return self", "docstring": "Creates the bucket.\n\nArgs:\n project_id: the project in which to create the bucket.\n\nReturns:\n The bucket.\n\nRaises:\n Exception if there was an error creating the bucket.", "source": "juraj_google_style"} +{"code": "def _bot(self, k):\n\n if k < 2:\n raise ValueError(\"k smaller than 2\")\n G = np.ones((self.m, self.m))\n np.fill_diagonal(G, 0)\n for i in range(self.m):\n for j in range(self.m):\n if i == j:\n continue\n if i <= k and j <= k:\n G[i][j] = 0\n return G", "docstring": "Description:\n Bottom k breaking\n Parameters:\n k: the number of alternatives to break from lowest rank", "source": "juraj_google_style"} +{"code": "def get_built_in(self, language, level, data):\n\n # Language is python\n pp = pprint.PrettyPrinter(indent=level)\n\n lookup = {'python' : pp.pformat(data),\n 'json' : str(json.dumps(data, sort_keys=True, indent=level, separators=(',', ': ')))}\n\n self.data_structure = lookup[language]", "docstring": "Gets the return string for a language that's supported by python.\n Used in cases when python provides support for the conversion.\n\nArgs:\n language: string the langage to return for.\n\n level: integer, the indentation level.\n\n data: python data structure being converted (list of tuples)\n\nReturns:\n None, updates self.data_structure", "source": "juraj_google_style"} +{"code": "def upload(self, title, description=\"\", keywords=\"\", developer_tags=None, access_control=AccessControl.Public):\n\n # Raise ApiError if not authenticated\n if not self.authenticated:\n raise ApiError(_(\"Authentication is required\"))\n\n # create media group\n my_media_group = gdata.media.Group(\n title=gdata.media.Title(text=title),\n description=gdata.media.Description(description_type='plain',\n text=description),\n keywords=gdata.media.Keywords(text=keywords),\n category=[gdata.media.Category(\n text='Autos',\n scheme='http://gdata.youtube.com/schemas/2007/categories.cat',\n label='Autos')],\n #player = None\n )\n\n # Access Control\n extension = self._access_control(access_control, my_media_group)\n\n # create video entry\n video_entry = gdata.youtube.YouTubeVideoEntry(\n media=my_media_group, extension_elements=extension)\n\n # add developer tags\n if developer_tags:\n video_entry.AddDeveloperTags(developer_tags)\n\n # upload meta data only\n response = Api.yt_service.GetFormUploadToken(video_entry)\n\n # parse response tuple and use the variables to build a form\n post_url = response[0]\n youtube_token = response[1]\n\n return {'post_url': post_url, 'youtube_token': youtube_token}", "docstring": "Browser based upload\n Creates the video entry and meta data to initiate a browser upload\n\n Authentication is needed\n\n Params:\n title: string\n description: string\n keywords: comma seperated string\n developer_tags: tuple\n\nReturns:\n dict contains post_url and youtube_token. i.e { 'post_url': post_url, 'youtube_token': youtube_token }\n\nRaises:\n ApiError: on no authentication", "source": "juraj_google_style"} +{"code": "def raster_binarization(given_value, rasterfilename):\n\n origin_raster = RasterUtilClass.read_raster(rasterfilename)\n binary_raster = numpy.where(origin_raster.data == given_value, 1, 0)\n return binary_raster", "docstring": "Make the raster into binarization.\n\n The opening and closing are based on binary image. Therefore we need to\n make the raster into binarization.\n\nArgs:\n given_value: The given value's pixels will be value in 1,\n other pixels will be value in 0.\n rasterfilename: The initial rasterfilena,e.\n\nReturns:\n binary_raster: Raster after binarization.", "source": "juraj_google_style"} +{"code": "def prop(pode, prop):\n\n form = pode[0][0]\n if prop.startswith(form):\n prop = prop[len(form):]\n if prop[0] == ':':\n prop = prop[1:]\n return pode[1]['props'].get(prop)", "docstring": "Return the valu of a given property on the node.\n\nArgs:\n pode (tuple): A packed node.\n prop (str): Property to retrieve.\n\nNote:\n The prop argument may be the full property name (foo:bar:baz), relative property name (:baz) , or the unadorned\n property name (baz).\n\n Returns:", "source": "juraj_google_style"} +{"code": "def _check_module(folder):\n\n if not folder.exists():\n folder.mkdir(parents=True, exist_ok=True, mode=0o755)\n (folder / '__init__.py').touch()", "docstring": "Create module folder with empty __init__.py if it doesn't exist.\n\nArgs:\n folder (pathlib.Path): Module path.", "source": "juraj_google_style"} +{"code": "def __init__(self, api, path, options):\n\n self._init(api, path, options)", "docstring": "Initialize.\n\nArgs:\n api: storage_api instance.\n path: bucket path of form '/bucket'.\n options: a dict of listbucket options. Please see listbucket doc.", "source": "juraj_google_style"} +{"code": "def _are_scopes_sufficient(authorized_scopes, sufficient_scopes):\n\n for sufficient_scope_set in sufficient_scopes:\n if sufficient_scope_set.issubset(authorized_scopes):\n return True\n return False", "docstring": "Check if a list of authorized scopes satisfies any set of sufficient scopes.\n\nArgs:\n authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes\n sufficient_scopes: a set of sets of strings, return value from _process_scopes", "source": "juraj_google_style"} +{"code": "def splitext2(filepath):\n\n root, filename = os.path.split(safepath(filepath))\n filename, ext = os.path.splitext(safepath(filename))\n return root, filename, ext", "docstring": "Split filepath into root, filename, ext\n\nArgs:\n filepath (str, path): file path\n\nReturns:\n str", "source": "juraj_google_style"} +{"code": "def add(self, rule: 'functions.ReplacementRule') -> None:\n\n self.matcher.add(rule.pattern, rule.replacement)", "docstring": "Add a new rule to the replacer.\n\nArgs:\n rule:\n The rule to add.", "source": "juraj_google_style"} +{"code": "def get(name):\n\n for matcher in matchers:\n if matcher.__name__ == name or getattr(matcher, 'name', None) == name:\n return matcher", "docstring": "Returns a matcher instance by class or alias name.\n\nArgs:\n name (str): matcher class name or alias.\n\nReturns:\n matcher: found matcher instance, otherwise ``None``.", "source": "juraj_google_style"} +{"code": "def _configure_tls_parameters(parameters):\n\n cert = config.conf[\"tls\"][\"certfile\"]\n key = config.conf[\"tls\"][\"keyfile\"]\n if cert and key:\n _log.info(\n \"Authenticating with server using x509 (certfile: %s, keyfile: %s)\",\n cert,\n key,\n )\n parameters.credentials = pika.credentials.ExternalCredentials()\n else:\n cert, key = None, None\n\n if SSLOptions is None:\n parameters.ssl = True\n parameters.ssl_options = {\n \"keyfile\": key,\n \"certfile\": cert,\n \"ca_certs\": config.conf[\"tls\"][\"ca_cert\"],\n \"cert_reqs\": ssl.CERT_REQUIRED,\n \"ssl_version\": ssl.PROTOCOL_TLSv1_2,\n }\n else:\n ssl_context = ssl.create_default_context()\n if config.conf[\"tls\"][\"ca_cert\"]:\n try:\n ssl_context.load_verify_locations(cafile=config.conf[\"tls\"][\"ca_cert\"])\n except ssl.SSLError as e:\n raise ConfigurationException(\n 'The \"ca_cert\" setting in the \"tls\" section is invalid ({})'.format(\n e\n )\n )\n ssl_context.options |= ssl.OP_NO_SSLv2\n ssl_context.options |= ssl.OP_NO_SSLv3\n ssl_context.options |= ssl.OP_NO_TLSv1\n ssl_context.options |= ssl.OP_NO_TLSv1_1\n ssl_context.verify_mode = ssl.CERT_REQUIRED\n ssl_context.check_hostname = True\n if cert and key:\n try:\n ssl_context.load_cert_chain(cert, key)\n except ssl.SSLError as e:\n raise ConfigurationException(\n 'The \"keyfile\" setting in the \"tls\" section is invalid ({})'.format(\n e\n )\n )\n parameters.ssl_options = SSLOptions(\n ssl_context, server_hostname=parameters.host\n )", "docstring": "Configure the pika connection parameters for TLS based on the configuration.\n\n This modifies the object provided to it. This accounts for whether or not\n the new API based on the standard library's SSLContext is available for\n pika.\n\nArgs:\n parameters (pika.ConnectionParameters): The connection parameters to apply\n TLS connection settings to.", "source": "juraj_google_style"} +{"code": "def __call__(self, fn):\n\n\n def benchmark(app, *args, **kwargs):\n\n\n # before = float('{0:.4f}'.format(time.clock()))\n before = datetime.datetime.now()\n data = fn(app, *args, **kwargs)\n # after = float('{0:.4f}'.format(time.clock()))\n after = datetime.datetime.now()\n app.tcex.log.debug(\n 'function: \"{}\", benchmark_time: \"{}\"'.format(\n self.__class__.__name__, after - before\n )\n )\n return data\n\n return benchmark", "docstring": "Implement __call__ function for decorator.\n\nArgs:\n fn (function): The decorated function.\n\nReturns:\n function: The custom decorator function.", "source": "juraj_google_style"} +{"code": "def create_app(config=None, config_obj=None):\n\n app = Flask(__name__)\n # configure application from external configs\n configure_app(app, config=config, config_obj=config_obj)\n # register different parts of the application\n register_blueprints(app)\n # setup extensions\n bind_extensions(app)\n return app", "docstring": "Flask app factory function.\n\nArgs:\n config (Optional[path]): path to a Python module config file\n config_obj (Optional[class]): Python config object", "source": "juraj_google_style"} +{"code": "def rms(x):\n\n try:\n return (np.array(x) ** 2).mean() ** 0.5\n except:\n x = np.array(dropna(x))\n invN = 1.0 / len(x)\n return (sum(invN * (x_i ** 2) for x_i in x)) ** .5", "docstring": "Root Mean Square\"\n\nArgs:\n x (seq of float): A sequence of numerical values\n\nReturns:\n The square root of the average of the squares of the values\n\n math.sqrt(sum(x_i**2 for x_i in x) / len(x))\n\n or\n\n return (np.array(x) ** 2).mean() ** 0.5\n\n >>> rms([0, 2, 4, 4])\n 3.0", "source": "juraj_google_style"} +{"code": "def delete_idx_status(self, rdf_class):\n\n\n sparql_template = \n rdf_types = [rdf_class.uri] + [item.uri\n for item in rdf_class.subclasses]\n sparql = sparql_template.format(\"\\n\\t\\t\".join(rdf_types))\n log.warn(\"Deleting index status for %s\", rdf_class.uri)\n return self.tstore_conn.update_query(sparql)", "docstring": "Removes all of the index status triples from the datastore\n\nArgs:\n -----\n rdf_class: The class of items to remove the status from", "source": "juraj_google_style"} +{"code": "def exit_handler(signum, frame):\n\n\n LOGGER.debug('signal {} was caught'.format(signum))\n sys.exit(128 + signum)", "docstring": "Catch SIGTERM and SIGHUP and call \"sys.exit\" which raises\n \"SystemExit\" exception.\n This will trigger all the cleanup code defined in ContextManagers\n and \"finally\" statements.\n\n For more details about the arguments see \"signal\" documentation.\n\nArgs:\n signum(int): The signal's number\n frame(frame): The current stack frame, can be None", "source": "juraj_google_style"} +{"code": "def parameterize(\n self,\n country: Optional[str] = \"South Sudan\",\n state: Optional[str] = None,\n year: Optional[int] = None,\n month: Optional[int] = None,\n unit: Optional[str] = None,\n fallback_aggaxes: List[str] = [\"year\", \"month\"],\n aggfunc: Callable = np.mean,\n ):\n\n\n valid_axes = (\"country\", \"state\", \"year\", \"month\")\n\n if any(map(lambda axis: axis not in valid_axes, fallback_aggaxes)):\n raise ValueError(\n \"All elements of the fallback_aggaxes set must be one of the \"\n f\"following: {valid_axes}\"\n )\n\n for n in self.nodes(data=True):\n for indicator in n[1][\"indicators\"].values():\n indicator.mean, indicator.unit = get_indicator_value(\n indicator,\n country,\n state,\n year,\n month,\n unit,\n fallback_aggaxes,\n aggfunc,\n )\n indicator.stdev = 0.1 * abs(indicator.mean)", "docstring": "Parameterize the analysis graph.\n\nArgs:\n country\n year\n month\n fallback_aggaxes:\n An iterable of strings denoting the axes upon which to perform\n fallback aggregation if the desired constraints cannot be met.\n aggfunc: The function that will be called to perform the\n aggregation if there are multiple matches.", "source": "juraj_google_style"} +{"code": "def _isbn_cleanse(isbn, checksum=True):\n\n if not isinstance(isbn, string_types):\n raise TypeError('ISBN must be a string, received %r' % isbn)\n\n if PY2 and isinstance(isbn, str): # pragma: Python 2\n isbn = unicode(isbn)\n uni_input = False\n else: # pragma: Python 3\n uni_input = True\n\n for dash in DASHES:\n isbn = isbn.replace(dash, unicode())\n\n if checksum:\n if not isbn[:-1].isdigit():\n raise IsbnError('non-digit parts')\n if len(isbn) == 9:\n isbn = '0' + isbn\n if len(isbn) == 10:\n if not (isbn[-1].isdigit() or isbn[-1] in 'Xx'):\n raise IsbnError('non-digit or X checksum')\n elif len(isbn) == 13:\n if not isbn[-1].isdigit():\n raise IsbnError('non-digit checksum')\n if not isbn.startswith(('978', '979')):\n raise IsbnError('invalid Bookland region')\n else:\n raise IsbnError('ISBN must be either 10 or 13 characters long')\n else:\n if len(isbn) == 8:\n isbn = '0' + isbn\n elif len(isbn) == 12 and not isbn[:3].startswith(('978', '979')):\n raise IsbnError('invalid Bookland region')\n if not isbn.isdigit():\n raise IsbnError('non-digit parts')\n if not len(isbn) in (9, 12):\n raise IsbnError('ISBN must be either 9 or 12 characters long '\n 'without checksum')\n if PY2 and not uni_input: # pragma: Python 2\n # Sadly, type ping-pong is required to maintain backwards compatibility\n # with previous pyisbn releases for Python 2 users.\n return str(isbn)\n else: # pragma: Python 3\n return isbn", "docstring": "Check ISBN is a string, and passes basic sanity checks.\n\nArgs:\n isbn (str): SBN, ISBN-10 or ISBN-13\n checksum (bool): ``True`` if ``isbn`` includes checksum character\n\nReturns:\n ``str``: ISBN with hyphenation removed, including when called with a\n SBN\n\nRaises:\n TypeError: ``isbn`` is not a ``str`` type\n IsbnError: Incorrect length for ``isbn``\n IsbnError: Incorrect SBN or ISBN formatting", "source": "juraj_google_style"} +{"code": "def topsSSE(symbols=None, on_data=None, token='', version=''):\n\n return _runSSE('tops', symbols, on_data, token, version)", "docstring": "TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book.\n TOPS is ideal for developers needing both quote and trade data.\n\n https://iexcloud.io/docs/api/#tops\n\nArgs:\n symbols (string); Tickers to request\n on_data (function): Callback on data\n token (string); Access token\n version (string); API version", "source": "juraj_google_style"} +{"code": "def is_control(input, model_file=None, model_proto=None, name=None):\n\n\n return _gen_sentencepiece_processor_op.sentencepiece_get_piece_type(\n input, model_file=model_file, model_proto=model_proto, name=name,\n piece_type=1)", "docstring": "Returns true if input id is control piece.\n\nArgs:\n input: An arbitrary tensor of int32.\n model_file: The sentencepiece model file path.\n model_proto: The sentencepiece model serialized proto.\n Either `model_file` or `model_proto` must be set.\n name: The name argument that is passed to the op function.\n\nReturns:\n A tensor of bool with the same shape as input.", "source": "juraj_google_style"} +{"code": "def __call__(self, environ, start_response): # pylint: disable=invalid-name\n\n request = wrappers.Request(environ)\n parsed_url = urlparse.urlparse(request.path)\n clean_path = _clean_path(parsed_url.path, self._path_prefix)\n\n # pylint: disable=too-many-function-args\n if clean_path in self.data_applications:\n return self.data_applications[clean_path](environ, start_response)\n else:\n logger.warn('path %s not found, sending 404', clean_path)\n return http_util.Respond(request, 'Not found', 'text/plain', code=404)(\n environ, start_response)", "docstring": "Central entry point for the TensorBoard application.\n\n This method handles routing to sub-applications. It does simple routing\n using regular expression matching.\n\n This __call__ method conforms to the WSGI spec, so that instances of this\n class are WSGI applications.\n\nArgs:\n environ: See WSGI spec.\n start_response: See WSGI spec.\n\nReturns:\n A werkzeug Response.", "source": "juraj_google_style"} +{"code": "def export_to_tf_tensor(self, x):\n\n mesh_impl = self.mesh_impl(x)\n return mesh_impl.export_to_tf_tensor(\n x, self.tensors[x].to_laid_out_tensor())", "docstring": "Turn a Tensor into a tf.Tensor.\n\nArgs:\n x: Tensor.\n\nReturns:\n tf.Tensor.", "source": "juraj_google_style"} +{"code": "def __init__(self, fold_scope_location, field_type):\n\n super(FoldedContextField, self).__init__(fold_scope_location, field_type)\n self.fold_scope_location = fold_scope_location\n self.field_type = field_type\n self.validate()", "docstring": "Construct a new FoldedContextField object for this folded field.\n\nArgs:\n fold_scope_location: FoldScopeLocation specifying the location of\n the context field being output.\n field_type: GraphQL type object, specifying the type of the field being output.\n Since the field is folded, this must be a GraphQLList of some kind.\n\nReturns:\n new FoldedContextField object", "source": "juraj_google_style"} +{"code": "def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec):\n\n key_ranges_by_ns = []\n # Split each ns into n splits. If a ns doesn't have enough scatter to\n # split into n, the last few splits are None.\n for namespace in namespaces:\n ranges = cls._split_ns_by_scatter(\n shard_count,\n namespace,\n query_spec.entity_kind,\n app)\n # The nth split of each ns will be assigned to the nth shard.\n # Shuffle so that None are not all by the end.\n random.shuffle(ranges)\n key_ranges_by_ns.append(ranges)\n\n # KeyRanges from different namespaces might be very different in size.\n # Use round robin to make sure each shard can have at most one split\n # or a None from a ns.\n ranges_by_shard = [[] for _ in range(shard_count)]\n for ranges in key_ranges_by_ns:\n for i, k_range in enumerate(ranges):\n if k_range:\n ranges_by_shard[i].append(k_range)\n\n key_ranges_by_shard = []\n for ranges in ranges_by_shard:\n if ranges:\n key_ranges_by_shard.append(key_ranges.KeyRangesFactory.create_from_list(\n ranges))\n return key_ranges_by_shard", "docstring": "Get a list of key_ranges.KeyRanges objects, one for each shard.\n\n This method uses scatter index to split each namespace into pieces\n and assign those pieces to shards.\n\nArgs:\n app: app_id in str.\n namespaces: a list of namespaces in str.\n shard_count: number of shards to split.\n query_spec: model.QuerySpec.\n\nReturns:\n a list of key_ranges.KeyRanges objects.", "source": "juraj_google_style"} +{"code": "def _addResults(self, results):\n\n # -----------------------------------------------------------------------\n # If the model potentially has temporal inferences.\n if self.__isTemporal:\n shiftedInferences = self.__inferenceShifter.shift(results).inferences\n self.__currentResult = copy.deepcopy(results)\n self.__currentResult.inferences = shiftedInferences\n self.__currentInference = shiftedInferences\n\n # -----------------------------------------------------------------------\n # The current model has no temporal inferences.\n else:\n self.__currentResult = copy.deepcopy(results)\n self.__currentInference = copy.deepcopy(results.inferences)\n\n # -----------------------------------------------------------------------\n # Save the current ground-truth results\n self.__currentGroundTruth = copy.deepcopy(results)", "docstring": "Stores the current model results in the manager's internal store\n\n Parameters:\n -----------------------------------------------------------------------\n results: A ModelResults object that contains the current timestep's\n input/inferences", "source": "juraj_google_style"} +{"code": "def find(self, instance_id):\n\n instance = AtlasServiceInstance.Instance(instance_id, self.backend)\n self.backend.storage.populate(instance)\n return instance", "docstring": "find an instance\n\n Create a new instance and populate it with data stored if it exists.\n\nArgs:\n instance_id (str): UUID of the instance\n\nReturns:\n AtlasServiceInstance.Instance: An instance", "source": "juraj_google_style"} +{"code": "def _get_flags(osm_obj):\n\n flags = []\n if osm_obj.visible:\n flags.append('visible')\n if osm_obj.user:\n flags.append('user: %s' % osm_obj.user)\n if osm_obj.timestamp:\n flags.append('timestamp: %s' % osm_obj.timestamp.isoformat())\n if osm_obj.tags:\n flags.append(', '.join('%s: %s' % (k, v)\n for k, v in sorted(osm_obj.tags.items())))\n return flags", "docstring": "Create element independent flags output.\n\nArgs:\n osm_obj (Node): Object with OSM-style metadata\n\nReturns:\n list: Human readable flags output", "source": "juraj_google_style"} +{"code": "def make_string_field_value(cls, field):\n\n if field.regex is not None:\n raise NotImplementedError\n\n string_range = cls.get_range(field)\n\n return cls.get_random_string(string_range)", "docstring": "String Field has three constraints (apart from anything\n in the super class)\n\nArgs:\n field (StringField): actual string field object from a\n model declaration\n\nReturns:\n random string value", "source": "juraj_google_style"} +{"code": "def task(self, task_uuid):\n\n request = clearly_pb2.FindTaskRequest(task_uuid=task_uuid)\n task = self._stub.find_task(request)\n if task.uuid:\n ClearlyClient._display_task(task, True, True, True)\n else:\n print(EMPTY)", "docstring": "Finds one specific task.\n\nArgs:\n task_uuid (str): the task id", "source": "juraj_google_style"} +{"code": "def find_container_traits(cls_or_string):\n\n\n if utils.is_str(cls_or_string):\n if not templates.is_instantiation(cls_or_string):\n return None\n name = templates.name(cls_or_string)\n if name.startswith('std::'):\n name = name[len('std::'):]\n if name.startswith('std::tr1::'):\n name = name[len('std::tr1::'):]\n for cls_traits in all_container_traits:\n if cls_traits.name() == name:\n return cls_traits\n else:\n\n if isinstance(cls_or_string, class_declaration.class_types):\n # Look in the cache.\n if cls_or_string.cache.container_traits is not None:\n return cls_or_string.cache.container_traits\n\n # Look for a container traits\n for cls_traits in all_container_traits:\n if cls_traits.is_my_case(cls_or_string):\n # Store in the cache\n if isinstance(cls_or_string, class_declaration.class_types):\n cls_or_string.cache.container_traits = cls_traits\n return cls_traits", "docstring": "Find the container traits type of a declaration.\n\nArgs:\n cls_or_string (str | declarations.declaration_t): a string\n\nReturns:\n declarations.container_traits: a container traits", "source": "juraj_google_style"} +{"code": "def open_audio(frequency=44100, format=AudioFormat.default, channels=2, chunksize=1024):\n\n check_int_err(lib.Mix_OpenAudio(frequency, format, channels, chunksize))", "docstring": "Open the mixer with a certain audio format.\n\nArgs:\n frequency (int): Output sampling frequency in samples per second (Hz).\n format (AudioFormat): Output sample format.\n channels (int): Number of sound channels in output. Set to 2 for stereo, 1 for mono.\n chunksize (int): Bytes used per output sample.\n\nRaises:\n SDLError: If the audio device cannot be opened.", "source": "juraj_google_style"} +{"code": "def __init__(self, backend, job_id):\n\n self._job_id = job_id\n self._backend = backend", "docstring": "Initializes the asynchronous job.\n\nArgs:\n backend (BaseBackend): the backend used to run the job.\n job_id (str): a unique id in the context of the backend used to run\n the job.", "source": "juraj_google_style"} +{"code": "def from_Z(z: int):\n\n for sym, data in _pt_data.items():\n if data[\"Atomic no\"] == z:\n return Element(sym)\n raise ValueError(\"No element with this atomic number %s\" % z)", "docstring": "Get an element from an atomic number.\n\nArgs:\n z (int): Atomic number\n\nReturns:\n Element with atomic number z.", "source": "juraj_google_style"} +{"code": "def dump(ofp, *pb_objs, **kwargs):\n\n mode = 'wb'\n if isinstance(ofp, str):\n ostream = open(ofp, mode=mode, **kwargs)\n else:\n ostream = open(fileobj=ofp, mode=mode, **kwargs)\n with ostream:\n ostream.write(*pb_objs)", "docstring": "Write to a stream.\n\nArgs:\n ofp (string or file-like object): output stream.\n pb_objs (*protobuf.message.Message): list of protobuf message objects\n to be written.", "source": "juraj_google_style"} +{"code": "def disconnect(signal, receiver):\n\n inputkey = __make_id(receiver)\n\n with __lock:\n __purge()\n receivers = __receivers.get(signal)\n\n for idx in six.moves.range(len(receivers)):\n connected = receivers[idx]()\n\n if inputkey != __make_id(connected):\n continue\n\n del receivers[idx]\n return True # receiver successfully disconnected!\n\n return False", "docstring": "Disconnect the receiver `func` from the signal, identified by\n `signal_id`.\n\nArgs:\n signal: The signal identifier.\n receiver: The callable receiver to disconnect.\n\nReturns:\n True if the receiver was successfully disconnected. False otherwise.", "source": "juraj_google_style"} +{"code": "def multiple(layer: int, limit: int) -> Set[str]:\n\n\treturn {str(x).zfill(2) for x in [2**x for x in range(limit)] if x % 2**(layer - 1) == 0}", "docstring": "Returns a set of strings to be used as Slots with Pabianas default Clock.\n\nArgs:\n layer: The layer in the hierarchy this Area is placed in.\n Technically, the number specifies how many of the Clocks signals are relevant to the Area.\n Between 1 and limit.\n limit: The number of layers of the hierarchy.", "source": "juraj_google_style"} +{"code": "def QA_fetch_financial_report_adv(code, start, end=None, ltype='EN'):\n\n\n if end is None:\n\n return QA_DataStruct_Financial(QA_fetch_financial_report(code, start, ltype=ltype))\n else:\n series = pd.Series(\n data=month_data, index=pd.to_datetime(month_data), name='date')\n timerange = series.loc[start:end].tolist()\n return QA_DataStruct_Financial(QA_fetch_financial_report(code, timerange, ltype=ltype))", "docstring": "高级财务查询接口\n\nArgs:\n code {[type]} -- [description]\n start {[type]} -- [description]\n Keyword Arguments:\n end {[type]} -- [description] (default: {None})", "source": "juraj_google_style"} +{"code": "def get_output_dict(stack):\n\n outputs = {}\n if 'Outputs' not in stack:\n return outputs\n\n for output in stack['Outputs']:\n logger.debug(\" %s %s: %s\", stack['StackName'], output['OutputKey'],\n output['OutputValue'])\n outputs[output['OutputKey']] = output['OutputValue']\n return outputs", "docstring": "Returns a dict of key/values for the outputs for a given CF stack.\n\nArgs:\n stack (dict): The stack object to get\n outputs from.\n\nReturns:\n dict: A dictionary with key/values for each output on the stack.", "source": "juraj_google_style"} +{"code": "def ch_start_time(self, *channels: List[Channel]) -> int:\n\n intervals = list(itertools.chain(*(self._table[chan] for chan in channels\n if chan in self._table)))\n if intervals:\n return min((interval.begin for interval in intervals))\n return 0", "docstring": "Return earliest start time in this collection.\n\nArgs:\n *channels: Channels over which to obtain start_time.", "source": "juraj_google_style"} +{"code": "def apply(\n self,\n func,\n axis=0,\n broadcast=None,\n raw=False,\n reduce=None,\n result_type=None,\n convert_dtype=True,\n args=(),\n **kwds\n ):\n\n axis = self._get_axis_number(axis)\n ErrorMessage.non_verified_udf()\n if isinstance(func, string_types):\n if axis == 1:\n kwds[\"axis\"] = axis\n result = self._string_function(func, *args, **kwds)\n # Sometimes we can return a scalar here\n if isinstance(result, BasePandasDataset):\n return result._query_compiler\n return result\n elif isinstance(func, dict):\n if axis == 1:\n raise TypeError(\n \"(\\\"'dict' object is not callable\\\", \"\n \"'occurred at index {0}'\".format(self.index[0])\n )\n if len(self.columns) != len(set(self.columns)):\n warnings.warn(\n \"duplicate column names not supported with apply().\",\n FutureWarning,\n stacklevel=2,\n )\n elif not callable(func) and not is_list_like(func):\n raise TypeError(\"{} object is not callable\".format(type(func)))\n query_compiler = self._query_compiler.apply(func, axis, *args, **kwds)\n return query_compiler", "docstring": "Apply a function along input axis of DataFrame.\n\nArgs:\n func: The function to apply\n axis: The axis over which to apply the func.\n broadcast: Whether or not to broadcast.\n raw: Whether or not to convert to a Series.\n reduce: Whether or not to try to apply reduction procedures.\n\nReturns:\n Series or DataFrame, depending on func.", "source": "juraj_google_style"} +{"code": "def to_grayscale(img, num_output_channels=1):\n\n if not _is_pil_image(img):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n if num_output_channels == 1:\n img = img.convert('L')\n elif num_output_channels == 3:\n img = img.convert('L')\n np_img = np.array(img, dtype=np.uint8)\n np_img = np.dstack([np_img, np_img, np_img])\n img = Image.fromarray(np_img, 'RGB')\n else:\n raise ValueError('num_output_channels should be either 1 or 3')\n\n return img", "docstring": "Convert image to grayscale version of image.\n\nArgs:\n img (PIL Image): Image to be converted to grayscale.\n\nReturns:\n PIL Image: Grayscale version of the image.\n if num_output_channels = 1 : returned image is single channel\n\n if num_output_channels = 3 : returned image is 3 channel with r = g = b", "source": "juraj_google_style"} +{"code": "def uma_rp_get_claims_gathering_url(self, ticket):\n\n params = {\n 'oxd_id': self.oxd_id,\n 'claims_redirect_uri': self.config.get('client',\n 'claims_redirect_uri'),\n 'ticket': ticket\n }\n logger.debug(\"Sending command `uma_rp_get_claims_gathering_url` with \"\n \"params %s\", params)\n response = self.msgr.request(\"uma_rp_get_claims_gathering_url\",\n **params)\n logger.debug(\"Received response: %s\", response)\n\n if response['status'] == 'error':\n raise OxdServerError(response['data'])\n return response['data']['url']", "docstring": "UMA RP function to get the claims gathering URL.\n\n Parameters:\n * **ticket (str):** ticket to pass to the auth server. for 90% of the cases, this will be obtained from 'need_info' error of get_rpt\n\nReturns:\n **string** specifying the claims gathering url", "source": "juraj_google_style"} +{"code": "def murmur2(key):\n\n\n # Convert key to bytes or bytearray\n if isinstance(key, bytearray) or (six.PY3 and isinstance(key, bytes)):\n data = key\n else:\n data = bytearray(str(key).encode())\n\n length = len(data)\n seed = 0x9747b28c\n # 'm' and 'r' are mixing constants generated offline.\n # They're not really 'magic', they just happen to work well.\n m = 0x5bd1e995\n r = 24\n\n # Initialize the hash to a random value\n h = seed ^ length\n length4 = length // 4\n\n for i in range(length4):\n i4 = i * 4\n k = ((data[i4 + 0] & 0xff) +\n ((data[i4 + 1] & 0xff) << 8) +\n ((data[i4 + 2] & 0xff) << 16) +\n ((data[i4 + 3] & 0xff) << 24))\n k &= 0xffffffff\n k *= m\n k &= 0xffffffff\n k ^= (k % 0x100000000) >> r # k ^= k >>> r\n k &= 0xffffffff\n k *= m\n k &= 0xffffffff\n\n h *= m\n h &= 0xffffffff\n h ^= k\n h &= 0xffffffff\n\n # Handle the last few bytes of the input array\n extra_bytes = length % 4\n if extra_bytes >= 3:\n h ^= (data[(length & ~3) + 2] & 0xff) << 16\n h &= 0xffffffff\n if extra_bytes >= 2:\n h ^= (data[(length & ~3) + 1] & 0xff) << 8\n h &= 0xffffffff\n if extra_bytes >= 1:\n h ^= (data[length & ~3] & 0xff)\n h &= 0xffffffff\n h *= m\n h &= 0xffffffff\n\n h ^= (h % 0x100000000) >> 13 # h >>> 13;\n h &= 0xffffffff\n h *= m\n h &= 0xffffffff\n h ^= (h % 0x100000000) >> 15 # h >>> 15;\n h &= 0xffffffff\n\n return h", "docstring": "Pure-python Murmur2 implementation.\n\n Based on java client, see org.apache.kafka.common.utils.Utils.murmur2\n\nArgs:\n key: if not a bytes type, encoded using default encoding\n\n Returns: MurmurHash2 of key bytearray", "source": "juraj_google_style"} +{"code": "def get_configured_consensus_module(block_id, state_view):\n\n settings_view = SettingsView(state_view)\n\n default_consensus = \\\n 'genesis' if block_id == NULL_BLOCK_IDENTIFIER else 'devmode'\n consensus_module_name = settings_view.get_setting(\n 'sawtooth.consensus.algorithm', default_value=default_consensus)\n return ConsensusFactory.get_consensus_module(\n consensus_module_name)", "docstring": "Returns the consensus_module based on the consensus module set by\n the \"sawtooth_settings\" transaction family.\n\nArgs:\n block_id (str): the block id associated with the current state_view\n state_view (:obj:`StateView`): the current state view to use for\n setting values\n\nRaises:\n UnknownConsensusModuleError: Thrown when an invalid consensus\n module has been configured.", "source": "juraj_google_style"} +{"code": "def _SetCredentials(self, **kwds):\n\n args = {\n 'api_key': self._API_KEY,\n 'client': self,\n 'client_id': self._CLIENT_ID,\n 'client_secret': self._CLIENT_SECRET,\n 'package_name': self._PACKAGE,\n 'scopes': self._SCOPES,\n 'user_agent': self._USER_AGENT,\n }\n args.update(kwds)\n # credentials_lib can be expensive to import so do it only if needed.\n from apitools.base.py import credentials_lib\n # TODO(craigcitro): It's a bit dangerous to pass this\n # still-half-initialized self into this method, but we might need\n # to set attributes on it associated with our credentials.\n # Consider another way around this (maybe a callback?) and whether\n # or not it's worth it.\n self._credentials = credentials_lib.GetCredentials(**args)", "docstring": "Fetch credentials, and set them for this client.\n\n Note that we can't simply return credentials, since creating them\n may involve side-effecting self.\n\nArgs:\n **kwds: Additional keyword arguments are passed on to GetCredentials.\n\nReturns:\n None. Sets self._credentials.", "source": "juraj_google_style"} +{"code": "def create(self, name, domain_name):\n\n name = self.wrap(self.resource.create(dict(name=name,\n domain_name=domain_name)))\n\n self.add(name)\n return name", "docstring": "Register a url (e.g. wallet.gem.co) for\n\nArgs:\n name (str): human-readable wallet name (e.g. wallet)\n domain_name (str): the domain name to create subdomain on (e.g. gem.co)\n this domain must already be registered with Gem\n\n Returns: The new round.NetkiName", "source": "juraj_google_style"} +{"code": "def _get_password(params):\n\n user_name = params['user']\n service_name = params['host'] + ':' + params['driver']\n return keyring.get_password(service_name=service_name,\n username=user_name)", "docstring": "Get the password for a database connection from :mod:`keyring`\n\nArgs:\n params (dict): database configuration, as defined in :mod:`ozelot.config`\n\nReturns:\n str: password", "source": "juraj_google_style"} +{"code": "def destroy(self, prefix_names=None):\n\n if prefix_names is None:\n self.destroy(prefix_names=self.prefixes.keys())\n return\n\n for prefix_name in prefix_names:\n if prefix_name == 'current' and self.current in prefix_names:\n continue\n\n elif prefix_name == 'current':\n prefix_name = self.current\n\n self.get_prefix(prefix_name).destroy()\n self.prefixes.pop(prefix_name)\n if self.prefixes:\n self._update_current()\n\n if not self.prefixes:\n shutil.rmtree(self.path)", "docstring": "Destroy all the given prefixes and remove any left files if no more\n prefixes are left\n\nArgs:\n prefix_names(list of str): list of prefix names to destroy, if None\n passed (default) will destroy all of them", "source": "juraj_google_style"} +{"code": "def __DeviceImpl__add_command(self, cmd, device_level=True):\n\n add_name_in_list = False # This flag is always False, what use is it?\n try:\n config = dict(cmd.__tango_command__[1][2])\n if config and (\"Display level\" in config):\n disp_level = config[\"Display level\"]\n else:\n disp_level = DispLevel.OPERATOR\n self._add_command(cmd.__name__, cmd.__tango_command__[1], disp_level,\n device_level)\n if add_name_in_list:\n cl = self.get_device_class()\n cl.dyn_cmd_added_methods.append(cmd.__name__)\n except:\n if add_name_in_list:\n self._remove_cmd(cmd.__name__)\n raise\n return cmd", "docstring": "add_command(self, cmd, level=TANGO::OPERATOR) -> cmd\n\n Add a new command to the device command list.\n\n Parameters :\n - cmd : the new command to be added to the list\n - device_level : Set this flag to true if the command must be added\n for only this device\n\n Return : Command\n\n Throws : DevFailed", "source": "juraj_google_style"} +{"code": "def as_dict(self, verbosity: int = 0) -> Dict:\n\n\n d = {\n \"@module\": self.__class__.__module__,\n \"@class\": self.__class__.__name__,\n \"matrix\": self._matrix.tolist(),\n }\n (a, b, c), (alpha, beta, gamma) = self.lengths_and_angles\n if verbosity > 0:\n d.update(\n {\n \"a\": a,\n \"b\": b,\n \"c\": c,\n \"alpha\": alpha,\n \"beta\": beta,\n \"gamma\": gamma,\n \"volume\": self.volume,\n }\n )\n\n return d", "docstring": "Json-serialization dict representation of the Lattice.\n\nArgs:\n verbosity (int): Verbosity level. Default of 0 only includes the\n matrix representation. Set to 1 for more details.", "source": "juraj_google_style"} +{"code": "def _resolve_attribute_match(self, match):\n\n if match.group(1) == 'cluster':\n return str(self.cluster_id)\n\n return self.get(match.group(1), match.group(0))", "docstring": "Replaces a reference to an attribute with the value of the attribute.\n\nArgs:\n match (re.match object): A match object containing a match to a reference to an attribute.", "source": "juraj_google_style"} +{"code": "def iso_date(d) -> str:\n\n if isinstance(d, datetime):\n return d.isoformat()\n elif isinstance(d, date):\n return datetime.combine(d, datetime.min.time()).isoformat()\n else:\n try:\n datetime.strptime(d, '%Y-%m-%dT%H:%M:%S')\n return d\n except ValueError:\n try:\n datetime.strptime(d, '%Y-%m-%d')\n return d + \"T00:00:00\"\n except ValueError:\n pass\n raise ISODateError(\"Can not convert value to ISO format for kg\")", "docstring": "Return iso format of a date\n\nArgs:\n d:\n Returns: str", "source": "juraj_google_style"} +{"code": "def continue_abort(self,\n root_pipeline_key,\n cursor=None,\n max_to_notify=_MAX_ABORTS_TO_BEGIN):\n\n if not isinstance(root_pipeline_key, db.Key):\n root_pipeline_key = db.Key(root_pipeline_key)\n # NOTE: The results of this query may include _PipelineRecord instances\n # that are not actually \"reachable\", meaning you cannot get to them by\n # starting at the root pipeline and following \"fanned_out\" onward. This\n # is acceptable because even these defunct _PipelineRecords will properly\n # set their status to ABORTED when the signal comes, regardless of any\n # other status they may have had.\n #\n # The only gotcha here is if a Pipeline's finalize method somehow modifies\n # its inputs (like deleting an input file). In the case there are\n # unreachable child pipelines, it will appear as if two finalize methods\n # have been called instead of just one. The saving grace here is that\n # finalize must be idempotent, so this *should* be harmless.\n query = (\n _PipelineRecord.all(cursor=cursor)\n .filter('root_pipeline =', root_pipeline_key))\n results = query.fetch(max_to_notify)\n\n task_list = []\n for pipeline_record in results:\n if pipeline_record.status not in (\n _PipelineRecord.RUN, _PipelineRecord.WAITING):\n continue\n\n pipeline_key = pipeline_record.key()\n task_list.append(taskqueue.Task(\n name='%s-%s-abort' % (self.task_name, pipeline_key.name()),\n url=self.abort_handler_path,\n params=dict(pipeline_key=pipeline_key, purpose=_BarrierRecord.ABORT),\n headers={'X-Ae-Pipeline-Key': pipeline_key}))\n\n # Task continuation with sequence number to prevent fork-bombs.\n if len(results) == max_to_notify:\n the_match = re.match('(.*)-([0-9]+)', self.task_name)\n if the_match:\n prefix = the_match.group(1)\n end = int(the_match.group(2)) + 1\n else:\n prefix = self.task_name\n end = 0\n task_list.append(taskqueue.Task(\n name='%s-%d' % (prefix, end),\n url=self.fanout_abort_handler_path,\n params=dict(root_pipeline_key=root_pipeline_key,\n cursor=query.cursor())))\n\n if task_list:\n try:\n taskqueue.Queue(self.queue_name).add(task_list)\n except (taskqueue.TombstonedTaskError, taskqueue.TaskAlreadyExistsError):\n pass", "docstring": "Sends the abort signal to all children for a root pipeline.\n\nArgs:\n root_pipeline_key: db.Key of the root pipeline to abort.\n cursor: The query cursor for enumerating _PipelineRecords when inserting\n tasks to cause child pipelines to terminate.\n max_to_notify: Used for testing.", "source": "juraj_google_style"} +{"code": "def double_strike(self, action):\n\n if action == 'on':\n action = 'G'\n elif action == 'off':\n action = 'H'\n else:\n raise RuntimeError('Invalid action for function doubleStrike. Options are on and off')\n self.send(chr(27)+action)", "docstring": "Enable/cancel doublestrike printing\n\nArgs:\n action: Enable or disable doublestrike printing. Options are 'on' and 'off'\n\nReturns:\n None\n\nRaises:\n RuntimeError: Invalid action.", "source": "juraj_google_style"} +{"code": "def __init__(self, tcex, name, description, data_type, interval, keyed=False):\n\n self.tcex = tcex\n self._metric_data_type = data_type\n self._metric_description = description\n self._metric_id = None\n self._metric_interval = interval\n self._metric_keyed = keyed\n self._metric_name = name\n\n if not self.metric_find():\n self.metric_create()", "docstring": "Initialize the Class properties.\n\nArgs:\n name (str): The name for the metric.\n description (str): The description of the metric.\n data_type (str): The type of metric: Sum, Count, Min, Max, First, Last, and Average.\n interval (str): The metric interval: Hourly, Daily, Weekly, Monthly, and Yearly.\n keyed (bool, default:False): Indicates whether the data will have a keyed value.", "source": "juraj_google_style"} +{"code": "def get_file_handle(file_path):\n\n LOG.debug(\"Check if file end is correct\")\n\n if not os.path.exists(file_path):\n raise IOError(\"No such file:{0}\".format(file_path))\n\n if not os.path.splitext(file_path)[-1] in VALID_ENDINGS:\n raise IOError(\"Not a valid vcf file name: {}\".format(file_path))\n\n vcf_obj = VCF(file_path)\n\n return vcf_obj", "docstring": "Return cyvcf2 VCF object\n\nArgs:\n file_path(str)\n\nReturns:\n vcf_obj(cyvcf2.VCF)", "source": "juraj_google_style"} +{"code": "def from_dict(self, dictionary):\n\n\n for remote_name, remote_value in dictionary.items():\n # Check if a local attribute is exposed with the remote_name\n # if no attribute is exposed, return None\n local_name = next((name for name, attribute in self._attributes.items() if attribute.remote_name == remote_name), None)\n\n if local_name:\n setattr(self, local_name, remote_value)\n else:\n # print('Attribute %s could not be added to object %s' % (remote_name, self))\n pass", "docstring": "Sets all the exposed ReST attribues from the given dictionary\n\nArgs:\n dictionary (dict): dictionnary containing the raw object attributes and their values.\n\nExample:\n >>> info = {\"name\": \"my group\", \"private\": False}\n >>> group = NUGroup()\n >>> group.from_dict(info)\n >>> print \"name: %s - private: %s\" % (group.name, group.private)\n \"name: my group - private: False\"", "source": "juraj_google_style"} +{"code": "def _GetInode(self, inode_value):\n\n if isinstance(inode_value, py2to3.INTEGER_TYPES):\n return inode_value\n\n if isinstance(inode_value, float):\n return int(inode_value)\n\n if not isinstance(inode_value, py2to3.STRING_TYPES):\n return -1\n\n if b'-' in inode_value:\n inode_value, _, _ = inode_value.partition(b'-')\n\n try:\n return int(inode_value, 10)\n except ValueError:\n return -1", "docstring": "Retrieves the inode from the inode value.\n\nArgs:\n inode_value (int|str): inode, such as 1 or '27-128-1'.\n\nReturns:\n int: inode or -1 if the inode value cannot be converted to an integer.", "source": "juraj_google_style"} +{"code": "def HasColumn(self, table_name, column_name):\n\n if not self._connection:\n raise IOError('Not opened.')\n\n if not column_name:\n return False\n\n table_name = table_name.lower()\n column_names = self._column_names_per_table.get(table_name, None)\n if column_names is None:\n column_names = []\n\n self._cursor.execute(self._HAS_COLUMN_QUERY.format(table_name))\n for row in self._cursor.fetchall():\n if not row[1]:\n continue\n\n row_column_name = row[1]\n if isinstance(row_column_name, bytes):\n row_column_name = row_column_name.decode('utf-8')\n\n column_names.append(row_column_name.lower())\n\n self._column_names_per_table[table_name] = column_names\n\n column_name = column_name.lower()\n return column_name in column_names", "docstring": "Determines if a specific column exists.\n\nArgs:\n table_name (str): name of the table.\n column_name (str): name of the column.\n\nReturns:\n bool: True if the column exists.\n\nRaises:\n IOError: if the database file is not opened.\n OSError: if the database file is not opened.", "source": "juraj_google_style"} +{"code": "def main(argv):\n\n\n parser = OptionParser(helpString)\n\n parser.add_option(\"--jobID\", action=\"store\", type=\"int\", default=None,\n help=\"jobID of the job within the dbTable [default: %default].\")\n\n parser.add_option(\"--modelID\", action=\"store\", type=\"str\", default=None,\n help=(\"Tell worker to re-run this model ID. When specified, jobID \"\n \"must also be specified [default: %default].\"))\n\n parser.add_option(\"--workerID\", action=\"store\", type=\"str\", default=None,\n help=(\"workerID of the scheduler's SlotAgent (GenericWorker) that \"\n \"hosts this SpecializedWorker [default: %default].\"))\n\n parser.add_option(\"--params\", action=\"store\", default=None,\n help=\"Create and execute a new hypersearch request using this JSON \" \\\n \"format params string. This is helpful for unit tests and debugging. \" \\\n \"When specified jobID must NOT be specified. [default: %default].\")\n\n parser.add_option(\"--clearModels\", action=\"store_true\", default=False,\n help=\"clear out the models table before starting [default: %default].\")\n\n parser.add_option(\"--resetJobStatus\", action=\"store_true\", default=False,\n help=\"Reset the job status before starting [default: %default].\")\n\n parser.add_option(\"--logLevel\", action=\"store\", type=\"int\", default=None,\n help=\"override default log level. Pass in an integer value that \"\n \"represents the desired logging level (10=logging.DEBUG, \"\n \"20=logging.INFO, etc.) [default: %default].\")\n\n # Evaluate command line arguments\n (options, args) = parser.parse_args(argv[1:])\n if len(args) != 0:\n raise RuntimeError(\"Expected no command line arguments, but got: %s\" % \\\n (args))\n\n if (options.jobID and options.params):\n raise RuntimeError(\"--jobID and --params can not be used at the same time\")\n\n if (options.jobID is None and options.params is None):\n raise RuntimeError(\"Either --jobID or --params must be specified.\")\n\n initLogging(verbose=True)\n\n # Instantiate the HypersearchWorker and run it\n hst = HypersearchWorker(options, argv[1:])\n\n # Normal use. This is one of among a number of workers. If we encounter\n # an exception at the outer loop here, we fail the entire job.\n if options.params is None:\n try:\n jobID = hst.run()\n\n except Exception, e:\n jobID = options.jobID\n msg = StringIO.StringIO()\n print >>msg, \"%s: Exception occurred in Hypersearch Worker: %r\" % \\\n (ErrorCodes.hypersearchLogicErr, e)\n traceback.print_exc(None, msg)\n\n completionReason = ClientJobsDAO.CMPL_REASON_ERROR\n completionMsg = msg.getvalue()\n hst.logger.error(completionMsg)\n\n # If no other worker already marked the job as failed, do so now.\n jobsDAO = ClientJobsDAO.get()\n workerCmpReason = jobsDAO.jobGetFields(options.jobID,\n ['workerCompletionReason'])[0]\n if workerCmpReason == ClientJobsDAO.CMPL_REASON_SUCCESS:\n jobsDAO.jobSetFields(options.jobID, fields=dict(\n cancel=True,\n workerCompletionReason = ClientJobsDAO.CMPL_REASON_ERROR,\n workerCompletionMsg = completionMsg),\n useConnectionID=False,\n ignoreUnchanged=True)\n\n\n # Run just 1 worker for the entire job. Used for unit tests that run in\n # 1 process\n else:\n jobID = None\n completionReason = ClientJobsDAO.CMPL_REASON_SUCCESS\n completionMsg = \"Success\"\n\n try:\n jobID = hst.run()\n except Exception, e:\n jobID = hst._options.jobID\n completionReason = ClientJobsDAO.CMPL_REASON_ERROR\n completionMsg = \"ERROR: %s\" % (e,)\n raise\n finally:\n if jobID is not None:\n cjDAO = ClientJobsDAO.get()\n cjDAO.jobSetCompleted(jobID=jobID,\n completionReason=completionReason,\n completionMsg=completionMsg)\n\n return jobID", "docstring": "The main function of the HypersearchWorker script. This parses the command\n line arguments, instantiates a HypersearchWorker instance, and then\n runs it.\n\n Parameters:\n ----------------------------------------------------------------------\n retval: jobID of the job we ran. This is used by unit test code\n when calling this working using the --params command\n line option (which tells this worker to insert the job\n itself).", "source": "juraj_google_style"} +{"code": "def GetPointWithDistanceTraveled(self, shape_dist_traveled):\n\n if not self.distance:\n return None\n if shape_dist_traveled <= self.distance[0]:\n return self.points[0]\n if shape_dist_traveled >= self.distance[-1]:\n return self.points[-1]\n\n index = bisect.bisect(self.distance, shape_dist_traveled)\n (lat0, lng0, dist0) = self.points[index - 1]\n (lat1, lng1, dist1) = self.points[index]\n\n # Interpolate if shape_dist_traveled does not equal to any of the point\n # in shape segment.\n # (lat0, lng0) (lat, lng) (lat1, lng1)\n # -----|--------------------|---------------------|------\n # dist0 shape_dist_traveled dist1\n # \\------- ca --------/ \\-------- bc -------/\n # \\----------------- ba ------------------/\n ca = shape_dist_traveled - dist0\n bc = dist1 - shape_dist_traveled\n ba = bc + ca\n if ba == 0:\n # This only happens when there's data error in shapes and should have been\n # catched before. Check to avoid crash.\n return None\n # This won't work crossing longitude 180 and is only an approximation which\n # works well for short distance.\n lat = (lat1 * ca + lat0 * bc) / ba\n lng = (lng1 * ca + lng0 * bc) / ba\n return (lat, lng, shape_dist_traveled)", "docstring": "Returns a point on the shape polyline with the input shape_dist_traveled.\n\nArgs:\n shape_dist_traveled: The input shape_dist_traveled.\n\nReturns:\n The shape point as a tuple (lat, lng, shape_dist_traveled), where lat and\n lng is the location of the shape point, and shape_dist_traveled is an\n increasing metric representing the distance traveled along the shape.\n Returns None if there is data error in shape.", "source": "juraj_google_style"} +{"code": "def convert_one(self, op: ops.Operation) -> ops.OP_TREE:\n\n\n # Known gate name\n if not isinstance(op, ops.GateOperation):\n raise TypeError(\"{!r} is not a gate operation.\".format(op))\n\n if is_native_ion_gate(op.gate):\n return [op]\n # one choice of known Hadamard gate decomposition\n if isinstance(op.gate, ops.HPowGate) and op.gate.exponent == 1:\n return [ops.Rx(np.pi).on(op.qubits[0]),\n ops.Ry(-1 * np.pi/2).on(op.qubits[0])]\n # one choice of known CNOT gate decomposition\n if isinstance(op.gate, ops.CNotPowGate) and op.gate.exponent == 1:\n return [ops.Ry(np.pi/2).on(op.qubits[0]),\n MS(np.pi/4).on(op.qubits[0], op.qubits[1]),\n ops.Rx(-1*np.pi/2).on(op.qubits[0]),\n ops.Rx(-1*np.pi/2).on(op.qubits[1]),\n ops.Ry(-1*np.pi/2).on(op.qubits[0])]\n # Known matrix\n mat = protocols.unitary(op, None) if len(\n op.qubits) <= 2 else None\n if mat is not None and len(op.qubits) == 1:\n gates = optimizers.single_qubit_matrix_to_phased_x_z(mat)\n return [g.on(op.qubits[0]) for g in gates]\n elif mat is not None and len(op.qubits) == 2:\n return two_qubit_matrix_to_ion_operations(\n op.qubits[0], op.qubits[1], mat)\n else:\n if self.ignore_failures:\n return [op]\n else:\n raise TypeError(\n \"Don't know how to work with {!r}. \"\n \"It isn't a native Ion Trap operation, \"\n \"a 1 or 2 qubit gate with a known unitary, \"\n \"or composite.\".format(op.gate))", "docstring": "Convert a single (one- or two-qubit) operation\n\n into ion trap native gates\n\nArgs:\n op: gate operation to be converted\n\nReturns:\n the desired operation implemented with ion trap gates", "source": "juraj_google_style"} +{"code": "def __frontend_limit_descriptor(self, api_info):\n\n if api_info.frontend_limits is None:\n return None\n\n descriptor = {}\n for propname, descname in (('unregistered_user_qps', 'unregisteredUserQps'),\n ('unregistered_qps', 'unregisteredQps'),\n ('unregistered_daily', 'unregisteredDaily')):\n if getattr(api_info.frontend_limits, propname) is not None:\n descriptor[descname] = getattr(api_info.frontend_limits, propname)\n\n rules = self.__frontend_limit_rules_descriptor(api_info)\n if rules:\n descriptor['rules'] = rules\n\n return descriptor", "docstring": "Builds a frontend limit descriptor from API info.\n\nArgs:\n api_info: An _ApiInfo object.\n\nReturns:\n A dictionary with frontend limit information.", "source": "juraj_google_style"} +{"code": "def display_element_selected(self, f):\n\n self._display_element_selected_func = f\n\n @wraps(f)\n def wrapper(*args, **kw):\n self._flask_view_func(*args, **kw)\n return f", "docstring": "Decorator routes Alexa Display.ElementSelected request to the wrapped view function.\n\n @ask.display_element_selected\n def eval_element():\n return \"\", 200\n\n The wrapped function is registered as the display_element_selected view function\n and renders the response for requests.\n\nArgs:\n f {function} -- display_element_selected view function", "source": "juraj_google_style"} +{"code": "def update_parser(parser):\n\n def __stdin(s):\n if s is None:\n return None\n if s == '-':\n return sys.stdin\n return open(s, 'r', encoding = 'utf8')\n parser.add_argument('--root-prompt',\n metavar = 'STR',\n default = 'PlayBoy',\n help = 'the root prompt string')\n parser.add_argument('--temp-dir',\n metavar = 'DIR',\n default = '/tmp/easyshell_demo',\n help = 'the directory to save history files')\n parser.add_argument('--debug',\n action = 'store_true',\n help = 'turn debug infomation on')\n parser.add_argument('file',\n metavar = 'FILE',\n nargs = '?',\n type = __stdin,\n help = \"execute script in non-interactive mode. '-' = stdin\")", "docstring": "Update the parser object for the shell.\n\nArgs:\n parser: An instance of argparse.ArgumentParser.", "source": "juraj_google_style"} +{"code": "def get_resource_from_handle(self, resource_handle, verify_repo=True):\n\n if verify_repo:\n # we could fix the handle at this point, but handles should\n # always be made from repo.make_resource_handle... for now,\n # at least, error to catch any \"incorrect\" construction of\n # handles...\n if resource_handle.variables.get(\"repository_type\") != self.name():\n raise ResourceError(\"repository_type mismatch - requested %r, \"\n \"repository_type is %r\"\n % (resource_handle.variables[\"repository_type\"],\n self.name()))\n\n if resource_handle.variables.get(\"location\") != self.location:\n raise ResourceError(\"location mismatch - requested %r, \"\n \"repository location is %r \"\n % (resource_handle.variables[\"location\"],\n self.location))\n\n resource = self.pool.get_resource_from_handle(resource_handle)\n resource._repository = self\n return resource", "docstring": "Get a resource.\n\nArgs:\n resource_handle (`ResourceHandle`): Handle of the resource.\n\nReturns:\n `PackageRepositoryResource` instance.", "source": "juraj_google_style"} +{"code": "def __init__(self, action_meanings):\n\n self.action_meanings = action_meanings\n self._wait = True\n # If action_space will be needed, one could use e.g. gym.spaces.Dict.\n self.action_space = None\n self._last_step_tuples = None\n self.action_meanings = action_meanings\n self.name_to_action_num = {name: num for num, name in\n enumerate(self.action_meanings)}", "docstring": "Constructor for PlayerEnv.\n\nArgs:\n action_meanings: list of strings indicating action names. Can be obtain by\n >>> env = gym.make(\"PongNoFrameskip-v4\") # insert your game name\n >>> env.unwrapped.get_action_meanings()\n See gym AtariEnv get_action_meanings() for more details.", "source": "juraj_google_style"} +{"code": "def _get_status_code(self, http_status):\n\n try:\n return int(http_status.split(' ', 1)[0])\n except TypeError:\n _logger.warning('Unable to find status code in HTTP status %r.',\n http_status)\n return 500", "docstring": "Get the HTTP status code from an HTTP status string.\n\nArgs:\n http_status: A string containing a HTTP status code and reason.\n\nReturns:\n An integer with the status code number from http_status.", "source": "juraj_google_style"} +{"code": "def get_capture_handler_config_by_name(self, name):\n\n handler_confs = []\n for address, stream_capturer in self._stream_capturers.iteritems():\n handler_data = stream_capturer[0].dump_handler_config_data()\n for h in handler_data:\n if h['handler']['name'] == name:\n handler_confs.append(h)\n\n return handler_confs", "docstring": "Return data for handlers of a given name.\n\nArgs:\n name:\n Name of the capture handler(s) to return config data for.\n\nReturns:\n Dictionary dump from the named capture handler as given by\n the :func:`SocketStreamCapturer.dump_handler_config_data` method.", "source": "juraj_google_style"} +{"code": "def select_best_paths(examples):\n\n possible_paths = {} # {varname: [paths]}\n\n # collect list of all possible paths to all existing variables\n for example in examples:\n dom = _create_dom(example[\"html\"])\n matching_elements = _match_elements(dom, example[\"vars\"])\n\n for key, match in matching_elements.items():\n if key not in possible_paths: # TODO: merge paths together?\n possible_paths[key] = _collect_paths(match)\n\n # leave only paths, that works in all examples where, are required\n for example in examples:\n dom = _create_dom(example[\"html\"])\n matching_elements = _match_elements(dom, example[\"vars\"])\n\n for key, paths in possible_paths.items():\n if key not in matching_elements:\n continue\n\n possible_paths[key] = filter(\n lambda path: _is_working_path(\n dom,\n path,\n matching_elements[key]\n ),\n paths\n )\n\n priorities = [\n \"find\",\n \"left_neighbour_tag\",\n \"right_neighbour_tag\",\n \"wfind\",\n \"match\",\n \"Chained\"\n ]\n priorities = dict(map(lambda x: (x[1], x[0]), enumerate(priorities)))\n\n # sort all paths by priority table\n for key in possible_paths.keys():\n possible_paths[key] = list(sorted(\n possible_paths[key],\n key=lambda x: priorities.get(x.call_type, 100)\n ))\n\n return possible_paths", "docstring": "Process `examples`, select only paths that works for every example. Select\n best paths with highest priority.\n\nArgs:\n examples (dict): Output from :func:`.read_config`.\n\nReturns:\n list: List of :class:`.PathCall` and :class:`.Chained` objects.", "source": "juraj_google_style"} +{"code": "def get_file(self, file_name, local_destination=None, **kwargs):\n\n if not local_destination:\n local_destination = file_name\n\n return SubprocessTask(\n self._rsync_cmd() +\n ['-ut', '%s:%s' % (self.hostname, file_name), local_destination],\n **kwargs)", "docstring": "Get a file from a remote host with rsync.\n\nArgs:\n file_name (str): The relative location of the file on the remote\n host.\n\n local_destination (str): The destination for the file on the local\n host. If `None`, will be assumed to be the same as\n **file_name**. Default `None`.\n\n **kwargs: Passed to ``SubprocessTask``'s init method.\n\nReturns:\n ``pyrem.task.SubprocessTask``: The resulting task.", "source": "juraj_google_style"} +{"code": "def device_id_to_slug(did):\n\n\n try:\n device_slug = IOTileDeviceSlug(did, allow_64bits=False)\n except ValueError:\n raise ArgumentError(\"Unable to recognize {} as a device id\".format(did))\n\n return str(device_slug)", "docstring": "Converts a device id into a correct device slug.\n\nArgs:\n did (long) : A device id\n did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, d--XXXX, d--XXXX-XXXX-XXXX-XXXX\n\nReturns:\n str: The device slug in the d--XXXX-XXXX-XXXX-XXXX format\n\nRaises:\n ArgumentError: if the ID is not in the [1, 16**12] range, or if not a valid string", "source": "juraj_google_style"} +{"code": "def detect_arbitrary_send(self, contract):\n\n ret = []\n for f in [f for f in contract.functions if f.contract == contract]:\n nodes = self.arbitrary_send(f)\n if nodes:\n ret.append((f, nodes))\n return ret", "docstring": "Detect arbitrary send\n\nArgs:\n contract (Contract)\n\nReturns:\n list((Function), (list (Node)))", "source": "juraj_google_style"} +{"code": "def condition_details_has_owner(condition_details, owner):\n\n if 'subconditions' in condition_details:\n result = condition_details_has_owner(condition_details['subconditions'], owner)\n if result:\n return True\n\n elif isinstance(condition_details, list):\n for subcondition in condition_details:\n result = condition_details_has_owner(subcondition, owner)\n if result:\n return True\n else:\n if 'public_key' in condition_details \\\n and owner == condition_details['public_key']:\n return True\n return False", "docstring": "Check if the public_key of owner is in the condition details\n as an Ed25519Fulfillment.public_key\n\nArgs:\n condition_details (dict): dict with condition details\n owner (str): base58 public key of owner\n\nReturns:\n bool: True if the public key is found in the condition details, False otherwise", "source": "juraj_google_style"} +{"code": "def __init__(self, version_string, first_matched_type, second_matched_type):\n\n super(TooManyTypesError, self).__init__(\n 'Release \"{}\" cannot match types \"{}\" and \"{}\"'.format(\n version_string, first_matched_type, second_matched_type\n )\n )", "docstring": "Constructor.\n\nArgs:\n version_string (str): The string that gave too many types.\n first_matched_type (str): The name of the first detected type.\n second_matched_type (str): The name of the second detected type", "source": "juraj_google_style"} +{"code": "def new(cls, access_token, environment='prod'):\n\n request = RequestBuilder \\\n .request(environment) \\\n .to_service(cls.SERVICE_NAME, cls.SERVICE_VERSION) \\\n .throw(\n StorageForbiddenException,\n lambda resp: 'You are forbidden to do this.'\n if resp.status_code == 403 else None\n ) \\\n .throw(\n StorageNotFoundException,\n lambda resp: 'The entity is not found'\n if resp.status_code == 404 else None\n ) \\\n .throw(\n StorageException,\n lambda resp: 'Server response: {0} - {1}'.format(resp.status_code, resp.text)\n if not resp.ok else None\n )\n\n authenticated_request = request.with_token(access_token)\n\n return cls(request, authenticated_request)", "docstring": "Create a new storage service REST client.\n\nArgs:\n environment: The service environment to be used for the client\n access_token: The access token used to authenticate with the\n service\n\nReturns:\n A storage_service.api.ApiClient instance\n\nExample:\n >>> storage_client = ApiClient.new(my_access_token)", "source": "juraj_google_style"} +{"code": "def __xor__(self, other: 'TensorFluent') -> 'TensorFluent':\n\n return self._binary_op(self, other, tf.logical_xor, tf.bool)", "docstring": "Returns a TensorFluent for the xor logical operator.\n\nArgs:\n self: The first operand.\n other: The second operand.\n\nReturns:\n A TensorFluent wrapping the operator's output.", "source": "juraj_google_style"} +{"code": "def extract(self, text: str) -> List[Extraction]:\n\n\n doc = self._tokenizer.tokenize_to_spacy_doc(text)\n self._load_matcher()\n\n matches = [x for x in self._matcher(doc) if x[1] != x[2]]\n pos_filtered_matches = []\n neg_filtered_matches = []\n for idx, start, end in matches:\n span_doc = self._tokenizer.tokenize_to_spacy_doc(doc[start:end].text)\n this_spacy_rule = self._matcher.get(idx)\n relations = self._find_relation(span_doc, this_spacy_rule)\n rule_id, _ = self._hash_map[idx]\n this_rule = self._rule_lst[rule_id]\n if self._filter_match(doc[start:end], relations, this_rule.patterns):\n value = self._form_output(doc[start:end], this_rule.output_format, relations, this_rule.patterns)\n if this_rule.polarity:\n pos_filtered_matches.append((start, end, value, rule_id, relations))\n else:\n neg_filtered_matches.append((start, end, value, rule_id, relations))\n\n return_lst = []\n if pos_filtered_matches:\n longest_lst_pos = self._get_longest(pos_filtered_matches)\n if neg_filtered_matches:\n longest_lst_neg = self._get_longest(neg_filtered_matches)\n return_lst = self._reject_neg(longest_lst_pos, longest_lst_neg)\n else:\n return_lst = longest_lst_pos\n\n extractions = []\n for (start, end, value, rule_id, relation) in return_lst:\n this_extraction = Extraction(value=value,\n extractor_name=self.name,\n start_token=start,\n end_token=end,\n start_char=doc[start].idx,\n end_char=doc[end-1].idx+len(doc[end-1]),\n rule_id=rule_id.split(\"rule_id##\")[0],\n match_mapping=relation)\n extractions.append(this_extraction)\n\n return extractions", "docstring": "Extract from text\n\nArgs:\n text (str): input str to be extracted.\n\nReturns:\n List[Extraction]: the list of extraction or the empty list if there are no matches.", "source": "juraj_google_style"} +{"code": "def __init__(self, on_exception=Exception, limit=5, interval=None,\n validator=None):\n\n self.attempts = 0\n self._on_exception = on_exception\n\n self._setup_limit(limit)\n self._setup_interval(interval)\n self._setup_validator(validator)", "docstring": "Configure how a function should be retried.\n\nArgs:\n on_exception (BaseException): The exception to catch. Use this to\n set which exception and it's subclasses to catch.\n limit ()", "source": "juraj_google_style"} +{"code": "def pager(__text: str, *, pager: Optional[str] = 'less'):\n\n if pager:\n run([pager, ], input=__text.encode())\n else:\n print(__text)", "docstring": "Pass output through pager.\n\n See :manpage:`less(1)`, if you wish to configure the default pager. For\n example, you may wish to check ``FRSX`` options.\n\nArgs:\n __text: Text to page\n pager: Pager to use", "source": "juraj_google_style"} +{"code": "def modify_prefix(channel, new_prefix):\n\n\n # Create embed UI object\n gui = ui_embed.UI(\n channel,\n \"Prefix updated\",\n \"Modis prefix is now `{}`\".format(new_prefix),\n modulename=modulename\n )\n\n return gui", "docstring": "Creates an embed UI containing the prefix modified message\n\nArgs:\n channel (discord.Channel): The Discord channel to bind the embed to\n new_prefix (str): The value of the new prefix\n\nReturns:\n embed: The created embed", "source": "juraj_google_style"} +{"code": "def remove_forwarding_rules(self, forwarding_rules):\n\n rules_dict = [rule.__dict__ for rule in forwarding_rules]\n\n return self.get_data(\n \"load_balancers/%s/forwarding_rules/\" % self.id,\n type=DELETE,\n params={\"forwarding_rules\": rules_dict}\n )", "docstring": "Removes existing forwarding rules from a LoadBalancer.\n\nArgs:\n forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects", "source": "juraj_google_style"} +{"code": "def ReadFileObject(self, file_object):\n\n # TODO: add try, except?\n yaml_generator = yaml.safe_load_all(file_object)\n\n last_artifact_definition = None\n for yaml_definition in yaml_generator:\n try:\n artifact_definition = self.ReadArtifactDefinitionValues(yaml_definition)\n except errors.FormatError as exception:\n error_location = 'At start'\n if last_artifact_definition:\n error_location = 'After: {0:s}'.format(last_artifact_definition.name)\n\n raise errors.FormatError(\n '{0:s} {1!s}'.format(error_location, exception))\n\n yield artifact_definition\n last_artifact_definition = artifact_definition", "docstring": "Reads artifact definitions from a file-like object.\n\nArgs:\n file_object (file): file-like object to read from.\n\nYields:\n ArtifactDefinition: an artifact definition.\n\nRaises:\n FormatError: if the format of the YAML artifact definition is not set\n or incorrect.", "source": "juraj_google_style"} +{"code": "def _Open(self, path_spec=None, mode='rb'):\n\n if not path_spec:\n raise ValueError('Missing path specification.')\n\n file_system = resolver.Resolver.OpenFileSystem(\n path_spec, resolver_context=self._resolver_context)\n\n file_entry = file_system.GetFileEntryByPathSpec(path_spec)\n if not file_entry:\n file_system.Close()\n raise IOError('Unable to retrieve file entry.')\n\n if not file_entry.IsFile():\n file_system.Close()\n raise IOError('Not a regular file.')\n\n self._file_system = file_system\n self._zip_file = self._file_system.GetZipFile()\n self._zip_info = file_entry.GetZipInfo()\n\n self._current_offset = 0\n self._uncompressed_stream_size = self._zip_info.file_size", "docstring": "Opens the file-like object defined by path specification.\n\nArgs:\n path_spec (Optional[PathSpec]): path specification.\n mode (Optional[str]): file access mode.\n\nRaises:\n AccessError: if the access to open the file was denied.\n IOError: if the file-like object could not be opened.\n OSError: if the file-like object could not be opened.\n PathSpecError: if the path specification is incorrect.\n ValueError: if the path specification is invalid.", "source": "juraj_google_style"} +{"code": "def at(self, row, col):\n\n if not (isinstance(row, int) and isinstance(col, int)):\n raise TypeError(row, col)\n return self._values[row][col]", "docstring": "Return the value at the given cell position.\n\nArgs:\n row (int): zero-based row number\n col (int): zero-based column number\n\nReturns:\n cell value\n\nRaises:\n TypeError: if ``row`` or ``col`` is not an ``int``\n IndexError: if the position is out of range", "source": "juraj_google_style"} +{"code": "def _try_recover(self, trial, error_msg):\n\n try:\n self.trial_executor.stop_trial(\n trial,\n error=error_msg is not None,\n error_msg=error_msg,\n stop_logger=False)\n trial.result_logger.flush()\n if self.trial_executor.has_resources(trial.resources):\n logger.info(\"Attempting to recover\"\n \" trial state from last checkpoint.\")\n self.trial_executor.start_trial(trial)\n if trial.status == Trial.ERROR:\n raise RuntimeError(\"Trial did not start correctly.\")\n else:\n logger.debug(\"Notifying Scheduler and requeueing trial.\")\n self._requeue_trial(trial)\n except Exception:\n logger.exception(\"Error recovering trial from checkpoint, abort.\")\n self._scheduler_alg.on_trial_error(self, trial)\n self._search_alg.on_trial_complete(trial.trial_id, error=True)", "docstring": "Tries to recover trial.\n\n Notifies SearchAlgorithm and Scheduler if failure to recover.\n\nArgs:\n trial (Trial): Trial to recover.\n error_msg (str): Error message from prior to invoking this method.", "source": "juraj_google_style"} +{"code": "def _PrintExtractionStatusUpdateWindow(self, processing_status):\n\n if self._stdout_output_writer:\n self._ClearScreen()\n\n output_text = 'plaso - {0:s} version {1:s}\\n\\n'.format(\n self._tool_name, plaso.__version__)\n self._output_writer.Write(output_text)\n\n self.PrintExtractionStatusHeader(processing_status)\n\n table_view = views.CLITabularTableView(column_names=[\n 'Identifier', 'PID', 'Status', 'Memory', 'Sources', 'Events',\n 'File'], column_sizes=[15, 7, 15, 15, 15, 15, 0])\n\n self._AddExtractionProcessStatusTableRow(\n processing_status.foreman_status, table_view)\n\n for worker_status in processing_status.workers_status:\n self._AddExtractionProcessStatusTableRow(worker_status, table_view)\n\n table_view.Write(self._output_writer)\n self._output_writer.Write('\\n')\n\n if processing_status.aborted:\n self._output_writer.Write(\n 'Processing aborted - waiting for clean up.\\n\\n')\n\n # TODO: remove update flicker. For win32console we could set the cursor\n # top left, write the table, clean the remainder of the screen buffer\n # and set the cursor at the end of the table.\n if self._stdout_output_writer:\n # We need to explicitly flush stdout to prevent partial status updates.\n sys.stdout.flush()", "docstring": "Prints an extraction status update in window mode.\n\nArgs:\n processing_status (ProcessingStatus): processing status.", "source": "juraj_google_style"} +{"code": "def _stride(stride_spec):\n\n if stride_spec is None:\n return [1, 1, 1, 1]\n elif isinstance(stride_spec, tf.compat.integral_types):\n return [1, stride_spec, stride_spec, 1]\n elif len(stride_spec) == 1:\n return [1, stride_spec[0], stride_spec[0], 1]\n elif len(stride_spec) == 2:\n return [1, stride_spec[0], stride_spec[1], 1]\n else:\n assert len(stride_spec) == 4\n return stride_spec", "docstring": "Expands the stride spec into a length 4 list.\n\nArgs:\n stride_spec: If length 0, 1 or 2 then assign the inner dimensions, otherwise\n return stride_spec if it is length 4.\n\nReturns:\n A length 4 list.", "source": "juraj_google_style"} +{"code": "def set_api_url(self, api_url=\"https://{lang}.wikipedia.org/w/api.php\", lang=\"en\"):\n\n old_api_url = self._api_url\n old_lang = self._lang\n self._lang = lang.lower()\n self._api_url = api_url.format(lang=self._lang)\n try:\n self._get_site_info()\n self.__supported_languages = None # reset this\n except MediaWikiException:\n # reset api url and lang in the event that the exception was caught\n self._api_url = old_api_url\n self._lang = old_lang\n raise MediaWikiAPIURLError(api_url)\n self.clear_memoized()", "docstring": "Set the API URL and language\n\nArgs:\n api_url (str): API URL to use\n lang (str): Language of the API URL\n\nRaises:\n :py:func:`mediawiki.exceptions.MediaWikiAPIURLError`: if the \\\n url is not a valid MediaWiki site", "source": "juraj_google_style"} +{"code": "def _colourise(text: str, colour: str) -> str:\n\n if COLOUR:\n text = style(text, fg=colour, bold=True)\n return text", "docstring": "Colour text, if possible.\n\nArgs:\n text: Text to colourise\n colour: Colour to display text in\n\nReturns:\n Colourised text, if possible", "source": "juraj_google_style"} +{"code": "def _MergeIdenticalCaseInsensitive(self, a, b):\n\n if a.lower() != b.lower():\n raise MergeError(\"values must be the same (case insensitive) \"\n \"('%s' vs '%s')\" % (transitfeed.EncodeUnicode(a),\n transitfeed.EncodeUnicode(b)))\n return b", "docstring": "Tries to merge two strings.\n\n The string are required to be the same ignoring case. The second string is\n always used as the merged value.\n\nArgs:\n a: The first string.\n b: The second string.\n\nReturns:\n The merged string. This is equal to the second string.\n\nRaises:\n MergeError: The strings were not the same ignoring case.", "source": "juraj_google_style"} +{"code": "def _maybe_commit(self, transaction):\n\n try:\n transaction._commit()\n return True\n except exceptions.GoogleAPICallError as exc:\n if transaction._read_only:\n raise\n\n if isinstance(exc, exceptions.Aborted):\n # If a read-write transaction returns ABORTED, retry.\n return False\n else:\n raise", "docstring": "Try to commit the transaction.\n\n If the transaction is read-write and the ``Commit`` fails with the\n ``ABORTED`` status code, it will be retried. Any other failure will\n not be caught.\n\nArgs:\n transaction (~.firestore_v1beta1.transaction.Transaction): The\n transaction to be ``Commit``-ed.\n\nReturns:\n bool: Indicating if the commit succeeded.", "source": "juraj_google_style"} +{"code": "def load_partition_data(self, index):\n\n\n info = self.partitions[index]\n data = PartitionData(info)\n\n for utt_id in info.utt_ids:\n utt_data = [c._file[utt_id][:] for c in self.containers]\n data.utt_data.append(utt_data)\n\n return data", "docstring": "Load and return the partition with the given index.\n\nArgs:\n index (int): The index of partition, that refers to the index in ``self.partitions``.\n\nReturns:\n PartitionData: A PartitionData object containing the data for the partition with the given index.", "source": "juraj_google_style"} +{"code": "def generate(self, model, outfolder, *, exclude=None):\n\n with pythonic_names():\n super().generate(model, outfolder)\n\n check_dependency = self.with_dependencies and model.eResource\n if check_dependency:\n if exclude is None:\n exclude = set()\n resource = model.eResource\n # the current resource had been managed and is excluded from further generations\n exclude.add(resource)\n rset = resource.resource_set\n direct_resources = {r for r in rset.resources.values() if r not in exclude}\n for resource in direct_resources:\n self.generate(resource.contents[0], outfolder, exclude=exclude)", "docstring": "Generate model code.\n\nArgs:\n model: The meta-model to generate code for.\n outfolder: Path to the directoty that will contain the generated code.\n exclude: List of referenced resources for which code was already generated\n (to prevent regeneration).", "source": "juraj_google_style"} +{"code": "def commutator(A, B=None):\n\n if B:\n return A * B - B * A\n return SPre(A) - SPost(A)", "docstring": "Commutator of `A` and `B`\n\n If ``B != None``, return the commutator :math:`[A,B]`, otherwise return\n the super-operator :math:`[A,\\cdot]`. The super-operator :math:`[A,\\cdot]`\n maps any other operator ``B`` to the commutator :math:`[A, B] = A B - B A`.\n\nArgs:\n A: The first operator to form the commutator of.\n B: The second operator to form the commutator of, or None.\n\nReturns:\n SuperOperator: The linear superoperator :math:`[A,\\cdot]`", "source": "juraj_google_style"} +{"code": "def __init__(self, tcex):\n\n self._tcex = tcex\n self._is_organization = False\n self._notification_type = None\n self._recipients = None\n self._priority = 'Low'", "docstring": "Initialize the Class properties.\n\nArgs:\n tcex (obj): An instance of TcEx object.", "source": "juraj_google_style"} +{"code": "def fixed_development_directory(templates, inventory, topics, user):\n\n\n echo(\"Fixed syntax has been deprecated, see positional syntax\")\n\n project, item, task = topics[0].split(\"/\")\n\n template = binding_from_item(inventory, item)\n pattern = pattern_from_template(templates, template)\n\n if find_positional_arguments(pattern):\n echo(\"\\\"%s\\\" uses a positional syntax\" % project)\n echo(\"Try this:\")\n echo(\" be in %s\" % \" \".join([project, item, task]))\n sys.exit(USER_ERROR)\n\n keys = {\n \"cwd\": os.getcwd(),\n \"project\": project,\n \"item\": item.replace(\"\\\\\", \"/\"),\n \"user\": user,\n \"task\": task,\n \"type\": task, # deprecated\n }\n\n try:\n return pattern.format(**keys).replace(\"\\\\\", \"/\")\n except KeyError as exc:\n echo(\"TEMPLATE ERROR: %s is not an available key\\n\" % exc)\n echo(\"Available keys\")\n for key in keys:\n echo(\"\\n- %s\" % key)\n sys.exit(1)", "docstring": "Return absolute path to development directory\n\nArgs:\n templates (dict): templates.yaml\n inventory (dict): inventory.yaml\n context (dict): The be context, from context()\n topics (list): Arguments to `in`\n user (str): Current `be` user", "source": "juraj_google_style"} +{"code": "def intersect(self, other):\n\n self.automaton = fst.intersect(self.automaton, other.automaton)\n return self", "docstring": "Constructs an unminimized DFA recognizing\n the intersection of the languages of two given DFAs.\n\nArgs:\n other (DFA): The other DFA that will be used\n for the intersect operation\n\nReturns:\n Returns:\n DFA: The resulting DFA", "source": "juraj_google_style"} +{"code": "def generate_exact(self, model, vcpu_num, host_cpu):\n\n\n nested = {'Intel': 'vmx', 'AMD': 'svm'}\n cpu = ET.Element('cpu', match='exact')\n ET.SubElement(cpu, 'model').text = model\n cpu.append(self.generate_topology(vcpu_num))\n\n vendor = host_cpu.findtext('vendor')\n if not nested.get(vendor):\n LOGGER.debug(\n 'Unknown vendor: {0}, did not configure nested '\n 'virtualization cpu flag on guest.'.format(vendor)\n )\n return cpu\n\n model_vendor = LibvirtCPU.get_cpu_vendor(family=model)\n if vendor != model_vendor:\n LOGGER.debug(\n (\n 'Not enabling nested virtualization feature, host '\n 'vendor is: {0}, guest vendor: '\n '{1}'.format(vendor, model_vendor)\n )\n )\n return cpu\n\n flag = nested[vendor]\n if host_cpu.find('feature/[@name=\"{0}\"]'.format(flag)) is not None:\n cpu.append(self.generate_feature(name=flag))\n else:\n LOGGER.debug(\n (\n 'missing {0} cpu flag on host, nested '\n 'virtualization will probably not '\n 'work.'\n ).format(flag)\n )\n\n return cpu", "docstring": "Generate exact CPU model with nested virtualization CPU feature.\n\nArgs:\n model(str): libvirt supported CPU model\n vcpu_num(int): number of virtual cpus\n host_cpu(lxml.etree.Element): the host CPU model\n\nReturns:\n lxml.etree.Element: CPU XML node", "source": "juraj_google_style"} +{"code": "def Pager(self, service):\n\n has_page = True\n while has_page:\n page = service.query(self)\n yield page\n has_page = self.HasNext(page)\n if has_page:\n self.NextPage()", "docstring": "A page generator for this service query and the provided service.\n\n This generates a page as a result from using the provided service's query()\n method until there are no more results to fetch.\n\nArgs:\n service: The service object for making a query using this service query.\n\nYields:\n A resulting page from querying the provided service.", "source": "juraj_google_style"} +{"code": "def get_by(self, field, value):\n\n return self._client.get_by(field=field, value=value)", "docstring": "Gets all drive enclosures that match the filter.\n\n The search is case-insensitive.\n\nArgs:\n Field: field name to filter.\n Value: value to filter.\n\nReturns:\n list: A list of drive enclosures.", "source": "juraj_google_style"} +{"code": "def before_request(self, request, method, url, headers):\n\n # pylint: disable=unused-argument\n # (pylint doesn't correctly recognize overridden methods.)\n parts = urllib.parse.urlsplit(url)\n # Strip query string and fragment\n audience = urllib.parse.urlunsplit(\n (parts.scheme, parts.netloc, parts.path, \"\", \"\"))\n token = self._get_jwt_for_audience(audience)\n self.apply(headers, token=token)", "docstring": "Performs credential-specific before request logic.\n\nArgs:\n request (Any): Unused. JWT credentials do not need to make an\n HTTP request to refresh.\n method (str): The request's HTTP method.\n url (str): The request's URI. This is used as the audience claim\n when generating the JWT.\n headers (Mapping): The request's headers.", "source": "juraj_google_style"} +{"code": "def from_dict(cls, tx):\n\n inputs = [Input.from_dict(input_) for input_ in tx['inputs']]\n outputs = [Output.from_dict(output) for output in tx['outputs']]\n return cls(tx['operation'], tx['asset'], inputs, outputs,\n tx['metadata'], tx['version'], hash_id=tx['id'])", "docstring": "Transforms a Python dictionary to a Transaction object.\n\nArgs:\n tx_body (dict): The Transaction to be transformed.\n\nReturns:\n :class:`~bigchaindb.common.transaction.Transaction`", "source": "juraj_google_style"} +{"code": "def _get_user_id(arguments_dict):\n\n if 'user_id' not in arguments_dict:\n raise TypeError('Each invocation of a UserTaskMixin subclass must include the user_id')\n user_id = arguments_dict['user_id']\n try:\n get_user_model().objects.get(pk=user_id)\n except (ValueError, get_user_model().DoesNotExist):\n raise TypeError('Invalid user_id: {}'.format(user_id))\n return user_id", "docstring": "Get and validate the `user_id` argument to a task derived from `UserTaskMixin`.\n\nArgs:\n arguments_dict (dict): The parsed positional and keyword arguments to the task\n\n Returns\n -------\n int: The primary key of a user record (may not be an int if using a custom user model)", "source": "juraj_google_style"} +{"code": "def __init__(self, application_namespace=None, application_data=None):\n\n super(ApplicationSpecificInformation, self).__init__(\n Tags.APPLICATION_SPECIFIC_INFORMATION)\n\n if application_namespace is None:\n self.application_namespace = ApplicationNamespace()\n else:\n self.application_namespace = application_namespace\n\n if application_data is None:\n self.application_data = ApplicationData()\n else:\n self.application_data = application_data\n\n self.validate()", "docstring": "Construct an ApplicationSpecificInformation object.\n\nArgs:\n application_namespace (ApplicationNamespace): The name of a\n namespace supported by the server. Optional, defaults to None.\n application_data (ApplicationData): String data relevant to the\n specified namespace. Optional, defaults to None.", "source": "juraj_google_style"} +{"code": "def etm_register_write(self, register_index, value, delay=False):\n\n self._dll.JLINKARM_ETM_WriteReg(int(register_index), int(value), int(delay))\n return None", "docstring": "Writes a value to an ETM register.\n\nArgs:\n self (JLink): the ``JLink`` instance.\n register_index (int): the register to write to.\n value (int): the value to write to the register.\n delay (bool): boolean specifying if the write should be buffered.\n\nReturns:\n ``None``", "source": "juraj_google_style"} +{"code": "def _object_url(self, objtype, objid):\n\n return \"{base_url}/api/{api_version}/{controller}/{obj_id}\".format(\n base_url=self._base_url(),\n api_version=self.api_version,\n controller=self._controller_name(objtype),\n obj_id=objid\n )", "docstring": "Generate the URL for the specified object\n\nArgs:\n objtype (str): The object's type\n objid (int): The objects ID\n\nReturns:\n A string containing the URL of the object", "source": "juraj_google_style"} +{"code": "def modify_module(channel, module_name, module_state):\n\n\n # Create embed UI object\n gui = ui_embed.UI(\n channel,\n \"{} updated\".format(module_name),\n \"{} is now {}\".format(module_name, \"activated\" if module_state else \"deactivated\"),\n modulename=modulename\n )\n\n return gui", "docstring": "Creates an embed UI containing the module modified message\n\nArgs:\n channel (discord.Channel): The Discord channel to bind the embed to\n module_name (str): The name of the module that was updated\n module_state (bool): The current state of the module\n\nReturns:\n embed: The created embed", "source": "juraj_google_style"} +{"code": "def sunrise(self, date=None, zenith=None):\n\n return (segment.sunrise(date, zenith) for segment in self)", "docstring": "Calculate sunrise times for locations.\n\nArgs:\n date (datetime.date): Calculate rise or set for given date\n zenith (str): Calculate sunrise events, or end of twilight\n\nReturns:\n list of list of datetime.datetime: The time for the sunrise for\n each point in each segment", "source": "juraj_google_style"} +{"code": "def _ParseLogLine(self, parser_mediator, structure):\n\n try:\n date_time = dfdatetime_time_elements.TimeElements(\n time_elements_tuple=structure.date_time)\n # TODO: check if date and time values are local time or in UTC.\n date_time.is_local_time = True\n except ValueError:\n parser_mediator.ProduceExtractionWarning(\n 'invalid date time value: {0!s}'.format(structure.date_time))\n return\n\n event_data = SophosAVLogEventData()\n event_data.text = structure.text\n\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_ADDED,\n time_zone=parser_mediator.timezone)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a log line.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n structure (pyparsing.ParseResults): structure of tokens derived from\n a line of a text file.", "source": "juraj_google_style"} +{"code": "def group_pairs(pair_list):\n\n # Initialize dict of lists\n groupid_to_items = defaultdict(list)\n # Insert each item into the correct group\n for item, groupid in pair_list:\n groupid_to_items[groupid].append(item)\n return groupid_to_items", "docstring": "Groups a list of items using the first element in each pair as the item and\n the second element as the groupid.\n\nArgs:\n pair_list (list): list of 2-tuples (item, groupid)\n\nReturns:\n dict: groupid_to_items: maps a groupid to a list of items\n\n SeeAlso:\n group_items", "source": "juraj_google_style"} +{"code": "def walk(self, action, user_data=None):\n\n action(self.index_file, self.__root, 0, user_data)\n self.__do_walk(self.__root, 1, action, user_data)", "docstring": "Walk the hierarchy, applying action to each filename.\n\nArgs:\n action: callable, the callable to invoke for each filename,\n will be invoked with the filename, the subfiles, and\n the level in the sitemap.", "source": "juraj_google_style"} +{"code": "def get_airports(self, country):\n\n url = AIRPORT_BASE.format(country.replace(\" \", \"-\"))\n return self._fr24.get_airports_data(url)", "docstring": "Returns a list of all the airports\n For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc\n\nArgs:\n country (str): The country for which the airports will be fetched\n\n Example::\n\n from pyflightdata import FlightData\n f=FlightData()\n f.get_airports('India')", "source": "juraj_google_style"} +{"code": "def quad_genz_keister_18(order):\n\n order = sorted(GENZ_KEISTER_18.keys())[order]\n\n abscissas, weights = GENZ_KEISTER_18[order]\n abscissas = numpy.array(abscissas)\n weights = numpy.array(weights)\n\n weights /= numpy.sum(weights)\n abscissas *= numpy.sqrt(2)\n\n return abscissas, weights", "docstring": "Hermite Genz-Keister 18 rule.\n\nArgs:\n order (int):\n The quadrature order. Must be in the interval (0, 8).\n\nReturns:\n (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):\n Abscissas and weights\n\nExample:\n >>> abscissas, weights = quad_genz_keister_18(1)\n >>> print(numpy.around(abscissas, 4))\n [-1.7321 0. 1.7321]\n >>> print(numpy.around(weights, 4))\n [0.1667 0.6667 0.1667]", "source": "juraj_google_style"} +{"code": "def declare_queue(self, queue_name):\n\n attempts = 1\n while True:\n try:\n if queue_name not in self.queues:\n self.emit_before(\"declare_queue\", queue_name)\n self._declare_queue(queue_name)\n self.queues.add(queue_name)\n self.emit_after(\"declare_queue\", queue_name)\n\n delayed_name = dq_name(queue_name)\n self._declare_dq_queue(queue_name)\n self.delay_queues.add(delayed_name)\n self.emit_after(\"declare_delay_queue\", delayed_name)\n\n self._declare_xq_queue(queue_name)\n break\n except (pika.exceptions.AMQPConnectionError,\n pika.exceptions.AMQPChannelError) as e: # pragma: no cover\n # Delete the channel and the connection so that the next\n # caller may initiate new ones of each.\n del self.channel\n del self.connection\n\n attempts += 1\n if attempts > MAX_DECLARE_ATTEMPTS:\n raise ConnectionClosed(e) from None\n\n self.logger.debug(\n \"Retrying declare due to closed connection. [%d/%d]\",\n attempts, MAX_DECLARE_ATTEMPTS,\n )", "docstring": "Declare a queue. Has no effect if a queue with the given\n name already exists.\n\n Parameters:\n queue_name(str): The name of the new queue.\n\nRaises:\n ConnectionClosed: If the underlying channel or connection\n has been closed.", "source": "juraj_google_style"} +{"code": "def _ProcessPathSpec(self, extraction_worker, parser_mediator, path_spec):\n\n self._current_display_name = parser_mediator.GetDisplayNameForPathSpec(\n path_spec)\n\n try:\n extraction_worker.ProcessPathSpec(parser_mediator, path_spec)\n\n except KeyboardInterrupt:\n self._abort = True\n\n self._processing_status.aborted = True\n if self._status_update_callback:\n self._status_update_callback(self._processing_status)\n\n # We cannot recover from a CacheFullError and abort processing when\n # it is raised.\n except dfvfs_errors.CacheFullError:\n # TODO: signal engine of failure.\n self._abort = True\n logger.error((\n 'ABORT: detected cache full error while processing '\n 'path spec: {0:s}').format(self._current_display_name))\n\n # All exceptions need to be caught here to prevent the worker\n # from being killed by an uncaught exception.\n except Exception as exception: # pylint: disable=broad-except\n parser_mediator.ProduceExtractionWarning((\n 'unable to process path specification with error: '\n '{0!s}').format(exception), path_spec=path_spec)\n\n if getattr(self._processing_configuration, 'debug_output', False):\n logger.warning(\n 'Unhandled exception while processing path spec: {0:s}.'.format(\n self._current_display_name))\n logger.exception(exception)\n\n pdb.post_mortem()", "docstring": "Processes a path specification.\n\nArgs:\n extraction_worker (worker.ExtractionWorker): extraction worker.\n parser_mediator (ParserMediator): parser mediator.\n path_spec (dfvfs.PathSpec): path specification.", "source": "juraj_google_style"} +{"code": "def get(self, identifier, default=None):\n\n split_label = (tuple(identifier.split('.'))\n if isinstance(identifier, str) else tuple(identifier))\n if len(split_label) == 1:\n identifier = split_label[0]\n return self.__dict__.get(identifier, default)\n path_item = self\n for identifier in split_label:\n if path_item == default or path_item is None:\n return default\n path_item = path_item.get(identifier, default)\n return path_item", "docstring": "Get a node of the AttrTree using its path string.\n\nArgs:\n identifier: Path string of the node to return\n default: Value to return if no node is found\n\nReturns:\n The indexed node of the AttrTree", "source": "juraj_google_style"} +{"code": "def Var(self, mu=None):\n\n if mu is None:\n mu = self.Mean()\n\n var = 0.0\n for x, p in self.d.iteritems():\n var += p * (x - mu) ** 2\n return var", "docstring": "Computes the variance of a PMF.\n\nArgs:\n mu: the point around which the variance is computed;\n if omitted, computes the mean\n\nReturns:\n float variance", "source": "juraj_google_style"} +{"code": "def remove(self, oid):\n\n hba = self.lookup_by_oid(oid)\n partition = self.parent\n devno = hba.properties.get('device-number', None)\n if devno:\n partition.devno_free_if_allocated(devno)\n wwpn = hba.properties.get('wwpn', None)\n if wwpn:\n partition.wwpn_free_if_allocated(wwpn)\n assert 'hba-uris' in partition.properties\n hba_uris = partition.properties['hba-uris']\n hba_uris.remove(hba.uri)\n super(FakedHbaManager, self).remove(oid)", "docstring": "Remove a faked HBA resource.\n\n This method also updates the 'hba-uris' property in the parent\n Partition resource, by removing the URI for the faked HBA resource.\n\n Parameters:\n\n oid (string):\n The object ID of the faked HBA resource.", "source": "juraj_google_style"} +{"code": "def __init__(self, hash_queue, hash_analysis_queue, **kwargs):\n\n super(ViperAnalyzer, self).__init__(\n hash_queue, hash_analysis_queue, **kwargs)\n self._checked_for_old_python_version = False\n self._host = None\n self._port = None\n self._protocol = None\n self._url = None", "docstring": "Initializes a Viper hash analyzer.\n\nArgs:\n hash_queue (Queue.queue): contains hashes to be analyzed.\n hash_analysis_queue (Queue.queue): that the analyzer will append\n HashAnalysis objects this queue.", "source": "juraj_google_style"} +{"code": "def diff_commonOverlap(self, text1, text2):\n\n # Cache the text lengths to prevent multiple calls.\n text1_length = len(text1)\n text2_length = len(text2)\n # Eliminate the null case.\n if text1_length == 0 or text2_length == 0:\n return 0\n # Truncate the longer string.\n if text1_length > text2_length:\n text1 = text1[-text2_length:]\n elif text1_length < text2_length:\n text2 = text2[:text1_length]\n text_length = min(text1_length, text2_length)\n # Quick check for the worst case.\n if text1 == text2:\n return text_length\n\n # Start by looking for a single character match\n # and increase length until no match is found.\n # Performance analysis: https://neil.fraser.name/news/2010/11/04/\n best = 0\n length = 1\n while True:\n pattern = text1[-length:]\n found = text2.find(pattern)\n if found == -1:\n return best\n length += found\n if found == 0 or text1[-length:] == text2[:length]:\n best = length\n length += 1", "docstring": "Determine if the suffix of one string is the prefix of another.\n\nArgs:\n text1 First string.\n text2 Second string.\n\nReturns:\n The number of characters common to the end of the first\n string and the start of the second string.", "source": "juraj_google_style"} +{"code": "def expression_filter(self, name, **kwargs):\n\n\n def decorator(func):\n self.filters[name] = ExpressionFilter(name, func, **kwargs)\n\n return decorator", "docstring": "Returns a decorator function for adding an expression filter.\n\nArgs:\n name (str): The name of the filter.\n **kwargs: Variable keyword arguments for the filter.\n\nReturns:\n Callable[[Callable[[AbstractExpression, Any], AbstractExpression]]]: A decorator\n function for adding an expression filter.", "source": "juraj_google_style"} +{"code": "def __init__(\n self,\n nb_url: Optional[str] = None,\n nb_token: Optional[str] = None,\n use_slugs: bool = True,\n flatten_custom_fields: bool = True,\n filter_parameters: Optional[Dict[str, Any]] = None,\n **kwargs: Any,\n ) -> None:\n\n filter_parameters = filter_parameters or {}\n\n nb_url = nb_url or os.environ.get(\"NB_URL\", \"http://localhost:8080\")\n nb_token = nb_token or os.environ.get(\n \"NB_TOKEN\", \"0123456789abcdef0123456789abcdef01234567\"\n )\n headers = {\"Authorization\": \"Token {}\".format(nb_token)}\n\n # Create dict of hosts using 'devices' from NetBox\n r = requests.get(\n \"{}/api/dcim/devices/?limit=0\".format(nb_url),\n headers=headers,\n params=filter_parameters,\n )\n r.raise_for_status()\n nb_devices = r.json()\n\n hosts = {}\n for d in nb_devices[\"results\"]:\n host: HostsDict = {\"data\": {}}\n\n # Add value for IP address\n if d.get(\"primary_ip\", {}):\n host[\"hostname\"] = d[\"primary_ip\"][\"address\"].split(\"/\")[0]\n\n # Add values that don't have an option for 'slug'\n host[\"data\"][\"serial\"] = d[\"serial\"]\n host[\"data\"][\"vendor\"] = d[\"device_type\"][\"manufacturer\"][\"name\"]\n host[\"data\"][\"asset_tag\"] = d[\"asset_tag\"]\n\n if flatten_custom_fields:\n for cf, value in d[\"custom_fields\"].items():\n host[\"data\"][cf] = value\n else:\n host[\"data\"][\"custom_fields\"] = d[\"custom_fields\"]\n\n # Add values that do have an option for 'slug'\n if use_slugs:\n host[\"data\"][\"site\"] = d[\"site\"][\"slug\"]\n host[\"data\"][\"role\"] = d[\"device_role\"][\"slug\"]\n host[\"data\"][\"model\"] = d[\"device_type\"][\"slug\"]\n\n # Attempt to add 'platform' based of value in 'slug'\n host[\"platform\"] = d[\"platform\"][\"slug\"] if d[\"platform\"] else None\n\n else:\n host[\"data\"][\"site\"] = d[\"site\"][\"name\"]\n host[\"data\"][\"role\"] = d[\"device_role\"]\n host[\"data\"][\"model\"] = d[\"device_type\"]\n host[\"platform\"] = d[\"platform\"]\n\n # Assign temporary dict to outer dict\n hosts[d[\"name\"]] = host\n\n # Pass the data back to the parent class\n super().__init__(hosts=hosts, groups={}, defaults={}, **kwargs)", "docstring": "Netbox plugin\n\nArgs:\n nb_url: Netbox url, defaults to http://localhost:8080.\n You can also use env variable NB_URL\n nb_token: Netbokx token. You can also use env variable NB_TOKEN\n use_slugs: Whether to use slugs or not\n flatten_custom_fields: Whether to assign custom fields directly to the host or not\n filter_parameters: Key-value pairs to filter down hosts", "source": "juraj_google_style"} +{"code": "def set_consistent(self, consistent_config):\n\n\n # add job control plane if needed\n self.topology._add_job_control_plane()\n self.oport.operator.consistent(consistent_config)\n return self._make_placeable()", "docstring": "Indicates that the stream is the start of a consistent region.\n\nArgs:\n consistent_config(consistent.ConsistentRegionConfig): the configuration of the consistent region.\n\nReturns:\n Stream: Returns this stream.\n\n .. versionadded:: 1.11", "source": "juraj_google_style"} +{"code": "def design_stat_cooling(self, value=\"Cooling\"):\n\n if value is not None:\n try:\n value = str(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type str '\n 'for field `design_stat_cooling`'.format(value))\n if ',' in value:\n raise ValueError('value should not contain a comma '\n 'for field `design_stat_cooling`')\n vals = set()\n vals.add(\"Cooling\")\n if value not in vals:\n raise ValueError('value {} is not an accepted value for '\n 'field `design_stat_cooling`'.format(value))\n\n self._design_stat_cooling = value", "docstring": "Corresponds to IDD Field `design_stat_cooling`\n\nArgs:\n value (str): value for IDD Field `design_stat_cooling`\n Accepted values are:\n - Cooling\n Default value: Cooling\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def describe_enum(enum_definition):\n\n enum_descriptor = EnumDescriptor()\n enum_descriptor.name = enum_definition.definition_name().split('.')[-1]\n\n values = []\n for number in enum_definition.numbers():\n value = enum_definition.lookup_by_number(number)\n values.append(describe_enum_value(value))\n\n if values:\n enum_descriptor.values = values\n\n return enum_descriptor", "docstring": "Build descriptor for Enum class.\n\nArgs:\n enum_definition: Enum class to provide descriptor for.\n\nReturns:\n Initialized EnumDescriptor instance describing the Enum class.", "source": "juraj_google_style"} +{"code": "def tunnel(container, local_port, remote_port=None, gateway_port=None):\n\n if remote_port is None:\n remote_port = local_port\n if gateway_port is None:\n gateway_port = remote_port\n\n remote_host = get_ip(container)\n\n command = % {\n 'key_filename': env.key_filename,\n 'local_port': local_port,\n 'gateway_port': gateway_port,\n 'gateway_user': env.user,\n 'gateway_host': env.host,\n 'remote_port': remote_port,\n 'remote_host': remote_host,\n }\n\n command = command.replace('\\n', '')\n\n local(command)", "docstring": "Set up an SSH tunnel into the container, using the host as a gateway host.\n\nArgs:\n * container: Container name or ID\n * local_port: Local port\n * remote_port=None: Port on the Docker container (defaults to local_port)\n * gateway_port=None: Port on the gateway host (defaults to remote_port)", "source": "juraj_google_style"} +{"code": "def is_valid_embedding(emb, source, target):\n\n for _ in diagnose_embedding(emb, source, target):\n return False\n return True", "docstring": "A simple (bool) diagnostic for minor embeddings.\n\n See :func:`diagnose_embedding` for a more detailed diagnostic / more information.\n\nArgs:\n emb (dict): a dictionary mapping source nodes to arrays of target nodes\n source (graph or edgelist): the graph to be embedded\n target (graph or edgelist): the graph being embedded into\n\nReturns:\n bool: True if `emb` is valid.", "source": "juraj_google_style"} +{"code": "def extend(self, elts):\n\n # Use a copy, not a reference, as it is later necessary to mutate\n # the proto field from which elts are drawn in order to construct\n # the bundled request.\n elts = elts[:]\n self._in_deque.append(elts)\n event = self._event_for(elts)\n self._event_deque.append(event)\n return event", "docstring": "Adds elts to the tasks.\n\nArgs:\n elts (Sequence): a iterable of elements that can be appended to the\n task's bundle_field.\n\nReturns:\n Event: an event that can be used to wait on the response.", "source": "juraj_google_style"} +{"code": "def thermal_conductivity(self, temperature, volume):\n\n gamma = self.gruneisen_parameter(temperature, volume)\n theta_d = self.debye_temperature(volume) # K\n theta_a = theta_d * self.natoms**(-1./3.) # K\n prefactor = (0.849 * 3 * 4**(1./3.)) / (20. * np.pi**3)\n # kg/K^3/s^3\n prefactor = prefactor * (self.kb/self.hbar)**3 * self.avg_mass\n kappa = prefactor / (gamma**2 - 0.514 * gamma + 0.228)\n # kg/K/s^3 * Ang = (kg m/s^2)/(Ks)*1e-10\n # = N/(Ks)*1e-10 = Nm/(Kms)*1e-10 = W/K/m*1e-10\n kappa = kappa * theta_a**2 * volume**(1./3.) * 1e-10\n return kappa", "docstring": "Eq(17) in 10.1103/PhysRevB.90.174107\n\nArgs:\n temperature (float): temperature in K\n volume (float): in Ang^3\n\nReturns:\n float: thermal conductivity in W/K/m", "source": "juraj_google_style"} +{"code": "def encode_dataset(dataset, vocabulary):\n\n def encode(features):\n return {k: vocabulary.encode_tf(v) for k, v in features.items()}\n return dataset.map(encode, num_parallel_calls=tf.data.experimental.AUTOTUNE)", "docstring": "Encode from strings to token ids.\n\nArgs:\n dataset: a tf.data.Dataset with string values.\n vocabulary: a mesh_tensorflow.transformer.Vocabulary\n\nReturns:\n a tf.data.Dataset with integer-vector values ending in EOS=1", "source": "juraj_google_style"} +{"code": "def get(self, profile_id):\n\n if profile_id not in self._profiles:\n try:\n self._profiles[profile_id] = self._get_profile(profile_id)\n except (ValueError,\n IOError) as e:\n six.raise_from(RegistryError(e), e)\n return self._profiles[profile_id]", "docstring": "Returns the profile with the received ID as a dict\n\n If a local copy of the profile exists, it'll be returned. If not, it'll\n be downloaded from the web. The results are cached, so any subsequent\n calls won't hit the filesystem or the web.\n\nArgs:\n profile_id (str): The ID of the profile you want.\n\nRaises:\n RegistryError: If there was some problem opening the profile file\n or its format was incorrect.", "source": "juraj_google_style"} +{"code": "def change_numbering(self, rename_dict, inplace=False):\n\n output = self if inplace else self.copy()\n new_index = [rename_dict.get(key, key) for key in self.index]\n output.index = new_index\n if not inplace:\n return output", "docstring": "Return the reindexed version of Cartesian.\n\nArgs:\n rename_dict (dict): A dictionary mapping integers on integers.\n\nReturns:\n Cartesian: A renamed copy according to the dictionary passed.", "source": "juraj_google_style"} +{"code": "def section(self, regex, config='running_config'):\n\n if config in ['running_config', 'startup_config']:\n config = getattr(self, config)\n match = re.search(regex, config, re.M)\n if not match:\n raise TypeError('config section not found')\n block_start, line_end = match.regs[0]\n\n match = re.search(r'^[^\\s]', config[line_end:], re.M)\n if not match:\n raise TypeError('could not find end block')\n _, block_end = match.regs[0]\n\n block_end = line_end + block_end\n return config[block_start:block_end]", "docstring": "Returns a section of the config\n\nArgs:\n regex (str): A valid regular expression used to select sections\n of configuration to return\n config (str): The configuration to return. Valid values for config\n are \"running_config\" or \"startup_config\". The default value\n is \"running_config\"\n\nReturns:\n The configuration section as a string object.", "source": "juraj_google_style"} +{"code": "def delete_keys(d: Dict[Any, Any],\n keys_to_delete: List[Any],\n keys_to_keep: List[Any]) -> None:\n\n for k in keys_to_delete:\n if k in d and k not in keys_to_keep:\n del d[k]", "docstring": "Deletes keys from a dictionary, in place.\n\nArgs:\n d:\n dictonary to modify\n keys_to_delete:\n if any keys are present in this list, they are deleted...\n keys_to_keep:\n ... unless they are present in this list.", "source": "juraj_google_style"} +{"code": "def get_group(self, name, user_name=None):\n\n self.project_service.set_auth(self._token_project)\n return self.project_service.get_group(name, user_name)", "docstring": "Get information on the given group or whether or not a user is a member\n of the group.\n\nArgs:\n name (string): Name of group to query.\n user_name (optional[string]): Supply None if not interested in\n determining if user is a member of the given group.\n\nReturns:\n (mixed): Dictionary if getting group information or bool if a user\n name is supplied.\n\nRaises:\n requests.HTTPError on failure.", "source": "juraj_google_style"} +{"code": "def save_summaries(frames, keys, selected_summaries, batch_dir, batch_name):\n\n if not frames:\n logger.info(\"Could save summaries - no summaries to save!\")\n logger.info(\"You have no frames - aborting\")\n return None\n if not keys:\n logger.info(\"Could save summaries - no summaries to save!\")\n logger.info(\"You have no keys - aborting\")\n return None\n\n selected_summaries_dict = create_selected_summaries_dict(selected_summaries)\n summary_df = pd.concat(frames, keys=keys, axis=1)\n # saving the selected summaries\n for key, value in selected_summaries_dict.items():\n _summary_file_name = os.path.join(batch_dir, \"summary_%s_%s.csv\" % (\n key, batch_name))\n _summary_df = summary_df.iloc[:,\n summary_df.columns.get_level_values(1) == value]\n # include function to tweak headers here (need to learn MultiIndex)\n _header = _summary_df.columns\n _summary_df.to_csv(_summary_file_name, sep=\";\")\n logger.info(\n \"saved summary (%s) to:\\n %s\" % (key, _summary_file_name))\n logger.info(\"finished saving summaries\")\n return summary_df", "docstring": "Writes the summaries to csv-files\n\nArgs:\n frames: list of ``cellpy`` summary DataFrames\n keys: list of indexes (typically run-names) for the different runs\n selected_summaries: list defining which summary data to save\n batch_dir: directory to save to\n batch_name: the batch name (will be used for making the file-name(s))\n\n Returns: a pandas DataFrame with your selected summaries.", "source": "juraj_google_style"} +{"code": "def example_number_for_non_geo_entity(country_calling_code):\n\n metadata = PhoneMetadata.metadata_for_nongeo_region(country_calling_code, None)\n if metadata is not None:\n # For geographical entities, fixed-line data is always present. However, for non-geographical\n # entities, this is not the case, so we have to go through different types to find the\n # example number. We don't check fixed-line or personal number since they aren't used by\n # non-geographical entities (if this changes, a unit-test will catch this.)\n for desc in (metadata.mobile, metadata.toll_free, metadata.shared_cost, metadata.voip,\n metadata.voicemail, metadata.uan, metadata.premium_rate):\n try:\n if (desc is not None and desc.example_number is not None):\n return parse(_PLUS_SIGN + unicod(country_calling_code) + desc.example_number, UNKNOWN_REGION)\n except NumberParseException:\n pass\n return None", "docstring": "Gets a valid number for the specified country calling code for a non-geographical entity.\n\nArgs:\n country_calling_code -- The country calling code for a non-geographical entity.\n\n Returns a valid number for the non-geographical entity. Returns None when\n the metadata does not contain such information, or the country calling\n code passed in does not belong to a non-geographical entity.", "source": "juraj_google_style"} +{"code": "def pnum_to_processor_coordinates(mesh_shape, pnum):\n\n ret = []\n for dimsize in mesh_shape.to_integer_list[::-1]:\n ret.append(pnum % dimsize)\n pnum //= dimsize\n return ret[::-1]", "docstring": "Coordinates of a processor in the mesh.\n\nArgs:\n mesh_shape: a Shape\n pnum: an integer less than len(mesh_shape)\n\nReturns:\n a list of integers with length len(mesh_shape)", "source": "juraj_google_style"} +{"code": "def hash_(token: str, hash_size: int) -> int:\n\n return murmurhash3_32(token, positive=True) % hash_size", "docstring": "Convert a token to a hash of given size.\n\nArgs:\n token: a word\n hash_size: hash size\n\nReturns:\n int, hashed token", "source": "juraj_google_style"} +{"code": "def load(self, spec):\n\n if spec.template is not None:\n return self.loader.unicode(spec.template, spec.template_encoding)\n\n path = self._find(spec)\n\n return self.loader.read(path, spec.template_encoding)", "docstring": "Find and return the template associated to a TemplateSpec instance.\n\n Returns the template as a unicode string.\n\nArgs:\n spec: a TemplateSpec instance.", "source": "juraj_google_style"} +{"code": "def vgg11_bn(pretrained=False, **kwargs):\n\n if pretrained:\n kwargs['init_weights'] = False\n model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn']))\n return model", "docstring": "VGG 11-layer model (configuration \"A\") with batch normalization\n\nArgs:\n pretrained (bool): If True, returns a model pre-trained on ImageNet", "source": "juraj_google_style"} +{"code": "def get_fail_graph(self, failure_index=None):\n\n phase, _ = self._get_failed_phase(failure_index)\n return phase.get_graph()", "docstring": "Returns a graph showing a solve failure.\n\nArgs:\n failure_index: See `failure_reason`\n\nReturns:\n A pygraph.digraph object.", "source": "juraj_google_style"} +{"code": "def __init__(self, plugin_callback, plugin_dir = 'workers'):\n\n\n # Set the callback, the plugin directory and load the plugins\n self.plugin_callback = plugin_callback\n self.plugin_dir = plugin_dir\n self.load_all_plugins()\n\n # Now setup dynamic monitoring of the plugins directory\n self.watcher = dir_watcher.DirWatcher(self.plugin_path)\n self.watcher.register_callbacks(self.on_created, self.on_modified, self.on_deleted)\n self.watcher.start_monitoring()", "docstring": "Initialize the Plugin Manager for Workbench.\n\nArgs:\n plugin_callback: The callback for plugin. This is called when plugin is added.\n plugin_dir: The dir where plugin resides.", "source": "juraj_google_style"} +{"code": "def list_functions(mod_name):\n\n mod = sys.modules[mod_name]\n return [func.__name__ for func in mod.__dict__.values()\n if is_mod_function(mod, func)]", "docstring": "Lists all functions declared in a module.\n\n http://stackoverflow.com/a/1107150/3004221\n\nArgs:\n mod_name: the module name\n\nReturns:\n A list of functions declared in that module.", "source": "juraj_google_style"} +{"code": "def remove_from_list(self, key: str, value, count: int = 0,\n pipeline: bool = False):\n\n if pipeline:\n if redis.__version__ == '2.10.6':\n self._pipeline.lrem(name=key, value=value, num=count)\n else:\n self._pipeline.lrem(key, count, value)\n else:\n if self._db.exists(key):\n if redis.__version__ == '2.10.6':\n self._db.lrem(name=key, value=value, num=count)\n else:\n self._db.lrem(key, count, value)", "docstring": "Remove specified value(s) from the list stored at key.\n\nArgs:\n key (str): Key where the list is stored.\n value: value to remove\n count (int): Number of entries to remove, default 0 == all\n pipeline(bool): If True, start a transaction block. Default False.", "source": "juraj_google_style"} +{"code": "def _add_data_types_and_routes_to_api(self, namespace, desc):\n\n\n env = self._get_or_create_env(namespace.name)\n\n for item in desc:\n if isinstance(item, AstTypeDef):\n api_type = self._create_type(env, item)\n namespace.add_data_type(api_type)\n self._check_canonical_name_available(item, namespace.name)\n elif isinstance(item, AstStructPatch) or isinstance(item, AstUnionPatch):\n # Handle patches later.\n base_name = self._get_base_name(item.name, namespace.name)\n self._patch_data_by_canonical_name[base_name] = (item, namespace)\n elif isinstance(item, AstRouteDef):\n route = self._create_route(env, item)\n namespace.add_route(route)\n self._check_canonical_name_available(item, namespace.name, allow_duplicate=True)\n elif isinstance(item, AstImport):\n # Handle imports later.\n pass\n elif isinstance(item, AstAlias):\n alias = self._create_alias(env, item)\n namespace.add_alias(alias)\n self._check_canonical_name_available(item, namespace.name)\n elif isinstance(item, AstAnnotationDef):\n annotation = self._create_annotation(env, item)\n namespace.add_annotation(annotation)\n self._check_canonical_name_available(item, namespace.name)\n elif isinstance(item, AstAnnotationTypeDef):\n annotation_type = self._create_annotation_type(env, item)\n namespace.add_annotation_type(annotation_type)\n self._check_canonical_name_available(item, namespace.name)\n else:\n raise AssertionError('Unknown AST node type %r' %\n item.__class__.__name__)", "docstring": "From the raw output of the parser, create forward references for each\n user-defined type (struct, union, route, and alias).\n\nArgs:\n namespace (stone.api.Namespace): Namespace for definitions.\n desc (List[stone.stone.parser._Element]): All AST nodes in a spec\n file in the order they were defined. Should not include a\n namespace declaration.", "source": "juraj_google_style"} +{"code": "def get_classes_in_module(module, superclass=object):\n\n\n ret = []\n for classname in dir(module):\n attr = module.__getattribute__(classname)\n try:\n if issubclass(attr, superclass) and (attr != superclass):\n ret.append(attr)\n except TypeError:\n # \"issubclass() arg 1 must be a class\"\n pass\n except RuntimeError:\n # a99.get_python_logger().exception(\"Failed probing attribute '{}'\".format(classname))\n # raise\n pass\n return ret", "docstring": "Returns a list with all classes in module that descend from parent\n\nArgs:\n module: builtins.module\n superclass: a class\n\n Returns: list", "source": "juraj_google_style"} +{"code": "def lookupSpatialReferenceID(wellKnownText):\n\n payload = {'mode': 'wkt',\n 'terms': wellKnownText}\n\n try:\n r = requests.get('http://prj2epsg.org/search.json', params=payload)\n except requests.exceptions.ConnectionError:\n print(\"SRID Lookup Error: Could not automatically determine spatial \"\n \"reference ID, because there is no internet connection. \"\n \"Please check connection and try again.\")\n exit(1)\n\n if r.status_code == 200:\n json = r.json()\n\n for code in json['codes']:\n return code['code']", "docstring": "This function can be used to look up the EPSG spatial reference system using the web service available at:\n http://prj2epsg.org\n\nArgs:\n wellKnownText (str): The Well Known Text definition of the spatial reference system.\n\nReturns:\n int: Spatial Reference ID", "source": "juraj_google_style"} +{"code": "def iec2bytes(size_spec, only_positive=True):\n\n scale = 1\n try:\n size = int(0 + size_spec) # return numeric values as-is\n except (TypeError, ValueError):\n spec = size_spec.strip().lower()\n\n for exp, iec_unit in enumerate(IEC_UNITS[1:], 1):\n iec_unit = iec_unit.lower()\n if spec.endswith(iec_unit):\n spec = spec[:-len(iec_unit)]\n scale = 2 ** (10 * exp)\n break\n elif spec.endswith(iec_unit[0]):\n spec = spec[:-1]\n scale = 2 ** (10 * exp)\n break\n else:\n if spec.endswith('b'):\n spec = spec[:-1]\n\n try:\n if '.' in spec:\n size = float(spec.strip())\n else:\n size = int(spec.strip(), base=0)\n except (TypeError, ValueError) as cause:\n raise ValueError('Invalid bytes size specification {!r}: {}'.format(size_spec, cause))\n\n if only_positive and size < 0:\n raise ValueError('Invalid negative bytes size specification {!r}'.format(size_spec))\n\n return int(size * scale)", "docstring": "Convert a size specification, optionally containing a scaling\n unit in IEC notation, to a number of bytes.\n\n Parameters:\n size_spec (str): Number, optionally followed by a unit.\n only_positive (bool): Allow only positive values?\n\nReturns:\n Numeric bytes size.\n\nRaises:\n ValueError: Unknown unit specifiers, or bad leading integer.", "source": "juraj_google_style"} +{"code": "def _check_error(self, response, json_response=None):\n\n\n # If status code is 4xx or 5xx, that should be an error\n if response.status_code >= 400:\n json_response = json_response or self._get_json_response(response)\n err_cls = self._check_http_error_code(response.status_code)\n try:\n raise err_cls(\"%s error: %s\" % (response.status_code, json_response[\"error\"][\"error_msg\"]), response.status_code)\n # This is to catch error when we post get oauth data\n except TypeError:\n raise err_cls(\"%s error: %s\" % (response.status_code, json_response[\"error_description\"]), response.status_code)\n\n # Return True if everything is OK\n return True", "docstring": "Check for HTTP error code from the response, raise exception if there's any\n\nArgs:\n response (object): Object returned by requests' `get` and `post`\n methods\n\n json_response (dict): JSON response, if applicable\n\nRaises:\n HTTPError: If the status code of response is either 4xx or 5xx\n\nReturns:\n True if status code is not error code", "source": "juraj_google_style"} +{"code": "def ias60(msg):\n\n d = hex2bin(data(msg))\n\n if d[12] == '0':\n return None\n\n ias = bin2int(d[13:23]) # kts\n return ias", "docstring": "Indicated airspeed\n\nArgs:\n msg (String): 28 bytes hexadecimal message (BDS60) string\n\nReturns:\n int: indicated airspeed in knots", "source": "juraj_google_style"} +{"code": "def find_wells_with_curve(self, mnemonic, alias=None):\n\n return Project([w for w in self if w.get_curve(mnemonic, alias=alias) is not None])", "docstring": "Returns a new Project with only the wells which have the named curve.\n\nArgs:\n menmonic (str): the name of the curve to look for.\n alias (dict): a welly alias dictionary.\n\nReturns:\n project.", "source": "juraj_google_style"} +{"code": "def __init__(self, variant_type='snv'):\n\n super(VcfPlugin, self).__init__()\n\n self.individual_objs = []\n self.case_objs = []\n\n self.variant_type = variant_type\n logger.info(\"Setting variant type to {0}\".format(variant_type))\n\n self.variant_columns = ['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER']\n\n self.head = None\n self.vep_header = None\n self.snpeff_header = None\n\n\n self.filters.can_filter_gene = True\n self.filters.can_filter_frequency = True\n self.filters.can_filter_cadd = True\n self.filters.can_filter_consequence = True\n self.filters.can_filter_impact_severity = True\n self.filters.can_filter_sv = True\n self.filters.can_filter_sv_len = True\n self.filters.can_filter_inheritance = True", "docstring": "Initialize a vcf adapter.\n\n When instansiating all cases are found.\n\nArgs:\n variant_type(str) : 'snv' or 'sv'", "source": "juraj_google_style"} +{"code": "def _GetTypeFromScope(self, package, type_name, scope):\n\n if type_name not in scope:\n components = _PrefixWithDot(package).split('.')\n while components:\n possible_match = '.'.join(components + [type_name])\n if possible_match in scope:\n type_name = possible_match\n break\n else:\n components.pop(-1)\n return scope[type_name]", "docstring": "Finds a given type name in the current scope.\n\nArgs:\n package: The package the proto should be located in.\n type_name: The name of the type to be found in the scope.\n scope: Dict mapping short and full symbols to message and enum types.\n\nReturns:\n The descriptor for the requested type.", "source": "juraj_google_style"} +{"code": "def resume_training(self, train_data, model_path, valid_data=None):\n\n restore_state = self.checkpointer.restore(model_path)\n loss_fn = self._get_loss_fn()\n self.train()\n self._train_model(\n train_data=train_data,\n loss_fn=loss_fn,\n valid_data=valid_data,\n restore_state=restore_state,\n )", "docstring": "This model resume training of a classifier by reloading the appropriate state_dicts for each model\n\nArgs:\n train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of\n X (data) and Y (labels) for the train split\n model_path: the path to the saved checpoint for resuming training\n valid_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of\n X (data) and Y (labels) for the dev split", "source": "juraj_google_style"} +{"code": "def view(self, vleaf, fpath=None, cleanup=True, format=None):\n\n graph = self.create_graphviz_digraph(vleaf, format=format)\n graph.view(fpath, cleanup=cleanup)", "docstring": "View the graph.\n\nArgs:\n vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt.\n fpath (`str`): The file path used to save.\n cleanup (`bool`): Clean up the source file after rendering. Default is True.\n format (str):\n Force overwrite ``format`` (``'pdf', 'png', ...)``) configuration.", "source": "juraj_google_style"} +{"code": "def config_file(self, filename):\n\n if os.path.isfile(filename):\n with open(filename, 'r') as fh:\n self._config_data = json.load(fh)\n else:\n self.tcex.log.error('Could not load configuration file \"{}\".'.format(filename))", "docstring": "Load configuration data from provided file and inject values into sys.argv.\n\nArgs:\n config (str): The configuration file name.", "source": "juraj_google_style"} +{"code": "def clean(deltox=False):\n\n\n basedir = dirname(__file__)\n\n print(cyan('delete temp files and dirs for packaging'))\n local(flo(\n 'rm -rf '\n '{basedir}/.eggs/ '\n '{basedir}/utlz.egg-info/ '\n '{basedir}/dist '\n '{basedir}/README '\n '{basedir}/build/ '\n ))\n\n print(cyan('\\ndelete temp files and dirs for editing'))\n local(flo(\n 'rm -rf '\n '{basedir}/.cache '\n '{basedir}/.ropeproject '\n ))\n\n print(cyan('\\ndelete bytecode compiled versions of the python src'))\n # cf. http://stackoverflow.com/a/30659970\n local(flo('find {basedir}/utlz {basedir}/tests ') +\n '\\( -name \\*pyc -o -name \\*.pyo -o -name __pycache__ '\n '-o -name \\*.so -o -name \\*.o -o -name \\*.c \\) '\n '-prune '\n '-exec rm -rf {} +')\n\n if deltox:\n print(cyan('\\ndelete tox virual environments'))\n local(flo('cd {basedir} && rm -rf .tox/'))", "docstring": "Delete temporary files not under version control.\n\nArgs:\n deltox: If True, delete virtual environments used by tox", "source": "juraj_google_style"} +{"code": "def extract_response(self, extractors):\n\n if not extractors:\n return {}\n\n logger.log_debug(\"start to extract from response object.\")\n extracted_variables_mapping = OrderedDict()\n extract_binds_order_dict = utils.ensure_mapping_format(extractors)\n\n for key, field in extract_binds_order_dict.items():\n extracted_variables_mapping[key] = self.extract_field(field)\n\n return extracted_variables_mapping", "docstring": "extract value from requests.Response and store in OrderedDict.\n\nArgs:\n extractors (list):\n\n [\n {\"resp_status_code\": \"status_code\"},\n {\"resp_headers_content_type\": \"headers.content-type\"},\n {\"resp_content\": \"content\"},\n {\"resp_content_person_first_name\": \"content.person.name.first_name\"}\n ]\n\nReturns:\n OrderDict: variable binds ordered dict", "source": "juraj_google_style"} +{"code": "def check_error_response(self, body, status):\n\n status_code = int(status.split(' ', 1)[0])\n if status_code >= 300:\n raise errors.BackendError(body, status)", "docstring": "Raise an exception if the response from the backend was an error.\n\nArgs:\n body: A string containing the backend response body.\n status: A string containing the backend response status.\n\nRaises:\n BackendError if the response is an error.", "source": "juraj_google_style"} +{"code": "def run(self, data):\n\n result_type = namedtuple('Result', 'code messages')\n\n if self.passes is True:\n result = result_type(Checker.Code.PASSED, '')\n elif self.passes is False:\n if self.allow_failure:\n result = result_type(Checker.Code.IGNORED, '')\n else:\n result = result_type(Checker.Code.FAILED, '')\n else:\n try:\n result = self.check(data, **self.arguments)\n messages = ''\n if isinstance(result, tuple):\n result, messages = result\n\n if result not in Checker.Code:\n result = Checker.Code.PASSED if bool(result) else Checker.Code.FAILED\n\n if result == Checker.Code.FAILED and self.allow_failure:\n result = Checker.Code.IGNORED\n\n result = result_type(result, messages)\n except NotImplementedError:\n result = result_type(Checker.Code.NOT_IMPLEMENTED, '')\n self.result = result", "docstring": "Run the check method and format the result for analysis.\n\nArgs:\n data (DSM/DMM/MDM): DSM/DMM/MDM instance to check.\n\nReturns:\n tuple (int, str): status constant from Checker class and messages.", "source": "juraj_google_style"} +{"code": "def _ip_int_from_string(self, ip_str):\n\n octets = ip_str.split('.')\n if len(octets) != 4:\n raise AddressValueError(ip_str)\n\n packed_ip = 0\n for oc in octets:\n try:\n packed_ip = (packed_ip << 8) | self._parse_octet(oc)\n except ValueError:\n raise AddressValueError(ip_str)\n return packed_ip", "docstring": "Turn the given IP string into an integer for comparison.\n\nArgs:\n ip_str: A string, the IP ip_str.\n\nReturns:\n The IP ip_str as an integer.\n\nRaises:\n AddressValueError: if ip_str isn't a valid IPv4 Address.", "source": "juraj_google_style"} +{"code": "def delete_tag(self, tag_name, **kwargs):\n\n resp = self._delete(self._u(self._TAG_ENDPOINT_SUFFIX, tag_name),\n **kwargs)\n resp.raise_for_status()\n # successful delete returns 204, which has no associated json\n return resp", "docstring": "delete a tag by name\n\nArgs:\n tag_name (string): name of tag to delete", "source": "juraj_google_style"} +{"code": "def generateCoincMatrix(nCoinc=10, length=500, activity=50):\n\n\n coincMatrix0 = SM32(int(nCoinc), int(length))\n theOnes = numpy.array([1.0] * activity, dtype=numpy.float32)\n for rowIdx in xrange(nCoinc):\n coinc = numpy.array(random.sample(xrange(length),\n activity), dtype=numpy.uint32)\n coinc.sort()\n coincMatrix0.setRowFromSparse(rowIdx, coinc, theOnes)\n\n # This is the right code to use, it's faster, but it derails the unit\n # testing of the pooling for now.\n coincMatrix = SM32(int(nCoinc), int(length))\n coincMatrix.initializeWithFixedNNZR(activity)\n\n return coincMatrix0", "docstring": "Generate a coincidence matrix. This is used to generate random inputs to the\n temporal learner and to compare the predicted output against.\n\n It generates a matrix of nCoinc rows, each row has length 'length' and has\n a total of 'activity' bits on.\n\n Parameters:\n -----------------------------------------------\n nCoinc: the number of rows to generate\n length: the length of each row\n activity: the number of ones to put into each row.", "source": "juraj_google_style"} +{"code": "def add_comment(self, app_id, record_id, field_id, message):\n\n\n self._swimlane.request(\n 'post',\n 'app/{0}/record/{1}/{2}/comment'.format(\n app_id,\n record_id,\n field_id\n ),\n json={\n 'message': message,\n 'createdDate': pendulum.now().to_rfc3339_string()\n }\n )", "docstring": "Directly add a comment to a record without retrieving the app or record first\n\n Warnings:\n Does not perform any app, record, or field ID validation\n\nArgs:\n app_id (str): Full App ID string\n record_id (str): Full parent Record ID string\n field_id (str): Full field ID to target reference field on parent Record string\n message (str): New comment message body", "source": "juraj_google_style"} +{"code": "def get_projection_on_elements(self, structure):\n\n dico = {}\n for spin in self.data.keys():\n dico[spin] = [[defaultdict(float)\n for i in range(self.nkpoints)]\n for j in range(self.nbands)]\n\n for iat in range(self.nions):\n name = structure.species[iat].symbol\n for spin, d in self.data.items():\n for k, b in itertools.product(range(self.nkpoints),\n range(self.nbands)):\n dico[spin][b][k][name] = np.sum(d[k, b, iat, :])\n\n return dico", "docstring": "Method returning a dictionary of projections on elements.\n\nArgs:\n structure (Structure): Input structure.\n\nReturns:\n a dictionary in the {Spin.up:[k index][b index][{Element:values}]]", "source": "juraj_google_style"} +{"code": "def cols_to_dt(df, col_list,set_format = None,infer_format = True,dest = False):\n\n if not dest:\n return _pd.DataFrame({col_name:col_to_dt(df,col_name,set_format,infer_format) for col_name in col_list})\n for col_name in col_list:\n col_to_dt(df,col_name,set_format,infer_format,dest)", "docstring": "Coerces a list of columns to datetime\n Parameters:\n df - DataFrame\n DataFrame to operate on\n col_list - list of strings\n names of columns to coerce\n dest - bool, default False\n Whether to apply the result to the DataFrame or return it.\n True is apply, False is return.", "source": "juraj_google_style"} +{"code": "def _GetRecordValue(self, record, value_entry):\n\n column_type = record.get_column_type(value_entry)\n long_value = None\n\n if record.is_long_value(value_entry):\n long_value = record.get_value_data_as_long_value(value_entry)\n\n if record.is_multi_value(value_entry):\n # TODO: implement\n raise ValueError('Multi value support not implemented yet.')\n\n if column_type == pyesedb.column_types.NULL:\n return None\n\n if column_type == pyesedb.column_types.BOOLEAN:\n # TODO: implement\n raise ValueError('Boolean value support not implemented yet.')\n\n if column_type in self.INTEGER_COLUMN_TYPES:\n if long_value:\n raise ValueError('Long integer value not supported.')\n return record.get_value_data_as_integer(value_entry)\n\n if column_type in self.FLOATING_POINT_COLUMN_TYPES:\n if long_value:\n raise ValueError('Long floating point value not supported.')\n return record.get_value_data_as_floating_point(value_entry)\n\n if column_type in self.STRING_COLUMN_TYPES:\n if long_value:\n return long_value.get_data_as_string()\n return record.get_value_data_as_string(value_entry)\n\n if column_type == pyesedb.column_types.GUID:\n # TODO: implement\n raise ValueError('GUID value support not implemented yet.')\n\n if long_value:\n return long_value.get_data()\n return record.get_value_data(value_entry)", "docstring": "Retrieves a specific value from the record.\n\nArgs:\n record (pyesedb.record): ESE record.\n value_entry (int): value entry.\n\nReturns:\n object: value.\n\nRaises:\n ValueError: if the value is not supported.", "source": "juraj_google_style"} +{"code": "def delete_note(self, note_id):\n\n # notes have to be trashed before deletion\n note, status = self.trash_note(note_id)\n if (status == -1):\n return note, status\n\n params = '/i/%s' % (str(note_id))\n request = Request(url=DATA_URL+params, method='DELETE')\n request.add_header(self.header, self.get_token())\n try:\n response = urllib2.urlopen(request)\n except IOError as e:\n return e, -1\n except HTTPError as e:\n if e.code == 401:\n raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.')\n else:\n return e, -1\n return {}, 0", "docstring": "Method to permanently delete a note\n\nArgs:\n - note_id (string): key of the note to trash\n\nReturns:\n A tuple `(note, status)`\n\n - note (dict): an empty dict or an error message\n - status (int): 0 on success and -1 otherwise", "source": "juraj_google_style"} +{"code": "def db_dp004(self, value=None):\n\n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError('value {} need to be of type float '\n 'for field `db_dp004`'.format(value))\n\n self._db_dp004 = value", "docstring": "Corresponds to IDD Field `db_dp004`\n mean coincident dry-bulb temperature to\n Dew-point temperature corresponding to 0.4% annual cumulative frequency of occurrence\n\nArgs:\n value (float): value for IDD Field `db_dp004`\n Unit: C\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def flag_all(self, thresh_dict=None, include=None, exclude=None):\n\n if thresh_dict is None:\n thresh_dict = {}\n row_idx = set()\n col_idx = set()\n include = self.results if include is None else include\n include = list(\n set(include) - set(exclude)) if exclude is not None else include\n for diagnostic in include:\n if diagnostic in thresh_dict:\n flagged = self.flag(diagnostic, thresh_dict[diagnostic])\n else:\n flagged = self.flag(diagnostic)\n\n if diagnostic == 'RowMahalanobisDistances':\n row_idx = row_idx.union(flagged)\n else:\n col_idx = col_idx.union(flagged)\n\n return sorted(list(row_idx)), sorted(list(col_idx))", "docstring": "Returns indices of (rows, columns) that satisfy flag() on any\n diagnostic. Uses user-provided thresholds in thresh_dict/\n\nArgs:\n thresh_dict (dict): dictionary of diagnostic->threshold functions\n include (list): optional sublist of diagnostics to flag\n exclude (list): optional sublist of diagnostics to not flag", "source": "juraj_google_style"} +{"code": "def where(self, cond, other, **kwargs):\n\n\n assert isinstance(\n cond, type(self)\n ), \"Must have the same DataManager subclass to perform this operation\"\n if isinstance(other, type(self)):\n # Note: Currently we are doing this with two maps across the entire\n # data. This can be done with a single map, but it will take a\n # modification in the `BlockPartition` class.\n # If this were in one pass it would be ~2x faster.\n # TODO (devin-petersohn) rewrite this to take one pass.\n def where_builder_first_pass(cond, other, **kwargs):\n return cond.where(cond, other, **kwargs)\n\n def where_builder_second_pass(df, new_other, **kwargs):\n return df.where(new_other.eq(True), new_other, **kwargs)\n\n first_pass = cond._inter_manager_operations(\n other, \"left\", where_builder_first_pass\n )\n final_pass = self._inter_manager_operations(\n first_pass, \"left\", where_builder_second_pass\n )\n return self.__constructor__(final_pass.data, self.index, self.columns)\n else:\n axis = kwargs.get(\"axis\", 0)\n # Rather than serializing and passing in the index/columns, we will\n # just change this index to match the internal index.\n if isinstance(other, pandas.Series):\n other.index = pandas.RangeIndex(len(other.index))\n\n def where_builder_series(df, cond):\n if axis == 0:\n df.index = pandas.RangeIndex(len(df.index))\n cond.index = pandas.RangeIndex(len(cond.index))\n else:\n df.columns = pandas.RangeIndex(len(df.columns))\n cond.columns = pandas.RangeIndex(len(cond.columns))\n return df.where(cond, other, **kwargs)\n\n reindexed_self, reindexed_cond, a = self.copartition(\n axis, cond, \"left\", False\n )\n # Unwrap from list given by `copartition`\n reindexed_cond = reindexed_cond[0]\n new_data = reindexed_self.inter_data_operation(\n axis, lambda l, r: where_builder_series(l, r), reindexed_cond\n )\n return self.__constructor__(new_data, self.index, self.columns)", "docstring": "Gets values from this manager where cond is true else from other.\n\nArgs:\n cond: Condition on which to evaluate values.\n\nReturns:\n New DataManager with updated data and index.", "source": "juraj_google_style"} +{"code": "def __init__(self, config_files):\n\n for config_file, is_production in config_files:\n if os.path.isfile(config_file):\n self.config_file = config_file\n self.is_production = is_production\n self.config = configparser.SafeConfigParser()\n self.config.read([self.config_file], encoding='utf-8')\n return\n\n raise IOError(\"No configuration file found.\")", "docstring": "Creates a new config object.\n\n Parameters:\n config_files: Dictionary with file_name: is_production setting", "source": "juraj_google_style"} +{"code": "def _GetMemberDataTypeMaps(self, data_type_definition, data_type_map_cache):\n\n if not data_type_definition:\n raise errors.FormatError('Missing data type definition')\n\n members = getattr(data_type_definition, 'members', None)\n if not members:\n raise errors.FormatError('Invalid data type definition missing members')\n\n data_type_maps = []\n\n members_data_size = 0\n for member_definition in members:\n if isinstance(member_definition, data_types.MemberDataTypeDefinition):\n member_definition = member_definition.member_data_type_definition\n\n if (data_type_definition.byte_order != definitions.BYTE_ORDER_NATIVE and\n member_definition.byte_order == definitions.BYTE_ORDER_NATIVE):\n # Make a copy of the data type definition where byte-order can be\n # safely changed.\n member_definition = copy.copy(member_definition)\n member_definition.name = '_{0:s}_{1:s}'.format(\n data_type_definition.name, member_definition.name)\n member_definition.byte_order = data_type_definition.byte_order\n\n if member_definition.name not in data_type_map_cache:\n data_type_map = DataTypeMapFactory.CreateDataTypeMapByType(\n member_definition)\n data_type_map_cache[member_definition.name] = data_type_map\n\n data_type_map = data_type_map_cache[member_definition.name]\n if members_data_size is not None:\n if not isinstance(member_definition, data_types.PaddingDefinition):\n byte_size = member_definition.GetByteSize()\n else:\n _, byte_size = divmod(\n members_data_size, member_definition.alignment_size)\n if byte_size > 0:\n byte_size = member_definition.alignment_size - byte_size\n\n data_type_map.byte_size = byte_size\n\n if byte_size is None:\n members_data_size = None\n else:\n members_data_size += byte_size\n\n data_type_maps.append(data_type_map)\n\n return data_type_maps", "docstring": "Retrieves the member data type maps.\n\nArgs:\n data_type_definition (DataTypeDefinition): data type definition.\n data_type_map_cache (dict[str, DataTypeMap]): cached data type maps.\n\nReturns:\n list[DataTypeMap]: member data type maps.\n\nRaises:\n FormatError: if the data type maps cannot be determined from the data\n type definition.", "source": "juraj_google_style"} +{"code": "def _merge(d, u):\n\n for k, v in u.items():\n # if we have a mapping, recursively merge the values\n if isinstance(v, collections.Mapping):\n d[k] = _merge(d.get(k, {}), v)\n\n # if d (the dict to merge into) is a dict, just add the\n # value to the dict.\n elif isinstance(d, collections.MutableMapping):\n d[k] = v\n\n # otherwise if d (the dict to merge into) is not a dict (e.g. when\n # recursing into it, `d.get(k, {})` may not be a dict), then do what\n # `update` does and prefer the new value.\n #\n # this means that something like `{'foo': 1}` when updated with\n # `{'foo': {'bar': 1}}` would have the original value (`1`) overwritten\n # and would become: `{'foo': {'bar': 1}}`\n else:\n d = {k: v}\n\n return d", "docstring": "Merge two dictionaries (or DotDicts) together.\n\nArgs:\n d: The dictionary/DotDict to merge into.\n u: The source of the data to merge.", "source": "juraj_google_style"} +{"code": "def _backspaced_single_line_animation(animation_, *args, **kwargs):\n\n animation_gen = animation_(*args, **kwargs)\n yield next(animation_gen) # no backing up on the first frame\n yield from util.concatechain(\n util.BACKSPACE_GEN(kwargs['width']), animation_gen)", "docstring": "Turn an animation into an automatically backspaced animation.\n\nArgs:\n animation: A function that returns a generator that yields\n strings for animation frames.\n args: Arguments for the animation function.\n kwargs: Keyword arguments for the animation function.\n\nReturns:\n the animation generator, with backspaces applied to each but the first\n frame.", "source": "juraj_google_style"} +{"code": "def __init__(self, band_type=None, rate=None, burst_size=None):\n\n super().__init__()\n self.band_type = band_type\n self.rate = rate\n self.burst_size = burst_size\n self.update_length()", "docstring": "Create a MeterBandHeader with the optional parameters below.\n\nArgs:\n band_type (MeterBandType): One of OFPMBT_*.\n rate (int): Rate for this band.\n burst_size (int): Size of bursts.", "source": "juraj_google_style"} +{"code": "def stack_and_pad_tensors(batch, padding_index=DEFAULT_PADDING_INDEX, dim=0):\n\n lengths = [tensor.shape[0] for tensor in batch]\n max_len = max(lengths)\n padded = [pad_tensor(tensor, max_len, padding_index) for tensor in batch]\n lengths = torch.tensor(lengths)\n padded = torch.stack(padded, dim=dim).contiguous()\n for _ in range(dim):\n lengths = lengths.unsqueeze(0)\n return padded, lengths", "docstring": "Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``.\n\nArgs:\n batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad.\n padding_index (int, optional): Index to pad tensors with.\n dim (int, optional): Dimension on to which to concatenate the batch of tensors.\n\n Returns\n torch.Tensor, torch.Tensor: Padded tensors and original lengths of tensors.", "source": "juraj_google_style"} +{"code": "def write_wgetrc(_path):\n\n http_proxy = str(CFG[\"gentoo\"][\"http_proxy\"])\n ftp_proxy = str(CFG[\"gentoo\"][\"ftp_proxy\"])\n\n path.mkfile_uchroot(\"/etc/wgetrc\")\n with open(_path, 'w') as wgetrc:\n if http_proxy is not None:\n http_s = \"http_proxy = {0}\".format(http_proxy)\n https_s = \"https_proxy = {0}\".format(http_proxy)\n wgetrc.write(\"use_proxy = on\\n\")\n wgetrc.write(http_s + \"\\n\")\n wgetrc.write(https_s + \"\\n\")\n\n if ftp_proxy is not None:\n fp_s = \"ftp_proxy={0}\".format(ftp_proxy)\n wgetrc.write(fp_s + \"\\n\")", "docstring": "Write a valid gentoo wgetrc file to :path:.\n\nArgs:\n path - The output path of the wgetrc", "source": "juraj_google_style"} +{"code": "def keys(self, full_grid=False):\n\n keys = super(GridSpace, self).keys()\n if self.ndims == 1 or not full_grid:\n return keys\n dim1_keys = sorted(set(k[0] for k in keys))\n dim2_keys = sorted(set(k[1] for k in keys))\n return [(d1, d2) for d1 in dim1_keys for d2 in dim2_keys]", "docstring": "Returns the keys of the GridSpace\n\nArgs:\n full_grid (bool, optional): Return full cross-product of keys\n\nReturns:\n List of keys", "source": "juraj_google_style"} +{"code": "def prange(N=1, dim=1):\n\n A = {}\n r = numpy.arange(N, dtype=int)\n key = numpy.zeros(dim, dtype=int)\n for i in range(N):\n key[-1] = i\n A[tuple(key)] = 1*(r==i)\n\n return Poly(A, dim, (N,), int)", "docstring": "Constructor to create a range of polynomials where the exponent vary.\n\nArgs:\n N (int):\n Number of polynomials in the array.\n dim (int):\n The dimension the polynomial should span.\n\nReturns:\n (Poly):\n A polynomial array of length N containing simple polynomials with\n increasing exponent.\n\nExample:\n >>> print(prange(4))\n [1, q0, q0^2, q0^3]\n >>> print(prange(4, dim=3))\n [1, q2, q2^2, q2^3]", "source": "juraj_google_style"} +{"code": "def __init__(self, context):\n\n self._logdir = context.logdir\n self._db_uri = context.db_uri\n self._window_title = context.window_title\n self._multiplexer = context.multiplexer\n self._db_connection_provider = context.db_connection_provider\n self._assets_zip_provider = context.assets_zip_provider", "docstring": "Instantiates CorePlugin.\n\nArgs:\n context: A base_plugin.TBContext instance.", "source": "juraj_google_style"} +{"code": "def get(self, id_or_url, default=None):\n\n if '/' in id_or_url:\n id = urls.SheetUrl.from_string(id_or_url).id\n else:\n id = id_or_url\n try:\n return self[id]\n except KeyError:\n return default", "docstring": "Fetch and return the spreadsheet with the given id or url.\n\nArgs:\n id_or_url (str): unique alphanumeric id or URL of the spreadsheet\n\nReturns:\n New SpreadSheet instance or given default if none is found\n\nRaises:\n ValueError: if an URL is given from which no id could be extracted", "source": "juraj_google_style"} +{"code": "def set_session(self, headers=None):\n\n if headers is None:\n headers = {\n 'User-Agent':\n ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)'\n ' AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/48.0.2564.116 Safari/537.36')\n }\n elif not isinstance(headers, dict):\n raise TypeError('\"headers\" must be a dict object')\n\n self.session = Session(self.proxy_pool)\n self.session.headers.update(headers)", "docstring": "Init session with default or custom headers\n\nArgs:\n headers: A dict of headers (default None, thus using the default\n header to init the session)", "source": "juraj_google_style"} +{"code": "def getWhoisInfo(domain):\n\n new = []\n\n # Grabbing the aliases\n try:\n emails = {}\n emails[\"type\"] = \"i3visio.alias\"\n emails[\"value\"] = str(domain.split(\".\")[0])\n emails[\"attributes\"] = []\n new.append(emails)\n except:\n pass\n\n info = whois.whois(domain)\n\n if info.status == None:\n raise Exception(\"UnknownDomainError: \" + domain + \" could not be resolved.\")\n\n # Grabbing the emails\n try:\n emails = {}\n emails[\"type\"] = \"i3visio.email\"\n if type(info.emails) is not list:\n aux = [info.emails]\n emails[\"value\"] = json.dumps(aux)\n else:\n emails[\"value\"] = json.dumps(info.emails)\n emails[\"attributes\"] = []\n new.append(emails)\n except:\n pass\n\n # Grabbing the country\n try:\n tmp = {}\n tmp[\"type\"] = \"i3visio.location.country\"\n tmp[\"value\"] = str(info.country)\n tmp[\"attributes\"] = []\n new.append(tmp)\n except:\n pass\n\n # Grabbing the regitrar\n try:\n tmp = {}\n tmp[\"type\"] = \"i3visio.registrar\"\n tmp[\"value\"] = str(info.registrar)\n tmp[\"attributes\"] = []\n new.append(tmp)\n except:\n pass\n\n # Grabbing the regitrar\n try:\n tmp = {}\n tmp[\"type\"] = \"i3visio.fullname\"\n try:\n tmp[\"value\"] = str(info.name)\n except:\n tmp[\"value\"] = info.name\n tmp[\"attributes\"] = []\n new.append(tmp)\n except:\n pass\n\n return new", "docstring": "Method that trie to recover the whois info from a domain.\n\nArgs:\n -----\n domain: The domain to verify.\n\nReturns:\n --------\n dict: A dictionary containing the result as an i3visio entity with its\n `value`, `type` and `attributes`.", "source": "juraj_google_style"} +{"code": "def transfer_project(self, to_project_id, **kwargs):\n\n path = '/groups/%s/projects/%s' % (self.id, to_project_id)\n self.manager.gitlab.http_post(path, **kwargs)", "docstring": "Transfer a project to this group.\n\nArgs:\n to_project_id (int): ID of the project to transfer\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabTransferProjectError: If the project could not be transfered", "source": "juraj_google_style"} +{"code": "def delete_image(self, name: str) -> None:\n\n logger.debug(\"deleting Docker image: %s\", name)\n path = \"docker/images/{}\".format(name)\n response = self.__api.delete(path)\n if response.status_code != 204:\n try:\n self.__api.handle_erroneous_response(response)\n except Exception:\n logger.exception(\"failed to delete Docker image: %s\", name)\n raise\n else:\n logger.info(\"deleted Docker image: %s\", name)", "docstring": "Deletes a Docker image with a given name.\n\n Parameters:\n name: the name of the Docker image.", "source": "juraj_google_style"} +{"code": "def statsDF(token='', version=''):\n\n df = pd.DataFrame(stats(token, version))\n _toDatetime(df)\n return df", "docstring": "https://iexcloud.io/docs/api/#stats-intraday\n\nArgs:\n token (string); Access token\n version (string); API version\n\nReturns:\n DataFrame: result", "source": "juraj_google_style"} +{"code": "def parsemeta(metadataloc):\n\n\n # filename or directory? if several fit, use first one and warn\n if os.path.isdir(metadataloc):\n metalist = glob.glob(os.path.join(metadataloc, METAPATTERN))\n if not metalist:\n raise MTLParseError(\n \"No files matching metadata file pattern in directory %s.\"\n % metadataloc)\n elif len(metalist) > 0:\n metadatafn = metalist[0]\n filehandle = open(metadatafn, 'r')\n if len(metalist) > 1:\n logging.warning(\n \"More than one file in directory match metadata \"\n + \"file pattern. Using %s.\" % metadatafn)\n elif os.path.isfile(metadataloc):\n metadatafn = metadataloc\n filehandle = open(metadatafn, 'r')\n logging.info(\"Using file %s.\" % metadatafn)\n elif 'L1_METADATA_FILE' in metadataloc:\n filehandle = StringIO(metadataloc)\n else:\n raise MTLParseError(\n \"File location %s is unavailable \" % metadataloc\n + \"or doesn't contain a suitable metadata file.\")\n\n # Reading file line by line and inserting data into metadata dictionary\n status = 0\n metadata = {}\n grouppath = []\n dictpath = [metadata]\n\n for line in filehandle:\n if status == 4:\n # we reached the end in the previous iteration,\n # but are still reading lines\n logging.warning(\n \"Metadata file %s appears to \" % metadatafn\n + \"have extra lines after the end of the metadata. \"\n + \"This is probably, but not necessarily, harmless.\")\n status = _checkstatus(status, line)\n grouppath, dictpath = _transstat(status, grouppath, dictpath, line)\n\n return metadata", "docstring": "Parses the metadata from a Landsat image bundle.\n\nArgs:\n metadataloc: a filename or a directory.\n\n Returns metadata dictionary", "source": "juraj_google_style"} +{"code": "def create_profile(profile_name):\n\n try:\n profile = Profile(profile_name=profile_name)\n profile.full_clean()\n profile.save()\n except ValidationError as err:\n raise ValCannotCreateError(err.message_dict)", "docstring": "Used to create Profile objects in the database\n\n A profile needs to exists before an EncodedVideo object can be created.\n\nArgs:\n profile_name (str): ID of the profile\n\nRaises:\n ValCannotCreateError: Raised if the profile name is invalid or exists", "source": "juraj_google_style"} +{"code": "def info(self, message, domain=None):\n\n if domain is None:\n domain = self.extension_name\n info(message, domain)", "docstring": "Shortcut function for `utils.loggable.info`\n\nArgs:\n message: see `utils.loggable.info`\n domain: see `utils.loggable.info`", "source": "juraj_google_style"} +{"code": "def update_config_pwd(msg, cfg):\n\n msg_type = msg.__class__.__name__.lower()\n key_fmt = msg.profile + \"_\" + msg_type\n if isinstance(msg._auth, (MutableSequence, tuple)):\n cfg.pwd[key_fmt] = \" :: \".join(msg._auth)\n else:\n cfg.pwd[key_fmt] = msg._auth", "docstring": "Updates the profile's auth entry with values set by the user.\n This will overwrite existing values.\n\nArgs:\n :msg: (Message class) an instance of a message class.\n :cfg: (jsonconfig.Config) config instance.", "source": "juraj_google_style"} +{"code": "def _HasDuplicateRegistryKeyPaths(\n self, filename, artifact_definition, source):\n\n result = False\n intersection = self._artifact_registry_key_paths.intersection(\n set(source.keys))\n if intersection:\n duplicate_key_paths = '\\n'.join(intersection)\n logging.warning((\n 'Artifact definition: {0:s} in file: {1:s} has duplicate '\n 'Registry key paths:\\n{2:s}').format(\n artifact_definition.name, filename, duplicate_key_paths))\n result = True\n\n self._artifact_registry_key_paths.update(source.keys)\n return result", "docstring": "Checks if Registry key paths are not already defined by other artifacts.\n\n Note that at the moment this function will only find exact duplicate\n Registry key paths.\n\nArgs:\n filename (str): name of the artifacts definition file.\n artifact_definition (ArtifactDefinition): artifact definition.\n source (SourceType): source definition.\n\nReturns:\n bool: True if the Registry key paths defined by the source type\n are used in other artifacts.", "source": "juraj_google_style"} +{"code": "def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n\n # Convert the value to binary and pad it as needed.\n binary = \"{0:b}\".format(abs(self.value))\n binary = (\"0\" * (64 - (len(binary) % 64))) + binary\n\n # If the value is negative, convert via two's complement.\n if self.value < 0:\n binary = binary.replace('1', 'i')\n binary = binary.replace('0', '1')\n binary = binary.replace('i', '0')\n\n pivot = binary.rfind('0')\n binary = binary[0:pivot] + '1' + ('0' * len(binary[pivot + 1:]))\n\n # Convert each byte to hex and build the hex string for the value.\n hexadecimal = b''\n for i in range(0, len(binary), 8):\n byte = binary[i:i + 8]\n byte = int(byte, 2)\n hexadecimal += struct.pack('!B', byte)\n\n self.length = len(hexadecimal)\n super(BigInteger, self).write(ostream, kmip_version=kmip_version)\n ostream.write(hexadecimal)", "docstring": "Write the encoding of the BigInteger to the output stream.\n\nArgs:\n ostream (Stream): A buffer to contain the encoded bytes of a\n BigInteger object. Usually a BytearrayStream object.\n Required.\n kmip_version (KMIPVersion): An enumeration defining the KMIP\n version with which the object will be encoded. Optional,\n defaults to KMIP 1.0.", "source": "juraj_google_style"} +{"code": "def _enum_from_op_string(op_string):\n\n try:\n return _COMPARISON_OPERATORS[op_string]\n except KeyError:\n choices = \", \".join(sorted(_COMPARISON_OPERATORS.keys()))\n msg = _BAD_OP_STRING.format(op_string, choices)\n raise ValueError(msg)", "docstring": "Convert a string representation of a binary operator to an enum.\n\n These enums come from the protobuf message definition\n ``StructuredQuery.FieldFilter.Operator``.\n\nArgs:\n op_string (str): A comparison operation in the form of a string.\n Acceptable values are ``<``, ``<=``, ``==``, ``>=``\n and ``>``.\n\nReturns:\n int: The enum corresponding to ``op_string``.\n\nRaises:\n ValueError: If ``op_string`` is not a valid operator.", "source": "juraj_google_style"} +{"code": "def __init__(self, mutation_list):\n\n self.mutation_list = [(i[0], int(i[1]), self._standard_resname(i[2])) for i in mutation_list]\n self.chains_and_residues = [(i[0], int(i[1])) for i in mutation_list]", "docstring": "Initialize the parameters which indicate what mutations will occur\n\nArgs:\n chain:\n residue_number:\n mutate_to:", "source": "juraj_google_style"} +{"code": "def read_to_offset(self, offset):\n\n assert offset >= self._offset\n result = self._buffer[self._offset: offset]\n self._offset += len(result)\n return result", "docstring": "Returns bytes from self._buffer and update related offsets.\n\nArgs:\n offset: read from current offset to this offset, exclusive.\n\nReturns:\n Requested bytes from buffer.", "source": "juraj_google_style"} +{"code": "def compute_strongly_connected_components(function):\n\n visited = {n:False for n in function.nodes}\n assigned = {n:False for n in function.nodes}\n components = []\n l = []\n\n def visit(node):\n if not visited[node]:\n visited[node] = True\n for son in node.sons:\n visit(son)\n l.append(node)\n\n for n in function.nodes:\n visit(n)\n\n def assign(node, root):\n if not assigned[node]:\n assigned[node] = True\n root.append(node)\n for father in node.fathers:\n assign(father, root)\n\n for n in l:\n component = []\n assign(n, component)\n if component:\n components.append(component)\n\n return components", "docstring": "Compute strongly connected components\n Based on Kosaraju algo\n Implem follows wikipedia algo: https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm#The_algorithm\n\nArgs:\n function (core.declarations.function.Function)\n\nReturns:\n list(list(nodes))", "source": "juraj_google_style"} +{"code": "def weighted_choice(item_probabilities):\n\n probability_sum = sum(x[1] for x in item_probabilities)\n assert probability_sum > 0\n random_value = random.random() * probability_sum\n summed_probability = 0\n for item, value in item_probabilities:\n summed_probability += value\n if summed_probability > random_value:\n return item", "docstring": "Randomly choses an item according to defined weights\n\nArgs:\n item_probabilities: list of (item, probability)-tuples\n\nReturns:\n random item according to the given weights", "source": "juraj_google_style"} +{"code": "def eld_complete(U,p_min,p_max,d,brk):\n\n\n model = Model(\"Economic load dispatching\")\n\n p,F = {},{}\n for u in U:\n p[u] = model.addVar(lb=p_min[u], ub=p_max[u], name=\"p(%s)\"%u) # capacity\n F[u] = model.addVar(lb=0,name=\"fuel(%s)\"%u)\n\n # set fuel costs based on piecewise linear approximation\n for u in U:\n abrk = [X for (X,Y) in brk[u]]\n bbrk = [Y for (X,Y) in brk[u]]\n\n # convex combination part:\n K = len(brk[u])-1\n z = {}\n for k in range(K+1):\n z[k] = model.addVar(ub=1) # do not name variables for avoiding clash\n\n model.addCons(p[u] == quicksum(abrk[k]*z[k] for k in range(K+1)))\n model.addCons(F[u] == quicksum(bbrk[k]*z[k] for k in range(K+1)))\n model.addCons(quicksum(z[k] for k in range(K+1)) == 1)\n model.addConsSOS2([z[k] for k in range(K+1)])\n\n # demand satisfaction\n model.addCons(quicksum(p[u] for u in U) == d, \"demand\")\n\n # objective\n model.setObjective(quicksum(F[u] for u in U), \"minimize\")\n\n model.data = p\n return model", "docstring": "eld -- economic load dispatching in electricity generation\n Parameters:\n - U: set of generators (units)\n - p_min[u]: minimum operating power for unit u\n - p_max[u]: maximum operating power for unit u\n - d: demand\n - brk[k]: (x,y) coordinates of breakpoint k, k=0,...,K\n Returns a model, ready to be solved.", "source": "juraj_google_style"} +{"code": "def FindModuleIdDefiningFlag(self, flagname, default=None):\n\n registered_flag = self.FlagDict().get(flagname)\n if registered_flag is None:\n return default\n for module_id, flags in six.iteritems(self.FlagsByModuleIdDict()):\n for flag in flags:\n # It must compare the flag with the one in FlagDict. This is because a\n # flag might be overridden only for its long name (or short name),\n # and only its short name (or long name) is considered registered.\n if (flag.name == registered_flag.name and\n flag.short_name == registered_flag.short_name):\n return module_id\n return default", "docstring": "Return the ID of the module defining this flag, or default.\n\nArgs:\n flagname: Name of the flag to lookup.\n default: Value to return if flagname is not defined. Defaults\n to None.\n\nReturns:\n The ID of the module which registered the flag with this name.\n If no such module exists (i.e. no flag with this name exists),\n we return default.", "source": "juraj_google_style"} +{"code": "def bootstrap(score_objs, n_boot=1000):\n\n all_samples = np.random.choice(score_objs, size=(n_boot, len(score_objs)), replace=True)\n return all_samples.sum(axis=1)", "docstring": "Given a set of DistributedROC or DistributedReliability objects, this function performs a\n bootstrap resampling of the objects and returns n_boot aggregations of them.\n\nArgs:\n score_objs: A list of DistributedROC or DistributedReliability objects. Objects must have an __add__ method\n n_boot (int): Number of bootstrap samples\n\nReturns:\n An array of DistributedROC or DistributedReliability", "source": "juraj_google_style"} +{"code": "def RemoveClientLabels(self, client_id, labels):\n\n for label in labels:\n keyword = self._NormalizeKeyword(label)\n # This might actually delete a keyword with the same name as the label (if\n # there is one).\n data_store.REL_DB.RemoveClientKeyword(client_id, keyword)\n data_store.REL_DB.RemoveClientKeyword(client_id, \"label:%s\" % keyword)", "docstring": "Removes all labels for a given client.\n\nArgs:\n client_id: The client_id.\n labels: A list of labels to remove.", "source": "juraj_google_style"} +{"code": "def predict_on_batch(self, data: Union[list, tuple],\n return_indexes: bool = False) -> List[List[str]]:\n\n X = self._transform_batch(data)\n objects_number, lengths = len(X[0]), [len(elem) for elem in data[0]]\n Y = self.model_.predict_on_batch(X)\n labels = np.argmax(Y, axis=-1)\n answer: List[List[str]] = [None] * objects_number\n for i, (elem, length) in enumerate(zip(labels, lengths)):\n elem = elem[:length]\n answer[i] = elem if return_indexes else self.tags.idxs2toks(elem)\n return answer", "docstring": "Makes predictions on a single batch\n\nArgs:\n data: a batch of word sequences together with additional inputs\n return_indexes: whether to return tag indexes in vocabulary or tags themselves\n\nReturns:\n a batch of label sequences", "source": "juraj_google_style"} +{"code": "def _on_channel_open(self, channel):\n\n channel.add_on_close_callback(self._on_channel_close)\n channel.add_on_cancel_callback(self._on_cancel)\n\n channel.basic_qos(callback=self._on_qosok, **config.conf[\"qos\"])", "docstring": "Callback used when a channel is opened.\n\n This registers all the channel callbacks.\n\nArgs:\n channel (pika.channel.Channel): The channel that successfully opened.", "source": "juraj_google_style"} +{"code": "def set(self, key, val):\n\n self._create_file_if_none_exists()\n with open(self.filename, 'r+b') as file_object:\n cache_pickle = pickle.load(file_object)\n cache_pickle[key] = val\n file_object.seek(0)\n pickle.dump(cache_pickle, file_object)", "docstring": "Sets a value in a key.\n\nArgs:\n key (str): Key for the value.\n val: Value to set.\n\nReturns:\n Retrieved value.", "source": "juraj_google_style"} +{"code": "def exists(self, filename):\n\n result = True\n for repo in self._children:\n if not repo.exists(filename):\n result = False\n return result", "docstring": "Report whether a file exists on all distribution points.\n\n Determines file type by extension.\n\nArgs:\n filename: Filename you wish to check. (No path! e.g.:\n \"AdobeFlashPlayer-14.0.0.176.pkg\")\n\nReturns:\n Boolean", "source": "juraj_google_style"} +{"code": "def Inference(probability=None, relation=None, name=None, concept=None):\n\n atts = {}\n if probability is not None:\n atts['probability'] = str(probability)\n if relation is not None:\n atts['relation'] = relation\n inf = objectify.Element('Inference', attrib=atts)\n if name is not None:\n inf.Name = name\n if concept is not None:\n inf.Concept = concept\n return inf", "docstring": "Represents a probable cause / relation between this event and some prior.\n\nArgs:\n probability(float): Value 0.0 to 1.0.\n relation(str): e.g. 'associated' or 'identified' (see Voevent spec)\n name(str): e.g. name of identified progenitor.\n concept(str): One of a 'formal UCD-like vocabulary of astronomical\n concepts', e.g. http://ivoat.ivoa.net/stars.supernova.Ia - see\n VOEvent spec.", "source": "juraj_google_style"} +{"code": "def _wait_for_any_event(events, timeout_s):\n\n def any_event_set():\n return any(event.is_set() for event in events)\n\n result = timeouts.loop_until_timeout_or_true(\n timeout_s, any_event_set, sleep_s=_WAIT_FOR_ANY_EVENT_POLL_S)\n\n return result or any_event_set()", "docstring": "Wait for any in a list of threading.Event's to be set.\n\nArgs:\n events: List of threading.Event's.\n timeout_s: Max duration in seconds to wait before returning.\n\nReturns:\n True if at least one event was set before the timeout expired, else False.", "source": "juraj_google_style"} +{"code": "def gene_by_alias(self, symbol, build='37'):\n\n res = self.hgnc_collection.find({'hgnc_symbol': symbol, 'build':build})\n if res.count() == 0:\n res = self.hgnc_collection.find({'aliases': symbol, 'build':build})\n\n return res", "docstring": "Return a iterable with hgnc_genes.\n\n If the gene symbol is listed as primary the iterable will only have\n one result. If not the iterable will include all hgnc genes that have\n the symbol as an alias.\n\nArgs:\n symbol(str)\n build(str)\n\nReturns:\n res(pymongo.Cursor(dict))", "source": "juraj_google_style"} +{"code": "def __init__(self, context_reading_spec, sequence_reading_spec): # pylint: disable=super-init-not-called\n\n self._context_reading_spec = context_reading_spec\n self._sequence_reading_spec = sequence_reading_spec", "docstring": "Constructs a TFRecordSequenceExampleAdapter.\n\nArgs:\n context_reading_spec: `dict`, feature name to tf.FixedLenFeature or\n tf.VarLenFeature for the context features. Passed to\n tf.io.parse_single_sequence_example.\n sequence_reading_spec: `dict`, feature name to tf.FixedLenFeature or\n tf.VarLenFeature for the sequence features. Passed to\n tf.io.parse_single_sequence_example.", "source": "juraj_google_style"} +{"code": "def recentlyAdded(self, libtype='episode', maxresults=50):\n\n return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults)", "docstring": "Returns a list of recently added episodes from this library section.\n\n Parameters:\n maxresults (int): Max number of items to return (default 50).", "source": "juraj_google_style"} +{"code": "def delete_asset(self, asset_id, asset_type):\n\n return self.asset(asset_id, asset_type=asset_type, action='DELETE')", "docstring": "Delete the asset with the provided asset_id.\n\nArgs:\n asset_id: The id of the asset.\n asset_type: The asset type.\n\n Returns:", "source": "juraj_google_style"} +{"code": "def add_file_group(self, fileGrp):\n\n el_fileSec = self._tree.getroot().find('mets:fileSec', NS)\n if el_fileSec is None:\n el_fileSec = ET.SubElement(self._tree.getroot(), TAG_METS_FILESEC)\n el_fileGrp = el_fileSec.find('mets:fileGrp[@USE=\"%s\"]' % fileGrp, NS)\n if el_fileGrp is None:\n el_fileGrp = ET.SubElement(el_fileSec, TAG_METS_FILEGRP)\n el_fileGrp.set('USE', fileGrp)\n return el_fileGrp", "docstring": "Add a new ``mets:fileGrp``.\n\nArgs:\n fileGrp (string): ``USE`` attribute of the new filegroup.", "source": "juraj_google_style"} +{"code": "def inflate_plugin_dict(plugin_dict, inflate_plugin):\n\n plugins = []\n for identifier, definition in plugin_dict.items():\n try:\n plugins.append(inflate_plugin(identifier, definition))\n except PluginNotFoundError as e:\n logger.error('Could not import plugin identified by %s. '\n 'Exception: %s.', identifier, e)\n return plugins", "docstring": "Inflate a list of strings/dictionaries to a list of plugin instances.\n\nArgs:\n plugin_dict (dict): a dict of dict.\n inflate_plugin (method): the method to inflate the plugin.\n\nReturns:\n list: a plugin instances list.", "source": "juraj_google_style"} +{"code": "def swo_set_host_buffer_size(self, buf_size):\n\n buf = ctypes.c_uint32(buf_size)\n res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_HOST,\n ctypes.byref(buf))\n if res < 0:\n raise errors.JLinkException(res)\n\n return None", "docstring": "Sets the size of the buffer used by the host to collect SWO data.\n\nArgs:\n self (JLink): the ``JLink`` instance\n buf_size (int): the new size of the host buffer\n\nReturns:\n ``None``\n\nRaises:\n JLinkException: on error", "source": "juraj_google_style"} +{"code": "def get_document(project_id, knowledge_base_id, document_id):\n\n import dialogflow_v2beta1 as dialogflow\n client = dialogflow.DocumentsClient()\n document_path = client.document_path(project_id, knowledge_base_id,\n document_id)\n\n response = client.get_document(document_path)\n print('Got Document:')\n print(' - Display Name: {}'.format(response.display_name))\n print(' - Knowledge ID: {}'.format(response.name))\n print(' - MIME Type: {}'.format(response.mime_type))\n print(' - Knowledge Types:')\n for knowledge_type in response.knowledge_types:\n print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type]))\n print(' - Source: {}\\n'.format(response.content_uri))", "docstring": "Gets a Document.\n\nArgs:\n project_id: The GCP project linked with the agent.\n knowledge_base_id: Id of the Knowledge base.\n document_id: Id of the Document.", "source": "juraj_google_style"} +{"code": "def emit(self, record):\n\n record.task = self.cur_task\n\n if record.levelno >= self.dump_level and self.cur_task:\n self.tasks[self.cur_task].failed = True\n self.tasks[self.cur_task].force_show = True\n\n # Makes no sense to start a task with an error log\n is_start = START_TASK_REG.match(str(record.msg))\n if is_start:\n self.handle_new_task(is_start.groupdict()['task_name'], record)\n return\n\n is_end = END_TASK_REG.match(str(record.msg))\n if is_end:\n self.handle_closed_task(is_end.groupdict()['task_name'], record)\n return\n\n force_show_record = ALWAYS_SHOW_REG.match(str(record.msg))\n if force_show_record:\n record.msg = force_show_record.groupdict()['message']\n self.pretty_emit(record)\n\n if (\n not force_show_record and self.should_show_by_level(record)\n and self.should_show_by_depth()\n ):\n self.pretty_emit(record)\n return\n\n if self.cur_task:\n self.tasks[self.cur_task].append(record)", "docstring": "Handle the given record, this is the entry point from the python\n logging facility\n\n Params:\n record (logging.LogRecord): log record to handle\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def find_sanitiser_nodes(\n sanitiser,\n sanitisers_in_file\n):\n\n for sanitiser_tuple in sanitisers_in_file:\n if sanitiser == sanitiser_tuple.trigger_word:\n yield sanitiser_tuple.cfg_node", "docstring": "Find nodes containing a particular sanitiser.\n\nArgs:\n sanitiser(string): sanitiser to look for.\n sanitisers_in_file(list[Node]): list of CFG nodes with the sanitiser.\n\nReturns:\n Iterable of sanitiser nodes.", "source": "juraj_google_style"} +{"code": "def __init__(self, instrumentation_key, wsgi_application, *args, **kwargs):\n\n if not instrumentation_key:\n raise Exception('Instrumentation key was required but not provided')\n if not wsgi_application:\n raise Exception('WSGI application was required but not provided')\n telemetry_channel = kwargs.pop('telemetry_channel', None)\n if not telemetry_channel:\n sender = applicationinsights.channel.AsynchronousSender()\n queue = applicationinsights.channel.AsynchronousQueue(sender)\n telemetry_channel = applicationinsights.channel.TelemetryChannel(None, queue)\n self.client = applicationinsights.TelemetryClient(instrumentation_key, telemetry_channel)\n self.client.context.device.type = \"PC\"\n self._wsgi_application = wsgi_application\n self._common_properties = kwargs.pop('common_properties', {})", "docstring": "Initialize a new instance of the class.\n\nArgs:\n instrumentation_key (str). the instrumentation key to use while sending telemetry to the service.\\n\n wsgi_application (func). the WSGI application that we're wrapping.", "source": "juraj_google_style"} +{"code": "def CopyFromDict(self, attributes):\n\n for attribute_name, attribute_value in attributes.items():\n # Not using startswith to improve performance.\n if attribute_name[0] == '_':\n continue\n setattr(self, attribute_name, attribute_value)", "docstring": "Copies the attribute container from a dictionary.\n\nArgs:\n attributes (dict[str, object]): attribute values per name.", "source": "juraj_google_style"} +{"code": "def get_validators(self, id=None, endpoint=None):\n\n return self._call_endpoint(GET_VALIDATORS, id=id, endpoint=endpoint)", "docstring": "Returns the current NEO consensus nodes information and voting status.\n\nArgs:\n id: (int, optional) id to use for response tracking\n endpoint: (RPCEndpoint, optional) endpoint to specify to use\n\nReturns:\n json object of the result or the error encountered in the RPC call", "source": "juraj_google_style"} +{"code": "def Sign(self, data, signing_key, verify_key=None):\n\n\n if signing_key.KeyLen() < 2048:\n logging.warning(\"signing key is too short.\")\n\n self.signature = signing_key.Sign(data)\n self.signature_type = self.SignatureType.RSA_PKCS1v15\n\n self.digest = hashlib.sha256(data).digest()\n self.digest_type = self.HashType.SHA256\n self.data = data\n\n # Test we can verify before we send it off.\n if verify_key is None:\n verify_key = signing_key.GetPublicKey()\n\n # Verify our own data.\n self.Verify(verify_key)\n\n return self", "docstring": "Use the data to sign this blob.\n\nArgs:\n data: String containing the blob data.\n signing_key: The key to sign with.\n verify_key: Key to verify with. If None we assume the signing key also\n contains the public key.\n\nReturns:\n self for call chaining.", "source": "juraj_google_style"} +{"code": "def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename):\n\n\n if not tf.gfile.Exists(data_dir):\n tf.gfile.MakeDirs(data_dir)\n\n file_path = generator_utils.maybe_download(tmp_dir, _TAR, _URL)\n tar_all = tarfile.open(file_path)\n tar_all.extractall(tmp_dir)\n tar_all.close()\n tar_train = tarfile.open(os.path.join(tmp_dir, \"train-novels.tar\"))\n tar_train.extractall(tmp_dir)\n tar_train.close()\n\n vocab_path = os.path.join(data_dir, vocab_filename)\n if not tf.gfile.Exists(vocab_path):\n with tf.gfile.GFile(os.path.join(tmp_dir, _VOCAB), \"r\") as infile:\n reader = csv.reader(infile, delimiter=\"\\t\")\n words = [row[0] for row in reader]\n words = [_UNK] + words[:vocab_size]\n with tf.gfile.GFile(vocab_path, \"w\") as outfile:\n outfile.write(\"\\n\".join(words))", "docstring": "Downloading and preparing the dataset.\n\nArgs:\n tmp_dir: tem directory\n data_dir: data directory\n vocab_size: size of vocabulary\n vocab_filename: name of vocab file", "source": "juraj_google_style"} +{"code": "def collective_dr_squared( self ):\n\n return sum( np.square( sum( [ atom.dr for atom in self.atoms ] ) ) )", "docstring": "Squared sum of total displacements for these atoms.\n\nArgs:\n None\n\nReturns:\n (Float): The square of the summed total displacements for these atoms.", "source": "juraj_google_style"} +{"code": "def dataframe(start_row=0, max_rows=None, use_cache=True):\n\n output = QueryOutput()\n output._output_type = 'dataframe'\n output._dataframe_start_row = start_row\n output._dataframe_max_rows = max_rows\n output._use_cache = use_cache\n return output", "docstring": "Construct a query output object where the result is a dataframe\n\nArgs:\n start_row: the row of the table at which to start the export (default 0).\n max_rows: an upper limit on the number of rows to export (default None).\n use_cache: whether to use cached results or not (default True).", "source": "juraj_google_style"} +{"code": "def __init__(self, path, text_field, label_field,\n fine_grained=False, **kwargs):\n\n fields = [('text', text_field), ('label', label_field)]\n examples = []\n\n def get_label_str(label):\n return label.split(':')[0] if not fine_grained else label\n label_field.preprocessing = data.Pipeline(get_label_str)\n\n for line in open(os.path.expanduser(path), 'rb'):\n # there is one non-ASCII byte: sisterBADBYTEcity; replaced with space\n label, _, text = line.replace(b'\\xf0', b' ').decode().partition(' ')\n examples.append(data.Example.fromlist([text, label], fields))\n\n super(TREC, self).__init__(examples, fields, **kwargs)", "docstring": "Create an TREC dataset instance given a path and fields.\n\nArgs:\n path: Path to the data file.\n text_field: The field that will be used for text data.\n label_field: The field that will be used for label data.\n fine_grained: Whether to use the fine-grained (50-class) version of TREC\n or the coarse grained (6-class) version.\n Remaining keyword arguments: Passed to the constructor of\n data.Dataset.", "source": "juraj_google_style"} +{"code": "def update_batch(self, loss_per_instance):\n\n if self.batch_indices is None:\n raise TensorForceError(\"Need to call get_batch before each update_batch call.\")\n # if len(loss_per_instance) != len(self.batch_indices):\n # raise TensorForceError(\"For all instances a loss value has to be provided.\")\n\n for index, loss in zip(self.batch_indices, loss_per_instance):\n # Sampling priority is proportional to the largest absolute temporal difference error.\n new_priority = (np.abs(loss) + self.prioritization_constant) ** self.prioritization_weight\n self.observations._move(index, new_priority)\n self.none_priority_index += 1", "docstring": "Computes priorities according to loss.\n\nArgs:\n loss_per_instance:", "source": "juraj_google_style"} +{"code": "def url_stats(self, short):\n\n data = dict(action='url-stats', shorturl=short)\n jsondata = self._api_request(params=data)\n\n return _json_to_shortened_url(jsondata['link'])", "docstring": "Get stats for short URL or keyword.\n\n Parameters:\n short: Short URL (http://example.com/abc) or keyword (abc).\n\nReturns:\n ShortenedURL: Shortened URL and associated data.\n\nRaises:\n ~yourls.exceptions.YOURLSHTTPError: HTTP error with response from\n YOURLS API.\n requests.exceptions.HTTPError: Generic HTTP error.", "source": "juraj_google_style"} +{"code": "def __init__(self, low, high, output_shape):\n\n self.__low = low\n self.__high = high\n self.__output_shape = output_shape", "docstring": "Init.\n\nArgs:\n low: Lower boundary of the output interval.\n All values generated will be greater than or equal to low.\n\n high: Upper boundary of the output interval.\n All values generated will be less than high.\n\n output_shape: Output shape.\n the shape is `(batch size, d1, d2, d3, ...)`.", "source": "juraj_google_style"} +{"code": "def get_dependent_projects(self, recursive = True):\n\n projects = {}\n for name, ref in list(self.dependencies.items()):\n try:\n prj = self.vcp.projects[name]\n except KeyError:\n logger.error(\"Unknown project '%s' in project '%s' dependencies!\", name, self.name)\n continue\n projects[name] = prj\n if recursive:\n projects.update(prj.get_dependent_projects())\n return projects", "docstring": "Get the dependencies of the Project\n\nArgs:\n recursive (bool): add the dependant project's dependencies too\n\nReturns:\n dict of project name and project instances", "source": "juraj_google_style"} +{"code": "def gru_feedfwd(a_t, h_prev, filters, name=None):\n\n\n with tf.variable_scope(name, default_name=\"GRU\", values=[a_t, h_prev]):\n # we use right matrix multiplication to handle batches\n # W_z and W_r have shape 2d, d. U_z U_r have shape d,d\n z_t = (\n tf.sigmoid(\n tpu_conv1d(a_t, filters, 1, padding=\"SAME\", name=\"W_z\") +\n tpu_conv1d(h_prev, filters, 1, padding=\"SAME\", name=\"U_z\")))\n r_t = (\n tf.sigmoid(\n tpu_conv1d(a_t, filters, 1, padding=\"SAME\", name=\"W_r\") +\n tpu_conv1d(h_prev, filters, 1, padding=\"SAME\", name=\"U_r\")))\n h_tilde = (\n tf.tanh(\n tpu_conv1d(a_t, filters, 1, padding=\"SAME\", name=\"W\") +\n tpu_conv1d(r_t * h_prev, filters, 1, padding=\"SAME\", name=\"U\")))\n h_t = (1. - z_t) * h_prev + z_t * h_tilde\n\n return h_t", "docstring": "position-wise Feed-fwd GRU gates following the MPNN.\n\nArgs:\n a_t: Tensor of shape [batch, length, depth] of current input\n h_prev: Tensor of shape [batch, length, depth] of prev input\n filters: an integer specifying number of dimensions of the filters\n name: A string\n\nReturns:\n h_t: [batch, length, filters] hidden state", "source": "juraj_google_style"} +{"code": "def timeseries_from_mat(filename, varname=None, fs=1.0):\n\n import scipy.io as sio\n if varname is None:\n mat_dict = sio.loadmat(filename)\n if len(mat_dict) > 1:\n raise ValueError('Must specify varname: file contains '\n 'more than one variable. ')\n else:\n mat_dict = sio.loadmat(filename, variable_names=(varname,))\n array = mat_dict.popitem()[1]\n return Timeseries(array, fs=fs)", "docstring": "load a multi-channel Timeseries from a MATLAB .mat file\n\nArgs:\n filename (str): .mat file to load\n varname (str): variable name. only needed if there is more than one\n variable saved in the .mat file\n fs (scalar): sample rate of timeseries in Hz. (constant timestep assumed)\n\nReturns:\n Timeseries", "source": "juraj_google_style"} +{"code": "def columns(self, dimensions=None):\n\n if dimensions is None:\n dimensions = self.dimensions()\n else:\n dimensions = [self.get_dimension(d, strict=True) for d in dimensions]\n return OrderedDict([(d.name, self.dimension_values(d)) for d in dimensions])", "docstring": "Convert dimension values to a dictionary.\n\n Returns a dictionary of column arrays along each dimension\n of the element.\n\nArgs:\n dimensions: Dimensions to return as columns\n\nReturns:\n Dictionary of arrays for each dimension", "source": "juraj_google_style"} +{"code": "def _validator(code_or_name, validator_type):\n\n if validator_type == \"error\":\n from .errors import codes\n from .errors import EXT\n elif validator_type == \"warning\":\n from .warnings import codes\n from .warnings import EXT\n else:\n pass # TODO (bev) ValueError?\n\n def decorator(func):\n def wrapper(*args, **kw):\n extra = func(*args, **kw)\n if extra is None: return []\n if isinstance(code_or_name, string_types):\n code = EXT\n name = codes[code][0] + \":\" + code_or_name\n else:\n code = code_or_name\n name = codes[code][0]\n text = codes[code][1]\n return [(code, name, text, extra)]\n wrapper.validator_type = validator_type\n return wrapper\n\n return decorator", "docstring": "Internal shared implementation to handle both error and warning\n validation checks.\n\nArgs:\n code code_or_name (int or str) : a defined error code or custom message\n validator_type (str) : either \"error\" or \"warning\"\n\nReturns:\n validation decorator", "source": "juraj_google_style"} +{"code": "def print_probabilities(state: State, ndigits: int = 4,\n file: TextIO = None) -> None:\n\n prob = bk.evaluate(state.probabilities())\n for index, prob in np.ndenumerate(prob):\n prob = round(prob, ndigits)\n if prob == 0.0:\n continue\n ket = \"\".join([str(n) for n in index])\n print(ket, \":\", prob, file=file)", "docstring": "Pretty print state probabilities.\n\nArgs:\n state:\n ndigits: Number of digits of accuracy\n file: Output stream (Defaults to stdout)", "source": "juraj_google_style"} +{"code": "def format_color(text, color, use_color_setting):\n\n if not use_color_setting:\n return text\n else:\n return '{}{}{}'.format(color, text, NORMAL)", "docstring": "Format text with color.\n\nArgs:\n text - Text to be formatted with color if `use_color`\n color - The color start string\n use_color_setting - Whether or not to color", "source": "juraj_google_style"} +{"code": "def _set_axis(self,traces,on=None,side='right',title=''):\n\n\tfig={}\n\tfig_cpy=fig_to_dict(self).copy()\n\tfig['data']=fig_cpy['data']\n\tfig['layout']=fig_cpy['layout']\n\tfig=Figure(fig)\n\ttraces=make_list(traces)\n\n\tdef update_data(trace,y):\n\t\tanchor=fig.axis['def'][y]['anchor'] if 'anchor' in fig.axis['def'][y] else 'x1'\n\t\tidx=fig.trace_dict[trace] if isinstance(trace,str) else trace\n\t\tfig['data'][idx]['xaxis']=anchor\n\t\tfig['data'][idx]['yaxis']=y\n\n\tfor trace in traces:\n\t\tif on:\n\t\t\tif on not in fig.axis['def']:\n\t\t\t\traise Exception('\"on\" axis does not exists: {0}'.format(on))\n\t\t\tupdate_data(trace,y=on)\n\t\telse:\n\t\t\tcurr_x,curr_y=fig.axis['ref'][trace]\n\t\t\tdomain='[0.0, 1.0]' if 'domain' not in fig.axis['def'][curr_y] else str(fig.axis['def'][curr_y]['domain'])\n\t\t\ttry:\n\t\t\t\tnew_axis=fig.axis['dom']['y'][domain][side]\n\t\t\texcept KeyError:\n\t\t\t\taxis=fig.axis['def'][curr_y].copy()\n\t\t\t\t### check overlaying values\n\t\t\t\taxis.update(title=title,overlaying=curr_y,side=side,anchor=curr_x)\n\t\t\t\taxis_idx=str(fig.axis['len']['y']+1)\n\t\t\t\tfig['layout']['yaxis{0}'.format(axis_idx)]=axis\n\t\t\t\tnew_axis='y{0}'.format(axis_idx)\n\t\t\tupdate_data(trace,y=new_axis)\n\n\n\tfor k in list(fig.axis['def'].keys()):\n\t\tid='{0}axis{1}'.format(k[0],k[-1:])\n\t\tif k not in fig.axis['ref_axis']:\n\t\t\ttry:\n\t\t\t\tdel fig['layout'][id]\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\n\treturn fig", "docstring": "Sets the axis in which each trace should appear\n If the axis doesn't exist then a new axis is created\n\n Parameters:\n -----------\n traces : list(str)\n List of trace names\n on : string\n The axis in which the traces should be placed.\n If this is not indicated then a new axis will be\n created\n side : string\n Side where the axis will be placed\n 'left'\n 'right'\n title : string\n Sets the title of the axis\n Applies only to new axis", "source": "juraj_google_style"} +{"code": "def write_file(path, data, mode='w'): # type: (str, str, str) -> None\n\n with open(path, mode) as f:\n f.write(data)", "docstring": "Write data to a file.\n\nArgs:\n path (str): path to the file.\n data (str): data to be written to the file.\n mode (str): mode which the file will be open.", "source": "juraj_google_style"} +{"code": "def basis_state(str_state, num):\n\n n = int(str_state, 2)\n if num >= len(str_state):\n state = np.zeros(1 << num, dtype=complex)\n state[n] = 1\n return state\n else:\n raise QiskitError('size of bitstring is greater than num.')", "docstring": "Return a basis state ndarray.\n\nArgs:\n str_state (string): a string representing the state.\n num (int): the number of qubits\n\nReturns:\n ndarray: state(2**num) a quantum state with basis basis state.\n\nRaises:\n QiskitError: if the dimensions is wrong", "source": "juraj_google_style"} +{"code": "def get_config(self, name):\n\n if name not in self.registry:\n msg = \"Given config name '{}' is not registered.\"\n raise NotRegisteredError(msg.format(name))\n\n return copy.deepcopy(self.registry[name])", "docstring": "Return a registred configuration for given config name.\n\nArgs:\n name (string): A registred config name.\n\nRaises:\n NotRegisteredError: If given config name does not exist in\n registry.\n\nReturns:\n dict: Configuration.", "source": "juraj_google_style"} +{"code": "def plot_pie(self, key=\"wall_time\", minfract=0.05, **kwargs):\n\n timers = self.timers()\n n = len(timers)\n\n # Make square figures and axes\n import matplotlib.pyplot as plt\n from matplotlib.gridspec import GridSpec\n fig = plt.gcf()\n gspec = GridSpec(n, 1)\n for idx, timer in enumerate(timers):\n ax = plt.subplot(gspec[idx, 0])\n ax.set_title(str(timer))\n timer.pie(ax=ax, key=key, minfract=minfract, show=False)\n\n return fig", "docstring": "Plot pie charts of the different timers.\n\nArgs:\n key: Keyword used to extract data from timers.\n minfract: Don't show sections whose relative weight is less that minfract.\n\nReturns:\n `matplotlib` figure", "source": "juraj_google_style"} +{"code": "def _get_acorn(self, method, *items):\n\n #IMPORTANT!! I lost two hours because the ndarray becomes unstable if you\n #don't call the original method first. Somehow passing the array instance to\n #other methods changed its internal representation and made it unusable by\n #the original numpy functions. Putting them first makes it work.\n\n # Because we had to subclass numpy.ndarray, the original methods get\n # stuck in an infinite loop (max. recursion depth exceeded errors). So,\n # we instead grab the reference to the original ndarray object.\n if method == \"slice\":\n r = np.ndarray.__acornext__.__getslice__(self, *items)\n else:\n r = np.ndarray.__acornext__.__getitem__(self, *items)\n\n if not (decorating or streamlining):\n from acorn.logging.decoration import (pre, post, _fqdn)\n if method == \"slice\":\n fqdn = \"numpy.ndarray.__getslice__\"\n else:\n fqdn = \"numpy.ndarray.__getitem__\"\n preres = pre(fqdn, np.ndarray, 5, self, *items)\n entry, bound, ekey = preres\n # This method can trick acorn into thinking that it is a bound\n # method. We want it to behave like it's not.\n post(fqdn, \"numpy\", r, entry, np.ndarray, ekey)\n return r", "docstring": "Gets either a slice or an item from an array. Used for the __getitem__\n and __getslice__ special methods of the sub-classed array.\n\nArgs:\n method (str): on of ['slice', 'item'].", "source": "juraj_google_style"} +{"code": "def wasp_snp_directory(vcf, directory, sample_name=None):\n\n chrom = []\n pos = []\n ref = []\n alt = []\n vcf_reader = pyvcf.Reader(open(vcf, 'r'))\n if sample_name:\n def condition(record, sample_name):\n return sample_name in [x.sample for x in record.get_hets()]\n else:\n def condition(record, sample_name):\n return len(record.get_hets()) > 0\n for record in vcf_reader:\n if condition(record, sample_name):\n if len(record.ALT) == 1:\n chrom.append(record.CHROM)\n pos.append(record.POS)\n ref.append(record.REF)\n alt.append(record.ALT[0].sequence)\n df = pd.DataFrame([chrom, pos, ref, alt], \n index=['chrom', 'position', 'RefAllele', 'AltAllele']).T\n if not os.path.exists(directory):\n os.makedirs(directory)\n for c in set(df.chrom):\n tdf = df[df.chrom == c]\n if tdf.shape[0] > 0:\n f = gzip.open(os.path.join(directory, '{}.snps.txt.gz'.format(c)),\n 'wb')\n lines = (tdf.position.astype(str) + '\\t' + tdf.RefAllele + '\\t' +\n tdf.AltAllele)\n f.write('\\n'.join(lines) + '\\n')\n f.close()", "docstring": "Convert VCF file into input for WASP. Only bi-allelic heterozygous sites are\n used.\n\n Parameters:\n -----------\n vcf : str\n Path to VCF file.\n\n directory : str\n Output directory. This is the directory that will hold the files for\n WASP.\n\n sample_name : str\n If provided, use this sample name to get heterozygous SNPs from VCF\n file.", "source": "juraj_google_style"} +{"code": "def parse_date(datestr):\n\n\n match = re.match(\n r'([0-9]{4})(-?([0-9]{1,2}))?(-?([0-9]{1,2}))?(_w)?$', datestr)\n if not match:\n return (arrow.get(datestr,\n tzinfo=config.timezone).replace(tzinfo=config.timezone),\n 'day', 'YYYY-MM-DD')\n\n year, month, day, week = match.group(1, 3, 5, 6)\n start = arrow.Arrow(year=int(year), month=int(\n month or 1), day=int(day or 1), tzinfo=config.timezone)\n\n if week:\n return start.span('week')[0], 'week', WEEK_FORMAT\n if day:\n return start, 'day', DAY_FORMAT\n if month:\n return start, 'month', MONTH_FORMAT\n if year:\n return start, 'year', YEAR_FORMAT\n\n raise ValueError(\"Could not parse date: {}\".format(datestr))", "docstring": "Parse a date expression into a tuple of:\n\n (start_date, span_type, span_format)\n\nArgs:\n datestr -- A date specification, in the format of YYYY-MM-DD (dashes optional)", "source": "juraj_google_style"} +{"code": "def m_seg(p1, p2, rad, dist):\n\n v = vector(p1, p2)\n m = unit(rotate(v, rad), dist)\n return translate(p1, m), translate(p2, m)", "docstring": "move segment by distance\n\nArgs:\n p1, p2: point(x, y)\n rad: relative direction angle(radian)\n dist: distance\n\nReturns:\n translated segment(p1, p2)", "source": "juraj_google_style"} +{"code": "def dropout(x, keep_prob, noise_shape=None, name=None):\n\n noise_shape = convert_to_shape(noise_shape)\n if noise_shape is None:\n noise_shape = x.shape\n with tf.variable_scope(name, default_name=\"dropout\"):\n if keep_prob == 1.0:\n return x\n noise = cast(less(random_uniform(\n x.mesh, noise_shape, dtype=x.dtype), keep_prob), x.dtype)\n noise /= keep_prob\n return x * noise", "docstring": "Dropout layer.\n\nArgs:\n x: a Tensor\n keep_prob: a float between 0.0 and 1.0\n noise_shape: an optional Shape (a subset of x.shape)\n name: an optional string\n\nReturns:\n a Tensor", "source": "juraj_google_style"} +{"code": "def get_box_field(self, box_key, field_key = None):\n\n\t\t#does not work\n\t\tself._raise_unimplemented_error()\n\n\t\turi = '/'.join([self.api_uri,\n\t\t\t\t\t\tself.boxes_suffix,\n\t\t\t\t\t\tbox_key,\n\t\t\t\t\t\tself.fields_suffix\n\t\t\t\t\t\t])\n\t\tif field_key:\n\t\t\turi = '/'.join([uri, field_key])\n\n\t\treturn self._req('get', uri)", "docstring": "Gets one/all field in a box\n\nArgs:\n box_key \t\tkey for pipeline\n field_key \t\t\tkey for field (default: None i.e. ALL)\n returns\t\t\t\tstatus code, field dict or list thereof", "source": "juraj_google_style"} +{"code": "def find_links(url):\n\n url = protocolise(url)\n content = requests.get(url).content\n flike = StringIO(content)\n root = html.parse(flike).getroot()\n atags = root.cssselect('a')\n hrefs = [a.attrib['href'] for a in atags]\n # !!! This does the wrong thing for bbc.co.uk/index.html\n hrefs = [h if h.startswith('http') else '/'.join([url, h]) for h in hrefs ]\n return hrefs", "docstring": "Find the href destinations of all links at URL\n\nArgs:\n - `url`:\n\n Return: list[str]\n Exceptions: None", "source": "juraj_google_style"} +{"code": "def ParseCacheEntry(self, file_object, block_offset):\n\n cache_entry_map = self._GetDataTypeMap('chrome_cache_entry')\n\n try:\n cache_entry, _ = self._ReadStructureFromFileObject(\n file_object, block_offset, cache_entry_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.UnableToParseFile((\n 'Unable to parse cache entry at offset: 0x{0:08x} with error: '\n '{1!s}').format(block_offset, exception))\n\n cache_entry_object = CacheEntry()\n\n cache_entry_object.hash = cache_entry.hash\n cache_entry_object.next = CacheAddress(cache_entry.next_address)\n cache_entry_object.rankings_node = CacheAddress(\n cache_entry.rankings_node_address)\n cache_entry_object.creation_time = cache_entry.creation_time\n\n byte_array = cache_entry.key\n byte_string = bytes(bytearray(byte_array))\n cache_entry_object.key, _, _ = byte_string.partition(b'\\x00')\n\n try:\n cache_entry_object.original_url = cache_entry_object.key.decode('ascii')\n except UnicodeDecodeError as exception:\n raise errors.ParseError(\n 'Unable to decode original URL in key with error: {0!s}'.format(\n exception))\n\n return cache_entry_object", "docstring": "Parses a cache entry.\n\nArgs:\n file_object (dfvfs.FileIO): a file-like object to read from.\n block_offset (int): block offset of the cache entry.\n\nReturns:\n CacheEntry: cache entry.\n\nRaises:\n ParseError: if the cache entry cannot be read.", "source": "juraj_google_style"} +{"code": "def identifiers(config):\n\n ids = []\n if (config.klass_name == 'gen'):\n for generator in os.listdir(config.generator_dir):\n if (generator == '__init__.py'):\n continue\n (gid, ext) = os.path.splitext(generator)\n if (ext == '.py' and\n os.path.isfile(os.path.join(config.generator_dir, generator))):\n ids.append(gid)\n else:\n for image_file in os.listdir(config.image_dir):\n (iid, ext) = os.path.splitext(image_file)\n if (ext in ['.jpg', '.png', '.tif'] and\n os.path.isfile(os.path.join(config.image_dir, image_file))):\n ids.append(iid)\n return ids", "docstring": "Show list of identifiers for this prefix.\n\n Handles both the case of local file based identifiers and\n also image generators.\n\nArgs:\n config - configuration object in which:\n config.klass_name - 'gen' if a generator function\n config.generator_dir - directory for generator code\n config.image_dir - directory for images\n\nReturns:\n ids - a list of ids", "source": "juraj_google_style"} +{"code": "def derive_temporary_python2_environment(\n destination_directory: str,\n python3_environment: PreparedEnv,\n verbose: bool,\n env_name: str = '.test_virtualenv_py2',\n python_path: str = \"/usr/bin/python2.7\") -> PreparedEnv:\n\n\n shutil.rmtree(destination_directory)\n input_directory = cast(str, python3_environment.destination_directory)\n os.chdir(input_directory)\n conversion_script_path = os.path.join(\n input_directory,\n 'dev_tools',\n 'python2.7-generate.sh')\n shell_tools.run_cmd('bash',\n conversion_script_path,\n destination_directory,\n input_directory,\n python3_environment.virtual_env_path,\n out=sys.stderr)\n os.chdir(destination_directory)\n\n # Create virtual environment.\n env_path = os.path.join(destination_directory, env_name)\n # (These files are output by dev_tools/python2.7-generate.sh.)\n req_path = os.path.join(destination_directory, 'requirements.txt')\n dev_req_path = os.path.join(destination_directory,\n 'pip-list-test-tools.txt')\n contrib_req_path = os.path.join(destination_directory,\n 'cirq',\n 'contrib',\n 'contrib-requirements.txt')\n req_paths = [req_path, dev_req_path, contrib_req_path]\n create_virtual_env(venv_path=env_path,\n python_path=python_path,\n requirements_paths=req_paths,\n verbose=verbose)\n\n return PreparedEnv(github_repo=python3_environment.repository,\n actual_commit_id=python3_environment.actual_commit_id,\n compare_commit_id=python3_environment.compare_commit_id,\n destination_directory=destination_directory,\n virtual_env_path=env_path)", "docstring": "Creates a python 2.7 environment starting from a prepared python 3 one.\n\nArgs:\n destination_directory: Where to put the python 2 environment.\n python3_environment: The prepared environment to start from.\n verbose: When set, more progress output is produced.\n env_name: The name to use for the virtualenv directory.\n python_path: The python binary to use.\n\nReturns:\n A description of the environment that was prepared.", "source": "juraj_google_style"} +{"code": "def get_lattice_type(number):\n\n f = lambda i, j: i <= number <= j\n cs = {'triclinic': (1, 2), 'monoclinic': (3, 15),\n 'orthorhombic': (16, 74), 'tetragonal': (75, 142),\n 'trigonal': (143, 167), 'hexagonal': (168, 194),\n 'cubic': (195, 230)}\n\n crystal_system = None\n for k, v in cs.items():\n if f(*v):\n crystal_system = k\n break\n\n if number in [146, 148, 155, 160, 161, 166, 167]:\n return \"rhombohedral\"\n elif crystal_system == \"trigonal\":\n return \"hexagonal\"\n else:\n return crystal_system", "docstring": "Return the lattice crystal system.\n\n Hexagonal cells are differentiated into rhombohedral and hexagonal\n lattices.\n\nArgs:\n number (int): The international space group number.\n\nReturns:\n str: The lattice crystal system.", "source": "juraj_google_style"} +{"code": "def resize_bytes(fobj, old_size, new_size, offset):\n\n\n if new_size < old_size:\n delete_size = old_size - new_size\n delete_at = offset + new_size\n delete_bytes(fobj, delete_size, delete_at)\n elif new_size > old_size:\n insert_size = new_size - old_size\n insert_at = offset + old_size\n insert_bytes(fobj, insert_size, insert_at)", "docstring": "Resize an area in a file adding and deleting at the end of it.\n Does nothing if no resizing is needed.\n\nArgs:\n fobj (fileobj)\n old_size (int): The area starting at offset\n new_size (int): The new size of the area\n offset (int): The start of the area\n\nRaises:\n IOError", "source": "juraj_google_style"} +{"code": "def get_pending_enrollment_message(cls, pending_users, enrolled_in):\n\n pending_emails = [pending_user.user_email for pending_user in pending_users]\n return (\n 'warning',\n _(\n \"The following learners do not have an account on \"\n \"{platform_name}. They have not been enrolled in \"\n \"{enrolled_in}. When these learners create an account, they will \"\n \"be enrolled automatically: {pending_email_list}\"\n ).format(\n platform_name=settings.PLATFORM_NAME,\n enrolled_in=enrolled_in,\n pending_email_list=', '.join(pending_emails),\n )\n )", "docstring": "Create message for the users who were enrolled in a course or program.\n\nArgs:\n users: An iterable of PendingEnterpriseCustomerUsers who were successfully linked with a pending enrollment\n enrolled_in (str): A string identifier for the course or program the pending users were linked to\n\nReturns:\n tuple: A 2-tuple containing a message type and message text", "source": "juraj_google_style"} +{"code": "def setAltInterface(self, alternate):\n r\n if isinstance(alternate, Interface):\n alternate = alternate.alternateSetting\n\n self.dev.set_interface_altsetting(self.__claimed_interface, alternate)", "docstring": "r\"\"\"Sets the active alternate setting of the current interface.\n\nArgs:\n alternate: an alternate setting number or an Interface object.", "source": "juraj_google_style"} +{"code": "def top2_reduced(params, moments):\n\n params = np.asarray(params)\n alpha = params[0]\n a = params[1:5]\n b = params[5:]\n p = np.asarray(moments)\n p1 = alpha*a+(1-alpha)*b-p[:4]\n p21 = alpha*a[0]*a[2:]/(1-a[0])+(1-alpha)*b[0]*b[2:]/(1-b[0])-p[4:6]\n p22 = alpha*a[1]*np.hstack((a[0],a[3]))/(1-a[1])+(1-alpha)*b[1]*np.hstack((b[0],b[3]))/(1-b[1])-p[6:8]\n p23 = alpha*a[2]*a[:2]/(1-a[2])+(1-alpha)*b[2]*b[:2]/(1-b[2])-p[8:10]\n p24 = alpha*a[3]*a[1:3]/(1-a[3])+(1-alpha)*b[3]*b[1:3]/(1-b[3])-p[10:]\n allp = np.concatenate((p1,p21,p22,p23,p24))\n return np.sum(allp**2)", "docstring": "Description:\n Top 2 alternatives 12 moment conditions objective function\n Parameters:\n params: all parameters for the Plackett-Luce mixture model (numpy ndarray)\n moments: values of the moment conditions from the data (numpy ndarray)", "source": "juraj_google_style"} +{"code": "def is_initialised( self ):\n\n if not self.lattice:\n raise AttributeError('Running a simulation needs the lattice to be initialised')\n if not self.atoms:\n raise AttributeError('Running a simulation needs the atoms to be initialised')\n if not self.number_of_jumps and not self.for_time:\n raise AttributeError('Running a simulation needs number_of_jumps or for_time to be set')", "docstring": "Check whether the simulation has been initialised.\n\nArgs:\n None\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def global_idx_to_numeric_idx(self, axis, indices):\n\n assert axis in [\"row\", \"col\", \"columns\"]\n if axis == \"row\":\n return pandas.Index(\n pandas.Series(np.arange(len(self.index)), index=self.index)\n .loc[indices]\n .values\n )\n elif axis in [\"col\", \"columns\"]:\n return pandas.Index(\n pandas.Series(np.arange(len(self.columns)), index=self.columns)\n .loc[indices]\n .values\n )", "docstring": "Note: this function involves making copies of the index in memory.\n\nArgs:\n axis: Axis to extract indices.\n indices: Indices to convert to numerical.\n\nReturns:\n An Index object.", "source": "juraj_google_style"} +{"code": "def __init__(self, json_data):\n\n super(SimpleDataModel, self).__init__()\n for attribute, value in json_dict(json_data).items():\n setattr(self, attribute, value)", "docstring": "Init a new SimpleDataModel object from a dictionary or JSON string.\n\nArgs:\n json_data(dict, basestring): Input JSON string or dictionary.\n\nRaises:\n TypeError: If the input object is not a dictionary or string.", "source": "juraj_google_style"} +{"code": "def from_label(cls, label):\n r\n z = np.zeros(len(label), dtype=np.bool)\n x = np.zeros(len(label), dtype=np.bool)\n for i, char in enumerate(label):\n if char == 'X':\n x[-i - 1] = True\n elif char == 'Z':\n z[-i - 1] = True\n elif char == 'Y':\n z[-i - 1] = True\n x[-i - 1] = True\n elif char != 'I':\n raise QiskitError(\"Pauli string must be only consisted of 'I', 'X', \"\n \"'Y' or 'Z' but you have {}.\".format(char))\n return cls(z=z, x=x)", "docstring": "r\"\"\"Take pauli string to construct pauli.\n\n The qubit index of pauli label is q_{n-1} ... q_0.\n E.g., a pauli is $P_{n-1} \\otimes ... \\otimes P_0$\n\nArgs:\n label (str): pauli label\n\nReturns:\n Pauli: the constructed pauli\n\nRaises:\n QiskitError: invalid character in the label", "source": "juraj_google_style"} +{"code": "def _maybe_download_corpora(tmp_dir):\n\n mnli_filename = \"MNLI.zip\"\n mnli_finalpath = os.path.join(tmp_dir, \"MNLI\")\n if not tf.gfile.Exists(mnli_finalpath):\n zip_filepath = generator_utils.maybe_download(\n tmp_dir, mnli_filename, _MNLI_URL)\n zip_ref = zipfile.ZipFile(zip_filepath, \"r\")\n zip_ref.extractall(tmp_dir)\n zip_ref.close()\n\n return mnli_finalpath", "docstring": "Download corpora for multinli.\n\nArgs:\n tmp_dir: a string\n\nReturns:\n a string", "source": "juraj_google_style"} +{"code": "def display_required_items(msg_type):\n\n print(\"Configure a profile for: \" + msg_type)\n print(\"You will need the following information:\")\n for k, v in CONFIG[msg_type][\"settings\"].items():\n print(\" * \" + v)\n print(\"Authorization/credentials required:\")\n for k, v in CONFIG[msg_type][\"auth\"].items():\n print(\" * \" + v)", "docstring": "Display the required items needed to configure a profile for the given\n message type.\n\nArgs:\n :msg_type: (str) message type to create config entry.", "source": "juraj_google_style"} +{"code": "def rename_edges(self, old_node_name, new_node_name):\n\n graph = self.graph\n for node, edges in graph.items():\n if node == old_node_name:\n graph[new_node_name] = copy(edges)\n del graph[old_node_name]\n\n else:\n if old_node_name in edges:\n edges.remove(old_node_name)\n edges.add(new_node_name)", "docstring": "Change references to a node in existing edges.\n\nArgs:\n old_node_name (str): The old name for the node.\n new_node_name (str): The new name for the node.", "source": "juraj_google_style"} +{"code": "def add_config_paths(**kwargs):\n\n\n for k, path in kwargs.items():\n if not os.path.exists(path):\n raise ValueError(\n 'Configuration file \"{}\" does not exist'.format(k))\n if k in cf.get_option('config_paths'):\n raise ValueError('Configuration {!r} already exists'.format(k))\n\n kwargs.update(**cf.get_option('config_paths'))\n cf.set_option('config_paths', kwargs)", "docstring": "Add to the pool of available configuration files for BIDSLayout.\n\nArgs:\n kwargs: dictionary specifying where to find additional config files.\n Keys are names, values are paths to the corresponding .json file.\n\nExample:\n > add_config_paths(my_config='/path/to/config')\n > layout = BIDSLayout('/path/to/bids', config=['bids', 'my_config'])", "source": "juraj_google_style"} +{"code": "def inner_content(node):\n\n\n from lxml import etree\n\n # Include text content at the start of the node.\n parts = [node.text]\n\n for child in node.getchildren():\n # Include the child serialized to raw XML.\n parts.append(etree.tostring(child, encoding=\"utf-8\"))\n\n # Include any text following the child.\n parts.append(child.tail)\n\n # Discard any non-existent text parts and return.\n return \"\".join(filter(None, parts))", "docstring": "Returns the inner content of a given XML node, including tags.\n\nArgs:\n node (lxml.etree.Element): The node whose inner content is desired.\n\nReturns:\n str: The inner content of the node.", "source": "juraj_google_style"} +{"code": "def pack_tag(field_number, wire_type):\n\n if not 0 <= wire_type <= _WIRETYPE_MAX:\n raise errors.EncodeError('Unknown wire type: %d' % wire_type)\n return (field_number << TAG_TYPE_BITS) | wire_type", "docstring": "Returns an unsigned 32-bit integer that encodes the field number and\n wire type information in standard protocol message wire format.\n\nArgs:\n field_number: Expected to be an integer in the range [1, 1 << 29)\n wire_type: One of the WIRETYPE_* constants.", "source": "juraj_google_style"} +{"code": "def to_hdf(self,path,key,mode='a'):\n\n pd.DataFrame(self.serialize()).to_hdf(path,key,mode=mode,format='table',complib='zlib',complevel=9)\n f = h5py.File(path,'r+')\n f[key].attrs[\"microns_per_pixel\"] = float(self.microns_per_pixel) if self.microns_per_pixel is not None else np.nan\n f.close()", "docstring": "Save the CellDataFrame to an hdf5 file.\n\nArgs:\n path (str): the path to save to\n key (str): the name of the location to save it to\n mode (str): write mode", "source": "juraj_google_style"} +{"code": "def _construct_operation_id(self, service_name, protorpc_method_name):\n\n\n # camelCase the ProtoRPC method name\n method_name_camel = util.snake_case_to_headless_camel_case(\n protorpc_method_name)\n\n return '{0}_{1}'.format(service_name, method_name_camel)", "docstring": "Return an operation id for a service method.\n\nArgs:\n service_name: The name of the service.\n protorpc_method_name: The ProtoRPC method name.\n\nReturns:\n A string representing the operation id.", "source": "juraj_google_style"} +{"code": "def expand(self, other):\n\n if len(other) == 2:\n other += other\n mid = len(other) // 2\n self.ll = map(min, self.ll, other[:mid])\n self.ur = map(max, self.ur, other[mid:])", "docstring": "Expands this envelope by the given Envelope or tuple.\n\nArgs:\n other -- Envelope, two-tuple, or four-tuple", "source": "juraj_google_style"} +{"code": "def CSS_setMediaText(self, styleSheetId, range, text):\n\n\t\tassert isinstance(text, (str,)\n\t\t ), \"Argument 'text' must be of type '['str']'. Received type: '%s'\" % type(\n\t\t text)\n\t\tsubdom_funcs = self.synchronous_command('CSS.setMediaText', styleSheetId=\n\t\t styleSheetId, range=range, text=text)\n\t\treturn subdom_funcs", "docstring": "Function path: CSS.setMediaText\n Domain: CSS\n Method name: setMediaText\n\n Parameters:\n Required arguments:\n 'styleSheetId' (type: StyleSheetId) -> No description\n 'range' (type: SourceRange) -> No description\n 'text' (type: string) -> No description\n\nReturns:\n 'media' (type: CSSMedia) -> The resulting CSS media rule after modification.\n\n Description: Modifies the rule selector.", "source": "juraj_google_style"} +{"code": "def restore_state(self, state):\n\n\n super(ReferenceController, self).restore_state(state)\n\n state_name = state.get('state_name')\n state_version = state.get('state_version')\n\n if state_name != self.STATE_NAME or state_version != self.STATE_VERSION:\n raise ArgumentError(\"Invalid emulated device state name or version\", found=(state_name, state_version),\n expected=(self.STATE_NAME, self.STATE_VERSION))\n\n self.app_info = state.get('app_info', (0, \"0.0\"))\n self.os_info = state.get('os_info', (0, \"0.0\"))\n\n # Notify all subsystems of our intent to restore in case they need to prepare\n self.sensor_log.prepare_for_restore()\n\n # Restore all of the subsystems\n self.remote_bridge.restore(state.get('remote_bridge', {}))\n self.tile_manager.restore(state.get('tile_manager', {}))\n self.config_database.restore(state.get('config_database', {}))\n self.sensor_log.restore(state.get('sensor_log', {}))", "docstring": "Restore the current state of this emulated object.\n\nArgs:\n state (dict): A previously dumped state produced by dump_state.", "source": "juraj_google_style"} +{"code": "def create_object(self, obj_type, payload, return_fields=None):\n\n self._validate_obj_type_or_die(obj_type)\n\n query_params = self._build_query_params(return_fields=return_fields)\n\n url = self._construct_url(obj_type, query_params)\n opts = self._get_request_options(data=payload)\n self._log_request('post', url, opts)\n if(self.session.cookies):\n # the first 'get' or 'post' action will generate a cookie\n # after that, we don't need to re-authenticate\n self.session.auth = None\n r = self.session.post(url, **opts)\n\n self._validate_authorized(r)\n\n if r.status_code != requests.codes.CREATED:\n response = utils.safe_json_load(r.content)\n already_assigned = 'is assigned to another network view'\n if response and already_assigned in response.get('text'):\n exception = ib_ex.InfobloxMemberAlreadyAssigned\n else:\n exception = ib_ex.InfobloxCannotCreateObject\n raise exception(\n response=response,\n obj_type=obj_type,\n content=r.content,\n args=payload,\n code=r.status_code)\n\n return self._parse_reply(r)", "docstring": "Create an Infoblox object of type 'obj_type'\n\nArgs:\n obj_type (str): Infoblox object type,\n e.g. 'network', 'range', etc.\n payload (dict): Payload with data to send\n return_fields (list): List of fields to be returned\n\nReturns:\n The object reference of the newly create object\n\nRaises:\n InfobloxException", "source": "juraj_google_style"} +{"code": "def _ExportEvent(self, output_module, event, deduplicate_events=True):\n\n if event.timestamp != self._export_event_timestamp:\n self._FlushExportBuffer(\n output_module, deduplicate_events=deduplicate_events)\n self._export_event_timestamp = event.timestamp\n\n self._export_event_heap.PushEvent(event)", "docstring": "Exports an event using an output module.\n\nArgs:\n output_module (OutputModule): output module.\n event (EventObject): event.\n deduplicate_events (Optional[bool]): True if events should be\n deduplicated.", "source": "juraj_google_style"} +{"code": "def export_default_scripts(target_folder, source_folder = None, raise_errors = False, verbose=False):\n\n\n scripts_to_load = get_classes_in_folder(source_folder, Script)\n\n if verbose:\n print(('attempt to load {:d} scripts: '.format(len(scripts_to_load))))\n\n loaded_scripts, failed, loaded_instruments = Script.load_and_append(scripts_to_load, raise_errors=raise_errors)\n\n for name, value in loaded_scripts.items():\n filename = os.path.join(target_folder, '{:s}.b26'.format(name))\n value.save_b26(filename)\n\n if verbose:\n print('\\n================================================')\n print('================================================')\n print(('saved {:d} scripts, {:d} failed'.format(len(loaded_scripts), len(failed))))\n if failed != {}:\n for error_name, error in failed.items():\n print(('failed to create script: ', error_name, error))", "docstring": "tries to instantiate all the scripts that are imported in /scripts/__init__.py\n saves each script that could be instantiated into a .b26 file in the folder path\n\nArgs:\n target_folder: target path for .b26 files\n source_folder: location of python script files", "source": "juraj_google_style"} +{"code": "def add_symbol(self, symbol_name, namespace_stack, node, module):\n\n # TODO(nnorwitz): verify symbol_name doesn't contain :: ?\n if namespace_stack:\n # Handle non-global symbols (ie, in some namespace).\n last_namespace = self.namespaces\n for namespace in namespace_stack:\n last_namespace = last_namespace.setdefault(namespace, {})\n else:\n last_namespace = self.namespaces[None]\n return self._add(symbol_name, last_namespace, node, module)", "docstring": "Adds symbol_name defined in namespace_stack to the symbol table.\n\nArgs:\n symbol_name: 'name of the symbol to lookup'\n namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in']\n node: ast.Node that defines this symbol\n module: module (any object) this symbol is defined in\n\nReturns:\n bool(if symbol was *not* already present)", "source": "juraj_google_style"} +{"code": "def range(self, dim, data_range=True, dimension_range=True):\n\n iskdim = self.get_dimension(dim) not in self.vdims\n return super(StatisticsElement, self).range(dim, iskdim, dimension_range)", "docstring": "Return the lower and upper bounds of values along dimension.\n\nArgs:\n dimension: The dimension to compute the range on.\n data_range (bool): Compute range from data values\n dimension_range (bool): Include Dimension ranges\n Whether to include Dimension range and soft_range\n in range calculation\n\nReturns:\n Tuple containing the lower and upper bound", "source": "juraj_google_style"} +{"code": "def _register_preallocated_ips(self, conf):\n\n for dom_name, dom_spec in conf.get('domains', {}).items():\n for idx, nic in enumerate(dom_spec.get('nics', [])):\n if 'ip' not in nic:\n continue\n\n net = conf['nets'][nic['net']]\n if self._subnet_store.is_leasable_subnet(net['gw']):\n nic['ip'] = _create_ip(\n net['gw'], int(nic['ip'].split('.')[-1])\n )\n\n dom_name = dom_spec['name']\n if not _ip_in_subnet(net['gw'], nic['ip']):\n raise RuntimeError(\n \"%s:nic%d's IP [%s] is outside the subnet [%s]\" % (\n dom_name,\n dom_spec['nics'].index(nic),\n nic['ip'],\n net['gw'],\n ),\n )\n\n if nic['ip'] in net['mapping'].values():\n conflict_list = [\n name for name, ip in net['mapping'].items()\n if ip == net['ip']\n ]\n raise RuntimeError(\n 'IP %s was to several domains: %s %s' % (\n nic['ip'],\n dom_name,\n ' '.join(conflict_list),\n ),\n )\n\n self._add_nic_to_mapping(net, dom_spec, nic)", "docstring": "Parse all the domains in the given conf and preallocate all their ips\n into the networks mappings, raising exception on duplicated ips or ips\n out of the allowed ranges\n\n See Also:\n :mod:`lago.subnet_lease`\n\nArgs:\n conf (dict): Configuration spec to parse\n\nReturns:\n None\n\nRaises:\n RuntimeError: if there are any duplicated ips or any ip out of the\n allowed range", "source": "juraj_google_style"} +{"code": "def ensure_proc_terminate(proc):\n\n if isinstance(proc, list):\n for p in proc:\n ensure_proc_terminate(p)\n return\n\n def stop_proc_by_weak_ref(ref):\n proc = ref()\n if proc is None:\n return\n if not proc.is_alive():\n return\n proc.terminate()\n proc.join()\n\n assert isinstance(proc, mp.Process)\n atexit.register(stop_proc_by_weak_ref, weakref.ref(proc))", "docstring": "Make sure processes terminate when main process exit.\n\nArgs:\n proc (multiprocessing.Process or list)", "source": "juraj_google_style"} +{"code": "def get_measurements(region, core_info, data, extra_offset=0):\n\n measurements = []\n clean_core_info = [x for x in core_info if x]\n cores = len(clean_core_info)\n for k in data:\n if k not in [\"1\", \"Region Info\", \"Event\", \"Metric\", \"CPU clock\"]:\n slot = data[k]\n for i in range(cores):\n core = core_info[i]\n idx = extra_offset + i\n if core and slot[idx]:\n measurements.append((region, k, core, slot[idx]))\n\n return measurements", "docstring": "Get the complete measurement info from likwid's region info.\n\nArgs:\n region: The region we took a measurement in.\n core_info: The core information.\n data: The raw data.\n extra_offset (int): default = 0\n\n Returns (list((region, metric, core, value))):\n A list of measurement tuples, a tuple contains the information about\n the region, the metric, the core and the actual value.", "source": "juraj_google_style"} +{"code": "def query(self, queryEngine, query=None, vendorSpecific=None, **kwargs):\n\n response = self.queryResponse(queryEngine, query, vendorSpecific, **kwargs)\n return self._read_stream_response(response)", "docstring": "See Also: queryResponse()\n\nArgs:\n queryEngine:\n query:\n vendorSpecific:\n **kwargs:\n\n Returns:", "source": "juraj_google_style"} +{"code": "def create_cloudwatch_event(app_name, env, region, rules):\n\n session = boto3.Session(profile_name=env, region_name=region)\n cloudwatch_client = session.client('events')\n\n rule_name = rules.get('rule_name')\n schedule = rules.get('schedule')\n rule_description = rules.get('rule_description')\n json_input = rules.get('json_input', {})\n\n if schedule is None:\n LOG.critical('Schedule is required and no schedule is defined!')\n raise InvalidEventConfiguration('Schedule is required and no schedule is defined!')\n\n if rule_name is None:\n LOG.critical('Rule name is required and no rule_name is defined!')\n raise InvalidEventConfiguration('Rule name is required and no rule_name is defined!')\n else:\n LOG.info('%s and %s', app_name, rule_name)\n rule_name = \"{}_{}\".format(app_name, rule_name.replace(' ', '_'))\n\n if rule_description is None:\n rule_description = \"{} - {}\".format(app_name, rule_name)\n\n lambda_arn = get_lambda_arn(app=app_name, account=env, region=region)\n\n # Add lambda permissions\n account_id = get_env_credential(env=env)['accountId']\n principal = \"events.amazonaws.com\"\n statement_id = '{}_cloudwatch_{}'.format(app_name, rule_name)\n source_arn = 'arn:aws:events:{}:{}:rule/{}'.format(region, account_id, rule_name)\n add_lambda_permissions(\n function=lambda_arn,\n statement_id=statement_id,\n action='lambda:InvokeFunction',\n principal=principal,\n source_arn=source_arn,\n env=env,\n region=region, )\n\n # Create Cloudwatch rule\n cloudwatch_client.put_rule(\n Name=rule_name,\n ScheduleExpression=schedule,\n State='ENABLED',\n Description=rule_description, )\n\n targets = []\n # TODO: read this one from file event-config-*.json\n json_payload = '{}'.format(json.dumps(json_input))\n\n target = {\n \"Id\": app_name,\n \"Arn\": lambda_arn,\n \"Input\": json_payload,\n }\n\n targets.append(target)\n\n put_targets_response = cloudwatch_client.put_targets(Rule=rule_name, Targets=targets)\n LOG.debug('Cloudwatch put targets response: %s', put_targets_response)\n\n LOG.info('Created Cloudwatch event \"%s\" with schedule: %s', rule_name, schedule)", "docstring": "Create cloudwatch event for lambda from rules.\n\nArgs:\n app_name (str): name of the lambda function\n env (str): Environment/Account for lambda function\n region (str): AWS region of the lambda function\n rules (dict): Trigger rules from the settings", "source": "juraj_google_style"} +{"code": "def set_pattern_actual_step(self, patternnumber, value):\n\n _checkPatternNumber(patternnumber)\n _checkStepNumber(value)\n\n address = _calculateRegisterAddress('actualstep', patternnumber)\n self.write_register(address, value, 0)", "docstring": "Set the 'actual step' parameter for a given pattern.\n\nArgs:\n * patternnumber (integer): 0-7\n * value (integer): 0-7", "source": "juraj_google_style"} +{"code": "def django_cache_function(timeout: int = 5 * 60,\n cache_key: str = '',\n debug_cache: bool = False):\n\n cache_key = cache_key or None\n\n def decorator(fn):\n def wrapper(*args, **kwargs):\n # - NOTE that Django returns None from cache.get() for \"not in\n # cache\", so can't cache a None value;\n # https://docs.djangoproject.com/en/1.10/topics/cache/#basic-usage # noqa\n # - We need to store a bit more than just the function result\n # anyway, to detect hash collisions when the user doesn't specify\n # the cache_key, so we may as well use that format even if the\n # user does specify the cache_key, and then we can store a None\n # result properly as well.\n if cache_key:\n # User specified a cache key. This is easy.\n call_sig = ''\n _cache_key = cache_key\n check_stored_call_sig = False\n else:\n # User didn't specify a cache key, so we'll do one\n # automatically. Since we do this via a hash, there is a small\n # but non-zero chance of a hash collision.\n call_sig = get_call_signature(fn, args, kwargs)\n _cache_key = make_cache_key(call_sig)\n check_stored_call_sig = True\n if debug_cache:\n log.critical(\"Checking cache for key: \" + _cache_key)\n cache_result_tuple = cache.get(_cache_key) # TALKS TO CACHE HERE\n if cache_result_tuple is None:\n if debug_cache:\n log.debug(\"Cache miss\")\n else:\n if debug_cache:\n log.debug(\"Cache hit\")\n cached_call_sig, func_result = cache_result_tuple\n if (not check_stored_call_sig) or cached_call_sig == call_sig:\n return func_result\n log.warning(\n \"... Cache hit was due to hash collision; cached_call_sig \"\n \"{} != call_sig {}\".format(\n repr(cached_call_sig), repr(call_sig)))\n # If we get here, either it wasn't in the cache, or something\n # was in the cache that matched by cache_key but was actually a\n # hash collision. Either way, we must do the real work.\n func_result = fn(*args, **kwargs)\n cache_result_tuple = (call_sig, func_result)\n cache.set(key=_cache_key, value=cache_result_tuple,\n timeout=timeout) # TALKS TO CACHE HERE\n return func_result\n\n return wrapper\n\n return decorator", "docstring": "Decorator to add caching to a function in Django.\n Uses the Django default cache.\n\nArgs:\n timeout: timeout in seconds; use None for \"never expire\", as 0 means\n \"do not cache\".\n\n cache_key: optional cache key to use (if falsy, we'll invent one)\n debug_cache: show hits/misses?", "source": "juraj_google_style"} +{"code": "def next_population(self, population, fitnesses):\n\n return [self._next_solution() for _ in range(self._population_size)]", "docstring": "Make a new population after each optimization iteration.\n\nArgs:\n population: The population current population of solutions.\n fitnesses: The fitness associated with each solution in the population\n\nReturns:\n list; a list of solutions.", "source": "juraj_google_style"} +{"code": "def windows_from_blocksize(self, blocksize_xy=512):\n\n meta = self._get_template_for_given_resolution(self.dst_res, \"meta\")\n width = meta[\"width\"]\n height = meta[\"height\"]\n blocksize_wins = windows_from_blocksize(blocksize_xy, width, height)\n\n self.windows = np.array([win[1] for win in blocksize_wins])\n self.windows_row = np.array([win[0][0] for win in blocksize_wins])\n self.windows_col = np.array([win[0][1] for win in blocksize_wins])\n return self", "docstring": "Create rasterio.windows.Window instances with given size which fully cover the raster.\n\nArgs:\n blocksize_xy {int or list of two int} -- Size of the window. If one integer is given it defines\n the width and height of the window. If a list of two integers if given the first defines the\n width and the second the height.\n\nReturns:\n None -- But the attributes ``windows``, ``windows_row`` and ``windows_col`` are updated.", "source": "juraj_google_style"} +{"code": "def __cloudflare_request(self, *, account, path, args=None):\n\n if not args:\n args = {}\n\n if not self.cloudflare_initialized[account.account_id]:\n self.cloudflare_session[account.account_id] = requests.Session()\n self.cloudflare_session[account.account_id].headers.update({\n 'X-Auth-Email': account.email,\n 'X-Auth-Key': account.api_key,\n 'Content-Type': 'application/json'\n })\n self.cloudflare_initialized[account.account_id] = True\n\n if 'per_page' not in args:\n args['per_page'] = 100\n\n response = self.cloudflare_session[account.account_id].get(account.endpoint + path, params=args)\n if response.status_code != 200:\n raise CloudFlareError('Request failed: {}'.format(response.text))\n\n return response.json()", "docstring": "Helper function to interact with the CloudFlare API.\n\nArgs:\n account (:obj:`CloudFlareAccount`): CloudFlare Account object\n path (`str`): URL endpoint to communicate with\n args (:obj:`dict` of `str`: `str`): A dictionary of arguments for the endpoint to consume\n\nReturns:\n `dict`", "source": "juraj_google_style"} +{"code": "def diff_xIndex(self, diffs, loc):\n\n chars1 = 0\n chars2 = 0\n last_chars1 = 0\n last_chars2 = 0\n for x in range(len(diffs)):\n (op, text) = diffs[x]\n if op != self.DIFF_INSERT: # Equality or deletion.\n chars1 += len(text)\n if op != self.DIFF_DELETE: # Equality or insertion.\n chars2 += len(text)\n if chars1 > loc: # Overshot the location.\n break\n last_chars1 = chars1\n last_chars2 = chars2\n\n if len(diffs) != x and diffs[x][0] == self.DIFF_DELETE:\n # The location was deleted.\n return last_chars2\n # Add the remaining len(character).\n return last_chars2 + (loc - last_chars1)", "docstring": "loc is a location in text1, compute and return the equivalent location\n in text2. e.g. \"The cat\" vs \"The big cat\", 1->1, 5->8\n\nArgs:\n diffs: Array of diff tuples.\n loc: Location within text1.\n\nReturns:\n Location within text2.", "source": "juraj_google_style"} +{"code": "def notify(self, new_issues, existing_issues, fixed_issues):\n\n if len(new_issues + existing_issues + fixed_issues) > 0:\n maxlen = max(len(x['properties']['source']) for x in (new_issues + existing_issues + fixed_issues)) + 2\n text_tmpl = get_template('domain_hijacking.txt')\n html_tmpl = get_template('domain_hijacking.html')\n issues_text = text_tmpl.render(\n new_issues=new_issues,\n existing_issues=existing_issues,\n fixed_issues=fixed_issues,\n maxlen=maxlen\n )\n issues_html = html_tmpl.render(\n new_issues=new_issues,\n existing_issues=existing_issues,\n fixed_issues=fixed_issues,\n maxlen=maxlen\n )\n\n try:\n send_notification(\n subsystem=self.name,\n recipients=[NotificationContact('email', addr) for addr in self.recipients],\n subject=self.subject,\n body_html=issues_html,\n body_text=issues_text\n )\n except Exception as ex:\n self.log.exception('Failed sending notification email: {}'.format(ex))", "docstring": "Send notifications (email, slack, etc.) for any issues that are currently open or has just been closed\n\nArgs:\n new_issues (`list` of :obj:`DomainHijackIssue`): List of newly discovered issues\n existing_issues (`list` of :obj:`DomainHijackIssue`): List of existing open issues\n fixed_issues (`list` of `dict`): List of fixed issues\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def from_snl(cls, snl):\n\n hist = []\n for h in snl.history:\n d = h.description\n d['_snl'] = {'url': h.url, 'name': h.name}\n hist.append(d)\n return cls(snl.structure, history=hist)", "docstring": "Create TransformedStructure from SNL.\n\nArgs:\n snl (StructureNL): Starting snl\n\nReturns:\n TransformedStructure", "source": "juraj_google_style"} +{"code": "def get_language_stemmer(language):\n\n from lunr.languages import SUPPORTED_LANGUAGES\n from nltk.stem.snowball import SnowballStemmer\n\n return SnowballStemmer(SUPPORTED_LANGUAGES[language])", "docstring": "Retrieves the SnowballStemmer for a particular language.\n\nArgs:\n language (str): ISO-639-1 code of the language.", "source": "juraj_google_style"} +{"code": "def predict(self, df_data, threshold=0.05, **kwargs):\n\n nb_jobs = kwargs.get(\"nb_jobs\", SETTINGS.NB_JOBS)\n list_nodes = list(df_data.columns.values)\n if nb_jobs != 1:\n result_feature_selection = Parallel(n_jobs=nb_jobs)(delayed(self.run_feature_selection)\n (df_data, node, idx, **kwargs)\n for idx, node in enumerate(list_nodes))\n else:\n result_feature_selection = [self.run_feature_selection(df_data, node, idx, **kwargs) for idx, node in enumerate(list_nodes)]\n for idx, i in enumerate(result_feature_selection):\n try:\n i.insert(idx, 0)\n except AttributeError: # if results are numpy arrays\n result_feature_selection[idx] = np.insert(i, idx, 0)\n matrix_results = np.array(result_feature_selection)\n matrix_results *= matrix_results.transpose()\n np.fill_diagonal(matrix_results, 0)\n matrix_results /= 2\n\n graph = nx.Graph()\n\n for (i, j), x in np.ndenumerate(matrix_results):\n if matrix_results[i, j] > threshold:\n graph.add_edge(list_nodes[i], list_nodes[j],\n weight=matrix_results[i, j])\n for node in list_nodes:\n if node not in graph.nodes():\n graph.add_node(node)\n return graph", "docstring": "Predict the skeleton of the graph from raw data.\n\n Returns iteratively the feature selection algorithm on each node.\n\nArgs:\n df_data (pandas.DataFrame): data to construct a graph from\n threshold (float): cutoff value for feature selection scores\n kwargs (dict): additional arguments for algorithms\n\nReturns:\n networkx.Graph: predicted skeleton of the graph.", "source": "juraj_google_style"} +{"code": "def build_defaults(self, defaults_node):\n\n proxy_name = defaults_node.defaults_header.proxy_name.text\n config_block_lines = self.__build_config_block(\n defaults_node.config_block)\n return config.Defaults(\n name=proxy_name,\n config_block=config_block_lines)", "docstring": "parse `defaults` sections, and return a config.Defaults\n\nArgs:\n defaults_node (TreeNode): Description\n\nReturns:\n config.Defaults: an object", "source": "juraj_google_style"} +{"code": "def _federation_indicators(catalog, central_catalog,\n identifier_search=False):\n\n result = {\n 'datasets_federados_cant': None,\n 'datasets_federados_pct': None,\n 'datasets_no_federados_cant': None,\n 'datasets_federados_eliminados_cant': None,\n 'distribuciones_federadas_cant': None,\n 'datasets_federados_eliminados': [],\n 'datasets_no_federados': [],\n 'datasets_federados': [],\n\n }\n try:\n central_catalog = readers.read_catalog(central_catalog)\n except Exception as e:\n msg = u'Error leyendo el catálogo central: {}'.format(str(e))\n logger.error(msg)\n return result\n\n generator = FederationIndicatorsGenerator(central_catalog, catalog,\n id_based=identifier_search)\n result.update({\n 'datasets_federados_cant':\n generator.datasets_federados_cant(),\n 'datasets_no_federados_cant':\n generator.datasets_no_federados_cant(),\n 'datasets_federados_eliminados_cant':\n generator.datasets_federados_eliminados_cant(),\n 'datasets_federados_eliminados':\n generator.datasets_federados_eliminados(),\n 'datasets_no_federados':\n generator.datasets_no_federados(),\n 'datasets_federados':\n generator.datasets_federados(),\n 'datasets_federados_pct':\n generator.datasets_federados_pct(),\n 'distribuciones_federadas_cant':\n generator.distribuciones_federadas_cant()\n })\n return result", "docstring": "Cuenta la cantidad de datasets incluídos tanto en la lista\n 'catalogs' como en el catálogo central, y genera indicadores a partir\n de esa información.\n\nArgs:\n catalog (dict): catálogo ya parseado\n central_catalog (str o dict): ruta a catálogo central, o un dict\n con el catálogo ya parseado", "source": "juraj_google_style"} +{"code": "def pool_delete(self, pool_id):\n\n return self._get('pools/{0}.json'.format(pool_id), method='DELETE',\n auth=True)", "docstring": "Delete a pool (Requires login) (UNTESTED) (Moderator+).\n\n Parameters:\n pool_id (int): Where pool_id is the pool id.", "source": "juraj_google_style"} +{"code": "def put(self, resource):\n\n\n endpoint = self.endpoint\n\n if resource.id:\n endpoint = self._build_url(endpoint, resource.id)\n\n response = self.api.execute(\"PUT\", endpoint, json=resource.as_dict())\n\n if not response.ok:\n raise Error.parse(response.json())\n\n return self._cls.parse(response.json())", "docstring": "Edits an existing resource\n\nArgs:\n resource - gophish.models.Model - The resource instance", "source": "juraj_google_style"} +{"code": "def pop_chunk(self, chunk_max_size):\n\n if self._total_length < chunk_max_size:\n # fastpath (the whole queue fit in a single chunk)\n res = self._tobytes()\n self.clear()\n return res\n first_iteration = True\n while True:\n try:\n data = self._deque.popleft()\n data_length = len(data)\n self._total_length -= data_length\n if first_iteration:\n # first iteration\n if data_length == chunk_max_size:\n # we are lucky !\n return data\n elif data_length > chunk_max_size:\n # we have enough data at first iteration\n # => fast path optimization\n view = self._get_pointer_or_memoryview(data,\n data_length)\n self.appendleft(view[chunk_max_size:])\n return view[:chunk_max_size]\n else:\n # no single iteration fast path optimization :-(\n # let's use a WriteBuffer to build the result chunk\n chunk_write_buffer = WriteBuffer()\n else:\n # not first iteration\n if chunk_write_buffer._total_length + data_length \\\n > chunk_max_size:\n view = self._get_pointer_or_memoryview(data,\n data_length)\n limit = chunk_max_size - \\\n chunk_write_buffer._total_length - data_length\n self.appendleft(view[limit:])\n data = view[:limit]\n chunk_write_buffer.append(data)\n if chunk_write_buffer._total_length >= chunk_max_size:\n break\n except IndexError:\n # the buffer is empty (so no memoryview inside)\n self._has_view = False\n break\n first_iteration = False\n return chunk_write_buffer._tobytes()", "docstring": "Pops a chunk of the given max size.\n\n Optimized to avoid too much string copies.\n\nArgs:\n chunk_max_size (int): max size of the returned chunk.\n\nReturns:\n string (bytes) with a size <= chunk_max_size.", "source": "juraj_google_style"} +{"code": "def rtt_get_num_down_buffers(self):\n\n cmd = enums.JLinkRTTCommand.GETNUMBUF\n dir = ctypes.c_int(enums.JLinkRTTDirection.DOWN)\n return self.rtt_control(cmd, dir)", "docstring": "After starting RTT, get the current number of down buffers.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n The number of configured down buffers on the target.\n\nRaises:\n JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails.", "source": "juraj_google_style"} +{"code": "def get_network_usage(access_token, subscription_id, location):\n\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/providers/Microsoft.Network/locations/', location,\n '/usages?api-version=', NETWORK_API])\n return do_get(endpoint, access_token)", "docstring": "List network usage and limits for a location.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n location (str): Azure data center location. E.g. westus.\n\nReturns:\n HTTP response. JSON body of network usage.", "source": "juraj_google_style"} +{"code": "def _create_events_writer(self, directory):\n\n total_size = 0\n events_files = self._fetch_events_files_on_disk()\n for file_name in events_files:\n file_path = os.path.join(self._events_directory, file_name)\n total_size += tf.io.gfile.stat(file_path).length\n\n if total_size >= self.total_file_size_cap_bytes:\n # The total size written to disk is too big. Delete events files until\n # the size is below the cap.\n for file_name in events_files:\n if total_size < self.total_file_size_cap_bytes:\n break\n\n file_path = os.path.join(self._events_directory, file_name)\n file_size = tf.io.gfile.stat(file_path).length\n try:\n tf.io.gfile.remove(file_path)\n total_size -= file_size\n logger.info(\n \"Deleted %s because events files take up over %d bytes\",\n file_path, self.total_file_size_cap_bytes)\n except IOError as err:\n logger.error(\"Deleting %s failed: %s\", file_path, err)\n\n # We increment this index because each events writer must differ in prefix.\n self._events_file_count += 1\n file_path = \"%s.%d.%d\" % (\n os.path.join(directory, DEBUGGER_EVENTS_FILE_STARTING_TEXT),\n time.time(), self._events_file_count)\n logger.info(\"Creating events file %s\", file_path)\n return pywrap_tensorflow.EventsWriter(tf.compat.as_bytes(file_path))", "docstring": "Creates a new events writer.\n\nArgs:\n directory: The directory in which to write files containing events.\n\nReturns:\n A new events writer, which corresponds to a new events file.", "source": "juraj_google_style"} +{"code": "def calculate_oobatake_dH(seq, temp):\n\n\n seq = ssbio.protein.sequence.utils.cast_to_str(seq)\n\n dH = 0\n temp += 273.15\n T0 = 298.15\n for aa in seq:\n H0 = oobatake_dictionary[aa]['dH'] * 1000\n dH += H0\n return dH + _sum_of_dCp(seq) * (temp - T0)", "docstring": "Get dH using Oobatake method in units cal/mol.\n\nArgs:\n seq (str, Seq, SeqRecord): Amino acid sequence\n temp (float): Temperature in degrees C\n\nReturns:\n float: dH in units cal/mol", "source": "juraj_google_style"} +{"code": "def RegisterHelper(cls, resolver_helper):\n\n if resolver_helper.type_indicator in cls._resolver_helpers:\n raise KeyError((\n 'Resolver helper object already set for type indicator: '\n '{0!s}.').format(resolver_helper.type_indicator))\n\n cls._resolver_helpers[resolver_helper.type_indicator] = resolver_helper", "docstring": "Registers a path specification resolver helper.\n\nArgs:\n resolver_helper (ResolverHelper): resolver helper.\n\nRaises:\n KeyError: if resolver helper object is already set for the corresponding\n type indicator.", "source": "juraj_google_style"} +{"code": "def getline(self, lnum=None):\n\n return self._vim.current.buffer[lnum] if lnum else self._vim.current.line", "docstring": "Get a line from the current buffer.\n\nArgs:\n lnum (Optional[str]): Number of the line to get, current if ``None``.\n\n Todo:\n - Give this more behavior of Vim ``getline()``?\n - ``buffer[index]`` is zero-based, this is probably too confusing", "source": "juraj_google_style"} +{"code": "def corpus_token_counts(\n text_filepattern, corpus_max_lines, split_on_newlines=True):\n\n counts = collections.Counter()\n for doc in _read_filepattern(\n text_filepattern,\n max_lines=corpus_max_lines,\n split_on_newlines=split_on_newlines):\n counts.update(encode(_native_to_unicode(doc)))\n\n mlperf_log.transformer_print(\n key=mlperf_log.PREPROC_VOCAB_SIZE, value=len(counts))\n return counts", "docstring": "Read the corpus and compute a dictionary of token counts.\n\nArgs:\n text_filepattern: A pattern matching one or more files.\n corpus_max_lines: An integer; maximum total lines to read.\n split_on_newlines: A boolean. If true, then split files by lines and strip\n leading and trailing whitespace from each line. Otherwise, treat each\n file as a single string.\n\nReturns:\n a dictionary mapping token to count.", "source": "juraj_google_style"} +{"code": "def __init__(self, fut, file_obj, tid=None):\n\n super().__init__()\n self._tid = tid\n if isinstance(file_obj, str):\n self.file_obj = File(file_obj)\n elif isinstance(file_obj, File):\n self.file_obj = file_obj\n else:\n raise ValueError(\"DataFuture must be initialized with a str or File\")\n self.parent = fut\n self._exception = None\n\n if fut is None:\n logger.debug(\"Setting result to filepath since no future was passed\")\n self.set_result(self.file_obj)\n\n else:\n if isinstance(fut, Future):\n self.parent.add_done_callback(self.parent_callback)\n else:\n raise NotFutureError(\"DataFuture can be created only with a FunctionFuture on None\")\n\n logger.debug(\"Creating DataFuture with parent: %s\", self.parent)\n logger.debug(\"Filepath: %s\", self.filepath)", "docstring": "Construct the DataFuture object.\n\n If the file_obj is a string convert to a File.\n\nArgs:\n - fut (AppFuture) : AppFuture that this DataFuture will track\n - file_obj (string/File obj) : Something representing file(s)\n\n Kwargs:\n - tid (task_id) : Task id that this DataFuture tracks", "source": "juraj_google_style"} +{"code": "def __init__(self, time: Timestamp, duration: Union[Duration, timedelta],\n operation: ops.Operation) -> None:\n\n self.time = time\n self.duration = Duration.create(duration)\n self.operation = operation", "docstring": "Initializes the scheduled operation.\n\nArgs:\n time: When the operation starts.\n duration: How long the operation lasts.\n operation: The operation.", "source": "juraj_google_style"} +{"code": "def destroy(ads):\n\n for ad in ads:\n try:\n ad.services.stop_all()\n except:\n ad.log.exception('Failed to clean up properly.')", "docstring": "Cleans up AndroidDevice objects.\n\nArgs:\n ads: A list of AndroidDevice objects.", "source": "juraj_google_style"} +{"code": "def list_runs(self, project, entity=None):\n\n query = gql()\n return self._flatten_edges(self.gql(query, variable_values={\n 'entity': entity or self.settings('entity'),\n 'model': project or self.settings('project')})['model']['buckets'])", "docstring": "Lists runs in W&B scoped by project.\n\nArgs:\n project (str): The project to scope the runs to\n entity (str, optional): The entity to scope this project to. Defaults to public models\n\nReturns:\n [{\"id\",name\",\"description\"}]", "source": "juraj_google_style"} +{"code": "def ssh(container, cmd='', user='root', password='root'):\n\n ip = get_ip(container)\n ssh_cmd = 'sshpass -p \\'%s\\' ssh -A -t -o StrictHostKeyChecking=no \\'%s\\'@%s' % (password, user, ip)\n local('ssh -A -t -o StrictHostKeyChecking=no -i \"%s\" %s@%s %s %s' % (\n env.key_filename, env.user, env.host, ssh_cmd, cmd))", "docstring": "SSH into a running container, using the host as a jump host. This requires\n the container to have a running sshd process.\n\nArgs:\n * container: Container name or ID\n * cmd='': Command to run in the container\n * user='root': SSH username\n * password='root': SSH password", "source": "juraj_google_style"} +{"code": "def begin_block(self, req_begin_block):\n\n self.abort_if_abci_chain_is_not_synced()\n\n chain_shift = 0 if self.chain is None else self.chain['height']\n logger.debug('BEGIN BLOCK, height:%s, num_txs:%s',\n req_begin_block.header.height + chain_shift,\n req_begin_block.header.num_txs)\n\n self.block_txn_ids = []\n self.block_transactions = []\n return ResponseBeginBlock()", "docstring": "Initialize list of transaction.\n\nArgs:\n req_begin_block: block object which contains block header\n and block hash.", "source": "juraj_google_style"} +{"code": "def get_json_qry_item(dataset, param, no_key=False):\n\n\n def get_dataset_vals(ds, key, filter_tup=tuple()):\n def reduce_list(value):\n if isinstance(value, list):\n if len(value) == 1:\n return value[0]\n return value\n\n def merge_list(value):\n if isinstance(value, list):\n rtn_list = []\n for item in value:\n if isinstance(item, list):\n rtn_list += item\n else:\n rtn_list.append(item)\n try:\n return list(set(rtn_list))\n except TypeError:\n return rtn_list\n return value\n\n def test_elem(elem, filter_tup):\n search_lst = elem\n if isinstance(elem, dict):\n search_lst = elem.get(filter_tup[0], [])\n if filter_tup[2] == '=':\n try:\n if elem.subject == filter_tup[1]:\n return True\n except AttributeError:\n pass\n test_lst = [item for item in search_lst \\\n if (isinstance(item, dict) \\\n and item.subject == filter_tup[1]) \\\n or item == filter_tup[1]]\n if test_lst:\n return True\n return False\n\n def filter_list(ds, key, filter_tup):\n rtn_list = ds\n if key:\n rtn_list = merge_list([reduce_list(reduce_list(elem)[key]) \\\n for elem in ds\n if isinstance(reduce_list(elem), dict)\n and reduce_list(elem).get(key)])\n if filter_tup:\n return [elem for elem in rtn_list \\\n if test_elem(elem, filter_tup)]\n return rtn_list\n\n if isinstance(ds, list):\n return filter_list(ds, key, filter_tup)\n elif isinstance(ds, dict):\n search_dict = ds\n if key:\n search_dict = ds.get(key,[])\n if filter_tup:\n datalist = []\n for elem in search_dict:\n if filter_tup[2] == \"=\":\n # pdb.set_trace()\n if filter_tup[1] in elem.get(filter_tup[0], []):\n if isinstance(elem, list):\n datalist += elem\n else:\n datalist.append(elem)\n elif filter_tup[2] == \"!=\":\n if filter_tup[1] not in elem.get(filter_tup[0], []):\n datalist.append(elem)\n return datalist\n # return [elem for elem in ds[key] \\\n # if filter_tup[1] in elem.get(filter_tup[0], []) \\\n # and elem]\n return merge_list(search_dict)\n if param == \"*\":\n return dataset\n try:\n if param.startswith(\"=\"):\n # if the dataset length is '0' consider it a false match\n if dataset:\n return [pyrdf(param[1:])]\n return []\n except AttributeError:\n pass\n if hasattr(param, 'parsed_tree'):\n param = param.parsed_tree\n\n if hasattr(param, 'selector'):\n if no_key:\n key = None\n else:\n key = get_element(param.selector)\n rtn_obj = None\n if hasattr(param, 'ident'):\n if key:\n rtn_obj = get_dataset_vals(dataset,\n key,\n ('rdf_type',\n param.ident, \"=\"))\n elif param.ident in dataset.get('rdf_type', []):\n rtn_obj = dataset\n else:\n rtn_obj = [value for value in dataset.values()\n if param.ident in value.get('rdf_type', [])]\n # pdb.set_trace()\n elif hasattr(param, 'attrib'):\n # if param.parsed_tree.attrib == 'bf_role':\n # pdb.set_trace()\n rtn_obj = get_dataset_vals(dataset,\n key,\n (param.attrib,\n param.value,\n param.operator))\n if rtn_obj is not None:\n if hasattr(param, 'selector') \\\n and hasattr(param.selector, 'selector') \\\n and rtn_obj:\n rtn_obj = get_json_qry_item(rtn_obj, param.selector, True)\n return rtn_obj\n if key:\n return dataset[key]\n else:\n return dataset\n elif hasattr(param, 'element'):\n key = param.element\n return get_dataset_vals(dataset, key)", "docstring": "reads the paramater and returns the selected element\n\nArgs:\n dataset: the dataset to search\n param: the paramater to search by\n no_key: wheather to use the 'param' 'element' to filter the list.\n This is passed True after the first run during recurssive call\n when the key has already been used to select subset of the\n dataset", "source": "juraj_google_style"} +{"code": "def get_uri_parts(self, value):\n\n if value.startswith('pyuri_'):\n value = self.rpyhttp(value)\n parts = self.parse_uri(value)\n try:\n return (self.ns_dict[parts[0]], parts[1])\n except KeyError:\n try:\n return (self.ns_dict[parts[0].lower()], parts[1])\n except KeyError:\n return ((None, parts[0]), parts[1])", "docstring": "takes an value and returns a tuple of the parts\n\nArgs:\n value: a uri in any form pyuri, ttl or full IRI", "source": "juraj_google_style"} +{"code": "def has_checked_field(self, locator, **kwargs):\n\n\n kwargs[\"checked\"] = True\n return self.has_selector(\"field\", locator, **kwargs)", "docstring": "Checks if the page or current node has a radio button or checkbox with the given label,\n value, or id, that is currently checked.\n\nArgs:\n locator (str): The label, name, or id of a checked field.\n **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.\n\nReturns:\n bool: Whether it exists.", "source": "juraj_google_style"} +{"code": "def __init__(self,\n coupling_map,\n initial_layout=None,\n trials=20,\n seed=None):\n\n super().__init__()\n self.coupling_map = coupling_map\n self.initial_layout = initial_layout\n self.trials = trials\n self.seed = seed\n\n self.requires.append(BarrierBeforeFinalMeasurements())", "docstring": "Maps a DAGCircuit onto a `coupling_map` using swap gates.\n\nArgs:\n coupling_map (CouplingMap): Directed graph represented a coupling map.\n initial_layout (Layout): initial layout of qubits in mapping\n trials (int): the number of attempts the randomized algorithm makes.\n seed (int): initial seed.", "source": "juraj_google_style"} +{"code": "def SetProtocol(self, protocol):\n\n protocol = protocol.lower().strip()\n if protocol not in ['http', 'https']:\n raise ValueError('Invalid protocol specified for Viper lookup')\n self._analyzer.SetProtocol(protocol)", "docstring": "Sets the protocol that will be used to query Viper.\n\nArgs:\n protocol (str): protocol to use to query Viper. Either 'http' or 'https'.\n\nRaises:\n ValueError: If an invalid protocol is selected.", "source": "juraj_google_style"} +{"code": "def _register_callback(self, cb):\n\n if isinstance(cb, (list, tuple)):\n for x in cb:\n self._register_callback(x)\n return\n assert isinstance(cb, Callback), cb\n assert not isinstance(self._callbacks, Callbacks), \\\n \"Cannot register more callbacks after trainer was setup!\"\n if not self.is_chief and cb.chief_only:\n logger.warn(\"Callback {} is chief-only, skipped.\".format(str(cb)))\n return False\n else:\n self._callbacks.append(cb)\n return True", "docstring": "Register callbacks to the trainer.\n It can only be called before :meth:`Trainer.train()`.\n\nArgs:\n cb (Callback or [Callback]): a callback or a list of callbacks\n\nReturns:\n succeed or not", "source": "juraj_google_style"} +{"code": "def _wrap_callback_errors(callback, message):\n\n try:\n callback(message)\n except Exception:\n # Note: the likelihood of this failing is extremely low. This just adds\n # a message to a queue, so if this doesn't work the world is in an\n # unrecoverable state and this thread should just bail.\n _LOGGER.exception(\n \"Top-level exception occurred in callback while processing a \" \"message\"\n )\n message.nack()", "docstring": "Wraps a user callback so that if an exception occurs the message is\n nacked.\n\nArgs:\n callback (Callable[None, Message]): The user callback.\n message (~Message): The Pub/Sub message.", "source": "juraj_google_style"} +{"code": "def _get_prop_from_modelclass(modelclass, name):\n\n if name == '__key__':\n return modelclass._key\n\n parts = name.split('.')\n part, more = parts[0], parts[1:]\n prop = modelclass._properties.get(part)\n if prop is None:\n if issubclass(modelclass, model.Expando):\n prop = model.GenericProperty(part)\n else:\n raise TypeError('Model %s has no property named %r' %\n (modelclass._get_kind(), part))\n\n while more:\n part = more.pop(0)\n if not isinstance(prop, model.StructuredProperty):\n raise TypeError('Model %s has no property named %r' %\n (modelclass._get_kind(), part))\n maybe = getattr(prop, part, None)\n if isinstance(maybe, model.Property) and maybe._name == part:\n prop = maybe\n else:\n maybe = prop._modelclass._properties.get(part)\n if maybe is not None:\n # Must get it this way to get the copy with the long name.\n # (See StructuredProperty.__getattr__() for details.)\n prop = getattr(prop, maybe._code_name)\n else:\n if issubclass(prop._modelclass, model.Expando) and not more:\n prop = model.GenericProperty()\n prop._name = name # Bypass the restriction on dots.\n else:\n raise KeyError('Model %s has no property named %r' %\n (prop._modelclass._get_kind(), part))\n\n return prop", "docstring": "Helper for FQL parsing to turn a property name into a property object.\n\nArgs:\n modelclass: The model class specified in the query.\n name: The property name. This may contain dots which indicate\n sub-properties of structured properties.\n\nReturns:\n A Property object.\n\nRaises:\n KeyError if the property doesn't exist and the model clas doesn't\n derive from Expando.", "source": "juraj_google_style"} +{"code": "def resolve(self, pid, vendorSpecific=None):\n\n response = self.resolveResponse(pid, vendorSpecific)\n return self._read_dataone_type_response(\n response, 'ObjectLocationList', response_is_303_redirect=True\n )", "docstring": "See Also: resolveResponse()\n\nArgs:\n pid:\n vendorSpecific:\n\n Returns:", "source": "juraj_google_style"} +{"code": "def GetUsernameForPath(self, path):\n\n path = path.lower()\n\n user_accounts = self._user_accounts.get(self.CURRENT_SESSION, {})\n for user_account in iter(user_accounts.values()):\n if not user_account.user_directory:\n continue\n\n user_directory = user_account.user_directory.lower()\n if path.startswith(user_directory):\n return user_account.username\n\n return None", "docstring": "Retrieves a username for a specific path.\n\n This is determining if a specific path is within a user's directory and\n returning the username of the user if so.\n\nArgs:\n path (str): path.\n\nReturns:\n str: username or None if the path does not appear to be within a user's\n directory.", "source": "juraj_google_style"} +{"code": "def get_data_path(self, filename, env_prefix=None):\n\n if env_prefix == None:\n target_file = filename\n else:\n target_file = os.path.join(env_prefix, filename)\n\n if os.path.exists(os.path.join(self._data_path, target_file)):\n return os.path.join(self._data_path, target_file)\n else:\n raise DataNotFoundError(\n u(\"Cannot find data file: {0}\").format(target_file))", "docstring": "Get data path.\n\nArgs:\n filename (string) : Name of file inside of /data folder to retrieve.\n\n Kwargs:\n env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa\n\nReturns:\n String - path to file.\n\n Usage::\n\n open(WTF_DATA_MANAGER.get_data_path('testdata.csv')\n\n Note: WTF_DATA_MANAGER is a provided global instance of DataManager", "source": "juraj_google_style"} +{"code": "def serialize_example(transformed_json_data, info_dict):\n\n import six\n import tensorflow as tf\n\n def _make_int64_list(x):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=x))\n def _make_bytes_list(x):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=x))\n def _make_float_list(x):\n return tf.train.Feature(float_list=tf.train.FloatList(value=x))\n\n if sorted(six.iterkeys(transformed_json_data)) != sorted(six.iterkeys(info_dict)):\n raise ValueError('Keys do not match %s, %s' % (list(six.iterkeys(transformed_json_data)),\n list(six.iterkeys(info_dict))))\n\n ex_dict = {}\n for name, info in six.iteritems(info_dict):\n if info['dtype'] == tf.int64:\n ex_dict[name] = _make_int64_list(transformed_json_data[name])\n elif info['dtype'] == tf.float32:\n ex_dict[name] = _make_float_list(transformed_json_data[name])\n elif info['dtype'] == tf.string:\n ex_dict[name] = _make_bytes_list(transformed_json_data[name]) \n else:\n raise ValueError('Unsupported data type %s' % info['dtype'])\n\n ex = tf.train.Example(features=tf.train.Features(feature=ex_dict))\n return ex.SerializeToString()", "docstring": "Makes a serialized tf.example.\n\nArgs:\n transformed_json_data: dict of transformed data.\n info_dict: output of feature_transforms.get_transfrormed_feature_info()\n\nReturns:\n The serialized tf.example version of transformed_json_data.", "source": "juraj_google_style"} +{"code": "def inference(self, observed_arr):\n\n if observed_arr.ndim != 2:\n observed_arr = observed_arr.reshape((observed_arr.shape[0], -1))\n\n pred_arr = self.__nn.inference(observed_arr)\n return pred_arr", "docstring": "Draws samples from the `fake` distribution.\n\nArgs:\n observed_arr: `np.ndarray` of observed data points.\n\nReturns:\n `np.ndarray` of inferenced.", "source": "juraj_google_style"} +{"code": "def money(s, thousand_sep=\".\", decimal_sep=\",\"):\n\n s = s.replace(thousand_sep, \"\")\n s = s.replace(decimal_sep, \".\")\n return Decimal(s)", "docstring": "Converts money amount in string to a Decimal object.\n\n With the default arguments, the format is expected to be\n ``-38.500,00``, where dots separate thousands and comma the decimals.\n\nArgs:\n thousand_sep: Separator for thousands.\n decimal_sep: Separator for decimals.\n\nReturns:\n A ``Decimal`` object of the string encoded money amount.", "source": "juraj_google_style"} +{"code": "def repay_funding(self, amount, currency):\n\n params = {\n 'amount': amount,\n 'currency': currency # example: USD\n }\n return self._send_message('post', '/funding/repay',\n data=json.dumps(params))", "docstring": "Repay funding. Repays the older funding records first.\n\nArgs:\n amount (int): Amount of currency to repay\n currency (str): The currency, example USD\n\nReturns:\n Not specified by cbpro.", "source": "juraj_google_style"} +{"code": "def mark_backward(output_tensor, used_node_names):\n\n op = output_tensor.op\n if op.name in used_node_names:\n return\n used_node_names.add(op.name)\n for input_tensor in op.inputs:\n mark_backward(input_tensor, used_node_names)\n for control_input_op in op.control_inputs:\n used_node_names.add(control_input_op.name)\n for input_tensor in control_input_op.inputs:\n mark_backward(input_tensor, used_node_names)", "docstring": "Function to propagate backwards in the graph and mark nodes as used.\n\n Traverses recursively through the graph from the end tensor, through the op\n that generates the tensor, and then to the input tensors that feed the op.\n Nodes encountered are stored in used_node_names.\n\nArgs:\n output_tensor: A Tensor which we start the propagation.\n used_node_names: A list of strings, stores the name of nodes we've marked as\n visited.", "source": "juraj_google_style"} +{"code": "def get_product_value(self, value_name, wanted_type=None):\n\n if not self.__reg_products_handle:\n return None\n subkey, search_value_name = os.path.split(value_name)\n try:\n if subkey:\n\n handle = win32api.RegOpenKeyEx( # pylint: disable=no-member\n self.__reg_products_handle,\n subkey,\n 0,\n win32con.KEY_READ | self.__reg_32bit_access)\n item_value, item_type = self.__reg_query_value(handle, search_value_name)\n win32api.RegCloseKey(handle) # pylint: disable=no-member\n else:\n item_value, item_type = \\\n win32api.RegQueryValueEx(self.__reg_products_handle, value_name) # pylint: disable=no-member\n except pywintypes.error as exc: # pylint: disable=no-member\n if exc.winerror == winerror.ERROR_FILE_NOT_FOUND:\n # Not Found\n return None\n raise\n\n if wanted_type and item_type not in self.__reg_types[wanted_type]:\n item_value = None\n return item_value", "docstring": "For the product section of the registry return the name value.\n\nArgs:\n value_name (str): Registry value name.\n wanted_type (str):\n The type of value wanted if the type does not match\n None is return. wanted_type support values are\n ``str`` ``int`` ``list`` ``bytes``.\n\nReturns:\n value: Value requested or ``None`` if not found.", "source": "juraj_google_style"} +{"code": "def step(self, actions):\n\n\n observations, raw_rewards, dones, infos = self._step(actions)\n\n # Process rewards.\n raw_rewards = raw_rewards.astype(np.float32)\n processed_rewards = self.process_rewards(raw_rewards)\n\n # Process observations.\n processed_observations = self.process_observations(observations)\n\n # Record history.\n self.trajectories.step(processed_observations, raw_rewards,\n processed_rewards, dones, actions)\n\n return processed_observations, processed_rewards, dones, infos", "docstring": "Takes a step in all environments.\n\n Subclasses should override _step to do the actual reset if something other\n than the default implementation is desired.\n\nArgs:\n actions: Batch of actions.\n\nReturns:\n (preprocessed_observations, processed_rewards, dones, infos).", "source": "juraj_google_style"} +{"code": "def enable(self, key_id, **kwargs):\n\n path = '%s/%s/enable' % (self.path, key_id)\n self.gitlab.http_post(path, **kwargs)", "docstring": "Enable a deploy key for a project.\n\nArgs:\n key_id (int): The ID of the key to enable\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabProjectDeployKeyError: If the key could not be enabled", "source": "juraj_google_style"} +{"code": "def download(self, url, destination_path):\n\n self._pbar_url.update_total(1)\n future = self._executor.submit(self._sync_download, url, destination_path)\n return promise.Promise.resolve(future)", "docstring": "Download url to given path.\n\n Returns Promise -> sha256 of downloaded file.\n\nArgs:\n url: address of resource to download.\n destination_path: `str`, path to directory where to download the resource.\n\nReturns:\n Promise obj -> (`str`, int): (downloaded object checksum, size in bytes).", "source": "juraj_google_style"} +{"code": "def __init__(\n self, resolver_context, file_system, path_spec, is_root=False,\n is_virtual=False):\n\n compressed_stream = resolver.Resolver.OpenFileObject(\n path_spec, resolver_context=resolver_context)\n if not compressed_stream:\n raise errors.BackEndError(\n 'Unable to open compressed stream: {0:s}.'.format(\n self.path_spec.comparable))\n\n super(CompressedStreamFileEntry, self).__init__(\n resolver_context, file_system, path_spec, is_root=is_root,\n is_virtual=is_virtual)\n self._compressed_stream = compressed_stream\n self.entry_type = definitions.FILE_ENTRY_TYPE_FILE", "docstring": "Initializes a file entry.\n\nArgs:\n resolver_context (Context): resolver context.\n file_system (FileSystem): file system.\n path_spec (PathSpec): path specification.\n is_root (Optional[bool]): True if the file entry is the root file entry\n of the corresponding file system.\n is_virtual (Optional[bool]): True if the file entry is a virtual file\n\nRaises:\n BackEndError: when the compressed stream is missing.", "source": "juraj_google_style"} +{"code": "def __init__(self, name, *, instance, install_script='', image_name='',\n **extra_kwargs):\n\n self._cmd_fn = None\n self._cmd = None\n self._status_fn = None # location of output of last status\n self.last_status = -1\n\n self._can_run = False # indicates that things needed for .run were created\n self.initialize_called = False\n\n self.name = name\n self.instance = instance\n self.install_script = install_script\n self.extra_kwargs = extra_kwargs\n\n self.public_ip = u.get_public_ip(instance)\n self.ip = u.get_ip(instance)\n self.sftp = None\n self._linux_type = 'ubuntu'\n\n # heuristic to tell if I'm using Amazon image name\n # default image has name like 'amzn2-ami-hvm-2.0.20180622.1-x86_64-gp2'\n if 'amzn' in image_name.lower() or 'amazon' in image_name.lower():\n self.log('Detected Amazon Linux image')\n self._linux_type = 'amazon'\n self.run_counter = 0\n\n launch_id = util.random_id()\n self.local_scratch = f\"{TMPDIR}/{name}-{launch_id}\"\n self.remote_scratch = f\"{TMPDIR}/{name}-{launch_id}\"\n\n os.system('mkdir -p ' + self.local_scratch)\n\n self._initialized_fn = f'is_initialized'\n\n # _current_directory tracks current directory on task machine\n # used for uploading without specifying absolute path on target machine\n if self._linux_type == 'ubuntu':\n # self._current_directory = '/home/ubuntu'\n self.ssh_username = 'ubuntu' # default username on task machine\n elif self._linux_type == 'amazon':\n # self._current_directory = '/home/ec2-user'\n self.ssh_username = 'ec2-user'\n self.homedir = '/home/' + self.ssh_username\n\n self.ssh_client = u.ssh_to_task(self)\n self._setup_tmux()\n self._run_raw('mkdir -p ' + self.remote_scratch)\n\n self._can_run = True\n\n if self._is_initialized_fn_present():\n self.log(\"reusing previous initialized state\")\n else:\n self.log(\"running install script\")\n\n # bin/bash needed to make self-executable or use with UserData\n self.install_script = '#!/bin/bash\\n' + self.install_script\n self.install_script += f'\\necho ok > {self._initialized_fn}\\n'\n self.file_write('install.sh', util.shell_add_echo(self.install_script))\n self.run('bash -e install.sh') # fail on errors\n assert self._is_initialized_fn_present(), f\"Install script didn't write to {self._initialized_fn}\"\n\n self._mount_efs()\n self.connect_instructions = f.strip()\n self.log(\"Initialize complete\")\n self.log(self.connect_instructions)", "docstring": "Initializes Task on top of existing AWS instance. Blocks until instance is ready to execute\n shell commands.\n\nArgs:\n name: task name\n instance: ec2.Instance object (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#instance)\n install_script:\n image_name: AWS image name\n **extra_kwargs: unused kwargs (kept for compatibility with other backends)", "source": "juraj_google_style"} +{"code": "def raster_to_asc(raster_f, asc_f):\n\n raster_r = RasterUtilClass.read_raster(raster_f)\n RasterUtilClass.write_asc_file(asc_f, raster_r.data, raster_r.nCols, raster_r.nRows,\n raster_r.geotrans, raster_r.noDataValue)", "docstring": "Converting Raster format to ASCII raster.\n\nArgs:\n raster_f: raster file.\n asc_f: output ASCII file.", "source": "juraj_google_style"} +{"code": "def find_one(self, collection, query):\n\n obj = getattr(self.db, collection)\n result = obj.find_one(query)\n return result", "docstring": "Search a collection for the query provided and return one result. Just\n a raw interface to mongo to do any query you want.\n\nArgs:\n collection: The db collection. See main class documentation.\n query: A mongo find query.\n\nReturns:\n pymongo Cursor object with the results.", "source": "juraj_google_style"} +{"code": "def Parse(self, raw_data):\n\n self.results = raw_data\n for f in self.filters:\n self.results = f.Parse(self.results)\n return self.results", "docstring": "Take the results and yield results that passed through the filters.\n\n The output of each filter is used as the input for successive filters.\n\nArgs:\n raw_data: An iterable series of rdf values.\n\nReturns:\n A list of rdf values that matched all filters.", "source": "juraj_google_style"} +{"code": "def list_source_code(self, context: int = 5) -> None:\n\n self._verify_entrypoint_selected()\n\n current_trace_frame = self.trace_tuples[\n self.current_trace_frame_index\n ].trace_frame\n\n filename = os.path.join(self.repository_directory, current_trace_frame.filename)\n file_lines: List[str] = []\n\n try:\n # Use readlines instead of enumerate(file) because mock_open\n # doesn't support __iter__ until python 3.7.1.\n with open(filename, \"r\") as file:\n file_lines = file.readlines()\n except FileNotFoundError:\n self.warning(f\"Couldn't open {filename}.\")\n return\n\n self._output_file_lines(current_trace_frame, file_lines, context)", "docstring": "Show source code around the current trace frame location.\n\n Parameters:\n context: int number of lines to show above and below trace location\n (default: 5)", "source": "juraj_google_style"} +{"code": "def gen_textfiles_from_filenames(\n filenames: Iterable[str]) -> Generator[TextIO, None, None]:\n\n for filename in filenames:\n with open(filename) as f:\n yield f", "docstring": "Generates file-like objects from a list of filenames.\n\nArgs:\n filenames: iterable of filenames\n\nYields:\n each file as a :class:`TextIO` object", "source": "juraj_google_style"} +{"code": "def summarize(self, document, Abstractor, similarity_filter=None):\n\n if isinstance(document, str) is False:\n raise TypeError(\"The type of document must be str.\")\n\n if isinstance(Abstractor, AbstractableDoc) is False:\n raise TypeError(\"The type of Abstractor must be AbstractableDoc.\")\n\n if isinstance(similarity_filter, SimilarityFilter) is False and similarity_filter is not None:\n raise TypeError(\"The type of similarity_filter must be SimilarityFilter.\")\n\n normalized_sentences = self.listup_sentence(document)\n\n # for filtering similar sentences.\n if similarity_filter is not None:\n normalized_sentences = similarity_filter.similar_filter_r(normalized_sentences)\n\n self.tokenize(document)\n words = self.token\n\n fdist = nltk.FreqDist(words)\n top_n_words = [w[0] for w in fdist.items()][:self.target_n]\n scored_list = self.__closely_associated_score(normalized_sentences, top_n_words)\n filtered_list = Abstractor.filter(scored_list)\n result_list = [normalized_sentences[idx] for (idx, score) in filtered_list]\n result_dict = {\n \"summarize_result\": result_list,\n \"scoring_data\": filtered_list\n }\n return result_dict", "docstring": "Execute summarization.\n\nArgs:\n document: The target document.\n Abstractor: The object of AbstractableDoc.\n similarity_filter The object of SimilarityFilter.\n\nReturns:\n dict data.\n - \"summarize_result\": The list of summarized sentences.,\n - \"scoring_data\": The list of scores.", "source": "juraj_google_style"} +{"code": "def has_register(self, register):\n\n has_reg = False\n if (isinstance(register, QuantumRegister) and\n register in self.qregs):\n has_reg = True\n elif (isinstance(register, ClassicalRegister) and\n register in self.cregs):\n has_reg = True\n return has_reg", "docstring": "Test if this circuit has the register r.\n\nArgs:\n register (Register): a quantum or classical register.\n\nReturns:\n bool: True if the register is contained in this circuit.", "source": "juraj_google_style"} +{"code": "def move_file(src, dest):\n\n try:\n os.replace(src, dest)\n except Exception as ex_replace:\n logger.error(f\"error moving file {src} to \"\n f\"{dest}. {ex_replace}\")\n raise", "docstring": "Move source file to destination.\n\n Overwrites dest.\n\nArgs:\n src: str or path-like. source file\n dest: str or path-like. destination file\n\nReturns:\n None.\n\nRaises:\n FileNotFoundError: out path parent doesn't exist.\n OSError: if any IO operations go wrong.", "source": "juraj_google_style"} +{"code": "def solve_ideal(n,c,t,segments):\n\n model = base_model(n,c,t) # base model for minimizing cost or time\n x,u,C,T = model.data\n\n # store the set of solutions for plotting\n cand = []\n # print(\"optimizing time\"\n model.setObjective(T, \"minimize\")\n stat1 = optimize(model,cand)\n\n # print(\"optimizing cost\"\n model.setObjective(C, \"minimize\")\n stat2 = optimize(model,cand) #find the minimum cost routes\n\n if stat1 != \"optimal\" or stat2 != \"optimal\":\n return []\n\n times = [ti for (ti,ci) in cand]\n costs = [ci for (ti,ci) in cand]\n min_time = min(times)\n min_cost = min(costs)\n # print(\"ideal point:\",min_time,\",\",min_cost\n\n #===============================================================\n # Objective function is f1^2 + f2^2 where f=Sum tx-min_time and g=Sum cx-min_cost\n f1 = model.addVar(vtype=\"C\", name=\"f1\")\n f2 = model.addVar(vtype=\"C\", name=\"f2\")\n\n model.addCons(f1 == T - min_time, \"obj1\")\n model.addCons(f2 == C - min_cost, \"obj2\")\n\n # print(\"optimizing distance to ideal point:\"\n for i in range(segments+1):\n lambda_ = float(i)/segments\n # print(lambda_\n z = model.addVar(name=\"z\")\n Obj = model.addCons(lambda_*f1*f1 + (1-lambda_)*f2*f2 == z)\n model.setObjective(z, \"minimize\")\n optimize(model, cand) # find the minimum cost routes\n return cand", "docstring": "solve_ideal: use ideal point for finding set of solutions for two-objective TSP\n Parameters:\n - n: number of cities\n - c,t: alternative edge weights, to compute two objective functions\n - segments: number of segments for finding various non-dominated solutions\n Returns list of candidate solutions", "source": "juraj_google_style"} +{"code": "def load(self, filething):\n\n\n fileobj = filething.fileobj\n\n try:\n self.info = self._Info(fileobj)\n self.tags = self._Tags(fileobj, self.info)\n self.info._post_tags(fileobj)\n except (error, IOError) as e:\n reraise(self._Error, e, sys.exc_info()[2])\n except EOFError:\n raise self._Error(\"no appropriate stream found\")", "docstring": "load(filething)\n\n Load file information from a filename.\n\nArgs:\n filething (filething)\n\nRaises:\n mutagen.MutagenError", "source": "juraj_google_style"} +{"code": "def test_service(self,\n filename: str = TEST_FILENAME,\n period_ms: int = TEST_PERIOD_MS) -> None:\n\n # A test service. This works! (As long as you can write to the file.)\n def write(msg):\n f.write('{}: {}\\n'.format(arrow.now(), msg))\n f.flush()\n\n self.info(\"Starting test service; writing data periodically to \"\n \"{}\".format(TEST_FILENAME))\n f = open(filename, 'a') # open for append\n write('STARTING')\n retcode = None\n # if the stop event hasn't been fired keep looping\n while retcode != win32event.WAIT_OBJECT_0:\n write('Test data; will now wait {} ms'.format(period_ms))\n # block for a while seconds and listen for a stop event\n retcode = win32event.WaitForSingleObject(self.h_stop_event,\n period_ms)\n write('SHUTTING DOWN')\n f.close()\n self.info(\"Test service FINISHED.\")", "docstring": "A test service.\n\n Writes to a file occasionally, so you can see it's running.\n\nArgs:\n filename: file to write data to periodically\n period_ms: period, in milliseconds", "source": "juraj_google_style"} +{"code": "def pull_screenrecord(self, bit_rate: int = 5000000, time_limit: int = 180, remote: _PATH = '/sdcard/demo.mp4', local: _PATH = 'demo.mp4') -> None:\n\n self.screenrecord(bit_rate, time_limit, filename=remote)\n self.pull(remote, local)", "docstring": "Recording the display of devices running Android 4.4 (API level 19) and higher. Then copy it to your computer.\n\nArgs:\n bit_rate:You can increase the bit rate to improve video quality, but doing so results in larger movie files.\n time_limit: Sets the maximum recording time, in seconds, and the maximum value is 180 (3 minutes).", "source": "juraj_google_style"} +{"code": "def observe(self, value):\n\n self._buffer.append(value)\n if len(self._buffer) == _BUFFER_SIZE:\n self._flush()", "docstring": "Samples an observation's value.\n\nArgs:\n value: A numeric value signifying the value to be sampled.", "source": "juraj_google_style"} +{"code": "def create(configs):\n\n if not configs:\n raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG)\n elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN:\n ads = get_all_instances()\n elif not isinstance(configs, list):\n raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)\n elif isinstance(configs[0], dict):\n # Configs is a list of dicts.\n ads = get_instances_with_configs(configs)\n elif isinstance(configs[0], basestring):\n # Configs is a list of strings representing serials.\n ads = get_instances(configs)\n else:\n raise Error('No valid config found in: %s' % configs)\n valid_ad_identifiers = list_adb_devices() + list_adb_devices_by_usb_id()\n\n for ad in ads:\n if ad.serial not in valid_ad_identifiers:\n raise DeviceError(ad, 'Android device is specified in config but'\n ' is not attached.')\n _start_services_on_ads(ads)\n return ads", "docstring": "Creates AndroidDevice controller objects.\n\nArgs:\n configs: A list of dicts, each representing a configuration for an\n Android device.\n\nReturns:\n A list of AndroidDevice objects.", "source": "juraj_google_style"} +{"code": "def __init__(self, stdout, stderr):\n\n self.out = stdout\n self.err = stderr", "docstring": "Construct an ScpError.\n\nArgs:\n stdout (str): Captured stdout of scp subprocess.\n stderr (str): Captured stderr of scp subprocess.", "source": "juraj_google_style"} +{"code": "def parse(self, filename):\n\n with io.open(filename, 'r', encoding='utf-8') as _:\n lines = _.readlines()\n\n all_source_files = set()\n source_map = {}\n\n lineno = 0\n root = None\n index = None\n cur_level = -1\n parent_queue = []\n\n for line in lines:\n try:\n level, line = dedent(line)\n if line.startswith('#'):\n lineno += 1\n continue\n elif line.startswith('\\\\#'):\n line = line[1:]\n except IndentError as exc:\n error('bad-indent', 'Invalid indentation', filename=filename,\n lineno=lineno, column=exc.column)\n\n if not line:\n lineno += 1\n continue\n\n source_file = dequote(line)\n\n if not source_file:\n lineno += 1\n continue\n\n if source_file in all_source_files:\n error('sitemap-duplicate', 'Filename listed twice',\n filename=filename, lineno=lineno, column=level * 8 + 1)\n\n all_source_files.add(source_file)\n source_map[source_file] = (lineno, level * 8 + 1)\n\n page = OrderedDict()\n\n if root is not None and level == 0:\n error('sitemap-error', 'Sitemaps only support one root',\n filename=filename, lineno=lineno, column=0)\n\n if root is None:\n root = page\n index = source_file\n else:\n lvl_diff = cur_level - level\n while lvl_diff >= 0:\n parent_queue.pop()\n lvl_diff -= 1\n\n parent_queue[-1][source_file] = page\n\n parent_queue.append(page)\n\n cur_level = level\n\n lineno += 1\n\n return Sitemap(root, filename, index, source_map)", "docstring": "Parse a sitemap file.\n\nArgs:\n filename: str, the path to the sitemap file.\n\nReturns:\n Sitemap: the generated sitemap.", "source": "juraj_google_style"} +{"code": "def get_pluggable_module_information(self, id_or_uri):\n\n uri = self._client.build_uri(id_or_uri) + \"/pluggableModuleInformation\"\n return self._client.get(uri)", "docstring": "Gets all the pluggable module information.\n\nArgs:\n id_or_uri: Can be either the interconnect id or uri.\n\nReturns:\n array: dicts of the pluggable module information.", "source": "juraj_google_style"} +{"code": "def get_jwt_dict(jwt_bu64):\n\n jwt_tup = get_jwt_tup(jwt_bu64)\n try:\n jwt_dict = json.loads(jwt_tup[0].decode('utf-8'))\n jwt_dict.update(json.loads(jwt_tup[1].decode('utf-8')))\n jwt_dict['_sig_sha1'] = hashlib.sha1(jwt_tup[2]).hexdigest()\n except TypeError as e:\n raise JwtException('Decode failed. error=\"{}\"'.format(e))\n return jwt_dict", "docstring": "Parse Base64 encoded JWT and return as a dict.\n\n - JWTs contain a set of values serialized to a JSON dict. This decodes the JWT and\n returns it as a dict containing Unicode strings.\n - In addition, a SHA1 hash is added to the dict for convenience.\n\nArgs:\n jwt_bu64: bytes\n JWT, encoded using a a URL safe flavor of Base64.\n\nReturns:\n dict: Values embedded in and derived from the JWT.", "source": "juraj_google_style"} +{"code": "def retryable(a_func, retry_options, **kwargs):\n\n delay_mult = retry_options.backoff_settings.retry_delay_multiplier\n max_delay_millis = retry_options.backoff_settings.max_retry_delay_millis\n has_timeout_settings = _has_timeout_settings(retry_options.backoff_settings)\n\n if has_timeout_settings:\n timeout_mult = retry_options.backoff_settings.rpc_timeout_multiplier\n max_timeout = (retry_options.backoff_settings.max_rpc_timeout_millis /\n _MILLIS_PER_SECOND)\n total_timeout = (retry_options.backoff_settings.total_timeout_millis /\n _MILLIS_PER_SECOND)\n\n def inner(*args):\n\n delay = retry_options.backoff_settings.initial_retry_delay_millis\n exc = errors.RetryError('Retry total timeout exceeded before any'\n 'response was received')\n if has_timeout_settings:\n timeout = (\n retry_options.backoff_settings.initial_rpc_timeout_millis /\n _MILLIS_PER_SECOND)\n\n now = time.time()\n deadline = now + total_timeout\n else:\n timeout = None\n deadline = None\n\n while deadline is None or now < deadline:\n try:\n to_call = add_timeout_arg(a_func, timeout, **kwargs)\n return to_call(*args)\n except Exception as exception: # pylint: disable=broad-except\n code = config.exc_to_code(exception)\n if code not in retry_options.retry_codes:\n raise errors.RetryError(\n 'Exception occurred in retry method that was not'\n ' classified as transient', exception)\n\n exc = errors.RetryError(\n 'Retry total timeout exceeded with exception', exception)\n\n # Sleep a random number which will, on average, equal the\n # expected delay.\n to_sleep = random.uniform(0, delay * 2)\n time.sleep(to_sleep / _MILLIS_PER_SECOND)\n delay = min(delay * delay_mult, max_delay_millis)\n\n if has_timeout_settings:\n now = time.time()\n timeout = min(\n timeout * timeout_mult, max_timeout, deadline - now)\n\n raise exc\n\n return inner", "docstring": "Creates a function equivalent to a_func, but that retries on certain\n exceptions.\n\nArgs:\n a_func (callable): A callable.\n retry_options (RetryOptions): Configures the exceptions upon which the\n callable should retry, and the parameters to the exponential backoff\n retry algorithm.\n kwargs: Addtional arguments passed through to the callable.\n\nReturns:\n Callable: A function that will retry on exception.", "source": "juraj_google_style"} +{"code": "def VShadowPathSpecGetStoreIndex(path_spec):\n\n store_index = getattr(path_spec, 'store_index', None)\n\n if store_index is None:\n location = getattr(path_spec, 'location', None)\n\n if location is None or not location.startswith('/vss'):\n return None\n\n store_index = None\n try:\n store_index = int(location[4:], 10) - 1\n except (TypeError, ValueError):\n pass\n\n if store_index is None or store_index < 0:\n return None\n\n return store_index", "docstring": "Retrieves the store index from the path specification.\n\nArgs:\n path_spec (PathSpec): path specification.\n\nReturns:\n int: store index or None if not available.", "source": "juraj_google_style"} +{"code": "def insert(self, table, insert_obj, ignore=True):\n\n\n if isinstance(insert_obj, pd.DataFrame):\n if insert_obj.empty:\n raise ValueError('The input DataFrame is empty, please check!')\n insert_obj = insert_obj.to_dict(orient='records')\n elif not isinstance(insert_obj, list):\n raise ValueError(\n f\"The {reprlib.repr(insert_obj)} must be list of dicts type!\")\n\n ignore_str = 'IGNORE' if ignore else ''\n return self._session.execute(\n table.__table__.insert().prefix_with(ignore_str), insert_obj)", "docstring": "[insert bulk data]\n\nArgs:\n table {[DeclarativeMeta cls]} -- [reflection of table]\n insert_obj {[pd.DataFrame or list of dicts]} -- [insert_obj]\n\n Keyword Arguments:\n ignore {bool} -- [wether ignore exception or not] (default: {True})\n\nRaises:\n ValueError -- [f\"The {reprlib.repr(insert_obj)} must be list of dicts type!\"]\n\nReturns:\n [type] -- [description]", "source": "juraj_google_style"} +{"code": "def __init__(self, return_type, cl_function_name, parameter_list, cl_code_file,\n var_replace_dict=None, **kwargs):\n\n self._var_replace_dict = var_replace_dict\n\n with open(os.path.abspath(cl_code_file), 'r') as f:\n code = f.read()\n\n if var_replace_dict is not None:\n code = code % var_replace_dict\n\n super().__init__(return_type, cl_function_name, parameter_list, code, **kwargs)\n self._code = code", "docstring": "Create a CL function for a library function.\n\n These functions are not meant to be optimized, but can be used a helper functions in models.\n\nArgs:\n cl_function_name (str): The name of the CL function\n cl_code_file (str): The location of the code file\n var_replace_dict (dict): In the cl_code file these replacements will be made\n (using the % format function of Python)", "source": "juraj_google_style"} +{"code": "def locked_put(self, credentials):\n\n keyring.set_password(self._service_name, self._user_name,\n credentials.to_json())", "docstring": "Write Credentials to file.\n\nArgs:\n credentials: Credentials, the credentials to store.", "source": "juraj_google_style"} +{"code": "def _CompositeMapByteStream(\n self, byte_stream, byte_offset=0, context=None, **unused_kwargs):\n\n elements_data_size = None\n elements_terminator = None\n number_of_elements = None\n\n if self._HasElementsDataSize():\n elements_data_size = self._EvaluateElementsDataSize(context)\n\n element_byte_size = self._element_data_type_definition.GetByteSize()\n if element_byte_size is not None:\n number_of_elements, _ = divmod(elements_data_size, element_byte_size)\n else:\n elements_terminator = (\n self._element_data_type_definition.elements_terminator)\n\n elif self._HasElementsTerminator():\n elements_terminator = self._data_type_definition.elements_terminator\n\n elif self._HasNumberOfElements():\n number_of_elements = self._EvaluateNumberOfElements(context)\n\n if elements_terminator is None and number_of_elements is None:\n raise errors.MappingError(\n 'Unable to determine element terminator or number of elements')\n\n context_state = getattr(context, 'state', {})\n\n elements_data_offset = context_state.get('elements_data_offset', 0)\n element_index = context_state.get('element_index', 0)\n element_value = None\n mapped_values = context_state.get('mapped_values', [])\n size_hints = context_state.get('size_hints', {})\n subcontext = context_state.get('context', None)\n\n if not subcontext:\n subcontext = DataTypeMapContext()\n\n try:\n while byte_stream[byte_offset:]:\n if (number_of_elements is not None and\n element_index == number_of_elements):\n break\n\n if (elements_data_size is not None and\n elements_data_offset >= elements_data_size):\n break\n\n element_value = self._element_data_type_map.MapByteStream(\n byte_stream, byte_offset=byte_offset, context=subcontext)\n\n byte_offset += subcontext.byte_size\n elements_data_offset += subcontext.byte_size\n element_index += 1\n mapped_values.append(element_value)\n\n if (elements_terminator is not None and\n element_value == elements_terminator):\n break\n\n except errors.ByteStreamTooSmallError as exception:\n context_state['context'] = subcontext\n context_state['elements_data_offset'] = elements_data_offset\n context_state['element_index'] = element_index\n context_state['mapped_values'] = mapped_values\n raise errors.ByteStreamTooSmallError(exception)\n\n except Exception as exception:\n raise errors.MappingError(exception)\n\n if number_of_elements is not None and element_index != number_of_elements:\n context_state['context'] = subcontext\n context_state['elements_data_offset'] = elements_data_offset\n context_state['element_index'] = element_index\n context_state['mapped_values'] = mapped_values\n\n error_string = (\n 'Unable to read: {0:s} from byte stream at offset: {1:d} '\n 'with error: missing element: {2:d}').format(\n self._data_type_definition.name, byte_offset, element_index - 1)\n raise errors.ByteStreamTooSmallError(error_string)\n\n if (elements_terminator is not None and\n element_value != elements_terminator and (\n elements_data_size is None or\n elements_data_offset < elements_data_size)):\n byte_stream_size = len(byte_stream)\n\n size_hints[self._data_type_definition.name] = DataTypeMapSizeHint(\n byte_stream_size - byte_offset)\n\n context_state['context'] = subcontext\n context_state['elements_data_offset'] = elements_data_offset\n context_state['element_index'] = element_index\n context_state['mapped_values'] = mapped_values\n context_state['size_hints'] = size_hints\n\n error_string = (\n 'Unable to read: {0:s} from byte stream at offset: {1:d} '\n 'with error: unable to find elements terminator').format(\n self._data_type_definition.name, byte_offset)\n raise errors.ByteStreamTooSmallError(error_string)\n\n if context:\n context.byte_size = elements_data_offset\n context.state = {}\n\n return tuple(mapped_values)", "docstring": "Maps a sequence of composite data types on a byte stream.\n\nArgs:\n byte_stream (bytes): byte stream.\n byte_offset (Optional[int]): offset into the byte stream where to start.\n context (Optional[DataTypeMapContext]): data type map context.\n\nReturns:\n tuple[object, ...]: mapped values.\n\nRaises:\n ByteStreamTooSmallError: if the byte stream is too small.\n MappingError: if the data type definition cannot be mapped on\n the byte stream.", "source": "juraj_google_style"} +{"code": "def query(self, coords, **kwargs):\n\n return super(Lenz2017Query, self).query(coords, **kwargs)", "docstring": "Returns E(B-V), in mags, at the specified location(s) on the sky.\n\nArgs:\n coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.\n\nReturns:\n A float array of the reddening, in magnitudes of E(B-V), at the\n selected coordinates.", "source": "juraj_google_style"} +{"code": "def __init__(self, file_object, encoding='utf-8', end_of_line='\\n'):\n\n super(TextFile, self).__init__()\n self._file_object = file_object\n self._file_object_size = file_object.get_size()\n self._encoding = encoding\n self._end_of_line = end_of_line.encode(self._encoding)\n self._end_of_line_length = len(self._end_of_line)\n self._lines = []\n self._lines_buffer = b''\n self._lines_buffer_offset = 0\n self._current_offset = 0", "docstring": "Initializes the text file.\n\nArgs:\n file_object (FileIO): a file-like object to read from.\n encoding (Optional[str]): text encoding.\n end_of_line (Optional[str]): end of line indicator.", "source": "juraj_google_style"} +{"code": "def get_book_metadata(self, asin):\n\n kbm = self._get_api_call('get_book_metadata', '\"%s\"' % asin)\n return KindleCloudReaderAPI._kbm_to_book(kbm)", "docstring": "Returns a book's metadata.\n\nArgs:\n asin: The ASIN of the book to be queried.\n\nReturns:\n A `KindleBook` instance corresponding to the book associated with\n `asin`.", "source": "juraj_google_style"} +{"code": "def _kl_uniform_uniform(a, b, name=None):\n\n with tf.name_scope(name or \"kl_uniform_uniform\"):\n # Consistent with\n # http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 60\n # Watch out for the change in conventions--they use 'a' and 'b' to refer to\n # lower and upper bounds respectively there.\n final_batch_shape = distribution_util.get_broadcast_shape(\n a.low, b.low, a.high, b.high)\n dtype = dtype_util.common_dtype(\n [a.low, a.high, b.low, b.high], tf.float32)\n return tf.where((b.low <= a.low) & (a.high <= b.high),\n tf.math.log(b.high - b.low) - tf.math.log(a.high - a.low),\n tf.broadcast_to(\n dtype_util.as_numpy_dtype(dtype)(np.inf),\n final_batch_shape))", "docstring": "Calculate the batched KL divergence KL(a || b) with a and b Uniform.\n\n Note that the KL divergence is infinite if the support of `a` is not a subset\n of the support of `b`.\n\nArgs:\n a: instance of a Uniform distribution object.\n b: instance of a Uniform distribution object.\n name: (optional) Name to use for created operations.\n default is \"kl_uniform_uniform\".\n\nReturns:\n Batchwise KL(a || b)", "source": "juraj_google_style"} +{"code": "def check_session(self, key, *, session=None):\n\n self.append({\n \"Verb\": \"check-session\",\n \"Key\": key,\n \"Session\": extract_attr(session, keys=[\"ID\"])\n })\n return self", "docstring": "Fails the transaction if Key is not currently locked by Session\n\n Parameters:\n key (str): Key to check\n session (ObjectID): Session ID", "source": "juraj_google_style"} +{"code": "def set(self, key, samples, sampling_rate):\n\n if not np.issubdtype(samples.dtype, np.floating):\n raise ValueError('Samples are required as np.float32!')\n\n if len(samples.shape) > 1:\n raise ValueError('Only single channel supported!')\n\n self.raise_error_if_not_open()\n\n if key in self._file:\n del self._file[key]\n\n samples = (samples * MAX_INT16_VALUE).astype(np.int16)\n\n dset = self._file.create_dataset(key, data=samples)\n dset.attrs[SAMPLING_RATE_ATTR] = sampling_rate", "docstring": "Set the samples and sampling-rate for the given key.\n Existing data will be overwritten.\n The samples have to have ``np.float32`` datatype and values in\n the range of -1.0 and 1.0.\n\nArgs:\n key (str): A key to store the data for.\n samples (numpy.ndarray): 1-D array of audio samples (np.float32).\n sampling_rate (int): The sampling-rate of the audio samples.\n\nNote:\n The container has to be opened in advance.", "source": "juraj_google_style"} +{"code": "def get_events_for_blocks(self, blocks, subscriptions):\n\n\n events = []\n for blkw in blocks:\n events.extend(self.get_events_for_block(blkw, subscriptions))\n return events", "docstring": "Get a list of events associated with all the blocks.\n\nArgs:\n blocks (list of BlockWrapper): The blocks to search for events that\n match each subscription.\n subscriptions (list of EventSubscriptions): EventFilter and\n event type to filter events.\n\n Returns (list of Events): The Events associated which each block id.\n\nRaises:\n KeyError A receipt is missing from the receipt store.", "source": "juraj_google_style"} +{"code": "def interruptWrite(self, endpoint, buffer, timeout = 100):\n r\n return self.dev.write(endpoint, buffer, timeout)", "docstring": "r\"\"\"Perform a interrupt write request to the endpoint specified.\n\nArgs:\n endpoint: endpoint number.\n buffer: sequence data buffer to write.\n This parameter can be any sequence type.\n timeout: operation timeout in milliseconds. (default: 100)\n Returns the number of bytes written.", "source": "juraj_google_style"} +{"code": "def new(self, name, *args, **kwargs):\n\n if name in self._instance_map:\n raise ValueError('Instance {0} is already initialized'\n .format(name))\n\n instance = self._class_map[name](*args, **kwargs)\n self._instance_map[name] = instance\n return instance", "docstring": "Create an instance.\n\nArgs:\n name (str): The name of the class\n args: The arguments to pass to the class.\n kwargs: The keyword arguments to pass to the class.\n\nReturns:\n instance", "source": "juraj_google_style"} +{"code": "def _validate_clientsecrets(clientsecrets_dict):\n\n _INVALID_FILE_FORMAT_MSG = (\n 'Invalid file format. See '\n 'https://developers.google.com/api-client-library/'\n 'python/guide/aaa_client_secrets')\n\n if clientsecrets_dict is None:\n raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG)\n try:\n (client_type, client_info), = clientsecrets_dict.items()\n except (ValueError, AttributeError):\n raise InvalidClientSecretsError(\n _INVALID_FILE_FORMAT_MSG + ' '\n 'Expected a JSON object with a single property for a \"web\" or '\n '\"installed\" application')\n\n if client_type not in VALID_CLIENT:\n raise InvalidClientSecretsError(\n 'Unknown client type: {0}.'.format(client_type))\n\n for prop_name in VALID_CLIENT[client_type]['required']:\n if prop_name not in client_info:\n raise InvalidClientSecretsError(\n 'Missing property \"{0}\" in a client type of \"{1}\".'.format(\n prop_name, client_type))\n for prop_name in VALID_CLIENT[client_type]['string']:\n if client_info[prop_name].startswith('[['):\n raise InvalidClientSecretsError(\n 'Property \"{0}\" is not configured.'.format(prop_name))\n return client_type, client_info", "docstring": "Validate parsed client secrets from a file.\n\nArgs:\n clientsecrets_dict: dict, a dictionary holding the client secrets.\n\nReturns:\n tuple, a string of the client type and the information parsed\n from the file.", "source": "juraj_google_style"} +{"code": "def __init__(self, item_cls, data):\n\n super(ResourceList, self).__init__()\n if data is not None:\n\n data = json.loads(data) if type(data) is not dict else data\n paging = data['list_info']\n raw_items = data.get(self.items_keys[item_cls.__name__])\n\n if raw_items:\n\n # Wrap raw items in object containers\n for raw_item in raw_items:\n self.append(item_cls(raw_item))\n\n # Paging info\n self.page = paging['page']\n self.num_pages = paging['num_pages']\n self.num_results = paging['num_results']\n self.page_size = paging['page_size']", "docstring": "Initialization of the list\n\nArgs:\n item_cls (str): Object class matching the list items\n data (str or dict): A dictionary or raw JSON string that is returned by a request.", "source": "juraj_google_style"} +{"code": "def outgoing_args(self, nodeid):\n\n _vars = self._vars\n _hcons = self._hcons\n args = self.args(nodeid) # args is a copy; we can edit it\n for arg, val in list(args.items()):\n # don't include constant args or intrinsic args\n if arg == IVARG_ROLE or val not in _vars:\n del args[arg]\n else:\n refs = _vars[val]['refs']\n # don't include if not HCONS or pointing to other IV or LBL\n if not (val in _hcons or IVARG_ROLE in refs or 'LBL' in refs):\n del args[arg]\n return args", "docstring": "Return the arguments going from *nodeid* to other predications.\n\n Valid arguments include regular variable arguments and scopal\n (label-selecting or HCONS) arguments. MOD/EQ\n links, intrinsic arguments, and constant arguments are not\n included.\n\nArgs:\n nodeid: the nodeid of the EP that is the arguments' source\n\nReturns:\n dict: `{role: tgt}`", "source": "juraj_google_style"} +{"code": "def set(self, key, value):\n\n\n data = self._load_file()\n data[key] = value\n self._save_file(data)", "docstring": "Set the value of a key\n\nArgs:\n key (string): The key used to store this value\n value (string): The value to store", "source": "juraj_google_style"} +{"code": "def _get_ip_unnumbered(self, unnumbered_type, unnumbered_name):\n\n unnumbered_type = self._callback(unnumbered_type, handler='get_config')\n unnumbered_name = self._callback(unnumbered_name, handler='get_config')\n unnumbered_type = pynos.utilities.return_xml(str(unnumbered_type))\n unnumbered_name = pynos.utilities.return_xml(str(unnumbered_name))\n return pynos.utilities.merge_xml(unnumbered_type, unnumbered_name)", "docstring": "Get and merge the `ip unnumbered` config from an interface.\n\n You should not use this method.\n You probably want `Interface.ip_unnumbered`.\n\nArgs:\n unnumbered_type: XML document with the XML to get the donor type.\n unnumbered_name: XML document with the XML to get the donor name.\n\nReturns:\n Merged XML document.\n\nRaises:\n None", "source": "juraj_google_style"} +{"code": "def codify(combination):\n\n\n\n\tif (isinstance(combination, int) and\n\t\t(combination < 0 or combination >= LIMIT)):\n\t\traise errors.FlagError(\"Out-of-range flag-combination!\")\n\n\tcodes = []\n\n\tfor enum in (Style, Color, Fill):\n\t\tfor flag in enum:\n\t\t\tif combination & flag:\n\t\t\t\tcodes.append(str(flag))\n\n\treturn \";\".join(codes)", "docstring": "Gets escape-codes for flag combinations.\n\nArgs:\n combination (int): Either a single integer-convertible flag\n or an OR'd flag-combination.\n\nReturns:\n A semi-colon-delimited string of appropriate escape sequences.\n\nRaises:\n errors.FlagError if the combination is out-of-range.", "source": "juraj_google_style"} +{"code": "def received_response(self, value):\n\n if value == self._defaults['receivedResponse'] and 'receivedResponse' in self._values:\n del self._values['receivedResponse']\n else:\n self._values['receivedResponse'] = value", "docstring": "The received_response property.\n\nArgs:\n value (string). the property value.", "source": "juraj_google_style"} +{"code": "def generate_workflow_description(self):\n\n if not self.tasks:\n raise WorkflowError('Workflow contains no tasks, and cannot be executed.')\n\n self.definition = self.workflow_skeleton()\n\n if self.batch_values:\n self.definition[\"batch_values\"] = self.batch_values\n\n all_input_port_values = [t.inputs.__getattribute__(input_port_name).value for t in self.tasks for\n input_port_name in t.inputs._portnames]\n for task in self.tasks:\n # only include multiplex output ports in this task if other tasks refer to them in their inputs.\n # 1. find the multplex output port_names in this task\n # 2. see if they are referred to in any other tasks inputs\n # 3. If not, exclude them from the workflow_def\n output_multiplex_ports_to_exclude = []\n multiplex_output_port_names = [portname for portname in task.outputs._portnames if\n task.outputs.__getattribute__(portname).is_multiplex]\n for p in multiplex_output_port_names:\n output_port_reference = 'source:' + task.name + ':' + p\n if output_port_reference not in all_input_port_values:\n output_multiplex_ports_to_exclude.append(p)\n\n task_def = task.generate_task_workflow_json(\n output_multiplex_ports_to_exclude=output_multiplex_ports_to_exclude)\n self.definition['tasks'].append(task_def)\n\n if self.callback:\n self.definition['callback'] = self.callback\n\n return self.definition", "docstring": "Generate workflow json for launching the workflow against the gbdx api\n\nArgs:\n None\n\nReturns:\n json string", "source": "juraj_google_style"} +{"code": "def add_node(self, node_id, name, labels):\n\n self.neo_db.add_node(node_id, name, labels)", "docstring": "Add a node to the graph with name and labels.\n\nArgs:\n node_id: the unique node_id e.g. 'www.evil4u.com'\n name: the display name of the node e.g. 'evil4u'\n labels: a list of labels e.g. ['domain','evil']\n\nReturns:\n Nothing", "source": "juraj_google_style"} +{"code": "def download_file(url, destination, **kwargs):\n\n web_file = open_remote_url(url, **kwargs)\n file_size = 0\n\n if not web_file:\n logger.error(\n \"Remote file not found. Attempted URLs: {}\".format(url))\n return\n\n modified = is_remote_file_modified(web_file, destination)\n if modified:\n logger.info(\"Downloading: \" + web_file.url)\n file_size = copy_remote_file(web_file, destination)\n else:\n logger.info(\"File up-to-date: \" + destination)\n\n web_file.close()\n return file_size", "docstring": "Download file process:\n - Open the url\n - Check if it has been downloaded and it hanged.\n - Download it to the destination folder.\n\nArgs:\n :urls: url to take the file.\n :destionation: place to store the downloaded file.", "source": "juraj_google_style"} +{"code": "def activate(self, user):\n\n org_user = self.organization.add_user(user, **self.activation_kwargs())\n self.invitee = user\n self.save()\n return org_user", "docstring": "Updates the `invitee` value and saves the instance\n\n Provided as a way of extending the behavior.\n\nArgs:\n user: the newly created user\n\nReturns:\n the linking organization user", "source": "juraj_google_style"} +{"code": "def view_status_code(codes):\n\n\n if \",\" not in codes:\n try:\n code = int(codes)\n except ValueError:\n return Response(\"Invalid status code\", status=400)\n return status_code(code)\n\n choices = []\n for choice in codes.split(\",\"):\n if \":\" not in choice:\n code = choice\n weight = 1\n else:\n code, weight = choice.split(\":\")\n\n try:\n choices.append((int(code), float(weight)))\n except ValueError:\n return Response(\"Invalid status code\", status=400)\n\n code = weighted_choice(choices)\n\n return status_code(code)", "docstring": "Return status code or random status code if more than one are given\n ---\n tags:\n - Status codes\n parameters:\n - in: path\n name: codes\n produces:\n - text/plain\n responses:\n 100:\n description: Informational responses\n 200:\n description: Success\n 300:\n description: Redirection\n 400:\n description: Client Errors\n 500:\n description: Server Errors", "source": "juraj_google_style"} +{"code": "def mjpeg_url(self, channelno=None, typeno=None):\n\n if channelno is None:\n channelno = 0\n\n if typeno is None:\n typeno = 1\n\n cmd = \"mjpg/video.cgi?channel={0}&subtype={1}\".format(\n channelno, typeno)\n return '{0}{1}'.format(self._base_url, cmd)", "docstring": "Return MJPEG streaming url\n\n Params:\n channelno: integer, the video channel index which starts from 1,\n default 1 if not specified.\n\n typeno: the stream type, default 0 if not specified. It can be\n the following value:\n\n 0-Main Stream\n 1-Extra Stream 1 (Sub Stream)\n 2-Extra Stream 2 (Sub Stream)", "source": "juraj_google_style"} +{"code": "def switch_window(self, window_id: int):\n\n\n # windows are numbered sequentially 0, 1, 2, ...\n # create any missing windows and make them point to the same directory\n if window_id not in self.tmux_available_window_ids:\n for i in range(max(self.tmux_available_window_ids) + 1, window_id + 1):\n self._run_raw(f'tmux new-window -t {self.tmux_session} -d')\n self.tmux_available_window_ids.append(i)\n\n self.tmux_window_id = window_id", "docstring": "Switches currently active tmux window for given task. 0 is the default window\n\nArgs:\n window_id: integer id of tmux window to use", "source": "juraj_google_style"} +{"code": "def from_optimize_result(cls, result, n, m, index=None):\n\n coords = pd.DataFrame(result.x.reshape((m, n)), index=index)\n projection = cls(coords)\n projection.stress = result.fun\n return projection", "docstring": "Construct a Projection from the output of an optimization.\n\nArgs:\n result (:py:class:`scipy.optimize.OptimizeResult`): Object\n returned by :py:func:`scipy.optimize.minimize`.\n n (`int`): Number of dimensions.\n m (`int`): Number of samples.\n index (`list-like`): Names of samples. (Optional).\n\nReturns:\n :py:class:`pymds.Projection`", "source": "juraj_google_style"} +{"code": "def __init__(self, host, namespace='', cache=None):\n\n super(Store, self).__init__()\n self._host = host\n self._namespace = namespace\n self._cache = cache", "docstring": "Initialise the store.\n\nArgs:\n host (string): The host of your api, e.g. http://localhost:8000\n namespace (string, optional): An aditional name space to append\n to the host, e.g. api/v1\n cache (:class:`cinder_data.cache.Cache`, optional): An instance of your chosen caching\n system that must be must adhear to the :class:`cinder_data.cache.Cache` interface.", "source": "juraj_google_style"} +{"code": "def _method_response_handler(self, response: Dict[str, Any]):\n\n code = response.get(\"CODE\")\n if code in (200, 300):\n self._result_handler(response)\n else:\n asyncio.ensure_future(self._gen_result_handler(response))", "docstring": "处理200~399段状态码,为对应的响应设置结果.\n\n Parameters:\n (response): - 响应的python字典形式数据\n\nReturns:\n (bool): - 准确地说没有错误就会返回True", "source": "juraj_google_style"} +{"code": "def __init__(self, text: str, schema_data: SchemaData, mid: ModuleId):\n\n super().__init__(text)\n self.mid = mid\n self.schema_data = schema_data", "docstring": "Initialize the parser instance.\n\nArgs:\n text: Feature expression text.\n schema_data: Data for the current schema.\n mid: Identifier of the context module.\n\nRaises:\n ModuleNotRegistered: If `mid` is not registered in the data model.", "source": "juraj_google_style"} +{"code": "def resize(x, mode, factor=4):\n\n assert mode in ['bilinear', 'nearest'], mode\n shp = tf.shape(x)[2:] * factor\n # NCHW -> NHWC\n x = tf.transpose(x, [0, 2, 3, 1])\n if mode == 'bilinear':\n x = tf.image.resize_bilinear(x, shp, align_corners=True)\n else:\n # better approximation of what Caffe is doing\n x = tf.image.resize_nearest_neighbor(x, shp, align_corners=False)\n # NHWC -> NCHW\n return tf.transpose(x, [0, 3, 1, 2])", "docstring": "Resize input tensor with unkown input-shape by a factor\n\nArgs:\n x (tf.Tensor): tensor NCHW\n factor (int, optional): resize factor for H, W\n\nNote:\n Differences here against Caffe have huge impacts on the\n quality of the predictions.\n\nReturns:\n tf.Tensor: resized tensor NCHW", "source": "juraj_google_style"} +{"code": "def share(self, group_id, group_access, expires_at=None, **kwargs):\n\n path = '/projects/%s/share' % self.get_id()\n data = {'group_id': group_id,\n 'group_access': group_access,\n 'expires_at': expires_at}\n self.manager.gitlab.http_post(path, post_data=data, **kwargs)", "docstring": "Share the project with a group.\n\nArgs:\n group_id (int): ID of the group.\n group_access (int): Access level for the group.\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabCreateError: If the server failed to perform the request", "source": "juraj_google_style"} +{"code": "def compute_shader(self, source) -> 'ComputeShader':\n\n\n res = ComputeShader.__new__(ComputeShader)\n res.mglo, ls1, ls2, ls3, ls4, res._glo = self.mglo.compute_shader(source)\n\n members = {}\n\n for item in ls1:\n obj = Uniform.__new__(Uniform)\n obj.mglo, obj._location, obj._array_length, obj._dimension, obj._name = item\n members[obj.name] = obj\n\n for item in ls2:\n obj = UniformBlock.__new__(UniformBlock)\n obj.mglo, obj._index, obj._size, obj._name = item\n members[obj.name] = obj\n\n res._members = members\n res.ctx = self\n res.extra = None\n return res", "docstring": "A :py:class:`ComputeShader` is a Shader Stage that is used entirely for computing arbitrary information.\n While it can do rendering, it is generally used for tasks not directly related to drawing.\n\nArgs:\n source (str): The source of the compute shader.\n\nReturns:\n :py:class:`ComputeShader` object", "source": "juraj_google_style"} +{"code": "def get_forced_variation(self, experiment, user_id):\n\n\n forced_variations = experiment.forcedVariations\n if forced_variations and user_id in forced_variations:\n variation_key = forced_variations.get(user_id)\n variation = self.config.get_variation_from_key(experiment.key, variation_key)\n if variation:\n self.logger.info('User \"%s\" is forced in variation \"%s\".' % (user_id, variation_key))\n return variation\n\n return None", "docstring": "Determine if a user is forced into a variation for the given experiment and return that variation.\n\nArgs:\n experiment: Object representing the experiment for which user is to be bucketed.\n user_id: ID for the user.\n\nReturns:\n Variation in which the user with ID user_id is forced into. None if no variation.", "source": "juraj_google_style"} +{"code": "def get_protocol(url):\n\n\n if url not in URLHelper.__cache:\n URLHelper.__cache[url] = urlparse(url)\n\n return URLHelper.__cache[url].scheme", "docstring": "Get the protocol (e.g. http, https or ftp) of the given URL.\n\nArgs:\n url (str): The URL to get the protocol from.\n\nReturns:\n str: The URL protocol", "source": "juraj_google_style"} +{"code": "def __init__(self, NID_AUT = None, NID_SES= None):\n\n self.session.headers[\"User-Agent\"] = \\\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) Chrome/32.0.1700.76 Safari/537.36\"\n self.session.cookies.set('NID_AUT', NID_AUT)\n self.session.cookies.set('NID_SES', NID_SES)", "docstring": "Initialize ndrive instance\n\n Using given user information, login to ndrive server and create a session\n\nArgs:\n NID_AUT: Naver account authentication info\n NID_SES: Naver account session info\n\n Returns:", "source": "juraj_google_style"} +{"code": "def ascii_tree(self, no_types: bool = False, val_count: bool = False) -> str:\n\n return self.schema._ascii_tree(\"\", no_types, val_count)", "docstring": "Generate ASCII art representation of the schema tree.\n\nArgs:\n no_types: Suppress output of data type info.\n val_count: Show accumulated validation counts.\n\nReturns:\n String with the ASCII tree.", "source": "juraj_google_style"} +{"code": "def _set_class_path(cls, module_dict=sys.modules):\n\n # Do not traverse the class hierarchy fetching the class path attribute.\n found = cls.__dict__.get('_class_path')\n if found is not None:\n return\n\n # Do not set the _class_path for the base-class, otherwise all children's\n # lookups for _class_path will fall through and return 'Pipeline' above.\n # This situation can happen if users call the generic Pipeline.from_id\n # to get the result of a Pipeline without knowing its specific class.\n if cls is Pipeline:\n return\n\n class_path = '%s.%s' % (cls.__module__, cls.__name__)\n # When a WSGI handler is invoked as an entry point, any Pipeline class\n # defined in the same file as the handler will get __module__ set to\n # __main__. Thus we need to find out its real fully qualified path.\n if cls.__module__ == '__main__':\n for name, module in module_dict.items():\n if name == '__main__':\n continue\n found = getattr(module, cls.__name__, None)\n if found is cls:\n class_path = '%s.%s' % (name, cls.__name__)\n break\n cls._class_path = class_path", "docstring": "Sets the absolute path to this class as a string.\n\n Used by the Pipeline API to reconstruct the Pipeline sub-class object\n at execution time instead of passing around a serialized function.\n\nArgs:\n module_dict: Used for testing.", "source": "juraj_google_style"} +{"code": "def arr_select(value): # function factory\n\n def f_eq(arr):\n return np.equal(np.bitwise_and(arr, value), value)\n f_eq.__name__ = \"arr_bitwise_and_\" + str(value) # or use inspect module: inspect.stack()[0][3]\n return f_eq", "docstring": "Selecting array elements by bitwise and comparison to a given value.\n\n Parameters:\n value : int\n Value to which array elements are compared to.\n\nReturns:\n array : np.array", "source": "juraj_google_style"} +{"code": "def _CreateProcessingConfiguration(self, knowledge_base):\n\n # TODO: pass preferred_encoding.\n configuration = configurations.ProcessingConfiguration()\n configuration.artifact_filters = self._artifact_filters\n configuration.credentials = self._credential_configurations\n configuration.debug_output = self._debug_mode\n configuration.event_extraction.text_prepend = self._text_prepend\n configuration.extraction.hasher_file_size_limit = (\n self._hasher_file_size_limit)\n configuration.extraction.hasher_names_string = self._hasher_names_string\n configuration.extraction.process_archives = self._process_archives\n configuration.extraction.process_compressed_streams = (\n self._process_compressed_streams)\n configuration.extraction.yara_rules_string = self._yara_rules_string\n configuration.filter_file = self._filter_file\n configuration.input_source.mount_path = self._mount_path\n configuration.log_filename = self._log_file\n configuration.parser_filter_expression = self._parser_filter_expression\n configuration.preferred_year = self._preferred_year\n configuration.profiling.directory = self._profiling_directory\n configuration.profiling.sample_rate = self._profiling_sample_rate\n configuration.profiling.profilers = self._profilers\n configuration.temporary_directory = self._temporary_directory\n\n if not configuration.parser_filter_expression:\n operating_system = knowledge_base.GetValue('operating_system')\n operating_system_product = knowledge_base.GetValue(\n 'operating_system_product')\n operating_system_version = knowledge_base.GetValue(\n 'operating_system_version')\n preset_definitions = (\n parsers_manager.ParsersManager.GetPresetsForOperatingSystem(\n operating_system, operating_system_product,\n operating_system_version))\n\n if preset_definitions:\n preset_names = [\n preset_definition.name for preset_definition in preset_definitions]\n filter_expression = ','.join(preset_names)\n\n logger.info('Parser filter expression set to: {0:s}'.format(\n filter_expression))\n configuration.parser_filter_expression = filter_expression\n\n return configuration", "docstring": "Creates a processing configuration.\n\nArgs:\n knowledge_base (KnowledgeBase): contains information from the source\n data needed for parsing.\n\nReturns:\n ProcessingConfiguration: processing configuration.\n\nRaises:\n BadConfigOption: if more than 1 parser and parser plugins preset\n was found for the detected operating system.", "source": "juraj_google_style"} +{"code": "def _init_from_bool(self, z, x):\n\n if z is None:\n raise QiskitError(\"z vector must not be None.\")\n if x is None:\n raise QiskitError(\"x vector must not be None.\")\n if len(z) != len(x):\n raise QiskitError(\"length of z and x vectors must be \"\n \"the same. (z: {} vs x: {})\".format(len(z), len(x)))\n\n z = _make_np_bool(z)\n x = _make_np_bool(x)\n self._z = z\n self._x = x\n\n return self", "docstring": "Construct pauli from boolean array.\n\nArgs:\n z (numpy.ndarray): boolean, z vector\n x (numpy.ndarray): boolean, x vector\n\nReturns:\n Pauli: self\n\nRaises:\n QiskitError: if z or x are None or the length of z and x are different.", "source": "juraj_google_style"} +{"code": "def __init__(self, hashes):\n\n self.Root = MerkleTree.__Build([MerkleTreeNode(hash) for hash in hashes])\n depth = 1\n i = self.Root\n while i.LeftChild is not None:\n depth = depth + 1\n i = i.LeftChild\n self.Depth = depth", "docstring": "Crease an instance.\n\nArgs:\n hashes (list): each hash is of bytearray type.", "source": "juraj_google_style"} +{"code": "def make_unique_script_attr(attributes):\n\n filtered_attr = []\n script_list = []\n for attr in attributes:\n if attr.Usage != TransactionAttributeUsage.Script:\n filtered_attr.append(attr)\n else:\n data = attr.Data\n if isinstance(data, UInt160):\n # convert it to equal type\n data = attr.Data.ToArray()\n\n # only add if it's not already in the list\n if data not in script_list:\n script_list.append(data)\n filtered_attr.append(attr)\n\n return filtered_attr", "docstring": "Filter out duplicate `Script` TransactionAttributeUsage types.\n\nArgs:\n attributes: a list of TransactionAttribute's\n\nReturns:\n list:", "source": "juraj_google_style"} +{"code": "def dropout_no_scaling(x, keep_prob):\n\n if keep_prob == 1.0:\n return x\n mask = tf.less(tf.random_uniform(tf.shape(x)), keep_prob)\n return x * cast_like(mask, x)", "docstring": "Like tf.nn.dropout, but does not scale up. Works on integers also.\n\nArgs:\n x: a Tensor\n keep_prob: a floating point number\n\nReturns:\n Tensor of the same shape as x.", "source": "juraj_google_style"} +{"code": "def label_sequential_regions(inlist):\n\n import more_itertools as mit\n\n df = pd.DataFrame(inlist).set_index(0)\n\n labeled = {}\n for label in df[1].unique():\n iterable = df[df[1] == label].index.tolist()\n labeled.update({'{}{}'.format(label, i + 1): items for i, items in\n enumerate([list(group) for group in mit.consecutive_groups(iterable)])})\n\n return labeled", "docstring": "Input a list of labeled tuples and return a dictionary of sequentially labeled regions.\n\nArgs:\n inlist (list): A list of tuples with the first number representing the index and the second the index label.\n\nReturns:\n dict: Dictionary of labeled regions.\n\nExample:\n >>> label_sequential_regions([(1, 'O'), (2, 'O'), (3, 'O'), (4, 'M'), (5, 'M'), (6, 'I'), (7, 'M'), (8, 'O'), (9, 'O')])\n {'O1': [1, 2, 3], 'M1': [4, 5], 'I1': [6], 'M2': [7], 'O2': [8, 9]}", "source": "juraj_google_style"} +{"code": "def search(self, search_phrase, limit=None):\n\n\n # SQLite FTS can't find terms with `-`, therefore all hyphens replaced with underscore before save.\n # Now to make proper query we need to replace all hyphens in the search phrase.\n # See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries\n search_phrase = search_phrase.replace('-', '_')\n terms = SearchTermParser().parse(search_phrase)\n from_year = terms.pop('from', None)\n to_year = terms.pop('to', None)\n\n query, query_params = self._make_query_from_terms(terms)\n\n self._parsed_query = (query, query_params)\n\n connection = self.backend.library.database.connection\n\n connection.connection.create_function('rank', 1, _make_rank_func((1., .1, 0, 0)))\n\n # SQLite FTS implementation does not allow to create indexes on FTS tables.\n # see https://sqlite.org/fts3.html 1.5. Summary, p 1:\n # ... it is not possible to create indices ...\n #\n # So, filter years range here.\n\n results = connection.execute(query, query_params).fetchall()\n\n for result in results:\n vid, dataset_vid, score, db_from_year, db_to_year = result\n if from_year and from_year < db_from_year:\n continue\n if to_year and to_year > db_to_year:\n continue\n yield PartitionSearchResult(\n vid=vid, dataset_vid=dataset_vid, score=score)", "docstring": "Finds partitions by search phrase.\n\nArgs:\n search_phrase (str or unicode):\n limit (int, optional): how many results to generate. None means without limit.\n\n Generates:\n PartitionSearchResult instances.", "source": "juraj_google_style"} +{"code": "def run(self, dag):\n\n # Walk through the DAG and expand each non-basis node\n for node in dag.op_nodes():\n basic_insts = ['measure', 'reset', 'barrier', 'snapshot']\n if node.name in basic_insts:\n # TODO: this is legacy behavior.Basis_insts should be removed that these\n # instructions should be part of the device-reported basis. Currently, no\n # backend reports \"measure\", for example.\n continue\n if node.name in self.basis: # If already a base, ignore.\n continue\n\n # TODO: allow choosing other possible decompositions\n rule = node.op.definition\n if not rule:\n raise QiskitError(\"Cannot unroll the circuit to the given basis, %s. \"\n \"No rule to expand instruction %s.\" %\n (str(self.basis), node.op.name))\n\n # hacky way to build a dag on the same register as the rule is defined\n # TODO: need anonymous rules to address wires by index\n decomposition = DAGCircuit()\n decomposition.add_qreg(rule[0][1][0][0])\n for inst in rule:\n decomposition.apply_operation_back(*inst)\n\n unrolled_dag = self.run(decomposition) # recursively unroll ops\n dag.substitute_node_with_dag(node, unrolled_dag)\n return dag", "docstring": "Expand all op nodes to the given basis.\n\nArgs:\n dag(DAGCircuit): input dag\n\nRaises:\n QiskitError: if unable to unroll given the basis due to undefined\n decomposition rules (such as a bad basis) or excessive recursion.\n\nReturns:\n DAGCircuit: output unrolled dag", "source": "juraj_google_style"} +{"code": "def _astimezone_ts(self, timezone):\n\n if self.created.tzinfo is timezone:\n return self\n else:\n nw_obj = Timestamps((None,)*4)\n nw_obj.created = self.created.astimezone(timezone)\n nw_obj.changed = self.changed.astimezone(timezone)\n nw_obj.mft_changed = self.mft_changed.astimezone(timezone)\n nw_obj.accessed = self.accessed.astimezone(timezone)\n\n return nw_obj", "docstring": "Changes the time zones of all timestamps.\n\n Receives a new timezone and applies to all timestamps, if necessary.\n\nArgs:\n timezone (:obj:`tzinfo`): Time zone to be applied\n\nReturns:\n A new ``Timestamps`` object if the time zone changes, otherwise returns ``self``.", "source": "juraj_google_style"} +{"code": "def get_op_or_tensor_by_name(name):\n\n G = tfv1.get_default_graph()\n\n def f(n):\n if len(n) >= 3 and n[-2] == ':':\n return G.get_tensor_by_name(n)\n else:\n return G.get_operation_by_name(n)\n\n if not isinstance(name, list):\n return f(name)\n else:\n return list(map(f, name))", "docstring": "Get either tf.Operation of tf.Tensor from names.\n\nArgs:\n name (list[str] or str): names of operations or tensors.\n\nRaises:\n KeyError, if the name doesn't exist", "source": "juraj_google_style"} +{"code": "def __init__(self, version: str = None, api_url: str = None) -> None:\n\n\n bel_versions = bel_specification.get_bel_versions()\n\n # use bel_utils._default_to_version to check if valid version, and if it exists or not\n if not version:\n self.version = config[\"bel\"][\"lang\"][\"default_bel_version\"]\n else:\n self.version = version\n\n if self.version not in bel_versions:\n log.warning(\n f\"Cannot validate with invalid version: {self.version} in BEL Versions: {bel_versions}\"\n )\n\n if not api_url:\n self.api_url = config[\"bel_api\"][\"servers\"][\"api_url\"]\n else:\n self.api_url = api_url\n\n # Validation error/warning messages\n # List[Tuple[str, str]], e.g. [('ERROR', 'this is an error msg'), ('WARNING', 'this is a warning'), ]\n self.validation_messages = []\n\n # self.semantics = BELSemantics() # each instance also instantiates a BELSemantics object used in parsing statements\n self.spec = bel_specification.get_specification(self.version)\n\n # bel_utils._dump_spec(self.spec)\n\n # Import Tatsu parser\n # use importlib to import our parser (a .py file) and set the BELParse object as an instance variable\n try:\n parser_fn = self.spec[\"admin\"][\"parser_fn\"]\n\n parser_name = os.path.basename(parser_fn).replace(\".py\", \"\")\n module_spec = importlib.util.spec_from_file_location(parser_name, parser_fn)\n imported_parser = importlib.util.module_from_spec(module_spec)\n module_spec.loader.exec_module(imported_parser)\n self.parser = imported_parser.BELParser()\n except Exception as e:\n # if not found, we raise the NoParserFound exception which can be found in bel.lang.exceptions\n raise bel_ex.NoParserFound(f\"Version: {self.version} Msg: {e}\")", "docstring": "Initialize BEL object used for validating/processing/etc BEL statements\n\nArgs:\n version (str): BEL Version, defaults to config['bel']['lang']['default_bel_version']\n api_url (str): BEL API endpoint, defaults to config['bel_api']['servers']['api_url']", "source": "juraj_google_style"} +{"code": "def encode_consumer_metadata_request(cls, client_id, correlation_id, payloads):\n\n message = []\n message.append(cls._encode_message_header(client_id, correlation_id,\n KafkaProtocol.CONSUMER_METADATA_KEY))\n message.append(struct.pack('>h%ds' % len(payloads), len(payloads), payloads))\n\n msg = b''.join(message)\n return write_int_string(msg)", "docstring": "Encode a ConsumerMetadataRequest\n\nArgs:\n client_id: string\n correlation_id: int\n payloads: string (consumer group)", "source": "juraj_google_style"} +{"code": "def get_transcript_format(transcript_content):\n\n try:\n sjson_obj = json.loads(transcript_content)\n except ValueError:\n # With error handling (set to 'ERROR_RAISE'), we will be getting\n # the exception if something went wrong in parsing the transcript.\n srt_subs = SubRipFile.from_string(transcript_content, error_handling=SubRipFile.ERROR_RAISE)\n if len(srt_subs) > 0:\n return TranscriptFormat.SRT\n return TranscriptFormat.SJSON", "docstring": "Returns transcript format.\n\nArgs:\n transcript_content (str): Transcript file content.", "source": "juraj_google_style"} +{"code": "def get(self, key):\n\n data = self._store.get(key)\n if not data:\n return None\n value, expire = data\n if expire and time.time() > expire:\n del self._store[key]\n return None\n return value", "docstring": "Get an item from the cache\n\nArgs:\n key: item key\n\nReturns:\n the value of the item or None if the item isn't in the cache", "source": "juraj_google_style"} +{"code": "def list_resource_groups(access_token, subscription_id):\n\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourceGroups/',\n '?api-version=', RESOURCE_API])\n return do_get(endpoint, access_token)", "docstring": "List the resource groups in a subscription.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n\nReturns:\n HTTP response.", "source": "juraj_google_style"} +{"code": "def _check_special_kwargs(self, name):\n\n keys = []\n # find any %method names in the template string\n functions = re.findall(r\"\\%\\w+\", self.templates[name])\n if not functions:\n return keys\n\n # loop over special method names and extract keywords\n for function in functions:\n method = getattr(self, function[1:])\n # get source code of special method\n source = self._find_source(method)\n fkeys = re.findall(r'kwargs\\[(.*?)\\]', source)\n if fkeys:\n # evaluate to proper string\n fkeys = [ast.literal_eval(k) for k in fkeys]\n keys.extend(fkeys)\n return keys", "docstring": "check special functions for kwargs\n\n Checks the content of the special functions (%methodname) for\n any keyword arguments referenced within\n\n Parameters:\n name (str):\n A path key name\n\nReturns:\n A list of keyword arguments found in any special functions", "source": "juraj_google_style"} +{"code": "def render_secrets(\n config_path,\n secret_path,\n):\n\n with open(secret_path, 'r') as s_fh:\n secret_ini = anyconfig.load(s_fh, ac_parser='ini')\n\n with open(config_path, 'r') as c_fh:\n raw_cfg = c_fh.read()\n\n rendered_cfg = anytemplate.renders(raw_cfg, secret_ini, at_engine='jinja2')\n\n p_config = ProsperConfig(config_path)\n local_config = configparser.ConfigParser()\n local_config.optionxform = str\n local_config.read_string(rendered_cfg)\n\n p_config.local_config = local_config\n\n return p_config", "docstring": "combine a jinja template with a secret .ini file\n\nArgs:\n config_path (str): path to .cfg file with jinja templating\n secret_path (str): path to .ini-like secrets file\n\nReturns:\n ProsperConfig: rendered configuration object", "source": "juraj_google_style"} +{"code": "def NotIn(self, *values):\n\n self._awql = self._CreateMultipleValuesCondition(values, 'NOT_IN')\n return self._query_builder", "docstring": "Sets the type of the WHERE clause as \"in\".\n\nArgs:\n *values: The values to be used in the WHERE condition.\n\nReturns:\n The query builder that this WHERE builder links to.", "source": "juraj_google_style"} +{"code": "def parse_case(config):\n\n if 'owner' not in config:\n raise ConfigError(\"A case has to have a owner\")\n\n if 'family' not in config:\n raise ConfigError(\"A case has to have a 'family'\")\n\n individuals = parse_individuals(config['samples'])\n case_data = {\n 'owner': config['owner'],\n 'collaborators': [config['owner']],\n 'case_id': config['family'],\n 'display_name': config.get('family_name', config['family']),\n 'genome_build': config.get('human_genome_build'),\n 'rank_model_version': config.get('rank_model_version'),\n 'rank_score_threshold': config.get('rank_score_threshold', 0),\n 'analysis_date': config['analysis_date'],\n 'individuals': individuals,\n 'vcf_files': {\n 'vcf_snv': config.get('vcf_snv'),\n 'vcf_sv': config.get('vcf_sv'),\n 'vcf_str': config.get('vcf_str'),\n 'vcf_cancer': config.get('vcf_cancer'),\n 'vcf_snv_research': config.get('vcf_snv_research'),\n 'vcf_sv_research': config.get('vcf_sv_research'),\n 'vcf_cancer_research': config.get('vcf_cancer_research'),\n },\n 'default_panels': config.get('default_gene_panels', []),\n 'gene_panels': config.get('gene_panels', []),\n 'assignee': config.get('assignee'),\n 'peddy_ped': config.get('peddy_ped'),\n 'peddy_sex': config.get('peddy_sex'),\n 'peddy_check': config.get('peddy_check'),\n 'delivery_report': config.get('delivery_report'),\n 'multiqc': config.get('multiqc'),\n 'track': config.get('track', 'rare'),\n }\n\n # add the pedigree figure, this is a xml file which is dumped in the db\n if 'madeline' in config:\n mad_path = Path(config['madeline'])\n if not mad_path.exists():\n raise ValueError(\"madeline path not found: {}\".format(mad_path))\n with mad_path.open('r') as in_handle:\n case_data['madeline_info'] = in_handle.read()\n\n if (case_data['vcf_files']['vcf_cancer'] or case_data['vcf_files']['vcf_cancer_research']):\n case_data['track'] = 'cancer'\n\n return case_data", "docstring": "Parse case information from config or PED files.\n\nArgs:\n config (dict): case config with detailed information\n\nReturns:\n dict: parsed case data", "source": "juraj_google_style"} +{"code": "def pymmh3_hash64(key: Union[bytes, bytearray],\n seed: int = 0,\n x64arch: bool = True) -> Tuple[int, int]:\n\n\n hash_128 = pymmh3_hash128(key, seed, x64arch)\n\n unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF # low half\n if unsigned_val1 & 0x8000000000000000 == 0:\n signed_val1 = unsigned_val1\n else:\n signed_val1 = -((unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF) + 1)\n\n unsigned_val2 = (hash_128 >> 64) & 0xFFFFFFFFFFFFFFFF # high half\n if unsigned_val2 & 0x8000000000000000 == 0:\n signed_val2 = unsigned_val2\n else:\n signed_val2 = -((unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1)\n\n return signed_val1, signed_val2", "docstring": "Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.\n\nArgs:\n key: data to hash\n seed: seed\n x64arch: is a 64-bit architecture available?\n\nReturns:\n tuple: tuple of integers, ``(signed_val1, signed_val2)``", "source": "juraj_google_style"} +{"code": "def set_control_mode(self, modevalue):\n\n minimalmodbus._checkInt(modevalue, minvalue=0, maxvalue=3, description='control mode') \n self.write_register(4101, modevalue)", "docstring": "Set the control method using the corresponding integer value.\n\nArgs:\n modevalue(int): 0-3\n\n The modevalue is one of the keys in :data:`CONTROL_MODES`.", "source": "juraj_google_style"} +{"code": "def export(self, composite=False):\n\n\n if composite:\n if rname_rfc6680 is None:\n raise NotImplementedError(\"Your GSSAPI implementation does \"\n \"not support RFC 6680 (the GSSAPI \"\n \"naming extensions)\")\n\n return rname_rfc6680.export_name_composite(self)\n else:\n return rname.export_name(self)", "docstring": "Export this name as a token.\n\n This method exports the name into a byte string which can then be\n imported by using the `token` argument of the constructor.\n\nArgs:\n composite (bool): whether or not use to a composite token --\n :requires-ext:`rfc6680`\n\nReturns:\n bytes: the exported name in token form\n\nRaises:\n MechanismNameRequiredError\n BadNameTypeError\n BadNameError", "source": "juraj_google_style"} +{"code": "def kcenter(I,J,c,k):\n\n\n model = Model(\"k-center\")\n z = model.addVar(vtype=\"C\", name=\"z\")\n x,y = {},{}\n\n for j in J:\n y[j] = model.addVar(vtype=\"B\", name=\"y(%s)\"%j)\n for i in I:\n x[i,j] = model.addVar(vtype=\"B\", name=\"x(%s,%s)\"%(i,j))\n\n\n for i in I:\n model.addCons(quicksum(x[i,j] for j in J) == 1, \"Assign(%s)\"%i)\n\n for j in J:\n model.addCons(x[i,j] <= y[j], \"Strong(%s,%s)\"%(i,j))\n model.addCons(c[i,j]*x[i,j] <= z, \"Max_x(%s,%s)\"%(i,j))\n\n model.addCons(quicksum(y[j] for j in J) == k, \"Facilities\")\n\n model.setObjective(z, \"minimize\")\n model.data = x,y\n\n return model", "docstring": "kcenter -- minimize the maximum travel cost from customers to k facilities.\n Parameters:\n - I: set of customers\n - J: set of potential facilities\n - c[i,j]: cost of servicing customer i from facility j\n - k: number of facilities to be used\n Returns a model, ready to be solved.", "source": "juraj_google_style"} +{"code": "def setDirname(self, dirname):\n\n # Make sure the dirname always ends in\n # a path separator character\n sep = utils._getPathSep(dirname)\n if not dirname.endswith(sep):\n dirname += sep\n\n self._dir = utils.asString(dirname)", "docstring": "Set a new directory name for the sequence.\n\nArgs:\n dirname (str): the new directory name", "source": "juraj_google_style"} +{"code": "def startstop(inst_id, cmdtodo):\n\n tar_inst = EC2R.Instance(inst_id)\n thecmd = getattr(tar_inst, cmdtodo)\n response = thecmd()\n return response", "docstring": "Start or Stop the Specified Instance.\n\nArgs:\n inst_id (str): instance-id to perform command against\n cmdtodo (str): command to perform (start or stop)\n\nReturns:\n response (dict): reponse returned from AWS after\n performing specified action.", "source": "juraj_google_style"} +{"code": "def last_timestamp(self, event_key=None):\n\n if event_key is None:\n timestamps = [self._trackers[key].first_timestamp\n for key in self._trackers]\n return max(timestamp for timestamp in timestamps if timestamp >= 0)\n else:\n return self._trackers[event_key].last_timestamp", "docstring": "Obtain the last timestamp.\n\nArgs:\n event_key: the type key of the sought events (e.g., constants.NAN_KEY). If\n None, includes all event type keys.\n\nReturns:\n Last (latest) timestamp of all the events of the given type (or all\n event types if event_key is None).", "source": "juraj_google_style"} +{"code": "def ReceiveMessagesRelationalFlows(self, client_id, messages):\n\n now = time.time()\n unprocessed_msgs = []\n message_handler_requests = []\n dropped_count = 0\n for session_id, msgs in iteritems(\n collection.Group(messages, operator.attrgetter(\"session_id\"))):\n\n # Remove and handle messages to WellKnownFlows\n leftover_msgs = self.HandleWellKnownFlows(msgs)\n\n for msg in leftover_msgs:\n if (msg.auth_state != msg.AuthorizationState.AUTHENTICATED and\n msg.session_id != self.unauth_allowed_session_id):\n dropped_count += 1\n continue\n\n if session_id in queue_manager.session_id_map:\n message_handler_requests.append(\n rdf_objects.MessageHandlerRequest(\n client_id=msg.source.Basename(),\n handler_name=queue_manager.session_id_map[session_id],\n request_id=msg.response_id,\n request=msg.payload))\n else:\n unprocessed_msgs.append(msg)\n\n if dropped_count:\n logging.info(\"Dropped %d unauthenticated messages for %s\", dropped_count,\n client_id)\n\n if unprocessed_msgs:\n flow_responses = []\n for message in unprocessed_msgs:\n flow_responses.append(\n rdf_flow_objects.FlowResponseForLegacyResponse(message))\n\n data_store.REL_DB.WriteFlowResponses(flow_responses)\n\n for msg in unprocessed_msgs:\n if msg.type == rdf_flows.GrrMessage.Type.STATUS:\n stat = rdf_flows.GrrStatus(msg.payload)\n if stat.status == rdf_flows.GrrStatus.ReturnedStatus.CLIENT_KILLED:\n # A client crashed while performing an action, fire an event.\n crash_details = rdf_client.ClientCrash(\n client_id=client_id,\n session_id=msg.session_id,\n backtrace=stat.backtrace,\n crash_message=stat.error_message,\n nanny_status=stat.nanny_status,\n timestamp=rdfvalue.RDFDatetime.Now())\n events.Events.PublishEvent(\n \"ClientCrash\", crash_details, token=self.token)\n\n if message_handler_requests:\n data_store.REL_DB.WriteMessageHandlerRequests(message_handler_requests)\n\n logging.debug(\"Received %s messages from %s in %s sec\", len(messages),\n client_id,\n time.time() - now)", "docstring": "Receives and processes messages for flows stored in the relational db.\n\nArgs:\n client_id: The client which sent the messages.\n messages: A list of GrrMessage RDFValues.", "source": "juraj_google_style"} +{"code": "def search_by_name(cls, name):\n\n records = aleph.downloadRecords(\n aleph.searchInAleph(\"aut\", name, False, \"wau\")\n )\n\n for record in records:\n marc = MARCXMLRecord(record)\n\n author = cls.parse_author(marc)\n\n if author:\n yield author", "docstring": "Look for author in NK Aleph authority base by `name`.\n\nArgs:\n name (str): Author's name.\n\nYields:\n obj: :class:`Author` instances.", "source": "juraj_google_style"} +{"code": "def check_data_type(self):\n\n metadata_type = self.column_metadata.get('type')\n if self.type != metadata_type and metadata_type not in self.type:\n raise ValueError('Types of transformer don\\'t match')", "docstring": "Check the type of the transformer and column match.\n\nArgs:\n column_metadata(dict): Metadata of the column.\n\n Raises a ValueError if the types don't match", "source": "juraj_google_style"} +{"code": "def __init__(self, value):\n\n super(BinaryParserException, self).__init__()\n self._value = value", "docstring": "Constructor.\n\nArgs:\n - `value`: A string description.", "source": "juraj_google_style"} +{"code": "def _get_colordata(bs, elements, bs_projection):\n\n contribs = {}\n if bs_projection and bs_projection.lower() == \"elements\":\n projections = bs.get_projection_on_elements()\n\n for spin in (Spin.up, Spin.down):\n if spin in bs.bands:\n contribs[spin] = []\n for band_idx in range(bs.nb_bands):\n colors = []\n for k_idx in range(len(bs.kpoints)):\n if bs_projection and bs_projection.lower() == \"elements\":\n c = [0, 0, 0]\n projs = projections[spin][band_idx][k_idx]\n # note: squared color interpolations are smoother\n # see: https://youtu.be/LKnqECcg6Gw\n projs = dict(\n [(k, v ** 2) for k, v in projs.items()])\n total = sum(projs.values())\n if total > 0:\n for idx, e in enumerate(elements):\n c[idx] = math.sqrt(projs[\n e] / total) # min is to handle round errors\n\n c = [c[1], c[2],\n c[0]] # prefer blue, then red, then green\n\n else:\n c = [0, 0, 0] if spin == Spin.up \\\n else [0, 0,\n 1] # black for spin up, blue for spin down\n\n colors.append(c)\n\n contribs[spin].append(colors)\n contribs[spin] = np.array(contribs[spin])\n\n return contribs", "docstring": "Get color data, including projected band structures\n\nArgs:\n bs: Bandstructure object\n elements: elements (in desired order) for setting to blue, red, green\n bs_projection: None for no projection, \"elements\" for element projection\n\n Returns:", "source": "juraj_google_style"} +{"code": "def gff3_verifier(entries, line=None):\n\n\n regex = r'^[a-zA-Z0-9.:^*$@!+_?-|]+\\t.+\\t.+\\t\\d+\\t\\d+\\t' \\\n + r'\\d*\\.?\\d*\\t[+-.]\\t[.0-2]\\t.+{0}$'.format(os.linesep)\n delimiter = r'\\t'\n\n for entry in entries:\n try:\n entry_verifier([entry.write()], regex, delimiter)\n except FormatError as error:\n # Format info on what entry error came from\n if line:\n intro = 'Line {0}'.format(str(line))\n elif error.part == 0:\n intro = 'Entry with source {0}'.format(entry.source)\n else:\n intro = 'Entry with Sequence ID {0}'.format(entry.seqid)\n\n # Generate error\n if error.part == 0:\n msg = '{0} has no Sequence ID'.format(intro)\n elif error.part == 1:\n msg = '{0} has no source'.format(intro)\n elif error.part == 2:\n msg = '{0} has non-numerical characters in type'.format(intro)\n elif error.part == 3:\n msg = '{0} has non-numerical characters in ' \\\n 'start position'.format(intro)\n elif error.part == 4:\n msg = '{0} has non-numerical characters in ' \\\n 'end position'.format(intro)\n elif error.part == 5:\n msg = '{0} has non-numerical characters in score'.format(intro)\n elif error.part == 6:\n msg = '{0} strand not in [+-.]'.format(intro)\n elif error.part == 7:\n msg = '{0} phase not in [.0-2]'.format(intro)\n elif error.part == 8:\n msg = '{0} has no attributes'.format(intro)\n else:\n msg = 'Unknown Error: Likely a Bug'\n raise FormatError(message=msg)\n\n if line:\n line += 1", "docstring": "Raises error if invalid GFF3 format detected\n\nArgs:\n entries (list): A list of GFF3Entry instances\n\n line (int): Line number of first entry\n\nRaises:\n FormatError: Error when GFF3 format incorrect with descriptive message", "source": "juraj_google_style"} +{"code": "def _should_catch_error(self, error, errors=()):\n\n\n caught_errors = (\n errors or\n self.session.driver.invalid_element_errors + (ElementNotFound,))\n\n return isinstance(error, caught_errors)", "docstring": "Returns whether to catch the given error.\n\nArgs:\n error (Exception): The error to consider.\n errors (Tuple[Type[Exception], ...], optional): The exception types that should be\n caught. Defaults to :class:`ElementNotFound` plus any driver-specific invalid\n element errors.\n\nReturns:\n bool: Whether to catch the given error.", "source": "juraj_google_style"} +{"code": "def post(self, *messages):\n\n url = \"queues/%s/messages\" % self.name\n\n msgs = [{'body': msg} if isinstance(msg, basestring) else msg\n for msg in messages]\n data = json.dumps({'messages': msgs})\n\n result = self.client.post(url=url, body=data,\n headers={'Content-Type': 'application/json'})\n\n return result['body']", "docstring": "Executes an HTTP request to create message on the queue.\n Creates queue if not existed.\n\nArgs:\n messages -- An array of messages to be added to the queue.", "source": "juraj_google_style"} +{"code": "def walk(self, walk_func):\n\n nodes = self.topological_sort()\n # Reverse so we start with nodes that have no dependencies.\n nodes.reverse()\n\n for n in nodes:\n walk_func(n)", "docstring": "Walks each node of the graph in reverse topological order.\n This can be used to perform a set of operations, where the next\n operation depends on the previous operation. It's important to note\n that walking happens serially, and is not paralellized.\n\nArgs:\n walk_func (:class:`types.FunctionType`): The function to be called\n on each node of the graph.", "source": "juraj_google_style"} +{"code": "def summaryDF(date=None, token='', version=''):\n\n df = pd.DataFrame(summary(date, token, version))\n _toDatetime(df)\n return df", "docstring": "https://iexcloud.io/docs/api/#stats-historical-summary\n\nArgs:\n token (string); Access token\n version (string); API version\n\nReturns:\n DataFrame: result", "source": "juraj_google_style"} +{"code": "def emit_tree_format(tree, verbose=False):\n\n if verbose:\n print(\"Converting: \" + repr(tree))\n ret_str = __recursive_formatter(tree)\n return ret_str", "docstring": "Returns a tree representation of a parse tree.\n\nArgs:\n tree: the parse tree whose tree representation is to be generated\n verbose (bool): if True prints the parse tree to be formatted\n\nReturns:\n str: tree-like representation of the parse tree", "source": "juraj_google_style"} +{"code": "def adafactor_decay_rate_adam(beta2):\n\n t = tf.to_float(tf.train.get_or_create_global_step()) + 1.0\n decay = beta2 * (1.0 - tf.pow(beta2, t - 1.0)) / (1.0 - tf.pow(beta2, t))\n # decay = tf.cond(tf.equal(t, 1.0), lambda: beta2, lambda: decay)\n return decay", "docstring": "Second-moment decay rate like Adam, subsuming the correction factor.\n\nArgs:\n beta2: a float between 0 and 1\n\nReturns:\n a scalar", "source": "juraj_google_style"} +{"code": "def __init__(self, base_core, input_shape=None, name=\"skip_connection_core\"):\n\n super(SkipConnectionCore, self).__init__(name=name)\n self._base_core = base_core\n self._input_shape = input_shape", "docstring": "Construct a SkipConnectionCore.\n\nArgs:\n base_core: Base RNNCore to wrap.\n input_shape: Shape of the input as tuple, excluding the batch size.\n name: Name of the module.", "source": "juraj_google_style"} +{"code": "def __getattr__(self, name):\n\n if self.has_service_by_name(name):\n return self._service_objects[name]\n return self.__getattribute__(name)", "docstring": "Syntactic sugar to enable direct access of service objects by alias.\n\nArgs:\n name: string, the alias a service object was registered under.", "source": "juraj_google_style"} +{"code": "def restore(self, state):\n\n\n\n selector = DataStreamSelector.FromString(state.get(u'selector'))\n if self.selector != selector:\n raise ArgumentError(\"Attempted to restore an InvalidStreamWalker with a different selector\",\n selector=self.selector, serialized_data=state)\n\n if state.get(u'type') != u'invalid':\n raise ArgumentError(\"Invalid serialized state for InvalidStreamWalker\", serialized_data=state)", "docstring": "Restore the contents of this virtual stream walker.\n\nArgs:\n state (dict): The previously serialized state.\n\nRaises:\n ArgumentError: If the serialized state does not have\n a matching selector.", "source": "juraj_google_style"} +{"code": "def forum_post_list(self, creator_id=None, creator_name=None,\n topic_id=None, topic_title_matches=None,\n topic_category_id=None, body_matches=None):\n\n params = {\n 'search[creator_id]': creator_id,\n 'search[creator_name]': creator_name,\n 'search[topic_id]': topic_id,\n 'search[topic_title_matches]': topic_title_matches,\n 'search[topic_category_id]': topic_category_id,\n 'search[body_matches]': body_matches\n }\n return self._get('forum_posts.json', params)", "docstring": "Return a list of forum posts.\n\n Parameters:\n creator_id (int):\n creator_name (str):\n topic_id (int):\n topic_title_matches (str):\n topic_category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs &\n Features respectively).\n body_matches (str): Can be part of the post content.", "source": "juraj_google_style"} +{"code": "def copy_table(self, src, dst):\n\n # Create table.\n self.create_table_from(dst, src)\n\n # Copy contents of src to dst.\n self.execute(\"INSERT INTO {dst} SELECT * FROM {src}\"\n .format(dst=dst, src=src))\n\n # Commit changes.\n self.commit()", "docstring": "Create a carbon copy of the source table.\n\nArgs:\n src (str): The name of the table to copy.\n dst (str): The name of the target duplicate table.\n\nRaises:\n sql.OperationalError: If source table does not exist.", "source": "juraj_google_style"} +{"code": "def ParseNetworkConnectivityUsage(\n self, parser_mediator, cache=None, database=None, table=None,\n **unused_kwargs):\n\n # TODO: consider making ConnectStartTime + ConnectedTime an event.\n self._ParseGUIDTable(\n parser_mediator, cache, database, table,\n self._NETWORK_CONNECTIVITY_USAGE_VALUES_MAP,\n SRUMNetworkConnectivityUsageEventData)", "docstring": "Parses the network connectivity usage monitor table.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n cache (Optional[ESEDBCache]): cache, which contains information about\n the identifiers stored in the SruDbIdMapTable table.\n database (Optional[pyesedb.file]): ESE database.\n table (Optional[pyesedb.table]): table.", "source": "juraj_google_style"} +{"code": "def add_spin_by_element(self, spins):\n\n for site in self.sites:\n new_sp = {}\n for sp, occu in site.species.items():\n sym = sp.symbol\n oxi_state = getattr(sp, \"oxi_state\", None)\n new_sp[Specie(sym, oxidation_state=oxi_state,\n properties={'spin': spins.get(str(sp), spins.get(sym, None))})] = occu\n site.species = new_sp", "docstring": "Add spin states to a structure.\n\nArgs:\n spisn (dict): Dict of spins associated with\n elements or species, e.g. {\"Ni\":+5} or {\"Ni2+\":5}", "source": "juraj_google_style"} +{"code": "def __init__(self, solution_size, population_size=20):\n\n super(StandardOptimizer, self).__init__()\n\n # Set general algorithm paramaters\n self._solution_size = solution_size\n self._population_size = population_size\n\n # Parameters for metaheuristic optimization\n self._hyperparameters['_population_size'] = {\n 'type': 'int',\n 'min': 2,\n 'max': 1026\n }", "docstring": "Initialize general optimization attributes and bookkeeping\n\nArgs:\n solution_size: The number of values in each solution.\n population_size: The number of solutions in every generation.", "source": "juraj_google_style"} +{"code": "def markdown_table(data, headers):\n\n\n maxx = [max([len(x) for x in column]) for column in zip(*data)]\n maxx = [max(ll) for ll in zip(maxx, [len(x) for x in headers])]\n mask = \" | \".join([\"%-{0:d}s\".format(n) for n in maxx])\n\n ret = [mask % headers]\n\n ret.append(\" | \".join([\"-\"*n for n in maxx]))\n for line in data:\n ret.append(mask % line)\n return ret", "docstring": "Creates MarkDown table. Returns list of strings\n\nArgs:\n data -- [(cell00, cell01, ...), (cell10, cell11, ...), ...]\n headers -- sequence of strings: (header0, header1, ...)", "source": "juraj_google_style"} +{"code": "def check_tweet(tweet, validation_checking=False):\n\n\n if \"id\" not in tweet:\n raise NotATweetError(\"This text has no 'id' key\")\n\n original_format = is_original_format(tweet)\n\n if original_format:\n _check_original_format_tweet(tweet, validation_checking=validation_checking)\n else:\n _check_activity_streams_tweet(tweet, validation_checking=validation_checking)\n\n return original_format", "docstring": "Ensures a tweet is valid and determines the type of format for the tweet.\n\nArgs:\n tweet (dict/Tweet): the tweet payload\n validation_checking (bool): check for valid key structure in a tweet.", "source": "juraj_google_style"} +{"code": "def create(self, resource, timeout=-1):\n\n return self._client.create(resource, timeout=timeout, default_values=self.DEFAULT_VALUES)", "docstring": "Creates a scope.\n\nArgs:\n resource (dict): Object to create.\n timeout:\n Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n in OneView, just stop waiting for its completion.\n\nReturns:\n dict: Created scope.", "source": "juraj_google_style"} +{"code": "def zip(self, destination: typing.Union[str, Path] = None, encode: bool = True) -> str:\n\n if encode:\n self._encode()\n\n if destination is None:\n destination_path = self.miz_path.parent.joinpath(f'{self.miz_path.stem}_EMIZ.miz')\n else:\n destination_path = elib.path.ensure_file(destination, must_exist=False)\n\n LOGGER.debug('zipping mission to: %s', destination_path)\n\n destination_path.write_bytes(dummy_miz)\n\n with ZipFile(str(destination_path), mode='w', compression=8) as zip_file:\n\n for root, _, items in os.walk(self.temp_dir.absolute()):\n for item in items:\n item_abs_path = Path(root, item).absolute()\n item_rel_path = Path(item_abs_path).relative_to(self.temp_dir)\n zip_file.write(item_abs_path, arcname=item_rel_path)\n\n return str(destination_path)", "docstring": "Write mission, dictionary etc. to a MIZ file\n\nArgs:\n destination: target MIZ file (if none, defaults to source MIZ + \"_EMIZ\"\n\n Returns: destination file", "source": "juraj_google_style"} +{"code": "def extract_derivative_feature(feature):\n\n first_derivative_feature = processing.derivative_extraction(\n feature, DeltaWindows=2)\n second_derivative_feature = processing.derivative_extraction(\n first_derivative_feature, DeltaWindows=2)\n\n # Creating the future cube for each file\n feature_cube = np.concatenate(\n (feature[:, :, None], first_derivative_feature[:, :, None],\n second_derivative_feature[:, :, None]),\n axis=2)\n return feature_cube", "docstring": "This function extracts temporal derivative features which are\n first and second derivatives.\n\nArgs:\n feature (array): The feature vector which its size is: N x M\n\nReturns:\n array: The feature cube vector which contains the static, first and second derivative features of size: N x M x 3", "source": "juraj_google_style"} +{"code": "def mkdir_uchroot(dirpath, root=\".\"):\n\n from benchbuild.utils.uchroot import no_args, uretry\n\n uchroot = no_args()\n uchroot = uchroot[\"-E\", \"-A\", \"-C\", \"-w\", \"/\", \"-r\"]\n uchroot = uchroot[os.path.abspath(root)]\n uretry(uchroot[\"--\", \"/bin/mkdir\", \"-p\", dirpath])", "docstring": "Create a file inside a uchroot env.\n\n You will want to use this when you need to create a file with apropriate\n rights inside a uchroot container with subuid/subgid handling enabled.\n\nArgs:\n dirpath:\n The dirpath that should be created. Absolute inside the\n uchroot container.\n root:\n The root PATH of the container filesystem as seen outside of\n the container.", "source": "juraj_google_style"} +{"code": "def get(self, url, params=None, **kwargs):\n\n check_type(url, basestring, may_be_none=False)\n check_type(params, dict)\n\n # Expected response code\n erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET'])\n\n response = self.request('GET', url, erc, params=params, **kwargs)\n return extract_and_parse_json(response)", "docstring": "Sends a GET request.\n\nArgs:\n url(basestring): The URL of the API endpoint.\n params(dict): The parameters for the HTTP GET request.\n **kwargs:\n erc(int): The expected (success) response code for the request.\n others: Passed on to the requests package.\n\nRaises:\n ApiError: If anything other than the expected response code is\n returned by the Webex Teams API endpoint.", "source": "juraj_google_style"} +{"code": "def laid_out_pcoord(self, mesh_axis):\n\n divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:])\n modulus = self.shape[mesh_axis].size\n def my_fn(pnum):\n return (pnum // divisor) % modulus\n return self.slicewise(my_fn, self.laid_out_pnum())", "docstring": "Returns a LaidOutTensor containing the processor coordinate.\n\nArgs:\n mesh_axis: int.\n\nReturns:\n LaidOutTensor where each slice is an integer scalar.", "source": "juraj_google_style"} +{"code": "def load(self, fobj, index=None):\n\n if index is None:\n index = self._get_tab_index()\n page = self.pages[index]\n\n if fobj is None:\n return\n\n\n if not isinstance(fobj, tuple(page.clss_load)):\n raise RuntimeError('Object to load must be in {0!s} (not a {1!s})'.format(\n [x.__name__ for x in page.clss_load], fobj.__class__.__name__))\n\n page.editor.load(fobj)\n self._update_gui_text_tabs()", "docstring": "Loads given DataFile object. **tolerant with None**\n\nArgs:\n fobj: object of one of accepted classes\n index: tab index to load fobj into. If not passed, loads into current tab", "source": "juraj_google_style"} +{"code": "def build_batch(cls, size, **kwargs):\n\n return [cls.build(**kwargs) for _ in range(size)]", "docstring": "Build a batch of instances of the given class, with overriden attrs.\n\nArgs:\n size (int): the number of instances to build\n\nReturns:\n object list: the built instances", "source": "juraj_google_style"} +{"code": "def select_files(self, what=\"o\"):\n\n choices = collections.OrderedDict([\n (\"i\", self.input_file),\n (\"o\", self.output_file),\n (\"f\", self.files_file),\n (\"j\", self.job_file),\n (\"l\", self.log_file),\n (\"e\", self.stderr_file),\n (\"q\", self.qout_file),\n ])\n\n if what == \"all\":\n return [getattr(v, \"path\") for v in choices.values()]\n\n selected = []\n for c in what:\n try:\n selected.append(getattr(choices[c], \"path\"))\n except KeyError:\n logger.warning(\"Wrong keyword %s\" % c)\n\n return selected", "docstring": "Helper function used to select the files of a task.\n\nArgs:\n what: string with the list of characters selecting the file type\n Possible choices:\n i ==> input_file,\n o ==> output_file,\n f ==> files_file,\n j ==> job_file,\n l ==> log_file,\n e ==> stderr_file,\n q ==> qout_file,\n all ==> all files.", "source": "juraj_google_style"} +{"code": "def gpio_set(self, pins, states):\n\n if len(pins) != len(states):\n raise ValueError('Length mismatch between pins and states.')\n\n size = len(pins)\n indices = (ctypes.c_uint8 * size)(*pins)\n states = (ctypes.c_uint8 * size)(*states)\n result_states = (ctypes.c_uint8 * size)()\n result = self._dll.JLINK_EMU_GPIO_SetState(ctypes.byref(indices),\n ctypes.byref(states),\n ctypes.byref(result_states),\n size)\n if result < 0:\n raise errors.JLinkException(result)\n\n return list(result_states)", "docstring": "Sets the state for one or more user-controllable GPIOs.\n\n For each of the given pins, sets the the corresponding state based on\n the index.\n\nArgs:\n self (JLink): the ``JLink`` instance\n pins (list): list of GPIO indices\n states (list): list of states to set\n\nReturns:\n A list of updated states.\n\nRaises:\n JLinkException: on error.\n ValueError: if ``len(pins) != len(states)``", "source": "juraj_google_style"} +{"code": "def __init__(self, scopes=None, service_account_name='default', **kwds):\n\n # If there is a connectivity issue with the metadata server,\n # detection calls may fail even if we've already successfully\n # identified these scopes in the same execution. However, the\n # available scopes don't change once an instance is created,\n # so there is no reason to perform more than one query.\n self.__service_account_name = service_account_name\n cached_scopes = None\n cache_filename = kwds.get('cache_filename')\n if cache_filename:\n cached_scopes = self._CheckCacheFileForMatch(\n cache_filename, scopes)\n\n scopes = cached_scopes or self._ScopesFromMetadataServer(scopes)\n\n if cache_filename and not cached_scopes:\n self._WriteCacheFile(cache_filename, scopes)\n\n # We check the scopes above, but don't need them again after\n # this point. Newer versions of oauth2client let us drop them\n # here, but since we support older versions as well, we just\n # catch and squelch the warning.\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n super(GceAssertionCredentials, self).__init__(scope=scopes, **kwds)", "docstring": "Initializes the credentials instance.\n\nArgs:\n scopes: The scopes to get. If None, whatever scopes that are\n available to the instance are used.\n service_account_name: The service account to retrieve the scopes\n from.\n **kwds: Additional keyword args.", "source": "juraj_google_style"} +{"code": "def shop(self, index):\n\n return UserShopFront(self.usr, item.owner, item.id, str(item.price))", "docstring": "Return's the user shop the indexed item is in\n\n Parameters:\n index (int) -- The item index\n\n Returns\n UserShopFront - User shop item is in", "source": "juraj_google_style"} +{"code": "def add_string(self, data):\n\n lines = []\n while data:\n match = self._line_end_re.search(data)\n if match is None:\n chunk = data\n else:\n chunk = data[:match.end()]\n\n data = data[len(chunk):]\n\n if self._buf and self._buf[-1].endswith(b('\\r')) and not chunk.startswith(b('\\n')):\n # if we get a carriage return followed by something other than\n # a newline then we assume that we're overwriting the current\n # line (ie. a progress bar)\n #\n # We don't terminate lines that end with a carriage return until\n # we see what's coming next so we can distinguish between a\n # progress bar situation and a Windows line terminator.\n #\n # TODO(adrian): some day these hacks should be replaced with\n # real terminal emulation\n lines.append(self._finish_line())\n\n self._buf.append(chunk)\n if chunk.endswith(b('\\n')):\n lines.append(self._finish_line())\n\n return lines", "docstring": "Process some data splitting it into complete lines and buffering the rest\n\nArgs:\n data: A `str` in Python 2 or `bytes` in Python 3\n\nReturns:\n list of complete lines ending with a carriage return (eg. a progress\n bar) or a newline.", "source": "juraj_google_style"} +{"code": "def rotate(self, matrix, tol=1e-3):\n\n matrix = SquareTensor(matrix)\n if not matrix.is_rotation(tol):\n raise ValueError(\"Rotation matrix is not valid.\")\n sop = SymmOp.from_rotation_and_translation(matrix,\n [0., 0., 0.])\n return self.transform(sop)", "docstring": "Applies a rotation directly, and tests input matrix to ensure a valid\n rotation.\n\nArgs:\n matrix (3x3 array-like): rotation matrix to be applied to tensor\n tol (float): tolerance for testing rotation matrix validity", "source": "juraj_google_style"} +{"code": "def for_executor(cls, executor: Optional[Executor]) -> 'Subsystem':\n\n if isinstance(executor, ThreadPoolExecutor):\n return _ThreadingSubsystem(executor)\n elif executor is None:\n return _AsyncioSubsystem()\n else:\n raise TypeError(executor)", "docstring": "Return a subsystem based on the given executor. If ``executor`` is\n None, use :mod:`asyncio`. If ``executor`` is a\n :class:`concurrent.futures.ThreadPoolExecutor`, use :mod:`threading`.\n\nArgs:\n executor: The executor in use, if any.", "source": "juraj_google_style"} +{"code": "def _updateInferenceStats(self, statistics, objectName=None):\n\n L6aLearnableCells = self.getL6aLearnableCells()\n L6aSensoryAssociatedCells = self.getL6aSensoryAssociatedCells()\n L6aRepresentations = self.getL6aRepresentations()\n L4Representations = self.getL4Representations()\n L4PredictedCells = self.getL4PredictedCells()\n L2Representation = self.getL2Representations()\n\n for i in xrange(self.numColumns):\n statistics[\"L6a SensoryAssociatedCells C\" + str(i)].append(\n len(L6aSensoryAssociatedCells[i]))\n statistics[\"L6a LearnableCells C\" + str(i)].append(\n len(L6aLearnableCells[i]))\n statistics[\"L6a Representation C\" + str(i)].append(\n len(L6aRepresentations[i]))\n statistics[\"L4 Representation C\" + str(i)].append(\n len(L4Representations[i]))\n statistics[\"L4 Predicted C\" + str(i)].append(len(L4PredictedCells[i]))\n statistics[\"L2 Representation C\" + str(i)].append(\n len(L2Representation[i]))\n statistics[\"Full L2 SDR C\" + str(i)].append(sorted(\n [int(c) for c in L2Representation[i]]))\n statistics[\"L4 Apical Segments C\" + str(i)].append(len(\n self.L4Regions[i].getSelf()._tm.getActiveApicalSegments()))\n\n # add true overlap and classification result if objectName was learned\n if objectName in self.learnedObjects:\n objectRepresentation = self.learnedObjects[objectName]\n statistics[\"Overlap L2 with object C\" + str(i)].append(\n len(objectRepresentation[i] & L2Representation[i]))\n\n if objectName in self.learnedObjects:\n if self.isObjectClassified(objectName, minOverlap=30):\n statistics[\"Correct classification\"].append(1.0)\n else:\n statistics[\"Correct classification\"].append(0.0)", "docstring": "Updates the inference statistics.\n\n Parameters:\n ----------------------------\n @param statistics (dict)\n Dictionary in which to write the statistics\n\n @param objectName (str)\n Name of the inferred object, if known. Otherwise, set to None.", "source": "juraj_google_style"} +{"code": "def probabilistic_collocation(order, dist, subset=.1):\n\n abscissas, weights = chaospy.quad.collection.golub_welsch(order, dist)\n\n likelihood = dist.pdf(abscissas)\n\n alpha = numpy.random.random(len(weights))\n alpha = likelihood > alpha*subset*numpy.max(likelihood)\n\n abscissas = abscissas.T[alpha].T\n weights = weights[alpha]\n return abscissas, weights", "docstring": "Probabilistic collocation method.\n\nArgs:\n order (int, numpy.ndarray) : Quadrature order along each axis.\n dist (Dist) : Distribution to generate samples from.\n subset (float) : Rate of which to removed samples.", "source": "juraj_google_style"} +{"code": "def CanonicalPathToLocalPath(path):\n r\n # Account for raw devices\n path = path.replace(\"/\\\\\", \"\\\\\")\n path = path.replace(\"/\", \"\\\\\")\n m = re.match(r\"\\\\([a-zA-Z]):(.*)$\", path)\n if m:\n path = \"%s:\\\\%s\" % (m.group(1), m.group(2).lstrip(\"\\\\\"))\n\n return path", "docstring": "r\"\"\"Converts the canonical paths as used by GRR to OS specific paths.\n\n Due to the inconsistencies between handling paths in windows we need to\n convert a path to an OS specific version prior to using it. This function\n should be called just before any OS specific functions.\n\n Canonical paths on windows have:\n - / instead of \\.\n - Begin with /X:// where X is the drive letter.\n\nArgs:\n path: A canonical path specification.\n\nReturns:\n A windows specific path.", "source": "juraj_google_style"} +{"code": "def __init__(self, config={}):\n\n self._config = config\n\n # The child class should override these properties or else the\n # restclient won't work. Reevalute whether to do this as an abstract\n # base class so it doesn't get used by itself.\n self._headers = {}\n self._base_url = \"\"\n\n if config.get('session'):\n self._session = requests.Session()\n else:\n self._session = requests", "docstring": "Base class for interacting with RESTful APIs\n Child class MUST have a ._base_url property!\n\nArgs:\n config (dict): Arbitrary options that child classes can access", "source": "juraj_google_style"} +{"code": "def console_get_alignment(con: tcod.console.Console) -> int:\n\n return int(lib.TCOD_console_get_alignment(_console(con)))", "docstring": "Return this consoles current alignment mode.\n\nArgs:\n con (Console): Any Console instance.\n\n .. deprecated:: 8.5\n Check :any:`Console.default_alignment` instead.", "source": "juraj_google_style"} +{"code": "def sync(coro, timeout=None):\n\n loop = initloop()\n return asyncio.run_coroutine_threadsafe(coro, loop).result(timeout)", "docstring": "Schedule a coroutine to run on the global loop and return it's result.\n\nArgs:\n coro (coroutine): The coroutine instance.\n\nNote:\n This API is thread safe and should only be called by non-loop threads.", "source": "juraj_google_style"} +{"code": "def normalize_partial_name(decl):\n\n if decl.cache.normalized_partial_name is None:\n decl.cache.normalized_partial_name = normalize(decl.partial_name)\n return decl.cache.normalized_partial_name", "docstring": "Cached variant of normalize\n\nArgs:\n decl (declaration.declaration_t): the declaration\n\nReturns:\n str: normalized name", "source": "juraj_google_style"} +{"code": "def __init__(self, launchdjobs):\n\n self.launchdjobs = launchdjobs\n\n self.blacklist_regex = [\n re.compile(r\"^0x[a-z0-9]+\\.anonymous\\..+$\"),\n re.compile(r\"^0x[a-z0-9]+\\.mach_init\\.(crash_inspector|Inspector)$\"),\n ]", "docstring": "Initialize.\n\nArgs:\n launchdjobs: NSCFArray of NSCFDictionarys containing launchd job data from\n the ServiceManagement framework.", "source": "juraj_google_style"} +{"code": "def array_to_base64_png(array):\n\n # TODO(cais): Deal with 3D case.\n # TODO(cais): If there are None values in here, replace them with all NaNs.\n array = np.array(array, dtype=np.float32)\n if len(array.shape) != 2:\n raise ValueError(\n \"Expected rank-2 array; received rank-%d array.\" % len(array.shape))\n if not np.size(array):\n raise ValueError(\n \"Cannot encode an empty array (size: %s) as image.\" % (array.shape,))\n\n is_infinity = np.isinf(array)\n is_positive = array > 0.0\n is_positive_infinity = np.logical_and(is_infinity, is_positive)\n is_negative_infinity = np.logical_and(is_infinity,\n np.logical_not(is_positive))\n is_nan = np.isnan(array)\n finite_indices = np.where(np.logical_and(np.logical_not(is_infinity),\n np.logical_not(is_nan)))\n if np.size(finite_indices):\n # Finite subset is not empty.\n minval = np.min(array[finite_indices])\n maxval = np.max(array[finite_indices])\n scaled = np.array((array - minval) / (maxval - minval) * 255,\n dtype=np.uint8)\n rgb = np.repeat(np.expand_dims(scaled, -1), IMAGE_COLOR_CHANNELS, axis=-1)\n else:\n rgb = np.zeros(array.shape + (IMAGE_COLOR_CHANNELS,), dtype=np.uint8)\n\n # Color-code pixels that correspond to infinities and nans.\n rgb[is_positive_infinity] = POSITIVE_INFINITY_RGB\n rgb[is_negative_infinity] = NEGATIVE_INFINITY_RGB\n rgb[is_nan] = NAN_RGB\n\n image_encoded = base64.b64encode(encoder.encode_png(rgb))\n return image_encoded", "docstring": "Convert an array into base64-enoded PNG image.\n\nArgs:\n array: A 2D np.ndarray or nested list of items.\n\nReturns:\n A base64-encoded string the image. The image is grayscale if the array is\n 2D. The image is RGB color if the image is 3D with lsat dimension equal to\n 3.\n\nRaises:\n ValueError: If the input `array` is not rank-2, or if the rank-2 `array` is\n empty.", "source": "juraj_google_style"} +{"code": "def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:\n\n series = table[self.name]\n\n self._check_series_name(series)\n\n validators = self.validators\n\n results = pd.DataFrame({validator: series for validator in validators}, index=series.index)\n\n for name, func in validators.items():\n results[name] = func(results[name])\n\n results['dtype'] = self._validate_series_dtype(series)\n\n if self.unique:\n results['unique'] = v.funcs.unique(series)\n\n if failed_only:\n results = find_failed_rows(results)\n\n return results", "docstring": "Return a dataframe of validation results for the appropriate series vs the vector of validators.\n\nArgs:\n table (pd.DataFrame): A dataframe on which to apply validation logic.\n failed_only (bool): If ``True``: return only the indexes that failed to validate.", "source": "juraj_google_style"} +{"code": "def Deserialize(self, reader):\n\n super(ContractState, self).Deserialize(reader)\n\n code = FunctionCode()\n code.Deserialize(reader)\n self.Code = code\n\n self.ContractProperties = reader.ReadUInt8()\n self.Name = reader.ReadVarString(max=252)\n self.CodeVersion = reader.ReadVarString(max=252)\n self.Author = reader.ReadVarString(max=252)\n self.Email = reader.ReadVarString(max=252)\n self.Description = reader.ReadVarString(max=65536)", "docstring": "Deserialize full object.\n\nArgs:\n reader (neocore.IO.BinaryReader):", "source": "juraj_google_style"} +{"code": "def SetCACertificatesPath(self, ca_certificates_path):\n\n if not ca_certificates_path:\n return\n\n if not os.path.exists(ca_certificates_path):\n raise errors.BadConfigOption(\n 'No such certificate file: {0:s}.'.format(ca_certificates_path))\n\n self._ca_certs = ca_certificates_path\n logger.debug('Elasticsearch ca_certs: {0!s}'.format(ca_certificates_path))", "docstring": "Sets the path to the CA certificates.\n\nArgs:\n ca_certificates_path (str): path to file containing a list of root\n certificates to trust.\n\nRaises:\n BadConfigOption: if the CA certificates file does not exist.", "source": "juraj_google_style"} +{"code": "def _create_outbound_stream(self, config=None):\n\n if config is None:\n raise ValueError('No stream config to create stream from.')\n\n name = self._get_stream_name(config)\n stream_handlers = self._get_stream_handlers(config, name)\n stream_input = config.get('input', None)\n stream_output = config.get('output', None)\n\n if type(stream_output) is int:\n return PortOutputStream(name,\n stream_input,\n stream_output,\n stream_handlers,\n zmq_args={'zmq_context': self.broker.context,\n 'zmq_proxy_xsub_url': self.broker.XSUB_URL,\n 'zmq_proxy_xpub_url': self.broker.XPUB_URL})\n else:\n if stream_output is not None:\n log.warn(\"Output of stream {} is not an integer port. \"\n \"Stream outputs can only be ports.\".format(name))\n return ZMQStream(name,\n stream_input,\n stream_handlers,\n zmq_args={'zmq_context': self.broker.context,\n 'zmq_proxy_xsub_url': self.broker.XSUB_URL,\n 'zmq_proxy_xpub_url': self.broker.XPUB_URL})", "docstring": "Creates an outbound stream from its config.\n\n Params:\n config: stream configuration as read by ait.config\n\nReturns:\n stream: a Stream\n\nRaises:\n ValueError: if any of the required config values are missing", "source": "juraj_google_style"} +{"code": "def _OpenFileObject(self, path_spec):\n\n if not path_spec.HasParent():\n raise errors.PathSpecError(\n 'Unsupported path specification without parent.')\n\n file_object = resolver.Resolver.OpenFileObject(\n path_spec.parent, resolver_context=self._resolver_context)\n qcow_file = pyqcow.file()\n qcow_file.open_file_object(file_object)\n return qcow_file", "docstring": "Opens the file-like object defined by path specification.\n\nArgs:\n path_spec (PathSpec): path specification.\n\nReturns:\n pyqcow.file: a file-like object.\n\nRaises:\n PathSpecError: if the path specification is incorrect.", "source": "juraj_google_style"} +{"code": "def save_pkl(filename=None, times=None):\n\n if times is None:\n if not f.root.stopped:\n times = collapse.collapse_times()\n else:\n times = f.root.times\n else:\n if isinstance(times, (list, tuple)):\n for t in times:\n if not isinstance(t, Times):\n raise TypeError(\"Expected single Times instance or list/tuple of Times instances for param 'times'.\")\n elif not isinstance(times, Times):\n raise TypeError(\"Expected single Times instance or list/tuple of Times instances for param 'times'.\")\n if filename is not None:\n with open(str(filename), 'wb') as file:\n pickle.dump(times, file)\n else:\n return pickle.dumps(times)", "docstring": "Serialize and / or save a Times data object using pickle (cPickle).\n\nArgs:\n filename (None, optional): Filename to dump to. If not provided,\n returns serialized object.\n times (None, optional): object to dump. If non provided, uses\n current root.\n\nReturns:\n pkl: Pickled Times data object, only if no filename provided.\n\nRaises:\n TypeError: If 'times' is not a Times object or a list of tuple of\n them.", "source": "juraj_google_style"} +{"code": "def connect(url, prefix=None, **kwargs):\n\n return connection(url, prefix=get_prefix(prefix), **kwargs)", "docstring": "connect and return a connection instance from url\n\nArgs:\n - url (str): xbahn connection url", "source": "juraj_google_style"} +{"code": "def create_public_ip(access_token, subscription_id, resource_group, public_ip_name, dns_label,\n location):\n\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourceGroups/', resource_group,\n '/providers/Microsoft.Network/publicIPAddresses/', public_ip_name,\n '?api-version=', NETWORK_API])\n ip_body = {'location': location}\n properties = {'publicIPAllocationMethod': 'Dynamic'}\n properties['dnsSettings'] = {'domainNameLabel': dns_label}\n ip_body['properties'] = properties\n body = json.dumps(ip_body)\n return do_put(endpoint, body, access_token)", "docstring": "Create a public ip address.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n resource_group (str): Azure resource group name.\n public_ip_name (str): Name of the new public ip address resource.\n dns_label (str): DNS label to apply to the IP address.\n location (str): Azure data center location. E.g. westus.\n\nReturns:\n HTTP response. Public IP address JSON body.", "source": "juraj_google_style"} +{"code": "def now_playing(self, **kwargs):\n\n path = self._get_path('now_playing')\n\n response = self._GET(path, kwargs)\n self._set_attrs_to_values(response)\n return response", "docstring": "Get the list of movies playing in theatres. This list refreshes\n every day. The maximum number of items this list will include is 100.\n\nArgs:\n page: (optional) Minimum value of 1. Expected value is an integer.\n language: (optional) ISO 639-1 code.\n\nReturns:\n A dict representation of the JSON returned from the API.", "source": "juraj_google_style"} +{"code": "def generate_string(self, initial_logits, initial_state, sequence_length):\n\n\n current_logits = initial_logits\n current_state = initial_state\n\n generated_letters = []\n for _ in range(sequence_length):\n # Sample a character index from distribution.\n char_index = tf.squeeze(tf.multinomial(current_logits, 1))\n char_one_hot = tf.one_hot(char_index, self._output_size, 1.0, 0.0)\n generated_letters.append(char_one_hot)\n\n # Feed character back into the deep_lstm.\n gen_out_seq, current_state = self._core(\n tf.nn.relu(self._embed_module(char_one_hot)),\n current_state)\n current_logits = self._output_module(gen_out_seq)\n\n generated_string = tf.stack(generated_letters)\n\n return generated_string", "docstring": "Builds sub-graph to generate a string, sampled from the model.\n\nArgs:\n initial_logits: Starting logits to sample from.\n initial_state: Starting state for the RNN core.\n sequence_length: Number of characters to sample.\n\nReturns:\n A Tensor of characters, with dimensions `[sequence_length, batch_size,\n output_size]`.", "source": "juraj_google_style"} +{"code": "def __init__(self, destination, transport):\n\n self._destination = destination\n self._transport = transport", "docstring": "Create a new ADB stream.\n\nArgs:\n destination: String identifier for the destination of this stream.\n transport: AdbStreamTransport to use for reads/writes.", "source": "juraj_google_style"} +{"code": "def refresh(self, access_token=None, **kwargs):\n\n if not self.token_lock.locked():\n with self.token_lock:\n if access_token == self.access_token or access_token is None:\n if self.developer_token is not None:\n r = self._httpclient.request(\n method='POST',\n url=self.developer_token_url,\n path='/request_token',\n headers={\n 'Authorization': 'Bearer {}'.format(\n self.developer_token\n )\n },\n timeout=30,\n raise_for_status=True\n )\n\n elif all(\n [\n self.client_id,\n self.client_secret,\n self.refresh_token\n ]\n ):\n data = {\n 'client_id': self.client_id,\n 'client_secret': self.client_secret,\n 'refresh_token': self.refresh_token,\n 'grant_type': 'refresh_token'\n }\n r = self._httpclient.request(\n method='POST',\n url=self.token_url,\n json=data,\n path='/api/oauth2/RequestToken',\n **kwargs\n )\n else:\n raise PartialCredentialsError(\n \"Missing one or more required credentials\"\n )\n\n if r:\n if not r.ok:\n raise PanCloudError(\n '%s %s: %s' % (\n r.status_code, r.reason, r.text)\n )\n try:\n r_json = r.json()\n except ValueError as e:\n raise PanCloudError(\"Invalid JSON: %s\" % e)\n else:\n if r.json().get(\n 'error_description'\n ) or r.json().get(\n 'error'\n ):\n raise PanCloudError(r.text)\n self.access_token = r_json.get(\n 'access_token', None\n )\n self.jwt_exp = self._decode_exp(\n self.access_token_)\n if r_json.get('refresh_token', None):\n self.refresh_token = \\\n r_json.get('refresh_token')\n self.write_credentials()\n return self.access_token_", "docstring": "Refresh access and refresh tokens.\n\nArgs:\n access_token (str): Access token to refresh. Defaults to ``None``.\n\nReturns:\n str: Refreshed access token.", "source": "juraj_google_style"} +{"code": "def list_objects(self, path='', relative=False, first_level=False,\n max_request_entries=None):\n\n entries = 0\n next_values = []\n max_request_entries_arg = None\n\n if not relative:\n path = self.relpath(path)\n\n # From root\n if not path:\n objects = self._list_locators()\n\n # Sub directory\n else:\n objects = self._list_objects(\n self.get_client_kwargs(path), max_request_entries)\n\n # Yield file hierarchy\n for obj in objects:\n # Generate first level objects entries\n try:\n name, header, is_directory = obj\n except ValueError:\n # Locators\n name, header = obj\n is_directory = True\n\n # Start to generate subdirectories content\n if is_directory and not first_level:\n name = next_path = name.rstrip('/') + '/'\n\n if path:\n next_path = '/'.join((path.rstrip('/'), name))\n\n if max_request_entries is not None:\n max_request_entries_arg = max_request_entries - entries\n\n next_values.append((\n name, self._generate_async(self.list_objects(\n next_path, relative=True,\n max_request_entries=max_request_entries_arg))))\n\n entries += 1\n yield name, header\n if entries == max_request_entries:\n return\n\n for next_name, generator in next_values:\n # Generate other levels objects entries\n for name, header in generator:\n\n entries += 1\n yield '/'.join((next_name.rstrip('/'), name)), header\n if entries == max_request_entries:\n return", "docstring": "List objects.\n\nArgs:\n path (str): Path or URL.\n relative (bool): Path is relative to current root.\n first_level (bool): It True, returns only first level objects.\n Else, returns full tree.\n max_request_entries (int): If specified, maximum entries returned\n by request.\n\nReturns:\n generator of tuple: object name str, object header dict", "source": "juraj_google_style"} +{"code": "def parse_tmhmm_long(tmhmm_results):\n\n with open(tmhmm_results) as f:\n lines = f.read().splitlines()\n\n infodict = defaultdict(dict)\n\n for l in lines:\n if 'Number of predicted TMHs:' in l:\n gene = l.split(' Number')[0].strip('# ')\n infodict[gene]['num_tm_helices'] = int(l.split(': ')[1])\n\n if 'WARNING' in l:\n log.warning('{}: no TMHMM predictions'.format(l))\n continue\n\n # TODO: POSSIBLE N-term signal sequence - parse this\n\n # Look for the lines without #, these are the TM predicted regions\n if '#' not in l:\n stuff = l.split()\n if stuff[1] == 'TMHMM2.0':\n\n gene = stuff[0]\n region = stuff[2]\n region_start = stuff[3]\n region_end = stuff[4]\n\n if 'sequence' in infodict[gene]:\n tm_seq = infodict[gene]['sequence']\n else:\n tm_seq = ''\n\n if region == 'outside':\n info = 'O'\n elif region == 'inside':\n info = 'I'\n elif region == 'TMhelix':\n info = 'T'\n else:\n log.error('{}: unknown region type'.format(info))\n info = '-'\n\n for r in range(int(region_start), int(region_end) + 1):\n tm_seq += info\n\n infodict[gene]['sequence'] = tm_seq\n\n return infodict", "docstring": "Parse the 'long' output format of TMHMM and return a dictionary of ``{sequence_ID: TMHMM_prediction}``.\n\nArgs:\n tmhmm_results (str): Path to long format TMHMM output.\n\nReturns:\n dict: Dictionary of ``{sequence_ID: TMHMM_prediction}``", "source": "juraj_google_style"} +{"code": "def is_coord_subset_pbc(subset, superset, atol=1e-8, mask=None):\n\n c1 = np.array(subset, dtype=np.float64)\n c2 = np.array(superset, dtype=np.float64)\n if mask is not None:\n m = np.array(mask, dtype=np.int)\n else:\n m = np.zeros((len(subset), len(superset)), dtype=np.int)\n atol = np.zeros(3, dtype=np.float64) + atol\n return cuc.is_coord_subset_pbc(c1, c2, atol, m)", "docstring": "Tests if all fractional coords in subset are contained in superset.\n\nArgs:\n subset, superset: List of fractional coords\n atol (float or size 3 array): Tolerance for matching\n mask (boolean array): Mask of matches that are not allowed.\n i.e. if mask[1,2] == True, then subset[1] cannot be matched\n to superset[2]\n\nReturns:\n True if all of subset is in superset.", "source": "juraj_google_style"} +{"code": "def _record_blank(self, current, dict_obj):\n\n if not self.list_blank:\n return\n if self.list_blank not in current:\n self.blank.append(dict_obj)", "docstring": "records the dictionay in the the 'blank' attribute based on the\n 'list_blank' path\n\nArgs:\n -----\n current: the current dictionay counts\n dict_obj: the original dictionary object", "source": "juraj_google_style"} +{"code": "def __init__(self, **kwargs):\n\n try:\n self.UIStatusMsg = ''\n self.mac = kwargs.get('EUI')\n self.handle = None\n self.AutoDUTEnable = False\n self._is_net = False # whether device is through ser2net\n self.logStatus = {'stop':'stop', 'running':'running', 'pauseReq':'pauseReq', 'paused':'paused'}\n self.logThreadStatus = self.logStatus['stop']\n self.connectType = (kwargs.get('Param5')).strip().lower() if kwargs.get('Param5') is not None else 'usb'\n if self.connectType == 'ip':\n self.dutIpv4 = kwargs.get('TelnetIP')\n self.dutPort = kwargs.get('TelnetPort')\n self.port = self.dutIpv4 + ':' + self.dutPort\n else:\n self.port = kwargs.get('SerialPort')\n self.intialize()\n except Exception, e:\n ModuleHelper.WriteIntoDebugLogger('initialize() Error: ' + str(e))", "docstring": "initialize the serial port and default network parameters\n\nArgs:\n **kwargs: Arbitrary keyword arguments\n Includes 'EUI' and 'SerialPort'", "source": "juraj_google_style"} +{"code": "def from_raw(self, file_names=None, **kwargs):\n\n # This function only loads one test at a time (but could contain several\n # files). The function from_res() also implements loading several\n # datasets (using list of lists as input).\n\n if file_names:\n self.file_names = file_names\n\n if not isinstance(file_names, (list, tuple)):\n self.file_names = [file_names, ]\n\n # file_type = self.tester\n raw_file_loader = self.loader\n set_number = 0\n test = None\n counter = 0\n self.logger.debug(\"start iterating through file(s)\")\n for f in self.file_names:\n self.logger.debug(\"loading raw file:\")\n self.logger.debug(f\"{f}\")\n new_tests = raw_file_loader(f, **kwargs)\n if new_tests:\n if test is not None:\n self.logger.debug(\"continuing reading files...\")\n _test = self._append(test[set_number], new_tests[set_number])\n if not _test:\n self.logger.warning(f\"EMPTY TEST: {f}\")\n continue\n test[set_number] = _test\n self.logger.debug(\"added this test - started merging\")\n for j in range(len(new_tests[set_number].raw_data_files)):\n raw_data_file = new_tests[set_number].raw_data_files[j]\n file_size = new_tests[set_number].raw_data_files_length[j]\n test[set_number].raw_data_files.append(raw_data_file)\n test[set_number].raw_data_files_length.append(file_size)\n counter += 1\n if counter > 10:\n self.logger.debug(\"ERROR? Too many files to merge\")\n raise ValueError(\"Too many files to merge - \"\n \"could be a p2-p3 zip thing\")\n else:\n self.logger.debug(\"getting data from first file\")\n if new_tests[set_number].no_data:\n self.logger.debug(\"NO DATA\")\n else:\n test = new_tests\n else:\n self.logger.debug(\"NOTHING LOADED\")\n\n self.logger.debug(\"finished loading the raw-files\")\n\n test_exists = False\n if test:\n if test[0].no_data:\n self.logging.debug(\"the first dataset (or only dataset) loaded from the raw data file is empty\")\n else:\n test_exists = True\n\n if test_exists:\n if not prms.Reader.sorted_data:\n self.logger.debug(\"sorting data\")\n test[set_number] = self._sort_data(test[set_number])\n\n self.datasets.append(test[set_number])\n else:\n self.logger.warning(\"No new datasets added!\")\n self.number_of_datasets = len(self.datasets)\n self.status_datasets = self._validate_datasets()\n self._invent_a_name()\n return self", "docstring": "Load a raw data-file.\n\nArgs:\n file_names (list of raw-file names): uses CellpyData.file_names if\n None. If the list contains more than one file name, then the\n runs will be merged together.", "source": "juraj_google_style"} +{"code": "def es_json(self, role='rdf_class', remove_empty=True, **kwargs):\n\n def test_idx_status(cls_inst, **kwargs):\n\n if kwargs.get(\"force\") == True:\n return False\n idx_time = cls_inst.get(\"kds_esIndexTime\", [None])[0]\n mod_time = cls_inst.get(\"dcterm_modified\", [None])[0]\n error_msg = cls_inst.get(\"kds_esIndexError\", [None])[0]\n if (not idx_time) or \\\n error_msg or \\\n (idx_time and mod_time and idx_time < mod_time):\n return False\n return True\n\n # if self.__class__.__name__ == 'rdf_type':\n # pdb.set_trace()\n rtn_obj = {}\n if kwargs.get(\"depth\"):\n kwargs['depth'] += 1\n else:\n kwargs['depth'] = 1\n if role == 'rdf_class':\n if test_idx_status(self, **kwargs):\n return None\n for prop, value in self.items():\n if prop in ['kds_esIndexTime', 'kds_esIndexError']:\n continue\n new_val = value.es_json()\n rtn_method = get_attr(self[prop], 'kds_esObjectType', [])\n if 'kdr_Array' in rtn_method:\n rtn_obj[prop] = new_val\n elif (remove_empty and new_val) or not remove_empty:\n if len(new_val) == 1:\n rtn_obj[prop] = new_val[0]\n else:\n rtn_obj[prop] = new_val\n nested_props = None\n else:\n try:\n nested_props = self.es_defs.get('kds_esNestedProps',\n list(self.keys())).copy()\n except AttributeError:\n nested_props = list(self.keys())\n for prop, value in self.items():\n # if prop == 'bf_hasInstance':\n # pdb.set_trace()\n if prop in ['kds_esIndexTime', 'kds_esIndexError']:\n continue\n new_val = value.es_json(**kwargs)\n rtn_method = get_attr(self[prop], 'kds_esObjectType', [])\n if 'kdr_Array' in rtn_method:\n rtn_obj[prop] = new_val\n elif (remove_empty and new_val) or not remove_empty:\n if len(new_val) == 1:\n rtn_obj[prop] = new_val[0] \\\n if not isinstance(new_val, dict) \\\n else new_val\n else:\n rtn_obj[prop] = new_val\n # if 'bf_Work' in self.hierarchy:\n # pdb.set_trace()\n\n rtn_obj = get_es_label(rtn_obj, self)\n rtn_obj = get_es_value(rtn_obj, self)\n rtn_obj = get_es_ids(rtn_obj, self)\n if nested_props:\n nested_props += ['value', 'id', 'uri']\n rtn_obj = {key: value\n for key, value in rtn_obj.items()\n if key in nested_props}\n # rml_procs = self.es_defs.get(\"kds_esRmlProcessor\", [])\n # # if role == 'rdf_class':\n # # pdb.set_trace()\n # rml_procs = [proc for proc in rml_procs\n # if role == 'rdf_class' or\n # proc['force']]\n # if rml_procs:\n # rml_maps = {}\n # for rml in rml_procs:\n # proc_kwargs = {rml['subj']: self.subject,\n # \"dataset\": self.dataset}\n # proc_kwargs.update(rml['proc_kwargs'])\n # rml_maps[rml['name']] = rml['processor'](**proc_kwargs)\n # if rml_maps:\n # rtn_obj['rml_map'] = rml_maps\n rml_maps = self.get_all_rml(role=role)\n if rml_maps:\n rtn_obj['rml_map'] = rml_maps\n # if self.get('bf_contribution'):\n # pdb.set_trace()\n return rtn_obj", "docstring": "Returns a JSON object of the class for insertion into es\n\nArgs:\n role: the role states how the class data should be returned\n depending upon whether it is used as a subject of an object.\n options are kds_esNested or rdf_class\n remove_empty: True removes empty items from es object", "source": "juraj_google_style"} +{"code": "def __init__(self, length=None, vendor=None):\n\n super().__init__(action_type=ActionType.OFPAT_VENDOR, length=length)\n self.vendor = vendor", "docstring": "Create an ActionVendorHeader with the optional parameters below.\n\nArgs:\n length (int): Length is a multiple of 8.\n vender (int): Vendor ID with the same form as in VendorHeader.\n Defaults to None.", "source": "juraj_google_style"} +{"code": "def namespace_for_prefix(self, prefix):\n\n try:\n ni = self.__lookup_prefix(prefix)\n except PrefixNotFoundError:\n return None\n else:\n return ni.uri", "docstring": "Get the namespace the given prefix maps to.\n\nArgs:\n prefix (str): The prefix\n\nReturns:\n str: The namespace, or None if the prefix isn't mapped to\n anything in this set.", "source": "juraj_google_style"} +{"code": "def __init__(self, failfast=False, save_tests=False, report_template=None, report_dir=None,\n log_level=\"INFO\", log_file=None):\n\n self.exception_stage = \"initialize HttpRunner()\"\n kwargs = {\n \"failfast\": failfast,\n \"resultclass\": report.HtmlTestResult\n }\n self.unittest_runner = unittest.TextTestRunner(**kwargs)\n self.test_loader = unittest.TestLoader()\n self.save_tests = save_tests\n self.report_template = report_template\n self.report_dir = report_dir\n self._summary = None\n if log_file:\n logger.setup_logger(log_level, log_file)", "docstring": "initialize HttpRunner.\n\nArgs:\n failfast (bool): stop the test run on the first error or failure.\n save_tests (bool): save loaded/parsed tests to JSON file.\n report_template (str): report template file path, template should be in Jinja2 format.\n report_dir (str): html report save directory.\n log_level (str): logging level.\n log_file (str): log file path.", "source": "juraj_google_style"} +{"code": "def mkzip(archive, items, mode=\"w\", save_full_paths=False):\n\n close = False\n try:\n if not isinstance(archive, zipfile.ZipFile):\n archive = zipfile.ZipFile(archive, mode, allowZip64=True)\n close = True\n logger.info(\"mkdzip: Creating %s, from: %s\", archive.filename, items)\n if isinstance(items, str):\n items = [items]\n for item in items:\n item = os.path.abspath(item)\n basename = os.path.basename(item)\n if os.path.isdir(item):\n for root, directoires, filenames in os.walk(item):\n for filename in filenames:\n path = os.path.join(root, filename)\n if save_full_paths:\n archive_path = path.encode(\"utf-8\")\n else:\n archive_path = os.path.join(\n basename, path.replace(item, \"\").strip(\"\\\\/\")\n ).encode(\"utf-8\")\n archive.write(path, archive_path)\n elif os.path.isfile(item):\n if save_full_paths:\n archive_name = item.encode(\"utf-8\")\n else:\n archive_name = basename.encode(\"utf-8\")\n archive.write(item, archive_name) # , zipfile.ZIP_DEFLATED)\n return True\n except Exception as e:\n logger.error(\"Error occurred during mkzip: %s\" % e)\n return False\n finally:\n if close:\n archive.close()", "docstring": "Recursively zip a directory.\n\nArgs:\n archive (zipfile.ZipFile or str): ZipFile object add to or path to the\n output zip archive.\n items (str or list of str): Single item or list of items (files and\n directories) to be added to zipfile.\n mode (str): w for create new and write a for append to.\n save_full_paths (bool): Preserve full paths.", "source": "juraj_google_style"} +{"code": "def __mul__(self, repeat):\n\n if not isinstance(repeat, int):\n raise TypeError(\"Can only multiply a graph with an integer\")\n # copy edges\n new_edges = []\n for i in range(repeat):\n for vertex1, vertex2 in self.edges:\n new_edges.append(frozenset([vertex1+i*self.num_vertices, vertex2+i*self.num_vertices]))\n # copy numbers\n new_numbers = np.zeros((repeat, len(self.numbers)), int)\n new_numbers[:] = self.numbers\n new_numbers = new_numbers.ravel()\n # copy orders\n new_orders = np.zeros((repeat, len(self.orders)), int)\n new_orders[:] = self.orders\n new_orders = new_orders.ravel()\n # copy symbols\n if self.symbols is not None:\n new_symbols = self.symbols*repeat\n else:\n new_symbols = None\n return MolecularGraph(new_edges, new_numbers, new_orders, new_symbols)", "docstring": "Construct a graph that repeats this graph a number of times\n\nArgs:\n | ``repeat`` -- The number of repetitions.", "source": "juraj_google_style"} +{"code": "def __init__(\n self,\n function_approximator,\n batch_size=4,\n map_size=(10, 10),\n memory_num=4,\n repeating_penalty=0.5,\n enemy_num=2,\n enemy_init_dist=5\n ):\n\n self.__map_arr = self.__create_map(map_size)\n self.__agent_pos = self.START_POS\n\n self.__enemy_num = enemy_num\n self.__enemy_pos_list = [None] * enemy_num\n self.__enemy_init_dist = enemy_init_dist\n self.__create_enemy(self.__map_arr)\n\n self.__reward_list = []\n self.__route_memory_list = []\n self.__memory_num = memory_num\n self.__repeating_penalty = repeating_penalty\n\n self.__batch_size = batch_size\n\n super().__init__(function_approximator)\n self.__inferencing_flag = False", "docstring": "Init.\n\nArgs:\n function_approximator: is-a `FunctionApproximator`.\n map_size: Size of map.\n memory_num: The number of step of agent's memory.\n repeating_penalty: The value of penalty in the case that agent revisit.\n enemy_num: The number of enemies.\n enemy_init_dist: Minimum euclid distance of initial position of agent and enemies.", "source": "juraj_google_style"} +{"code": "def _DownloadAuthUrl(self, url, dest_dir):\n\n dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)\n dest_file.close()\n dest = dest_file.name\n\n self.logger.info(\n 'Downloading url from %s to %s using authentication token.', url, dest)\n\n if not self.token:\n response = self.watcher.GetMetadata(\n self.token_metadata_key, recursive=False, retry=False)\n\n if not response:\n self.logger.info(\n 'Authentication token not found. Attempting unauthenticated '\n 'download.')\n return self._DownloadUrl(url, dest_dir)\n\n self.token = '%s %s' % (\n response.get('token_type', ''), response.get('access_token', ''))\n\n try:\n request = urlrequest.Request(url)\n request.add_unredirected_header('Metadata-Flavor', 'Google')\n request.add_unredirected_header('Authorization', self.token)\n content = urlrequest.urlopen(request).read().decode('utf-8')\n except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:\n self.logger.warning('Could not download %s. %s.', url, str(e))\n return None\n\n with open(dest, 'wb') as f:\n f.write(content)\n\n return dest", "docstring": "Download a Google Storage URL using an authentication token.\n\n If the token cannot be fetched, fallback to unauthenticated download.\n\nArgs:\n url: string, the URL to download.\n dest_dir: string, the path to a directory for storing metadata scripts.\n\nReturns:\n string, the path to the file storing the metadata script.", "source": "juraj_google_style"} +{"code": "def full_game_name(short_name):\n\n camel_game_name = misc_utils.snakecase_to_camelcase(short_name)\n full_name = camel_game_name + ATARI_GAME_MODE\n return full_name", "docstring": "CamelCase game name with mode suffix.\n\nArgs:\n short_name: snake_case name without mode e.g \"crazy_climber\"\n\nReturns:\n full game name e.g. \"CrazyClimberNoFrameskip-v4\"", "source": "juraj_google_style"} +{"code": "def GetPresetsByOperatingSystem(self, operating_system):\n\n preset_definitions = []\n for preset_definition in self._definitions.values():\n for preset_operating_system in preset_definition.operating_systems:\n if preset_operating_system.IsEquivalent(operating_system):\n preset_definitions.append(preset_definition)\n\n return preset_definitions", "docstring": "Retrieves preset definitions for a specific operating system.\n\nArgs:\n operating_system (OperatingSystemArtifact): an operating system artifact\n attribute container.\n\nReturns:\n list[PresetDefinition]: preset definition that correspond with the\n operating system.", "source": "juraj_google_style"} +{"code": "def read_html_file(data_dir, fileroot, encoding=None):\n\n fname = os.path.join(\n data_dir, RAW_HTML_DIRNAME, fileroot + RAW_HTML_EXT)\n encodings = (encoding,) if encoding else ('utf-8', 'iso-8859-1') # 'utf-16'\n for encoding in encodings:\n try:\n with io.open(fname, mode='rt', encoding=encoding) as f:\n raw_html = f.read()\n break\n except (UnicodeDecodeError, UnicodeError):\n raw_html = None\n\n return ftfy.fix_encoding(raw_html).strip()", "docstring": "Read the HTML file corresponding to identifier ``fileroot``\n in the raw HTML directory below the root ``data_dir``.\n\nArgs:\n data_dir (str)\n fileroot (str)\n encoding (str)\n\nReturns:\n str", "source": "juraj_google_style"} +{"code": "def decstr2int(dec_str, decimals):\n\n if not isinstance(decimals, int):\n raise TypeError('decimals must be an integer')\n try:\n dollars, cents = dec_str.split('.')\n except ValueError:\n if '.' not in dec_str:\n dollars = dec_str\n cents = '0'\n else:\n raise ValueError('Invalid decimal string')\n else:\n if len(cents) < decimals:\n cents = cents.ljust(decimals, '0')\n elif decimals < 1:\n cents = '0'\n elif len(cents) > decimals:\n cents = cents[:decimals]\n try:\n cents = int(cents)\n except:\n cents = 0\n try:\n return int(int(dollars) * (10 ** decimals)) + cents\n except:\n raise ValueError('Invalid decimal string')", "docstring": "Returns an integer that has the value of the decimal string:\n dec_str*10^decimals\n\nArgs:\n dec_str (string) that represents a decimal number\n decimals (int): number of decimals for creating the integer output\n\nReturns:\n (int)\n\nRaises:\n ValueError if dec_string is not a valid decimal string\n TypeError if decimals is not an integer\n Note: values may be truncated (not rounded).", "source": "juraj_google_style"} +{"code": "def update(self, data):\n\n # If the instance was terminated, remove it\n updated = self.set_property('state', data['state'])\n updated |= self.set_property('notes', sorted(data['notes'] or []))\n updated |= self.set_property('last_notice', data['last_notice'])\n\n if updated:\n self.set_property('last_change', datetime.now())\n\n return updated", "docstring": "Updates the object information based on live data, if there were any changes made. Any changes will be\n automatically applied to the object, but will not be automatically persisted. You must manually call\n `db.session.add(instance)` on the object.\n\nArgs:\n data (:obj:): AWS API Resource object fetched from AWS API\n\nReturns:\n `bool`", "source": "juraj_google_style"} +{"code": "def count_stages(self, matrix_name):\n\n return len(self.data[matrix_name]) if matrix_name in self.data else 0", "docstring": "Number of registered stages for given matrix name.\n\n Parameters:\n matrix_name (str): name of the matrix\n\nReturns:\n int: number of reported stages for given matrix name.", "source": "juraj_google_style"} +{"code": "def is_remote_file_modified(web_file, destination):\n\n try:\n # check datetime of last modified in file.\n last_mod = web_file.headers.get('last-modified')\n if last_mod:\n web_file_time = time.strptime(\n web_file.headers.get(\n 'last-modified'), '%a, %d %b %Y %H:%M:%S %Z')\n else:\n web_file_time = time.gmtime()\n\n web_file_size = int(web_file.headers.get('content-length', -1))\n if os.path.exists(destination):\n file_time = time.gmtime(os.path.getmtime(destination))\n file_size = os.path.getsize(destination)\n if file_time >= web_file_time and file_size == web_file_size:\n return False\n\n except Exception as ex:\n msg = ('Fail checking if remote file is modified default returns TRUE'\n ' - {}'.format(ex))\n logger.debug(msg)\n\n return True", "docstring": "Check if online file has been modified.\n\nArgs:\n :web_file: online file to check.\n :destination: path of the offline file to compare.", "source": "juraj_google_style"} +{"code": "def filter(self, *query_filter):\n\n for query in query_filter:\n self.query.append(query)\n return self", "docstring": "Set the query filter to perform the query with\n\nArgs:\n *query_filter: Simplified Query Language filter", "source": "juraj_google_style"} +{"code": "def index(self, ref, columns):\n\n from ambry.orm.exc import NotFoundError\n\n logger.debug('Creating index for partition.\\n ref: {}, columns: {}'.format(ref, columns))\n\n connection = self._backend._get_connection()\n\n try:\n table_or_partition = self._library.partition(ref)\n except NotFoundError:\n table_or_partition = ref\n\n\n self._backend.index(connection, table_or_partition, columns)", "docstring": "Create an index on the columns.\n\nArgs:\n ref (str): id, vid, name or versioned name of the partition.\n columns (list of str): names of the columns needed indexes.", "source": "juraj_google_style"} +{"code": "def __init__(self,\n unique_identifier=None,\n data=None):\n\n super(DecryptResponsePayload, self).__init__(\n enums.Tags.RESPONSE_PAYLOAD\n )\n\n self._unique_identifier = None\n self._data = None\n\n self.unique_identifier = unique_identifier\n self.data = data", "docstring": "Construct a Decrypt response payload struct.\n\nArgs:\n unique_identifier (string): The ID of the managed object (e.g.,\n a symmetric key) used for decryption. Required for encoding\n and decoding.\n data (bytes): The decrypted data in binary form. Required for\n encoding and decoding.", "source": "juraj_google_style"} +{"code": "def Bernoulli(cls,\n mean: 'TensorFluent',\n batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:\n\n probs = mean.tensor\n dist = tf.distributions.Bernoulli(probs=probs, dtype=tf.bool)\n batch = mean.batch\n if not batch and batch_size is not None:\n t = dist.sample(batch_size)\n batch = True\n else:\n t = dist.sample()\n scope = mean.scope.as_list()\n return (dist, TensorFluent(t, scope, batch=batch))", "docstring": "Returns a TensorFluent for the Bernoulli sampling op with given mean parameter.\n\nArgs:\n mean: The mean parameter of the Bernoulli distribution.\n batch_size: The size of the batch (optional).\n\nReturns:\n The Bernoulli distribution and a TensorFluent sample drawn from the distribution.", "source": "juraj_google_style"} +{"code": "def WideResnet(num_blocks=3, hidden_size=64, num_output_classes=10,\n mode='train'):\n\n del mode\n return layers.Serial(\n layers.Conv(hidden_size, (3, 3), padding='SAME'),\n WideResnetGroup(num_blocks, hidden_size),\n WideResnetGroup(num_blocks, hidden_size * 2, (2, 2)),\n WideResnetGroup(num_blocks, hidden_size * 4, (2, 2)), layers.BatchNorm(),\n layers.Relu(), layers.AvgPool(pool_size=(8, 8)), layers.Flatten(),\n layers.Dense(num_output_classes), layers.LogSoftmax())", "docstring": "WideResnet from https://arxiv.org/pdf/1605.07146.pdf.\n\nArgs:\n num_blocks: int, number of blocks in a group.\n hidden_size: the size of the first hidden layer (multiplied later).\n num_output_classes: int, number of classes to distinguish.\n mode: is it training or eval.\n\nReturns:\n The WideResnet model with given layer and output sizes.", "source": "juraj_google_style"} +{"code": "def invite_by_email(self, email, user, organization, **kwargs):\n # type: (Text, AbstractUser, AbstractBaseOrganization) -> OrganizationInvitationBase\n\n try:\n invitee = self.user_model.objects.get(email__iexact=email)\n except self.user_model.DoesNotExist:\n invitee = None\n\n # TODO allow sending just the OrganizationUser instance\n user_invitation = self.invitation_model.objects.create(\n invitee=invitee,\n invitee_identifier=email.lower(),\n invited_by=user,\n organization=organization,\n )\n self.send_invitation(user_invitation)\n return user_invitation", "docstring": "Primary interface method by which one user invites another to join\n\nArgs:\n email:\n request:\n **kwargs:\n\nReturns:\n an invitation instance\n\nRaises:\n MultipleObjectsReturned if multiple matching users are found", "source": "juraj_google_style"} +{"code": "def get_penalty_model(specification):\n\n\n # check that the feasible_configurations are spin\n feasible_configurations = specification.feasible_configurations\n if specification.vartype is dimod.BINARY:\n feasible_configurations = {tuple(2 * v - 1 for v in config): en\n for config, en in feasible_configurations.items()}\n\n # convert ising_quadratic_ranges to the form we expect\n ising_quadratic_ranges = specification.ising_quadratic_ranges\n quadratic_ranges = {(u, v): ising_quadratic_ranges[u][v] for u, v in specification.graph.edges}\n\n bqm, gap = generate(specification.graph,\n feasible_configurations,\n specification.decision_variables,\n specification.ising_linear_ranges,\n quadratic_ranges,\n specification.min_classical_gap,\n None) # unspecified smt solver\n\n try:\n ground = max(feasible_configurations.values())\n except ValueError:\n ground = 0.0 # if empty\n\n return pm.PenaltyModel.from_specification(specification, bqm, gap, ground)", "docstring": "Factory function for penaltymodel_maxgap.\n\nArgs:\n specification (penaltymodel.Specification): The specification\n for the desired penalty model.\n\nReturns:\n :class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.\n\nRaises:\n :class:`penaltymodel.ImpossiblePenaltyModel`: If the penalty cannot be built.\n\n Parameters:\n priority (int): -100", "source": "juraj_google_style"} +{"code": "def save(self, path_info, checksum):\n\n assert path_info[\"scheme\"] == \"local\"\n assert checksum is not None\n\n path = path_info[\"path\"]\n assert os.path.exists(path)\n\n actual_mtime, actual_size = get_mtime_and_size(path)\n actual_inode = get_inode(path)\n\n existing_record = self.get_state_record_for_inode(actual_inode)\n if not existing_record:\n self._insert_new_state_record(\n path, actual_inode, actual_mtime, actual_size, checksum\n )\n return\n\n self._update_state_for_path_changed(\n path, actual_inode, actual_mtime, actual_size, checksum\n )", "docstring": "Save checksum for the specified path info.\n\nArgs:\n path_info (dict): path_info to save checksum for.\n checksum (str): checksum to save.", "source": "juraj_google_style"} +{"code": "def IsDeletedOrDefault(clean_lines, linenum):\n\n open_paren = clean_lines.elided[linenum].find('(')\n if open_paren < 0:\n return False\n (close_line, _, close_paren) = CloseExpression(\n clean_lines, linenum, open_paren)\n if close_paren < 0:\n return False\n return Match(r'\\s*=\\s*(?:delete|default)\\b', close_line[close_paren:])", "docstring": "Check if current constructor or operator is deleted or default.\n\nArgs:\n clean_lines: A CleansedLines instance containing the file.\n linenum: The number of the line to check.\n\nReturns:\n True if this is a deleted or default constructor.", "source": "juraj_google_style"} +{"code": "def get_avatar(from_header, size=64, default=\"retro\"):\n\n params = OrderedDict([(\"s\", size), (\"d\", default)])\n query = parse.urlencode(params)\n address = email.utils.parseaddr(from_header)[1]\n value_hash = sha256(address.encode(\"utf-8\")).hexdigest()\n return \"https://seccdn.libravatar.org/avatar/{}?{}\".format(value_hash, query)", "docstring": "Get the avatar URL from the email's From header.\n\nArgs:\n from_header (str): The email's From header. May contain the sender's full name.\n\nReturns:\n str: The URL to that sender's avatar.", "source": "juraj_google_style"} +{"code": "def _lease_valid(self, lease):\n\n if not lease.exist:\n return None\n\n if lease.has_env:\n return lease.uuid_path\n else:\n self._release(lease)\n return None", "docstring": "Check if the given lease exist and still has a prefix that owns it.\n If the lease exist but its prefix isn't, remove the lease from this\n store.\n\nArgs:\n lease (lago.subnet_lease.Lease): Object representation of the\n lease\n\nReturns:\n str or None: If the lease and its prefix exists, return the path\n to the uuid of the prefix, else return None.", "source": "juraj_google_style"} +{"code": "def construct_graph(sakefile, settings):\n\n verbose = settings[\"verbose\"]\n sprint = settings[\"sprint\"]\n G = nx.DiGraph()\n sprint(\"Going to construct Graph\", level=\"verbose\")\n for target in sakefile:\n if target == \"all\":\n # we don't want this node\n continue\n if \"formula\" not in sakefile[target]:\n # that means this is a meta target\n for atomtarget in sakefile[target]:\n if atomtarget == \"help\":\n continue\n sprint(\"Adding '{}'\".format(atomtarget), level=\"verbose\")\n data_dict = sakefile[target][atomtarget]\n data_dict[\"parent\"] = target\n G.add_node(atomtarget, **data_dict)\n else:\n sprint(\"Adding '{}'\".format(target), level=\"verbose\")\n G.add_node(target, **sakefile[target])\n sprint(\"Nodes are built\\nBuilding connections\", level=\"verbose\")\n for node in G.nodes(data=True):\n sprint(\"checking node {} for dependencies\".format(node[0]),\n level=\"verbose\")\n # normalize all paths in output\n for k, v in node[1].items():\n if v is None: node[1][k] = []\n if \"output\" in node[1]:\n for index, out in enumerate(node[1]['output']):\n node[1]['output'][index] = clean_path(node[1]['output'][index])\n if \"dependencies\" not in node[1]:\n continue\n sprint(\"it has dependencies\", level=\"verbose\")\n connects = []\n # normalize all paths in dependencies\n for index, dep in enumerate(node[1]['dependencies']):\n dep = os.path.normpath(dep)\n shrt = \"dependencies\"\n node[1]['dependencies'][index] = clean_path(node[1][shrt][index])\n for node in G.nodes(data=True):\n connects = []\n if \"dependencies\" not in node[1]:\n continue\n for dep in node[1]['dependencies']:\n matches = check_for_dep_in_outputs(dep, verbose, G)\n if not matches:\n continue\n for match in matches:\n sprint(\"Appending {} to matches\".format(match), level=\"verbose\")\n connects.append(match)\n if connects:\n for connect in connects:\n G.add_edge(connect, node[0])\n return G", "docstring": "Takes the sakefile dictionary and builds a NetworkX graph\n\nArgs:\n A dictionary that is the parsed Sakefile (from sake.py)\n The settings dictionary\n\nReturns:\n A NetworkX graph", "source": "juraj_google_style"} +{"code": "def __init__(self, target_pixels=None, **kwargs):\n\n super(OpenImagesV4Config, self).__init__(**kwargs)\n self._target_pixels = target_pixels", "docstring": "BuilderConfig for OpenImagesV4.\n\nArgs:\n target_pixels: If given, rescale the images so that the number of pixels\n is roughly this value.\n **kwargs: keyword arguments forward to super.", "source": "juraj_google_style"} +{"code": "def check_type(o, acceptable_types, may_be_none=True):\n\n if not isinstance(acceptable_types, tuple):\n acceptable_types = (acceptable_types,)\n\n if may_be_none and o is None:\n # Object is None, and that is OK!\n pass\n elif isinstance(o, acceptable_types):\n # Object is an instance of an acceptable type.\n pass\n else:\n # Object is something else.\n error_message = (\n \"We were expecting to receive an instance of one of the following \"\n \"types: {types}{none}; but instead we received {o} which is a \"\n \"{o_type}.\".format(\n types=\", \".join([repr(t.__name__) for t in acceptable_types]),\n none=\"or 'None'\" if may_be_none else \"\",\n o=o,\n o_type=repr(type(o).__name__)\n )\n )\n raise TypeError(error_message)", "docstring": "Object is an instance of one of the acceptable types or None.\n\nArgs:\n o: The object to be inspected.\n acceptable_types: A type or tuple of acceptable types.\n may_be_none(bool): Whether or not the object may be None.\n\nRaises:\n TypeError: If the object is None and may_be_none=False, or if the\n object is not an instance of one of the acceptable types.", "source": "juraj_google_style"} +{"code": "def get_enterprise_customer_or_404(enterprise_uuid):\n\n EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer') # pylint: disable=invalid-name\n try:\n enterprise_uuid = UUID(enterprise_uuid)\n return EnterpriseCustomer.objects.get(uuid=enterprise_uuid) # pylint: disable=no-member\n except (TypeError, ValueError, EnterpriseCustomer.DoesNotExist):\n LOGGER.error('Unable to find enterprise customer for UUID: [%s]', enterprise_uuid)\n raise Http404", "docstring": "Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404.\n\nArgs:\n enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch.\n\nReturns:\n (EnterpriseCustomer): The EnterpriseCustomer given the UUID.", "source": "juraj_google_style"} +{"code": "def updateRuleOnLogicalInterface(self, logicalInterfaceId, ruleId, name, condition, description=None):\n\n req = ApiClient.oneRuleForLogicalInterfaceUrl % (self.host, \"/draft\", logicalInterfaceId, ruleId)\n body = {\"logicalInterfaceId\" : logicalInterfaceId, \"id\" : ruleId, \"name\" : name, \"condition\" : condition}\n if description:\n body[\"description\"] = description\n resp = requests.put(req, auth=self.credentials, headers={\"Content-Type\":\"application/json\"},\n data=json.dumps(body), verify=self.verify)\n if resp.status_code == 200:\n self.logger.debug(\"Logical interface rule updated\")\n else:\n raise ibmiotf.APIException(resp.status_code, \"HTTP error updating logical interface rule\", resp)\n return resp.json()", "docstring": "Updates a rule on a logical interface..\n Parameters:\n - logicalInterfaceId (string),\n - ruleId (string)\n - name (string)\n - condition (string)\n - description (string, optional)\n Returns: response (object).\n Throws APIException on failure.", "source": "juraj_google_style"} +{"code": "def start_txn(self, txn_name=None):\n\n\n\n\t\t# if no name provided, create one\n\t\tif not txn_name:\n\t\t\ttxn_name = uuid.uuid4().hex\n\n\t\t# request new transaction\n\t\ttxn_response = self.api.http_request('POST','%s/fcr:tx' % self.root, data=None, headers=None)\n\n\t\t# if 201, transaction was created\n\t\tif txn_response.status_code == 201:\n\n\t\t\ttxn_uri = txn_response.headers['Location']\n\t\t\tlogger.debug(\"spawning transaction: %s\" % txn_uri)\n\n\t\t\t# init new Transaction, and pass Expires header\n\t\t\ttxn = Transaction(\n\t\t\t\tself, # pass the repository\n\t\t\t\ttxn_name,\n\t\t\t\ttxn_uri,\n\t\t\t\texpires = txn_response.headers['Expires'])\n\n\t\t\t# append to self\n\t\t\tself.txns[txn_name] = txn\n\n\t\t\t# return\n\t\t\treturn txn", "docstring": "Request new transaction from repository, init new Transaction,\n store in self.txns\n\nArgs:\n txn_name (str): human name for transaction\n\nReturns:\n (Transaction): returns intance of newly created transaction", "source": "juraj_google_style"} +{"code": "def filter_single_value(cls, part_info, error_msg=None):\n # type: (Type[T], PartInfo, str) -> T\n\n filtered = cls.filter_values(part_info)\n if len(filtered) != 1:\n if error_msg is None:\n error_msg = \"Expected a single %s, got %s of them\" % \\\n (cls.__name__, len(filtered))\n raise BadValueError(error_msg)\n return filtered[0]", "docstring": "Filter the part_info dict list looking for a single instance of our\n class\n\nArgs:\n part_info (dict): {part_name: [Info] or None} as returned from\n Controller.run_hook()\n error_msg (str, optional): Specific error message to show if\n there isn't a single value\n\nReturns:\n info subclass of cls", "source": "juraj_google_style"} +{"code": "def get_max_capvol(self, remove=True, insert=True, volume=None):\n\n\n vol = volume if volume else self.struc_oxid.volume\n return self._get_max_cap_ah(remove, insert) * 1000 * 1E24 / (vol * const.N_A)", "docstring": "Give max capacity in mAh/cc for inserting and removing a charged cation into base structure.\n\nArgs:\n remove: (bool) whether to allow cation removal\n insert: (bool) whether to allow cation insertion\n volume: (float) volume to use for normalization (default=volume of initial structure)\n\nReturns:\n max vol capacity in mAh/cc", "source": "juraj_google_style"} +{"code": "def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f):\n\n\n if re < 2500:\n return (1.2 + (160 / re)) * ((ent_pipe_id / exit_pipe_id) ** 4)\n else:\n return (0.6 + 0.48 * f) * (ent_pipe_id / exit_pipe_id) ** 2\\\n * ((ent_pipe_id / exit_pipe_id) ** 2 - 1)", "docstring": "Returns the minor loss coefficient for a square reducer.\n\n Parameters:\n ent_pipe_id: Entrance pipe's inner diameter.\n exit_pipe_id: Exit pipe's inner diameter.\n re: Reynold's number.\n f: Darcy friction factor.", "source": "juraj_google_style"} +{"code": "def ParseSearchRow(self, parser_mediator, query, row, **unused_kwargs):\n\n query_hash = hash(query)\n\n event_data = TwitterAndroidSearchEventData()\n event_data.query = query\n event_data.name = self._GetRowValue(query_hash, row, 'name')\n event_data.search_query = self._GetRowValue(query_hash, row, 'query')\n\n timestamp = self._GetRowValue(query_hash, row, 'time')\n if timestamp:\n date_time = dfdatetime_java_time.JavaTime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_CREATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a search row from the database.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n query (str): query that created the row.\n row (sqlite3.Row): row resulting from query.", "source": "juraj_google_style"} +{"code": "def get_average_along_axis(self, ind):\n\n m = self.data[\"total\"]\n ng = self.dim\n if ind == 0:\n total = np.sum(np.sum(m, axis=1), 1)\n elif ind == 1:\n total = np.sum(np.sum(m, axis=0), 1)\n else:\n total = np.sum(np.sum(m, axis=0), 0)\n return total / ng[(ind + 1) % 3] / ng[(ind + 2) % 3]", "docstring": "Get the averaged total of the volumetric data a certain axis direction.\n For example, useful for visualizing Hartree Potentials from a LOCPOT\n file.\n\nArgs:\n ind (int): Index of axis.\n\nReturns:\n Average total along axis", "source": "juraj_google_style"} +{"code": "def filter_by_analysis_period(self, analysis_period):\n\n self._check_analysis_period(analysis_period)\n _filtered_data = self.filter_by_moys(analysis_period.moys)\n _filtered_data.header._analysis_period = analysis_period\n return _filtered_data", "docstring": "Filter a Data Collection based on an analysis period.\n\nArgs:\n analysis period: A Ladybug analysis period\n\nReturns:\n A new Data Collection with filtered data", "source": "juraj_google_style"} +{"code": "def case(self, case_id=None):\n\n if case_id:\n for case in self.case_objs:\n if case.case_id == case_id:\n return case\n else:\n if self.cases:\n return list(self.case_objs)[0]\n\n return Case(case_id='unknown')", "docstring": "Return a Case object\n\n If no case_id is given return one case\n\nArgs:\n case_id (str): A case id\n\nReturns:\n A Case object", "source": "juraj_google_style"} +{"code": "def speak(self, message):\n\n campfire = self.get_campfire()\n if not isinstance(message, Message):\n message = Message(campfire, message)\n\n result = self._connection.post(\n \"room/%s/speak\" % self.id,\n {\"message\": message.get_data()},\n parse_data=True,\n key=\"message\"\n )\n\n if result[\"success\"]:\n return Message(campfire, result[\"data\"])\n return result[\"success\"]", "docstring": "Post a message.\n\nArgs:\n message (:class:`Message` or string): Message\n\nReturns:\n bool. Success", "source": "juraj_google_style"} +{"code": "def __init__(self, tokens, lineno=0):\n\n self.tokens = tokens\n self.lineno = lineno\n self.parsed = False", "docstring": "Base Node\n\nArgs:\n tokens (list): tokenlist\n lineno (int): Line number of node", "source": "juraj_google_style"} +{"code": "def sample_variants(self, variants, sample_name, category = 'snv'):\n\n LOG.info('Retrieving variants for subject : {0}'.format(sample_name))\n has_allele = re.compile('1|2') # a non wild-type allele is called at least once in this sample\n\n query = {\n '$and': [\n {'_id' : { '$in' : variants}},\n {'category' : category},\n {'samples': {\n '$elemMatch': { 'display_name' : sample_name, 'genotype_call': { '$regex' : has_allele } }\n }}\n ]\n }\n\n result = self.variant_collection.find(query)\n return result", "docstring": "Given a list of variants get variant objects found in a specific patient\n\nArgs:\n variants(list): a list of variant ids\n sample_name(str): a sample display name\n category(str): 'snv', 'sv' ..\n\nReturns:\n result(iterable(Variant))", "source": "juraj_google_style"} +{"code": "def _right_pad(x, final_rank):\n\n padded_shape = tf.concat(\n [tf.shape(input=x),\n tf.ones(final_rank - tf.rank(x), dtype=tf.int32)],\n axis=0)\n static_padded_shape = None\n if x.shape.is_fully_defined() and isinstance(final_rank, int):\n static_padded_shape = x.shape.as_list()\n extra_dims = final_rank - len(static_padded_shape)\n static_padded_shape.extend([1] * extra_dims)\n\n padded_x = tf.reshape(x, static_padded_shape or padded_shape)\n return padded_x", "docstring": "Pads the shape of x to the right to be of rank final_rank.\n\n Expands the dims of `x` to the right such that its rank is equal to\n final_rank. For example, if `x` is of shape [1, 5, 7, 2] and `final_rank` is\n 7, we return padded_x, which is of shape [1, 5, 7, 2, 1, 1, 1].\n\nArgs:\n x: The tensor whose shape is to be padded.\n final_rank: Scalar int32 `Tensor` or Python `int`. The desired rank of x.\n\nReturns:\n padded_x: A tensor of rank final_rank.", "source": "juraj_google_style"} +{"code": "def _StartWorkerProcess(self, process_name, storage_writer):\n\n analysis_plugin = self._analysis_plugins.get(process_name, None)\n if not analysis_plugin:\n logger.error('Missing analysis plugin: {0:s}'.format(process_name))\n return None\n\n if self._use_zeromq:\n queue_name = '{0:s} output event queue'.format(process_name)\n output_event_queue = zeromq_queue.ZeroMQPushBindQueue(\n name=queue_name, timeout_seconds=self._QUEUE_TIMEOUT)\n # Open the queue so it can bind to a random port, and we can get the\n # port number to use in the input queue.\n output_event_queue.Open()\n\n else:\n output_event_queue = multi_process_queue.MultiProcessingQueue(\n timeout=self._QUEUE_TIMEOUT)\n\n self._event_queues[process_name] = output_event_queue\n\n if self._use_zeromq:\n queue_name = '{0:s} input event queue'.format(process_name)\n input_event_queue = zeromq_queue.ZeroMQPullConnectQueue(\n name=queue_name, delay_open=True, port=output_event_queue.port,\n timeout_seconds=self._QUEUE_TIMEOUT)\n\n else:\n input_event_queue = output_event_queue\n\n process = analysis_process.AnalysisProcess(\n input_event_queue, storage_writer, self._knowledge_base,\n analysis_plugin, self._processing_configuration,\n data_location=self._data_location,\n event_filter_expression=self._event_filter_expression,\n name=process_name)\n\n process.start()\n\n logger.info('Started analysis plugin: {0:s} (PID: {1:d}).'.format(\n process_name, process.pid))\n\n try:\n self._StartMonitoringProcess(process)\n except (IOError, KeyError) as exception:\n logger.error((\n 'Unable to monitor analysis plugin: {0:s} (PID: {1:d}) '\n 'with error: {2!s}').format(process_name, process.pid, exception))\n\n process.terminate()\n return None\n\n self._RegisterProcess(process)\n return process", "docstring": "Creates, starts, monitors and registers a worker process.\n\nArgs:\n process_name (str): process name.\n storage_writer (StorageWriter): storage writer for a session storage used\n to create task storage.\n\nReturns:\n MultiProcessWorkerProcess: extraction worker process or None on error.", "source": "juraj_google_style"} +{"code": "def setMeterPassword(self, new_pwd, pwd=\"00000000\"):\n\n result = False\n self.setContext(\"setMeterPassword\")\n try:\n if len(new_pwd) != 8 or len(pwd) != 8:\n self.writeCmdMsg(\"Passwords must be exactly eight characters.\")\n self.setContext(\"\")\n return result\n\n if not self.request(False):\n self.writeCmdMsg(\"Pre command read failed: check serial line.\")\n else:\n if not self.serialCmdPwdAuth(pwd):\n self.writeCmdMsg(\"Password failure\")\n else:\n req_pwd = binascii.hexlify(new_pwd.zfill(8))\n req_str = \"015731023030323028\" + req_pwd + \"2903\"\n req_str += self.calc_crc16(req_str[2:].decode(\"hex\"))\n self.m_serial_port.write(req_str.decode(\"hex\"))\n if self.m_serial_port.getResponse(self.getContext()).encode(\"hex\") == \"06\":\n self.writeCmdMsg(\"Success(setMeterPassword): 06 returned.\")\n result = True\n self.serialPostEnd()\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n\n self.setContext(\"\")\n return result", "docstring": "Serial Call to set meter password. USE WITH CAUTION.\n\nArgs:\n new_pwd (str): 8 digit numeric password to set\n pwd (str): Old 8 digit numeric password.\n\nReturns:\n bool: True on completion with ACK.", "source": "juraj_google_style"} +{"code": "def _GetDictFromStringsTable(self, parser_mediator, table):\n\n if not table:\n return {}\n\n record_values = {}\n for record in table.records:\n if parser_mediator.abort:\n break\n\n if record.get_number_of_values() != 2:\n continue\n\n identification = self._GetRecordValue(record, 0)\n filename = self._GetRecordValue(record, 1)\n\n if not identification:\n continue\n record_values[identification] = filename\n\n return record_values", "docstring": "Build a dictionary of the value in the strings table.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n table (pyesedb.table): strings table.\n\nReturns:\n dict[str,object]: values per column name.", "source": "juraj_google_style"} +{"code": "def are_equal_xml(a_xml, b_xml):\n\n a_dom = xml.dom.minidom.parseString(a_xml)\n b_dom = xml.dom.minidom.parseString(b_xml)\n return are_equal_elements(a_dom.documentElement, b_dom.documentElement)", "docstring": "Normalize and compare XML documents for equality. The document may or may not be\n a DataONE type.\n\nArgs:\n a_xml: str\n b_xml: str\n XML documents to compare for equality.\n\nReturns:\n bool: ``True`` if the XML documents are semantically equivalent.", "source": "juraj_google_style"} +{"code": "def _open_config_files(self, command_line_args):\n\n # open any default config files\n config_files = [open(f) for files in map(glob.glob, map(os.path.expanduser, self._default_config_files))\n for f in files]\n\n # list actions with is_config_file_arg=True. Its possible there is more\n # than one such arg.\n user_config_file_arg_actions = [\n a for a in self._actions if getattr(a, \"is_config_file_arg\", False)]\n\n if not user_config_file_arg_actions:\n return config_files\n\n for action in user_config_file_arg_actions:\n # try to parse out the config file path by using a clean new\n # ArgumentParser that only knows this one arg/action.\n arg_parser = argparse.ArgumentParser(\n prefix_chars=self.prefix_chars,\n add_help=False)\n\n arg_parser._add_action(action)\n\n # make parser not exit on error by replacing its error method.\n # Otherwise it sys.exits(..) if, for example, config file\n # is_required=True and user doesn't provide it.\n def error_method(self, message):\n pass\n arg_parser.error = types.MethodType(error_method, arg_parser)\n\n # check whether the user provided a value\n parsed_arg = arg_parser.parse_known_args(args=command_line_args)\n if not parsed_arg:\n continue\n namespace, _ = parsed_arg\n user_config_file = getattr(namespace, action.dest, None)\n\n if not user_config_file:\n continue\n # validate the user-provided config file path\n user_config_file = os.path.expanduser(user_config_file)\n if not os.path.isfile(user_config_file):\n self.error('File not found: %s' % user_config_file)\n\n config_files += [open(user_config_file)]\n\n return config_files", "docstring": "Tries to parse config file path(s) from within command_line_args.\n Returns a list of opened config files, including files specified on the\n commandline as well as any default_config_files specified in the\n constructor that are present on disk.\n\nArgs:\n command_line_args: List of all args (already split on spaces)", "source": "juraj_google_style"} +{"code": "def assign(var, new_val, assign_fn=assign_slice):\n\n if isinstance(var, Tensor):\n var = var.operation\n if not isinstance(var, Variable):\n raise ValueError(\"var must be a mtf.Variable or its output Tensor.\")\n return Assign([var], [new_val], assign_fn=assign_fn)", "docstring": "Assign a new value to a variable.\n\nArgs:\n var: either a Variable operation or its output Tensor.\n new_val: a Tensor\n assign_fn: a function from\n (mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation\n\nReturns:\n an Operation\n\nRaises:\n ValueError: if var is not a Variable and var.operation is not a Variable", "source": "juraj_google_style"} +{"code": "def describe_ring(self, keyspace):\n\n self._seqid += 1\n d = self._reqs[self._seqid] = defer.Deferred()\n self.send_describe_ring(keyspace)\n return d", "docstring": "get the token ring: a map of ranges to host addresses,\n represented as a set of TokenRange instead of a map from range\n to list of endpoints, because you can't use Thrift structs as\n map keys:\n https://issues.apache.org/jira/browse/THRIFT-162\n\n for the same reason, we can't return a set here, even though\n order is neither important nor predictable.\n\n Parameters:\n - keyspace", "source": "juraj_google_style"} +{"code": "def setConfiguration(self, configuration):\n r\n if isinstance(configuration, Configuration):\n configuration = configuration.value\n\n self.dev.set_configuration(configuration)", "docstring": "r\"\"\"Set the active configuration of a device.\n\nArgs:\n configuration: a configuration value or a Configuration object.", "source": "juraj_google_style"} +{"code": "def load_config(logdir):\n # pylint: disable=missing-raises-doc\n\n config_path = logdir and os.path.join(logdir, 'config.yaml')\n if not config_path or not tf.gfile.Exists(config_path):\n message = (\n 'Cannot resume an existing run since the logging directory does not '\n 'contain a configuration file.')\n raise IOError(message)\n with tf.gfile.FastGFile(config_path, 'r') as file_:\n config = yaml.load(file_, Loader=yaml.Loader)\n message = 'Resume run and write summaries and checkpoints to {}.'\n tf.logging.info(message.format(config.logdir))\n return config", "docstring": "Load a configuration from the log directory.\n\nArgs:\n logdir: The logging directory containing the configuration file.\n\nRaises:\n IOError: The logging directory does not contain a configuration file.\n\nReturns:\n Configuration object.", "source": "juraj_google_style"} +{"code": "def MapFile(self, key_path_prefix, registry_file):\n\n self._registry_files[key_path_prefix.upper()] = registry_file\n registry_file.SetKeyPathPrefix(key_path_prefix)", "docstring": "Maps the Windows Registry file to a specific key path prefix.\n\nArgs:\n key_path_prefix (str): key path prefix.\n registry_file (WinRegistryFile): Windows Registry file.", "source": "juraj_google_style"} +{"code": "def kcover(I,J,c,k):\n\n\n model = Model(\"k-center\")\n\n z,y,x = {},{},{}\n for i in I:\n z[i] = model.addVar(vtype=\"B\", name=\"z(%s)\"%i, obj=1)\n for j in J:\n y[j] = model.addVar(vtype=\"B\", name=\"y(%s)\"%j)\n for i in I:\n x[i,j] = model.addVar(vtype=\"B\", name=\"x(%s,%s)\"%(i,j))\n\n for i in I:\n model.addCons(quicksum(x[i,j] for j in J) + z[i] == 1, \"Assign(%s)\"%i)\n for j in J:\n model.addCons(x[i,j] <= y[j], \"Strong(%s,%s)\"%(i,j))\n\n model.addCons(sum(y[j] for j in J) == k, \"k_center\")\n model.data = x,y,z\n\n return model", "docstring": "kcover -- minimize the number of uncovered customers from k facilities.\n Parameters:\n - I: set of customers\n - J: set of potential facilities\n - c[i,j]: cost of servicing customer i from facility j\n - k: number of facilities to be used\n Returns a model, ready to be solved.", "source": "juraj_google_style"} +{"code": "def _validate_body_parameters(self, body, action_spec):\n\n processed_params = []\n for param_name, param_spec in action_spec['parameters'].items():\n if param_spec['in'] == 'body':\n processed_params.append(param_name)\n\n # Check type\n if 'type' in param_spec.keys() and not self.check_type(body, param_spec['type']):\n msg = \"Check type did not validate for {0} and {1}\".format(param_spec['type'], body)\n return False, msg\n # Check schema\n elif 'schema' in param_spec.keys():\n if 'type' in param_spec['schema'].keys() and param_spec['schema']['type'] == 'array':\n # It is an array get value from definition\n definition_name = self.get_definition_name_from_ref(param_spec['schema']['items']['$ref'])\n if len(body) > 0 and not self.validate_definition(definition_name, body[0]):\n msg = \"The body did not validate against its definition\"\n return False, msg\n elif ('type' in param_spec['schema'].keys() and not\n self.check_type(body, param_spec['schema']['type'])):\n # Type but not array\n msg = \"Check type did not validate for {0} and {1}\".format(param_spec['schema']['type'], body)\n return False, msg\n else:\n definition_name = self.get_definition_name_from_ref(param_spec['schema']['$ref'])\n if not self.validate_definition(definition_name, body):\n msg = \"The body did not validate against its definition\"\n return False, msg\n # Check required\n if not all(param in processed_params for param, spec in action_spec['parameters'].items()\n if spec['in'] == 'body' and 'required' in spec and spec['required']):\n msg = \"Not all required parameters were present\"\n return False, msg\n\n return True, \"\"", "docstring": "Check the body parameter for the action specification.\n\nArgs:\n body: body parameter to check.\n action_spec: specification of the action.\n\nReturns:\n True if the body is valid.\n A string containing an error msg in case the body did not validate,\n otherwise the string is empty", "source": "juraj_google_style"} +{"code": "def is_closed(self):\n\n for t in self.smi_vector:\n found = False\n for s in self.sm_vector:\n if self.observation_table[s] == self.observation_table[t]:\n self.equiv_classes[t] = s\n found = True\n break\n if not found:\n return False, t\n return True, None", "docstring": "_check if the observation table is closed.\n\nArgs:\n None\n\nReturns:\n tuple (bool, str): True if the observation table is\n closed and false otherwise. If the table is not closed\n the escaping string is returned.", "source": "juraj_google_style"} +{"code": "def read(self, size=None):\n\n if not self._is_open:\n raise IOError('Not opened.')\n\n if self._current_offset < 0:\n raise IOError(\n 'Invalid current offset: {0:d} value less than zero.'.format(\n self._current_offset))\n\n if self._file_data is None or self._current_offset >= self._size:\n return b''\n\n if size is None:\n size = self._size\n if self._current_offset + size > self._size:\n size = self._size - self._current_offset\n\n start_offset = self._current_offset\n self._current_offset += size\n return self._file_data[start_offset:self._current_offset]", "docstring": "Reads a byte string from the file-like object at the current offset.\n\n The function will read a byte string of the specified size or\n all of the remaining data if no size was specified.\n\nArgs:\n size (Optional[int]): number of bytes to read, where None is all\n remaining data.\n\nReturns:\n bytes: data read.\n\nRaises:\n IOError: if the read failed.\n OSError: if the read failed.", "source": "juraj_google_style"} +{"code": "def __valueKeyWithHeaderIndex(self, values):\n\n\n\t\tmachingIndexes = {}\n\t\tfor index, name in enumerate(self.header):\n\t\t\tif name in values:\n\t\t\t\tmachingIndexes[index] = values[name]\n\t\treturn machingIndexes", "docstring": "This is hellper function, so that we can mach decision values with row index\n as represented in header index.\n\nArgs:\n values (dict): Normaly this will have dict of header values and values from decision\n\nReturns:\n >>> return()\n {\n values[headerName] : int(headerName index in header array),\n ...\n }", "source": "juraj_google_style"} +{"code": "def mme_matches(case_obj, institute_obj, mme_base_url, mme_token):\n\n data = {\n 'institute' : institute_obj,\n 'case' : case_obj,\n 'server_errors' : []\n }\n matches = {}\n # loop over the submitted samples and get matches from the MatchMaker server\n if not case_obj.get('mme_submission'):\n return None\n\n for patient in case_obj['mme_submission']['patients']:\n patient_id = patient['id']\n matches[patient_id] = None\n url = ''.join([ mme_base_url, '/matches/', patient_id])\n server_resp = matchmaker_request(url=url, token=mme_token, method='GET')\n if 'status_code' in server_resp: # the server returned a valid response\n # and this will be a list of match objects sorted by desc date\n pat_matches = []\n if server_resp.get('matches'):\n pat_matches = parse_matches(patient_id, server_resp['matches'])\n matches[patient_id] = pat_matches\n else:\n LOG.warning('Server returned error message: {}'.format(server_resp['message']))\n data['server_errors'].append(server_resp['message'])\n\n data['matches'] = matches\n\n return data", "docstring": "Show Matchmaker submission data for a sample and eventual matches.\n\nArgs:\n case_obj(dict): a scout case object\n institute_obj(dict): an institute object\n mme_base_url(str) base url of the MME server\n mme_token(str) auth token of the MME server\n\nReturns:\n data(dict): data to display in the html template", "source": "juraj_google_style"} +{"code": "def get_package_install_path(self, path):\n\n from rez.package_repository import package_repository_manager\n\n pkg_repo = package_repository_manager.get_repository(path)\n\n return pkg_repo.get_package_payload_path(\n package_name=self.package.name,\n package_version=self.package.version\n )", "docstring": "Return the installation path for a package (where its payload goes).\n\nArgs:\n path (str): Package repository path.", "source": "juraj_google_style"} +{"code": "def _refresh(self, _):\n\n # pylint: disable=import-error\n from google.appengine.api import app_identity\n try:\n token, _ = app_identity.get_access_token(self._scopes)\n except app_identity.Error as e:\n raise exceptions.CredentialsError(str(e))\n self.access_token = token", "docstring": "Refresh self.access_token.\n\nArgs:\n _: (ignored) A function matching httplib2.Http.request's signature.", "source": "juraj_google_style"} +{"code": "def get_creator_by_name(name):\n\n return {'docker(container)': Container.creator,\n 'shell': Bash.creator, 'docker(image)': Image.creator,\n 'python': Script.creator, 'packer': Packer.creator,\n 'ansible(simple)': Ansible.creator}[name]", "docstring": "Get creator function by name.\n\nArgs:\n name (str): name of the creator function.\n\nReturns:\n function: creater function.", "source": "juraj_google_style"} +{"code": "def getSpatialReferenceId(self, session):\n\n statement = .format(self.geometryColumnName,\n self.tableName,\n self.id)\n\n result = session.execute(statement)\n\n for row in result:\n return row.srid", "docstring": "Retrieve the spatial reference id by which the geometry column is registered.\n\n This method is a veneer for an SQL query that calls the ``ST_SRID()`` function on the geometry column.\n\nArgs:\n session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.\n\nReturns:\n str: PostGIS spatial reference ID.", "source": "juraj_google_style"} +{"code": "def WriteManyToPath(objs, filepath):\n\n with io.open(filepath, mode=\"w\", encoding=\"utf-8\") as filedesc:\n WriteManyToFile(objs, filedesc)", "docstring": "Serializes and writes given Python objects to a multi-document YAML file.\n\nArgs:\n objs: An iterable of Python objects to serialize.\n filepath: A path to the file into which the object is to be written.", "source": "juraj_google_style"} +{"code": "def _PrintCheckDependencyStatus(\n self, dependency, result, status_message, verbose_output=True):\n\n if not result or dependency.is_optional:\n if dependency.is_optional:\n status_indicator = '[OPTIONAL]'\n else:\n status_indicator = '[FAILURE]'\n\n print('{0:s}\\t{1:s}'.format(status_indicator, status_message))\n\n elif verbose_output:\n print('[OK]\\t\\t{0:s}'.format(status_message))", "docstring": "Prints the check dependency status.\n\nArgs:\n dependency (DependencyDefinition): dependency definition.\n result (bool): True if the Python module is available and conforms to\n the minimum required version, False otherwise.\n status_message (str): status message.\n verbose_output (Optional[bool]): True if output should be verbose.", "source": "juraj_google_style"} +{"code": "def __init__(self, usb):\n\n self._usb = usb\n self._protocol = self.protocol_handler(usb)", "docstring": "Constructs a FastbootCommands instance.\n\nArgs:\n usb: UsbHandle instance.", "source": "juraj_google_style"} +{"code": "def sg_min(tensor, opt):\n r\n return tf.reduce_min(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)", "docstring": "r\"\"\"Computes the minimum of elements across axis of a tensor.\n\n See `tf.reduce_min()` in tensorflow.\n\nArgs:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains reduced dimensions with length 1.\n name: If provided, replace current tensor's name.\n\nReturns:\n A `Tensor`.", "source": "juraj_google_style"} +{"code": "def GetFileEntryByPathSpec(self, path_spec):\n\n return compressed_stream_file_entry.CompressedStreamFileEntry(\n self._resolver_context, self, path_spec, is_root=True, is_virtual=True)", "docstring": "Retrieves a file entry for a path specification.\n\nArgs:\n path_spec (PathSpec): a path specification.\n\nReturns:\n CompressedStreamFileEntry: a file entry or None if not available.", "source": "juraj_google_style"} +{"code": "def get_phonopy_structure(pmg_structure):\n\n\n symbols = [site.specie.symbol for site in pmg_structure]\n\n return PhonopyAtoms(symbols=symbols, cell=pmg_structure.lattice.matrix,\n scaled_positions=pmg_structure.frac_coords)", "docstring": "Convert a pymatgen Structure object to a PhonopyAtoms object.\n\nArgs:\n pmg_structure (pymatgen Structure): A Pymatgen structure object.", "source": "juraj_google_style"} +{"code": "def create_workspace_config(namespace, workspace, body):\n\n\n #json_body = {\n # \"namespace\" : mnamespace,\n # \"name\" : method,\n # \"rootEntityType\" : root_etype,\n # \"inputs\" : {},\n # \"outputs\" : {},\n # \"prerequisites\" : {}\n #}\n uri = \"workspaces/{0}/{1}/methodconfigs\".format(namespace, workspace)\n return __post(uri, json=body)", "docstring": "Create method configuration in workspace.\n\nArgs:\n namespace (str): project to which workspace belongs\n workspace (str): Workspace name\n body (json) : a filled-in JSON object for the new method config\n (e.g. see return value of get_workspace_config)\n\n Swagger:\n https://api.firecloud.org/#!/Method_Configurations/postWorkspaceMethodConfig\n DUPLICATE: https://api.firecloud.org/#!/Workspaces/postWorkspaceMethodConfig", "source": "juraj_google_style"} +{"code": "def _get_descending_key(gettime=time.time):\n\n now_descending = int((_FUTURE_TIME - gettime()) * 100)\n request_id_hash = os.environ.get(\"REQUEST_ID_HASH\")\n if not request_id_hash:\n request_id_hash = str(random.getrandbits(32))\n return \"%d%s\" % (now_descending, request_id_hash)", "docstring": "Returns a key name lexically ordered by time descending.\n\n This lets us have a key name for use with Datastore entities which returns\n rows in time descending order when it is scanned in lexically ascending order,\n allowing us to bypass index building for descending indexes.\n\nArgs:\n gettime: Used for testing.\n\nReturns:\n A string with a time descending key.", "source": "juraj_google_style"} +{"code": "def WriteConfig(self, config_file=None):\n\n config_file = config_file or self.config_file\n config_name = os.path.splitext(os.path.basename(config_file))[0]\n config_lock = (\n '%s/lock/google_%s.lock' % (constants.LOCALSTATEDIR, config_name))\n with file_utils.LockFile(config_lock):\n with open(config_file, 'w') as config_fp:\n if self.config_header:\n self._AddHeader(config_fp)\n self.config.write(config_fp)", "docstring": "Write the config values to a given file.\n\nArgs:\n config_file: string, the file location of the config file to write.", "source": "juraj_google_style"} +{"code": "def _StartAnalysisProcesses(self, storage_writer, analysis_plugins):\n\n logger.info('Starting analysis plugins.')\n\n for analysis_plugin in analysis_plugins.values():\n self._analysis_plugins[analysis_plugin.NAME] = analysis_plugin\n\n process = self._StartWorkerProcess(analysis_plugin.NAME, storage_writer)\n if not process:\n logger.error('Unable to create analysis process: {0:s}'.format(\n analysis_plugin.NAME))\n\n logger.info('Analysis plugins running')", "docstring": "Starts the analysis processes.\n\nArgs:\n storage_writer (StorageWriter): storage writer.\n analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that\n should be run and their names.", "source": "juraj_google_style"} +{"code": "def get_all_publications(return_namedtuples=True):\n\n sources = [\n ben_cz.get_publications,\n grada_cz.get_publications,\n cpress_cz.get_publications,\n zonerpress_cz.get_publications,\n ]\n\n # get data from all scrappers\n publications = []\n for source in sources:\n publications.extend(\n filters.filter_publications(source())\n )\n\n # convert to namedtuples\n if return_namedtuples:\n publications = map(lambda x: x.to_namedtuple(), publications)\n\n return publications", "docstring": "Get list publications from all available source.\n\nArgs:\n return_namedtuples (bool, default True): Convert :class:`.Publication`\n structures to namedtuples (used in AMQP\n communication).\n\nReturns:\n list: List of :class:`.Publication` structures converted to namedtuple.", "source": "juraj_google_style"} +{"code": "def addLogicalInterfaceToDeviceType(self, typeId, logicalInterfaceId):\n\n req = ApiClient.allDeviceTypeLogicalInterfacesUrl % (self.host, \"/draft\", typeId)\n body = {\"id\" : logicalInterfaceId}\n# body = {\"name\" : \"required but not used!!!\", \"id\" : logicalInterfaceId, \"schemaId\" : schemaId}\n# if description:\n# body[\"description\"] = description\n resp = requests.post(req, auth=self.credentials, headers={\"Content-Type\":\"application/json\"}, data=json.dumps(body),\n verify=self.verify)\n if resp.status_code == 201:\n self.logger.debug(\"Logical interface added to a device type\")\n else:\n raise ibmiotf.APIException(resp.status_code, \"HTTP error adding logical interface to a device type\", resp)\n return resp.json()", "docstring": "Adds a logical interface to a device type.\n Parameters:\n - typeId (string) - the device type\n - logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface\n - description (string) - optional (not used)\n Throws APIException on failure.", "source": "juraj_google_style"} +{"code": "def prepare_csv_read(data, field_names, *args, **kwargs):\n\n if hasattr(data, 'readlines') or isinstance(data, list):\n pass\n elif isinstance(data, basestring):\n data = open(data)\n else:\n raise TypeError('Unable to handle data of type %r' % type(data))\n return csv.DictReader(data, field_names, *args, **kwargs)", "docstring": "Prepare various input types for CSV parsing.\n\nArgs:\n data (iter): Data to read\n field_names (tuple of str): Ordered names to assign to fields\n\nReturns:\n csv.DictReader: CSV reader suitable for parsing\n\nRaises:\n TypeError: Invalid value for data", "source": "juraj_google_style"} +{"code": "def FromString(val):\n\n # first, check if the value supplied is the string literal of the enum (e.g. \"String\")\n\n if isinstance(val, bytes):\n val = val.decode('utf-8')\n\n try:\n return ContractParameterType[val]\n except Exception as e:\n # ignore a KeyError if the val isn't found in the Enum\n pass\n\n # second, check if the value supplied is bytes or hex-encoded (e.g. b'07')\n try:\n if isinstance(val, (bytearray, bytes)):\n int_val = int.from_bytes(val, 'little')\n else:\n int_val = int.from_bytes(binascii.unhexlify(val), 'little')\n except (binascii.Error, TypeError) as e:\n # if it's not hex-encoded, then convert as int (e.g. \"7\" or 7)\n int_val = int(val)\n\n return ContractParameterType(int_val)", "docstring": "Create a ContractParameterType object from a str\n\nArgs:\n val (str): the value to be converted to a ContractParameterType.\n val can be hex encoded (b'07'), int (7), string int (\"7\"), or string literal (\"String\")\n\nReturns:\n ContractParameterType", "source": "juraj_google_style"} +{"code": "def __init__(self, features, targets, **kwargs):\n\n # Init model\n super().__init__(**kwargs)\n\n # Set axes\n self.features = features\n self.targets = targets\n\n # Train model\n self.fit(features.train, targets.train)", "docstring": "Inits a Random Forest Classifier with a market attribute\n\nArgs:\n **kwargs: Scikit Learn's RandomForestClassifier kwargs", "source": "juraj_google_style"} +{"code": "def connected_site_pairs( self ):\n\n site_connections = {}\n for initial_site in self.sites:\n if not initial_site.label in site_connections:\n site_connections[ initial_site.label ] = []\n for final_site in initial_site.p_neighbours:\n if final_site.label not in site_connections[ initial_site.label ]:\n site_connections[ initial_site.label ].append( final_site.label )\n return site_connections", "docstring": "Returns a dictionary of all connections between pair of sites (by site label).\n e.g. for a linear lattice A-B-C will return::\n\n { 'A' : [ 'B' ], 'B' : [ 'A', 'C' ], 'C' : [ 'B' ] }\n\nArgs:\n None\n\nReturns:\n site_connections (Dict{Str List[Str]}): A dictionary of neighbouring site types in the lattice.", "source": "juraj_google_style"} +{"code": "def add_hgnc_id(self, genes):\n\n genes_by_alias = self.genes_by_alias()\n\n for gene in genes:\n id_info = genes_by_alias.get(gene['hgnc_symbol'])\n if not id_info:\n LOG.warning(\"Gene %s does not exist in scout\", gene['hgnc_symbol'])\n continue\n gene['hgnc_id'] = id_info['true']\n if not id_info['true']:\n if len(id_info['ids']) > 1:\n LOG.warning(\"Gene %s has ambiguous value, please choose one hgnc id in result\", gene['hgnc_symbol'])\n gene['hgnc_id'] = ','.join([str(hgnc_id) for hgnc_id in id_info['ids']])", "docstring": "Add the correct hgnc id to a set of genes with hgnc symbols\n\nArgs:\n genes(list(dict)): A set of genes with hgnc symbols only", "source": "juraj_google_style"} +{"code": "def _get_napp_key(self, key, user=None, napp=None):\n\n if user is None:\n user = self.user\n if napp is None:\n napp = self.napp\n kytos_json = self._installed / user / napp / 'kytos.json'\n try:\n with kytos_json.open() as file_descriptor:\n meta = json.load(file_descriptor)\n return meta[key]\n except (FileNotFoundError, json.JSONDecodeError, KeyError):\n return ''", "docstring": "Return a value from kytos.json.\n\nArgs:\n user (string): A Username.\n napp (string): A NApp name\n key (string): Key used to get the value within kytos.json.\n\nReturns:\n meta (object): Value stored in kytos.json.", "source": "juraj_google_style"} +{"code": "def __eq__(self, other):\n\n # pylint: disable=too-many-boolean-expressions\n if (type(self) is type(other) and\n self._index == other._index and\n self._drives == other._drives and\n self._controls == other._controls and\n self._measures == other._measures and\n self._acquires == other._acquires):\n return True\n return False", "docstring": "Two physical qubits are the same if they have the same index and channels.\n\nArgs:\n other (Qubit): other Qubit\n\nReturns:\n bool: are self and other equal.", "source": "juraj_google_style"} +{"code": "def execute_async_script(self, script, *args):\n\n return self._execute(Command.EXECUTE_ASYNC_SCRIPT, {\n 'script': script,\n 'args': list(args)})", "docstring": "Execute JavaScript Asynchronously in current context.\n\n Support:\n Web(WebView)\n\nArgs:\n script: The JavaScript to execute.\n *args: Arguments for your JavaScript.\n\nReturns:\n Returns the return value of the function.", "source": "juraj_google_style"} +{"code": "def ProduceExtractionWarning(self, message, path_spec=None):\n\n if not self._storage_writer:\n raise RuntimeError('Storage writer not set.')\n\n if not path_spec and self._file_entry:\n path_spec = self._file_entry.path_spec\n\n parser_chain = self.GetParserChain()\n warning = warnings.ExtractionWarning(\n message=message, parser_chain=parser_chain, path_spec=path_spec)\n self._storage_writer.AddWarning(warning)\n self._number_of_warnings += 1\n\n self.last_activity_timestamp = time.time()", "docstring": "Produces an extraction warning.\n\nArgs:\n message (str): message of the warning.\n path_spec (Optional[dfvfs.PathSpec]): path specification, where None\n will use the path specification of current file entry set in\n the mediator.\n\nRaises:\n RuntimeError: when storage writer is not set.", "source": "juraj_google_style"} +{"code": "def Log_startViolationsReport(self, config):\n\n\t\tassert isinstance(config, (list, tuple)\n\t\t ), \"Argument 'config' must be of type '['list', 'tuple']'. Received type: '%s'\" % type(\n\t\t config)\n\t\tsubdom_funcs = self.synchronous_command('Log.startViolationsReport',\n\t\t config=config)\n\t\treturn subdom_funcs", "docstring": "Function path: Log.startViolationsReport\n Domain: Log\n Method name: startViolationsReport\n\n Parameters:\n Required arguments:\n 'config' (type: array) -> Configuration for violations.\n No return value.\n\n Description: start violation reporting.", "source": "juraj_google_style"} +{"code": "def create_pane(widgets, horizontal, parent_widget=None, compact=False,\n compact_spacing=2):\n\n pane = parent_widget or QtGui.QWidget()\n type_ = QtGui.QHBoxLayout if horizontal else QtGui.QVBoxLayout\n layout = type_()\n if compact:\n layout.setSpacing(compact_spacing)\n layout.setContentsMargins(compact_spacing, compact_spacing,\n compact_spacing, compact_spacing)\n\n for widget in widgets:\n stretch = 0\n if isinstance(widget, tuple):\n widget, stretch = widget\n\n if isinstance(widget, int):\n layout.addSpacing(widget)\n elif widget:\n layout.addWidget(widget, stretch)\n else:\n layout.addStretch()\n\n pane.setLayout(layout)\n return pane", "docstring": "Create a widget containing an aligned set of widgets.\n\nArgs:\n widgets (list of `QWidget`).\n horizontal (bool).\n align (str): One of:\n - 'left', 'right' (horizontal);\n - 'top', 'bottom' (vertical)\n parent_widget (`QWidget`): Owner widget, QWidget is created if this\n is not provided.\n\nReturns:\n `QWidget`", "source": "juraj_google_style"} +{"code": "def calc_stats(prices):\n\n if isinstance(prices, pd.Series):\n return PerformanceStats(prices)\n elif isinstance(prices, pd.DataFrame):\n return GroupStats(*[prices[x] for x in prices.columns])\n else:\n raise NotImplementedError('Unsupported type')", "docstring": "Calculates performance stats of a given object.\n\n If object is Series, a PerformanceStats object is\n returned. If object is DataFrame, a GroupStats object\n is returned.\n\nArgs:\n * prices (Series, DataFrame): Set of prices", "source": "juraj_google_style"} +{"code": "def __eq__(self, other: 'TensorFluent') -> 'TensorFluent':\n\n return self._binary_op(self, other, tf.equal, tf.float32)", "docstring": "Returns a TensorFluent for the equal relational operator.\n\nArgs:\n self: The first operand.\n other: The second operand.", "source": "juraj_google_style"} +{"code": "def connect(self,\n fedora_url,\n data=None,\n method='Get'):\n\n if data is None:\n data = {}\n if not fedora_url.startswith(\"http\"):\n fedora_url = urllib.parse.urljoin(self.base_url, fedora_url)\n request = urllib.request.Request(fedora_url,\n method=method)\n request.add_header('Accept', 'text/turtle')\n request.add_header('Content-Type', 'text/turtle')\n if len(data) > 0:\n request.data = data\n try:\n response = urllib.request.urlopen(request)\n except urllib.error.URLError as err:\n if hasattr(err, 'reason'):\n print(\"failed to reach server at {} with {} method\".format(\n fedora_url,\n request.method))\n print(\"Reason: \", err.reason)\n print(\"Data: \", data)\n elif hasattr(err, 'code'):\n print(\"Server error {}\".format(err.code))\n raise err\n return response", "docstring": "Method attempts to connect to REST servers of the Fedora\n Commons repository using optional data parameter.\n\nArgs:\n fedora_url(string): Fedora URL\n data(dict): Data to through to REST endpoint\n method(str): REST Method, defaults to GET\n\nReturns:\n result(string): Response string from Fedora", "source": "juraj_google_style"} +{"code": "def subcommand(self, *args):\n\n return Subcommand(*args, directory=self.directory, env_vars=self.env_vars)", "docstring": "Get subcommand acting on a service. Subcommand will run in service directory\n and with the environment variables used to run the service itself.\n\nArgs:\n *args: Arguments to run command (e.g. \"redis-cli\", \"-n\", \"1\")\n\nReturns:\n Subcommand object.", "source": "juraj_google_style"} +{"code": "def checkUser(self, user):\n\n return not self.conn(\"POST\", \"{0}/GetCredentialType.srf\".format(SkypeConnection.API_MSACC),\n json={\"username\": user}).json().get(\"IfExistsResult\")", "docstring": "Query a username or email address to see if a corresponding Microsoft account exists.\n\nArgs:\n user (str): username or email address of an account\n\nReturns:\n bool: whether the account exists", "source": "juraj_google_style"} +{"code": "def walk(self, address):\n\n\n for step in self._walk_to_address(address):\n node = step\n yield node.address, node.data\n\n to_process = deque()\n\n to_process.extendleft(\n node.children)\n\n while to_process:\n node = to_process.pop()\n\n yield node.address, node.data\n\n if node.children:\n to_process.extendleft(\n node.children)", "docstring": "Returns a stream of pairs of node addresses and data, raising\n AddressNotInTree if ADDRESS is not in the tree.\n\n First the ancestors of ADDRESS (including itself) are yielded,\n earliest to latest, and then the descendants of ADDRESS are\n yielded in an unspecified order.\n\nArgs:\n address (str): the address to be walked", "source": "juraj_google_style"} +{"code": "def _GetMetadataRequest(self, metadata_url, params=None, timeout=None):\n\n headers = {'Metadata-Flavor': 'Google'}\n params = urlparse.urlencode(params or {})\n url = '%s?%s' % (metadata_url, params)\n request = urlrequest.Request(url, headers=headers)\n request_opener = urlrequest.build_opener(urlrequest.ProxyHandler({}))\n timeout = timeout or self.timeout\n return request_opener.open(request, timeout=timeout*1.1)", "docstring": "Performs a GET request with the metadata headers.\n\nArgs:\n metadata_url: string, the URL to perform a GET request on.\n params: dictionary, the query parameters in the GET request.\n timeout: int, timeout in seconds for metadata requests.\n\nReturns:\n HTTP response from the GET request.\n\nRaises:\n urlerror.HTTPError: raises when the GET request fails.", "source": "juraj_google_style"} +{"code": "def color_set_hsv(c: Color, h: float, s: float, v: float) -> None:\n\n new_color = ffi.new(\"TCOD_color_t*\")\n lib.TCOD_color_set_HSV(new_color, h, s, v)\n c[:] = new_color.r, new_color.g, new_color.b", "docstring": "Set a color using: hue, saturation, and value parameters.\n\n Does not return a new Color. ``c`` is modified inplace.\n\nArgs:\n c (Union[Color, List[Any]]): A Color instance, or a list of any kind.\n h (float): Hue, from 0 to 360.\n s (float): Saturation, from 0 to 1.\n v (float): Value, from 0 to 1.", "source": "juraj_google_style"} +{"code": "def _create_w_objective(m, X, R):\n\n genes, clusters = m.shape\n cells = X.shape[1]\n R1 = R.reshape((genes, 1)).dot(np.ones((1, cells)))\n def objective(w):\n # convert w into a matrix first... because it's a vector for\n # optimization purposes\n w = w.reshape((m.shape[1], X.shape[1]))\n d = m.dot(w)+eps\n return np.sum((X + R1)*np.log(d + R1) - X*np.log(d))/genes\n def deriv(w):\n # derivative of objective wrt all elements of w\n # for w_{ij}, the derivative is... m_j1+...+m_jn sum over genes minus \n # x_ij\n w2 = w.reshape((m.shape[1], X.shape[1]))\n d = m.dot(w2)+eps\n temp = X/d\n temp2 = (X+R1)/(d+R1)\n m1 = m.T.dot(temp2)\n m2 = m.T.dot(temp)\n deriv = m1 - m2\n return deriv.flatten()/genes\n return objective, deriv", "docstring": "Creates an objective function and its derivative for W, given M and X (data)\n\nArgs:\n m (array): genes x clusters\n X (array): genes x cells\n R (array): 1 x genes", "source": "juraj_google_style"} +{"code": "def decode_conjure_bean_type(cls, obj, conjure_type):\n\n deserialized = {} # type: Dict[str, Any]\n for (python_arg_name, field_definition) \\\n in conjure_type._fields().items():\n field_identifier = field_definition.identifier\n\n if field_identifier not in obj or obj[field_identifier] is None:\n cls.check_null_field(\n obj, deserialized, python_arg_name, field_definition)\n else:\n value = obj[field_identifier]\n field_type = field_definition.field_type\n deserialized[python_arg_name] = \\\n cls.do_decode(value, field_type)\n return conjure_type(**deserialized)", "docstring": "Decodes json into a conjure bean type (a plain bean, not enum\n or union).\n\nArgs:\n obj: the json object to decode\n conjure_type: a class object which is the bean type\n we're decoding into\n\nReturns:\n A instance of a bean of type conjure_type.", "source": "juraj_google_style"} +{"code": "def suggest(self, query):\n\n res, suggest = self.search(query, results=1, suggestion=True)\n try:\n title = suggest or res[0]\n except IndexError: # page doesn't exist\n title = None\n return title", "docstring": "Gather suggestions based on the provided title or None if no\n suggestions found\n\nArgs:\n query (str): Page title\n\nReturns:\n String or None: Suggested page title or **None** if no \\\n suggestion found", "source": "juraj_google_style"} +{"code": "def list_container_instance_groups_sub(access_token, subscription_id):\n\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/providers/Microsoft.ContainerInstance/ContainerGroups',\n '?api-version=', CONTAINER_API])\n return do_get(endpoint, access_token)", "docstring": "List the container groups in a subscription.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n\nReturns:\n HTTP response. JSON list of container groups and their properties.", "source": "juraj_google_style"} +{"code": "def predict(self, a, b):\n\n a = np.array(a).reshape((-1, 1))\n b = np.array(b).reshape((-1, 1))\n return (mutual_info_regression(a, b.reshape((-1,))) + mutual_info_regression(b, a.reshape((-1,))))/2", "docstring": "Compute the test statistic\n\nArgs:\n a (array-like): Variable 1\n b (array-like): Variable 2\n\nReturns:\n float: test statistic", "source": "juraj_google_style"} +{"code": "def StopTaskStorage(self, abort=False):\n\n if self._storage_type != definitions.STORAGE_TYPE_SESSION:\n raise IOError('Unsupported storage type.')\n\n if os.path.isdir(self._merge_task_storage_path):\n if abort:\n shutil.rmtree(self._merge_task_storage_path)\n else:\n os.rmdir(self._merge_task_storage_path)\n\n if os.path.isdir(self._processed_task_storage_path):\n if abort:\n shutil.rmtree(self._processed_task_storage_path)\n else:\n os.rmdir(self._processed_task_storage_path)\n\n if os.path.isdir(self._task_storage_path):\n if abort:\n shutil.rmtree(self._task_storage_path)\n else:\n os.rmdir(self._task_storage_path)\n\n self._merge_task_storage_path = None\n self._processed_task_storage_path = None\n self._task_storage_path = None", "docstring": "Removes the temporary path for the task storage.\n\n The results of tasks will be lost on abort.\n\nArgs:\n abort (bool): True to indicate the stop is issued on abort.\n\nRaises:\n IOError: if the storage type is not supported.\n OSError: if the storage type is not supported.", "source": "juraj_google_style"} +{"code": "def render_template(cmd_derived_from_alias, pos_args_table):\n\n try:\n cmd_derived_from_alias = normalize_placeholders(cmd_derived_from_alias, inject_quotes=True)\n template = jinja.Template(cmd_derived_from_alias)\n\n # Shlex.split allows us to split a string by spaces while preserving quoted substrings\n # (positional arguments in this case)\n rendered = shlex.split(template.render(pos_args_table))\n\n # Manually check if there is any runtime error (such as index out of range)\n # since Jinja template engine only checks for compile time error.\n # Only check for runtime errors if there is an empty string in rendered.\n if '' in rendered:\n check_runtime_errors(cmd_derived_from_alias, pos_args_table)\n\n return rendered\n except Exception as exception:\n # Exception raised from runtime error\n if isinstance(exception, CLIError):\n raise\n\n # The template has some sort of compile time errors\n split_exception_message = str(exception).split()\n\n # Check if the error message provides the index of the erroneous character\n error_index = split_exception_message[-1]\n if error_index.isdigit():\n split_exception_message.insert(-1, 'index')\n error_msg = RENDER_TEMPLATE_ERROR.format(' '.join(split_exception_message), cmd_derived_from_alias)\n\n # Calculate where to put an arrow (^) char so that it is exactly below the erroneous character\n # e.g. ... \"{{a.split('|)}}\"\n # ^\n error_msg += '\\n{}^'.format(' ' * (len(error_msg) - len(cmd_derived_from_alias) + int(error_index) - 1))\n else:\n exception_str = str(exception).replace('\"{{', '}}').replace('}}\"', '}}')\n error_msg = RENDER_TEMPLATE_ERROR.format(cmd_derived_from_alias, exception_str)\n\n raise CLIError(error_msg)", "docstring": "Render cmd_derived_from_alias as a Jinja template with pos_args_table as the arguments.\n\nArgs:\n cmd_derived_from_alias: The string to be injected with positional arguemnts.\n pos_args_table: The dictionary used to rendered.\n\nReturns:\n A processed string with positional arguments injected.", "source": "juraj_google_style"} +{"code": "def _wait_and_kill(pid_to_wait, pids_to_kill):\n\n # cloud workers don't have psutil\n import psutil\n if psutil.pid_exists(pid_to_wait):\n psutil.Process(pid=pid_to_wait).wait()\n\n for pid_to_kill in pids_to_kill:\n if psutil.pid_exists(pid_to_kill):\n p = psutil.Process(pid=pid_to_kill)\n p.kill()\n p.wait()", "docstring": "Helper function.\n\n Wait for a process to finish if it exists, and then try to kill a list of\n processes.\n\n Used by local_train\n\nArgs:\n pid_to_wait: the process to wait for.\n pids_to_kill: a list of processes to kill after the process of pid_to_wait finishes.", "source": "juraj_google_style"} +{"code": "def Find(self, find_specs=None):\n\n if not find_specs:\n find_specs = [FindSpec()]\n\n registry_key = self._win_registry.GetRootKey()\n for matching_path in self._FindInKey(registry_key, find_specs, 0):\n yield matching_path", "docstring": "Searches for matching keys within the Windows Registry.\n\nArgs:\n find_specs (list[FindSpec]): find specifications. where None\n will return all allocated Windows Registry keys.\n\nYields:\n str: key path of a matching Windows Registry key.", "source": "juraj_google_style"} +{"code": "def write(self, data, echo=None):\n\n\n if echo or (echo is None and self.echo):\n sys.stdout.write(data.decode('latin1'))\n sys.stdout.flush()\n self.channel.write(data)", "docstring": "Write data to channel.\n\nArgs:\n data(bytes): The data to write to the channel.\n echo(bool): Whether to echo the written data to stdout.\n\nRaises:\n EOFError: If the channel was closed before all data was sent.", "source": "juraj_google_style"} +{"code": "def parse_results(self, data):\n\n results = []\n if len(data[\"Records\"]) < 1:\n return -1\n\n codes = data[\"Records\"][0][\"Results\"]\n for code in codes.split(\",\"):\n results.append(str(code))\n\n self.addr1 = data[\"Records\"][0][\"AddressLine1\"]\n self.addr2 = data[\"Records\"][0][\"AddressLine2\"]\n self.city = data[\"Records\"][0][\"City\"]\n self.name = data[\"Records\"][0][\"NameFull\"]\n self.phone = data[\"Records\"][0][\"PhoneNumber\"]\n self.province = data[\"Records\"][0][\"State\"]\n self.postal = data[\"Records\"][0][\"PostalCode\"]\n self.recordID = data[\"Records\"][0][\"RecordID\"]\n return results", "docstring": "parse_results\n\n Parses the MelissaData response.\n\nArgs:\n data (dict): Contains MelissaData response\n\nReturns:\n results, either contains a dict with corrected address info or -1 for an invalid address.", "source": "juraj_google_style"} +{"code": "def getText(page, output = \"text\"):\n\n CheckParent(page)\n dl = page.getDisplayList()\n # available output types\n formats = (\"text\", \"html\", \"json\", \"xml\", \"xhtml\", \"dict\", \"rawdict\")\n # choose which of them also include images in the TextPage\n images = (0, 1, 1, 0, 1, 1, 1) # controls image inclusion in text page\n try:\n f = formats.index(output.lower())\n except:\n f = 0\n flags = TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE\n if images[f] :\n flags |= TEXT_PRESERVE_IMAGES\n tp = dl.getTextPage(flags) # TextPage with / without images\n t = tp._extractText(f)\n del dl\n del tp\n return t", "docstring": "Extract a document page's text.\n\nArgs:\n output: (str) text, html, dict, json, rawdict, xhtml or xml.\n\nReturns:\n the output of TextPage methods extractText, extractHTML, extractDICT, extractJSON, extractRAWDICT, extractXHTML or etractXML respectively. Default and misspelling choice is \"text\".", "source": "juraj_google_style"} +{"code": "def playlist_song_delete(self, playlist_song):\n\n\n\t\tself.playlist_songs_delete([playlist_song])\n\n\t\treturn self.playlist(playlist_song['playlistId'], include_songs=True)", "docstring": "Delete song from playlist.\n\n Parameters:\n playlist_song (str): A playlist song dict.\n\nReturns:\n dict: Playlist dict including songs.", "source": "juraj_google_style"} +{"code": "def __init__(self, service_name, user_name):\n\n super(Storage, self).__init__(lock=threading.Lock())\n self._service_name = service_name\n self._user_name = user_name", "docstring": "Constructor.\n\nArgs:\n service_name: string, The name of the service under which the\n credentials are stored.\n user_name: string, The name of the user to store credentials for.", "source": "juraj_google_style"} +{"code": "def write_supercells_with_displacements(supercell, cells_with_disps, filename=\"geo.gen\"):\n\n\n # original cell\n write_dftbp(filename + \"S\", supercell)\n\n # displaced cells\n for ii in range(len(cells_with_disps)):\n write_dftbp(filename + \"S-{:03d}\".format(ii+1), cells_with_disps[ii])", "docstring": "Writes perfect supercell and supercells with displacements\n\nArgs:\n supercell: perfect supercell\n cells_with_disps: supercells with displaced atoms\n filename: root-filename", "source": "juraj_google_style"} +{"code": "def GetFeeds(client):\n\n feed_service = client.GetService('FeedService', 'v201809')\n\n feeds = []\n more_pages = True\n\n selector = {\n 'fields': ['Id', 'Name', 'Attributes'],\n 'predicates': [\n {\n 'field': 'Origin',\n 'operator': 'EQUALS',\n 'values': ['USER']\n },\n {\n 'field': 'FeedStatus',\n 'operator': 'EQUALS',\n 'values': ['ENABLED']\n }\n ],\n 'paging': {\n 'startIndex': 0,\n 'numberResults': PAGE_SIZE\n }\n }\n\n while more_pages:\n page = feed_service.get(selector)\n\n if 'entries' in page:\n feeds.extend(page['entries'])\n\n selector['paging']['startIndex'] += PAGE_SIZE\n more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries'])\n\n return feeds", "docstring": "Returns a list of all enabled Feeds.\n\nArgs:\n client: an AdWordsClient instance.\n\nReturns:\n A list containing all enabled Feeds.", "source": "juraj_google_style"} +{"code": "def remove_showcase(self, showcase):\n # type: (Union[hdx.data.showcase.Showcase,Dict,str]) -> None\n\n dataset_showcase = self._get_dataset_showcase_dict(showcase)\n showcase = hdx.data.showcase.Showcase({'id': dataset_showcase['showcase_id']}, configuration=self.configuration)\n showcase._write_to_hdx('disassociate', dataset_showcase, 'package_id')", "docstring": "Remove dataset from showcase\n\nArgs:\n showcase (Union[Showcase,Dict,str]): Either a showcase id string or showcase metadata from a Showcase object or dictionary\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def references_json(references):\n\n\n references_json = []\n for r in references:\n ref = r.ref\n ref['attributes'] = r._to_json_like(include_defaults=False)\n references_json.append(ref)\n\n return references_json", "docstring": "Given a list of all models in a graph, return JSON representing\n them and their properties.\n\nArgs:\n references (seq[Model]) :\n A list of models to convert to JSON\n\nReturns:\n list", "source": "juraj_google_style"} +{"code": "def visualizeFeaturesFolder(folder, dimReductionMethod, priorKnowledge = \"none\"):\n\n if dimReductionMethod==\"pca\":\n allMtFeatures, wavFilesList, _ = aF.dirWavFeatureExtraction(folder, 30.0, 30.0, 0.050, 0.050, compute_beat = True)\n if allMtFeatures.shape[0]==0:\n print(\"Error: No data found! Check input folder\")\n return\n\n namesCategoryToVisualize = [ntpath.basename(w).replace('.wav','').split(\" --- \")[0] for w in wavFilesList]; \n namesToVisualize = [ntpath.basename(w).replace('.wav','') for w in wavFilesList]; \n\n (F, MEAN, STD) = aT.normalizeFeatures([allMtFeatures])\n F = np.concatenate(F)\n\n # check that the new PCA dimension is at most equal to the number of samples\n K1 = 2\n K2 = 10\n if K1 > F.shape[0]:\n K1 = F.shape[0]\n if K2 > F.shape[0]:\n K2 = F.shape[0]\n pca1 = sklearn.decomposition.PCA(n_components = K1)\n pca1.fit(F) \n pca2 = sklearn.decomposition.PCA(n_components = K2)\n pca2.fit(F) \n\n finalDims = pca1.transform(F)\n finalDims2 = pca2.transform(F)\n else: \n allMtFeatures, Ys, wavFilesList = aF.dirWavFeatureExtractionNoAveraging(folder, 20.0, 5.0, 0.040, 0.040) # long-term statistics cannot be applied in this context (LDA needs mid-term features)\n if allMtFeatures.shape[0]==0:\n print(\"Error: No data found! Check input folder\")\n return\n\n namesCategoryToVisualize = [ntpath.basename(w).replace('.wav','').split(\" --- \")[0] for w in wavFilesList]; \n namesToVisualize = [ntpath.basename(w).replace('.wav','') for w in wavFilesList]; \n\n ldaLabels = Ys\n if priorKnowledge==\"artist\":\n uNamesCategoryToVisualize = list(set(namesCategoryToVisualize))\n YsNew = np.zeros( Ys.shape )\n for i, uname in enumerate(uNamesCategoryToVisualize): # for each unique artist name:\n indicesUCategories = [j for j, x in enumerate(namesCategoryToVisualize) if x == uname]\n for j in indicesUCategories:\n indices = np.nonzero(Ys==j)\n YsNew[indices] = i\n ldaLabels = YsNew\n\n (F, MEAN, STD) = aT.normalizeFeatures([allMtFeatures])\n F = np.array(F[0])\n\n clf = sklearn.discriminant_analysis.LinearDiscriminantAnalysis(n_components=10)\n clf.fit(F, ldaLabels) \n reducedDims = clf.transform(F)\n\n pca = sklearn.decomposition.PCA(n_components = 2)\n pca.fit(reducedDims)\n reducedDims = pca.transform(reducedDims)\n\n # TODO: CHECK THIS ... SHOULD LDA USED IN SEMI-SUPERVISED ONLY????\n\n uLabels = np.sort(np.unique((Ys))) # uLabels must have as many labels as the number of wavFilesList elements\n reducedDimsAvg = np.zeros( (uLabels.shape[0], reducedDims.shape[1] ) )\n finalDims = np.zeros( (uLabels.shape[0], 2) ) \n for i, u in enumerate(uLabels):\n indices = [j for j, x in enumerate(Ys) if x == u]\n f = reducedDims[indices, :]\n finalDims[i, :] = f.mean(axis=0)\n finalDims2 = reducedDims\n\n for i in range(finalDims.shape[0]): \n plt.text(finalDims[i,0], finalDims[i,1], ntpath.basename(wavFilesList[i].replace('.wav','')), horizontalalignment='center', verticalalignment='center', fontsize=10)\n plt.plot(finalDims[i,0], finalDims[i,1], '*r')\n plt.xlim([1.2*finalDims[:,0].min(), 1.2*finalDims[:,0].max()])\n plt.ylim([1.2*finalDims[:,1].min(), 1.2*finalDims[:,1].max()]) \n plt.show()\n\n SM = 1.0 - distance.squareform(distance.pdist(finalDims2, 'cosine'))\n for i in range(SM.shape[0]):\n SM[i,i] = 0.0;\n\n\n chordialDiagram(\"visualization\", SM, 0.50, namesToVisualize, namesCategoryToVisualize)\n\n SM = 1.0 - distance.squareform(distance.pdist(F, 'cosine'))\n for i in range(SM.shape[0]):\n SM[i,i] = 0.0;\n chordialDiagram(\"visualizationInitial\", SM, 0.50, namesToVisualize, namesCategoryToVisualize)\n\n # plot super-categories (i.e. artistname\n uNamesCategoryToVisualize = sort(list(set(namesCategoryToVisualize)))\n finalDimsGroup = np.zeros( (len(uNamesCategoryToVisualize), finalDims2.shape[1] ) )\n for i, uname in enumerate(uNamesCategoryToVisualize):\n indices = [j for j, x in enumerate(namesCategoryToVisualize) if x == uname]\n f = finalDims2[indices, :]\n finalDimsGroup[i, :] = f.mean(axis=0)\n\n SMgroup = 1.0 - distance.squareform(distance.pdist(finalDimsGroup, 'cosine'))\n for i in range(SMgroup.shape[0]):\n SMgroup[i,i] = 0.0;\n chordialDiagram(\"visualizationGroup\", SMgroup, 0.50, uNamesCategoryToVisualize, uNamesCategoryToVisualize)", "docstring": "This function generates a chordial visualization for the recordings of the provided path.\n\nArgs:\n - folder: path of the folder that contains the WAV files to be processed\n - dimReductionMethod: method used to reduce the dimension of the initial feature space before computing the similarity.\n - priorKnowledge: if this is set equal to \"artist\"", "source": "juraj_google_style"} +{"code": "def get_proposed_feature(project):\n\n change_collector = ChangeCollector(project)\n collected_changes = change_collector.collect_changes()\n try:\n new_feature_info = one_or_raise(collected_changes.new_feature_info)\n importer, _, _ = new_feature_info\n except ValueError:\n raise BalletError('Too many features collected')\n module = importer()\n feature = _get_contrib_feature_from_module(module)\n return feature", "docstring": "Get the proposed feature\n\n The path of the proposed feature is determined by diffing the project\n against a comparison branch, such as master. The feature is then imported\n from that path and returned.\n\nArgs:\n project (ballet.project.Project): project info\n\nRaises:\n ballet.exc.BalletError: more than one feature collected", "source": "juraj_google_style"} +{"code": "def from_sasl_name(cls, name=None):\n\n if rfc5801 is None:\n raise NotImplementedError(\"Your GSSAPI implementation does not \"\n \"have support for RFC 5801\")\n if isinstance(name, six.text_type):\n name = name.encode(_utils._get_encoding())\n\n m = rfc5801.inquire_mech_for_saslname(name)\n\n return cls(m)", "docstring": "Create a Mechanism from its SASL name\n\nArgs:\n name (str): SASL name of the desired mechanism\n\nReturns:\n Mechanism: the desired mechanism\n\nRaises:\n GSSError\n\n :requires-ext:`rfc5801`", "source": "juraj_google_style"} +{"code": "def _add_cadd_score(self, variant_obj, info_dict):\n\n cadd_score = info_dict.get('CADD')\n if cadd_score:\n logger.debug(\"Updating cadd_score to: {0}\".format(\n cadd_score))\n variant_obj.cadd_score = float(cadd_score)", "docstring": "Add the cadd score to the variant\n\nArgs:\n variant_obj (puzzle.models.Variant)\n info_dict (dict): A info dictionary", "source": "juraj_google_style"} +{"code": "def __init__(self, identifier):\n\n super(Volume, self).__init__()\n self.identifier = identifier\n self._attributes = {}\n self._extents = []\n self._is_parsed = False", "docstring": "Initializes a volume.\n\nArgs:\n identifier (str): identifier of the attribute within the volume.", "source": "juraj_google_style"} +{"code": "def load(filename):\n\n if not os.path.exists(filename):\n LOG.error(\"load object - File '%s' does not exist.\", filename)\n return None\n\n obj = None\n with open(filename, 'rb') as obj_file:\n obj = dill.load(obj_file)\n return obj", "docstring": "Load a pickled obj from the filesystem.\n\n You better know what you expect from the given pickle, because we don't check it.\n\nArgs:\n filename (str): The filename we load the object from.\n\nReturns:\n The object we were able to unpickle, else None.", "source": "juraj_google_style"} +{"code": "def random_name(num_surnames=2):\n\n a = []\n\n # Prefix\n if random.random() < _PROB_PREF:\n a.append(_prefixes[random.randint(0, len(_prefixes) - 1)])\n\n # Forename\n a.append(_forenames[random.randint(0, len(_forenames) - 1)])\n\n # Surnames\n for i in range(num_surnames):\n a.append(_surnames[random.randint(0, len(_surnames) - 1)])\n\n # Suffix\n if random.random() < _PROB_SUFF:\n a.append(_suffixes[random.randint(0, len(_suffixes) - 1)])\n\n return \" \".join(a)", "docstring": "Returns a random person name\n\nArgs:\n num_surnames -- number of surnames", "source": "juraj_google_style"} +{"code": "def _parse_email(self, val):\n\n\n ret = {\n 'type': None,\n 'value': None\n }\n\n try:\n\n ret['type'] = val[1]['type']\n\n except (KeyError, ValueError, TypeError):\n\n pass\n\n ret['value'] = val[3].strip()\n\n try:\n\n self.vars['email'].append(ret)\n\n except AttributeError:\n\n self.vars['email'] = []\n self.vars['email'].append(ret)", "docstring": "The function for parsing the vcard email addresses.\n\nArgs:\n val (:obj:`list`): The value to parse.", "source": "juraj_google_style"} +{"code": "def remove_padding(sequence):\n\n length = sequence.pop('length')\n sequence = tools.nested.map(lambda tensor: tensor[:length], sequence)\n return sequence", "docstring": "Selects the used frames of a sequence, up to its length.\n\n This function does not expect a batch of sequences, but a single sequence.\n The sequence must be a dict with `length` key, which will removed from the\n result.\n\nArgs:\n sequence: Nested dict of tensors with time dimension.\n\nReturns:\n Nested dict of tensors with padding elements and `length` key removed.", "source": "juraj_google_style"} +{"code": "def _get_mpr_view(self, connection, table):\n\n logger.debug(\n 'Looking for view of the table.\\n table: {}'.format(table.vid))\n view = self.get_view_name(table)\n view_exists = self._relation_exists(connection, view)\n if view_exists:\n logger.debug(\n 'View of the table exists.\\n table: {}, view: {}'\n .format(table.vid, view))\n return view\n raise MissingViewError('sqlite database does not have view for {} table.'\n .format(table.vid))", "docstring": "Finds and returns view name in the sqlite db represented by given connection.\n\nArgs:\n connection: connection to sqlite db where to look for partition table.\n table (orm.Table):\n\nRaises:\n MissingViewError: if database does not have partition table.\n\nReturns:\n str: database table storing partition data.", "source": "juraj_google_style"} +{"code": "def tags(self, where, archiver=\"\", timeout=DEFAULT_TIMEOUT):\n\n return self.query(\"select * where {0}\".format(where), archiver, timeout).get('metadata',{})", "docstring": "Retrieves tags for all streams matching the given WHERE clause\n\nArgs:\n [where]: the where clause (e.g. 'path like \"keti\"', 'SourceName = \"TED Main\"')\n [archiver]: if specified, this is the archiver to use. Else, it will run on the first archiver passed\n into the constructor for the client\n [timeout]: time in seconds to wait for a response from the archiver", "source": "juraj_google_style"} +{"code": "def is_glacier(s3_client, bucket, prefix):\n\n response = s3_client.list_objects_v2(Bucket=bucket,\n Prefix=prefix,\n MaxKeys=3) # 3 to not fetch _SUCCESS\n\n for key in response['Contents']:\n if key.get('StorageClass', 'STANDARD') == 'GLACIER':\n return True\n return False", "docstring": "Check if prefix is archived in Glacier, by checking storage class of\n first object inside that prefix\n\nArgs:\n s3_client - boto3 S3 client (not service)\n bucket - valid extracted bucket (without protocol and prefix)\n example: sowplow-events-data\n prefix - valid S3 prefix (usually, run_id)\n example: snowplow-archive/enriched/archive/", "source": "juraj_google_style"} +{"code": "def stop(self, wait=True):\n\n assert not self._stopped, \"Already stopped\"\n self._stopped = True\n self._tornado.stop(wait)\n self._http.stop()", "docstring": "Stop the Bokeh Server.\n\n This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well\n as stops the ``HTTPServer`` that this instance was configured with.\n\nArgs:\n fast (bool):\n Whether to wait for orderly cleanup (default: True)\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def Deserialize(self, reader):\n\n self.Script = reader.ReadVarBytes()\n self.ParameterList = reader.ReadVarBytes()\n self.ReturnType = reader.ReadByte()", "docstring": "Deserialize full object.\n\nArgs:\n reader (neo.IO.BinaryReader):", "source": "juraj_google_style"} +{"code": "def setLCD(self, password=\"00000000\"):\n\n result = False\n self.setContext(\"setLCD\")\n try:\n self.clearCmdMsg()\n\n if len(password) != 8:\n self.writeCmdMsg(\"Invalid password length.\")\n self.setContext(\"\")\n return result\n\n if not self.request():\n self.writeCmdMsg(\"Bad read CRC on setting\")\n else:\n if not self.serialCmdPwdAuth(password):\n self.writeCmdMsg(\"Password failure\")\n else:\n req_table = \"\"\n\n fill_len = 40 - len(self.m_lcd_items)\n\n for lcdid in self.m_lcd_items:\n append_val = binascii.hexlify(str(lcdid).zfill(2))\n req_table += append_val\n\n for i in range(0, fill_len):\n append_val = binascii.hexlify(str(0).zfill(2))\n req_table += append_val\n\n req_str = \"015731023030443228\" + req_table + \"2903\"\n req_str += self.calc_crc16(req_str[2:].decode(\"hex\"))\n self.m_serial_port.write(req_str.decode(\"hex\"))\n if self.m_serial_port.getResponse(self.getContext()).encode(\"hex\") == \"06\":\n self.writeCmdMsg(\"Success: 06 returned.\")\n result = True\n self.serialPostEnd()\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n\n self.setContext(\"\")\n return result", "docstring": "Serial call to set LCD using meter object bufer.\n\n Used with :func:`~ekmmeters.V4Meter.addLcdItem`.\n\nArgs:\n password (str): Optional password\n\nReturns:\n bool: True on completion and ACK.", "source": "juraj_google_style"} +{"code": "def normalize(input_tensor, output_tensor):\n\n image_dims = utils.get_img_shape(input_tensor)[1:]\n return output_tensor / np.prod(image_dims)", "docstring": "Normalizes the `output_tensor` with respect to `input_tensor` dimensions.\n This makes regularizer weight factor more or less uniform across various input image dimensions.\n\nArgs:\n input_tensor: An tensor of shape: `(samples, channels, image_dims...)` if `image_data_format=\n channels_first` or `(samples, image_dims..., channels)` if `image_data_format=channels_last`.\n output_tensor: The tensor to normalize.\n\nReturns:\n The normalized tensor.", "source": "juraj_google_style"} +{"code": "def get_users_by_email(cls, emails):\n\n users = User.objects.filter(email__in=emails)\n present_emails = users.values_list('email', flat=True)\n missing_emails = list(set(emails) - set(present_emails))\n return users, missing_emails", "docstring": "Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't.\n\nArgs:\n emails: An iterable of email addresses to split between existing and nonexisting\n\nReturns:\n users: Queryset of users who exist in the OpenEdX platform and who were in the list of email addresses\n missing_emails: List of unique emails which were in the original list, but do not yet exist as users", "source": "juraj_google_style"} +{"code": "def GetParserObjects(cls, parser_filter_expression=None):\n\n includes, excludes = cls._GetParserFilters(parser_filter_expression)\n\n parser_objects = {}\n for parser_name, parser_class in iter(cls._parser_classes.items()):\n # If there are no includes all parsers are included by default.\n if not includes and parser_name in excludes:\n continue\n\n if includes and parser_name not in includes:\n continue\n\n parser_object = parser_class()\n if parser_class.SupportsPlugins():\n plugin_includes = None\n if parser_name in includes:\n plugin_includes = includes[parser_name]\n\n parser_object.EnablePlugins(plugin_includes)\n\n parser_objects[parser_name] = parser_object\n\n return parser_objects", "docstring": "Retrieves the parser objects.\n\nArgs:\n parser_filter_expression (Optional[str]): parser filter expression,\n where None represents all parsers and plugins.\n\nReturns:\n dict[str, BaseParser]: parsers per name.", "source": "juraj_google_style"} +{"code": "def check_partition_column(partition_column, cols):\n\n for k, v in cols.items():\n if k == partition_column:\n if v == \"int\":\n return\n else:\n raise InvalidPartitionColumn(\n \"partition_column must be int, and not {0}\".format(v)\n )\n raise InvalidPartitionColumn(\n \"partition_column {0} not found in the query\".format(partition_column)\n )", "docstring": "Check partition_column existence and type\n\nArgs:\n partition_column: partition_column name\n cols: dict with columns names and python types\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def integer_key_convert(dictin, dropfailedkeys=False):\n # type: (DictUpperBound, bool) -> Dict\n\n return key_value_convert(dictin, keyfn=int, dropfailedkeys=dropfailedkeys)", "docstring": "Convert keys of dictionary to integers\n\nArgs:\n dictin (DictUpperBound): Input dictionary\n dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False.\n\nReturns:\n Dict: Dictionary with keys converted to integers", "source": "juraj_google_style"} +{"code": "def normalize_collaboration(collaboration):\n\n if not collaboration:\n return []\n\n collaboration = collaboration.strip()\n if collaboration.startswith('(') and collaboration.endswith(')'):\n collaboration = collaboration[1:-1]\n\n collaborations = _RE_AND.split(collaboration)\n collaborations = (_RE_COLLABORATION_LEADING.sub('', collab)\n for collab in collaborations)\n collaborations = (_RE_COLLABORATION_TRAILING.sub('', collab)\n for collab in collaborations)\n\n return [collab.strip() for collab in collaborations]", "docstring": "Normalize collaboration string.\n\nArgs:\n collaboration: a string containing collaboration(s) or None\n\nReturns:\n list: List of extracted and normalized collaborations\n\nExample:\n >>> from inspire_schemas.utils import normalize_collaboration\n >>> normalize_collaboration('for the CMS and ATLAS Collaborations')\n ['CMS', 'ATLAS']", "source": "juraj_google_style"} +{"code": "def get_existing_path(path, topmost_path=None):\n\n prev_path = None\n\n if topmost_path:\n topmost_path = os.path.normpath(topmost_path)\n\n while True:\n if os.path.exists(path):\n return path\n\n path = os.path.dirname(path)\n if path == prev_path:\n return None\n\n if topmost_path and os.path.normpath(path) == topmost_path:\n return None\n\n prev_path = path", "docstring": "Get the longest parent path in `path` that exists.\n\n If `path` exists, it is returned.\n\nArgs:\n path (str): Path to test\n topmost_path (str): Do not test this path or above\n\nReturns:\n str: Existing path, or None if no path was found.", "source": "juraj_google_style"} +{"code": "def toregex(text, exact=False):\n\n\n if isregex(text):\n return text\n\n escaped = re.escape(normalize_text(text))\n if exact:\n escaped = r\"\\A{}\\Z\".format(escaped)\n\n return re.compile(escaped)", "docstring": "Returns a compiled regular expression for the given text.\n\nArgs:\n text (str | RegexObject): The text to match.\n exact (bool, optional): Whether the generated regular expression should match exact\n strings. Defaults to False.\n\nReturns:\n RegexObject: A compiled regular expression that will match the text.", "source": "juraj_google_style"} +{"code": "def task_view_generator(job_descriptor):\n\n for task_descriptor in job_descriptor.task_descriptors:\n jd = JobDescriptor(job_descriptor.job_metadata, job_descriptor.job_params,\n job_descriptor.job_resources, [task_descriptor])\n yield jd", "docstring": "Generator that yields a task-specific view of the job.\n\n This generator exists to make it easy for callers to iterate over the tasks\n in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.\n\nArgs:\n job_descriptor: A JobDescriptor with 1 or more tasks.\n\nYields:\n A JobDescriptor with a single task.", "source": "juraj_google_style"} +{"code": "def most_uncertain_by_mask(self, mask, y):\n\n idxs = np.where(mask)[0]\n # the most uncertain samples will have abs(probs-1/num_classes) close to 0;\n return idxs[np.argsort(np.abs(self.probs[idxs,y]-(1/self.num_classes)))[:4]]", "docstring": "Extracts the first 4 most uncertain indexes from the ordered list of probabilities\n\nArgs:\n mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else\n y (int): the selected class\n\nReturns:\n idxs (ndarray): An array of indexes of length 4", "source": "juraj_google_style"} +{"code": "def cross_section(verts, tris, plane_orig, plane_normal, **kwargs):\n\n mesh = TriangleMesh(verts, tris)\n plane = Plane(plane_orig, plane_normal)\n return cross_section_mesh(mesh, plane, **kwargs)", "docstring": "Compute the planar cross section of a mesh. This returns a set of\n polylines.\n\nArgs:\n verts: Nx3 array of the vertices position\n faces: Nx3 array of the faces, containing vertex indices\n plane_orig: 3-vector indicating the plane origin\n plane_normal: 3-vector indicating the plane normal\n\nReturns:\n A list of Nx3 arrays, each representing a disconnected portion\n of the cross section as a polyline", "source": "juraj_google_style"} +{"code": "def boundary_words(seq):\n\n in_word = None\n for char in seq:\n if char == '\\x00' and in_word is not None:\n in_word = not in_word\n elif char in WHITESPACE_CHARS:\n if in_word is not None and in_word:\n yield '\\x00'\n in_word = False\n else:\n if in_word is not None and not in_word:\n yield '\\x00'\n in_word = True\n yield char", "docstring": "Wraps all word transitions with a boundary token character (\\x00).\n\nArgs:\n - `seq`:", "source": "juraj_google_style"} +{"code": "def get_instances(serials):\n\n objs = []\n for s in serials:\n objs.append(Monsoon(serial=s))\n return objs", "docstring": "Create Monsoon instances from a list of serials.\n\nArgs:\n serials: A list of Monsoon (integer) serials.\n\nReturns:\n A list of Monsoon objects.", "source": "juraj_google_style"} +{"code": "def update_panel(self, panel_obj, version=None, date_obj=None):\n\n LOG.info(\"Updating panel %s\", panel_obj['panel_name'])\n # update date of panel to \"today\"\n date = panel_obj['date']\n if version:\n LOG.info(\"Updating version from {0} to version {1}\".format(\n panel_obj['version'], version))\n panel_obj['version'] = version\n # Updating version should not update date\n if date_obj:\n date = date_obj\n else:\n date = date_obj or dt.datetime.now()\n panel_obj['date'] = date\n\n updated_panel = self.panel_collection.find_one_and_replace(\n {'_id': panel_obj['_id']},\n panel_obj,\n return_document=pymongo.ReturnDocument.AFTER\n )\n\n return updated_panel", "docstring": "Replace a existing gene panel with a new one\n\n Keeps the object id\n\nArgs:\n panel_obj(dict)\n version(float)\n date_obj(datetime.datetime)\n\nReturns:\n updated_panel(dict)", "source": "juraj_google_style"} +{"code": "def uncheck(self, locator=None, allow_label_click=None, **kwargs):\n\n\n self._check_with_label(\n \"checkbox\", False, locator=locator, allow_label_click=allow_label_click, **kwargs)", "docstring": "Find a check box and uncheck it. The check box can be found via name, id, or label text. ::\n\n page.uncheck(\"German\")\n\nArgs:\n locator (str, optional): Which check box to uncheck.\n allow_label_click (bool, optional): Attempt to click the label to toggle state if\n element is non-visible. Defaults to :data:`capybara.automatic_label_click`.\n **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.", "source": "juraj_google_style"} +{"code": "def _parse_flags(element):\n\n visible = True if element.get('visible') else False\n user = element.get('user')\n timestamp = element.get('timestamp')\n if timestamp:\n timestamp = utils.Timestamp.parse_isoformat(timestamp)\n tags = {}\n try:\n for tag in element['tag']:\n key = tag.get('k')\n value = tag.get('v')\n tags[key] = value\n except AttributeError:\n pass\n\n return visible, user, timestamp, tags", "docstring": "Parse OSM XML element for generic data.\n\nArgs:\n element (etree.Element): Element to parse\n\nReturns:\n tuple: Generic OSM data for object instantiation", "source": "juraj_google_style"} +{"code": "def convertFsDirWavToWav(dirName, Fs, nC):\n\n\n types = (dirName+os.sep+'*.wav',) # the tuple of file types\n filesToProcess = []\n\n for files in types:\n filesToProcess.extend(glob.glob(files)) \n\n newDir = dirName + os.sep + \"Fs\" + str(Fs) + \"_\" + \"NC\"+str(nC)\n if os.path.exists(newDir) and newDir!=\".\":\n shutil.rmtree(newDir) \n os.makedirs(newDir) \n\n for f in filesToProcess: \n _, wavFileName = ntpath.split(f) \n command = \"avconv -i \\\"\" + f + \"\\\" -ar \" +str(Fs) + \" -ac \" + str(nC) + \" \\\"\" + newDir + os.sep + wavFileName + \"\\\"\";\n print(command)\n os.system(command)", "docstring": "This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels.\n\nArgs:\n - dirName: the path of the folder where the WAVs are stored\n - Fs: the sampling rate of the generated WAV files\n - nC: the number of channesl of the generated WAV files", "source": "juraj_google_style"} +{"code": "def pipeline_status(url, pipeline_id, auth, verify_ssl):\n\n status_result = requests.get(url + '/' + pipeline_id + '/status', headers=X_REQ_BY, auth=auth, verify=verify_ssl)\n status_result.raise_for_status()\n logging.debug('Status request: ' + url + '/status')\n logging.debug(status_result.json())\n return status_result.json()", "docstring": "Retrieve the current status for a pipeline.\n\nArgs:\n url (str): the host url in the form 'http://host:port/'.\n pipeline_id (str): the ID of of the exported pipeline.\n auth (tuple): a tuple of username, and password.\n verify_ssl (bool): whether to verify ssl certificates\n\nReturns:\n dict: the response json", "source": "juraj_google_style"} +{"code": "def read_tree_nexus(nexus):\n\n if not isinstance(nexus, str):\n raise TypeError(\"nexus must be a str\")\n if nexus.lower().endswith('.gz'): # gzipped file\n f = gopen(expanduser(nexus))\n elif isfile(expanduser(nexus)): # plain-text file\n f = open(expanduser(nexus))\n else:\n f = nexus.splitlines()\n trees = dict()\n for line in f:\n if isinstance(line,bytes):\n l = line.decode().strip()\n else:\n l = line.strip()\n if l.lower().startswith('tree '):\n i = l.index('='); left = l[:i].strip(); right = l[i+1:].strip()\n name = ' '.join(left.split(' ')[1:])\n trees[name] = read_tree_newick(right)\n if hasattr(f,'close'):\n f.close()\n return trees", "docstring": "Read a tree from a Nexus string or file\n\nArgs:\n ``nexus`` (``str``): Either a Nexus string or the path to a Nexus file (plain-text or gzipped)\n\nReturns:\n ``dict`` of ``Tree``: A dictionary of the trees represented by ``nexus``, where keys are tree names (``str``) and values are ``Tree`` objects", "source": "juraj_google_style"} +{"code": "def _UpdateEtag(self, response):\n\n etag = response.headers.get('etag', self.etag)\n etag_updated = self.etag != etag\n self.etag = etag\n return etag_updated", "docstring": "Update the etag from an API response.\n\nArgs:\n response: HTTP response with a header field.\n\nReturns:\n bool, True if the etag in the response header updated.", "source": "juraj_google_style"} +{"code": "def load_and_print_resfile(filename, info_dict=None):\n\n\n # self.test_no = None\n # self.mass = 1.0 # mass of (active) material (in mg)\n # self.no_cycles = 0.0\n # self.charge_steps = None # not in use at the moment\n # self.discharge_steps = None # not in use at the moment\n # self.ir_steps = None # dict # not in use at the moment\n # self.ocv_steps = None # dict # not in use at the moment\n # self.nom_cap = 3579 # mAh/g (used for finding c-rates)\n # self.mass_given = False\n # self.c_mode = True\n # self.starts_with = \"discharge\"\n # self.material = \"noname\"\n # self.merged = False\n # self.file_errors = None # not in use at the moment\n # self.loaded_from = None # name of the .res file it is loaded from\n # (can be list if merged)\n # self.raw_data_files = []\n # self.raw_data_files_length = []\n # # self.parent_filename = None # name of the .res file it is loaded from\n # (basename) (can be list if merded)\n # # self.parent_filename = if listtype, for file in etc,,,\n # os.path.basename(self.loaded_from)\n # self.channel_index = None\n # self.channel_number = None\n # self.creator = None\n # self.item_ID = None\n # self.schedule_file_name = None\n # self.start_datetime = None\n # self.test_ID = None\n # self.name = None\n\n # NEXT: include nom_cap, tot_mass and parameters table in save/load hdf5\n if info_dict is None:\n info_dict = dict()\n info_dict[\"mass\"] = 1.23 # mg\n info_dict[\"nom_cap\"] = 3600 # mAh/g (active material)\n info_dict[\"tot_mass\"] = 2.33 # mAh/g (total mass of material)\n\n d = CellpyData()\n\n print(\"filename:\", filename)\n print(\"info_dict in:\", end=' ')\n print(info_dict)\n\n d.from_raw(filename)\n d.set_mass(info_dict[\"mass\"])\n d.make_step_table()\n d.make_summary()\n\n for test in d.datasets:\n print(\"newtest\")\n print(test)\n\n return info_dict", "docstring": "Load a raw data file and print information.\n\nArgs:\n filename (str): name of the resfile.\n info_dict (dict):\n\nReturns:\n info (str): string describing something.", "source": "juraj_google_style"} +{"code": "def distance(self, other):\n\n return distance(self.lat, self.lon, None, other.lat, other.lon, None)", "docstring": "Distance between points\n\nArgs:\n other (:obj:`Point`)\n\nReturns:\n float: Distance in km", "source": "juraj_google_style"} +{"code": "def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n\n tstream = BytearrayStream()\n\n self.hashing_algorithm.write(tstream, kmip_version=kmip_version)\n self.digest_value.write(tstream, kmip_version=kmip_version)\n self.key_format_type.write(tstream, kmip_version=kmip_version)\n\n self.length = tstream.length()\n super(Digest, self).write(ostream, kmip_version=kmip_version)\n ostream.write(tstream.buffer)", "docstring": "Write the data encoding the Digest object to a stream.\n\nArgs:\n ostream (Stream): A data stream in which to encode object data,\n supporting a write method; usually a BytearrayStream object.\n kmip_version (KMIPVersion): An enumeration defining the KMIP\n version with which the object will be encoded. Optional,\n defaults to KMIP 1.0.", "source": "juraj_google_style"} +{"code": "def __init__(self, duration: int = None, name: str = None):\n\n if isinstance(duration, int):\n self._duration = duration\n else:\n raise PulseError('Pulse duration should be integer.')\n\n if name:\n self._name = name\n else:\n self._name = 'p%d' % Command.pulseIndex\n Command.pulseIndex += 1", "docstring": "Create a new command.\n\nArgs:\n duration (int): Duration of this command.\n name (str): Name of this command.\n\nRaises:\n PulseError: when duration is not number of points.", "source": "juraj_google_style"} +{"code": "def _parse_ISBN_EAN(details):\n\n isbn_ean = _get_td_or_none(\n details,\n \"ctl00_ContentPlaceHolder1_tblRowIsbnEan\"\n )\n\n if not isbn_ean:\n return None, None\n\n ean = None\n isbn = None\n if \"/\" in isbn_ean: # ISBN and EAN are stored in same string\n isbn, ean = isbn_ean.split(\"/\")\n isbn = isbn.strip()\n ean = ean.strip()\n else:\n isbn = isbn_ean.strip()\n\n if not isbn:\n isbn = None\n\n return isbn, ean", "docstring": "Parse ISBN and EAN.\n\nArgs:\n details (obj): HTMLElement containing slice of the page with details.\n\nReturns:\n (ISBN, EAN): Tuple with two string or two None.", "source": "juraj_google_style"} +{"code": "def numberify_data(self, source, start=1):\n\n if type(source) is str:\n try:\n fd = open(source, 'r+')\n data = fd.readlines()\n for index, item in enumerate(data):\n data[index] = item.strip('\\n')\n fd.close()\n except IOError as e:\n print 'I/O error({0}): {1}'.format(e.errno, e.strerror)\n return False\n elif type(source) is list:\n data = source\n else:\n print 'Data error. Pass a filename or a list'\n return False\n return dict(list(enumerate(data, start)))", "docstring": "Return a dictionary with numberified data\n\nArgs:\n source -- source of data(filename or a list)\n start -- starting index of numbering", "source": "juraj_google_style"} +{"code": "def get_log_file_name(level=INFO):\n\n if level not in converter.ABSL_LEVELS:\n raise ValueError('Invalid absl.logging level {}'.format(level))\n stream = get_absl_handler().python_handler.stream\n if (stream == sys.stderr or stream == sys.stdout or\n not hasattr(stream, 'name')):\n return ''\n else:\n return stream.name", "docstring": "Returns the name of the log file.\n\n For Python logging, only one file is used and level is ignored. And it returns\n empty string if it logs to stderr/stdout or the log stream has no `name`\n attribute.\n\nArgs:\n level: int, the absl.logging level.\n\nRaises:\n ValueError: Raised when `level` has an invalid value.", "source": "juraj_google_style"} +{"code": "def fit_predict(self, X, y, X_):\n\n\n self.fit(X, y)\n return self.predict(X_)", "docstring": "Shortcut to `model.fit(X, y); return model.predict(X_)`.\n\n Parameters:\n -----------\n X : matrix, shape (n_samples, n_features)\n The samples, the train data.\n\n y : vector, shape (n_samples,)\n The target labels.\n\n X_ : matrix, shape (m_samples, m_features)\n The samples which labels to predict.\n\nReturns:\n --------\n y : vector, shape (m_samples,)\n The predicted labels.", "source": "juraj_google_style"} +{"code": "def parse_json_path(self, jsonpath):\n\n\n if jsonpath not in self.parsed:\n try:\n self.parsed[jsonpath] = self.parser(jsonpath)\n except Exception:\n self.log(\"Invalid Json Path: \" + jsonpath, \"error\")\n raise InvalidJsonPathError(\"Invalid Json Path\")\n\n return self.parsed[jsonpath]", "docstring": "Parse a jsonpath\n\nArgs:\n jsonpath: str\n\n Returns: a parsed json path", "source": "juraj_google_style"} +{"code": "def match(subject: Expression, pattern: Pattern) -> Iterator[Substitution]:\n r\n if not is_constant(subject):\n raise ValueError(\"The subject for matching must be constant.\")\n global_constraints = [c for c in pattern.constraints if not c.variables]\n local_constraints = set(c for c in pattern.constraints if c.variables)\n for subst in _match([subject], pattern.expression, Substitution(), local_constraints):\n for constraint in global_constraints:\n if not constraint(subst):\n break\n else:\n yield subst", "docstring": "r\"\"\"Tries to match the given *pattern* to the given *subject*.\n\n Yields each match in form of a substitution.\n\n Parameters:\n subject:\n An subject to match.\n pattern:\n The pattern to match.\n\nYields:\n All possible match substitutions.\n\nRaises:\n ValueError:\n If the subject is not constant.", "source": "juraj_google_style"} +{"code": "def _parse_udf_vol_descs(self, extent, length, descs):\n # type: (int, int, PyCdlib._UDFDescriptors) -> None\n\n # Read in the Volume Descriptor Sequence\n self._seek_to_extent(extent)\n vd_data = self._cdfp.read(length)\n\n # And parse it. Since the sequence doesn't have to be in any set order,\n # and since some of the entries may be missing, we parse the Descriptor\n # Tag (the first 16 bytes) to find out what kind of descriptor it is,\n # then construct the correct type based on that. We keep going until we\n # see a Terminating Descriptor.\n\n block_size = self.pvd.logical_block_size()\n offset = 0\n current_extent = extent\n done = False\n while not done:\n desc_tag = udfmod.UDFTag()\n desc_tag.parse(vd_data[offset:], current_extent)\n if desc_tag.tag_ident == 1:\n descs.pvd.parse(vd_data[offset:offset + 512], current_extent, desc_tag)\n elif desc_tag.tag_ident == 4:\n descs.impl_use.parse(vd_data[offset:offset + 512], current_extent, desc_tag)\n elif desc_tag.tag_ident == 5:\n descs.partition.parse(vd_data[offset:offset + 512], current_extent, desc_tag)\n elif desc_tag.tag_ident == 6:\n descs.logical_volume.parse(vd_data[offset:offset + 512], current_extent, desc_tag)\n elif desc_tag.tag_ident == 7:\n descs.unallocated_space.parse(vd_data[offset:offset + 512], current_extent, desc_tag)\n elif desc_tag.tag_ident == 8:\n descs.terminator.parse(current_extent, desc_tag)\n done = True\n else:\n raise pycdlibexception.PyCdlibInvalidISO('UDF Tag identifier not %d' % (desc_tag.tag_ident))\n\n offset += block_size\n current_extent += 1", "docstring": "An internal method to parse a set of UDF Volume Descriptors.\n\n Parameters:\n extent - The extent at which to start parsing.\n length - The number of bytes to read from the incoming ISO.\n descs - The _UDFDescriptors object to store parsed objects into.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def do_set_log_file(self, args):\n\n params = args.split()\n try:\n filename = params[0]\n logging.basicConfig(filename=filename)\n except IndexError:\n self.do_help('set_log_file')", "docstring": "Set the log file.\n\n Usage:\n set_log_file filename\n Parameters:\n filename: log file name to write to\n\n THIS CAN ONLY BE CALLED ONCE AND MUST BE CALLED\n BEFORE ANY LOGGING STARTS.", "source": "juraj_google_style"} +{"code": "def op_and(self, *elements):\n\n expression = self.add_operator(Operator(';'))\n for element in elements:\n expression.add_element(element)\n return expression", "docstring": "Update the ``Expression`` by joining the specified additional\n ``elements`` using an \"AND\" ``Operator``\n\nArgs:\n *elements (BaseExpression): The ``Expression`` and/or\n ``Constraint`` elements which the \"AND\" ``Operator`` applies\n to.\n\nReturns:\n Expression: ``self`` or related ``Expression``.", "source": "juraj_google_style"} +{"code": "def build_parameters(self, stack, provider_stack=None):\n\n resolved = _resolve_parameters(stack.parameter_values, stack.blueprint)\n required_parameters = list(stack.required_parameter_definitions)\n all_parameters = list(stack.all_parameter_definitions)\n parameters = _handle_missing_parameters(resolved, all_parameters,\n required_parameters,\n provider_stack)\n\n param_list = []\n\n for key, value in parameters:\n param_dict = {\"ParameterKey\": key}\n if value is UsePreviousParameterValue:\n param_dict[\"UsePreviousValue\"] = True\n else:\n param_dict[\"ParameterValue\"] = str(value)\n\n param_list.append(param_dict)\n\n return param_list", "docstring": "Builds the CloudFormation Parameters for our stack.\n\nArgs:\n stack (:class:`stacker.stack.Stack`): A stacker stack\n provider_stack (dict): An optional Stacker provider object\n\nReturns:\n dict: The parameters for the given stack", "source": "juraj_google_style"} +{"code": "def playlists_iter(self, *, start_token=None, page_size=250):\n\n\n\t\tstart_token = None\n\n\t\twhile True:\n\t\t\tresponse = self._call(\n\t\t\t\tmc_calls.PlaylistFeed,\n\t\t\t\tmax_results=page_size,\n\t\t\t\tstart_token=start_token\n\t\t\t)\n\t\t\titems = response.body.get('data', {}).get('items', [])\n\n\t\t\tif items:\n\t\t\t\tyield items\n\n\t\t\tstart_token = response.body.get('nextPageToken')\n\t\t\tif start_token is None:\n\t\t\t\tbreak", "docstring": "Get a paged iterator of library playlists.\n\n Parameters:\n start_token (str): The token of the page to return.\n Default: Not sent to get first page.\n page_size (int, Optional): The maximum number of results per returned page.\n Max allowed is ``49995``.\n Default: ``250``\n\nYields:\n list: Playlist dicts.", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.ListProfiles = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.ProfileService/ListProfiles\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.ListProfilesRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.ListProfilesResponse.FromString,\n )\n self.CreateProfile = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.ProfileService/CreateProfile\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.CreateProfileRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__pb2.Profile.FromString,\n )\n self.GetProfile = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.ProfileService/GetProfile\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.GetProfileRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__pb2.Profile.FromString,\n )\n self.UpdateProfile = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.ProfileService/UpdateProfile\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.UpdateProfileRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__pb2.Profile.FromString,\n )\n self.DeleteProfile = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.ProfileService/DeleteProfile\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.DeleteProfileRequest.SerializeToString,\n response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,\n )\n self.SearchProfiles = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.ProfileService/SearchProfiles\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.SearchProfilesRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.SearchProfilesResponse.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def label_count(self, label_list_ids=None):\n\n count = collections.defaultdict(int)\n\n for label_list in self.label_lists.values():\n if label_list_ids is None or label_list.idx in label_list_ids:\n for label_value, label_count in label_list.label_count().items():\n count[label_value] += label_count\n\n return count", "docstring": "Return a dictionary containing the number of times,\n every label-value in this utterance is occurring.\n\nArgs:\n label_list_ids (list): If not None, only labels from label-lists\n with an id contained in this list\n are considered.\n\nReturns:\n dict: A dictionary containing the number of occurrences\n with the label-value as key.", "source": "juraj_google_style"} +{"code": "def indexes(self, collection=None):\n\n\n indexes = []\n\n for collection_name in self.collections():\n if collection and collection != collection_name:\n continue\n for index_name in self.db[collection_name].index_information():\n if index_name != '_id_':\n indexes.append(index_name)\n return indexes", "docstring": "Return a list with the current indexes\n\n Skip the mandatory _id_ indexes\n\nArgs:\n collection(str)\n\nReturns:\n indexes(list)", "source": "juraj_google_style"} +{"code": "def ceil(cls, x: 'TensorFluent') -> 'TensorFluent':\n\n return cls._unary_op(x, tf.ceil, tf.float32)", "docstring": "Returns a TensorFluent for the ceil function.\n\nArgs:\n x: The input fluent.\n\nReturns:\n A TensorFluent wrapping the ceil function.", "source": "juraj_google_style"} +{"code": "def traverse_bfs(self):\n\n if not isinstance(include_self, bool):\n raise TypeError(\"include_self must be a bool\")\n q = deque(); dist = dict(); dist[self] = 0; q.append((self,0))\n while len(q) != 0:\n curr = q.popleft(); yield curr\n for c in curr[0].children:\n if c not in dist:\n if c.edge_length is None:\n el = 0\n else:\n el = c.edge_length\n dist[c] = dist[curr[0]] + el; q.append((c,dist[c]))\n if curr[0].parent is not None and curr[0].parent not in dist:\n if curr[0].edge_length is None:\n el = 0\n else:\n el = curr[0].edge_length\n dist[curr[0].parent] = dist[curr[0]] + el; q.append((curr[0].parent,dist[curr[0].parent]))", "docstring": "Perform a Breadth-First Search (BFS) starting at this ``Node`` object'. Yields (``Node``, distance) tuples\n\nArgs:\n ``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False``", "source": "juraj_google_style"} +{"code": "def update(self, rid, data, raise_on_error=True):\n\n return self.put(rid, data, raise_on_error)", "docstring": "Update the for the provided Id. Alias for put() method.\n\nArgs:\n rid (str): The record identifier.\n data (dict): The record data.\n raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.\n\nReturns:\n object : Python request response.", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.send = channel.stream_stream(\n '/predix.eventhub.Publisher/send',\n request_serializer=EventHub__pb2.PublishRequest.SerializeToString,\n response_deserializer=EventHub__pb2.PublishResponse.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def save_image(image_url, image_directory, image_name):\n\n image_type = get_image_type(image_url)\n if image_type is None:\n raise ImageErrorException(image_url)\n full_image_file_name = os.path.join(image_directory, image_name + '.' + image_type)\n\n # If the image is present on the local filesystem just copy it\n if os.path.exists(image_url):\n shutil.copy(image_url, full_image_file_name)\n return image_type\n\n try:\n # urllib.urlretrieve(image_url, full_image_file_name)\n with open(full_image_file_name, 'wb') as f:\n user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'\n request_headers = {'User-Agent': user_agent}\n requests_object = requests.get(image_url, headers=request_headers)\n try:\n content = requests_object.content\n # Check for empty response\n f.write(content)\n except AttributeError:\n raise ImageErrorException(image_url)\n except IOError:\n raise ImageErrorException(image_url)\n return image_type", "docstring": "Saves an online image from image_url to image_directory with the name image_name.\n Returns the extension of the image saved, which is determined dynamically.\n\nArgs:\n image_url (str): The url of the image.\n image_directory (str): The directory to save the image in.\n image_name (str): The file name to save the image as.\n\nRaises:\n ImageErrorException: Raised if unable to save the image at image_url", "source": "juraj_google_style"} +{"code": "def phenotypes_to_scored(self,phenotypes=None,overwrite=False):\n\n if not self.is_uniform(): raise ValueError(\"inconsistent phenotypes\")\n if phenotypes is None: \n phenotypes = self.phenotypes\n elif isinstance(phenotypes,str):\n phenotypes = [phenotypes]\n def _post(binary,phenotype_label,phenotypes,overwrite):\n d = binary.copy()\n if len(set(phenotypes)&set(list(binary.keys()))) > 0 and overwrite==False:\n raise ValueError(\"Error, phenotype already exists as a scored type\")\n for label in phenotypes: d[label] = 0\n if phenotype_label == phenotype_label and phenotype_label in phenotypes:\n d[phenotype_label] = 1\n return d\n output = self.copy()\n output['scored_calls'] = output.apply(lambda x: \n _post(x['scored_calls'],x['phenotype_label'],phenotypes,overwrite)\n ,1)\n return output", "docstring": "Add mutually exclusive phenotypes to the scored calls\n\nArgs:\n phenotypes (list): a list of phenotypes to add to scored calls. if none or not set, add them all\n overwrite (bool): if True allow the overwrite of a phenotype, if False, the phenotype must not exist in the scored calls\n\nReturns:\n CellDataFrame", "source": "juraj_google_style"} +{"code": "def _get_augmented_label_matrix(self, L, higher_order=False):\n\n # Create a helper data structure which maps cliques (as tuples of member\n # sources) --> {start_index, end_index, maximal_cliques}, where\n # the last value is a set of indices in this data structure\n self.c_data = {}\n for i in range(self.m):\n self.c_data[i] = {\n \"start_index\": i * self.k,\n \"end_index\": (i + 1) * self.k,\n \"max_cliques\": set(\n [\n j\n for j in self.c_tree.nodes()\n if i in self.c_tree.node[j][\"members\"]\n ]\n ),\n }\n\n L_ind = self._create_L_ind(L)\n\n # Get the higher-order clique statistics based on the clique tree\n # First, iterate over the maximal cliques (nodes of c_tree) and\n # separator sets (edges of c_tree)\n if higher_order:\n L_aug = np.copy(L_ind)\n for item in chain(self.c_tree.nodes(), self.c_tree.edges()):\n if isinstance(item, int):\n C = self.c_tree.node[item]\n C_type = \"node\"\n elif isinstance(item, tuple):\n C = self.c_tree[item[0]][item[1]]\n C_type = \"edge\"\n else:\n raise ValueError(item)\n members = list(C[\"members\"])\n nc = len(members)\n\n # If a unary maximal clique, just store its existing index\n if nc == 1:\n C[\"start_index\"] = members[0] * self.k\n C[\"end_index\"] = (members[0] + 1) * self.k\n\n # Else add one column for each possible value\n else:\n L_C = np.ones((self.n, self.k ** nc))\n for i, vals in enumerate(product(range(self.k), repeat=nc)):\n for j, v in enumerate(vals):\n L_C[:, i] *= L_ind[:, members[j] * self.k + v]\n\n # Add to L_aug and store the indices\n if L_aug is not None:\n C[\"start_index\"] = L_aug.shape[1]\n C[\"end_index\"] = L_aug.shape[1] + L_C.shape[1]\n L_aug = np.hstack([L_aug, L_C])\n else:\n C[\"start_index\"] = 0\n C[\"end_index\"] = L_C.shape[1]\n L_aug = L_C\n\n # Add to self.c_data as well\n id = tuple(members) if len(members) > 1 else members[0]\n self.c_data[id] = {\n \"start_index\": C[\"start_index\"],\n \"end_index\": C[\"end_index\"],\n \"max_cliques\": set([item]) if C_type == \"node\" else set(item),\n }\n return L_aug\n else:\n return L_ind", "docstring": "Returns an augmented version of L where each column is an indicator\n for whether a certain source or clique of sources voted in a certain\n pattern.\n\nArgs:\n L: An [n,m] scipy.sparse label matrix with values in {0,1,...,k}", "source": "juraj_google_style"} +{"code": "def get_rows_fieldnames_from_raw_sql(\n session: Union[Session, Engine, Connection],\n sql: str) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:\n\n result = session.execute(sql) # type: ResultProxy\n fieldnames = result.keys()\n rows = result.fetchall()\n return rows, fieldnames", "docstring": "Returns results and column names from a query.\n\nArgs:\n session: SQLAlchemy :class:`Session`, :class:`Engine`, or\n :class:`Connection` object\n sql: raw SQL to execure\n\nReturns:\n ``(rows, fieldnames)`` where ``rows`` is the usual set of results and\n ``fieldnames`` are the name of the result columns/fields.", "source": "juraj_google_style"} +{"code": "def StartFlowAndWait(client_id,\n token=None,\n timeout=DEFAULT_TIMEOUT,\n **flow_args):\n\n flow_urn = flow.StartAFF4Flow(\n client_id=client_id, token=token, sync=True, **flow_args)\n\n WaitForFlow(flow_urn, token=token, timeout=timeout)\n\n return flow_urn", "docstring": "Runs a flow and waits for it to finish.\n\nArgs:\n client_id: The client id of the client to run on.\n token: The datastore access token.\n timeout: How long to wait for a flow to complete, maximum.\n **flow_args: Pass through to flow.\n\nReturns:\n The urn of the flow that was run.", "source": "juraj_google_style"} +{"code": "def __init__(self,\n kernel_fn,\n verbose=False,\n random_state=None):\n\n self.kernel_fn = kernel_fn\n self.verbose = verbose\n self.random_state = check_random_state(random_state)", "docstring": "Init function\n\nArgs:\n kernel_fn: function that transforms an array of distances into an\n array of proximity values (floats).\n verbose: if true, print local prediction values from linear model.\n random_state: an integer or numpy.RandomState that will be used to\n generate random numbers. If None, the random state will be\n initialized using the internal numpy seed.", "source": "juraj_google_style"} +{"code": "def remove_words(self, words):\n\n for word in words:\n self._dictionary.pop(word.lower())\n self._update_dictionary()", "docstring": "Remove a list of words from the word frequency list\n\nArgs:\n words (list): The list of words to remove", "source": "juraj_google_style"} +{"code": "def view(filepath):\n\n try:\n view_func = getattr(view, PLATFORM)\n except AttributeError:\n raise RuntimeError('platform %r not supported' % PLATFORM)\n view_func(filepath)", "docstring": "Open filepath with its default viewing application (platform-specific).\n\nArgs:\n filepath: Path to the file to open in viewer.\n\nRaises:\n RuntimeError: If the current platform is not supported.", "source": "juraj_google_style"} +{"code": "def _send_trace(self, chunk=None):\n\n\n self._trace_sm_running = True\n # If we failed to transmit a chunk, we will be requeued with an argument\n if chunk is None:\n chunk = self._next_tracing_chunk(20)\n\n if chunk is None or len(chunk) == 0:\n self._trace_sm_running = False\n return\n\n try:\n self._send_notification(TracingChar.value_handle, chunk)\n self._defer(self._send_trace)\n except bable_interface.BaBLEException as err:\n if err.packet.status == 'Rejected': # If we are streaming too fast, back off and try again\n time.sleep(0.05)\n self._defer(self._send_trace, [chunk])\n else:\n self._audit('ErrorStreamingTrace') # If there was an error, stop streaming but don't choke\n self._logger.exception(\"Error while tracing data\")", "docstring": "Stream tracing data to the ble client in 20 byte chunks\n\nArgs:\n chunk (bytearray): A chunk that should be sent instead of requesting a\n new chunk from the pending reports.", "source": "juraj_google_style"} +{"code": "def murmur3_64(data: Union[bytes, bytearray], seed: int = 19820125) -> int:\n # noqa\n m = 0xc6a4a7935bd1e995\n r = 47\n\n mask = 2 ** 64 - 1\n\n length = len(data)\n\n h = seed ^ ((m * length) & mask)\n\n offset = (length // 8) * 8\n # RNC: was /, but for Python 3 that gives float; brackets added for clarity\n for ll in range(0, offset, 8):\n k = bytes_to_long(data[ll:ll + 8])\n k = (k * m) & mask\n k ^= (k >> r) & mask\n k = (k * m) & mask\n h = (h ^ k)\n h = (h * m) & mask\n\n l = length & 7\n\n if l >= 7:\n h = (h ^ (data[offset + 6] << 48))\n\n if l >= 6:\n h = (h ^ (data[offset + 5] << 40))\n\n if l >= 5:\n h = (h ^ (data[offset + 4] << 32))\n\n if l >= 4:\n h = (h ^ (data[offset + 3] << 24))\n\n if l >= 3:\n h = (h ^ (data[offset + 2] << 16))\n\n if l >= 2:\n h = (h ^ (data[offset + 1] << 8))\n\n if l >= 1:\n h = (h ^ data[offset])\n h = (h * m) & mask\n\n h ^= (h >> r) & mask\n h = (h * m) & mask\n h ^= (h >> r) & mask\n\n return h", "docstring": "Pure 64-bit Python implementation of MurmurHash3; see\n http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash\n (plus RNC bugfixes).\n\nArgs:\n data: data to hash\n seed: seed\n\nReturns:\n integer hash", "source": "juraj_google_style"} +{"code": "def unsubscribe_stratgy(self, strategy_id):\n\n\n today = datetime.date.today()\n order_id = str(uuid.uuid1())\n if strategy_id in self._subscribed_strategy.keys():\n self._subscribed_strategy[strategy_id]['status'] = 'canceled'\n\n self.coins_history.append(\n [0,\n strategy_id,\n str(today),\n 0,\n order_id,\n 'unsubscribe']\n )", "docstring": "取消订阅某一个策略\n\nArgs:\n strategy_id {[type]} -- [description]", "source": "juraj_google_style"} +{"code": "def get_resource(self, resource_key, **variables):\n\n handle = self.make_resource_handle(resource_key, **variables)\n return self.get_resource_from_handle(handle, verify_repo=False)", "docstring": "Get a resource.\n\n Attempts to get and return a cached version of the resource if\n available, otherwise a new resource object is created and returned.\n\nArgs:\n resource_key (`str`): Name of the type of `Resources` to find\n variables: data to identify / store on the resource\n\nReturns:\n `PackageRepositoryResource` instance.", "source": "juraj_google_style"} +{"code": "def wmo(self, value=None):\n\n if value is not None:\n try:\n value = str(value)\n except ValueError:\n raise ValueError('value {} need to be of type str '\n 'for field `wmo`'.format(value))\n if ',' in value:\n raise ValueError('value should not contain a comma '\n 'for field `wmo`')\n\n self._wmo = value", "docstring": "Corresponds to IDD Field `wmo` usually a 6 digit field. Used as\n alpha in EnergyPlus.\n\nArgs:\n value (str): value for IDD Field `wmo`\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def offset(self, num_to_skip):\n\n query = query_mod.Query(self)\n return query.offset(num_to_skip)", "docstring": "Skip to an offset in a query with this collection as parent.\n\n See\n :meth:`~.firestore_v1beta1.query.Query.offset` for\n more information on this method.\n\nArgs:\n num_to_skip (int): The number of results to skip at the beginning\n of query results. (Must be non-negative.)\n\nReturns:\n ~.firestore_v1beta1.query.Query: An offset query.", "source": "juraj_google_style"} +{"code": "def load(fh, model):\n\n graphs = penman.load(fh, cls=XMRSCodec)\n xs = [model.from_triples(g.triples()) for g in graphs]\n return xs", "docstring": "Deserialize PENMAN graphs from a file (handle or filename)\n\nArgs:\n fh: filename or file object\n model: Xmrs subclass instantiated from decoded triples\n\nReturns:\n a list of objects (of class *model*)", "source": "juraj_google_style"} +{"code": "def Lock(fd, path, blocking):\n\n operation = fcntl.LOCK_EX if blocking else fcntl.LOCK_EX | fcntl.LOCK_NB\n try:\n fcntl.flock(fd, operation)\n except IOError as e:\n if e.errno == errno.EWOULDBLOCK:\n raise IOError('Exception locking %s. File already locked.' % path)\n else:\n raise IOError('Exception locking %s. %s.' % (path, str(e)))", "docstring": "Lock the provided file descriptor.\n\nArgs:\n fd: int, the file descriptor of the file to lock.\n path: string, the name of the file to lock.\n blocking: bool, whether the function should return immediately.\n\nRaises:\n IOError, raised from flock while attempting to lock a file.", "source": "juraj_google_style"} +{"code": "def request_json(link, outfile, force_rerun_flag, outdir=None):\n\n if not outdir:\n outdir = ''\n outfile = op.join(outdir, outfile)\n\n if force_rerun(flag=force_rerun_flag, outfile=outfile):\n text_raw = requests.get(link)\n my_dict = text_raw.json()\n with open(outfile, 'w') as f:\n json.dump(my_dict, f)\n\n log.debug('Loaded and saved {} to {}'.format(link, outfile))\n else:\n with open(outfile, 'r') as f:\n my_dict = json.load(f)\n log.debug('Loaded {}'.format(outfile))\n\n return my_dict", "docstring": "Download a file in JSON format from a web request\n\nArgs:\n link: Link to web request\n outfile: Name of output file\n outdir: Directory of output file\n force_rerun_flag: If true, redownload the file\n\nReturns:\n dict: contents of the JSON request", "source": "juraj_google_style"} +{"code": "def _parse_shape(self, space):\n\n if isinstance(space, gym.spaces.Discrete):\n return ()\n if isinstance(space, gym.spaces.Box):\n return space.shape\n raise NotImplementedError()", "docstring": "Get a tensor shape from a OpenAI Gym space.\n\nArgs:\n space: Gym space.\n\nRaises:\n NotImplementedError: For spaces other than Box and Discrete.\n\nReturns:\n Shape tuple.", "source": "juraj_google_style"} +{"code": "def process_input(self, stream, value, rpc_executor):\n\n\n self.sensor_log.push(stream, value)\n\n # FIXME: This should be specified in our device model\n if stream.important:\n associated_output = stream.associated_stream()\n self.sensor_log.push(associated_output, value)\n\n to_check = deque([x for x in self.roots])\n\n while len(to_check) > 0:\n node = to_check.popleft()\n if node.triggered():\n try:\n results = node.process(rpc_executor, self.mark_streamer)\n for result in results:\n result.raw_time = value.raw_time\n self.sensor_log.push(node.stream, result)\n except:\n self._logger.exception(\"Unhandled exception in graph node processing function for node %s\", str(node))\n\n # If we generated any outputs, notify our downstream nodes\n # so that they are also checked to see if they should run.\n if len(results) > 0:\n to_check.extend(node.outputs)", "docstring": "Process an input through this sensor graph.\n\n The tick information in value should be correct and is transfered\n to all results produced by nodes acting on this tick.\n\nArgs:\n stream (DataStream): The stream the input is part of\n value (IOTileReading): The value to process\n rpc_executor (RPCExecutor): An object capable of executing RPCs\n in case we need to do that.", "source": "juraj_google_style"} +{"code": "def set_forced_variation(self, experiment_key, user_id, variation_key):\n\n\n if not self.is_valid:\n self.logger.error(enums.Errors.INVALID_DATAFILE.format('set_forced_variation'))\n return False\n\n if not validator.is_non_empty_string(experiment_key):\n self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('experiment_key'))\n return False\n\n if not isinstance(user_id, string_types):\n self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('user_id'))\n return False\n\n return self.config.set_forced_variation(experiment_key, user_id, variation_key)", "docstring": "Force a user into a variation for a given experiment.\n\nArgs:\n experiment_key: A string key identifying the experiment.\n user_id: The user ID.\n variation_key: A string variation key that specifies the variation which the user.\n will be forced into. If null, then clear the existing experiment-to-variation mapping.\n\nReturns:\n A boolean value that indicates if the set completed successfully.", "source": "juraj_google_style"} +{"code": "def autodecode(b):\n\n import warnings\n import chardet\n\n try:\n return b.decode()\n except UnicodeError:\n result = chardet.detect(b)\n if result['confidence'] < 0.95:\n warnings.warn('autodecode failed with utf-8; guessing %s' % result['encoding'])\n return result.decode(result['encoding'])", "docstring": "Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect\n\nArgs:\n b (bytes): byte string\n\nReturns:\n str: decoded text string", "source": "juraj_google_style"} +{"code": "def GetEntries(\n self, parser_mediator, cookie_data=None, url=None, **kwargs):\n\n fields = cookie_data.split('.')\n number_of_fields = len(fields)\n\n if number_of_fields not in (1, 6):\n parser_mediator.ProduceExtractionWarning(\n 'unsupported number of fields: {0:d} in cookie: {1:s}'.format(\n number_of_fields, self.COOKIE_NAME))\n return\n\n if number_of_fields == 1:\n domain_hash = None\n visitor_identifier = None\n first_visit_posix_time = None\n previous_visit_posix_time = None\n\n try:\n # TODO: fix that we're losing precision here use dfdatetime.\n last_visit_posix_time = int(fields[0], 10) / 10000000\n except ValueError:\n last_visit_posix_time = None\n\n number_of_sessions = None\n\n elif number_of_fields == 6:\n domain_hash = fields[0]\n visitor_identifier = fields[1]\n\n # TODO: Double check this time is stored in UTC and not local time.\n try:\n first_visit_posix_time = int(fields[2], 10)\n except ValueError:\n first_visit_posix_time = None\n\n try:\n previous_visit_posix_time = int(fields[3], 10)\n except ValueError:\n previous_visit_posix_time = None\n\n try:\n last_visit_posix_time = int(fields[4], 10)\n except ValueError:\n last_visit_posix_time = None\n\n try:\n number_of_sessions = int(fields[5], 10)\n except ValueError:\n number_of_sessions = None\n\n event_data = GoogleAnalyticsEventData('utma')\n event_data.cookie_name = self.COOKIE_NAME\n event_data.domain_hash = domain_hash\n event_data.sessions = number_of_sessions\n event_data.url = url\n event_data.visitor_id = visitor_identifier\n\n if first_visit_posix_time is not None:\n date_time = dfdatetime_posix_time.PosixTime(\n timestamp=first_visit_posix_time)\n event = time_events.DateTimeValuesEvent(\n date_time, 'Analytics Creation Time')\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n if previous_visit_posix_time is not None:\n date_time = dfdatetime_posix_time.PosixTime(\n timestamp=previous_visit_posix_time)\n event = time_events.DateTimeValuesEvent(\n date_time, 'Analytics Previous Time')\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n date_time = None\n if last_visit_posix_time is not None:\n date_time = dfdatetime_posix_time.PosixTime(\n timestamp=last_visit_posix_time)\n timestamp_description = definitions.TIME_DESCRIPTION_LAST_VISITED\n elif first_visit_posix_time is None and previous_visit_posix_time is None:\n # If both creation_time and written_time are None produce an event\n # object without a timestamp.\n date_time = dfdatetime_semantic_time.SemanticTime('Not set')\n timestamp_description = definitions.TIME_DESCRIPTION_NOT_A_TIME\n\n if date_time is not None:\n event = time_events.DateTimeValuesEvent(date_time, timestamp_description)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Extracts event objects from the cookie.\n\nArgs:\n parser_mediator (ParserMediator): parser mediator.\n cookie_data (str): cookie data.\n url (str): URL or path where the cookie got set.", "source": "juraj_google_style"} +{"code": "def ensure_app_config_dir(appname, *args):\n\n from ubelt import util_path\n dpath = get_app_config_dir(appname, *args)\n util_path.ensuredir(dpath)\n return dpath", "docstring": "Calls `get_app_config_dir` but ensures the directory exists.\n\nArgs:\n appname (str): the name of the application\n *args: any other subdirectories may be specified\n\n SeeAlso:\n get_app_config_dir\n\nExample:\n >>> import ubelt as ub\n >>> dpath = ub.ensure_app_config_dir('ubelt')\n >>> assert exists(dpath)", "source": "juraj_google_style"} +{"code": "def _decoder(image, shrink):\n\n decoder = dmtxDecodeCreate(image, shrink)\n if not decoder:\n raise PyLibDMTXError('Could not create decoder')\n else:\n try:\n yield decoder\n finally:\n dmtxDecodeDestroy(byref(decoder))", "docstring": "A context manager for `DmtxDecode`, created and destroyed by\n `dmtxDecodeCreate` and `dmtxDecodeDestroy`.\n\nArgs:\n image (POINTER(DmtxImage)):\n shrink (int):\n\nYields:\n POINTER(DmtxDecode): The created decoder\n\nRaises:\n PyLibDMTXError: If the decoder could not be created.", "source": "juraj_google_style"} +{"code": "def __init__(self, size, dropout=None, lstmcell_args={}, named_tensors=None, scope='internal_lstm', summary_labels=()):\n\n self.size = size\n self.dropout = dropout\n self.lstmcell_args = lstmcell_args\n super(InternalLstm, self).__init__(named_tensors=named_tensors, scope=scope, summary_labels=summary_labels)", "docstring": "LSTM layer.\n\nArgs:\n size: LSTM size.\n dropout: Dropout rate.", "source": "juraj_google_style"} +{"code": "def get_openapi_dict(self, services, hostname=None, x_google_api_name=False):\n\n\n if not isinstance(services, (tuple, list)):\n services = [services]\n\n # The type of a class that inherits from remote.Service is actually\n # remote._ServiceClass, thanks to metaclass strangeness.\n # pylint: disable=protected-access\n util.check_list_type(services, remote._ServiceClass, 'services',\n allow_none=False)\n\n return self.__api_openapi_descriptor(services, hostname=hostname, x_google_api_name=x_google_api_name)", "docstring": "JSON dict description of a protorpc.remote.Service in OpenAPI format.\n\nArgs:\n services: Either a single protorpc.remote.Service or a list of them\n that implements an api/version.\n hostname: string, Hostname of the API, to override the value set on the\n current service. Defaults to None.\n\nReturns:\n dict, The OpenAPI descriptor document as a JSON dict.", "source": "juraj_google_style"} +{"code": "def CopyFromStringTuple(self, time_elements_tuple):\n\n if len(time_elements_tuple) < 7:\n raise ValueError((\n 'Invalid time elements tuple at least 7 elements required,'\n 'got: {0:d}').format(len(time_elements_tuple)))\n\n year, month, day_of_month, hours, minutes, seconds, microseconds = (\n time_elements_tuple)\n\n try:\n microseconds = int(microseconds, 10)\n except (TypeError, ValueError):\n raise ValueError('Invalid microsecond value: {0!s}'.format(microseconds))\n\n if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND:\n raise ValueError('Invalid number of microseconds.')\n\n fraction_of_second = (\n decimal.Decimal(microseconds) / definitions.MICROSECONDS_PER_SECOND)\n\n time_elements_tuple = (\n year, month, day_of_month, hours, minutes, seconds,\n str(fraction_of_second))\n\n super(TimeElementsInMicroseconds, self).CopyFromStringTuple(\n time_elements_tuple)", "docstring": "Copies time elements from string-based time elements tuple.\n\nArgs:\n time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]):\n time elements, contains year, month, day of month, hours, minutes,\n seconds and microseconds.\n\nRaises:\n ValueError: if the time elements tuple is invalid.", "source": "juraj_google_style"} +{"code": "def request(self, send_terminator = False):\n\n self.m_a_crc = False\n start_context = self.getContext()\n self.setContext(\"request[v3A]\")\n try:\n self.m_serial_port.write(\"2f3f\".decode(\"hex\") +\n self.m_meter_address +\n \"210d0a\".decode(\"hex\"))\n self.m_raw_read_a = self.m_serial_port.getResponse(self.getContext())\n unpacked_read_a = self.unpackStruct(self.m_raw_read_a, self.m_blk_a)\n self.convertData(unpacked_read_a, self.m_blk_a, 1)\n self.m_a_crc = self.crcMeterRead(self.m_raw_read_a, self.m_blk_a)\n if send_terminator:\n self.serialPostEnd()\n self.calculateFields()\n self.makeReturnFormat()\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n\n self.setContext(start_context)\n return self.m_a_crc", "docstring": "Required request() override for v3 and standard method to read meter.\n\nArgs:\n send_terminator (bool): Send termination string at end of read.\n\nReturns:\n bool: CRC request flag result from most recent read", "source": "juraj_google_style"} +{"code": "def Histograms(self, run, tag):\n\n accumulator = self.GetAccumulator(run)\n return accumulator.Histograms(tag)", "docstring": "Retrieve the histogram events associated with a run and tag.\n\nArgs:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\nRaises:\n KeyError: If the run is not found, or the tag is not available for\n the given run.\n\nReturns:\n An array of `event_accumulator.HistogramEvents`.", "source": "juraj_google_style"} +{"code": "def ends_of_next_whole_turn(self, root):\n\n # simple confirmation that the root is actually a root.\n # otherwise it may seem to work but would be totally out of spec\n if root.parent:\n raise ValueError('Unexpectedly received a node with a parent for'\n ' root:\\n{}'.format(root))\n # build the list of eots (or just the root if first turn) to be run\n leaves = list(root.leaves())\n kw_starts = list()\n if leaves[0] is root:\n # build ends of state kwargs as only the root\n kw_starts.append({'root': root})\n else:\n # build ends of state kwargs as eots in the tree\n for leaf in leaves:\n # ignore mana drains\n if not leaf.is_mana_drain:\n kw_starts.append({'root_eot': leaf})\n # run a single turn for each starting point\n for kw_start in kw_starts:\n for eot in self.ends_of_one_state(**kw_start):\n yield eot", "docstring": "Simulate one complete turn to completion and generate each end of\n turn reached during the simulation.\n\n Note on mana drain:\n Generates but does not continue simulation of mana drains.\n\nArgs:\n root: a start state with no parent", "source": "juraj_google_style"} +{"code": "def generate(organization, package, destination):\n\n gen = ResourceGenerator(organization, package)\n\n tmp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)\n try:\n tmp.write(gen.conf())\n finally:\n tmp.close()\n\n shutil.copy(tmp.name, os.path.join(destination, 'conf.py'))\n\n tmp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)\n try:\n tmp.write(gen.makefile())\n finally:\n tmp.close()\n\n shutil.copy(tmp.name, os.path.join(destination, 'Makefile'))", "docstring": "Generates the Sphinx configuration and Makefile.\n\nArgs:\n organization (str): the organization name.\n package (str): the package to be documented.\n destination (str): the destination directory.", "source": "juraj_google_style"} +{"code": "def add_pagination_meta(self, params, meta):\n\n meta['page_size'] = params['page_size']\n meta['page'] = params['page']\n\n meta['prev'] = \"page={0}&page_size={1}\".format(\n params['page'] - 1, params['page_size']\n ) if meta['page'] > 0 else None\n\n meta['next'] = \"page={0}&page_size={1}\".format(\n params['page'] + 1, params['page_size']\n ) if meta.get('has_more', True) else None", "docstring": "Extend default meta dictionary value with pagination hints.\n\nNote:\n This method handler attaches values to ``meta`` dictionary without\n changing it's reference. This means that you should never replace\n ``meta`` dictionary with any other dict instance but simply modify\n its content.\n\nArgs:\n params (dict): dictionary of decoded parameter values\n meta (dict): dictionary of meta values attached to response", "source": "juraj_google_style"} +{"code": "def get(self, catID, includeRelationships=False):\n\n url = '%(base_url)s/record/%(catID)s' % {\n 'base_url': self.base_url, 'catID': catID\n }\n r = self.gbdx_connection.get(url)\n r.raise_for_status()\n return r.json()", "docstring": "Retrieves the strip footprint WKT string given a cat ID.\n\nArgs:\n catID (str): The source catalog ID from the platform catalog.\n includeRelationships (bool): whether to include graph links to related objects. Default False.\n\nReturns:\n record (dict): A dict object identical to the json representation of the catalog record", "source": "juraj_google_style"} +{"code": "def from_json(cls, json):\n\n mapreduce_spec = cls(json[\"name\"],\n json[\"mapreduce_id\"],\n json[\"mapper_spec\"],\n json.get(\"params\"),\n json.get(\"hooks_class_name\"))\n return mapreduce_spec", "docstring": "Create new MapreduceSpec from the json, encoded by to_json.\n\nArgs:\n json: json representation of MapreduceSpec.\n\nReturns:\n an instance of MapreduceSpec with all data deserialized from json.", "source": "juraj_google_style"} +{"code": "def shell_call(command, **kwargs):\n\n command = list(command)\n for i in range(len(command)):\n m = CMD_VARIABLE_RE.match(command[i])\n if m:\n var_id = m.group(1)\n if var_id in kwargs:\n command[i] = kwargs[var_id]\n return subprocess.call(command) == 0", "docstring": "Calls shell command with parameter substitution.\n\nArgs:\n command: command to run as a list of tokens\n **kwargs: dirctionary with substitutions\n\nReturns:\n whether command was successful, i.e. returned 0 status code\n\n Example of usage:\n shell_call(['cp', '${A}', '${B}'], A='src_file', B='dst_file')\n will call shell command:\n cp src_file dst_file", "source": "juraj_google_style"} +{"code": "def _on_connected(self, device):\n\n self._logger.debug(\"Device connected event: {}\".format(device))\n\n self.connected = True\n self._connection_handle = device['connection_handle']\n self.device.connected = True\n self._audit('ClientConnected')", "docstring": "Callback function called when a connected event has been received.\n It is executed in the baBLE working thread: should not be blocking.\n\nArgs:\n device (dict): Information about the newly connected device", "source": "juraj_google_style"} +{"code": "def create_policy(self, id, policy):\n\n return self.request(\"policy\", id, json=policy, method=\"post\")", "docstring": "Create policy.\n\n https://www.nomadproject.io/api/acl-policies.html\n\nArgs:\n - policy\n returns: request.Response\n\nRaises:\n - nomad.api.exceptions.BaseNomadException\n - nomad.api.exceptions.URLNotFoundNomadException", "source": "juraj_google_style"} +{"code": "def declare_field(self, type, name, offset=None, length=None):\n\n if offset is None:\n offset = self._implicit_offset\n\n if length is None:\n def no_length_handler():\n f = getattr(self, \"unpack_\" + type)\n return f(offset)\n setattr(self, name, no_length_handler)\n else:\n\n def explicit_length_handler():\n f = getattr(self, \"unpack_\" + type)\n return f(offset, length)\n setattr(self, name, explicit_length_handler)\n\n setattr(self, \"_off_\" + name, offset)\n if type == \"byte\":\n self._implicit_offset = offset + 1\n elif type == \"int8\":\n self._implicit_offset = offset + 1\n elif type == \"word\":\n self._implicit_offset = offset + 2\n elif type == \"word_be\":\n self._implicit_offset = offset + 2\n elif type == \"int16\":\n self._implicit_offset = offset + 2\n elif type == \"dword\":\n self._implicit_offset = offset + 4\n elif type == \"dword_be\":\n self._implicit_offset = offset + 4\n elif type == \"int32\":\n self._implicit_offset = offset + 4\n elif type == \"qword\":\n self._implicit_offset = offset + 8\n elif type == \"int64\":\n self._implicit_offset = offset + 8\n elif type == \"float\":\n self._implicit_offset = offset + 4\n elif type == \"double\":\n self._implicit_offset = offset + 8\n elif type == \"dosdate\":\n self._implicit_offset = offset + 4\n elif type == \"filetime\":\n self._implicit_offset = offset + 8\n elif type == \"systemtime\":\n self._implicit_offset = offset + 8\n elif type == \"guid\":\n self._implicit_offset = offset + 16\n elif type == \"binary\":\n self._implicit_offset = offset + length\n elif type == \"string\" and length is not None:\n self._implicit_offset = offset + length\n elif type == \"wstring\" and length is not None:\n self._implicit_offset = offset + (2 * length)\n elif \"string\" in type and length is None:\n raise ParseException(\"Implicit offset not supported \"\n \"for dynamic length strings\")\n else:\n raise ParseException(\"Implicit offset not supported \"\n \"for type: {}\".format(type))", "docstring": "Declaratively add fields to this block.\n This method will dynamically add corresponding\n offset and unpacker methods to this block.\n\nArgs:\n - `type`: A string. Should be one of the unpack_* types.\n - `name`: A string.\n - `offset`: A number.\n - `length`: (Optional) A number. For (w)strings, length in chars.", "source": "juraj_google_style"} +{"code": "def UsesArtifact(self, artifacts):\n\n # If artifact is a single string, see if it is in the list of artifacts\n # as-is. Otherwise, test whether any of the artifacts passed in to this\n # function exist in the list of artifacts.\n if isinstance(artifacts, string_types):\n return artifacts in self.artifacts\n else:\n return any(True for artifact in artifacts if artifact in self.artifacts)", "docstring": "Determines if the check uses the specified artifact.\n\nArgs:\n artifacts: Either a single artifact name, or a list of artifact names\n\nReturns:\n True if the check uses a specific artifact.", "source": "juraj_google_style"} +{"code": "def faster_roc(actuals, controls):\n\n assert(type(actuals) is np.ndarray)\n assert(type(controls) is np.ndarray)\n\n if len(actuals)<500:\n raise RuntimeError('This method might be incorrect when '+\n 'not enough actuals are present. Needs to be checked before '+\n 'proceeding. Stopping here for you to do so.')\n\n actuals = np.ravel(actuals)\n controls = np.ravel(controls)\n if np.isnan(actuals).any():\n raise RuntimeError('NaN found in actuals')\n if np.isnan(controls).any():\n raise RuntimeError('NaN found in controls')\n\n thresholds = np.hstack([-np.inf, np.unique(actuals), np.inf])+np.finfo(float).eps\n true_pos_rate = np.nan*np.empty(thresholds.size-1)\n false_pos_rate = np.nan*np.empty(thresholds.size-1)\n num_act = float(len(actuals))\n num_ctr = float(len(controls))\n\n actuals = 1-(np.cumsum(np.histogram(actuals, thresholds)[0])/num_act)\n controls = 1-(np.cumsum(np.histogram(controls, thresholds)[0])/num_ctr)\n true_pos_rate = actuals\n false_pos_rate = controls\n #true_pos_rate = np.concatenate(([0], true_pos_rate, [1]))\n false_pos_rate = false_pos_rate\n auc = -1*np.dot(np.diff(false_pos_rate), true_pos_rate[0:-1])\n # treat cases where TPR of one is not reached before FPR of one\n # by using trapezoidal integration for the last segment\n # (add the missing triangle)\n if false_pos_rate[-2] == 1:\n auc += ((1-true_pos_rate[-3])*.5*(1-false_pos_rate[-3]))\n return (auc, true_pos_rate, false_pos_rate)", "docstring": "Histogram based implementation of AUC unde ROC curve.\n Parameters:\n actuals : list\n A list of numeric values for positive observations.\n controls : list\n A list of numeric values for negative observations.", "source": "juraj_google_style"} +{"code": "def download_from_url(path, url):\n\n filename = url.split(\"/\")[-1]\n found_file = find_file(path, filename, max_depth=0)\n if found_file is None:\n filename = os.path.join(path, filename)\n tf.logging.info(\"Downloading from %s to %s.\" % (url, filename))\n inprogress_filepath = filename + \".incomplete\"\n inprogress_filepath, _ = urllib.request.urlretrieve(\n url, inprogress_filepath, reporthook=download_report_hook)\n # Print newline to clear the carriage return from the download progress.\n print()\n tf.gfile.Rename(inprogress_filepath, filename)\n return filename\n else:\n tf.logging.info(\"Already downloaded: %s (at %s).\" % (url, found_file))\n return found_file", "docstring": "Download content from a url.\n\nArgs:\n path: string directory where file will be downloaded\n url: string url\n\nReturns:\n Full path to downloaded file", "source": "juraj_google_style"} +{"code": "def start(component, exact):\n # type: (str, str) -> None\n\n version_file = conf.get_path('version_file', 'VERSION')\n\n develop = conf.get('git.devel_branch', 'develop')\n common.assert_on_branch(develop)\n\n with conf.within_proj_dir():\n out = shell.run('git status --porcelain', capture=True).stdout\n lines = out.split(os.linesep)\n has_changes = any(\n not l.startswith('??') for l in lines if l.strip()\n )\n\n if has_changes:\n log.info(\"Cannot release: there are uncommitted changes\")\n exit(1)\n\n old_ver, new_ver = versioning.bump(component, exact)\n\n log.info(\"Bumping package version\")\n log.info(\" old version: <35>{}\".format(old_ver))\n log.info(\" new version: <35>{}\".format(new_ver))\n\n with conf.within_proj_dir():\n branch = 'release/' + new_ver\n\n common.git_checkout(branch, create=True)\n\n log.info(\"Creating commit for the release\")\n shell.run('git add {ver_file} && git commit -m \"{msg}\"'.format(\n ver_file=version_file,\n msg=\"Releasing v{}\".format(new_ver)\n ))", "docstring": "Create a new release branch.\n\nArgs:\n component (str):\n Version component to bump when creating the release. Can be *major*,\n *minor* or *patch*.\n exact (str):\n The exact version to set for the release. Overrides the component\n argument. This allows to re-release a version if something went\n wrong with the release upload.", "source": "juraj_google_style"} +{"code": "def exclude(self, func=None):\n\n func = _make_callable(func)\n inverse = lambda x: not func(x)\n return self.filter(inverse)", "docstring": "Return a new Collection excluding some items\n\n Parameters:\n\n func : function(Node) -> Scalar\n\n A function that, when called on each item\n in the collection, returns a boolean-like\n value. If no function is provided, then\n truthy items will be removed.\n\nReturns:\n A new Collection consisting of the items\n where bool(func(item)) == False", "source": "juraj_google_style"} +{"code": "def __init__(self, action_type=None, dl_addr=None):\n\n super().__init__(action_type, length=16)\n self.dl_addr = dl_addr", "docstring": "Create an ActionDLAddr with the optional parameters below.\n\nArgs:\n action_type (:class:`~pyof.v0x01.common.action.ActionType`):\n :attr:`~ActionType.OFPAT_SET_DL_SRC` or\n :attr:`~ActionType.OFPAT_SET_DL_DST`.\n dl_addr (:class:`~.HWAddress`): Ethernet address.\n Defaults to None.", "source": "juraj_google_style"} +{"code": "def segment(self, text):\n\n\n files = {'text': text}\n res, status_code = self.post(self.segmentation_service, files=files)\n\n if status_code != 200:\n logger.debug('Segmentation failed.')\n\n return self.decode(res), status_code", "docstring": "Call the segmenter in order to split text in sentences.\n\nArgs:\n text (str): Text to be segmented.\n\nReturns:\n dict, int: A dict containing a list of dicts with the offsets of\n each sentence; an integer representing the response code.", "source": "juraj_google_style"} +{"code": "def getFingerprintsForTexts(self, strings, sparsity=1.0):\n\n body = [{\"text\": s} for s in strings]\n return self._text.getRepresentationsForBulkText(self._retina, json.dumps(body), sparsity)", "docstring": "Bulk get Fingerprint for text.\n\nArgs:\n strings, list(str): A list of texts to be evaluated (required)\n sparsity, float: Sparsify the resulting expression to this percentage (optional)\n\nReturns:\n list of Fingerprint\n\nRaises:\n CorticalioException: if the request was not successful", "source": "juraj_google_style"} +{"code": "def read(self, size=None):\n\n if not self._database_object:\n raise IOError('Not opened.')\n\n if self._current_offset < 0:\n raise IOError('Invalid offset value out of bounds.')\n\n if size == 0 or self._current_offset >= self._size:\n return b''\n\n if size is None:\n size = self._size\n if self._current_offset + size > self._size:\n size = self._size - self._current_offset\n\n start_offset = self._current_offset\n self._current_offset += size\n return self._blob[start_offset:self._current_offset]", "docstring": "Reads a byte string from the file-like object at the current offset.\n\n The function will read a byte string of the specified size or\n all of the remaining data if no size was specified.\n\nArgs:\n size (Optional[int]): number of bytes to read, where None is all\n remaining data.\n\nReturns:\n bytes: data read.\n\nRaises:\n IOError: if the read failed.\n OSError: if the read failed.", "source": "juraj_google_style"} +{"code": "def enhance_pubmed_annotations(pubmed: Mapping[str, Any]) -> Mapping[str, Any]:\n\n\n text = pubmed[\"title\"] + pubmed[\"abstract\"]\n\n annotations = {}\n\n for nsarg in pubmed[\"annotations\"]:\n url = f'{config[\"bel_api\"][\"servers\"][\"api_url\"]}/terms/{url_path_param_quoting(nsarg)}'\n log.info(f\"URL: {url}\")\n r = get_url(url)\n log.info(f\"Result: {r}\")\n new_nsarg = \"\"\n if r and r.status_code == 200:\n term = r.json()\n new_nsarg = bel_utils.convert_nsarg(term[\"id\"], decanonicalize=True)\n\n pubmed[\"annotations\"][nsarg][\"name\"] = term[\"name\"]\n pubmed[\"annotations\"][nsarg][\"label\"] = term[\"label\"]\n pubmed[\"annotations\"][nsarg][\"entity_types\"] = list(\n set(\n pubmed[\"annotations\"][nsarg][\"entity_types\"]\n + term.get(\"entity_types\", [])\n )\n )\n pubmed[\"annotations\"][nsarg][\"annotation_types\"] = list(\n set(\n pubmed[\"annotations\"][nsarg][\"annotation_types\"]\n + term.get(\"annotation_types\", [])\n )\n )\n\n if new_nsarg != nsarg:\n annotations[new_nsarg] = copy.deepcopy(pubmed[\"annotations\"][nsarg])\n else:\n annotations[nsarg] = copy.deepcopy(pubmed[\"annotations\"][nsarg])\n\n for nsarg in annotations:\n for idx, span in enumerate(annotations[nsarg][\"spans\"]):\n string = text[span[\"begin\"] - 1 : span[\"end\"] - 1]\n annotations[nsarg][\"spans\"][idx][\"text\"] = string\n\n pubmed[\"annotations\"] = copy.deepcopy(annotations)\n\n return pubmed", "docstring": "Enhance pubmed namespace IDs\n\n Add additional entity and annotation types to annotations\n Use preferred id for namespaces as needed\n Add strings from Title, Abstract matching Pubtator BioConcept spans\n\n NOTE - basically duplicated code with bel_api:api.services.pubmed\n\nArgs:\n pubmed\n\nReturns:\n pubmed object", "source": "juraj_google_style"} +{"code": "def extract_cookies(self, response, request, referrer_host=None):\n\n new_response = HTTPResponseInfoWrapper(response)\n new_request = convert_http_request(request, referrer_host)\n\n self._cookie_jar.extract_cookies(new_response, new_request)", "docstring": "Wrapped ``extract_cookies``.\n\nArgs:\n response: An instance of :class:`.http.request.Response`.\n request: An instance of :class:`.http.request.Request`.\n referrer_host (str): An hostname or IP address of the referrer\n URL.", "source": "juraj_google_style"} +{"code": "def random(cls, num_qubits, seed=None):\n\n if seed is not None:\n np.random.seed(seed)\n z = np.random.randint(2, size=num_qubits).astype(np.bool)\n x = np.random.randint(2, size=num_qubits).astype(np.bool)\n return cls(z, x)", "docstring": "Return a random Pauli on number of qubits.\n\nArgs:\n num_qubits (int): the number of qubits\n seed (int): Optional. To set a random seed.\n\nReturns:\n Pauli: the random pauli", "source": "juraj_google_style"} +{"code": "def get(cls, blob_key, **ctx_options):\n\n fut = cls.get_async(blob_key, **ctx_options)\n return fut.get_result()", "docstring": "Retrieve a BlobInfo by key.\n\nArgs:\n blob_key: A blob key. This may be a str, unicode or BlobKey instance.\n **ctx_options: Context options for Model().get_by_id().\n\nReturns:\n A BlobInfo entity associated with the provided key, If there was\n no such entity, returns None.", "source": "juraj_google_style"} +{"code": "def cancel(self, subscription_id, data={}, **kwargs):\n\n url = \"{}/{}/cancel\".format(self.base_url, subscription_id)\n return self.post_url(url, data, **kwargs)", "docstring": "Cancel subscription given by subscription_id\n\nArgs:\n subscription_id : Id for which subscription has to be cancelled\n\nReturns:\n Subscription Dict for given subscription id", "source": "juraj_google_style"} +{"code": "def cancel(self, workflow_id):\n\n self.logger.debug('Canceling workflow: ' + workflow_id)\n url = '%(wf_url)s/%(wf_id)s/cancel' % {\n 'wf_url': self.workflows_url, 'wf_id': workflow_id\n }\n r = self.gbdx_connection.post(url, data='')\n r.raise_for_status()", "docstring": "Cancels a running workflow.\n\nArgs:\n workflow_id (str): Workflow id.\n\nReturns:\n Nothing", "source": "juraj_google_style"} +{"code": "def AddAnalysisReport(self, analysis_report):\n\n self._RaiseIfNotWritable()\n\n self._storage_file.AddAnalysisReport(analysis_report)\n\n report_identifier = analysis_report.plugin_name\n self._session.analysis_reports_counter['total'] += 1\n self._session.analysis_reports_counter[report_identifier] += 1\n self.number_of_analysis_reports += 1", "docstring": "Adds an analysis report.\n\nArgs:\n analysis_report (AnalysisReport): analysis report.\n\nRaises:\n IOError: when the storage writer is closed.\n OSError: when the storage writer is closed.", "source": "juraj_google_style"} +{"code": "def filename(self, appendix=None, create_if_not_existing=False):\n\n\n # if provided path is a relative path and self.data_path exists, build path\n if os.path.isabs(self.settings['path']) == False and self.data_path is not None:\n path = os.path.join(self.data_path, self.settings['path'])\n else:\n path = self.settings['path']\n\n tag = self.settings['tag']#.replace('.','-')\n\n filename = os.path.join(path, \"{:s}_{:s}\".format(self.start_time.strftime('%y%m%d-%H_%M_%S'),tag))\n\n if os.path.exists(filename) == False and create_if_not_existing:\n os.makedirs(filename)\n\n if appendix is not None:\n filename = os.path.join(filename, \"{:s}_{:s}{:s}\".format(self.start_time.strftime('%y%m%d-%H_%M_%S'),tag,appendix))\n\n # windows can't deal with long filenames so we have to use the prefix '\\\\\\\\?\\\\'\n # if len(filename.split('\\\\\\\\?\\\\')) == 1:\n # filename = '\\\\\\\\?\\\\' + filename\n\n return filename", "docstring": "creates a filename based\n\nArgs:\n appendix: appendix for file\n\n Returns: filename", "source": "juraj_google_style"} +{"code": "def true_positives(y, y_pred):\n\n\n y, y_pred = convert_assert(y, y_pred)\n assert_binary_problem(y)\n\n return np.count_nonzero(y_pred[y == 1] == 1)", "docstring": "True-positives\n\n Parameters:\n -----------\n y : vector, shape (n_samples,)\n The target labels.\n\n y_pred : vector, shape (n_samples,)\n The predicted labels.\n\nReturns:\n --------\n tp : integer, the number of true-positives", "source": "juraj_google_style"} +{"code": "def write(self, b):\n\n if not self._writable:\n raise UnsupportedOperation('write')\n\n # This function write data in a buffer\n # \"flush()\" need to be called to really write content on\n # Cloud Storage\n size = len(b)\n with self._seek_lock:\n start = self._seek\n end = start + size\n self._seek = end\n\n buffer = self._write_buffer\n if end <= len(buffer):\n buffer = memoryview(buffer)\n buffer[start:end] = b\n return size", "docstring": "Write the given bytes-like object, b, to the underlying raw stream,\n and return the number of bytes written.\n\nArgs:\n b (bytes-like object): Bytes to write.\n\nReturns:\n int: The number of bytes written.", "source": "juraj_google_style"} +{"code": "def _full_axis_reduce(self, axis, func, alternate_index=None):\n\n result = self.data.map_across_full_axis(axis, func)\n if axis == 0:\n columns = alternate_index if alternate_index is not None else self.columns\n return self.__constructor__(result, index=[\"__reduced__\"], columns=columns)\n else:\n index = alternate_index if alternate_index is not None else self.index\n return self.__constructor__(result, index=index, columns=[\"__reduced__\"])", "docstring": "Applies map that reduce Manager to series but require knowledge of full axis.\n\nArgs:\n func: Function to reduce the Manager by. This function takes in a Manager.\n axis: axis to apply the function to.\n alternate_index: If the resulting series should have an index\n different from the current query_compiler's index or columns.\n\nReturns:\n Pandas series containing the reduced data.", "source": "juraj_google_style"} +{"code": "def parse(self, data, extent, desc_tag):\n # type: (bytes, int, UDFTag) -> None\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Descriptor already initialized')\n\n (tag_unused, self.vol_desc_seqnum, self.desc_char_set,\n self.logical_vol_ident, logical_block_size, domain_ident,\n logical_volume_contents_use, map_table_length, num_partition_maps,\n impl_ident, self.implementation_use, self.integrity_sequence_length,\n self.integrity_sequence_extent, partition_map,\n end_unused) = struct.unpack_from(self.FMT, data, 0)\n\n self.desc_tag = desc_tag\n\n if logical_block_size != 2048:\n raise pycdlibexception.PyCdlibInvalidISO('Volume Descriptor block size is not 2048')\n\n self.domain_ident = UDFEntityID()\n self.domain_ident.parse(domain_ident)\n if self.domain_ident.identifier[:19] != b'*OSTA UDF Compliant':\n raise pycdlibexception.PyCdlibInvalidISO(\"Volume Descriptor Identifier not '*OSTA UDF Compliant'\")\n\n if map_table_length != 6:\n raise pycdlibexception.PyCdlibInvalidISO('Volume Descriptor map table length not 6')\n\n if num_partition_maps != 1:\n raise pycdlibexception.PyCdlibInvalidISO('Volume Descriptor number of partition maps not 1')\n\n self.impl_ident = UDFEntityID()\n self.impl_ident.parse(impl_ident)\n\n self.partition_map = UDFPartitionMap()\n self.partition_map.parse(partition_map)\n\n self.logical_volume_contents_use = UDFLongAD()\n self.logical_volume_contents_use.parse(logical_volume_contents_use)\n\n self.orig_extent_loc = extent\n\n self._initialized = True", "docstring": "Parse the passed in data into a UDF Logical Volume Descriptor.\n\n Parameters:\n data - The data to parse.\n extent - The extent that this descriptor currently lives at.\n desc_tag - A UDFTag object that represents the Descriptor Tag.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def song_play(self, song):\n\n\n\t\tif 'storeId' in song:\n\t\t\tsong_id = song['storeId']\n\t\telif 'trackId' in song:\n\t\t\tsong_id = song['trackId']\n\t\telse:\n\t\t\tsong_id = song['id']\n\n\t\tsong_duration = song['durationMillis']\n\n\t\tevent = mc_calls.ActivityRecordRealtime.play(song_id, song_duration)\n\t\tresponse = self._call(\n\t\t\tmc_calls.ActivityRecordRealtime,\n\t\t\tevent\n\t\t)\n\n\t\treturn True if response.body['eventResults'][0]['code'] == 'OK' else False", "docstring": "Add play to song play count.\n\n Parameters:\n song (dict): A song dict.\n\nReturns:\n bool: ``True`` if successful, ``False`` if not.", "source": "juraj_google_style"} +{"code": "def compute_output_shape(self, input_shape):\n\n input_shape = tf.TensorShape(input_shape)\n input_shape = input_shape.with_rank_at_least(2)\n if tf.compat.dimension_value(input_shape[-1]) is None:\n raise ValueError(\n 'The innermost dimension of `input_shape` must be defined, '\n 'but saw: {}'.format(input_shape))\n return input_shape[:-1].concatenate(self.units)", "docstring": "Computes the output shape of the layer.\n\nArgs:\n input_shape: Shape tuple (tuple of integers) or list of shape tuples\n (one per output tensor of the layer). Shape tuples can include None for\n free dimensions, instead of an integer.\n\nReturns:\n output_shape: A tuple representing the output shape.\n\nRaises:\n ValueError: If innermost dimension of `input_shape` is not defined.", "source": "juraj_google_style"} +{"code": "def set_current(self, current):\n\n self.current = current\n self.input = current.input\n # self.req = current.request\n # self.resp = current.response\n self.output = current.output\n self.cmd = current.task_data['cmd']\n\n if self.cmd and NEXT_CMD_SPLITTER in self.cmd:\n self.cmd, self.next_cmd = self.cmd.split(NEXT_CMD_SPLITTER)\n else:\n self.next_cmd = None", "docstring": "Creates some aliases for attributes of ``current``.\n\nArgs:\n current: :attr:`~zengine.engine.WFCurrent` object.", "source": "juraj_google_style"} +{"code": "def _CreateOutputModule(self, options):\n\n formatter_mediator = formatters_mediator.FormatterMediator(\n data_location=self._data_location)\n\n try:\n formatter_mediator.SetPreferredLanguageIdentifier(\n self._preferred_language)\n except (KeyError, TypeError) as exception:\n raise RuntimeError(exception)\n\n mediator = output_mediator.OutputMediator(\n self._knowledge_base, formatter_mediator,\n preferred_encoding=self.preferred_encoding)\n mediator.SetTimezone(self._preferred_time_zone)\n\n try:\n output_module = output_manager.OutputManager.NewOutputModule(\n self._output_format, mediator)\n\n except (KeyError, ValueError) as exception:\n raise RuntimeError(\n 'Unable to create output module with error: {0!s}'.format(\n exception))\n\n if output_manager.OutputManager.IsLinearOutputModule(self._output_format):\n output_file_object = open(self._output_filename, 'wb')\n output_writer = tools.FileObjectOutputWriter(output_file_object)\n output_module.SetOutputWriter(output_writer)\n\n helpers_manager.ArgumentHelperManager.ParseOptions(options, output_module)\n\n # Check if there are parameters that have not been defined and need to\n # in order for the output module to continue. Prompt user to supply\n # those that may be missing.\n missing_parameters = output_module.GetMissingArguments()\n while missing_parameters:\n for parameter in missing_parameters:\n value = self._PromptUserForInput(\n 'Missing parameter {0:s} for output module'.format(parameter))\n if value is None:\n logger.warning(\n 'Unable to set the missing parameter for: {0:s}'.format(\n parameter))\n continue\n\n setattr(options, parameter, value)\n\n helpers_manager.ArgumentHelperManager.ParseOptions(\n options, output_module)\n missing_parameters = output_module.GetMissingArguments()\n\n return output_module", "docstring": "Creates the output module.\n\nArgs:\n options (argparse.Namespace): command line arguments.\n\nReturns:\n OutputModule: output module.\n\nRaises:\n RuntimeError: if the output module cannot be created.", "source": "juraj_google_style"} +{"code": "def cols_(df,col_list,func,*args,**kwargs):\n\n return _pd.DataFrame({col_name:func(df,col_name,*args,**kwargs) for col_name in col_list})", "docstring": "Do a function over a list of columns and return the result\n Parameters:\n df - DataFrame\n DataFrame to operate on\n col_list - list of strings\n names of columns to coerce\n func - function\n function to use", "source": "juraj_google_style"} +{"code": "def run_command(commands):\n # type: (Union[AnyStr, List[AnyStr]]) -> List[AnyStr]\n\n # commands = StringClass.convert_unicode2str(commands)\n # print(commands)\n\n use_shell = False\n subprocess_flags = 0\n startupinfo = None\n if sysstr == 'Windows':\n if isinstance(commands, list):\n commands = ' '.join(str(c) for c in commands)\n import ctypes\n SEM_NOGPFAULTERRORBOX = 0x0002 # From MSDN\n ctypes.windll.kernel32.SetErrorMode(SEM_NOGPFAULTERRORBOX)\n subprocess_flags = 0x8000000 # win32con.CREATE_NO_WINDOW?\n # this startupinfo structure prevents a console window from popping up on Windows\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n # not sure if node outputs on stderr or stdout so capture both\n else: # for Linux/Unix OS, commands is better to be a list.\n if is_string(commands):\n use_shell = True\n # https://docs.python.org/2/library/subprocess.html\n # Using shell=True can be a security hazard.\n elif isinstance(commands, list):\n # the executable path may be enclosed with quotes, if not windows, delete the quotes\n if commands[0][0] == commands[0][-1] == '\"' or \\\n commands[0][0] == commands[0][-1] == \"'\":\n commands[0] = commands[0][1:-1]\n for idx, v in enumerate(commands):\n if isinstance(v, int) or isinstance(v, float):\n # Fix :TypeError: execv() arg 2 must contain only strings\n commands[idx] = repr(v)\n print(commands)\n process = subprocess.Popen(commands, shell=use_shell, stdout=subprocess.PIPE,\n stdin=open(os.devnull),\n stderr=subprocess.STDOUT, universal_newlines=True,\n startupinfo=startupinfo,\n creationflags=subprocess_flags)\n out, err = process.communicate()\n recode = process.returncode\n\n if out is None:\n return ['']\n if recode is not None and recode != 0:\n raise subprocess.CalledProcessError(-1, commands,\n \"ERROR occurred when running subprocess!\")\n if '\\n' in out:\n return out.split('\\n')\n\n return [out]", "docstring": "Execute external command, and return the output lines list. In windows, refers to\n `handling-subprocess-crash-in-windows`_.\n\nArgs:\n commands: string or list\n\nReturns:\n output lines\n\n .. _handling-subprocess-crash-in-windows:\n https://stackoverflow.com/questions/5069224/handling-subprocess-crash-in-windows", "source": "juraj_google_style"} +{"code": "def to_string(self, ast_obj=None, fmt: str = \"medium\") -> str:\n\n\n if not ast_obj:\n ast_obj = self\n\n bel_relation = None\n if self.bel_relation and fmt == \"short\":\n bel_relation = self.spec[\"relations\"][\"to_short\"].get(\n self.bel_relation, self.bel_relation\n )\n elif self.bel_relation:\n bel_relation = self.spec[\"relations\"][\"to_long\"].get(\n self.bel_relation, self.bel_relation\n )\n\n if self.bel_subject and bel_relation and self.bel_object:\n if isinstance(self.bel_object, BELAst):\n return \"{} {} ({})\".format(\n self.bel_subject.to_string(fmt=fmt),\n bel_relation,\n self.bel_object.to_string(fmt=fmt),\n )\n else:\n return \"{} {} {}\".format(\n self.bel_subject.to_string(fmt=fmt),\n bel_relation,\n self.bel_object.to_string(fmt=fmt),\n )\n\n elif self.bel_subject:\n return \"{}\".format(self.bel_subject.to_string(fmt=fmt))\n\n else:\n return \"\"", "docstring": "Convert AST object to string\n\nArgs:\n fmt (str): short, medium, long formatted BEL statements\n short = short function and short relation format\n medium = short function and long relation format\n long = long function and long relation format\n canonicalize\n\nReturns:\n str: string version of BEL AST", "source": "juraj_google_style"} +{"code": "def _buckets(data, bucket_count=None):\n\n # TODO(nickfelt): remove on-demand imports once dep situation is fixed.\n import tensorflow.compat.v1 as tf\n if bucket_count is None:\n bucket_count = summary_v2.DEFAULT_BUCKET_COUNT\n with tf.name_scope('buckets', values=[data, bucket_count]), \\\n tf.control_dependencies([tf.assert_scalar(bucket_count),\n tf.assert_type(bucket_count, tf.int32)]):\n data = tf.reshape(data, shape=[-1]) # flatten\n data = tf.cast(data, tf.float64)\n is_empty = tf.equal(tf.size(input=data), 0)\n\n def when_empty():\n return tf.constant([], shape=(0, 3), dtype=tf.float64)\n\n def when_nonempty():\n min_ = tf.reduce_min(input_tensor=data)\n max_ = tf.reduce_max(input_tensor=data)\n range_ = max_ - min_\n is_singular = tf.equal(range_, 0)\n\n def when_nonsingular():\n bucket_width = range_ / tf.cast(bucket_count, tf.float64)\n offsets = data - min_\n bucket_indices = tf.cast(tf.floor(offsets / bucket_width),\n dtype=tf.int32)\n clamped_indices = tf.minimum(bucket_indices, bucket_count - 1)\n one_hots = tf.one_hot(clamped_indices, depth=bucket_count)\n bucket_counts = tf.cast(tf.reduce_sum(input_tensor=one_hots, axis=0),\n dtype=tf.float64)\n edges = tf.linspace(min_, max_, bucket_count + 1)\n left_edges = edges[:-1]\n right_edges = edges[1:]\n return tf.transpose(a=tf.stack(\n [left_edges, right_edges, bucket_counts]))\n\n def when_singular():\n center = min_\n bucket_starts = tf.stack([center - 0.5])\n bucket_ends = tf.stack([center + 0.5])\n bucket_counts = tf.stack([tf.cast(tf.size(input=data), tf.float64)])\n return tf.transpose(\n a=tf.stack([bucket_starts, bucket_ends, bucket_counts]))\n\n return tf.cond(is_singular, when_singular, when_nonsingular)\n\n return tf.cond(is_empty, when_empty, when_nonempty)", "docstring": "Create a TensorFlow op to group data into histogram buckets.\n\nArgs:\n data: A `Tensor` of any shape. Must be castable to `float64`.\n bucket_count: Optional positive `int` or scalar `int32` `Tensor`.\n\nReturns:\n A `Tensor` of shape `[k, 3]` and type `float64`. The `i`th row is\n a triple `[left_edge, right_edge, count]` for a single bucket.\n The value of `k` is either `bucket_count` or `1` or `0`.", "source": "juraj_google_style"} +{"code": "def _oai_to_xml(marc_oai): # TODO: move this to MARC XML parser?\n\n record = MARCXMLRecord(marc_oai)\n record.oai_marc = False\n\n return record.to_XML()", "docstring": "Convert OAI to MARC XML.\n\nArgs:\n marc_oai (str): String with either OAI or MARC XML.\n\nReturns:\n str: String with MARC XML.", "source": "juraj_google_style"} +{"code": "def read(self, size=None):\n\n if not self._is_open:\n raise IOError('Not opened.')\n\n if size is None:\n size = self._size - self._file_object.tell()\n\n return self._file_object.read(size)", "docstring": "Reads a byte string from the file-like object at the current offset.\n\n The function will read a byte string of the specified size or\n all of the remaining data if no size was specified.\n\nArgs:\n size (Optional[int]): number of bytes to read, where None is all\n remaining data.\n\nReturns:\n bytes: data read.\n\nRaises:\n IOError: if the read failed.\n OSError: if the read failed.", "source": "juraj_google_style"} +{"code": "def gradient_helper(optimizer, loss, var_list=None):\n\n if var_list is None:\n var_list = tf.compat.v1.trainable_variables()\n\n grads_and_vars = optimizer.compute_gradients(loss, var_list=var_list)\n grads = [pair[0] for pair in grads_and_vars]\n\n return grads, optimizer.apply_gradients(grads_and_vars)", "docstring": "A helper to get the gradients out at each step.\n\nArgs:\n optimizer: the optimizer op.\n loss: the op that computes your loss value.\n\n Returns: the gradient tensors and the train_step op.", "source": "juraj_google_style"} +{"code": "def _evolve(self, state, qargs=None):\n\n # If subsystem evolution we use the SuperOp representation\n if qargs is not None:\n return SuperOp(self)._evolve(state, qargs)\n\n # Otherwise we compute full evolution directly\n state = self._format_state(state)\n if state.shape[0] != self._input_dim:\n raise QiskitError(\n \"QuantumChannel input dimension is not equal to state dimension.\"\n )\n if state.ndim == 1 and self._data[1] is None and len(\n self._data[0]) == 1:\n # If we only have a single Kraus operator we can implement unitary-type\n # evolution of a state vector psi -> K[0].psi\n return np.dot(self._data[0][0], state)\n # Otherwise we always return a density matrix\n state = self._format_state(state, density_matrix=True)\n kraus_l, kraus_r = self._data\n if kraus_r is None:\n kraus_r = kraus_l\n return np.einsum('AiB,BC,AjC->ij', kraus_l, state,\n np.conjugate(kraus_r))", "docstring": "Evolve a quantum state by the QuantumChannel.\n\nArgs:\n state (QuantumState): The input statevector or density matrix.\n qargs (list): a list of QuantumState subsystem positions to apply\n the operator on.\n\nReturns:\n QuantumState: the output quantum state.\n\nRaises:\n QiskitError: if the operator dimension does not match the\n specified QuantumState subsystem dimensions.", "source": "juraj_google_style"} +{"code": "def _compute_nfp_real(l, u, counts, sizes):\n\n if l > u:\n raise ValueError(\"l must be less or equal to u\")\n return np.sum((float(sizes[u])-sizes[l:u+1])/float(sizes[u])*counts[l:u+1])", "docstring": "Computes the expected number of false positives caused by using\n u to approximate set sizes in the interval [l, u], using the real\n set size distribution.\n\nArgs:\n l: the lower bound on set sizes.\n u: the upper bound on set sizes.\n counts: the complete distribution of set sizes.\n sizes: the complete domain of set sizes.\n\n Return (float): the expected number of false positives.", "source": "juraj_google_style"} +{"code": "def get_problem_name(base_name, was_reversed=False, was_copy=False):\n\n if any(base_name.endswith(suffix) for suffix in (\"_rev\", \"_copy\")):\n raise ValueError(\"`base_name` cannot end in '_rev' or '_copy'\")\n name = base_name\n if was_copy:\n name = \"%s_copy\" % name\n if was_reversed:\n name = \"%s_rev\" % name\n return name", "docstring": "Construct a problem name from base and reversed/copy options.\n\n Inverse of `parse_problem_name`.\n\nArgs:\n base_name: base problem name. Should not end in \"_rev\" or \"_copy\"\n was_reversed: if the problem is to be reversed\n was_copy: if the problem is to be copied\n\nReturns:\n string name consistent with use with `parse_problem_name`.\n\nRaises:\n ValueError if `base_name` ends with \"_rev\" or \"_copy\"", "source": "juraj_google_style"} +{"code": "def _processing_limit(self, spec):\n\n processing_rate = float(spec.mapper.params.get(\"processing_rate\", 0))\n slice_processing_limit = -1\n if processing_rate > 0:\n slice_processing_limit = int(math.ceil(\n parameters.config._SLICE_DURATION_SEC*processing_rate/\n int(spec.mapper.shard_count)))\n return slice_processing_limit", "docstring": "Get the limit on the number of map calls allowed by this slice.\n\nArgs:\n spec: a Mapreduce spec.\n\nReturns:\n The limit as a positive int if specified by user. -1 otherwise.", "source": "juraj_google_style"} +{"code": "def __init__(self, campfire, data=None):\n\n super(CampfireEntity, self).__init__(data)\n self._campfire = campfire\n self._connection = None\n if self._campfire:\n self._connection = self._campfire.get_connection()", "docstring": "Initialize.\n\nArgs:\n campfire (:class:`Campfire`): Campfire Instance\n\n Kwargs:\n data (dict): Entity data", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.Alarm = channel.unary_unary(\n '/etcdserverpb.Maintenance/Alarm',\n request_serializer=rpc__pb2.AlarmRequest.SerializeToString,\n response_deserializer=rpc__pb2.AlarmResponse.FromString,\n )\n self.Status = channel.unary_unary(\n '/etcdserverpb.Maintenance/Status',\n request_serializer=rpc__pb2.StatusRequest.SerializeToString,\n response_deserializer=rpc__pb2.StatusResponse.FromString,\n )\n self.Defragment = channel.unary_unary(\n '/etcdserverpb.Maintenance/Defragment',\n request_serializer=rpc__pb2.DefragmentRequest.SerializeToString,\n response_deserializer=rpc__pb2.DefragmentResponse.FromString,\n )\n self.Hash = channel.unary_unary(\n '/etcdserverpb.Maintenance/Hash',\n request_serializer=rpc__pb2.HashRequest.SerializeToString,\n response_deserializer=rpc__pb2.HashResponse.FromString,\n )\n self.HashKV = channel.unary_unary(\n '/etcdserverpb.Maintenance/HashKV',\n request_serializer=rpc__pb2.HashKVRequest.SerializeToString,\n response_deserializer=rpc__pb2.HashKVResponse.FromString,\n )\n self.Snapshot = channel.unary_stream(\n '/etcdserverpb.Maintenance/Snapshot',\n request_serializer=rpc__pb2.SnapshotRequest.SerializeToString,\n response_deserializer=rpc__pb2.SnapshotResponse.FromString,\n )\n self.MoveLeader = channel.unary_unary(\n '/etcdserverpb.Maintenance/MoveLeader',\n request_serializer=rpc__pb2.MoveLeaderRequest.SerializeToString,\n response_deserializer=rpc__pb2.MoveLeaderResponse.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def playlist_create(\n\t\tself,\n\t\tname,\n\t\tdescription='',\n\t\t*,\n\t\tmake_public=False,\n\t\tsongs=None\n\t):\n\n\n\t\tshare_state = 'PUBLIC' if make_public else 'PRIVATE'\n\n\t\tplaylist = self._call(\n\t\t\tmc_calls.PlaylistsCreate,\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tshare_state\n\t\t).body\n\n\t\tif songs:\n\t\t\tplaylist = self.playlist_songs_add(songs, playlist)\n\n\t\treturn playlist", "docstring": "Create a playlist.\n\n Parameters:\n name (str): Name to give the playlist.\n description (str): Description to give the playlist.\n make_public (bool, Optional): If ``True`` and account has a subscription,\n make playlist public.\n Default: ``False``\n songs (list, Optional): A list of song dicts to add to the playlist.\n\nReturns:\n dict: Playlist information.", "source": "juraj_google_style"} +{"code": "def analyze_number(var, err=''):\n\n n, u = split_unit(var)\n if not isinstance(var, string_types):\n return (var, u)\n if is_color(var):\n return (var, 'color')\n if is_int(n):\n n = int(n)\n elif is_float(n):\n n = float(n)\n else:\n raise SyntaxError('%s ´%s´' % (err, var))\n return (n, u)", "docstring": "Analyse number for type and split from unit\n 1px -> (q, 'px')\n\nArgs:\n var (str): number string\n kwargs:\n err (str): Error message\n\nRaises:\n SyntaxError\n\nReturns:\n tuple", "source": "juraj_google_style"} +{"code": "def write_sudoers_entry(username=None, sudoers_entry=None):\n\n\n sudoers_path = '/etc/sudoers'\n rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)\n tmp_sudoers_path = '/tmp/sudoers_{0}'.format(rnd_chars)\n execute_command(\n shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), sudoers_path, tmp_sudoers_path))))\n execute_command(\n shlex.split(str('{0} chmod 777 {1}'.format(sudo_check(), tmp_sudoers_path))))\n with open(tmp_sudoers_path, mode=text_type('r')) as tmp_sudoers_file:\n sudoers_entries = tmp_sudoers_file.readlines()\n sudoers_output = list()\n for entry in sudoers_entries:\n if entry and not entry.startswith(username):\n sudoers_output.append(entry)\n if sudoers_entry:\n sudoers_output.append('{0} {1}'.format(username, sudoers_entry))\n sudoers_output.append('\\n')\n with open(tmp_sudoers_path, mode=text_type('w+')) as tmp_sudoers_file:\n tmp_sudoers_file.writelines(sudoers_output)\n sudoers_check_result = execute_command(\n shlex.split(str('{0} {1} -cf {2}'.format(sudo_check(), LINUX_CMD_VISUDO, tmp_sudoers_path))))\n if sudoers_check_result[1] > 0:\n raise ValueError(sudoers_check_result[0][1])\n execute_command(\n shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), tmp_sudoers_path, sudoers_path))))\n execute_command(shlex.split(str('{0} chown root:root {1}'.format(sudo_check(), sudoers_path))))\n execute_command(shlex.split(str('{0} chmod 440 {1}'.format(sudo_check(), sudoers_path))))\n execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_sudoers_path))))", "docstring": "Write sudoers entry.\n\nArgs:\n user (User): Instance of User containing sudoers entry.\n\nReturns:\n str: sudoers entry for the specified user.", "source": "juraj_google_style"} +{"code": "def record(self, rr_version):\n # type: (str) -> bytes\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('PX record not yet initialized!')\n\n outlist = [b'PX', struct.pack('=BBLLLLLLLL', RRPXRecord.length(rr_version),\n SU_ENTRY_VERSION, self.posix_file_mode,\n utils.swab_32bit(self.posix_file_mode),\n self.posix_file_links,\n utils.swab_32bit(self.posix_file_links),\n self.posix_user_id,\n utils.swab_32bit(self.posix_user_id),\n self.posix_group_id,\n utils.swab_32bit(self.posix_group_id))]\n if rr_version == '1.12':\n outlist.append(struct.pack('=LL', self.posix_serial_number,\n utils.swab_32bit(self.posix_serial_number)))\n # The rr_version can never be \"wrong\" at this point; if it was, it would\n # have thrown an exception earlier when calling length(). So just skip\n # any potential checks here.\n\n return b''.join(outlist)", "docstring": "Generate a string representing the Rock Ridge POSIX File Attributes\n record.\n\n Parameters:\n rr_version - The Rock Ridge version to use.\n\nReturns:\n String containing the Rock Ridge record.", "source": "juraj_google_style"} +{"code": "def AddProcessingOptions(self, argument_group):\n\n argument_group.add_argument(\n '--single_process', '--single-process', dest='single_process',\n action='store_true', default=False, help=(\n 'Indicate that the tool should run in a single process.'))\n\n argument_helper_names = ['temporary_directory', 'workers', 'zeromq']\n if self._CanEnforceProcessMemoryLimit():\n argument_helper_names.append('process_resources')\n helpers_manager.ArgumentHelperManager.AddCommandLineArguments(\n argument_group, names=argument_helper_names)", "docstring": "Adds the processing options to the argument group.\n\nArgs:\n argument_group (argparse._ArgumentGroup): argparse argument group.", "source": "juraj_google_style"} +{"code": "def Serialize(self, writer):\n\n super(AccountState, self).Serialize(writer)\n writer.WriteUInt160(self.ScriptHash)\n writer.WriteBool(self.IsFrozen)\n writer.WriteVarInt(len(self.Votes))\n for vote in self.Votes:\n writer.WriteBytes(vote)\n\n blen = len(self.Balances)\n writer.WriteVarInt(blen)\n\n for key, fixed8 in self.Balances.items():\n writer.WriteUInt256(key)\n writer.WriteFixed8(fixed8)", "docstring": "Serialize full object.\n\nArgs:\n writer (neo.IO.BinaryWriter):", "source": "juraj_google_style"} +{"code": "def from_config(config, **options):\n\n expected_args = ('prefix', 'realclass')\n for arg in expected_args:\n if arg not in options:\n msg = \"Required option missing: {0}\"\n raise rconfig.ConfigurationError(msg.format(arg))\n # Not logging unrecognized options here, because they might be used\n # by the real event store instantiated below.\n\n classpath = options['realclass']\n classpath_pieces = classpath.split('.')\n classname = classpath_pieces[-1]\n modulepath = '.'.join(classpath_pieces[0:-1])\n module = importlib.import_module(modulepath)\n estore_class = getattr(module, classname)\n\n return RotatedEventStore(lambda fname: estore_class(fname),\n options['path'], options['prefix'])", "docstring": "Instantiate an `RotatedEventStore` from config.\n\n Parameters:\n _config -- the configuration file options read from file(s).\n **options -- various options given to the specific event store. Shall\n not be used with this event store. Warning will be logged\n for every extra non-recognized option. The only required\n key to this function is 'path'.\n\n returns -- a newly instantiated `RotatedEventStore`.", "source": "juraj_google_style"} +{"code": "def _getFuncArgs(func):\n r\n code = func.func_code\n Defaults = func.func_defaults\n\n nargs = code.co_argcount\n ArgNames = code.co_varnames[:nargs]\n\n Args = OrderedDict()\n argCount = len(ArgNames)\n defCount = len(Defaults) if Defaults else 0\n diff = argCount - defCount\n\n for i in range(0, diff):\n Args[ArgNames[i]] = {}\n\n for i in range(diff, argCount):\n Args[ArgNames[i]] = {'default': Defaults[i - diff]}\n\n return Args", "docstring": "r\"\"\"Gives the details on the args of the given func.\n\nArgs:\n func (function): The function to get details on.", "source": "juraj_google_style"} +{"code": "def parse_transcripts(transcript_lines):\n\n LOG.info(\"Parsing transcripts\")\n # Parse the transcripts, we need to check if it is a request or a file handle\n if isinstance(transcript_lines, DataFrame):\n transcripts = parse_ensembl_transcript_request(transcript_lines)\n else:\n transcripts = parse_ensembl_transcripts(transcript_lines)\n\n # Since there can be multiple lines with information about the same transcript\n # we store transcript information in a dictionary for now\n parsed_transcripts = {}\n # Loop over the parsed transcripts\n for tx in transcripts:\n tx_id = tx['ensembl_transcript_id']\n ens_gene_id = tx['ensembl_gene_id']\n\n # Check if the transcript has been added\n # If not, create a new transcript\n if not tx_id in parsed_transcripts:\n tx_info = {\n 'chrom': tx['chrom'],\n 'transcript_start': tx['transcript_start'],\n 'transcript_end': tx['transcript_end'],\n 'mrna': set(),\n 'mrna_predicted': set(),\n 'nc_rna': set(),\n 'ensembl_gene_id': ens_gene_id,\n 'ensembl_transcript_id': tx_id,\n }\n parsed_transcripts[tx_id] = tx_info\n\n tx_info = parsed_transcripts[tx_id]\n # Add the ref seq information\n if tx.get('refseq_mrna_predicted'):\n tx_info['mrna_predicted'].add(tx['refseq_mrna_predicted'])\n if tx.get('refseq_mrna'):\n tx_info['mrna'].add(tx['refseq_mrna'])\n if tx.get('refseq_ncrna'):\n tx_info['nc_rna'].add(tx['refseq_ncrna'])\n\n return parsed_transcripts", "docstring": "Parse and massage the transcript information\n\n There could be multiple lines with information about the same transcript.\n This is why it is necessary to parse the transcripts first and then return a dictionary\n where all information has been merged.\n\nArgs:\n transcript_lines(): This could be an iterable with strings or a pandas.DataFrame\n\nReturns:\n parsed_transcripts(dict): Map from enstid -> transcript info", "source": "juraj_google_style"} +{"code": "def get_session_user(session_id, **kwargs):\n\n\n hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty\n validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'),\n type='file',\n cookie_expires=True,\n data_dir=config.get('COOKIES', 'DATA_DIR', '/tmp'),\n file_dir=config.get('COOKIES', 'FILE_DIR', '/tmp/auth'))\n\n hydra_session = hydra_session_object.get_by_id(session_id)\n\n if hydra_session is not None:\n return hydra_session['user_id']\n\n return None", "docstring": "Given a session ID, get the user ID that it is associated with\n\nArgs:\n session_id (string): The user's ID to identify the cookie to remove\n\nReturns:\n user_id (string) or None if the session does not exist", "source": "juraj_google_style"} +{"code": "def one_of(self, chset: str) -> str:\n\n res = self.peek()\n if res in chset:\n self.offset += 1\n return res\n raise UnexpectedInput(self, \"one of \" + chset)", "docstring": "Parse one character form the specified set.\n\nArgs:\n chset: string of characters to try as alternatives.\n\nReturns:\n The character that was actually matched.\n\nRaises:\n UnexpectedInput: If the next character is not in `chset`.", "source": "juraj_google_style"} +{"code": "def __getitem__(self, pkg_id):\n\n if pkg_id in self.__reg_software:\n return self.__reg_software[pkg_id]\n else:\n raise KeyError(pkg_id)", "docstring": "Returns information on a package.\n\nArgs:\n pkg_id (str): Package Id of the software/component\n\nReturns:\n dict or list: List if ``version_only`` is ``True`` otherwise dict", "source": "juraj_google_style"} +{"code": "def get_profiles(adapter, vcf_file):\n\n\n vcf = get_file_handle(vcf_file)\n individuals = vcf.samples\n profiles = {individual: [] for individual in individuals}\n\n for profile_variant in adapter.profile_variants():\n\n ref = profile_variant['ref']\n alt = profile_variant['alt']\n\n pos = profile_variant['pos']\n end = pos + 1\n chrom = profile_variant['chrom']\n\n region = f\"{chrom}:{pos}-{end}\"\n\n #Find variants in region\n\n found_variant = False\n for variant in vcf(region):\n\n variant_id = get_variant_id(variant)\n\n #If variant id i.e. chrom_pos_ref_alt matches\n if variant_id == profile_variant['_id']:\n found_variant = True\n #find genotype for each individual in vcf\n for i, individual in enumerate(individuals):\n\n genotype = GENOTYPE_MAP[variant.gt_types[i]]\n if genotype == 'hom_alt':\n gt_str = f\"{alt}{alt}\"\n elif genotype == 'het':\n gt_str = f\"{ref}{alt}\"\n else:\n gt_str = f\"{ref}{ref}\"\n\n #Append genotype to profile string of individual\n profiles[individual].append(gt_str)\n\n #Break loop if variant is found in region\n break\n\n #If no call was found for variant, give all samples a hom ref genotype\n if not found_variant:\n for individual in individuals: profiles[individual].append(f\"{ref}{ref}\")\n\n\n return profiles", "docstring": "Given a vcf, get a profile string for each sample in the vcf\n based on the profile variants in the database\n\nArgs:\n adapter(MongoAdapter): Adapter to mongodb\n vcf_file(str): Path to vcf file\n\nReturns:\n profiles (dict(str)): The profiles (given as strings) for each sample\n in vcf.", "source": "juraj_google_style"} +{"code": "def __init__(self, callback):\n\n self._callback = callback\n self._brocade_vswitch = brocade_vswitch(callback=pynos.utilities.return_xml)", "docstring": "Vcenter init function\n\nArgs:\n callback: Callback function that will be called for each action\n\nReturns:\n Vcenter Object\n\nRaises:\n None", "source": "juraj_google_style"} +{"code": "def import_gssapi_extension(name):\n\n\n try:\n path = 'gssapi.raw.ext_{0}'.format(name)\n __import__(path)\n return sys.modules[path]\n except ImportError:\n return None", "docstring": "Import a GSSAPI extension module\n\n This method imports a GSSAPI extension module based\n on the name of the extension (not including the\n 'ext_' prefix). If the extension is not available,\n the method retuns None.\n\nArgs:\n name (str): the name of the extension\n\nReturns:\n module: Either the extension module or None", "source": "juraj_google_style"} +{"code": "def get_metric_parsers(metric_packages=tuple(), include_defaults=True):\n\n metric_parsers = set()\n\n if include_defaults:\n import git_code_debt.metrics\n metric_parsers.update(discover(git_code_debt.metrics, is_metric_cls))\n\n for metric_package in metric_packages:\n metric_parsers.update(discover(metric_package, is_metric_cls))\n return metric_parsers", "docstring": "Gets all of the metric parsers.\n\nArgs:\n metric_packages - Defaults to no extra packages. An iterable of\n metric containing packages. A metric inherits DiffParserBase\n and does not have __metric__ = False\n A metric package must be imported using import a.b.c\n include_defaults - Whether to include the generic metric parsers", "source": "juraj_google_style"} +{"code": "def update_metadata(self, resource, keys_vals):\n\n self.metadata_service.set_auth(self._token_metadata)\n self.metadata_service.update(resource, keys_vals)", "docstring": "Updates key-value pairs with the given resource.\n\n Will attempt to update all key-value pairs even if some fail.\n Keys must already exist.\n\nArgs:\n resource (intern.resource.boss.BossResource)\n keys_vals (dictionary): Collection of key-value pairs to update on\n the given resource.\n\nRaises:\n HTTPErrorList on failure.", "source": "juraj_google_style"} +{"code": "def __find_variant(self, value):\n\n if isinstance(value, bool):\n return messages.Variant.BOOL\n elif isinstance(value, six.integer_types):\n return messages.Variant.INT64\n elif isinstance(value, float):\n return messages.Variant.DOUBLE\n elif isinstance(value, six.string_types):\n return messages.Variant.STRING\n elif isinstance(value, (list, tuple)):\n # Find the most specific variant that covers all elements.\n variant_priority = [None,\n messages.Variant.INT64,\n messages.Variant.DOUBLE,\n messages.Variant.STRING]\n chosen_priority = 0\n for v in value:\n variant = self.__find_variant(v)\n try:\n priority = variant_priority.index(variant)\n except IndexError:\n priority = -1\n if priority > chosen_priority:\n chosen_priority = priority\n return variant_priority[chosen_priority]\n # Unrecognized type.\n return None", "docstring": "Find the messages.Variant type that describes this value.\n\nArgs:\n value: The value whose variant type is being determined.\n\nReturns:\n The messages.Variant value that best describes value's type,\n or None if it's a type we don't know how to handle.", "source": "juraj_google_style"} +{"code": "def get_statuses(self, batch_ids):\n\n with self._lock:\n return {b: self.get_status(b) for b in batch_ids}", "docstring": "Returns a statuses dict for the requested batches.\n\nArgs:\n batch_ids (list of str): The ids of the batches to get statuses for\n\nReturns:\n dict: A dict with keys of batch ids, and values of status enums", "source": "juraj_google_style"} +{"code": "def _get_cached_response_from_django_cache(key):\n\n if TieredCache._should_force_django_cache_miss():\n return CachedResponse(is_found=False, key=key, value=None)\n\n cached_value = django_cache.get(key, _CACHE_MISS)\n is_found = cached_value is not _CACHE_MISS\n return CachedResponse(is_found, key, cached_value)", "docstring": "Retrieves a CachedResponse for the given key from the django cache.\n\n If the request was set to force cache misses, then this will always\n return a cache miss response.\n\nArgs:\n key (string)\n\nReturns:\n A CachedResponse with is_found status and value.", "source": "juraj_google_style"} +{"code": "def save_qasm(self,\n file_path: Union[str, bytes, int],\n header: Optional[str] = None,\n precision: int = 10,\n qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,\n ) -> None:\n\n self._to_qasm_output(header, precision, qubit_order).save(file_path)", "docstring": "Save a QASM file equivalent to the circuit.\n\nArgs:\n file_path: The location of the file where the qasm will be written.\n header: A multi-line string that is placed in a comment at the top\n of the QASM. Defaults to a cirq version specifier.\n precision: Number of digits to use when representing numbers.\n qubit_order: Determines how qubits are ordered in the QASM\n register.", "source": "juraj_google_style"} +{"code": "def predict(self, X, with_noise=True):\n\n m, v = self._predict(X, False, with_noise)\n # We can take the square root because v is just a diagonal matrix of variances\n return m, np.sqrt(v)", "docstring": "Predictions with the model. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given.\n\n Parameters:\n X (np.ndarray) - points to run the prediction for.\n with_noise (bool) - whether to add noise to the prediction. Default is True.", "source": "juraj_google_style"} +{"code": "def transform(self, col):\n\n\n out = pd.DataFrame(index=col.index)\n out[self.col_name] = col.apply(self.get_val, axis=1)\n\n if self.subtype == 'int':\n out[self.col_name] = out[self.col_name].astype(int)\n\n return out", "docstring": "Prepare the transformer to convert data and return the processed table.\n\nArgs:\n col(pandas.DataFrame): Data to transform.\n\nReturns:\n pandas.DataFrame", "source": "juraj_google_style"} +{"code": "def validate_file(fn, options=None):\n\n file_results = FileValidationResults(filepath=fn)\n output.info(\"Performing JSON schema validation on %s\" % fn)\n\n if not options:\n options = ValidationOptions(files=fn)\n\n try:\n with open(fn) as instance_file:\n file_results.object_results = validate(instance_file, options)\n\n except Exception as ex:\n if 'Expecting value' in str(ex):\n line_no = str(ex).split()[3]\n file_results.fatal = ValidationErrorResults(\n 'Invalid JSON input on line %s' % line_no\n )\n else:\n file_results.fatal = ValidationErrorResults(ex)\n\n msg = (\"Unexpected error occurred with file '{fn}'. No further \"\n \"validation will be performed: {error}\")\n output.info(msg.format(fn=fn, error=str(ex)))\n\n file_results.is_valid = (all(object_result.is_valid\n for object_result in file_results.object_results)\n and not file_results.fatal)\n\n return file_results", "docstring": "Validate the input document `fn` according to the options passed in.\n\n If any exceptions are raised during validation, no further validation\n will take place.\n\nArgs:\n fn: The filename of the JSON file to be validated.\n options: An instance of ``ValidationOptions``.\n\nReturns:\n An instance of FileValidationResults.", "source": "juraj_google_style"} +{"code": "def update_vmss(access_token, subscription_id, resource_group, vmss_name, body):\n\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourceGroups/', resource_group,\n '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name,\n '?api-version=', COMP_API])\n return do_put(endpoint, body, access_token)", "docstring": "Update a VMSS with a new JSON body. E.g. do a GET, change something, call this.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n resource_group (str): Azure resource group name.\n vm_name (str): Name of the virtual machine.\n body (dict): JSON body of the VM scale set.\n\nReturns:\n HTTP response.", "source": "juraj_google_style"} +{"code": "def noisy_moments(self, moments: 'Iterable[cirq.Moment]',\n system_qubits: Sequence['cirq.Qid']\n ) -> Sequence['cirq.OP_TREE']:\n\n if not hasattr(self.noisy_moment, '_not_overridden'):\n result = []\n for moment in moments:\n result.append(self.noisy_moment(moment, system_qubits))\n return result\n\n if not hasattr(self.noisy_operation, '_not_overridden'):\n result = []\n for moment in moments:\n result.append([self.noisy_operation(op) for op in moment])\n return result\n\n assert False, 'Should be unreachable.'", "docstring": "Adds possibly stateful noise to a series of moments.\n\nArgs:\n moments: The moments to add noise to.\n system_qubits: A list of all qubits in the system.\n\nReturns:\n A sequence of OP_TREEs, with the k'th tree corresponding to the\n noisy operations for the k'th moment.", "source": "juraj_google_style"} +{"code": "def consume(self, message):\n\n if 'jsonrpc' not in message or message['jsonrpc'] != JSONRPC_VERSION:\n log.warn(\"Unknown message type %s\", message)\n return\n\n if 'id' not in message:\n log.debug(\"Handling notification from client %s\", message)\n self._handle_notification(message['method'], message.get('params'))\n elif 'method' not in message:\n log.debug(\"Handling response from client %s\", message)\n self._handle_response(message['id'], message.get('result'), message.get('error'))\n else:\n try:\n log.debug(\"Handling request from client %s\", message)\n self._handle_request(message['id'], message['method'], message.get('params'))\n except JsonRpcException as e:\n log.exception(\"Failed to handle request %s\", message['id'])\n self._consumer({\n 'jsonrpc': JSONRPC_VERSION,\n 'id': message['id'],\n 'error': e.to_dict()\n })\n except Exception: # pylint: disable=broad-except\n log.exception(\"Failed to handle request %s\", message['id'])\n self._consumer({\n 'jsonrpc': JSONRPC_VERSION,\n 'id': message['id'],\n 'error': JsonRpcInternalError.of(sys.exc_info()).to_dict()\n })", "docstring": "Consume a JSON RPC message from the client.\n\nArgs:\n message (dict): The JSON RPC message sent by the client", "source": "juraj_google_style"} +{"code": "def git_ls_remote(self, uri, ref):\n\n logger.debug(\"Invoking git to retrieve commit id for repo %s...\", uri)\n lsremote_output = subprocess.check_output(['git',\n 'ls-remote',\n uri,\n ref])\n if b\"\\t\" in lsremote_output:\n commit_id = lsremote_output.split(b\"\\t\")[0]\n logger.debug(\"Matching commit id found: %s\", commit_id)\n return commit_id\n else:\n raise ValueError(\"Ref \\\"%s\\\" not found for repo %s.\" % (ref, uri))", "docstring": "Determine the latest commit id for a given ref.\n\nArgs:\n uri (string): git URI\n ref (string): git ref\n\nReturns:\n str: A commit id", "source": "juraj_google_style"} +{"code": "def cleanup_mprocess(config_path, cfg):\n\n for key in ('keyFile', 'logPath', 'dbpath'):\n remove_path(cfg.get(key, None))\n isinstance(config_path, str) and os.path.exists(config_path) and remove_path(config_path)", "docstring": "remove all process's stuff\n\nArgs:\n config_path - process's options file\n cfg - process's config", "source": "juraj_google_style"} +{"code": "def sg_max(tensor, opt):\n r\n return tf.reduce_max(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)", "docstring": "r\"\"\"Computes the maximum of elements across axis of a tensor.\n\n See `tf.reduce_max()` in tensorflow.\n\nArgs:\n tensor: A `Tensor` (automatically given by chain).\n opt:\n axis : A tuple/list of integers or an integer. The axis to reduce.\n keep_dims: If true, retains reduced dimensions with length 1.\n name: If provided, replace current tensor's name.\n\nReturns:\n A `Tensor`.", "source": "juraj_google_style"} +{"code": "def priceTarget(symbol, token='', version=''):\n\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/price-target', token, version)", "docstring": "Provides the latest avg, high, and low analyst price target for a symbol.\n\n https://iexcloud.io/docs/api/#price-target\n Updates at 10am, 11am, 12pm UTC every day\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n dict: result", "source": "juraj_google_style"} +{"code": "def compare_song_collections(src_songs, dst_songs):\n\n\n\tdef gather_field_values(song):\n\t\treturn tuple((_normalize_metadata(song[field]) for field in _filter_comparison_fields(song)))\n\n\tdst_songs_criteria = {gather_field_values(_normalize_song(dst_song)) for dst_song in dst_songs}\n\n\treturn [src_song for src_song in src_songs if gather_field_values(_normalize_song(src_song)) not in dst_songs_criteria]", "docstring": "Compare two song collections to find missing songs.\n\n Parameters:\n src_songs (list): Google Music song dicts or filepaths of local songs.\n\n dest_songs (list): Google Music song dicts or filepaths of local songs.\n\nReturns:\n A list of Google Music song dicts or local song filepaths from source missing in destination.", "source": "juraj_google_style"} +{"code": "def __init__(self, entries, working_ion_entry):\n\n self._entries = entries\n self._working_ion = working_ion_entry.composition.elements[0]\n self._working_ion_entry = working_ion_entry\n\n # Prepare to make phase diagram: determine elements and set their energy\n # to be very high\n elements = set()\n for entry in entries:\n elements.update(entry.composition.elements)\n\n # Set an artificial energy for each element for convex hull generation\n element_energy = max([entry.energy_per_atom for entry in entries]) + 10\n\n pdentries = []\n pdentries.extend(entries)\n pdentries.extend([PDEntry(Composition({el: 1}), element_energy)\n for el in elements])\n\n # Make phase diagram to determine which entries are stable vs. unstable\n pd = PhaseDiagram(pdentries)\n\n lifrac = lambda e: e.composition.get_atomic_fraction(self._working_ion)\n\n # stable entries ordered by amount of Li asc\n self._stable_entries = tuple(sorted([e for e in pd.stable_entries\n if e in entries], key=lifrac))\n\n # unstable entries ordered by amount of Li asc\n self._unstable_entries = tuple(sorted([e for e in pd.unstable_entries\n if e in entries], key=lifrac))\n\n # create voltage pairs\n self._vpairs = tuple([InsertionVoltagePair(self._stable_entries[i],\n self._stable_entries[i + 1],\n working_ion_entry)\n for i in range(len(self._stable_entries) - 1)])", "docstring": "Create a new InsertionElectrode.\n\nArgs:\n entries: A list of ComputedStructureEntries (or subclasses)\n representing the different topotactic states of the battery,\n e.g. TiO2 and LiTiO2.\n working_ion_entry: A single ComputedEntry or PDEntry\n representing the element that carries charge across the\n battery, e.g. Li.", "source": "juraj_google_style"} +{"code": "def notify_rollover(self, stream):\n\n\n self.offset -= 1\n\n if not self.matches(stream):\n return\n\n if self._count == 0:\n raise InternalError(\"BufferedStreamWalker out of sync with storage engine, count was wrong.\")\n\n self._count -= 1", "docstring": "Notify that a reading in the given stream was overwritten.\n\nArgs:\n stream (DataStream): The stream that had overwritten data.", "source": "juraj_google_style"} +{"code": "def dumps(ms, single=False, pretty_print=False, **kwargs):\n\n if single:\n ms = [ms]\n return serialize(ms, pretty_print=pretty_print, **kwargs)", "docstring": "Serialize an Xmrs object to the Prolog representation\n\nArgs:\n ms: an iterator of Xmrs objects to serialize (unless the\n *single* option is `True`)\n single: if `True`, treat *ms* as a single Xmrs object instead\n of as an iterator\n pretty_print: if `True`, add newlines and indentation\n\nReturns:\n the Prolog string representation of a corpus of Xmrs", "source": "juraj_google_style"} +{"code": "def _ReadFileEntry(self, file_object, file_offset):\n\n if self.file_format == 'bin-big-endian':\n data_type_map = self._CPIO_BINARY_BIG_ENDIAN_FILE_ENTRY\n file_entry_data_size = self._CPIO_BINARY_BIG_ENDIAN_FILE_ENTRY_SIZE\n elif self.file_format == 'bin-little-endian':\n data_type_map = self._CPIO_BINARY_LITTLE_ENDIAN_FILE_ENTRY\n file_entry_data_size = self._CPIO_BINARY_LITTLE_ENDIAN_FILE_ENTRY_SIZE\n elif self.file_format == 'odc':\n data_type_map = self._CPIO_PORTABLE_ASCII_FILE_ENTRY\n file_entry_data_size = self._CPIO_PORTABLE_ASCII_FILE_ENTRY_SIZE\n elif self.file_format in ('crc', 'newc'):\n data_type_map = self._CPIO_NEW_ASCII_FILE_ENTRY\n file_entry_data_size = self._CPIO_NEW_ASCII_FILE_ENTRY_SIZE\n\n file_entry = self._ReadStructure(\n file_object, file_offset, file_entry_data_size, data_type_map,\n 'file entry')\n\n file_offset += file_entry_data_size\n\n if self.file_format in ('bin-big-endian', 'bin-little-endian'):\n file_entry.modification_time = (\n (file_entry.modification_time.upper << 16) |\n file_entry.modification_time.lower)\n\n file_entry.file_size = (\n (file_entry.file_size.upper << 16) | file_entry.file_size.lower)\n\n if self.file_format == 'odc':\n for attribute_name in self._CPIO_ATTRIBUTE_NAMES_ODC:\n value = getattr(file_entry, attribute_name, None)\n try:\n value = int(value, 8)\n except ValueError:\n raise errors.FileFormatError(\n 'Unable to convert attribute: {0:s} into an integer'.format(\n attribute_name))\n\n value = setattr(file_entry, attribute_name, value)\n\n elif self.file_format in ('crc', 'newc'):\n for attribute_name in self._CPIO_ATTRIBUTE_NAMES_CRC:\n value = getattr(file_entry, attribute_name, None)\n try:\n value = int(value, 16)\n except ValueError:\n raise errors.FileFormatError(\n 'Unable to convert attribute: {0:s} into an integer'.format(\n attribute_name))\n\n value = setattr(file_entry, attribute_name, value)\n\n path_data = file_object.read(file_entry.path_size)\n\n file_offset += file_entry.path_size\n\n # TODO: should this be ASCII?\n path = path_data.decode('ascii')\n path, _, _ = path.partition('\\x00')\n\n if self.file_format in ('bin-big-endian', 'bin-little-endian'):\n padding_size = file_offset % 2\n if padding_size > 0:\n padding_size = 2 - padding_size\n\n elif self.file_format == 'odc':\n padding_size = 0\n\n elif self.file_format in ('crc', 'newc'):\n padding_size = file_offset % 4\n if padding_size > 0:\n padding_size = 4 - padding_size\n\n file_offset += padding_size\n\n archive_file_entry = CPIOArchiveFileEntry()\n\n archive_file_entry.data_offset = file_offset\n archive_file_entry.data_size = file_entry.file_size\n archive_file_entry.group_identifier = file_entry.group_identifier\n archive_file_entry.inode_number = file_entry.inode_number\n archive_file_entry.modification_time = file_entry.modification_time\n archive_file_entry.path = path\n archive_file_entry.mode = file_entry.mode\n archive_file_entry.size = (\n file_entry_data_size + file_entry.path_size + padding_size +\n file_entry.file_size)\n archive_file_entry.user_identifier = file_entry.user_identifier\n\n file_offset += file_entry.file_size\n\n if self.file_format in ('bin-big-endian', 'bin-little-endian'):\n padding_size = file_offset % 2\n if padding_size > 0:\n padding_size = 2 - padding_size\n\n elif self.file_format == 'odc':\n padding_size = 0\n\n elif self.file_format in ('crc', 'newc'):\n padding_size = file_offset % 4\n if padding_size > 0:\n padding_size = 4 - padding_size\n\n if padding_size > 0:\n archive_file_entry.size += padding_size\n\n return archive_file_entry", "docstring": "Reads a file entry.\n\nArgs:\n file_object (FileIO): file-like object.\n file_offset (int): offset of the data relative from the start of\n the file-like object.\n\nReturns:\n CPIOArchiveFileEntry: a file entry.\n\nRaises:\n FileFormatError: if the file entry cannot be read.", "source": "juraj_google_style"} +{"code": "def strip_quotes(self, content):\n\n error_msg = \"Following rule is badly quoted: {}\"\n if (content.startswith('\"') and content.endswith('\"')) or \\\n (content.startswith(\"'\") and content.endswith(\"'\")):\n return content[1:-1]\n # Quote starting but not ended\n elif (content.startswith('\"') and not content.endswith('\"')) or \\\n (content.startswith(\"'\") and not content.endswith(\"'\")):\n raise InvalidImportRule(error_msg.format(content))\n # Quote ending but not started\n elif (not content.startswith('\"') and content.endswith('\"')) or \\\n (not content.startswith(\"'\") and content.endswith(\"'\")):\n raise InvalidImportRule(error_msg.format(content))\n\n return content", "docstring": "Unquote given rule.\n\nArgs:\n content (str): An import rule.\n\nRaises:\n InvalidImportRule: Raise exception if the rule is badly quoted\n (not started or not ended quotes).\n\nReturns:\n string: The given rule unquoted.", "source": "juraj_google_style"} +{"code": "def remove(self, x):\n\n with tf.name_scope(\"pad_reduce/remove\"):\n x_shape = x.get_shape().as_list()\n x = tf.gather_nd(\n x,\n indices=self.nonpad_ids,\n )\n if not tf.executing_eagerly():\n # This is a hack but for some reason, gather_nd return a tensor of\n # undefined shape, so the shape is set up manually\n x.set_shape([None] + x_shape[1:])\n return x", "docstring": "Remove padding from the given tensor.\n\nArgs:\n x (tf.Tensor): of shape [dim_origin,...]\n\nReturns:\n a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin", "source": "juraj_google_style"} +{"code": "def update_headers(self, headers):\n\n check_type(headers, dict, may_be_none=False)\n self._req_session.headers.update(headers)", "docstring": "Update the HTTP headers used for requests in this session.\n\n Note: Updates provided by the dictionary passed as the `headers`\n parameter to this method are merged into the session headers by adding\n new key-value pairs and/or updating the values of existing keys. The\n session headers are not replaced by the provided dictionary.\n\nArgs:\n headers(dict): Updates to the current session headers.", "source": "juraj_google_style"} +{"code": "def read(self, vals):\n\n i = 0\n if len(vals[i]) == 0:\n self.leapyear_observed = None\n else:\n self.leapyear_observed = vals[i]\n i += 1\n if len(vals[i]) == 0:\n self.daylight_saving_start_day = None\n else:\n self.daylight_saving_start_day = vals[i]\n i += 1\n if len(vals[i]) == 0:\n self.daylight_saving_end_day = None\n else:\n self.daylight_saving_end_day = vals[i]\n i += 1\n count = int(vals[i])\n i += 1\n for _ in range(count):\n obj = Holiday()\n obj.read(vals[i:i + obj.field_count])\n self.add_holiday(obj)\n i += obj.field_count", "docstring": "Read values.\n\nArgs:\n vals (list): list of strings representing values", "source": "juraj_google_style"} +{"code": "def __init__(self, file_path_regex=None, log_format_regex=None, top_dir=None):\n\n if file_path_regex is not None:\n self.file_path_regex = file_path_regex\n if log_format_regex is not None:\n self.log_format_regex = log_format_regex\n if top_dir is not None:\n self.top_dir = top_dir\n self._content = None", "docstring": "Init method.\n\nArgs:\n file_path_regex (regex): the regex to find the log files.\n log_format_regex (regex): the regex to parse the log files.\n top_dir (str): the path to the root directory containing the logs.", "source": "juraj_google_style"} +{"code": "def make_tpot_pmml_config(config, user_classpath = []):\n\n\ttpot_keys = set(config.keys())\n\tclasses = _supported_classes(user_classpath)\n\tpmml_keys = (set(classes)).union(set([_strip_module(class_) for class_ in classes]))\n\treturn { key : config[key] for key in (tpot_keys).intersection(pmml_keys)}", "docstring": "Translates a regular TPOT configuration to a PMML-compatible TPOT configuration.\n\n Parameters:\n ----------\n obj: config\n The configuration dictionary.\n\n user_classpath: list of strings, optional\n The paths to JAR files that provide custom Transformer, Selector and/or Estimator converter classes.\n The JPMML-SkLearn classpath is constructed by appending user JAR files to package JAR files.", "source": "juraj_google_style"} +{"code": "def Unzip(iterable):\n\n lefts = []\n rights = []\n\n for left, right in iterable:\n lefts.append(left)\n rights.append(right)\n\n return lefts, rights", "docstring": "Unzips specified iterable of pairs to pair of two iterables.\n\n This function is an inversion of the standard `zip` function and the following\n hold:\n\n * ∀ l, r. l, r == unzip(zip(l, r))\n * ∀ p. p == zip(unzip(p))\n\nExample:\n >>> Unzip([(\"foo\", 1), (\"bar\", 2), (\"baz\", 3)])\n ([\"foo\", \"bar\", \"baz\"], [1, 2, 3])\n\nArgs:\n iterable: An iterable of pairs to unzip.\n\nReturns:\n A pair of iterables after unzipping.", "source": "juraj_google_style"} +{"code": "def first(series, order_by=None):\n\n\n if order_by is not None:\n series = order_series_by(series, order_by)\n first_s = series.iloc[0]\n return first_s", "docstring": "Returns the first value of a series.\n\nArgs:\n series (pandas.Series): column to summarize.\n\n Kwargs:\n order_by: a pandas.Series or list of series (can be symbolic) to order\n the input series by before summarization.", "source": "juraj_google_style"} +{"code": "def create(cls, endpoint_name, json_body, original_response):\n\n\n if endpoint_name == \"property/value_report\":\n return ValueReportResponse(endpoint_name, json_body, original_response)\n\n if endpoint_name == \"property/rental_report\":\n return RentalReportResponse(endpoint_name, json_body, original_response)\n\n prefix = endpoint_name.split(\"/\")[0]\n\n if prefix == \"block\":\n return BlockResponse(endpoint_name, json_body, original_response)\n\n if prefix == \"zip\":\n return ZipCodeResponse(endpoint_name, json_body, original_response)\n\n if prefix == \"msa\":\n return MsaResponse(endpoint_name, json_body, original_response)\n\n return PropertyResponse(endpoint_name, json_body, original_response)", "docstring": "Factory for creating the correct type of Response based on the data.\n\nArgs:\n endpoint_name (str) - The endpoint of the request, such as \"property/value\"\n json_body - The response body in json format.\n original_response (response object) - server response returned from an http request.", "source": "juraj_google_style"} +{"code": "def LockedWrite(self, cache_data):\n\n if isinstance(cache_data, six.text_type):\n cache_data = cache_data.encode(encoding=self._encoding)\n\n with self._thread_lock:\n if not self._EnsureFileExists():\n return False\n with self._process_lock_getter() as acquired_plock:\n if not acquired_plock:\n return False\n with open(self._filename, 'wb') as f:\n f.write(cache_data)\n return True", "docstring": "Acquire an interprocess lock and write a string.\n\n This method safely acquires the locks then writes a string\n to the cache file. If the string is written successfully\n the function will return True, if the write fails for any\n reason it will return False.\n\nArgs:\n cache_data: string or bytes to write.\n\nReturns:\n bool: success", "source": "juraj_google_style"} +{"code": "def copy2(src, dst, metadata=None, retry_params=None):\n\n common.validate_file_path(src)\n common.validate_file_path(dst)\n\n if metadata is None:\n metadata = {}\n copy_meta = 'COPY'\n else:\n copy_meta = 'REPLACE'\n metadata.update({'x-goog-copy-source': src,\n 'x-goog-metadata-directive': copy_meta})\n\n api = storage_api._get_storage_api(retry_params=retry_params)\n status, resp_headers, content = api.put_object(\n api_utils._quote_filename(dst), headers=metadata)\n errors.check_status(status, [200], src, metadata, resp_headers, body=content)", "docstring": "Copy the file content from src to dst.\n\nArgs:\n src: /bucket/filename\n dst: /bucket/filename\n metadata: a dict of metadata for this copy. If None, old metadata is copied.\n For example, {'x-goog-meta-foo': 'bar'}.\n retry_params: An api_utils.RetryParams for this call to GCS. If None,\n the default one is used.\n\nRaises:\n errors.AuthorizationError: if authorization failed.\n errors.NotFoundError: if an object that's expected to exist doesn't.", "source": "juraj_google_style"} +{"code": "def __call__(self, index, graph):\n\n count = 0\n for c in self.criteria:\n if c(index, graph):\n count += 1\n return (count % 2) == 1", "docstring": "Evaluates all the criteria and applies a generalized XOR opartion\n\nArgs:\n | ``index`` -- the index of the vertex/edge on which the criterion\n is applied\n | ``graph`` -- the graph on which the criterion is tested\n\n when the XOR operation is applied to more than two criteria, True\n is only returned when an odd number of criteria return True.", "source": "juraj_google_style"} +{"code": "def __init__(self, output_mediator):\n\n super(LinearOutputModule, self).__init__(output_mediator)\n self._output_writer = None", "docstring": "Initializes a linear output module.\n\nArgs:\n output_mediator (OutputMediator): mediates interactions between output\n modules and other components, such as storage and dfvfs.\n\nRaises:\n ValueError: if the output writer is missing.", "source": "juraj_google_style"} +{"code": "def add_ssa_ir(function, all_state_variables_instances):\n\n\n if not function.is_implemented:\n return\n\n init_definition = dict()\n for v in function.parameters:\n if v.name:\n init_definition[v.name] = (v, function.entry_point)\n function.entry_point.add_ssa_ir(Phi(LocalIRVariable(v), set()))\n\n for v in function.returns:\n if v.name:\n init_definition[v.name] = (v, function.entry_point)\n\n # We only add phi function for state variable at entry node if\n # The state variable is used\n # And if the state variables is written in another function (otherwise its stay at index 0)\n for (_, variable_instance) in all_state_variables_instances.items():\n if is_used_later(function.entry_point, variable_instance):\n # rvalues are fixed in solc_parsing.declaration.function\n function.entry_point.add_ssa_ir(Phi(StateIRVariable(variable_instance), set()))\n\n add_phi_origins(function.entry_point, init_definition, dict())\n\n\n for node in function.nodes:\n for (variable, nodes) in node.phi_origins_local_variables.values():\n if len(nodes)<2:\n continue\n if not is_used_later(node, variable):\n continue\n node.add_ssa_ir(Phi(LocalIRVariable(variable), nodes))\n for (variable, nodes) in node.phi_origins_state_variables.values():\n if len(nodes)<2:\n continue\n #if not is_used_later(node, variable.name, []):\n # continue\n node.add_ssa_ir(Phi(StateIRVariable(variable), nodes))\n\n init_local_variables_instances = dict()\n for v in function.parameters:\n if v.name:\n new_var = LocalIRVariable(v)\n function.add_parameter_ssa(new_var)\n if new_var.is_storage:\n fake_variable = LocalIRVariable(v)\n fake_variable.name = 'STORAGE_'+fake_variable.name\n fake_variable.set_location('reference_to_storage')\n new_var.refers_to = {fake_variable}\n init_local_variables_instances[fake_variable.name] = fake_variable\n init_local_variables_instances[v.name] = new_var\n\n for v in function.returns:\n if v.name:\n new_var = LocalIRVariable(v)\n function.add_return_ssa(new_var)\n if new_var.is_storage:\n fake_variable = LocalIRVariable(v)\n fake_variable.name = 'STORAGE_'+fake_variable.name\n fake_variable.set_location('reference_to_storage')\n new_var.refers_to = {fake_variable}\n init_local_variables_instances[fake_variable.name] = fake_variable\n init_local_variables_instances[v.name] = new_var\n\n all_init_local_variables_instances = dict(init_local_variables_instances)\n\n init_state_variables_instances = dict(all_state_variables_instances)\n\n initiate_all_local_variables_instances(function.nodes, init_local_variables_instances, all_init_local_variables_instances)\n\n generate_ssa_irs(function.entry_point,\n dict(init_local_variables_instances),\n all_init_local_variables_instances,\n dict(init_state_variables_instances),\n all_state_variables_instances,\n init_local_variables_instances,\n [])\n\n fix_phi_rvalues_and_storage_ref(function.entry_point,\n dict(init_local_variables_instances),\n all_init_local_variables_instances,\n dict(init_state_variables_instances),\n all_state_variables_instances,\n init_local_variables_instances)", "docstring": "Add SSA version of the IR\n\nArgs:\n function\n all_state_variables_instances", "source": "juraj_google_style"} +{"code": "def mnist_model(image, labels, mesh):\n\n batch_dim = mtf.Dimension(\"batch\", FLAGS.batch_size)\n row_blocks_dim = mtf.Dimension(\"row_blocks\", 4)\n col_blocks_dim = mtf.Dimension(\"col_blocks\", 4)\n rows_dim = mtf.Dimension(\"rows_size\", 7)\n cols_dim = mtf.Dimension(\"cols_size\", 7)\n\n classes_dim = mtf.Dimension(\"classes\", 10)\n one_channel_dim = mtf.Dimension(\"one_channel\", 1)\n\n x = mtf.import_tf_tensor(\n mesh, tf.reshape(image, [FLAGS.batch_size, 4, 7, 4, 7, 1]),\n mtf.Shape(\n [batch_dim, row_blocks_dim, rows_dim,\n col_blocks_dim, cols_dim, one_channel_dim]))\n x = mtf.transpose(x, [\n batch_dim, row_blocks_dim, col_blocks_dim,\n rows_dim, cols_dim, one_channel_dim])\n\n # add some convolutional layers to demonstrate that convolution works.\n fh_dim = mtf.Dimension(\"fh\", 9)\n fw_dim = mtf.Dimension(\"fw\", 9)\n filters1_dim = mtf.Dimension(\"filters1\", 16)\n filters2_dim = mtf.Dimension(\"filters2\", 16)\n kernel1 = mtf.get_variable(\n mesh, \"kernel1\", [fh_dim, fw_dim, one_channel_dim, filters1_dim])\n kernel2 = mtf.get_variable(\n mesh, \"kernel2\", [fh_dim, fw_dim, filters1_dim, filters2_dim])\n\n f1 = mtf.relu(mtf.conv2d_with_blocks(\n x, kernel1, strides=[1, 1, 1, 1], padding=\"SAME\",\n h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim))\n f2 = mtf.relu(mtf.conv2d_with_blocks(\n f1, kernel2, strides=[1, 1, 1, 1], padding=\"SAME\",\n h_blocks_dim=row_blocks_dim, w_blocks_dim=col_blocks_dim))\n x = mtf.reduce_mean(f2, reduced_dim=filters2_dim)\n\n # add some fully-connected dense layers.\n hidden_dim1 = mtf.Dimension(\"hidden1\", FLAGS.hidden_size)\n hidden_dim2 = mtf.Dimension(\"hidden2\", FLAGS.hidden_size)\n\n h1 = mtf.layers.dense(\n x, hidden_dim1,\n reduced_dims=x.shape.dims[-4:],\n activation=mtf.relu, name=\"hidden1\")\n h2 = mtf.layers.dense(\n h1, hidden_dim2,\n activation=mtf.relu, name=\"hidden2\")\n logits = mtf.layers.dense(h2, classes_dim, name=\"logits\")\n if labels is None:\n loss = None\n else:\n labels = mtf.import_tf_tensor(\n mesh, tf.reshape(labels, [FLAGS.batch_size]), mtf.Shape([batch_dim]))\n loss = mtf.layers.softmax_cross_entropy_with_logits(\n logits, mtf.one_hot(labels, classes_dim), classes_dim)\n loss = mtf.reduce_mean(loss)\n return logits, loss", "docstring": "The model.\n\nArgs:\n image: tf.Tensor with shape [batch, 28*28]\n labels: a tf.Tensor with shape [batch] and dtype tf.int32\n mesh: a mtf.Mesh\n\nReturns:\n logits: a mtf.Tensor with shape [batch, 10]\n loss: a mtf.Tensor with shape []", "source": "juraj_google_style"} +{"code": "def mix_over_posterior_draws(means, variances):\n\n # The inputs `means`, `variances` have shape\n # `concat([\n # [num_posterior_draws],\n # sample_shape,\n # batch_shape,\n # [num_timesteps]])`\n # Because MixtureSameFamily mixes over the rightmost batch dimension,\n # we need to move the `num_posterior_draws` dimension to be rightmost\n # in the batch shape. This requires use of `Independent` (to preserve\n # `num_timesteps` as part of the event shape) and `move_dimension`.\n # TODO(b/120245392): enhance `MixtureSameFamily` to reduce along an\n # arbitrary axis, and eliminate `move_dimension` calls here.\n\n with tf.compat.v1.name_scope(\n 'mix_over_posterior_draws', values=[means, variances]):\n num_posterior_draws = dist_util.prefer_static_value(\n tf.shape(input=means))[0]\n\n component_observations = tfd.Independent(\n distribution=tfd.Normal(\n loc=dist_util.move_dimension(means, 0, -2),\n scale=tf.sqrt(dist_util.move_dimension(variances, 0, -2))),\n reinterpreted_batch_ndims=1)\n\n return tfd.MixtureSameFamily(\n mixture_distribution=tfd.Categorical(\n logits=tf.zeros([num_posterior_draws],\n dtype=component_observations.dtype)),\n components_distribution=component_observations)", "docstring": "Construct a predictive normal distribution that mixes over posterior draws.\n\nArgs:\n means: float `Tensor` of shape\n `[num_posterior_draws, ..., num_timesteps]`.\n variances: float `Tensor` of shape\n `[num_posterior_draws, ..., num_timesteps]`.\n\nReturns:\n mixture_dist: `tfd.MixtureSameFamily(tfd.Independent(tfd.Normal))` instance\n representing a uniform mixture over the posterior samples, with\n `batch_shape = ...` and `event_shape = [num_timesteps]`.", "source": "juraj_google_style"} +{"code": "def depth_soil_conductivity(self, value=None):\n\n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type float '\n 'for field `depth_soil_conductivity`'.format(value))\n\n self._depth_soil_conductivity = value", "docstring": "Corresponds to IDD Field `depth_soil_conductivity`\n\nArgs:\n value (float): value for IDD Field `depth_soil_conductivity`\n Unit: W/m-K,\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def _LastEntryTimestamp(dct, upper_bound_timestamp):\n\n if upper_bound_timestamp is None:\n upper_bound = lambda _: True\n else:\n upper_bound = lambda key: key <= upper_bound_timestamp\n\n try:\n return max(filter(upper_bound, iterkeys(dct)))\n except ValueError: # Thrown if `max` input (result of filtering) is empty.\n return None", "docstring": "Searches for greatest timestamp lower than the specified one.\n\nArgs:\n dct: A dictionary from timestamps to some items.\n upper_bound_timestamp: An upper bound for timestamp to be returned.\n\nReturns:\n Greatest timestamp that is lower than the specified one. If no such value\n exists, `None` is returned.", "source": "juraj_google_style"} +{"code": "def range(self, dimension, data_range=True, dimension_range=True):\n\n dimension = self.get_dimension(dimension)\n if dimension is None or (not data_range and not dimension_range):\n return (None, None)\n elif all(util.isfinite(v) for v in dimension.range) and dimension_range:\n return dimension.range\n elif data_range:\n if dimension in self.kdims+self.vdims:\n dim_vals = self.dimension_values(dimension.name)\n lower, upper = util.find_range(dim_vals)\n else:\n dname = dimension.name\n match_fn = lambda x: dname in x.kdims + x.vdims\n range_fn = lambda x: x.range(dname)\n ranges = self.traverse(range_fn, [match_fn])\n lower, upper = util.max_range(ranges)\n else:\n lower, upper = (np.NaN, np.NaN)\n if not dimension_range:\n return lower, upper\n return util.dimension_range(lower, upper, dimension.range, dimension.soft_range)", "docstring": "Return the lower and upper bounds of values along dimension.\n\nArgs:\n dimension: The dimension to compute the range on.\n data_range (bool): Compute range from data values\n dimension_range (bool): Include Dimension ranges\n Whether to include Dimension range and soft_range\n in range calculation\n\nReturns:\n Tuple containing the lower and upper bound", "source": "juraj_google_style"} +{"code": "def topological_sort(data):\n\n\n def check_self_dependencies(input_data):\n\n for k, v in input_data.items():\n if k in v:\n raise ValueError('Self-dependency, {} depends on itself.'.format(k))\n\n def prepare_input_data(input_data):\n\n return {k: set(v) for k, v in input_data.items()}\n\n def find_items_without_dependencies(input_data):\n\n return list(reduce(set.union, input_data.values()) - set(input_data.keys()))\n\n def add_empty_dependencies(data):\n items_without_dependencies = find_items_without_dependencies(data)\n data.update({item: set() for item in items_without_dependencies})\n\n def get_sorted(input_data):\n data = input_data\n while True:\n ordered = set(item for item, dep in data.items() if len(dep) == 0)\n if not ordered:\n break\n yield ordered\n data = {item: (dep - ordered) for item, dep in data.items() if item not in ordered}\n\n if len(data) != 0:\n raise ValueError('Cyclic dependencies exist '\n 'among these items: {}'.format(', '.join(repr(x) for x in data.items())))\n\n check_self_dependencies(data)\n\n if not len(data):\n return []\n\n data_copy = prepare_input_data(data)\n add_empty_dependencies(data_copy)\n\n result = []\n for d in get_sorted(data_copy):\n try:\n d = sorted(d)\n except TypeError:\n d = list(d)\n\n result.extend(d)\n return result", "docstring": "Topological sort the given dictionary structure.\n\nArgs:\n data (dict); dictionary structure where the value is a list of dependencies for that given key.\n For example: ``{'a': (), 'b': ('a',)}``, where ``a`` depends on nothing and ``b`` depends on ``a``.\n\nReturns:\n tuple: the dependencies in constructor order", "source": "juraj_google_style"} +{"code": "def datasets_list(self, project_id=None, max_results=0, page_token=None):\n\n if project_id is None:\n project_id = self._project_id\n url = Api._ENDPOINT + (Api._DATASETS_PATH % (project_id, ''))\n\n args = {}\n if max_results != 0:\n args['maxResults'] = max_results\n if page_token is not None:\n args['pageToken'] = page_token\n\n return datalab.utils.Http.request(url, args=args, credentials=self._credentials)", "docstring": "Issues a request to list the datasets in the project.\n\nArgs:\n project_id: the project id to use to fetch the results; use None for the default project.\n max_results: an optional maximum number of tables to retrieve.\n page_token: an optional token to continue the retrieval.\n\nReturns:\n A parsed result object.\n\nRaises:\n Exception if there is an error performing the operation.", "source": "juraj_google_style"} +{"code": "def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'):\n\n with tf.variable_scope(scope):\n if stride > 1:\n avg_pool = CONFIG[dim]['avg_pool']\n x = avg_pool(x,\n pool_size=(stride, stride),\n strides=(stride, stride),\n padding='VALID')\n\n input_channels = tf.shape(x)[3]\n diff = output_channels - input_channels\n x = tf.pad(\n x, [[0, 0], [0, 0], [0, 0],\n [diff // 2, diff // 2]])\n return x", "docstring": "Downsamples 'x' by `stride` using average pooling.\n\nArgs:\n x: input tensor of size [N, H, W, C]\n output_channels: Desired number of output channels.\n dim: '2d' if 2-dimensional, '3d' if 3-dimensional.\n stride: What stride to use. Usually 1 or 2.\n scope: Optional variable scope.\n\nReturns:\n A downsampled tensor of size [N, H/2, W/2, output_channels] if stride\n is 2, else returns a tensor of size [N, H, W, output_channels] if\n stride is 1.", "source": "juraj_google_style"} +{"code": "def __init__(self, prefs, kappa=2.0, omega=0.5, beta=1.0, mu=1.0,\n phi=scipy.ones(N_NT) / N_NT,\n freeparams=['kappa', 'omega', 'beta', 'mu', 'eta']):\n\n self._nsites = len(prefs)\n assert self.nsites > 0, \"No preferences specified\"\n\n assert all(map(lambda x: x in self.ALLOWEDPARAMS, freeparams)),\\\n \"Invalid entry in freeparams\\nGot: {0}\\nAllowed: {1}\".format(\n ', '.join(freeparams), ', '.join(self.ALLOWEDPARAMS))\n self._freeparams = list(freeparams) # underscore as `freeparams` is property\n\n # put prefs in pi\n self.pi = scipy.ndarray((self.nsites, N_AA), dtype='float')\n assert (isinstance(prefs, list) and\n all([isinstance(x, dict) for x in prefs])),\\\n \"prefs is not a list of dicts\"\n for r in range(self.nsites):\n assert set(prefs[r].keys()) == set(AA_TO_INDEX.keys()),\\\n \"prefs not keyed by amino acids for site {0}\".format(r)\n assert abs(1 - sum(prefs[r].values())) <= ALMOST_ZERO,\\\n \"prefs don't sum to one for site {0}\".format(r)\n for (a, aa) in INDEX_TO_AA.items():\n _checkParam('pi', prefs[r][aa], self.PARAMLIMITS, self.PARAMTYPES)\n self.pi[r][a] = prefs[r][aa]\n self.pi[r] /= self.pi[r].sum() # renormalize to sum to one\n\n # set up attributes defined solely in terms of preferences\n self.pi_codon = scipy.full((self.nsites, N_CODON), -1, dtype='float')\n self.ln_pi_codon = scipy.full((self.nsites, N_CODON), -1, dtype='float')\n self.piAx_piAy = scipy.full((self.nsites, N_CODON, N_CODON), -1,\n dtype='float')\n\n # construct eta from phi\n _checkParam('phi', phi, self.PARAMLIMITS, self.PARAMTYPES)\n assert abs(1 - phi.sum()) <= ALMOST_ZERO, \"phi doesn't sum to 1\"\n self.phi = phi.copy()\n self.phi /= self.phi.sum()\n self._eta_from_phi()\n\n # set attributes to calling params\n self._mu = mu # underscore as `mu` is property\n self.kappa = kappa\n self.omega = omega\n self.beta = beta\n for (name, value) in [('kappa', self.kappa), ('omega', self.omega),\n ('beta', self.beta), ('eta', self.eta), ('mu', self.mu)]:\n _checkParam(name, value, self.PARAMLIMITS, self.PARAMTYPES)\n\n # define other params, initialized appropriately\n self.piAx_piAy_beta = scipy.zeros((self.nsites, N_CODON, N_CODON),\n dtype='float')\n self.ln_piAx_piAy_beta = scipy.zeros((self.nsites, N_CODON, N_CODON),\n dtype='float')\n self.Prxy = scipy.zeros((self.nsites, N_CODON, N_CODON), dtype='float')\n self.prx = scipy.zeros((self.nsites, N_CODON), dtype='float')\n self.Qxy = scipy.zeros((N_CODON, N_CODON), dtype='float')\n self.Frxy = scipy.ones((self.nsites, N_CODON, N_CODON), dtype='float')\n self.Frxy_no_omega = scipy.ones((self.nsites, N_CODON, N_CODON),\n dtype='float')\n self.D = scipy.zeros((self.nsites, N_CODON), dtype='float')\n self.A = scipy.zeros((self.nsites, N_CODON, N_CODON), dtype='float')\n self.Ainv = scipy.zeros((self.nsites, N_CODON, N_CODON), dtype='float')\n self.dPrxy = {}\n self.B = {}\n self.dprx = {}\n for param in self.freeparams:\n if param == 'mu':\n self.dprx['mu'] = 0.0\n elif self.PARAMTYPES[param] == float:\n self.dPrxy[param] = scipy.zeros((self.nsites, N_CODON, N_CODON),\n dtype='float')\n self.B[param] = scipy.zeros((self.nsites, N_CODON, N_CODON),\n dtype='float')\n self.dprx[param] = scipy.zeros((self.nsites, N_CODON), dtype='float')\n else:\n assert self.PARAMTYPES[param][0] == scipy.ndarray\n paramshape = self.PARAMTYPES[param][1]\n assert len(paramshape) == 1, \"Can't handle multi-dimensional ndarray\"\n paramlen = paramshape[0]\n self.dPrxy[param] = scipy.zeros((paramlen, self.nsites, N_CODON,\n N_CODON), dtype='float')\n self.B[param] = scipy.zeros((paramlen, self.nsites, N_CODON,\n N_CODON), dtype='float')\n self.dprx[param] = scipy.zeros((paramlen, self.nsites, N_CODON),\n dtype='float')\n\n # indexes diagonals in square matrices\n self._diag_indices = scipy.diag_indices(N_CODON)\n\n self.updateParams({}, update_all=True)", "docstring": "Initialize an `ExpCM` object.\n\nArgs:\n `prefs` (list)\n List of dicts giving amino-acid preferences for\n each site. Each dict keyed by amino acid letter\n codes, value is pref > 0 and < 1. Must sum to 1\n at each site.\n `kappa`, `omega`, `beta`, `mu`, `phi`\n Model params described in main class doc string.\n `freeparams` (list of strings)\n Specifies free parameters.", "source": "juraj_google_style"} +{"code": "def gcd_float(numbers, tol=1e-8):\n\n\n def pair_gcd_tol(a, b):\n\n while b > tol:\n a, b = b, a % b\n return a\n\n n = numbers[0]\n for i in numbers:\n n = pair_gcd_tol(n, i)\n return n", "docstring": "Returns the greatest common divisor for a sequence of numbers.\n Uses a numerical tolerance, so can be used on floats\n\nArgs:\n numbers: Sequence of numbers.\n tol: Numerical tolerance\n\nReturns:\n (int) Greatest common divisor of numbers.", "source": "juraj_google_style"} +{"code": "def text2text_txt_tab_iterator(txt_path):\n\n for line in txt_line_iterator(txt_path):\n if line and \"\\t\" in line:\n parts = line.split(\"\\t\", 1)\n inputs, targets = parts[:2]\n yield {\"inputs\": inputs.strip(), \"targets\": targets.strip()}", "docstring": "Yield dicts for Text2TextProblem.generate_samples from lines of txt_path.\n\nArgs:\n txt_path: path to txt file with a record per line, source and target\n are tab-separated.\n\nYields:\n {\"inputs\": inputs, \"targets\": targets}", "source": "juraj_google_style"} +{"code": "def by_issn(issn):\n\n # monkeypatched to allow search in NTK's Aleph\n old_url = aleph.ALEPH_URL\n aleph.ALEPH_URL = NTK_ALEPH_URL\n records = aleph.getISSNsXML(issn, base=\"STK02\")\n aleph.ALEPH_URL = old_url\n\n # process all records\n for record in records:\n marc = MARCXMLRecord(record)\n\n # following values were requested by @bjackova in\n # https://github.com/WebArchivCZ/WA-KAT/issues/66\n additional_info = {\n \"222\": marc.get(\"222\", None),\n \"PER\": marc.get(\"PER\", None),\n \"776\": marc.get(\"776\", None),\n \"008\": marc.get(\"008\", None),\n \"alt_end_date\": \"\" # just reminder that it is filled later\n }\n additional_info = {\n key: val\n for key, val in additional_info.iteritems()\n if val\n }\n\n # check whether there is alternative date in 008\n alt_end_date = None\n alt_creation_date = None\n if additional_info[\"008\"]:\n # 131114c20139999xr-q||p|s||||||---a0eng-c -> 2013\n alt_creation_date = additional_info[\"008\"][7:11]\n\n # 131114c20139999xr-q||p|s||||||---a0eng-c -> 9999\n alt_end_date = additional_info[\"008\"][11:15]\n if alt_end_date in [\"9999\", \"****\"]:\n alt_creation_date += \"-\" # library convention is xxxx-\n alt_end_date = None\n\n additional_info[\"alt_end_date\"] = alt_end_date\n\n # parse author\n author = Author.parse_author(marc)\n\n model = Model(\n url=_first_or_none(\n marc.get(\"856u\")\n ),\n conspect=_first_or_none(\n marc.get(\"072a\")\n ),\n annotation_tags=_first_or_none(\n marc.get(\"520a\")\n ),\n periodicity=_first_or_none(\n marc.get(\"310a\")\n ),\n title_tags=_first_or_none(\n marc.get(\"222a\")\n ),\n subtitle_tags=_first_or_none(\n marc.get(\"245b\")\n ),\n place_tags=remove_hairs(\n _first_or_none(marc.get(\"260a\")) or \"\"\n ),\n author_tags=author._asdict() if author else None,\n publisher_tags=remove_hairs(\n (\n _first_or_none(marc.get(\"260b\")) or\n _first_or_none(marc.get(\"264b\")) or\n \"\",\n ),\n \", \"\n ),\n creation_dates=_first_or_none(\n marc.get(\"260c\", [alt_creation_date])\n ),\n lang_tags=_first_or_none(\n marc.get(\"040b\")\n ),\n keyword_tags=marc.get(\"650a07\"),\n source_info=_first_or_none(\n marc.get(\"500a\")\n ),\n original_xml=record,\n additional_info=additional_info,\n )\n\n yield _add_source(model)", "docstring": "Query aleph for records with given `issn`. The lookup is directed to the\n NTK's Aleph.\n\nArgs:\n issn (str): ISSN of the periodical.\n\nReturns:\n obj: :class:`Model` instances for each record.", "source": "juraj_google_style"} +{"code": "def ProcessConfigOverrides(filename):\n\n\n abs_filename = os.path.abspath(filename)\n cfg_filters = []\n keep_looking = True\n while keep_looking:\n abs_path, base_name = os.path.split(abs_filename)\n if not base_name:\n break # Reached the root directory.\n\n cfg_file = os.path.join(abs_path, \"CPPLINT.cfg\")\n abs_filename = abs_path\n if not os.path.isfile(cfg_file):\n continue\n\n try:\n with open(cfg_file) as file_handle:\n for line in file_handle:\n line, _, _ = line.partition('#') # Remove comments.\n if not line.strip():\n continue\n\n name, _, val = line.partition('=')\n name = name.strip()\n val = val.strip()\n if name == 'set noparent':\n keep_looking = False\n elif name == 'filter':\n cfg_filters.append(val)\n elif name == 'exclude_files':\n # When matching exclude_files pattern, use the base_name of\n # the current file name or the directory name we are processing.\n # For example, if we are checking for lint errors in /foo/bar/baz.cc\n # and we found the .cfg file at /foo/CPPLINT.cfg, then the config\n # file's \"exclude_files\" filter is meant to be checked against \"bar\"\n # and not \"baz\" nor \"bar/baz.cc\".\n if base_name:\n pattern = re.compile(val)\n if pattern.match(base_name):\n _cpplint_state.PrintInfo('Ignoring \"%s\": file excluded by '\n '\"%s\". File path component \"%s\" matches pattern \"%s\"\\n' %\n (filename, cfg_file, base_name, val))\n return False\n elif name == 'linelength':\n global _line_length\n try:\n _line_length = int(val)\n except ValueError:\n _cpplint_state.PrintError('Line length must be numeric.')\n elif name == 'extensions':\n global _valid_extensions\n try:\n extensions = [ext.strip() for ext in val.split(',')]\n _valid_extensions = set(extensions)\n except ValueError:\n sys.stderr.write('Extensions should be a comma-separated list of values;'\n 'for example: extensions=hpp,cpp\\n'\n 'This could not be parsed: \"%s\"' % (val,))\n elif name == 'headers':\n global _header_extensions\n try:\n extensions = [ext.strip() for ext in val.split(',')]\n _header_extensions = set(extensions)\n except ValueError:\n sys.stderr.write('Extensions should be a comma-separated list of values;'\n 'for example: extensions=hpp,cpp\\n'\n 'This could not be parsed: \"%s\"' % (val,))\n elif name == 'root':\n global _root\n _root = val\n else:\n _cpplint_state.PrintError(\n 'Invalid configuration option (%s) in file %s\\n' %\n (name, cfg_file))\n\n except IOError:\n _cpplint_state.PrintError(\n \"Skipping config file '%s': Can't open for reading\\n\" % cfg_file)\n keep_looking = False\n\n # Apply all the accumulated filters in reverse order (top-level directory\n # config options having the least priority).\n for cfg_filter in reversed(cfg_filters):\n _AddFilters(cfg_filter)\n\n return True", "docstring": "Loads the configuration files and processes the config overrides.\n\nArgs:\n filename: The name of the file being processed by the linter.\n\nReturns:\n False if the current |filename| should not be processed further.", "source": "juraj_google_style"} +{"code": "def setup(__pkg: str) -> jinja2.Environment:\n\n dirs = [path.join(d, 'templates')\n for d in xdg_basedir.get_data_dirs(__pkg)]\n\n env = jinja2.Environment(\n autoescape=jinja2.select_autoescape(['html', 'xml']),\n loader=jinja2.ChoiceLoader([jinja2.FileSystemLoader(s) for s in dirs]))\n env.loader.loaders.append(jinja2.PackageLoader(__pkg, 'templates'))\n env.filters.update(FILTERS)\n\n return env", "docstring": "Configure a new Jinja environment with our filters.\n\nArgs:\n __pkg: Package name to use as base for templates searches\n\nReturns:\n Configured Jinja environment", "source": "juraj_google_style"} +{"code": "def _parse_query_key(self, key, val, is_escaped):\n\n if key.endswith('__contains'):\n key = key[:-10]\n val = self._parse_query_modifier('contains', val, is_escaped)\n elif key.endswith('__range'):\n key = key[:-7]\n val = self._parse_query_modifier('range', val, is_escaped)\n elif key.endswith('__startswith'):\n key = key[:-12]\n val = self._parse_query_modifier('startswith', val, is_escaped)\n elif key.endswith('__endswith'):\n key = key[:-10]\n val = self._parse_query_modifier('endswith', val, is_escaped)\n # lower than\n elif key.endswith('__lt'):\n key = key[:-4]\n val = self._parse_query_modifier('lt', val, is_escaped)\n # greater than\n elif key.endswith('__gt'):\n key = key[:-4]\n val = self._parse_query_modifier('gt', val, is_escaped)\n # lower than or equal\n elif key.endswith('__lte'):\n key = key[:-5]\n val = self._parse_query_modifier('lte', val, is_escaped)\n # greater than or equal\n elif key.endswith('__gte'):\n key = key[:-5]\n val = self._parse_query_modifier('gte', val, is_escaped)\n elif key != 'NOKEY' and not is_escaped:\n val = self._escape_query(val)\n return key, val", "docstring": "Strips query modifier from key and call's the appropriate value modifier.\n\nArgs:\n key (str): Query key\n val: Query value\n\nReturns:\n Parsed query key and value.", "source": "juraj_google_style"} +{"code": "def connectionReady(self, res=None):\n\n self._channel = yield self._allocate_channel()\n if _pika_version < pkg_resources.parse_version(\"1.0.0b1\"):\n extra_args = dict(all_channels=True)\n else:\n extra_args = dict(global_qos=True)\n yield self._channel.basic_qos(\n prefetch_count=config.conf[\"qos\"][\"prefetch_count\"],\n prefetch_size=config.conf[\"qos\"][\"prefetch_size\"],\n **extra_args\n )\n if _pika_version < pkg_resources.parse_version(\"1.0.0b1\"):\n TwistedProtocolConnection.connectionReady(self, res)", "docstring": "Callback invoked when the AMQP connection is ready (when self.ready fires).\n\n This API is not meant for users.\n\nArgs:\n res: This is an unused argument that provides compatibility with Pika\n versions lower than 1.0.0.", "source": "juraj_google_style"} +{"code": "def sg_sugar_func(func):\n r\n @wraps(func)\n def wrapper(tensor, **kwargs):\n # call sugar function\n out = func(tensor, tf.sg_opt(kwargs))\n # save node info for reuse\n out._sugar = tf.sg_opt(func=func, arg=tf.sg_opt(kwargs)+sg_get_context(), prev=tensor)\n # inject reuse function\n out.sg_reuse = types.MethodType(sg_reuse, out)\n return out\n\n return wrapper", "docstring": "r\"\"\" Decorates a function `func` so that it can be a sugar function.\n Sugar function can be used in a chainable manner.\n\nArgs:\n func: function to decorate\n\nReturns:\n A sugar function.", "source": "juraj_google_style"} +{"code": "def SetUsername(self, username):\n\n self._username = username\n logger.debug('Elasticsearch username: {0!s}'.format(username))", "docstring": "Sets the username.\n\nArgs:\n username (str): username to authenticate with.", "source": "juraj_google_style"} +{"code": "def orbit(self, orbit):\n\n\n self._orbit = orbit\n tle = Tle.from_orbit(orbit)\n lines = tle.text.splitlines()\n\n if len(lines) == 3:\n _, line1, line2 = lines\n else:\n line1, line2 = lines\n\n self.tle = twoline2rv(line1, line2, wgs72)", "docstring": "Initialize the propagator\n\nArgs:\n orbit (Orbit)", "source": "juraj_google_style"} +{"code": "def is_number(s):\n\n try:\n float(s)\n return True\n except ValueError:\n pass\n\n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n\n return False", "docstring": "Determines if the input is numeric\n\nArgs:\n s: The value to check.\n\nReturns:\n bool: ``True`` if the input is numeric, ``False`` otherwise.", "source": "juraj_google_style"} +{"code": "def topics(self, exclude_internal_topics=True):\n\n topics = set(self._partitions.keys())\n if exclude_internal_topics:\n return topics - self.internal_topics\n else:\n return topics", "docstring": "Get set of known topics.\n\nArgs:\n exclude_internal_topics (bool): Whether records from internal topics\n (such as offsets) should be exposed to the consumer. If set to\n True the only way to receive records from an internal topic is\n subscribing to it. Default True\n\nReturns:\n set: {topic (str), ...}", "source": "juraj_google_style"} +{"code": "def get_additional_charge_by_description(self, description):\n\n params = {\n \"description\": description\n }\n return self.client._get(self.url + 'recurringBillItems/', params=params, headers=self.get_headers())", "docstring": "Query extra charges of shop’s invoices that meet the stipulated filters.\n\nArgs:\n description: Description entered in the extra charge.\n\n Returns:", "source": "juraj_google_style"} +{"code": "def run_scratch(self, path_to_scratch, num_cores=1, outname=None, outdir=None, force_rerun=False):\n\n if not outname:\n outname = self.project_name\n if not outdir:\n outdir = ''\n\n outname = op.join(outdir, outname)\n\n self.out_sspro = '{}.ss'.format(outname)\n self.out_sspro8 = '{}.ss8'.format(outname)\n self.out_accpro = '{}.acc'.format(outname)\n self.out_accpro20 = '{}.acc20'.format(outname)\n\n # TODO: check for multiple output files in command_runner\n ssbio.utils.command_runner(\n shell_command='{} {} {} {}'.format(path_to_scratch, self.seq_file, outname, num_cores),\n force_rerun_flag=force_rerun, outfile_checker='{}.ss'.format(outname))", "docstring": "Run SCRATCH on the sequence_file that was loaded into the class.\n\nArgs:\n path_to_scratch: Path to the SCRATCH executable, run_SCRATCH-1D_predictors.sh\n outname: Prefix to name the output files\n outdir: Directory to store the output files\n force_rerun: Flag to force rerunning of SCRATCH even if the output files exist\n\n Returns:", "source": "juraj_google_style"} +{"code": "def FromStream(cls, stream):\n\n\n if stream.system:\n specifier = DataStreamSelector.MatchSystemOnly\n else:\n specifier = DataStreamSelector.MatchUserOnly\n\n return DataStreamSelector(stream.stream_type, stream.stream_id, specifier)", "docstring": "Create a DataStreamSelector from a DataStream.\n\nArgs:\n stream (DataStream): The data stream that we want to convert.", "source": "juraj_google_style"} +{"code": "def __init__(self, lower=True, num_norm=True,\n use_char=True, initial_vocab=None):\n\n self._num_norm = num_norm\n self._use_char = use_char\n self._word_vocab = Vocabulary(lower=lower)\n self._char_vocab = Vocabulary(lower=False)\n self._label_vocab = Vocabulary(lower=False, unk_token=False)\n\n if initial_vocab:\n self._word_vocab.add_documents([initial_vocab])\n self._char_vocab.add_documents(initial_vocab)", "docstring": "Create a preprocessor object.\n\nArgs:\n lower: boolean. Whether to convert the texts to lowercase.\n use_char: boolean. Whether to use char feature.\n num_norm: boolean. Whether to normalize text.\n initial_vocab: Iterable. Initial vocabulary for expanding word_vocab.", "source": "juraj_google_style"} +{"code": "def __call__(self, *args, **kwargs):\n\n for loop, m in self.iter_methods():\n coro = m(*args, **kwargs)\n self.submit_coroutine(coro, loop)", "docstring": "Triggers all stored callbacks (coroutines)\n\nArgs:\n *args: Positional arguments to pass to callbacks\n **kwargs: Keyword arguments to pass to callbacks", "source": "juraj_google_style"} +{"code": "def find_replace_string(obj, find, replace):\n\n try:\n strobj = str(obj)\n newStr = string.replace(strobj, find, replace)\n if newStr == strobj:\n return obj\n else:\n return newStr\n\n except:\n line, filename, synerror = trace()\n raise ArcRestHelperError({\n \"function\": \"find_replace_string\",\n \"line\": line,\n \"filename\": filename,\n \"synerror\": synerror,\n }\n )\n finally:\n pass", "docstring": "Performs a string.replace() on the input object.\n\nArgs:\n obj (object): The object to find/replace. It will be cast to ``str``.\n find (str): The string to search for.\n replace (str): The string to replace with.\n\nReturns:\n str: The replaced string.", "source": "juraj_google_style"} +{"code": "def _calc_cc(self, iso_size):\n # type: (int) -> Tuple[int, int]\n\n cylsize = self.geometry_heads * self.geometry_sectors * 512\n frac = iso_size % cylsize\n padding = 0\n if frac > 0:\n padding = cylsize - frac\n cc = (iso_size + padding) // cylsize\n if cc > 1024:\n cc = 1024\n\n return (cc, padding)", "docstring": "A method to calculate the 'cc' and the 'padding' values for this\n hybridization.\n\n Parameters:\n iso_size - The size of the ISO, excluding the hybridization.\n\nReturns:\n A tuple containing the cc value and the padding.", "source": "juraj_google_style"} +{"code": "def Network_setCookies(self, cookies):\n\n\t\tassert isinstance(cookies, (list, tuple)\n\t\t ), \"Argument 'cookies' must be of type '['list', 'tuple']'. Received type: '%s'\" % type(\n\t\t cookies)\n\t\tsubdom_funcs = self.synchronous_command('Network.setCookies', cookies=cookies\n\t\t )\n\t\treturn subdom_funcs", "docstring": "Function path: Network.setCookies\n Domain: Network\n Method name: setCookies\n\n WARNING: This function is marked 'Experimental'!\n\n Parameters:\n Required arguments:\n 'cookies' (type: array) -> Cookies to be set.\n No return value.\n\n Description: Sets given cookies.", "source": "juraj_google_style"} +{"code": "def from_specification(specification, env_prefix=None, separator='.',\n parent_names=None):\n\n items = {}\n for item_name, item_info in six.iteritems(specification):\n names = copy.copy(parent_names) if parent_names else []\n items[item_name] = _generate_item(item_name,\n item_info,\n env_prefix,\n separator,\n names)\n return items", "docstring": "Used to create YapconfItems from a specification dictionary.\n\nArgs:\n specification (dict): The specification used to\n initialize ``YapconfSpec``\n env_prefix (str): Prefix to add to environment names\n separator (str): Separator for nested items\n parent_names (list): Parents names of any given item\n\nReturns:\n A dictionary of names to YapconfItems", "source": "juraj_google_style"} +{"code": "def __init__(self, k_range, query_spec):\n\n self._key_range = k_range\n self._query_spec = query_spec\n self._cursor = None\n self._query = None", "docstring": "Init.\n\nArgs:\n k_range: a key_range.KeyRange object that defines the entity keys to\n operate on. KeyRange object already contains a namespace.\n query_spec: a model.query_spec object that defines how to retrieve\n entities from datastore.", "source": "juraj_google_style"} +{"code": "def get_path_list(self, type_str=None):\n\n return list(\n reversed(\n [v.label_str for v in self.parent_gen if type_str in (None, v.type_str)]\n )\n )", "docstring": "Get list of the labels of the nodes leading up to this node from the root.\n\nArgs:\n type_str:\n SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include\n information from nodes of that type.\n\nReturns:\n list of str: The labels of the nodes leading up to this node from the root.", "source": "juraj_google_style"} +{"code": "def random_product(items, num=None, rng=None):\n\n import utool as ut\n rng = ut.ensure_rng(rng, 'python')\n seen = set()\n items = [list(g) for g in items]\n max_num = ut.prod(map(len, items))\n if num is None:\n num = max_num\n if num > max_num:\n raise ValueError('num exceedes maximum number of products')\n\n # TODO: make this more efficient when num is large\n if num > max_num // 2:\n for prod in ut.shuffle(list(it.product(*items)), rng=rng):\n yield prod\n else:\n while len(seen) < num:\n # combo = tuple(sorted(rng.choice(items, size, replace=False)))\n idxs = tuple(rng.randint(0, len(g) - 1) for g in items)\n if idxs not in seen:\n seen.add(idxs)\n prod = tuple(g[x] for g, x in zip(items, idxs))\n yield prod", "docstring": "Yields `num` items from the cartesian product of items in a random order.\n\nArgs:\n items (list of sequences): items to get caresian product of\n packed in a list or tuple.\n (note this deviates from api of it.product)\n\nExample:\n import utool as ut\n items = [(1, 2, 3), (4, 5, 6, 7)]\n rng = 0\n list(ut.random_product(items, rng=0))\n list(ut.random_product(items, num=3, rng=0))", "source": "juraj_google_style"} +{"code": "def rate_to_mcs(rate, bw=20, long_gi=True):\n\n if bw not in [20, 40, 80, 160]:\n raise Exception(\"Unknown bandwidth: %d MHz\" % (bw))\n idx = int((math.log(bw/10, 2)-1)*2)\n if not long_gi:\n idx += 1\n\n for mcs, rates in MCS_TABLE.items():\n if abs(rates[idx] - rate) < 1e-3:\n return mcs\n\n # failed. Try dot11a rates\n for idx, r in enumerate(DOT11A_RATES):\n if abs(r-rate) < 1e-3:\n return idx\n\n raise Exception(\"MCS not found: rate=%f, bw=%d, long_gi=%s\" %\n (rate, bw, long_gi))", "docstring": "Convert bit rate to MCS index.\n\nArgs:\n rate (float): bit rate in Mbps\n bw (int): bandwidth, 20, 40, 80, ...\n long_gi (bool): True if long GI is used.\n\nReturns:\n mcs (int): MCS index\n\n >>> rate_to_mcs(120, bw=40, long_gi=False)\n 5", "source": "juraj_google_style"} +{"code": "def create_downloader_of_type(type_name):\n\n downloaders = available_downloaders()\n\n if type_name not in downloaders.keys():\n raise UnknownDownloaderException('Unknown downloader: %s' % (type_name,))\n\n return downloaders[type_name]()", "docstring": "Create an instance of the downloader with the given name.\n\nArgs:\n type_name: The name of a downloader.\n\nReturns:\n An instance of the downloader with the given type.", "source": "juraj_google_style"} +{"code": "def is_commit_id_equal(self, dest, name):\n\n if not name:\n # Then avoid an unnecessary subprocess call.\n return False\n\n return self.get_revision(dest) == name", "docstring": "Return whether the current commit hash equals the given name.\n\nArgs:\n dest: the repository directory.\n name: a string name.", "source": "juraj_google_style"} +{"code": "def run( self, for_time=None ):\n\n self.for_time = for_time\n try:\n self.is_initialised()\n except AttributeError:\n raise\n if self.number_of_equilibration_jumps > 0:\n for step in range( self.number_of_equilibration_jumps ):\n self.lattice.jump()\n self.reset()\n if self.for_time:\n self.number_of_jumps = 0\n while self.lattice.time < self.for_time:\n self.lattice.jump()\n self.number_of_jumps += 1\n else: \n for step in range( self.number_of_jumps ):\n self.lattice.jump()\n self.has_run = True", "docstring": "Run the simulation.\n\nArgs:\n for_time (:obj:Float, optional): If `for_time` is set, then run the simulation until a set amount of time has passed. Otherwise, run the simulation for a set number of jumps. Defaults to None.\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def run(self, sensor_graph, model):\n\n\n # This check can be done if there is 1 input and it is count == 1\n # and the stream type is input or unbuffered\n\n for node, inputs, outputs in sensor_graph.iterate_bfs():\n if node.num_inputs != 1:\n continue\n\n input_a, trigger_a = node.inputs[0]\n if input_a.selector.match_type not in [DataStream.InputType, DataStream.UnbufferedType]:\n continue\n\n if not isinstance(trigger_a, InputTrigger):\n continue\n\n if trigger_a.comp_string != u'==':\n continue\n\n if not trigger_a.use_count:\n continue\n\n if trigger_a.reference != 1:\n continue\n\n # here we're looking at count input | unbuffered X == 1\n node.inputs[0] = (input_a, TrueTrigger())", "docstring": "Run this optimization pass on the sensor graph\n\n If necessary, information on the device model being targeted\n can be found in the associated model argument.\n\nArgs:\n sensor_graph (SensorGraph): The sensor graph to optimize\n model (DeviceModel): The device model we're using", "source": "juraj_google_style"} +{"code": "def compute_cost(A2, Y):\n\n\n m = Y.shape[1] # number of example\n\n # Compute the cross-entropy cost\n logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y))\n cost = -np.sum(logprobs) / m\n\n cost = np.squeeze(cost) # makes sure cost is the dimension we expect.\n # E.g., turns [[17]] into 17\n\n assert (isinstance(cost, float))\n\n return cost", "docstring": "Computes the cross-entropy cost given in equation (13)\n\nArgs:\n A2 -- The sigmoid output of the second activation, of shape (1, number of examples)\n Y -- \"true\" labels vector of shape (1, number of examples)\n parameters -- python dictionary containing your parameters W1, b1, W2 and b2\n\nReturns:\n cost -- cross-entropy cost given equation (13)", "source": "juraj_google_style"} +{"code": "def delete_entities(namespace, workspace, json_body):\n\n\n uri = \"workspaces/{0}/{1}/entities/delete\".format(namespace, workspace)\n return __post(uri, json=json_body)", "docstring": "Delete entities in a workspace.\n\n Note: This action is not reversible. Be careful!\n\nArgs:\n namespace (str): project to which workspace belongs\n workspace (str): Workspace name\n json_body:\n [\n {\n \"entityType\": \"string\",\n \"entityName\": \"string\"\n }\n ]\n\n Swagger:\n https://api.firecloud.org/#!/Entities/deleteEntities", "source": "juraj_google_style"} +{"code": "def _GetDateTime(self, filetime):\n\n if filetime == 0:\n return dfdatetime_semantic_time.SemanticTime('Not set')\n\n return dfdatetime_filetime.Filetime(timestamp=filetime)", "docstring": "Retrieves the date and time from a FILETIME timestamp.\n\nArgs:\n filetime (int): FILETIME timestamp.\n\nReturns:\n dfdatetime.DateTimeValues: date and time.", "source": "juraj_google_style"} +{"code": "def __init__(self, location=None, **kwargs):\n\n if not location:\n raise ValueError('Missing location value.')\n\n parent = None\n if 'parent' in kwargs:\n parent = kwargs['parent']\n del kwargs['parent']\n\n if parent:\n raise ValueError('Parent value set.')\n\n # Within the path specification the path should be absolute.\n location = os.path.abspath(location)\n\n super(OSPathSpec, self).__init__(location=location, parent=parent, **kwargs)", "docstring": "Initializes a path specification.\n\n Note that the operating system path specification cannot have a parent.\n\nArgs:\n location (Optional[str]): operating specific location string e.g.\n /opt/dfvfs or C:\\\\Opt\\\\dfvfs.\n\nRaises:\n ValueError: when location is not set or parent is set.", "source": "juraj_google_style"} +{"code": "def keypoint_rot90(keypoint, factor, rows, cols, **params):\n\n if factor < 0 or factor > 3:\n raise ValueError('Parameter n must be in range [0;3]')\n x, y, angle, scale = keypoint\n if factor == 1:\n keypoint = [y, (cols - 1) - x, angle - math.pi / 2, scale]\n if factor == 2:\n keypoint = [(cols - 1) - x, (rows - 1) - y, angle - math.pi, scale]\n if factor == 3:\n keypoint = [(rows - 1) - y, x, angle + math.pi / 2, scale]\n return keypoint", "docstring": "Rotates a keypoint by 90 degrees CCW (see np.rot90)\n\nArgs:\n keypoint (tuple): A tuple (x, y, angle, scale).\n factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.\n rows (int): Image rows.\n cols (int): Image cols.", "source": "juraj_google_style"} +{"code": "def _transform_col(self, x, col):\n\n\n return norm.ppf(self.ecdfs[col](x) * .998 + .001)", "docstring": "Normalize one numerical column.\n\nArgs:\n x (numpy.array): a numerical column to normalize\n col (int): column index\n\nReturns:\n A normalized feature vector.", "source": "juraj_google_style"} +{"code": "def get_average_record(self, n):\n\n history_deque = collections.deque()\n averages = []\n for d in self.data_points:\n history_deque.appendleft(d)\n if len(history_deque) > n:\n history_deque.pop()\n avg = sum(history_deque) / len(history_deque)\n averages.append(round(avg, self.lr))\n return averages", "docstring": "Returns a list of average current numbers, each representing the\n average over the last n data points.\n\nArgs:\n n: Number of data points to average over.\n\nReturns:\n A list of average current values.", "source": "juraj_google_style"} +{"code": "def boundary_transform(seq, force_edges = True):\n\n gen = boundary_words(seq)\n if force_edges:\n gen = boundary_edges(gen)\n gen = remove_duplicates(gen)\n for char in gen:\n yield char", "docstring": "Wraps all word transitions with a boundary token character (\\x00).\n If desired (with ``force_edges`` set to ``True``), this inserts\n the boundary character at the beginning and end of the string.\n\nArgs:\n - `seq`:\n - `force_edges = True`:", "source": "juraj_google_style"} +{"code": "def render_category(category='', template=None):\n\n # pylint:disable=too-many-return-statements\n\n # See if this is an aliased path\n redir = get_redirect()\n if redir:\n return redir\n\n # Forbidden template types\n if template and template.startswith('_'):\n raise http_error.Forbidden(\"Template is private\")\n if template in ['entry', 'error']:\n raise http_error.BadRequest(\"Invalid view requested\")\n\n if category:\n # See if there's any entries for the view...\n if not orm.select(e for e in model.Entry if e.category == category or\n e.category.startswith(category + '/')):\n raise http_error.NotFound(\"No such category\")\n\n if not template:\n template = Category(category).get('Index-Template') or 'index'\n\n tmpl = map_template(category, template)\n\n if not tmpl:\n # this might actually be a malformed category URL\n test_path = '/'.join((category, template)) if category else template\n logger.debug(\"Checking for malformed category %s\", test_path)\n record = orm.select(\n e for e in model.Entry if e.category == test_path).exists()\n if record:\n return redirect(url_for('category', category=test_path, **request.args))\n\n # nope, we just don't know what this is\n raise http_error.NotFound(\"No such view\")\n\n view_spec = view.parse_view_spec(request.args)\n view_spec['category'] = category\n view_obj = view.View(view_spec)\n\n rendered, etag = render_publ_template(\n tmpl,\n _url_root=request.url_root,\n category=Category(category),\n view=view_obj)\n\n if request.if_none_match.contains(etag):\n return 'Not modified', 304\n\n return rendered, {'Content-Type': mime_type(tmpl),\n 'ETag': etag}", "docstring": "Render a category page.\n\nArgs:\n category -- The category to render\n template -- The template to render it with", "source": "juraj_google_style"} +{"code": "def solveCuttingStock(w,q,B):\n\n t = [] # patterns\n m = len(w)\n\n # Generate initial patterns with one size for each item width\n for (i,width) in enumerate(w):\n pat = [0]*m # vector of number of orders to be packed into one roll (bin)\n pat[i] = int(B/width)\n t.append(pat)\n\n # if LOG:\n # print \"sizes of orders=\",w\n # print \"quantities of orders=\",q\n # print \"roll size=\",B\n # print \"initial patterns\",t\n\n K = len(t)\n master = Model(\"master LP\") # master LP problem\n x = {}\n\n for k in range(K):\n x[k] = master.addVar(vtype=\"I\", name=\"x(%s)\"%k)\n\n orders = {}\n\n for i in range(m):\n orders[i] = master.addCons(\n quicksum(t[k][i]*x[k] for k in range(K) if t[k][i] > 0) >= q[i], \"Order(%s)\"%i)\n\n master.setObjective(quicksum(x[k] for k in range(K)), \"minimize\")\n\n # master.Params.OutputFlag = 0 # silent mode\n\n # iter = 0\n while True:\n # print \"current patterns:\"\n # for ti in t:\n # print ti\n # print\n\n # iter += 1\n relax = master.relax()\n relax.optimize()\n pi = [relax.getDualsolLinear(c) for c in relax.getConss()] # keep dual variables\n\n knapsack = Model(\"KP\") # knapsack sub-problem\n knapsack.setMaximize # maximize\n y = {}\n\n for i in range(m):\n y[i] = knapsack.addVar(lb=0, ub=q[i], vtype=\"I\", name=\"y(%s)\"%i)\n\n knapsack.addCons(quicksum(w[i]*y[i] for i in range(m)) <= B, \"Width\")\n\n knapsack.setObjective(quicksum(pi[i]*y[i] for i in range(m)), \"maximize\")\n\n knapsack.hideOutput() # silent mode\n knapsack.optimize()\n # if LOG:\n # print \"objective of knapsack problem:\", knapsack.ObjVal\n if knapsack.getObjVal() < 1+EPS: # break if no more columns\n break\n\n pat = [int(y[i].X+0.5) for i in y] # new pattern\n t.append(pat)\n # if LOG:\n # print \"shadow prices and new pattern:\"\n # for (i,d) in enumerate(pi):\n # print \"\\t%5s%12s%7s\" % (i,d,pat[i])\n # print\n\n # add new column to the master problem\n col = Column()\n for i in range(m):\n if t[K][i] > 0:\n col.addTerms(t[K][i], orders[i])\n x[K] = master.addVar(obj=1, vtype=\"I\", name=\"x(%s)\"%K, column=col)\n\n # master.write(\"MP\" + str(iter) + \".lp\")\n K += 1\n\n\n # Finally, solve the IP\n # if LOG:\n # master.Params.OutputFlag = 1 # verbose mode\n master.optimize()\n\n # if LOG:\n # print\n # print \"final solution (integer master problem): objective =\", master.ObjVal\n # print \"patterns:\"\n # for k in x:\n # if x[k].X > EPS:\n # print \"pattern\",k,\n # print \"\\tsizes:\",\n # print [w[i] for i in range(m) if t[k][i]>0 for j in range(t[k][i]) ],\n # print \"--> %s rolls\" % int(x[k].X+.5)\n\n rolls = []\n for k in x:\n for j in range(int(x[k].X + .5)):\n rolls.append(sorted([w[i] for i in range(m) if t[k][i]>0 for j in range(t[k][i])]))\n rolls.sort()\n return rolls", "docstring": "solveCuttingStock: use column generation (Gilmore-Gomory approach).\n Parameters:\n - w: list of item's widths\n - q: number of items of a width\n - B: bin/roll capacity\n Returns a solution: list of lists, each of which with the cuts of a roll.", "source": "juraj_google_style"} +{"code": "def group_modes(modes):\n\n if len(modes) > 0:\n previous = modes[0]\n grouped = []\n\n for changep in modes[1:]:\n if changep['label'] != previous['label']:\n previous['to'] = changep['from']\n grouped.append(previous)\n previous = changep\n\n previous['to'] = modes[-1]['to']\n grouped.append(previous)\n return grouped\n else:\n return modes", "docstring": "Groups consecutive transportation modes with same label, into one\n\nArgs:\n modes (:obj:`list` of :obj:`dict`)\n\nReturns:\n :obj:`list` of :obj:`dict`", "source": "juraj_google_style"} +{"code": "def apply(self, func, **kwargs):\n\n oid = self.oid\n self.call_queue.append((func, kwargs))\n\n def call_queue_closure(oid_obj, call_queues):\n for func, kwargs in call_queues:\n if isinstance(func, ray.ObjectID):\n func = ray.get(func)\n if isinstance(kwargs, ray.ObjectID):\n kwargs = ray.get(kwargs)\n\n oid_obj = func(oid_obj, **kwargs)\n\n return oid_obj\n\n oid = deploy_ray_func.remote(\n call_queue_closure, oid, kwargs={\"call_queues\": self.call_queue}\n )\n self.call_queue = []\n\n return PyarrowOnRayFramePartition(oid)", "docstring": "Apply a function to the object stored in this partition.\n\n Note: It does not matter if func is callable or an ObjectID. Ray will\n handle it correctly either way. The keyword arguments are sent as a\n dictionary.\n\nArgs:\n func: The function to apply.\n\nReturns:\n A RayRemotePartition object.", "source": "juraj_google_style"} +{"code": "def fit_anonymous(self, struct1, struct2, niggli=True):\n\n struct1, struct2 = self._process_species([struct1, struct2])\n struct1, struct2, fu, s1_supercell = self._preprocess(struct1, struct2,\n niggli)\n\n matches = self._anonymous_match(struct1, struct2, fu, s1_supercell,\n break_on_match=True, single_match=True)\n\n if matches:\n return True\n else:\n return False", "docstring": "Performs an anonymous fitting, which allows distinct species in one\n structure to map to another. E.g., to compare if the Li2O and Na2O\n structures are similar.\n\nArgs:\n struct1 (Structure): 1st structure\n struct2 (Structure): 2nd structure\n\nReturns:\n True/False: Whether a species mapping can map struct1 to stuct2", "source": "juraj_google_style"} +{"code": "def _GetArchiveTypes(self, mediator, path_spec):\n\n try:\n type_indicators = analyzer.Analyzer.GetArchiveTypeIndicators(\n path_spec, resolver_context=mediator.resolver_context)\n except IOError as exception:\n type_indicators = []\n\n warning_message = (\n 'analyzer failed to determine archive type indicators '\n 'with error: {0!s}').format(exception)\n mediator.ProduceExtractionWarning(warning_message, path_spec=path_spec)\n\n return type_indicators", "docstring": "Determines if a data stream contains an archive such as: TAR or ZIP.\n\nArgs:\n mediator (ParserMediator): mediates the interactions between\n parsers and other components, such as storage and abort signals.\n path_spec (dfvfs.PathSpec): path specification of the data stream.\n\nReturns:\n list[str]: dfVFS archive type indicators found in the data stream.", "source": "juraj_google_style"} +{"code": "def dumps(xs, model=None, properties=False, indent=True, **kwargs):\n\n xs = list(xs)\n\n if not xs:\n return ''\n\n given_class = xs[0].__class__ # assume they are all the same\n if model is None:\n model = xs[0].__class__\n\n if not hasattr(model, 'to_triples'):\n raise TypeError(\n '{} class does not implement to_triples()'.format(model.__name__)\n )\n\n # convert MRS to DMRS if necessary; EDS cannot convert\n if given_class.__name__ in ('Mrs', 'Xmrs'):\n xs = [model.from_xmrs(x, **kwargs) for x in xs]\n elif given_class.__name__ == 'Eds' and model.__name__ != 'Eds':\n raise ValueError('Cannot convert EDS to non-EDS')\n\n codec = XMRSCodec()\n graphs = [\n codec.triples_to_graph(model.to_triples(x, properties=properties))\n for x in xs\n ]\n\n if 'pretty_print' in kwargs:\n indent = kwargs['pretty_print']\n\n return penman.dumps(graphs, cls=XMRSCodec, indent=indent)", "docstring": "Serialize Xmrs (or subclass) objects to PENMAN notation\n\nArgs:\n xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to\n serialize\n model: Xmrs subclass used to get triples\n properties: if `True`, encode variable properties\n indent: if `True`, adaptively indent; if `False` or `None`,\n don't indent; if a non-negative integer N, indent N spaces\n per level\n\nReturns:\n the PENMAN serialization of *xs*", "source": "juraj_google_style"} +{"code": "def map(self, callback: Callable[[T], U]) -> 'Option[U]':\n\n return self._type.Some(callback(self._val)) if self._is_some else cast('Option[U]', NONE)", "docstring": "Applies the ``callback`` with the contained value as its argument or\n returns :py:data:`NONE`.\n\nArgs:\n callback: The callback to apply to the contained value.\n\nReturns:\n The ``callback`` result wrapped in an :class:`Option` if the\n contained value is ``Some``, otherwise :py:data:`NONE`\n\nExample:\n >>> Some(10).map(lambda x: x * x)\n Some(100)\n >>> NONE.map(lambda x: x * x)\n NONE", "source": "juraj_google_style"} +{"code": "def _CreateWindowsPathResolver(\n self, file_system, mount_point, environment_variables):\n\n if environment_variables is None:\n environment_variables = []\n\n path_resolver = windows_path_resolver.WindowsPathResolver(\n file_system, mount_point)\n\n for environment_variable in environment_variables:\n name = environment_variable.name.lower()\n if name not in ('systemroot', 'userprofile'):\n continue\n\n path_resolver.SetEnvironmentVariable(\n environment_variable.name, environment_variable.value)\n\n return path_resolver", "docstring": "Create a Windows path resolver and sets the environment variables.\n\nArgs:\n file_system (dfvfs.FileSystem): file system.\n mount_point (dfvfs.PathSpec): mount point path specification.\n environment_variables (list[EnvironmentVariableArtifact]): environment\n variables.\n\nReturns:\n dfvfs.WindowsPathResolver: Windows path resolver.", "source": "juraj_google_style"} +{"code": "def verify_server_core(timeout=120, start_delay=90):\n\n timestamp = time.time()\n last_check = time.time() + start_delay - 10\n last_delay_notification = time.time() - 10\n server_down = True\n return_val = False\n timeout += 1\n # loop until the server is up or the timeout is reached\n while((time.time()-timestamp) < timeout) and server_down:\n # if delaying, the start of the check, print waiting to start\n if start_delay > 0 and time.time() - timestamp < start_delay \\\n and (time.time()-last_delay_notification) > 5:\n print(\"Delaying server status check until %ss. Current time: %ss\" \\\n % (start_delay, int(time.time() - timestamp)))\n last_delay_notification = time.time()\n # send a request check every 10s until the server is up\n while ((time.time()-last_check) > 10) and server_down:\n print(\"Checking status of servers at %ss\" % \\\n int((time.time()-timestamp)))\n last_check = time.time()\n try:\n repo = requests.get(CFG.REPOSITORY_URL)\n repo_code = repo.status_code\n print (\"\\t\", CFG.REPOSITORY_URL, \" - \", repo_code)\n except:\n repo_code = 400\n print (\"\\t\", CFG.REPOSITORY_URL, \" - DOWN\")\n try:\n triple = requests.get(CFG.DATA_TRIPLESTORE.url)\n triple_code = triple.status_code\n print (\"\\t\", CFG.DATA_TRIPLESTORE.url, \" - \", triple_code)\n except:\n triple_code = 400\n print (\"\\t\", CFG.DATA_TRIPLESTORE.url, \" - down\")\n if repo_code == 200 and triple_code == 200:\n server_down = False\n return_val = True\n print(\"**** Servers up at %ss\" % \\\n int((time.time()-timestamp)))\n break\n return return_val", "docstring": "checks to see if the server_core is running\n\nArgs:\n delay: will cycle till core is up.\n timeout: number of seconds to wait", "source": "juraj_google_style"} +{"code": "def wiki_delete(self, page_id):\n\n return self._get('wiki_pages/{0}.json'.format(page_id), auth=True,\n method='DELETE')", "docstring": "Delete a specific page wiki (Requires login) (UNTESTED) (Builder+).\n\n Parameters:\n page_id (int):", "source": "juraj_google_style"} +{"code": "def __init__(self, config):\n\n\n self.name = config['name']\n self.config = config\n self.entities = {}\n self.files = []\n\n self.include = listify(self.config.get('include', []))\n self.exclude = listify(self.config.get('exclude', []))\n\n if self.include and self.exclude:\n raise ValueError(\"The 'include' and 'exclude' arguments cannot \"\n \"both be set. Please pass at most one of these \"\n \"for domain '%s'.\" % self.name)\n\n self.path_patterns = listify(config.get('default_path_patterns', []))", "docstring": "A set of rules that applies to one or more directories\n within a Layout.\n\nArgs:\n name (str): The name of the Domain.\n config (dict): The configuration dictionary that defines the\n entities and paths for the current domain.", "source": "juraj_google_style"} +{"code": "def _PrintEventLabelsCounter(\n self, event_labels_counter, session_identifier=None):\n\n if not event_labels_counter:\n return\n\n title = 'Event tags generated per label'\n if session_identifier:\n title = '{0:s}: {1:s}'.format(title, session_identifier)\n\n table_view = views.ViewsFactory.GetTableView(\n self._views_format_type,\n column_names=['Label', 'Number of event tags'], title=title)\n\n for key, value in sorted(event_labels_counter.items()):\n if key == 'total':\n continue\n table_view.AddRow([key, value])\n\n try:\n total = event_labels_counter['total']\n except KeyError:\n total = 'N/A'\n\n table_view.AddRow(['Total', total])\n\n table_view.Write(self._output_writer)", "docstring": "Prints the event labels counter.\n\nArgs:\n event_labels_counter (collections.Counter): number of event tags per\n label.\n session_identifier (Optional[str]): session identifier.", "source": "juraj_google_style"} +{"code": "def get_processid(config):\n\n pidfile = config.get('daemon', 'pidfile', fallback=None)\n if pidfile is None:\n raise ValueError(\"Configuration doesn't have pidfile option!\")\n\n try:\n with open(pidfile, 'r') as _file:\n pid = _file.read().rstrip()\n try:\n pid = int(pid)\n except ValueError:\n raise ValueError(\"stale pid file with invalid data:{}\"\n .format(pid))\n else:\n if pid in [-1, 1]:\n raise ValueError(\"invalid PID ({})\".format(pid))\n else:\n return pid\n except OSError as exc:\n if exc.errno == 2:\n print(\"CRITICAL: anycast-healthchecker could be down as pid file \"\n \"{} doesn't exist\".format(pidfile))\n sys.exit(2)\n else:\n raise ValueError(\"error while reading pid file:{}\".format(exc))", "docstring": "Return process id of anycast-healthchecker.\n\nArgs:\n config (obj): A configparser object with the configuration of\n anycast-healthchecker.\n\nReturns:\n The process id found in the pid file\n\nRaises:\n ValueError in the following cases\n - pidfile option is missing from the configuration\n - pid is either -1 or 1\n - stale pidfile, either with no data or invalid data\n - failure to read pidfile", "source": "juraj_google_style"} +{"code": "def __init__(self, plist_filename):\n\n self.filename = plist_filename\n\n with open(self.filename, 'r') as plist_file:\n self.soup = BeautifulSoup(plist_file, 'lxml-xml')\n self.properties = self.soup.findChild(name='dict')\n\n if self.properties is None:\n raise RuntimeError('Invalid property list file provided')", "docstring": "Initialize a property list representation from an existing file.\n\nArgs:\n plist_filename: A string containing the full path to a\n Doxygen-generated property list file.\n\nRaises:\n OSError / FileNotFoundError: Input file cannot be read\n RuntimeError: The property list file is not of the expected format", "source": "juraj_google_style"} +{"code": "def get_supported_filepaths(filepaths, supported_extensions, max_depth=float('inf')):\n\n\n\tsupported_filepaths = []\n\n\tfor path in filepaths:\n\t\tif os.name == 'nt' and CYGPATH_RE.match(path):\n\t\t\tpath = convert_cygwin_path(path)\n\n\t\tif os.path.isdir(path):\n\t\t\tfor root, __, files in walk_depth(path, max_depth):\n\t\t\t\tfor f in files:\n\t\t\t\t\tif f.lower().endswith(supported_extensions):\n\t\t\t\t\t\tsupported_filepaths.append(os.path.join(root, f))\n\t\telif os.path.isfile(path) and path.lower().endswith(supported_extensions):\n\t\t\tsupported_filepaths.append(path)\n\n\treturn supported_filepaths", "docstring": "Get filepaths with supported extensions from given filepaths.\n\n Parameters:\n filepaths (list or str): Filepath(s) to check.\n\n supported_extensions (tuple or str): Supported file extensions or a single file extension.\n\n max_depth (int): The depth in the directory tree to walk.\n A depth of '0' limits the walk to the top directory.\n Default: No limit.\n\nReturns:\n A list of supported filepaths.", "source": "juraj_google_style"} +{"code": "def load(self, filename, bs=512):\n\n self.__filename = filename\n self.__volumes = []\n\n # Detect partitioning scheme\n self.__partition_scheme = rawdisk.scheme.common.detect_scheme(filename)\n\n plugin_objects = [plugin.plugin_object for plugin in self.__fs_plugins]\n fs_detector = FilesystemDetector(fs_plugins=plugin_objects)\n\n if self.__partition_scheme == PartitionScheme.SCHEME_MBR:\n self.__load_mbr_volumes(filename, fs_detector, bs)\n elif self.__partition_scheme == PartitionScheme.SCHEME_GPT:\n self.__load_gpt_volumes(filename, fs_detector, bs)\n else:\n self.logger.warning('Partitioning scheme could not be determined.')\n # try detecting standalone volume\n volume = fs_detector.detect_standalone(filename, offset=0)\n if volume is not None:\n volume.load(filename, offset=0)\n self.__volumes.append(volume)\n else:\n self.logger.warning(\n 'Were not able to detect standalone volume type')", "docstring": "Starts filesystem analysis. Detects supported filesystems and \\\n loads :attr:`partitions` array.\n\nArgs:\n filename - Path to file or device for reading.\n\nRaises:\n IOError - File/device does not exist or is not readable.", "source": "juraj_google_style"} +{"code": "def __get_scope(cls,\n expr: Union['Expression', Tuple]) -> Set[str]:\n\n scope = set()\n for i, atom in enumerate(expr):\n if isinstance(atom, Expression):\n scope.update(cls.__get_scope(atom._expr))\n elif type(atom) in [tuple, list]:\n scope.update(cls.__get_scope(atom))\n elif atom == 'pvar_expr':\n functor, params = expr[i+1]\n arity = len(params) if params is not None else 0\n name = '{}/{}'.format(functor, arity)\n scope.add(name)\n break\n return scope", "docstring": "Returns the set of fluents in the expression's scope.\n\nArgs:\n expr: Expression object or nested tuple of Expressions.\n\nReturns:\n The set of fluents in the expression's scope.", "source": "juraj_google_style"} +{"code": "def fileLoad(self, filePath=None, updatePath=True):\n\n if not filePath:\n filePath = self.filePath\n if not os.path.isfile(filePath):\n raise FileNotFoundError(\"Data file '%s' does not exist.\" % (filePath))\n else:\n print(\"Importing existing data file '%s' ... \" % (filePath), end=\"\", flush=True)\n with open(filePath, \"r\") as q:\n data_raw = q.read()\n print(\"Imported!\")\n self.data = json.loads(data_raw)\n if updatePath:\n self.filePath = filePath", "docstring": "Load a JSON data file into the internal JSON data dictionary.\n\n Current internal data will be overwritten.\n If no file path is provided, the stored data file path will be used.\n\nArgs:\n filePath (Optional[str]): A relative or absolute path to a\n '.json' file. Defaults to None.\n updatePath (Optional[bool]): Specifies whether or not to update\n the stored data file path. Defaults to True.", "source": "juraj_google_style"} +{"code": "def calculate_etag(self, expected=None):\n\n md5s = []\n with open(self.filepath, 'rb') as fp:\n while True:\n data = fp.read(CHUNK_SIZE)\n if not data:\n break\n md5s.append(hashlib.md5(data))\n\n digests = b\"\".join(m.digest() for m in md5s)\n\n new_md5 = hashlib.md5(digests)\n new_etag = '%s-%s' % (new_md5.hexdigest(),len(md5s))\n self.etag = new_etag\n\n return new_etag", "docstring": "calculates a multipart upload etag in the same way as amazon s3\n\nArgs:\n source_path -- The file to calculate the etage for\n chunk_size -- The chunk size to calculate for.\n expected -- optional If passed a string, the string\n will be compared to the resulting etag and raise an\n exception if they don't match", "source": "juraj_google_style"} +{"code": "def get_unverified_claims(token):\n\n try:\n claims = jws.get_unverified_claims(token)\n except:\n raise JWTError('Error decoding token claims.')\n\n try:\n claims = json.loads(claims.decode('utf-8'))\n except ValueError as e:\n raise JWTError('Invalid claims string: %s' % e)\n\n if not isinstance(claims, Mapping):\n raise JWTError('Invalid claims string: must be a json object')\n\n return claims", "docstring": "Returns the decoded claims without verification of any kind.\n\nArgs:\n token (str): A signed JWT to decode the headers from.\n\nReturns:\n dict: The dict representation of the token claims.\n\nRaises:\n JWTError: If there is an exception decoding the token.", "source": "juraj_google_style"} +{"code": "def __init__(self, resolver_context):\n\n super(CompressedStreamFileSystem, self).__init__(resolver_context)\n self._compression_method = None", "docstring": "Initializes a compressed stream file system.\n\nArgs:\n resolver_context (Context): a resolver context.", "source": "juraj_google_style"} +{"code": "def drop(self, items):\n\n self._manager.leaser.remove(items)\n self._manager.maybe_resume_consumer()", "docstring": "Remove the given messages from lease management.\n\nArgs:\n items(Sequence[DropRequest]): The items to drop.", "source": "juraj_google_style"} +{"code": "def update_entity(namespace, workspace, etype, ename, updates):\n\n headers = _fiss_agent_header({\"Content-type\": \"application/json\"})\n uri = \"{0}workspaces/{1}/{2}/entities/{3}/{4}\".format(fcconfig.root_url,\n namespace, workspace, etype, ename)\n\n # FIXME: create __patch method, akin to __get, __delete etc\n return __SESSION.patch(uri, headers=headers, json=updates)", "docstring": "Update entity attributes in a workspace.\n\nArgs:\n namespace (str): project to which workspace belongs\n workspace (str): Workspace name\n etype (str): Entity type\n ename (str): Entity name\n updates (list(dict)): List of updates to entity from _attr_set, e.g.\n\n Swagger:\n https://api.firecloud.org/#!/Entities/update_entity", "source": "juraj_google_style"} +{"code": "def minimum(x1, x2, output_shape=None, name=None):\n\n output_shape = convert_to_shape(output_shape)\n with tf.name_scope(name, default_name=\"minimum\"):\n x1, x2 = binary_arguments_to_tensors(x1, x2)\n return MinMaxOperation(\n tf.minimum, x1, x2, output_shape=_infer_binary_broadcast_shape(\n x1.shape, x2.shape, output_shape)).outputs[0]", "docstring": "Binary minimum with broadcsting.\n\nArgs:\n x1: a Tensor\n x2: a Tensor\n output_shape: an optional Shape\n name: an optional string\n\nReturns:\n a Tensor", "source": "juraj_google_style"} +{"code": "def get_by_resource(self, resource_uri):\n\n uri = self.URI + self.RESOURCES_PATH + '/' + resource_uri\n return self._client.get(id_or_uri=uri)", "docstring": "Gets all the labels for the specified resource\n\nArgs:\n resource_uri: The resource URI\n\nReturns:\n dict: Resource Labels", "source": "juraj_google_style"} +{"code": "def get_storage(self, contract_hash, storage_key, id=None, endpoint=None):\n\n result = self._call_endpoint(GET_STORAGE, params=[contract_hash, binascii.hexlify(storage_key.encode('utf-8')).decode('utf-8')], id=id, endpoint=endpoint)\n try:\n\n return bytearray(binascii.unhexlify(result.encode('utf-8')))\n except Exception as e:\n raise NEORPCException(\"could not decode result %s \" % e)", "docstring": "Returns a storage item of a specified contract\n\nArgs:\n contract_hash: (str) hash of the contract to lookup, for example 'd7678dd97c000be3f33e9362e673101bac4ca654'\n storage_key: (str) storage key to lookup, for example 'totalSupply'\n id: (int, optional) id to use for response tracking\n endpoint: (RPCEndpoint, optional) endpoint to specify to use\n\nReturns:\n bytearray: bytearray value of the storage item", "source": "juraj_google_style"} +{"code": "def FormatArtifacts(self, artifacts):\n\n artifact_definitions = [artifact.AsDict() for artifact in artifacts]\n json_data = json.dumps(artifact_definitions)\n return json_data", "docstring": "Formats artifacts to desired output format.\n\nArgs:\n artifacts (list[ArtifactDefinition]): artifact definitions.\n\nReturns:\n str: formatted string of artifact definition.", "source": "juraj_google_style"} +{"code": "def join_room(self, room_id_or_alias):\n\n response = self.api.join_room(room_id_or_alias)\n room_id = (\n response[\"room_id\"] if \"room_id\" in response else room_id_or_alias\n )\n return self._mkroom(room_id)", "docstring": "Join a room.\n\nArgs:\n room_id_or_alias (str): Room ID or an alias.\n\nReturns:\n Room\n\nRaises:\n MatrixRequestError", "source": "juraj_google_style"} +{"code": "def _register(self, name, AttrCls):\n\n if not issubclass(AttrCls, StateAttr):\n raise TypeError(\"The second argument must a StateAttr instance.\")\n if len(name) > 40:\n raise ValueError(\"Name can count at most 40 characters.\")\n self._fields[name] = AttrCls(self._owner, name)", "docstring": "Register a new attribute to take care of with dump and load\n\nArgs:\n | ``name`` -- the name to be used in the dump file\n | ``AttrCls`` -- an attr class describing the attribute", "source": "juraj_google_style"} +{"code": "def _generate_G_points(self, kpoint):\n\n gpoints = []\n for i in range(2 * self._nbmax[2] + 1):\n i3 = i - 2 * self._nbmax[2] - 1 if i > self._nbmax[2] else i\n for j in range(2 * self._nbmax[1] + 1):\n j2 = j - 2 * self._nbmax[1] - 1 if j > self._nbmax[1] else j\n for k in range(2 * self._nbmax[0] + 1):\n k1 = k - 2 * self._nbmax[0] - 1 if k > self._nbmax[0] else k\n G = np.array([k1, j2, i3])\n v = kpoint + G\n g = np.linalg.norm(np.dot(v, self.b))\n E = g ** 2 / self._C\n if E < self.encut:\n gpoints.append(G)\n return np.array(gpoints, dtype=np.float64)", "docstring": "Helper function to generate G-points based on nbmax.\n\n This function iterates over possible G-point values and determines\n if the energy is less than G_{cut}. Valid values are appended to\n the output array. This function should not be called outside of\n initialization.\n\nArgs:\n kpoint (np.array): the array containing the current k-point value\n\nReturns:\n a list containing valid G-points", "source": "juraj_google_style"} +{"code": "def orient_undirected_graph(self, data, graph, **kwargs):\n\n # Building setup w/ arguments.\n self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test]\n self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.method_indep]\n self.arguments['{DIRECTED}'] = 'TRUE'\n self.arguments['{ALPHA}'] = str(self.alpha)\n self.arguments['{NJOBS}'] = str(self.nb_jobs)\n self.arguments['{VERBOSE}'] = str(self.verbose).upper()\n\n fe = DataFrame(nx.adj_matrix(graph, weight=None).todense())\n fg = DataFrame(1 - fe.values)\n\n results = self._run_pc(data, fixedEdges=fe, fixedGaps=fg, verbose=self.verbose)\n\n return nx.relabel_nodes(nx.DiGraph(results),\n {idx: i for idx, i in enumerate(data.columns)})", "docstring": "Run PC on an undirected graph.\n\nArgs:\n data (pandas.DataFrame): DataFrame containing the data\n graph (networkx.Graph): Skeleton of the graph to orient\n\nReturns:\n networkx.DiGraph: Solution given by PC on the given skeleton.", "source": "juraj_google_style"} +{"code": "def get(self, key):\n\n\n match = self._get_match(key=key)\n\n if not match:\n return None\n\n return self._get_value_from_match(key=key, match=match)", "docstring": "Gets the value of the property of the given key.\n\nArgs:\n key (str): Key of the property to look-up.", "source": "juraj_google_style"} +{"code": "def show_stories(self, raw=False, limit=None):\n\n show_stories = self._get_stories('showstories', limit)\n if raw:\n show_stories = [story.raw for story in show_stories]\n return show_stories", "docstring": "Returns list of item ids of latest Show HN stories\n\nArgs:\n limit (int): specifies the number of stories to be returned.\n raw (bool): Flag to indicate whether to transform all\n objects into raw json.\n\nReturns:\n `list` object containing ids of Show HN stories.", "source": "juraj_google_style"} +{"code": "def get_extension_by_name(cert_obj, extension_name):\n\n try:\n return cert_obj.extensions.get_extension_for_oid(\n getattr(cryptography.x509.oid.ExtensionOID, extension_name)\n )\n except cryptography.x509.ExtensionNotFound:\n pass", "docstring": "Get a standard certificate extension by attribute name.\n\nArgs:\n cert_obj: cryptography.Certificate\n Certificate containing a standard extension.\n\n extension_name : str\n Extension name. E.g., 'SUBJECT_DIRECTORY_ATTRIBUTES'.\n\nReturns:\n Cryptography.Extension", "source": "juraj_google_style"} +{"code": "def _get_magic_menu(self,menuidentifier, menulabel=None):\n\n menu = self._magic_menu_dict.get(menuidentifier,None)\n if not menu :\n if not menulabel:\n menulabel = re.sub(\"([a-zA-Z]+)([A-Z][a-z])\",\"\\g<1> \\g<2>\",menuidentifier)\n menu = QtGui.QMenu(menulabel,self.magic_menu)\n self._magic_menu_dict[menuidentifier]=menu\n self.magic_menu.insertMenu(self.magic_menu_separator,menu)\n return menu", "docstring": "return a submagic menu by name, and create it if needed\n\n parameters:\n -----------\n\n menulabel : str\n Label for the menu\n\n Will infere the menu name from the identifier at creation if menulabel not given.\n To do so you have too give menuidentifier as a CamelCassedString", "source": "juraj_google_style"} +{"code": "def get_day_end(config):\n\n day_start_datetime = datetime.datetime.combine(datetime.date.today(), config['day_start'])\n day_end_datetime = day_start_datetime - datetime.timedelta(seconds=1)\n return day_end_datetime.time()", "docstring": "Get the day end time given the day start. This assumes full 24h day.\n\nArgs:\n config (dict): Configdict. Needed to extract ``day_start``.\n\nNote:\n This is merely a convinience funtion so we do not have to deduct this from ``day_start``\n by hand all the time.", "source": "juraj_google_style"} +{"code": "def __init__(self, shape, min_value, max_value, alpha=0.0, beta=0.0, scope='beta', summary_labels=()):\n\n assert min_value is None or max_value > min_value\n self.shape = shape\n self.min_value = min_value\n self.max_value = max_value\n action_size = util.prod(self.shape)\n\n self.alpha = Linear(size=action_size, bias=alpha, scope='alpha', summary_labels=summary_labels)\n self.beta = Linear(size=action_size, bias=beta, scope='beta', summary_labels=summary_labels)\n\n super(Beta, self).__init__(shape=shape, scope=scope, summary_labels=summary_labels)", "docstring": "Beta distribution.\n\nArgs:\n shape: Action shape.\n min_value: Minimum value of continuous actions.\n max_value: Maximum value of continuous actions.\n alpha: Optional distribution bias for the alpha value.\n beta: Optional distribution bias for the beta value.", "source": "juraj_google_style"} +{"code": "def get_email_message(self, message_uid, message_type=\"text/plain\"):\n\n self._mail.select(\"inbox\")\n result = self._mail.uid('fetch', message_uid, \"(RFC822)\")\n msg = email.message_from_string(result[1][0][1])\n\n try:\n # Try to handle as multipart message first.\n for part in msg.walk():\n if part.get_content_type() == message_type:\n return part.get_payload(decode=True)\n except:\n # handle as plain text email\n return msg.get_payload(decode=True)", "docstring": "Fetch contents of email.\n\nArgs:\n message_uid (int): IMAP Message UID number.\n\n Kwargs:\n message_type: Can be 'text' or 'html'", "source": "juraj_google_style"} +{"code": "def __init__(self, dataset_merger, problem_type=transitfeed.TYPE_WARNING,\n **kwargs):\n\n kwargs['type'] = problem_type\n kwargs['entity_type_name'] = dataset_merger.ENTITY_TYPE_NAME\n transitfeed.ExceptionWithContext.__init__(self, None, None, **kwargs)\n self.dataset_merger = dataset_merger", "docstring": "Initialise the exception object.\n\nArgs:\n dataset_merger: The DataSetMerger instance that generated this problem.\n problem_type: The problem severity. This should be set to one of the\n corresponding constants in transitfeed.\n kwargs: Keyword arguments to be saved as instance attributes.", "source": "juraj_google_style"} +{"code": "def _page(self, text, html=False):\n\n line_height = QtGui.QFontMetrics(self.font).height()\n minlines = self._control.viewport().height() / line_height\n if self.paging != 'none' and \\\n re.match(\"(?:[^\\n]*\\n){%i}\" % minlines, text):\n if self.paging == 'custom':\n self.custom_page_requested.emit(text)\n else:\n self._page_control.clear()\n cursor = self._page_control.textCursor()\n if html:\n self._insert_html(cursor, text)\n else:\n self._insert_plain_text(cursor, text)\n self._page_control.moveCursor(QtGui.QTextCursor.Start)\n\n self._page_control.viewport().resize(self._control.size())\n if self._splitter:\n self._page_control.show()\n self._page_control.setFocus()\n else:\n self.layout().setCurrentWidget(self._page_control)\n elif html:\n self._append_html(text)\n else:\n self._append_plain_text(text)", "docstring": "Displays text using the pager if it exceeds the height of the\n viewport.\n\n Parameters:\n -----------\n html : bool, optional (default False)\n If set, the text will be interpreted as HTML instead of plain text.", "source": "juraj_google_style"} +{"code": "def transformer_text_encoder(inputs,\n target_space,\n hparams,\n name=None):\n\n with tf.variable_scope(name, default_name=\"transformer_text_encoder\"):\n inputs = common_layers.flatten4d3d(inputs)\n [\n encoder_input,\n encoder_self_attention_bias,\n ed,\n ] = transformer_layers.transformer_prepare_encoder(\n inputs, target_space=target_space, hparams=hparams)\n encoder_input = tf.nn.dropout(encoder_input, 1.0 - hparams.dropout)\n encoder_output = transformer_layers.transformer_encoder(\n encoder_input, encoder_self_attention_bias, hparams)\n return encoder_output, ed", "docstring": "Transformer text encoder over inputs with unmasked full attention.\n\nArgs:\n inputs: Tensor of shape [batch, length, 1, hparams.hidden_size].\n target_space: int. Used for encoding inputs under a target space id.\n hparams: HParams.\n name: string, variable scope.\n\nReturns:\n encoder_output: Tensor of shape [batch, length, hparams.hidden_size].\n ed: Tensor of shape [batch, 1, 1, length]. Encoder-decoder attention bias\n for any padded tokens.", "source": "juraj_google_style"} +{"code": "def getGUA(self, filterByPrefix=None):\n\n print '%s call getGUA' % self.port\n print filterByPrefix\n globalAddrs = []\n try:\n # get global addrs set if multiple\n globalAddrs = self.getGlobal()\n\n if filterByPrefix is None:\n return self.__padIp6Addr(globalAddrs[0])\n else:\n for line in globalAddrs:\n line = self.__padIp6Addr(line)\n print \"Padded IPv6 Address:\" + line\n if line.startswith(filterByPrefix):\n return line\n print 'no global address matched'\n return str(globalAddrs[0])\n except Exception, e:\n ModuleHelper.WriteIntoDebugLogger('getGUA() Error: ' + str(e))\n return e", "docstring": "get expected global unicast IPv6 address of OpenThreadWpan\n\nArgs:\n filterByPrefix: a given expected global IPv6 prefix to be matched\n\nReturns:\n a global IPv6 address", "source": "juraj_google_style"} +{"code": "def __init__(self, source_path):\n\n self.source_path = source_path\n self.package = get_developer_package(source_path)\n self.type_settings = self.package.config.plugins.release_hook\n self.settings = self.type_settings.get(self.name())", "docstring": "Create a release hook.\n\nArgs:\n source_path: Path containing source that was released.", "source": "juraj_google_style"} +{"code": "def allconcat_ring(xs, devices, concat_axis):\n\n n = len(xs)\n if n == 1:\n return xs\n # [target, source]\n parts = [[xs[target] if target == source else None for source in xrange(n)]\n for target in xrange(n)]\n for distance in xrange(1, n // 2 + 1):\n for target in xrange(n):\n source = (target + distance) % n\n if parts[target][source] is None:\n with tf.device(devices[target]):\n parts[target][source] = tf.identity(parts[(target + 1) % n][source])\n source = (target - distance) % n\n if parts[target][source] is None:\n with tf.device(devices[target]):\n parts[target][source] = tf.identity(parts[(target - 1) % n][source])\n return mtf.parallel(devices, tf.concat, parts, axis=[concat_axis] * n)", "docstring": "Concatenate all Tensors everywhere.\n\n Performance-optimized for a ring of devices.\n\nArgs:\n xs: a list of n tf.Tensors\n devices: a list of n strings\n concat_axis: an integer\n\nReturns:\n a list of n Tensors", "source": "juraj_google_style"} +{"code": "def __init__(self, ethertype=None):\n\n super().__init__(action_type=ActionType.OFPAT_POP_MPLS)\n self.ethertype = ethertype", "docstring": "Create an ActionPopMPLS with the optional parameters below.\n\nArgs:\n ethertype (int): indicates the Ethertype of the payload.", "source": "juraj_google_style"} +{"code": "def new_cells(self, name=None, formula=None):\n\n # Outside formulas only\n return self._impl.new_cells(name, formula).interface", "docstring": "Create a cells in the space.\n\nArgs:\n name: If omitted, the model is named automatically ``CellsN``,\n where ``N`` is an available number.\n func: The function to define the formula of the cells.\n\nReturns:\n The new cells.", "source": "juraj_google_style"} +{"code": "def do_REMOTE(self,\n target: str,\n remote_command: str,\n source: list,\n *args,\n **kwargs) -> None:\n\n if target == self.messaging._service_name:\n info = 'target for remote command is the bot itself! Returning the function'\n self.logger.info(info)\n return self._handle_command(remote_command, source, *args, **kwargs)\n\n try:\n target = self.messaging._address_map[target]\n except KeyError:\n warn = ' Target %s, not found in addresses. Are you sure that %s sent an IDENT message?'\n self.logger.warn(warn, target, target)\n # TODO: raise an error instead of returning?\n # NOTE: Bail here since there's no point in going forward\n return\n\n self.logger.info(' REMOTE %s, target: %s | %s, %s',\n remote_command, target, args, kwargs)\n\n # package the binary together\n source = target + source\n self.messaging.send_command_response(source,\n remote_command,\n *args, \n **kwargs)", "docstring": "Send a remote command to a service. Used\n\nArgs:\n target: The service that the command gets set to\n remote_command: The command to do remotely.\n source: the binary source of the zmq_socket. Packed to send to the", "source": "juraj_google_style"} +{"code": "def __init__(self, latitude, longitude, comment=None):\n\n super(Xearth, self).__init__(latitude, longitude)\n self.comment = comment", "docstring": "Initialise a new ``Xearth`` object.\n\nArgs:\n latitude (float): Location's latitude\n longitude (float): Location's longitude\n comment (str): Comment for location", "source": "juraj_google_style"} +{"code": "def get_without(self, fragments,\n use_lookup=None):\n\n if use_lookup is None:\n use_lookup = settings['defaults']['use_lookup']\n\n if pd.api.types.is_list_like(fragments):\n for fragment in fragments:\n try:\n index_of_all_fragments |= fragment.index\n except NameError:\n index_of_all_fragments = fragment.index\n else:\n index_of_all_fragments = fragments.index\n missing_part = self.loc[self.index.difference(index_of_all_fragments)]\n missing_part = missing_part.fragmentate(use_lookup=use_lookup)\n return sorted(missing_part, key=len, reverse=True)", "docstring": "Return self without the specified fragments.\n\nArgs:\n fragments: Either a list of :class:`~chemcoord.Cartesian` or a\n :class:`~chemcoord.Cartesian`.\n use_lookup (bool): Use a lookup variable for\n :meth:`~chemcoord.Cartesian.get_bonds`. The default is\n specified in ``settings['defaults']['use_lookup']``\n\nReturns:\n list: List containing :class:`~chemcoord.Cartesian`.", "source": "juraj_google_style"} +{"code": "def __init__(self, _args):\n\n super(TcExLib, self).__init__(_args)\n\n # properties\n self.latest_version = None\n self.lib_directory = 'lib_{}.{}.{}'.format(\n sys.version_info.major, sys.version_info.minor, sys.version_info.micro\n )\n self.requirements_file = 'requirements.txt'\n self.static_lib_dir = 'lib_latest'\n self.use_temp_requirements_file = False", "docstring": "Initialize Class properties.\n\nArgs:\n _args (namespace): The argparser args Namespace.", "source": "juraj_google_style"} +{"code": "def load_pos_model(lang=\"en\", version=\"2\"):\n\n src_dir = \"pos{}\".format(version)\n p = locate_resource(src_dir, lang)\n fh = _open(p)\n return dict(np.load(fh))", "docstring": "Return a part of speech tagger parameters for `lang` and of version `version`\n\nArgs:\n lang (string): language code.\n version (string): version of the parameters to be used.", "source": "juraj_google_style"} +{"code": "def get_diff_coeff(hvec, n=1):\n\n hvec = np.array(hvec, dtype=np.float)\n acc = len(hvec)\n exp = np.column_stack([np.arange(acc)]*acc)\n a = np.vstack([hvec] * acc) ** exp\n b = np.zeros(acc)\n b[n] = factorial(n)\n return np.linalg.solve(a, b)", "docstring": "Helper function to find difference coefficients of an\n derivative on an arbitrary mesh.\n\nArgs:\n hvec (1D array-like): sampling stencil\n n (int): degree of derivative to find", "source": "juraj_google_style"} +{"code": "def submit_evaluation(self, variant_obj, user_obj, institute_obj, case_obj, link, criteria):\n\n variant_specific = variant_obj['_id']\n variant_id = variant_obj['variant_id']\n user_id = user_obj['_id']\n user_name = user_obj.get('name', user_obj['_id'])\n institute_id = institute_obj['_id']\n case_id = case_obj['_id']\n\n evaluation_terms = [evluation_info['term'] for evluation_info in criteria]\n\n classification = get_acmg(evaluation_terms)\n\n evaluation_obj = build_evaluation(\n variant_specific=variant_specific,\n variant_id=variant_id,\n user_id=user_id,\n user_name=user_name,\n institute_id=institute_id,\n case_id=case_id,\n classification=classification,\n criteria=criteria\n )\n\n self._load_evaluation(evaluation_obj)\n\n # Update the acmg classification for the variant:\n self.update_acmg(institute_obj, case_obj, user_obj, link, variant_obj, classification)\n return classification", "docstring": "Submit an evaluation to the database\n\n Get all the relevant information, build a evaluation_obj\n\nArgs:\n variant_obj(dict)\n user_obj(dict)\n institute_obj(dict)\n case_obj(dict)\n link(str): variant url\n criteria(list(dict)):\n\n [\n {\n 'term': str,\n 'comment': str,\n 'links': list(str)\n },\n .\n .\n ]", "source": "juraj_google_style"} +{"code": "def get_attribute_label(\n self, main_type, sub_type, unique_id, attribute_id, label, owner=None, params=None\n ):\n\n return self.attribute_label(\n main_type, sub_type, unique_id, attribute_id, label, owner=owner, params=params\n )", "docstring": "Args:\n owner:\n main_type:\n sub_type:\n unique_id:\n attribute_id:\n label:\n params:\n\n Return:", "source": "juraj_google_style"} +{"code": "def _get_job_resources(args):\n\n logging = param_util.build_logging_param(\n args.logging) if args.logging else None\n timeout = param_util.timeout_in_seconds(args.timeout)\n log_interval = param_util.log_interval_in_seconds(args.log_interval)\n\n return job_model.Resources(\n min_cores=args.min_cores,\n min_ram=args.min_ram,\n machine_type=args.machine_type,\n disk_size=args.disk_size,\n disk_type=args.disk_type,\n boot_disk_size=args.boot_disk_size,\n preemptible=args.preemptible,\n image=args.image,\n regions=args.regions,\n zones=args.zones,\n logging=logging,\n logging_path=None,\n service_account=args.service_account,\n scopes=args.scopes,\n keep_alive=args.keep_alive,\n cpu_platform=args.cpu_platform,\n network=args.network,\n subnetwork=args.subnetwork,\n use_private_address=args.use_private_address,\n accelerator_type=args.accelerator_type,\n accelerator_count=args.accelerator_count,\n nvidia_driver_version=args.nvidia_driver_version,\n timeout=timeout,\n log_interval=log_interval,\n ssh=args.ssh)", "docstring": "Extract job-global resources requirements from input args.\n\nArgs:\n args: parsed command-line arguments\n\nReturns:\n Resources object containing the requested resources for the job", "source": "juraj_google_style"} +{"code": "def from_dir(cls, top, exts=None, exclude_dirs=\"_*\"):\n\n pseudos = []\n\n if exts == \"all_files\":\n for f in [os.path.join(top, fn) for fn in os.listdir(top)]:\n if os.path.isfile(f):\n try:\n p = Pseudo.from_file(f)\n if p:\n pseudos.append(p)\n else:\n logger.info('Skipping file %s' % f)\n except:\n logger.info('Skipping file %s' % f)\n if not pseudos:\n logger.warning('No pseudopotentials parsed from folder %s' % top)\n return None\n logger.info('Creating PseudoTable with %i pseudopotentials' % len(pseudos))\n\n else:\n if exts is None: exts=(\"psp8\",)\n\n for p in find_exts(top, exts, exclude_dirs=exclude_dirs):\n try:\n pseudos.append(Pseudo.from_file(p))\n except Exception as exc:\n logger.critical(\"Error in %s:\\n%s\" % (p, exc))\n\n return cls(pseudos).sort_by_z()", "docstring": "Find all pseudos in the directory tree starting from top.\n\nArgs:\n top: Top of the directory tree\n exts: List of files extensions. if exts == \"all_files\"\n we try to open all files in top\n exclude_dirs: Wildcard used to exclude directories.\n\n return: :class:`PseudoTable` sorted by atomic number Z.", "source": "juraj_google_style"} +{"code": "def response(uri, method, res, token='', keyword='',\n content='', raw_flag=False):\n\n if method == 'GET' or (method == 'PUT' and not token):\n # response body\n data = res.read()\n data_utf8 = data.decode('utf-8')\n if token:\n datas = json.loads(data_utf8)\n else:\n token = json.loads(data_utf8)['hash']\n return token\n\n if keyword == 'serial':\n # filtering with keyword\n record = search_record(datas, 'SOA')[0]\n\n # if SOA record, remove priority unnecessary\n del record['priority']\n\n # override ttl\n record['ttl'] = int(record['ttl'])\n\n c = JSONConverter(content['domain'])\n new_record = c.get_soa(record, content)\n return record, new_record\n\n elif keyword:\n # '--search' option of 'get' subcommand\n records = search_record(datas, keyword)\n datas.update({\"records\": records})\n\n if uri.split('/')[3] == 'template':\n # 'tmpl_get' subcommand\n\n if len(uri.split('/')) == 5:\n # when specify template identfier\n #print_formatted(datas)\n utils.pretty_print(datas)\n\n else:\n # when get all templates\n for data in datas:\n #print_formatted(data)\n utils.pretty_print(datas)\n\n else:\n # 'get' subcommand\n if raw_flag:\n return datas\n else:\n #print_formatted(datas)\n if len(uri.split('zone/')) > 1:\n domain = uri.split('zone/')[1]\n else:\n domain = ''\n utils.pretty_print(datas, keyword, domain)\n\n else:\n # response non JSON data\n data = res.read()\n print(data)", "docstring": "Response of tonicdns_client request\n\nArgs:\n uri: TonicDNS API URI\n method: TonicDNS API request method\n res: Response of against request to TonicDNS API\n token: TonicDNS API token\n keyword: Processing keyword\n content: JSON data\n raw_flag: True is return responsed raw data, False is pretty print", "source": "juraj_google_style"} +{"code": "def _FormatSourceShort(self, event):\n\n source_short, _ = self._output_mediator.GetFormattedSources(event)\n if source_short is None:\n data_type = getattr(event, 'data_type', 'UNKNOWN')\n raise errors.NoFormatterFound(\n 'Unable to find event formatter for: {0:s}.'.format(data_type))\n\n return source_short", "docstring": "Formats the short source.\n\nArgs:\n event (EventObject): event.\n\nReturns:\n str: short source field.\n\nRaises:\n NoFormatterFound: If no event formatter can be found to match the data\n type in the event.", "source": "juraj_google_style"} +{"code": "def set_log_level(verbose, quiet):\n\n if quiet:\n verbose = -1\n if verbose < 0:\n verbose = logging.CRITICAL\n elif verbose == 0:\n verbose = logging.WARNING\n elif verbose == 1:\n verbose = logging.INFO\n elif 1 < verbose:\n verbose = logging.DEBUG\n LOGGER.setLevel(verbose)", "docstring": "Ses the logging level of the script based on command line options.\n\nArgs:\n - `verbose`:\n - `quiet`:", "source": "juraj_google_style"} +{"code": "def name(self):\n\n return ctypes.cast(self.sName, ctypes.c_char_p).value.decode()", "docstring": "Returns the name of the device.\n\nArgs:\n self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance\n\nReturns:\n Device name.", "source": "juraj_google_style"} +{"code": "def verify(self, obj):\n\n\n if not isinstance(obj, int):\n raise ValidationError(\"Object is not a int\", reason='object is not a int', object=obj,\n type=type(obj), int_type=int)\n\n return obj", "docstring": "Verify that the object conforms to this verifier's schema\n\nArgs:\n obj (object): A python object to verify\n\nRaises:\n ValidationError: If there is a problem verifying the dictionary, a\n ValidationError is thrown with at least the reason key set indicating\n the reason for the lack of validation.", "source": "juraj_google_style"} +{"code": "def _ProcessSources(\n self, source_path_specs, extraction_worker, parser_mediator,\n storage_writer, filter_find_specs=None):\n\n if self._processing_profiler:\n self._processing_profiler.StartTiming('process_sources')\n\n number_of_consumed_sources = 0\n\n self._UpdateStatus(\n definitions.STATUS_INDICATOR_COLLECTING, '',\n number_of_consumed_sources, storage_writer)\n\n display_name = ''\n path_spec_generator = self._path_spec_extractor.ExtractPathSpecs(\n source_path_specs, find_specs=filter_find_specs,\n recurse_file_system=False,\n resolver_context=parser_mediator.resolver_context)\n\n for path_spec in path_spec_generator:\n if self._abort:\n break\n\n display_name = parser_mediator.GetDisplayNameForPathSpec(path_spec)\n\n # TODO: determine if event sources should be DataStream or FileEntry\n # or both.\n event_source = event_sources.FileEntryEventSource(path_spec=path_spec)\n storage_writer.AddEventSource(event_source)\n\n self._UpdateStatus(\n definitions.STATUS_INDICATOR_COLLECTING, display_name,\n number_of_consumed_sources, storage_writer)\n\n # Force the status update here to make sure the status is up to date.\n self._UpdateStatus(\n definitions.STATUS_INDICATOR_RUNNING, display_name,\n number_of_consumed_sources, storage_writer, force=True)\n\n if self._processing_profiler:\n self._processing_profiler.StartTiming('get_event_source')\n\n event_source = storage_writer.GetFirstWrittenEventSource()\n\n if self._processing_profiler:\n self._processing_profiler.StopTiming('get_event_source')\n\n while event_source:\n if self._abort:\n break\n\n self._ProcessPathSpec(\n extraction_worker, parser_mediator, event_source.path_spec)\n number_of_consumed_sources += 1\n\n if self._guppy_memory_profiler:\n self._guppy_memory_profiler.Sample()\n\n self._UpdateStatus(\n extraction_worker.processing_status, self._current_display_name,\n number_of_consumed_sources, storage_writer)\n\n if self._processing_profiler:\n self._processing_profiler.StartTiming('get_event_source')\n\n event_source = storage_writer.GetNextWrittenEventSource()\n\n if self._processing_profiler:\n self._processing_profiler.StopTiming('get_event_source')\n\n if self._abort:\n status = definitions.STATUS_INDICATOR_ABORTED\n else:\n status = definitions.STATUS_INDICATOR_COMPLETED\n\n # Force the status update here to make sure the status is up to date\n # on exit.\n self._UpdateStatus(\n status, '', number_of_consumed_sources, storage_writer, force=True)\n\n if self._processing_profiler:\n self._processing_profiler.StopTiming('process_sources')", "docstring": "Processes the sources.\n\nArgs:\n source_path_specs (list[dfvfs.PathSpec]): path specifications of\n the sources to process.\n extraction_worker (worker.ExtractionWorker): extraction worker.\n parser_mediator (ParserMediator): parser mediator.\n storage_writer (StorageWriter): storage writer for a session storage.\n filter_find_specs (Optional[list[dfvfs.FindSpec]]): find specifications\n used in path specification extraction.", "source": "juraj_google_style"} +{"code": "def setSwarmState(self, swarmId, newStatus):\n\n assert (newStatus in ['active', 'completing', 'completed', 'killed'])\n\n # Set the swarm status\n swarmInfo = self._state['swarms'][swarmId]\n if swarmInfo['status'] == newStatus:\n return\n\n # If some other worker noticed it as completed, setting it to completing\n # is obviously old information....\n if swarmInfo['status'] == 'completed' and newStatus == 'completing':\n return\n\n self._dirty = True\n swarmInfo['status'] = newStatus\n if newStatus == 'completed':\n (modelId, errScore) = self._hsObj._resultsDB.bestModelIdAndErrScore(swarmId)\n swarmInfo['bestModelId'] = modelId\n swarmInfo['bestErrScore'] = errScore\n\n # If no longer active, remove it from the activeSwarms entry\n if newStatus != 'active' and swarmId in self._state['activeSwarms']:\n self._state['activeSwarms'].remove(swarmId)\n\n # If new status is 'killed', kill off any running particles in that swarm\n if newStatus=='killed':\n self._hsObj.killSwarmParticles(swarmId)\n\n # In case speculative particles are enabled, make sure we generate a new\n # swarm at this time if all of the swarms in the current sprint have\n # completed. This will insure that we don't mark the sprint as completed\n # before we've created all the possible swarms.\n sprintIdx = swarmInfo['sprintIdx']\n self.isSprintActive(sprintIdx)\n\n # Update the sprint status. Check all the swarms that belong to this sprint.\n # If they are all completed, the sprint is completed.\n sprintInfo = self._state['sprints'][sprintIdx]\n\n statusCounts = dict(active=0, completing=0, completed=0, killed=0)\n bestModelIds = []\n bestErrScores = []\n for info in self._state['swarms'].itervalues():\n if info['sprintIdx'] != sprintIdx:\n continue\n statusCounts[info['status']] += 1\n if info['status'] == 'completed':\n bestModelIds.append(info['bestModelId'])\n bestErrScores.append(info['bestErrScore'])\n\n if statusCounts['active'] > 0:\n sprintStatus = 'active'\n elif statusCounts['completing'] > 0:\n sprintStatus = 'completing'\n else:\n sprintStatus = 'completed'\n sprintInfo['status'] = sprintStatus\n\n # If the sprint is complete, get the best model from all of its swarms and\n # store that as the sprint best\n if sprintStatus == 'completed':\n if len(bestErrScores) > 0:\n whichIdx = numpy.array(bestErrScores).argmin()\n sprintInfo['bestModelId'] = bestModelIds[whichIdx]\n sprintInfo['bestErrScore'] = bestErrScores[whichIdx]\n else:\n # This sprint was empty, most likely because all particles were\n # killed. Give it a huge error score\n sprintInfo['bestModelId'] = 0\n sprintInfo['bestErrScore'] = numpy.inf\n\n\n # See if our best err score got NO BETTER as compared to a previous\n # sprint. If so, stop exploring subsequent sprints (lastGoodSprint\n # is no longer None).\n bestPrior = numpy.inf\n for idx in range(sprintIdx):\n if self._state['sprints'][idx]['status'] == 'completed':\n (_, errScore) = self.bestModelInCompletedSprint(idx)\n if errScore is None:\n errScore = numpy.inf\n else:\n errScore = numpy.inf\n if errScore < bestPrior:\n bestPrior = errScore\n\n if sprintInfo['bestErrScore'] >= bestPrior:\n self._state['lastGoodSprint'] = sprintIdx-1\n\n # If ALL sprints up to the last good one are done, the search is now over\n if self._state['lastGoodSprint'] is not None \\\n and not self.anyGoodSprintsActive():\n self._state['searchOver'] = True", "docstring": "Change the given swarm's state to 'newState'. If 'newState' is\n 'completed', then bestModelId and bestErrScore must be provided.\n\n Parameters:\n ---------------------------------------------------------------------\n swarmId: swarm Id\n newStatus: new status, either 'active', 'completing', 'completed', or\n 'killed'", "source": "juraj_google_style"} +{"code": "def create_s3_bucket(cls, bucket_name, bucket_region, bucket_account, template):\n\n s3 = get_aws_session(bucket_account).client('s3', region_name=bucket_region)\n\n # Check to see if the bucket already exists and if we have access to it\n try:\n s3.head_bucket(Bucket=bucket_name)\n except ClientError as ex:\n status_code = ex.response['ResponseMetadata']['HTTPStatusCode']\n\n # Bucket exists and we do not have access\n if status_code == 403:\n raise Exception('Bucket {} already exists but we do not have access to it and so cannot continue'.format(\n bucket_name\n ))\n\n # Bucket does not exist, lets create one\n elif status_code == 404:\n try:\n s3.create_bucket(\n Bucket=bucket_name,\n CreateBucketConfiguration={\n 'LocationConstraint': bucket_region\n }\n )\n\n auditlog(\n event='cloudtrail.create_s3_bucket',\n actor=cls.ns,\n data={\n 'account': bucket_account.account_name,\n 'bucket_region': bucket_region,\n 'bucket_name': bucket_name\n }\n )\n except Exception:\n raise Exception('An error occured while trying to create the bucket, cannot continue')\n\n try:\n bucket_acl = template.render(\n bucket_name=bucket_name,\n account_id=bucket_account.account_number\n )\n s3.put_bucket_policy(Bucket=bucket_name, Policy=bucket_acl)\n\n except Exception as ex:\n raise Warning('An error occurred while setting bucket policy: {}'.format(ex))", "docstring": "Creates the S3 bucket on the account specified as the destination account for log files\n\nArgs:\n bucket_name (`str`): Name of the S3 bucket\n bucket_region (`str`): AWS Region for the bucket\n bucket_account (:obj:`Account`): Account to create the S3 bucket in\n template (:obj:`Template`): Jinja2 Template object for the bucket policy\n\nReturns:\n `None`", "source": "juraj_google_style"} +{"code": "def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):\n\n\n if not current_app.testing: # pragma: no cover\n try:\n # Prepare Sendgrid helper objects\n from sendgrid.helpers.mail import Email, Content, Substitution, Mail\n from_email = Email(sender_email, sender_name)\n to_email = Email(recipient)\n text_content = Content('text/plain', text_message)\n html_content = Content('text/html', html_message)\n # Prepare Sendgrid Mail object\n # Note: RFC 1341: text must be first, followed by html\n mail = Mail(from_email, subject, to_email, text_content)\n mail.add_content(html_content)\n # Send mail via the Sendgrid API\n response = self.sg.client.mail.send.post(request_body=mail.get())\n print(response.status_code)\n print(response.body)\n print(response.headers)\n except ImportError:\n raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)\n except Exception as e:\n print(e)\n print(e.body)\n raise", "docstring": "Send email message via sendgrid-python.\n\nArgs:\n recipient: Email address or tuple of (Name, Email-address).\n subject: Subject line.\n html_message: The message body in HTML.\n text_message: The message body in plain text.", "source": "juraj_google_style"} +{"code": "def new(self):\n # type: () -> None\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('PD record already initialized!')\n\n self._initialized = True\n self.padding = b''", "docstring": "Create a new Rock Ridge Platform Dependent record.\n\n Parameters:\n None.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def write_inputs(self, output_dir, **kwargs):\n\n write_lammps_inputs(output_dir=output_dir,\n script_template=self.script_template,\n settings=self.settings, data=self.data,\n script_filename=self.script_filename, **kwargs)", "docstring": "Writes all input files (input script, and data if needed).\n Other supporting files are not handled at this moment.\n\nArgs:\n output_dir (str): Directory to output the input files.\n **kwargs: kwargs supported by LammpsData.write_file.", "source": "juraj_google_style"} +{"code": "def search(self, query, verbose=0):\n\n if verbose > 0:\n print(\"searching \" + query)\n query = query.lower()\n qgram = ng(query, self.slb)\n qocument = set()\n for q in qgram:\n if q in self.ngrams.keys():\n for i in self.ngrams[q]:\n qocument.add(i)\n self.qocument = qocument\n results = {}\n for i in qocument:\n for j in self.D[i].keys():\n if not j in results.keys():\n results[j] = 0\n results[j] = results[j] + self.D[i][j]\n sorted_results = sorted(results.items(), key=operator.itemgetter(1), reverse=True)\n return [self.elements[f[0]] for f in sorted_results]", "docstring": "Searches files satisfying query\n\n It first decompose the query in ngrams, then score each document containing\n at least one ngram with the number. The ten document having the most ngrams\n in common with the query are selected.\n\nArgs:\n query (str): what to search;\n results_number (int): number of results to return (default: 10)", "source": "juraj_google_style"} +{"code": "def __init__(self, endpoint_name, sagemaker_session=None):\n\n super(ChainerPredictor, self).__init__(endpoint_name, sagemaker_session, npy_serializer, numpy_deserializer)", "docstring": "Initialize an ``ChainerPredictor``.\n\nArgs:\n endpoint_name (str): The name of the endpoint to perform inference on.\n sagemaker_session (sagemaker.session.Session): Session object which manages interactions with\n Amazon SageMaker APIs and any other AWS services needed. If not specified, the estimator creates one\n using the default AWS configuration chain.", "source": "juraj_google_style"} +{"code": "def extend(*args):\n\n if not args:\n return {}\n\n first = args[0]\n rest = args[1:]\n out = type(first)(first)\n for each in rest:\n out.update(each)\n return out", "docstring": "shallow dictionary merge\n\nArgs:\n a: dict to extend\n b: dict to apply to a\n\nReturns:\n new instance of the same type as _a_, with _a_ and _b_ merged.", "source": "juraj_google_style"} +{"code": "def _from_axis_angle(cls, axis, angle):\n\n mag_sq = np.dot(axis, axis)\n if mag_sq == 0.0:\n raise ZeroDivisionError(\"Provided rotation axis has no length\")\n # Ensure axis is in unit vector form\n if (abs(1.0 - mag_sq) > 1e-12):\n axis = axis / sqrt(mag_sq)\n theta = angle / 2.0\n r = cos(theta)\n i = axis * sin(theta)\n\n return cls(r, i[0], i[1], i[2])", "docstring": "Initialise from axis and angle representation\n\n Create a Quaternion by specifying the 3-vector rotation axis and rotation\n angle (in radians) from which the quaternion's rotation should be created.\n\n Params:\n axis: a valid numpy 3-vector\n angle: a real valued angle in radians", "source": "juraj_google_style"} +{"code": "def noise_get_fbm(\n n: tcod.noise.Noise,\n f: Sequence[float],\n oc: float,\n typ: int = NOISE_DEFAULT,\n) -> float:\n\n return float(\n lib.TCOD_noise_get_fbm_ex(n.noise_c, ffi.new(\"float[4]\", f), oc, typ)\n )", "docstring": "Return the fractal Brownian motion sampled from the ``f`` coordinate.\n\nArgs:\n n (Noise): A Noise instance.\n f (Sequence[float]): The point to sample the noise from.\n typ (int): The noise algorithm to use.\n octaves (float): The level of level. Should be more than 1.\n\nReturns:\n float: The sampled noise value.", "source": "juraj_google_style"} +{"code": "def add_candidate_peer_endpoints(self, peer_endpoints):\n\n with self._lock:\n for endpoint in peer_endpoints:\n if endpoint not in self._candidate_peer_endpoints:\n self._candidate_peer_endpoints.append(endpoint)", "docstring": "Adds candidate endpoints to the list of endpoints to\n attempt to peer with.\n\nArgs:\n peer_endpoints ([str]): A list of public uri's which the\n validator can attempt to peer with.", "source": "juraj_google_style"} +{"code": "def _process_dataset(name, directory, num_shards, synset_to_human,\n image_to_bboxes):\n\n filenames, synsets, labels = _find_image_files(directory, FLAGS.labels_file)\n humans = _find_human_readable_labels(synsets, synset_to_human)\n bboxes = _find_image_bounding_boxes(filenames, image_to_bboxes)\n _process_image_files(name, filenames, synsets, labels,\n humans, bboxes, num_shards)", "docstring": "Process a complete data set and save it as a TFRecord.\n\nArgs:\n name: string, unique identifier specifying the data set.\n directory: string, root path to the data set.\n num_shards: integer number of shards for this data set.\n synset_to_human: dict of synset to human labels, e.g.,\n 'n02119022' --> 'red fox, Vulpes vulpes'\n image_to_bboxes: dictionary mapping image file names to a list of\n bounding boxes. This list contains 0+ bounding boxes.", "source": "juraj_google_style"} +{"code": "def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n\n local_stream = utils.BytearrayStream()\n\n if self._unique_identifier is not None:\n self._unique_identifier.write(\n local_stream,\n kmip_version=kmip_version\n )\n if self._offset is not None:\n self._offset.write(local_stream, kmip_version=kmip_version)\n if self._template_attribute is not None:\n self._template_attribute.write(\n local_stream,\n kmip_version=kmip_version\n )\n\n self.length = local_stream.length()\n super(RekeyRequestPayload, self).write(\n output_stream,\n kmip_version=kmip_version\n )\n output_stream.write(local_stream.buffer)", "docstring": "Write the data encoding the Rekey request payload to a stream.\n\nArgs:\n output_stream (stream): A data stream in which to encode object\n data, supporting a write method; usually a BytearrayStream\n object.\n kmip_version (KMIPVersion): An enumeration defining the KMIP\n version with which the object will be encoded. Optional,\n defaults to KMIP 1.0.", "source": "juraj_google_style"} +{"code": "def duration_to_string(duration):\n\n\n m, s = divmod(duration, 60)\n h, m = divmod(m, 60)\n return \"%d:%02d:%02d\" % (h, m, s)", "docstring": "Converts a duration to a string\n\nArgs:\n duration (int): The duration in seconds to convert\n\n Returns s (str): The duration as a string", "source": "juraj_google_style"} +{"code": "def forward(self, device_port, local_port=None):\n\n port = self._adb_device.forward(device_port, local_port)\n return (self._host, port)", "docstring": "Forward device port to local\n\nArgs:\n device_port: port inside device\n local_port: port on PC, if this value is None, a port will random pick one.\n\nReturns:\n tuple, (host, local_port)", "source": "juraj_google_style"} +{"code": "def _read_accept_states(self):\n\n states = []\n i = 0\n regex = re.compile('[ \\t\\n\\r:,]+')\n found = 0 # For maintaining the state of yy_accept declaration\n state = 0 # For maintaining the state of opening and closing tag of yy_accept\n mapping = [] # For writing each set of yy_accept\n cur_line = None\n with open(self.outfile) as flex_file:\n for cur_line in flex_file:\n if cur_line[0:37] == \"static yyconst flex_int16_t yy_accept\" or cur_line[0:35] == \"static const flex_int16_t yy_accept\":\n found = 1\n continue\n if found == 1:\n # print x\n if state == 0 and cur_line[0:5] == \" {\":\n mapping.append(0) # there is always a zero there\n state = 1\n continue\n\n if state == 1:\n if cur_line[0:7] != \" } ;\":\n cur_line = \"\".join(cur_line.split())\n if cur_line == '':\n continue\n if cur_line[cur_line.__len__() - 1] == ',':\n splitted_line = regex.split(\n cur_line[:cur_line.__len__() - 1])\n else:\n splitted_line = regex.split(cur_line)\n mapping = mapping + splitted_line\n continue\n else:\n cleared = []\n for j in mapping:\n cleared.append(int(j))\n max_value = max(cleared)\n for i in range(0, len(cleared)):\n if cleared[i] > 0 and cleared[\n i] < (max_value - 1):\n states.append(i)\n return states\n return []", "docstring": "Read DFA accepted states from flex compiled file\n\nArgs:\n None\n\nReturns:\n list: The list of accepted states", "source": "juraj_google_style"} +{"code": "def loopUntil(\n self, condition=None, timeout: float = 0) -> Iterator[object]:\n\n endTime = time.time() + timeout\n while True:\n test = condition and condition()\n if test:\n yield test\n return\n elif timeout and time.time() > endTime:\n yield False\n return\n else:\n yield test\n self.waitOnUpdate(endTime - time.time() if timeout else 0)", "docstring": "Iterate until condition is met, with optional timeout in seconds.\n The yielded value is that of the condition or False when timed out.\n\nArgs:\n condition: Predicate function that is tested after every network\n update.\n timeout: Maximum time in seconds to wait.\n If 0 then no timeout is used.", "source": "juraj_google_style"} +{"code": "def _add_function(self, func, identify_observed):\n\n\n key = self.make_key(func)\n if key not in self.observers:\n self.observers[key] = ObserverFunction(\n func, identify_observed, (key, self.observers))\n return True\n else:\n return False", "docstring": "Add a function as an observer.\n\nArgs:\n func: The function to register as an observer.\n identify_observed: See docstring for add_observer.\n\nReturns:\n True if the function is added, otherwise False.", "source": "juraj_google_style"} +{"code": "def ohlc(symbol, token='', version=''):\n\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/ohlc', token, version)", "docstring": "Returns the official open and close for a give symbol.\n\n https://iexcloud.io/docs/api/#news\n 9:30am-5pm ET Mon-Fri\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n dict: result", "source": "juraj_google_style"} +{"code": "def back_propagation(self, delta_arr):\n\n re_encoder_delta_arr, delta_hidden_arr, re_encoder_grads_list = self.__retrospective_encoder.hidden_back_propagate(\n delta_arr[:, -1]\n )\n re_encoder_grads_list.insert(0, None)\n re_encoder_grads_list.insert(0, None)\n\n observed_arr, encoded_arr, decoded_arr, re_encoded_arr = self.__inferenced_tuple\n delta_arr = self.__encoder_decoder_controller.computable_loss.compute_delta(\n decoded_arr, \n observed_arr\n )\n delta_arr[:, -1] += re_encoder_delta_arr[:, -1]\n\n decoder_grads_list, encoder_delta_arr, encoder_grads_list = self.__encoder_decoder_controller.back_propagation(\n delta_arr\n )\n return re_encoder_grads_list, decoder_grads_list, encoder_delta_arr, encoder_grads_list", "docstring": "Back propagation.\n\nArgs:\n delta_output_arr: Delta.\n\nReturns:\n Tuple data.\n - decoder's `list` of gradations,\n - encoder's `np.ndarray` of Delta,\n - encoder's `list` of gradations.", "source": "juraj_google_style"} +{"code": "def guess_peb_size(path):\n\n file_offset = 0\n offsets = []\n f = open(path, 'rb')\n f.seek(0,2)\n file_size = f.tell()+1\n f.seek(0)\n\n for _ in range(0, file_size, FILE_CHUNK_SZ):\n buf = f.read(FILE_CHUNK_SZ)\n for m in re.finditer(UBI_EC_HDR_MAGIC, buf):\n start = m.start()\n\n if not file_offset:\n file_offset = start\n idx = start\n else:\n idx = start+file_offset\n\n offsets.append(idx)\n\n file_offset += FILE_CHUNK_SZ\n f.close()\n\n occurances = {}\n for i in range(0, len(offsets)):\n try:\n diff = offsets[i] - offsets[i-1]\n except:\n diff = offsets[i]\n\n if diff not in occurances:\n occurances[diff] = 0\n\n occurances[diff] += 1\n\n most_frequent = 0\n block_size = None\n\n for offset in occurances:\n if occurances[offset] > most_frequent:\n most_frequent = occurances[offset]\n block_size = offset\n\n return block_size", "docstring": "Determine the most likely block size\n\nArgs:\n Str:path -- Path to file.\n\nReturns:\n Int -- PEB size.\n\n Searches file for Magic Number, picks most\n common length between them.", "source": "juraj_google_style"} +{"code": "def __init__(self, kind, required=False, default_factory=None,\n can_be_none=False):\n\n if required and default_factory is not None:\n raise ValueError(\"No default_factory value when option is required.\")\n self.kind = kind\n self.required = required\n self.default_factory = default_factory\n self.can_be_none = can_be_none", "docstring": "Init.\n\nArgs:\n kind: type of the option.\n required: whether user is required to supply a value.\n default_factory: a factory, when called, returns the default value.\n can_be_none: whether value can be None.\n\nRaises:\n ValueError: if arguments aren't compatible.", "source": "juraj_google_style"} +{"code": "def serialize_to_xml(root, block):\n\n root.tag = 'ubcpi'\n\n if block.rationale_size is not None:\n if block.rationale_size.get('min'):\n root.set('rationale_size_min', unicode(block.rationale_size.get('min')))\n if block.rationale_size.get('max'):\n root.set('rationale_size_max', unicode(block.rationale_size['max']))\n\n if block.algo:\n if block.algo.get('name'):\n root.set('algorithm', block.algo.get('name'))\n if block.algo.get('num_responses'):\n root.set('num_responses', unicode(block.algo.get('num_responses')))\n\n display_name = etree.SubElement(root, 'display_name')\n display_name.text = block.display_name\n\n question = etree.SubElement(root, 'question')\n question_text = etree.SubElement(question, 'text')\n question_text.text = block.question_text['text']\n serialize_image(block.question_text, question)\n\n options = etree.SubElement(root, 'options')\n serialize_options(options, block)\n\n seeds = etree.SubElement(root, 'seeds')\n serialize_seeds(seeds, block)", "docstring": "Serialize the Peer Instruction XBlock's content to XML.\n\nArgs:\n block (PeerInstructionXBlock): The peer instruction block to serialize.\n root (etree.Element): The XML root node to update.\n\nReturns:\n etree.Element", "source": "juraj_google_style"} +{"code": "def _expect(self, expected, times=50):\n\n logger.debug('[%s] Expecting [%s]', self.port, expected)\n retry_times = 10\n while times:\n if not retry_times:\n break\n\n line = self._readline()\n\n if line == expected:\n return\n\n if not line:\n retry_times -= 1\n time.sleep(0.1)\n\n times -= 1\n\n raise Exception('failed to find expected string[%s]' % expected)", "docstring": "Find the `expected` line within `times` trials.\n\nArgs:\n expected str: the expected string\n times int: number of trials", "source": "juraj_google_style"} +{"code": "def add_config(self, slot, config_id, config_type, value):\n\n\n if slot not in self.config_database:\n self.config_database[slot] = {}\n\n self.config_database[slot][config_id] = (config_type, value)", "docstring": "Add a config variable assignment to this sensor graph.\n\nArgs:\n slot (SlotIdentifier): The slot identifier that this config\n variable is assigned to.\n config_id (int): The 16-bit id of this config_id\n config_type (str): The type of the config variable, currently\n supported are fixed width integer types, strings and binary\n blobs.\n value (str|int|bytes): The value to assign to the config variable.", "source": "juraj_google_style"} +{"code": "def _ImportPythonModule(module_name):\n\n try:\n module_object = list(map(__import__, [module_name]))[0]\n except ImportError:\n return None\n\n # If the module name contains dots get the upper most module object.\n if '.' in module_name:\n for submodule_name in module_name.split('.')[1:]:\n module_object = getattr(module_object, submodule_name, None)\n\n return module_object", "docstring": "Imports a Python module.\n\nArgs:\n module_name (str): name of the module.\n\nReturns:\n module: Python module or None if the module cannot be imported.", "source": "juraj_google_style"} +{"code": "def PrintMessage(self, message):\n\n if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and\n self.descriptor_pool and self._TryPrintAsAnyMessage(message)):\n return\n fields = message.ListFields()\n if self.use_index_order:\n fields.sort(key=lambda x: x[0].index)\n for field, value in fields:\n if _IsMapEntry(field):\n for key in sorted(value):\n # This is slow for maps with submessage entires because it copies the\n # entire tree. Unfortunately this would take significant refactoring\n # of this file to work around.\n #\n # TODO(haberman): refactor and optimize if this becomes an issue.\n entry_submsg = value.GetEntryClass()(key=key, value=value[key])\n self.PrintField(field, entry_submsg)\n elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n for element in value:\n self.PrintField(field, element)\n else:\n self.PrintField(field, value)", "docstring": "Convert protobuf message to text format.\n\nArgs:\n message: The protocol buffers message.", "source": "juraj_google_style"} +{"code": "def CreateFeedItemAddOperation(name, price, date, ad_customizer_feed):\n\n feed_item = {\n 'feedId': ad_customizer_feed['feedId'],\n 'attributeValues': [\n {\n 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'],\n 'stringValue': name\n },\n {\n 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'],\n 'stringValue': price\n },\n {\n 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'],\n 'stringValue': date\n }\n ]\n }\n\n operation = {\n 'operator': 'ADD',\n 'operand': feed_item\n }\n\n return operation", "docstring": "Creates a FeedItemOperation.\n\n The generated FeedItemOperation will create a FeedItem with the specified\n values when sent to FeedItemService.mutate.\n\nArgs:\n name: the value for the name attribute of the FeedItem.\n price: the value for the price attribute of the FeedItem.\n date: the value for the date attribute of the FeedItem.\n ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems\n with.\n\nReturns:\n A new FeedItemOperation for adding a FeedItem.", "source": "juraj_google_style"} +{"code": "def datasets_insert(self, dataset_name, friendly_name=None, description=None):\n\n url = Api._ENDPOINT + (Api._DATASETS_PATH % (dataset_name.project_id, ''))\n data = {\n 'kind': 'bigquery#dataset',\n 'datasetReference': {\n 'projectId': dataset_name.project_id,\n 'datasetId': dataset_name.dataset_id\n },\n }\n if friendly_name:\n data['friendlyName'] = friendly_name\n if description:\n data['description'] = description\n return datalab.utils.Http.request(url, data=data, credentials=self._credentials)", "docstring": "Issues a request to create a dataset.\n\nArgs:\n dataset_name: the name of the dataset to create.\n friendly_name: (optional) the friendly name for the dataset\n description: (optional) a description for the dataset\n\nReturns:\n A parsed result object.\n\nRaises:\n Exception if there is an error performing the operation.", "source": "juraj_google_style"} +{"code": "def get(self, title):\n\n key = '/library/sections/%s/all' % self.key\n return self.fetchItem(key, title__iexact=title)", "docstring": "Returns the media item with the specified title.\n\n Parameters:\n title (str): Title of the item to return.", "source": "juraj_google_style"} +{"code": "def import_tsv(self, tsv_file):\n\n r = fapi.upload_entities_tsv(self.namespace, self.name,\n self.tsv_file, self.api_url)\n fapi._check_response_code(r, 201)", "docstring": "Upload entity data to workspace from tsv loadfile.\n\nArgs:\n tsv_file (file): Tab-delimited file of entity data", "source": "juraj_google_style"} +{"code": "def read(self, n):\n\n if self._EOF:\n return \"\"\n\n while self._seg_index <= self._last_seg_index:\n result = self._read_from_seg(n)\n if result != \"\":\n return result\n else:\n self._next_seg()\n\n self._EOF = True\n return \"\"", "docstring": "Read data from file segs.\n\nArgs:\n n: max bytes to read. Must be positive.\n\nReturns:\n some bytes. May be smaller than n bytes. \"\" when no more data is left.", "source": "juraj_google_style"} +{"code": "def _get_expiration(self, headers: dict) -> int:\n\n expiration_str = headers.get('expires')\n if not expiration_str:\n return 0\n expiration = datetime.strptime(expiration_str, '%a, %d %b %Y %H:%M:%S %Z')\n delta = (expiration - datetime.utcnow()).total_seconds()\n return math.ceil(abs(delta))", "docstring": "Gets the expiration time of the data from the response headers.\n\nArgs:\n headers: dictionary of headers from ESI\n\nReturns:\n value of seconds from now the data expires", "source": "juraj_google_style"} +{"code": "def check_imported(module):\n\n imported = True\n module_info = ('', '', '')\n # TODO: if possible, update to a cleaner method that doesn't require importing the module\n # and running inline code.\n try:\n importlib.import_module(module)\n module_info = imp.find_module(module)\n except ImportError:\n imported = False\n\n # get module path\n module_path = module_info[1]\n description = module_info[2]\n\n if not description:\n # if description is None or empty string the module could not be imported\n imported = False\n elif not description and not module_path:\n # if description/module_path are None or empty string the module could not be imported\n imported = False\n elif module_path is not None and (\n 'dist-packages' in module_path or 'site-packages' in module_path\n ):\n # if dist-packages|site-packages in module_path the import doesn't count\n imported = False\n return imported", "docstring": "Check whether the provide module can be imported (package installed).\n\nArgs:\n module (str): The name of the module to check availability.\n\nReturns:\n bool: True if the module can be imported, False otherwise.", "source": "juraj_google_style"} +{"code": "def _map_condition(self, wire_map, condition):\n\n if condition is None:\n new_condition = None\n else:\n # Map the register name, using fact that registers must not be\n # fragmented by the wire_map (this must have been checked\n # elsewhere)\n bit0 = (condition[0], 0)\n new_condition = (wire_map.get(bit0, bit0)[0], condition[1])\n return new_condition", "docstring": "Use the wire_map dict to change the condition tuple's creg name.\n\nArgs:\n wire_map (dict): a map from wires to wires\n condition (tuple): (ClassicalRegister,int)\n\nReturns:\n tuple(ClassicalRegister,int): new condition", "source": "juraj_google_style"} +{"code": "def expect_false(condition, msg, extras=None):\n\n try:\n asserts.assert_false(condition, msg, extras)\n except signals.TestSignal as e:\n logging.exception('Expected a `False` value, got `True`.')\n recorder.add_error(e)", "docstring": "Expects an expression evaluates to False.\n\n If the expectation is not met, the test is marked as fail after its\n execution finishes.\n\nArgs:\n expr: The expression that is evaluated.\n msg: A string explaining the details in case of failure.\n extras: An optional field for extra information to be included in test\n result.", "source": "juraj_google_style"} +{"code": "def __init__(self, data_type_definition):\n\n super(StructureMap, self).__init__(data_type_definition)\n self._attribute_names = self._GetAttributeNames(data_type_definition)\n self._data_type_map_cache = {}\n self._data_type_maps = self._GetMemberDataTypeMaps(\n data_type_definition, self._data_type_map_cache)\n self._fold_byte_stream = None\n self._format_string = None\n self._map_byte_stream = None\n self._number_of_attributes = len(self._attribute_names)\n self._operation = None\n self._structure_values_class = (\n runtime.StructureValuesClassFactory.CreateClass(\n data_type_definition))\n\n if self._CheckCompositeMap(data_type_definition):\n self._fold_byte_stream = self._CompositeFoldByteStream\n self._map_byte_stream = self._CompositeMapByteStream\n else:\n self._fold_byte_stream = self._LinearFoldByteStream\n self._map_byte_stream = self._LinearMapByteStream\n self._operation = self._GetByteStreamOperation()", "docstring": "Initializes a structure data type map.\n\nArgs:\n data_type_definition (DataTypeDefinition): data type definition.", "source": "juraj_google_style"} +{"code": "def __init__(self, mpls_ttl=None):\n\n super().__init__(action_type=ActionType.OFPAT_SET_MPLS_TTL, length=8)\n self.mpls_ttl = mpls_ttl", "docstring": "Create an ActionSetMPLSTTL with the optional parameters below.\n\nArgs:\n mpls_ttl (int): The mpls_ttl field is the MPLS TTL to set.", "source": "juraj_google_style"} +{"code": "def _parse_authors(authors):\n\n link = authors.find(\"a\")\n link = link[0].params.get(\"href\") if link else None\n\n author_list = _strip_content(authors)\n\n if \"(\" in author_list:\n author_list = author_list.split(\"(\")[0]\n\n if not author_list.strip():\n return []\n\n return map(\n lambda author: Author(author.strip(), link),\n author_list.strip().split(\",\")\n )", "docstring": "Parse informations about authors of the book.\n\nArgs:\n dom (obj): HTMLElement containing slice of the page with details.\n\nReturns:\n list: List of :class:`.Author` objects. Blank if no author \\\n found.", "source": "juraj_google_style"} +{"code": "def GetMessages(self, formatter_mediator, event):\n\n if self.DATA_TYPE != event.data_type:\n raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(\n event.data_type))\n\n event_values = event.CopyToDict()\n\n restore_point_event_type = event_values.get(\n 'restore_point_event_type', None)\n if restore_point_event_type is not None:\n event_values['restore_point_event_type'] = (\n self._RESTORE_POINT_EVENT_TYPES.get(\n restore_point_event_type, 'UNKNOWN'))\n\n restore_point_type = event_values.get('restore_point_type', None)\n if restore_point_type is not None:\n event_values['restore_point_type'] = (\n self._RESTORE_POINT_EVENT_TYPES.get(restore_point_type, 'UNKNOWN'))\n\n return self._ConditionalFormatMessages(event_values)", "docstring": "Determines the formatted message strings for an event object.\n\nArgs:\n formatter_mediator (FormatterMediator): mediates the interactions\n between formatters and other components, such as storage and Windows\n EventLog resources.\n event (EventObject): event.\n\nReturns:\n tuple(str, str): formatted message string and short message string.\n\nRaises:\n WrongFormatter: if the event object cannot be formatted by the formatter.", "source": "juraj_google_style"} +{"code": "def reset_port_protection(self, id_or_uri, timeout=-1):\n\n uri = self._client.build_uri(id_or_uri) + \"/resetportprotection\"\n return self._client.update_with_zero_body(uri, timeout)", "docstring": "Triggers a reset of port protection.\n\n Cause port protection to be reset on all the interconnects of the logical interconnect that matches ID.\n\nArgs:\n id_or_uri: Can be either the interconnect id or the interconnect uri.\n timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n in OneView; it just stops waiting for its completion.\n\nReturns:\n dict: The interconnect.", "source": "juraj_google_style"} +{"code": "def predict(parameters, X):\n\n\n # Computes probabilities using forward propagation,\n # and classifies to 0/1 using 0.5 as the threshold.\n A2, cache = forward_propagation(X, parameters)\n predictions = np.array([1 if (i > 0.5) else 0 for i in A2[0]])\n\n return predictions", "docstring": "Using the learned parameters, predicts a class for each example in X\n\nArgs:\n parameters -- python dictionary containing your parameters\n X -- input data of size (n_x, m)\n\n Returns\n predictions -- vector of predictions of our model (red: 0 / blue: 1)", "source": "juraj_google_style"} +{"code": "def ParseSMS(self, parser_mediator, query, row, **unused_kwargs):\n\n query_hash = hash(query)\n\n phone_number = self._GetRowValue(query_hash, row, 'dstnum_sms')\n if phone_number:\n phone_number = phone_number.replace(' ', '')\n\n event_data = SkypeSMSEventData()\n event_data.number = phone_number\n event_data.query = query\n event_data.text = self._GetRowValue(query_hash, row, 'msg_sms')\n\n timestamp = self._GetRowValue(query_hash, row, 'time_sms')\n if timestamp:\n date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(date_time, 'SMS from Skype')\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses an SMS.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n query (str): query that created the row.\n row (sqlite3.Row): row resulting from query.", "source": "juraj_google_style"} +{"code": "def norm(self, coords: Vector3Like, frac_coords: bool = True) -> float:\n\n return np.sqrt(self.dot(coords, coords, frac_coords=frac_coords))", "docstring": "Compute the norm of vector(s).\n\nArgs:\n coords:\n Array-like object with the coordinates.\n frac_coords:\n Boolean stating whether the vector corresponds to fractional or\n cartesian coordinates.\n\nReturns:\n one-dimensional `numpy` array.", "source": "juraj_google_style"} +{"code": "def util_pattern_space(time_series, lag, dim):\n\n n = len(time_series)\n\n if lag * dim > n:\n raise Exception('Result matrix exceeded size limit, try to change lag or dim.')\n elif lag < 1:\n raise Exception('Lag should be greater or equal to 1.')\n\n pattern_space = np.empty((n - lag * (dim - 1), dim))\n for i in range(n - lag * (dim - 1)):\n for j in range(dim):\n pattern_space[i][j] = time_series[i + j * lag]\n\n return pattern_space", "docstring": "Create a set of sequences with given lag and dimension\n\nArgs:\n time_series: Vector or string of the sample data\n lag: Lag between beginning of sequences\n dim: Dimension (number of patterns)\n\nReturns:\n 2D array of vectors", "source": "juraj_google_style"} +{"code": "def _setweights(self):\n\n for name_w in self.weights:\n raw_w = getattr(self.module, name_w + '_raw')\n w = torch.nn.functional.dropout(raw_w, p=self.dropout, training=self.training)\n if hasattr(self.module, name_w):\n delattr(self.module, name_w)\n setattr(self.module, name_w, w)", "docstring": "Uses pytorch's built-in dropout function to apply dropout to the parameters of\n the wrapped module.\n\nArgs:\n None\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def detect_format(program, attributes) -> str:\n\n\n def fmt(attr):\n\n\n return attr.array_length * attr.dimension, attr.shape\n\n return ' '.join('%d%s' % fmt(program[a]) for a in attributes)", "docstring": "Detect format for vertex attributes.\n The format returned does not contain padding.\n\nArgs:\n program (Program): The program.\n attributes (list): A list of attribute names.\n\nReturns:\n str", "source": "juraj_google_style"} +{"code": "def ask_yes_no(question, default='no', answer=None):\n u\n default = default.lower()\n yes = [u'yes', u'ye', u'y']\n no = [u'no', u'n']\n if default in no:\n help_ = u'[N/y]?'\n default = False\n else:\n default = True\n help_ = u'[Y/n]?'\n while 1:\n display = question + '\\n' + help_\n if answer is None:\n log.debug(u'Under None')\n answer = six.moves.input(display)\n answer = answer.lower()\n if answer == u'':\n log.debug(u'Under blank')\n return default\n if answer in yes:\n log.debug(u'Must be true')\n return True\n elif answer in no:\n log.debug(u'Must be false')\n return False\n else:\n sys.stdout.write(u'Please answer yes or no only!\\n\\n')\n sys.stdout.flush()\n answer = None\n six.moves.input(u'Press enter to continue')\n sys.stdout.write('\\n\\n\\n\\n\\n')\n sys.stdout.flush()", "docstring": "u\"\"\"Will ask a question and keeps prompting until\n answered.\n\nArgs:\n question (str): Question to ask end user\n\n default (str): Default answer if user just press enter at prompt\n\n answer (str): Used for testing\n\nReturns:\n (bool) Meaning:\n\n True - Answer is yes\n\n False - Answer is no", "source": "juraj_google_style"} +{"code": "def ParsePathItem(item, opts=None):\n\n if item == os.path.curdir:\n return CurrentComponent()\n\n if item == os.path.pardir:\n return ParentComponent()\n\n recursion = PATH_RECURSION_REGEX.search(item)\n if recursion is None:\n return GlobComponent(item, opts)\n\n start, end = recursion.span()\n if not (start == 0 and end == len(item)):\n raise ValueError(\"malformed recursive component\")\n\n if recursion.group(\"max_depth\"):\n max_depth = int(recursion.group(\"max_depth\"))\n else:\n max_depth = None\n\n return RecursiveComponent(max_depth=max_depth, opts=opts)", "docstring": "Parses string path component to an `PathComponent` instance.\n\nArgs:\n item: A path component string to be parsed.\n opts: A `PathOpts` object.\n\nReturns:\n `PathComponent` instance corresponding to given path fragment.\n\nRaises:\n ValueError: If the path item contains a recursive component fragment but\n cannot be parsed as such.", "source": "juraj_google_style"} +{"code": "def select_symbols(self, symbols, ret_list=False):\n\n symbols = list_strings(symbols)\n exclude = symbols[0].startswith(\"-\")\n\n if exclude:\n if not all(s.startswith(\"-\") for s in symbols):\n raise ValueError(\"When excluding symbols, all strings must start with `-`\")\n symbols = [s[1:] for s in symbols]\n\n symbols = set(symbols)\n pseudos = []\n for p in self:\n if exclude:\n if p.symbol in symbols: continue\n else:\n if p.symbol not in symbols: continue\n\n pseudos.append(p)\n\n if ret_list:\n return pseudos\n else:\n return self.__class__(pseudos)", "docstring": "Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols.\n\nArgs:\n symbols: str or list of symbols\n Prepend the symbol string with \"-\", to exclude pseudos.\n ret_list: if True a list of pseudos is returned instead of a :class:`PseudoTable`", "source": "juraj_google_style"} +{"code": "def logs_urlpatterns(admin_view=lambda x: x):\n\n return [\n url(r'^$',\n admin_view(LogsMenu.as_view()),\n name='logs'),\n url(r'^status_codes$',\n admin_view(LogsStatusCodes.as_view()),\n name='logs_status_codes'),\n url(r'^status_codes_by_date$',\n admin_view(LogsStatusCodesByDate.as_view()),\n name='logs_status_codes_by_date'),\n url(r'^most_visited_pages$',\n admin_view(LogsMostVisitedPages.as_view()),\n name='logs_most_visited_pages')\n ]", "docstring": "Return the URL patterns for the logs views.\n\nArgs:\n admin_view (callable): admin_view method from an AdminSite instance.\n\nReturns:\n list: the URL patterns for the logs views.", "source": "juraj_google_style"} +{"code": "def pull(self, device_filename, dest_file=None, timeout_ms=None):\n\n should_return_data = dest_file is None\n if isinstance(dest_file, six.string_types):\n dest_file = open(dest_file, 'w')\n elif dest_file is None:\n dest_file = six.StringIO()\n self.filesync_service.recv(device_filename, dest_file,\n timeouts.PolledTimeout.from_millis(timeout_ms))\n if should_return_data:\n return dest_file.getvalue()", "docstring": "Pull file from device.\n\nArgs:\n device_filename: The filename on the device to pull.\n dest_file: If set, a filename or writable file-like object.\n timeout_ms: Expected timeout for the pull.\n\nReturns:\n The file data if dest_file is not set, None otherwise.", "source": "juraj_google_style"} +{"code": "def add(self, other, axis=\"columns\", level=None, fill_value=None):\n\n return self._binary_op(\n \"add\", other, axis=axis, level=level, fill_value=fill_value\n )", "docstring": "Add this DataFrame to another or a scalar/list.\n\nArgs:\n other: What to add this this DataFrame.\n axis: The axis to apply addition over. Only applicaable to Series\n or list 'other'.\n level: A level in the multilevel axis to add over.\n fill_value: The value to fill NaN.\n\nReturns:\n A new DataFrame with the applied addition.", "source": "juraj_google_style"} +{"code": "def manufacturer(self):\n\n buf = ctypes.cast(self.sManu, ctypes.c_char_p).value\n return buf.decode() if buf else None", "docstring": "Returns the name of the manufacturer of the device.\n\nArgs:\n self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance\n\nReturns:\n Manufacturer name.", "source": "juraj_google_style"} +{"code": "def attention_bias_same_segment(query_segment_id, memory_segment_id):\n\n ret = (tf.to_float(\n tf.not_equal(\n tf.expand_dims(query_segment_id, 2),\n tf.expand_dims(memory_segment_id, 1))) *\n large_compatible_negative(memory_segment_id.dtype))\n return tf.expand_dims(ret, axis=1)", "docstring": "Create an bias tensor to be added to attention logits.\n\n Positions with the same segment_ids can see each other.\n\nArgs:\n query_segment_id: a float `Tensor` with shape [batch, query_length].\n memory_segment_id: a float `Tensor` with shape [batch, memory_length].\n\nReturns:\n a `Tensor` with shape [batch, 1, query_length, memory_length].", "source": "juraj_google_style"} +{"code": "def __init__(self, _args):\n\n super(TcExPackage, self).__init__(_args)\n\n # properties\n self.features = ['aotExecutionEnabled', 'secureParams']\n\n # properties\n self._app_packages = []\n self.package_data = {'errors': [], 'updates': [], 'bundle': [], 'package': []}\n self.validation_data = {}", "docstring": "Initialize Class properties.\n\nArgs:\n _args (namespace): The argparser args Namespace.", "source": "juraj_google_style"} +{"code": "def _GetApprovals(self,\n approval_type,\n offset,\n count,\n filter_func=None,\n token=None):\n\n approvals_base_urn = aff4.ROOT_URN.Add(\"users\").Add(\n token.username).Add(\"approvals\").Add(approval_type)\n\n all_children = aff4.FACTORY.RecursiveMultiListChildren([approvals_base_urn])\n\n approvals_urns = []\n for subject, children in all_children:\n # We only want to process leaf nodes.\n if children:\n continue\n approvals_urns.append(subject)\n\n approvals_urns.sort(key=lambda x: x.age, reverse=True)\n approvals = list(\n aff4.FACTORY.MultiOpen(\n approvals_urns,\n mode=\"r\",\n aff4_type=aff4_security.Approval,\n age=aff4.ALL_TIMES,\n token=token))\n approvals_by_urn = {}\n for approval in approvals:\n approvals_by_urn[approval.symlink_urn or approval.urn] = approval\n\n cur_offset = 0\n sorted_approvals = []\n for approval_urn in approvals_urns:\n try:\n approval = approvals_by_urn[approval_urn]\n except KeyError:\n continue\n\n if filter_func is not None and not filter_func(approval):\n continue\n cur_offset += 1\n if cur_offset <= offset:\n continue\n if count and len(sorted_approvals) >= count:\n break\n sorted_approvals.append(approval)\n\n subjects_urns = [a.Get(a.Schema.SUBJECT) for a in approvals]\n subjects_by_urn = {}\n for subject in aff4.FACTORY.MultiOpen(subjects_urns, mode=\"r\", token=token):\n subjects_by_urn[subject.urn] = subject\n\n return sorted_approvals, subjects_by_urn", "docstring": "Gets all approvals for a given user and approval type.\n\nArgs:\n approval_type: The type of approvals to get.\n offset: The starting index within the collection.\n count: The number of items to return.\n filter_func: A predicate function, returning True if a specific approval\n should be included in the result and False otherwise.\n token: The token identifying the user.\n\nReturns:\n A list of approvals of the given approval type.", "source": "juraj_google_style"} +{"code": "def parse_mapreduce_yaml(contents):\n\n try:\n builder = yaml_object.ObjectBuilder(MapReduceYaml)\n handler = yaml_builder.BuilderHandler(builder)\n listener = yaml_listener.EventListener(handler)\n listener.Parse(contents)\n\n mr_info = handler.GetResults()\n except (ValueError, yaml_errors.EventError), e:\n raise errors.BadYamlError(e)\n\n if len(mr_info) < 1:\n raise errors.BadYamlError(\"No configs found in mapreduce.yaml\")\n if len(mr_info) > 1:\n raise errors.MultipleDocumentsInMrYaml(\"Found %d YAML documents\" %\n len(mr_info))\n\n jobs = mr_info[0]\n job_names = set(j.name for j in jobs.mapreduce)\n if len(jobs.mapreduce) != len(job_names):\n raise errors.BadYamlError(\n \"Overlapping mapreduce names; names must be unique\")\n\n return jobs", "docstring": "Parses mapreduce.yaml file contents.\n\nArgs:\n contents: mapreduce.yaml file contents.\n\nReturns:\n MapReduceYaml object with all the data from original file.\n\nRaises:\n errors.BadYamlError: when contents is not a valid mapreduce.yaml file.", "source": "juraj_google_style"} +{"code": "def resolution(self, indicator=None):\n\n self._request_entity = 'dnsResolution'\n self._request_uri = '{}/dnsResolutions'.format(self._request_uri)\n if indicator is not None:\n self._request_uri = '{}/{}/dnsResolutions'.format(self._api_uri, indicator)", "docstring": "Update the URI to retrieve host resolutions for the provided indicator.\n\nArgs:\n indicator (string): The indicator to retrieve resolutions.", "source": "juraj_google_style"} +{"code": "def get_wallace_tensor(self, tau):\n\n b = 0.5 * (np.einsum(\"ml,kn->klmn\", tau, np.eye(3)) +\n np.einsum(\"km,ln->klmn\", tau, np.eye(3)) +\n np.einsum(\"nl,km->klmn\", tau, np.eye(3)) +\n np.einsum(\"kn,lm->klmn\", tau, np.eye(3)) +\n -2*np.einsum(\"kl,mn->klmn\", tau, np.eye(3)))\n strain = self.get_strain_from_stress(tau)\n b += self.get_effective_ecs(strain)\n return b", "docstring": "Gets the Wallace Tensor for determining yield strength\n criteria.\n\nArgs:\n tau (3x3 array-like): stress at which to evaluate\n the wallace tensor", "source": "juraj_google_style"} +{"code": "def _validate_user_inputs(self, attributes=None, event_tags=None):\n\n\n if attributes and not validator.are_attributes_valid(attributes):\n self.logger.error('Provided attributes are in an invalid format.')\n self.error_handler.handle_error(exceptions.InvalidAttributeException(enums.Errors.INVALID_ATTRIBUTE_FORMAT))\n return False\n\n if event_tags and not validator.are_event_tags_valid(event_tags):\n self.logger.error('Provided event tags are in an invalid format.')\n self.error_handler.handle_error(exceptions.InvalidEventTagException(enums.Errors.INVALID_EVENT_TAG_FORMAT))\n return False\n\n return True", "docstring": "Helper method to validate user inputs.\n\nArgs:\n attributes: Dict representing user attributes.\n event_tags: Dict representing metadata associated with an event.\n\nReturns:\n Boolean True if inputs are valid. False otherwise.", "source": "juraj_google_style"} +{"code": "def _edit_tags(self, tag, items, locked=True, remove=False):\n\n if not isinstance(items, list):\n items = [items]\n value = getattr(self, tag + 's')\n existing_cols = [t.tag for t in value if t and remove is False]\n d = tag_helper(tag, existing_cols + items, locked, remove)\n self.edit(**d)\n self.refresh()", "docstring": "Helper to edit and refresh a tags.\n\n Parameters:\n tag (str): tag name\n items (list): list of tags to add\n locked (bool): lock this field.\n remove (bool): If this is active remove the tags in items.", "source": "juraj_google_style"} +{"code": "def swd_read16(self, offset):\n\n value = self._dll.JLINK_SWD_GetU16(offset)\n return ctypes.c_uint16(value).value", "docstring": "Gets a unit of ``16`` bits from the input buffer.\n\nArgs:\n self (JLink): the ``JLink`` instance\n offset (int): the offset (in bits) from which to start reading\n\nReturns:\n The integer read from the input buffer.", "source": "juraj_google_style"} +{"code": "def supervised_to_dict(dataset, text2self):\n\n def my_fn(inputs, targets):\n if text2self:\n return {\"targets\": targets}\n else:\n return {\"inputs\": inputs, \"targets\": targets}\n return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)", "docstring": "Turns a supervised dataset into a dataset with a feature dictionary.\n\n if text2self, then the features dictionary contains a \"targets\" key.\n else, the features dictionary contains \"inputs\" and \"targets\" keys.\n\nArgs:\n dataset: a tf.data.Dataset\n text2self: a boolean\n\nReturns:\n a tf.data.Dataset", "source": "juraj_google_style"} +{"code": "def add(self, username, user_api, filename=None):\n\n keys = API.__get_keys(filename)\n user = user_api.find(username)[0]\n distinguished_name = user.entry_dn\n if 'ldapPublicKey' not in user.objectClass:\n raise ldap3.core.exceptions.LDAPNoSuchAttributeResult(\n 'LDAP Public Key Object Class not found. ' +\n 'Please ensure user was created correctly.')\n else:\n for key in list(set(keys)): # prevents duplicate insertion\n print(key)\n try:\n SSHKey(key).parse()\n except Exception as err:\n raise err from None\n else:\n operation = {'sshPublicKey': [(ldap3.MODIFY_ADD, [key])]}\n self.client.modify(distinguished_name, operation)", "docstring": "Add SSH public key to a user's profile.\n\nArgs:\n username: Username to attach SSH public key to\n filename: Filename containing keys to add (optional)\n\nRaises:\n ldap3.core.exceptions.LDAPNoSuchAttributeResult:\n ldapPublicKey isn't attached to objectClass", "source": "juraj_google_style"} +{"code": "def __init__(self, cache_file_name=None, update_cache=True, req_timeout=90.0):\n\n\n # TODO - lookup request rate limit\n # By observation, ShadowServer can be quite slow, so give it 90 seconds before it times out.\n self._requests = MultiRequest(max_requests=2, req_timeout=req_timeout)\n\n # Create an ApiCache if instructed to\n self._cache = ApiCache(cache_file_name, update_cache) if cache_file_name else None", "docstring": "Establishes basic HTTP params and loads a cache.\n\nArgs:\n cache_file_name: String file name of cache.\n update_cache: Determines whether cache should be written out back to the disk when closing it.\n Default is `True`.\n req_timeout: Maximum number of seconds to wait without reading a response byte before deciding an error has occurred.\n Default is 90.0 seconds.", "source": "juraj_google_style"} +{"code": "def __init__(self, parent=None):\n\n super(CSVImportDialog, self).__init__(parent)\n self._modal = True\n self._windowTitle = 'Import CSV'\n self._encodingKey = None\n self._filename = None\n self._delimiter = None\n self._header = None\n # self._detector = Detector()\n self._initUI()", "docstring": "Constructs the object with the given parent.\n\nArgs:\n parent (QObject, optional): Causes the objected to be owned\n by `parent` instead of Qt. Defaults to `None`.", "source": "juraj_google_style"} +{"code": "def wigner_data(q_result, meas_qubits, labels, shots=None):\n\n num = len(meas_qubits)\n\n dim = 2**num\n p = [0.5 + 0.5 * np.sqrt(3), 0.5 - 0.5 * np.sqrt(3)]\n parity = 1\n\n for i in range(num):\n parity = np.kron(parity, p)\n\n w = [0] * len(labels)\n wpt = 0\n counts = [marginal_counts(q_result.get_counts(circ), meas_qubits)\n for circ in labels]\n for entry in counts:\n x = [0] * dim\n\n for i in range(dim):\n if bin(i)[2:].zfill(num) in entry:\n x[i] = float(entry[bin(i)[2:].zfill(num)])\n\n if shots is None:\n shots = np.sum(x)\n\n for i in range(dim):\n w[wpt] = w[wpt] + (x[i] / shots) * parity[i]\n wpt += 1\n\n return w", "docstring": "Get the value of the Wigner function from measurement results.\n\nArgs:\n q_result (Result): Results from execution of a state tomography\n circuits on a backend.\n meas_qubits (list[int]): a list of the qubit indexes measured.\n labels (list[str]): a list of names of the circuits\n shots (int): number of shots\n\nReturns:\n list: The values of the Wigner function at measured points in\n phase space", "source": "juraj_google_style"} +{"code": "def AssignTasksToClient(self, client_id):\n\n rules = self.Get(self.Schema.RULES)\n if not rules:\n return 0\n\n if data_store.RelationalDBEnabled():\n last_foreman_run = self._GetLastForemanRunTimeRelational(client_id)\n else:\n last_foreman_run = self._GetLastForemanRunTime(client_id)\n\n latest_rule = max(rule.created for rule in rules)\n\n if latest_rule <= last_foreman_run:\n return 0\n\n # Update the latest checked rule on the client.\n if data_store.RelationalDBEnabled():\n try:\n self._SetLastForemanRunTimeRelational(client_id, latest_rule)\n except db.UnknownClientError:\n pass\n\n # If the relational db is used for reads, we don't have to update the\n # aff4 object.\n if not data_store.RelationalDBEnabled():\n self._SetLastForemanRunTime(client_id, latest_rule)\n\n relevant_rules = []\n expired_rules = False\n\n now = time.time() * 1e6\n\n for rule in rules:\n if rule.expires < now:\n expired_rules = True\n continue\n if rule.created <= int(last_foreman_run):\n continue\n\n relevant_rules.append(rule)\n\n if data_store.RelationalDBEnabled():\n client_data = data_store.REL_DB.ReadClientFullInfo(client_id)\n if client_data is None:\n return\n else:\n client_data = aff4.FACTORY.Open(client_id, mode=\"rw\", token=self.token)\n\n actions_count = 0\n for rule in relevant_rules:\n if self._EvaluateRules(rule, client_data):\n actions_count += self._RunActions(rule, client_id)\n\n if expired_rules:\n self.ExpireRules()\n\n return actions_count", "docstring": "Examines our rules and starts up flows based on the client.\n\nArgs:\n client_id: Client id of the client for tasks to be assigned.\n\nReturns:\n Number of assigned tasks.", "source": "juraj_google_style"} +{"code": "def _ParseContainerTable(self, parser_mediator, table, container_name):\n\n if table is None:\n raise ValueError('Missing table value.')\n\n for record_index, esedb_record in enumerate(table.records):\n if parser_mediator.abort:\n break\n\n # TODO: add support for:\n # wpnidm, iecompat, iecompatua, DNTException, DOMStore\n if container_name == 'Content':\n value_mappings = self._CONTAINER_TABLE_VALUE_MAPPINGS\n else:\n value_mappings = None\n\n try:\n record_values = self._GetRecordValues(\n parser_mediator, table.name, esedb_record,\n value_mappings=value_mappings)\n\n except UnicodeDecodeError:\n parser_mediator.ProduceExtractionWarning((\n 'Unable to retrieve record values from record: {0:d} '\n 'in table: {1:s}').format(record_index, table.name))\n continue\n\n if (container_name in self._SUPPORTED_CONTAINER_NAMES or\n container_name.startswith('MSHist')):\n access_count = record_values.get('AccessCount', None)\n cached_filename = record_values.get('Filename', None)\n cached_file_size = record_values.get('FileSize', None)\n cache_identifier = record_values.get('CacheId', None)\n container_identifier = record_values.get('ContainerId', None)\n entry_identifier = record_values.get('EntryId', None)\n file_extension = record_values.get('FileExtension', None)\n redirect_url = record_values.get('RedirectUrl', None)\n sync_count = record_values.get('SyncCount', None)\n\n url = record_values.get('Url', '')\n # Ignore an URL that start with a binary value.\n if ord(url[0]) < 0x20 or ord(url[0]) == 0x7f:\n url = None\n\n request_headers = record_values.get('RequestHeaders', None)\n # Ignore non-Unicode request headers values.\n if not isinstance(request_headers, py2to3.UNICODE_TYPE):\n request_headers = None\n\n response_headers = record_values.get('ResponseHeaders', None)\n # Ignore non-Unicode response headers values.\n if not isinstance(response_headers, py2to3.UNICODE_TYPE):\n response_headers = None\n\n event_data = MsieWebCacheContainerEventData()\n event_data.access_count = access_count\n event_data.cached_filename = cached_filename\n event_data.cached_file_size = cached_file_size\n event_data.cache_identifier = cache_identifier\n event_data.container_identifier = container_identifier\n event_data.entry_identifier = entry_identifier\n event_data.file_extension = file_extension\n event_data.redirect_url = redirect_url\n event_data.request_headers = request_headers\n event_data.response_headers = response_headers\n event_data.sync_count = sync_count\n event_data.url = url\n\n timestamp = record_values.get('SyncTime', None)\n if timestamp:\n date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, 'Synchronization time')\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = record_values.get('CreationTime', None)\n if timestamp:\n date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_CREATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = record_values.get('ExpiryTime', None)\n if timestamp:\n date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_EXPIRATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = record_values.get('ModifiedTime', None)\n if timestamp:\n date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_MODIFICATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = record_values.get('AccessedTime', None)\n if timestamp:\n date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = record_values.get('PostCheckTime', None)\n if timestamp:\n date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, 'Post check time')\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a Container_# table.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n table (pyesedb.table): table.\n container_name (str): container name, which indicates the table type.\n\nRaises:\n ValueError: if the table value is missing.", "source": "juraj_google_style"} +{"code": "def iter(self, max_value: int) -> Iterator[int]:\n\n return chain.from_iterable(\n (self._get_range(elem, max_value) for elem in self.sequences))", "docstring": "Iterates through the sequence numbers contained in the set, bounded\n by the given maximum value (in place of any ``*``).\n\nArgs:\n max_value: The maximum value of the set.", "source": "juraj_google_style"} +{"code": "def swd_read32(self, offset):\n\n value = self._dll.JLINK_SWD_GetU32(offset)\n return ctypes.c_uint32(value).value", "docstring": "Gets a unit of ``32`` bits from the input buffer.\n\nArgs:\n self (JLink): the ``JLink`` instance\n offset (int): the offset (in bits) from which to start reading\n\nReturns:\n The integer read from the input buffer.", "source": "juraj_google_style"} +{"code": "def turb45(msg):\n\n d = hex2bin(data(msg))\n if d[0] == '0':\n return None\n\n turb = bin2int(d[1:3])\n return turb", "docstring": "Turbulence.\n\nArgs:\n msg (String): 28 bytes hexadecimal message string\n\nReturns:\n int: Turbulence level. 0=NIL, 1=Light, 2=Moderate, 3=Severe", "source": "juraj_google_style"} +{"code": "def __init__(self, logger, proto_id=None):\n\n self.logger = logger\n self.proto_id = proto_id or '66'", "docstring": "Constructor.\n\nArgs:\n logger: logger object, used to write to SysLog and serial port.\n proto_id: string, the routing protocol identifier for Google IP changes.", "source": "juraj_google_style"} +{"code": "def __call__(self, class_logits, box_regression):\n\n\n class_logits = cat(class_logits, dim=0)\n box_regression = cat(box_regression, dim=0)\n device = class_logits.device\n\n if not hasattr(self, \"_proposals\"):\n raise RuntimeError(\"subsample needs to be called before\")\n\n proposals = self._proposals\n\n labels = cat([proposal.get_field(\"labels\") for proposal in proposals], dim=0)\n regression_targets = cat(\n [proposal.get_field(\"regression_targets\") for proposal in proposals], dim=0\n )\n\n classification_loss = F.cross_entropy(class_logits, labels)\n\n # get indices that correspond to the regression targets for\n # the corresponding ground truth labels, to be used with\n # advanced indexing\n sampled_pos_inds_subset = torch.nonzero(labels > 0).squeeze(1)\n labels_pos = labels[sampled_pos_inds_subset]\n if self.cls_agnostic_bbox_reg:\n map_inds = torch.tensor([4, 5, 6, 7], device=device)\n else:\n map_inds = 4 * labels_pos[:, None] + torch.tensor(\n [0, 1, 2, 3], device=device)\n\n box_loss = smooth_l1_loss(\n box_regression[sampled_pos_inds_subset[:, None], map_inds],\n regression_targets[sampled_pos_inds_subset],\n size_average=False,\n beta=1,\n )\n box_loss = box_loss / labels.numel()\n\n return classification_loss, box_loss", "docstring": "Computes the loss for Faster R-CNN.\n This requires that the subsample method has been called beforehand.\n\nArgs:\n class_logits (list[Tensor])\n box_regression (list[Tensor])\n\nReturns:\n classification_loss (Tensor)\n box_loss (Tensor)", "source": "juraj_google_style"} +{"code": "def IsErrorSuppressedByNolint(category, linenum):\n\n return (linenum in _error_suppressions.get(category, set()) or\n linenum in _error_suppressions.get(None, set()))", "docstring": "Returns true if the specified error category is suppressed on this line.\n\n Consults the global error_suppressions map populated by\n ParseNolintSuppressions/ResetNolintSuppressions.\n\nArgs:\n category: str, the category of the error.\n linenum: int, the current line number.\n\nReturns:\n bool, True iff the error should be suppressed due to a NOLINT comment.", "source": "juraj_google_style"} +{"code": "def diagnose(self, institute, case, user, link, level, omim_id, remove=False):\n\n if level == 'phenotype':\n case_key = 'diagnosis_phenotypes'\n elif level == 'gene':\n case_key = 'diagnosis_genes'\n else:\n raise TypeError('wrong level')\n\n diagnosis_list = case.get(case_key, [])\n omim_number = int(omim_id.split(':')[-1])\n\n updated_case = None\n if remove and omim_number in diagnosis_list:\n updated_case = self.case_collection.find_one_and_update(\n {'_id': case['_id']},\n {'$pull': {case_key: omim_number}},\n return_document=pymongo.ReturnDocument.AFTER\n )\n\n elif omim_number not in diagnosis_list:\n updated_case = self.case_collection.find_one_and_update(\n {'_id': case['_id']},\n {'$push': {case_key: omim_number}},\n return_document=pymongo.ReturnDocument.AFTER\n )\n\n if updated_case:\n self.create_event(\n institute=institute,\n case=case,\n user=user,\n link=link,\n category='case',\n verb='update_diagnosis',\n subject=case['display_name'],\n content=omim_id\n )\n\n return updated_case", "docstring": "Diagnose a case using OMIM ids.\n\nArgs:\n institute (dict): A Institute object\n case (dict): Case object\n user (dict): A User object\n link (str): The url to be used in the event\n level (str): choices=('phenotype','gene')\n\nReturns:\n updated_case", "source": "juraj_google_style"} +{"code": "def input(self, opt):\n\n\n for key in self.command['input']:\n if (key == opt) or (self.command['input'][key]['name'] == opt):\n return self._send_command(['input', key, 'command'])\n return False", "docstring": "Description:\n\n Set the input\n Call with no arguments to get current setting\n\nArgs:\n opt: string\n Name provided from input list or key from yaml (\"HDMI 1\" or \"hdmi_1\")", "source": "juraj_google_style"} +{"code": "def get_group_id(self, uuid=None):\n\n group_data = self.get_group(uuid)\n try:\n return group_data['response']['docs'][0]['id']\n except (KeyError, IndexError):\n failure_message = ('Error in get_group response data - '\n 'got {0}'.format(group_data))\n log.exception(failure_message)\n raise PyLmodUnexpectedData(failure_message)", "docstring": "Get group id based on uuid.\n\nArgs:\n uuid (str): optional uuid. defaults to self.cuuid\n\nRaises:\n PyLmodUnexpectedData: No group data was returned.\n requests.RequestException: Exception connection error\n\nReturns:\n int: numeric group id", "source": "juraj_google_style"} +{"code": "def retire(did):\n\n try:\n if dao.get(did) is None:\n return 'This asset DID is not in OceanDB', 404\n else:\n dao.delete(did)\n return 'Succesfully deleted', 200\n except Exception as err:\n return f'Some error: {str(err)}', 500", "docstring": "Retire metadata of an asset\n ---\n tags:\n - ddo\n parameters:\n - name: did\n in: path\n description: DID of the asset.\n required: true\n type: string\n responses:\n 200:\n description: successfully deleted\n 404:\n description: This asset DID is not in OceanDB\n 500:\n description: Error", "source": "juraj_google_style"} +{"code": "def _is_hostmask(self, ip_str):\n\n bits = ip_str.split('.')\n try:\n parts = [x for x in map(int, bits) if x in self._valid_mask_octets]\n except ValueError:\n return False\n if len(parts) != len(bits):\n return False\n if parts[0] < parts[-1]:\n return True\n return False", "docstring": "Test if the IP string is a hostmask (rather than a netmask).\n\nArgs:\n ip_str: A string, the potential hostmask.\n\nReturns:\n A boolean, True if the IP string is a hostmask.", "source": "juraj_google_style"} +{"code": "def bulkBatchDF(symbols, fields=None, range_='1m', last=10, token='', version=''):\n\n dat = bulkBatch(symbols, fields, range_, last, token, version)\n ret = {}\n for symbol in dat:\n for field in dat[symbol]:\n if field not in ret:\n ret[field] = pd.DataFrame()\n\n d = dat[symbol][field]\n d = _MAPPING[field](d)\n d['symbol'] = symbol\n ret[field] = pd.concat([ret[field], d], sort=True)\n\n return ret", "docstring": "Optimized batch to fetch as much as possible at once\n\n https://iexcloud.io/docs/api/#batch-requests\n\nArgs:\n symbols (list); List of tickers to request\n fields (list); List of fields to request\n range_ (string); Date range for chart\n last (int);\n token (string); Access token\n version (string); API version\n\nReturns:\n DataFrame: results in json", "source": "juraj_google_style"} +{"code": "def __init__(self, *args, **kwargs):\n\n # we want to own all of our bits so we can normalize them without\n # altering the caller's data unexpectedly. So deepcopy.\n args = deepcopy(args)\n kwargs = deepcopy(kwargs)\n super(Metadata, self).__init__(*args, **kwargs)\n self._ensure_id()\n self._ensure_version()\n self._validate()\n self._normalize_dates()\n self._validate_interval()", "docstring": "prepare compliant, normalized metadata from inputs\n\nArgs:\n kwargs: key-value pairs for metadata fields.\n\nRaises:\n InvalidDatalakeMetadata if required fields are missing and cannot\n be inferred.", "source": "juraj_google_style"} +{"code": "def instantiate(config):\n\n\n\n for handle, cfg in list(config[\"apps\"].items()):\n if not cfg.get(\"enabled\", True):\n continue\n app = get_application(handle)\n instances[app.handle] = app(cfg)", "docstring": "instantiate all registered vodka applications\n\nArgs:\n config (dict or MungeConfig): configuration object", "source": "juraj_google_style"} +{"code": "def _convert_args(handler, args):\n\n\n args = list(args)\n params = inspect.signature(handler).parameters\n for i, (arg, name) in enumerate(zip(args, params)):\n default = params[name].default\n annotation = params[name].annotation\n\n if annotation != inspect.Parameter.empty:\n if isinstance(annotation, type) and annotation != str:\n # The parameter is annotated with a type that isn't str: convert\n # the arg to that type.\n args[i] = annotation(arg)\n elif default != inspect.Parameter.empty:\n if default is not None and not isinstance(default, str):\n # The parameter has a default value that isn't None or a str:\n # convert the arg to the default value's type.\n args[i] = type(default)(arg)\n\n return args", "docstring": "Convert a list of command arguments to types specified by the handler.\n\nArgs:\n handler: a command handler function.\n args: the list of string arguments to pass to handler.\n\nReturns:\n A new list containing `args` that have been converted to the expected type\n for `handler`. For each function parameter of `handler` that has either an\n explicit type annotation or a non-None default value, the corresponding\n element in `args` is converted to that type.", "source": "juraj_google_style"} +{"code": "def get_transcript_ids(ensembl, gene_id):\n\n\n ensembl_genes = ensembl.get_genes_for_hgnc_id(gene_id)\n transcript_ids = ensembl.get_transcript_ids_for_ensembl_gene_ids(ensembl_genes, [gene_id])\n\n # sometimes we get HGNC symbols that do not match the ensembl rest version\n # that we are currentl using. We can look for earlier HGNC symbols for\n # the gene using the service at rest.genenames.org\n alt_symbols = []\n if len(transcript_ids) == 0:\n alt_symbols = ensembl.get_previous_symbol(gene_id)\n genes = [ensembl.get_genes_for_hgnc_id(symbol) for symbol in alt_symbols]\n genes = [item for sublist in genes for item in sublist]\n ensembl_genes += genes\n symbols = [gene_id] + alt_symbols\n\n transcript_ids = ensembl.get_transcript_ids_for_ensembl_gene_ids(ensembl_genes, symbols)\n\n return get_transcript_lengths(ensembl, transcript_ids)", "docstring": "gets transcript IDs for a gene.\n\nArgs:\n ensembl: EnsemblRequest object to request data from ensembl\n gene_id: HGNC symbol for gene\n\nReturns:\n dictionary of transcript ID: transcript lengths for all transcripts\n for a given HGNC symbol.", "source": "juraj_google_style"} +{"code": "def _get_type_name(type_):\n # type: (type) -> str\n\n name = repr(type_)\n if name.startswith(\"<\"):\n name = getattr(type_, \"__qualname__\", getattr(type_, \"__name__\", \"\"))\n return name.rsplit(\".\", 1)[-1] or repr(type_)", "docstring": "Return a displayable name for the type.\n\nArgs:\n type_: A class object.\n\nReturns:\n A string value describing the class name that can be used in a natural\n language sentence.", "source": "juraj_google_style"} +{"code": "def on_message(self, message):\n\n\n if 'content' in message['d']:\n metadata = self._parse_metadata(message)\n message = Message(text=message['d']['content'],\n metadata=metadata).__dict__\n logger.debug(message)\n self.baseplate.tell(message)", "docstring": "Runs on a create_message event from websocket connection\n\nArgs:\n message (dict): Full message from Discord websocket connection\"", "source": "juraj_google_style"} +{"code": "def _GetTripSequence(self, schedule=None):\n\n if schedule is None:\n schedule = getattr(self, \"_schedule\", None)\n if schedule is None:\n warnings.warn(\"No longer supported. _schedule attribute is used to get \"\n \"stop_times table\", DeprecationWarning)\n cursor = schedule._connection.cursor()\n cursor.execute(\"SELECT trip_id,stop_sequence FROM stop_times \"\n \"WHERE stop_id=?\",\n (self.stop_id, ))\n return [(schedule.GetTrip(row[0]), row[1]) for row in cursor]", "docstring": "Return a list of (trip, stop_sequence) for all trips visiting this stop.\n\n A trip may be in the list multiple times with different index.\n stop_sequence is an integer.\n\nArgs:\n schedule: Deprecated, do not use.", "source": "juraj_google_style"} +{"code": "def _process_image(filename, coder):\n\n # Read the image file.\n with tf.gfile.FastGFile(filename, 'r') as f:\n image_data = f.read()\n\n # Clean the dirty data.\n if _is_png(filename):\n # 1 image is a PNG.\n print('Converting PNG to JPEG for %s' % filename)\n image_data = coder.png_to_jpeg(image_data)\n elif _is_cmyk(filename):\n # 22 JPEG images are in CMYK colorspace.\n print('Converting CMYK to RGB for %s' % filename)\n image_data = coder.cmyk_to_rgb(image_data)\n\n # Decode the RGB JPEG.\n image = coder.decode_jpeg(image_data)\n\n # Check that image converted to RGB\n assert len(image.shape) == 3\n height = image.shape[0]\n width = image.shape[1]\n assert image.shape[2] == 3\n\n return image_data, height, width", "docstring": "Process a single image file.\n\nArgs:\n filename: string, path to an image file e.g., '/path/to/example.JPG'.\n coder: instance of ImageCoder to provide TensorFlow image coding utils.\n\nReturns:\n image_buffer: string, JPEG encoding of RGB image.\n height: integer, image height in pixels.\n width: integer, image width in pixels.", "source": "juraj_google_style"} +{"code": "def __init__(self, values=[]):\n\n\n self.values = values\n self.score = None\n self.probability = 0\n self.failed_trials = 0\n self.id = uuid.uuid4()\n self.error = None", "docstring": "EmployerBee object: stores individual employer bee information such\n as ID, position (current values), fitness function return value,\n fitness score, and probability of being chosen during the onlooker\n phase\n\nArgs:\n values (list): position/current values for the bee", "source": "juraj_google_style"} +{"code": "def find_sorted_task_dependencies(task, task_name, task_id):\n\n log.info(\"find_sorted_task_dependencies {} {}\".format(task_name, task_id))\n\n cot_input_dependencies = [\n _craft_dependency_tuple(task_name, task_type, task_id)\n for task_type, task_id in task['extra'].get('chainOfTrust', {}).get('inputs', {}).items()\n ]\n\n upstream_artifacts_dependencies = [\n _craft_dependency_tuple(task_name, artifact_dict['taskType'], artifact_dict['taskId'])\n for artifact_dict in task.get('payload', {}).get('upstreamArtifacts', [])\n ]\n\n dependencies = [*cot_input_dependencies, *upstream_artifacts_dependencies]\n dependencies = _sort_dependencies_by_name_then_task_id(dependencies)\n\n parent_task_id = get_parent_task_id(task) or get_decision_task_id(task)\n parent_task_type = 'parent'\n # make sure we deal with the decision task first, or we may populate\n # signing:build0:decision before signing:decision\n parent_tuple = _craft_dependency_tuple(task_name, parent_task_type, parent_task_id)\n dependencies.insert(0, parent_tuple)\n\n log.info('found dependencies: {}'.format(dependencies))\n return dependencies", "docstring": "Find the taskIds of the chain of trust dependencies of a given task.\n\nArgs:\n task (dict): the task definition to inspect.\n task_name (str): the name of the task, for logging and naming children.\n task_id (str): the taskId of the task.\n\nReturns:\n list: tuples associating dependent task ``name`` to dependent task ``taskId``.", "source": "juraj_google_style"} +{"code": "def send_message(self, to=None, msg=None):\n\n url = self.root_url + \"send_message\"\n values = {}\n if to is not None:\n values[\"to\"] = to\n if msg is not None:\n values[\"msg\"] = msg\n return self._query(url, values)", "docstring": "method to send a message to a user\n\n Parameters:\n to -> recipient\n msg -> message to send", "source": "juraj_google_style"} +{"code": "def assert_files_same(path1, path2):\n # type: (str, str) -> None\n\n difflines = compare_files(path1, path2)\n assert len(difflines) == 0, ''.join(['\\n'] + difflines)", "docstring": "Asserts that two files are the same and returns delta using\n -, ?, + format if not\n\nArgs:\n path1 (str): Path to first file\n path2 (str): Path to second file\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def create(self, instance, parameters, existing=True):\n\n return self.service_instance.create(instance, parameters, existing)", "docstring": "Create an instance\n\nArgs:\n instance (AtlasServiceInstance.Instance): Existing or New instance\n parameters (dict): Parameters for the instance\n\n Keyword Arguments:\n existing (bool): True (use an existing cluster), False (create a new cluster)\n\nReturns:\n ProvisionedServiceSpec: Status", "source": "juraj_google_style"} +{"code": "def _load_sentence_list(self, path):\n\n\n result = {}\n\n for entry in textfile.read_separated_lines_generator(path, separator='\\t', max_columns=3):\n if self.include_languages is None or entry[1] in self.include_languages:\n result[entry[0]] = entry[1:]\n\n return result", "docstring": "Load and filter the sentence list.\n\nArgs:\n path (str): Path to the sentence list.\n\nReturns:\n dict: Dictionary of sentences (id : language, transcription)", "source": "juraj_google_style"} +{"code": "def find_documents(self, sentence, limit=None, must_sort=True,\n search_type='fuzzy'):\n\n sentence = sentence.strip()\n sentence = strip_accents(sentence)\n\n if sentence == u\"\":\n return self.get_all_docs()\n\n result_list_list = []\n total_results = 0\n\n for query_parser in self.search_param_list[search_type]:\n query = query_parser[\"query_parser\"].parse(sentence)\n\n sortedby = None\n if must_sort and \"sortedby\" in query_parser:\n sortedby = query_parser['sortedby']\n if sortedby:\n results = self.__searcher.search(\n query, limit=limit, sortedby=sortedby\n )\n else:\n results = self.__searcher.search(\n query, limit=limit\n )\n results = [\n (result['docid'], result['doctype'])\n for result in results\n ]\n\n result_list_list.append(results)\n total_results += len(results)\n\n if not must_sort and total_results >= limit:\n break\n\n # merging results\n docs = set()\n for result_intermediate in result_list_list:\n for result in result_intermediate:\n doc = self._docs_by_id.get(result[0])\n if doc is None:\n continue\n docs.add(doc)\n\n docs = [d for d in docs]\n\n if not must_sort and limit is not None:\n docs = docs[:limit]\n\n return docs", "docstring": "Returns all the documents matching the given keywords\n\nArgs:\n sentence --- a sentenced query\n\nReturns:\n An array of document (doc objects)", "source": "juraj_google_style"} +{"code": "def restore(self, sess, save_path):\n\n\n if self._saver is None:\n raise TensorForceError(\"register_saver_ops should be called before restore\")\n self._saver.restore(sess=sess, save_path=save_path)", "docstring": "Restores the values of the managed variables from disk location.\n\nArgs:\n sess: The session for which to save the managed variables.\n save_path: The path used to save the data to.", "source": "juraj_google_style"} +{"code": "def truncate(string, maxchar):\n\n if maxchar < 4:\n raise TruncateError(\"Maxchar must be > 3\")\n\n if len(string) <= maxchar:\n return string\n else:\n return string[:maxchar - 3] + \"...\"", "docstring": "Truncate a string to a maximum number of characters.\n\n If the string is longer than maxchar, then remove excess\n characters and append an ellipses.\n\nArgs:\n string (str): String to truncate.\n maxchar (int): Maximum length of string in characters. Must be >= 4.\n\nReturns:\n str: Of length <= maxchar.\n\nRaises:\n TruncateError: In case of an error.", "source": "juraj_google_style"} +{"code": "def datasets_equal(dataset, other, fields_dataset=None,\n fields_distribution=None, return_diff=False):\n\n dataset_is_equal = True\n dataset_diff = []\n\n # Campos a comparar. Si es un campo anidado escribirlo como lista\n if not fields_dataset:\n fields_dataset = [\n 'title',\n ['publisher', 'name']\n ]\n\n for field_dataset in fields_dataset:\n if isinstance(field_dataset, list):\n value = traverse_dict(dataset, field_dataset)\n other_value = traverse_dict(other, field_dataset)\n else:\n value = dataset.get(field_dataset)\n other_value = other.get(field_dataset)\n\n if value != other_value:\n dataset_diff.append({\n \"error_location\": field_dataset,\n \"dataset_value\": value,\n \"other_value\": other_value\n })\n dataset_is_equal = False\n\n if fields_distribution:\n dataset_distributions = dataset.get(\"distribution\")\n other_distributions = other.get(\"distribution\")\n\n if len(dataset_distributions) != len(other_distributions):\n logger.info(\"{} distribuciones en origen y {} en destino\".format(\n len(dataset_distributions), len(other_distributions)))\n dataset_is_equal = False\n\n distributions_equal = True\n for dataset_distribution, other_distribution in zip(\n dataset_distributions, other_distributions):\n\n for field_distribution in fields_distribution:\n if isinstance(field_distribution, list):\n value = traverse_dict(\n dataset_distribution, field_distribution)\n other_value = traverse_dict(\n other_distribution, field_distribution)\n else:\n value = dataset_distribution.get(field_distribution)\n other_value = other_distribution.get(field_distribution)\n\n if value != other_value:\n dataset_diff.append({\n \"error_location\": \"{} ({})\".format(\n field_distribution,\n dataset_distribution.get(\"title\")\n ),\n \"dataset_value\": value,\n \"other_value\": other_value\n })\n distributions_equal = False\n\n if not distributions_equal:\n dataset_is_equal = False\n\n if return_diff:\n return dataset_diff\n else:\n return dataset_is_equal", "docstring": "Función de igualdad de dos datasets: se consideran iguales si\n los valores de los campos 'title', 'publisher.name',\n 'accrualPeriodicity' e 'issued' son iguales en ambos.\n\nArgs:\n dataset (dict): un dataset, generado por la lectura de un catálogo\n other (dict): idem anterior\n\nReturns:\n bool: True si son iguales, False en caso contrario", "source": "juraj_google_style"} +{"code": "def from_json(cls, name, spec):\n\n if \"run\" not in spec:\n raise TuneError(\"No trainable specified!\")\n\n # Special case the `env` param for RLlib by automatically\n # moving it into the `config` section.\n if \"env\" in spec:\n spec[\"config\"] = spec.get(\"config\", {})\n spec[\"config\"][\"env\"] = spec[\"env\"]\n del spec[\"env\"]\n\n spec = copy.deepcopy(spec)\n\n run_value = spec.pop(\"run\")\n try:\n exp = cls(name, run_value, **spec)\n except TypeError:\n raise TuneError(\"Improper argument from JSON: {}.\".format(spec))\n return exp", "docstring": "Generates an Experiment object from JSON.\n\nArgs:\n name (str): Name of Experiment.\n spec (dict): JSON configuration of experiment.", "source": "juraj_google_style"} +{"code": "def transcodeImage(self, media, height, width, opacity=100, saturation=100):\n\n if media:\n transcode_url = '/photo/:/transcode?height=%s&width=%s&opacity=%s&saturation=%s&url=%s' % (\n height, width, opacity, saturation, media)\n return self.url(transcode_url, includeToken=True)", "docstring": "Returns the URL for a transcoded image from the specified media object.\n Returns None if no media specified (needed if user tries to pass thumb\n or art directly).\n\n Parameters:\n height (int): Height to transcode the image to.\n width (int): Width to transcode the image to.\n opacity (int): Opacity of the resulting image (possibly deprecated).\n saturation (int): Saturating of the resulting image.", "source": "juraj_google_style"} +{"code": "def refresh(self, **kwargs):\n\n if self._id_attr:\n path = '%s/%s' % (self.manager.path, self.id)\n else:\n path = self.manager.path\n server_data = self.manager.gitlab.http_get(path, **kwargs)\n self._update_attrs(server_data)", "docstring": "Refresh a single object from server.\n\nArgs:\n **kwargs: Extra options to send to the server (e.g. sudo)\n\n Returns None (updates the object)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabGetError: If the server cannot perform the request", "source": "juraj_google_style"} +{"code": "def rsolve(A, b, epsilon=_epsilon):\n r\n A = asarray(A, float)\n b = asarray(b, float)\n if A.shape[0] == 0:\n return zeros((A.shape[1],))\n if A.shape[1] == 0:\n return zeros((0,))\n try:\n x = lstsq(A, b, rcond=epsilon)\n r = sum(x[3] > epsilon)\n if r == 0:\n return zeros(A.shape[1])\n return x[0]\n except (ValueError, LinAlgError) as e:\n warnings.warn(str(e), RuntimeWarning)\n return solve(A, b)", "docstring": "r\"\"\"Robust solve for the linear equations.\n\nArgs:\n A (array_like): Coefficient matrix.\n b (array_like): Ordinate values.\n\nReturns:\n :class:`numpy.ndarray`: Solution ``x``.", "source": "juraj_google_style"} +{"code": "def pauli_single(cls, num_qubits, index, pauli_label):\n\n tmp = Pauli.from_label(pauli_label)\n z = np.zeros(num_qubits, dtype=np.bool)\n x = np.zeros(num_qubits, dtype=np.bool)\n\n z[index] = tmp.z[0]\n x[index] = tmp.x[0]\n\n return cls(z, x)", "docstring": "Generate single qubit pauli at index with pauli_label with length num_qubits.\n\nArgs:\n num_qubits (int): the length of pauli\n index (int): the qubit index to insert the single qubii\n pauli_label (str): pauli\n\nReturns:\n Pauli: single qubit pauli", "source": "juraj_google_style"} +{"code": "def _add_tags(self, tags):\n # type: (List[str]) -> bool\n\n alltagsadded = True\n for tag in tags:\n if not self._add_tag(tag):\n alltagsadded = False\n return alltagsadded", "docstring": "Add a list of tag\n\nArgs:\n tags (List[str]): list of tags to add\n\nReturns:\n bool: True if all tags added or False if any already present.", "source": "juraj_google_style"} +{"code": "def simple_clip_matrix(scale, znear, zfar, aspectratio=1.0):\n\n m = numpy.zeros((4,4))\n m[0,0] = scale/aspectratio\n m[1,1] = scale\n m[2,2] = (zfar + znear) / (znear - zfar)\n m[2,3] = 2*zfar*znear / (znear - zfar)\n m[3,2] = -1\n\n return m", "docstring": "Given the parameters for a frustum returns a 4x4 perspective\n projection matrix\n\n Parameters:\n float scale:\n float znear,zfar: near/far plane z, float\n\n Return: a 4x4 perspective matrix", "source": "juraj_google_style"} +{"code": "def __init__(self,\n hostname=DEFAULT_HOSTNAME,\n protocol=DEFAULT_PROTOCOL,\n email=DEFAULT_EMAIL):\n\n super(grute, self).__init__(hostname, protocol)\n self.email = email", "docstring": "Initialize a new grute remote.\n\nArgs:\n hostname (str: \"openconnecto.me\"): The hostname where grute lives\n protocol (str: \"http\"): The protocol over which to access grute\n email (str: \"\"): The email to which completion notifications should\n be sent (unless overridden in individual calls). Note that the\n completion URLs are also accessible via this Python API.", "source": "juraj_google_style"} +{"code": "def publishApp(self, app_info, map_info=None, fsInfo=None):\n\n if self.securityhandler is None:\n print (\"Security handler required\")\n return\n appDet = None\n try:\n app_results = []\n if isinstance(app_info, list):\n for appDet in app_info:\n app_results.append(self._publishAppLogic(appDet=appDet,map_info=map_info,fsInfo=fsInfo))\n else:\n app_results.append(self._publishAppLogic(appDet=app_info,map_info=map_info,fsInfo=fsInfo))\n return app_results\n\n except (common.ArcRestHelperError) as e:\n raise e\n except Exception as e:\n\n line, filename, synerror = trace()\n raise common.ArcRestHelperError({\n \"function\": \"publishApp\",\n \"line\": line,\n \"filename\": filename,\n \"synerror\": synerror,\n })\n\n finally:\n appDet = None\n\n del appDet\n gc.collect()", "docstring": "Publishes apps to AGOL/Portal\n\nArgs:\n app_info (list): A list of JSON configuration apps to publish.\n map_info (list): Defaults to ``None``.\n fsInfo (list): Defaults to ``None``.\n\nReturns:\n dict: A dictionary of results objects.", "source": "juraj_google_style"} +{"code": "def _add_sink_state(self, states):\n\n cleared = []\n for i in range(0, 128):\n cleared.append(-1)\n states.append(cleared)", "docstring": "This function adds a sing state in the total states\n\nArgs:\n states (list): The current states\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def _set_root(self, request):\n\n if request.state_root:\n root = request.state_root\n else:\n head = self._get_chain_head()\n root = head.state_root_hash\n\n try:\n self._tree.set_merkle_root(root)\n except KeyError as e:\n LOGGER.debug('Unable to find root \"%s\" in database', e)\n raise _ResponseFailed(self._status.NO_ROOT)\n\n return root", "docstring": "Sets the root of the merkle tree, returning any head id used.\n\nNote:\n This method will fail if `_tree` has not been set\n\nArgs:\n request (object): The parsed protobuf request object\n\nReturns:\n str: the state root of the head block used to specify the root\n\nRaises:\n ResponseFailed: Failed to set the root if the merkle tree", "source": "juraj_google_style"} +{"code": "def _on_scan(self, info):\n\n\n device_id = info['uuid']\n expiration_time = info.get('validity_period', 60)\n infocopy = deepcopy(info)\n\n infocopy['expiration_time'] = monotonic() + expiration_time\n\n with self._scan_lock:\n self._scanned_devices[device_id] = infocopy", "docstring": "Callback called when a new device is discovered on this CMDStream\n\nArgs:\n info (dict): Information about the scanned device", "source": "juraj_google_style"} +{"code": "def add(self, spec):\n\n for limit in spec.limit_to:\n if limit not in self.limit_to:\n self.limit_to.append(limit)", "docstring": "Add limitations of given spec to self's.\n\nArgs:\n spec (PackageSpec): another spec.", "source": "juraj_google_style"} +{"code": "def on(self, event):\n\n def decorator(f):\n self.add_event_handler(f, event)\n return f\n\n return decorator", "docstring": "Decorator helper method around `add_event_handler`. Example:\n\n >>> from telethon import TelegramClient, events\n >>> client = TelegramClient(...)\n >>>\n >>> @client.on(events.NewMessage)\n ... async def handler(event):\n ... ...\n ...\n >>>\n\nArgs:\n event (`_EventBuilder` | `type`):\n The event builder class or instance to be used,\n for instance ``events.NewMessage``.", "source": "juraj_google_style"} +{"code": "def multivariate_hypergeometric_expval(n, m):\n\n m = np.asarray(m, float)\n return n * (m / m.sum())", "docstring": "Expected value of multivariate hypergeometric distribution.\n\n Parameters:\n - `n` : Number of draws.\n - `m` : Number of items in each categoy.", "source": "juraj_google_style"} +{"code": "def end_episode(self, agent_indices):\n\n with tf.name_scope('end_episode/'):\n return tf.cond(\n self._is_training,\n lambda: self._define_end_episode(agent_indices), str)", "docstring": "Add episodes to the memory and perform update steps if memory is full.\n\n During training, add the collected episodes of the batch indices that\n finished their episode to the memory. If the memory is full, train on it,\n and then clear the memory. A summary string is returned if requested at\n this step.\n\nArgs:\n agent_indices: Tensor containing current batch indices.\n\nReturns:\n Summary tensor.", "source": "juraj_google_style"} +{"code": "def NormalizePath(path):\n\n path = os.path.normpath(path)\n\n for sys_path in sys.path:\n if not sys_path:\n continue\n\n # Append '/' at the end of the path if it's not there already.\n sys_path = os.path.join(sys_path, '')\n\n if path.startswith(sys_path):\n return path[len(sys_path):]\n\n return path", "docstring": "Removes any Python system path prefix from the given path.\n\n Python keeps almost all paths absolute. This is not what we actually\n want to return. This loops through system paths (directories in which\n Python will load modules). If \"path\" is relative to one of them, the\n directory prefix is removed.\n\nArgs:\n path: absolute path to normalize (relative paths will not be altered)\n\nReturns:\n Relative path if \"path\" is within one of the sys.path directories or\n the input otherwise.", "source": "juraj_google_style"} +{"code": "def _remove(self, client_kwargs):\n\n with _handle_oss_error():\n bucket = self._get_bucket(client_kwargs)\n\n # Object\n if 'key' in client_kwargs:\n return bucket.delete_object(key=client_kwargs['key'])\n\n # Bucket\n return bucket.delete_bucket()", "docstring": "Remove an object.\n\nArgs:\n client_kwargs (dict): Client arguments.", "source": "juraj_google_style"} +{"code": "def get_oauth_data(self, code, client_id, client_secret, state):\n\n request = self._get_request()\n response = request.post(self.OAUTH_TOKEN_URL, {\n \"state\": state,\n \"code\": code,\n \"grant_type\": \"authorization_code\",\n \"client_id\": client_id,\n \"client_secret\": client_secret\n })\n return HSAccessTokenAuth.from_response(response)", "docstring": "Get Oauth data from HelloSign\n\nArgs:\n code (str): Code returned by HelloSign for our callback url\n\n client_id (str): Client id of the associated app\n\n client_secret (str): Secret token of the associated app\n\nReturns:\n A HSAccessTokenAuth object", "source": "juraj_google_style"} +{"code": "def snake_case_to_headless_camel_case(snake_string):\n\n return ''.join([snake_string.split('_')[0]] +\n list(sub_string.capitalize()\n for sub_string in snake_string.split('_')[1:]))", "docstring": "Convert snake_case to headlessCamelCase.\n\nArgs:\n snake_string: The string to be converted.\n\nReturns:\n The input string converted to headlessCamelCase.", "source": "juraj_google_style"} +{"code": "def out_file_name(out_dir, fname, ext=None):\n\n if ext is None:\n return os.path.join(out_dir, os.path.basename(fname))\n\n fname = remove_ext(fname)\n return os.path.join(out_dir, '{}.{}'.format(fname, ext))", "docstring": "Return path of output file, given a directory, file name and extension.\n\n If fname is a path, it is converted to its basename.\n\nArgs:\n out_dir (str): path to the directory where output should be written.\n fname (str): path to the input file.\n ext (str): file extension of the output file (defaults to None).\n\nReturns:\n str: out_dir + fname with extension replaced. If `ext` is `None`, the\n original extension is kept.", "source": "juraj_google_style"} +{"code": "def write_pascal_results(self, all_boxes):\n\n for cls_ind, cls in enumerate(self.classes):\n print('Writing {} VOC results file'.format(cls))\n filename = self.get_result_file_template().format(cls)\n with open(filename, 'wt') as f:\n for im_ind, index in enumerate(self.image_set_index):\n dets = all_boxes[im_ind]\n if dets.shape[0] < 1:\n continue\n h, w = self._get_imsize(self.image_path_from_index(im_ind))\n # the VOCdevkit expects 1-based indices\n for k in range(dets.shape[0]):\n if (int(dets[k, 0]) == cls_ind):\n f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\\n'.\n format(index, dets[k, 1],\n int(dets[k, 2] * w) + 1, int(dets[k, 3] * h) + 1,\n int(dets[k, 4] * w) + 1, int(dets[k, 5] * h) + 1))", "docstring": "write results files in pascal devkit path\n Parameters:\n ----------\n all_boxes: list\n boxes to be processed [bbox, confidence]\n\nReturns:\n ----------\n None", "source": "juraj_google_style"} +{"code": "def Run(script, container=None, exit_on_error=False, gas=Fixed8.Zero(), test_mode=True):\n\n\n from neo.Core.Blockchain import Blockchain\n from neo.SmartContract.StateMachine import StateMachine\n from neo.EventHub import events\n\n bc = Blockchain.Default()\n\n accounts = DBCollection(bc._db, DBPrefix.ST_Account, AccountState)\n assets = DBCollection(bc._db, DBPrefix.ST_Asset, AssetState)\n validators = DBCollection(bc._db, DBPrefix.ST_Validator, ValidatorState)\n contracts = DBCollection(bc._db, DBPrefix.ST_Contract, ContractState)\n storages = DBCollection(bc._db, DBPrefix.ST_Storage, StorageItem)\n\n script_table = CachedScriptTable(contracts)\n service = StateMachine(accounts, validators, assets, contracts, storages, None)\n\n engine = ApplicationEngine(\n trigger_type=TriggerType.Application,\n container=container,\n table=script_table,\n service=service,\n gas=gas,\n testMode=test_mode,\n exit_on_error=exit_on_error\n )\n\n script = binascii.unhexlify(script)\n\n engine.LoadScript(script)\n\n try:\n success = engine.Execute()\n engine.testMode = True\n service.ExecutionCompleted(engine, success)\n except Exception as e:\n engine.testMode = True\n service.ExecutionCompleted(engine, False, e)\n\n for event in service.events_to_dispatch:\n events.emit(event.event_type, event)\n\n return engine", "docstring": "Runs a script in a test invoke environment\n\nArgs:\n script (bytes): The script to run\n container (neo.Core.TX.Transaction): [optional] the transaction to use as the script container\n\nReturns:\n ApplicationEngine", "source": "juraj_google_style"} +{"code": "def verify(self, message, signature):\n\n message = _helpers._to_bytes(message, encoding='utf-8')\n return PKCS1_v1_5.new(self._pubkey).verify(\n SHA256.new(message), signature)", "docstring": "Verifies a message against a signature.\n\nArgs:\n message: string or bytes, The message to verify. If string, will be\n encoded to bytes as utf-8.\n signature: string or bytes, The signature on the message.\n\nReturns:\n True if message was signed by the private key associated with the\n public key that this object was constructed with.", "source": "juraj_google_style"} +{"code": "def DOMDebugger_removeXHRBreakpoint(self, url):\n\n\t\tassert isinstance(url, (str,)\n\t\t ), \"Argument 'url' must be of type '['str']'. Received type: '%s'\" % type(\n\t\t url)\n\t\tsubdom_funcs = self.synchronous_command('DOMDebugger.removeXHRBreakpoint',\n\t\t url=url)\n\t\treturn subdom_funcs", "docstring": "Function path: DOMDebugger.removeXHRBreakpoint\n Domain: DOMDebugger\n Method name: removeXHRBreakpoint\n\n Parameters:\n Required arguments:\n 'url' (type: string) -> Resource URL substring.\n No return value.\n\n Description: Removes breakpoint from XMLHttpRequest.", "source": "juraj_google_style"} +{"code": "def AddArguments(cls, argument_group):\n\n argument_group.add_argument(\n '--slice', metavar='DATE', dest='slice', type=str, default='',\n action='store', help=(\n 'Create a time slice around a certain date. This parameter, if '\n 'defined will display all events that happened X minutes before '\n 'and after the defined date. X is controlled by the parameter '\n '--slice_size but defaults to 5 minutes.'))\n\n argument_group.add_argument(\n '--slice_size', '--slice-size', dest='slice_size', type=int, default=5,\n action='store', help=(\n 'Defines the slice size. In the case of a regular time slice it '\n 'defines the number of minutes the slice size should be. In the '\n 'case of the --slicer it determines the number of events before '\n 'and after a filter match has been made that will be included in '\n 'the result set. The default value is 5. See --slice or --slicer '\n 'for more details about this option.'))\n\n argument_group.add_argument(\n '--slicer', dest='slicer', action='store_true', default=False, help=(\n 'Create a time slice around every filter match. This parameter, '\n 'if defined will save all X events before and after a filter '\n 'match has been made. X is defined by the --slice_size '\n 'parameter.'))\n\n argument_group.add_argument(\n 'filter', nargs='?', action='store', metavar='FILTER', default=None,\n type=str, help=(\n 'A filter that can be used to filter the dataset before it '\n 'is written into storage. More information about the filters '\n 'and how to use them can be found here: {0:s}').format(\n cls._DOCUMENTATION_URL))", "docstring": "Adds command line arguments to an argument group.\n\n This function takes an argument parser or an argument group object and adds\n to it all the command line arguments this helper supports.\n\nArgs:\n argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):\n argparse group.", "source": "juraj_google_style"} +{"code": "def _call_post_with_session(self, url, payload):\n\n now = datetime.datetime.utcnow()\n if now >= self.expires_at:\n # Create a new session with a valid token\n self.session.close()\n self._create_session()\n response = self.session.post(url, data=payload)\n return response.status_code, response.text", "docstring": "Make a post request using the session object to a SuccessFactors endpoint.\n\nArgs:\n url (str): The url to post to.\n payload (str): The json encoded payload to post.", "source": "juraj_google_style"} +{"code": "def __init__(self, source_name: str, target_name: str, weight: float = 1):\n\n # We must not only declare the properties but also initialize them,\n # otherwise the IDE will show warnings wherever the properties are accessed.\n\n self.source_name: str = source_name\n\n\n self.target_name: str = target_name\n\n\n self.weight: float = weight\n\n\n raise NotImplementedError(\"DBEdge is just an abstract base class that defines \"\n \"the interface of actual edge model objects. \"\n \"{} - {} ({})\".format(source_name, target_name, weight))", "docstring": "Initialization.\n\nArgs:\n source_name (str): The name of the source node of the edge.\n target_name (str): The name of the target node of the edge.\n weight (float): The weight of the edge.", "source": "juraj_google_style"} +{"code": "def reqNewsArticle(\n self, providerCode: str, articleId: str,\n newsArticleOptions: List[TagValue] = None) -> NewsArticle:\n\n return self._run(\n self.reqNewsArticleAsync(\n providerCode, articleId, newsArticleOptions))", "docstring": "Get the body of a news article.\n\n This method is blocking.\n\n https://interactivebrokers.github.io/tws-api/news.html\n\nArgs:\n providerCode: Code indicating news provider, like 'BZ' or 'FLY'.\n articleId: ID of the specific article.\n newsArticleOptions: Unknown.", "source": "juraj_google_style"} +{"code": "def defaults(cls, *options, **kwargs):\n\n if kwargs and len(kwargs) != 1 and list(kwargs.keys())[0] != 'backend':\n raise Exception('opts.defaults only accepts \"backend\" keyword argument')\n\n cls._linemagic(cls._expand_options(merge_options_to_dict(options)), backend=kwargs.get('backend'))", "docstring": "Set default options for a session.\n\n Set default options for a session. whether in a Python script or\n a Jupyter notebook.\n\nArgs:\n *options: Option objects used to specify the defaults.\n backend: The plotting extension the options apply to", "source": "juraj_google_style"} +{"code": "def load_scatter_table(self, fn):\n\n data = pickle.load(file(fn))\n\n if (\"version\" not in data) or (data[\"version\"]!=tmatrix_aux.VERSION):\n warnings.warn(\"Loading data saved with another version.\", Warning)\n\n (self.num_points, self.D_max, self._psd_D, self._S_table, \n self._Z_table, self._angular_table, self._m_table, \n self.geometries) = data[\"psd_scatter\"]\n return (data[\"time\"], data[\"description\"])", "docstring": "Load the scattering lookup tables.\n\n Load the scattering lookup tables saved with save_scatter_table.\n\nArgs:\n fn: The name of the scattering table file.", "source": "juraj_google_style"} +{"code": "def register(self, name, asymmetric=False):\n\n def register_func(func):\n if asymmetric:\n self._asymmetric.append(name)\n self.store[name] = func\n return func\n return register_func", "docstring": "Decorator for registering a measure with PyPhi.\n\nArgs:\n name (string): The name of the measure.\n\n Keyword Args:\n asymmetric (boolean): ``True`` if the measure is asymmetric.", "source": "juraj_google_style"} +{"code": "def __init__(self, name, default=None, help=None, type=str):\n\n self._name = name\n self._default = default\n self._help = help\n self._type = type", "docstring": "Initialise the workflow option.\n\nArgs:\n name (str): The name of the option under which the value will be stored.\n default: The default value that should be used when no value is specified.\n Set to None to make this a non-optional option.\n help (str): A short help string for this option.\n type: The type of the option. Supported types are: str, int, float, bool", "source": "juraj_google_style"} +{"code": "def dr( self, atom1, atom2 ):\n\n return self.cell.dr( atom1.r, atom2.r )", "docstring": "Calculate the distance between two atoms.\n\nArgs:\n atom1 (vasppy.Atom): Atom 1.\n atom2 (vasppy.Atom): Atom 2.\n\nReturns:\n (float): The distance between Atom 1 and Atom 2.", "source": "juraj_google_style"} +{"code": "def InternalSendApdu(self, apdu_to_send):\n\n response = None\n if not self.use_legacy_format:\n response = apdu.ResponseApdu(self.transport.SendMsgBytes(\n apdu_to_send.ToByteArray()))\n if response.sw1 == 0x67 and response.sw2 == 0x00:\n # If we failed using the standard format, retry with the\n # legacy format.\n self.use_legacy_format = True\n return self.InternalSendApdu(apdu_to_send)\n else:\n response = apdu.ResponseApdu(self.transport.SendMsgBytes(\n apdu_to_send.ToLegacyU2FByteArray()))\n return response", "docstring": "Send an APDU to the device.\n\n Sends an APDU to the device, possibly falling back to the legacy\n encoding format that is not ISO7816-4 compatible.\n\nArgs:\n apdu_to_send: The CommandApdu object to send\n\nReturns:\n The ResponseApdu object constructed out of the devices reply.", "source": "juraj_google_style"} +{"code": "def HandleAccounts(self, result):\n\n self.logger.debug('Checking for changes to user accounts.')\n configured_users = self.utils.GetConfiguredUsers()\n enable_oslogin = self._GetEnableOsLoginValue(result)\n enable_two_factor = self._GetEnableTwoFactorValue(result)\n if enable_oslogin:\n desired_users = {}\n self.oslogin.UpdateOsLogin(True, two_factor_desired=enable_two_factor)\n else:\n desired_users = self._GetAccountsData(result)\n self.oslogin.UpdateOsLogin(False)\n remove_users = sorted(set(configured_users) - set(desired_users.keys()))\n self._UpdateUsers(desired_users)\n self._RemoveUsers(remove_users)\n self.utils.SetConfiguredUsers(desired_users.keys())", "docstring": "Called when there are changes to the contents of the metadata server.\n\nArgs:\n result: json, the deserialized contents of the metadata server.", "source": "juraj_google_style"} +{"code": "def get_nic(access_token, subscription_id, resource_group, nic_name):\n\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourceGroups/', resource_group,\n '/providers/Microsoft.Network/networkInterfaces/', nic_name,\n '?api-version=', NETWORK_API])\n return do_get(endpoint, access_token)", "docstring": "Get details about a network interface.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n resource_group (str): Azure resource group name.\n nic_name (str): Name of the NIC.\n\nReturns:\n HTTP response. NIC JSON body.", "source": "juraj_google_style"} +{"code": "def lint(exclude, skip_untracked, commit_only):\n # type: (List[str], bool, bool) -> None\n\n exclude = list(exclude) + conf.get('lint.exclude', [])\n runner = LintRunner(exclude, skip_untracked, commit_only)\n\n if not runner.run():\n exit(1)", "docstring": "Lint python files.\n\nArgs:\n exclude (list[str]):\n A list of glob string patterns to test against. If the file/path\n matches any of those patters, it will be filtered out.\n skip_untracked (bool):\n If set to **True** it will skip all files not tracked by git.\n commit_only (bool):\n Only lint files that are staged for commit.", "source": "juraj_google_style"} +{"code": "def mctransp(I,J,K,c,d,M):\n\n\n model = Model(\"multi-commodity transportation\")\n\n # Create variables\n x = {}\n for (i,j,k) in c:\n x[i,j,k] = model.addVar(vtype=\"C\", name=\"x(%s,%s,%s)\" % (i,j,k), obj=c[i,j,k])\n\n # tuplelist is a Gurobi data structure to manage lists of equal sized tuples - try itertools as alternative\n arcs = tuplelist([(i,j,k) for (i,j,k) in x])\n\n # Demand constraints\n for i in I:\n for k in K:\n model.addCons(sum(x[i,j,k] for (i,j,k) in arcs.select(i,\"*\",k)) == d[i,k], \"Demand(%s,%s)\" % (i,k))\n\n # Capacity constraints\n for j in J:\n model.addCons(sum(x[i,j,k] for (i,j,k) in arcs.select(\"*\",j,\"*\")) <= M[j], \"Capacity(%s)\" % j)\n\n model.data = x\n return model", "docstring": "mctransp -- model for solving the Multi-commodity Transportation Problem\n Parameters:\n - I: set of customers\n - J: set of facilities\n - K: set of commodities\n - c[i,j,k]: unit transportation cost on arc (i,j) for commodity k\n - d[i][k]: demand for commodity k at node i\n - M[j]: capacity\n Returns a model, ready to be solved.", "source": "juraj_google_style"} +{"code": "def _parse(self, stream):\n\n builddata = json.load(stream)\n log.debug('This is a JSON build file.')\n\n if 'targets' not in builddata:\n log.warn('Warning: No targets defined here.')\n return\n\n for tdata in builddata['targets']:\n # TODO: validate name\n target = address.new(target=tdata.pop('name'),\n repo=self.target.repo,\n path=self.target.path)\n # Duplicate target definition? Uh oh.\n if target in self.node and 'target_obj' in self.node[target]:\n raise error.ButcherError(\n 'Target is defined more than once: %s', target)\n\n rule_obj = targets.new(name=target,\n ruletype=tdata.pop('type'),\n **tdata)\n\n log.debug('New target: %s', target)\n self.add_node(target, {'target_obj': rule_obj})\n\n # dep could be \":blabla\" or \"//foo:blabla\" or \"//foo/bar:blabla\"\n for dep in rule_obj.composed_deps() or []:\n d_target = address.new(dep)\n if not d_target.repo: # \":blabla\"\n d_target.repo = self.target.repo\n if d_target.repo == self.target.repo and not d_target.path:\n d_target.path = self.target.path\n if d_target not in self.nodes():\n self.add_node(d_target)\n log.debug('New dep: %s -> %s', target, d_target)\n self.add_edge(target, d_target)", "docstring": "Parse a JSON BUILD file.\n\nArgs:\n builddata: dictionary of buildfile data\n reponame: name of the repo that it came from\n path: directory path within the repo", "source": "juraj_google_style"} +{"code": "def total_duration(utterances: List[Utterance]) -> int:\n\n\n return sum([duration(utter) for utter in utterances])", "docstring": "Get the duration of an entire list of utterances in milliseconds\n\nArgs:\n utterances: The list of utterance we are finding the duration of", "source": "juraj_google_style"} +{"code": "def archive(self, output_path):\n\n\n if self.path is None:\n raise ArgumentError(\"Cannot archive a recipe yet without a reference to its original yaml file in self.path\")\n\n outfile = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)\n\n outfile.write(self.path, arcname=\"recipe_script.yaml\")\n\n written_files = set()\n\n for _factory, args, _resources, files in self.steps:\n for arg_name in files:\n file_path = args[arg_name]\n\n if file_path in written_files:\n continue\n\n if os.path.basename(file_path) != file_path:\n raise ArgumentError(\"Cannot archive a recipe yet that references file not in the same directory as the recipe\")\n\n full_path = os.path.join(os.path.dirname(self.path), file_path)\n outfile.write(full_path, arcname=file_path)\n written_files.add(file_path)", "docstring": "Archive this recipe and all associated files into a .ship archive.\n\nArgs:\n output_path (str): The path where the .ship file should be saved.", "source": "juraj_google_style"} +{"code": "def __constructMetricsModules(self, metricSpecs):\n\n if not metricSpecs:\n return\n\n self.__metricSpecs = metricSpecs\n for spec in metricSpecs:\n if not InferenceElement.validate(spec.inferenceElement):\n raise ValueError(\"Invalid inference element for metric spec: %r\" %spec)\n\n self.__metrics.append(metrics.getModule(spec))\n self.__metricLabels.append(spec.getLabel())", "docstring": "Creates the required metrics modules\n\n Parameters:\n -----------------------------------------------------------------------\n metricSpecs:\n A sequence of MetricSpec objects that specify which metric modules to\n instantiate", "source": "juraj_google_style"} +{"code": "def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):\n\n local_buffer = utils.BytearrayStream()\n\n if self._unique_identifier:\n self._unique_identifier.write(\n local_buffer,\n kmip_version=kmip_version\n )\n\n self.length = local_buffer.length()\n super(GetAttributeListRequestPayload, self).write(\n output_buffer,\n kmip_version=kmip_version\n )\n output_buffer.write(local_buffer.buffer)", "docstring": "Write the data encoding the GetAttributeList request payload to a\n stream.\n\nArgs:\n output_buffer (stream): A data stream in which to encode object\n data, supporting a write method; usually a BytearrayStream\n object.\n kmip_version (KMIPVersion): An enumeration defining the KMIP\n version with which the object will be encoded. Optional,\n defaults to KMIP 1.0.", "source": "juraj_google_style"} +{"code": "def generator_consumer(coro): # pragma: no cover\n\n if not asyncio.iscoroutinefunction(coro):\n raise TypeError('paco: coro must be a coroutine function')\n\n @functools.wraps(coro)\n @asyncio.coroutine\n def wrapper(*args, **kw):\n if len(args) > 1 and isgenerator(args[1]):\n args = list(args)\n args[1] = (yield from consume(args[1])\n if hasattr(args[1], '__anext__')\n else list(args[1]))\n args = tuple(args)\n return (yield from coro(*args, **kw))\n return wrapper", "docstring": "Decorator wrapper that consumes sync/async generators provided as\n interable input argument.\n\n This function is only intended to be used internally.\n\nArgs:\n coro (coroutinefunction): function to decorate\n\nRaises:\n TypeError: if function or coroutine function is not provided.\n\nReturns:\n function: decorated function.", "source": "juraj_google_style"} +{"code": "def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):\n\n # if isinstance(hour, bytes) and len(hour) == 6 and ord(hour[0]) < 24:\n # # Pickle support\n # self = object.__new__(cls)\n # self.__setstate(hour, minute or None)\n # self._hashcode = -1\n # return self\n hour, minute, second, microsecond = _check_time_fields(\n hour, minute, second, microsecond)\n _check_tzinfo_arg(tzinfo)\n self = object.__new__(cls)\n self._hour = hour\n self._minute = minute\n self._second = second\n self._microsecond = microsecond\n self._tzinfo = tzinfo\n self._hashcode = -1\n return self", "docstring": "Constructor.\n\nArgs:\n hour, minute (required)\n second, microsecond (default to zero)\n tzinfo (default to None)", "source": "juraj_google_style"} +{"code": "def set_property(self, key, value):\n\n value_type = type(value)\n if value_type not in [str, int, bool]:\n raise NotImplementedError(\n 'Only string, integer, and boolean properties are implemented')\n\n key_object = self.properties.findChild(name='key', text=key)\n\n # Key (and value, if it's a valid property list) don't exist\n if key_object is None:\n key_object = self.soup.new_tag('key')\n key_object.string = key\n\n self.properties.append(key_object)\n\n value_object = self.soup.new_tag(\n {str: 'string', int: 'integer', bool: str(value).lower()}[\n value_type])\n if value_type is not bool:\n value_object.string = str(value)\n\n self.properties.append(value_object)\n\n return\n\n # Key (and value, if it's a valid property list) exist\n # Eh, just remove the key+value tags from the tree and re-add them\n # (with the new value)\n value_object = key_object.find_next_sibling()\n\n key_object.decompose()\n value_object.decompose()\n\n self.set_property(key, value)", "docstring": "Set a new (or updating existing) key value pair.\n\nArgs:\n key: A string containing the key namespace\n value: A str, int, or bool value\n\nRaises:\n NotImplementedError: an unsupported value-type was provided", "source": "juraj_google_style"} +{"code": "def load_template(filename):\n # type: (str) -> str\n\n template_file = os.path.join(PKG_DIR, 'templates', filename)\n with open(template_file) as fp:\n return fp.read()", "docstring": "Load template from file.\n\n The templates are part of the package and must be included as\n ``package_data`` in project ``setup.py``.\n\nArgs:\n filename (str):\n The template path. Relative to `peltak` package directory.\n\nReturns:\n str: The content of the chosen template.", "source": "juraj_google_style"} +{"code": "def disassemble(self, start=None, end=None, arch_mode=None):\n\n if arch_mode is None:\n arch_mode = self.binary.architecture_mode\n\n curr_addr = start if start else self.binary.ea_start\n end_addr = end if end else self.binary.ea_end\n\n while curr_addr < end_addr:\n # Fetch the instruction.\n encoding = self.__fetch_instr(curr_addr)\n\n # Decode it.\n asm_instr = self.disassembler.disassemble(encoding, curr_addr, architecture_mode=arch_mode)\n\n if not asm_instr:\n return\n\n yield curr_addr, asm_instr, asm_instr.size\n\n # update instruction pointer\n curr_addr += asm_instr.size", "docstring": "Disassemble native instructions.\n\nArgs:\n start (int): Start address.\n end (int): End address.\n arch_mode (int): Architecture mode.\n\nReturns:\n (int, Instruction, int): A tuple of the form (address, assembler instruction, instruction size).", "source": "juraj_google_style"} +{"code": "def CleanVacuousVersions(clients=None, dry_run=True):\n\n\n if not clients:\n index = client_index.CreateClientIndex()\n clients = index.LookupClients([\".\"])\n clients.sort()\n with data_store.DB.GetMutationPool() as pool:\n\n logging.info(\"checking %d clients\", len(clients))\n for batch in collection.Batch(clients, 10000):\n # TODO(amoser): This only works on datastores that use the Bigtable\n # scheme.\n client_infos = data_store.DB.MultiResolvePrefix(\n batch, [\"aff4:\", \"aff4:\"], data_store.DB.ALL_TIMESTAMPS)\n\n for client, type_list in client_infos:\n cleared = 0\n kept = 0\n updates = []\n for a, _, ts in type_list:\n if ts != 0:\n updates.append((ts, a))\n updates = sorted(updates)\n dirty = True\n for ts, a in updates:\n if a == \"aff4:type\":\n if dirty:\n kept += 1\n dirty = False\n else:\n cleared += 1\n if not dry_run:\n pool.DeleteAttributes(client, [\"aff4:type\"], start=ts, end=ts)\n if pool.Size() > 1000:\n pool.Flush()\n else:\n dirty = True\n logging.info(\"%s: kept %d and cleared %d\", client, kept, cleared)", "docstring": "A script to remove no-op client versions.\n\n This script removes versions of a client when it is identical to the previous,\n in the sense that no versioned attributes were changed since the previous\n client version.\n\nArgs:\n clients: A list of ClientURN, if empty cleans all clients.\n dry_run: whether this is a dry run", "source": "juraj_google_style"} +{"code": "def _build_state_value(request_handler, user):\n\n uri = request_handler.request.url\n token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),\n action_id=str(uri))\n return uri + ':' + token", "docstring": "Composes the value for the 'state' parameter.\n\n Packs the current request URI and an XSRF token into an opaque string that\n can be passed to the authentication server via the 'state' parameter.\n\nArgs:\n request_handler: webapp.RequestHandler, The request.\n user: google.appengine.api.users.User, The current user.\n\nReturns:\n The state value as a string.", "source": "juraj_google_style"} +{"code": "def handle_command(command):\n\n try:\n cmds = command.split(None, 1)\n cmd = cmds[0]\n if cmd == 'new':\n add_task(get_arg(cmds))\n elif cmd == 'done':\n mark_done(int(get_arg(cmds)))\n elif cmd == 'list':\n for task in format_tasks(list_tasks()):\n print task\n elif cmd == 'delete':\n delete_task(int(get_arg(cmds)))\n else:\n print_usage()\n except Exception, e: # pylint: disable=broad-except\n print e\n print_usage()", "docstring": "Accepts a string command and performs an action.\n\nArgs:\n command: the command to run as a string.", "source": "juraj_google_style"} +{"code": "def action_scope(self, action_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]:\n\n return dict(zip(self.rddl.domain.action_fluent_ordering, action_fluents))", "docstring": "Returns a partial scope with current action-fluents.\n\nArgs:\n action_fluents (Sequence[tf.Tensor]): The action fluents.\n\nReturns:\n A mapping from action fluent names to :obj:`rddl2tf.fluent.TensorFluent`.", "source": "juraj_google_style"} +{"code": "def leave_swarm(self, force=False):\n\n url = self._url('/swarm/leave')\n response = self._post(url, params={'force': force})\n # Ignore \"this node is not part of a swarm\" error\n if force and response.status_code == http_client.NOT_ACCEPTABLE:\n return True\n # FIXME: Temporary workaround for 1.13.0-rc bug\n # https://github.com/docker/docker/issues/29192\n if force and response.status_code == http_client.SERVICE_UNAVAILABLE:\n return True\n self._raise_for_status(response)\n return True", "docstring": "Leave a swarm.\n\nArgs:\n force (bool): Leave the swarm even if this node is a manager.\n Default: ``False``\n\nReturns:\n ``True`` if the request went through.\n\nRaises:\n :py:class:`docker.errors.APIError`\n If the server returns an error.", "source": "juraj_google_style"} +{"code": "def __init__(self,\n domain_mapper,\n mode='classification',\n class_names=None,\n random_state=None):\n\n self.random_state = random_state\n self.mode = mode\n self.domain_mapper = domain_mapper\n self.local_exp = {}\n self.intercept = {}\n self.score = None\n self.local_pred = None\n self.scaled_data = None\n if mode == 'classification':\n self.class_names = class_names\n self.top_labels = None\n self.predict_proba = None\n elif mode == 'regression':\n self.class_names = ['negative', 'positive']\n self.predicted_value = None\n self.min_value = 0.0\n self.max_value = 1.0\n self.dummy_label = 1\n else:\n raise LimeError('Invalid explanation mode \"{}\". '\n 'Should be either \"classification\" '\n 'or \"regression\".'.format(mode))", "docstring": "Initializer.\n\nArgs:\n domain_mapper: must inherit from DomainMapper class\n type: \"classification\" or \"regression\"\n class_names: list of class names (only used for classification)\n random_state: an integer or numpy.RandomState that will be used to\n generate random numbers. If None, the random state will be\n initialized using the internal numpy seed.", "source": "juraj_google_style"} +{"code": "def tables_list(self, dataset_name, max_results=0, page_token=None):\n\n url = Api._ENDPOINT +\\\n (Api._TABLES_PATH % (dataset_name.project_id, dataset_name.dataset_id, '', ''))\n\n args = {}\n if max_results != 0:\n args['maxResults'] = max_results\n if page_token is not None:\n args['pageToken'] = page_token\n\n return google.datalab.utils.Http.request(url, args=args, credentials=self.credentials)", "docstring": "Issues a request to retrieve a list of tables.\n\nArgs:\n dataset_name: the name of the dataset to enumerate.\n max_results: an optional maximum number of tables to retrieve.\n page_token: an optional token to continue the retrieval.\n\nReturns:\n A parsed result object.\n\nRaises:\n Exception if there is an error performing the operation.", "source": "juraj_google_style"} +{"code": "def _flatten_beam_dim(tensor):\n\n shape = _shape_list(tensor)\n shape[0] *= shape[1]\n shape.pop(1) # Remove beam dim\n return tf.reshape(tensor, shape)", "docstring": "Reshapes first two dimensions in to single dimension.\n\nArgs:\n tensor: Tensor to reshape of shape [A, B, ...]\n\nReturns:\n Reshaped tensor of shape [A*B, ...]", "source": "juraj_google_style"} +{"code": "def inception_v3_parameters(weight_decay=0.00004, stddev=0.1,\n batch_norm_decay=0.9997, batch_norm_epsilon=0.001):\n\n # Set weight_decay for weights in Conv and FC layers.\n with scopes.arg_scope([ops.conv2d, ops.fc],\n weight_decay=weight_decay):\n # Set stddev, activation and parameters for batch_norm.\n with scopes.arg_scope([ops.conv2d],\n stddev=stddev,\n activation=tf.nn.relu,\n batch_norm_params={\n 'decay': batch_norm_decay,\n 'epsilon': batch_norm_epsilon}) as arg_scope:\n yield arg_scope", "docstring": "Yields the scope with the default parameters for inception_v3.\n\nArgs:\n weight_decay: the weight decay for weights variables.\n stddev: standard deviation of the truncated guassian weight distribution.\n batch_norm_decay: decay for the moving average of batch_norm momentums.\n batch_norm_epsilon: small float added to variance to avoid dividing by zero.\n\nYields:\n a arg_scope with the parameters needed for inception_v3.", "source": "juraj_google_style"} +{"code": "def _generate_examples(self, images_dir_path, csv_path=None, csv_usage=None):\n\n if csv_path:\n with tf.io.gfile.GFile(csv_path) as csv_f:\n reader = csv.DictReader(csv_f)\n data = [(row[\"image\"], int(row[\"level\"]))\n for row in reader\n if csv_usage is None or row[\"Usage\"] == csv_usage]\n else:\n data = [(fname[:-5], -1)\n for fname in tf.io.gfile.listdir(images_dir_path)\n if fname.endswith(\".jpeg\")]\n for name, label in data:\n yield {\n \"name\": name,\n \"image\": _resize_image_if_necessary(\n tf.io.gfile.GFile(\"%s/%s.jpeg\" % (images_dir_path, name),\n mode=\"rb\"),\n target_pixels=self.builder_config.target_pixels),\n \"label\": label,\n }", "docstring": "Yields Example instances from given CSV.\n\nArgs:\n images_dir_path: path to dir in which images are stored.\n csv_path: optional, path to csv file with two columns: name of image and\n label. If not provided, just scan image directory, don't set labels.\n csv_usage: optional, subset of examples from the csv file to use based on\n the \"Usage\" column from the csv.", "source": "juraj_google_style"} +{"code": "def get_doc_id(document_pb, expected_prefix):\n\n prefix, document_id = document_pb.name.rsplit(DOCUMENT_PATH_DELIMITER, 1)\n if prefix != expected_prefix:\n raise ValueError(\n \"Unexpected document name\",\n document_pb.name,\n \"Expected to begin with\",\n expected_prefix,\n )\n\n return document_id", "docstring": "Parse a document ID from a document protobuf.\n\nArgs:\n document_pb (google.cloud.proto.firestore.v1beta1.\\\n document_pb2.Document): A protobuf for a document that\n was created in a ``CreateDocument`` RPC.\n expected_prefix (str): The expected collection prefix for the\n fully-qualified document name.\n\nReturns:\n str: The document ID from the protobuf.\n\nRaises:\n ValueError: If the name does not begin with the prefix.", "source": "juraj_google_style"} +{"code": "def __init__(self, key, attributes):\n\n\n self.key = key\n self.attributes = attributes", "docstring": "Object initialization\n\nArgs:\n key: String name of an attributes key that represents the unique identify of the request\n attributes: Dictionary whose keys match the string values of the request attribute's names and values correspond the the request attribute values", "source": "juraj_google_style"} +{"code": "def format(\n self, text=None,\n width=60, chars=False, fill=False, newlines=False,\n prepend=None, append=None, strip_first=False, strip_last=False,\n lstrip=False):\n\n # Basic usage of iter_format_block(), for convenience.\n return '\\n'.join(\n self.iter_format_block(\n (self.text if text is None else text) or '',\n prepend=prepend,\n append=append,\n strip_first=strip_first,\n strip_last=strip_last,\n width=width,\n chars=chars,\n fill=fill,\n newlines=newlines,\n lstrip=lstrip\n )\n )", "docstring": "Format a long string into a block of newline seperated text.\n\nArgs:\n See iter_format_block().", "source": "juraj_google_style"} +{"code": "def ReleaseObject(self, identifier):\n\n if identifier not in self._values:\n raise KeyError('Missing cached object for identifier: {0:s}'.format(\n identifier))\n\n cache_value = self._values[identifier]\n if not cache_value:\n raise RuntimeError('Missing cache value for identifier: {0:s}'.format(\n identifier))\n\n cache_value.DecrementReferenceCount()", "docstring": "Releases a cached object based on the identifier.\n\n This method decrements the cache value reference count.\n\nArgs:\n identifier (str): VFS object identifier.\n\nRaises:\n KeyError: if the VFS object is not found in the cache.\n RuntimeError: if the cache value is missing.", "source": "juraj_google_style"} +{"code": "def compile_state_action_constraints(self,\n state: Sequence[tf.Tensor],\n action: Sequence[tf.Tensor]) -> List[TensorFluent]:\n\n scope = self.transition_scope(state, action)\n constraints = []\n with self.graph.as_default():\n with tf.name_scope('state_action_constraints'):\n for p in self.rddl.domain.constraints:\n fluent = self._compile_expression(p, scope)\n constraints.append(fluent)\n return constraints", "docstring": "Compiles the state-action constraints given current `state` and `action` fluents.\n\nArgs:\n state (Sequence[tf.Tensor]): The current state fluents.\n action (Sequence[tf.Tensor]): The action fluents.\n\nReturns:\n A list of :obj:`rddl2tf.fluent.TensorFluent`.", "source": "juraj_google_style"} +{"code": "def set_log_level(self, log_level):\n\n if log_level == 'DEBUG':\n self.log.setLevel(logging.DEBUG)\n self.log.debug(\"Changing log level to \"+log_level)\n elif log_level == 'INFO':\n self.log.setLevel(logging.INFO)\n self.log.info(\"Changing log level to \"+log_level)\n elif log_level == 'WARNING':\n self.log.setLevel(logging.WARNING)\n self.log.warning(\"Changing log level to \"+log_level)\n elif log_level == 'ERROR':\n self.log.setLevel(logging.ERROR)\n self.log.error(\"Changing log level to \"+log_level)\n elif log_level == 'CRITICAL':\n self.log.setLevel(logging.CRITICAL)\n self.log.critical(\"Changing log level to \"+log_level)\n elif log_level == 'NOTSET':\n self.log.setLevel(logging.NOTSET)\n else:\n raise NotImplementedError('Not implemented log level '+str(log_level))", "docstring": "Configures class log level\n\nArgs:\n log_level (:obj:`str`): log level ('NOTSET','DEBUG','INFO' 'WARNING',\n 'ERROR', 'CRITICAL')", "source": "juraj_google_style"} +{"code": "def create_room(self, alias=None, is_public=False, invitees=None):\n\n response = self.api.create_room(alias=alias,\n is_public=is_public,\n invitees=invitees)\n return self._mkroom(response[\"room_id\"])", "docstring": "Create a new room on the homeserver.\n\nArgs:\n alias (str): The canonical_alias of the room.\n is_public (bool): The public/private visibility of the room.\n invitees (str[]): A set of user ids to invite into the room.\n\nReturns:\n Room\n\nRaises:\n MatrixRequestError", "source": "juraj_google_style"} +{"code": "def truncate_rationale(rationale, max_length=MAX_RATIONALE_SIZE_IN_EVENT):\n\n if isinstance(rationale, basestring) and max_length is not None and len(rationale) > max_length:\n return rationale[0:max_length], True\n else:\n return rationale, False", "docstring": "Truncates the rationale for analytics event emission if necessary\n\nArgs:\n rationale (string): the string value of the rationale\n max_length (int): the max length for truncation\n\nReturns:\n truncated_value (string): the possibly truncated version of the rationale\n was_truncated (bool): returns true if the rationale is truncated", "source": "juraj_google_style"} +{"code": "def CheckMySQLConnection(db_options):\n\n for tries_left in range(_MYSQL_MAX_RETRIES, -1, -1):\n try:\n connection_options = dict(\n host=db_options[\"Mysql.host\"],\n port=db_options[\"Mysql.port\"],\n db=db_options[\"Mysql.database_name\"],\n user=db_options[\"Mysql.database_username\"],\n passwd=db_options[\"Mysql.database_password\"],\n charset=\"utf8\")\n\n ssl_enabled = \"Mysql.client_key_path\" in db_options\n if ssl_enabled:\n connection_options[\"ssl\"] = {\n \"key\": db_options[\"Mysql.client_key_path\"],\n \"cert\": db_options[\"Mysql.client_cert_path\"],\n \"ca\": db_options[\"Mysql.ca_cert_path\"],\n }\n\n connection = MySQLdb.connect(**connection_options)\n\n if ssl_enabled:\n cursor = connection.cursor()\n cursor.execute(\"SHOW VARIABLES LIKE 'have_ssl'\")\n res = cursor.fetchone()\n if res[0] == \"have_ssl\" and res[1] == \"YES\":\n print(\"SSL enabled successfully.\")\n else:\n print(\"Unable to establish SSL connection to MySQL.\")\n return False\n\n return True\n except MySQLdb.OperationalError as mysql_op_error:\n if len(mysql_op_error.args) < 2:\n # We expect the exception's arguments to be an error-code and\n # an error message.\n print(\"Unexpected exception type received from MySQL. %d attempts \"\n \"left: %s\" % (tries_left, mysql_op_error))\n time.sleep(_MYSQL_RETRY_WAIT_SECS)\n continue\n if mysql_op_error.args[0] == mysql_conn_errors.CONNECTION_ERROR:\n print(\"Failed to connect to MySQL. Is it running? %d attempts left.\" %\n tries_left)\n elif mysql_op_error.args[0] == mysql_conn_errors.UNKNOWN_HOST:\n print(\"Unknown-hostname error encountered while trying to connect to \"\n \"MySQL.\")\n return False # No need for retry.\n elif mysql_op_error.args[0] == general_mysql_errors.BAD_DB_ERROR:\n # GRR db doesn't exist yet. That's expected if this is the initial\n # setup.\n return True\n elif mysql_op_error.args[0] in (\n general_mysql_errors.ACCESS_DENIED_ERROR,\n general_mysql_errors.DBACCESS_DENIED_ERROR):\n print(\"Permission error encountered while trying to connect to \"\n \"MySQL: %s\" % mysql_op_error)\n return False # No need for retry.\n else:\n print(\"Unexpected operational error encountered while trying to \"\n \"connect to MySQL. %d attempts left: %s\" %\n (tries_left, mysql_op_error))\n except MySQLdb.Error as mysql_error:\n print(\"Unexpected error encountered while trying to connect to MySQL. \"\n \"%d attempts left: %s\" % (tries_left, mysql_error))\n time.sleep(_MYSQL_RETRY_WAIT_SECS)\n return False", "docstring": "Checks whether a connection can be established to MySQL.\n\nArgs:\n db_options: A dict mapping GRR MySQL config options to their values.\n\nReturns:\n A boolean indicating whether a connection could be made to a MySQL server\n instance with the given options.", "source": "juraj_google_style"} +{"code": "def setKeySequenceCounter(self, iKeySequenceValue):\n\n print '%s call setKeySequenceCounter' % self.port\n print iKeySequenceValue\n try:\n cmd = WPANCTL_CMD + 'setprop Network:KeyIndex %s' % str(iKeySequenceValue)\n if self.__sendCommand(cmd)[0] != 'Fail':\n time.sleep(1)\n return True\n else:\n return False\n except Exception, e:\n ModuleHelper.WriteIntoDebugLogger('setKeySequenceCounter() Error: ' + str(e))", "docstring": "set the Key sequence counter corresponding to Thread Network master key\n\nArgs:\n iKeySequenceValue: key sequence value\n\nReturns:\n True: successful to set the key sequence\n False: fail to set the key sequence", "source": "juraj_google_style"} +{"code": "def licenses(self):\n\n buf_size = self.MAX_BUF_SIZE\n buf = (ctypes.c_char * buf_size)()\n res = self._dll.JLINK_GetAvailableLicense(buf, buf_size)\n if res < 0:\n raise errors.JLinkException(res)\n return ctypes.string_at(buf).decode()", "docstring": "Returns a string of the built-in licenses the J-Link has.\n\nArgs:\n self (JLink): the ``JLink`` instance\n\nReturns:\n String of the contents of the built-in licenses the J-Link has.", "source": "juraj_google_style"} +{"code": "def body(self, body):\n\n self._request.body = body\n self.add_matcher(matcher('BodyMatcher', body))", "docstring": "Defines the body data to match.\n\n ``body`` argument can be a ``str``, ``binary`` or a regular expression.\n\nArgs:\n body (str|binary|regex): body data to match.\n\nReturns:\n self: current Mock instance.", "source": "juraj_google_style"} +{"code": "def delete_existing_policy(self, scaling_policy, server_group):\n\n self.log.info(\"Deleting policy %s on %s\", scaling_policy['policyName'], server_group)\n delete_dict = {\n \"application\":\n self.app,\n \"description\":\n \"Delete scaling policy\",\n \"job\": [{\n \"policyName\": scaling_policy['policyName'],\n \"serverGroupName\": server_group,\n \"credentials\": self.env,\n \"region\": self.region,\n \"provider\": \"aws\",\n \"type\": \"deleteScalingPolicy\",\n \"user\": \"foremast-autoscaling-policy\"\n }]\n }\n wait_for_task(json.dumps(delete_dict))", "docstring": "Given a scaling_policy and server_group, deletes the existing scaling_policy.\n Scaling policies need to be deleted instead of upserted for consistency.\n\nArgs:\n scaling_policy (json): the scaling_policy json from Spinnaker that should be deleted\n server_group (str): the affected server_group", "source": "juraj_google_style"} +{"code": "def delete_channel(self, channel_name, project_name, dataset_name):\n\n return self.resources.delete_channel(channel_name, project_name,\n dataset_name)", "docstring": "Deletes a channel given its name, name of its project\n , and name of its dataset.\n\nArgs:\n channel_name (str): Channel name\n project_name (str): Project name\n dataset_name (str): Dataset name\n\nReturns:\n bool: True if channel deleted, False if not", "source": "juraj_google_style"} +{"code": "def eval_in_new(cls, expr, *args, **kwargs):\n\n ctx = cls(*args, **kwargs)\n ctx.env.rec_new(expr)\n return ctx.eval(expr)", "docstring": ":meth:`eval` an expression in a new, temporary :class:`Context`.\n\n This should be safe to use directly on user input.\n\nArgs:\n expr (LispVal): The expression to evaluate.\n *args: Args for the :class:`Context` constructor.\n **kwargs: Kwargs for the :class:`Context` constructor.", "source": "juraj_google_style"} +{"code": "def text_search(self, search, *, limit=0, table='assets'):\n\n return backend.query.text_search(self.connection, search, limit=limit,\n table=table)", "docstring": "Return an iterator of assets that match the text search\n\nArgs:\n search (str): Text search string to query the text index\n limit (int, optional): Limit the number of returned documents.\n\nReturns:\n iter: An iterator of assets that match the text search.", "source": "juraj_google_style"} +{"code": "def getPosition(self):\n\n result = dict()\n for (varName, value) in self.permuteVars.iteritems():\n result[varName] = value.getPosition()\n\n return result", "docstring": "Return the position of this particle. This returns a dict() of key\n value pairs where each key is the name of the flattened permutation\n variable and the value is its chosen value.\n\n Parameters:\n --------------------------------------------------------------\n retval: dict() of flattened permutation choices", "source": "juraj_google_style"} +{"code": "def distplot(n_traces=1,n=500,dispersion=3,mode=None):\n\n\treturn histogram(n_traces,n,dispersion,mode)", "docstring": "Returns a DataFrame with the required format for\n a distribution plot (distplot)\n\n Parameters:\n -----------\n n_traces : int\n Number of traces\n n : int\n Number of points for each trace\n mode : string\n Format for each item\n 'abc' for alphabet columns\n 'stocks' for random stock names", "source": "juraj_google_style"} +{"code": "def gradient_summaries(grad_vars, groups=None, scope='gradients'):\n\n groups = groups or {r'all': r'.*'}\n grouped = collections.defaultdict(list)\n for grad, var in grad_vars:\n if grad is None:\n continue\n for name, pattern in groups.items():\n if re.match(pattern, var.name):\n name = re.sub(pattern, name, var.name)\n grouped[name].append(grad)\n for name in groups:\n if name not in grouped:\n tf.logging.warn(\"No variables matching '{}' group.\".format(name))\n summaries = []\n for name, grads in grouped.items():\n grads = [tf.reshape(grad, [-1]) for grad in grads]\n grads = tf.concat(grads, 0)\n summaries.append(tf.summary.histogram(scope + '/' + name, grads))\n return tf.summary.merge(summaries)", "docstring": "Create histogram summaries of the gradient.\n\n Summaries can be grouped via regexes matching variables names.\n\nArgs:\n grad_vars: List of (gradient, variable) tuples as returned by optimizers.\n groups: Mapping of name to regex for grouping summaries.\n scope: Name scope for this operation.\n\nReturns:\n Summary tensor.", "source": "juraj_google_style"} +{"code": "def begin_episode(self, agent_indices):\n\n with tf.name_scope('begin_episode/'):\n if self._last_state is None:\n reset_state = tf.no_op()\n else:\n reset_state = utility.reinit_nested_vars(\n self._last_state, agent_indices)\n reset_buffer = self._current_episodes.clear(agent_indices)\n with tf.control_dependencies([reset_state, reset_buffer]):\n return tf.constant('')", "docstring": "Reset the recurrent states and stored episode.\n\nArgs:\n agent_indices: Tensor containing current batch indices.\n\nReturns:\n Summary tensor.", "source": "juraj_google_style"} +{"code": "def make_group_index(self, groupby_cols, bool_arr):\n\n factor_list, values_list = self.factorize_groupby_cols(groupby_cols)\n\n # create unique groups for groupby loop\n if len(factor_list) == 0:\n # no columns to groupby over, so directly aggregate the measure\n # columns to 1 total\n tmp_rootdir = self.create_tmp_rootdir()\n carray_factor = bcolz.zeros(len(self), dtype='int64', rootdir=tmp_rootdir, mode='w')\n carray_values = ['Total']\n elif len(factor_list) == 1:\n # single column groupby, the groupby output column\n # here is 1:1 to the values\n carray_factor = factor_list[0]\n carray_values = values_list[0]\n else:\n # multi column groupby\n # first combine the factorized columns to single values\n if self.group_cache_valid(col_list=groupby_cols):\n # there is a group cache that we can use\n col_rootdir = os.path.join(self.rootdir, self.create_group_base_name(groupby_cols))\n col_factor_rootdir = col_rootdir + '.factor'\n carray_factor = bcolz.carray(rootdir=col_factor_rootdir)\n col_values_rootdir = col_rootdir + '.values'\n carray_values = bcolz.carray(rootdir=col_values_rootdir)\n else:\n # create a brand new groupby col combination\n carray_factor, carray_values = \\\n self.create_group_column_factor(factor_list, groupby_cols, cache=self.auto_cache)\n\n nr_groups = len(carray_values)\n skip_key = None\n\n if bool_arr is not None:\n # make all non relevant combinations -1\n tmp_rootdir = self.create_tmp_rootdir()\n carray_factor = bcolz.eval(\n '(factor + 1) * bool - 1',\n user_dict={'factor': carray_factor, 'bool': bool_arr}, rootdir=tmp_rootdir, mode='w')\n # now check how many unique values there are left\n tmp_rootdir = self.create_tmp_rootdir()\n labels = bcolz.carray([], dtype='int64', expectedlen=len(carray_factor), rootdir=tmp_rootdir, mode='w')\n carray_factor, values = ctable_ext.factorize(carray_factor, labels)\n # values might contain one value too much (-1) (no direct lookup\n # possible because values is a reversed dict)\n filter_check = \\\n [key for key, value in values.items() if value == -1]\n if filter_check:\n skip_key = filter_check[0]\n # the new nr of groups depends on the outcome after filtering\n nr_groups = len(values)\n\n # using nr_groups as a total length might be one one off due to the skip_key\n # (skipping a row in aggregation)\n # but that is okay normally\n\n if skip_key is None:\n # if we shouldn't skip a row, set it at the first row after the total number of groups\n skip_key = nr_groups\n\n return carray_factor, nr_groups, skip_key", "docstring": "Create unique groups for groupby loop\n\nArgs:\n factor_list:\n values_list:\n groupby_cols:\n bool_arr:\n\nReturns:\n carray: (carray_factor)\n int: (nr_groups) the number of resulting groups\n int: (skip_key)", "source": "juraj_google_style"} +{"code": "def parse(self, data, extent, desc_tag, parent):\n # type: (bytes, int, UDFTag, UDFFileEntry) -> int\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('UDF File Identifier Descriptor already initialized')\n\n (tag_unused, file_version_num, self.file_characteristics,\n self.len_fi, icb, self.len_impl_use) = struct.unpack_from(self.FMT, data, 0)\n\n self.desc_tag = desc_tag\n\n if file_version_num != 1:\n raise pycdlibexception.PyCdlibInvalidISO('File Identifier Descriptor file version number not 1')\n\n if self.file_characteristics & 0x2:\n self.isdir = True\n\n if self.file_characteristics & 0x8:\n self.isparent = True\n\n self.icb = UDFLongAD()\n self.icb.parse(icb)\n\n start = struct.calcsize(self.FMT)\n end = start + self.len_impl_use\n self.impl_use = data[start:end]\n\n start = end\n end = start + self.len_fi\n # The very first byte of the File Identifier describes whether this is\n # an 8-bit or 16-bit encoded string; this corresponds to whether we\n # encode with 'latin-1' or with 'utf-16_be'. We save that off because we have\n # to write the correct thing out when we record.\n if not self.isparent:\n encoding = bytes(bytearray([data[start]]))\n if encoding == b'\\x08':\n self.encoding = 'latin-1'\n elif encoding == b'\\x10':\n self.encoding = 'utf-16_be'\n else:\n raise pycdlibexception.PyCdlibInvalidISO('Only UDF File Identifier Descriptor Encodings 8 or 16 are supported')\n\n start += 1\n\n self.fi = data[start:end]\n\n self.orig_extent_loc = extent\n\n self.parent = parent\n\n self._initialized = True\n\n return end + UDFFileIdentifierDescriptor.pad(end)", "docstring": "Parse the passed in data into a UDF File Identifier Descriptor.\n\n Parameters:\n data - The data to parse.\n extent - The extent that this descriptor currently lives at.\n desc_tag - A UDFTag object that represents the Descriptor Tag.\n parent - The UDF File Entry representing the parent.\n\nReturns:\n The number of bytes this descriptor consumed.", "source": "juraj_google_style"} +{"code": "def __init__(self, experimenter=None, data=None):\n\n super().__init__()\n self.experimenter = experimenter\n self.data = data", "docstring": "Create a QueuePropExperimenter with the optional parameters below.\n\nArgs:\n experimenter (int): Experimenter ID which takes the same form as in\n struct ofp_experimenter_header.\n data (bytes): Experimenter defined data.", "source": "juraj_google_style"} +{"code": "def dispatch_callback(self, items):\n\n if not self._manager.is_active:\n return\n\n batched_commands = collections.defaultdict(list)\n\n for item in items:\n batched_commands[item.__class__].append(item)\n\n _LOGGER.debug(\"Handling %d batched requests\", len(items))\n\n if batched_commands[requests.LeaseRequest]:\n self.lease(batched_commands.pop(requests.LeaseRequest))\n if batched_commands[requests.ModAckRequest]:\n self.modify_ack_deadline(batched_commands.pop(requests.ModAckRequest))\n # Note: Drop and ack *must* be after lease. It's possible to get both\n # the lease the and ack/drop request in the same batch.\n if batched_commands[requests.AckRequest]:\n self.ack(batched_commands.pop(requests.AckRequest))\n if batched_commands[requests.NackRequest]:\n self.nack(batched_commands.pop(requests.NackRequest))\n if batched_commands[requests.DropRequest]:\n self.drop(batched_commands.pop(requests.DropRequest))", "docstring": "Map the callback request to the appropriate gRPC request.\n\nArgs:\n action (str): The method to be invoked.\n kwargs (Dict[str, Any]): The keyword arguments for the method\n specified by ``action``.\n\nRaises:\n ValueError: If ``action`` isn't one of the expected actions\n \"ack\", \"drop\", \"lease\", \"modify_ack_deadline\" or \"nack\".", "source": "juraj_google_style"} +{"code": "def sheetNames(book=None):\n\n if book:\n if not book.lower() in [x.lower() for x in bookNames()]:\n return False\n else:\n book=activeBook()\n if not book:\n return False\n poBook=PyOrigin.WorksheetPages(book)\n if not len(poBook):\n return None\n return [x.GetName() for x in poBook.Layers()]", "docstring": "return sheet names of a book.\n\nArgs:\n book (str, optional): If a book is given, pull names from\n that book. Otherwise, try the active one\n\nReturns:\n list of sheet names (typical case).\n None if book has no sheets.\n False if book doesn't exlist.", "source": "juraj_google_style"} +{"code": "def encode(self, s):\n\n # Make sure that the data is a single channel, 16bit, 16kHz wave.\n # TODO(chorowski): the directory may not be writable, this should fallback\n # to a temp path, and provide instructions for installing sox.\n if s.endswith(\".mp3\"):\n # TODO(dliebling) On Linux, check if libsox-fmt-mp3 is installed.\n out_filepath = s[:-4] + \".wav\"\n call([\n \"sox\", \"--guard\", s, \"-r\", \"16k\", \"-b\", \"16\", \"-c\", \"1\", out_filepath\n ])\n s = out_filepath\n elif not s.endswith(\".wav\"):\n out_filepath = s + \".wav\"\n if not os.path.exists(out_filepath):\n call([\"sox\", \"-r\", \"16k\", \"-b\", \"16\", \"-c\", \"1\", s, out_filepath])\n s = out_filepath\n rate, data = wavfile.read(s)\n assert rate == self._sample_rate\n assert len(data.shape) == 1\n if data.dtype not in [np.float32, np.float64]:\n data = data.astype(np.float32) / np.iinfo(data.dtype).max\n return data.tolist()", "docstring": "Transform a string with a filename into a list of float32.\n\nArgs:\n s: path to the file with a waveform.\n\nReturns:\n samples: list of int16s", "source": "juraj_google_style"} +{"code": "def denorm(self,arr):\n\n if type(arr) is not np.ndarray: arr = to_np(arr)\n if len(arr.shape)==3: arr = arr[None]\n return self.transform.denorm(np.rollaxis(arr,1,4))", "docstring": "Reverse the normalization done to a batch of images.\n\nArgs:\n arr: of shape/size (N,3,sz,sz)", "source": "juraj_google_style"} +{"code": "def ReadSerializedDict(cls, json_dict):\n\n if json_dict:\n json_object = cls._ConvertDictToObject(json_dict)\n if not isinstance(json_object, containers_interface.AttributeContainer):\n raise TypeError('{0:s} is not an attribute container type.'.format(\n type(json_object)))\n return json_object\n\n return None", "docstring": "Reads an attribute container from serialized dictionary form.\n\nArgs:\n json_dict (dict[str, object]): JSON serialized objects.\n\nReturns:\n AttributeContainer: attribute container or None.\n\nRaises:\n TypeError: if the serialized dictionary does not contain an\n AttributeContainer.", "source": "juraj_google_style"} +{"code": "def maybe_download(self, filename, work_directory, source_url):\n\n if not os.path.exists(work_directory):\n os.makedirs(work_directory)\n filepath = os.path.join(work_directory, filename)\n if not os.path.exists(filepath):\n temp_file_name, _ = urllib.request.urlretrieve(source_url)\n copyfile(temp_file_name, filepath)\n print('Successfully downloaded', filename)\n return filepath", "docstring": "Download the data from source url, unless it's already here.\n\nArgs:\n filename: string, name of the file in the directory.\n work_directory: string, path to working directory.\n source_url: url to download from if file doesn't exist.\n\nReturns:\n Path to resulting file.", "source": "juraj_google_style"} +{"code": "def filter_out_spontaneous_genes(genes, custom_spont_id=None):\n\n new_genes = DictList()\n for gene in genes:\n if not is_spontaneous(gene, custom_id=custom_spont_id):\n new_genes.append(gene)\n\n return new_genes", "docstring": "Return the DictList of genes that are not spontaneous in a model.\n\nArgs:\n genes (DictList): Genes DictList\n custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``\n\nReturns:\n DictList: genes excluding ones that are spontaneous", "source": "juraj_google_style"} +{"code": "def push(self, source_file, device_filename, timeout_ms=None):\n\n mtime = 0\n if isinstance(source_file, six.string_types):\n mtime = os.path.getmtime(source_file)\n source_file = open(source_file)\n\n self.filesync_service.send(\n source_file, device_filename, mtime=mtime,\n timeout=timeouts.PolledTimeout.from_millis(timeout_ms))", "docstring": "Push source_file to file on device.\n\nArgs:\n source_file: Either a filename or file-like object to push to the device.\n If a filename, will set the remote mtime to match the local mtime,\n otherwise will use the current time.\n device_filename: The filename on the device to write to.\n timeout_ms: Expected timeout for any part of the push.", "source": "juraj_google_style"} +{"code": "def MessageToJson(message, including_default_value_fields=False):\n\n js = _MessageToJsonObject(message, including_default_value_fields)\n return json.dumps(js, indent=2)", "docstring": "Converts protobuf message to JSON format.\n\nArgs:\n message: The protocol buffers message instance to serialize.\n including_default_value_fields: If True, singular primitive fields,\n repeated fields, and map fields will always be serialized. If\n False, only serialize non-empty fields. Singular message fields\n and oneof fields are not affected by this option.\n\nReturns:\n A string containing the JSON formatted protocol buffer message.", "source": "juraj_google_style"} +{"code": "def __delete__(self, obj):\n\n\n if self.name in obj._property_values:\n old_value = obj._property_values[self.name]\n del obj._property_values[self.name]\n self.trigger_if_changed(obj, old_value)\n\n if self.name in obj._unstable_default_values:\n del obj._unstable_default_values[self.name]", "docstring": "Implement the deleter for the Python `descriptor protocol`_.\n\nArgs:\n obj (HasProps) : An instance to delete this property from", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.GenerateAccessToken = channel.unary_unary(\n \"/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken\",\n request_serializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.GenerateAccessTokenRequest.SerializeToString,\n response_deserializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.GenerateAccessTokenResponse.FromString,\n )\n self.GenerateIdToken = channel.unary_unary(\n \"/google.iam.credentials.v1.IAMCredentials/GenerateIdToken\",\n request_serializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.GenerateIdTokenRequest.SerializeToString,\n response_deserializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.GenerateIdTokenResponse.FromString,\n )\n self.SignBlob = channel.unary_unary(\n \"/google.iam.credentials.v1.IAMCredentials/SignBlob\",\n request_serializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.SignBlobRequest.SerializeToString,\n response_deserializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.SignBlobResponse.FromString,\n )\n self.SignJwt = channel.unary_unary(\n \"/google.iam.credentials.v1.IAMCredentials/SignJwt\",\n request_serializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.SignJwtRequest.SerializeToString,\n response_deserializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.SignJwtResponse.FromString,\n )\n self.GenerateIdentityBindingAccessToken = channel.unary_unary(\n \"/google.iam.credentials.v1.IAMCredentials/GenerateIdentityBindingAccessToken\",\n request_serializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.GenerateIdentityBindingAccessTokenRequest.SerializeToString,\n response_deserializer=google_dot_iam_dot_credentials_dot_v1_dot_common__pb2.GenerateIdentityBindingAccessTokenResponse.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def ReadIndex(self, index_file=None):\n\n\n self.index_file = index_file or self.index_file\n fullpath = os.path.join(self.template_dir, self.index_file)\n if self.index_file and fullpath not in self.INDEX:\n self.index = IndexTable(self._PreParse, self._PreCompile, fullpath)\n self.INDEX[fullpath] = self.index\n else:\n self.index = self.INDEX[fullpath]\n\n # Does the IndexTable have the right columns.\n if \"Template\" not in self.index.index.header: # pylint: disable=E1103\n raise CliTableError(\"Index file does not have 'Template' column.\")", "docstring": "Reads the IndexTable index file of commands and templates.\n\nArgs:\n index_file: String, file where template/command mappings reside.\n\nRaises:\n CliTableError: A template column was not found in the table.", "source": "juraj_google_style"} +{"code": "def format(self, exclude_class=False):\n\n\n if exclude_class:\n msg = self.msg\n else:\n msg = \"%s: %s\" % (self.__class__.__name__, self.msg)\n\n if len(self.params) != 0:\n paramstring = \"\\n\".join([str(key) + \": \" + str(val) for key, val in self.params.items()])\n msg += \"\\nAdditional Information:\\n\" + paramstring\n\n return msg", "docstring": "Format this exception as a string including class name.\n\nArgs:\n exclude_class (bool): Whether to exclude the exception class\n name when formatting this exception\n\nReturns:\n string: a multiline string with the message, class name and\n key value parameters passed to create the exception.", "source": "juraj_google_style"} +{"code": "def DeserializeFromDB(buffer):\n\n m = StreamManager.GetStream(buffer)\n reader = BinaryReader(m)\n uns = UnspentCoinState()\n uns.Deserialize(reader)\n\n StreamManager.ReleaseStream(m)\n\n return uns", "docstring": "Deserialize full object.\n\nArgs:\n buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from.\n\nReturns:\n UnspentCoinState:", "source": "juraj_google_style"} +{"code": "def unpack(self, fmt, length=1):\n\n try:\n info = struct.unpack(fmt, self.stream.read(length))[0]\n except struct.error as e:\n raise SDKException(ErrorCode.unpack_error(e.args[0]))\n return info", "docstring": "Unpack the stream contents according to the specified format in `fmt`.\n For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html\n\nArgs:\n fmt (str): format string.\n length (int): amount of bytes to read.\n\nReturns:\n variable: the result according to the specified format.", "source": "juraj_google_style"} +{"code": "def filter(self, items=None, like=None, regex=None, axis=None):\n\n nkw = count_not_none(items, like, regex)\n if nkw > 1:\n raise TypeError(\n \"Keyword arguments `items`, `like`, or `regex` are mutually exclusive\"\n )\n if nkw == 0:\n raise TypeError(\"Must pass either `items`, `like`, or `regex`\")\n if axis is None:\n axis = \"columns\" # This is the default info axis for dataframes\n\n axis = self._get_axis_number(axis)\n labels = self.columns if axis else self.index\n\n if items is not None:\n bool_arr = labels.isin(items)\n elif like is not None:\n\n def f(x):\n return like in to_str(x)\n\n bool_arr = labels.map(f).tolist()\n else:\n\n def f(x):\n return matcher.search(to_str(x)) is not None\n\n matcher = re.compile(regex)\n bool_arr = labels.map(f).tolist()\n if not axis:\n return self[bool_arr]\n return self[self.columns[bool_arr]]", "docstring": "Subset rows or columns based on their labels\n\nArgs:\n items (list): list of labels to subset\n like (string): retain labels where `arg in label == True`\n regex (string): retain labels matching regex input\n axis: axis to filter on\n\nReturns:\n A new DataFrame with the filter applied.", "source": "juraj_google_style"} +{"code": "def __init__(self, parser, codegen, writer):\n\n self._parser = parser\n self._codegen = codegen\n self._symbolgen = SymtableCodeGen()\n self._writer = writer\n self._sources = []\n self._searchers = []\n self._borrowers = []", "docstring": "Creates an instance of *MibCompiler* class.\n\nArgs:\n parser: ASN.1 MIB parser object\n codegen: MIB transformation object\n writer: transformed MIB storing object", "source": "juraj_google_style"} +{"code": "def _create_output_from_match(self, match_result):\n\n if isinstance(match_result, dict):\n return LinterOutput(self.name, **match_result)\n return LinterOutput(self.name, *match_result)", "docstring": "Create Result instance from pattern match results.\n\nArgs:\n match: Pattern match.", "source": "juraj_google_style"} +{"code": "def draw_line(self, x1, y1, x2, y2, color):\n\n check_int_err(lib.lineRGBA(self._ptr, x1, y1, x2, y2, color[0], color[1], color[2], color[3]))", "docstring": "Draw a line.\n\nArgs:\n x1 (int): The x coordinate of the start of the line.\n y1 (int): The y coordinate of the start of the line.\n x2 (int): The x coordinate of the end of the line.\n y2 (int): The y coordinate of the end of the line.\n color (Tuple[int, int, int, int]): The color of the circle.\n\nRaises:\n SDLError: If an error is encountered.", "source": "juraj_google_style"} +{"code": "def create_checksum_object_from_stream(\n f, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM\n):\n\n checksum_str = calculate_checksum_on_stream(f, algorithm)\n checksum_pyxb = d1_common.types.dataoneTypes.checksum(checksum_str)\n checksum_pyxb.algorithm = algorithm\n return checksum_pyxb", "docstring": "Calculate the checksum of a stream.\n\nArgs:\n f: file-like object\n Only requirement is a ``read()`` method that returns ``bytes``.\n\n algorithm: str\n Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.\n\nReturns:\n Populated Checksum PyXB object.", "source": "juraj_google_style"} +{"code": "def ExamineEvent(self, mediator, event):\n\n if event.data_type not in self._DATATYPES:\n return\n\n url = getattr(event, 'url', None)\n if url is None:\n return\n parsed_url = urlparse.urlparse(url)\n domain = getattr(parsed_url, 'netloc', None)\n if domain in self._domains:\n # We've already found an event containing this domain.\n return\n self._domains.append(domain)", "docstring": "Analyzes an event and extracts domains from it.\n\n We only evaluate straightforward web history events, not visits which can\n be inferred by TypedURLs, cookies or other means.\n\nArgs:\n mediator (AnalysisMediator): mediates interactions between\n analysis plugins and other components, such as storage and dfvfs.\n event (EventObject): event to examine.", "source": "juraj_google_style"} +{"code": "def build_parameter(name, properties):\n\n p = Parameter(name, Type=properties.get(\"type\"))\n for name, attr in PARAMETER_PROPERTIES.items():\n if name in properties:\n setattr(p, attr, properties[name])\n return p", "docstring": "Builds a troposphere Parameter with the given properties.\n\nArgs:\n name (string): The name of the parameter.\n properties (dict): Contains the properties that will be applied to the\n parameter. See:\n http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html\n\nReturns:\n :class:`troposphere.Parameter`: The created parameter object.", "source": "juraj_google_style"} +{"code": "def login(self, username, *, token=None):\n\n\n\t\tself._username = username\n\t\tself._oauth(username, token=token)\n\n\t\treturn self.is_authenticated", "docstring": "Log in to Google Music.\n\n Parameters:\n username (str, Optional): Your Google Music username.\n Used for keeping stored OAuth tokens for multiple accounts separate.\n device_id (str, Optional): A mobile device ID or music manager uploader ID.\n Default: MAC address is used.\n token (dict, Optional): An OAuth token compatible with ``requests-oauthlib``.\n\nReturns:\n bool: ``True`` if successfully authenticated, ``False`` if not.", "source": "juraj_google_style"} +{"code": "def build_recursive_localize_env(destination, inputs):\n\n export_input_dirs = '\\n'.join([\n 'export {0}={1}/{2}'.format(var.name, destination.rstrip('/'),\n var.docker_path.rstrip('/'))\n for var in inputs\n if var.recursive and var.docker_path\n ])\n return export_input_dirs", "docstring": "Return a multi-line string with export statements for the variables.\n\nArgs:\n destination: Folder where the data will be put.\n For example /mnt/data\n inputs: a list of InputFileParam\n\nReturns:\n a multi-line string with a shell script that sets environment variables\n corresponding to the inputs.", "source": "juraj_google_style"} +{"code": "def from_string(cls, key, key_id=None):\n\n key = _helpers.from_bytes(key) # PEM expects str in Python 3\n marker_id, key_bytes = pem.readPemBlocksFromFile(\n six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)\n\n # Key is in pkcs1 format.\n if marker_id == 0:\n private_key = rsa.key.PrivateKey.load_pkcs1(\n key_bytes, format='DER')\n # Key is in pkcs8.\n elif marker_id == 1:\n key_info, remaining = decoder.decode(\n key_bytes, asn1Spec=_PKCS8_SPEC)\n if remaining != b'':\n raise ValueError('Unused bytes', remaining)\n private_key_info = key_info.getComponentByName('privateKey')\n private_key = rsa.key.PrivateKey.load_pkcs1(\n private_key_info.asOctets(), format='DER')\n else:\n raise ValueError('No key could be detected.')\n\n return cls(private_key, key_id=key_id)", "docstring": "Construct an Signer instance from a private key in PEM format.\n\nArgs:\n key (str): Private key in PEM format.\n key_id (str): An optional key id used to identify the private key.\n\nReturns:\n google.auth.crypt.Signer: The constructed signer.\n\nRaises:\n ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in\n PEM format.", "source": "juraj_google_style"} +{"code": "def enbase64(byte_str):\n\n\n # Python 3: base64.b64encode() expects type byte\n if isinstance(byte_str, str) and not PYTHON2:\n byte_str = bytes(byte_str, 'utf-8')\n return base64.b64encode(byte_str)", "docstring": "Encode bytes/strings to base64.\n\nArgs:\n - ``byte_str``: The string or bytes to base64 encode.\n\nReturns:\n - byte_str encoded as base64.", "source": "juraj_google_style"} +{"code": "def send_image(self, url, name, **imageinfo):\n\n return self.client.api.send_content(\n self.room_id, url, name, \"m.image\",\n extra_information=imageinfo\n )", "docstring": "Send a pre-uploaded image to the room.\n\n See http://matrix.org/docs/spec/r0.0.1/client_server.html#m-image\n for imageinfo\n\nArgs:\n url (str): The mxc url of the image.\n name (str): The filename of the image.\n imageinfo (): Extra information about the image.", "source": "juraj_google_style"} +{"code": "def bootstrap_results(self, init_state):\n\n with tf.compat.v1.name_scope(\n name=mcmc_util.make_name(self.name, 'remc', 'bootstrap_results'),\n values=[init_state]):\n replica_results = [\n self.replica_kernels[i].bootstrap_results(init_state)\n for i in range(self.num_replica)\n ]\n\n init_state_parts = (\n list(init_state)\n if mcmc_util.is_list_like(init_state) else [init_state])\n\n # Convert all states parts to tensor...\n replica_states = [[\n tf.convert_to_tensor(value=s) for s in init_state_parts\n ] for i in range(self.num_replica)]\n\n if not mcmc_util.is_list_like(init_state):\n replica_states = [s[0] for s in replica_states]\n\n return ReplicaExchangeMCKernelResults(\n replica_states=replica_states,\n replica_results=replica_results,\n sampled_replica_states=replica_states,\n sampled_replica_results=replica_results,\n )", "docstring": "Returns an object with the same type as returned by `one_step`.\n\nArgs:\n init_state: `Tensor` or Python `list` of `Tensor`s representing the\n initial state(s) of the Markov chain(s).\n\nReturns:\n kernel_results: A (possibly nested) `tuple`, `namedtuple` or `list` of\n `Tensor`s representing internal calculations made within this function.\n This inculdes replica states.", "source": "juraj_google_style"} +{"code": "def GetSortedEvents(self, time_range=None):\n\n if not self._is_open:\n raise IOError('Unable to read from closed storage writer.')\n\n event_heap = event_heaps.EventHeap()\n\n for event in self._events:\n if (time_range and (\n event.timestamp < time_range.start_timestamp or\n event.timestamp > time_range.end_timestamp)):\n continue\n\n # Make a copy of the event before adding the event data.\n event = copy.deepcopy(event)\n # TODO: refactor this into psort.\n self._ReadEventDataIntoEvent(event)\n\n event_heap.PushEvent(event)\n\n return iter(event_heap.PopEvents())", "docstring": "Retrieves the events in increasing chronological order.\n\nArgs:\n time_range (Optional[TimeRange]): time range used to filter events\n that fall in a specific period.\n\nReturns:\n generator(EventObject): event generator.\n\nRaises:\n IOError: when the storage writer is closed.\n OSError: when the storage writer is closed.", "source": "juraj_google_style"} +{"code": "def deepcopy_dict(data):\n\n try:\n return copy.deepcopy(data)\n except TypeError:\n copied_data = {}\n for key, value in data.items():\n if isinstance(value, dict):\n copied_data[key] = deepcopy_dict(value)\n else:\n try:\n copied_data[key] = copy.deepcopy(value)\n except TypeError:\n copied_data[key] = value\n\n return copied_data", "docstring": "deepcopy dict data, ignore file object (_io.BufferedReader)\n\nArgs:\n data (dict): dict data structure\n {\n 'a': 1,\n 'b': [2, 4],\n 'c': lambda x: x+1,\n 'd': open('LICENSE'),\n 'f': {\n 'f1': {'a1': 2},\n 'f2': io.open('LICENSE', 'rb'),\n }\n }\n\nReturns:\n dict: deep copied dict data, with file object unchanged.", "source": "juraj_google_style"} +{"code": "def __set__(self, instance, value):\n\n if value is None and self.default:\n self._cache[instance] = self.default\n\n else:\n try:\n cleaned_value = self.field_value(value)\n\n except NodeTypeError as node_error:\n raise SchemaNodeError('{}.{}: {}'.format(\n instance.__class__.__name__, self.alias, node_error.args[0])\n )\n\n try:\n self.is_valid(cleaned_value)\n\n except SchemaNodeValidatorError as error:\n raise SchemaNodeError(\n '{}.{} Error for value `{}` : {}'.format(\n instance.__class__.__name__,\n self.alias,\n value,\n error.args[0]\n )\n )\n\n self._cache[instance] = cleaned_value", "docstring": "Python descriptor protocol `__set__` magic method.\n\nArgs:\n instance (object): The instance with descriptor attribute.\n value (object): The value for instance attribute.", "source": "juraj_google_style"} +{"code": "def __init__(\n self, resolver_context, file_system, path_spec, is_root=False,\n is_virtual=False):\n\n super(SQLiteBlobFileEntry, self).__init__(\n resolver_context, file_system, path_spec, is_root=is_root,\n is_virtual=is_virtual)\n self._number_of_entries = None\n\n if is_virtual:\n self.entry_type = definitions.FILE_ENTRY_TYPE_DIRECTORY\n else:\n self.entry_type = definitions.FILE_ENTRY_TYPE_FILE", "docstring": "Initializes a file entry.\n\nArgs:\n resolver_context (Context): resolver context.\n file_system (FileSystem): file system.\n path_spec (PathSpec): path specification.\n is_root (Optional[bool]): True if the file entry is the root file entry\n of the corresponding file system.\n is_virtual (Optional[bool]): True if the file entry is a virtual file\n entry emulated by the corresponding file system.", "source": "juraj_google_style"} +{"code": "def generate_secret_file(file_path, pattern, service, environment, clients):\n\n changed = False\n with open(file_path) as json_file:\n data = json.load(json_file, object_pairs_hook=OrderedDict)\n try:\n for key, value in data[\"params\"][environment].items():\n if pattern in key:\n if \"aws:kms:decrypt\" in value:\n print(\"Found match, key {} but value is encrypted already; skipping...\".format(key))\n else:\n print(\"Found match, encrypting key {}\".format(key))\n encrypted_password = ef_utils.kms_encrypt(clients['kms'], service, environment, value)\n data[\"params\"][environment][key] = format_secret(encrypted_password)\n changed = True\n except KeyError:\n ef_utils.fail(\"Error env: {} does not exist in parameters file\".format(environment))\n\n if changed:\n with open(file_path, \"w\") as encrypted_file:\n json.dump(data, encrypted_file, indent=2, separators=(',', ': '))\n # Writing new line here so it conforms to WG14 N1256 5.1.1.1 (so github doesn't complain)\n encrypted_file.write(\"\\n\")", "docstring": "Generate a parameter files with it's secrets encrypted in KMS\n\nArgs:\n file_path (string): Path to the parameter file to be encrypted\n pattern (string): Pattern to do fuzzy string matching\n service (string): Service to use KMS key to encrypt file\n environment (string): Environment to encrypt values\n clients (dict): KMS AWS client that has been instantiated\n\nReturns:\n None\n\nRaises:\n IOError: If the file does not exist", "source": "juraj_google_style"} +{"code": "def setValue(self, value):\n\n if value >= self.minimum() and value <= self.maximum():\n self._lineEdit.setText(str(value))\n elif value < self.minimum():\n self._lineEdit.setText(str(self.minimum()))\n elif value > self.maximum():\n self._lineEdit.setText(str(self.maximum()))\n return True", "docstring": "setter function to _lineEdit.text. Sets minimum/maximum as new value if value is out of bounds.\n\nArgs:\n value (int/long): new value to set.\n\n Returns\n True if all went fine.", "source": "juraj_google_style"} +{"code": "def parse_peddy_ped_check(lines):\n\n ped_check = []\n header = []\n for i,line in enumerate(lines):\n line = line.rstrip()\n if i == 0:\n # Header line\n header = line.lstrip('#').split(',')\n else:\n pair_info = dict(zip(header, line.split(',')))\n\n # the number of sites at which sample_a was heterozygous\n pair_info['hets_a'] = convert_number(pair_info['hets_a'])\n\n # the number of sites at which sample_b was heterozygous\n pair_info['hets_b'] = convert_number(pair_info['hets_b'])\n\n # the number of sites at which the 2 samples shared no alleles \n # (should approach 0 for parent-child pairs).\n pair_info['ibs0'] = convert_number(pair_info['ibs0'])\n\n # the number of sites and which the 2 samples where both \n # hom-ref, both het, or both hom-alt.\n pair_info['ibs2'] = convert_number(pair_info['ibs2'])\n\n # the number of sites that was used to predict the relatedness.\n pair_info['n'] = convert_number(pair_info['n'])\n\n # the relatedness reported in the ped file.\n pair_info['rel'] = convert_number(pair_info['rel'])\n\n # the relatedness reported in the ped file.\n pair_info['pedigree_relatedness'] = convert_number(pair_info['pedigree_relatedness'])\n\n # difference between the preceding 2 colummns.\n pair_info['rel_difference'] = convert_number(pair_info['rel_difference'])\n\n # the number of sites at which both samples were hets.\n pair_info['shared_hets'] = convert_number(pair_info['shared_hets'])\n\n # boolean indicating that this pair is a parent-child pair \n # according to the ped file.\n pair_info['pedigree_parents'] = make_bool(pair_info.get('pedigree_parents'))\n\n # boolean indicating that this pair is expected to be a parent-child\n # pair according to the ibs0 (< 0.012) calculated from the genotypes.\n pair_info['predicted_parents'] = make_bool(pair_info.get('predicted_parents'))\n\n # boolean indicating that the preceding 2 columns do not match\n pair_info['parent_error'] = make_bool(pair_info.get('parent_error'))\n\n # boolean indicating that rel > 0.75 and ibs0 < 0.012\n pair_info['sample_duplication_error'] = make_bool(pair_info.get('sample_duplication_error'))\n\n\n ped_check.append(pair_info)\n\n return ped_check", "docstring": "Parse a .ped_check.csv file\n\nArgs:\n lines(iterable(str))\n\nReturns:\n ped_check(list(dict))", "source": "juraj_google_style"} +{"code": "def dataframe_from_excel(path, sheetname=0, header=0, skiprows=None): # , parse_dates=False):\n\n sheetname = sheetname or 0\n if isinstance(sheetname, (basestring, float)):\n try:\n sheetname = int(sheetname)\n except (TypeError, ValueError, OverflowError):\n sheetname = str(sheetname)\n wb = xlrd.open_workbook(path)\n # if isinstance(sheetname, int):\n # sheet = wb.sheet_by_index(sheetname)\n # else:\n # sheet = wb.sheet_by_name(sheetname)\n # assert(not parse_dates, \"`parse_dates` argument and function not yet implemented!\")\n # table = [sheet.row_values(i) for i in range(sheet.nrows)]\n return pd.io.excel.read_excel(wb, sheetname=sheetname, header=header, skiprows=skiprows, engine='xlrd')", "docstring": "Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name\n\nArgs:\n path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from\n ext (str): file name extension (to filter files by)\n date_parser (function): if the MultiIndex can be interpretted as a datetime, this parser will be used\n\nReturns:\n dict of DataFrame: { file_path: flattened_data_frame }", "source": "juraj_google_style"} +{"code": "def array_to_csv(array_like): # type: (np.array or Iterable or int or float) -> str\n\n stream = StringIO()\n np.savetxt(stream, array_like, delimiter=',', fmt='%s')\n return stream.getvalue()", "docstring": "Convert an array like object to CSV.\n\n To understand better what an array like object is see:\n https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays\n\nArgs:\n array_like (np.array or Iterable or int or float): array like object to be converted to CSV.\n\nReturns:\n (str): object serialized to CSV", "source": "juraj_google_style"} +{"code": "def _parse_url_and_validate(cls, url):\n\n parsed_url = urlparse(url)\n if parsed_url.scheme and parsed_url.netloc:\n final_url = parsed_url.geturl()\n else:\n raise BadURLException\n return final_url", "docstring": "Recieves a URL string and validates it using urlparse.\n\nArgs:\n url: A URL string\n\nReturns:\n parsed_url: A validated URL\n\nRaises:\n BadURLException", "source": "juraj_google_style"} +{"code": "def CheckVlogArguments(filename, clean_lines, linenum, error):\n\n line = clean_lines.elided[linenum]\n if Search(r'\\bVLOG\\((INFO|ERROR|WARNING|DFATAL|FATAL)\\)', line):\n error(filename, linenum, 'runtime/vlog', 5,\n 'VLOG() should be used with numeric verbosity level. '\n 'Use LOG() if you want symbolic severity levels.')", "docstring": "Checks that VLOG() is only used for defining a logging level.\n\n For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and\n VLOG(FATAL) are not.\n\nArgs:\n filename: The name of the current file.\n clean_lines: A CleansedLines instance containing the file.\n linenum: The number of the line to check.\n error: The function to call with any errors found.", "source": "juraj_google_style"} +{"code": "def _add_rank_score(self, variant_obj, info_dict):\n\n rank_score_entry = info_dict.get('RankScore')\n if rank_score_entry:\n for family_annotation in rank_score_entry.split(','):\n rank_score = family_annotation.split(':')[-1]\n logger.debug(\"Updating rank_score to: {0}\".format(\n rank_score))\n variant_obj.rank_score = float(rank_score)", "docstring": "Add the rank score if found\n\nArgs:\n variant_obj (puzzle.models.Variant)\n info_dict (dict): A info dictionary", "source": "juraj_google_style"} +{"code": "def get_blob(profile, sha):\n\n resource = \"/blobs/\" + sha\n data = api.get_request(profile, resource)\n return prepare(data)", "docstring": "Fetch a blob.\n\nArgs:\n profile\n A profile generated from ``simplygithub.authentication.profile``.\n Such profiles tell this module (i) the ``repo`` to connect to,\n and (ii) the ``token`` to connect with.\n\n sha\n The SHA of the blob to fetch.\n\nReturns:\n A dict with data about the blob.", "source": "juraj_google_style"} +{"code": "def GetDefinitionByName(self, name):\n\n lookup_name = name.lower()\n if lookup_name not in self._definitions:\n lookup_name = self._aliases.get(name, None)\n\n return self._definitions.get(lookup_name, None)", "docstring": "Retrieves a specific data type definition by name.\n\nArgs:\n name (str): name of the data type definition.\n\nReturns:\n DataTypeDefinition: data type definition or None if not available.", "source": "juraj_google_style"} +{"code": "def apply_operation(self, symmop):\n\n\n def operate_site(site):\n new_cart = symmop.operate(site.coords)\n return Site(site.species, new_cart,\n properties=site.properties)\n\n self._sites = [operate_site(s) for s in self._sites]", "docstring": "Apply a symmetry operation to the molecule.\n\nArgs:\n symmop (SymmOp): Symmetry operation to apply.", "source": "juraj_google_style"} +{"code": "def wiki_create(self, title, body, other_names=None):\n\n params = {\n 'wiki_page[title]': title,\n 'wiki_page[body]': body,\n 'wiki_page[other_names]': other_names\n }\n return self._get('wiki_pages.json', params, method='POST', auth=True)", "docstring": "Action to lets you create a wiki page (Requires login) (UNTESTED).\n\n Parameters:\n title (str): Page title.\n body (str): Page content.\n other_names (str): Other names.", "source": "juraj_google_style"} +{"code": "def delete_by_file(self, file_obj):\n\n BalancedDiscStorage._check_interface(file_obj)\n\n file_hash = self._get_hash(file_obj)\n\n return self.delete_by_hash(file_hash)", "docstring": "Remove file from the storage. File is identified by opened `file_obj`,\n from which the hashes / path are computed.\n\nArgs:\n file_obj (file): Opened file-like object, which is used to compute\n hashes.\n\nRaises:\n IOError: If the `file_obj` is not in storage.", "source": "juraj_google_style"} +{"code": "def write_fasta_file(seq_records, outname, outdir=None, outext='.faa', force_rerun=False):\n\n\n if not outdir:\n outdir = ''\n outfile = ssbio.utils.outfile_maker(inname='', outname=outname, outdir=outdir, outext=outext)\n\n if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):\n SeqIO.write(seq_records, outfile, \"fasta\")\n\n return outfile", "docstring": "Write a FASTA file for a SeqRecord or a list of SeqRecord objects.\n\nArgs:\n seq_records (SeqRecord, list): SeqRecord or a list of SeqRecord objects\n outname: Name of the output file which will have outext appended to it\n outdir: Path to directory to output sequences to\n outext: Extension of FASTA file, default \".faa\"\n force_rerun: If file should be overwritten if it exists\n\nReturns:\n str: Path to output FASTA file.", "source": "juraj_google_style"} +{"code": "def get_available_transcript_languages(video_id):\n\n available_languages = VideoTranscript.objects.filter(\n video__edx_video_id=video_id\n ).values_list(\n 'language_code', flat=True\n )\n return list(available_languages)", "docstring": "Get available transcript languages\n\nArgs:\n video_id(unicode): An id identifying the Video.\n\nReturns:\n A list containing transcript language codes for the Video.", "source": "juraj_google_style"} +{"code": "def __init__(self, data_parallelism, expert_parallelism, gates):\n\n self._gates = gates\n self._dp = data_parallelism\n self._ep = expert_parallelism\n assert len(gates) == self._dp.n\n self._dispatchers = self._dp(SparseDispatcher, self._ep.n, gates)", "docstring": "Create a DistributedSparseDispatcher.\n\nArgs:\n data_parallelism: a Parallelism object.\n expert_parallelism: a Parallelism object.\n gates: a list of datashard_parallelism.n `Tensor`s of shapes\n `[batch_size[d], num_experts]`.\n\nReturns:\n a DistributedSparseDispatcher", "source": "juraj_google_style"} +{"code": "def create_batch(cls, size, **kwargs):\n\n return [cls.create(**kwargs) for _ in range(size)]", "docstring": "Create a batch of instances of the given class, with overriden attrs.\n\nArgs:\n size (int): the number of instances to create\n\nReturns:\n object list: the created instances", "source": "juraj_google_style"} +{"code": "def __load_config__(self, config, **kwargs):\n\n # The configuration cannot be initialised more than once\n if self.__is_initialized__:\n raise ImportError(\"RdfConfigManager has already been initialized\")\n self.__set_cfg_reqs__(**kwargs)\n self.__set_cfg_attrs__(config, **kwargs)\n self.__config__['TURN_ON_VOCAB'] = kwargs.get(\"turn_on_vocab\",\n self.__config__.get(\"TURN_ON_VOCAB\",\n self.__cfg_reqs__[\"TURN_ON_VOCAB\"]['default']))\n errors = self.__verify_config__(self.__config__, **kwargs)\n self.__reslove_errors__(errors, **kwargs)\n log.info(\"CONFIGURATION validated\")\n self.__is_initialized__ = True\n log.info(\"Initializing directories\")\n self.__initialize_directories__(**kwargs)\n log.info(\"Setting Logging\")\n self.__set_logging__(**kwargs)\n log.info(\"setting RDF Namespaces\")\n self.__load_namespaces__(**kwargs)\n log.info(\"Initializing Connections\")\n self.__initialize_conns__(**kwargs)\n log.info(\"Registering RML Mappings\")\n self.__register_mappings__(**kwargs)\n self.__run_defs__(**kwargs)", "docstring": "Reads a python config file and initializes the cloass\n\nArgs:\n obj: the config data", "source": "juraj_google_style"} +{"code": "def _big_endian_int(bits: np.ndarray) -> int:\n\n result = 0\n for e in bits:\n result <<= 1\n if e:\n result |= 1\n return result", "docstring": "Returns the big-endian integer specified by the given bits.\n\n For example, [True, False, False, True, False] becomes binary 10010 which\n is 18 in decimal.\n\nArgs:\n bits: Descending bits of the integer, with the 1s bit at the end.\n\nReturns:\n The integer.", "source": "juraj_google_style"} +{"code": "def deploy(app_id, version, promote, quiet):\n # type: (str, str, bool, bool) -> None\n\n gae_app = GaeApp.for_branch(git.current_branch().name)\n\n if gae_app is None and None in (app_id, version):\n msg = (\n \"Can't find an AppEngine app setup for branch <35>{}<32> and\"\n \"--project and --version were not given.\"\n )\n log.err(msg, git.current_branch().name)\n sys.exit(1)\n\n if version is not None:\n gae_app.version = version\n\n if app_id is not None:\n gae_app.app_id = app_id\n\n gae_app.deploy(promote, quiet)", "docstring": "Deploy the app to AppEngine.\n\nArgs:\n app_id (str):\n AppEngine App ID. Overrides config value app_id if given.\n version (str):\n AppEngine project version. Overrides config values if given.\n promote (bool):\n If set to **True** promote the current remote app version to the one\n that's being deployed.\n quiet (bool):\n If set to **True** this will pass the ``--quiet`` flag to gcloud\n command.", "source": "juraj_google_style"} +{"code": "def _parse_stop_words_file(self, path):\n\n language = None\n loaded = False\n\n if os.path.isfile(path):\n self._logger.debug('Loading stop words in %s', path)\n\n language = path.split('-')[-1]\n\n if not language in self.__stop_words:\n self.__stop_words[language] = set()\n\n with codecs.open(path, 'r', 'UTF-8') as file:\n loaded = True\n for word in file:\n self.__stop_words[language].add(word.strip())\n\n return loaded", "docstring": "Load stop words from the given path.\n\n Parse the stop words file, saving each word found in it in a set\n for the language of the file. This language is obtained from\n the file name. If the file doesn't exist, the method will have\n no effect.\n\nArgs:\n path: Path to the stop words file.\n\nReturns:\n A boolean indicating whether the file was loaded.", "source": "juraj_google_style"} +{"code": "def edit(self, **kwargs):\n\n if 'id' not in kwargs:\n kwargs['id'] = self.ratingKey\n if 'type' not in kwargs:\n kwargs['type'] = utils.searchType(self.type)\n\n part = '/library/sections/%s/all?%s' % (self.librarySectionID,\n urlencode(kwargs))\n self._server.query(part, method=self._server._session.put)", "docstring": "Edit an object.\n\n Parameters:\n kwargs (dict): Dict of settings to edit.\n\nExample:\n {'type': 1,\n 'id': movie.ratingKey,\n 'collection[0].tag.tag': 'Super',\n 'collection.locked': 0}", "source": "juraj_google_style"} +{"code": "def get_vocabulary(preprocess_output_dir, name):\n\n vocab_file = os.path.join(preprocess_output_dir, CATEGORICAL_ANALYSIS % name)\n if not file_io.file_exists(vocab_file):\n raise ValueError('File %s not found in %s' %\n (CATEGORICAL_ANALYSIS % name, preprocess_output_dir))\n\n labels = python_portable_string(\n file_io.read_file_to_string(vocab_file)).split('\\n')\n label_values = [x for x in labels if x] # remove empty lines\n\n return label_values", "docstring": "Loads the vocabulary file as a list of strings.\n\nArgs:\n preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name.\n name: name of the csv column.\n\nReturns:\n List of strings.\n\nRaises:\n ValueError: if file is missing.", "source": "juraj_google_style"} +{"code": "def get_repository_method(namespace, method, snapshot_id, wdl_only=False):\n\n uri = \"methods/{0}/{1}/{2}?onlyPayload={3}\".format(namespace, method,\n snapshot_id,\n str(wdl_only).lower())\n return __get(uri)", "docstring": "Get a method definition from the method repository.\n\nArgs:\n namespace (str): Methods namespace\n method (str): method name\n version (int): snapshot_id of the method\n wdl_only (bool): Exclude metadata\n\n Swagger:\n https://api.firecloud.org/#!/Method_Repository/get_api_methods_namespace_name_snapshotId", "source": "juraj_google_style"} +{"code": "def run_node(self, node, stim):\n\n if isinstance(node, string_types):\n node = self.nodes[node]\n\n result = node.transformer.transform(stim)\n if node.is_leaf():\n return listify(result)\n\n stim = result\n # If result is a generator, the first child will destroy the\n # iterable, so cache via list conversion\n if len(node.children) > 1 and isgenerator(stim):\n stim = list(stim)\n return list(chain(*[self.run_node(c, stim) for c in node.children]))", "docstring": "Executes the Transformer at a specific node.\n\nArgs:\n node (str, Node): If a string, the name of the Node in the current\n Graph. Otherwise the Node instance to execute.\n stim (str, stim, list): Any valid input to the Transformer stored\n at the target node.", "source": "juraj_google_style"} +{"code": "def Normalize(self, fraction=1.0):\n\n if self.log:\n raise ValueError(\"Pmf is under a log transform\")\n\n total = self.Total()\n if total == 0.0:\n raise ValueError('total probability is zero.')\n logging.warning('Normalize: total probability is zero.')\n return total\n\n factor = float(fraction) / total\n for x in self.d:\n self.d[x] *= factor\n\n return total", "docstring": "Normalizes this PMF so the sum of all probs is fraction.\n\nArgs:\n fraction: what the total should be after normalization\n\n Returns: the total probability before normalizing", "source": "juraj_google_style"} +{"code": "def route(self, method, pattern):\n\n def decorator(callback):\n self._router.add(method, pattern, callback)\n return callback\n return decorator", "docstring": "Decorator to add route for a request with any HTTP method.\n\nArgs:\n method (str): HTTP method name, e.g. GET, POST, etc.\n pattern (str): Routing pattern the path must match.\n\nReturns:\n function: Decorator function to add route.", "source": "juraj_google_style"} +{"code": "def __init__(self, agent, environment, repeat_actions=1, history=None, id_=0):\n\n super(Runner, self).__init__(agent, environment, repeat_actions, history)\n\n self.id = id_ # the worker's ID in a distributed run (default=0)\n self.current_timestep = None", "docstring": "Initialize a single Runner object (one Agent/one Environment).\n\nArgs:\n id_ (int): The ID of this Runner (for distributed TF runs).", "source": "juraj_google_style"} +{"code": "def book(symbol=None, token='', version=''):\n\n _raiseIfNotStr(symbol)\n if symbol:\n return _getJson('deep/book?symbols=' + symbol, token, version)\n return _getJson('deep/book', token, version)", "docstring": "Book shows IEX’s bids and asks for given symbols.\n\n https://iexcloud.io/docs/api/#deep-book\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n dict: result", "source": "juraj_google_style"} +{"code": "def liquid_precipitation_depth(self, value=999.0):\n\n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type float '\n 'for field `liquid_precipitation_depth`'.format(value))\n\n self._liquid_precipitation_depth = value", "docstring": "Corresponds to IDD Field `liquid_precipitation_depth`\n\nArgs:\n value (float): value for IDD Field `liquid_precipitation_depth`\n Unit: mm\n Missing value: 999.0\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def equals(self, rhs):\n\n\n try:\n return round(rhs-self._float_value, self._places) == 0\n except TypeError:\n # This is probably because either float_value or rhs is not a number.\n return False", "docstring": "Check to see if RHS is almost equal to float_value\n\nArgs:\n rhs: the value to compare to float_value\n\nReturns:\n bool", "source": "juraj_google_style"} +{"code": "def _ExpandDirectories(filenames):\n\n expanded = set()\n for filename in filenames:\n if not os.path.isdir(filename):\n expanded.add(filename)\n continue\n\n for root, _, files in os.walk(filename):\n for loopfile in files:\n fullname = os.path.join(root, loopfile)\n if fullname.startswith('.' + os.path.sep):\n fullname = fullname[len('.' + os.path.sep):]\n expanded.add(fullname)\n\n filtered = []\n for filename in expanded:\n if os.path.splitext(filename)[1][1:] in GetAllExtensions():\n filtered.append(filename)\n\n return filtered", "docstring": "Searches a list of filenames and replaces directories in the list with\n all files descending from those directories. Files with extensions not in\n the valid extensions list are excluded.\n\nArgs:\n filenames: A list of files or directories\n\nReturns:\n A list of all files that are members of filenames or descended from a\n directory in filenames", "source": "juraj_google_style"} +{"code": "def add_edge(self, edge, double=False):\n\n (left_entity, right_entity) = edge\n self.add_node(left_entity)\n self.add_node(right_entity)\n self[left_entity].update({right_entity:self[right_entity]})\n if double:\n self.add_edge((edge[1], edge[0]))", "docstring": "Adds an edge to the ``DictGraph``. An edge is just a pair of **node\n objects**. If the **node objects** are not in the graph they are\n created.\n\nArgs:\n - edge(iterable) An ordered pair of **node objects**. The edge is\n assumed to have a direction from the first to the second **node\n object**.\n - double(``bool``) [default: ``False```] If ``True`` the the reverse\n edge is also added.", "source": "juraj_google_style"} +{"code": "def __init__(self, mapreduce_spec, shard_state, task_retry_count=0):\n\n self._shard_state = shard_state\n self.mapreduce_spec = mapreduce_spec\n # TODO(user): Create a hierarchy of Context classes. Certain fields\n # like task_retry_count only makes sense in TaskAttemptContext.\n self.task_retry_count = task_retry_count\n\n if self.mapreduce_spec:\n self.mapreduce_id = self.mapreduce_spec.mapreduce_id\n else:\n # Only in tests\n self.mapreduce_id = None\n if shard_state:\n self.shard_id = shard_state.get_shard_id()\n else:\n # Only in tests\n self.shard_id = None\n\n # TODO(user): Allow user to specify max entity count for the pool\n # as they know how big their entities are.\n self._mutation_pool = _MutationPool(mapreduce_spec=mapreduce_spec)\n self._counters = _Counters(shard_state)\n # TODO(user): Remove this after fixing\n # keyhole/dataeng/imagery/feeds/client_lib.py in another CL.\n self.counters = self._counters\n\n self._pools = {}\n self.register_pool(\"mutation_pool\", self._mutation_pool)\n self.register_pool(\"counters\", self.counters)", "docstring": "Constructor.\n\nArgs:\n mapreduce_spec: mapreduce specification as model.MapreduceSpec.\n shard_state: an instance of model.ShardState. This has to be the same\n instance as the one MapperWorkerHandler mutates. All mutations are\n flushed to datastore in the end of the slice.\n task_retry_count: how many times this task has been retried.", "source": "juraj_google_style"} +{"code": "def get_file_network_traffic(self, resources):\n\n api_name = 'virustotal-file-network-traffic'\n api_endpoint = 'file/network-traffic'\n return self._extract_all_responses(resources, api_endpoint, api_name)", "docstring": "Retrieves a report about the network traffic of a md5, sha1, and/or sha2 hash of\n file, when it is executed.\n\nArgs:\n resources: list of string hashes.", "source": "juraj_google_style"} +{"code": "def post_cutout(self, token, channel,\n x_start,\n y_start,\n z_start,\n data,\n resolution=0):\n\n return self.data.post_cutout(token, channel,\n x_start,\n y_start,\n z_start,\n data,\n resolution)", "docstring": "Post a cutout to the server.\n\nArgs:\n token (str)\n channel (str)\n x_start (int)\n y_start (int)\n z_start (int)\n data (numpy.ndarray): A numpy array of data. Pass in (x, y, z)\n resolution (int : 0): Resolution at which to insert the data\n\nReturns:\n bool: True on success\n\nRaises:\n RemoteDataUploadError: if there's an issue during upload.", "source": "juraj_google_style"} +{"code": "def get_links(network_id, template_id=None, **kwargs):\n\n user_id = kwargs.get('user_id')\n try:\n net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()\n net_i.check_read_permission(user_id=user_id)\n except NoResultFound:\n raise ResourceNotFoundError(\"Network %s not found\"%(network_id))\n\n link_qry = db.DBSession.query(Link).filter(\n Link.network_id==network_id,\n Link.status=='A').options(\n noload('network')\n ).options(\n joinedload_all('types.templatetype')\n ).options(\n joinedload_all('attributes.attr')\n )\n\n if template_id is not None:\n link_qry = link_qry.filter(ResourceType.link_id==Link.id,\n TemplateType.id==ResourceType.type_id,\n TemplateType.template_id==template_id)\n\n links = link_qry.all()\n return links", "docstring": "Get all the links in a network.\n\nArgs:\n network_id (int): The network in which to search\n template_id (int): Only return links whose type is in this template.", "source": "juraj_google_style"} +{"code": "def __init__(self, engine):\n\n super(StatikJinjaTemplateProvider, self).__init__(engine)\n project = engine.project\n\n logger.debug(\"Instantiating Jinja2 template provider\")\n\n # now load our template tags\n self.templatetags_path = os.path.join(project.path, project.TEMPLATETAGS_DIR)\n if os.path.exists(self.templatetags_path) and os.path.isdir(self.templatetags_path):\n # dynamically import modules; they register themselves with our template tag store\n import_python_modules_by_path(self.templatetags_path)\n\n extensions = [\n 'statik.jinja2ext.StatikUrlExtension',\n 'statik.jinja2ext.StatikAssetExtension',\n 'statik.jinja2ext.StatikLoremIpsumExtension',\n 'statik.jinja2ext.StatikTemplateTagsExtension',\n 'jinja2.ext.do',\n 'jinja2.ext.loopcontrols',\n 'jinja2.ext.with_',\n 'jinja2.ext.autoescape',\n ]\n\n jinja2_config = project.config.vars.get('jinja2', dict())\n extensions.extend(jinja2_config.get('extensions', list()))\n\n self.env = jinja2.Environment(\n loader=jinja2.FileSystemLoader(\n engine.template_paths,\n encoding=project.config.encoding\n ),\n extensions=extensions\n )\n\n if templatetags.store.filters:\n logger.debug(\n \"Loaded custom template tag filters: %s\",\n \", \".join(templatetags.store.filters)\n )\n self.env.filters.update(templatetags.store.filters)\n\n # configure views for the Jinja2 templating environment\n self.env.statik_views = project.views\n self.env.statik_base_url = project.config.base_path\n self.env.statik_base_asset_url = add_url_path_component(\n project.config.base_path,\n project.config.assets_dest_path\n )", "docstring": "Constructor.\n\nArgs:\n engine: The StatikTemplateEngine to which this template provider belongs.", "source": "juraj_google_style"} +{"code": "def repr(self, changed_widgets=None):\n\n if changed_widgets is None:\n changed_widgets = {}\n local_changed_widgets = {}\n _innerHTML = self.innerHTML(local_changed_widgets)\n\n if self._ischanged() or ( len(local_changed_widgets) > 0 ):\n self._backup_repr = ''.join(('<', self.type, ' ', self._repr_attributes, '>', \n _innerHTML, ''))\n #faster but unsupported before python3.6\n #self._backup_repr = f'<{self.type} {self._repr_attributes}>{_innerHTML}'\n if self._ischanged():\n # if self changed, no matter about the children because will be updated the entire parent\n # and so local_changed_widgets is not merged\n changed_widgets[self] = self._backup_repr\n self._set_updated()\n else:\n changed_widgets.update(local_changed_widgets)\n return self._backup_repr", "docstring": "It is used to automatically represent the object to HTML format\n packs all the attributes, children and so on.\n\nArgs:\n changed_widgets (dict): A dictionary containing a collection of tags that have to be updated.\n The tag that have to be updated is the key, and the value is its textual repr.", "source": "juraj_google_style"} +{"code": "def __setitem__(self, key, value):\n\n if key not in self.data:\n self.data[key] = [value]\n else:\n self.data[key].append(value)", "docstring": "Adds value to the list of values for the specified key.\n\nArgs:\n key (object): Key\n value (object): Value", "source": "juraj_google_style"} +{"code": "def query(self, expr, **kwargs):\n\n columns = self.columns\n\n def query_builder(df, **kwargs):\n # This is required because of an Arrow limitation\n # TODO revisit for Arrow error\n df = df.copy()\n df.index = pandas.RangeIndex(len(df))\n df.columns = columns\n df.query(expr, inplace=True, **kwargs)\n df.columns = pandas.RangeIndex(len(df.columns))\n return df\n\n func = self._prepare_method(query_builder, **kwargs)\n new_data = self._map_across_full_axis(1, func)\n # Query removes rows, so we need to update the index\n new_index = self.compute_index(0, new_data, True)\n\n return self.__constructor__(new_data, new_index, self.columns, self.dtypes)", "docstring": "Query columns of the DataManager with a boolean expression.\n\nArgs:\n expr: Boolean expression to query the columns with.\n\nReturns:\n DataManager containing the rows where the boolean expression is satisfied.", "source": "juraj_google_style"} +{"code": "def _free_up_space(self, size, this_rel_path=None):\n\n\n # Amount of space we are over ( bytes ) for next put\n space = self.size + size - self.maxsize\n\n if space <= 0:\n return\n\n removes = []\n\n for row in self.database.execute(\"SELECT path, size, time FROM files ORDER BY time ASC\"):\n\n if space > 0:\n removes.append(row[0])\n space -= row[1]\n else:\n break\n\n for rel_path in removes:\n if rel_path != this_rel_path:\n global_logger.debug(\"Deleting {}\".format(rel_path))\n self.remove(rel_path)", "docstring": "If there are not size bytes of space left, delete files\n until there is\n\nArgs:\n size: size of the current file\n this_rel_path: rel_pat to the current file, so we don't delete it.", "source": "juraj_google_style"} +{"code": "def get_dimension(self, key, value, **kwargs):\n\n return self._get_object_by_name(self._DIMENSION_ENDPOINT_SUFFIX,\n '{0}/{1}'.format(key, value),\n **kwargs)", "docstring": "get a dimension by key and value\n\nArgs:\n key (string): key of the dimension\n value (string): value of the dimension\n\nReturns:\n dictionary of response", "source": "juraj_google_style"} +{"code": "def run(self, module, post_check):\n\n try:\n # Simulate the sys.path behaviour decribed here:\n #\n # https://docs.python.org/2/library/sys.html#sys.path\n _cwd = os.getcwd()\n _sys_path = list(sys.path)\n _sys_argv = list(sys.argv)\n sys.path.insert(0, os.path.dirname(self._path))\n sys.argv = [os.path.basename(self._path)] + self._argv\n\n exec(self._code, module.__dict__)\n post_check()\n\n except Exception as e:\n self._failed = True\n self._error_detail = traceback.format_exc()\n\n _exc_type, _exc_value, exc_traceback = sys.exc_info()\n filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]\n\n self._error = \"%s\\nFile \\\"%s\\\", line %d, in %s:\\n%s\" % (str(e), os.path.basename(filename), line_number, func, txt)\n\n finally:\n # undo sys.path, CWD fixups\n os.chdir(_cwd)\n sys.path = _sys_path\n sys.argv = _sys_argv\n self.ran = True", "docstring": "Execute the configured source code in a module and run any post\n checks.\n\nArgs:\n module (Module) : a module to execute the configured code in.\n\n post_check(callable) : a function that can raise an exception\n if expected post-conditions are not met after code execution.", "source": "juraj_google_style"} +{"code": "def _ListFileEntry(\n self, file_system, file_entry, parent_full_path, output_writer):\n\n # Since every file system implementation can have their own path\n # segment separator we are using JoinPath to be platform and file system\n # type independent.\n full_path = file_system.JoinPath([parent_full_path, file_entry.name])\n if not self._list_only_files or file_entry.IsFile():\n output_writer.WriteFileEntry(full_path)\n\n for sub_file_entry in file_entry.sub_file_entries:\n self._ListFileEntry(file_system, sub_file_entry, full_path, output_writer)", "docstring": "Lists a file entry.\n\nArgs:\n file_system (dfvfs.FileSystem): file system that contains the file entry.\n file_entry (dfvfs.FileEntry): file entry to list.\n parent_full_path (str): full path of the parent file entry.\n output_writer (StdoutWriter): output writer.", "source": "juraj_google_style"} +{"code": "def track_file_ident_desc(self, file_ident):\n # type: (UDFFileIdentifierDescriptor) -> None\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('UDF File Entry not initialized')\n\n self.fi_descs.append(file_ident)", "docstring": "A method to start tracking a UDF File Identifier descriptor in this\n UDF File Entry. Both 'tracking' and 'addition' add the identifier to\n the list of file identifiers, but tracking doees not expand or\n otherwise modify the UDF File Entry.\n\n Parameters:\n file_ident - The UDF File Identifier Descriptor to start tracking.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def Exponential(cls,\n mean: 'TensorFluent',\n batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:\n\n rate = 1 / mean.tensor\n dist = tf.distributions.Exponential(rate)\n batch = mean.batch\n if not batch and batch_size is not None:\n t = dist.sample(batch_size)\n batch = True\n else:\n t = dist.sample()\n scope = mean.scope.as_list()\n return (dist, TensorFluent(t, scope, batch=batch))", "docstring": "Returns a TensorFluent for the Exponential sampling op with given mean parameter.\n\nArgs:\n mean: The mean parameter of the Exponential distribution.\n batch_size: The size of the batch (optional).\n\nReturns:\n The Exponential distribution and a TensorFluent sample drawn from the distribution.", "source": "juraj_google_style"} +{"code": "def delete_group(self, name):\n\n self.service.delete_group(\n name, self.url_prefix, self.auth, self.session,\n self.session_send_opts)", "docstring": "Delete given group.\n\nArgs:\n name (string): Name of group.\n\nRaises:\n requests.HTTPError on failure.", "source": "juraj_google_style"} +{"code": "def readMonthTariffs(self, months_type):\n\n self.setContext(\"readMonthTariffs\")\n try:\n\n req_type = binascii.hexlify(str(months_type).zfill(1))\n req_str = \"01523102303031\" + req_type + \"282903\"\n work_table = self.m_mons\n if months_type == ReadMonths.kWhReverse:\n work_table = self.m_rev_mons\n\n self.request(False)\n req_crc = self.calc_crc16(req_str[2:].decode(\"hex\"))\n req_str += req_crc\n self.m_serial_port.write(req_str.decode(\"hex\"))\n raw_ret = self.m_serial_port.getResponse(self.getContext())\n self.serialPostEnd()\n unpacked_read = self.unpackStruct(raw_ret, work_table)\n self.convertData(unpacked_read, work_table, self.m_kwh_precision)\n return_crc = self.calc_crc16(raw_ret[1:-2])\n if str(return_crc) == str(work_table[\"crc16\"][MeterData.StringValue]):\n ekm_log(\"Months CRC success, type = \" + str(req_type))\n self.setContext(\"\")\n return True\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n\n self.setContext(\"\")\n return False", "docstring": "Serial call to read month tariffs block into meter object buffer.\n\nArgs:\n months_type (int): A :class:`~ekmmeters.ReadMonths` value.\n\nReturns:\n bool: True on completion.", "source": "juraj_google_style"} +{"code": "def get(self, identifier, default=None):\n\n if isinstance(identifier, int):\n values = list(self.data.values())\n if 0 <= identifier < len(values):\n return values[identifier]\n else:\n return default\n return super(Overlay, self).get(identifier, default)", "docstring": "Get a layer in the Overlay.\n\n Get a particular layer in the Overlay using its path string\n or an integer index.\n\nArgs:\n identifier: Index or path string of the item to return\n default: Value to return if no item is found\n\nReturns:\n The indexed layer of the Overlay", "source": "juraj_google_style"} +{"code": "def files_sharedPublicURL(self, *, id: str, **kwargs) -> SlackResponse:\n\n self._validate_xoxp_token()\n kwargs.update({\"id\": id})\n return self.api_call(\"files.sharedPublicURL\", json=kwargs)", "docstring": "Enables a file for public/external sharing.\n\nArgs:\n id (str): The file id. e.g. 'F1234467890'", "source": "juraj_google_style"} +{"code": "def extract_run_id(key):\n\n filename = key.split('/')[-2] # -1 element is empty string\n run_id = filename.lstrip('run=')\n try:\n datetime.strptime(run_id, '%Y-%m-%d-%H-%M-%S')\n return key\n except ValueError:\n return None", "docstring": "Extract date part from run id\n\nArgs:\n key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/\n (trailing slash is required)\n\n >>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/')\n 'shredded-archive/run=2012-12-11-01-11-33/'\n >>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33')\n >>> extract_run_id('shredded-archive/run=2012-13-11-01-11-33/')", "source": "juraj_google_style"} +{"code": "def functions(start=None, end=None):\n\n start, end = fix_addresses(start, end)\n\n for func_t in idautils.Functions(start, end):\n yield Function(func_t)", "docstring": "Get all functions in range.\n\nArgs:\n start: Start address of the range. Defaults to IDB start.\n end: End address of the range. Defaults to IDB end.\n\nReturns:\n This is a generator that iterates over all the functions in the IDB.", "source": "juraj_google_style"} +{"code": "def create(limit=None, unwatched=False):\n\n scope = 'all'\n if limit is None:\n limit = 0\n else:\n scope = 'count'\n\n return Policy(scope, unwatched, limit)", "docstring": "Creates a :class:`~plexapi.sync.Policy` object for provided options and automatically sets proper `scope`\n value.\n\n Parameters:\n limit (int): limit items by count.\n unwatched (bool): if True then watched items wouldn't be synced.\n\nReturns:\n :class:`~plexapi.sync.Policy`.", "source": "juraj_google_style"} +{"code": "def sari_score(predictions, labels, features, **unused_kwargs):\n\n if \"inputs\" not in features:\n raise ValueError(\"sari_score requires inputs feature\")\n\n # Convert the inputs and outputs to a [batch_size, sequence_length] tensor.\n inputs = tf.squeeze(features[\"inputs\"], axis=[-1, -2])\n outputs = tf.to_int32(tf.argmax(predictions, axis=-1))\n outputs = tf.squeeze(outputs, axis=[-1, -2])\n\n # Convert the labels to a [batch_size, 1, sequence_length] tensor.\n labels = tf.squeeze(labels, axis=[-1, -2])\n labels = tf.expand_dims(labels, axis=1)\n\n score, _, _, _ = get_sari(inputs, outputs, labels)\n return score, tf.constant(1.0)", "docstring": "Computes the SARI scores from the given source, prediction and targets.\n\n An approximate SARI scoring method since we do not glue word pieces or\n decode the ids and tokenize the output. By default, we use ngram order of 4.\n Also, this does not have beam search.\n\nArgs:\n predictions: tensor, model predictions.\n labels: tensor, gold output.\n features: dict, containing inputs.\n\nReturns:\n sari: int, approx sari score", "source": "juraj_google_style"} +{"code": "def __init__(self, **kwargs):\n\n BestFit.__init__(self, **kwargs)\n # set defaults\n self.set_defaults(degree=1, resolution=1000)", "docstring": "Constructor\n\nArgs:\n **kwargs:\n degree: int, default=1\n degree of polynomial fitting\n resolution: int, default=1000", "source": "juraj_google_style"} +{"code": "def set_s3_prefix(self, region, name):\n\n ct = self.session.client('cloudtrail', region_name=region)\n ct.update_trail(Name=name, S3KeyPrefix=self.account.account_name)\n\n auditlog(\n event='cloudtrail.set_s3_prefix',\n actor=self.ns,\n data={\n 'account': self.account.account_name,\n 'region': region\n }\n )\n self.log.info('Updated S3KeyPrefix to {0} for {0}/{1}'.format(\n self.account.account_name,\n region\n ))", "docstring": "Sets the S3 prefix for a CloudTrail Trail\n\nArgs:\n region (`str`): Name of the AWS region\n name (`str`): Name of the CloudTrail Trail\n\nReturns:\n `None`", "source": "juraj_google_style"} +{"code": "def get2(item, key, if_none=None, strict=True):\n\n\n if not strict and item.get(key) == \"\":\n return if_none\n elif item.get(key) is None:\n return if_none\n else:\n return item.get(key)", "docstring": "similar to dict.get functionality but None value will return then\n if_none value\n\nArgs:\n item: dictionary to search\n key: the dictionary key\n if_none: the value to return if None is passed in\n strict: if False an empty string is treated as None", "source": "juraj_google_style"} +{"code": "def commit_signature(vcs, user_config, signature):\n\n if signature not in get_staged_signatures(vcs):\n raise NotStagedError\n evidence_path = _get_committed_history_path(vcs)\n committed_signatures = get_committed_signatures(vcs)\n if signature in committed_signatures:\n raise AlreadyCommittedError\n committed_signatures.append(signature)\n string = '\\n'.join(committed_signatures[-user_config['history_limit']:])\n with open(evidence_path, 'w') as f:\n f.write(string)\n unstage_signature(vcs, signature)", "docstring": "Add `signature` to the list of committed signatures\n\n The signature must already be staged\n\nArgs:\n vcs (easyci.vcs.base.Vcs)\n user_config (dict)\n signature (basestring)\n\nRaises:\n NotStagedError\n AlreadyCommittedError", "source": "juraj_google_style"} +{"code": "def export_model(self, export_formats, export_dir=None):\n\n export_dir = export_dir or self.logdir\n return self._export_model(export_formats, export_dir)", "docstring": "Exports model based on export_formats.\n\n Subclasses should override _export_model() to actually\n export model to local directory.\n\nArgs:\n export_formats (list): List of formats that should be exported.\n export_dir (str): Optional dir to place the exported model.\n Defaults to self.logdir.\n\nReturns:\n A dict that maps ExportFormats to successfully exported models.", "source": "juraj_google_style"} +{"code": "def _make_query_from_terms(self, terms):\n\n\n expanded_terms = self._expand_terms(terms)\n\n cterms = ''\n\n if expanded_terms['doc']:\n cterms = self.backend._and_join(expanded_terms['doc'])\n\n if expanded_terms['keywords']:\n if cterms:\n cterms = self.backend._and_join(\n cterms, self.backend._join_keywords(expanded_terms['keywords']))\n else:\n cterms = self.backend._join_keywords(expanded_terms['keywords'])\n\n logger.debug('Dataset terms conversion: `{}` terms converted to `{}` query.'.format(terms, cterms))\n return cterms", "docstring": "Creates a query for dataset from decomposed search terms.\n\nArgs:\n terms (dict or unicode or string):\n\nReturns:\n tuple: First element is str with FTS query, second is parameters of the query.", "source": "juraj_google_style"} +{"code": "def execute(self, shell = True):\n\n\t\tprocess = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell)\n\t\tself.output, self.errors = process.communicate()", "docstring": "Executes the command setted into class\n\nArgs:\n shell (boolean): Set True if command is a shell command. Default: True", "source": "juraj_google_style"} +{"code": "def hottestmonth(self, value=None):\n\n if value is not None:\n try:\n value = int(value)\n except ValueError:\n raise ValueError('value {} need to be of type int '\n 'for field `hottestmonth`'.format(value))\n if value < 1:\n raise ValueError('value need to be greater or equal 1 '\n 'for field `hottestmonth`')\n if value > 12:\n raise ValueError('value need to be smaller 12 '\n 'for field `hottestmonth`')\n\n self._hottestmonth = value", "docstring": "Corresponds to IDD Field `hottestmonth`\n\nArgs:\n value (int): value for IDD Field `hottestmonth`\n value >= 1\n value <= 12\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def deserialize_block(value):\n\n # Block id strings are stored under batch/txn ids for reference.\n # Only Blocks, not ids or Nones, should be returned by _get_block.\n block = Block()\n block.ParseFromString(value)\n return BlockWrapper(\n block=block)", "docstring": "Deserialize a byte string into a BlockWrapper\n\nArgs:\n value (bytes): the byte string to deserialze\n\nReturns:\n BlockWrapper: a block wrapper instance", "source": "juraj_google_style"} +{"code": "def do_ams_post(endpoint, path, body, access_token, rformat=\"json\", ds_min_version=\"3.0;NetFx\"):\n\n min_ds = dsversion_min\n content_acceptformat = json_acceptformat\n acceptformat = json_acceptformat\n if rformat == \"json_only\":\n min_ds = ds_min_version\n content_acceptformat = json_only_acceptformat\n if rformat == \"xml\":\n content_acceptformat = xml_acceptformat\n acceptformat = xml_acceptformat + \",application/xml\"\n headers = {\"Content-Type\": content_acceptformat,\n \"DataServiceVersion\": min_ds,\n \"MaxDataServiceVersion\": dsversion_max,\n \"Accept\": acceptformat,\n \"Accept-Charset\" : charset,\n \"Authorization\": \"Bearer \" + access_token,\n \"x-ms-version\" : xmsversion}\n response = requests.post(endpoint, data=body, headers=headers, allow_redirects=False)\n # AMS response to the first call can be a redirect,\n # so we handle it here to make it transparent for the caller...\n if response.status_code == 301:\n redirected_url = ''.join([response.headers['location'], path])\n response = requests.post(redirected_url, data=body, headers=headers)\n return response", "docstring": "Do a AMS HTTP POST request and return JSON.\n\nArgs:\n endpoint (str): Azure Media Services Initial Endpoint.\n path (str): Azure Media Services Endpoint Path.\n body (str): Azure Media Services Content Body.\n access_token (str): A valid Azure authentication token.\n rformat (str): A required JSON Accept Format.\n ds_min_version (str): A required DS MIN Version.\n\nReturns:\n HTTP response. JSON body.", "source": "juraj_google_style"} +{"code": "def __init__(self, date_time, date_time_description):\n\n super(OLECFSummaryInformationEvent, self).__init__(\n date_time, date_time_description)\n self.name = 'Summary Information'", "docstring": "Initializes an event.\n\nArgs:\n date_time (dfdatetime.DateTimeValues): date and time values.\n date_time_description (str): description of the meaning of the date\n and time values.", "source": "juraj_google_style"} +{"code": "def isPortAvailable(port='/dev/ttyUSB0'):\n\n isPortAvailable = serial.tools.list_ports.grep(port)\n\n try:\n next(isPortAvailable)\n available = True\n except StopIteration:\n available = False\n\n return available", "docstring": "Checks whether specified port is available.\n\n Source code derived from @lqdev suggestion per #38\n\nArgs:\n port: Serial port location i.e. 'COM1'. Default is /dev/ttyUSB0\n\nReturns:\n available: Boolean value indicating presence of port", "source": "juraj_google_style"} +{"code": "def update_plot_limits(ax, white_space):\n\n\n if hasattr(ax, 'zz_dataLim'):\n bounds = ax.xy_dataLim.bounds\n ax.set_xlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space)\n ax.set_ylim(bounds[1] - white_space, bounds[1] + bounds[3] + white_space)\n\n bounds = ax.zz_dataLim.bounds\n ax.set_zlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space)\n else:\n bounds = ax.dataLim.bounds\n assert not any(map(np.isinf, bounds)), 'Cannot set bounds if dataLim has infinite elements'\n ax.set_xlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space)\n ax.set_ylim(bounds[1] - white_space, bounds[1] + bounds[3] + white_space)", "docstring": "Sets the limit options of a matplotlib plot.\n\nArgs:\n ax: matplotlib axes\n white_space(float): whitespace added to surround the tight limit of the data\n\n Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d", "source": "juraj_google_style"} +{"code": "def init(self, force_deploy=False):\n\n machines = self.provider_conf.machines\n networks = self.provider_conf.networks\n _networks = []\n for network in networks:\n ipnet = IPNetwork(network.cidr)\n _networks.append({\n \"netpool\": list(ipnet)[10:-10],\n \"cidr\": network.cidr,\n \"roles\": network.roles,\n \"gateway\": ipnet.ip\n })\n\n vagrant_machines = []\n vagrant_roles = {}\n j = 0\n for machine in machines:\n for _ in range(machine.number):\n vagrant_machine = {\n \"name\": \"enos-%s\" % j,\n \"cpu\": machine.flavour_desc[\"core\"],\n \"mem\": machine.flavour_desc[\"mem\"],\n \"ips\": [n[\"netpool\"].pop() for n in _networks],\n }\n vagrant_machines.append(vagrant_machine)\n # Assign the machines to the right roles\n for role in machine.roles:\n vagrant_roles.setdefault(role, []).append(vagrant_machine)\n j = j + 1\n\n logger.debug(vagrant_roles)\n\n loader = FileSystemLoader(searchpath=TEMPLATE_DIR)\n env = Environment(loader=loader, autoescape=True)\n template = env.get_template('Vagrantfile.j2')\n vagrantfile = template.render(machines=vagrant_machines,\n provider_conf=self.provider_conf)\n vagrantfile_path = os.path.join(os.getcwd(), \"Vagrantfile\")\n with open(vagrantfile_path, 'w') as f:\n f.write(vagrantfile)\n\n # Build env for Vagrant with a copy of env variables (needed by\n # subprocess opened by vagrant\n v_env = dict(os.environ)\n v_env['VAGRANT_DEFAULT_PROVIDER'] = self.provider_conf.backend\n\n v = vagrant.Vagrant(root=os.getcwd(),\n quiet_stdout=False,\n quiet_stderr=False,\n env=v_env)\n if force_deploy:\n v.destroy()\n v.up()\n v.provision()\n roles = {}\n for role, machines in vagrant_roles.items():\n for machine in machines:\n keyfile = v.keyfile(vm_name=machine['name'])\n port = v.port(vm_name=machine['name'])\n address = v.hostname(vm_name=machine['name'])\n roles.setdefault(role, []).append(\n Host(address,\n alias=machine['name'],\n user=self.provider_conf.user,\n port=port,\n keyfile=keyfile))\n\n networks = [{\n 'cidr': str(n[\"cidr\"]),\n 'start': str(n[\"netpool\"][0]),\n 'end': str(n[\"netpool\"][-1]),\n 'dns': '8.8.8.8',\n 'gateway': str(n[\"gateway\"]),\n 'roles': n[\"roles\"]\n } for n in _networks]\n logger.debug(roles)\n logger.debug(networks)\n\n return (roles, networks)", "docstring": "Reserve and deploys the vagrant boxes.\n\nArgs:\n force_deploy (bool): True iff new machines should be started", "source": "juraj_google_style"} +{"code": "def send_client_cmd(self, data, cmd=None, via_queue=None):\n\n mq_channel = self._connect_mq()\n if cmd:\n data['cmd'] = cmd\n if via_queue:\n mq_channel.basic_publish(exchange='',\n routing_key=via_queue,\n body=json.dumps(data))\n else:\n mq_channel.basic_publish(exchange=self.prv_exchange,\n routing_key='',\n body=json.dumps(data))", "docstring": "Send arbitrary cmd and data to client\n\n if queue name passed by \"via_queue\" parameter,\n that queue will be used instead of users private exchange.\n\nArgs:\n data: dict\n cmd: string\n via_queue: queue name,", "source": "juraj_google_style"} +{"code": "def __init__(self, name, aliases=None, description=None, urls=None):\n\n super(FixedSizeDataTypeDefinition, self).__init__(\n name, aliases=aliases, description=description, urls=urls)\n self.size = definitions.SIZE_NATIVE\n self.units = 'bytes'", "docstring": "Initializes a fixed-size data type definition.\n\nArgs:\n name (str): name.\n aliases (Optional[list[str]]): aliases.\n description (Optional[str]): description.\n urls (Optional[list[str]]): URLs.", "source": "juraj_google_style"} +{"code": "def parse(self, template):\n\n self._compile_delimiters()\n\n start_index = 0\n content_end_index, parsed_section, section_key = None, None, None\n parsed_template = ParsedTemplate()\n\n states = []\n\n while True:\n match = self._template_re.search(template, start_index)\n\n if match is None:\n break\n\n match_index = match.start()\n end_index = match.end()\n\n matches = match.groupdict()\n\n # Normalize the matches dictionary.\n if matches['change'] is not None:\n matches.update(tag='=', tag_key=matches['delims'])\n elif matches['raw'] is not None:\n matches.update(tag='&', tag_key=matches['raw_name'])\n\n tag_type = matches['tag']\n tag_key = matches['tag_key']\n leading_whitespace = matches['whitespace']\n\n # Standalone (non-interpolation) tags consume the entire line,\n # both leading whitespace and trailing newline.\n did_tag_begin_line = match_index == 0 or template[match_index - 1] in END_OF_LINE_CHARACTERS\n did_tag_end_line = end_index == len(template) or template[end_index] in END_OF_LINE_CHARACTERS\n is_tag_interpolating = tag_type in ['', '&']\n\n if did_tag_begin_line and did_tag_end_line and not is_tag_interpolating:\n if end_index < len(template):\n end_index += template[end_index] == '\\r' and 1 or 0\n if end_index < len(template):\n end_index += template[end_index] == '\\n' and 1 or 0\n elif leading_whitespace:\n match_index += len(leading_whitespace)\n leading_whitespace = ''\n\n # Avoid adding spurious empty strings to the parse tree.\n if start_index != match_index:\n parsed_template.add(template[start_index:match_index])\n\n start_index = end_index\n\n if tag_type in ('#', '^'):\n # Cache current state.\n state = (tag_type, end_index, section_key, parsed_template)\n states.append(state)\n\n # Initialize new state\n section_key, parsed_template = tag_key, ParsedTemplate()\n continue\n\n if tag_type == '/':\n if tag_key != section_key:\n raise ParsingError(\"Section end tag mismatch: %s != %s\" % (tag_key, section_key))\n\n # Restore previous state with newly found section data.\n parsed_section = parsed_template\n\n (tag_type, section_start_index, section_key, parsed_template) = states.pop()\n node = self._make_section_node(template, tag_type, tag_key, parsed_section,\n section_start_index, match_index)\n\n else:\n node = self._make_interpolation_node(tag_type, tag_key, leading_whitespace)\n\n parsed_template.add(node)\n\n # Avoid adding spurious empty strings to the parse tree.\n if start_index != len(template):\n parsed_template.add(template[start_index:])\n\n return parsed_template", "docstring": "Parse a template string starting at some index.\n\n This method uses the current tag delimiter.\n\nArgs:\n template: a unicode string that is the template to parse.\n\n index: the index at which to start parsing.\n\nReturns:\n a ParsedTemplate instance.", "source": "juraj_google_style"} +{"code": "def _ParseFiletime(self, byte_stream):\n\n filetime_map = self._GetDataTypeMap('filetime')\n\n try:\n filetime = self._ReadStructureFromByteStream(\n byte_stream, 0, filetime_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError(\n 'Unable to parse FILETIME value with error: {0!s}'.format(\n exception))\n\n if filetime == 0:\n return None\n\n try:\n return dfdatetime_filetime.Filetime(timestamp=filetime)\n except ValueError:\n raise errors.ParseError(\n 'Invalid FILETIME value: 0x{0:08x}'.format(filetime))", "docstring": "Parses a FILETIME date and time value from a byte stream.\n\nArgs:\n byte_stream (bytes): byte stream.\n\nReturns:\n dfdatetime.Filetime: FILETIME date and time value or None if no\n value is set.\n\nRaises:\n ParseError: if the FILETIME could not be parsed.", "source": "juraj_google_style"} +{"code": "def get_filename(self, tag):\n\n if tag.find('filename', recursive=False) is not None:\n return tag.filename.contents[0]\n elif tag.find('anchorfile', recursive=False) is not None:\n return tag.anchorfile.contents[0] + '#' + tag.anchor.contents[0]", "docstring": "Extract and return a documentation filename from a tag.\n\n Override as necessary, though this default implementation probably\n covers all the cases of interest.\n\nArgs:\n tag: A BeautifulSoup Tag that satisfies match_criterion.\n\nReturns:\n A string that would be appropriate to use as the documentation\n filename for an entry in a Zeal database.", "source": "juraj_google_style"} +{"code": "def do_delete(endpoint, access_token):\n\n headers = {\"Authorization\": 'Bearer ' + access_token}\n headers['User-Agent'] = get_user_agent()\n return requests.delete(endpoint, headers=headers)", "docstring": "Do an HTTP GET request and return JSON.\n\nArgs:\n endpoint (str): Azure Resource Manager management endpoint.\n access_token (str): A valid Azure authentication token.\n\nReturns:\n HTTP response.", "source": "juraj_google_style"} +{"code": "def ExtractEvents(self, parser_mediator, registry_key, **kwargs):\n\n self._ParseLogonApplications(parser_mediator, registry_key)\n self._ParseRegisteredDLLs(parser_mediator, registry_key)", "docstring": "Extracts events from a Windows Registry key.\n\nArgs:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n registry_key (dfwinreg.WinRegistryKey): Windows Registry key.", "source": "juraj_google_style"} +{"code": "def load(self, txt_fst_file_name):\n\n with open(txt_fst_file_name, 'r') as input_filename:\n for line in input_filename:\n line = line.strip()\n split_line = line.split()\n if len(split_line) == 1:\n self[int(split_line[0])].final = True\n else:\n self.add_arc(int(split_line[0]), int(split_line[1]),\n split_line[2].decode('hex'))", "docstring": "Save the transducer in the text file format of OpenFST.\n The format is specified as follows:\n arc format: src dest ilabel olabel [weight]\n final state format: state [weight]\n lines may occur in any order except initial state must be first line\n\nArgs:\n txt_fst_file_name (str): The input file\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def get_transcript_credentials_state_for_org(org, provider=None):\n\n query_filter = {'org': org}\n if provider:\n query_filter['provider'] = provider\n\n return {\n credential.provider: credential.exists\n for credential in ThirdPartyTranscriptCredentialsState.objects.filter(**query_filter)\n }", "docstring": "Returns transcript credentials state for an org\n\nArgs:\n org (unicode): course organization\n provider (unicode): transcript provider\n\nReturns:\n dict: provider name and their credential existance map\n\n {\n u'Cielo24': True\n }\n {\n u'3PlayMedia': False,\n u'Cielo24': True\n }", "source": "juraj_google_style"} +{"code": "def __init__(self, filesystem, os_path_module=None):\n\n self.filesystem = filesystem\n self.sep = filesystem.path_separator\n self.altsep = filesystem.alternative_path_separator\n self.linesep = filesystem.line_separator()\n self._os_module = os\n if os_path_module is None:\n self.path = FakePathModule(self.filesystem, self)\n else:\n warnings.warn(FAKE_PATH_MODULE_DEPRECATION, DeprecationWarning,\n stacklevel=2)\n self.path = os_path_module\n if IS_PY2:\n self.fdopen = self._fdopen_ver2\n else:\n self.fdopen = self._fdopen\n self.__class__.devnull = ('/dev/nul' if filesystem.is_windows_fs\n else '/dev/nul')", "docstring": "Also exposes self.path (to fake os.path).\n\nArgs:\n filesystem: FakeFilesystem used to provide file system information\n os_path_module: (deprecated) Optional FakePathModule instance", "source": "juraj_google_style"} +{"code": "def is_node_inside_try_except(node: astroid.Raise) -> bool:\n\n context = find_try_except_wrapper_node(node)\n return isinstance(context, astroid.TryExcept)", "docstring": "Check if the node is directly under a Try/Except statement.\n (but not under an ExceptHandler!)\n\nArgs:\n node (astroid.Raise): the node raising the exception.\n\nReturns:\n bool: True if the node is inside a try/except statement, False otherwise.", "source": "juraj_google_style"} +{"code": "def add_element_with_atts_to_etree(self, etree, name, atts):\n\n xml_atts = {}\n for att in atts.keys():\n val = atts[att]\n if (val is not None):\n xml_atts[self._xml_att_name(att)] = str(val)\n if (len(xml_atts) > 0):\n e = Element(name, xml_atts)\n if (self.pretty_xml):\n e.tail = \"\\n\"\n etree.append(e)", "docstring": "Add element with name and atts to etree iff there are any atts.\n\n Parameters:\n etree - an etree object\n name - XML element name\n atts - dicts of attribute values. Attribute names are transformed", "source": "juraj_google_style"} +{"code": "def decode_from_file(estimator,\n vocabulary,\n model_type,\n batch_size,\n sequence_length,\n checkpoint_path=\"\",\n input_filename=gin.REQUIRED,\n output_filename=gin.REQUIRED,\n eos_id=1):\n\n with tf.gfile.Open(input_filename) as f:\n text = f.read()\n records = text.split(\"\\n\")\n inputs = [record.strip() for record in records]\n # Strip the last empty line.\n if not inputs[-1]:\n inputs.pop()\n n = len(inputs)\n # encode all inputs\n all_input_ids = []\n for line in inputs:\n ids = inputs_vocabulary(vocabulary).encode(line.strip())\n if model_type != \"lm\":\n # for text2self problems, the inputs represent a partial sequence\n # to be continued, and should not be terminated by EOS.\n # for sequence-to-sequence problems, the input needs to be EOS-terminated\n ids += [eos_id]\n if len(ids) > sequence_length:\n ids = ids[:sequence_length]\n else:\n ids.extend([0] * (sequence_length - len(ids)))\n all_input_ids.append(ids)\n # pad to make an integral number of batches\n all_input_ids.extend([all_input_ids[0]] * (-n % batch_size))\n padded_n = len(all_input_ids)\n all_input_ids = np.array(all_input_ids, dtype=np.int32)\n\n def input_fn(params):\n del params\n dataset = tf.data.Dataset.from_tensor_slices({\"inputs\": all_input_ids})\n dataset = dataset.batch(batch_size, drop_remainder=True)\n return dataset\n\n result_iter = estimator.predict(input_fn, checkpoint_path=checkpoint_path)\n vocab_size = targets_vocabulary(vocabulary).vocab_size\n decodes = []\n for i, result in enumerate(result_iter):\n output_ids = clean_decodes(list(result[\"outputs\"]), vocab_size)\n output_string = targets_vocabulary(vocabulary).decode(\n [int(x) for x in output_ids])\n decodes.append(output_string)\n if i & (i - 1) == 0:\n if i < len(inputs):\n # LOG every power of 2, don't log if it's padded input i >= len(inputs)\n tf.logging.info(\"decode %d input = %s\" % (i, inputs[i]))\n tf.logging.info(\" output = %s\" % output_string)\n\n # BUG WORKAROUND - on TF1.13 and earlier, the output for each batch is\n # repeated a number of times equal to the number of cores.\n if len(decodes) == padded_n:\n tf.logging.info(\"number of decodes matches number of inputs\")\n elif len(decodes) % padded_n == 0:\n num_cores = len(decodes) // padded_n\n tf.logging.info(\"output is repeated num_cores times - removing extras\")\n\n def keep(i):\n return i % (batch_size * num_cores) < batch_size\n\n decodes = [d for i, d in enumerate(decodes) if keep(i)]\n else:\n raise ValueError(\"unexpected number of outputs\")\n output_file = tf.gfile.Open(output_filename, \"w\")\n decodes = decodes[:n]\n for d in decodes:\n output_file.write(d)\n output_file.write(\"\\n\")\n output_file.close()", "docstring": "Decode from a text file.\n\nArgs:\n estimator: a TPUEstimator\n vocabulary: a mtf.transformer.vocabulary.Vocabulary\n model_type: a string\n batch_size: an integer\n sequence_length: an integer (maximum decode length)\n checkpoint_path: an optional string\n input_filename: a string\n output_filename: a string\n eos_id: EOS id", "source": "juraj_google_style"} +{"code": "def write_header(term='bash', tree_dir=None, name=None):\n\n\n assert term in ['bash', 'tsch', 'modules'], 'term must be either bash, tsch, or module'\n\n product_dir = tree_dir.rstrip('/')\n base = 'export' if term == 'bash' else 'setenv'\n\n if term != 'modules':\n hdr = .format(name, term, base, product_dir)\n else:\n hdr = .format(product_dir, name)\n\n return hdr.strip()", "docstring": "Write proper file header in a given shell format\n\n Parameters:\n term (str):\n The type of shell header to write, can be \"bash\", \"tsch\", or \"modules\"\n tree_dir (str):\n The path to this repository\n name (str):\n The name of the configuration\n\nReturns:\n A string header to insert", "source": "juraj_google_style"} +{"code": "def from_event(cls, event):\n\n return cls(\n uuid=event['uuid'],\n job_type=event['job_type'],\n event_type=event['type'],\n queue=event['queue'],\n hostname=event['hostname'],\n pid=event['pid'],\n name=event['name'],\n workflow_id=event['workflow_id'],\n event_time=event['time'],\n duration=event['duration']\n )", "docstring": "Create a JobEvent object from the event dictionary returned by celery.\n\nArgs:\n event (dict): The dictionary as returned by celery.\n\nReturns:\n JobEvent: A fully initialized JobEvent object.", "source": "juraj_google_style"} +{"code": "def create_header(cls, request_id=None):\n\n header = {\n 'msgid' : bkserial.make_id(),\n 'msgtype' : cls.msgtype\n }\n if request_id is not None:\n header['reqid'] = request_id\n return header", "docstring": "Return a message header fragment dict.\n\nArgs:\n request_id (str or None) :\n Message ID of the message this message replies to\n\nReturns:\n dict : a message header", "source": "juraj_google_style"} +{"code": "def __init__(self, path, encoding=\"utf-8\", chunk_size=io.DEFAULT_BUFFER_SIZE):\n\n if encoding.lower() not in supported_encodings:\n error_message = \"{0} encoding was not supported/tested.\".format(encoding)\n error_message += \"Supported encodings are '{0}'\".format(\",\".join(supported_encodings))\n raise NotImplementedError(error_message)\n\n self.path = path\n self.encoding = encoding.lower()\n self.chunk_size = chunk_size\n self.iterator = FileReadBackwardsIterator(io.open(self.path, mode=\"rb\"), self.encoding, self.chunk_size)", "docstring": "Constructor for FileReadBackwards.\n\nArgs:\n path: Path to the file to be read\n encoding (str): Encoding\n chunk_size (int): How many bytes to read at a time", "source": "juraj_google_style"} +{"code": "def _respond(self, channel, text):\n\n result = self._format_message(channel, text)\n if result is not None:\n logger.info(\n 'Sending message: %r',\n truncate(result, max_len=50),\n )\n self.socket.send_str(result)", "docstring": "Respond to a message on the current socket.\n\nArgs:\n channel (:py:class:`str`): The channel to send to.\n text (:py:class:`str`): The message text to send.", "source": "juraj_google_style"} +{"code": "def print_middleware_tree(self, *, EOL=os.linesep, **kwargs): # noqa pragma: no cover\n\n\n def mask_to_method_name(mask):\n if mask == HTTPMethod.ALL:\n return 'ALL'\n methods = set(HTTPMethod) - {HTTPMethod.ALL}\n names = (method.name for method in methods if method.value & mask)\n return '+'.join(names)\n\n def path_to_str(path):\n if isinstance(path, str):\n return path\n return path.pattern.replace('\\\\', '')\n\n def decend_into_tree(chain, level):\n lines_ = []\n for mw in chain:\n info = (mask_to_method_name(mw.mask),\n path_to_str(mw.path),\n mw.func)\n prefix = \"│   \" * level\n lines_ += [prefix + \"├── %s %s %s\" % info]\n if mw.is_subchain:\n lines_ += decend_into_tree(mw.func, level + 1)\n if level:\n lines_[-1] = lines_[-1].replace('├', '└')\n return lines_\n\n lines = [self.name]\n lines += decend_into_tree(self.middleware, 0)\n lines.append('┴')\n print(EOL.join(lines), **kwargs)", "docstring": "Prints a unix-tree-like output of the structure of the web\n application to the file specified (stdout by default).\n\nArgs:\n EOL (str): The character or string that ends the line.\n **kwargs: Arguments pass to the standard print function.\n This allows specifying the file to write to and the\n ability to flush output upon creation.", "source": "juraj_google_style"} +{"code": "def files_comments_edit(\n self, *, comment: str, file: str, id: str, **kwargs\n ) -> SlackResponse:\n\n kwargs.update({\"comment\": comment, \"file\": file, \"id\": id})\n return self.api_call(\"files.comments.edit\", json=kwargs)", "docstring": "Edit an existing file comment.\n\nArgs:\n comment (str): The body of the comment.\n e.g. 'Everyone should take a moment to read this file.'\n file (str): The file id. e.g. 'F1234467890'\n id (str): The file comment id. e.g. 'Fc1234567890'", "source": "juraj_google_style"} +{"code": "def check_python_import(package_or_module):\n\n logger = logging.getLogger(__name__)\n logger.debug(\"Checking python import '%s'...\", package_or_module)\n loader = pkgutil.get_loader(package_or_module)\n found = loader is not None\n if found:\n logger.debug(\"Python %s '%s' found\",\n \"package\" if loader.is_package(package_or_module)\n else \"module\", package_or_module)\n else: # pragma: no cover\n logger.debug(\"Python import '%s' not found\", package_or_module)\n return found", "docstring": "Checks if a python package or module is importable.\n\nArgs:\n package_or_module -- the package or module name to check\n\nReturns:\n True or False", "source": "juraj_google_style"} +{"code": "def compact_interval_string(value_list):\n\n\n if not value_list:\n return ''\n\n value_list.sort()\n\n # Start by simply building up a list of separate contiguous intervals\n interval_list = []\n curr = []\n for val in value_list:\n if curr and (val > curr[-1] + 1):\n interval_list.append((curr[0], curr[-1]))\n curr = [val]\n else:\n curr.append(val)\n\n if curr:\n interval_list.append((curr[0], curr[-1]))\n\n # For each interval collapse it down to \"first, last\" or just \"first\" if\n # if first == last.\n return ','.join([\n '{}-{}'.format(pair[0], pair[1]) if pair[0] != pair[1] else str(pair[0])\n for pair in interval_list\n ])", "docstring": "Compact a list of integers into a comma-separated string of intervals.\n\nArgs:\n value_list: A list of sortable integers such as a list of numbers\n\nReturns:\n A compact string representation, such as \"1-5,8,12-15\"", "source": "juraj_google_style"} +{"code": "def load(self, train=True, test=True, shuffle=True) -> tuple:\n\n return self.__load(self.__load_files, train, test, shuffle=shuffle)", "docstring": "Load the vectorized representations of the stored data files\n\nArgs:\n train: Whether to load train data\n test: Whether to load test data", "source": "juraj_google_style"} +{"code": "def query_file(self, file_sha, verbose=False):\n\n\n # Sanity check sha hash input\n if len(file_sha) not in [64, 40]: # sha256 and sha1 lengths\n print('File sha looks malformed: {:s}'.format(file_sha))\n return {'file_sha': file_sha, 'malformed': True}\n\n # Call and return the internal query method\n return self._query('file', file_sha, verbose)", "docstring": "Query the VirusTotal Service\n\nArgs:\n file_sha (str): The file sha1 or sha256 hash\n url (str): The domain/url to be queried (default=None)", "source": "juraj_google_style"} +{"code": "def from_raw(self, raw: RawScalar) -> Optional[ScalarValue]:\n\n if isinstance(raw, str):\n return raw", "docstring": "Return a cooked value of the receiver type.\n\nArgs:\n raw: Raw value obtained from JSON parser.", "source": "juraj_google_style"} +{"code": "def compare_modules(file_, imports):\n\n modules = parse_requirements(file_)\n\n imports = [imports[i][\"name\"] for i in range(len(imports))]\n modules = [modules[i][\"name\"] for i in range(len(modules))]\n modules_not_imported = set(modules) - set(imports)\n\n return modules_not_imported", "docstring": "Compare modules in a file to imported modules in a project.\n\nArgs:\n file_ (str): File to parse for modules to be compared.\n imports (tuple): Modules being imported in the project.\n\nReturns:\n tuple: The modules not imported in the project, but do exist in the\n specified file.", "source": "juraj_google_style"} +{"code": "def base62_decode(string):\n\n\n alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n base = len(alphabet)\n strlen = len(string)\n num = 0\n\n idx = 0\n for char in string:\n power = (strlen - (idx + 1))\n num += alphabet.index(char) * (base ** power)\n idx += 1\n\n return int(num)", "docstring": "Decode a Base X encoded string into the number\n\nArgs:\n - `string`: The encoded string\n - `alphabet`: The alphabet to use for encoding\n Stolen from: http://stackoverflow.com/a/1119769/1144479", "source": "juraj_google_style"} +{"code": "def set_json(self, reason='', new_page=False):\n\n compressed_json = json.dumps(self._compress_json(self.cached_json))\n\n if len(compressed_json) > self.max_page_size:\n raise OverflowError(\n 'Usernotes page is too large (>{0} characters)'.\n format(self.max_page_size)\n )\n\n if new_page:\n self.subreddit.wiki.create(\n self.page_name,\n compressed_json,\n reason\n )\n # Set the page as hidden and available to moderators only\n self.subreddit.wiki[self.page_name].mod.update(False, permlevel=2)\n else:\n self.subreddit.wiki[self.page_name].edit(\n compressed_json,\n reason\n )", "docstring": "Send the JSON from the cache to the usernotes wiki page.\n\nArgs:\n reason: the change reason that will be posted to the wiki changelog\n (str)\n\nRaises:\n OverflowError if the new JSON data is greater than max_page_size", "source": "juraj_google_style"} +{"code": "def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float:\n\n\n if len(ref) == 0:\n raise EmptyReferenceException(\n \"Cannot calculating word error rate against a length 0 \"\\\n \"reference sequence.\")\n\n distance = min_edit_distance(ref, hyp)\n return 100 * float(distance) / len(ref)", "docstring": "Calculate the word error rate of a sequence against a reference.\n\nArgs:\n ref: The gold-standard reference sequence\n hyp: The hypothesis to be evaluated against the reference.\n\nReturns:\n The word error rate of the supplied hypothesis with respect to the\n reference string.\n\nRaises:\n persephone.exceptions.EmptyReferenceException: If the length of the reference sequence is 0.", "source": "juraj_google_style"} +{"code": "def jobUpdateResults(self, jobID, results):\n\n with ConnectionFactory.get() as conn:\n query = 'UPDATE %s SET _eng_last_update_time=UTC_TIMESTAMP(), ' \\\n ' results=%%s ' \\\n ' WHERE job_id=%%s' % (self.jobsTableName,)\n conn.cursor.execute(query, [results, jobID])", "docstring": "Update the results string and last-update-time fields of a model.\n\n Parameters:\n ----------------------------------------------------------------\n jobID: job ID of model to modify\n results: new results (json dict string)", "source": "juraj_google_style"} +{"code": "def filter_parts(cls, part_info):\n # type: (Type[T], PartInfo) -> Dict[str, List[T]]\n\n filtered = OrderedDict()\n for part_name, info_list in part_info.items():\n if info_list is None or isinstance(info_list, Exception):\n continue\n info_list = [i for i in info_list if isinstance(i, cls)]\n if info_list:\n filtered[part_name] = info_list\n return filtered", "docstring": "Filter the part_info dict looking for instances of our class\n\nArgs:\n part_info (dict): {part_name: [Info] or None} as returned from\n Controller.run_hook()\n\nReturns:\n dict: {part_name: [info]} where info is a subclass of cls", "source": "juraj_google_style"} +{"code": "def get_replicas(self, service_id: str) -> str:\n\n # Initialising empty list\n replicas = []\n\n # Raise an exception if we are not a manager\n if not self._manager:\n raise RuntimeError('Only the Swarm manager node can retrieve '\n 'replication level of the service')\n\n service_tasks = self._client.services.get(service_id).tasks()\n for task in service_tasks:\n if task['Status']['State'] == \"running\":\n replicas.append(task)\n return len(replicas)", "docstring": "Get the replication level of a service.\n\nArgs:\n service_id (str): docker swarm service id\n\nReturns:\n str, replication level of the service", "source": "juraj_google_style"} +{"code": "def reopen_encoded(fileobj, mode='r', fallback_encoding=None):\n\n encoding = determine_encoding(fileobj.name, fallback_encoding)\n fileobj.close()\n return open(fileobj.name, mode, encoding=encoding)", "docstring": "Makes sure that a file was opened with some valid encoding.\n\nArgs:\n fileobj (file): The file-object.\n mode (str, optional): The mode in which to re-open the file.\n fallback_encoding (str, optional): The encoding in which to re-open\n the file if it does not specify an encoding itself.\n\nReturns:\n file: The re-opened file.", "source": "juraj_google_style"} +{"code": "def parse(self, rrstr):\n # type: (bytes) -> int\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('PX record already initialized!')\n\n (su_len, su_entry_version_unused, posix_file_mode_le, posix_file_mode_be,\n posix_file_links_le, posix_file_links_be, posix_file_user_id_le,\n posix_file_user_id_be, posix_file_group_id_le,\n posix_file_group_id_be) = struct.unpack_from('=BBLLLLLLLL', rrstr[:38], 2)\n\n # We assume that the caller has already checked the su_entry_version,\n # so we don't bother.\n\n if posix_file_mode_le != utils.swab_32bit(posix_file_mode_be):\n raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file mode do not agree')\n\n if posix_file_links_le != utils.swab_32bit(posix_file_links_be):\n raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file links do not agree')\n\n if posix_file_user_id_le != utils.swab_32bit(posix_file_user_id_be):\n raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file user ID do not agree')\n\n if posix_file_group_id_le != utils.swab_32bit(posix_file_group_id_be):\n raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file group ID do not agree')\n\n # In Rock Ridge 1.09 and 1.10, there is no serial number so the su_len\n # is 36, while in Rock Ridge 1.12, there is an 8-byte serial number so\n # su_len is 44.\n if su_len == 36:\n posix_file_serial_number_le = 0\n elif su_len == 44:\n (posix_file_serial_number_le,\n posix_file_serial_number_be) = struct.unpack_from('=LL',\n rrstr[:44], 36)\n if posix_file_serial_number_le != utils.swab_32bit(posix_file_serial_number_be):\n raise pycdlibexception.PyCdlibInvalidISO('PX record big and little-endian file serial number do not agree')\n else:\n raise pycdlibexception.PyCdlibInvalidISO('Invalid length on Rock Ridge PX record')\n\n self.posix_file_mode = posix_file_mode_le\n self.posix_file_links = posix_file_links_le\n self.posix_user_id = posix_file_user_id_le\n self.posix_group_id = posix_file_group_id_le\n self.posix_serial_number = posix_file_serial_number_le\n\n self._initialized = True\n\n return su_len", "docstring": "Parse a Rock Ridge POSIX File Attributes record out of a string.\n\n Parameters:\n rrstr - The string to parse the record out of.\n\nReturns:\n A string representing the RR version, either 1.09 or 1.12.", "source": "juraj_google_style"} +{"code": "def get_all_aminames(i_info):\n\n for i in i_info:\n try:\n # pylint: disable=maybe-no-member\n i_info[i]['aminame'] = EC2R.Image(i_info[i]['ami']).name\n except AttributeError:\n i_info[i]['aminame'] = \"Unknown\"\n return i_info", "docstring": "Get Image_Name for each instance in i_info.\n\nArgs:\n i_info (dict): information on instances and details.\n\nReturns:\n i_info (dict): i_info is returned with the aminame\n added for each instance.", "source": "juraj_google_style"} +{"code": "def move_spines(ax, sides, dists):\n\n for side, dist in zip(sides, dists):\n ax.spines[side].set_position((\"axes\", dist))\n return ax", "docstring": "Move the entire spine relative to the figure.\n\n Parameters:\n ax: axes to operate on\n sides: list of sides to move. Sides: top, left, bottom, right\n dists: list of float distances to move. Should match sides in length.\n\nExample:\n move_spines(ax, sides=['left', 'bottom'], dists=[-0.02, 0.1])", "source": "juraj_google_style"} +{"code": "def __call__(self, *x_batch, **kwargs) -> Union[List, np.ndarray]:\n\n with self.graph.as_default():\n K.set_session(self.sess)\n return self._net.predict_on_batch(x_batch, **kwargs)", "docstring": "Predicts answers on batch elements.\n\nArgs:\n instance: a batch to predict answers on", "source": "juraj_google_style"} +{"code": "def MakeSimpleProtoClass(fields, full_name=None, pool=None):\n\n factory = message_factory.MessageFactory(pool=pool)\n\n if full_name is not None:\n try:\n proto_cls = _GetMessageFromFactory(factory, full_name)\n return proto_cls\n except KeyError:\n # The factory's DescriptorPool doesn't know about this class yet.\n pass\n\n # Get a list of (name, field_type) tuples from the fields dict. If fields was\n # an OrderedDict we keep the order, but otherwise we sort the field to ensure\n # consistent ordering.\n field_items = fields.items()\n if not isinstance(fields, OrderedDict):\n field_items = sorted(field_items)\n\n # Use a consistent file name that is unlikely to conflict with any imported\n # proto files.\n fields_hash = hashlib.sha1()\n for f_name, f_type in field_items:\n fields_hash.update(f_name.encode('utf-8'))\n fields_hash.update(str(f_type).encode('utf-8'))\n proto_file_name = fields_hash.hexdigest() + '.proto'\n\n # If the proto is anonymous, use the same hash to name it.\n if full_name is None:\n full_name = ('net.proto2.python.public.proto_builder.AnonymousProto_' +\n fields_hash.hexdigest())\n try:\n proto_cls = _GetMessageFromFactory(factory, full_name)\n return proto_cls\n except KeyError:\n # The factory's DescriptorPool doesn't know about this class yet.\n pass\n\n # This is the first time we see this proto: add a new descriptor to the pool.\n factory.pool.Add(\n _MakeFileDescriptorProto(proto_file_name, full_name, field_items))\n return _GetMessageFromFactory(factory, full_name)", "docstring": "Create a Protobuf class whose fields are basic types.\n\n Note: this doesn't validate field names!\n\nArgs:\n fields: dict of {name: field_type} mappings for each field in the proto. If\n this is an OrderedDict the order will be maintained, otherwise the\n fields will be sorted by name.\n full_name: optional str, the fully-qualified name of the proto type.\n pool: optional DescriptorPool instance.\n\nReturns:\n a class, the new protobuf class with a FileDescriptor.", "source": "juraj_google_style"} +{"code": "def RemoveTask(self, task):\n\n with self._lock:\n if task.identifier not in self._tasks_abandoned:\n raise KeyError('Task {0:s} was not abandoned.'.format(task.identifier))\n\n if not task.has_retry:\n raise KeyError(\n 'Will not remove a task {0:s} without retry task.'.format(\n task.identifier))\n\n del self._tasks_abandoned[task.identifier]\n\n logger.debug('Removed task {0:s}.'.format(task.identifier))", "docstring": "Removes an abandoned task.\n\nArgs:\n task (Task): task.\n\nRaises:\n KeyError: if the task was not abandoned or the task was abandoned and\n was not retried.", "source": "juraj_google_style"} +{"code": "def tinsel(to_patch, module_name, decorator=mock_decorator):\n\n def fn_decorator(function):\n def wrapper(*args, **kwargs):\n with patch(to_patch, decorator):\n m = importlib.import_module(module_name)\n reload(m)\n function(*args, **kwargs)\n\n reload(m)\n return wrapper\n return fn_decorator", "docstring": "Decorator for simple in-place decorator mocking for tests\n\nArgs:\n to_patch: the string path of the function to patch\n module_name: complete string path of the module to reload\n decorator (optional): replacement decorator. By default a pass-through\n will be used.\n\nReturns:\n A wrapped test function, during the context of execution the specified\n path is patched.", "source": "juraj_google_style"} +{"code": "def _redis_watcher(state):\n\n conf = state.app.config\n\n r = redis.client.StrictRedis(\n host=conf.get('WAFFLE_REDIS_HOST', 'localhost'),\n port=conf.get('WAFFLE_REDIS_PORT', 6379))\n\n sub = r.pubsub(ignore_subscribe_messages=True)\n sub.subscribe(conf.get('WAFFLE_REDIS_CHANNEL', 'waffleconf'))\n\n while True:\n for msg in sub.listen():\n # Skip non-messages\n if not msg['type'] == 'message':\n continue\n\n tstamp = float(msg['data'])\n\n # Compare timestamps and update config if needed\n if tstamp > state._tstamp:\n state.update_conf()\n state._tstamp = tstamp", "docstring": "Listen to redis channel for a configuration update notifications.\n\nArgs:\n state (_WaffleState): Object that contains reference to app and its\n configstore.", "source": "juraj_google_style"} +{"code": "def remove_attribute(self, attribute: str) -> None:\n\n attr_index = self.__attr_index(attribute)\n if attr_index is not None:\n self.yaml_node.value.pop(attr_index)", "docstring": "Remove an attribute from the node.\n\n Use only if is_mapping() returns True.\n\nArgs:\n attribute: The name of the attribute to remove.", "source": "juraj_google_style"} +{"code": "def __init__(self, server, port, project_key=None,\n run_asyncore_thread=True):\n\n self.server = server\n self.port = port\n\n super(ZEOWrapper, self).__init__(\n project_key=project_key,\n run_asyncore_thread=run_asyncore_thread,\n )", "docstring": "Initialize the object.\n\nArgs:\n conf_path (str): See :attr:`conf_path`.\n project_key (str, default None): See :attr:`project_key`. If not\n set, the root of the database is used (this may cause\n performace issues).\n run_asyncore_thread (bool, default True): Run external asyncore\n thread, which handles connections to database? Default True.", "source": "juraj_google_style"} +{"code": "def get_variant(variant_handle, context=None):\n\n if isinstance(variant_handle, dict):\n variant_handle = ResourceHandle.from_dict(variant_handle)\n\n variant_resource = package_repository_manager.get_resource_from_handle(variant_handle)\n variant = Variant(variant_resource, context=context)\n return variant", "docstring": "Create a variant given its handle (or serialized dict equivalent)\n\nArgs:\n variant_handle (`ResourceHandle` or dict): Resource handle, or\n equivalent serialized dict representation from\n ResourceHandle.to_dict\n context (`ResolvedContext`): The context this variant is associated\n with, if any.\n\nReturns:\n `Variant`.", "source": "juraj_google_style"} +{"code": "def directional_poisson_ratio(self, n, m, tol=1e-8):\n\n n, m = get_uvec(n), get_uvec(m)\n if not np.abs(np.dot(n, m)) < tol:\n raise ValueError(\"n and m must be orthogonal\")\n v = self.compliance_tensor.einsum_sequence([n]*2 + [m]*2)\n v *= -1 / self.compliance_tensor.einsum_sequence([n]*4)\n return v", "docstring": "Calculates the poisson ratio for a specific direction\n relative to a second, orthogonal direction\n\nArgs:\n n (3-d vector): principal direction\n m (3-d vector): secondary direction orthogonal to n\n tol (float): tolerance for testing of orthogonality", "source": "juraj_google_style"} +{"code": "def write_failure_file(failure_msg): # type: (str) -> None\n\n file_path = os.path.join(_env.output_dir, 'failure')\n write_file(file_path, failure_msg)", "docstring": "Create a file 'failure' if training fails after all algorithm output (for example, logging) completes,\n the failure description should be written to this file. In a DescribeTrainingJob response, Amazon SageMaker\n returns the first 1024 characters from this file as FailureReason.\n See: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html\n\nArgs:\n failure_msg: The description of failure", "source": "juraj_google_style"} +{"code": "def get_learning_rate(self, iter):\n\n lr = self.scheduler.get_learning_rate(iter)\n if iter < self.warmup_iter:\n lr *= (iter + 1) * 1.0 / self.warmup_iter\n return lr", "docstring": "Get learning rate with exponential decay based on current iteration.\n\nArgs:\n iter (int): Current iteration (starting with 0).\n\nReturns:\n float: Learning rate", "source": "juraj_google_style"} +{"code": "def _AddHeader(self, fp):\n\n text = textwrap.wrap(\n textwrap.dedent(self.config_header), break_on_hyphens=False)\n fp.write('\\n'.join(['# ' + line for line in text]))\n fp.write('\\n\\n')", "docstring": "Create a file header in the config.\n\nArgs:\n fp: int, a file pointer for writing the header.", "source": "juraj_google_style"} +{"code": "def run(self, input_dir, output_file_path):\n\n logging.info('Running defense %s', self.submission_id)\n tmp_run_dir = self.temp_copy_extracted_submission()\n output_dir = os.path.dirname(output_file_path)\n output_filename = os.path.basename(output_file_path)\n cmd = ['--network=none',\n '-m=24g',\n '--cpus=3.75',\n '-v', '{0}:/input_images:ro'.format(input_dir),\n '-v', '{0}:/output_data'.format(output_dir),\n '-v', '{0}:/code'.format(tmp_run_dir),\n '-w', '/code',\n self.container_name,\n './' + self.entry_point,\n '/input_images',\n '/output_data/' + output_filename]\n elapsed_time_sec = self.run_with_time_limit(cmd)\n sudo_remove_dirtree(tmp_run_dir)\n return elapsed_time_sec", "docstring": "Runs defense inside Docker.\n\nArgs:\n input_dir: directory with input (adversarial images).\n output_file_path: path of the output file.\n\nReturns:\n how long it took to run submission in seconds", "source": "juraj_google_style"} +{"code": "def get_cached_or_new(url, new=False):\n\n garbage_collection()\n\n old_req = DATABASE.get(url)\n\n if old_req and not new:\n return old_req\n\n if not (url.startswith(\"http://\") or url.startswith(\"https://\")):\n raise ValueError(\"Invalid URL `%s`!\" % url)\n\n req = RequestInfo(url=url)\n DATABASE[url] = req\n\n return req", "docstring": "Look into the database and return :class:`RequestInfo` if the `url` was\n already analyzed, or create and return new instance, if not.\n\n If the `new` is set to True, always create new instance.\n\nArgs:\n url (str): URL of the analyzed resource.\n new (bool, default False): Force new instance?\n\nReturns:\n obj: :class:`RequestInfo` instance.", "source": "juraj_google_style"} +{"code": "def Copy(From, To):\n\n from benchbuild.utils.cmd import cp\n cp(\"-ar\", \"--reflink=auto\", From, To)", "docstring": "Small copy wrapper.\n\nArgs:\n From (str): Path to the SOURCE.\n To (str): Path to the TARGET.", "source": "juraj_google_style"} +{"code": "def port(self, check=False):\n\n if not self.__ports: # refresh ports if sequence is empty\n self.refresh()\n\n try:\n port = self.__ports.pop()\n if check:\n while not self.__check_port(port):\n self.release_port(port)\n port = self.__ports.pop()\n except (IndexError, KeyError):\n raise IndexError(\"Could not find a free port,\\nclosed ports: {closed}\".format(closed=self.__closed))\n self.__closed.add(port)\n return port", "docstring": "return next opened port\n\nArgs:\n check - check is port realy free", "source": "juraj_google_style"} +{"code": "def read(self, file_des, num_bytes):\n\n file_handle = self.filesystem.get_open_file(file_des)\n file_handle.raw_io = True\n return file_handle.read(num_bytes)", "docstring": "Read number of bytes from a file descriptor, returns bytes read.\n\nArgs:\n file_des: An integer file descriptor for the file object requested.\n num_bytes: Number of bytes to read from file.\n\nReturns:\n Bytes read from file.\n\nRaises:\n OSError: bad file descriptor.\n TypeError: if file descriptor is not an integer.", "source": "juraj_google_style"} +{"code": "def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''):\n\n\n log.info('Get latest data for sensors. Stop with Ctrl+C.')\n log.info('Stops automatically in %ss', search_duratio_sec)\n log.info('MACs: %s', macs)\n\n datas = dict()\n\n for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device):\n datas[new_data[0]] = new_data[1]\n\n return datas", "docstring": "Get lates data for sensors in the MAC's list.\n\nArgs:\n macs (array): MAC addresses\n search_duratio_sec (int): Search duration in seconds. Default 5\n bt_device (string): Bluetooth device id\n\nReturns:\n dict: MAC and state of found sensors", "source": "juraj_google_style"} +{"code": "def add_menu_item(self, command, title):\n\n m_item = Gtk.MenuItem()\n m_item.set_label(title)\n m_item.connect('activate', command)\n self.menu.append(m_item)\n self.menu.show_all()", "docstring": "Add mouse right click menu item.\n\nArgs:\n command (callable): function that will be called after left mouse click on title\n title (str): label that will be shown in menu", "source": "juraj_google_style"} +{"code": "def iter_train_batches(self, max_yield=999):\n\n\n for ev, sample_batch in self._augment_with_replay(\n self.sample_tasks.completed_prefetch(\n blocking_wait=True, max_yield=max_yield)):\n sample_batch.decompress_if_needed()\n self.batch_buffer.append(sample_batch)\n if sum(b.count\n for b in self.batch_buffer) >= self.train_batch_size:\n train_batch = self.batch_buffer[0].concat_samples(\n self.batch_buffer)\n yield train_batch\n self.batch_buffer = []\n\n # If the batch was replayed, skip the update below.\n if ev is None:\n continue\n\n # Put in replay buffer if enabled\n if self.replay_buffer_num_slots > 0:\n if len(self.replay_batches) < self.replay_buffer_num_slots:\n self.replay_batches.append(sample_batch)\n else:\n self.replay_batches[self.replay_index] = sample_batch\n self.replay_index += 1\n self.replay_index %= self.replay_buffer_num_slots\n\n ev.set_weights.remote(self.broadcasted_weights)\n self.num_weight_syncs += 1\n self.num_sent_since_broadcast += 1\n\n # Kick off another sample request\n self.sample_tasks.add(ev, ev.sample.remote())", "docstring": "Iterate over train batches.\n\nArgs:\n max_yield (int): Max number of batches to iterate over in this\n cycle. Setting this avoids iter_train_batches returning too\n much data at once.", "source": "juraj_google_style"} +{"code": "def plot(self, freq=None, figsize=(15, 5), title=None,\n logy=False, **kwargs):\n\n\n if title is None:\n title = self._get_default_plot_title(\n freq, 'Equity Progression')\n\n ser = self._get_series(freq).rebase()\n return ser.plot(figsize=figsize, logy=logy,\n title=title, **kwargs)", "docstring": "Helper function for plotting the series.\n\nArgs:\n * freq (str): Data frequency used for display purposes.\n Refer to pandas docs for valid freq strings.\n * figsize ((x,y)): figure size\n * title (str): Title if default not appropriate\n * logy (bool): log-scale for y axis\n * kwargs: passed to pandas' plot method", "source": "juraj_google_style"} +{"code": "def in_array_list(array_list, a, tol=1e-5):\n\n if len(array_list) == 0:\n return False\n axes = tuple(range(1, a.ndim + 1))\n if not tol:\n return np.any(np.all(np.equal(array_list, a[None, :]), axes))\n else:\n return np.any(np.sum(np.abs(array_list - a[None, :]), axes) < tol)", "docstring": "Extremely efficient nd-array comparison using numpy's broadcasting. This\n function checks if a particular array a, is present in a list of arrays.\n It works for arrays of any size, e.g., even matrix searches.\n\nArgs:\n array_list ([array]): A list of arrays to compare to.\n a (array): The test array for comparison.\n tol (float): The tolerance. Defaults to 1e-5. If 0, an exact match is\n done.\n\nReturns:\n (bool)", "source": "juraj_google_style"} +{"code": "def on_hello(self, message):\n\n\n logger.info(\"Got a hello\")\n self.identify(self.token)\n self.heartbeat_thread = Heartbeat(self.ws,\n message['d']['heartbeat_interval'])\n self.heartbeat_thread.start()\n return", "docstring": "Runs on a hello event from websocket connection\n\nArgs:\n message (dict): Full message from Discord websocket connection\"", "source": "juraj_google_style"} +{"code": "def DeregisterHelper(cls, analyzer_helper):\n\n if analyzer_helper.type_indicator not in cls._analyzer_helpers:\n raise KeyError(\n 'Analyzer helper object not set for type indicator: {0:s}.'.format(\n analyzer_helper.type_indicator))\n\n analyzer_helper = cls._analyzer_helpers[analyzer_helper.type_indicator]\n\n cls._FlushCache(analyzer_helper.format_categories)\n\n del cls._analyzer_helpers[analyzer_helper.type_indicator]", "docstring": "Deregisters a format analyzer helper.\n\nArgs:\n analyzer_helper (AnalyzerHelper): analyzer helper.\n\nRaises:\n KeyError: if analyzer helper object is not set for the corresponding\n type indicator.", "source": "juraj_google_style"} +{"code": "def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None:\n\n if hasattr(Circuit, name):\n if allow_overwrite:\n warnings.warn(f\"Circuit has attribute `{name}`.\")\n else:\n raise ValueError(f\"Circuit has attribute `{name}`.\")\n if name.startswith(\"run_with_\"):\n if allow_overwrite:\n warnings.warn(f\"Gate name `{name}` may conflict with run of backend.\")\n else:\n raise ValueError(f\"Gate name `{name}` shall not start with 'run_with_'.\")\n if not allow_overwrite:\n if name in GATE_SET:\n raise ValueError(f\"Gate '{name}' is already exists in gate set.\")\n if name in GLOBAL_MACROS:\n raise ValueError(f\"Macro '{name}' is already exists.\")\n GLOBAL_MACROS[name] = func", "docstring": "Register new macro to Circuit.\n\nArgs:\n name (str): The name of macro.\n func (callable): The function to be called.\n allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.\n Otherwise, raise the ValueError.\n\nRaises:\n ValueError: The name is duplicated with existing macro, gate or method.\n When `allow_overwrite=True`, this error is not raised.", "source": "juraj_google_style"} +{"code": "def _AddSerializedEvent(self, event):\n\n identifier = identifiers.SQLTableIdentifier(\n self._CONTAINER_TYPE_EVENT,\n self._serialized_event_heap.number_of_events + 1)\n event.SetIdentifier(identifier)\n\n serialized_data = self._SerializeAttributeContainer(event)\n\n self._serialized_event_heap.PushEvent(event.timestamp, serialized_data)\n\n if self._serialized_event_heap.data_size > self._maximum_buffer_size:\n self._WriteSerializedAttributeContainerList(self._CONTAINER_TYPE_EVENT)", "docstring": "Adds an serialized event.\n\nArgs:\n event (EventObject): event.\n\nRaises:\n IOError: if the event cannot be serialized.\n OSError: if the event cannot be serialized.", "source": "juraj_google_style"} +{"code": "def write_tabular(obj, filepath):\n\n _, fn, ext = splitext2(filepath)\n if ext == '.h5':\n _write_tabular_h5(obj, filepath)\n elif ext == '.pkl':\n _write_tabular_pickle(obj, filepath)\n else:\n raise NotImplementedError", "docstring": "Write tabular object in HDF5 or pickle format\n\nArgs:\n obj (array or DataFrame): tabular object to write\n filepath (path-like): path to write to; must end in '.h5' or '.pkl'", "source": "juraj_google_style"} +{"code": "def Database_executeSQL(self, databaseId, query):\n\n\t\tassert isinstance(query, (str,)\n\t\t ), \"Argument 'query' must be of type '['str']'. Received type: '%s'\" % type(\n\t\t query)\n\t\tsubdom_funcs = self.synchronous_command('Database.executeSQL', databaseId\n\t\t =databaseId, query=query)\n\t\treturn subdom_funcs", "docstring": "Function path: Database.executeSQL\n Domain: Database\n Method name: executeSQL\n\n Parameters:\n Required arguments:\n 'databaseId' (type: DatabaseId) -> No description\n 'query' (type: string) -> No description\n\nReturns:\n 'columnNames' (type: array) -> No description\n 'values' (type: array) -> No description\n 'sqlError' (type: Error) -> No description", "source": "juraj_google_style"} +{"code": "def add_argument(self, arg_name, arg_value):\n\n\n if len(self._employers) > 0:\n self._logger.log(\n 'warn',\n 'Adding an argument after the employers have been created'\n )\n if self._args is None:\n self._args = {}\n self._args[arg_name] = arg_value", "docstring": "Add an additional argument to be passed to the fitness function\n via additional arguments dictionary; this argument/value is not tuned\n\nArgs:\n arg_name (string): name/dictionary key of argument\n arg_value (any): dictionary value of argument", "source": "juraj_google_style"} +{"code": "def encode_fetch_request(cls, client_id, correlation_id, payloads=None,\n max_wait_time=100, min_bytes=4096):\n\n\n payloads = [] if payloads is None else payloads\n grouped_payloads = group_by_topic_and_partition(payloads)\n\n message = []\n message.append(cls._encode_message_header(client_id, correlation_id,\n KafkaProtocol.FETCH_KEY))\n\n # -1 is the replica id\n message.append(struct.pack('>iiii', -1, max_wait_time, min_bytes,\n len(grouped_payloads)))\n\n for topic, topic_payloads in grouped_payloads.items():\n message.append(write_short_string(topic))\n message.append(struct.pack('>i', len(topic_payloads)))\n for partition, payload in topic_payloads.items():\n message.append(struct.pack('>iqi', partition, payload.offset,\n payload.max_bytes))\n\n msg = b''.join(message)\n return struct.pack('>i%ds' % len(msg), len(msg), msg)", "docstring": "Encodes some FetchRequest structs\n\nArgs:\n client_id: string\n correlation_id: int\n payloads: list of FetchRequest\n max_wait_time: int, how long to block waiting on min_bytes of data\n min_bytes: int, the minimum number of bytes to accumulate before\n returning the response", "source": "juraj_google_style"} +{"code": "def __init__(self, session, object_factory):\n\n check_type(session, RestSession)\n\n super(PeopleAPI, self).__init__()\n\n self._session = session\n self._object_factory = object_factory", "docstring": "Initialize a new PeopleAPI object with the provided RestSession.\n\nArgs:\n session(RestSession): The RESTful session object to be used for\n API calls to the Webex Teams service.\n\nRaises:\n TypeError: If the parameter types are incorrect.", "source": "juraj_google_style"} +{"code": "def rename_next_state_fluent(name: str) -> str:\n\n i = name.index('/')\n functor = name[:i-1]\n arity = name[i+1:]\n return \"{}/{}\".format(functor, arity)", "docstring": "Returns next state fluent canonical name.\n\nArgs:\n name (str): The current state fluent name.\n\nReturns:\n str: The next state fluent name.", "source": "juraj_google_style"} +{"code": "def plot_spectrum_min_max(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, c=None, **kwargs):\n\n ax = plt.gca()\n\n plot_f, plot_data = self.grab_data(f_start, f_stop, if_id)\n\n #Using accending frequency for all plots.\n if self.header[b'foff'] < 0:\n plot_data = plot_data[..., ::-1] # Reverse data\n plot_f = plot_f[::-1]\n\n fig_max = plot_data[0].max()\n fig_min = plot_data[0].min()\n\n print(\"averaging along time axis...\")\n\n #Since the data has been squeezed, the axis for time goes away if only one bin, causing a bug with axis=1\n if len(plot_data.shape) > 1:\n plot_max = plot_data.max(axis=0)\n plot_min = plot_data.min(axis=0)\n plot_data = plot_data.mean(axis=0)\n else:\n plot_max = plot_data.max()\n plot_min = plot_data.min()\n plot_data = plot_data.mean()\n\n # Rebin to max number of points\n dec_fac_x = 1\n MAX_PLT_POINTS = 8*64 # Low resoluition to see the difference.\n if plot_data.shape[0] > MAX_PLT_POINTS:\n dec_fac_x = int(plot_data.shape[0] / MAX_PLT_POINTS)\n\n plot_data = rebin(plot_data, dec_fac_x, 1)\n plot_min = rebin(plot_min, dec_fac_x, 1)\n plot_max = rebin(plot_max, dec_fac_x, 1)\n plot_f = rebin(plot_f, dec_fac_x, 1)\n\n if logged:\n plt.plot(plot_f, db(plot_data), \"#333333\", label='mean', **kwargs)\n plt.plot(plot_f, db(plot_max), \"#e74c3c\", label='max', **kwargs)\n plt.plot(plot_f, db(plot_min), '#3b5b92', label='min', **kwargs)\n plt.ylabel(\"Power [dB]\")\n else:\n plt.plot(plot_f, plot_data, \"#333333\", label='mean', **kwargs)\n plt.plot(plot_f, plot_max, \"#e74c3c\", label='max', **kwargs)\n plt.plot(plot_f, plot_min, '#3b5b92', label='min', **kwargs)\n plt.ylabel(\"Power [counts]\")\n plt.xlabel(\"Frequency [MHz]\")\n plt.legend()\n\n try:\n plt.title(self.header[b'source_name'])\n except KeyError:\n plt.title(self.filename)\n\n plt.xlim(plot_f[0], plot_f[-1])\n if logged:\n plt.ylim(db(fig_min),db(fig_max))", "docstring": "Plot frequency spectrum of a given file\n\nArgs:\n logged (bool): Plot in linear (False) or dB units (True)\n if_id (int): IF identification (if multiple IF signals in file)\n c: color for line\n kwargs: keyword args to be passed to matplotlib plot()", "source": "juraj_google_style"} +{"code": "def __div__(self, other):\n\n if isinstance(other, LazyOpResult):\n other = other.expr\n return NumpyArrayWeld(\n numpy_weld_impl.div(\n self.expr,\n other,\n self.weld_type\n ),\n self.weld_type\n )", "docstring": "Summary\n\nArgs:\n other (TYPE): Description\n\nReturns:\n TYPE: Description", "source": "juraj_google_style"} +{"code": "def to_representation(self, instance):\n\n\n if not isinstance(instance, dict):\n data = super(\n DynamicEphemeralSerializer,\n self\n ).to_representation(instance)\n else:\n data = instance\n instance = EphemeralObject(data)\n\n if self.id_only():\n return data\n else:\n return tag_dict(data, serializer=self, instance=instance)", "docstring": "Provides post processing. Sub-classes should implement their own\n to_representation method, but pass the resulting dict through\n this function to get tagging and field selection.\n\nArgs:\n instance: Serialized dict, or object. If object,\n it will be serialized by the super class's\n to_representation() method.", "source": "juraj_google_style"} +{"code": "def delete_vmss(access_token, subscription_id, resource_group, vmss_name):\n\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourceGroups/', resource_group,\n '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name,\n '?api-version=', COMP_API])\n return do_delete(endpoint, access_token)", "docstring": "Delete a virtual machine scale set.\n\nArgs:\n access_token (str): A valid Azure authentication token.\n subscription_id (str): Azure subscription id.\n resource_group (str): Azure resource group name.\n vmss_name (str): Name of the virtual machine scale set.\n\nReturns:\n HTTP response.", "source": "juraj_google_style"} +{"code": "def EscapeWildcards(string):\n\n precondition.AssertType(string, Text)\n return string.replace(\"%\", r\"\\%\").replace(\"_\", r\"\\_\")", "docstring": "Escapes wildcard characters for strings intended to be used with `LIKE`.\n\n Databases don't automatically escape wildcard characters ('%', '_'), so any\n non-literal string that is passed to `LIKE` and is expected to match literally\n has to be manually escaped.\n\nArgs:\n string: A string to escape.\n\nReturns:\n An escaped string.", "source": "juraj_google_style"} +{"code": "def SetDefault(self, name, value):\n\n fl = self.FlagDict()\n if name not in fl:\n self._SetUnknownFlag(name, value)\n return\n if self.IsParsed():\n logging.warn(\n 'FLAGS.SetDefault called on flag \"%s\" after flag parsing. Call this '\n 'method at the top level of a module to avoid overwriting the value '\n 'passed at the command line.',\n name)\n fl[name]._set_default(value) # pylint: disable=protected-access\n self._AssertValidators(fl[name].validators)", "docstring": "Changes the default value (and current value) of the named flag object.\n\n Call this method at the top level of a module to avoid overwriting the value\n passed at the command line.\n\nArgs:\n name: A string, the name of the flag to modify.\n value: The new default value.\n\nRaises:\n UnrecognizedFlagError: When there is no registered flag named name.\n IllegalFlagValueError: When value is not valid.", "source": "juraj_google_style"} +{"code": "def __init__(self, channel):\n\n self.CreateCompany = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.CompanyService/CreateCompany\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.CreateCompanyRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__pb2.Company.FromString,\n )\n self.GetCompany = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.CompanyService/GetCompany\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.GetCompanyRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__pb2.Company.FromString,\n )\n self.UpdateCompany = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.CompanyService/UpdateCompany\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.UpdateCompanyRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__pb2.Company.FromString,\n )\n self.DeleteCompany = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.CompanyService/DeleteCompany\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.DeleteCompanyRequest.SerializeToString,\n response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,\n )\n self.ListCompanies = channel.unary_unary(\n \"/google.cloud.talent.v4beta1.CompanyService/ListCompanies\",\n request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.ListCompaniesRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_company__service__pb2.ListCompaniesResponse.FromString,\n )", "docstring": "Constructor.\n\nArgs:\n channel: A grpc.Channel.", "source": "juraj_google_style"} +{"code": "def __init__(self, isbn):\n\n super(Isbn, self).__init__()\n self._isbn = isbn\n if len(isbn) in (9, 12):\n self.isbn = _isbn_cleanse(isbn, False)\n else:\n self.isbn = _isbn_cleanse(isbn)", "docstring": "Initialise a new ``Isbn`` object.\n\nArgs:\n isbn (str): ISBN string", "source": "juraj_google_style"} +{"code": "def get_reference(root):\n\n reference = {}\n elem = root.find('bibliographyLink')\n if elem is None:\n raise MissingElementError('bibliographyLink')\n\n # Try to get reference info via DOI, fall back on preferredKey if necessary.\n ref_doi = elem.get('doi', None)\n ref_key = elem.get('preferredKey', None)\n\n if ref_doi is not None:\n try:\n ref = crossref_api.works(ids=ref_doi)['message']\n except (HTTPError, habanero.RequestError, ConnectionError):\n if ref_key is None:\n raise KeywordError('DOI not found and preferredKey attribute not set')\n else:\n warn('Missing doi attribute in bibliographyLink or lookup failed. '\n 'Setting \"detail\" key as a fallback; please update to the appropriate fields.'\n )\n reference['detail'] = ref_key\n if reference['detail'][-1] != '.':\n reference['detail'] += '.'\n else:\n if ref_key is not None:\n warn('Using DOI to obtain reference information, rather than preferredKey.')\n reference['doi'] = elem.attrib['doi']\n # Now get elements of the reference data\n # Assume that the reference returned by the DOI lookup always has a container-title\n reference['journal'] = ref.get('container-title')[0]\n ref_year = ref.get('published-print') or ref.get('published-online')\n reference['year'] = int(ref_year['date-parts'][0][0])\n reference['volume'] = int(ref.get('volume'))\n reference['pages'] = ref.get('page')\n reference['authors'] = []\n for author in ref['author']:\n auth = {}\n auth['name'] = ' '.join([author['given'], author['family']])\n # Add ORCID if available\n orcid = author.get('ORCID')\n if orcid:\n auth['ORCID'] = orcid.lstrip('http://orcid.org/')\n reference['authors'].append(auth)\n\n elif ref_key is not None:\n warn('Missing doi attribute in bibliographyLink. '\n 'Setting \"detail\" key as a fallback; please update to the appropriate fields.'\n )\n reference['detail'] = ref_key\n if reference['detail'][-1] != '.':\n reference['detail'] += '.'\n else:\n # Need one of DOI or preferredKey\n raise MissingAttributeError('preferredKey', 'bibliographyLink')\n\n return reference", "docstring": "Read reference info from root of ReSpecTh XML file.\n\nArgs:\n root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file\n\nReturns:\n properties (`dict`): Dictionary with reference information", "source": "juraj_google_style"} +{"code": "def __setitem__(self, key, value):\n\n if not self._is_valid(value):\n value = self._fix_value(value)\n self._inner.__setitem__(key, value)", "docstring": "Attempt to set the value at position `key` to the `value`.\n\n If a value is not the correct type, an attempt will be made to\n convert it to the correct type.\n\nArgs:\n key: An index.\n value: A value to set.", "source": "juraj_google_style"} +{"code": "def col_isnum(df,col_name = None):\n\n col_list = df.select_dtypes(include = 'number').columns\n if col_name is None:\n return col_list\n else:\n return col_name in col_list", "docstring": "Returns a list of columns that are of type 'number'. If col_name is specified, returns\n whether the column in the DataFrame is of type 'number' instead.\n Parameters:\n df - DataFrame\n DataFrame to check\n col_name - string, default None\n If specified, this function will True if df[col_name] is of type 'number'", "source": "juraj_google_style"} +{"code": "def _make_gh_link_node(app, rawtext, role, kind, api_type, id, options=None):\n\n url = \"%s/%s/%s\" % (_BOKEH_GH, api_type, id)\n options = options or {}\n set_classes(options)\n node = nodes.reference(\n rawtext, kind + utils.unescape(id), refuri=url, **options)\n return node", "docstring": "Return a link to a Bokeh Github resource.\n\nArgs:\n app (Sphinx app) : current app\n rawtext (str) : text being replaced with link node.\n role (str) : role name\n kind (str) : resource type (issue, pull, etc.)\n api_type (str) : type for api link\n id : (str) : id of the resource to link to\n options (dict) : options dictionary passed to role function", "source": "juraj_google_style"} +{"code": "def integers(start, count):\n\n if count < 0:\n raise ValueError(\"integers() count cannot be negative\")\n return query(irange(start, start + count))", "docstring": "Generates in sequence the integral numbers within a range.\n\n Note: This method uses deferred execution.\n\nArgs:\n start: The first integer in the sequence.\n count: The number of sequential integers to generate.\n\nReturns:\n A Queryable over the specified range of integers.\n\nRaises:\n ValueError: If count is negative.", "source": "juraj_google_style"} +{"code": "def vert_tab_pos(self, positions):\n\n if positions == 'clear':\n self.send(chr(27)+'B'+chr(0))\n return\n if positions.min < 1 or positions.max >255:\n raise RuntimeError('Invalid position parameter in function horzTabPos')\n sendstr = chr(27) + 'D'\n if len(positions)<=16:\n for position in positions:\n sendstr += chr(position)\n self.send(sendstr + chr(0))\n else:\n raise RuntimeError('Too many positions in function vertTabPos')", "docstring": "Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions.\n\nArgs:\n positions -- Either a list of tab positions (between 1 and 255), or 'clear'.\n\nReturns:\n None\n\nRaises:\n RuntimeError: Invalid position parameter.\n RuntimeError: Too many positions.", "source": "juraj_google_style"} +{"code": "def convert_nsarg(\n nsarg: str,\n api_url: str = None,\n namespace_targets: Mapping[str, List[str]] = None,\n canonicalize: bool = False,\n decanonicalize: bool = False,\n) -> str:\n\n\n if not api_url:\n api_url = config[\"bel_api\"][\"servers\"][\"api_url\"]\n if not api_url:\n log.error(\"Missing api url - cannot convert namespace\")\n return None\n\n params = None\n if namespace_targets:\n namespace_targets_str = json.dumps(namespace_targets)\n params = {\"namespace_targets\": namespace_targets_str}\n\n if not namespace_targets:\n if canonicalize:\n api_url = api_url + \"/terms/{}/canonicalized\"\n elif decanonicalize:\n api_url = api_url + \"/terms/{}/decanonicalized\"\n else:\n log.warning(\"Missing (de)canonical flag - cannot convert namespaces\")\n return nsarg\n else:\n\n api_url = (\n api_url + \"/terms/{}/canonicalized\"\n ) # overriding with namespace_targets\n\n request_url = api_url.format(url_path_param_quoting(nsarg))\n\n r = get_url(request_url, params=params, timeout=10)\n\n if r and r.status_code == 200:\n nsarg = r.json().get(\"term_id\", nsarg)\n elif not r or r.status_code == 404:\n log.error(f\"[de]Canonicalization endpoint missing: {request_url}\")\n\n return nsarg", "docstring": "[De]Canonicalize NSArg\n\nArgs:\n nsarg (str): bel statement string or partial string (e.g. subject or object)\n api_url (str): BEL.bio api url to use, e.g. https://api.bel.bio/v1\n namespace_targets (Mapping[str, List[str]]): formatted as in configuration file example\n canonicalize (bool): use canonicalize endpoint/namespace targets\n decanonicalize (bool): use decanonicalize endpoint/namespace targets\n\n Results:\n str: converted NSArg", "source": "juraj_google_style"} +{"code": "def dismiss_prompt(self, text=None, wait=None):\n\n\n with self.driver.dismiss_modal(\"prompt\", text=text, wait=wait):\n yield", "docstring": "Execute the wrapped code, dismissing a prompt.\n\nArgs:\n text (str | RegexObject, optional): Text to match against the text in the modal.\n wait (int | float, optional): Maximum time to wait for the modal to appear after\n executing the wrapped code.\n\nRaises:\n ModalNotFound: If a modal dialog hasn't been found.", "source": "juraj_google_style"} +{"code": "def resolve_image_exif(self, image_url):\n\n files = self.mets.find_files(url=image_url)\n if files:\n image_filename = self.download_file(files[0]).local_filename\n else:\n image_filename = self.download_url(image_url)\n\n if image_url not in self.image_cache['exif']:\n self.image_cache['exif'][image_url] = OcrdExif(Image.open(image_filename))\n return self.image_cache['exif'][image_url]", "docstring": "Get the EXIF metadata about an image URL as :class:`OcrdExif`\n\nArgs:\n image_url (string) : URL of image\n\n Return\n :class:`OcrdExif`", "source": "juraj_google_style"} +{"code": "def _get_parser_call_method(self, parser_to_method):\n\n def inner_call(args=None, instance=None):\n\n parser = self._cls.parser\n namespace = parser.parse_args(_get_args_to_parse(args, sys.argv))\n if instance is None:\n # If the __init__ method is not part of the method to\n # decorate we cannot instantiate the class\n if \"__init__\" not in parser_to_method:\n raise ParseThisError((\"'__init__' method is not decorated. \"\n \"Please provide an instance to \"\n \"'{}.parser.call' or decorate the \"\n \"'__init___' method with \"\n \"'create_parser'\"\n .format(self._cls.__name__)))\n # We instantiate the class from the command line arguments\n instance = _call_method_from_namespace(self._cls, \"__init__\",\n namespace)\n method_name = parser_to_method[namespace.method]\n return _call_method_from_namespace(instance, method_name, namespace)\n return inner_call", "docstring": "Return the parser special method 'call' that handles sub-command\n calling.\n\nArgs:\n parser_to_method: mapping of the parser registered name\n to the method it is linked to", "source": "juraj_google_style"} +{"code": "def cw_ssim_value(self, target, width=30):\n\n if not isinstance(target, SSIMImage):\n target = SSIMImage(target, size=self.img.size)\n\n # Define a width for the wavelet convolution\n widths = np.arange(1, width+1)\n\n # Use the image data as arrays\n sig1 = np.asarray(self.img.img_gray.getdata())\n sig2 = np.asarray(target.img_gray.getdata())\n\n # Convolution\n cwtmatr1 = signal.cwt(sig1, signal.ricker, widths)\n cwtmatr2 = signal.cwt(sig2, signal.ricker, widths)\n\n # Compute the first term\n c1c2 = np.multiply(abs(cwtmatr1), abs(cwtmatr2))\n c1_2 = np.square(abs(cwtmatr1))\n c2_2 = np.square(abs(cwtmatr2))\n num_ssim_1 = 2 * np.sum(c1c2, axis=0) + self.k\n den_ssim_1 = np.sum(c1_2, axis=0) + np.sum(c2_2, axis=0) + self.k\n\n # Compute the second term\n c1c2_conj = np.multiply(cwtmatr1, np.conjugate(cwtmatr2))\n num_ssim_2 = 2 * np.abs(np.sum(c1c2_conj, axis=0)) + self.k\n den_ssim_2 = 2 * np.sum(np.abs(c1c2_conj), axis=0) + self.k\n\n # Construct the result\n ssim_map = (num_ssim_1 / den_ssim_1) * (num_ssim_2 / den_ssim_2)\n\n # Average the per pixel results\n index = np.average(ssim_map)\n return index", "docstring": "Compute the complex wavelet SSIM (CW-SSIM) value from the reference\n image to the target image.\n\nArgs:\n target (str or PIL.Image): Input image to compare the reference image\n to. This may be a PIL Image object or, to save time, an SSIMImage\n object (e.g. the img member of another SSIM object).\n width: width for the wavelet convolution (default: 30)\n\nReturns:\n Computed CW-SSIM float value.", "source": "juraj_google_style"} +{"code": "def elevation(self, value=0.0):\n\n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError('value {} need to be of type float '\n 'for field `elevation`'.format(value))\n if value < -1000.0:\n raise ValueError('value need to be greater or equal -1000.0 '\n 'for field `elevation`')\n if value >= 9999.9:\n raise ValueError('value need to be smaller 9999.9 '\n 'for field `elevation`')\n\n self._elevation = value", "docstring": "Corresponds to IDD Field `elevation`\n\nArgs:\n value (float): value for IDD Field `elevation`\n Unit: m\n Default value: 0.0\n value >= -1000.0\n value < 9999.9\n if `value` is None it will not be checked against the\n specification and is assumed to be a missing value\n\nRaises:\n ValueError: if `value` is not a valid value", "source": "juraj_google_style"} +{"code": "def _make_instance(self, node_data):\n\n node_data['from_db'] = self._from_db\n clone = self.__call__(**node_data)\n clone.setattrs(container = self,\n _is_item = True)\n for name in self._nodes:\n _name = un_camel(name)\n if _name in node_data: # check for partial data\n getattr(clone, name)._load_data(node_data[_name])\n _key = clone._get_linked_model_key()\n if _key:\n self.node_dict[_key] = clone\n return clone", "docstring": "Create a ListNode instance from node_data\n\nArgs:\n node_data (dict): Data to create ListNode item.\n\nReturns:\n ListNode item.", "source": "juraj_google_style"} +{"code": "def sorted(field_name, ascending=True, fields=None, count=5):\n\n if field_name is None:\n raise Exception('Sort field must be specified')\n direction = '' if ascending else ' DESC'\n projection = Sampling._create_projection(fields)\n return lambda sql: 'SELECT %s FROM (%s) ORDER BY %s%s LIMIT %d' % (projection, sql, field_name,\n direction, count)", "docstring": "Provides a sampling strategy that picks from an ordered set of rows.\n\nArgs:\n field_name: the name of the field to sort the rows by.\n ascending: whether to sort in ascending direction or not.\n fields: an optional list of field names to retrieve.\n count: optional number of rows to limit the sampled results to.\n\nReturns:\n A sampling function that can be applied to get the initial few rows.", "source": "juraj_google_style"} +{"code": "def _send_query(self, query: Dict[str, Any]):\n\n queryb = self.encoder(query)\n self._client.write(queryb)\n if self.debug is True:\n print(\"send query {}\".format(queryb))\n\n return True", "docstring": "将请求编码为字节串发送出去给服务端.\n\n Parameters:\n (query): - 请求的的python字典形式数据\n\nReturns:\n (bool): - 准确地说没有错误就会返回True", "source": "juraj_google_style"} +{"code": "def update_workspace_config(namespace, workspace, cnamespace, configname, body):\n\n uri = \"workspaces/{0}/{1}/method_configs/{2}/{3}\".format(namespace,\n workspace, cnamespace, configname)\n return __post(uri, json=body)", "docstring": "Update method configuration in workspace.\n\nArgs:\n namespace (str): project to which workspace belongs\n workspace (str): Workspace name\n cnamespace (str): Configuration namespace\n configname (str): Configuration name\n body (json): new body (definition) of the method config\n\n Swagger:\n https://api.firecloud.org/#!/Method_Configurations/updateWorkspaceMethodConfig", "source": "juraj_google_style"} +{"code": "def mount(self, app=None):\n\n for endpoint in self._routes:\n endpoint.register_app(app)\n\n return self", "docstring": "Mounts all registered routes to a bottle.py application instance.\n\nArgs:\n app (instance): A `bottle.Bottle()` application instance.\n\nReturns:\n The Router instance (for chaining purposes).", "source": "juraj_google_style"} +{"code": "def _print_results(filename, data):\n\n if filename:\n with open(filename, 'wb') as f:\n f.write(data)\n else:\n print data", "docstring": "Print data to a file or STDOUT.\n\nArgs:\n filename (str or None): If None, print to STDOUT; otherwise, print\n to the file with this name.\n data (str): Data to print.", "source": "juraj_google_style"} +{"code": "def update_from_group(self, data=None, timeout=-1):\n\n uri = \"{}/updateFromGroup\".format(self.data[\"uri\"])\n return self._helper.update(data, uri, timeout=timeout)", "docstring": "Use this action to make a logical enclosure consistent with the enclosure group when the logical enclosure is\n in the Inconsistent state.\n\nArgs:\n timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n in OneView; it just stops waiting for its completion.\n\nReturns:\n dict: Logical enclosure.", "source": "juraj_google_style"} +{"code": "def format_returnvalue(self, value):\n\n\n self._ensure_loaded()\n\n if not self.return_info.is_data:\n return None\n\n # If the return value is typed, use the type_system to format it\n if self.return_info.type_name is not None:\n return typeinfo.type_system.format_value(value, self.return_info.type_name, self.return_info.formatter)\n\n # Otherwise we expect a callable function to convert this value to a string\n return self.return_info.formatter(value)", "docstring": "Format the return value of this function as a string.\n\nArgs:\n value (object): The return value that we are supposed to format.\n\nReturns:\n str: The formatted return value, or None if this function indicates\n that it does not return data", "source": "juraj_google_style"} +{"code": "def generate_delete_user_command(username=None, manage_home=None):\n\n command = None\n remove_home = '-r' if manage_home else ''\n\n if get_platform() in ('Linux', 'OpenBSD'):\n command = '{0} {1} {2} {3}'.format(sudo_check(), LINUX_CMD_USERDEL, remove_home, username)\n elif get_platform() == 'FreeBSD': # pragma: FreeBSD\n command = '{0} {1} userdel {2} -n {3}'.format(sudo_check(), FREEBSD_CMD_PW, remove_home, username)\n if command:\n return shlex.split(str(command))", "docstring": "Generate command to delete a user.\n\nArgs:\n username (str): user name\n manage_home (bool): manage home directory\n\nReturns:\n list: The user delete command string split into shell-like syntax", "source": "juraj_google_style"} +{"code": "def list_repository_methods(namespace=None, name=None, snapshotId=None):\n\n params = {k:v for (k,v) in locals().items() if v is not None}\n return __get(\"methods\", params=params)", "docstring": "List method(s) in the methods repository.\n\nArgs:\n namespace (str): Method Repository namespace\n name (str): method name\n snapshotId (int): method snapshot ID\n\n Swagger:\n https://api.firecloud.org/#!/Method_Repository/listMethodRepositoryMethods", "source": "juraj_google_style"} +{"code": "def set(self, time):\n\n self._time = time\n self._pb.sec = int(self._time)\n self._pb.nsec = int((self._time - self._pb.sec) * 10 ** 9)", "docstring": "Sets time in seconds since Epoch\n\nArgs:\n time (:obj:`float`): time in seconds since Epoch (see time.time())\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def _generate_async(self, generator):\n\n first_value_future = self._workers.submit(next, generator)\n\n def get_first_element(future=first_value_future):\n\n try:\n yield future.result()\n except StopIteration:\n return\n\n return chain(get_first_element(), generator)", "docstring": "Return the previous generator object after having run the first element\n evaluation as a background task.\n\nArgs:\n generator (iterable): A generator function.\n\nReturns:\n iterable: The generator function with first element evaluated\n in background.", "source": "juraj_google_style"} +{"code": "def asdatetime(self, naive=True):\n\n args = list(self.timetuple()[0:6])+[self.microsecond]\n if not naive:\n args.append(self.tzinfo)\n return datetime.datetime(*args)", "docstring": "Return this datetime_tz as a datetime object.\n\nArgs:\n naive: Return *without* any tz info.\n\nReturns:\n This datetime_tz as a datetime object.", "source": "juraj_google_style"} +{"code": "def init_log(log_file):\n\n #Create the log file\n log = None\n try:\n log = open(log_file, 'a')\n\n #Change the output to both the windows and log file\n #original = sys.stdout\n sys.stdout = Tee(sys.stdout, log)\n except:\n pass\n return log", "docstring": "Creates log file on disk and \"Tees\" :py:class:`sys.stdout` to console and disk\n\nArgs:\n log_file (str): The path on disk to append or create the log file.\n\nReturns:\n file: The opened log file.", "source": "juraj_google_style"} +{"code": "def start(self, interval_s):\n\n if self.running:\n return False\n\n self.stopped.clear()\n\n def _execute():\n # Always execute immediately once\n if not self.method() and self.stop_if_false:\n return\n while not self.stopped.wait(interval_s):\n if not self.method() and self.stop_if_false:\n return\n\n self.thread = threading.Thread(target=_execute)\n self.thread.daemon = True\n self.thread.start()\n return True", "docstring": "Starts executing the method at the specified interval.\n\nArgs:\n interval_s: The amount of time between executions of the method.\n\nReturns:\n False if the interval was already running.", "source": "juraj_google_style"} +{"code": "def parse_delta(__string: str) -> datetime.timedelta:\n\n if not __string:\n return datetime.timedelta(0)\n match = re.fullmatch(r, __string, re.VERBOSE)\n if not match:\n raise ValueError('Unable to parse delta {!r}'.format(__string))\n match_dict = {k: int(v) if v else 0 for k, v in match.groupdict().items()}\n return datetime.timedelta(**match_dict)", "docstring": "Parse ISO-8601 duration string.\n\nArgs:\n __string: Duration string to parse\n\nReturns:\n Parsed delta object", "source": "juraj_google_style"} +{"code": "def get_sample_window(self, type_tag, size=10):\n\n\n # Convert size to MB\n size = size * 1024 * 1024\n\n # Grab all the samples of type=type_tag, sort by import_time (newest to oldest)\n cursor = self.database[self.sample_collection].find({'type_tag': type_tag},\n {'md5': 1,'length': 1}).sort('import_time',pymongo.DESCENDING)\n total_size = 0\n md5_list = []\n for item in cursor:\n if total_size > size:\n return md5_list\n md5_list.append(item['md5'])\n total_size += item['length']\n\n # If you get this far you don't have 'size' amount of data\n # so just return what you've got\n return md5_list", "docstring": "Get a window of samples not to exceed size (in MB).\n\nArgs:\n type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...).\n size: Size of samples in MBs.\n\nReturns:\n a list of md5s.", "source": "juraj_google_style"} +{"code": "def wavelength_match(a, b):\n\n if type(a) == (type(b) or\n isinstance(a, numbers.Number) and\n isinstance(b, numbers.Number)):\n return a == b\n elif a is None or b is None:\n return False\n elif isinstance(a, (list, tuple)) and len(a) == 3:\n return a[0] <= b <= a[2]\n elif isinstance(b, (list, tuple)) and len(b) == 3:\n return b[0] <= a <= b[2]\n else:\n raise ValueError(\"Can only compare wavelengths of length 1 or 3\")", "docstring": "Return if two wavelengths are equal.\n\nArgs:\n a (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl\n b (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl", "source": "juraj_google_style"} +{"code": "def popn(self, buffer_type, count):\n\n\n buffer_type = str(buffer_type)\n\n if buffer_type == u'streaming':\n chosen_buffer = self.streaming_data\n else:\n chosen_buffer = self.storage_data\n\n if count > len(chosen_buffer):\n raise StreamEmptyError(\"Not enough data in buffer for popn command\", requested=count, stored=len(chosen_buffer), buffer=buffer_type)\n\n popped = chosen_buffer[:count]\n remaining = chosen_buffer[count:]\n\n if buffer_type == u'streaming':\n self.streaming_data = remaining\n else:\n self.storage_data = remaining\n\n return popped", "docstring": "Remove and return the oldest count values from the named buffer\n\nArgs:\n buffer_type (str): The buffer to pop from (either u\"storage\" or u\"streaming\")\n count (int): The number of readings to pop\n\nReturns:\n list(IOTileReading): The values popped from the buffer", "source": "juraj_google_style"} +{"code": "def mkdir(self, path):\n\n\n self.__validate_storage_path(path, projects_allowed=False)\n parent_metadata = self.get_parent(path)\n self.api_client.create_folder(path.split('/')[-1], parent_metadata['uuid'])", "docstring": "Create a folder in the storage service pointed by the given path.\n\nArgs:\n path (str): The path of the folder to be created\n\nReturns:\n None\n\nRaises:\n StorageArgumentException: Invalid arguments\n StorageForbiddenException: Server response code 403\n StorageNotFoundException: Server response code 404\n StorageException: other 400-600 error codes", "source": "juraj_google_style"} +{"code": "def DotProductAttention(query, key, value, mask, dropout, mode, rng):\n\n depth = np.shape(query)[-1]\n dots = np.matmul(query, np.swapaxes(key, -1, -2)) / np.sqrt(depth)\n if mask is not None:\n dots = np.where(mask, dots, -1e9)\n # Softmax.\n dots = np.exp(dots - backend.logsumexp(dots, axis=-1, keepdims=True))\n if dropout >= 1.0:\n raise ValueError('Dropout rates must be lower than 1.')\n if dropout is not None and dropout > 0.0 and mode == 'train':\n keep = backend.random.bernoulli(rng, 1.0 - dropout, dots.shape)\n dots = np.where(keep, dots / (1.0 - dropout), 0)\n out = np.matmul(dots, value)\n return out", "docstring": "Core dot product self-attention.\n\nArgs:\n query: array of representations\n key: array of representations\n value: array of representations\n mask: attention-mask, gates attention\n dropout: float: dropout rate\n mode: 'eval' or 'train': whether to use dropout\n rng: JAX PRNGKey: subkey for disposable use\n\nReturns:\n Self attention for q, k, v arrays.", "source": "juraj_google_style"} +{"code": "def _parse_hextet(self, hextet_str):\n\n # Whitelist the characters, since int() allows a lot of bizarre stuff.\n if not self._HEX_DIGITS.issuperset(hextet_str):\n raise ValueError\n if len(hextet_str) > 4:\n raise ValueError\n hextet_int = int(hextet_str, 16)\n if hextet_int > 0xFFFF:\n raise ValueError\n return hextet_int", "docstring": "Convert an IPv6 hextet string into an integer.\n\nArgs:\n hextet_str: A string, the number to parse.\n\nReturns:\n The hextet as an integer.\n\nRaises:\n ValueError: if the input isn't strictly a hex number from [0..FFFF].", "source": "juraj_google_style"} +{"code": "def df_first_row_to_dict(df):\n\n if df is not None:\n return [dict(r) for i, r in df.head(1).iterrows()][0]", "docstring": "First DataFrame row to list of dict\n\nArgs:\n df (pandas.DataFrame): A DataFrame with at least one row\n\nReturns:\n A list of dict that looks like:\n\n [{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}]\n\n from a DataFrame that looks like:\n\n C1 C2 C3\n 1 x y z\n\n Else if `df` is `None`, returns `None`", "source": "juraj_google_style"} +{"code": "def terminate_ec2_instance(client, resource):\n\n # TODO: Implement disabling of TerminationProtection\n instance = EC2Instance.get(resource.id)\n if instance.state == 'terminated':\n return ActionStatus.IGNORED, {}\n client.terminate_instances(InstanceIds=[resource.id])\n return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}", "docstring": "Terminate an EC2 Instance\n\n This function will terminate an EC2 Instance.\n\nArgs:\n client (:obj:`boto3.session.Session.client`): A boto3 client object\n resource (:obj:`Resource`): The resource object to terminate\n\nReturns:\n `ActionStatus`", "source": "juraj_google_style"} +{"code": "def l2_regression_loss(y, target, name=None):\n\n with tf.name_scope(name, 'l2_regression', [y, target]) as scope:\n y = tf.convert_to_tensor(y, name='y')\n target = tf.convert_to_tensor(target, name='target')\n return tf.sqrt(l2_regression_sq_loss(y, target, name=scope))", "docstring": "Calculates the square root of the SSE between y and target.\n\nArgs:\n y: the calculated values.\n target: the desired values.\n name: the name for this op, defaults to l2_regression\n\nReturns:\n A tensorflow op.", "source": "juraj_google_style"} +{"code": "def random_data(line_count=1, chars_per_line=80):\n\n divide_lines = chars_per_line * line_count\n return '\\n'.join(random_line_data(chars_per_line) for x in range(int(divide_lines / chars_per_line)))", "docstring": "Function to creates lines of random string data\n\nArgs:\n line_count: An integer that says how many lines to return\n chars_per_line: An integer that says how many characters per line to return\n\nReturns:\n A String", "source": "juraj_google_style"} +{"code": "def _get_block_sizes(resnet_size):\n\n choices = {\n 18: [2, 2, 2, 2],\n 34: [3, 4, 6, 3],\n 50: [3, 4, 6, 3],\n 101: [3, 4, 23, 3],\n 152: [3, 8, 36, 3],\n 200: [3, 24, 36, 3]\n }\n\n try:\n return choices[resnet_size]\n except KeyError:\n err = ('Could not find layers for selected Resnet size.\\n'\n 'Size received: {}; sizes allowed: {}.'.format(\n resnet_size, choices.keys()))\n raise ValueError(err)", "docstring": "Retrieve the size of each block_layer in the ResNet model.\n\n The number of block layers used for the Resnet model varies according\n to the size of the model. This helper grabs the layer set we want, throwing\n an error if a non-standard size has been selected.\n\nArgs:\n resnet_size: The number of convolutional layers needed in the model.\n\nReturns:\n A list of block sizes to use in building the model.\n\nRaises:\n KeyError: if invalid resnet_size is received.", "source": "juraj_google_style"} +{"code": "def interior_angle(p1, p2, o=(0, 0)):\n\n v1 = vector(o, p1)\n v2 = vector(o, p2)\n len1 = distance(o, p1)\n len2 = distance(o, p2)\n try:\n return acos(dot_product(v1, v2) / (len1 * len2))\n except ZeroDivisionError:\n raise ValueError(\"p1 or p2 is overlapped with origin\")", "docstring": "Returns interior angle of two vector(0 <= θ <= pi)\n\nArgs:\n p1, p2: point (x, y)\n o: origin\n\nRaises:\n ValueError: p1 or p2 is overlapped with origin", "source": "juraj_google_style"} +{"code": "def __init__(self, steps_col, slc):\n\n self._col = steps_col\n self._idx = slc.indices(len(self._col))\n self._flt = {\n 'snap': False,\n 'rprof': False,\n 'fields': [],\n 'func': lambda _: True,\n }\n self._dflt_func = self._flt['func']", "docstring": "Initialization of instances:\n\nArgs:\n steps_col (:class:`_Steps` or :class:`_Snaps`): steps collection,\n i.e. :attr:`StagyyData.steps` or :attr:`StagyyData.snaps`\n attributes.\n slc (slice): slice of desired isteps or isnap.", "source": "juraj_google_style"} +{"code": "def get_event(self, event_name, event_history=None):\n\n if event_history is None:\n event_history = event_name + '_history'\n return self._db.rpoplpush(event_name, event_history)", "docstring": "Get an event from the database.\n\n Gets an event from the named event list removing the event and\n adding it to the event history.\n\nArgs:\n event_name (str): Event list key.\n event_history (str, optional): Event history list.\n\nReturns:\n str: string representation of the event object", "source": "juraj_google_style"} +{"code": "def get_user_from_social_auth(tpa_provider, tpa_username):\n\n user_social_auth = UserSocialAuth.objects.select_related('user').filter(\n user__username=tpa_username, provider=tpa_provider.backend_name\n ).first()\n\n return user_social_auth.user if user_social_auth else None", "docstring": "Find the LMS user from the LMS model `UserSocialAuth`.\n\nArgs:\n tpa_provider (third_party_auth.provider): third party auth provider object\n tpa_username (str): Username returned by the third party auth", "source": "juraj_google_style"} +{"code": "def launch_batch_workflow(self, batch_workflow):\n\n\n # hit workflow api\n url = '%(base_url)s/batch_workflows' % {\n 'base_url': self.base_url\n }\n try:\n r = self.gbdx_connection.post(url, json=batch_workflow)\n batch_workflow_id = r.json()['batch_workflow_id']\n return batch_workflow_id\n except TypeError as e:\n self.logger.debug('Batch Workflow not launched, reason: {0}'.format(e))", "docstring": "Launches GBDX batch workflow.\n\nArgs:\n batch_workflow (dict): Dictionary specifying batch workflow tasks.\n\nReturns:\n Batch Workflow id (str).", "source": "juraj_google_style"} +{"code": "def _eval_once(saver, summary_writer, top_1_op, top_5_op, summary_op):\n\n with tf.Session() as sess:\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n print(\"ckpt.model_checkpoint_path: {0}\".format(ckpt.model_checkpoint_path))\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n # Assuming model_checkpoint_path looks something like:\n # /my-favorite-path/imagenet_train/model.ckpt-0,\n # extract global_step from it.\n global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]\n print('Successfully loaded model from %s at step=%s.' %\n (ckpt.model_checkpoint_path, global_step))\n else:\n print('No checkpoint file found')\n return\n\n # Start the queue runners.\n coord = tf.train.Coordinator()\n try:\n threads = []\n for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):\n threads.extend(qr.create_threads(sess, coord=coord, daemon=True,\n start=True))\n\n num_iter = int(math.ceil(FLAGS.num_examples / FLAGS.batch_size))\n # Counts the number of correct predictions.\n count_top_1 = 0.0\n count_top_5 = 0.0\n total_sample_count = num_iter * FLAGS.batch_size\n step = 0\n\n print('%s: starting evaluation on (%s).' % (datetime.now(), FLAGS.subset))\n start_time = time.time()\n while step < num_iter and not coord.should_stop():\n top_1, top_5 = sess.run([top_1_op, top_5_op])\n count_top_1 += np.sum(top_1)\n count_top_5 += np.sum(top_5)\n step += 1\n if step % 20 == 0:\n duration = time.time() - start_time\n sec_per_batch = duration / 20.0\n examples_per_sec = FLAGS.batch_size / sec_per_batch\n print('%s: [%d batches out of %d] (%.1f examples/sec; %.3f'\n 'sec/batch)' % (datetime.now(), step, num_iter,\n examples_per_sec, sec_per_batch))\n start_time = time.time()\n\n # Compute precision @ 1.\n precision_at_1 = count_top_1 / total_sample_count\n recall_at_5 = count_top_5 / total_sample_count\n print('%s: precision @ 1 = %.4f recall @ 5 = %.4f [%d examples]' %\n (datetime.now(), precision_at_1, recall_at_5, total_sample_count))\n\n summary = tf.Summary()\n summary.ParseFromString(sess.run(summary_op))\n summary.value.add(tag='Precision @ 1', simple_value=precision_at_1)\n summary.value.add(tag='Recall @ 5', simple_value=recall_at_5)\n summary_writer.add_summary(summary, global_step)\n\n except Exception as e: # pylint: disable=broad-except\n coord.request_stop(e)\n\n coord.request_stop()\n coord.join(threads, stop_grace_period_secs=10)", "docstring": "Runs Eval once.\n\nArgs:\n saver: Saver.\n summary_writer: Summary writer.\n top_1_op: Top 1 op.\n top_5_op: Top 5 op.\n summary_op: Summary op.", "source": "juraj_google_style"} +{"code": "def is_available(workshift_profile, shift):\n\n if shift.week_long:\n return True\n\n start_time = (\n shift.start_time\n if shift.start_time is not None\n else time(hour=0)\n )\n end_time = (\n shift.end_time\n if shift.end_time is not None\n else time(hour=23, minute=59)\n )\n relevant_blocks = list()\n\n for block in workshift_profile.time_blocks.order_by('start_time'):\n if block.day == shift.day and block.preference == TimeBlock.BUSY \\\n and block.start_time < end_time \\\n and block.end_time > start_time:\n relevant_blocks.append(block)\n\n # Time blocks should be ordered; so go through and see if there is a wide\n # enough window for the workshifter to do the shift. If there is,\n # return True.\n if not relevant_blocks:\n return True\n\n hours_delta = timedelta(hours=float(shift.hours))\n\n # Check the time between shift start and block start\n block = relevant_blocks.pop(0)\n start_delta = timedelta(\n hours=block.start_time.hour - start_time.hour,\n minutes=block.start_time.minute - start_time.minute,\n )\n\n if start_delta >= hours_delta:\n return True\n\n while len(relevant_blocks) > 0:\n block, prev_block = relevant_blocks.pop(0), block\n\n # Check the time between the last block and the next block\n # is larger than the length of the shift\n start_end_delta = timedelta(\n hours=block.start_time.hour - prev_block.end_time.hour,\n minutes=block.start_time.minute - prev_block.end_time.minute,\n )\n\n if start_end_delta >= hours_delta:\n return True\n\n # Check the time between the end of the time block to the end of the shift\n end_delta = timedelta(\n hours=end_time.hour - block.end_time.hour,\n minutes=end_time.minute - block.end_time.minute,\n )\n\n if end_delta >= hours_delta:\n return True\n\n return False", "docstring": "Check whether a specified user is able to do a specified workshift.\n Parameters:\n workshift_profile is the workshift profile for a user\n shift is a weekly recurring workshift\n\nReturns:\n True if the user has enough free time between the shift's start time\n and end time to do the shift's required number of hours.\n False otherwise.", "source": "juraj_google_style"} +{"code": "def get_url(url: str, params: dict = {}, timeout: float = 5.0, cache: bool = True):\n\n\n try:\n\n if not cache:\n with requests_cache.disabled():\n r = requests.get(url, params=params, timeout=timeout)\n else:\n r = requests.get(url, params=params, timeout=timeout)\n\n log.debug(f\"Response headers {r.headers} From cache {r.from_cache}\")\n return r\n\n except requests.exceptions.Timeout:\n log.warn(f\"Timed out getting url in get_url: {url}\")\n return None\n except Exception as e:\n log.warn(f\"Error getting url: {url} error: {e}\")\n return None", "docstring": "Wrapper for requests.get(url)\n\nArgs:\n url: url to retrieve\n params: query string parameters\n timeout: allow this much time for the request and time it out if over\n cache: Cache for up to a day unless this is false\n\nReturns:\n Requests Result obj or None if timed out", "source": "juraj_google_style"} +{"code": "def _stop_trial(self, trial, error=False, error_msg=None,\n stop_logger=True):\n\n\n if stop_logger:\n trial.close_logger()\n\n if error:\n self.set_status(trial, Trial.ERROR)\n else:\n self.set_status(trial, Trial.TERMINATED)\n\n try:\n trial.write_error_log(error_msg)\n if hasattr(trial, \"runner\") and trial.runner:\n if (not error and self._reuse_actors\n and self._cached_actor is None):\n logger.debug(\"Reusing actor for {}\".format(trial.runner))\n self._cached_actor = trial.runner\n else:\n logger.info(\n \"Destroying actor for trial {}. If your trainable is \"\n \"slow to initialize, consider setting \"\n \"reuse_actors=True to reduce actor creation \"\n \"overheads.\".format(trial))\n trial.runner.stop.remote()\n trial.runner.__ray_terminate__.remote()\n except Exception:\n logger.exception(\"Error stopping runner for Trial %s\", str(trial))\n self.set_status(trial, Trial.ERROR)\n finally:\n trial.runner = None", "docstring": "Stops this trial.\n\n Stops this trial, releasing all allocating resources. If stopping the\n trial fails, the run will be marked as terminated in error, but no\n exception will be thrown.\n\nArgs:\n error (bool): Whether to mark this trial as terminated in error.\n error_msg (str): Optional error message.\n stop_logger (bool): Whether to shut down the trial logger.", "source": "juraj_google_style"} +{"code": "def save_issue_data_task(self, issue, task_id, namespace='open'):\n\n\n issue_data = self.get_saved_issue_data(issue, namespace)\n\n if not issue_data.has_key('tasks'):\n issue_data['tasks'] = [task_id]\n elif task_id not in issue_data['tasks']:\n issue_data['tasks'].append(task_id)", "docstring": "Saves a issue data (tasks, etc.) to local data.\n\nArgs:\n issue:\n `int`. Github issue number.\n task:\n `int`. Asana task ID.\n namespace:\n `str`. Namespace for storing this issue.", "source": "juraj_google_style"} +{"code": "def get_servo_torque(self):\n\n data = []\n data.append(0x09)\n data.append(self.servoid)\n data.append(RAM_READ_REQ)\n data.append(PWM_RAM)\n data.append(BYTE2)\n send_data(data)\n rxdata = []\n try:\n rxdata = SERPORT.read(13)\n if ord(rxdata[10])<=127:\n return ((ord(rxdata[10])&0x03)<<8) | (ord(rxdata[9])&0xFF)\n else:\n return (ord(rxdata[10])-0xFF)*0xFF + (ord(rxdata[9])&0xFF)-0xFF\n except HerkulexError:\n raise HerkulexError(\"could not communicate with motors\")", "docstring": "Gets the current torque of Herkulex\n\n Gives the current load on the servo shaft.\n It is actually the PWM value to the motors\n\nArgs:\n none\n\nReturns:\n int: the torque on servo shaft. range from -1023 to 1023\n\nRaises:\n SerialException: Error occured while opening serial port", "source": "juraj_google_style"} +{"code": "def _probe_characteristics_finished(self, result):\n\n\n handle = result['context']['handle']\n conn_id = result['context']['connection_id']\n\n conndata = self._get_connection(handle, 'preparing')\n\n if conndata is None:\n self._logger.info('Connection disconnected before probe_char... finished, conn_id=%d',\n conn_id)\n return\n\n callback = conndata['callback']\n\n if result['result'] is False:\n conndata['failed'] = True\n conndata['failure_reason'] = 'Could not probe GATT characteristics'\n self.disconnect_async(conn_id, self._on_connection_failed)\n return\n\n # Validate that this is a proper IOTile device\n services = result['return_value']['services']\n if TileBusService not in services:\n conndata['failed'] = True\n conndata['failure_reason'] = 'TileBus service not present in GATT services'\n self.disconnect_async(conn_id, self._on_connection_failed)\n return\n\n conndata['chars_done_time'] = time.time()\n service_time = conndata['services_done_time'] - conndata['connect_time']\n char_time = conndata['chars_done_time'] - conndata['services_done_time']\n total_time = service_time + char_time\n conndata['state'] = 'connected'\n conndata['services'] = services\n\n # Create a report parser for this connection for when reports are streamed to us\n conndata['parser'] = IOTileReportParser(report_callback=self._on_report, error_callback=self._on_report_error)\n conndata['parser'].context = conn_id\n\n del conndata['disconnect_handler']\n\n with self.count_lock:\n self.connecting_count -= 1\n\n self._logger.info(\"Total time to connect to device: %.3f (%.3f enumerating services, %.3f enumerating chars)\", total_time, service_time, char_time)\n callback(conndata['connection_id'], self.id, True, None)", "docstring": "Callback when BLE adapter has finished probing services and characteristics for a device\n\nArgs:\n result (dict): Result from the probe_characteristics command", "source": "juraj_google_style"} +{"code": "def from_json(cls, data):\n\n optional_keys = ('city', 'state', 'country', 'latitude', 'longitude',\n 'time_zone', 'elevation', 'station_id', 'source')\n for key in optional_keys:\n if key not in data:\n data[key] = None\n\n return cls(data['city'], data['state'], data['country'], data['latitude'],\n data['longitude'], data['time_zone'], data['elevation'],\n data['station_id'], data['source'])", "docstring": "Create a location from a dictionary.\n\nArgs:\n data: {\n \"city\": \"-\",\n \"latitude\": 0,\n \"longitude\": 0,\n \"time_zone\": 0,\n \"elevation\": 0}", "source": "juraj_google_style"} +{"code": "def new_space_from_module(self, module, recursive=False, **params):\n\n if \"bases\" in params:\n params[\"bases\"] = get_impls(params[\"bases\"])\n\n space = (\n self._impl.model.currentspace\n ) = self._impl.new_space_from_module(\n module, recursive=recursive, **params\n )\n return get_interfaces(space)", "docstring": "Create a child space from an module.\n\n Alias to :py:meth:`import_module`.\n\nArgs:\n module: a module object or name of the module object.\n recursive: Not yet implemented.\n **params: arguments to pass to ``new_space``\n\nReturns:\n The new child space created from the module.", "source": "juraj_google_style"} +{"code": "def from_rotation_and_translation(\n rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)),\n translation_vec=(0, 0, 0), tol=0.1):\n\n rotation_matrix = np.array(rotation_matrix)\n translation_vec = np.array(translation_vec)\n if rotation_matrix.shape != (3, 3):\n raise ValueError(\"Rotation Matrix must be a 3x3 numpy array.\")\n if translation_vec.shape != (3,):\n raise ValueError(\"Translation vector must be a rank 1 numpy array \"\n \"with 3 elements.\")\n affine_matrix = np.eye(4)\n affine_matrix[0:3][:, 0:3] = rotation_matrix\n affine_matrix[0:3][:, 3] = translation_vec\n return SymmOp(affine_matrix, tol)", "docstring": "Creates a symmetry operation from a rotation matrix and a translation\n vector.\n\nArgs:\n rotation_matrix (3x3 array): Rotation matrix.\n translation_vec (3x1 array): Translation vector.\n tol (float): Tolerance to determine if rotation matrix is valid.\n\nReturns:\n SymmOp object", "source": "juraj_google_style"} +{"code": "def encodeRecord(self, record, toBeAdded=True):\n\n encoding=[self.fields[i].encodeValue(record[i], toBeAdded) for i in \\\n xrange(len(self.fields))]\n\n return encoding", "docstring": "Encode a record as a sparse distributed representation\n Parameters:\n --------------------------------------------------------------------\n record: Record to be encoded\n toBeAdded: Whether the encodings corresponding to the record are added to\n the corresponding fields", "source": "juraj_google_style"} +{"code": "def DownloadPqlResultToList(self, pql_query, values=None):\n\n results = []\n self._PageThroughPqlSet(pql_query, results.append, values)\n return results", "docstring": "Downloads the results of a PQL query to a list.\n\nArgs:\n pql_query: str a statement filter to apply (the query should not include\n the limit or the offset)\n [optional]\n values: A dict of python objects or a list of raw SOAP values to bind\n to the pql_query.\n\nReturns:\n a list of lists with the first being the header row and each subsequent\n list being a row of results.", "source": "juraj_google_style"} +{"code": "def _generate_state(self, trans):\n\n state = PDAState()\n state.id = self.nextstate()\n state.type = 2\n state.sym = state.id\n state.trans = trans.copy()\n self.toadd.append(state)\n return state.id", "docstring": "Creates a new POP state (type - 2) with the same transitions.\n The POPed symbol is the unique number of the state.\n\nArgs:\n trans (dict): Transition dictionary\n\nReturns:\n Int: The state identifier", "source": "juraj_google_style"} +{"code": "def gen_part_from_iterables(iterables: Iterable[Any],\n part_index: int) -> Generator[Any, None, None]:\n r\n # RST: make part of word bold/italic:\n # https://stackoverflow.com/questions/12771480/part-of-a-word-bold-in-restructuredtext # noqa\n for iterable in iterables:\n yield iterable[part_index]", "docstring": "r\"\"\"\n Yields the *n*\\ th part of each thing in ``iterables``.\n\nArgs:\n iterables: iterable of anything\n part_index: part index\n\nYields:\n ``item[part_index] for item in iterable``", "source": "juraj_google_style"} +{"code": "def validate_config_must_have(config, required_keys):\n\n missing_keys = set(required_keys) - set(config)\n if len(missing_keys) > 0:\n raise Exception('Invalid config with missing keys \"%s\"' % ', '.join(missing_keys))", "docstring": "Validate a config dictionary to make sure it has all of the specified keys\n\nArgs:\n config: the config to validate.\n required_keys: the list of possible keys that config must include.\n\nRaises:\n Exception if the config does not have any of them.", "source": "juraj_google_style"} +{"code": "def coupling(self, source_y, target_y, weight):\n\n v_pyramidal = source_y[1] - source_y[2]\n return (np.array([0, 0, 0, 0, 0, 1.0, 0, 0]) *\n (weight*self.g1*self.He2*self.ke2*self.S(v_pyramidal)))", "docstring": "How to couple the output of one node to the input of another.\n\nArgs:\n source_y (array of shape (8,)): state of the source node\n target_y (array of shape (8,)): state of the target node\n weight (float): the connection strength\n\nReturns:\n input (array of shape (8,)): value to drive each variable of the\n target node.", "source": "juraj_google_style"} +{"code": "def _CalculateStorageCounters(self, storage_reader):\n\n analysis_reports_counter = collections.Counter()\n analysis_reports_counter_error = False\n event_labels_counter = collections.Counter()\n event_labels_counter_error = False\n parsers_counter = collections.Counter()\n parsers_counter_error = False\n\n for session in storage_reader.GetSessions():\n # Check for a dict for backwards compatibility.\n if isinstance(session.analysis_reports_counter, dict):\n analysis_reports_counter += collections.Counter(\n session.analysis_reports_counter)\n elif isinstance(session.analysis_reports_counter, collections.Counter):\n analysis_reports_counter += session.analysis_reports_counter\n else:\n analysis_reports_counter_error = True\n\n # Check for a dict for backwards compatibility.\n if isinstance(session.event_labels_counter, dict):\n event_labels_counter += collections.Counter(\n session.event_labels_counter)\n elif isinstance(session.event_labels_counter, collections.Counter):\n event_labels_counter += session.event_labels_counter\n else:\n event_labels_counter_error = True\n\n # Check for a dict for backwards compatibility.\n if isinstance(session.parsers_counter, dict):\n parsers_counter += collections.Counter(session.parsers_counter)\n elif isinstance(session.parsers_counter, collections.Counter):\n parsers_counter += session.parsers_counter\n else:\n parsers_counter_error = True\n\n storage_counters = {}\n\n warnings_by_path_spec = collections.Counter()\n warnings_by_parser_chain = collections.Counter()\n\n for warning in list(storage_reader.GetWarnings()):\n warnings_by_path_spec[warning.path_spec.comparable] += 1\n warnings_by_parser_chain[warning.parser_chain] += 1\n\n storage_counters['warnings_by_path_spec'] = warnings_by_path_spec\n storage_counters['warnings_by_parser_chain'] = warnings_by_parser_chain\n\n if not analysis_reports_counter_error:\n storage_counters['analysis_reports'] = analysis_reports_counter\n\n if not event_labels_counter_error:\n storage_counters['event_labels'] = event_labels_counter\n\n if not parsers_counter_error:\n storage_counters['parsers'] = parsers_counter\n\n return storage_counters", "docstring": "Calculates the counters of the entire storage.\n\nArgs:\n storage_reader (StorageReader): storage reader.\n\nReturns:\n dict[str,collections.Counter]: storage counters.", "source": "juraj_google_style"} +{"code": "def set_ipv4_routing(self, vrf_name, default=False, disable=False):\n\n cmd = 'ip routing vrf %s' % vrf_name\n if default:\n cmd = 'default %s' % cmd\n elif disable:\n cmd = 'no %s' % cmd\n cmd = make_iterable(cmd)\n return self.configure(cmd)", "docstring": "Configures ipv4 routing for the vrf\n\nArgs:\n vrf_name (str): The VRF name to configure\n default (bool): Configures ipv4 routing for the vrf value to\n default if this value is true\n disable (bool): Negates the ipv4 routing for the vrf if set to true\n\nReturns:\n True if the operation was successful otherwise False", "source": "juraj_google_style"} +{"code": "def _calc_min_size(self, conv_layers):\n\n input_size = 1\n\n for _, conv_params, max_pooling in reversed(conv_layers):\n if max_pooling is not None:\n kernel_size, stride = max_pooling\n input_size = input_size * stride + (kernel_size - stride)\n\n if conv_params is not None:\n kernel_size, stride = conv_params\n input_size = input_size * stride + (kernel_size - stride)\n\n return input_size", "docstring": "Calculates the minimum size of the input layer.\n\n Given a set of convolutional layers, calculate the minimum value of\n the `input_height` and `input_width`, i.e. such that the output has\n size 1x1. Assumes snt.VALID padding.\n\nArgs:\n conv_layers: List of tuples `(output_channels, (kernel_size, stride),\n (pooling_size, pooling_stride))`\n\nReturns:\n Minimum value of input height and width.", "source": "juraj_google_style"} +{"code": "def __init__(self, name=None, eid=None):\n\n if None not in (name, eid):\n raise TypeError(\"Provide only a `name` or an `eid`.\")\n\n self._eid = eid or _get_enum(name)\n self._comments = EnumComments(self._eid)", "docstring": "Get an existing enum.\n\n Only provide one of `name` and `eid`.\n\nArgs:\n name: Name of the enum\n eid: Enum ID", "source": "juraj_google_style"} +{"code": "def delete(self, branch, commit_message, **kwargs):\n\n file_path = self.get_id().replace('/', '%2F')\n self.manager.delete(file_path, branch, commit_message, **kwargs)", "docstring": "Delete the file from the server.\n\nArgs:\n branch (str): Branch from which the file will be removed\n commit_message (str): Commit message for the deletion\n **kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\n GitlabAuthenticationError: If authentication is not correct\n GitlabDeleteError: If the server cannot perform the request", "source": "juraj_google_style"} +{"code": "def build_phenotype(phenotype_id, adapter):\n\n phenotype_obj = {}\n phenotype = adapter.hpo_term(phenotype_id)\n if phenotype:\n phenotype_obj['phenotype_id'] = phenotype['hpo_id']\n phenotype_obj['feature'] = phenotype['description']\n return phenotype", "docstring": "Build a small phenotype object\n\n Build a dictionary with phenotype_id and description\n\nArgs:\n phenotype_id (str): The phenotype id\n adapter (scout.adapter.MongoAdapter)\n\nReturns:\n phenotype_obj (dict):\n\n dict(\n phenotype_id = str,\n feature = str, # description of phenotype\n )", "source": "juraj_google_style"} +{"code": "def symbolic_heisenberg_eom(\n self, X=None, noises=None, expand_simplify=True):\n\n L, H = self.L, self.H\n\n if X is None:\n X = OperatorSymbol('X', hs=(L.space | H.space))\n\n summands = [I * (H * X - X * H), ]\n for Lk in L.matrix.ravel():\n summands.append(adjoint(Lk) * X * Lk)\n summands.append(-(adjoint(Lk) * Lk * X + X * adjoint(Lk) * Lk) / 2)\n\n if noises is not None:\n if not isinstance(noises, Matrix):\n noises = Matrix(noises)\n LambdaT = (noises.adjoint().transpose() * noises.transpose()).transpose()\n assert noises.shape == L.shape\n S = self.S\n summands.append((adjoint(noises) * S.adjoint() * (X * L - L * X))\n .expand()[0, 0])\n summand = (((L.adjoint() * X - X * L.adjoint()) * S * noises)\n .expand()[0, 0])\n summands.append(summand)\n if len(S.space & X.space):\n comm = (S.adjoint() * X * S - X)\n summands.append((comm * LambdaT).expand().trace())\n\n ret = OperatorPlus.create(*summands)\n if expand_simplify:\n ret = ret.expand().simplify_scalar()\n return ret", "docstring": "Compute the symbolic Heisenberg equations of motion of a system\n operator X. If no X is given, an OperatorSymbol is created in its\n place. If no noises are given, this correspnds to the\n ensemble-averaged Heisenberg equation of motion.\n\nArgs:\n X (Operator): A system operator\n noises (Operator): A vector of noise inputs\n\nReturns:\n Operator: The RHS of the Heisenberg equations of motion of X.", "source": "juraj_google_style"} +{"code": "def main(argv=None):\n\n args = None\n cmd = None\n\n try:\n args = parse_args(argv)\n\n if args.quiet:\n logger.setLevel(logging.CRITICAL)\n\n elif args.verbose:\n logger.setLevel(logging.DEBUG)\n\n cmd = args.func(args)\n ret = cmd.run_cmd()\n except KeyboardInterrupt:\n logger.exception(\"interrupted by the user\")\n ret = 252\n except NotDvcRepoError:\n logger.exception(\"\")\n ret = 253\n except DvcParserError:\n ret = 254\n except Exception: # pylint: disable=broad-except\n logger.exception(\"unexpected error\")\n ret = 255\n\n Analytics().send_cmd(cmd, args, ret)\n\n return ret", "docstring": "Run dvc CLI command.\n\nArgs:\n argv: optional list of arguments to parse. sys.argv is used by default.\n\nReturns:\n int: command's return code.", "source": "juraj_google_style"} +{"code": "def publish_metric(self, metric_name, metric_value, epoch_seconds=None):\n\n if epoch_seconds is None:\n epoch_seconds = self._reactor.seconds()\n self._client_factory.publish_metric(metric_name, metric_value, int(epoch_seconds))", "docstring": "Record a single hit on a given metric.\n\nArgs:\n metric_name: The name of the metric to record with Carbon.\n metric_value: The value to record with Carbon.\n epoch_seconds: Optionally specify the time for the metric hit.\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def round_f1_macro(y_true, y_predicted):\n\n try:\n predictions = [np.round(x) for x in y_predicted]\n except TypeError:\n predictions = y_predicted\n\n return f1_score(np.array(y_true), np.array(predictions), average=\"macro\")", "docstring": "Calculates F1 macro measure.\n\nArgs:\n y_true: list of true values\n y_predicted: list of predicted values\n\nReturns:\n F1 score", "source": "juraj_google_style"} +{"code": "def add_nodes(self, root_id, current_node, indent=1):\n\n # if the current node has no children, no need to continue\n if not current_node.children:\n return\n\n config.LOGGER.info(\"({count} of {total} uploaded) {indent}Processing {title} ({kind})\".format(\n count=self.node_count_dict['upload_count'],\n total=self.node_count_dict['total_count'],\n indent=\" \" * indent,\n title=current_node.title,\n kind=current_node.__class__.__name__)\n )\n\n # Send children in chunks to avoid gateway errors\n try:\n chunks = [current_node.children[x:x+10] for x in range(0, len(current_node.children), 10)]\n for chunk in chunks:\n payload_children = []\n\n for child in chunk:\n failed = [f for f in child.files if f.is_primary and (not f.filename or self.failed_uploads.get(f.filename))]\n if any(failed):\n if not self.failed_node_builds.get(root_id):\n error_message = \"\"\n for fail in failed:\n reason = fail.filename + \": \" + self.failed_uploads.get(fail.filename) if fail.filename else \"File failed to download\"\n error_message = error_message + reason + \", \"\n self.failed_node_builds[root_id] = {'node': current_node, 'error': error_message[:-2]}\n else:\n payload_children.append(child.to_dict())\n payload = {\n 'root_id': root_id,\n 'content_data': payload_children\n }\n\n # When iceqube is integrated, use this method to utilize upload file optimizations\n # response = config.SESSION.post(config.add_nodes_from_file_url(), files={'file': json.dumps(payload)})\n\n response = config.SESSION.post(config.add_nodes_url(), data=json.dumps(payload))\n if response.status_code != 200:\n self.failed_node_builds[root_id] = {'node': current_node, 'error': response.reason}\n else:\n response_json = json.loads(response._content.decode(\"utf-8\"))\n self.node_count_dict['upload_count'] += len(chunk)\n\n if response_json['root_ids'].get(child.get_node_id().hex):\n for child in chunk:\n self.add_nodes(response_json['root_ids'].get(child.get_node_id().hex), child, indent + 1)\n except ConnectionError as ce:\n self.failed_node_builds[root_id] = {'node': current_node, 'error': ce}", "docstring": "add_nodes: adds processed nodes to tree\n\nArgs:\n root_id (str): id of parent node on Kolibri Studio\n current_node (Node): node to publish children\n indent (int): level of indentation for printing\n Returns: link to uploadedchannel", "source": "juraj_google_style"} +{"code": "def GetParserPluginsInformation(cls, parser_filter_expression=None):\n\n parser_plugins_information = []\n for _, parser_class in cls.GetParsers(\n parser_filter_expression=parser_filter_expression):\n if parser_class.SupportsPlugins():\n for plugin_name, plugin_class in parser_class.GetPlugins():\n description = getattr(plugin_class, 'DESCRIPTION', '')\n parser_plugins_information.append((plugin_name, description))\n\n return parser_plugins_information", "docstring": "Retrieves the parser plugins information.\n\nArgs:\n parser_filter_expression (Optional[str]): parser filter expression,\n where None represents all parsers and plugins.\n\nReturns:\n list[tuple[str, str]]: pairs of parser plugin names and descriptions.", "source": "juraj_google_style"} +{"code": "def is_supported(cls, file=None, request=None, response=None,\n url_info=None):\n\n tests = (\n (response, cls.is_response),\n (file, cls.is_file),\n (request, cls.is_request),\n (url_info, cls.is_url)\n )\n\n for instance, method in tests:\n if instance:\n try:\n result = method(instance)\n except NotImplementedError:\n pass\n else:\n if result:\n return True\n elif result is VeryFalse:\n return VeryFalse", "docstring": "Given the hints, return whether the document is supported.\n\nArgs:\n file: A file object containing the document.\n request (:class:`.http.request.Request`): An HTTP request.\n response (:class:`.http.request.Response`): An HTTP response.\n url_info (:class:`.url.URLInfo`): A URLInfo.\n\nReturns:\n bool: If True, the reader should be able to read it.", "source": "juraj_google_style"} +{"code": "def _FindInKey(self, registry_key, find_specs, search_depth):\n\n sub_find_specs = []\n for find_spec in find_specs:\n match, key_path_match = find_spec.Matches(registry_key, search_depth)\n if match:\n yield registry_key.path\n\n # pylint: disable=singleton-comparison\n if key_path_match != False and not find_spec.AtMaximumDepth(search_depth):\n sub_find_specs.append(find_spec)\n\n if sub_find_specs:\n search_depth += 1\n for sub_registry_key in registry_key.GetSubkeys():\n for matching_path in self._FindInKey(\n sub_registry_key, sub_find_specs, search_depth):\n yield matching_path", "docstring": "Searches for matching keys within the Windows Registry key.\n\nArgs:\n registry_key (WinRegistryKey): Windows Registry key.\n find_specs (list[FindSpec]): find specifications.\n search_depth (int): number of key path segments to compare.\n\nYields:\n str: key path of a matching Windows Registry key.", "source": "juraj_google_style"} +{"code": "def _RunScript(self, script):\n\n process = subprocess.Popen(\n script, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n while True:\n for line in iter(process.stdout.readline, b''):\n self.logger.info(line.decode('utf-8').rstrip('\\n'))\n if process.poll() is not None:\n break", "docstring": "Run a script and log the streamed script output.\n\nArgs:\n script: string, the file location of an executable script.", "source": "juraj_google_style"} +{"code": "def set_value(self, value: ScalarType) -> None:\n\n if isinstance(value, bool):\n value_str = 'true' if value else 'false'\n else:\n value_str = str(value)\n start_mark = self.yaml_node.start_mark\n end_mark = self.yaml_node.end_mark\n # If we're of a class type, then we want to keep that tag so that the\n # correct Constructor is called. If we're a built-in type, set the tag\n # to the appropriate YAML tag.\n tag = self.yaml_node.tag\n if tag.startswith('tag:yaml.org,2002:'):\n tag = scalar_type_to_tag[type(value)]\n new_node = yaml.ScalarNode(tag, value_str, start_mark, end_mark)\n self.yaml_node = new_node", "docstring": "Sets the value of the node to a scalar value.\n\n After this, is_scalar(type(value)) will return true.\n\nArgs:\n value: The value to set this node to, a str, int, float, \\\n bool, or None.", "source": "juraj_google_style"} +{"code": "def execute(self, sensor_graph, scope_stack):\n\n\n parent = scope_stack[-1]\n alloc = parent.allocator\n\n # The output is unused\n output = alloc.allocate_stream(DataStream.UnbufferedType, attach=True)\n\n trigger_stream, trigger_cond = parent.trigger_chain()\n streamer_const = alloc.allocate_stream(DataStream.ConstantType, attach=True)\n\n sensor_graph.add_node(u\"({} {} && {} always) => {} using trigger_streamer\".format(trigger_stream, trigger_cond, streamer_const, output))\n sensor_graph.add_constant(streamer_const, self.index)", "docstring": "Execute this statement on the sensor_graph given the current scope tree.\n\n This adds a single node to the sensor graph with the trigger_streamer function\n as is processing function.\n\nArgs:\n sensor_graph (SensorGraph): The sensor graph that we are building or\n modifying\n scope_stack (list(Scope)): A stack of nested scopes that may influence\n how this statement allocates clocks or other stream resources.", "source": "juraj_google_style"} +{"code": "def update_instance(self, data):\n\n for key, val in iteritems(data):\n if not hasattr(self, key):\n raise AttributeError(\n \"No field named {key} for model {model}\".format(\n key=key,\n model=self.__class__.__name__\n )\n )\n\n setattr(self, key, val)\n\n self.save()\n\n return self", "docstring": "Update a single record by id with the provided data.\n\nArgs:\n data (dict): The new data to update the record with.\n\nReturns:\n self: This is an instance of itself with the updated data.\n\nRaises:\n AttributeError: This is raised if a key in the ``data`` isn't\n a field on the model.", "source": "juraj_google_style"} +{"code": "def _set_property(self, name, value):\n\n if name in worker_mapping().keys():\n setattr(self, name, value)\n return\n\n raise KeyError(\"Can't set `%s`!\" % name)", "docstring": "Set property `name` to `value`, but only if it is part of the mapping\n returned from `worker_mapping` (ie - data transported to frontend).\n\n This method is used from the REST API DB, so it knows what to set and\n what not, to prevent users from setting internal values.\n\nArgs:\n name (str): Name of the property to set.\n value (obj): Any python value.\n\nRaises:\n KeyError: If `name` can't be set.", "source": "juraj_google_style"} +{"code": "def preprocess_for_eval(image, image_size=224, normalize=True):\n\n if normalize: image = tf.to_float(image) / 255.0\n image = _do_scale(image, image_size + 32)\n if normalize: image = _normalize(image)\n image = _center_crop(image, image_size)\n image = tf.reshape(image, [image_size, image_size, 3])\n return image", "docstring": "Preprocesses the given image for evaluation.\n\nArgs:\n image: `Tensor` representing an image of arbitrary size.\n image_size: int, how large the output image should be.\n normalize: bool, if True the image is normalized.\n\nReturns:\n A preprocessed image `Tensor`.", "source": "juraj_google_style"} +{"code": "def to_FIB(self, other):\n\n\n if not isinstance(other, GroundedFunctionNetwork):\n raise TypeError(\n f\"Expected GroundedFunctionNetwork, but got {type(other)}\"\n )\n\n def shortname(var):\n return var[var.find(\"::\") + 2 : var.rfind(\"_\")]\n\n def shortname_vars(graph, shortname):\n return [v for v in graph.nodes() if shortname in v]\n\n this_var_nodes = [\n shortname(n)\n for (n, d) in self.nodes(data=True)\n if d[\"type\"] == \"variable\"\n ]\n other_var_nodes = [\n shortname(n)\n for (n, d) in other.nodes(data=True)\n if d[\"type\"] == \"variable\"\n ]\n\n shared_vars = set(this_var_nodes).intersection(set(other_var_nodes))\n full_shared_vars = {\n full_var\n for shared_var in shared_vars\n for full_var in shortname_vars(self, shared_var)\n }\n\n return ForwardInfluenceBlanket(self, full_shared_vars)", "docstring": "Creates a ForwardInfluenceBlanket object representing the\n intersection of this model with the other input model.\n\nArgs:\n other: The GroundedFunctionNetwork object to compare this model to.\n\nReturns:\n A ForwardInfluenceBlanket object to use for model comparison.", "source": "juraj_google_style"} +{"code": "def Main(url):\n\n # The object of Web-scraping.\n web_scrape = WebScraping()\n # Set the object of reading PDF files.\n web_scrape.readable_web_pdf = WebPDFReading()\n # Execute Web-scraping.\n document = web_scrape.scrape(url)\n # The object of automatic sumamrization.\n auto_abstractor = AutoAbstractor()\n # Set tokenizer. This is japanese tokenizer with MeCab.\n auto_abstractor.tokenizable_doc = MeCabTokenizer()\n # Object of abstracting and filtering document.\n abstractable_doc = TopNRankAbstractor()\n # Execute summarization.\n result_dict = auto_abstractor.summarize(document, abstractable_doc)\n # Output summarized sentence.\n [print(sentence) for sentence in result_dict[\"summarize_result\"]]", "docstring": "Entry Point.\n\nArgs:\n url: PDF url.", "source": "juraj_google_style"} +{"code": "def DeregisterAttributeContainer(cls, attribute_container_class):\n\n container_type = attribute_container_class.CONTAINER_TYPE.lower()\n if container_type not in cls._attribute_container_classes:\n raise KeyError(\n 'Attribute container class not set for container type: '\n '{0:s}.'.format(attribute_container_class.CONTAINER_TYPE))\n\n del cls._attribute_container_classes[container_type]", "docstring": "Deregisters an attribute container class.\n\n The attribute container classes are identified based on their lower case\n container type.\n\nArgs:\n attribute_container_class (type): attribute container class.\n\nRaises:\n KeyError: if attribute container class is not set for\n the corresponding container type.", "source": "juraj_google_style"} +{"code": "def __init__(self, event_type, event_data):\n\n\n self.type = event_type\n self.data = event_data", "docstring": "Creates a new event.\n\nArgs:\n event_type (int): the type of the event, see\n :class:`~bigchaindb.events.EventTypes`\n event_data (obj): the data of the event.", "source": "juraj_google_style"} +{"code": "def _build_request(self, verb, verb_arguments):\n\n method = getattr(self._component, verb)\n\n # Python insists that keys in **kwargs be strings (not variables).\n # Since we initially build our kwargs as a dictionary where one of the\n # keys is a variable (target), we need to convert keys to strings,\n # even though the variable in question is of type str.\n method_args = {str(k): v for k, v in verb_arguments.items()}\n return method(**method_args)", "docstring": "Builds HttpRequest object.\n\nArgs:\n verb (str): Request verb (ex. insert, update, delete).\n verb_arguments (dict): Arguments to be passed with the request.\n\nReturns:\n httplib2.HttpRequest: HttpRequest to be sent to the API.", "source": "juraj_google_style"} +{"code": "def decrypt(key, ciphertext, shift_function=shift_case_english):\n\n return [shift_function(key, symbol) for symbol in ciphertext]", "docstring": "Decrypt Shift enciphered ``ciphertext`` using ``key``.\n\nExample:\n >>> ''.join(decrypt(3, \"KHOOR\"))\n HELLO\n\n >> decrypt(15, [0xcf, 0x9e, 0xaf, 0xe0], shift_bytes)\n [0xde, 0xad, 0xbe, 0xef]\n\nArgs:\n key (int): The shift to use\n ciphertext (iterable): The symbols to decrypt\n shift_function (function (shift, symbol)): Shift function to apply to symbols in the ciphertext\n\nReturns:\n Decrypted ciphertext, list of plaintext symbols", "source": "juraj_google_style"} +{"code": "def __init__(self, assign_defaults=(), method_name=None):\n\n super(self.__class__, self).__init__(assign_defaults=assign_defaults,\n method_name=method_name)", "docstring": "Assigns arguments to the decorator.\n\nArgs:\n assign_defaults: A sequence of strings for the default values that should\n be provided. Defaults are shared across methods.\n method_name: If provided, use this as the method_name instead of the\n wrapped function's name.", "source": "juraj_google_style"} +{"code": "def delayedQuote(symbol, token='', version=''):\n\n _raiseIfNotStr(symbol)\n return _getJson('stock/' + symbol + '/delayed-quote', token, version)", "docstring": "This returns the 15 minute delayed market quote.\n\n https://iexcloud.io/docs/api/#delayed-quote\n 15min delayed\n 4:30am - 8pm ET M-F when market is open\n\nArgs:\n symbol (string); Ticker to request\n token (string); Access token\n version (string); API version\n\nReturns:\n dict: result", "source": "juraj_google_style"} +{"code": "def _update_triplestore(self, es_result, action_list, **kwargs):\n\n idx_time = XsdDatetime(datetime.datetime.utcnow())\n uri_keys = {}\n bnode_keys = {}\n for item in action_list:\n try:\n uri_keys[item['_id']] = item['_source'][\"uri\"]\n except KeyError:\n bnode_keys[item['_id']] = item['_id']\n error_dict = {}\n error_bnodes = {}\n if es_result[1]:\n for result in es_result[1]:\n err_item = list(result.values())[0]\n try:\n error_dict[uri_keys.pop(err_item['_id'])] = \\\n XsdString(err_item['error']['reason'])\n except KeyError:\n error_bnodes[bnode_keys.pop(err_item['_id'])] = \\\n XsdString(err_item['error']['reason'])\n if uri_keys:\n sparql_good = .format(idx_time=idx_time.sparql,\n subj_list=\"<%s>\" % \">\\n<\".join(uri_keys.values()))\n self.tstore_conn.update_query(sparql_good)\n # Process any errors that were found.\n if not error_dict:\n return\n # Delete all indexing triples related to the error subjects\n sparql_error = .format(subj_list=\"<%s>\" % \">\\n<\".join(error_dict.keys()))\n self.tstore_conn.update_query(sparql_error)\n del sparql_error\n sparql_update = .format(\n idx_time=idx_time.sparql,\n error_list=\"\\n\".join([\"(<%s> %s)\" % (key, val.sparql)\n for key, val in error_dict.items()]))\n\n # Create a turtle data stream of the new errors to upload into the\n # triplestore\n self.tstore_conn.update_query(sparql_update)\n del sparql_update", "docstring": "updates the triplestore with success of saves and failues of indexing\n\nArgs:\n -----\n es_result: the elasticsearch result list\n action_list: list of elasticsearch action items that were indexed", "source": "juraj_google_style"} +{"code": "def _rescale(vector):\n\n # Subtract min, making smallest value 0\n min_val = min(vector)\n vector = [v - min_val for v in vector]\n\n # Divide by max, making largest value 1\n max_val = float(max(vector))\n try:\n return [v / max_val for v in vector]\n except ZeroDivisionError: # All values are the same\n return [1.0] * len(vector)", "docstring": "Scale values in vector to the range [0, 1].\n\nArgs:\n vector: A list of real values.", "source": "juraj_google_style"} +{"code": "def hexstr(text):\n\n text = text.strip().lower()\n if text.startswith(('0x', '0X')):\n text = text[2:]\n\n if not text:\n raise s_exc.BadTypeValu(valu=text, name='hexstr',\n mesg='No string left after stripping')\n\n try:\n # checks for valid hex width and does character\n # checking in C without using regex\n s_common.uhex(text)\n except (binascii.Error, ValueError) as e:\n raise s_exc.BadTypeValu(valu=text, name='hexstr', mesg=str(e))\n return text", "docstring": "Ensure a string is valid hex.\n\nArgs:\n text (str): String to normalize.\n\nExample:\n Norm a few strings:\n\n hexstr('0xff00')\n hexstr('ff00')\n\nNote:\n Will accept strings prefixed by '0x' or '0X' and remove them.\n\nReturns:\n str: Normalized hex string.", "source": "juraj_google_style"} +{"code": "def stack1d(*points):\n\n result = np.empty((2, len(points)), order=\"F\")\n for index, point in enumerate(points):\n result[:, index] = point\n return result", "docstring": "Fill out the columns of matrix with a series of points.\n\n This is because ``np.hstack()`` will just make another 1D vector\n out of them and ``np.vstack()`` will put them in the rows.\n\nArgs:\n points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e.\n arrays with shape ``(2,)``.\n\nReturns:\n numpy.ndarray: The array with each point in ``points`` as its\n columns.", "source": "juraj_google_style"} +{"code": "def clone(self, *args, **overrides):\n\n clone = super(Layout, self).clone(*args, **overrides)\n clone._max_cols = self._max_cols\n return clone", "docstring": "Clones the Layout, overriding data and parameters.\n\nArgs:\n data: New data replacing the existing data\n shared_data (bool, optional): Whether to use existing data\n new_type (optional): Type to cast object to\n *args: Additional arguments to pass to constructor\n **overrides: New keyword arguments to pass to constructor\n\nReturns:\n Cloned Layout object", "source": "juraj_google_style"} +{"code": "def __process_inequalities(self, block_index):\n\n initial_block_index = block_index\n row_offsets = [0]\n for block, block_size in enumerate(self.block_struct):\n row_offsets.append(row_offsets[block] + block_size ** 2)\n\n if self._parallel:\n pool = Pool()\n for k, ineq in enumerate(self.constraints):\n block_index += 1\n monomials = self.localizing_monomial_sets[block_index -\n initial_block_index-1]\n lm = len(monomials)\n if isinstance(ineq, str):\n self.__parse_expression(ineq, row_offsets[block_index-1])\n continue\n if ineq.is_Relational:\n ineq = convert_relational(ineq)\n func = partial(moment_of_entry, monomials=monomials, ineq=ineq,\n substitutions=self.substitutions)\n if self._parallel and lm > 1:\n chunksize = max(int(np.sqrt(lm*lm/2) /\n cpu_count()), 1)\n iter_ = pool.map(func, ([row, column] for row in range(lm)\n for column in range(row, lm)),\n chunksize)\n else:\n iter_ = imap(func, ([row, column] for row in range(lm)\n for column in range(row, lm)))\n if block_index > self.constraint_starting_block + \\\n self._n_inequalities and lm > 1:\n is_equality = True\n else:\n is_equality = False\n for row, column, polynomial in iter_:\n if is_equality:\n row, column = 0, 0\n self.__push_facvar_sparse(polynomial, block_index,\n row_offsets[block_index-1],\n row, column)\n if is_equality:\n block_index += 1\n if is_equality:\n block_index -= 1\n if self.verbose > 0:\n sys.stdout.write(\"\\r\\x1b[KProcessing %d/%d constraints...\" %\n (k+1, len(self.constraints)))\n sys.stdout.flush()\n if self._parallel:\n pool.close()\n pool.join()\n\n if self.verbose > 0:\n sys.stdout.write(\"\\n\")\n return block_index", "docstring": "Generate localizing matrices\n\nArgs:\n inequalities -- list of inequality constraints\n monomials -- localizing monomials\n block_index -- the current block index in constraint matrices of the\n SDP relaxation", "source": "juraj_google_style"} +{"code": "def generate_srt_from_sjson(sjson_subs):\n\n\n output = ''\n\n equal_len = len(sjson_subs['start']) == len(sjson_subs['end']) == len(sjson_subs['text'])\n if not equal_len:\n return output\n\n for i in range(len(sjson_subs['start'])):\n item = SubRipItem(\n index=i,\n start=SubRipTime(milliseconds=sjson_subs['start'][i]),\n end=SubRipTime(milliseconds=sjson_subs['end'][i]),\n text=sjson_subs['text'][i]\n )\n output += (six.text_type(item))\n output += '\\n'\n return output", "docstring": "Generate transcripts from sjson to SubRip (*.srt).\n\nArgs:\n sjson_subs (dict): `sjson` subs.\n\nReturns:\n Subtitles in SRT format.", "source": "juraj_google_style"} +{"code": "def to_dict(ramons, flatten=False):\n\n if type(ramons) is not list:\n ramons = [ramons]\n\n out_ramons = {}\n for r in ramons:\n out_ramons[r.id] = {\n \"id\": r.id,\n \"type\": _reverse_ramon_types[type(r)],\n \"metadata\": vars(r)\n }\n return out_ramons", "docstring": "Converts a RAMON object list to a JSON-style dictionary. Useful for going\n from an array of RAMONs to a dictionary, indexed by ID.\n\nArgs:\n ramons (RAMON[]): A list of RAMON objects\n flatten (boolean: False): Not implemented\n\nReturns:\n dict: A python dictionary of RAMON objects.", "source": "juraj_google_style"} +{"code": "def map_into_course(self, course_key):\n\n return self.replace(usage_key=self.usage_key.map_into_course(course_key))", "docstring": "Return a new :class:`UsageKey` or :class:`AssetKey` representing this usage inside the\n course identified by the supplied :class:`CourseKey`. It returns the same type as\n `self`\n\nArgs:\n course_key (:class:`CourseKey`): The course to map this object into.\n\nReturns:\n A new :class:`CourseObjectMixin` instance.", "source": "juraj_google_style"} +{"code": "def fitness(self, width, height): \n\n assert(width > 0 and height > 0)\n\n rect, max_rect = self._select_position(width, height)\n if rect is None:\n return None\n\n # Return fitness\n return self._rect_fitness(max_rect, rect.width, rect.height)", "docstring": "Metric used to rate how much space is wasted if a rectangle is placed.\n Returns a value greater or equal to zero, the smaller the value the more\n 'fit' is the rectangle. If the rectangle can't be placed, returns None.\n\nArgs:\n width (int, float): Rectangle width\n height (int, float): Rectangle height\n\nReturns:\n int, float: Rectangle fitness\n None: Rectangle can't be placed", "source": "juraj_google_style"} +{"code": "def get_collection(self, key=None, name=None):\n\n if name is not None:\n logger.warn(\"TowerTensorHandle.get_collection(name=..) was renamed to (key=..) !\")\n key = name\n return self._ctx.get_collection_in_tower(key)", "docstring": "See :meth:`BaseTowerContext.get_collection_in_tower`.\n\nArgs:\n key (str): the key of the collection\n name: deprecated", "source": "juraj_google_style"} +{"code": "def get_lock_state_transaction(self, transaction_id):\n\n response = None\n try:\n response = requests.get(\n urls.get_lockstate_transaction(self._giid, transaction_id),\n headers={\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Cookie': 'vid={}'.format(self._vid)})\n except requests.exceptions.RequestException as ex:\n raise RequestError(ex)\n _validate_response(response)\n return json.loads(response.text)", "docstring": "Get lock state transaction status\n\nArgs:\n transaction_id: Transaction ID received from set_lock_state", "source": "juraj_google_style"} +{"code": "def __init__(self, start, length):\n\n assert(isinstance(start, Point) and not isinstance(length, Point))\n super(HSegment, self).__init__(start, Point(start.x+length, start.y))", "docstring": "Create an Horizontal segment given its left most end point and its\n length.\n\nArgs:\n - start (Point): Starting Point\n - length (number): segment length", "source": "juraj_google_style"} +{"code": "def get_stability_criteria(self, s, n):\n\n n = get_uvec(n)\n stress = s * np.outer(n, n)\n sym_wallace = self.get_symmetric_wallace_tensor(stress)\n return np.linalg.det(sym_wallace.voigt)", "docstring": "Gets the stability criteria from the symmetric\n Wallace tensor from an input vector and stress\n value.\n\nArgs:\n s (float): Stress value at which to evaluate\n the stability criteria\n n (3x1 array-like): direction of the applied\n stress", "source": "juraj_google_style"} +{"code": "def get_template_parameters_s3(template_key, s3_resource):\n\n for suffix in EFConfig.PARAMETER_FILE_SUFFIXES:\n parameters_key = template_key.replace(\"/templates\", \"/parameters\") + suffix\n try:\n obj = s3_resource.Object(EFConfig.S3_CONFIG_BUCKET, parameters_key)\n obj.get()\n return parameters_key\n except ClientError:\n continue\n return None", "docstring": "Checks for existance of parameters object in S3 against supported suffixes and returns parameters file key if found\n\nArgs:\n template_key: S3 key for template file. omit bucket.\n s3_resource: a boto3 s3 resource\n\nReturns:\n filename of parameters file if it exists", "source": "juraj_google_style"} +{"code": "def _add_to_ptr_size(self, ptr):\n # type: (path_table_record.PathTableRecord) -> int\n\n num_bytes_to_add = 0\n for pvd in self.pvds:\n # The add_to_ptr_size() method returns True if the PVD needs\n # additional space in the PTR to store this directory. We always\n # add 4 additional extents for that (2 for LE, 2 for BE).\n if pvd.add_to_ptr_size(path_table_record.PathTableRecord.record_length(ptr.len_di)):\n num_bytes_to_add += 4 * self.pvd.logical_block_size()\n\n return num_bytes_to_add", "docstring": "An internal method to add a PTR to a VD, adding space to the VD if\n necessary.\n\n Parameters:\n ptr - The PTR to add to the vd.\n\nReturns:\n The number of additional bytes that are needed to fit the new PTR\n (this may be zero).", "source": "juraj_google_style"} +{"code": "def __init__(self, alias, target, hstore_key):\n\n\n super().__init__(alias, target, output_field=target)\n self.alias, self.target, self.hstore_key = alias, target, hstore_key", "docstring": "Initializes a new instance of :see:HStoreColumn.\n\nArgs:\n alias:\n The table name.\n\n target:\n The field instance.\n\n hstore_key\n The name of the hstore key to include\n in the epxression.", "source": "juraj_google_style"} +{"code": "def MakeCdfFromPmf(pmf, name=None):\n\n if name == None:\n name = pmf.name\n return MakeCdfFromItems(pmf.Items(), name)", "docstring": "Makes a CDF from a Pmf object.\n\nArgs:\n pmf: Pmf.Pmf object\n name: string name for the data.\n\nReturns:\n Cdf object", "source": "juraj_google_style"} +{"code": "def read_bytes(self, length) -> bytes:\n\n value = self.stream.read(length)\n return value", "docstring": "Read the specified number of bytes from the stream.\n\nArgs:\n length (int): number of bytes to read.\n\nReturns:\n bytes: `length` number of bytes.", "source": "juraj_google_style"} +{"code": "def update_offset(self, offset):\n # type: (int) -> None\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('CE record not yet initialized!')\n\n self.offset_cont_area = offset", "docstring": "Update the offset for this CE record.\n\n Parameters:\n extent - The new offset for this CE record.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def save(variable, filename):\n\n fileObj = open(filename, 'wb')\n pickle.dump(variable, fileObj)\n fileObj.close()", "docstring": "Save variable on given path using Pickle\n\nArgs:\n variable: what to save\n path (str): path of the output", "source": "juraj_google_style"} +{"code": "def find_layer_idx(model, layer_name):\n\n layer_idx = None\n for idx, layer in enumerate(model.layers):\n if layer.name == layer_name:\n layer_idx = idx\n break\n\n if layer_idx is None:\n raise ValueError(\"No layer with name '{}' within the model\".format(layer_name))\n return layer_idx", "docstring": "Looks up the layer index corresponding to `layer_name` from `model`.\n\nArgs:\n model: The `keras.models.Model` instance.\n layer_name: The name of the layer to lookup.\n\nReturns:\n The layer index if found. Raises an exception otherwise.", "source": "juraj_google_style"} +{"code": "def _container_handler(ion_type, ctx):\n\n transition = None\n first = True\n at_top = ctx.depth == 0\n while True:\n data_event, self = (yield transition)\n if data_event is not None and data_event.type is ReadEventType.SKIP:\n yield ctx.read_data_transition(ctx.remaining, self, skip=True)\n\n if ctx.queue.position == ctx.limit:\n # We are at the end of the container.\n # Yield the close event and go to enclosing container.\n yield Transition(\n IonEvent(IonEventType.CONTAINER_END, ion_type, depth=ctx.depth-1),\n ctx.whence\n )\n\n if ion_type is IonType.STRUCT:\n # Read the field name.\n self_handler = _create_delegate_handler(self)\n (field_sid, _), _ = yield ctx.immediate_transition(\n _var_uint_field_handler(self_handler, ctx)\n )\n field_name = SymbolToken(None, field_sid)\n else:\n field_name = None\n\n expects_ivm = first and at_top\n transition = ctx.immediate_transition(\n _start_type_handler(field_name, self, ctx, expects_ivm, at_top=at_top)\n )\n first = False", "docstring": "Handler for the body of a container (or the top-level stream).\n\nArgs:\n ion_type (Optional[IonType]): The type of the container or ``None`` for the top-level.\n ctx (_HandlerContext): The context for the container.", "source": "juraj_google_style"} +{"code": "def _Open(self, path_spec, mode='rb'):\n\n if not path_spec.HasParent():\n raise errors.PathSpecError(\n 'Unsupported path specification without parent.')\n\n file_object = resolver.Resolver.OpenFileObject(\n path_spec.parent, resolver_context=self._resolver_context)\n\n try:\n vslvm_handle = pyvslvm.handle()\n vslvm_handle.open_file_object(file_object)\n # TODO: implement multi physical volume support.\n vslvm_handle.open_physical_volume_files_as_file_objects([\n file_object])\n vslvm_volume_group = vslvm_handle.get_volume_group()\n except:\n file_object.close()\n raise\n\n self._file_object = file_object\n self._vslvm_handle = vslvm_handle\n self._vslvm_volume_group = vslvm_volume_group", "docstring": "Opens the file system object defined by path specification.\n\nArgs:\n path_spec (PathSpec): path specification.\n mode (Optional[str]): file access mode. The default is 'rb' which\n represents read-only binary.\n\nRaises:\n AccessError: if the access to open the file was denied.\n IOError: if the file system object could not be opened.\n PathSpecError: if the path specification is incorrect.\n ValueError: if the path specification is invalid.", "source": "juraj_google_style"} +{"code": "def construct_analogy_test_set(test_examples, dictionary, ignore_missing=False):\n\n\n test = []\n\n for example in test_examples:\n try:\n test.append([dictionary[word] for word in example])\n except KeyError:\n if ignore_missing:\n pass\n else:\n raise\n\n try:\n test = np.array(test, dtype=np.int32)\n except ValueError as e:\n # This should use raise ... from ... in Python 3.\n raise ValueError('Each row of the test set should contain '\n '4 integer word ids', e)\n\n return test", "docstring": "Construct the analogy test set by mapping the words to their\n word vector ids.\n\nArgs:\n - test_examples: iterable of 4-word iterables\n - dictionay: a mapping from words to ids\n - boolean ignore_missing: if True, words in the test set\n that are not in the dictionary\n will be dropeed.\n\nReturns:\n - a N by 4 numpy matrix.", "source": "juraj_google_style"} +{"code": "def _FormatDateTime(self, event):\n\n try:\n datetime_object = datetime.datetime(\n 1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.UTC)\n datetime_object += datetime.timedelta(microseconds=event.timestamp)\n datetime_object.astimezone(self._output_mediator.timezone)\n\n return datetime_object.replace(tzinfo=None)\n\n except (OverflowError, ValueError) as exception:\n self._ReportEventError(event, (\n 'unable to copy timestamp: {0!s} to a human readable date and time '\n 'with error: {1!s}. Defaulting to: \"ERROR\"').format(\n event.timestamp, exception))\n return 'ERROR'", "docstring": "Formats the date to a datetime object without timezone information.\n\n Note: timezone information must be removed due to lack of support\n by xlsxwriter and Excel.\n\nArgs:\n event (EventObject): event.\n\nReturns:\n datetime.datetime|str: date and time value or a string containing\n \"ERROR\" on OverflowError.", "source": "juraj_google_style"} +{"code": "def get(self, id):\n\n for obj in self.model.db:\n if obj[\"id\"] == id:\n return self._cast_model(obj)\n\n return None", "docstring": "Get a object by id\n\nArgs:\n id (int): Object id\n\nReturns:\n Object: Object with specified id\n None: If object not found", "source": "juraj_google_style"} +{"code": "def save(self, vleaf, fpath, cleanup=False, format=None):\n\n graph = self.create_graphviz_digraph(vleaf, format=format)\n graph.render(fpath, cleanup=cleanup)", "docstring": "Save the graph to a given file path.\n\nArgs:\n vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt.\n fpath (`str`): The file path used to save.\n cleanup (`bool`): Clean up the source file after rendering. Default is False.\n format (str):\n Force overwrite ``format`` (``'pdf', 'png', ...)``) configuration.", "source": "juraj_google_style"} +{"code": "def distance(self, other):\n\n return np.linalg.norm(other.coords - self.coords)", "docstring": "Get distance between two sites.\n\nArgs:\n other: Other site.\n\nReturns:\n Distance (float)", "source": "juraj_google_style"} +{"code": "def set_name(self, vid, name=None, default=False, disable=False):\n\n cmds = self.command_builder('name', value=name, default=default,\n disable=disable)\n return self.configure_vlan(vid, cmds)", "docstring": "Configures the VLAN name\n\n EosVersion:\n 4.13.7M\n\nArgs:\n vid (str): The VLAN ID to Configures\n name (str): The value to configure the vlan name\n default (bool): Defaults the VLAN ID name\n disable (bool): Negates the VLAN ID name\n\nReturns:\n True if the operation was successful otherwise False", "source": "juraj_google_style"} +{"code": "def fastcc_consistent_subset(model, epsilon, solver):\n\n reaction_set = set(model.reactions)\n return reaction_set.difference(fastcc(model, epsilon, solver))", "docstring": "Return consistent subset of model.\n\n The largest consistent subset is returned as\n a set of reaction names.\n\nArgs:\n model: :class:`MetabolicModel` to solve.\n epsilon: Flux threshold value.\n solver: LP solver instance to use.\n\nReturns:\n Set of reaction IDs in the consistent reaction subset.", "source": "juraj_google_style"} +{"code": "def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n\n local_stream = utils.BytearrayStream()\n\n if self._unique_identifier is not None:\n self._unique_identifier.write(\n local_stream,\n kmip_version=kmip_version\n )\n if self._key_format_type is not None:\n self._key_format_type.write(\n local_stream,\n kmip_version=kmip_version\n )\n if self._key_compression_type is not None:\n self._key_compression_type.write(\n local_stream,\n kmip_version=kmip_version\n )\n if self._key_wrapping_specification is not None:\n self._key_wrapping_specification.write(\n local_stream,\n kmip_version=kmip_version\n )\n\n self.length = local_stream.length()\n super(GetRequestPayload, self).write(\n output_stream,\n kmip_version=kmip_version\n )\n output_stream.write(local_stream.buffer)", "docstring": "Write the data encoding the Get request payload to a stream.\n\nArgs:\n output_stream (stream): A data stream in which to encode object\n data, supporting a write method; usually a BytearrayStream\n object.\n kmip_version (KMIPVersion): An enumeration defining the KMIP\n version with which the object will be encoded. Optional,\n defaults to KMIP 1.0.", "source": "juraj_google_style"} +{"code": "def _to_qasm_output(\n self,\n header: Optional[str] = None,\n precision: int = 10,\n qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,\n ) -> QasmOutput:\n\n if header is None:\n header = 'Generated from Cirq v{}'.format(\n cirq._version.__version__)\n qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(\n self.all_qubits())\n return QasmOutput(operations=self.all_operations(),\n qubits=qubits,\n header=header,\n precision=precision,\n version='2.0')", "docstring": "Returns a QASM object equivalent to the circuit.\n\nArgs:\n header: A multi-line string that is placed in a comment at the top\n of the QASM. Defaults to a cirq version specifier.\n precision: Number of digits to use when representing numbers.\n qubit_order: Determines how qubits are ordered in the QASM\n register.", "source": "juraj_google_style"} +{"code": "def build_masked_loss(loss_function, mask_value):\n\n\n def masked_loss_function(y_true, y_pred):\n mask = K.cast(K.not_equal(y_true, mask_value), K.floatx())\n return loss_function(y_true * mask, y_pred * mask)\n\n return masked_loss_function", "docstring": "Builds a loss function that masks based on targets\n\nArgs:\n loss_function: The loss function to mask\n mask_value: The value to mask in the targets\n\nReturns:\n function: a loss function that acts like loss_function with masked inputs", "source": "juraj_google_style"} +{"code": "def getStreamNetworkAsWkt(self, session, withNodes=True):\n\n wkt_list = []\n\n for link in self.streamLinks:\n wkt_link = link.getAsWkt(session)\n\n if wkt_link:\n wkt_list.append(wkt_link)\n\n if withNodes:\n for node in link.nodes:\n wkt_node = node.getAsWkt(session)\n\n if wkt_node:\n wkt_list.append(wkt_node)\n\n return 'GEOMCOLLECTION ({0})'.format(', '.join(wkt_list))", "docstring": "Retrieve the stream network geometry in Well Known Text format.\n\nArgs:\n session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database\n withNodes (bool, optional): Include nodes. Defaults to False.\n\nReturns:\n str: Well Known Text string.", "source": "juraj_google_style"} +{"code": "def _log_to_stderr(self, record):\n\n # emit() is protected by a lock in logging.Handler, so we don't need to\n # protect here again.\n old_stream = self.stream\n self.stream = sys.stderr\n try:\n super(PythonHandler, self).emit(record)\n finally:\n self.stream = old_stream", "docstring": "Emits the record to stderr.\n\n This temporarily sets the handler stream to stderr, calls\n StreamHandler.emit, then reverts the stream back.\n\nArgs:\n record: logging.LogRecord, the record to log.", "source": "juraj_google_style"} +{"code": "def render_wrapper(self, region='us-east-1'):\n\n base = self.settings['pipeline']['base']\n\n if self.base:\n base = self.base\n\n email = self.settings['pipeline']['notifications']['email']\n slack = self.settings['pipeline']['notifications']['slack']\n baking_process = self.settings['pipeline']['image']['builder']\n provider = 'aws'\n root_volume_size = self.settings['pipeline']['image']['root_volume_size']\n bake_instance_type = self.settings['pipeline']['image']['bake_instance_type']\n\n ami_id = ami_lookup(name=base, region=region)\n\n ami_template_file = generate_packer_filename(provider, region, baking_process)\n\n pipeline_id = self.compare_with_existing(region=region)\n\n data = {\n 'app': {\n 'ami_id': ami_id,\n 'appname': self.app_name,\n 'group_name': self.group_name,\n 'repo_name': self.repo_name,\n 'base': base,\n 'environment': 'packaging',\n 'region': region,\n 'triggerjob': self.trigger_job,\n 'run_as_user': DEFAULT_RUN_AS_USER,\n 'email': email,\n 'slack': slack,\n 'root_volume_size': root_volume_size,\n 'bake_instance_type': bake_instance_type,\n 'ami_template_file': ami_template_file,\n 'pipeline': self.settings['pipeline']\n },\n 'id': pipeline_id\n }\n\n self.log.debug('Wrapper app data:\\n%s', pformat(data))\n\n wrapper = get_template(template_file='pipeline/pipeline_wrapper.json.j2', data=data, formats=self.generated)\n\n return json.loads(wrapper)", "docstring": "Generate the base Pipeline wrapper.\n\n This renders the non-repeatable stages in a pipeline, like jenkins, baking, tagging and notifications.\n\nArgs:\n region (str): AWS Region.\n\nReturns:\n dict: Rendered Pipeline wrapper.", "source": "juraj_google_style"} +{"code": "def QA_data_tick_resample(tick, type_='1min'):\n\n tick = tick.assign(amount=tick.price * tick.vol)\n resx = pd.DataFrame()\n _temp = set(tick.index.date)\n\n for item in _temp:\n _data = tick.loc[str(item)]\n _data1 = _data[time(9,\n 31):time(11,\n 30)].resample(\n type_,\n closed='right',\n base=30,\n loffset=type_\n ).apply(\n {\n 'price': 'ohlc',\n 'vol': 'sum',\n 'code': 'last',\n 'amount': 'sum'\n }\n )\n\n _data2 = _data[time(13,\n 1):time(15,\n 0)].resample(\n type_,\n closed='right',\n loffset=type_\n ).apply(\n {\n 'price': 'ohlc',\n 'vol': 'sum',\n 'code': 'last',\n 'amount': 'sum'\n }\n )\n\n resx = resx.append(_data1).append(_data2)\n resx.columns = resx.columns.droplevel(0)\n return resx.reset_index().drop_duplicates().set_index(['datetime', 'code'])", "docstring": "tick采样成任意级别分钟线\n\nArgs:\n tick {[type]} -- transaction\n\nReturns:\n [type] -- [description]", "source": "juraj_google_style"} +{"code": "def __init__(self, video, quality=None, download_dir=None, templates=None) -> None:\n\n self.video = video\n self.quality = quality or DEFAULT_OPTIONS['quality']\n self.download_dir = download_dir or DEFAULT_OPTIONS['download_dir']\n self.templates = templates or DEFAULT_OPTIONS['templates']\n\n if self.quality not in ('worst', 'best'):\n raise WrongQualityError", "docstring": "Create a VideoDownloader for a given video.\n\nArgs:\n video (Video): Video object.\n quality (str): Quality of the video (best/worst). Audio quality defaults to best.\n download_dir (str): Destination directory for the downloaded video.\n templates (dict): Dictionary of templates needed to generate a download path.", "source": "juraj_google_style"} +{"code": "def _load_callwraps(packname, package):\n\n global _callwraps\n from acorn.config import settings\n from acorn.logging.descriptors import _obj_getattr\n spack = settings(packname)\n if spack is not None:\n if spack.has_section(\"callwrap\"):\n wrappings = dict(spack.items(\"callwrap\"))\n for fqdn, target in wrappings.items():\n caller = _obj_getattr(package, target)\n _callwraps[fqdn] = caller", "docstring": "Loads the special call wrapping settings for functions in the specified\n package. This allows the result of the original method call to be cast as a\n different type, or passed to a different constructor before returning from\n the wrapped function.\n\nArgs:\n packname (str): name of the package to get config settings for.\n package: actual package object.", "source": "juraj_google_style"} +{"code": "def Get(self, path, follow_symlink = True):\n\n key = self._Key(path=path, follow_symlink=follow_symlink)\n try:\n return self._cache[key]\n except KeyError:\n value = Stat.FromPath(path, follow_symlink=follow_symlink)\n self._cache[key] = value\n\n # If we are not following symlinks and the file is a not symlink then\n # the stat result for this file stays the same even if we want to follow\n # symlinks.\n if not follow_symlink and not value.IsSymlink():\n self._cache[self._Key(path=path, follow_symlink=True)] = value\n\n return value", "docstring": "Stats given file or returns a cached result if available.\n\nArgs:\n path: A path to the file to perform `stat` on.\n follow_symlink: True if `stat` of a symlink should be returned instead of\n a file that it points to. For non-symlinks this setting has no effect.\n\nReturns:\n `Stat` object corresponding to the given path.", "source": "juraj_google_style"} +{"code": "def __init__(self, mixin, args, lineno=0):\n\n self.tokens = [mixin, args]\n self.lineno = lineno", "docstring": "This node represents mixin calls. The calls\n to these mixins are deferred until the second\n parse cycle. lessc.js allows calls to mixins not\n yet defined or known.\n\nArgs:\n mixin (Mixin): Mixin object\n args (list): Call arguments", "source": "juraj_google_style"} +{"code": "def get_commits(self, since_sha=None):\n\n assert self.tempdir\n\n cmd = ['git', 'log', '--first-parent', '--reverse', COMMIT_FORMAT]\n if since_sha:\n commits = [self.get_commit(since_sha)]\n cmd.append('{}..HEAD'.format(since_sha))\n else:\n commits = []\n cmd.append('HEAD')\n\n output = cmd_output(*cmd, cwd=self.tempdir)\n\n for sha, date in chunk_iter(output.splitlines(), 2):\n commits.append(Commit(sha, int(date)))\n\n return commits", "docstring": "Returns a list of Commit objects.\n\nArgs:\n since_sha - (optional) A sha to search from", "source": "juraj_google_style"} +{"code": "def simulate(self, action):\n\n with tf.name_scope('environment/simulate'):\n if action.dtype in (tf.float16, tf.float32, tf.float64):\n action = tf.check_numerics(action, 'action')\n observ_dtype = self._parse_dtype(self._batch_env.observation_space)\n observ, reward, done = tf.py_func(\n lambda a: self._batch_env.step(a)[:3], [action],\n [observ_dtype, tf.float32, tf.bool], name='step')\n observ = tf.check_numerics(observ, 'observ')\n reward = tf.check_numerics(reward, 'reward')\n return tf.group(\n self._observ.assign(observ),\n self._action.assign(action),\n self._reward.assign(reward),\n self._done.assign(done))", "docstring": "Step the batch of environments.\n\n The results of the step can be accessed from the variables defined below.\n\nArgs:\n action: Tensor holding the batch of actions to apply.\n\nReturns:\n Operation.", "source": "juraj_google_style"} +{"code": "def xor_bytes(a, b):\n\n assert isinstance(a, bytes)\n assert isinstance(b, bytes)\n assert len(a) == len(b)\n res = bytearray()\n for i in range(len(a)):\n res.append(a[i] ^ b[i])\n return bytes(res)", "docstring": "XOR on two bytes objects\n\nArgs:\n a (bytes): object 1\n b (bytes): object 2\n\nReturns:\n bytes: The XOR result", "source": "juraj_google_style"} +{"code": "def etm_supported(self):\n\n res = self._dll.JLINKARM_ETM_IsPresent()\n if (res == 1):\n return True\n\n # JLINKARM_ETM_IsPresent() only works on ARM 7/9 devices. This\n # fallback checks if ETM is present by checking the Cortex ROM table\n # for debugging information for ETM.\n info = ctypes.c_uint32(0)\n index = enums.JLinkROMTable.ETM\n res = self._dll.JLINKARM_GetDebugInfo(index, ctypes.byref(info))\n if (res == 1):\n return False\n\n return True", "docstring": "Returns if the CPU core supports ETM.\n\nArgs:\n self (JLink): the ``JLink`` instance.\n\nReturns:\n ``True`` if the CPU has the ETM unit, otherwise ``False``.", "source": "juraj_google_style"} +{"code": "def do_ams_patch(endpoint, path, body, access_token):\n\n headers = {\"Content-Type\": json_acceptformat,\n \"DataServiceVersion\": dsversion_min,\n \"MaxDataServiceVersion\": dsversion_max,\n \"Accept\": json_acceptformat,\n \"Accept-Charset\" : charset,\n \"Authorization\": \"Bearer \" + access_token,\n \"x-ms-version\" : xmsversion}\n response = requests.patch(endpoint, data=body, headers=headers, allow_redirects=False)\n # AMS response to the first call can be a redirect,\n # so we handle it here to make it transparent for the caller...\n if response.status_code == 301:\n redirected_url = ''.join([response.headers['location'], path])\n response = requests.patch(redirected_url, data=body, headers=headers)\n return response", "docstring": "Do a AMS PATCH request and return JSON.\n\nArgs:\n endpoint (str): Azure Media Services Initial Endpoint.\n path (str): Azure Media Services Endpoint Path.\n body (str): Azure Media Services Content Body.\n access_token (str): A valid Azure authentication token.\n\nReturns:\n HTTP response. JSON body.", "source": "juraj_google_style"} +{"code": "def _runExperimentImpl(options, model=None):\n\n json_helpers.validate(options.privateOptions,\n schemaDict=g_parsedPrivateCommandLineOptionsSchema)\n\n # Load the experiment's description.py module\n experimentDir = options.experimentDir\n descriptionPyModule = helpers.loadExperimentDescriptionScriptFromDir(\n experimentDir)\n expIface = helpers.getExperimentDescriptionInterfaceFromModule(\n descriptionPyModule)\n\n # Handle \"list checkpoints\" request\n if options.privateOptions['listAvailableCheckpoints']:\n _printAvailableCheckpoints(experimentDir)\n return None\n\n # Load experiment tasks\n experimentTasks = expIface.getModelControl().get('tasks', [])\n\n # If the tasks list is empty, and this is a nupic environment description\n # file being run from the OPF, convert it to a simple OPF description file.\n if (len(experimentTasks) == 0 and\n expIface.getModelControl()['environment'] == OpfEnvironment.Nupic):\n expIface.convertNupicEnvToOPF()\n experimentTasks = expIface.getModelControl().get('tasks', [])\n\n # Ensures all the source locations are either absolute paths or relative to\n # the nupic.datafiles package_data location.\n expIface.normalizeStreamSources()\n\n # Extract option\n newSerialization = options.privateOptions['newSerialization']\n\n # Handle listTasks\n if options.privateOptions['listTasks']:\n print \"Available tasks:\"\n\n for label in [t['taskLabel'] for t in experimentTasks]:\n print \"\\t\", label\n\n return None\n\n # Construct the experiment instance\n if options.privateOptions['runCheckpointName']:\n\n assert model is None\n\n checkpointName = options.privateOptions['runCheckpointName']\n\n model = ModelFactory.loadFromCheckpoint(\n savedModelDir=_getModelCheckpointDir(experimentDir, checkpointName),\n newSerialization=newSerialization)\n\n elif model is not None:\n print \"Skipping creation of OPFExperiment instance: caller provided his own\"\n else:\n modelDescription = expIface.getModelDescription()\n model = ModelFactory.create(modelDescription)\n\n # Handle \"create model\" request\n if options.privateOptions['createCheckpointName']:\n checkpointName = options.privateOptions['createCheckpointName']\n _saveModel(model=model,\n experimentDir=experimentDir,\n checkpointLabel=checkpointName,\n newSerialization=newSerialization)\n\n return model\n\n # Build the task list\n\n # Default task execution index list is in the natural list order of the tasks\n taskIndexList = range(len(experimentTasks))\n\n customTaskExecutionLabelsList = options.privateOptions['taskLabels']\n if customTaskExecutionLabelsList:\n taskLabelsList = [t['taskLabel'] for t in experimentTasks]\n taskLabelsSet = set(taskLabelsList)\n\n customTaskExecutionLabelsSet = set(customTaskExecutionLabelsList)\n\n assert customTaskExecutionLabelsSet.issubset(taskLabelsSet), \\\n (\"Some custom-provided task execution labels don't correspond \"\n \"to actual task labels: mismatched labels: %r; actual task \"\n \"labels: %r.\") % (customTaskExecutionLabelsSet - taskLabelsSet,\n customTaskExecutionLabelsList)\n\n taskIndexList = [taskLabelsList.index(label) for label in\n customTaskExecutionLabelsList]\n\n print \"#### Executing custom task list: %r\" % [taskLabelsList[i] for\n i in taskIndexList]\n\n # Run all experiment tasks\n for taskIndex in taskIndexList:\n\n task = experimentTasks[taskIndex]\n\n # Create a task runner and run it!\n taskRunner = _TaskRunner(model=model,\n task=task,\n cmdOptions=options)\n taskRunner.run()\n del taskRunner\n\n if options.privateOptions['checkpointModel']:\n _saveModel(model=model,\n experimentDir=experimentDir,\n checkpointLabel=task['taskLabel'],\n newSerialization=newSerialization)\n\n return model", "docstring": "Creates and runs the experiment\n\nArgs:\n options: namedtuple ParseCommandLineOptionsResult\n model: For testing: may pass in an existing OPF Model instance\n to use instead of creating a new one.\n\n Returns: reference to OPFExperiment instance that was constructed (this\n is provided to aid with debugging) or None, if none was\n created.", "source": "juraj_google_style"} +{"code": "def media_download(self, mxcurl, allow_remote=True):\n\n query_params = {}\n if not allow_remote:\n query_params[\"allow_remote\"] = False\n if mxcurl.startswith('mxc://'):\n return self._send(\n \"GET\", mxcurl[6:],\n api_path=\"/_matrix/media/r0/download/\",\n query_params=query_params,\n return_json=False\n )\n else:\n raise ValueError(\n \"MXC URL '%s' did not begin with 'mxc://'\" % mxcurl\n )", "docstring": "Download raw media from provided mxc URL.\n\nArgs:\n mxcurl (str): mxc media URL.\n allow_remote (bool): indicates to the server that it should not\n attempt to fetch the media if it is deemed remote. Defaults\n to true if not provided.", "source": "juraj_google_style"} +{"code": "def get_splitter_instance(split_type):\n\n if split_type is None:\n return NoneSplitter()\n elif split_type == 'Line':\n return LineSplitter()\n elif split_type == 'RecordIO':\n return RecordIOSplitter()\n else:\n raise ValueError('Invalid Split Type: %s' % split_type)", "docstring": "Return an Instance of :class:`sagemaker.local.data.Splitter` according to\n the specified `split_type`.\n\nArgs:\n split_type (str): either 'Line' or 'RecordIO'. Can be left as None to signal no data split\n will happen.\n\n Returns\n :class:`sagemaker.local.data.Splitter`: an Instance of a Splitter", "source": "juraj_google_style"} +{"code": "def _serialization_helper(self, ray_forking):\n\n if ray_forking:\n actor_handle_id = compute_actor_handle_id(\n self._ray_actor_handle_id, self._ray_actor_forks)\n else:\n actor_handle_id = self._ray_actor_handle_id\n\n # Note: _ray_actor_cursor and _ray_actor_creation_dummy_object_id\n # could be None.\n state = {\n \"actor_id\": self._ray_actor_id,\n \"actor_handle_id\": actor_handle_id,\n \"module_name\": self._ray_module_name,\n \"class_name\": self._ray_class_name,\n \"actor_cursor\": self._ray_actor_cursor,\n \"actor_method_names\": self._ray_actor_method_names,\n \"method_signatures\": self._ray_method_signatures,\n \"method_num_return_vals\": self._ray_method_num_return_vals,\n # Actors in local mode don't have dummy objects.\n \"actor_creation_dummy_object_id\": self.\n _ray_actor_creation_dummy_object_id,\n \"actor_method_cpus\": self._ray_actor_method_cpus,\n \"actor_driver_id\": self._ray_actor_driver_id,\n \"ray_forking\": ray_forking\n }\n\n if ray_forking:\n self._ray_actor_forks += 1\n new_actor_handle_id = actor_handle_id\n else:\n # The execution dependency for a pickled actor handle is never safe\n # to release, since it could be unpickled and submit another\n # dependent task at any time. Therefore, we notify the backend of a\n # random handle ID that will never actually be used.\n new_actor_handle_id = ActorHandleID(_random_string())\n # Notify the backend to expect this new actor handle. The backend will\n # not release the cursor for any new handles until the first task for\n # each of the new handles is submitted.\n # NOTE(swang): There is currently no garbage collection for actor\n # handles until the actor itself is removed.\n self._ray_new_actor_handles.append(new_actor_handle_id)\n\n return state", "docstring": "This is defined in order to make pickling work.\n\nArgs:\n ray_forking: True if this is being called because Ray is forking\n the actor handle and false if it is being called by pickling.\n\nReturns:\n A dictionary of the information needed to reconstruct the object.", "source": "juraj_google_style"} +{"code": "def shape4d(a, data_format='NHWC'):\n\n s2d = shape2d(a)\n if get_data_format(data_format, False) == 'NHWC':\n return [1] + s2d + [1]\n else:\n return [1, 1] + s2d", "docstring": "Ensuer a 4D shape, to use with 4D symbolic functions.\n\nArgs:\n a: a int or tuple/list of length 2\n\nReturns:\n list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``\n or ``[1, 1, a, a]`` depending on data_format.", "source": "juraj_google_style"} +{"code": "def get_attribute(self, attribute: str) -> 'Node':\n\n matches = [\n value_node for key_node, value_node in self.yaml_node.value\n if key_node.value == attribute\n ]\n if len(matches) != 1:\n raise SeasoningError(\n 'Attribute not found, or found multiple times: {}'.format(\n matches))\n return Node(matches[0])", "docstring": "Returns the node representing the given attribute's value.\n\n Use only if is_mapping() returns true.\n\nArgs:\n attribute: The name of the attribute to retrieve.\n\nRaises:\n KeyError: If the attribute does not exist.\n\nReturns:\n A node representing the value.", "source": "juraj_google_style"} +{"code": "def post_revert_tags(self, post_id, history_id):\n\n params = {'id': post_id, 'history_id': history_id}\n return self._get('post/revert_tags', params, 'PUT')", "docstring": "Function to reverts a post to a previous set of tags\n (Requires login) (UNTESTED).\n\n Parameters:\n post_id (int): The post id number to update.\n history_id (int): The id number of the tag history.", "source": "juraj_google_style"} +{"code": "def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,\n sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:\n r\n square_start = center-width/2\n square_stop = center+width/2\n if zeroed_width:\n zeroed_width = min(width, zeroed_width)\n gauss_zeroed_width = zeroed_width-width\n else:\n gauss_zeroed_width = None\n\n funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma,\n zeroed_width=gauss_zeroed_width, rescale_amp=True),\n functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma,\n zeroed_width=gauss_zeroed_width, rescale_amp=True),\n functools.partial(constant, amp=amp)]\n condlist = [times <= square_start, times >= square_stop]\n return np.piecewise(times.astype(np.complex_), condlist, funclist)", "docstring": "r\"\"\"Continuous gaussian square pulse.\n\nArgs:\n times: Times to output pulse for.\n amp: Pulse amplitude.\n center: Center of the square pulse component.\n width: Width of the square pulse component.\n sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.\n zeroed_width: Subtract baseline of gaussian square pulse\n to enforce $\\OmegaSquare(center \\pm zeroed_width/2)=0$.", "source": "juraj_google_style"} +{"code": "def read(self, n, echo=None):\n\n\n d = self.channel.read(n)\n if echo or (echo is None and self.echo):\n sys.stdout.write(d.decode('latin1'))\n sys.stdout.flush()\n return d", "docstring": "Read *n* bytes from the channel.\n\nArgs:\n n(int): The number of bytes to read from the channel.\n echo(bool): Whether to write the read data to stdout.\n\nReturns:\n bytes: *n* bytes of data.\n\nRaises:\n EOFError: If the channel was closed.", "source": "juraj_google_style"} +{"code": "def run(self, instance):\n\n\n last = instance\n\n for item in self.stack:\n if isinstance(item, str):\n last = getattr(last, item)\n else:\n last = last(*item[0], **item[1])\n\n self.stack = []\n return last", "docstring": "Run the recorded chain of methods on `instance`.\n\nArgs:\n instance: an object.", "source": "juraj_google_style"} +{"code": "def normalize_to_element(self, element, factor=1):\n\n all_comp = self._all_comp\n coeffs = self._coeffs\n current_el_amount = sum([all_comp[i][element] * abs(coeffs[i])\n for i in range(len(all_comp))]) / 2\n scale_factor = factor / current_el_amount\n self._coeffs = [c * scale_factor for c in coeffs]", "docstring": "Normalizes the reaction to one of the elements.\n By default, normalizes such that the amount of the element is 1.\n Another factor can be specified.\n\nArgs:\n element (Element/Specie): Element to normalize to.\n factor (float): Factor to normalize to. Defaults to 1.", "source": "juraj_google_style"} +{"code": "def __init__(self, instrument, probe_name, name = None, info = None, buffer_length = 100):\n\n\n\n assert isinstance(instrument, Instrument)\n assert isinstance(probe_name, str)\n assert probe_name in instrument._PROBES\n\n\n if name is None:\n name = probe_name\n assert isinstance(name, str)\n\n if info is None:\n info = ''\n assert isinstance(info, str)\n\n self.name = name\n self.info = info\n self.instrument = instrument\n self.probe_name = probe_name\n\n self.buffer = deque(maxlen = buffer_length)", "docstring": "creates a probe...\n\nArgs:\n name (optinal): name of probe, if not provided take name of function\n settings (optinal): a Parameter object that contains all the information needed in the script", "source": "juraj_google_style"} +{"code": "def get_contract_state(self, contract_hash, id=None, endpoint=None):\n\n return self._call_endpoint(GET_CONTRACT_STATE, params=[contract_hash], id=id, endpoint=endpoint)", "docstring": "Get a contract state object by its hash\n\nArgs:\n contract_hash: (str) the hash of the contract to lookup, for example 'd7678dd97c000be3f33e9362e673101bac4ca654'\n id: (int, optional) id to use for response tracking\n endpoint: (RPCEndpoint, optional) endpoint to specify to use\n\nReturns:\n json object of the result or the error encountered in the RPC call", "source": "juraj_google_style"} +{"code": "def transpose(self, name=None):\n\n if any(x > 1 for x in self._rate):\n raise base.NotSupportedError(\n \"Cannot transpose a dilated convolution module.\")\n\n if any(p != self._conv_op_padding for p in self._padding):\n raise base.NotSupportedError(\n \"Cannot tranpose a convolution using mixed paddings or paddings \"\n \"other than SAME or VALID.\")\n\n if name is None:\n name = self.module_name + \"_transpose\"\n\n def output_shape():\n if self._data_format == DATA_FORMAT_NCHW:\n return self.input_shape[2:4]\n else: # data_format == DATA_FORMAT_NHWC\n return self.input_shape[1:3]\n\n return Conv2DTranspose(output_channels=lambda: self._input_channels,\n output_shape=output_shape,\n kernel_shape=self._kernel_shape,\n stride=self._stride,\n padding=self._conv_op_padding,\n use_bias=self._use_bias,\n initializers=self._initializers,\n partitioners=self._partitioners,\n regularizers=self._regularizers,\n data_format=self._data_format,\n custom_getter=self._custom_getter,\n name=name)", "docstring": "Returns matching `Conv2DTranspose` module.\n\nArgs:\n name: Optional string assigning name of transpose module. The default name\n is constructed by appending \"_transpose\" to `self.name`.\n\nReturns:\n `Conv2DTranspose` module.\n\nRaises:\n base.NotSupportedError: If `rate` in any dimension > 1.", "source": "juraj_google_style"} +{"code": "def __init__(self, server, pipeline_name, stage_name, pipeline_counter=None):\n\n self.server = server\n self.pipeline_name = pipeline_name\n self.pipeline_counter = pipeline_counter\n self.stage_name = stage_name", "docstring": "A wrapper for the `Go stage API`__\n\n .. __: http://api.go.cd/current/#stages\n\nArgs:\n server (Server): A configured instance of\n :class:gocd.server.Server\n pipeline_name (str): The name of the pipeline we're working on\n stage_name (str): The name of the stage we're working on", "source": "juraj_google_style"} +{"code": "def __init__(\n self,\n cls,\n cls_args,\n kwargs,\n ex,\n ):\n\n msg = \"\\n\".join([\n \"\", # Newline to make the output cleaner\n \"module: {}\".format(cls.__module__),\n \"ctor: {}\".format(cls),\n \"ctor_args: {}\".format(cls_args),\n \"args (after removing args not in ctor_args): {}\".format(kwargs),\n \"only in ctor_args\".format(\n [x for x in cls_args if x not in kwargs]\n ),\n \"exception: {}\".format(ex),\n ])\n Exception.__init__(self, msg)\n self.type = str(\n type(self),\n )\n self.cls = str(cls)\n self.cls_args = str(cls_args)\n self.kwargs = str(kwargs)\n self.ex = str(ex)\n self.type = self.__class__.__name__", "docstring": "Note that type_assert can't be used because it would\n create a circular dependency.\n\nArgs:\n cls, type-or-static-method, The type or constructor\n that was attempted to unmarshal into\n cls_args: list, The arguments of @cls\n kwargs: dict, The arguments that were passed to @cls\n ex: Exception, The exception that was raised", "source": "juraj_google_style"} +{"code": "def record(self):\n # type: () -> bytes\n\n if not self._initialized:\n raise pycdlibexception.PyCdlibInternalError('El Torito Section Header not yet initialized')\n\n outlist = [struct.pack(self.FMT, self.header_indicator,\n self.platform_id, self.num_section_entries,\n self.id_string)]\n\n for entry in self.section_entries:\n outlist.append(entry.record())\n\n return b''.join(outlist)", "docstring": "Get a string representing this El Torito section header.\n\n Parameters:\n None.\n\nReturns:\n A string representing this El Torito section header.", "source": "juraj_google_style"} +{"code": "def parse(self, instr):\n # type: (bytes) -> bool\n\n if self._initialized:\n raise pycdlibexception.PyCdlibInternalError('This IsoHybrid object is already initialized')\n\n if len(instr) != 512:\n raise pycdlibexception.PyCdlibInvalidISO('Invalid size of the instr')\n\n if instr[0:32] == self.ORIG_HEADER:\n self.header = self.ORIG_HEADER\n elif instr[0:32] == self.MAC_AFP:\n self.header = self.MAC_AFP\n else:\n # If we didn't see anything that we expected, then this is not an\n # IsoHybrid ISO, so just quietly return False\n return False\n\n (self.mbr, self.rba, unused1, self.mbr_id,\n unused2) = struct.unpack_from(self.FMT, instr[:32 + struct.calcsize(self.FMT)], 32)\n\n if unused1 != 0:\n raise pycdlibexception.PyCdlibInvalidISO('Invalid IsoHybrid section')\n\n if unused2 != 0:\n raise pycdlibexception.PyCdlibInvalidISO('Invalid IsoHybrid section')\n\n offset = 32 + struct.calcsize(self.FMT)\n for i in range(1, 5):\n if bytes(bytearray([instr[offset]])) == b'\\x80':\n self.part_entry = i\n (const_unused, self.bhead, self.bsect, self.bcyle, self.ptype,\n self.ehead, self.esect, self.ecyle, self.part_offset,\n self.psize) = struct.unpack_from('=BBBBBBBBLL', instr[:offset + 16], offset)\n break\n offset += 16\n else:\n raise pycdlibexception.PyCdlibInvalidISO('No valid partition found in IsoHybrid!')\n\n if bytes(bytearray([instr[-2]])) != b'\\x55' or bytes(bytearray([instr[-1]])) != b'\\xaa':\n raise pycdlibexception.PyCdlibInvalidISO('Invalid tail on isohybrid section')\n\n self.geometry_heads = self.ehead + 1\n # FIXME: I can't see any way to compute the number of sectors from the\n # available information. For now, we just hard-code this at 32 and\n # hope for the best.\n self.geometry_sectors = 32\n\n self._initialized = True\n\n return True", "docstring": "A method to parse ISO hybridization info out of an existing ISO.\n\n Parameters:\n instr - The data for the ISO hybridization.\n\nReturns:\n Nothing.", "source": "juraj_google_style"} +{"code": "def noise_new(\n dim: int,\n h: float = NOISE_DEFAULT_HURST,\n l: float = NOISE_DEFAULT_LACUNARITY, # noqa: E741\n random: Optional[tcod.random.Random] = None,\n) -> tcod.noise.Noise:\n\n return tcod.noise.Noise(dim, hurst=h, lacunarity=l, seed=random)", "docstring": "Return a new Noise instance.\n\nArgs:\n dim (int): Number of dimensions. From 1 to 4.\n h (float): The hurst exponent. Should be in the 0.0-1.0 range.\n l (float): The noise lacunarity.\n random (Optional[Random]): A Random instance, or None.\n\nReturns:\n Noise: The new Noise instance.", "source": "juraj_google_style"} +{"code": "def num_samples(self, sr=None):\n\n native_sr = self.sampling_rate\n num_samples = units.seconds_to_sample(self.duration, native_sr)\n\n if sr is not None:\n ratio = float(sr) / native_sr\n num_samples = int(np.ceil(num_samples * ratio))\n\n return num_samples", "docstring": "Return the number of samples.\n\nArgs:\n sr (int): Calculate the number of samples with the given\n sampling-rate. If None use the native sampling-rate.\n\nReturns:\n int: Number of samples", "source": "juraj_google_style"} +{"code": "def _ExtractDataStream(\n self, file_entry, data_stream_name, destination_path, output_writer,\n skip_duplicates=True):\n\n if not data_stream_name and not file_entry.IsFile():\n return\n\n display_name = path_helper.PathHelper.GetDisplayNameForPathSpec(\n file_entry.path_spec)\n\n if skip_duplicates:\n try:\n digest = self._CalculateDigestHash(file_entry, data_stream_name)\n except (IOError, dfvfs_errors.BackEndError) as exception:\n output_writer.Write((\n '[skipping] unable to read content of file entry: {0:s} '\n 'with error: {1!s}\\n').format(display_name, exception))\n return\n\n if not digest:\n output_writer.Write(\n '[skipping] unable to read content of file entry: {0:s}\\n'.format(\n display_name))\n return\n\n duplicate_display_name = self._digests.get(digest, None)\n if duplicate_display_name:\n output_writer.Write((\n '[skipping] file entry: {0:s} is a duplicate of: {1:s} with '\n 'digest: {2:s}\\n').format(\n display_name, duplicate_display_name, digest))\n return\n\n self._digests[digest] = display_name\n\n target_directory, target_filename = self._CreateSanitizedDestination(\n file_entry, file_entry.path_spec, data_stream_name, destination_path)\n\n if not os.path.isdir(target_directory):\n os.makedirs(target_directory)\n\n target_path = os.path.join(target_directory, target_filename)\n\n if os.path.exists(target_path):\n output_writer.Write((\n '[skipping] unable to export contents of file entry: {0:s} '\n 'because exported file: {1:s} already exists.\\n').format(\n display_name, target_path))\n return\n\n try:\n self._WriteFileEntry(file_entry, data_stream_name, target_path)\n except (IOError, dfvfs_errors.BackEndError) as exception:\n output_writer.Write((\n '[skipping] unable to export contents of file entry: {0:s} '\n 'with error: {1!s}\\n').format(display_name, exception))\n\n try:\n os.remove(target_path)\n except (IOError, OSError):\n pass", "docstring": "Extracts a data stream.\n\nArgs:\n file_entry (dfvfs.FileEntry): file entry containing the data stream.\n data_stream_name (str): name of the data stream.\n destination_path (str): path where the extracted files should be stored.\n output_writer (CLIOutputWriter): output writer.\n skip_duplicates (Optional[bool]): True if files with duplicate content\n should be skipped.", "source": "juraj_google_style"} +{"code": "def _PathStripPrefix(self, path):\n\n if path.startswith('\\\\\\\\.\\\\') or path.startswith('\\\\\\\\?\\\\'):\n if len(path) < 7 or path[5] != ':' or path[6] != self._PATH_SEPARATOR:\n # Cannot handle a non-volume path.\n return None\n\n path = path[7:]\n\n elif path.startswith('\\\\\\\\'):\n # Cannot handle an UNC path.\n return None\n\n elif len(path) >= 3 and path[1] == ':':\n # Check if the path is a Volume 'absolute' path.\n if path[2] != self._PATH_SEPARATOR:\n # Cannot handle a Volume 'relative' path.\n return None\n\n path = path[3:]\n\n elif path.startswith('\\\\'):\n path = path[1:]\n\n else:\n # Cannot handle a relative path.\n return None\n\n return path", "docstring": "Strips the prefix from a path.\n\nArgs:\n path (str): Windows path to strip the prefix from.\n\nReturns:\n str: path without the prefix or None if the path is not supported.", "source": "juraj_google_style"} +{"code": "def filter_object(obj, marks, presumption=DELETE):\n\n if isinstance(obj, list):\n keys = reversed(range(0, len(obj)))\n else:\n keys = obj.keys()\n\n for k in keys:\n v = obj[k]\n m = marks.get(id(v), UNSPECIFIED)\n if m == DELETE:\n del obj[k] # an explicit deletion is irreversible.\n elif m == KEEP or presumption==KEEP:\n # keep descending, in case there are nodes we should delete.\n if isinstance(v, list) or isinstance(v, dict):\n filter_object(v, marks, presumption=KEEP)\n elif m == UNSPECIFIED:\n # ... and presumption == DELETE\n if isinstance(v, list) or isinstance(v, dict):\n filter_object(v, marks, presumption=DELETE)\n if len(v) == 0:\n del obj[k]\n else:\n del obj[k]", "docstring": "Filter down obj based on marks, presuming keys should be kept/deleted.\n\nArgs:\n obj: The object to be filtered. Filtering is done in-place.\n marks: An object mapping id(obj) --> {DELETE,KEEP}\n These values apply to the entire subtree, unless inverted.\n presumption: The default action to take on all keys.", "source": "juraj_google_style"} +{"code": "def check_candidate_exists(self, basepath, candidates):\n\n checked = []\n for item in candidates:\n abspath = os.path.join(basepath, item)\n if os.path.exists(abspath):\n checked.append(abspath)\n\n return checked", "docstring": "Check that at least one candidate exist into a directory.\n\nArgs:\n basepath (str): Directory path where to search for candidate.\n candidates (list): List of candidate file paths.\n\nReturns:\n list: List of existing candidates.", "source": "juraj_google_style"} +{"code": "def __init__(self, param_list):\n\n self.param_list = param_list\n for ps in param_list:\n # ps MUST be ParameterSpace\n logger.info(\"Add %s into SearchSpace\" % ps)", "docstring": "Initialize SearchSpace.\n\nArgs:\n param_list: List of ``ParameterSpace`` (or its subclass).", "source": "juraj_google_style"} +{"code": "def yaml_dump(data, stream=None):\n # type: (YamlData, Optional[TextIO]) -> Text\n\n return yaml.dump(\n data,\n stream=stream,\n Dumper=Dumper,\n default_flow_style=False\n )", "docstring": "Dump data to a YAML string/file.\n\nArgs:\n data (YamlData):\n The data to serialize as YAML.\n stream (TextIO):\n The file-like object to save to. If given, this function will write\n the resulting YAML to that stream.\n\nReturns:\n str: The YAML string.", "source": "juraj_google_style"} +{"code": "def traverse_pagination(response, endpoint, content_filter_query, query_params):\n\n results = response.get('results', [])\n\n page = 1\n while response.get('next'):\n page += 1\n response = endpoint().post(content_filter_query, **dict(query_params, page=page))\n results += response.get('results', [])\n\n return results", "docstring": "Traverse a paginated API response and extracts and concatenates \"results\" returned by API.\n\nArgs:\n response (dict): API response object.\n endpoint (Slumber.Resource): API endpoint object.\n content_filter_query (dict): query parameters used to filter catalog results.\n query_params (dict): query parameters used to paginate results.\n\nReturns:\n list: all the results returned by the API.", "source": "juraj_google_style"} +{"code": "def __init__(self, project_key, conf_path=settings.ZEO_CLIENT_PATH):\n\n super(self.__class__, self).__init__(\n conf_path=conf_path,\n project_key=project_key\n )", "docstring": "Constructor.\n\nArgs:\n project_key (str): Project key which is used for the root of DB.\n conf_path (str): Path to the client zeo configuration file. Default\n :attr:`.settings.ZEO_CLIENT_PATH`.", "source": "juraj_google_style"} +{"code": "def download_folder(bucket_name, prefix, target, sagemaker_session):\n\n boto_session = sagemaker_session.boto_session\n\n s3 = boto_session.resource('s3')\n bucket = s3.Bucket(bucket_name)\n\n prefix = prefix.lstrip('/')\n\n # there is a chance that the prefix points to a file and not a 'directory' if that is the case\n # we should just download it.\n objects = list(bucket.objects.filter(Prefix=prefix))\n\n if len(objects) > 0 and objects[0].key == prefix and prefix[-1] != '/':\n s3.Object(bucket_name, prefix).download_file(os.path.join(target, os.path.basename(prefix)))\n return\n\n # the prefix points to an s3 'directory' download the whole thing\n for obj_sum in bucket.objects.filter(Prefix=prefix):\n # if obj_sum is a folder object skip it.\n if obj_sum.key != '' and obj_sum.key[-1] == '/':\n continue\n obj = s3.Object(obj_sum.bucket_name, obj_sum.key)\n s3_relative_path = obj_sum.key[len(prefix):].lstrip('/')\n file_path = os.path.join(target, s3_relative_path)\n\n try:\n os.makedirs(os.path.dirname(file_path))\n except OSError as exc:\n # EEXIST means the folder already exists, this is safe to skip\n # anything else will be raised.\n if exc.errno != errno.EEXIST:\n raise\n obj.download_file(file_path)", "docstring": "Download a folder from S3 to a local path\n\nArgs:\n bucket_name (str): S3 bucket name\n prefix (str): S3 prefix within the bucket that will be downloaded. Can be a single file.\n target (str): destination path where the downloaded items will be placed\n sagemaker_session (:class:`sagemaker.session.Session`): a sagemaker session to interact with S3.", "source": "juraj_google_style"} +{"code": "def reset_folder(self, folder):\n\n warnings.warn('This is a destructive action that cannot be undone.')\n self.post('reset', data={}, params={'folder': folder})", "docstring": "Erase the database index from a given folder and restart Syncthing.\n\nArgs:\n folder (str): Folder ID.\n\nReturns:\n None", "source": "juraj_google_style"} +{"code": "def codeblocks(start=None, end=None, full=True):\n\n if full:\n for function in functions(start, end):\n fc = FlowChart(f=function.func_t)\n for block in fc:\n yield block\n\n else:\n start, end = fix_addresses(start, end)\n\n for code_block in FlowChart(bounds=(start, end)):\n yield code_block", "docstring": "Get all `CodeBlock`s in a given range.\n\nArgs:\n start - start address of the range. If `None` uses IDB start.\n end - end address of the range. If `None` uses IDB end.\n full - `True` is required to change node info (e.g. color). `False` causes faster iteration.", "source": "juraj_google_style"} +{"code": "def get_items_by_ids(self, item_ids, item_type=None):\n\n urls = [urljoin(self.item_url, F\"{i}.json\") for i in item_ids]\n result = self._run_async(urls=urls)\n items = [Item(r) for r in result if r]\n if item_type:\n return [item for item in items if item.item_type == item_type]\n else:\n return items", "docstring": "Given a list of item ids, return all the Item objects\n\nArgs:\n item_ids (obj): List of item IDs to query\n item_type (str): (optional) Item type to filter results with\n\nReturns:\n List of `Item` objects for given item IDs and given item type", "source": "juraj_google_style"} +{"code": "def get_wallet_height(self, id=None, endpoint=None):\n\n return self._call_endpoint(GET_WALLET_HEIGHT, id=id, endpoint=endpoint)", "docstring": "Get the current wallet index height.\n\nArgs:\n id: (int, optional) id to use for response tracking\n endpoint: (RPCEndpoint, optional) endpoint to specify to use\n\nReturns:\n json object of the result or the error encountered in the RPC call", "source": "juraj_google_style"} +{"code": "def _add_unitary_single(self, gate, qubit):\n\n # Compute einsum index string for 1-qubit matrix multiplication\n indexes = einsum_vecmul_index([qubit], self._number_of_qubits)\n # Convert to complex rank-2 tensor\n gate_tensor = np.array(gate, dtype=complex)\n # Apply matrix multiplication\n self._statevector = np.einsum(indexes, gate_tensor,\n self._statevector,\n dtype=complex,\n casting='no')", "docstring": "Apply an arbitrary 1-qubit unitary matrix.\n\nArgs:\n gate (matrix_like): a single qubit gate matrix\n qubit (int): the qubit to apply gate to", "source": "juraj_google_style"} +{"code": "def computePhase2(self, doLearn=False):\n\n\n # Phase 2: compute predicted state for each cell\n # - if a segment has enough horizontal connections firing because of\n # bottomUpInput, it's set to be predicting, and we queue up the segment\n # for reinforcement,\n # - if pooling is on, try to find the best weakly activated segment to\n # reinforce it, else create a new pooling segment.\n for c in xrange(self.numberOfCols):\n\n buPredicted = False # whether any cell in the column is predicted\n for i in xrange(self.cellsPerColumn):\n # Iterate over each of the segments of this cell\n maxConfidence = 0\n for s in self.cells[c][i]:\n\n # sum(connected synapses) >= activationThreshold?\n if self.isSegmentActive(s, self.activeState['t']):\n\n self.predictedState['t'][c,i] = 1\n buPredicted = True\n maxConfidence = max(maxConfidence, s.dutyCycle(readOnly=True))\n\n if doLearn:\n s.totalActivations += 1 # increment activationFrequency\n s.lastActiveIteration = self.iterationIdx\n # mark this segment for learning\n activeUpdate = self.getSegmentActiveSynapses(c,i,s,'t')\n activeUpdate.phase1Flag = False\n self.addToSegmentUpdates(c, i, activeUpdate)\n\n # Store the max confidence seen among all the weak and strong segments\n # as the cell's confidence.\n self.confidence['t'][c,i] = maxConfidence", "docstring": "This is the phase 2 of learning, inference and multistep prediction. During\n this phase, all the cell with lateral support have their predictedState\n turned on and the firing segments are queued up for updates.\n\n Parameters:\n --------------------------------------------\n doLearn: Boolean flag to queue segment updates during learning\n retval: ?", "source": "juraj_google_style"} +{"code": "def generate_license(args):\n\n\n with open(cwd + licenses_loc + args[2]) as f:\n license = f.read()\n\n license = license.format(name=args[0],\n email=args[1],\n license=args[2],\n project=args[3],\n year=args[5])\n\n with open('LICENSE' + args[4], 'w') as f:\n f.write(license)\n print('licenser: license file added to current directory')", "docstring": "Creates a LICENSE or LICENSE.txt file in the current directory. Reads from\n the 'assets' folder and looks for placeholders enclosed in curly braces.\n\nArgs:\n - (tuple) Name, email, license, project, ext, year", "source": "juraj_google_style"} +{"code": "def make_directory_writable(dirname):\n\n retval = shell_call(['docker', 'run', '-v',\n '{0}:/output_dir'.format(dirname),\n 'busybox:1.27.2',\n 'chmod', '-R', 'a+rwx', '/output_dir'])\n if not retval:\n logging.error('Failed to change permissions on directory: %s', dirname)\n return retval", "docstring": "Makes directory readable and writable by everybody.\n\nArgs:\n dirname: name of the directory\n\nReturns:\n True if operation was successfull\n\n If you run something inside Docker container and it writes files, then\n these files will be written as root user with restricted permissions.\n So to be able to read/modify these files outside of Docker you have to change\n permissions to be world readable and writable.", "source": "juraj_google_style"} +{"code": "def translate_opcodes(code_obj, target):\n\n\n target = get_py_internals(target)\n src_ops = code_obj.disassemble()\n\n dst_opmap = target['opmap']\n dst_ops = []\n\n op_iter = enumerate(src_ops)\n for i, op in op_iter:\n if isinstance(op, pwnypack.bytecode.Label):\n dst_ops.append(op)\n continue\n\n if op.name not in dst_opmap:\n if op.name == 'POP_JUMP_IF_FALSE' and 'JUMP_IF_TRUE' in dst_opmap:\n lbl = pwnypack.bytecode.Label()\n dst_ops.extend([\n pwnypack.bytecode.Op('JUMP_IF_TRUE', lbl),\n pwnypack.bytecode.Op('POP_TOP', None),\n pwnypack.bytecode.Op('JUMP_ABSOLUTE', op.arg),\n lbl,\n pwnypack.bytecode.Op('POP_TOP', None),\n ])\n elif op.name == 'POP_JUMP_IF_TRUE' and 'JUMP_IF_FALSE' in dst_opmap:\n lbl = pwnypack.bytecode.Label()\n dst_ops.extend([\n pwnypack.bytecode.Op('JUMP_IF_FALSE', lbl),\n pwnypack.bytecode.Op('POP_TOP', None),\n pwnypack.bytecode.Op('JUMP_ABSOLUTE', op.arg),\n lbl,\n pwnypack.bytecode.Op('POP_TOP', None),\n ])\n elif op.name == 'JUMP_IF_FALSE' and 'JUMP_IF_FALSE_OR_POP' in dst_opmap and \\\n src_ops[i + 1].name == 'POP_TOP':\n next(op_iter)\n dst_ops.append(pwnypack.bytecode.Op('JUMP_IF_FALSE_OR_POP', op.arg))\n elif op.name == 'JUMP_IF_TRUE' and 'JUMP_IF_TRUE_OR_POP' in dst_opmap and \\\n src_ops[i + 1].name == 'POP_TOP':\n next(op_iter)\n dst_ops.append(pwnypack.bytecode.Op('JUMP_IF_TRUE_OR_POP', op.arg))\n else:\n raise SyntaxError('Opcode %s not supported on target.' % op.name)\n else:\n dst_ops.append(op)\n\n code_obj.assemble(dst_ops, target)", "docstring": "Very crude inter-python version opcode translator. Raises SyntaxError when\n the opcode doesn't exist in the destination opmap. Used to transcribe\n python code objects between python versions.\n\nArgs:\n code_obj(pwnypack.bytecode.CodeObject): The code object representation\n to translate.\n target(dict): The py_internals structure for the target\n python version.", "source": "juraj_google_style"} +{"code": "def setRelay(self, seconds, relay, status, password=\"00000000\"):\n\n result = False\n self.setContext(\"setRelay\")\n try:\n self.clearCmdMsg()\n\n if len(password) != 8:\n self.writeCmdMsg(\"Invalid password length.\")\n self.setContext(\"\")\n return result\n\n if seconds < 0 or seconds > 9999:\n self.writeCmdMsg(\"Relay duration must be between 0 and 9999.\")\n self.setContext(\"\")\n return result\n\n if not self.requestA():\n self.writeCmdMsg(\"Bad read CRC on setting\")\n else:\n if not self.serialCmdPwdAuth(password):\n self.writeCmdMsg(\"Password failure\")\n else:\n req_str = \"\"\n req_str = (\"01573102303038\" +\n binascii.hexlify(str(relay)).zfill(2) +\n \"28\" +\n binascii.hexlify(str(status)).zfill(2) +\n binascii.hexlify(str(seconds).zfill(4)) + \"2903\")\n req_str += self.calc_crc16(req_str[2:].decode(\"hex\"))\n self.m_serial_port.write(req_str.decode(\"hex\"))\n if self.m_serial_port.getResponse(self.getContext()).encode(\"hex\") == \"06\":\n self.writeCmdMsg(\"Success: 06 returned.\")\n result = True\n self.serialPostEnd()\n except:\n ekm_log(traceback.format_exc(sys.exc_info()))\n\n self.setContext(\"\")\n return result", "docstring": "Serial call to set relay.\n\nArgs:\n seconds (int): Seconds to hold, ero is hold forever. See :class:`~ekmmeters.RelayInterval`.\n relay (int): Selected relay, see :class:`~ekmmeters.Relay`.\n status (int): Status to set, see :class:`~ekmmeters.RelayState`\n password (str): Optional password\n\nReturns:\n bool: True on completion and ACK.", "source": "juraj_google_style"} +{"code": "def get_eligible_features(examples, num_mutants):\n\n features_dict = (\n get_numeric_features_to_observed_range(\n examples))\n\n features_dict.update(\n get_categorical_features_to_sampling(\n examples, num_mutants))\n\n # Massage the features_dict into a sorted list before returning because\n # Polymer dom-repeat needs a list.\n features_list = []\n for k, v in sorted(features_dict.items()):\n v['name'] = k\n features_list.append(v)\n return features_list", "docstring": "Returns a list of JSON objects for each feature in the examples.\n\n This list is used to drive partial dependence plots in the plugin.\n\nArgs:\n examples: Examples to examine to determine the eligible features.\n num_mutants: The number of mutations to make over each feature.\n\nReturns:\n A list with a JSON object for each feature.\n Numeric features are represented as {name: observedMin: observedMax:}.\n Categorical features are repesented as {name: samples:[]}.", "source": "juraj_google_style"} +{"code": "def leaves(self, nodes=None, unique=True):\n\n if nodes is None:\n return super(DependencyTree, self).leaves(unique=unique)\n\n res = list()\n for child_id in nodes:\n for sub_child in self._all_nodes[child_id].leaves(unique=unique):\n if not unique or sub_child not in res:\n res.append(sub_child)\n return res", "docstring": "Get the leaves of the tree starting at this root.\n\nArgs:\n nodes (iterable): limit leaves for these node names\n unique: only include individual leaf nodes once\n\nReturns:\n list of leaf nodes", "source": "juraj_google_style"} +{"code": "def execute(self, action):\n\n next_state, rew, done, _ = self.env.step(action)\n return next_state, rew, done", "docstring": "Executes action, observes next state and reward.\n\nArgs:\n actions: Actions to execute.\n\nReturns:\n Tuple of (next state, bool indicating terminal, reward)", "source": "juraj_google_style"} +{"code": "def ReadResponses(self, request_list, timestamp=None):\n\n\n response_subjects = {}\n for request in request_list:\n response_subject = self.GetFlowResponseSubject(request.session_id,\n request.id)\n response_subjects[response_subject] = request\n\n response_data = dict(\n self.MultiResolvePrefix(\n response_subjects, self.FLOW_RESPONSE_PREFIX, timestamp=timestamp))\n\n for response_urn, request in sorted(iteritems(response_subjects)):\n responses = []\n for _, serialized, timestamp in response_data.get(response_urn, []):\n msg = rdf_flows.GrrMessage.FromSerializedString(serialized)\n msg.timestamp = timestamp\n responses.append(msg)\n\n yield (request, sorted(responses, key=lambda msg: msg.response_id))", "docstring": "Reads responses for multiple requests at the same time.\n\nArgs:\n request_list: The list of requests the responses should be fetched for.\n timestamp: A timestamp as used in the data store.\n\nYields:\n tuples (request, lists of fetched responses for the request)", "source": "juraj_google_style"} +{"code": "def enable(self, information, id_or_uri, timeout=-1):\n\n\n uri = self._client.build_uri(id_or_uri)\n\n return self._client.update(information, uri, timeout=timeout)", "docstring": "Enables or disables a range.\n\nArgs:\n information (dict): Information to update.\n id_or_uri: ID or URI of range.\n timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation\n in OneView; it just stops waiting for its completion.\n\nReturns:\n dict: Updated resource.", "source": "juraj_google_style"} +{"code": "def _Open(self, path_spec=None, mode='rb'):\n\n if not path_spec:\n raise ValueError('Missing path specification.')\n\n if not path_spec.HasParent():\n raise errors.PathSpecError(\n 'Unsupported path specification without parent.')\n\n table_name = getattr(path_spec, 'table_name', None)\n if table_name is None:\n raise errors.PathSpecError('Path specification missing table name.')\n\n column_name = getattr(path_spec, 'column_name', None)\n if column_name is None:\n raise errors.PathSpecError('Path specification missing column name.')\n\n row_condition = getattr(path_spec, 'row_condition', None)\n if row_condition:\n if not isinstance(row_condition, tuple) or len(row_condition) != 3:\n raise errors.PathSpecError((\n 'Unsupported row_condition not a tuple in the form: '\n '(column_name, operator, value).'))\n\n row_index = getattr(path_spec, 'row_index', None)\n if row_index is not None:\n if not isinstance(row_index, py2to3.INTEGER_TYPES):\n raise errors.PathSpecError(\n 'Unsupported row_index not of integer type.')\n\n if not row_condition and row_index is None:\n raise errors.PathSpecError(\n 'Path specification requires either a row_condition or row_index.')\n\n if self._database_object:\n raise IOError('Database file already set.')\n\n file_object = resolver.Resolver.OpenFileObject(\n path_spec.parent, resolver_context=self._resolver_context)\n\n try:\n database_object = sqlite_database.SQLiteDatabaseFile()\n database_object.Open(file_object)\n finally:\n file_object.close()\n\n # Sanity check the table and column names.\n error_string = ''\n if not database_object.HasTable(table_name):\n error_string = 'Missing table: {0:s}'.format(table_name)\n\n elif not database_object.HasColumn(table_name, column_name):\n error_string = 'Missing column: {0:s} in table: {1:s}'.format(\n column_name, table_name)\n\n elif not row_condition:\n query = 'SELECT {0:s} FROM {1:s} LIMIT 1 OFFSET {2:d}'.format(\n column_name, table_name, row_index)\n rows = database_object.Query(query)\n\n elif not database_object.HasColumn(table_name, row_condition[0]):\n error_string = (\n 'Missing row condition column: {0:s} in table: {1:s}'.format(\n row_condition[0], table_name))\n\n elif row_condition[1] not in self._OPERATORS:\n error_string = (\n 'Unsupported row condition operator: {0:s}.'.format(\n row_condition[1]))\n\n else:\n query = 'SELECT {0:s} FROM {1:s} WHERE {2:s} {3:s} ?'.format(\n column_name, table_name, row_condition[0], row_condition[1])\n rows = database_object.Query(query, parameters=(row_condition[2], ))\n\n # Make sure the query returns a single row, using cursor.rowcount\n # is not reliable for this purpose.\n if not error_string and (len(rows) != 1 or len(rows[0]) != 1):\n if not row_condition:\n error_string = (\n 'Unable to open blob in table: {0:s} and column: {1:s} '\n 'for row: {2:d}.').format(table_name, column_name, row_index)\n\n else:\n row_condition_string = ' '.join([\n '{0!s}'.format(value) for value in iter(row_condition)])\n error_string = (\n 'Unable to open blob in table: {0:s} and column: {1:s} '\n 'where: {2:s}.').format(\n table_name, column_name, row_condition_string)\n\n if error_string:\n database_object.Close()\n raise IOError(error_string)\n\n self._blob = rows[0][0]\n self._current_offset = 0\n self._database_object = database_object\n self._size = len(self._blob)\n self._table_name = table_name", "docstring": "Opens the file-like object defined by path specification.\n\nArgs:\n path_spec (PathSpec): path specification.\n mode (Optional[str]): file access mode.\n\nRaises:\n AccessError: if the access to open the file was denied.\n IOError: if the file-like object could not be opened.\n OSError: if the file-like object could not be opened.\n PathSpecError: if the path specification is incorrect.\n ValueError: if the path specification is invalid.", "source": "juraj_google_style"} +{"code": "def FileEntryExistsByPathSpec(self, path_spec):\n\n location = getattr(path_spec, 'location', None)\n\n if location is None:\n return False\n\n is_device = False\n if platform.system() == 'Windows':\n # Note that os.path.exists() returns False for Windows device files so\n # instead use libsmdev to do the check.\n try:\n is_device = pysmdev.check_device(location)\n except IOError as exception:\n # Since pysmdev will raise IOError when it has no access to the device\n # we check if the exception message contains ' access denied ' and\n # return true.\n\n # Note that exception.message no longer works in Python 3.\n exception_string = str(exception)\n if not isinstance(exception_string, py2to3.UNICODE_TYPE):\n exception_string = py2to3.UNICODE_TYPE(\n exception_string, errors='replace')\n\n if ' access denied ' in exception_string:\n is_device = True\n\n # Note that os.path.exists() returns False for broken symbolic links hence\n # an additional check using os.path.islink() is necessary.\n return is_device or os.path.exists(location) or os.path.islink(location)", "docstring": "Determines if a file entry for a path specification exists.\n\nArgs:\n path_spec (PathSpec): a path specification.\n\nReturns:\n bool: True if the file entry exists, false otherwise.", "source": "juraj_google_style"} +{"code": "def clear(self, keep_attrs=False):\n\n if not keep_attrs:\n for a in (self.graph_attr, self.node_attr, self.edge_attr):\n a.clear()\n del self.body[:]", "docstring": "Reset content to an empty body, clear graph/node/egde_attr mappings.\n\nArgs:\n keep_attrs (bool): preserve graph/node/egde_attr mappings", "source": "juraj_google_style"} +{"code": "def disconnect_async(self, conn_id, callback):\n\n\n found_handle = None\n # Find the handle by connection id\n for handle, conn in self._connections.items():\n if conn['connection_id'] == conn_id:\n found_handle = handle\n\n if found_handle is None:\n callback(conn_id, self.id, False, 'Invalid connection_id')\n return\n\n self._command_task.async_command(['_disconnect', found_handle], self._on_disconnect,\n {'connection_id': conn_id, 'handle': found_handle,\n 'callback': callback})", "docstring": "Asynchronously disconnect from a device that has previously been connected\n\nArgs:\n conn_id (int): a unique identifier for this connection on the DeviceManager\n that owns this adapter.\n callback (callable): A function called as callback(conn_id, adapter_id, success, failure_reason)\n when the disconnection finishes. Disconnection can only either succeed or timeout.", "source": "juraj_google_style"} +{"code": "def _CreateLineReader(self, file_object):\n\n # The Python 2 csv module reads bytes and the Python 3 csv module Unicode\n # reads strings.\n if py2to3.PY_3:\n line_reader = text_file.TextFile(\n file_object, encoding=self._encoding, end_of_line=self._end_of_line)\n\n # pylint: disable=protected-access\n maximum_read_buffer_size = line_reader._MAXIMUM_READ_BUFFER_SIZE\n\n else:\n line_reader = line_reader_file.BinaryLineReader(\n file_object, end_of_line=self._end_of_line)\n\n maximum_read_buffer_size = line_reader.MAXIMUM_READ_BUFFER_SIZE\n\n # Line length is one less than the maximum read buffer size so that we\n # tell if there's a line that doesn't end at the end before the end of\n # the file.\n if self._maximum_line_length > maximum_read_buffer_size:\n self._maximum_line_length = maximum_read_buffer_size - 1\n\n # If we specifically define a number of lines we should skip, do that here.\n for _ in range(0, self.NUMBER_OF_HEADER_LINES):\n line_reader.readline(self._maximum_line_length)\n return line_reader", "docstring": "Creates an object that reads lines from a text file.\n\n The line reader is advanced to the beginning of the DSV content, skipping\n any header lines.\n\nArgs:\n file_object (dfvfs.FileIO): file-like object.\n\nReturns:\n TextFile|BinaryLineReader: an object that implements an iterator\n over lines in a text file.\n\nRaises:\n UnicodeDecodeError: if the file cannot be read with the specified\n encoding.", "source": "juraj_google_style"} +{"code": "def _sendline(self, line):\n\n logging.info('%s: sending line', self.port)\n # clear buffer\n self._lines = []\n try:\n self._read()\n except socket.error:\n logging.debug('%s: Nothing cleared', self.port)\n\n print 'sending [%s]' % line\n self._write(line + '\\r\\n')\n\n # wait for write to complete\n time.sleep(0.1)", "docstring": "Send exactly one line to the device\n\nArgs:\n line str: data send to device", "source": "juraj_google_style"} +{"code": "def select_by_value(self, value):\n\n self._selected_key = None\n self._selected_item = None\n for k in self.children:\n item = self.children[k]\n item.attributes['selected'] = False\n if value == item.get_value():\n self._selected_key = k\n self._selected_item = item\n self._selected_item.attributes['selected'] = True", "docstring": "Selects an item by the text content of the child.\n\nArgs:\n value (str): Text content of the item that have to be selected.", "source": "juraj_google_style"} +{"code": "def _internal_add(self, pattern: Pattern, label, renaming) -> int:\n\n pattern_index = len(self.patterns)\n renamed_constraints = [c.with_renamed_vars(renaming) for c in pattern.local_constraints]\n constraint_indices = [self._add_constraint(c, pattern_index) for c in renamed_constraints]\n self.patterns.append((pattern, label, constraint_indices))\n self.pattern_vars.append(renaming)\n pattern = rename_variables(pattern.expression, renaming)\n state = self.root\n patterns_stack = [deque([pattern])]\n\n self._process_pattern_stack(state, patterns_stack, renamed_constraints, pattern_index)\n\n return pattern_index", "docstring": "Add a new pattern to the matcher.\n\n Equivalent patterns are not added again. However, patterns that are structurally equivalent,\n but have different constraints or different variable names are distinguished by the matcher.\n\nArgs:\n pattern: The pattern to add.\n\nReturns:\n The internal id for the pattern. This is mainly used by the :class:`CommutativeMatcher`.", "source": "juraj_google_style"} +{"code": "def load(fin, dtype=np.float32, max_vocab=None):\n\n vocab = {}\n arr = None\n i = 0\n for line in fin:\n if max_vocab is not None and i >= max_vocab:\n break\n try:\n token, v = _parse_line(line, dtype)\n except (ValueError, IndexError):\n raise ParseError(b'Parsing error in line: ' + line)\n if token in vocab:\n parse_warn(b'Duplicated vocabulary ' + token)\n continue\n if arr is None:\n arr = np.array(v, dtype=dtype).reshape(1, -1)\n else:\n if arr.shape[1] != len(v):\n raise ParseError(b'Vector size did not match in line: ' + line)\n arr = np.append(arr, [v], axis=0)\n vocab[token] = i\n i += 1\n return arr, vocab", "docstring": "Load word embedding file.\n\nArgs:\n fin (File): File object to read. File should be open for reading ascii.\n dtype (numpy.dtype): Element data type to use for the array.\n max_vocab (int): Number of vocabulary to read.\n\nReturns:\n numpy.ndarray: Word embedding representation vectors\n dict: Mapping from words to vector indices.", "source": "juraj_google_style"} +{"code": "def process_tag(self, tag_proc_name, tag):\n\n tag_processor = self.tag_procs[tag_proc_name]\n\n db_entry = (tag_processor.get_name(tag),\n tag_processor.get_entry_type(tag),\n tag_processor.get_filename(tag))\n\n self.zeal_db.insert(*db_entry)\n\n self.entry_count += 1", "docstring": "Process a tag with a tag processor and insert a DB entry.\n\nArgs:\n tag_proc_name: A string key that maps to the TagProcessor to use.\n tag: A BeautifulSoup Tag to process.", "source": "juraj_google_style"} +{"code": "def add_curves_from_las(self, fname, remap=None, funcs=None):\n\n try: # To treat as a single file\n self.add_curves_from_lasio(lasio.read(fname),\n remap=remap,\n funcs=funcs\n )\n except: # It's a list!\n for f in fname:\n self.add_curves_from_lasio(lasio.read(f),\n remap=remap,\n funcs=funcs\n )\n\n return None", "docstring": "Given a LAS file, add curves from it to the current well instance.\n Essentially just wraps ``add_curves_from_lasio()``.\n\nArgs:\n fname (str): The path of the LAS file to read curves from.\n remap (dict): Optional. A dict of 'old': 'new' LAS field names.\n funcs (dict): Optional. A dict of 'las field': function() for\n implementing a transform before loading. Can be a lambda.\n\nReturns:\n None. Works in place.", "source": "juraj_google_style"} +{"code": "def List(self, device_path):\n\n connection = self.protocol_handler.Open(self._handle, destination=b'sync:')\n listing = self.filesync_handler.List(connection, device_path)\n connection.Close()\n return listing", "docstring": "Return a directory listing of the given path.\n\nArgs:\n device_path: Directory to list.", "source": "juraj_google_style"} +{"code": "def bind(self, devices_to_bind):\n\n if self.entity_api_key == \"\":\n return {'status': 'failure', 'response': 'No API key found in request'}\n url = self.base_url + \"api/0.1.0/subscribe/bind\"\n headers = {\"apikey\": self.entity_api_key}\n data = {\n \"exchange\": \"amq.topic\",\n \"keys\": devices_to_bind,\n \"queue\": self.entity_id\n }\n\n with self.no_ssl_verification():\n r = requests.post(url, json=data, headers=headers)\n response = dict()\n if \"No API key\" in str(r.content.decode(\"utf-8\")):\n response[\"status\"] = \"failure\"\n r = json.loads(r.content.decode(\"utf-8\"))['message']\n elif 'bind queue ok' in str(r.content.decode(\"utf-8\")):\n response[\"status\"] = \"success\"\n r = r.content.decode(\"utf-8\")\n else:\n response[\"status\"] = \"failure\"\n r = r.content.decode(\"utf-8\")\n response[\"response\"] = str(r)\n return response", "docstring": "This function allows an entity to list the devices to subscribe for data. This function must be called\n at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here.\n\nArgs:\n devices_to_bind (list): an array of devices to listen to.\n Example bind([\"test100\",\"testDemo\"])", "source": "juraj_google_style"} +{"code": "def get_fieldset_index(fieldsets, index_or_name):\n\n if isinstance(index_or_name, six.integer_types):\n return index_or_name\n\n for key, value in enumerate(fieldsets):\n if value[0] == index_or_name:\n return key\n\n raise KeyError(\"Key not found: '{}'.\".format(index_or_name))", "docstring": "Return the index of a fieldset in the ``fieldsets`` list.\n\nArgs:\n fieldsets (list): The original ``fieldsets`` list.\n index_or_name (int or str): The value of the reference element, or directly its numeric index.\n\nReturns:\n (int) The index of the fieldset in the ``fieldsets`` list.", "source": "juraj_google_style"} +{"code": "def export_to_tf_tensor(self, x, laid_out_x):\n\n return self.combine_slices(laid_out_x.all_slices, x.shape)", "docstring": "Turn a Tensor into a tf.Tensor.\n\nArgs:\n x: a Tensor\n laid_out_x: a LaidOutTensor\n\nReturns:\n a tf.Tensor", "source": "juraj_google_style"} +{"code": "def _UpdateSudoer(self, user, sudoer=False):\n\n if sudoer:\n self.logger.info('Adding user %s to the Google sudoers group.', user)\n command = self.gpasswd_add_cmd.format(\n user=user, group=self.google_sudoers_group)\n else:\n self.logger.info('Removing user %s from the Google sudoers group.', user)\n command = self.gpasswd_remove_cmd.format(\n user=user, group=self.google_sudoers_group)\n\n try:\n subprocess.check_call(command.split(' '))\n except subprocess.CalledProcessError as e:\n self.logger.warning('Could not update user %s. %s.', user, str(e))\n return False\n else:\n self.logger.debug('Removed user %s from the Google sudoers group.', user)\n return True", "docstring": "Update sudoer group membership for a Linux user account.\n\nArgs:\n user: string, the name of the Linux user account.\n sudoer: bool, True if the user should be a sudoer.\n\nReturns:\n bool, True if user update succeeded.", "source": "juraj_google_style"} +{"code": "def struct_member_error(err, sid, name, offset, size):\n\n exception, msg = STRUCT_ERROR_MAP[err]\n struct_name = idc.GetStrucName(sid)\n return exception(('AddStructMember(struct=\"{}\", member=\"{}\", offset={}, size={}) '\n 'failed: {}').format(\n struct_name,\n name,\n offset,\n size,\n msg\n ))", "docstring": "Create and format a struct member exception.\n\nArgs:\n err: The error value returned from struct member creation\n sid: The struct id\n name: The member name\n offset: Memeber offset\n size: Member size\n\nReturns:\n A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an\n informative message.", "source": "juraj_google_style"} +{"code": "def _or_join(self, terms):\n\n\n if isinstance(terms, (tuple, list)):\n if len(terms) > 1:\n return '(' + ' OR '.join(terms) + ')'\n else:\n return terms[0]\n else:\n return terms", "docstring": "Joins terms using OR operator.\n\nArgs:\n terms (list): terms to join\n\nExample:\n self._or_join(['term1', 'term2']) -> 'term1 OR term2'\n\nReturns:\n str", "source": "juraj_google_style"} +{"code": "def on_connection_state_change(self, event_type, callback):\n\n listeners = self._connection_state_listeners.get(event_type, [])\n listeners.append(callback)\n self._connection_state_listeners[event_type] = listeners", "docstring": "Register a callback for a specific connection state change.\n\n Register a callback to be triggered when the connection changes to\n the specified state, signified by a ConnectionEvent.\n\n The callback must be a coroutine.\n\nArgs:\n event_type (ConnectionEvent): the connection event to listen for\n callback (coroutine): a coroutine to call on the event occurrence", "source": "juraj_google_style"} +{"code": "def setAccessPolicy(self, pid, accessPolicy, serialVersion, vendorSpecific=None):\n\n response = self.setAccessPolicyResponse(\n pid, accessPolicy, serialVersion, vendorSpecific\n )\n return self._read_boolean_response(response)", "docstring": "See Also: setAccessPolicyResponse()\n\nArgs:\n pid:\n accessPolicy:\n serialVersion:\n vendorSpecific:\n\n Returns:", "source": "juraj_google_style"} +{"code": "def QA_util_make_hour_index(day, type_='1h'):\n\n\n if QA_util_if_trade(day) is True:\n return pd.date_range(\n str(day) + ' 09:30:00',\n str(day) + ' 11:30:00',\n freq=type_,\n closed='right'\n ).append(\n pd.date_range(\n str(day) + ' 13:00:00',\n str(day) + ' 15:00:00',\n freq=type_,\n closed='right'\n )\n )\n else:\n return pd.DataFrame(['No trade'])", "docstring": "创建股票的小时线的index\n\nArgs:\n day {[type]} -- [description]\n\nReturns:\n [type] -- [description]", "source": "juraj_google_style"} +{"code": "def add_file_to_tree(tree, file_path, file_contents, is_executable=False):\n\n record = {\n \"path\": file_path,\n \"mode\": \"100755\" if is_executable else \"100644\",\n \"type\": \"blob\",\n \"content\": file_contents,\n }\n tree.append(record)\n return tree", "docstring": "Add a file to a tree.\n\nArgs:\n tree\n A list of dicts containing info about each blob in a tree.\n\n file_path\n The path of the new file in the tree.\n\n file_contents\n The (UTF-8 encoded) contents of the new file.\n\n is_executable\n If ``True``, the new file will get executable permissions (0755).\n Otherwise, it will get 0644 permissions.\n\nReturns:\n The provided tree, but with the new file added.", "source": "juraj_google_style"} +{"code": "def GetSubkeyByIndex(self, index):\n\n subkeys = list(self._subkeys.values())\n\n if index < 0 or index >= len(subkeys):\n raise IndexError('Index out of bounds.')\n\n return subkeys[index]", "docstring": "Retrieves a subkey by index.\n\nArgs:\n index (int): index of the subkey.\n\nReturns:\n WinRegistryKey: Windows Registry subkey or None if not found.\n\nRaises:\n IndexError: if the index is out of bounds.", "source": "juraj_google_style"} +{"code": "def create_tree(tree):\n\n # Create tree\n config.LOGGER.info(\"\\nCreating tree on Kolibri Studio...\")\n channel_id, channel_link = tree.upload_tree()\n # channel_id, channel_link = tree.upload_channel_structure()\n\n return channel_link, channel_id", "docstring": "create_tree: Upload tree to Kolibri Studio\n\nArgs:\n tree (ChannelManager): manager to handle communication to Kolibri Studio\n Returns: channel id of created channel and link to channel", "source": "juraj_google_style"} +{"code": "def build_exon(exon_info, build='37'):\n\n\n try:\n chrom = exon_info['chrom']\n except KeyError:\n raise KeyError(\"Exons has to have a chromosome\")\n\n try:\n start = int(exon_info['start'])\n except KeyError:\n raise KeyError(\"Exon has to have a start\")\n except TypeError:\n raise TypeError(\"Exon start has to be integer\")\n\n try:\n end = int(exon_info['end'])\n except KeyError:\n raise KeyError(\"Exon has to have a end\")\n except TypeError:\n raise TypeError(\"Exon end has to be integer\")\n\n try:\n rank = int(exon_info['rank'])\n except KeyError:\n raise KeyError(\"Exon has to have a rank\")\n except TypeError:\n raise TypeError(\"Exon rank has to be integer\")\n\n try:\n exon_id = exon_info['exon_id']\n except KeyError:\n raise KeyError(\"Exons has to have a id\")\n\n try:\n transcript = exon_info['transcript']\n except KeyError:\n raise KeyError(\"Exons has to have a transcript\")\n\n try:\n hgnc_id = int(exon_info['hgnc_id'])\n except KeyError:\n raise KeyError(\"Exons has to have a hgnc_id\")\n except TypeError:\n raise TypeError(\"hgnc_id has to be integer\")\n\n exon_obj = Exon(\n exon_id = exon_id,\n chrom = chrom,\n start = start,\n end = end,\n rank = rank,\n transcript = transcript,\n hgnc_id = hgnc_id,\n build = build,\n )\n\n return exon_obj", "docstring": "Build a Exon object object\n\nArgs:\n exon_info(dict): Exon information\n\nReturns:\n exon_obj(Exon)\n\n \"exon_id\": str, # str(chrom-start-end)\n \"chrom\": str,\n \"start\": int,\n \"end\": int,\n \"transcript\": str, # ENST ID\n \"hgnc_id\": int, # HGNC_id\n \"rank\": int, # Order of exon in transcript\n \"build\": str, # Genome build", "source": "juraj_google_style"}