content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import struct def readString(f, len_=1): """Read len_ bytes as a string in file f""" read_bytes = f.read(len_) str_fmt = '>'+str(len_)+'s' return struct.unpack( str_fmt, read_bytes )[0]
5ffbfdb55f0bbc2365d6d4417d50d309789079b9
166,148
def momentum(vector): """ Computes the momentum of a vector. Parameters: - `vector` : :class:`list` of :class:`floats` Moentum is computed as follow: - momentum = 100*(new - old)/old Returns the momentum of the vector (:class:`float`) """ return 100*((vector[0] - vector[-1])/vector[-1])
11159a1038588a538d4257384ac5565c90bb151b
136,279
from typing import List def get_citation_ids(article:dict,direction:str='citations')->List: """Get ids for papers cited / citing a paper in our corpus""" return [c['arxivId'] for c in article[direction]]
9eb45999e8351d03605b413e302860b8a26e5b6e
372,857
import shlex def parse_kv_pairs(key_value_string): """ Parse string of key value pairs to dict Example: 'key1=value1 "key 2"="value 2"' --> {'key1': value1, 'key 2': 'value 2'} parse(s) """ if not key_value_string: return {} return dict(token.split('=') for token in shlex.split(key_value_string))
90740cd31b0199b3701689ebcc4d70174d235c2e
300,213
def get_locations(content_div): """ Returns the location divs from the content block :param: content_div - the parent div that has all the location divs """ # the first element which is an empty div return content_div.findAll('div', recursive=False)[1:]
fa42998a10624151c73f811d62c8e691b9ff7409
344,447
import torch def rect_to_polar(real, imag): """Converts the rectangular complex representation to polar""" mag = torch.pow(real**2 + imag**2, 0.5) ang = torch.atan2(imag, real) return mag, ang
ff97f81d928a0c8aa66ee075bfd4df153029bed7
129,694
def _underlying_variable_ref(t): """Find the underlying variable ref. Traverses through Identity, ReadVariableOp, and Enter ops. Stops when op type has Variable or VarHandle in name. Args: t: a Tensor Returns: a Tensor that is a variable ref, or None on error. """ while t.op.type in ["Identity", "ReadVariableOp", "Enter"]: t = t.op.inputs[0] op_type = t.op.type if "Variable" in op_type or "VarHandle" in op_type: return t else: return None
c2d48b61e7236d1b28f0f905fd3d32429dcb1776
611,964
def generate_input_target_text(cut_word_list): """ 生成对应的训练集X和y,这里X和y都是分词过的词语list :param cut_word_list: 存储所有歌词,其每个元素是一个list,存储一首歌(一首歌使用的又是list of list结构,一个list是一句歌词); :return: input_texts: 数据集X对应的list target_texts: 数据集y对应的list max_seq_input: X中样本的最大长度 max_seq_target: y中样本的最大长度 input_words: 数据集X中的字列表,用于统计词频,产生word2index target_words: 数据集y中的字列表,用于统计词频,产生index2word """ # 生成X和y input_texts = [] # 数据集X target_texts = [] # 数据集y input_words = [] # 数据集X中的字列表,用于统计词频,产生word2index target_words = [] # 数据集y中的字列表,用于统计词频,产生index2word num_songs = len(cut_word_list) max_seq_input = 0 # 输入序列中的最大长度(模型中需要使用) max_seq_target = 0 # 输出序列中的最大长度(模型中需要使用) for i in range(0, num_songs): num_lines_eachSong = len(cut_word_list[i]) for j in range(0, num_lines_eachSong - 1): input_texts.append(cut_word_list[i][j]) input_words += (cut_word_list[i][j]) max_seq_input = max(max_seq_input, len(cut_word_list[i][j])) # 开始和结束的位置分别是:“\t”和"\n" target_texts.append(["\t"] + cut_word_list[i][j + 1]+ ["\n"]) target_words += (["\t"] + cut_word_list[i][j + 1] + ["\n"]) max_seq_target = max(max_seq_target, len(["\t"] + cut_word_list[i][j + 1] + ["\n"])) return input_texts, target_texts, max_seq_input, max_seq_target, input_words, target_words
dc36f7a618aab5342b849c9e1fa51bd7cd73cb92
433,690
def merge_dfs(df_list, keys_for_merge): """Joins all the dataframes on the keys. Does an outer join, does not check that all rows exist in all dataframes. Args: df_list: A list of pandas dataframes. Each needs to have the keys_for_merge as columns. keys_for_merge: A string list of column names to merge on. Typically ['plate', 'well'] aka WELL_MERGE_KEYS. Returns: The joined pandas dataframe. """ if len(df_list) < 1: raise ValueError('I need at least 1 df to merge') for k in keys_for_merge: if k not in df_list[0]: raise ValueError('df missing column %s. Has: %s' % (k, df_list[0].columns)) merged_df = df_list[0] for df in df_list[1:]: cols_to_add = keys_for_merge + [c for c in df.columns if c not in merged_df] for k in keys_for_merge: if k not in df: raise ValueError('df missing column %s. Has: %s' % (k, df[0].columns)) merged_df = merged_df.merge(df[cols_to_add], on=keys_for_merge, how='outer') return merged_df
f5b0ee9250f7d0c2a855c7b62684d12371a34ec5
129,422
import gzip def gzip_file(file, file_name): """ Gzip a file :param file file: :param str file_name: :return: the gzipped file :rtype: gzip file """ with gzip.open(file_name + '.gz', 'wb') as gzipped_file: gzipped_file.writelines(file) return gzipped_file
d1569b3ef8ebed46eb7a3fd128479d3999fb228c
31,282
def __calculate_waterfootprint(wf_ing, quantity): """ Calculate the right water footprint of a ingredient from its (l/kg) water footprint and the quantity provided (in gr). :param wf_ing: the water footprint of the ingredient. :param quantity: the quantity of the ingredient. :return: the water footprint calcuated on the quantity. """ return round((wf_ing * quantity) / 1000, 2)
eb675f718dfdf619cf874c8a1fb2cca2f55ed0a5
683,249
import uuid def fromMsg(msg): """Create UUID object from UniqueID message. :param msg: `uuid_msgs/UniqueID`_ message. :returns: :class:`uuid.UUID` object. """ return uuid.UUID(bytes = msg.uuid)
1be5562203b895ad434ea44300617437c1e478af
133,492
def cast_map_to_str_dict(map): """ Helper function to cast Unreal Map object to plain old python dict. This will also cast values and keys to str. Useful for metadata dicts. """ return {str(key): str(value) for (key, value) in map.items()}
cbe640af4a23fc6a348a08aaeb963fa06ced1446
259,049
def filter_str(check_str): """ 过滤无用字符 :param str check_str:待过滤的字符串 :return str temp:过滤后的字符串 """ temp = '' for i in check_str: if i != '\n' and i != '\x00': temp = temp + i return temp
2787d1455beb491b85ce3db17232503565b76693
636,149
def construct_rss_url(root_url, rss_feed_path): """ Construct URL for the RSS feed. Args root_url: Blog's root URL. rss_feed_path: String or Path object describing the path to the RSS feed under the blog's root directory. Returns The RSS feed URL as a string. """ sep = '' if root_url[-1] == '/' else '/' rss_url = root_url + sep + str(rss_feed_path) return rss_url
96fa2573ec2051511a6d1fa13fd269dea10d3ec0
476,682
import hashlib def get_md5(str_): """ hash function --md5 :param str_:origin str :return:hex digest """ md5 = hashlib.md5() md5.update(str_.encode('utf-8')) return md5.hexdigest()
fb905d673ac7407fcaa3f70a822620dd38dbb5e6
18,495
def find(x): """ Find the representative of a node """ if x.instance is None: return x else: # collapse the path and return the root x.instance = find(x.instance) return x.instance
5143e9d282fb1988d22273996dae36ed587bd9d2
2,062
from typing import Union def product(*args : Union[float,int]) -> Union[float,int]: """Returns the product of float or ints product(3,4,5) -> 60 product(*[3,4,5]) -> 60 """ prod = 1 for num in args: prod*=num return prod
555453bce30c01a28f5f299cc4b5787bf3cd63fa
440,134
def sanitize_string(string): """Sanitizes a string for it to be between U+0000 and U+FFFF""" if string: return ''.join(c for c in string if ord(c) <= 0xFFFF).strip()
4f01448b06180403dedbb787aaa0e072315ebb54
576,613
def cast_operator_matrix_dtype(matrix, dtype): """ Changes the dtype of a matrix, without changing the structural type of the object. This makes sure that if you pass sparse arrays to a LocalOperator, they remain sparse even if you change the dtype """ # must copy # return np.asarray(matrix, dtype=dtype) return matrix.astype(dtype)
d3f7f3277c540fc9f949f5e41021633abaab74a2
132,466
def get_jsonpath(obj: dict, jsonpath): """ Gets a value from a dictionary based on a jsonpath. It will only return one result, and if a key does not exist it will return an empty string as template tags should not raise errors. :param obj: The dictionary to query :param jsonpath: The path to the object (singular) :return: The most relevant object in the dictionary """ try: keys = str(jsonpath).split(".") val = obj for key in keys: val = val[key] return val except (KeyError, TypeError): return ""
0ddead3d3cc5cfdd3d6557921bfac5d98169f540
137,517
from typing import List def join_items_with_and(items: List[str]) -> str: """Join the list with commas and "and".""" if len(items) <= 2: return " and ".join(items) return "{} and {}".format(", ".join(items[:-1]), items[-1])
4f495f07bc7e421c5be0e9c58785cc53984403a3
592,443
def calc_check_digit(number): """Calculate the check digit.""" s = sum((2 - i) * int(n) for i, n in enumerate(number[:12])) % 11 return str((1 - s) % 10)
f19a256218e924a96fb4c490b44029613f6a7b97
312,624
def correct_protein_name_list(lst): """ Correct a list of protein names with incorrect separators involving '[Cleaved into: ...]' Args: lst (:obj:`str`): list of protein names with incorrect separators Returns: :obj:`str`: corrected list of protein names """ if lst: lst = lst.replace('[Cleaved into: Nuclear pore complex protein Nup98;', '[Cleaved into: Nuclear pore complex protein Nup98];') lst = lst.replace('[Cleaved into: Lamin-A/C;', '[Cleaved into: Lamin-A/C];') lst = lst.replace('[Cleaved into: Lamin-A/C ;', '[Cleaved into: Lamin-A/C ];') lst = lst.replace('[Includes: Maltase ;', '[Includes: Maltase ];') return lst
c612d7af7408a8df9ac07ea183c57d43f33ec200
538,388
from typing import List from typing import Any def split_list_into_consequtive_chunks(lst: List[Any], n_chunks) -> List[List[Any]]: """ >>> split_list_into_consequtive_chunks([1, 2, 3, 4, 5, 6, 7, 8], 3) [[1, 2, 3], [4, 5, 6], [7, 8]] >>> split_list_into_consequtive_chunks([1, 2, 3, 4, 5, 6, 7], 3) [[1, 2, 3], [4, 5], [6, 7]] >>> split_list_into_consequtive_chunks([1, 2, 3, 4, 5, 6], 3) [[1, 2], [3, 4], [5, 6]] >>> split_list_into_consequtive_chunks([], 2) [[], []] >>> split_list_into_consequtive_chunks([1], 2) [[1], []] """ result = [] min_files_in_chunk = len(lst) // n_chunks chunks_with_aditional_file = len(lst) - min_files_in_chunk * n_chunks for i in range(chunks_with_aditional_file): result.append(lst[i * (min_files_in_chunk + 1):i * (min_files_in_chunk + 1) + (min_files_in_chunk + 1)]) n_packed = (min_files_in_chunk+1) * chunks_with_aditional_file for i in range(n_chunks - chunks_with_aditional_file): result.append(lst[n_packed + i * min_files_in_chunk: n_packed + i * min_files_in_chunk + min_files_in_chunk]) return result
1762a0c5b743d8ce833c5206c5efa7f6e8c05253
483,198
def indent(text, indentation): """Indents a string of text with the given string of indentation. PARAMETERS: text -- str indentation -- str; prefix of indentation to add to the front of every new line. RETURNS: str; the newly indented string. """ return '\n'.join([indentation + line for line in text.splitlines()])
9854034bea05a318a3444ac771b0ae017b7c395a
404,677
from typing import List def get_package_nvrs(built_packages: List[dict]) -> List[str]: """ Construct package NVRs for built packages except the SRPM. Returns: list of nvrs """ packages = [] for package in built_packages: if package["arch"] == "src": continue epoch = f"{package['epoch']}:" if package["epoch"] != 0 else "" packages.append( f"{package['name']}-{epoch}{package['version']}-{package['release']}.{package['arch']}" ) return packages
a560d3dbf89fbb934fb100fdb73491df972a06de
629,046
def check_if_pack_on_hand(hand): """ Function used to check if player have a pack of cards on hand. :param hand: list of cards on player hand :return: list of cards values which can be played as pack """ tmp = {} for card in hand: if card[1] in tmp.keys(): tmp[card[1]] += 1 else: tmp[card[1]] = 1 keys = tmp.keys() packs = [] for key in keys: if tmp[key] >= 3: packs.append(key) return packs
4302b36395cb229119af0e279f4d9180b25e9d3d
594,535
def get_resource_requests_from_networktab(networktab): """ Parse `networktab` to extract only `ResourceSendRequest` information. """ events = networktab['traceEvents'] network_events = [] for event in events: if event['name'] == 'ResourceSendRequest': network_events.append(event) resource_requests = [] for ne in network_events: ne_data = ne['args']['data'] ne_dict = dict( method=ne_data['requestMethod'], url=ne_data['url'] ) resource_requests.append(ne_dict) return resource_requests
97e50596fbdd057878f2febfc49f3f7d81faa9f1
639,569
def clean_population_stats(data_frame): """ Clean our population dataframe. Rename some columns, drop some columns etc.. :param data_frame: population dataframe :return: pandas dataframe, cleaned """ df_pop = data_frame.drop(["Country Code", "Indicator Name", "Indicator Code", "Unnamed: 63"], axis=1) df_pop = df_pop.rename(columns={"Country Name": "country"}) df_pop = df_pop.melt(id_vars=["country"], var_name="year", value_name="total_population") df_pop["year"] = df_pop["year"].astype("float") return df_pop
eda1a48ec58d688b9586a938c78b0787346becba
549,081
def getMostStrictType(typeA: str, typeB: str) -> str: """Return the most 'strict' type of license from the available types. Args: typeA (str): type of the first license typeB (str): type of the second license Returns: str: the most 'strict' type """ strict = ["Public Domain", "Permissive", "Weak Copyleft", "Copyleft", "Viral"] if len(typeA) == 0: return typeB if len(typeB) == 0: return typeA return strict[max(strict.index(typeA), strict.index(typeB))]
e8eb0ced58e3f79c827078d5abe708eb86820da6
406,030
import math def getdistance(vector1, vector2): """ Accepts two vectors (track.normalizedlist arrays, containing weighted values for each track attribute). Vectors must be the same length. Returns the distance between the two vectors, or None if there is an error. """ try: result = math.sqrt(sum([math.pow(i - j, 2) for i, j in zip(vector1, vector2)])) return(result) except Exception as e: print('error in getdistance:\n{}'.format(e)) return(None)
5b15d7bc29b78f8e34e1b93c03c35f62ba39b179
149,137
import math def _full_length(length: int, kernel_size: int, stride: int): """ Given a convolution-like operation with the given kernel size and stride, return the length the input should have so that the last frame is full. """ length = max(length, kernel_size) return stride * math.ceil((length - kernel_size) / stride) + kernel_size
b77e13a6f7fd84f8acded525982e7abecfa4242a
171,788
from typing import Any def is_null(value: Any) -> bool: """ Check if value is NaN or None """ return value != value or value is None
7a9d82a78b58638aa87109e0376c2095ac7d8ad8
185,275
def get_connectivity(self, elem_tag): """Return the connectivity for one selected element Parameters ---------- self : Mesh an Mesh object elem_tag : int an element tag Returns ------- connect_select: numpy.array Selected connectivity. Return None if the tag does not exist """ for key in self.element: connect_select = self.element[key].get_connectivity(elem_tag) if connect_select is not None: return connect_select
b71e13a94bca667e3e9d643b0aa41c8e4f690b5a
449,111
def grazing(vs, eaten, zooplankton): """Zooplankton grows by amount digested, eaten decreases by amount grazed""" return {eaten: - vs.grazing[eaten], zooplankton: vs.grazing[eaten]}
9e955c3cc16e00f8fffd9ef210093ecd82ac11df
649,138
def add_sales_variance(bigTable): """ Adds a new column reporting the variance in unit_sales for each (item, store) tuple """ df = bigTable.groupby(['store_nbr', 'item_nbr'])['unit_sales']\ .var().reset_index() return bigTable.merge(df.rename(columns={'unit_sales': 'item_store_sales_variance' }), on=['store_nbr', 'item_nbr'])
709cd71354f89489bc1cb1e46f07a42777ad5bc4
506,862
def checkOtherPointsClicked(game, clickX, clickY): """ If one of the opponent's points cards has been clicked, return the card that was clicked, else None """ for card in game.otherPlayer.pointsCards: if card.imageObj.collidepoint(clickX, clickY): return card return None
f65b791e1048a0e27389e5e12187df175dff1041
578,412
def starts_with_wan(string): """Test if a string starts with Chinese \"ten thousand\".""" return string.startswith('万') or string.startswith('万元') \ or string.startswith('(万)') or string.startswith('(万元)') \ or string.startswith('(万元)')
5887aca9ad09e4c6178c154ea6d22e7d76653124
247,157
def getind(dataset, wid, spec): """ Specifies individual dataset for column 2 and 3 of table 2: In column 2 early decisions are considered while in column 3 late decisions are considered. For col 1 and 4 all decicions are taken into account. Args: dataset(Pd.DataFrame): dataset containing all considered individuals wid(int): Individual ID spec(int): specification parameter Returns: dataset_ind(Pd.DataFrame): Relevant individual-level dataframe containing only observations for individual whose ID=wid. """ dataset_ind = dataset[dataset.wid == wid] if spec == 2: dataset_ind = dataset_ind[dataset_ind.decisiondatenum < 4] elif spec == 3: dataset_ind = dataset_ind[dataset_ind.decisiondatenum >= 4] return dataset_ind
3d32705a726d653019f94232bf5f6177fa9c6a5a
258,632
def isWordGuessed(secretWord: str, lettersGuessed: list) -> bool: """Verify if secretWord was guessed Args: secretWord: the word the user is guessing lettersGuessed: what letters have been guessed so far Returns: bool: True if all the letters of secretWord are in lettersGuessed, False otherwise """ # return set(secretWord) <= set(lettersGuessed) return all(char in lettersGuessed for char in secretWord)
26b108324c36af5ace2ff7f0f39f39788f9cbbcd
279,612
def build_all_reduce_device_prefixes(job_name, num_tasks): """Build list of device prefix names for all_reduce. Args: job_name: 'worker', 'ps' or 'localhost'. num_tasks: number of jobs across which device names should be generated. Returns: A list of device name prefix strings. Each element spells out the full host name without adding the device. e.g. '/job:worker/task:0' """ if job_name != 'localhost': return ['/job:%s/task:%d' % (job_name, d) for d in range(0, num_tasks)] else: assert num_tasks == 1 return ['/job:%s' % job_name]
65383026a658af3cd192bf2302d5184e7b2219e7
387,137
import random def shuffle(alist): """Return a new shuffled list. >>> a = ["a", "b", "c", "d", "e"] >>> b = shuffle(a) >>> a ["a", "b", "c", "d", "e"] >>> b [...] """ blist = alist.copy() random.shuffle(blist) return blist
1646c0b7f49a683c11ccb4709bbc06e5699621db
318,758
def parse_config(configfile): """Parse the config file 'configfile' and return the parsed key-value pairs as dict""" return {k:v for k,v in map(lambda x: x.strip().split('='), filter(lambda x: not x.strip().startswith('#'), (line for line in open(configfile))))}
022243368fb63588a4bffaa6dad799e1bc5c2e66
689,053
def distance(pt1, pt2): """ Simple 2d euclidean distances between two points. args: pt1: The first point. pt2: The second point. """ return (pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2
bbbb44d10be96c10ad96db0fe242d81a7facfb68
479,414
def decode(obj): """decode an object""" if isinstance(obj, bytes): obj = obj.decode() return obj
649fc6b46b5b9609acbb7cd99fa66180411af055
66,013
import base64 def makeDid(vk, method="dad"): """ Create and return Did from bytes vk. vk is 32 byte verifier key from EdDSA (Ed25519) keypair """ # convert verkey to jsonable unicode string of base64 url-file safe vk64u = base64.urlsafe_b64encode(vk).decode("utf-8") did = "did:{}:{}".format(method, vk64u) return did
7b09205ca0f88fefb20b55443878761a5cb3614b
196,023
def set_empty(data): """ Tests if the set is empty. """ return not data
90a7019fbfb036bc50443de82e96a0ac425bbbbd
349,243
import json def to_review_json(s): """ Converts the string to json :param s: A string :return: A json formatted string representation of the object """ b = {} if s: b.update({"reviewComment": s}) return json.dumps(b) else: return None
384f8e4f8d625081fa858e184ae7a559f590a420
31,288
def structure_to_dict(structure): """Convert a ctypes.Structure to a dict""" out = {} for key, _ in structure._fields_: # pylint: disable=protected-access out[key] = getattr(structure, key) return out
5a2641dbd61458b3976fe9aa587cc3d39159da49
344,437
def _MakeLocationLookup(strText): """ Create location lookup dictionary from strPathProjectText. """ dicLocationLU = {} with open(strText) as txt: for line in txt.readlines()[1:]: lst = line.strip().split(':') k = lst[0].strip() v = [s.strip() for s in lst[1].split(',')] dicLocationLU[k] = v return dicLocationLU
d47b9e5430d75c3c0002c6b9fafa1671e5ec21a8
278,978
def score_filter(predictions, min_score): """Remove prediction bounding boxes with probability under a threshold Parameters ---------- predictions : dict all predictions min_score : int threshold score Returns ------- dict filtered predictions """ new_pred = {} new_pred['type'] = predictions['type'] new_pred['features'] = [] for feature in predictions['features']: if feature['properties']['score'] >= min_score: new_pred['features'].append(feature) return new_pred
28f8c0604f3dabc76ffbda911357d0bdd5bd5331
10,815
def to_int_action(toks): """Convert first token to integer""" return int(toks[0])
0e0d6ed3515a4170b01ed1cd05b0c82a0b01d0ae
139,839
import importlib def _load_player(modulename, package='.'): """ Load a Player class given the name of a module. :param modulename: where to look for the Player class (name of a module) :param package: where to look for the module (relative package) :return: the Player class (a class object) """ module = importlib.import_module(modulename, package=package) player_class = module.Player return player_class
7a6de7116fb3d664d01811473114eff5c29900ad
590,963
from typing import List def charge_set(ox_state: int) -> List[int]: """Set of defect charge states. -1 (1) is included for positive (negative) odd number. E.g., charge_set(3) = [-1, 0, 1, 2, 3] charge_set(-3) = [-3, -2, -1, 0, 1] charge_set(2) = [0, 1, 2] charge_set(-4) = [-4, -3, -2, -1, 0] Args: ox_state (int): an integer Returns: Set of candidate charges """ if ox_state >= 0: charges = [i for i in range(ox_state + 1)] if ox_state % 2 == 1: charges.insert(0, -1) else: charges = [i for i in range(ox_state, 1)] if ox_state % 2 == 1: charges.append(1) return charges
513ecbe67eef3e4e5da83c72e34bc027080e69cc
211,415
def all_served(state, goal): """Checks whether all passengers in goal have been served""" for thisPassenger in state.served: if not state.served[thisPassenger] and thisPassenger in goal.served and goal.served[thisPassenger]: return False return True
f4b44131ad82c0e6775e7dc2d59123494c3ff399
123,923
import yaml def load(filename): """Load yaml.""" settings = {} with open(filename, 'r') as f: settings = yaml.load(f, Loader=yaml.FullLoader) return settings
580b0ab3c76fef1220da255637458ce1334a05c8
250,025
def clenshaw_curtis_rule_growth(level): """ The number of samples in the 1D Clenshaw-Curtis quadrature rule of a given level. Parameters ---------- level : integer The level of the quadrature rule Return ------ num_samples_1d : integer The number of samples in the quadrature rule """ if level == 0: return 1 else: return 2**level+1
6bc6ac5caa1c41f9a8a77b25846d6a2d572bfa82
552,087
from typing import Union import json def dump_json(obj: Union[dict, list, str, int, float], **kwargs) -> bytes: """Dump dict to json encoded bytes string""" return json.dumps(obj, **kwargs).encode()
22006bf037b9a60ae2316f21df82ce6f559039ca
500,776
def strip_matching(from_str, char): """Strip a char from either side of the string if it occurs on both.""" if not char: return from_str clen = len(char) if from_str.startswith(char) and from_str.endswith(char): return from_str[clen:-clen] return from_str
9e5f5340e2ffde51d4fe8ed524561c99e0a22dcd
660,430
def get_ndistinct_subsequences(sequence): """ Computes the number of distinct subsequences for a given sequence, based on original implementation by Mohit Kumar available `here <https://www.geeksforgeeks.org/count-distinct-subsequences/>`_. Example -------- >>> sequence = [1,2,1,3] >>> ps.get_ndistinct_subsequences(sequence) 14 """ # this implementation works on strings, so parse non-strings to strings if sequence is not str: sequence = [str(e) for e in sequence] # create an array to store index of last last = [-1 for i in range(256 + 1)] # hard-coded value needs explaining -ojs # length of input string sequence_length = len(sequence) # dp[i] is going to store count of discount subsequence of length of i dp = [-2 for i in range(sequence_length + 1)] # empty substring has only one subseqence dp[0] = 1 # Traverse through all lengths from 1 to n for i in range(1, sequence_length + 1): # number of subseqence with substring str[0...i-1] dp[i] = 2 * dp[i - 1] # if current character has appeared before, then remove all subseqences ending with previous occurrence. if last[ord(sequence[i - 1])] != -1: dp[i] = dp[i] - dp[last[ord(sequence[i - 1])]] last[ord(sequence[i - 1])] = i - 1 return dp[sequence_length]
ba655e5d45176e77aacde895dc6928c22daad4ba
319,789
def get_feature_type (f_feature_names) : """Get the type of features in a dict""" dict_feature_type ={} fi = open(f_feature_names, mode='r', encoding='utf-8') for line in fi : line = line.rstrip() f_name, f_type = line.split("\t") dict_feature_type[f_name]=f_type fi.close() return dict_feature_type
205ba9e64024266c38ab3ee28c29bbe8065af546
125,314
def nth_combination(iterable, r, index): """Equivalent to list(combinations(iterable, r))[index].""" pool = tuple(iterable) n = len(pool) if r < 0 or r > n: raise ValueError c = 1 k = min(r, n - r) for i in range(1, k + 1): c = c * (n - k + 1) // i if index < 0: index += c if index < 0 or index >= c: raise IndexError result = [] while r: c, n, r = c * r // n, n - 1, r - 1 while index >= c: index -= c c, n = c * (n - r) // n, n - 1 result.append(pool[-1 - n]) return tuple(result)
4d36bc4d834298924c259060bf79f762a26ee5c6
414,545
def interpolate(color_a, color_b, factor): """ Interpolate between two colors be the given factor :param color_a: List or tuple of three value, red, green and blue :param color_b: List or tuple of three value, red, green and blue :param factor: Factor for interpolating between the two colors :return: Interpolated color """ if len(color_a) != 3 or len(color_b) != 3: raise ValueError("Both color inputs need to contain three values for red, green and blue.") if factor < 0.0 or factor > 1.0: raise ValueError("The factor has to be within the [0.0, 1.0] range.") return [color_a[i] + (color_b[i] - color_a[i]) * factor for i in range(3)]
dbd60cd891445a6f41ee5f6c3a625d87d037532c
327,845
import re def remove_junos_group(src): """ Remove XML attribute junos:group from the given string. :param str src: Source string :returns: String with junos:group occurrences removed. """ return re.sub(r' junos:group="[^"]+"', '', src)
311b335085b686e433a94da42abc22cbe959ef82
60,229
from typing import Union from typing import Tuple def output_name_to_outputs(name: str) -> Union[Tuple[int], Tuple[int, int]]: """ Finds the output path index associated with the output names specified in the config. For the baseband modules, these indices correspond directly to a physical output ( e.g. index 0 corresponds to output 1 etc.). For the RF modules, index 0 and 2 correspond to path0 of output 1 and output 2 respectively, and 1 and 3 to path1 of those outputs. Parameters ---------- name name of the output channel. e.g. 'complex_output_0'. Returns ------- : A tuple containing the indices of the physical (real) outputs. """ return { "complex_output_0": (0, 1), "complex_output_1": (2, 3), "real_output_0": (0,), "real_output_1": (1,), "real_output_2": (2,), "real_output_3": (3,), }[name]
3a159231dcab61bbeee12a33c426c678e95fc749
169,005
def _parse_data_row(row, columns, counters, **options): """Parse table data row. If a cell has multiple tags within it then each will be seperated by `sep` character. Parameters ---------- row : BeautifulSoup Tag object A <tr> tag from the html, with data in at least one cell. columns : list The list of column headers for the table. counters : dict Counters used for propogating multirow data. sep : string, optional (default='') Seperator between multiple tags in a cell. Returns ------- row_processed : list The processed row. """ sep = options.pop('sep', '') cells = row.find_all(['th', 'td']) cell_cursor = 0 row_processed = [] for col in columns: # Check if values to propagate if counters[col][0] > 0: cell_value = counters[col][1] counters[col][0] -= 1 # If not propagate, get from cell elif cell_cursor < len(cells): cell = cells[cell_cursor] rowspan = int(cell.attrs.pop('rowspan', 1)) cell_value = sep.join(cell.stripped_strings) if rowspan > 1: counters[col] = [rowspan - 1, cell_value] cell_cursor += 1 # If cursor out of index range, assume cells missing from else: cell_value = None row_processed.append(cell_value) return row_processed
500c9634b8110575d3c7800a0a1f2616fa08ac03
15,234
def _stringify_time_unit(value: int, unit: str): """ Returns a string to represent a value and time unit, ensuring that it uses the right plural form of the unit. >>> _stringify_time_unit(1, "seconds") "1 second" >>> _stringify_time_unit(24, "hours") "24 hours" >>> _stringify_time_unit(0, "minutes") "less than a minute" """ if value == 1: return f"{value} {unit[:-1]}" elif value == 0: return f"less than a {unit[:-1]}" else: return f"{value} {unit}"
6839bc944d1afb46d34dc2d2b9ddb3eb508a5c60
351,120
def add_header(image_string): """ Adds the base64 encoding header for jpg images to a base64 encoded string. :param image_string: A base64 encoded image string without a header :return: A base64 encoded string with a jpg header """ image_string = str(image_string)[2:] image_string_with_head = "data:image/jpeg;base64,"+str(image_string) return (image_string_with_head)
522ea9d89adeedab1c11bae0c032c28df51573d9
338,750
import math def almost_sqrt_factors(x): """Returns two integers that are close to each other and multiply to a product that is close to x. Args: x: the integer to factor into a nd b returns: a, b integers """ y = math.sqrt(x) a = math.floor(y) b = math.ceil(y) return int(a), int(b)
631e7770af3fe90d3218d37ef8d567cc2cad62e6
226,270
def get_kids(dic, resource, current): """ Function to get iteratively all kids regarding a parent agency. Input: - dic: Dictionary with the hierarchy of the agencies in the form of dic[parent_agency]=[child1, child2, ..., childN] - resource: String, the name of the parent agency - current: [], empty list to gather all kids Output: - List, containing the parent and all the children agencies, if any """ # Update the children list with the current agency current.append(resource) # If a leaf or no kids return if not(resource) in dic: pass else: # For each child agency for kid in dic[resource]: # Iteratively get their children as well current.extend(get_kids(dic, kid, current)) return sorted(list(set(current)))
6dbf752b8a523a4510d09bac95059bd35b1b67e5
405,752
def find_max(lst,start,end): """ 找从lst[start] 到 lst[end-1]之中的最大值下标 :return: 最大值在lst中的下标 """ max = start for i in range(start,end): if lst[i] > lst[max]: max = i return max
7525f6e8fcf324dd7f892d8f3e3ff5a19864c76c
136,841
def get_month(date): """ Extract month from date """ return int(date.split('-')[1])
eabf8f51554f537bbf12148eb9a9151fabe1cfad
19,704
def build_headers(access_token, client_id): """ :param access_token: Access token granted when the user links their account :param client_id: This is the api key for your own app :return: Dict of headers """ return {'Content-Type': 'application/json', 'Authorization': f'Bearer {access_token}', 'trakt-api-version': '2', 'trakt-api-key': client_id}
5cd8ae3e06f67b7a4fdb1644ae82c62cb54479cb
709,337
def is_indexable_but_not_string(obj): """Return True if ``obj`` is indexable but isn't a string.""" return not hasattr(obj, "strip") and hasattr(obj, "__getitem__")
40c35dd3f800a0b7f7ccee8f1164426626a48e00
683,197
def precision(tp, fp, eps: float = 1e-5) -> float: """ Calculates precision (a.k.a. positive predictive value) for binary classification and segmentation. Args: tp: number of true positives fp: number of false positives eps: epsilon to use Returns: precision value (0-1) """ # originally precision is: ppv = tp / (tp + fp + eps) # but when both masks are empty this gives: tp=0 and fp=0 => ppv=0 # so here precision is defined as ppv := 1 - fdr (false discovery rate) return 1 - fp / (tp + fp + eps)
f21e01489821b3aa62fb2041a2bf4f2f7427fdce
607,545
def mac_str(n): """ Converts MAC address integer to the hexadecimal string representation, separated by ':'. """ hexstr = "%012x" % n return ':'.join([hexstr[i:i+2] for i in range(0, len(hexstr), 2)])
634fe4c79772ada0ebde972140bdd28aa2bed0f3
499,663
def get_correct_query(input_query: str): """ Ignoring multiple whitespaces in input string :param input_query: string :return: same query with 1 whitespace between words """ correct_words = [] words = input_query.split(' ') for w in words: w = w.strip() if w != '': correct_words.append(w) ret = "" for w in correct_words: ret += w + " " return ret.strip()
0b49112ae8119e335a4d1ae7cecb0b59f87332d7
348,426
import _decimal import struct def decimal(value): """Encode a decimal.Decimal value. :param decimal.Decimal value: Value to encode :rtype: bytes """ if not isinstance(value, _decimal.Decimal): raise TypeError('decimal.Decimal type required') tmp = '%s' % value if '.' in tmp: decimals = len(tmp.split('.')[-1]) value = value.normalize() raw = int(value * (_decimal.Decimal(10)**decimals)) return struct.pack('>Bi', decimals, raw) return struct.pack('>Bi', 0, int(value))
66ff790763c818cb59fccd8919e6b4847c63c162
357,787
def split_instr(instr): """ Given an instruction of the form "name arg1, arg2, ...", returns the pair ("name", "arg1, arg2, ..."). If the instruction has no arguments, the second element of the pair is the empty string. """ result = instr.split(None, 1) if len(result) == 1: return result[0], "" else: return result
7bbc6ecf20c478ccce963be9f37fca0a330d3d80
622,703
import re import click def validate_email_address(ctx, param, value): """Ensure that email addresses provided are valid email strings""" # Really just check to match /^[^@]+@[^@]+\.[^@]+$/ email_re = re.compile('^[^@ ]+@[^@ ]+\.[^@ ]+$') if not email_re.match(value): raise click.BadParameter( "Invalid email address for {}: {}".format(param, value)) return value
4be5a86038b4f7be2fdf0f6f4c9f8d732d00454e
600,039
def select_number(list_of_numbers): """The player select *one* number of a list of numbers""" answer = "" while ((not answer.isdecimal()) or int(answer) not in list_of_numbers): answer = input("Please type selected number and press ENTER: ") return int(answer)
af91b18508ff361b0524a551949aac7d93f9afc6
699,324
import torch def decode_delta(delta: torch.Tensor, anchor_mesh: torch.Tensor) -> torch.Tensor: """Converts raw output to (x, y, w, h) format where (x, y) is the center, w is the width, and h is the height of the bounding box. Args: delta (torch.Tensor): Raw output from the YOLOLayer. anchor_mesh (torch.Tensor): Tensor containing the grid points and their respective anchor offsets. Returns: (torch.Tensor): Decoded bounding box tensor. """ delta[..., :2] = delta[..., :2] * anchor_mesh[..., 2:] + anchor_mesh[..., :2] delta[..., 2:] = torch.exp(delta[..., 2:]) * anchor_mesh[..., 2:] return delta
cfad342c545d5b0f223488f52a445d8580f42d16
513,355
def str2int(s: str) -> int: """将字符串数字转为整数 :param s: 字符串数字 :return: 对应的整形数,如果不是数字返回0 """ try: res = int(s) except Exception: res = 0 return res
6b7f77c30596b24f31cf102f89611cece1bf095e
496,057
import click def get_input_prompt(title, colour="white"): """Get prompt for input() function""" return click.style(f"- {title} \u2192 ", colour)
d263484b642126cd71a68791c0737a3714938705
427,010
def letter_code(letter): """Determine the ISO 6346 numeric code for a letter. Args: letter (str): A single letter. Returns: An integer character code equivalent to the supplied letter. """ value = ord(letter.lower()) - ord("a") + 10 return value + value // 11
22718e2d6f83b968a1ba9dc4cfec10fbe45d78fe
433,165
import string def base26(number: int) -> str: """Generate a base 26 representation of `number` Namely: - 0 -> A - 1 -> B - ... - 25 -> Z """ if number == 0: return string.ascii_uppercase[0] digits = [] while number: digits.append(string.ascii_uppercase[number % 26]) number //= 26 digits.reverse() return "".join(digits)
7fee5f3f8d363b862bb78f6a8d5ff52e12e4997e
514,445
def get_num_train_images(hparams): """Returns the number of training images according to the dataset.""" num_images_map = { 'imagenet': 1281167, 'cifar10': 50000, } if hparams.input_data.input_fn not in num_images_map: raise ValueError( f'Unknown dataset size for input_fn {hparams.input_data.input_fn}') num_images = num_images_map[hparams.input_data.input_fn] if hparams.input_data.max_samples > 0: return min(num_images, hparams.input_data.max_samples) return num_images
e75e827026b247158ca76890990b04d51cd99a6a
23,439
def _iou(p1, p2): """Computes intersection over union of two intervals. Args: p1 ((int,int)): First interval as (first ts, last ts) p2 ((int,int)): Second interval as (first ts, last ts) Returns: float: intersection over union of the two intervals. """ i_start = max(p1[0],p2[0]) i_end = min(p1[1],p2[1]) i_len = max(0,i_end-i_start) o_start = min(p1[0],p2[0]) o_end = max(p1[1],p2[1]) o_len = o_end-o_start return float(i_len)/o_len
2fbe75748a131ce2cfbfe7cee5a9fff300e617e1
59,882
import math def handle_flyaway(sim_clock, capsule): """ The user has started flying away from the moon. Since this is a lunar LANDING simulation, we wait until the capsule's velocity is positive (downward) before prompting for more input. Returns True if landed, False if simulation should continue. """ while True: w = (1 - capsule.m * capsule.g / (capsule.z * capsule.fuel_per_second)) / 2 delta_t = ( capsule.m * capsule.v / ( capsule.z * capsule.fuel_per_second * math.sqrt(w**2 + capsule.v / capsule.z) ) ) + 0.05 new_state = capsule.predict_motion(delta_t) if new_state.altitude <= 0: # have landed return True capsule.update_state(sim_clock, delta_t, new_state) if (new_state.velocity > 0) or (capsule.v <= 0): # return to normal sim return False
9534b1bb1979058c01094ab04ab6e2fabaedc231
425,072
import hashlib def CryptDeriveKey(password, key_len=0x20): """ Emulate MS CryptDeriveKey https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptderivekey :param bytes password: Password to base the key off of. :param int key_len: Length of key to be used. :return: Sequence of bytes representing the key to use. :rtype: bytes """ base_data = hashlib.sha1(password).digest() b1, b2 = bytearray(b'\x00' * 0x40), bytearray(b'\x00' * 0x40) for i in range(0, 0x40): b1[i] = 0x36 b2[i] = 0x5c if i < len(base_data): b1[i] ^= base_data[i] b2[i] ^= base_data[i] key_hash = hashlib.sha1(b1).digest() + hashlib.sha1(b2).digest() return key_hash[:key_len]
76ca203a59b98acf230b534d6d85797e21169eec
244,062
import json def read_reference_cities(reference_geojson_filename): """Returns list of cities as objects with fields 'id', 'properties', 'geometry' (as geojson features generated by overpass-api). """ with open(reference_geojson_filename) as f: geojson = json.load(f) return geojson['features']
58a96a3e1600c0d095dbf3fc317571d7cd62979d
470,919
def valid_version(version): """Return true if the **version** has the format 'x.x.x' with integers `x`""" try: numbers = [int(part) for part in version.split('.')] except ValueError: return False if len(numbers) == 3: return True else: return False
6639f8969579b51a307622bd35e1209a0d88cfc9
253,587
def head(*args, **kwargs): """Returns first n rows""" return lambda df: df.head(*args, **kwargs)
d480e678fa5261ce1e54ba886c8735aa06dfa694
372,626
def match(results, expected): """Return whether or not the results match the expectation. Excludes the response object.""" for result in results: result.pop('data') return results == expected
516e2ed197c161b4bccf69eca892c51042db5296
452,424
from typing import Iterable def duplicated(lst: Iterable) -> set: """Find which items are duplicated in a list/set/tuple (does not keep order) Args: lst: Iterable with items to check Returns: Set: set with items repeated (unique) Examples: >>> a = [1, 2, 3, 1, 4, 5, 2] >>> duplicated(a) {1, 2} """ seen = set() return set(x for x in lst if x in seen or seen.add(x))
9cd1ebf51b291baad673091f982425202a92cf61
211,994
def _make_env(environment): """Change from Docker environment to Kubernetes env Args: environment (dict): Docker-style environment data Returns: list: Kubernetes-style env data """ env = [] for key, value in environment.items(): env.append({"name": key, "value": value}) return env
ba3b149dbf27ecabb6287a7d067a0f242744cb7d
638,973
def _get_partition_from_id(partitions, user_partition_id): """ Look for a user partition with a matching id in the provided list of partitions. Returns: A UserPartition, or None if not found. """ for partition in partitions: if partition.id == user_partition_id: return partition return None
257db9d2302395055f90af87db68ebffde65f237
562,514
import json def output_fn(prediction_output, accept='application/json'): """ Converts the outputted json to bytes """ if accept == 'application/json': # logger.info("Output successfully parsed.") return json.dumps(prediction_output).encode('utf-8') raise Exception('Requested unsupported ContentType in Accept: ' + accept)
ad894d9cf3f0626a1fe8ef0a48a0d3034e2fbc95
404,668
def measure_relative(S): """Calculate the "measure-relative" score as defined in the paper Args: S (List[List[int]]): accuracy counts as defined in the paper Returns: score (float): measure-relative score """ denom = S[0][0] + S[1][1] + S[0][1] + S[1][0] if denom == 0: return 0 return (S[0][1] - S[1][0]) / denom
598330f5d8981cc19545fbe38c4579e4fa8078a9
509,220