content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def process_data(data_json, key1, renamed1, key2, renamed2, key3, renamed3,
key4, renamed4, key5, renamed5, key6="", renamed6=""):
"""Converts our list of dictionaries to a dictionary of lists,
while processing some of the data points (e.g. converting number strings
to ints and float, as we... | 120b13b0d4851ba8c351e7654372f068ed241590 | 236,517 |
def get_run_info_nextseq500( instrument_model, application_version, tree ):
"""
Helper function to get some info about the sequencing runs.
Args:
tree: xml tree
Returns:
dict: basic statistics about run, like date, instrument, number of lanes, flowcell ID, read lengths, etc.
"""
... | e2ff69ef20282692c43cc08047c971e1a0106b98 | 640,845 |
def asfrozenset(term):
"""Convert to frozenset if it is not already"""
return term if isinstance(term, frozenset) else frozenset(term) | 7f5e946ad245d64bb8979de078bf000df06171ae | 470,526 |
def livetime(match, hits):
"""Calculate the livetime represented by a set of simulation data.
Required argument for MongoSimsDB.
Note that `match.emissionrate` can be given a weight when registered by
`query`, so don't apply any weight here
Args:
match (SimDataMatch): info requested from m... | a608d4671d6ff1e9b0c9ccd1a8cf465f98852c20 | 566,237 |
def translate_error(error, translation_list, format_str=None):
"""Translates error or returns original error if no matches.
Note, an error will be translated if it is a child class of a value in
translation_list. Also, translations earlier in the list take priority.
Args:
error (Exception): Error to trans... | 9e717ac8978f11d120fd78aaff86dfc84bb1f56f | 118,558 |
def get_blue_green_from_app(app):
"""
Returns the blue_green object if exists and it's color field if exists
>>> get_blue_green_from_app({})
(None, None)
>>> get_blue_green_from_app({'blue_green': None})
(None, None)
>>> get_blue_green_from_app({'blue_green': {}})
(None, None)
>>... | c24c297f300fd4978aa1fd28245d835ef01ff387 | 683,763 |
def generate_label_asm(label, address):
"""
Return label definition text at a given address.
Format: '{label}: ; {address}'
"""
label_text = '%s: ; %x' % (label, address)
return (address, label_text, address) | 249653b5a37f83601c49c8876ea10027d3118aa1 | 463,551 |
import re
def has_numbers(string):
"""
Check if user's message has a number
:param string: User's message
:return: True/False (boolean)
"""
return bool(re.search(r'\d', string)) | 3ee518d8278513214334709839a106b958ff6797 | 167,208 |
def get_domain(entity_id):
"""Get domain portion of entity id."""
return entity_id.split('.')[0] | 8f94dc85cc6379dd2cd6807d6382d39551549207 | 415,095 |
def nearest_neighbor_interpolation(points):
"""
Input: list of points (x, y).
Returns a function f(x) which returns y value of nearest neighbor for given
x. At the midpoints (when distances to 2 closest points are the same) value
of point with lower x value is returned.
"""
points.sort(key=l... | 992e385d91a722989aef6c8f962863ddc46d6d25 | 646,768 |
def safe_union_two_by_name(df1, df2):
"""Combine common fields from two dataframes rowwise.
Note we do not use the ``pyspark.sql.DataFrame.unionByName``
function here because we explicitly reorder columns to the
order of ``take``.
Parameters
----------
df1 : pyspark.sql.DataFrame
f... | 82a341c995c9158010d1576b2e2c4c6faadfe606 | 665,324 |
import re
def lowercase(s, _sub=re.compile('[A-Z]').sub,
_repl=(lambda m: '.' + m.group(0).lower()), _cache={}):
"""Convert to lowercase with dots.
>>> lowercase('ResCompany')
'res.company'
"""
try:
return _cache[s]
except KeyError:
_cache[s] = s = _sub(_repl, s)... | 9a3c5f5ce49f95fa131313a2e4d06ba7e38105ad | 433,545 |
def fill_big_gaps(array, gap_size):
"""
Insert values into the given sorted list if there is a gap of more than ``gap_size``.
All values in the given array are preserved, even if they are within the ``gap_size`` of one another.
>>> fill_big_gaps([1, 2, 4], gap_size=0.75)
[1, 1.75, 2, 2.75, 3.5, 4]
... | 11ecb164b9e54c75db249ca27cbbdd582ed47945 | 696,201 |
def has_afg_license(instr):
"""Returns True if the first license includes an AFG license"""
return "AFG" in instr.query("LIC:ITEM? 0").strip().split('"')[3].split(",") | 0b9b2d65b7f910d3a4e412f67c76c5333d4f7d7b | 50,403 |
def limit(self, start_or_stop=None, stop=None, step=None):
"""
Create a new table with fewer rows.
See also: Python's builtin :func:`slice`.
:param start_or_stop:
If the only argument, then how many rows to include, otherwise,
the index of the first row to include.
:param stop:
... | b101ed9eba1b5771b7acbd555ae41c4365cea1d3 | 18,471 |
from typing import Union
from typing import Any
def lastindexof(x: Union[str, list], value: Any) -> int:
"""
For string input, returns the last index of substring in the input string.
For array input, returns the last index of value in the input array.
"""
if isinstance(x, str):
return x.r... | 0b8b4e1f4f7a795dff9b07db98afe721d049f298 | 447,790 |
import re
def parse_config_mirror_session_no_destination_interface(raw_result):
"""
Parse the 'no destination interface' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: str
:return: the raw string, no parsing
"""
show_re = (
r'Destination interface rem... | 6c900b36a3ac054ed4f265e4985af84e7fe5c6e1 | 255,661 |
import math
def extract_blob(blob, image):
""" Extract the pixels that make up the blob's neighbourhood
:param blob: the blob to extract
:param image: the image to extract the blob from
:returns: extracted square neighbourhood
"""
y, x, r = blob
hs, he = y - math.floor(r), y + math.floor(... | 6de6b8a959c81e56dc2bbf7d70460f0852a1622d | 329,155 |
def opinion(simulation):
""" Returns the opinion vector of a simulation. """
return simulation.S | 9bc3e155427bff98a2fb2f8082b7c6540099f6cf | 166,483 |
def create_property_array(df_column, property_mapping, current_value):
"""
Create a query JSON 'properties' array
Creates the properties array necessary for when the property_mapping is defined.
Args:
df_column (Series): A pandas Series to reconcile.
property_mapping (dict): The proper... | 2acb56529b5de6d066be406b99958fcd515d9150 | 259,637 |
from typing import Tuple
def parse_chunk(chunk: str) -> Tuple[str, int]:
"""Parse a chunk for rule name and error count.
:param chunk: The chunk of logs to process.
:returns: The rule name and count of errors found.
:raises ValueError: if a rule was not found.
"""
lines = chunk.splitlines()
... | c37668effa08117a0a0239eff5af335f5319776c | 301,655 |
from datetime import datetime
def alexa_datetime(date, time):
"""Return Alexa date and time strings as a datetime object."""
return datetime.strptime(date + " " + time, "%Y-%m-%d %H:%M") | 92a8cdc51f2058f1656cbae040f5401b049f8490 | 172,397 |
def nest_dict(flat_dict, sep='-'):
"""Return nested dict by splitting the keys on a delimiter.
Flask-wtf returns embedded document fields as a flattened dict, with
embedded document names embedded in the key. Any keys with empty values
will be removed.
For example, a document User may have an embe... | e8a9a38c06db49e50c1b0a1f0a5216c46bf0df9c | 393,010 |
def is_white_key(note):
"""True if note is represented by a white key"""
key_pattern = [
True,
False,
True,
True,
False,
True,
False,
True,
True,
False,
True,
False,
]
return key_pattern[(note - 21) % len(ke... | 515ba17c6f6234802c6ccb162e362d00dde62557 | 136,135 |
def get_item_properties(item, fields):
"""Return a tuple containing the item properties.
:param item: a single item resource (e.g. Server, Project, etc)
:param fields: tuple of strings with the desired field names
"""
return tuple([item.get(field, '') for field in fields]) | 23b24f51c5bcc0d5d26d497c967fd4c02c6aa7c1 | 91,054 |
def getByName(list, name):
"""
Return element by a given name.
"""
if list is None or name is None:
return None
for element in list:
if element.get('name') is None:
continue
if element['name'] == name:
return element
return None | 5dae082da8e6620b6ab44eed58f0fb012dce84eb | 101,844 |
def listminus(c1, c2):
"""Return a list of all elements of C1 that are not in C2, but in order."""
s2 = set(c2)
return [entry for entry in c1 if entry not in s2] | fce854870dfee595c89b576d3f6ab8957205d974 | 484,002 |
def duration(duration):
"""Filter that converts a duration in seconds to something like 01:54:01
"""
if duration is None:
return ''
duration = int(duration)
seconds = duration % 60
minutes = (duration // 60) % 60
hours = (duration // 60) // 60
s = '%02d' % (seconds)
m = '%0... | 7cd89654a84c2e3e41d96cb1b13688833ee54387 | 10,122 |
def open_file(filename, mode='r'):
"""
常用文件操作,可在python2和python3间切换.
mode: 'r' or 'w' for read or write
"""
return open(filename, mode, encoding='utf-8', errors='ignore') | 100179e22f140c4e8d25a1ccab94f9ca3831b5f3 | 691,138 |
def passwordExists(user):
"""Checks if the user has created a password for himself, passwords created by PSA are unusable"""
return user.has_usable_password() | 2b6dfbe31f3e9073ced5ebb634537cd101aaa37d | 220,372 |
import torch
def _float_from_bool(a):
"""
Since pytorch only supports matrix multiplication on float,
IoU computations are done using floating point types.
This function binarizes the input (positive to True and
nonpositive to False), and converts from bool to float.
If the data is already a ... | 3a16532903a44976a9dc036615c4887268096206 | 114,454 |
import math
def convert_state_to_hex(state: str) -> str:
"""
This assumes that state only has "x"s and Us or Ls or Fs or Rs or Bs or Ds
>>> convert_state_to_hex("xxxU")
'1'
>>> convert_state_to_hex("UxUx")
'a'
>>> convert_state_to_hex("UUxUx")
'1a'
"""
state = (
stat... | d722e07ab69c6b46f834eca04c7a8ba75520b145 | 679,457 |
def extract_dims(array, ndim=1):
"""Decrease the dimensionality of ``array`` by extracting ``ndim`` leading singleton dimensions."""
for _ in range(ndim):
assert len(array) == 1, len(array)
array = array[0]
return array | e51661bdce5029ecc58db892b761820c5f6de7e8 | 614,364 |
def _is_optional_field(field) -> bool:
"""Check if the input field is optional.
Args:
field (Field): input Field to check.
Returns:
bool: True if the input field is optional.
"""
# return isinstance(field.type, _GenericAlias) and type(None) in getattr(field.type, "__args__")
re... | a0e93747ab0044c5a8456f33e4a223bb2454dc3b | 427,441 |
def real(x):
"""
Takes the real part of a 4D tensor x, where the last axis is interpreted
as the real and imaginary parts.
Parameters
----------
x : tensor_like
Returns
-------
x[..., 0], which is interpreted as the real part of x
"""
return x[..., 0] | 364b4e3ab1f02dd92a5140244e6db5f3a4d80d64 | 363,919 |
def indent(t, indent=0, sep='\n'):
# type: (str, int, str) -> str
"""Indent text."""
return sep.join(' ' * indent + p for p in t.split(sep)) | 95263f43173a6ebc1cc1270f7ac7606484f99fd8 | 546,802 |
import random
def population(distribution, count=2048):
"""
Creates a list of numerical values (no uncertainty) of the specified
length that are representative of the distribution for use in less robust
statistical operations.
:param distribution:
The distribution instance on which to cre... | 70d74463b13fb4b9c5eaee03ac3010e5744972a4 | 278,729 |
from typing import Dict
def universal_detection_loss_weights(
loss_segmentation_word: float = 1e0,
loss_inst_dist: float = 1e0,
loss_mask_id: float = 1e-4,
loss_pq: float = 3e0,
loss_para: float = 1e0) -> Dict[str, float]:
"""A function that returns a dict for the weights of loss terms."""
ret... | 89996ea9be93748608ef84e5715b32d90c243d65 | 70,627 |
def averages_video_udea(dates, dlist, axes, names=['Exp1', 'Exp2'],
colors=['black', 'DodgerBlue'], xticks=None,
xlim=None, ylim=[-3, 3], title='',
xlabel=r'Year', ylabel=''):
"""Plot area average time series of variable for UdeA video.
In... | 4a47890ff8dfd08294bf41b3cc949e31c4339c6f | 530,034 |
def transpose(list_in):
"""
Shuffle/transpose a given 16 element list from
[ 0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15] to
[ 0, 4, 8, 12,
1, 5, 9, 13,
2, 6, 10, 14,
3, 7, 11, 15]
"""
list_out = []
for i in range(4):
for j in ... | 27237a93397bc18edd58ab0eb4689060fec1418e | 234,803 |
def fit_params_txt(fit_params, bp_list, out_dir):
"""Generates a text file in the same folder as the detrending plots that lists applied linear fit equations"""
# Create .txt file and copy breakpoint list
text_dir = out_dir + '\\detrending_fit_eqs.txt'
text_file = open(text_dir, 'w+')
bps_form = [i... | 5b0075fd90f25d446bbb1060da23b62221be6260 | 562,586 |
from datetime import datetime
def format_date(date):
"""Function takes a datetime object and stringifies it down to MM/DD/YYYY format"""
try:
start_date = datetime.strftime(date, '%m/%d/%Y')
except (TypeError, ValueError) as e:
start_date = date
pass
return start_date | 52cc6a1535789b010170444436c9e6122f9b29aa | 562,296 |
def _isInt(argstr):
""" Returns True if and only if the given string represents an integer. """
try:
int(argstr, 0) # hex values must have the "0x" prefix for this to work
return True
except (ValueError, TypeError):
return False | 6ec4bfd37b59b28317433fedcd68967193f47b3c | 601,956 |
def coerce_row_to_dict(schema, row):
"""
>>> from datashape import dshape
>>> schema = dshape('{x: int, y: int}')
>>> coerce_row_to_dict(schema, (1, 2)) # doctest: +SKIP
{'x': 1, 'y': 2}
Idempotent
>>> coerce_row_to_dict(schema, {'x': 1, 'y': 2}) # doctest: +SKIP
{'x': 1, 'y': 2}
... | 89ea04b6b73a8b7218a4cf2a1b584d2db583379c | 64,020 |
def point_window_unitxy(x, y, affine):
""" Given an x, y and a geotransform
Returns
- rasterio window representing 2x2 window whose center points encompass point
- the cartesian x, y coordinates of the point on the unit square
defined by the array center points.
((row1, row2), (co... | b7c2122569cf609c508d27ae74d035390c0d1744 | 282,755 |
import requests
def sendRequest(url, type="POST", params=None, headers=None):
"""
Send a request to a URL
### Input:
- `url` (str) | the url to send the request to
- `type` (str) | the type of request (GET or POST)
- `params` ... | 7f450b8eedf6405b237730b9f7d6da5277c41e7b | 14,080 |
def grandchildren_with_tag(child,tagnames):
"""Return children of child that have tag names in
the given set of tag names"""
ret=[]
for grandchild in child.iterchildren():
if grandchild.tag in tagnames:
ret.append(grandchild)
pass
pass
return ret | 1121345abab69f67abde0ee2b6e4629e71034c61 | 691,469 |
def lookup_fxn(x, vals):
"""
Builds a simple function that acts as a lookup table. Useful for
constructing bandwidth and weigth functions from existing values.
Parameters
----------
x : iterable
values to input for the function
vals : iterable
Output values for the function... | 0fbe32d19b84cf80db0f0621a9792f7a1234536d | 336,603 |
def search_ancestor(node, node_type_or_types):
"""
Recursively looks at the parents of a node and checks if the type names
match.
:param node: The node that is looked at.
:param node_type_or_types: A tuple or a string of type names that are
searched for.
"""
if not isinstance(node_t... | 5a40baad702cdb9bf8119b4f0b65fc3b484bc3e6 | 588,667 |
import re
def get_instances_from_report(report_file_path):
"""
Parse StegExpose report and return a list of (class, score).
E.g. [('p', 0.10), ('n', 0.05)]
"""
instances = []
with open(report_file_path, 'r') as report_file:
for line in report_file:
# Filter the lines witho... | dc5bbf747aa642456ec3080e2ca93a0f6a3086e1 | 572,160 |
def add_unique(list,elt):
"""Add an element uniquely to a list
"""
# Since we can't use set(), which uses memory addresses as hashes
# for any creation or order-sensitive operation in models
# instead we use lists and rather than foo = set(); foo.add(x)
# we use foo = []; add_unique(foo,x)
i... | c4353523900aaa00e0bde73335983b1f07b6c302 | 410,304 |
def pick_from_list(items, suffix):
""" Pick an element from list ending with suffix.
If no match is found, return None.
:param items list of items to be searched.
:suffix String suffix defining the match.
"""
match = None
for item in items:
if item.endswith(suffix):
mat... | b081cdba7de72c7864ab0ad3a7b358da267733e8 | 138,305 |
def build_streets_vertices(edges, shapes):
"""
Returns vertices and edges based on the subset of edges.
@param edges indexes
@param shapes streets
@return vertices, edges
*vertices* is a list of points.
*edges* is a list of `tuple(a, b)` where `a`, `b` ... | 6a1b5e0365a8e5dd89470476b41502470e490176 | 447,685 |
def isvideotype(x):
"""Is an object a vipy.video class Video, VideoCategory, Scene?"""
return (str(type(x)) in ["<class 'vipy.video.Video'>",
"<class 'vipy.video.VideoCategory'>",
"<class 'vipy.video.Scene'>"]) | c628a8671c8dfa4c03d56a8f2cd00c6f92065741 | 358,177 |
import random
def get_greeting(person):
""" Get a random greeting, greeting *person* """
greetings = ["hello!", "hi", "namaste", "privet", "konichiwa", "nihao!"]
return f"{random.choice(greetings).title()}, {person}." | b917af2dbe5f81c27631125e2e765fa76c5a030c | 575,217 |
def eventCoordinates(event):
""" Get the absolute coordinates of a mouse event.
http://www.quirksmode.org/js/events_properties.html#position
"""
return event.pageX, event.pageY | 7fb5439c221b9a617360c07ead9fe2f4ca3b4c10 | 521,516 |
def kernel_matrix(x, y):
"""
Returns kernel matrix (quadratic kernel, in this case) for input arrays, x
and y: K(x,y) = phi(x).phi(y), which for a quadratic kernel is (x.y)^2
"""
K = (x.dot(y.T))**2
return K | a1e5f666e6af3cde7588c3603a0cf56665643983 | 430,074 |
def recaman(length):
"""
Creates a Recamán's sequence
:param length: The length of the wanted sequence
:return: array containing the sequence
For more information about this sequence: https://en.wikipedia.org/wiki/Recam%C3%A1n%27s_sequence
"""
a = [0]
for n in range(1, length):
... | 8b9f03a09f18343a40e4466c726be2ff85ee83ea | 464,800 |
def process_hex(hex):
""" Processes hex data into a more usable format. """
# turn a hex section id into a hex category
category = hex['category'].split('_')[2]
hex['category'] = {
'DataListTypes': 'common',
'DataList1' : 'major',
'DataList2' : 'grand'
}[category]
r... | bcb2bb6bce8578ace58b05b474954ba66c9e2cc1 | 491,302 |
def verbaUtilizada(modelo):
"""
Dados os parametros do problema (armazenados em 'modelo'), calcula a verba utilizada
para distribuir 'totalCont + totalForm' alunos em 'totalTurmAbertas' turmas.
Retorna o valor da verba utilizada.
"""
usoVerba = (modelo.custoAluno*(modelo.xSoma + modelo.ySoma)
... | 39bf1691df146d663a79490f46463cbe09c4052f | 349,555 |
import inspect
import functools
def loggedmethod(method):
"""Decorator for LoggedObject methods, ensuring exceptions logging.
Whenever an exception is raised by a method this function decorates,
its details are logged through the object's `log` method at 'error'
level before it is raised again.
... | 1b1cf7bde0e8567d185c2a2db1c0b63daa85904a | 229,594 |
from typing import Callable
from typing import Tuple
def parse_line(line: str, distance_metric: Callable) -> Tuple[str, str, float]:
"""Parse a line of BLAST+6 output.
Parameters
----------
line : str
A blast line in format `-outfmt "6 qacc sacc length qlen slen ident"`
distance_metric : ... | 362a9ab44a32197c90e3d7064c11db7e7e0af2b6 | 600,766 |
def lstrip_namespace(s, namespaces):
"""
Remove starting namespace
:param s: input string
:type s: ```AnyStr```
:param namespaces: namespaces to strip
:type namespaces: ```Union[List[str], Tuple[str], Generator[str], Iterator[str]]```
:returns: `.lstrip`ped input (potentially just the ori... | ddb4ef24a1eec4a67772ad7fed29b69c0cfe83ca | 333,095 |
def join_labels(labels, join_symbol="|", threshold=1.e-6):
"""
Join labels with a joining symbol when they are very close
:param labels: a list of length-2 tuples, in the format(position, label)
:param join_symbol: the string to use to join different paths. By default, a pipe
:param threshold: the ... | b52b69a23dddec2edb81f022571c9e2f5573a229 | 596,952 |
def _uri(helper):
"""Returns the URL of the kvstore."""
return '/'.join((
helper.context_meta['server_uri'],
'servicesNS',
'nobody',
'Splunk_TA_paloalto',
'storage',
'collections',
'data',
'minemeldfeeds')) | d272afa2e9305a480609c215e653f3e80b1990b7 | 567,651 |
from typing import Optional
import json
def _try_parse_json(json_string: str, ref_val=None) -> Optional[dict]:
"""
Return whether the string can be interpreted as json.
:param json_string: str, string to check for json
:param ref_val: any, not used, interface design requirement
:return None if not... | a609eeefb32d88970ecf039578e8eb8a65ad8108 | 692,545 |
import shutil
def get_archive_name_and_format_for_shutil(path):
"""Returns archive name and format to shutil.make_archive() for the |path|.
e.g., returns ('/path/to/boot-img', 'gztar') if |path| is
'/path/to/boot-img.tar.gz'.
"""
for format_name, format_extensions, _ in shutil.get_unpack_formats(... | 152d68ea9613d7253f78c37ce85758a2c8bc67f9 | 700,162 |
def absolute_round(number: float) -> int:
""" Rounds the value of number and then produces the absolute value of that result
>>> absolute_round(-2.1)
2
>>> absolute_round(3.4)
3
>>> absolute_round(3.7)
4
>>> absolute_round(-2.9)
3
"""
return abs(round(number)) | 446786ad83dfb42e8643917d1e656b22e750654b | 118,388 |
import random
def roll_die(sides: int) -> int:
"""Rolls a die with given number of sides."""
return random.randint(1, sides) | 35cb7445f46a84e3232b7a24951139c635d912b3 | 245,029 |
from datetime import datetime
def _get_timestamp() -> str:
"""Create a timestamp in the right format."""
return datetime.utcnow().strftime("_%H:%M:%S,%m-%d-%Y") | ab12e853d21b854f8868164c1522b513d271456a | 256,142 |
def parse_title(line):
"""if this is title, return Tuple[level, content],
@type line: str
@return: Optional[Tuple[level, content]]
"""
line = line.strip()
if not line.startswith('#'):
return None
sharp_count = 0
for c in line:
if c == '#':
sharp_count += 1
... | 7c170f417755c878d225b780b8475a379501c19f | 707,815 |
from typing import Tuple
def get_default_optimisation_params(config: dict) -> Tuple[float, int]:
"""Get the default coverage distance (theta) and number of sensors to use when
optimising networks and generating figures.
Parameters
----------
config : dict
Parameters as loaded by utils.get... | c6dfe41d3d6be1eee2fec2c78413fa03c2033416 | 435,011 |
import hashlib
def _hash_file(fpath, algorithm="sha256", chunk_size=65535):
"""Calculates a file sha256 or md5 hash.
# Example
```python
>>> from keras.data_utils import _hash_file
>>> _hash_file('/path/to/file.zip')
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b8... | abc4874c9284a0e00392cc7668ce9d94e64e94ee | 674,086 |
import torch
def cosine_similarity(x, y=None, eps=1e-8):
"""Calculate cosine similarity between two matrices;
Args:
x: N*p tensor
y: M*p tensor or None; if None, set y = x
This function do not broadcast
Returns:
N*M tensor
"""
w1 = torch.norm(x, p=2, dim=1, keepdim=True)
if y is None... | 68faf837293556409899487b47de072d013a1f42 | 674,093 |
def parse_header(field):
"""Parses a single header key and converts it to the way it appears on a HTTP classified_request.
This function is necessary because the headers' keys are provided in the environment variables
not as they appear in a HTTP classified_request.
For example, it converts HTTP_USER_AG... | 42007140e1eb2922485785e1213eeac859b50348 | 578,196 |
import shutil
def process_java_resources(target, source, env):
"""Copy resource file into .resources dir. """
shutil.copy2(str(source[0]), str(target[0]))
return None | 3ee5194703956d43187a0c4f802c3ee4c132c18a | 40,440 |
def encode_sequence(sequence: str, encoding_scheme: dict):
"""
Encodes a peptide sequence with values provided by the encoding table/scheme.
"""
encoded_sequence = []
for aa in sequence:
try:
value = encoding_scheme.get(aa)
except Exception as e:
msg = f'{e}'
... | ee4bd552608be084523606ee14a41cbbe29483bf | 417,782 |
def is_component_enabled(env, cls):
""" Determine whether a trac component is enabled.
"""
# We would like to use env.is_enabled(cls) to do this,
# however, trac 0.11 does not have ComponentManager.is_enabled().
# So instead, rely on ComponentManager.__getitem__(), which does
# have the same lo... | 0f946d94706f03d86980f0a05a74d486cd77d4a9 | 533,018 |
import yaml
def read_yaml(file_path):
"""Read a YAML file by the given path.
Args:
file_path (str): The absolute path of the YAML file.
Returns:
dict: The data spec_reader from given YAML file.
"""
with open(file_path, "r") as file_object:
return yaml.safe_load(file_obje... | 808bb6c31bd62e3a3be587f500e83e923b967fec | 227,970 |
def _non_string_elements(x):
"""
Simple helper to check that all values of x are string. Returns all non string elements as (position, element).
:param x: Iterable
:return: [(int, !String), ...]
"""
problems = []
for i in range(0, len(x)):
if not isinstance(x[i], str):
p... | 974715622949157693084823a52a88973b51d100 | 1,095 |
def change_path_for_metric(path):
"""
Replace the '/' in the metric path by '_' so grafana can correctly use it.
:param path: path of the metric (example: runs/search)
:return: path with '_' instead of '/'
"""
if 'mlflow/' in path:
path = path.split('mlflow/')[-1]
return path.replace... | 72c887ddde6f34d30a00c21fa869ea919e554a61 | 510,170 |
def filter_matchable_fields(cite_keys, bib_dbs, desired_fields=["eprint", "doi"]):
"""Select bibtex entries which have certain desired fields.
To look up an entry in a different database, we need a
well-known identifier like a DOI or arXiv identifier. This
function will select those entries which have... | b76ae5131200cf532abf95205dbe888385209d26 | 562,128 |
def csv_to_list(s: str):
"""Parse comma-separated list (and make lowercase)"""
return [x.lower().strip() for x in s.split(',')] | bae07932fa373ce0935131f2c27ab794d880e188 | 516,384 |
def parse_int(sin):
"""A version of int but fail-safe"""
return int(sin) if sin.isdigit() else -99 | 204cbcb01b6df1bbdd09af318fdfe90feb5fe68f | 698,570 |
def FormatDatetime(date, day_only=False):
"""Returns a string representing the given UTC datetime."""
if not date:
return None
if day_only:
return date.strftime('%Y-%m-%d')
return date.strftime('%Y-%m-%d %H:%M:%S UTC') | c278c1d8cb5503bd384e2345da759009eef125a5 | 485,895 |
from typing import Dict
import json
def load_params_file(params_file: str) -> Dict:
"""
Load a JSON file of training parameters.
:param params_file: The input file.
:return: A dictionary of training parameters.
"""
with open(params_file, 'r') as fin:
return json.load(fin) | 0538c795c706f6a4edf1c523b643dc349d1e033e | 95,632 |
from typing import Dict
from typing import Optional
def make_env_shell_str(env: Dict[str, str]) -> Optional[str]:
"""
Transforms env dict to string suitable for use in shell
Returns None for empty dict
"""
env = env or {}
result = []
for k, v in env.items():
value = v
if "... | 1937f89bef2738d72dd426b687438d25f487771c | 367,212 |
def N_ref_macs(*, theta, mu):
"""
Calculate N0 reference size for a macs command.
Macs has a different meaning for the '-t theta' argument.
Theta is the 'mutation rate per site per 4N generations'.
theta = mu / (4 N)
"""
return theta / (4 * mu) | 93049546c95dde13cd60da75a99d39891b6cf0ca | 383,432 |
def parse_file_to_bucket_and_filename(file_path):
"""Divides file path to bucket name and file name"""
path_parts = file_path.split("//")
if len(path_parts) >= 2:
main_part = path_parts[1]
if "/" in main_part:
divide_index = main_part.index("/")
bucket_name = main_par... | ff252fd051e3236da45b58e58a0b5bb57106def5 | 264,850 |
def _index_spec_params(spec_params):
"""
Makes an index of the spec parameters. It dict-ifies the list of spec params
provided by the SpecManager, and also returns the set of param ids that are
used in groups.
This gets returned as a tuple (indexed params, group param ids)
"""
spec_params_di... | 19aa93b2d34fb448476a2ebe0a2666494eebb70b | 89,913 |
import torch
def cross_entropy_loss(stu_logits, tea_logits, temp=1.): # 使用交叉熵
""" the same as nn.CrossEntropyLoss, but more flexible
Args:
stu_logits: tensor of shape [N, class]
tea_logits: tensor of shape [N, class]
temp: the distillation temperature
Return:
kd_loss: the cross entropy on soft l... | a819855533900dcd91c4bfc5278962e506ecaf7f | 218,748 |
import pickle
def load(filename):
""" Loads in a saved instance of the SunXspex class.
Parameters
----------
filename : str
Filename for the pickled fitting class.
Returns
-------
Loaded in fitting class.
"""
with open(filename, 'rb') as f:
loaded = pickle.loa... | 6cc32b68ccb588d66bb072d0a3587dd82bcbe489 | 602,903 |
def get_range(distribution):
""" Returns the range of a distribution """
return max(distribution) - min(distribution) | 56c5ecb14c18a45f123368908d597ef429210dab | 336,556 |
def getPhenotype(chromosome, items):
"""
Given a chromosome, returns a list of items in the bag
:param chromosome:
:param items:
:return: list
"""
return [v for i, v in enumerate(items) if chromosome[i] == 1] | 19b7bc47cba3fdf652dd84d4c5c1932afde6cbde | 108,302 |
def talk_type(talk):
""" Return the pretty name for the type of the talk."""
if talk.admin_type:
typ = talk.get_admin_type_display()
else:
typ = talk.get_type_display()
return typ | 67374d7ffaa9c8298812df4a504845c790042502 | 380,257 |
import string
def get_gis_field(csv_field, gis_field_lookup):
"""return a (max) 10 character representation of csv_field that is unique to the list of analysis fields"""
if csv_field in gis_field_lookup:
return gis_field_lookup[csv_field]
gis_field_set = set(gis_field_lookup.values())
gis_fiel... | 8adfc88babc4514c715f63ec8c258268862226b2 | 600,794 |
import uuid
def create_marconi_headers(conf):
"""Returns headers to be used for all Marconi requests."""
headers = {
"User-Agent": conf.headers.user_agent,
"Accept": "application/json",
"X-Project-ID": conf.headers.project_id,
"Client-ID": str(uuid.uuid1()),
}
return ... | 73a4a348b36651f1431865c2b9f197ad78765a61 | 588,494 |
import itertools
def take(iterable, n):
"""Return first n items of the iterable as a list."""
return list(itertools.islice(iterable, n)) | dd8b9681707b6abb0b2974e383d053ec9011af88 | 585,582 |
def build_sub_O2(Graph):
"""
For each white node in Graph, we create a copy of Graph and perform O2 in that node.
Return a list of the graphs obtained.
"""
White = Graph.white()
sub_list = []
for index, n in enumerate(White):
temp_g = Graph.O2(n)
temp_g.labeling(index+1)
sub_list.append(temp_g)
retur... | 099ce3a5ac3b2dcdf1b1a05421ae8cb0e9a0dc07 | 519,848 |
from typing import List
from typing import Counter
def remove_rare(sentences: List[List[str]]) -> List[List[str]]:
"""
Remove rare words (those that appear at most once) from sentences.
Parameters
----------
sentences:
List of tokenized sentences.
"""
counts: Counter = Counter()
... | 1af60b7bb0393abf99db02abf6f4fea9d9529c15 | 47,572 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.