content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def is_multiline(string: str) -> bool: """Check whether a string consists of multiple lines.""" return "\n" in string
22e79546aa2b9d5516a100c9b035bcf7e57ebb45
670,809
def hello_user(user): """ this serves as a demo purpose :param user: :return: str """ return "What's up %s!" % user
eee024ed23d23dc3e982070188988772bf290413
670,811
def swat_port_map_1(): """Six plcs and hmi. Pox uses underscore MAC representation """ mac_to_port = { '00:1d:9c:c7:b0:70': 1, '00:1d:9c:c8:bc:46': 2, '00:1d:9c:c8:bd:f2': 3, '00:1d:9c:c7:fa:2c': 4, '00:1d:9c:c8:bc:2f': 5, '00:1d:9c:c7:fa:2d': 6, ...
c420aa1d47373ae02d3aa50ba39f654cf065140e
670,813
import requests def download_dff(url, path): """Downloads a missing DFF from the specified URL to a given FS path.""" resp = requests.get(url, stream=True) if resp.status_code != 200: print('DFF %s not found' % url) return False with open(path, 'wb') as fp: for chunk in resp.it...
d10e7983c1489446e5f337abf2c56f16b202fe39
670,814
import re def replace_fullwidth_alpha_numeral_to_halfwidth(text: str): """ Replace full-width alpha-numeral characters to half-width characters. Args: text (str): Text to replace. Returns: str: Replaced text. """ return re.sub(r'[A-Za-z0-9]', lambda mathobj: chr(ord(mathobj.g...
acf0d45e63a6595955c3da1d9f70424ea95c8d95
670,815
import os def construct_rentplus_name(sim_name): """ Returns an RentPlus inference filename (without file extension), based on a simulation name. """ d,f = os.path.split(sim_name) return os.path.join(d,'+'.join(['rentpls', f, ""]))
aeb5adb12822969e988b84e2cd9a33fbadcd69c9
670,816
def t_AND(t): """ \\band\\b """ return t
5f423881898258c6a1e0f70cc9d68637adc5868d
670,817
import math def qsub_format_memory(n): """Format memory in bytes for use in qsub resources.""" if n >= 10 * (1024 ** 3): return "%dGB" % math.ceil(n / (1024 ** 3)) if n >= 10 * (1024 ** 2): return "%dMB" % math.ceil(n / (1024 ** 2)) if n >= 10 * 1024: return "%dkB" % math.ceil(...
b0dc62c889b514382a7b5d97c4d9a85a1343f368
670,819
from typing import Tuple def get_mode(mode: str, line: str) -> Tuple[str, bool]: """Get the mode of the map. Args: mode (str): the current mode line (str): the line to check Returns: str, bool: the new mode, if the mode has changed """ if line == "" or line[0] == "#": ...
721d335ea1eaefbfc3f8a3ab60fb351d1b940674
670,820
def _applescriptify(text): """Replace double quotes in text.""" return text.replace('"', '" + quote + "')
8444cf8a7f4304cabb3f1b1e4d1bc7732e6fb01f
670,821
def _get_completed_count(action, completed_members): """returns the compelted member count.""" for member in completed_members: if member['action'] == action.id: return member['count'] return 0
b08a6619710c6a97a5302a9376db3396b28e3fcb
670,822
def TAny(_): """Accepts any value. """ return True
bcecc3f3778004b81eac293c7a216d5726fa47d9
670,823
def add_constants(parameters, chosen_pi_set): """ Parameters ---------- parameters: Names of the input pi numbers used in the py function chosen_pi_set: Current chosen pi set (PositiveParameterSet) Returns Function to support constant pi numbers ------- """ f_str = "# Constant(s):...
9efaf0d97d2d2dade3211883b3ea78833cb4ee48
670,824
def argwhere_to_tuples(argwhere_array): """ Converts the output locations array of np.argwhere(...) to a list of tuples. :param argwhere_array: Output of np.argwhere(...). :return: List of tuples, each tuple representing one argwhere position. """ return [tuple(x) for x in argwhere_array]
231d1327c274d2d87186752db13170acddb59989
670,827
def merge(llist, rlist, ascending=True): """ Merge two lists into an ordered list. If ascending == True build a ascending list If ascending == False build a descending list """ final = [] while llist or rlist: # This verification is necessary for not try to compare # a NoneTy...
b6be4da9bbe1971234848aec6ec151351997309e
670,828
def get_future_suppression_from_r0(R0, scenario): """ Returns the future suppression level for a given R0 and a "future scenario". Parameters ---------- R0:float Reproduction number scenario: str 'no_intervention', 'flatten_the_curve', 'social_distancing'. Returns -----...
e30dd2e2e12fc44c78df5e2be492dfa4f52c55b5
670,829
def split_by_comma(line): """ Converts the given line of text into comma-delimited tokens :param line: the line of text to process :return: an array of tokens contained in the line of text """ return line.split(",")
2d65538fa5a5cbcd14fefc269318baf9dcff926b
670,830
async def join(client, event): """Joins to voice channel.""" # Getting the author voice state voice_state = event.voice_state if voice_state is None: return 'You are not at a voice channel!' # Connecting the client to the same channel, where the user is. try: await client.jo...
f9ca34760719b8a73cd1e1d61556b72e37843459
670,831
import ast def parse_migration(f): """ Parse migration file and return (frozen_models, complete_apps). The returned objects are full-fledged Python data structures, as if we actually imported the migration file. But because we use ast.literal_eval(), this is safe to run on untrusted code. """...
c216c9cc5d11fdf9e62274b53678909032abcb0c
670,832
def set_conn_string(server, db_name, username, password): """ Sets connection string to SSAS database, in this case designed for Azure Analysis Services """ conn_string = ( "Provider=MSOLAP;Data Source={};Initial Catalog={};User ID={};" "Password={};Persist Security Info=True;Impers...
9b7d63a0ef97eb4012163550ed0548c5e531fe39
670,833
def one(x, default=None): """ Se le pasa una lista de elementos (normalmente de un xml) y devuelve el primero o None; sirve para ahorrar try/excepts y limpiar código""" try: return x[0] except IndexError: return default
31d14430803df99015122091aef8382cb6f2d0ef
670,834
from typing import OrderedDict import yaml def _get_oredered_loader(Loader): """Get OrderedLoader.""" class _OrderedLoader(Loader): pass def _construct_mapping(loader, node): loader.flatten_mapping(node) return OrderedDict(loader.construct_pairs(node)) _OrderedLoader.add_cons...
14ab70bd476a5de3de937bfa2dfb156101210a4b
670,836
def example_string(): """ returns a string """ return 'this is the example string'
c68f02da8fad8764a3f98853d7a02d083ecdb21a
670,837
def _is_number(s: str) -> bool: # pylint: disable=invalid-name """Return True if string is a number.""" return s.replace(".", "", 1).isdigit()
ec741bf8a140b2cb95f7389b77aba4ec98aad3b8
670,838
import os import re def get_profiles(): """Get names of profiles from ~/.aws/credentials file""" cred_file = os.path.abspath(os.path.expanduser('~/.aws/credentials')) rx = re.compile(r'^\[([^\]]+)\]$') profiles = [] text = '' try: with open(cred_file) as fp: text = fp.read(...
f86318f20b844dd1c658e6946611122660b8ac92
670,839
import sys import os def get_cache_directory() -> str: """Returns the cache directory based on the user's operating system""" directory: str = "" if sys.platform in ["linux", "linux2"]: directory = os.path.join(os.path.expanduser("~"), ".cache") elif sys.platform == "darwin": directory...
2a4beb04693eaeeea36dc9255e72bdaa42f8943f
670,840
import struct import fcntl import termios import os def terminal_width(): """Function to compute the terminal width.""" width = 0 try: s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(1, termios.TIOCGWINSZ, s) width = struct.unpack('HHHH', x)[1] except: pass if w...
3fe9e6e1e8988144ea12299d774cecb6c6d31cb4
670,841
def u_func(mahalanobis_dist, huber_denom, c_square): """ Huber's loss function :param mahalanobis_dist: Mahalanobis distance :param huber_denom: A constant in num_features (number of features) :param c_square: A constant in num_features and quantile (trade-off variable) :return: weight of sample...
d2cafbf4728e3d443423a6ed4a2b2d191943c18d
670,842
import os def combine(*parts): """combine ``parts`` into valid ZooKeeper path. :arg parts: list of str """ if not any(parts): return '/' parts = filter(lambda part: part, parts) return os.path.join(*parts)
06a00561c4cc236a328064400840f6ea5d23ece3
670,843
def ngrams(sequence, n: int): """ :return: The ngrams of the message in order """ assert isinstance(n, int) mlen = len(sequence) ngramlist = ( sequence[start:end] for start, end in zip( range(mlen - n + 1), range(n, mlen + 1))) return ngramlist
027ab61bd54979206765bfe5c42079f19bf44e42
670,844
import argparse def parameter_parser(): """ A method to parse up command line parameters. By default it learns on the Watts-Strogatz dataset. The default hyperparameters give good results without cross-validation. """ parser = argparse.ArgumentParser(description="Run CapsGNN.") parser.add_ar...
6f41e5f8721757599ca2b8a1354032603b4abfeb
670,845
def safe_int(string_, default=1): """Convert a string into a integer. If the conversion fails, return the default value. """ try: ret = int(float(string_)) except ValueError: return default else: return ret
838f3a479a0181a5bcba00c9a058ac5d342d8e22
670,846
def _build_flow_dict(G, R, capacity, weight): """Build a flow dictionary from a residual network. """ inf = float('inf') flow_dict = {} if G.is_multigraph(): for u in G: flow_dict[u] = {} for v, es in G[u].items(): flow_dict[u][v] = dict( ...
fd938df0563c6b59eba0d9b0226a67253b626cee
670,847
def reverse_bits(x, n): """reverse n bits of x""" rev = 0 for i in range(n): rev = (rev << 1) + (x & 1) x >>= 1 return rev
6a5daff588df545883b3dff6cd4f69d1f8988db5
670,848
def noop(sample, feat_idxs): """Don't expand.""" return []
d4844a6efea8e514be327390f2b320d8acb7a6a7
670,849
def get_approvals_from_scrape(soup): """Take a BeautifulSouped page and return a clean list of all approval dates.""" table = soup.find('table', attrs={'class':'approvals'}) approvals = [] if table: for tr in table.find_all('tr'): country = tr.find('th') date = tr.find('t...
91f57f1560f6d00811538fd523107b922b8e84be
670,850
import csv def write_colocated_gates(coloc_gates, fname): """ Writes the position of gates colocated with two radars Parameters ---------- coloc_gates : dict dictionary containing the colocated gates parameters fname : str file name where to store the data Returns ---...
aaf7421036f39c898a3ee9e7c166ce24cdda6b4e
670,851
def winners(metrics, metric_name, point_values): """Awards points to the top scoring users in a particular metric point_values should be a list of point values like [1000, 500, 200]. In this example, 1000 points are awarded to the top scoring member, 500 to the second place, and 200 to the third. Any n...
3361db63f498ad948d5d7c7882c5af73905fc762
670,852
def _minimum_bracket_reversals(input_string): """ Calculate the number of reversals to fix the brackets Args: input_string(string): Strings to be used for bracket reversal calculation Returns: int: Number of bracket reversals needed """ # this is technically write, # however t...
b93e1ef626ad3d64c15872675a1b94d5f97130a3
670,853
def shortText(a,b): """Returns a short portion of the text that shows the first difference a: the first text element b: the second text element """ a = repr(a) b = repr(b) displayLen = 20 halfDisplay = displayLen//2 if len(a)+len(b) < displayLen: return a+" "+b firstDiff = -1 i = 0 while i <...
a54cc9c5e310e6bf15f6ee99d8fdd50703faf221
670,854
def binary_search(given_array, key, starting_index, ending_index): """ Using binary search method to find the accurate(inplace) place for 'key' to reduce the complexity for comparisons of insertion sort""" if starting_index == ending_index: if given_array[starting_index] > key: return st...
78364e0d9c8441e567c901146e61548d7d118997
670,856
def rgb2hex(colorin): """ Convert (r,g,b) to hex """ r = int(colorin.split('(')[1].split(')')[0].split(',')[0]) g = int(colorin.split('(')[1].split(')')[0].split(',')[1]) b = int(colorin.split('(')[1].split(')')[0].split(',')[2]) return "#{:02x}{:02x}{:02x}".format(r,g,b)
1210f8e0c9188d92384fe50b8844be5de1a3689c
670,857
def count_groups(generator): """ Count the number of distinct elements in the stream, assuming that the elements come in groups. For example: >>> each(1, 2, 1, 10, 10, 5, 5) >> count_groups() 5 """ # Instead of using a sentinel value, just look at the first value output by # the...
edbdea6af044025ea7c82f62efce6dc21f01045e
670,858
def GetDetailedHelpForRemoveIamPolicyBinding(collection, example_id, role='roles/editor'): """Returns a detailed_help for a remove-iam-policy-binding command. Args: collection: Name of the command collection (ex: "project", "dataset") example_id: Collection iden...
f6d54cd3e3882155444fd720b0514ceda274fbb7
670,859
def simple_function(x): """Docstring.""" return x # comment
b949354a00f068f74459050baa85a85222dadd7a
670,861
def comprobar(cad): """funcion destinada a comprobar que sólo se introducen letras y espacios para los nombres""" list2 = cad.split() if len (list2) > 0: for i in range(0, len(list2)): if list2[i].isalpha()==False: return False return True else: ...
966e7b1ecacf06d303d7c253cc941d2d9ce75ab9
670,862
import json def load_coupling(name): """ Loads the coupling map that is given as a json file from a subfolder named layouts Args: name (string): name of the coupling map that was used when saving (corresponds to the filename without the extension .json) Returns: ...
067f9016dd1352c0f55f2e44edc947fd5674086d
670,863
import functools def deep_merge(*args): """Deep merge multiple dictionaries. >>> value_1 = { 'a': [1, 2], 'b': {'c': 1, 'z': [5, 6]}, 'e': {'f': {'g': {}}}, 'm': 1, } >>> value_2 = { 'a': [3, 4], 'b': {'d': 2, 'z': [7]}, 'e': {'f': {'h': 1}}, 'm': [1],...
9714b6c9173956e83b674ce4291bc9c47f736c64
670,864
def _get_flips(): """ Flips is a dict that contains the flips status of each orientation Returns ------- """ flips = { 'axial': {'x': False, 'y': False, 'z': False}, 'coronal': {'x': False, 'y': False, 'z': False}, 'impc_view': False, 'sagittal': {'x': False, 'y'...
f12712e2e4f73c8f3f5542675fa54900d1b66b91
670,865
def _normalize_seqs(s, t): """Normalize to DESeq2""" for ids in s: obj = s[ids] [obj.norm_freq.update({sample: 1.0 * obj.freq[sample] / t[sample]}) for sample in obj.norm_freq] s[ids] = obj return s
b57da5ae45f9ca76347ab8896bd36dc1bb026bdc
670,867
def str_to_bool(string): """Convert a string to a boolean value.""" if string.upper() in ["1", "ON", "TRUE", "YES"]: return True return False
bfd0858b1cd1bb6349abbec2dbf2c0b15b1f19d6
670,868
import re def _escape_and_globify(pattern_string): """Given a pattern string with a glob, create actual regex pattern. To require > 0 length glob, change the "*" to ".+". This is to handle strings like "*@company.com". (THe actual regex would probably be ".*@company.com", except that we don't want to...
da67c8941c5ab132d175c7723eebf12060179e3c
670,869
import socket def to_addrinfo(host_str): """ Tries to create a TCP socket 'addrinfo' without specific port for a host provided in `host_str`. Sets 'cannonname' in 'addrinfo' to `host_str` if it's resolved successfully. Args: host_str (string): Name or IPv4, or IPv6 of a host. Return...
d03bde69457968e69e34ab31e5a78838f5511217
670,870
def _dict_deep_merge(x, y): """Returns the union of x and y. y takes predescence. """ if x is None: return y if y is None: return x if isinstance(x, dict): if isinstance(y, dict): return {k: _dict_deep_merge(x.get(k), y.get(k)) for k in set(x).union(y)} assert y is None, repr(y) r...
ff53611f0da21bc69d1431d8a3d828513b7c09d9
670,872
def _get_QCheckTreeWidget(self): """ Get currently checked values in QCheckTreeWidget via re-mapping filter. Selected values are returned as a list. """ return [self._get_map(s) for s in self._checked_item_cache]
389c35fcfb651607d85bd28a6c0c5a46b63c46d4
670,873
import os def list_mhc_alleles(): """ Returns the list of available MHC alleles. """ mhc_alleles = [] for fname in os.listdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models')): mhc_name = fname.split('.model.gz')[0] mhc_alleles.append(mhc_name) return mhc_alle...
72f1aeb7fc3eae0772a6378592deb8bf92e203a9
670,874
def calc_pages(total_count: int, this_count: int): """ preforms ciel operation to find the total number of pages """ return -(-total_count // this_count)
6b01d317658aa3c7e08111142be61125de0a58ff
670,875
def getVariableExample(dev,var): """Example get variable function""" return(var._block.getUInt(var.bitOffset,var.bitSize))
b4038446e1f0cff5ab61ede7a63295dcc4e885e8
670,876
def transpose(xs): """ Transpose a matrix """ return map(list, zip(*xs))
09979f5b3995b1f3b893b0a754317f70f66a975d
670,877
def remove_prefix(text: str, prefix: str) -> str: """ Removes the prefix from the beginning of the text if the text starts with the prefix :param str text: text that potentially starts with a prefix :param str prefix: prefix that the text potentially starts with :return: the text with stripped pref...
c2a835695b6e505ecdd8ac66a00feda769dea143
670,878
def recognize_destination(line: str) -> bool: """ Recognizes .po file target string. """ if line.startswith("msgstr"): return True return False
da6c3f9344318fbd6cf5f1c636edf1586a0f1682
670,879
def flatten_list_prime(l): """ Flattens a list so that all prime numbers in embedded lists are returned in a flat list Parameters: - l: a list of numbers; largest prime cannot be greater than 1000 Returns: - flat_l: a flat list that has all the prime numbers in l ...
04b54f8927fd330e5cc33d8dbf2715799df951b0
670,880
def ignore_background(array, num_classes, ignore=0): """ :param array: [*],values in [0,num_classes) :param num_classes: C :param ignore: ignore value of background, here is 0 :return: [*] which ignore_index=num_classes """ array[array == ignore] = -1 array[array > ignore] -= 1 retur...
0d486b283eb096fd7a41900b2037c9c956934204
670,881
def read_file(data_file, mode='more'): """ 读文件, 原文件和数据文件 :return: 单行或数组 """ try: with open(data_file, 'r') as f: if mode == 'one': output = f.read() return output elif mode == 'more': output = f.readlines() ...
b4b789276d72491bd8ac77d1c08d46be2b3be804
670,882
def gruneisen_coefficient(tab, spec, *XYf): """Gruneisen Coefficient""" XYf = list(XYf) XYf[1] = tab.get_table('U{s}_DT', spec)(*XYf) return tab.get_table('P{s}_DU{s}', spec)(*XYf)
65d94044cbd931fb005e06927030307730070c72
670,883
def frequency(survey, responses): """ responses needs to be a single list""" freqs = {q : {o : 0 for o in q.options} for q in survey.questions} for response in responses: for q in response.keys(): o = response[q][0] freqs[q][o] += 1 return freqs
90f7266c229ef1fd194f4bea97142d1170b42768
670,884
def apply_iam_bindings_patch(current_policy, bindings_patch, action): """ Patches the current policy with the supplied patch. action can be add or remove. """ for item in bindings_patch['bindings']: members = item['members'] roles = item['roles'] for role in roles: if role not in current_pol...
2bc2a9204aaeb0680933fddef43ee62f103f1f39
670,885
import inspect from typing import Callable import gc def func_in_frame_info(frame_info: inspect.FrameInfo) -> Callable: """Find callable corresponding to given frame_info.""" f_code = frame_info.frame.f_code for obj in gc.get_referrers(f_code): if hasattr(obj, '__code__') and obj.__code__ is f_cod...
dab29216e7e8d0561e0c5b150b42e4b8a1890ec7
670,886
def convertType(pair: tuple): """Convert items to the appropriate types Arguments: pair: A tuple containing 2 items Returns: pair: A tuple containing 2 items where the second item is converted to the appropriate types """ # If it is not a pair if len(pair) != 2: ...
97a9012ea78de834f19ffdd28d144c374c2379e9
670,887
def header(text, color='black'): """Create an HTML header""" raw_html = f'<h1 style="margin-top:12px;color: {color};font-size:54px"><center>' + str( text) + '</center></h1>' return raw_html
666ce695b5814f657a283d2ef09d947158a37444
670,888
import torch def dist_cond(x: torch.Tensor, c: torch.Tensor, **kwargs): """ :param x: the feature vector of the Unet. shape (N,F,H,W) :param c: the external condition feature vectors. shape (C,N,F) :return: (C,N,F,H,W) """ x_orig = x # x = normalize(x, p=2, dim=1) # c = normalize(c, p...
fbbdbe9b8c8b1597cb0451876ad7f783e12a1451
670,889
import json def load_json(location): """ Read JSON file at `location` and return a list of ordered dicts, one for each entry. """ with open(location) as json_file: results = json.load(json_file) if isinstance(results, list): results = sorted(results) else: results =...
08549abd9c822dac6628c77871a4c03d018524d5
670,890
def validate_required_fields(metadata): """Check if the metadata can be used on analysis. This is evolving""" required = ['RESULTS-BALANCED_ACCURACY'] val = True for field in required: val = val & (field in metadata) return val
ab6c9cfec3f43c06c9b174681636eea6cd80be84
670,891
import csv def read_input_genes(filename): """ :param filename: :return: """ res = [] with open(filename, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in reader: res.append(''.join(row)) return res
0147c83f29c2e29757149cc23c3961a5a5be417c
670,893
import click from typing import Union from typing import Optional import re def _validate_cluster_id( ctx: click.core.Context, param: Union[click.core.Option, click.core.Parameter], value: Optional[Union[int, bool, str]], ) -> str: """ Validate that a value is a valid cluster ID. """ # We ...
13a630a29a7935980c28a552f16d4007fa73c42c
670,895
def gateway_environment(gateway_environment): """Enables path routing on gateway""" gateway_environment.update({"APICAST_PATH_ROUTING": True}) return gateway_environment
1c89bc7891696a3fab21b0caa968660ab8ff586b
670,896
import argparse def _parse_args(argv): """Parses command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--table_name', type=str) parser.add_argument('--table_size', type=str) parser.add_argument('--job-dir', type=str) parser.add_argument('--bucket_name', type=str)...
52e1bfbaea774cf0b851a4d625771bf2f37f5caf
670,898
def tree_serialize(obj): """Function to serialize a tree object""" res = b'' for i in obj.items: res += i.mode res += b' ' res += i.path res += b'\x00' sha = int(i.sha, 16) res += sha.to_bytes(20, byteorder="big") return res
94777a36828f4bd27a8135abe63567c999594bb3
670,900
def waitForThreadsToFinish(): """waitForThreadsToFinish() -> str Returns true if Nuke should wait for any Python threads to finish before exitting. @return: True or False.""" return ''
f074ad2202d994f273b349e4c38125da3146e4e6
670,901
def merge_words(current_words, new_words): """ Determine words to add and delete for words update. Parameters: list(dict). Currently existing words list(dict). Words after update Return: list(dict). Words to keep list(dict). Words to remove ...
0abe26bcbd5deb2c5bae5a6d7c8c3fb4c9427bd7
670,903
def for_each_in(cls, f, struct): """ Recursively traversing all lists and tuples in struct, apply f to each element that is an instance of cls. Returns structure with f applied. """ if isinstance(struct, list): return map(lambda x: for_each_in(cls, f, x), struct) elif isinstance(struct, tupl...
b81dd5bfeb7f140ef49a48bfd590e407568f913b
670,904
def pack(fmt, *values): """Return a string containing the values packed according to the given format. :type fmt: bytes | unicode :rtype: bytes """ return b''
668605773c21b7bdfaa78d4c51e4340abd186677
670,906
import collections def get_sectors(n_con): """ INPUTS: n_con (mysql) - A "normal" pymysql database connection OUTPUT: Dictionary with sectors as keys, and lists of ticker_id's as values """ sectors = collections.defaultdict(list) with n_con.cursor() as n_cur: n_cur.exec...
298741eedd8cffc96453882d449d479cd29e2f3c
670,908
def cublas_init(): """ Initialize Cublas. """ return 0
f87631b1026249ef50d496475695e357b5099da3
670,909
import unicodedata def unaccent(string): """ Receives a string and return it without accents :param string: accented string :return: unaccented string """ text = unicodedata.normalize('NFD', string) text = text.encode('ascii', 'ignore') text = text.decode("utf-8") return str(text...
4f49c9959ff9ae6bcf45fa5268a84e148dc9de68
670,910
def _recover_uid(good_id) -> int: """ Get the uid part of the good id. :param str good_id: the good id :return: the uid """ uid = int(good_id.split("_")[-2]) return uid
698fe08bb50011e989809d78002ab671af40f355
670,911
def test_1(): """ :return: """ return "<body>hh</body>"
841598fa12c30e824712342cce440a190b405f53
670,912
import argparse def create_parser(): """Create CLI parser using argparse Returns: args namespace """ # Init parser parser = argparse.ArgumentParser( description="Download a slideshare presentation.", ) # Add args parser.add_argument( "url", type=s...
12fd428ed28eab2c902ac8325550a107c36f4e79
670,913
import os import fnmatch def find_data_files(package_dir, patterns): """Recursively finds files whose names match the given shell patterns.""" paths = set() for directory, _, filenames in os.walk(package_dir): for pattern in patterns: for filename in fnmatch.filter(filenames, pattern): # NB: p...
b149541f20dd2533b9b2564d5a682552d83f8cbf
670,914
def get_10_mouse_val_test_splits(): """ Validation and test chromosome split for the mouse genome. Returns the first split from get_10_mouse_val_test_splits Returns: dict: nested python dictionary with one validation & test split """ return {0: get_1...
86d6675269373b0826db8f0a5f6d3c49e9fd1977
670,915
def is_ok( option ): """ treat None option as not OK """ return (option is not None and option.ok)
1cc8ea7018d3c32649e9142a800e7be97dbe62e4
670,916
def rgba2int(r, g, b, a): """ rgba2int: Converts an RGBA value into an integer :param r The red value (0-255) :param g The green value (0-255) :param b The blue value (0-255) :param a The alpha value (0-255) :returns: The RGBA value compact into a 4 byte integer. """ return (r << 24) ...
4aeb6612798de342556dbcd46e0f552e3c842be2
670,917
import re def findurls(text): """ Finds all urls in a string """ urls = re.findall('href="(.*?)"', text) return urls
e5d435dd073c7e781b14fd44c22a81c9c2019930
670,918
def table( caption="", thead="", tbody="", striped=True, bordered=False, hover=True, condensed=False, span=False): """ *Generate a table - TBS style* **Key Arguments:** - ``caption`` -- the table caption - ``thead`` -- the tabl...
b381a61757addf8457e9381708e60b21ecd01dba
670,919
def get_order(order): """ All the orders they create look something like this: "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza" Their preference is to get the orders as a nice clean string with spaces and capitals like so: "Burger Fries Chicken Pizza Pizza Pizza Sandwich Milksha...
b58620758a05a53dadd4e6b1d99491430a932bb1
670,920
def list_to_string(list_to_convert): """Returns a string with a commaseperatet list from the list""" return str(list_to_convert).strip('[]')
0ed6bff35b56b3bb343c6263964557beaa7a53f7
670,921
import logging def get_logger(name=__name__, level=logging.INFO): """ This pattern prevents creates implicitly creating a root logger by creating the sub-logger named __name__ Also by default sets level to INFO """ logger = logging.getLogger(name) logger.setLevel(level) return logger
8849d4964045fe05dca7d107c792062bc3163f71
670,923
import torch def __validate_model(loaded_model, dummy_model): """Validates that two models have the same architecture""" loaded_modules = [loaded_model] dummy_modules = [dummy_model] valid = torch.tensor(1, dtype=torch.long) try: while len(loaded_modules) > 0: loaded_module = ...
b233ae7ab2eee930eb83c8ec4b4f970fbfe05acd
670,924
import os import logging def getLargestItemInDir(directory): """ getLargestItemInDir finds the largest item inside the given directory :testedWith: TestCompletedDownloadsController:test_getLargestItemInDir :param directory: the directory to be explored :return: the largest item in the drectory or ...
89550e449eccac04cb527e4e8e82026f097a7e2e
670,925
def bit_invert(value, width=32): """! @brief Return the bitwise inverted value of the argument given a specified width. @param value Integer value to be inverted. @param width Bit width of both the input and output. If not supplied, this defaults to 32. @return Integer of the bitwise inversion of @...
bef9becb3e4fd3f291ac1ad1352630e6437f7fc3
670,926