content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import List from typing import Any from typing import Dict def create_filter_dict(filter_type: str, filter_by: str, filter_value: List[Any], operator: str) -> Dict[str, Any]: """Creates a dictionary with the filter for the list-incidents request. :param filter_type: The filter type. :param filter_by: The field name to filter by. :param filter_value: The filter value. :param operator: The operator to use for the filter. """ return {"filterType": filter_type, "operandOne": {"name": filter_by}, "operandTwoValues": filter_value, "operator": operator}
31c1a86c9fdfb193669e99cb1425bea9c89bf367
700,828
def get_resource_name(prefix, project_name): """Get a name that can be used for GCE resources.""" # https://cloud.google.com/compute/docs/reference/latest/instanceGroupManagers max_name_length = 58 project_name = project_name.lower().replace('_', '-') name = prefix + '-' + project_name return name[:max_name_length]
7779f71e00063b32566f05d4cb0d8daef81043c0
700,829
def find_beat(v): """ find the beat of a vector format midi using the autocorrelation function """ # binary vector for testing autocorrelation v2 = [0 if x[0] == -1 else 1 for x in v] result = [] # no need to check more than 24*4 = 96 # i.e. 4 quarter notes of standard midi for lag in range(96): s = 0 for i in range(len(v2)): if v2[i] > 0 and v2[(i + lag) % len(v2)] > 0: s += 1 result.append((lag, s)) k = 1 srt = sorted(result, key=lambda x: x[1]) while srt[-k][0] == 0: k += 1 return srt[-k][0]
b408afced09779eb69b40ae54d1fd2c2cfcf1906
700,830
def read_line_from_file(file): """Reads one line from a file and returns it as string.""" with open(file, "r") as f: result = f.readline() return result
3f3da3642e7931469e853c977aef67cd1024bbe5
700,831
def round_float(value, precision=1): """ Returns the float as a string, rounded to the specified precision and with trailing zeroes (and . if no decimals) removed. """ return str(round(value, precision)).rstrip("0").rstrip(".")
afa167709c73b2c536a795c0e38975e212311210
700,832
from typing import List import csv def read_sts_inputs(path: str) -> List[str]: """Read input texts from a tsv file, formatted like the official STS benchmark""" inputs = [] with open(path, 'r', encoding='utf8') as fh: reader = csv.reader(fh, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: try: sent_a, sent_b = row[5], row[6] inputs.append(sent_a) inputs.append(sent_b) except IndexError: print(f"Cannot parse line {row}") print(f"Done loading {len(inputs)} inputs from file '{path}'") return inputs
6af4e934d648b550298e71584eaf47e4267316ac
700,836
def standardize_parameter_type(original_type): """Standardize parameter type descriptions Args: original_type (str): The original type Returns: str: The standarized type name """ original_type = original_type.lower() if 'unc' in original_type: return 'uncertainty' if 'lev' in original_type: return 'lever' elif 'con' in original_type or 'fix' in original_type: return 'constant' raise ValueError('cannot decipher parameter ptype')
49a93bebd8ee4918bdf420ee8c285d6574a3d3d0
700,841
def _define_names(d_t, d_y, treatment_names, output_names): """ Helper function to get treatment and output names Parameters ---------- d_t: tuple of int Tuple of number of treatment (exclude control in discrete treatment scenario). d_y: tuple of int Tuple of number of outcome. treatment_names: optional None or list (Default=None) The name of treatment. In discrete treatment scenario, the name should not include the name of the baseline treatment (i.e. the control treatment, which by default is the alphabetically smaller) output_names: optional None or list (Default=None) The name of the outcome. Returns ------- d_t: int d_y: int treament_names: List output_names: List """ d_t = d_t[0] if d_t else 1 d_y = d_y[0] if d_y else 1 if treatment_names is None: treatment_names = [f"T{i}" for i in range(d_t)] if output_names is None: output_names = [f"Y{i}" for i in range(d_y)] return (d_t, d_y, treatment_names, output_names)
a475968ed70070175f5ef164d1748def62548c9d
700,845
def _as_vw_string(x, y=None): """Convert {feature: value} to something _VW understands Parameters ---------- x : {<feature>: <value>} y : int or float """ result = str(y) x = " ".join(["%s:%f" % (key, value) for (key, value) in list(x.items())]) return result + " | " + x
89e10d3bb8ad47ad4add6baee83280fa700ca65e
700,846
def index_settings(shards=5, refresh_interval=None): """Configure an index in ES with support for text transliteration.""" return { "index": { "number_of_shards": shards, "refresh_interval": refresh_interval, "analysis": { "analyzer": { "icu_latin": { "tokenizer": "lowercase", "filter": ["latinize"] } }, "filter": { "latinize": { "type": "icu_transform", "id": "Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC" # noqa } } } } }
29028b545da2e5ee2b0239029d34f863d1d9d943
700,851
import time def test_approach(approach: str, sample_no: int, func, args: tuple) -> str: """ For a given Sample #sample_no evaluates an approach by running func with provided args and logs run time """ res = f"{approach.capitalize()} Programming Approach for the Example #{sample_no}\n" start = time.time()+1 soln = func(*args) time.sleep(1) res += '%d\nTotal run time %.5f\n' % ( soln, time.time()-start) return res
ef34e7552a887fd4bee221a5d80bb3d5ab0003a9
700,852
def kwargs_to_str(kwargs): """ Returns a string of the form '(kw1=val1, kw2=val2)'. """ if len(kwargs) == 0: return "" else: return "(" + ", ".join(f"{k}={v}" for k, v in kwargs.items()) + ")"
39d50d77620061b99861fb7a1fea77ae2a2dc376
700,855
def add_CRUD_pset(pset, sm, model_name): """Adds the ServerModel CRUD function to the Primitve Set Parameters ---------- pset : PrimitiveSet the primitive set for adding the controller functions sm : ServerModel the ServerModel with the CRUD functions model_name : str the name of the OpenAPI model referring to its CRUD functions in the ServerModel ['cart' | 'pole' | 'direction'] Returns ------- PrimitiveSet the primitive set containing the ServerModel's CRUD function """ def pset_cart(): # cart CRUD functions pset.addTerminal(sm.create_cart) pset.addTerminal(sm.read_cart) pset.addTerminal(sm.update_cart) pset.addTerminal(sm.delete_cart) def pset_pole(): # cart CRUD functions pset.addTerminal(sm.create_pole) pset.addTerminal(sm.read_pole) pset.addTerminal(sm.update_pole) pset.addTerminal(sm.delete_pole) options = { 'cart': pset_cart, 'pole': pset_pole, } # add CRUD functions to pset options[model_name]() return pset
f0960c3b96789adfa2e56039ca7c072819438984
700,856
def to_litres(gallons): """Convert US gallons to metric litres""" return 3.78541 * gallons
d1a7be6f01c89b848128218cbec19913e76658cd
700,857
from typing import Sequence def all_unique(lst): """Returns True if all elements of Sequence `lst` are unique. False otherwise. """ assert isinstance(lst, Sequence) return bool(len(set(lst)) == len(lst))
546d4254d5ca287952eec6af2bda048e60bb6b89
700,860
def generate_average_csv(fname, fields, trait_list): """ Generate CSV called fname with fields and trait_list """ csv = open(fname, 'w') csv.write(','.join(map(str, fields)) + '\n') csv.write(','.join(map(str, trait_list)) + '\n') csv.close() return fname
43195ea054ea537a4860c07c03c96efc263c472f
700,861
def cpo(total_cost, total_transactions): """Return the CPT (Cost per Order). Args: total_cost (float): Total cost of marketing. total_transactions (int): Total number of transactions. Returns: cpt (float) as total cost per order """ return total_cost / total_transactions
aaaaf5a96fcbef65e59591954bded1afa13f8c47
700,868
def get_ground_truth(obj, image, question): """ Get the ground truth value for the image/question combination in reader study obj. """ ground_truths = obj.statistics["ground_truths"] return ground_truths[image][question]
522b5550344891e0985bacb9c763c4c52686cb67
700,870
def solve(f, x0): """ Solve the equation f(x) = x using a fixed point iteration. x0 is the start value. """ x = x0 for n in range(10000): # at most 10000 iterations oldX = x; x = f(x); if abs(x - oldX) < 1.0e-15: return x;
d5f5409d689c842c1a8c70b95c621360c9ae7c8c
700,874
def _total_solves(color_info): """ Return total number of linear solves required based on the given coloring info. Parameters ---------- color_info : dict dict['fwd'] = (col_lists, row_maps) col_lists is a list of column lists, the first being a list of uncolored columns. row_maps is a list of nonzero rows for each column, or None for uncolored columns. dict['rev'] = (row_lists, col_maps) row_lists is a list of row lists, the first being a list of uncolored rows. col_maps is a list of nonzero cols for each row, or None for uncolored rows. dict['sparsity'] = a nested dict specifying subjac sparsity for each total derivative. dict['J'] = ndarray, the computed boolean jacobian. Returns ------- int Total number of linear solves required to compute the total Jacobian. """ total_solves = 0 # lists[0] are the uncolored columns or rows, which are solved individually so # we add all of them, along with the number of remaining lists, where each # sublist is a bunch of columns or rows that are solved together, to get the total colors # (which equals the total number of linear solves). if 'fwd' in color_info: row_lists, _ = color_info['fwd'] total_solves += len(row_lists[0]) + len(row_lists[1:]) if 'rev' in color_info: col_lists, _ = color_info['rev'] total_solves += len(col_lists[0]) + len(col_lists[1:]) return total_solves
32031f2ba834f7d6ed310b0a71ab43884b424459
700,876
def gettext(msg, domain='python-apt'): # real signature unknown; restored from __doc__ """ gettext(msg: str[, domain: str = 'python-apt']) -> str Translate the given string. This is much faster than Python's version and only does translations after setlocale() has been called. """ return ""
a6d83a79110ec233f86878fc6aa9f37f2b3e61fa
700,878
def get_fields_by_name(model_cls, *field_names): """Return a dict of `models.Field` instances for named fields. Supports wildcard fetches using `'*'`. >>> get_fields_by_name(User, 'username', 'password') {'username': <django.db.models.fields.CharField: username>, 'password': <django.db.models.fields.CharField: password>} >>> get_fields_by_name(User, '*') {'username': <django.db.models.fields.CharField: username>, ..., 'date_joined': <django.db.models.fields.DateTimeField: date_joined>} """ if '*' in field_names: return dict((field.name, field) for field in model_cls._meta.fields) return dict((field_name, model_cls._meta.get_field(field_name)) for field_name in field_names)
8ce9c845adbff9bb53da50c7d7e208aa8077e718
700,884
def list_of_comments(fname) : """Returns list of str objects - comment records from file. - fname - file name for text file. """ #if not os.path.lexists(fname) : raise IOError('File %s is not available' % fname) f=open(fname,'r') cmts = [] for rec in f : if rec.isspace() : continue # ignore empty lines elif rec[0] == '#' : cmts.append(rec.rstrip('\n')) else : break f.close() if len(cmts)==0 : return None return cmts
5aea0668c006b4a4615cab01acd07db8dc1fb2b5
700,885
from typing import Dict def convert_to_km(distance: float, print_output: bool = True) -> Dict[str, float]: """Convert a miles distance into the double of km. Args: distance: a distance (in miles). print_output: if True, prints the progress. Returns: A dictionary with two keys ('original' and 'converted'). Raises: Exception: if the distance is not a valid value. """ if distance is None: raise Exception('distance is not valid') if print_output: print("calculating ...", "Using ", distance) return { "original": distance, # The constant 2*1.60934 is used as the robot is magic and covers twice # the distance if specified in km. "converted": distance * 3.21868 }
1fb9dbbeb890a348d0feeebaea1a308bc06b039d
700,889
import aiohttp def aiohttp_socket_timeout(socket_timeout_s): """ Return a aiohttp.ClientTimeout object with only socket timeouts set. """ return aiohttp.ClientTimeout(total=None, connect=None, sock_connect=socket_timeout_s, sock_read=socket_timeout_s)
c17a40a532aee15557b4e507439b0a7b2e98989e
700,890
def deg_to_arcsec(angle: float) -> float: """ Convert degrees to arcseconds. Args: angle: Angle in units of degrees. Returns: angle: Angle in units of arcseconds. """ return float(angle) * 3600.
02fd099627970116bf5513af8b8d2d62bdc8ed41
700,893
import json def update_chart_info(_figure, chart_data_json_str): """ A callback function to set the sample count for the number of samples that have been displayed on the chart. Args: _figure (object): A figure object for a dash-core-components Graph for the strip chart - triggers the callback. chart_data_json_str (str): A string representation of a JSON object containing the current chart data - triggers the callback. Returns: str: A string representation of a JSON object containing the chart info with the updated sample count. """ chart_data = json.loads(chart_data_json_str) chart_info = {'sample_count': chart_data['sample_count']} return json.dumps(chart_info)
fd28e28b7b48131bb56d6d9f29e4fe438b33bb7a
700,895
def read_file(filename): """ Return the content of a file as a list of strings, each corresponding to a line :param filename: string: location and name of the file :return: content of filename """ with open(filename, 'r') as ofile: content = ofile.read().splitlines() return content
58a2718265fef848e484178e407aee6f7017a52a
700,897
def score_1(game, player): # 82.14% """ Heuristics computing score using #player moves - k * #opponent moves :param game: game :param player: player :return: score """ if game.is_winner(player) or game.is_loser(player): return game.utility(player) opponent = game.get_opponent(player) player_moves = game.get_legal_moves(player) opponent_moves = game.get_legal_moves(opponent) # return float(len(player_moves) - len(opponent_moves)) # 72.86% # return float(len(player_moves) - 2 * len(opponent_moves)) # 79.29% # return float(len(player_moves) - 3 * len(opponent_moves)) # 79.29% # return float(len(player_moves) - 4 * len(opponent_moves)) # 79.29% # return float(len(player_moves) - 5 * len(opponent_moves)) # 80.71% # return float(len(player_moves) - 6 * len(opponent_moves)) # 80.71% return float(len(player_moves) - 7 * len(opponent_moves))
3995237f5d5474660c752c308e1077aad1743d06
700,898
def get_CV_current(CV): """ Helper function to compute CV current. Args: CV (pd.DataFrame): CV segement of charge Returns: (float): current reached at the end of the CV segment """ if not CV.empty: return(CV.current.iat[-1])
69e32ecadc57d0855eedfe3404db1e5ec9839862
700,904
def label_name(event_data): """Get the label name from a label-related webhook event.""" return event_data["label"]["name"]
903173b4fd9ddeb0a74a3e10be94626e0685a037
700,907
def bit_length_power_of_2(value): """Return the smallest power of 2 greater than a numeric value. :param value: Number to find the smallest power of 2 :type value: ``int`` :returns: ``int`` """ return 2 ** (int(value) - 1).bit_length()
bb49afee83ac255549ce5b5aaab80bb76ad4e337
700,908
import json def json_top_atom_count(json_str): """Count the number of atoms in a JSON topology used by wepy HDF5.""" top_d = json.loads(json_str) atom_count = 0 atom_count = 0 for chain in top_d['chains']: for residue in chain['residues']: atom_count += len(residue['atoms']) return atom_count
0e1e23cd4b9e5cedf3e6b5d815ee817798188752
700,910
def length_squared(point): """ square of length from origin of a point Args: point (QPointF) the point Returns square of length """ return point.x()*point.x() + point.y()*point.y()
0289ca736f087dd75f9b9e0f1347fdc223d03f84
700,911
def get_ancestor(taxid, tree, stop_nodes): """Walk up tree until reach a stop node, or root.""" t = taxid while True: if t in stop_nodes: return t elif not t or t == tree[t]: return t # root else: t = tree[t]
f7841bc5104f96cd66122165a0646b70fc3fd33e
700,914
def read_table(data, coerce_type, transpose=False): """ Reads in data from a simple table and forces it to be a particular type This is a helper function that allows data to be easily constained in a simple script ::return: a dictionary of with the keys being a tuple of the strings in the first row and colum of the table ::param data: the multiline string containing the table data ::param coerce_type: the type that the table data is converted to ::param transpose: reverses the data if needed Example: >>> table_data = ''' ... L1 L2 L3 L4 L5 L6 ... C1 6736 42658 70414 45170 184679 111569 ... C2 217266 227190 249640 203029 153531 117487 ... C3 35936 28768 126316 2498 130317 74034 ... C4 73446 52077 108368 75011 49827 62850 ... C5 174664 177461 151589 153300 59916 135162 ... C6 186302 189099 147026 164938 149836 286307 ... ''' >>> table = read_table(table_data, int) >>> table[("C1","L1")] 6736 >>> table[("C6","L5")] 149836 """ lines = data.splitlines() headings = lines[1].split() result = {} for row in lines[2:]: items = row.split() for i, item in enumerate(items[1:]): if transpose: key = (headings[i], items[0]) else: key = (items[0], headings[i]) result[key] = coerce_type(item) return result
6701736354b30d41b4adf7c6a11406f26c21c71b
700,919
def cat_arg_and_value(arg_name, value): """Concatenate a command line argument and its value This function returns ``arg_name`` and ``value concatenated in the best possible way for a command line execution, namely: - if arg_name starts with `--` (e.g. `--arg`): `arg_name=value` is returned (i.e. `--arg=val`) - if arg_name starts with `-` (e.g. `-a`): `arg_name value` is returned (i.e. `-a val`) - if arg_name does not start with `-` and it is a long option (e.g. `arg`): `--arg_name=value` (i.e., `--arg=val`) - if arg_name does not start with `-` and it is a short option (e.g. `a`): `-arg_name=value` (i.e., `-a val`) :param arg_name: the command line argument name :type arg_name: str :param value: the command line argument value :type value: str """ if arg_name.startswith("--"): return "=".join((arg_name, str(value))) elif arg_name.startswith("-"): return " ".join((arg_name, str(value))) elif len(arg_name) == 1: return " ".join(("-" + arg_name, str(value))) else: return "=".join(("--" + arg_name, str(value)))
bcd99ab465707e594646d2152ad7b10b32956f5e
700,921
def envelops(reg, target_reg): """Given a region and another target region, returns whether the region is enveloped within the target region.""" return (target_reg.start <= reg.start < target_reg.end) \ and (target_reg.start <= reg.end < target_reg.end)
716f2e905bdb852d9e0b85ff0482a70a64d325f1
700,927
from typing import MutableMapping from typing import Any def include_filter( include: MutableMapping[Any, Any], target: MutableMapping[Any, Any]) -> MutableMapping[Any, Any]: """Filters target by tree structure in include. Args: include: Dict of keys from target to include. An empty dict matches all values. target: Target dict to apply filter to. Returns: A new dict with values from target filtered out. If a filter key is passed that did not match any values, then an empty dict will be returned for that key. """ if not include: return target result = {} for key, subkeys in include.items(): if key in target: if subkeys and target[key] is not None: result[key] = include_filter(subkeys, target[key]) else: result[key] = target[key] return result
f1c10ec383a430700d8e7f58e8c9f6bc5180c844
700,928
def get_route_name(route): """Returns route name.""" # split once, take last peice name = route.split("/", 1)[-1] return name
3d5c916711a7631d4eb90c5eff6f1f745c97a664
700,932
import requests def get_remote_version(url: str) -> str: """Gets the remote file and returns it as a long string.""" response = requests.get(url) if response: #print("Getting remote version") s = response.text return s else: return "Url Not Found."
5d5ef45c5b74b326f9386214229529d9b71aca3d
700,934
def single_number_hashtable(nums: list[int]) -> int: """Returns the only element in `nums` that appears exactly once Complexity: n = len(nums) Time: O(n) Space: O(n) Args: nums: array of integers s.t. every element appears twice, except for one Returns: the only element in `nums` that appears exactly once Examples: >>> single_number_hashtable([2,2,1]) 1 >>> single_number_hashtable([4,1,2,1,2]) 4 >>> single_number_hashtable([1]) 1 >>> single_number_hashtable([1,1]) Traceback (most recent call last): ... ValueError: No element in `nums` appears exactly once. """ """ALGORITHM""" ## INITIALIZE VARS ## num_counts = {} for num in nums: num_counts[num] = num_counts.get(num, 0) + 1 for num, count in num_counts.items(): if count == 1: return num else: raise ValueError("No element in `nums` appears exactly once.")
f15b06d4f4683b9604e8b5ab6f2fe9be588551a6
700,935
def parse_card(card: str) -> tuple: """Separates the card into value and suit. Args: card (str): String representing a poker card, in the format ValueSuit, like '9D' (9 of Diamonds). Returns: tuple: Returns a tuple of the card, like (Value, Suit). Ex: '9D' -> ('9', 'D'). """ if len(card) == 3: #If we receive a card whose len is 3, this is 10 + S(suit), so we replace 10 for T to make things easier. return 'T', card[2] else: return card[0], card[1]
de9051906327dfcf01a3b2076acbed216ce43ced
700,937
def checksum1(data, stringlength): """ Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1 """ value_buffer = 0 for count in range(0, stringlength): value_buffer = value_buffer ^ data[count] return value_buffer&0xFE
504b848b651ae5e8c52c987a6a8e270259e1de44
700,942
def plugin_zip(p): """Maps columns to values for each row in a plugins sql_response and returns a list of dicts Parameters ---------- p : :class:`taniumpy.object_types.plugin.Plugin` * plugin object Returns ------- dict * the columns and result_rows of the sql_response in Plugin object zipped up into a dictionary """ return [ dict(list(zip(p.sql_response.columns, x))) for x in p.sql_response.result_row ]
b91e5403fd710875c4588afc0eba3da1b1a82c4a
700,947
def get_string_from_ascii(input): """ This function is reversed engineered and translated to python based on the CoderUtils class in the ELRO Android app :param input: A hex string :return: A string """ try: if len(input) != 32: return '' byt = bytearray.fromhex(input) name = "".join(map(chr, byt)) name = name.replace("@", "").replace("$", "") except: return '' return name
fdf878ac689c614720e9ad5ebeecbd32c9f893b1
700,949
def compute_mean_median(all_methods_df): """ Computes the mean values and the median values for each column of the Pandas.DataFrame grouped by the methods. Parameters ---------- all_methods_df : Pandas.DataFrame Returns ------- list - means: Pandas.DataFrame containing the mean values for each column of the Pandas.DataFrame grouped by the methods - medians: Pandas.DataFrame containing the meadian values for each column of the Pandas.DataFrame grouped by the methods """ grouped = all_methods_df.groupby("method") means = round(grouped.mean(), 4) medians = round(grouped.median(), 4) return [means, medians]
b4397bfcef8e0215e3478f1f50708aa4608a14e2
700,953
import torch def get_cosinebased_yaw_pitch(input_: torch.Tensor) -> torch.Tensor: """ Returns a tensor with two columns being yaw and pitch respectively. For yaw, it uses cos(yaw)'s value along with sin(yaw)'s sign. Args: input_: 1st column is sin(yaw), 2nd Column is cos(yaw), 3rd Column is sin(pitch) """ yaw_pitch_cosine = torch.zeros((input_.shape[0], 2)) yaw_pitch_cosine[:, 1] = torch.asin(input_[:, 2]) yaw = torch.acos(input_[:, 1]) right = (input_[:, 0] < 0.) yaw[right] = -1 * yaw[right] yaw_pitch_cosine[:, 0] = yaw return yaw_pitch_cosine
ca5c10908de8dfa8b86446a1874b1ef780ae5313
700,954
import re def CommitPositionFromBuildProperty(value): """Extracts the chromium commit position from a builders got_revision_cp property.""" # Match a commit position from a build properties commit string like # "refs/heads/master@{#819458}" test_arg_commit_position_re = r'\{#(?P<position>\d+)\}' match = re.search(test_arg_commit_position_re, value) if match: return int(match.group('position')) raise RuntimeError('Could not get chromium commit position from test arg.')
c0fdb07ce3be907db3ec8628eaefc3ad1453ef34
700,955
def traverse_tree(t, parent_name=""): """ Returns the list of all names in tree. """ if parent_name: full_node_name = parent_name + "/" + t.name else: full_node_name = t.name if (t.children is None): result = [full_node_name] else: result = [full_node_name + "/"] for i in t.children: result.extend(traverse_tree(i, full_node_name)) return result
16b1773895569c108fde5f9a1a43a12a24314dcc
700,957
def merge_again(other, script): """ Merge the two DataFrames for other and script together again, but keeping distinct rows for the cumulated levenshtein distances for each category (other and script). Returns DataFrame. """ data = other.merge(script, how="left", on="line") data.rename(columns={"lev-dist_x": "other", "lev-dist_y": "script"}, inplace=True) # print(data.head()) return data
204e716fce02765e2ba601f5d5a7f91efa792838
700,960
def subset_dict(d, selected_keys): """Given a dict {key: int} and a list of keys, return subset dict {key: int} for only key in keys. If a selected key is not in d, set its value to 0""" return {key: (0 if key not in d else d[key]) for key in selected_keys}
e16e5ce7a9baa0fa9dbf8bb65eadd9101e188092
700,962
def ctoa(character: str) -> int: """Find the ASCII value of character. Uses the ord builtin function. """ code = ord(character) return code
dbf3b01f331a976632ae2559e08488a3f6a7f15d
700,966
def resolve_translation(instance, _info, language_code): """Get translation object from instance based on language code.""" return instance.translations.filter(language_code=language_code).first()
aedd46bec3dc0d3a567718abf1fd69b460e69ba1
700,967
def _IsZonalGroup(ref): """Checks if reference to instance group is zonal.""" return ref.Collection() == 'compute.instanceGroupManagers'
bf48f2c277fb03db2f0cc3ea42234781df9a2500
700,971
def lex_ident(node_syn, pred_syn, gold_syn): """ 1. check if the predicted synset's lexname equals to the gold synset's name 2. check if the predicted synset's lexname is in the set of its wordnet hypernyms' lexnames (including hypernyms/instance_hypernyms) """ pred_lex = pred_syn.lexname() gold_lex = gold_syn.lexname() lex_ident_dev = pred_lex == gold_lex lex_ident_wn = pred_lex in [x.lexname() for x in node_syn.instance_hypernyms()] \ or pred_lex in [x.lexname() for x in node_syn.hypernyms()] return lex_ident_dev, lex_ident_wn, pred_lex, gold_lex
487fe7c0772d9ecaf84a6f8fe349b0ec20fd3646
700,972
def count_set_bits(number): """ Returns the number of set bits in number """ count = 0 while number: count += number & 1 number >>= 1 return count
b6326b77d6fb14ff31712571837396fcf2e2b0c0
700,976
def pjax(template_names, request, default="pjax_base.html"): """ Returns template name for request. :param request: Django request or boolean value :param template_names: Base theme name or comma-separated names of base and pjax templates. Examples:: {% extends "base.html"|pjax:request %} {% extends "base.html,pjax_base.html"|pjax:request %} context = {"is_pjax": True} {% extends "base.html"|pjax:is_pjax %} """ if isinstance(request, (bool, int)): is_pjax = request else: is_pjax = request.META.get("HTTP_X_PJAX", False) if "," in template_names: template_name, pjax_template_name = template_names.split(",", 1) else: template_name, pjax_template_name = template_names, default if is_pjax: return pjax_template_name.strip() or default return template_name.strip()
e74b1c76abfc68999c316021e6b70f6210125a2a
700,978
def make_header(ob_size): """Make the log header. This needs to be done dynamically because the observations used as input to the NN may differ. """ entries = [] entries.append("t") for i in range(ob_size): entries.append("ob{}".format(i)) for i in range(4): entries.append("ac{}".format(i)) entries.append("p") # roll rate entries.append("q") # pitch rate entries.append("r") # yaw rate entries.append("p-sp") # roll rate setpoint entries.append("q-sp") # pitch rate setpoint entries.append("r-sp") # yaw rate setpoint for i in range(4): entries.append("y{}".format(i)) for i in range(4): entries.append("w{}".format(i)) # ESC rpms entries.append("reward") return ",".join(entries)
82aa8359dad2e78f8d161a1811a7d71b2e496b49
700,980
def evaluate_g8( mu, kappa, nu, sigma, s8 ): """ Evaluate the eighth constraint equation and also return the jacobian :param float mu: The value of the modulus mu :param float kappa: The value of the modulus kappa :param float nu: The value of the modulus nu :param float sigma: The value of the modulus sigma :param float s8: The value of the constraint """ return 4 * mu * ( kappa + nu - 2 * sigma ) - 2 * sigma - s8**2,\ { 'mu':4 * ( kappa + nu - 2 * sigma ), 'kappa': 4 * mu, 'nu': 4 * mu, 'sigma':-8 * mu - 2, 's8':-2 * s8 }
d1be8deb9f38dae55082a341e2501044d7b2aef7
700,981
def ChangeBackslashToSlashInPatch(diff_text): """Formats file paths in the given patch text to Unix-style paths.""" if not diff_text: return None diff_lines = diff_text.split('\n') for i in range(len(diff_lines)): line = diff_lines[i] if line.startswith('--- ') or line.startswith('+++ '): diff_lines[i] = line.replace('\\', '/') return '\n'.join(diff_lines)
88dce5e16fb400ef2aa1c16950e45491baa5c961
700,985
def parse_line(text: str) -> str: """Parses one line into a word.""" text = text.rstrip() if text[0] == "+": return text[1:] if text[0] == "@" or text[0] == "!" or text[0] == "$": w = text.split("\t")[1] if "#" in w: return w.split("#")[0].rstrip() else: return w raise ValueError("Invalid input: "+text)
44e8bd0defc071438aea15002d3e3c6838e61bfb
700,986
def dict_to_cidr(obj): """ Take an dict of a Network object and return a cidr-formatted string. :param obj: Dict of an Network object """ return '%s/%s' % (obj['network_address'], obj['prefix_length'])
c915c16f28b42322c2f63743cdc43a58b964ba27
700,987
def replace_tuple(tuple_obj, replace_obj, replace_index): """Create a new tuple with a new object at index""" if len(tuple_obj) - 1 <= replace_index: return tuple_obj[:replace_index] + (replace_obj,) else: return tuple_obj[:replace_index] + (replace_obj,) + tuple_obj[replace_index+1:]
28c32ab516eddd7feb90e6b62221f56e8106a2f5
700,988
def center_crop_images(images, crop_resolution: int): """ Crops the center of the images Args: images: shape: (B, H, W, 3), H should be equal to W crop_resolution: target resolution for the crop Returns: cropped images which has the shape: (B, crop_resolution, crop_resolution, 3) """ # crop_resolution = tf.cast(crop_resolution, tf.float32) half_of_crop_resolution = crop_resolution / 2 image_height = images.shape[1] image_center = image_height / 2 from_ = int(image_center - half_of_crop_resolution) to_ = int(image_center + half_of_crop_resolution) return images[:, from_:to_, from_:to_, :]
3831dde49fba737f24706c5c19c380bf7d9f9222
700,989
def default_exception_serializer(exception): """ The default exception serializer for user exceptions in eval. """ return '%s: %s' % (type(exception).__name__, str(exception))
c630ddb9ec6ffc5381c11c4b06c277e4e55910de
700,991
import copy def remove_candidates(orders, candidates_to_remove): """ Remove a set of candidates from a list representing a preference order. """ projection = [] for c_vote in orders: temp_vote = copy.copy(c_vote) for c_remove in candidates_to_remove: temp_vote.remove(c_remove) projection.append(temp_vote) return projection
bd0b98acefacaf9891b4ab7109d01d187f1de85a
700,992
def factorial(n): """ Calculate n! Args: n(int): factorial to be computed Returns: n! """ if n == 0: return 1 # by definition of 0! return n * factorial(n-1)
a0e8e6edbf03bb1fb1e6a11d7ace41e37992b54f
700,995
def unique_filename(filename, upload_id): """Replace filename with upload_id, preserving file extension if any. Args: filename (str): Original filename upload_id (str): Unique upload ID Returns: str: An upload_id based filename """ if "." in filename: return ".".join([upload_id, filename.rsplit(".", 1)[1]]) else: return upload_id
04602532627d8557436c27f2e7d8165f638ed155
701,004
def ror (endv, iv): """ This capital budgeting function computes the rate of return on an investment for one period only. iv = initial investment value endv = total value at the end of the period Example: ror(100000, 129,500) """ return (endv - iv)/iv
43a1339d45725a5e04fd809a6cfb708b6b49b829
701,006
import torch def concatenate_list_of_dict(list_of_dict) -> dict: """ Concatenate dictionary with the same set of keys Args: list_of_dict: list of dictionary to concatenate Returns: output_dict: the concatenated dictionary """ # check that all dictionaries have the same set of keys for i in range(len(list_of_dict)-1): keys1 = set(list_of_dict[i].keys()) keys2 = set(list_of_dict[i+1].keys()) assert keys1 == keys2, "ERROR, Some dictionary contains different keys: {0} vs {1}".format(keys1, keys2) total_dict = {} for mydict in list_of_dict: for k, v in mydict.items(): if isinstance(v, list): if k in total_dict.keys(): total_dict[k] = total_dict[k] + v else: total_dict[k] = v elif isinstance(v, torch.Tensor): if k in total_dict.keys(): total_dict[k] = torch.cat((total_dict[k], v), dim=0) else: total_dict[k] = v elif isinstance(v, int) or isinstance(v, float): if k in total_dict.keys(): total_dict[k] = total_dict[k] + [v] else: total_dict[k] = [v] else: raise Exception("ERROR: Unexpected in concatenate_list_of_dict. \ Received {0}, {1}".format(type(v), v)) return total_dict
e38837d9e55cc17715bf988b585c3f4f371f7398
701,009
from typing import List import glob def get_manifest_list(manifests_dir: str) -> List[str]: """Get a list of manifest files from the manifest directory.""" yml_endings = ["yml", "yaml"] manifest_list = [] for yml_ending in yml_endings: manifest_list += glob.glob(f"{manifests_dir}/**/*.{yml_ending}", recursive=True) return manifest_list
0dc951cf08870c639735e24b048a41fb7ab6ea52
701,011
def checksum(s, m): """Create a checksum for a string of characters, modulo m""" # note, I *think* it's possible to have unicode chars in # a twitter handle. That makes it a bit interesting. # We don't handle unicode yet, just ASCII total = 0 for ch in s: # no non-printable ASCII chars, including space # but we want "!" to represent an increment of 1, hence 32 below total = (total + ord(ch)-32) % m return total
836e0f36ed3d87db8d3f2420230eb4f3f5d4d94c
701,013
def text_objects(text, font, color): """ Function for creating text and it's surrounding rectangle. Args: text (str): Text to be rendered. font (Font): Type of font to be used. color ((int, int, int)): Color to be used. Values should be in range 0-255. Returns: Text surface and it's surrounding rectangle. """ text_surface = font.render(text, True, color) return text_surface, text_surface.get_rect()
a9ed3d8a68c80930e2594b4dbef06e828de10513
701,017
def contains(value, lst): """ (object, list of list of object) -> bool Return whether value is an element of one of the nested lists in lst. >>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]) True """ found = False # We have not yet found value in the list. for i in range(len(lst)): for j in range(len(lst[i])): if lst[i][j] == value: found = True #for sublist in lst: # if value in sublist: # found = True return found
9d3690943c05b4220afabfa65402b7f12c1cb279
701,021
def UnbiasPmf(pmf, label=''): """Returns the Pmf with oversampling proportional to 1/value. Args: pmf: Pmf object. label: string label for the new Pmf. Returns: Pmf object """ new_pmf = pmf.Copy(label=label) for x, p in pmf.Items(): new_pmf.Mult(x, 1.0/x) new_pmf.Normalize() return new_pmf
1146d952bbac0ef3031e3259d98e0f343103598e
701,023
def _num_requests_needed(num_repos, factor=2, wiggle_room=100): """ Helper function to estimate the minimum number of API requests needed """ return num_repos * factor + wiggle_room
525af1e3aa5e1c0b35195fcd8e64cd32101bb6f2
701,029
def same_padding_for_kernel(shape, corr, strides_up=None): """Determine correct amount of padding for `same` convolution. To implement `'same'` convolutions, we first pad the image, and then perform a `'valid'` convolution or correlation. Given the kernel shape, this function determines the correct amount of padding so that the output of the convolution or correlation is the same size as the pre-padded input. Args: shape: Shape of the convolution kernel (without the channel dimensions). corr: Boolean. If `True`, assume cross correlation, if `False`, convolution. strides_up: If this is used for an upsampled convolution, specify the strides here. (For downsampled convolutions, specify `(1, 1)`: in that case, the strides don't matter.) Returns: The amount of padding at the beginning and end for each dimension. """ rank = len(shape) if strides_up is None: strides_up = rank * (1,) if corr: padding = [(s // 2, (s - 1) // 2) for s in shape] else: padding = [((s - 1) // 2, s // 2) for s in shape] padding = [((padding[i][0] - 1) // strides_up[i] + 1, (padding[i][1] - 1) // strides_up[i] + 1) for i in range(rank)] return padding
8d956c75a2e0609a04ec56374a4cb9b3b367b90a
701,031
def _extract_license_outliers(license_service_output): """Extract license outliers. This helper function extracts license outliers from the given output of license analysis REST service. :param license_service_output: output of license analysis REST service :return: list of license outlier packages """ outliers = [] if not license_service_output: return outliers outlier_packages = license_service_output.get('outlier_packages', {}) for pkg in outlier_packages.keys(): outliers.append({ 'package': pkg, 'license': outlier_packages.get(pkg, 'Unknown') }) return outliers
101a916fec08a3a5db1a09a2817e82314ca19f6b
701,032
def center(map, object): """ Center an ee.Image or ee.Feature on the map. Args: map: The map to center the object on. object: The ee.Image or ee.Feature to center. Returns: The provided map. """ coordinates = object.geometry().bounds().coordinates().getInfo()[0] bounds = [[point[1], point[0]] for point in coordinates] map.fit_bounds(bounds) return map
60a2baa1c4f83b0e9b1221bcc474f109c35cbd7a
701,034
def evaluations_to_columns(evaluation): """Convert the results of :meth:`metrics.ScoringMixIn.evaluate` to a pandas DataFrame-ready format Parameters ---------- evaluation: dict of OrderedDicts The result of consecutive calls to :meth:`metrics.ScoringMixIn.evaluate` for all given dataset types Returns ------- column_metrics: list of pairs A pair for each data_type-metric combination, where the first item is the key, and the second is the metric value Examples -------- >>> evaluations_to_columns({ ... 'in_fold': None, ... 'holdout': OrderedDict([('roc_auc_score', 0.9856), ('f1_score', 0.9768)]), ... 'oof': OrderedDict([('roc_auc_score', 0.9634)]) ... }) [['oof_roc_auc_score', 0.9634], ['holdout_roc_auc_score', 0.9856], ['holdout_f1_score', 0.9768]] """ data_types = ['oof', 'holdout', 'in_fold'] column_metrics = [] for data_type in data_types: if evaluation[data_type] is not None: for metric_key, metric_value in evaluation[data_type].items(): column_metrics.append([ F'{data_type}_{metric_key}', metric_value ]) return column_metrics
26c5f4b2a9830f7547f6b59d9653fea25345b43d
701,036
def merge(left: list, right: list) -> list: """Merges 2 sorted lists (left and right) in 1 single list, which is returned at the end. Time complexity: O(m), where m = len(left) + len(right).""" mid = [] i = 0 # Used to index the left list. j = 0 # Used to index the right list. while i < len(left) and j < len(right): if left[i] < right[j]: mid.append(left[i]) i += 1 else: mid.append(right[j]) j += 1 while i < len(left): mid.append(left[i]) i += 1 while j < len(right): mid.append(right[j]) j += 1 return mid
9f6c501469e79a9f5ecfd8e23ee3384fc56c5a48
701,037
def replace(i_list: list, target: int,new_value: int)-> list: """ Replace all the target value with a new value :param i_list: the list to be analyzed :param value: the value to replace :param target: the value to be replaced :return: the new list """ return list(map(lambda value: new_value if value == target else value, i_list))
d0d2bc928c915d3456a25cc4ff341b23a66c4098
701,038
def isPerfectSquare(p: int) -> bool: """Checks if given number is a perfect square. A perfect square is an integer that is a square of another integer. Parameters: p: int number to check Returns: result: bool True if number is a perfect square False if number is not a perfect square """ if p <= 1: return False x = p // 2 seen = set([x]) while x * x != p: x = (x + (p // x)) // 2 if x in seen: return False seen.add(x) return True
d9c725193a5100e06825944239fe3442bed17b92
701,043
def mean_expression(df, annotation, stage_regex=r".*", normal=False): """Return the mean expression values of the subset of samples. Parameters ---------- df: pandas.DataFrame Each row is a gene and each column is a sample. annotation: pandas.DataFrame A data frame with matching uuids and tumor stages. stage_regex: raw str, optional The regex used for filtering the "tumor_stage" column. Choose all by default. normal: bool, optional Return normal samples. Default is false. Returns ------- a pandas.Series with names as Ensembl IDs and values as TPMs, and a list of sample names. """ normalUUID = annotation[annotation["sample_type"].str.lower().str.contains("normal")]["uuid"].tolist() if normal: return df[normalUUID].mean(1) ids = annotation[ (~annotation["uuid"].isin(normalUUID)) & (annotation["tumor_stage"].str.contains(stage_regex, regex=True))]["uuid"].tolist() return (df[ids].mean(1), ids)
7e404aa4a69b7b967d830463d21d611e0cd47b36
701,046
import random def full_jitter(value): """Jitter the value across the full range (0 to value). This corresponds to the "Full Jitter" algorithm specified in the AWS blog's post on the performance of various jitter algorithms. (http://www.awsarchitectureblog.com/2015/03/backoff.html) Args: value: The unadulterated backoff value. """ return random.uniform(0, value)
0a5c233d3e0e58873d29de7e3d878fbcf3d0c47a
701,048
def eq(a, b, n): """Euler's quadratic formula""" ## : coefficient: a, b int ## : n int | n >= 0 rst = n**2 + a*n + b return rst
c5f9619e22d3131b905eba6bfe509020d1f7c917
701,054
def is_unqdn(cfg, name): """ Returns True if name has enough elements to be a unqdn (hostname.realm.site_id) False otherwise """ parts = name.split(".") if len(parts) >= 3: return True else: return False
28e530816ea418473858d2cb59e572d25a9f2d81
701,055
def is_valid_medialive_channel_arn(mlive_channel_arn): """Determine if the ARN provided is a valid / complete MediaLive Channel ARN""" if mlive_channel_arn.startswith("arn:aws:medialive:") and "channel" in mlive_channel_arn: return True else: return False
c2ddbdef180eabbc4f22399dd895b99555bb05d6
701,057
def convert_tf_to_crowdsourcing_format(images, detections): """ Args: images: dictionary {image_id : image info} (images from Steve's code) detections: detection output from multibox Returns: dict : a dictionary mapping image_ids to bounding box annotations """ image_annotations = {} for detection in detections: image_id = str(detection['image_id']) score = detection['score'] x1, y1, x2, y2 = detection['bbox'] # GVH: Do we want to check for reversal or area issues? image_width = images[image_id]['width'] image_height = images[image_id]['height'] if image_id not in image_annotations: image_annotations[image_id] = { "anno" : { "bboxes" : [] }, "image_id": image_id, "image_width": image_width, "image_height": image_height } bboxes = image_annotations[image_id]["anno"]["bboxes"] bboxes.append({ "x": x1 * image_width, "y": y1 * image_height, "x2": x2 * image_width, "y2": y2 * image_height, "image_height": image_height, "image_width": image_width, "score" : score }) return image_annotations
ba25ee0cb2eb570f745326dfe85c2bda972a3659
701,058
def patched_novoed_api(mocker): """Patches NovoEd API functionality""" return mocker.patch("novoed.tasks.api")
9bd7b15a6b34c9c659755fb36e422698a82be063
701,063
def tf(seconds): """ Formats time in seconds to days, hours, minutes, and seconds. Parameters ---------- seconds : float The time in seconds. Returns ------- str The formatted time. """ days = seconds // (60*60*24) seconds -= days * 60*60*24 hours = seconds // (60*60) seconds -= hours * 60*60 minutes = seconds // 60 seconds -= minutes * 60 tf = [] if days > 0: tf.append("%s days" % int(days)) if hours > 0: tf.append("%s hours" % int(hours)) if minutes > 0: tf.append("%s minutes" % int(minutes)) tf.append("%s seconds" % round(seconds, 2)) return ", ".join(tf)
22649dd1bd74cc08d73c5cd43b1b96658a3bcb3a
701,067
def squares_in_rectangle(length, width): """This function is the solution to the Codewars Rectangle into Squares Kata that can be found at: https://www.codewars.com/kata/55466989aeecab5aac00003e/train/python.""" if length == width: return None squares = [] while length > 0 and width > 0: if width < length: squares.append(width) length = length - width else: squares.append(length) width = width - length return squares
e0e32e2803ca752a24adf4cce353bf6cc49d4c08
701,075
def keep_node_permissive(data): """Return true for all nodes. Given BEL graph :code:`graph`, applying :func:`keep_node_permissive` with a predicate on the nodes iterable as in :code:`filter(keep_node_permissive, graph)` will result in the same iterable as iterating directly over a :class:`BELGraph` :param dict data: A PyBEL data dictionary :return: Always returns :data:`True` :rtype: bool """ return True
425ebf20686ea309e542b82b2fbbe7aa81cccb63
701,076
import torch def get_params(model): """Aggregates model parameters of all linear layers into a vector. Args: model: A (pre-trained) torch.nn.Module or torch.nn.Sequential model. Returns: The aggregated parameters. """ weights = list() biases = list() for module in model.modules(): if module.__class__.__name__ in ['Linear']: weights.append(module.weight.contiguous().view(-1)) biases.append(module.bias) weights.extend(biases) return torch.cat(weights)
c6a66f3a013f62e79e51f47d130e65b12b38ff33
701,079
def get_voted_content_for_user(user): """Returns a dict where: - The key is the content_type model - The values are list of id's of the different objects voted by the user """ if user.is_anonymous(): return {} user_votes = {} for (ct_model, object_id) in user.votes.values_list("content_type__model", "object_id"): list = user_votes.get(ct_model, []) list.append(object_id) user_votes[ct_model] = list return user_votes
799eff5efd184da0b5121f59025c39d0ddb593a3
701,082
def odd_occurences_in_array(a): """ Finds the odd number of occurences of an element in an array. XOR of all elements gives us odd occurring element. Note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x :param a """ result = 0 for number in a: result = result ^ number return result
8085fb8ffa5df9628caa5fef541b5d7b78c372b0
701,083
import re def extract_length(value): """ extract length data from a provided value Returns a tuple of a detected length value and a length unit. If no unit type can be extracted, it will be assumed that the provided value has no unit. Args: value: the value to parse Returns: the length and unit type """ if not value: return None, None matched = re.match(r'^\s*(\d*\.?\d*)\s*(\S*)?\s*$', value) if not matched: return None, None amount, unit = matched.groups() if not amount: amount = None unit = None elif not unit: unit = None return amount, unit
b418b76114fafe24c86c2e0dcfa62bb19b29ff59
701,087
def read_landmarks(f_landmarks): """ Reads file containing landmarks for image list. Specifically, <image name> x1 y1 ... xK yK is expected format. :param f_landmarks: text file with image list and corresponding landmarks :return: landmarks as type dictionary. """ landmarks_lut = {} with open(f_landmarks) as f: landmark_lines = f.readlines() for line in landmark_lines: line = line.replace("\n", "").split("\t") landmarks_lut[line[0]] = [int(k) for k in line[1:]] return landmarks_lut
9c4bf6b405f4fb49ace8badb4b3151cc457bbf84
701,094
import json def trigger_oauth_expires_test(limit): """ Test data for IFTTT trigger bunq_oauth_expires """ result = [{ "created_at": "2018-01-05T11:25:15+00:00", "expires_at": "2018-01-05T11:25:15+00:00", "meta": { "id": "1", "timestamp": "1515151515" } }, { "created_at": "2014-10-24T09:03:34+00:00", "expires_at": "2014-10-24T09:03:34+00:00", "meta": { "id": "2", "timestamp": "1414141414" } }, { "created_at": "2008-05-30T04:20:12+00:00", "expires_at": "2008-05-30T04:20:12+00:00", "meta": { "id": "3", "timestamp": "1212121212" } }] return json.dumps({"data": result[:limit]})
6f0bf5ed1f2749bf67d9068ac9eb85cc6fd86e17
701,096