content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def negative_log_likelihood(y_true, predicted_distributions): """Calculates the negative log likelihood of the predicted distribution ``predicted_distribution`` and the true label value ``y_true`` # Arguments y_true: Numpy array of shape [num_samples, 1]. predicted_distribution: TensorFlow probability distribution """ log_likelihood = predicted_distributions.log_prob(y_true) return - log_likelihood
cb212b478a087cf995be84549dea1ad0869838f5
654,867
def _count(bs) -> int: """Given a sequence of bools, count the Trues""" return sum(1 for b in bs if b)
58a030c42f369407f61c8f9234950d3c0bbc31b5
496,895
from typing import List from typing import Dict from typing import Any def parse_unknown_options(args: List[str]) -> Dict[str, Any]: """Parse unknown options from the CLI. Args: args: A list of strings from the CLI. Returns: Dict of parsed args. """ warning_message = ( "Please provide args with a proper " "identifier as the key and the following structure: " '--custom_argument="value"' ) assert all(a.startswith("--") for a in args), warning_message assert all(len(a.split("=")) == 2 for a in args), warning_message p_args = [a.lstrip("--").split("=") for a in args] assert all(k.isidentifier() for k, _ in p_args), warning_message r_args = {k: v for k, v in p_args} assert len(p_args) == len(r_args), "Replicated arguments!" return r_args
e356703c36e71ab15601d64cc9187e2a91cedff4
455,302
def parse_flag(value): """ Convert string to boolean (True or false) :param value: string value :return: True if the value is equal to "true" (case insensitive), otherwise False """ return value.lower() == "true"
4555e655ecd39f362d11065718e10b144ecf2b85
633,919
def user_name_to_file_name(user_name): """ Provides a standard way of going from a user_name to something that will be unique (should be ...) for files NOTE: NO extensions are added See Also: utils.get_save_root """ # Create a valid save name from the user_name (email) # ---------------------------------------------------------------------- # Good enough for now ... # Removes periods from email addresses, leaves other characters return user_name.replace('.', '')
d1e45e47f2da4f23c8b97081438aa2d732c56bb1
239,479
import yaml def load_config(path): """Load yaml collection configuration.""" with open(path, 'r') as stream: return yaml.load(stream, Loader=yaml.SafeLoader)
4beb9fff0d471bb23e06b55e18f4d286263fbd4e
644,258
def check_end_condition(grid): """The end condition: There are no more hidden characters. :param grid: The grid. :return: Returns False if there still are hidden characters, otherwise returns True. """ char_locs = grid[2] for x in char_locs: if char_locs[x][3] == 'H' or char_locs[x][3] == 'h': return False return True
93e25b0dcc8e6ed5fd8552b45e46be7081e6aa9a
248,216
import types def _get_object_config(obj): """Return the object's config depending on string, function, or others.""" if isinstance(obj, str): # Use the content of the string as the config for string. return obj elif isinstance(obj, types.FunctionType): # Keep track of the function's module and name in a dict as the config. return { 'module': obj.__module__, 'function_name': obj.__name__, } if not hasattr(obj, 'get_config'): raise TypeError(f'Unable to recognize the config of {obj}.') return obj.get_config()
ea95c5131e10400dd773a218cb93879849964027
469,100
from functools import reduce def excel_col_letter_to_index(x): """ Convert a 'AH','C', etc. style Excel column reference to its integer equivalent. @param x (str) The letter style Excel column reference. @return (int) The integer version of the column reference. """ return reduce(lambda s,a:s*26+ord(a)-ord('A')+1, x, 0)
800f650118c1216727be18722aa4b435ec34b56f
692,397
def delete_models(client, model=None, drawing=None, delete_views=None): """Delete one or more models from a drawing. Args: client (obj): creopyson Client model (str, optional): Model name (wildcard allowed: True). Defaults: all models will be deleted from the drawing. drawing (str, optional): Drawing name. Defaults: current active drawing. delete_views (boolean, optional): Whether to delete drawing views associated with the model. Defaults is False. Returns: None """ data = {} if drawing: data["drawing"] = drawing if model: data["model"] = model if delete_views: data["delete_views"] = delete_views return client._creoson_post("drawing", "delete_models", data)
213da46fcb9af55c340bc687010a2d44661e5e57
497,273
def apply_ratio(o_w, o_h, t_w, t_h): """Calculate width or height to keep aspect ratio. o_w, o_h -- origin width and height t_w, t_h -- target width or height, the dimension to be calculated must be set to 0. Returns: (w, h) -- the new dimensions """ new_w = t_h * o_w / o_h new_h = t_w * o_h / o_w return new_w+t_w, new_h+t_h
f3143e5a5ad8aeafbb913e73aab40e8e8990ddd6
16,045
def convert_to_list(xml_value): """ An expected list of references is None for zero values, a dict for one value, and a list for two or more values. Use this function to standardize to a list. If individual items contain an "@ref" field, use that in the returned list, otherwise return the whole item Args: xml_value (dict or list): value to transform to a list Returns: list: processed list of values from original xml_value """ if not xml_value: return [] elif isinstance(xml_value, dict): return [xml_value.get('@ref', xml_value)] else: return [val.get('@ref', val) for val in xml_value]
17bb8e21e4247a14a37bb98643cfe9f847168c4c
83,420
def get_attr(obj, attr, default=None): """Recursive get object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> get_attr(a, 'b.c') 4 >>> get_attr(a, 'b.c.y', None) >>> get_attr(a, 'b.c.y', 1) 1 """ if '.' not in attr: return getattr(obj, attr, default) else: L = attr.split('.') return get_attr(getattr(obj, L[0], default), '.'.join(L[1:]), default)
a14b821ed3d5ea61abc9b66cb80df4391519055d
464,170
def get_im_physical_coords(array, grid, image_data, direction): """ Converts one dimension of "pixel" image (row or column) coordinates to "physical" image (range or azimuth in meters) coordinates, for use in the various two-variable sicd polynomials. Parameters ---------- array : numpy.array|float|int either row or col coordinate component grid : sarpy.io.complex.sicd_elements.Grid.GridType image_data : sarpy.io.complex.sicd_elements.ImageData.ImageDataType direction : str one of 'Row' or 'Col' (case insensitive) to determine which Returns ------- numpy.array|float """ if direction.upper() == 'ROW': return (array - image_data.SCPPixel.Row)*grid.Row.SS elif direction.upper() == 'COL': return (array - image_data.SCPPixel.Col)*grid.Col.SS else: raise ValueError('Unrecognized direction {}'.format(direction))
18db75e08404004f0515233b4e759d4d69b92598
571,170
def contact_sequence(data, pIDs): """ Given a pd.DataFrame with variables ['gID', 'pID', 'begin', 'end'], generate a contact sequence of events (j, i, t) where j is the group member being interrupted, i is the group member doing the interrupting, and t is the start time of the interruptive speech. Ignores non-interruptive simultaneous speech. Ref: Holme & Saramäki (2012) """ C = [] data = data[data['pID'].isin(pIDs)] for i in range(len(data)): ego = data.iloc[i, :] interruptions = data[ (data['end'] > ego['end']) & (data['begin'] < ego['end']) & (data['begin'] >= ego['begin']) ] if interruptions.empty: continue else: for j in range(len(interruptions)): alter = interruptions.iloc[j, :] c = (ego['pID'], alter['pID'], alter['begin']) C.append(c) C = sorted(C, key = lambda x: x[2]) return C
bb36b4bddefc094f036a32319a5cdf47b146005d
645,057
def matrix_mult(a, b): """ Function that multiplies two matrices a and b Parameters ---------- a,b : matrices Returns ------- new_array : matrix The matrix product of the inputs """ new_array = [] for i in range(len(a)): new_array.append([0 for i in range(len(b[0]))]) for j in range(len(b[0])): for k in range(len(a[0])): new_array[i][j] += a[i][k] * b[k][j] return new_array
5e0f27f29b6977ea38987fa243f08bb1748d4567
708,359
def emulator_uses_kvm(emulator): """Determines if the emulator can use kvm.""" return emulator["uses_kvm"]
654ec1207180e0ac90af71d9333acf3ef431add6
67,164
def expand_features_and_labels(x_feat, y_labels): """ Take features and labels and expand them into labelled examples for the model. """ x_expanded = [] y_expanded = [] for x, y in zip(x_feat, y_labels): for segment in x: x_expanded.append(segment) y_expanded.append(y) return x_expanded, y_expanded
5cd5dbe18285fdcbc633809cd95dde17e32dd82b
47,651
import math def calc_rms(data, channel, num_channels, num_samples_per_channel): """ Calculate RMS of a data buffer """ value = 0.0 for i in range(num_samples_per_channel): index = (i * num_channels) + channel value += (data[index] * data[index]) / num_samples_per_channel return math.sqrt(value)
cd6bf82aeda1e54f692060befcfbd1dc47cedf86
171,620
def get_number_rows(pi_settings, ship_height, alien_height): """Determine the number of rows of aliens that fit on the screen.""" available_space_y = (pi_settings.screen_height - (3 * alien_height) - ship_height) number_rows = int(available_space_y / (alien_height)) return number_rows
3f0cb2282405e543aee93600dfdecda6a7870f79
537,110
def format_multitask_preds(preds): """ Input format: list of dicts (one per task, named with task_name), each having a 'predictions' list containing dictionaries that represent predictions for each sample. Prediction score is represented by the field {task_name}_score in each of those dicts. Output format: a list of lists of dictionaries, where now each dictionary include scores for all the tasks that were included in the input. """ out = [] score_names = [f"{task['task']}_score" for task in preds[1:]] first_task = preds[0] for sentence_idx, sentence in enumerate(first_task["predictions"]): out_sent = [] for token_idx, token in enumerate(sentence): for task, score in zip(preds[1:], score_names): token[score] = task["predictions"][sentence_idx][token_idx][score] out_sent.append(token) out.append(out_sent) return out
470b23f6a5cc6b8e48ce0becfafd62104e016de8
12,041
def rivers_with_stations(stations): """This returns a list of all the rivers which have monitoring stations on them""" rivers = [] for s in stations: if s.river not in rivers: rivers.append(s.river) return rivers
4fb7490a0613b2aded3ac42dccb225fef4a147ac
325,490
def calcStraightLine(x0, y0, x1, y1): """ calculates the slope and the axis intercept of a straight line using to points in an x, y grid :Parameters: x0, y0, x1, y1: float 2 points in an x, y grid :Returns: m, b: float the slope and the axis intercept of the calculated straight line """ m = (y1 - y0) /(x1 - x0) b = (x1*y0 - x0*y1)/(x1 - x0) return m, b
43ca4c5072ecb25d4cda334f1b51337cf8e4bc0d
562,728
def normalize_node_id(nid): """Returns a suitable DOT node id for `nid`.""" return '"%s"' % nid
ec40c11895ca6976792ba37eec10e6ef0d61bfde
319,282
def add_header(response): """Add header to response.""" response.cache_control.max_age = 300 response.cache_control.no_cache = True response.cache_control.must_revalidate = True response.cache_control.proxy_revalidate = True return response
b2ae7e23bd1b419c7c2664ee45dad4f0598617d4
464,802
def getReward(state, marker): """Given the state (a board) determine the reward.""" if ( state.gameWon() ): return marker * 10 else: return 0
b4532c64ae1229c15c4c4c391b07d4fb1fd0eba4
367,005
import torch def pow_p_norm(signal): """Compute 2 Norm""" return torch.pow(torch.norm(signal, p=2, dim=-1, keepdim=True), 2)
2f4a1cce69ce765b1768ed2548c2749f856b5c75
176,361
def recursive_multiply(a: int, b: int, _sum: int = 0) -> int: """Multiplies a with b, returns product Args: a (int): factor of product b (int): factor of product _sum (int): private, shouldn't be used Returns: int: product of a * b """ if b != 0: if b > 0: _sum += a b -= 1 else: _sum -= a b += 1 return recursive_multiply(a, b, _sum) else: return _sum
f8d13c02e96b5c90db3f1c3a4f00031c65066622
177,393
def filter_dictionary_starts_with(dictionary, prefix): """Filters a dictionary from a key prefix.""" return {key: dictionary[key] for key in dictionary if key.startswith(prefix)}
49fc5d9701c7f0c2856c10154508654a739f49c3
208,789
import socket import struct def ip2d(ip): """IP to decimal""" packed = socket.inet_aton(ip) return struct.unpack("!L", packed)[0]
0dbbac8438da0ce705633573c701033ee72763bb
467,122
def _dehydrate_token(token): """ Convert the request token into a dict suitable for storing in the session. """ session_token = {} session_token["key"] = token.key session_token["secret"] = token.secret return session_token
5b2b27e0e4f7de776d1ef35e16be1bec1328ef3b
204,959
def get_closer(a, b, test_val): """Returns which ever of a or b is closer to test_val""" diff_a = abs(a - test_val) diff_b = abs(b - test_val) if diff_a < diff_b: return a else: return b
42452b2b03314f96ca8793802e1cd7e5ec7a8b1b
117,000
def create_constant_learning_rate_fn(base_learning_rate): """Create a constant learning rate function. Args: base_learning_rate: learning rate that will always be returned Returns: function of the form f(step) -> learning_rate """ def step_fn(step): ## pylint: disable=unused-argument return base_learning_rate return step_fn
1ba81be7545080ec8be6ec550fe91500cee552ee
282,884
def strip_math(s): """remove latex formatting from mathtext""" remove = (r'\mathdefault', r'\rm', r'\cal', r'\tt', r'\it', '\\', '{', '}') s = s[1:-1] for r in remove: s = s.replace(r, '') return s
ef1231185b1344b6dbf8897198057a11b1ecc652
503,509
from importlib import import_module def load_app(module_name, objects=None): """Simply loads and returns an app module for you.\n Params: - module_name - module name of your app. - objects (str) - if provided, returns a certain part of the module instead of the whole thing. Example: `load_app('my_app', objects='views')` will return `my_app.views`. """ if objects: return import_module(module_name + '.' + objects) else: return import_module(module_name)
0bc98ba83a27302d1047c58ca7125f5ceecc419a
510,853
from typing import List def nine_to_no_fix(alts: List[str]) -> List[str]: """ Google ASR specific GASR gives 9 when the person says no or not. Therefore if both of them are present at the start of the sentence, convert all 9 to no """ count_9 = 0 count_no = 0 if len(alts) < 2: return alts for txt in alts: if txt: if txt.split()[0] == "9": count_9 += 1 elif txt.split()[0] in ["no", "not"]: count_no += 1 if count_no and count_9: output_texts = [] for txt in alts: if txt and txt.split()[0] == "9": output_texts.append("no " + " ".join(txt.split()[1:])) else: output_texts.append(txt) return output_texts else: return alts
0811e71f5128796f1dfc7d385465bdf8264b6b72
288,328
from datetime import datetime def minutes_to_datetime(minutes: int): """ Convert minutes to datetime :param minutes: int :return: datetime """ days, remainder = divmod(minutes, 24 * 60) hours, minutes = divmod(remainder, 60) return datetime(1900, 1, 1+days, hours, minutes)
4f4cae1cdd7cd8c30dfdd3318808bc6a688a9d04
281,275
def calc_step(epoch: int, n_batches: int, batch_index: int) -> int: """Calculates current step. Args: epoch (int): Current epoch. n_batches (int): Number of batches in dataloader. batch_index (int): Current batch index. Returns: int: Current step. """ return (epoch - 1) * n_batches + (1 + batch_index)
333ccb043213bc007d77c8e087c4523613605d8e
320,613
def get_feature(tablerow): """Extract the feature of a tablerow. Parameters: tablerow (bs4.BeautifulSoup): A tablerow from the wikipedia infobox in html Returns: feature (str): Feature of the tablerow Raises: None """ tableheader = tablerow.find('th') if tableheader: feature = tableheader.text else: feature = '' return feature
767f422aad2ff82fd86f10cbce9b6208fff6bef2
301,376
def _adjust_component(component: int) -> int: """Return the midpoint of the quadrant of the range 0-255 that the given component belongs to. Each quadrant spans 63 integers, and the midpoints are: 31, 95, 159, 223. >>> _adjust_component(25) 31 >>> _adjust_component(115) 95 """ if component <= 63: return 31 elif component > 63 and component <= 127: return 95 elif component > 127 and component <= 191: return 159 else: #component > 191 return 223
444baac61f20dc32d05c60900f6fe7dbf7374d51
670,731
def get_centroid(M): """ Returns the centroid using the inputted image moments. Centroid is computed as being the first moment in x and y divided by the zeroth moment. Parameters ---------- M : list List of image moments. Returns ------- tuple Centroid of the image moments. """ return int(M['m10']/M['m00']), int(M['m01']/M['m00'])
7da4f9ef80e7daee6d95c121088e136a4c93756c
491,835
def sorted_dict(d, key=None, reverse=False): """ Return dictionary sorted using key. If no key provided sorted by dict keys. """ if key is None: return dict(sorted(d.items(), key=lambda e: e[0], reverse=reverse)) return dict(sorted(d.items(), key=key, reverse=reverse))
97b08901c1cd39a2fb17ae6db0cfd088e8366e70
83,022
import fnmatch def select_signals(signal_list, signal_spec): """ Selects signals from a signal list following signal specifications. signal_list: List of strings of possible signal names signal_spec: List of strings with signal specifications including wildcards Normal Unix file name wildcards are accepted and extended with [<num>-<num>] type expressions so as e.g. a channel range can be selected. Returs select_list, select_index select_list: List of strings with selected signal names select_index: List of indices to signal list of the selected signals Raises ValueError if there is no match for one specification """ if (type(signal_spec) is not list): _signal_spec = [signal_spec] else: _signal_spec = signal_spec if ((len(_signal_spec) == 0) or (signal_list == [])): raise ValueError("No signal list or signal specification.") select_list = [] select_index = [] for ch in _signal_spec: # This will add a list of possible channel names to the _signal_spec while [<num>-<num>} is found startpos = 0 extended = False extended_list = [] while 1: # Searching for opening and closing [] for i1 in range(startpos,len(ch)): if (ch[i1] == '['): break else: break if (i1 == len(ch)-1): break for i2 in range(i1+1,len(ch)): if (ch[i2] == ']'): break else: break # found the opening and closing bracket # Trying to interpret the string between the brackets as <int> - <int> try: nums = ch[i1+1:i2].split('-') nums = [int(nums[0]), int(nums[1])] # Extracting the strings before and after the [] except Exception: if (i2 >= len(ch)-2): break startpos = i2+1 continue if (i1 == 0): str1 = "" else: str1 = ch[0:i1] if (i2 < len(ch)-1): str2 = ch[i2+1:len(ch)] else: str2 = "" extended = True for i in range(nums[0],nums[1]+1): # Adding all the possible strings extended_list.append(str1+str(i)+str2) startpos = i2+1 continue ch_match = False # if extended list is created not checking original name if (not extended): for i in range(len(signal_list)): if (fnmatch.fnmatch(signal_list[i], ch)): select_list.append(signal_list[i]) select_index.append(i) ch_match = True if (extended): for i in range(len(signal_list)): for che in extended_list: if (fnmatch.fnmatch(signal_list[i], che)): select_list.append(signal_list[i]) select_index.append(i) ch_match = True break if (not ch_match): raise ValueError("Signal name: " + ch + " is not present.") return select_list, select_index
9d39ef92641e851395f02c81117d046d907d229f
224,542
def crop_scores(player): """Select specific only parts of the full score object Args: player (dict): player object from which to read the score Returns: score (dict): filtered scores from the game data """ score = {} # if there is no active username, nobody finished, but the # last seen player might still get a valid rank if player['username'] in ['dead', 'open']: score['finished'] = 0 score['rank'] = player['finishrank'] return score keys_wanted = [ 'capitalships', 'freighters', 'planets', 'starbases', 'militaryscore', 'percent', ] score = {k: player['score'].get(k, None) for k in keys_wanted} score['finished'] = 1 score['rank'] = player['finishrank'] return score
5466cf39b59ce4b49b7da3ff2c355b2d7b46455c
35,959
def percent_delta(old_score, new_score): """Calculates the percent change between two scores. """ return float(new_score - old_score) / float(old_score)
ceaf4e0eecb436818c12a52c32fb1db7f88ca102
582,044
def accession_entry_map(klass): """Creates a `dict` mapping from accessions to the owning instance. for all instances in the database represented by `klass`. Parameters ---------- klass : :class:`Pubmed` or :class:`Psimi` A class having the accession attribute. Returns ------- dict[str, object] A dictionary mapping from accession to the associated instance. """ if not hasattr(klass, 'accession'): raise AttributeError( "`{}` does not have the attribute `accession`." % klass.__name__ ) items = klass.query.all() mapping = {e.accession: e for e in items} return mapping
d3ca955ccea5ee45e1eb938f89c6fdd61ff42390
322,982
def difference(li1, li2): """Difference of two lists.""" return list(list(set(li1)-set(li2)) + list(set(li2)-set(li1)))
c2e9b30c5eeed330f7a10531c4269c6aa43e3ab7
65,856
def calcGeometricMean (theList): """Calculates the geometric mean of a list of values. :param theList: The list of which the geometric mean :type theList: list :return: The geometric mean of the values of theList :rtype: float """ product = 1 root = 0 for value in theList: product *= value root += 1 return product ** (1 / root)
923ca02c2bb39e65fd7f25eaf0becaae03bdeb18
106,231
def equal_zip(*args): """ Zip which also verifies that all input lists are of the same length """ # make sure that all lists are of the same length assert len(set(map(len, args))) == 1, "lists are of different lengths {}".format(args) return zip(*args)
f50ad8586d24516ba641e1bbef5d62879a0f3d6b
23,922
def limit_vector(vector, bottom_limit, upper_limit): """ This function cut the a vector to keep only the values between the bottom_limit and the upper_limit. Parameters ---------- vector : list The vector that will be cut upper_limit : float The maximum value of the vector. bottom_limit : float The minimum value of the vector Returns ------- vector : iterable The limited vector """ temp = [] for x in vector: if bottom_limit <= x <= upper_limit: temp.append(x) return temp
5c520f09e6caac08461cd6add911ea69a12afa72
47,293
def dict_get(d, *args): """Get the values corresponding to the given keys in the provided dict.""" return [d[arg] for arg in args]
0202cbed5cc2b81b1d8b74986630e3c797596837
595,111
def construct_resolver(model_name, resolver_type): """Constructs a resolve_[cable_peer|connected_endpoint]_<endpoint> function for a given model type. Args: model_name (str): Name of the model to construct a resolver function for (e.g. CircuitTermination). resolver_type (str): One of ['connected_endpoint', 'cable_peer'] """ if resolver_type == "cable_peer": def resolve(self, args): peer = self.get_cable_peer() if type(peer).__name__ == model_name: return peer return None return resolve if resolver_type == "connected_endpoint": def resolve(self, args): peer = self.connected_endpoint if type(peer).__name__ == model_name: return peer return None return resolve
e7c16fec9e68d875725692349742380dfb1e0e2c
198,973
def Predict_Var(vcf, snp_mdl, ind_mdl): """Predicts the truth value of a variant Parameters ---------- vcf : DataFrame vcf file with variants of interest snp_mdl : XGBClassifier classifier object, trained on SNPs ind_mdl : XGBClassifier classifier object, trained on InDels Returns ------- int an integer representation of whether or not a variant is predicted to be real """ params = vcf.iloc[0:11].values if vcf['Is_SNP'] == 1: return int(snp_mdl.predict(params[None, :])) else: return int(ind_mdl.predict(params[None, :]))
1544785f95b02016f249f5b5e390a1b075c1325b
439,617
def slice_list(list_a: list, start: int, end: int): """Problem 18: Extract a slice from list. Parameters ---------- list_a : list The input list start : int The start of the slice end : int The end of the slice Returns ------- list A slice of the initial list Raises ------ TypeError If the given argument is not of `list` type ValueError If the values of `start` and / or `end` are invalid """ if not isinstance(list_a, list): raise TypeError('The argument given is not of `list` type.') if start < 1 or len(list_a) < start: raise ValueError('The value of `start` argument is not valid') if end < start or len(list_a) < end: raise ValueError('The value of `end` argument is not valid') return list_a[(start - 1):end]
853088bb218666771e6024953e9956524b139443
665,452
def rk4_step(force, state, time, dt): """Compute one step of the rk4 approximation. Parameters ---------- force : callable Vector field that is being integrated. state : array-like, shape=[2, dim] State at time t, corresponds to position and velocity variables at time t. time : float Time variable. dt : float Time-step in the integration. Returns ------- point_new : array-like, shape=[,,,, {dim, [n, n]}] First variable at time t + dt. vector_new : array-like, shape=[,,,, {dim, [n, n]}] Second variable at time t + dt. See Also -------- https://en.wikipedia.org/wiki/Runge–Kutta_methods """ k1 = force(state, time) k2 = force(state + dt / 2 * k1, time + dt / 2) k3 = force(state + dt / 2 * k2, time + dt / 2) k4 = force(state + dt * k3, time + dt) new_state = state + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4) return new_state
9d2eb400d608d1c15b73e1e78fcd3bebaff868bd
363,471
import time def fade_to_black(connection): """Transition from the current brightness to zero in a smooth fade""" command = "X03FE" # Lowers by 2 points # Loop until the number is 0 i = 0 while i < 128: connection.write(bytes(command, 'UTF-8')) i += 1 time.sleep(0.03) return True
1de93280291d873c8928140a6ff6410fce70bde1
405,390
import torch def _default_collate_mbatches_fn(mbatches): """Combines multiple mini-batches together. Concatenates each tensor in the mini-batches along dimension 0 (usually this is the batch size). :param mbatches: sequence of mini-batches. :return: a single mini-batch """ batch = [] for i in range(len(mbatches[0])): t = torch.cat([el[i] for el in mbatches], dim=0) batch.append(t) return batch
e3855ff27ec82e723008b9ad6ad6af94fda27b23
323,775
import pytz def add_timezone(time_record): """ Add a default America/New_York timezone info to a datetime object. Args: time_record: Datetime object. Returns: Datetime object with a timezone if time_record did not have tzinfo, otherwise return time_record itself. """ if time_record.tzname() is None: return time_record.replace(tzinfo=pytz.timezone('America/New_York')) return time_record
e3e16fbb87f9d5ff3a3bd5c7f24b3bd880700a00
127,352
import pickle def compare_pickles(filename_1, filename_2): """Read in both pickles, and see if they match, and return both of them. Inputs: filename_1: string filename_2: string Outputs: pickle_equal: boolean - True iff the pickles have identical contents pickle_1: object from filename_1 pickle_2: object from filename_2 """ pickle_1 = pickle.load(open(filename_1, "rb")) pickle_2 = pickle.load(open(filename_2, "rb")) pickle_equal = (pickle_1 == pickle_2) return pickle_equal, pickle_1, pickle_2
83af39a6b2416d15bbe97a3c29d7a3e6a8c43bd1
345,705
def clean_name(name): """Replace dashes and spaces with underscores""" return '_'.join(name.split()).replace('-', '_')
5de49ec064b3e6b4359d29d822fd732d080f8a43
641,612
from typing import Any import json def to_json(path: str, output: Any) -> None: """ Writes output to json file Args: path (str): Output path output (Any): Content to output """ with open(path, "w") as stream: return json.dump(output, stream)
9957f8678f94fb9c440cfc0d3387ae8f281e054b
512,454
from typing import List from typing import Any from typing import Dict import torch def my_data_collator(features: List[Any]) -> Dict[str, torch.Tensor]: """ A nearly identical version of the default_data_collator from the HuggingFace transformers library. """ first = features[0] batch = {} # Special handling for labels. # Ensure that tensor is created with the correct type # (it should be automatically the case, but let's make sure of it.) if "label" in first and first["label"] is not None: label = first["label"].item() if isinstance(first["label"], torch.Tensor) else first["label"] dtype = torch.long if isinstance(label, int) else torch.float batch["labels"] = torch.tensor([f["label"] for f in features], dtype=dtype) elif "label_ids" in first and first["label_ids"] is not None: if isinstance(first["label_ids"], torch.Tensor): batch["labels"] = torch.stack([f["label_ids"] for f in features]) else: dtype = torch.long if type(first["label_ids"][0]) is int else torch.float batch["labels"] = torch.tensor([f["label_ids"] for f in features], dtype=dtype) # Handling of all other possible keys. # Again, we will use the first element to figure out which key/values are not None for this model. for k, v in first.items(): if k not in ("label", "label_ids") and v is not None and not isinstance(v, str): if isinstance(v, torch.Tensor): batch[k] = torch.stack([f[k] for f in features]) else: batch[k] = torch.tensor([f[k] for f in features], dtype=torch.long) return batch
80e8e92fee033716ee1e5b22231e6127d2c6349e
595,991
import re def tokenize(text): """ First splits on r',|\.|and', strips the result, and removes empty tokens :param text: the text to tokenize :return: list of string tokens """ tokens = re.split(r',|\.(?![0-9])|and', text) tokens = [t.strip() for t in tokens] tokens = [t for t in tokens if t is not u''] return tokens
38cb91abc8c3cfdc87bf4aa3728184bb157daaf4
251,500
def convert_coord_to_axis(coord): """ Converts coordinate type to its single character axis identifier (tzyx). :param coord: (str) The coordinate to convert. :return: (str) The single character axis identifier of the coordinate (tzyx). """ axis_dict = {"time": "t", "longitude": "x", "latitude": "y", "level": "z"} return axis_dict.get(coord, None)
bc32c5837f7a4fb5a515ee4c3b50d67cf244da6a
261,953
def get_executors(tech): """From a loaded technique, get all executors.""" return tech['atomic_tests']
b5a8d6ed974c22f1c73b6671961b009828d1e87c
600,930
import random def generate_random(choicelist): """ This function generates a random choice of the items in the given list. """ random_choice = random.choice(choicelist) return random_choice
46129c987a78b11d8a12f43625cfd6b825efb0c9
440,138
import re def regex_compile(search_string): """ Used to compile regex search string to object. ------------Parameters---------- search_string : str : a regex pattern string to be used to search for ------------Yields-------------- A compiled regex object that can be used in regex matching commands. """ search_obj = re.compile(search_string) return search_obj
da9e64de7ba35ad3e58289827f973d127d3fc4ca
359,254
import json def get_json(data): """ Attempts to load json from data. @param data - String containing json @return - Dictionary|None """ try: return json.loads(data) except ValueError: return None
85ce81316904d5b52a21fa5c45365401ff9f3d85
311,467
import uuid def generate_molecule_object_dict(source, format, values): """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Optional dict of values (properties) for the MoleculeObject """ m = {"uuid": str(uuid.uuid4()), "source": source, "format": format} if values: m["values"] = values return m
4a917521a2fd5d4f5f5180aa7d5da60aec2cd00a
81,712
def is_viable_non_dupe(text: str, comparison) -> bool: """text must be longer than 2 ('""'), not 'NULL' and not in comparison. :param text: String to be tested. :param comparison: Dictionary or set to search for text in. :return: bool """ return 2 < len(text) and text != 'NULL' and text not in comparison
da575dffde2f13e849949350aabe73f40802f14a
697,200
def get_info(sets, **totals): """ Gets use input and adds values to the totals dictionary. Loops through the items in the totals dictionary and asks for user input for each amount and adds replaces that item's amount in the dictionary. Parameters: - sets (int): Number of sets for the current group of materials - **totals (dict): Unpacked dictionary of the totals for each set of materials. Ex: {Paper: 20, Color: 40} Returns: - (int): sets - The number of sets for the current group - (dict): totals - The material: amount dictionary for the current group """ # get user input for each item in 'totals' dictionary sets = int(input('\nHow many Sets?: ')) # loop through and replace the values in the dictionary passed # assign to a different variable by calling function on return for item in totals.keys(): totals[item] = int(input(f'How many {item} per set?: ')) return sets, totals
1d9b43c2fc10a05b23c60a8bd6230e3fac5141dc
544,376
def is_opening_ext_app(text): """ Checks if user wants to open an app. Parameters: text (string): user's speech Returns: (bool) """ state = False keyword = [ "open", "launch", "start" ] for word in keyword: if ((text.lower()).find(word.lower()) != -1): state = True return state
7a78306753cb53b3e5ff1bd2aee356c2a0a33fb6
461,601
def get_test_case_and_alg(basename): """ Extracts the changefile name and algorithm name from the basename of the file, e.g. changefile100Lazy Floyd-Warshall.out yields the output (changefile100, Lazy Floyd-Warshall) """ # Skip "changefile" in the search of an integer i = 10 while True: try: # Check if we have reached the start # of the algorithm name int(basename[i]) except ValueError: # We have reached the start of the # algorithm name break else: # We have not reached the start of # the algorithm name i += 1 # e.g. return (changefile100, Lazy Floyd-Warshall) return (basename[:i], basename[i:-4])
43e25512d534a2672b4a426f8670e92c6b07d79b
570,495
import re def check_date_format(date: str): """Parses a string for a date. Returns true if date is any of the following formats: MM/DD/YYYY MM/DD DD Arguments: date -- the date string """ return re.match('([0-9]){1,2}((\/)([0-9]){1,2}){0,1}((\/)([0-9]){4}){0,1}', date)
06287a64cc8e48367a8bab875e7165bd11fe6b23
296,863
def search_workspace(results, params, meta): """ Return result data from es_client.query and convert into a format conforming to the schema found in rpc-methods.yaml/definitions/methods/search_workspace/result """ return { "search_time": results["search_time"], "count": results["count"], "hits": [hit["doc"] for hit in results["hits"]], }
5a102b964d2ecacc4e8ae590a9afd5ed4d1dba23
446,882
import re def parse_timestep_str_from_path(path: str) -> str: """ Get the model timestep timestamp from a given path Args: path: A file or directory path that includes a timestep to extract Returns: The extrancted timestep string """ extracted_time = re.search(r"(\d\d\d\d\d\d\d\d\.\d\d\d\d\d\d)", path) if extracted_time is not None: return extracted_time.group(1) else: raise ValueError(f"No matching time pattern found in path: {path}")
fad83119e54fb7110e6f414d213cfa58c5b72db8
451,754
from typing import Any from typing import Optional from typing import Sequence def is_allowed_types(value: Any, allowed_types: Optional[Sequence[Any]], required: Optional[bool] = None) -> bool: """ Check whether the type of value is in the allowed types. :param value: the value to check the type of :param allowed_types: a list of allowed types, to be checked with :func:`isinstance`. If *None*, no type check is made. :return: whether the type is allowed """ if value is None and required is not None: return not required if allowed_types is None: return True tfound = False for t in allowed_types: if t is None: if value is None: tfound = True break elif isinstance(value, t): tfound = True break return tfound
2fd9dee9d83cd5b59b3486ab918ecd290552b6e6
118,934
def str2list(src: str) -> list: """Separate a string to a list by \n and ignore blank line at the end automatically.""" ret = src.split("\n") while ret[-1] == "\n" or ret[-1] == "": ret.pop() return ret
db14b8646db070563a7ad3cbb7a915588e9560d1
285,408
def pe6a(n=100): """ sum >>> pe6a() 25164150 """ s1 = sum(x for x in range(1, n + 1)) s2 = sum(x * x for x in range(1, n + 1)) return(s1 * s1 - s2)
8552ca60e9b734a7d3aa46ae416ee78ce7860aea
160,818
import requests import re def CTDrequest(chemName, association, outputPath): """ Function requests CTD database. Search all genes which interact with the chemical given in input. Could be several chemicals names. Analysis will be done like if it's only one chemical. If hierarchicalAssociations is used, chemical related to the chemical given in input are used as query. Focus on genes present in Homo sapiens. :param str chemName: chemical name of MeSH ids string :param str association: association name (hierarchicalAssociations or directAssociations) :param str outputPath: Folder path to save the results :return: - **homoGenesList** (*list*) – List of genes which interact with chemicals given in input (only Homo sapiens) - **chemMeSH** (*str*) – Composition of MeSH ID from chemicals given in input """ # Parameters URL = "http://ctdbase.org/tools/batchQuery.go" PARAMS = {'inputType': "chem", 'inputTerms': chemName, 'report': "genes_curated", 'format': "tsv", 'inputTermSearchType': association} homoResultsList = [] homoGenesList = [] meshNamesDict = {} chemMeSHList = [] # Request CTD requestResult = requests.get(url=URL, params=PARAMS) requestResultList = requestResult.text.split("\n") # Extract results only for Homo sapiens for element in requestResultList: elementList = element.split("\t") # resultsList.append(elementList) if re.match('#', elementList[0]): elementList[0] = re.sub('# ', "", elementList[0]) homoResultsList.append(elementList) else: if re.match(PARAMS['inputTerms'].lower(), elementList[0]): if elementList[6] == "Homo sapiens": homoResultsList.append(elementList) if elementList[4] not in homoGenesList: homoGenesList.append(elementList[4]) if elementList[1].lower() not in meshNamesDict: meshNamesDict[elementList[1].lower()] = elementList[2] # Result len # len(homoResultsList) # len(resultsList) # Build name of output results file for chem in chemName.split("|"): if chem in meshNamesDict: chemMeSHList.append(meshNamesDict[chem.lower()]) else: chemMeSHList.append(chem) chemMeSH = "_".join(chemMeSHList) resultFileName = outputPath + "/CTD_request_" + chemMeSH + ".tsv" # Write result into file with open(resultFileName, 'w') as outputFileHandler: for resultLine in homoResultsList: outputFileHandler.write("\t".join(resultLine)) outputFileHandler.write("\n") return chemMeSH, homoGenesList
2fc172e9de82568f84c386c791d0f44a966a65ce
464,380
import json from datetime import datetime import time def iso_to_unix_secs(s): """ convert an json str like {'time': '2022-02-05T15:20:09.429963Z'} to microsecs since unix epoch as a json str {'usecs': 1644927167429963} """ dt_str = json.loads(s)["time"] dt = datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%S.%fZ") usecs = int(time.mktime(dt.timetuple()) * 1000000 + dt.microsecond) return json.dumps({"usecs": usecs})
7421e6b1781b712ebc3b8bafd1d96f49c5f1d10c
35,587
import cmath import math def line_details(Z1_polar=True, Z1=[] , Z0_polar=True, Z0=[] , length=1 , CT=[1,1], VT=[1,1] , Prim=True): """This function returns the line details for a MiCOM P543 relay Inputs: Z1_polar: Set True if the input values for the line positive sequence impedance is in polar Set False for rectangular coordinates Z1: [Z1mag, Z1ang] for Z1_Polar = True, [R , jX] for Z1_Polar = False Z0_polar: Set True if the input values for the line positive sequence impedance is in polar Set False for rectangular coordinates Z0: [Z0mag, Z0ang] for Z0_Polar = True, [R , jX] for Z0_Polar = False CT: [Primary, Secondary] VT: [Primary, Secondary] Prim: Set True when the input parameters are in primary values, Set False for Secondary Values Outputs: A dictionary containing the following variables (in secondary values) Z1mag: Z1ang: K0mag: K0ang: """ if len(Z1) != 2: print('Z1 Argument Error') return if len(Z0) != 2: print('Z0 Argument Error') return if Z1_polar: Z1 = cmath.rect(Z1[0],math.radians(Z1[1])) else: Z1 = complex(Z1[0],Z1[1]) if Z0_polar: Z0 = cmath.rect(Z0[0],math.radians(Z0[1])) else: Z0 = complex(Z0[0],Z0[1]) if Prim: CTR = max(CT) / min(CT) VTR = max(VT) / min(VT) Z0 = Z0 * CTR/VTR Z1 = Z1 * CTR/VTR K0 = (Z0-Z1)/(3*Z1) K0mag = round(abs(K0),2) K0ang = round(math.degrees(cmath.phase(K0)),0) Z1mag = round(abs(Z1),2) Z1ang = round(math.degrees(cmath.phase(Z1)),0) return {'Z1mag':Z1mag, 'Z1ang':Z1ang, 'K0mag':K0mag, 'K0ang':K0ang}
154720abeef715745ee2616e858c5f610bf2cccc
605,381
def issafe(arg): """Returns False if arg contains ';' or '|'.""" return arg.find(';') == -1 and arg.find('|') == -1
f6746d5290e21eb84d7343792d277bce4c1871ff
21,804
def get_email_name(email_from): """parse email from header and return the name part First Last <ab@cd.com> -> First Last ab@cd.com -> "" """ if "<" in email_from: return email_from[: email_from.find("<")].strip() return ""
f8b9fad0a6ceff486a71b24995576845a521a83f
537,979
def remove_repeated_first_names(names): """ Question 14.4: Remove duplicate first names from input array """ seen = set() output = [] for name in names: if name[0] not in seen: output.append(name) seen.add(name[0]) return output
4b433d248bfde2075ca57d7cee6e6d6b7c224170
285,628
def get_location(response): """ Returns location of a transaction as returned in the header of a response object. :param response: response object succeeding a successful post request. :type response: requests.models.Response :return: str """ resource_location = response.headers('location') return resource_location
82bc9fb272d47fd8e9d245cb15d4581455c690a8
595,157
def _standardize_sample_or_class_weights(x_weight, output_names, weight_type): """Maps `sample_weight` or `class_weight` to model outputs. # Arguments x_weight: User-provided `sample_weight` or `class_weight` argument. output_names: List of output names (strings) in the model. weight_type: A string used purely for exception printing. # Returns A list of `sample_weight` or `class_weight` where there are exactly one element per model output. # Raises ValueError: In case of invalid user-provided argument. """ if x_weight is None or len(x_weight) == 0: return [None for _ in output_names] if len(output_names) == 1: if isinstance(x_weight, list) and len(x_weight) == 1: return x_weight if isinstance(x_weight, dict) and output_names[0] in x_weight: return [x_weight[output_names[0]]] else: return [x_weight] if isinstance(x_weight, list): if len(x_weight) != len(output_names): raise ValueError('Provided `' + weight_type + '` was a list of ' + str(len(x_weight)) + ' elements, but the model has ' + str(len(output_names)) + ' outputs. ' 'You should provide one `' + weight_type + '`' 'array per model output.') return x_weight if isinstance(x_weight, dict): x_weights = [] for name in output_names: x_weights.append(x_weight.get(name)) return x_weights else: raise TypeError('The model has multiple outputs, so `' + weight_type + '` ' 'should be either a list or a dict. ' 'Provided `' + weight_type + '` type not understood: ' + str(x_weight))
f0997b61a2759f35ee3aabddc8b57e3424843562
330,632
def traverse_enum(type_context, enum_proto, visitor): """Traverse an enum definition. Args: type_context: type_context.TypeContext for enum type. enum_proto: EnumDescriptorProto for enum. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plugin specific output. """ return visitor.visit_enum(enum_proto, type_context)
b83864f19eb9891b4cc6877a137949857343e18f
215,381
def remove_synthetic(entries): """ Filter the given entries by removing those that are synthetic. Args: entries: An iterable of Entry nodes Yields: An iterable of Entry nodes """ return (e for e in entries if not e.synthetic)
bbbd5f79d245520d26a804f4a3a7387c10975018
282,767
from typing import MutableMapping from typing import Any def basic_params_override(dtype: str = 'float32') -> MutableMapping[str, Any]: """Returns a basic parameter configuration for testing.""" return { 'train_dataset': { 'builder': 'synthetic', 'use_per_replica_batch_size': True, 'batch_size': 1, 'image_size': 224, 'dtype': dtype, }, 'validation_dataset': { 'builder': 'synthetic', 'batch_size': 1, 'use_per_replica_batch_size': True, 'image_size': 224, 'dtype': dtype, }, 'train': { 'steps': 1, 'epochs': 1, 'callbacks': { 'enable_checkpoint_and_export': True, 'enable_tensorboard': False, }, }, 'evaluation': { 'steps': 1, }, }
341e8e3df6b0ec99d148ea43909aa28404939c15
368,834
def predict_large_image(model, input_image): """Predict on an image larger than the one it was trained on All networks with U-net like architecture in this repo, use downsampling of 2, which is only conducive for images with shapes in powers of 2. If different, please crop / resize accordingly to avoid shape mismatches. :param keras.Model model: Model instance :param np.array input_image: as named. expected shape: [num_channels, (depth,) height, width] or [(depth,) height, width, num_channels] :return np.array predicted image: as named. Batch axis removed (and channel axis if num_channels=1) """ im_size = input_image.shape num_dims = len(im_size) assert num_dims in [4, 5], \ 'Invalid image shape: only 4D and 5D inputs - 2D / 3D ' \ 'images with channel and batch dim allowed' predicted_image = model.predict(input_image) return predicted_image
f762c997c953487df32e111babfb25059a2d344d
683,060
def buildIdtoLoc(geoDict, idNameDict): """ Build a dictionary mapping from user id to country for all classes Takes as input a dictionary mapping usernames to countries (as build by builddict, above) and a dictionary that maps from ids to names (as is built by globalUserList.readId2Name) and returns a dictionary that maps from user id to country """ retDict = {} for i in iter(idNameDict): if idNameDict[i] in geoDict: retDict[i] = geoDict[idNameDict[i]] else: retDict[i] = 'unknown' return retDict
2ace83855d81adf7dc6d804d3452c3c4b4a5037e
333,852
import re def getMessageError(response): """ Extracts the error message from an ERDDAP error output. """ emessageSearch = re.search(r'message="(.*)"', response) if emessageSearch: return emessageSearch.group(1) else: return ""
020a597e8b3a93a190536dd83b7dfe12d651ed07
694,226
def round_to_full_hour(time_step: int, base=3600) -> int: """Returns given `time_step` and rounds it to nearest full hour""" return base * round(time_step / base)
38b6d78b46e1c2d026a31c0906f0f5f149eddf02
443,570
def check_emptiness(param): """ Function that checks a canvas to see if is empty or not Args: param : str The string we want to check if is empty or not Returns: Bool True if empty, False if not. """ if param not in ['\n', '\r\n']: return True else: return False
a4a5a5a31836558931a6beee9f2bca9cb5b4f7dd
337,328
def vect_mult(_V, _a): """ Multiplies vector _V (in place) by number _a """ for i in range(len(_V)): _V[i] *= _a return _V
8035b8634dc88c98f03c1531d577a05f97215ae9
342,504
def multiplex_user_input(data, cube): """ Get input from the user and ensure it's a multi-dataset dict. Parameters ---------- data: Union[pandas.DataFrame, Dict[str, pandas.DataFrame]] User input. cube: kartothek.core.cube.cube.Cube Cube specification. Returns ------- pipeline_input: Dict[str, pandas.DataFrame] Input for write pipelines. """ if not isinstance(data, dict): data = {cube.seed_dataset: data} return data
27841b3e0e22cf8259ed73db9d2289903cd88b1d
222,334
def _create_product(product_name): """Given a product name, prompt for the price and quantity Return a new product record { "name": (str), "price": (float), "quantity": (int) } """ while True: try: product_price = float(input('What is the price for the item? ')) break except ValueError: print('Enter a valid price') while True: try: product_quantity = int(input('What is the quantity of the item? ')) break except ValueError: print('Enter a valid quantity') return { 'name': product_name, 'price': product_price, 'quantity': product_quantity }
6dbe3fd064a80e261018d4094e458c1bc22e6bf3
94,345
import json def load_json_file(file_path): """Return the contents of a json file in the file path.""" if not file_path: return {} try: with open(file_path, "r", encoding="uts-8") as read_file: data = json.load(read_file) return data except FileNotFoundError as error_obj: print(f"ERROR: JSON argument file '{file_path}' was not found.") raise error_obj
5ac25e98a476cf778aa291be5e84765d5babc9e9
304,481
import csv def read_csv(file_path): """ Reads all lines from csv file into a list representing the header and a seperate list holding all data. Args: file_path (str): Path to file Returns: tuple[list[str], list[list[str]]]: Header, other rows """ with open(file_path, "r", encoding="UTF8") as f: reader = csv.reader(f) header = next(reader) # Save header rows = [] for row in reader: rows.append(row) return header, rows
46b2dbc57c00cb4e4da83741d4c777495cdf021b
424,744