content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def read_csv_to_lol(full_path, sep=";"): """ Read csv file into lists of list. Make sure to have a empty line at the bottom """ with open(full_path, 'r') as ff: # read from CSV data = ff.readlines() # New line at the end of each line is removed data = [i.replace("\n", "") for...
e53c46c6a8eabaece788111530fbf859dd23133f
708,118
import json import sys import os def json_loads(data): """Load json data, allowing - to represent stdin.""" if data is None: return "" if data == "-": return json.load(sys.stdin) elif os.path.exists(data): with open(data, 'r') as handle: return json.load(handle) ...
f5bdad826578108adccc32ca93ecd474954bfb7d
708,119
def make_predictions(clf_object,predictors_str,data_source): """make_predictions comes up with predictions from given input data Input: clf_object object constructed classification model predictors_str nd str array stri...
ed5f29e65ddf3d7f7081b89e6f747925de944567
708,120
import random import string def generate_random_string(N): """ Generate a random string Parameters ------------- N length of the string Returns ------------- random_string Random string """ return ''.join(random.choice(string.ascii_uppercase + string.digits) f...
3e2e672140e18546260a0882fa6cf06073bdf8e7
708,121
import re def extract_charm_name_from_url(charm_url): """Extract the charm name from the charm url. E.g. Extract 'heat' from local:bionic/heat-12 :param charm_url: Name of model to query. :type charm_url: str :returns: Charm name :rtype: str """ charm_name = re.sub(r'-[0-9]+$', '', c...
9905d6b5c7a2f5047bc939d1b6e23d128ee8984d
708,122
def class_name(service_name: str) -> str: """Map service name to .pyi class name.""" return f"Service_{service_name}"
b4bed8a677f9eedfcd66d6d37078075b0967ea20
708,123
import re def select_devices(devices): """ 选择设备 """ device_count = len(devices) print("Device list:") print("0) All devices") for i, d in enumerate(devices, start=1): print("%d) %s\t%s" % (i, d['serial'], d['model'])) print("q) Exit this operation") selected = input("\nselect: ") ...
91c405c8a198deb01e8abecc592ac2286dc712fd
708,124
def is_number(s): """ Check if it is a number. Args: s: The variable that needs to be checked. Returns: bool: True if float, False otherwise. """ try: float(s) return True except ValueError: return False
071aeac26a5a907caf1764dc20d7de1c6408714b
708,125
import itertools def combineSets(listOfSets): """ Combines sets of strings by taking the cross product of the sets and \ concatenating the elements in the resulting tuples :param listOfSets: 2-D list of strings :returns: a list of strings """ totalCrossProduct = [''] for i in ...
26a383d224716fd8f4cf8589607e2df1ccb82a7e
708,126
def _GetTombstoneData(device, tombstone_file): """Retrieve the tombstone data from the device Args: device: An instance of DeviceUtils. tombstone_file: the tombstone to retrieve Returns: A list of lines """ return device.old_interface.GetProtectedFileContents( '/data/tombstones/' + tombsto...
99322ea3d67e150f4433c713159eb7bc8069271f
708,127
import time def _strTogYear(v): """Test gYear value @param v: the literal string @return v @raise ValueError: invalid value """ try: time.strptime(v+"-01-01", "%Y-%m-%d") return v except: raise ValueError("Invalid gYear %s" % v)
a65e04c2d3790d3d55bbc8788d6802e1aae1b78c
708,128
import random def giveHint(indexValue, myBoard): """Return a random matching card given the index of a card and a game board""" validMatches = [] card = myBoard[indexValue] for c in myBoard: if (card[0] == c[0]) and (myBoard.index(c) != indexValue): validMatches.append(myBoard....
e578f40e7d7e2e17ddac53f9cfdc219e47c861cd
708,129
async def make_getmatch_embed(data): """Generate the embed description and other components for a getmatch() command. As with its parent, remember that this currently does not support non team-vs. `data` is expected to be the output of `get_individual_match_data()`. The following `dict` is returned...
c37e0d6ee948259e4ad898d3cafb8e13b6452d80
708,130
import torch def compute_inverse_interpolation_img(weights, indices, img, b, h_i, w_i): """ weights: [b, h*w] indices: [b, h*w] img: [b, h*w, a, b, c, ...] """ w0, w1, w2, w3 = weights ff_idx, cf_idx, fc_idx, cc_idx = indices k = len(img.size()) - len(w0.size()) img_0 = w0[(...,) ...
6b69aa5ca372a9c8f976512191d4626919d71311
708,131
def decode(value): """Decode utf-8 value to string. Args: value: String to decode Returns: result: decoded value """ # Initialize key variables result = value # Start decode if value is not None: if isinstance(value, bytes) is True: result = value....
9704678f6ff96de3b711758922c28f5ecbd11bc7
708,133
def _parse_none(arg, fn=None): """Parse arguments with support for conversion to None. Args: arg (str): Argument to potentially convert. fn (func): Function to apply to the argument if not converted to None. Returns: Any: Arguments that are "none" or "0" are converted to None; ...
4ebd283eb9e2218e523ba185c4500c9879d5719d
708,135
def generate_constraint(category_id, user): """ generate the proper basic data structure to express a constraint based on the category string """ return {'year': category_id}
f55151a5b4b17bbf6eb697e1b1489ee4897f5db0
708,136
import os def input_file_exists(filepath): """ Return True if the file path exists, or is the stdin marker. """ return (filepath == '-') or os.path.exists(filepath)
5f6a0c2195ce90ba551679d516ebee0e593184c8
708,137
from typing import List from typing import Set def ladder_length(beginWord: str, endWord: str, wordList: List[str]) -> int: """ 双端交替迫近目标层,根据一层数量最多节点确定为目标层 :param beginWord: :param endWord: :param wordList: :return: >>> ladder_length('hit', 'cog', ["hot","dot","dog","lot","log","cog"]) ...
020f3ffd2e009b682a47ff9aad8d1d6025c29f37
708,138
def setup_option(request): """Создаем объект для удобство работы с переменными в тестовых методах """ setup_parameters = {} if request.config.getoption('--site_url'): setup_parameters['site_url'] = request.config.getoption('--site_url') return setup_parameters
49908ee8e1422cc4fd05c6d93a96c00d734cf6d1
708,139
def get_unique_tokens(texts): """ Returns a set of unique tokens. >>> get_unique_tokens(['oeffentl', 'ist', 'oeffentl']) {'oeffentl', 'ist'} """ unique_tokens = set() for text in texts: for token in text: unique_tokens.add(token) return unique_tokens
f9c174b264082b65a328fd9edf9421e7ff7808a2
708,140
def moved_in(nn_orig, nn_proj, i, k): """Determine points that are neighbours in the projection space, but were not neighbours in the original space. nn_orig neighbourhood matrix for original data nn_proj neighbourhood matrix for projection data i index of the point considered ...
b63a9b0f53554032fc920aeaf6d3d76b93dd8ab3
708,141
def getStatic(): """ These are "static" params for a smoother application flow and fine tuning of some params Not all functions are implemented yet Returns the necessary Params to run this application """ VISU_PAR = { # ============================================================================...
f82ed9c4156b8199be924fc1ed62398fcbad9e0c
708,142
def pagenav(object_list, base_url, order_by, reverse, cur_month, is_paginated, paginator): """Display page navigation for given list of objects""" return {'object_list': object_list, 'base_url': base_url, 'order_by': order_by, 'reverse': reverse, 'cur_month': cur_...
eb61fb76dd32b8d0b3e264e77ce912766d3e38da
708,143
def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. val: float or int src: tuple dst: tuple example: print(scale(99, (0.0, 99.0), (-1.0, +1.0))) """ return (float(val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]
26cfaccaeea861ccecb36697838710c0ab706520
708,145
def add(c1, c2): """Add two encrypted counters""" a1, b1 = c1 a2, b2 = c2 return (a1 + a2, b1 + b2)
d3e519524fac558622f692a46ffb8fed9899176f
708,146
def error_message(error, text): """ Gives default or custom text for the error. -------------------- Inputs <datatype>: - error <Error Object>: The error code - text <string>: Custom error text if error has no message Returns <datatype>: - error description <string>: The cust...
466fec2d2abefc9f05a3f0adf569fba1c63ea4c1
708,147
def no_rbac_suffix_in_test_filename(filename): """Check that RBAC filenames end with "_rbac" suffix. P101 """ if "patrole_tempest_plugin/tests/api" in filename: if filename.endswith('rbac_base.py'): return if not filename.endswith('_rbac.py'): return 0, "RBAC t...
6ebfcede8b6e30f24f5ecc1f9d3f0985bd4c44fa
708,148
def minimax(just_mapping, mapping): """ Scale the mapping to minimize the maximum error from just intonation. """ least_error = float("inf") best_mapping = mapping for i in range(len(just_mapping)): for j in range(i+1, len(just_mapping)): candidate = mapping / (mapping[i] + m...
b2226de7a916e3075327cd30c64e7412e186027d
708,151
def transform_color(color1, color2, skipR=1, skipG=1, skipB=1): """ transform_color(color1, color2, skipR=1, skipG=1, skipB=1) This function takes 2 color1 and color2 RGB color arguments, and then returns a list of colors in-between the color1 and color2 eg- tj.transform_color([0,0,0],[10,10,20]) returns a list:...
5f04daa951c59b0445387b2dc988ab7efb98aff4
708,152
import os def create_experiment_dirs(exp_dir): """ Create Directories of a regular tensorflow experiment directory :param exp_dir: :return summary_dir, checkpoint_dir: """ experiment_dir = os.path.realpath(os.path.join(os.path.dirname(__file__))) + "/experiments/" + exp_dir + "/" summary_d...
9707152a57a322ad2d935c2614386218c2c66ee9
708,153
def get_go_module_path(package): """assumption: package name starts with <host>/org/repo""" return "/".join(package.split("/")[3:])
1443d59391a36c7b9ba1d72ade9fd51f11cc1cc3
708,154
def generate_paths(data, path=''): """Iterate the json schema file and generate a list of all of the XPath-like expression for each primitive value. An asterisk * represents an array of items.""" paths = [] if isinstance(data, dict): if len(data) == 0: paths.append(f'{path}') ...
367f244b44c254b077907ff8b219186bd820fccd
708,155
def order_rep(dumper, data): """ YAML Dumper to represent OrderedDict """ return dumper.represent_mapping(u'tag:yaml.org,2002:map', data.items(), flow_style=False)
6b455d49cd5702324f4b1e825dabb4af90734730
708,157
def make1d(u, v, num_cols=224): """Make a 2D image index linear. """ return (u * num_cols + v).astype("int")
1f37c7ae06071ce641561eadc1d0a42a0b74508d
708,158
from datetime import datetime def header_to_date(header): """ return the initial date based on the header of an ascii file""" try: starttime = datetime.strptime(header[2], '%Y%m%d_%H%M') except ValueError: try: starttime = datetime.strptime( header[2] + '_' + he...
3e2757ae39a2a9008a5f0fb8cd8fe031770c83ad
708,159
import copy def permutationwithparity(n): """Returns a list of all permutation of n integers, with its first element being the parity""" if (n == 1): result = [[1,1]] return result else: result = permutationwithparity(n-1) newresult = [] for shorterpermutation in result: ...
218b728c2118a8cca98c019dff036e0ae2593974
708,161
def gravitationalPotentialEnergy(mass, gravity, y): """1 J = 1 N*m = 1 Kg*m**2/s**2 Variables: m=mass g=gravity constant y=height Usage: Energy stored by springs""" U = mass*gravity*y return U
f4fcfc9e7ddac8b246b2200e3886b79f6706936e
708,162
def to_list(obj): """List Converter Takes any object and converts it to a `list`. If the object is already a `list` it is just returned, If the object is None an empty `list` is returned, Else a `list` is created with the object as it's first element. Args: obj (any object): the object...
3ca373867ea3c30edcf7267bba69ef2ee3c7722e
708,163
def function(): """ >>> function() 'decorated function' """ return 'function'
46b892fb70b5672909d87efcf76ffd3f96f9cf7f
708,164
def load_stopwords(file_path): """ :param file_path: Stop word file path :return: Stop word list """ stopwords = [line.strip() for line in open(file_path, 'r', encoding='utf-8').readlines()] return stopwords
9cb6578b5cbc608bc72da7c4f363b4f84d0adbb7
708,165
from datetime import datetime import uuid def versioneer(): """ Function used to generate a new version string when saving a new Service bundle. User can also override this function to get a customized version format """ date_string = datetime.now().strftime("%Y%m%d") random_hash = uuid.uuid4(...
7c5123d28e3bee45f2c9f7d519e830cf80e9fea8
708,167
import subprocess def get_git_revision_hash(): """Returns the git version of this project""" return subprocess.check_output( ["git", "describe", "--always"], universal_newlines=True )
51c76a0e814cd8336d488c6d66a17ba3422c5c66
708,168
def train_test_split(df, frac): """ Create a Train/Test split function for a dataframe and return both the Training and Testing sets. Frac refers to the percent of data you would like to set aside for training. """ frac = round(len(df)*frac) train = df[:frac] test = df[frac:] r...
8e233e017a261141f57f7b2bff9a527e275d2ed9
708,169
def filter_imgs(df, properties = [], values = []): """Filters pandas dataframe according to properties and a range of values Input: df - Pandas dataframe properties - Array of column names to be filtered values - Array of tuples containing bounds for each filter Output: df - Filter...
cdc5c8bfef10fae60f48cee743df049581a0df04
708,170
from typing import Dict from typing import Any from typing import Optional def _add_extra_kwargs( kwargs: Dict[str, Any], extra_kwargs: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """ Safely add additional keyword arguments to an existing dictionary Parameters ---------- kwargs : dic...
cfc4c17f608c0b7fe1ae3046dc220d385c890caa
708,171
import random import math def Hiker(n,xLst,yLst,dist): """ Hiker is a function to generate lists of x and y coordinates of n steps for a random walk of n steps along with distance between the first and last point """ x0=0 y0=0 x=x0 y=y0 xLst[1] = x0 yLst[1] = y0 ...
abe341c8ecdc579de2b72f5af1ace3f07dd40dc3
708,172
def correct_repeat_line(): """ Matches repeat spec above """ return "2|1|2|3|4|5|6|7"
b9c1e48c5043a042b9f6a6253cba6ae8ce1ca32c
708,173
def char_decoding(value): """ Decode from 'UTF-8' string to unicode. :param value: :return: """ if isinstance(value, bytes): return value.decode('utf-8') # return directly if unicode or exc happens. return value
b8054b4a5012a6e23e2c08b6ff063cf3f71d6863
708,174
def get_relationship_length_fam_mean(data): """Calculate mean length of relationship for families DataDef 43 Arguments: data - data frames to fulfill definiton id Modifies: Nothing Returns: added_members mean_relationship_length - mean relationship length of families """ families...
4d9b76c4dca3e1f09e7dd2684bd96e25792177fd
708,176
import os def read_envs(): """Function will read in all environment variables into a dictionary :returns: Dictionary containing all environment variables or defaults :rtype: dict """ envs = {} envs['QUEUE_INIT_TIMEOUT'] = os.environ.get('QUEUE_INIT_TIMEOUT', '3600') envs['VALIDATION_TIMEOUT'] = os.environ.ge...
2d357796321d561a735461d425fa7c703082434c
708,177
import numpy def load_catalog_npy(catalog_path): """ Load a numpy catalog (extension ".npy") @param catalog_path: str @return record array """ return numpy.load(catalog_path)
912281ad17b043c6912075144e6a2ff3d849a391
708,178
import torch def exp2(input, *args, **kwargs): """ Computes the base two exponential function of ``input``. Examples:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.exp2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0])) tensor([6.2500e-02, 5.0000e-01, 1.0...
17cbc0917acf19932ec4d3a89de8d78545d02e31
708,179
import pprint import json def tryJsonOrPlain(text): """Return json formatted, if possible. Otherwise just return.""" try: return pprint.pformat( json.loads( text ), indent=1 ) except: return text
2431479abf6ab3c17ea63356ec740840d2d18a74
708,180
def get_pool_health(pool): """ Get ZFS list info. """ pool_name = pool.split()[0] pool_capacity = pool.split()[6] pool_health = pool.split()[9] return pool_name, pool_capacity, pool_health
1a9dbb8477d8735b225afc2bdd683f550602b36e
708,181
def sum_fib_dp(m, n): """ A dynamic programming version. """ if m > n: m, n = n, m large, small = 1, 0 # a running sum for Fibbo m ~ n + 1 running = 0 # dynamically update the two variables for i in range(n): large, small = large + small, large # note that (i + 1)...
5be6e57ddf54d185ca6d17adebd847d0bc2f56fc
708,183
def fibo_dyn2(n): """ return the n-th fibonacci number """ if n < 2: return 1 else: a, b = 1, 1 for _ in range(1,n): a, b = b, a+b return b
e8483e672914e20c6e7b892f3dab8fb299bac6fc
708,184
import io def parse_file(fname, is_true=True): """Parse file to get labels.""" labels = [] with io.open(fname, "r", encoding="utf-8", errors="igore") as fin: for line in fin: label = line.strip().split()[0] if is_true: assert label[:9] == "__label__" ...
ea6cbd4b1a272f472f8a75e1cc87a2209e439205
708,185
import optparse def _OptionParser(): """Returns the options parser for run-bisect-perf-regression.py.""" usage = ('%prog [options] [-- chromium-options]\n' 'Used by a try bot to run the bisection script using the parameters' ' provided in the auto_bisect/bisect.cfg file.') parser = optpars...
7485db294d89732c2c5223a3e3fe0b7773444b49
708,186
import json import os def load_config(filename): """ Returns: dict """ config = json.load(open(filename, 'r')) # back-compat if 'csvFile' in config: config['modelCategoryFile'] = config['csvFile'] del config['csvFile'] required_files = ["prefix", "modelCategoryFil...
af9f6cb02925d38077652703813b9fec201f12f7
708,187
def convert(chinese): """converts Chinese numbers to int in: string out: string """ numbers = {'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '壹':1, '贰':2, '叁':3, '肆':4, '伍':5, '陆':6, '柒':7, '捌':8, '玖':9, '两':2, '廿':20, '卅':30, '卌':40, '虚':50, '圆':60, '近':70, '枯':80, '无':90} ...
cf2ece895698e2d99fde815efa0339687eadda97
708,188
def getjflag(job): """Returns flag if job in finished state""" return 1 if job['jobstatus'] in ('finished', 'failed', 'cancelled', 'closed') else 0
bf0c0a85cb1af954d25f4350e55b9e3604cf7c79
708,189
def construct_pos_line(elem, coor, tags): """ Do the opposite of the parse_pos_line """ line = "{elem} {x:.10f} {y:.10f} {z:.10f} {tags}" return line.format(elem=elem, x=coor[0], y=coor[1], z=coor[2], tags=tags)
21ca509131c85a2c7bc24d00a28e7d4ea580a49a
708,191
def convert_time(time): """Convert given time to srt format.""" stime = '%(hours)02d:%(minutes)02d:%(seconds)02d,%(milliseconds)03d' % \ {'hours': time / 3600, 'minutes': (time % 3600) / 60, 'seconds': time % 60, 'milliseconds': (time % 1) * 1000} return st...
948e6567c8bc17ccb5f98cf8c8eaf8fe6e8d0bec
708,192
def Returns1(target_bitrate, result): """Score function that returns a constant value.""" # pylint: disable=W0613 return 1.0
727e58e0d6d596cf4833ca3ca1cbcec6b9eedced
708,193
import re def remove_repeats(msg): """ This function removes repeated characters from text. :param/return msg: String """ # twitter specific repeats msg = re.sub(r"(.)\1{2,}", r"\1\1\1", msg) # characters repeated 3 or more times # laughs msg = re.sub(r"(ja|Ja)(ja|Ja)+(j)?", r"jaja",...
590ab42f74deaa9f8dc1eb9c8b11d81622db2e6d
708,194
def _legend_main_get(project, row): """ forma la leyenda de la serie principal del gráfico input project: es el tag project del proyecto seleccionado en fichero XYplus_parameters.f_xml -en XYplus_main.py- row: es fila activa devuelta por select_master) de donde se ex...
3938d723bd44a67313b86f956464fd186ef25386
708,195
def repr_should_be_defined(obj): """Checks the obj.__repr__() method is properly defined""" obj_repr = repr(obj) assert isinstance(obj_repr, str) assert obj_repr == obj.__repr__() assert obj_repr.startswith("<") assert obj_repr.endswith(">") return obj_repr
28537f4f48b402a2eba290d8ece9b765eeb9fdc3
708,196
def is_char_token(c: str) -> bool: """Return true for single character tokens.""" return c in ["+", "-", "*", "/", "(", ")"]
3d5691c8c1b9a592987cdba6dd4809cf2c410ee8
708,197
import numpy def _float_arr_to_int_arr(float_arr): """Try to cast array to int64. Return original array if data is not representable.""" int_arr = float_arr.astype(numpy.int64) if numpy.any(int_arr != float_arr): # we either have a float that is too large or NaN return float_arr else: ...
73643757b84ec28ed721608a2176b292d6e90837
708,198
import re def error_038_italic_tag(text): """Fix the error and return (new_text, replacements_count) tuple.""" backup = text (text, count) = re.subn(r"<(i|em)>([^\n<>]+)</\1>", "''\\2''", text, flags=re.I) if re.search(r"</?(?:i|em)>", text, flags=re.I): return (backup, 0) else: re...
b0c2b571ade01cd483a3ffdc6f5c2bbb873cd13c
708,199
def families_horizontal_correctors(): """.""" return ['CH']
a3f8de3e0d44ea72d2fb98733050b7a2d598c142
708,200
def __load_txt_resource__(path): """ Loads a txt file template :param path: :return: """ txt_file = open(path, "r") return txt_file
9e3632098c297d1f6407559a86f0d8dc7b68ea75
708,201
import torch def policy_improvement(env, V, gamma): """ Obtain an improved policy based on the values @param env: OpenAI Gym environment @param V: policy values @param gamma: discount factor @return: the policy """ n_state = env.observation_space.n n_action = env.action_space.n ...
10587e5d4fb08158eff06a4305de6c02fc2d878c
708,202
import sys def func(back=2): """ Returns the function name """ return "{}".format(sys._getframe(back).f_code.co_name)
97332c32195418e4bf6dd6427adabbc5c4360580
708,203
def get_A2_const(alpha1, alpha2, lam_c, A1): """Function to compute the constant A2. Args: alpha1 (float): The alpha1 parameter of the WHSCM. alpha2 (float): The alpha2 parameter of the WHSCM. lam_c (float): The switching point between the two exponents of the dou...
16fe12e9ef9d72cfe7250cf840e222512409d377
708,205
def unique_list(a_list, unique_func=None, replace=False): """Unique a list like object. - collection: list like object - unique_func: the filter functions to return a hashable sign for unique - replace: the following replace the above with the same sign Return the unique subcollection of collectio...
8d7957a8dffc18b82e8a45129ba3634c28dd0d52
708,206
def gap2d_cx(cx): """Accumulates complexity of gap2d into cx = (h, w, flops, params, acts).""" cx["h"] = 1 cx["w"] = 1 return cx
28f6ba5f166f0b21674dfd507871743243fb4737
708,207
from typing import Sequence from typing import Any def find(sequence: Sequence, target_element: Any) -> int: """Find the index of the first occurrence of target_element in sequence. Args: sequence: A sequence which to search through target_element: An element to search in the sequence Re...
20edfae45baafa218d8d7f37e0409e6f4868b75d
708,209
from pathlib import Path from typing import List from typing import Dict import json def read_nli_data(p: Path) -> List[Dict]: """Read dataset which has been converted to nli form""" with open(p) as f: data = json.load(f) return data
2218d8dc06e3b9adfe89cb780a9ef4e7cb111d14
708,210
def prepare_data_from_stooq(df, to_prediction = False, return_days = 5): """ Prepares data for X, y format from pandas dataframe downloaded from stooq. Y is created as closing price in return_days - opening price Keyword arguments: df -- data frame contaning data from stooq return_days -- nu...
4b5bc45529b70ed1e8517a1d91fb5a6c2ff0b504
708,211
def represents_int_above_0(s: str) -> bool: """Returns value evaluating if a string is an integer > 0. Args: s: A string to check if it wil be a float. Returns: True if it converts to float, False otherwise. """ try: val = int(s) if val > 0: return True...
e39c4afeff8f29b86ef2a80be0af475223654449
708,212
def sydney(): """Import most recent Sydney dataset""" d = { 'zip':'Sydney_geol_100k_shape', 'snap':-1, } return(d)
f79a5002ef548769096d3aeb1ad2c7d77ac5ce68
708,213
def format_non_date(value): """Return non-date value as string.""" return_value = None if value: return_value = value return return_value
9a7a13d7d28a14f5e92920cfef7146f9259315ec
708,214
import functools import math def gcd_multiple(*args) -> int: """Return greatest common divisor of integers in args""" return functools.reduce(math.gcd, args)
c686b9495cd45ff047f091e31a79bedcd61f8842
708,215
from typing import Counter def chars_to_family(chars): """Takes a list of characters and constructs a family from them. So, A1B2 would be created from ['B', 'A', 'B'] for example.""" counter = Counter(chars) return "".join(sorted([char + str(n) for char, n in counter.items()]))
e78de779599f332045a98edde2aa0a0edc5a653b
708,216
import configparser def get_config_properties(config_file="config.properties", sections_to_fetch = None): """ Returns the list of properties as a dict of key/value pairs in the file config.properties. :param config_file: filename (string). :param section: name of section to fetch properties from (if s...
627d21327560595bb4c2905c98604926f03ca655
708,217
from typing import Dict def merge(source: Dict, destination: Dict) -> Dict: """ Deep merge two dictionaries Parameters ---------- source: Dict[Any, Any] Dictionary to merge from destination: Dict[Any, Any] Dictionary to merge to Returns ------- Dict[Any, Any] ...
4ffba933fe1ea939ecaa9f16452b74a4b3859f40
708,218
import ast def is_string_expr(expr: ast.AST) -> bool: """Check that the expression is a string literal.""" return ( isinstance(expr, ast.Expr) and isinstance(expr.value, ast.Constant) and isinstance(expr.value.value, str) )
f61418b5671c5e11c1e90fce8d90c583659d40e3
708,220
import subprocess def get_current_commit_id() -> str: """Get current commit id. Returns: str: current commit id. """ command = "git rev-parse HEAD" commit_id = ( subprocess.check_output(command.split()).strip().decode("utf-8") # noqa: S603 ) return commit_id
978bd35fc3cfe71fcc133a6e49fbbe0e27d4feda
708,221
import re def get_raw_code(file_path): """ Removes empty lines, leading and trailing whitespaces, single and multi line comments :param file_path: path to .java file :return: list with raw code """ raw_code = [] multi_line_comment = False with open(file_path, "r") as f: for ro...
6654a0423f024eaea3067c557984c3aa5e9494da
708,222
from typing import Pattern import re def _yaml_comment_regex() -> Pattern: """ From https://yaml-multiline.info/, it states that `#` cannot appear *after* a space or a newline, otherwise it will be a syntax error (for multiline strings that don't use a block scalar). This applies to single lines as we...
3b5739f460c3d2c66f802dd46e061d2d07030525
708,223
import re def format_ipc_dimension(number: float, decimal_places: int = 2) -> str: """ Format a dimension (e.g. lead span or height) according to IPC rules. """ formatted = '{:.2f}'.format(number) stripped = re.sub(r'^0\.', '', formatted) return stripped.replace('.', '')
60001f99b5f107faba19c664f90ee2e9fb61fe68
708,224
def num_in_row(board, row, num): """True if num is already in the row, False otherwise""" return num in board[row]
ca9ab9de4514740e25e0c55f3613d03b2844cdb8
708,225
def factorial_3(n, acc=1): """ Replace all recursive tail calls f(x=x1, y=y1, ...) with (x, y, ...) = (x1, y1, ...); continue """ while True: if n < 2: return 1 * acc (n, acc) = (n - 1, acc * n) continue break
e067cf4564056bf488e56fe58bbd5b998b0175f3
708,226
def mod(a1, a2): """ Function to give the remainder """ return a1 % a2
f5c03a952aed373e43933bafe37dbc75e796b74d
708,227
def encode_string(s): """ Simple utility function to make sure a string is proper to be used in a SQL query EXAMPLE: That's my boy! -> N'That''s my boy!' """ res = "N'"+s.replace("'","''")+"'" res = res.replace("\\''","''") res = res.replace("\''","''") return res
814822b9aa15def24f98b2b280ab899a3f7ea617
708,228
import subprocess def get_sha_from_ref(repo_url, reference): """ Returns the sha corresponding to the reference for a repo :param repo_url: location of the git repository :param reference: reference of the branch :returns: utf-8 encoded string of the SHA found by the git command """ # Using su...
d7ab3e98217fa57e0831a6df94d34f1cf45e3d97
708,230
def get_motif_proteins(meme_db_file): """ Hash motif_id's to protein names using the MEME DB file """ motif_protein = {} for line in open(meme_db_file): a = line.split() if len(a) > 0 and a[0] == 'MOTIF': if a[2][0] == '(': motif_protein[a[1]] = a[2][1:a[2].find(')')] else: mot...
88e42b84314593a965e7dd681ded612914e35629
708,231
import sys def in_ipython() -> bool: """try to detect whether we are in an ipython shell, e.g., a jupyter notebook""" ipy_module = sys.modules.get("IPython") if ipy_module: return bool(ipy_module.get_ipython()) else: return False
7a6804b964bd7fbde6d5795da953954343575413
708,232