content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def GetMappingKeyName(run, user):
"""Returns a str used to uniquely identify a mapping."""
return 'RunTesterMap_%s_%s' % (run.key().name(), str(user.user_id())) | b4eb80ca5f084ea956f6a458f92de1b85e722cda | 2,811 |
def year_from_operating_datetime(df):
"""Add a 'year' column based on the year in the operating_datetime.
Args:
df (pandas.DataFrame): A DataFrame containing EPA CEMS data.
Returns:
pandas.DataFrame: A DataFrame containing EPA CEMS data with a 'year'
column.
"""
df['year']... | 1c7bbc6465d174465151e5e777671f319ee656b7 | 2,812 |
def get_seats_percent(election_data):
"""
This function takes a lists of lists as and argument, with each list representing a party's election results,
and returns a tuple with the percentage of Bundestag seats won by various political affiliations.
Parameters:
election_data (list): A list of l... | a131d64747c5c0dde8511e9ec4da07252f96a6ec | 2,815 |
import random
def random_choice(gene):
"""
Randomly select a object, such as strings, from a list. Gene must have defined `choices` list.
Args:
gene (Gene): A gene with a set `choices` list.
Returns:
object: Selected choice.
"""
if not 'choices' in gene.__dict__:
rais... | 8a01a2039a04262aa4fc076bdd87dbf760f45253 | 2,817 |
from random import shuffle
def shuffle_list(*ls):
""" shuffle multiple list at the same time
:param ls:
:return:
"""
l = list(zip(*ls))
shuffle(l)
return zip(*l) | ec46e4a8da2c04cf62da2866d2d685fc796887e5 | 2,820 |
def nodes(G):
"""Returns an iterator over the graph nodes."""
return G.nodes() | 3a1a543f1af4d43c79fd0083eb77fedd696547ec | 2,821 |
def process_input(input_string, max_depth):
"""
Clean up the input, convert it to an array and compute the longest
array, per feature type.
"""
# remove the quotes and extra spaces from the input string
input_string = input_string.replace('"', '').replace(', ', ',').strip()
# convert the s... | ca0fddd0b3bf145c7fc0654212ae43f02799b466 | 2,822 |
def construct_tablepath(fmdict, prefix=''):
"""
Construct a suitable pathname for a CASA table made from fmdict,
starting with prefix. prefix can contain a /.
If prefix is not given, it will be set to
"ephem_JPL-Horizons_%s" % fmdict['NAME']
"""
if not prefix:
prefix = "ephem_JPL-H... | 95041aab91ac9994ef2068d5e05f6cd63969d94e | 2,823 |
def recursiveUpdate(target, source):
"""
Recursively update the target dictionary with the source dictionary, leaving unfound keys in place.
This is different than dict.update, which removes target keys not in the source
:param dict target: The dictionary to be updated
:param dict source: The dicti... | e1c11d0801be9526e8e73145b1dfc7be204fc7d0 | 2,825 |
def get_module_id_from_event(event):
"""
Helper function to get the module_id from an EventHub message
"""
if "iothub-connection-module_id" in event.message.annotations:
return event.message.annotations["iothub-connection-module-id".encode()].decode()
else:
return None | e183824fff183e3f95ef35c623b13245eb68a8b7 | 2,828 |
from typing import Collection
def A006577(start: int = 0, limit: int = 20) -> Collection[int]:
"""Number of halving and tripling steps to reach 1 in '3x+1' problem,
or -1 if 1 is never reached.
"""
def steps(n: int) -> int:
if n == 1:
return 0
x = 0
while True:
... | 47829838af8e2fdb191fdefa755e728db9c09559 | 2,831 |
def parabolic(f, x):
"""
Quadratic interpolation in order to estimate the location of a maximum
https://gist.github.com/endolith/255291
Args:
f (ndarray): a vector a samples
x (int): an index on the vector
Returns:
(vx, vy): the vertex coordinates of a parabola passing... | 4373ee6390f3523d0fd69487c27e05522bd8c230 | 2,839 |
import re
def get_better_loci(filename, cutoff):
"""
Returns a subset of loci such that each locus includes at least "cutoff"
different species.
:param filename:
:param cutoff:
:return:
"""
f = open(filename)
content = f.read()
f.close()
loci = re.split(r'//.*|', conte... | e2d563c9d0568cef59ea0280aae61a78bf4a6e7b | 2,840 |
import six
def canonicalize_monotonicity(monotonicity, allow_decreasing=True):
"""Converts string constants representing monotonicity into integers.
Args:
monotonicity: The monotonicities hyperparameter of a `tfl.layers` Layer
(e.g. `tfl.layers.PWLCalibration`).
allow_decreasing: If decreasing mono... | a9d0870d03f11d7bdff4c8f673cd78d072fa8478 | 2,843 |
def add_gdp(df, gdp, input_type="raw", drop=True):
"""Adds the `GDP` to the dataset. Assuming that both passed dataframes have a column named `country`.
Parameters
----------
df : pd.DataFrame
Training of test dataframe including the `country` column.
gdp : pd.DataFrame
Mapping betw... | 72e2b5fe839f3dbc71ca2def4be442535a0adb84 | 2,844 |
def ravel_group_params(parameters_group):
"""Take a dict(group -> {k->p}) and return a dict('group:k'-> p)
"""
return {f'{group_name}:{k}': p
for group_name, group_params in parameters_group.items()
for k, p in group_params.items()} | 4a768e89cd70b39bea4f658600690dcb3992a710 | 2,847 |
def _parse_path(**kw):
"""
Parse leaflet `Path` options.
http://leafletjs.com/reference-1.2.0.html#path
"""
color = kw.pop('color', '#3388ff')
return {
'stroke': kw.pop('stroke', True),
'color': color,
'weight': kw.pop('weight', 3),
'opacity': kw.pop('opacity', 1... | 02d3810ad69a1a0b8f16d61e661e246aea5c09cc | 2,851 |
from typing import Optional
import time
from datetime import datetime
def time_struct_2_datetime(
time_struct: Optional[time.struct_time],
) -> Optional[datetime]:
"""Convert struct_time to datetime.
Args:
time_struct (Optional[time.struct_time]): A time struct to convert.
Returns:
O... | 705b09428d218e8a47961e247b62b9dfd631a41f | 2,853 |
import time
def wait_for_compute_jobs(nevermined, account, jobs):
"""Monitor and wait for compute jobs to finish.
Args:
nevermined (:py:class:`nevermined_sdk_py.Nevermined`): A nevermined instance.
account (:py:class:`contracts_lib_py.account.Account`): Account that published
the ... | 98370b8d596f304630199578a360a639507ae3c3 | 2,855 |
def find_balanced(text, start=0, start_sep='(', end_sep=')'):
""" Finds balanced ``start_sep`` with ``end_sep`` assuming
that ``start`` is pointing to ``start_sep`` in ``text``.
"""
if start >= len(text) or start_sep != text[start]:
return start
balanced = 1
pos = start + 1
while... | 15c17a216405028b480efa9d12846905a1eb56d4 | 2,858 |
def gather_along_dim_with_dim_single(x, target_dim, source_dim, indices):
"""
This function indexes out a target dimension of a tensor in a structured way,
by allowing a different value to be selected for each member of a flat index
tensor (@indices) corresponding to a source dimension. This can be int... | 06fbba5478ddb21cda9a555c41c94c809244537c | 2,861 |
def extract_p(path, dict_obj, default):
"""
try to extract dict value in key path, if key error provide default
:param path: the nested dict key path, separated by '.'
(therefore no dots in key names allowed)
:param dict_obj: the dictinary object from which to extract
:param default: a default r... | 1a563212e229e67751584885c5db5ac19157c37f | 2,863 |
def group_bars(note_list):
"""
Returns a list of bars, where each bar is a list of notes. The
start and end times of each note are rescaled to units of bars, and
expressed relative to the beginning of the current bar.
Parameters
----------
note_list : list of tuples
List of not... | 3b12a7c7e2395caa3648abf152915ece4b325599 | 2,865 |
import re
def sample(s, n):
"""Show a sample of string s centered at position n"""
start = max(n - 8, 0)
finish = min(n + 24, len(s))
return re.escape(s[start:finish]) | 565f69224269ed7f5faa538d40ce277714144577 | 2,868 |
import math
def encode_integer_compact(value: int) -> bytes:
"""Encode an integer with signed VLQ encoding.
:param int value: The value to encode.
:return: The encoded integer.
:rtype: bytes
"""
if value == 0:
return b"\0"
if value < 0:
sign_bit = 0x40
value = -v... | daf9ed4a794754a3cd402e8cc4c3e614857941fe | 2,869 |
def get_html_subsection(name):
"""
Return a subsection as HTML, with the given name
:param name: subsection name
:type name: str
:rtype: str
"""
return "<h2>{}</h2>".format(name) | 2e0f37a7bb9815eda24eba210d8518e64595b9b7 | 2,872 |
import random
def shuffle(answers):
"""
Returns mixed answers and the index of the correct one,
assuming the first answer is the correct one.
"""
indices = list(range(len(answers)))
random.shuffle(indices)
correct = indices.index(0)
answers = [answers[i] for i in indices]
return an... | e597b4aeb65fecf47f4564f2fddb4d76d484707a | 2,875 |
from typing import List
from pathlib import Path
def get_requirements(req_file: str) -> List[str]:
"""
Extract requirements from provided file.
"""
req_path = Path(req_file)
requirements = req_path.read_text().split("\n") if req_path.exists() else []
return requirements | 3433cd117bbb0ced7ee8238e36f20c69e15c5260 | 2,876 |
def align_dataframes(framea, frameb, fill_value = 0.0):
"""Use pandas DataFrame structure to align two-dimensional data
:param framea: First pandas dataframe to align
:param frameb: Other pandas dataframe to align
:param fill_value: default fill value (0.0 float)
return: tuple of aligned frames
... | 86a5e8c399ab47a10715af6c90d0901c2207597c | 2,878 |
def dm2skin_normalizeWeightsConstraint(x):
"""Constraint used in optimization that ensures
the weights in the solution sum to 1"""
return sum(x) - 1.0 | 79024cb70fd6cbc3c31b0821baa1bcfb29317043 | 2,884 |
import glob
def find_pkg(pkg):
""" Find the package file in the repository """
candidates = glob.glob('/repo/' + pkg + '*.rpm')
if len(candidates) == 0:
print("No candidates for: '{0}'".format(pkg))
assert len(candidates) == 1
return candidates[0] | ac91f34ed7accd2c81e1c68e143319998de9cdf3 | 2,888 |
def _check_eq(value):
"""Returns a function that checks whether the value equals a
particular integer.
"""
return lambda x: int(x) == int(value) | 4d2a02727afd90dbc012d252b01ed72f745dc564 | 2,891 |
def calcPhase(star,time):
"""
Calculate the phase of an orbit, very simple calculation but used quite a lot
"""
period = star.period
phase = time/period
return phase | 4b282d9e4fdb76a4358d895ba30b902328ce030c | 2,893 |
def inv(n: int, n_bits: int) -> int:
"""Compute the bitwise inverse.
Args:
n: An integer.
n_bits: The bit-width of the integers used.
Returns:
The binary inverse of the input.
"""
# We should only invert the bits that are within the bit-width of the
# integers we use. W... | 5be1eaf13490091096b8cd13fdbcdbbbe43760da | 2,895 |
def check_for_features(cmph5_file, feature_list):
"""Check that all required features present in the cmph5_file. Return
a list of features that are missing.
"""
aln_group_path = cmph5_file['AlnGroup/Path'][0]
missing_features = []
for feature in feature_list:
if feature not in cmph5_fil... | 2d51e1389e6519607001ad2b0006581e6a876ddd | 2,899 |
import re
def compress_sparql(text: str, prefix: str, uri: str) -> str:
"""
Compress given SPARQL query by replacing all instances of the given uri with the given prefix.
:param text: SPARQL query to be compressed.
:param prefix: prefix to use as replace.
:param uri: uri instance to be replaced.
... | b86ceebadb262730fb4dec90b43e04a09d9c9541 | 2,901 |
def use(*authenticator_classes):
""" A decorator to attach one or more :class:`Authenticator`'s to the decorated class.
Usage:
from thorium import auth
@auth.use(BasicAuth, CustomAuth)
class MyEngine(Endpoint):
...
OR
@auth.use(BasicAuth)
@auth.use... | 27aeb7711c842540a1ed77a76cebeb61e0342f1e | 2,905 |
import math
def mutual_information(co_oc, oi, oj, n):
"""
:param co_oc: Number of co occurrences of the terms oi and oj in the corpus
:param oi: Number of occurrences of the term oi in the corpus
:param oj: Number of occurrences of the term oi in the corpus
:param n: Total number of words in the c... | 76c27295c7e757282573eab71f2bb7cfd3df74cb | 2,906 |
def merge_options(custom_options, **default_options):
"""
Utility function to merge some default options with a dictionary of custom_options.
Example: custom_options = dict(a=5, b=3)
merge_options(custom_options, a=1, c=4)
--> results in {a: 5, b: 3, c: 4}
"""
merged_option... | a1676c9304f3c231aefaeb107c8fb6f5a8251b26 | 2,909 |
def _filter_nones(centers_list):
"""
Filters out `None` from input list
Parameters
----------
centers_list : list
List potentially containing `None` elements
Returns
-------
new_list : list
List without any `None` elements
"""
return [c for c in centers_list if... | 031e878ebc8028deea238f5ac902ca55dba72a6d | 2,910 |
def isolate_integers(string):
"""Isolate positive integers from a string, returns as a list of integers."""
return [int(s) for s in string.split() if s.isdigit()] | cc95f7a37e3ae258ffaa54ec59f4630c600e84e1 | 2,911 |
import json
def store_barbican_secret_for_coriolis(
barbican, secret_info, name='Coriolis Secret'):
""" Stores secret connection info in Barbican for Coriolis.
:param barbican: barbican_client.Client instance
:param secret_info: secret info to store
:return: the HREF (URL) of the newly-create... | 218bf941203dd12bc78fc7a87d6a2f9f21761d57 | 2,912 |
def normalize(features):
"""
Scale data in provided series into [0,1] range.
:param features:
:return:
"""
return (features - features.min()) / (features.max() - features.min()) | a85d77e37e71c732471d7dcd42ae1aef2181f6dc | 2,915 |
from datetime import datetime
import time
def dateToUsecs(datestring):
"""Convert Date String to Unix Epoc Microseconds"""
dt = datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S")
return int(time.mktime(dt.timetuple())) * 1000000 | cba081ae63523c86572463249b4324f2183fcaaa | 2,917 |
def find_vertical_bounds(hp, T):
"""
Finds the upper and lower bounds of the characters' zone on the plate based on threshold value T
:param hp: horizontal projection (axis=1) of the plate image pixel intensities
:param T: Threshold value for bound detection
:return: upper and lower bounds
"""
N = len(hp)
# F... | 8520c3b638cafe1cfb2d86cc7ce8c3f28d132512 | 2,921 |
def cost_n_moves(prev_cost: int, weight: int = 1) -> int:
""" 'g(n)' cost function that adds a 'weight' to each move."""
return prev_cost + weight | 77a737d68f2c74eaba484b36191b95064b05e1a9 | 2,924 |
def meh(captcha):
"""Returns the sum of the digits which match the next one in the captcha
input string.
>>> meh('1122')
3
>>> meh('1111')
4
>>> meh('1234')
0
>>> meh('91212129')
9
"""
result = 0
for n in range(len(captcha)):
if captcha[n] == captcha[(n + 1) ... | 2ff68455b7bb826a81392dba3bc8899374cbcc3e | 2,927 |
def goodput_for_range(endpoint, first_packet, last_packet):
"""Computes the goodput (in bps) achieved between observing two specific packets"""
if first_packet == last_packet or \
first_packet.timestamp_us == last_packet.timestamp_us:
return 0
byte_count = 0
seen_first = False
for pa... | aea56993771c1a250dacdfccf8328c7a0d3ce50b | 2,929 |
def get_string_from_bytes(byte_data, encoding="ascii"):
"""Decodes a string from DAT file byte data.
Note that in byte form these strings are 0 terminated and this 0 is removed
Args:
byte_data (bytes) : the binary data to convert to a string
encoding (string) : optional, the encoding type to... | c07523139e2509fcc19b2ce1d9a933fcb648abfd | 2,931 |
def is_free(board: list, pos: int) -> bool:
"""checks if pos is free or filled"""
return board[pos] == " " | 64b75aa5d5b22887495e631e235632e080646422 | 2,933 |
def serialize_measurement(measurement):
"""Serializes a `openff.evaluator.unit.Measurement` into a dictionary of the form
`{'value', 'error'}`.
Parameters
----------
measurement : openff.evaluator.unit.Measurement
The measurement to serialize
Returns
-------
dict of str and str... | 69eedd9006c63f5734c762d6113495a913d5a8c4 | 2,935 |
def rename_record_columns(records, columns_to_rename):
"""
Renames columns for better desc and to match Socrata column names
:param records: list - List of record dicts
:param columns_to_rename: dict - Dict of Hasura columns and matching Socrata columns
"""
for record in records:
for col... | 41d5cc90a368f61e8ce138c54e9f5026bacd62b9 | 2,936 |
def remove_list_by_name(listslist, name):
"""
Finds a list in a lists of lists by it's name, removes and returns it.
:param listslist: A list of Twitter lists.
:param name: The name of the list to be found.
:return: The list with the name, if it was found. None otherwise.
"""
for i in range(... | 356a7d12f3b2af9951327984ac6d55ccb844bf72 | 2,939 |
def is_int(var):
"""
is this an integer (ie, not a float)?
"""
return isinstance(var, int) | 09924c6ea036fc7ee1add6ccbefc3fb0c9696345 | 2,944 |
def returnstringpacket(pkt):
"""Returns a packet as hex string"""
myString = ""
for c in pkt:
myString += "%02x" % c
return myString | 866ef7c69f522d4a2332798bdf97a966740ea0e4 | 2,945 |
def get_conversion_option(shape_records):
"""Prompts user for conversion options"""
print("1 - Convert to a single zone")
print("2 - Convert to one zone per shape (%d zones) (this can take a while)" % (len(shape_records)))
import_option = int(input("Enter your conversion selection: "))
return import... | 7608c588960eb3678970e0d4467c67ff9f17a331 | 2,952 |
from functools import reduce
import operator
def product_consec_digits(number, consecutive):
"""
Returns the largest product of "consecutive"
consecutive digits from number
"""
digits = [int(dig) for dig in str(number)]
max_start = len(digits) - consecutive
return [reduce(operator.mul, dig... | 2df16f7445e6d579b632e86904b77ec93e52a1f3 | 2,953 |
def generate_legacy_dir(ctx, config, manifest, layers):
"""Generate a intermediate legacy directory from the image represented by the given layers and config to /image_runfiles.
Args:
ctx: the execution context
config: the image config file
manifest: the image manifest file
layers: the ... | 6001820e63ac3586625f7ca29311d717cc1e4c07 | 2,954 |
def workflow_key(workflow):
"""Return text search key for workflow"""
# I wish tags were in the manifest :(
elements = [workflow['name']]
elements.extend(workflow['tags'])
elements.extend(workflow['categories'])
elements.append(workflow['author'])
return ' '.join(elements) | 57347705b605e68a286dd953de5bb157ac50628e | 2,955 |
import locale
import re
def parse_price(price):
"""
Convert string price to numbers
"""
if not price:
return 0
price = price.replace(',', '')
return locale.atoi(re.sub('[^0-9,]', "", price)) | bb90aa90b38e66adc73220665bb5e6458bfe5374 | 2,958 |
def zscore(dat, mean, sigma):
"""Calculates zscore of a data point in (or outside of) a dataset
zscore: how many sigmas away is a value from the mean of a dataset?
Parameters
----------
dat: float
Data point
mean: float
Mean of dataset
sigma: flaot
Sigma of dataset
... | b11216e50632e2024af0a389184d5e1dba7ed4fd | 2,963 |
def unused(attr):
"""
This function check if an attribute is not set (has no value in it).
"""
if attr is None:
return True
else:
return False | febc225f3924fdb9de6cfbf7eba871cce5b6e374 | 2,965 |
def get_evaluate_SLA(SLA_terms, topology, evaluate_individual):
"""Generate a function to evaluate if the flow reliability and latency requirements are met
Args:
SLA_terms {SLA} -- an SLA object containing latency and bandwidth requirements
topology {Topology} -- the reference topology object f... | 81fdaa07e3fc21066ab734bef0cc71457d40fb5b | 2,966 |
def latest_consent(user, research_study_id):
"""Lookup latest valid consent for user
:param user: subject of query
:param research_study_id: limit query to respective value
If latest consent for user is 'suspended' or 'deleted', this function
will return None. See ``consent_withdrawal_dates()`` f... | 2295b592a0c1fdaf3b1ed21e065f39e73a4bb622 | 2,967 |
from typing import Tuple
def find_next_tag(template: str, pointer: int, left_delimiter: str) -> Tuple[str, int]:
"""Find the next tag, and the literal between current pointer and that tag"""
split_index = template.find(left_delimiter, pointer)
if split_index == -1:
return (template[pointer:], le... | 82d091ef6738ffbe93e8ea8a0096161fc359e9cb | 2,968 |
def hamiltonian_c(n_max, in_w, e, d):
"""apply tridiagonal real Hamiltonian matrix to a complex vector
Parameters
----------
n_max : int
maximum n for cutoff
in_w : np.array(complex)
state in
d : np.array(complex)
diagonal elements of Hamiltonian
e : np.array(com... | 9b78d86592622100322d7a4ec031c1bd531ca51a | 2,970 |
def grow_population(initial, days_to_grow):
"""
Track the fish population growth from an initial population, growing over days_to_grow number of days.
To make this efficient two optimizations have been made:
1. Instead of tracking individual fish (which doubles every approx. 8 days which will result O... | 88b8283e5c1e6de19acb76278ef16d9d6b94de00 | 2,974 |
import six
def _ensure_list(alist): # {{{
"""
Ensure that variables used as a list are actually lists.
"""
# Authors
# -------
# Phillip J. Wolfram, Xylar Asay-Davis
if isinstance(alist, six.string_types):
# print 'Warning, converting %s to a list'%(alist)
alist = [alist]... | bd8115dad627f4553ded17757bfb838cfdb0200b | 2,975 |
def showgraphwidth(context, mapping):
"""Integer. The width of the graph drawn by 'log --graph' or zero."""
# just hosts documentation; should be overridden by template mapping
return 0 | 6e2fad8c80264a1030e5a113d66233c3adc28af8 | 2,980 |
def merge_two_sorted_array(l1, l2):
"""
Time Complexity: O(n+m)
Space Complexity: O(n+m)
:param l1: List[int]
:param l2: List[int]
:return: List[int]
"""
if not l1:
return l2
if not l2:
return l1
merge_list = []
i1 = 0
i2 = 0
l1_len = len(l1) - 1
... | 2671d21707056741bbdc4e3590135e7e1be4c7e9 | 2,987 |
def check_similarity(var1, var2, error):
"""
Check the simulatiry between two numbers, considering a error margin.
Parameters:
-----------
var1: float
var2: float
error: float
Returns:
-----------
similarity: boolean
"""
if((var1 <= (var2 + error)) and (v... | 305fd08cf4d8b1718d8560315ebf7bd03a4c7e2a | 2,989 |
def getCasing(word):
""" Returns the casing of a word"""
if len(word) == 0:
return 'other'
elif word.isdigit(): #Is a digit
return 'numeric'
elif word.islower(): #All lower case
return 'allLower'
elif word.isupper(): #All upper case
return 'allUpper'
elif word[0... | 2af70926c0cbbde6310abb573ccc3ee8260b86bd | 2,990 |
def normalize_angle(deg):
"""
Take an angle in degrees and return it as a value between 0 and 360
:param deg: float or int
:return: float or int, value between 0 and 360
"""
angle = deg
while angle > 360:
angle -= 360
while angle < 360:
angle += 360
return angle | cd4788819bbc8fce17ca7c7b1b320499a3893dee | 2,991 |
def makeFields(prefix, n):
"""Generate a list of field names with this prefix up to n"""
return [prefix+str(n) for n in range(1,n+1)] | 435571557ef556b99c4729500f372cc5c9180052 | 2,992 |
def process_input_dir(input_dir):
"""
Find all image file paths in subdirs, convert to str and extract labels from subdir names
:param input_dir Path object for parent directory e.g. train
:returns: list of file paths as str, list of image labels as str
"""
file_paths = list(input_dir.rglob('*.... | 569d4539368888c91a12538156c611d311da03b6 | 2,993 |
def fak(n):
""" Berechnet die Fakultaet der ganzen Zahl n. """
erg = 1
for i in range(2, n+1):
erg *= i
return erg | 9df6f4fa912a25535369f4deb0a06baef8e6bdcc | 2,994 |
import re
def create_sequences_sonnets(sonnets):
"""
This creates sequences as done in Homework 6, by mapping each word
to an integer in order to create a series of sequences. This function
specifically makes entire sonnets into individual sequences
and returns the list of processed sonnets back t... | 56087140fe5ed8934b64a18567b4e9023ddc6f59 | 2,995 |
def load_subspace_vectors(embd, subspace_words):
"""Loads all word vectors for the particular subspace in the list of words as a matrix
Arguments
embd : Dictonary of word-to-embedding for all words
subspace_words : List of words representing a particular subspace
Returns
subspace_e... | 5eb1db8be8801cf6b1fe294a6f2c93570e9a9fe1 | 3,000 |
import codecs
import binascii
def decode_hex(data):
"""Decodes a hex encoded string into raw bytes."""
try:
return codecs.decode(data, 'hex_codec')
except binascii.Error:
raise TypeError() | 115e89d6f80a6fc535f44d92f610a6312edf6daf | 3,001 |
def generate_headermap(line,startswith="Chr", sep="\t"):
"""
>>> line = "Chr\\tStart\\tEnd\\tRef\\tAlt\\tFunc.refGene\\tGene.refGene\\tGeneDetail.refGene\\tExonicFunc.refGene\\tAAChange.refGene\\tsnp138\\tsnp138NonFlagged\\tesp6500siv2_ea\\tcosmic70\\tclinvar_20150629\\tOtherinfo"
>>> generate_heade... | 16bbbc07fa13ff9bc8ec7af1aafc4ed65b20ec4c | 3,016 |
import math
def log_density_igaussian(z, z_var):
"""Calculate log density of zero-mean isotropic gaussian distribution given z and z_var."""
assert z.ndimension() == 2
assert z_var > 0
z_dim = z.size(1)
return -(z_dim/2)*math.log(2*math.pi*z_var) + z.pow(2).sum(1).div(-2*z_var) | a412b9e25aecfc2baed2d783a2d7cd281fadc9fb | 3,017 |
def _get_crop_frame(image, max_wiggle, tx, ty):
"""
Based on on the max_wiggle, determines a cropping frame.
"""
pic_width, pic_height = image.size
wiggle_room_x = max_wiggle * .5 * pic_width
wiggle_room_y = max_wiggle * .5 * pic_height
cropped_width = pic_width - wiggle_room_x
cropped_h... | 18442a97544d6c4bc4116dc43811c9fcd0d203c6 | 3,019 |
def l2sq(x):
"""Sum the matrix elements squared
"""
return (x**2).sum() | c02ea548128dde02e4c3e70f9280f1ded539cee9 | 3,020 |
def comp_number_phase_eq(self):
"""Compute the equivalent number of phase
Parameters
----------
self : LamSquirrelCage
A LamSquirrelCage object
Returns
-------
qb: float
Zs/p
"""
return self.slot.Zs / float(self.winding.p) | f4679cf92dffff138a5a96787244a984a11896f9 | 3,021 |
from typing import Optional
from typing import Iterable
def binidx(num: int, width: Optional[int] = None) -> Iterable[int]:
""" Returns the indices of bits with the value `1`.
Parameters
----------
num : int
The number representing the binary state.
width : int, optional
Minimum n... | 70d1895cf0141950d8e2f5efe6bfbf7bd8dbc30b | 3,024 |
def _get_object_description(target):
"""Return a string describing the *target*"""
if isinstance(target, list):
data = "<list, length {}>".format(len(target))
elif isinstance(target, dict):
data = "<dict, length {}>".format(len(target))
else:
data = target
return data | 57ad3803a702a1199639b8fe950ef14b8278bec1 | 3,027 |
def computeStatistic( benchmarks, field, func ):
"""
Return the result of func applied to the values of field in benchmarks.
Arguments:
benchmarks: The list of benchmarks to gather data from.
field: The field to gather from the benchmarks.
func: The function to apply to the data... | 7eced912d319a3261170f8274c4562db5e28c34c | 3,028 |
def flat_list_of_lists(l):
"""flatten a list of lists [[1,2], [3,4]] to [1,2,3,4]"""
return [item for sublist in l for item in sublist] | c121dff7d7d9a4da55dfb8aa1337ceeea191fc30 | 3,031 |
def multiVecMat( vector, matrix ):
"""
Pronásobí matici vektorem zprava.
Parametry:
----------
vector: list
Vektor
matrix: list
Pronásobená matice. Její dimenze se musí shodovat s dimenzí
vektoru.
Vrací:
list
Pole velikosti ve... | 8a10241173ab981d6007d8ff939199f9e86806e5 | 3,033 |
def etaCalc(T, Tr = 296.15, S = 110.4, nr = 1.83245*10**-5):
"""
Calculates dynamic gas viscosity in kg*m-1*s-1
Parameters
----------
T : float
Temperature (K)
Tr : float
Reference Temperature (K)
S : float
Sutherland constant (K)
nr : ... | 3f8182ea29fd558e86280477f2e435247d09798e | 3,037 |
def sharpe_ratio(R_p, sigma_p, R_f=0.04):
"""
:param R_p: 策略年化收益率
:param R_f: 无风险利率(默认0.04)
:param sigma_p: 策略收益波动率
:return: sharpe_ratio
"""
sharpe_ratio = 1.0 * (R_p - R_f) / sigma_p
return sharpe_ratio | d197df7aa3b92f3a32cc8f11eb675012ffe8af57 | 3,039 |
def _inline_svg(svg: str) -> str:
"""Encode SVG to be used inline as part of a data URI.
Replacements are not complete, but sufficient for this case.
See https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
for details.
"""
replaced = (
svg
.replace('\n', '%0A')
.r... | 4e3c25f5d91dd7691f42f9b9ace4d64a297eb32f | 3,040 |
import click
def implemented_verified_documented(function):
""" Common story options """
options = [
click.option(
'--implemented', is_flag=True,
help='Implemented stories only.'),
click.option(
'--unimplemented', is_flag=True,
help='Unimplement... | 8c1dd5aaa0b962d96e9e90336183a29e2cf360db | 3,041 |
import json
def get_config(config_path):
""" Open a Tiler config and return it as a dictonary """
with open(config_path) as config_json:
config_dict = json.load(config_json)
return config_dict | 72a2133b44ffc553ad72d6c9515f1f218de6a08c | 3,049 |
import binascii
def fmt_hex(bytes):
"""Format the bytes as a hex string, return upper-case version.
"""
# This is a separate function so as to not make the mistake of
# using the '%X' format string with an ints, which will not
# guarantee an even-length string.
#
# binascii works on all ve... | d25379ec333a653549c329932e304e61c57f173d | 3,050 |
import json
import six
def _HandleJsonList(response, service, method, errors):
"""Extracts data from one *List response page as JSON and stores in dicts.
Args:
response: str, The *List response in JSON
service: The service which responded to *List request
method: str, Method used to list resources. O... | db87c9ed87df1268e1187f74c193b5f96f9e10f7 | 3,054 |
def clip(x, min_, max_):
"""Clip value `x` by [min_, max_]."""
return min_ if x < min_ else (max_ if x > max_ else x) | 3ad7625fa3dc5a0c06bb86dc16698f6129ee9034 | 3,055 |
def coordinateToIndex(coordinate):
"""Return a raw index (e.g [4, 4]) from board coordinate (e.g. e4)"""
return [abs(int(coordinate[1]) - 8), ("a", "b", "c", "d", "e", "f", "g", "h").index(coordinate[0])] | d3dcf6d01c4bec2058cffef88867d45ba51ea560 | 3,069 |
def get_parent(inst, rel_type='cloudify.relationships.contained_in'):
"""
Gets the parent of an instance
:param `cloudify.context.NodeInstanceContext` inst: Cloudify instance
:param string rel_type: Relationship type
:returns: Parent context
:rtype: :class:`cloudify.context.RelationshipSubj... | 06bc76ec55735a47a3cf26df2daa4346290671ee | 3,071 |
def get_shared_keys(param_list):
"""
For the given list of parameter dictionaries, return a list of the dictionary
keys that appear in every parameter dictionary
>>> get_shared_keys([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'a':0, 'b':'beta'}])
['a', 'b']
>>> get_shared_keys([{'a':0, 'd':3}, {'a':0... | 0f6aa0df4d61ba166ac7d660be80a98fdbc29080 | 3,074 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.