content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def remove_whitespace(word): """Removes whitespace from word""" return word.strip()
6d70751cee467ad0455be7604521700803173c37
637,192
def key_for_path(p): """ Representation of the path, ID for a path :param p: a JSON path dictionary :return: a unique string for the path """ # key for a path is made of starting user id and ending business id in the path return '%s_%s' % (p[0]['props']['id'], p[-1]['props']['id'])
6755a46735d975656a17c091cd7f709c2f942d67
637,193
def cosine(s, prop): """ The Laplace transform of a goniometric function. """ P = s / (s ** 2 + 1) prop.s.append(s) prop.Ps.append(P) return P
f2021669861ed71f8f12a8db24c0c2a8faef7103
637,194
import os def localize_path(path, lang): """Return the path modified for this language. For example, "ui" becomes "ui-fr". """ head, tail = os.path.split(path) if tail == "ui": return os.path.join(head, tail + "-" + lang) else: sub_head, sub_tail = os.path.split(head) i...
b4ae834d1847360bdbce626297c2a073fd84833b
637,195
def short_to_full_git_sha(short, refs): """Converts a short git sha to a full sha :param short: A short git sha represented as a string :param refs: A list of refs in the git repository :return: The full git sha or None if one can't be found """ return [sha for sha in set(refs.values()) if sha....
490a8ddb719bf7e6e006abe48b5c773919480b71
637,197
def fix_ts(timestamp): """ Remove milliseconds from timestamps """ s, ms = divmod(int(timestamp), 1000) # import time # s = int(time.time()) # Uncomment for testing return s
8fc7e4e332cdb6cdc76d10569126607f96bcc093
637,198
import os def prep_output_folder(input_file, output_folder, overwrite_name): """Prepare the output folder. Creating required folder.""" output_folder = ( os.path.join(output_folder, overwrite_name) if overwrite_name else os.path.join(output_folder, input_file.split(".")[0].split("/")[-...
03a524881a567d15f4d922fce25c0fc93af42dfa
637,199
def get_f_H_gas_comp_in(P, Theta): """圧縮機吸引領域において過熱蒸気の圧力と温度から比エンタルピーを求める関数 (14) Args: P(float): 過熱蒸気の圧力 (MPa) Theta(dloat): 過熱蒸気の温度 (℃) Returns: float: 過熱蒸気の比エンタルピー (kJ/kg) """ K = Theta + 273.15 K2=K*K K3=K2*K P2=P*P P3=P2*P P4=P2*P2 return -1.00110355 *...
06c78b3029bd804362db15908cbafa05893bbe8b
637,200
import math def get_point_from_angle(point, angle, lenght): """ Return a point given a starting point, the angle that it has to form with respect to X-axis and how far from that point it has to be. :param point: Initial point :param angle: angle with respect to X-axis :param lenght: How far fr...
8dc330eed65c3ed5404ac7511a8396d1a453af83
637,201
from typing import Optional import ctypes def _gnu_get_libc_version() -> Optional[str]: """Gets the current GNU libc library version :return: GNU libc version :rtype: str """ try: prototype = ctypes.CFUNCTYPE(ctypes.c_char_p) ver = prototype( ('gnu_get_libc_vers...
4b7de3359be17c1077fa4149e57b10fab75041ec
637,202
def class_identifier(typ): """Return a string that identifies this type.""" return "{}.{}".format(typ.__module__, typ.__name__)
f2491824c32aeada8400595fec2cbc8c3658d587
637,203
def get_outcat_local(outcat): """ 返回局部区域的检测结果: 原始图为120*120 局部区域为30-->90, 30-->90 左开右闭 :param outcat: :return: """ # outcat = pd.read_csv(txt_name, sep='\t') cen1_min = 30 cen1_max = 90 cen2_min = 30 cen2_max = 90 aa = outcat.loc[outcat['Cen1'] > cen1_min] aa = aa.loc...
3ca463ca20b59f4ba6618c5eb430c14bab646917
637,204
import numpy def get_outliers(recordings): """Find outliers, given a list of data with already calculated features. Parameters ---------- recordings : list of dicts Each dict has the keys 'features' and 'HandwrittenData' Returns ------- List of dicts : Each dict has the k...
dec39d7c8b404980153e099c46bd5c42d06ed550
637,205
def save_df_as_csv(d, output_file, fields_order=None, csv_order_by=None, keep_index=False, encoding='utf-8-sig', blankna=False, excel=False, verbose=False, **kwargs): """Save a dataframe in a csv fields_order allows to precise what columns to put first (you don't need to specify all columns, only the ones you w...
2f5027f9d130297111016db3c2f5947ec616dc18
637,206
import os def _shared_variant_filtration(filter_type, snp_file, ref_file, vrn_files, variantcaller): """Share functionality for filtering variants. """ recal_file = "{base}.recal".format(base=os.path.splitext(snp_file)[0]) tranches_file = "{base}.tranches".format(base=os.path.splitext(snp_file)[0]) ...
8d35fb90a03f6fdf7fb9388b0a4129543f88833f
637,207
def read(df, filepath): """ Read a parquet file from AWS S3 alike service in pandas dataframe format. Parameters ---------- filepath : str Returns ------- Pandas.DataFrame """ return df.read_parquet(filepath)
4b1830e82ec1c9d77c3d05c5142a77e19dbba458
637,208
import os def _GetDirAbove(dirname): """Returns the directory "above" this file containing |dirname| (which must also be "above" this file).""" path = os.path.abspath(__file__) while True: path, tail = os.path.split(path) if not tail: return None if tail == dirname: return path
7931b4a77b40fae8a6e0921e9579895ae7d128d7
637,210
import inspect def get_instance_user_attributes(cls): """ Returns user attributes defined in a class or instance of a class :param cls: :return: list """ _def_attrs = dir(type('dummy', (object,), {})) _def_attrs.extend(['staticMetaObject']) attributes = inspect.getmembers(cls, lambda...
39806dbcd62a0a4984b997f778ed0508fb50738f
637,211
def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ result = [] for i in range(1, n + 1): if i % 3 == 0 and i % 5 != 0: result.append('Fizz') continue if i % 3 != 0 and i % 5 == 0: result.append('Buzz') continue ...
a299437477d6c96a89c158fdd7c7cdc59189d6af
637,213
def parseTimeExpr(timeExpr): """ Convert a time expression (ex. 1s 5m 1us 1ms) to a float seconds value """ if not timeExpr: return None if type(timeExpr) in (int, float): return timeExpr scale = 1 if timeExpr.endswith('us'): scale = 1 / 1000000 timeExpr = timeExpr[:-2] elif timeExpr.en...
303dab30ac1da4e0f7a1f61a9b2ef5ae22b5c645
637,215
def get_class_name(o, lower=False): """ Returns the class name of an object o. """ if not isinstance(o, type): o = o.__class__ if lower: return o.__name__.lower() else: return o.__name__
15ef10f6612e34e4c81bae707044daca15b5f81f
637,216
def _namespace_data(data: dict, namespace: str) -> dict: """Prefix configuration key with a namespace. Namespace is ConfigSource wide, and is resolved at source build time. It should be one of: - "target" - "app" - library name (where "mbed_lib.json" comes from) If given key is already na...
caf52e230465cb4f3d02b21187507d5fe7c123f2
637,217
def get_collection_from_id_recursive(collection, collection_id, current_id): """Return len of collection and the collection if it was a match""" if collection_id == current_id: return collection, 0 current_id += 1 for collection_nested in collection.collections: matched_collection, cur...
e133a58fd73a1ffb247437ac81a7ccae0a78ef63
637,218
def asc_test_config(tmpdir_factory): """Provides a mk8s test config Returns: str: the path to a json config file """ filename = tmpdir_factory.mktemp('data').join('mk8s_config.json').strpath config = \ """ { "pytest_zigzag_env_vars": { "BUILD_URL": null, "BUILD_NUMBER": n...
903cd52c977e2dcf81210d3a5bf2dcfd9cb8dd09
637,219
def left_rotate(a, d): """Python array slicing.""" if d == 0: return a first = a[:d] second = a[d:] return second + first
c131c0b205fb4ef16d57dccf61c2e1c216458f67
637,220
import os def get_next_screenshot_at_path(screenshot_path, prefix='screenshot', num_digits=4): """ :param screenshot_path: Root folder where the screenshots are being generated by the Launcher pr Editor. :param prefix: Generated screenshot files are named sequentially using the prefix. e...
5e0e00cbd4f635bfbfbc84c7c786a79e5bd13219
637,221
import time def format_time(ts): """Converts UNIX timestamp to local timestring with human-readable format""" return time.strftime("%d %B %Y, %I:%M %p", time.localtime(int(ts)))
4f6230c245e9b1c11a74378f7458b11326c00633
637,222
def extract_str(input_: str) -> str: """Extracts strings from the received input. Args: input_: Takes a string as argument. Returns: str: A string after removing special characters. """ return ''.join([i for i in input_ if not i.isdigit() and i not in [',', '.', '?', '-', '...
91788b9d6f656654e0d378dd9710f042e420ff33
637,224
def _sanitize(hex_str, comment_strings=None, ignore_strings=None): """ Sanitize string input before attempting to write to file. :param hex_str: the string input to sanitize :param comment_strings: a tuple of strings identifying comment characters :param ignore_strings: a tuple of strings to igno...
d89c1fea29480bd072de7c5b37967f4719f75557
637,225
def get_cf_specs_encoding(ds): """Get the ``cf_specs`` encoding value Parameters ---------- ds: xarray.DataArray, xarray.Dataset Return ------ str or None See also -------- get_cf_specs_from_encoding """ if ds is not None and not isinstance(ds, str): for source...
33b802ab91e9b6eefc9954f176597b58b8ca04a9
637,226
def streaming_step_properties(input, output, mapper, reducer=None, arguments=None): """ Create streaming step properties :param input: the input path of step :type input: string :param output: the output path of step :type output: string :param mapper: the mapper program of step :type...
d77532bbeeb9e80bc5657736e53af02bdeedc134
637,227
from typing import List import pathlib def find_all_coreref_files(directory: str) -> List[pathlib.Path]: """Searches for all the COREREF files in a directory and all its subdirectories. Parameters ---------- directory: str A string containing the path to directory where we want to search the ...
6fabc4adc435d96ce4123ae7ac8cd122d8d975d3
637,228
import inspect import re import six def parse_ctor_args(f, prefix=''): """Given an class or function, parse the class constructor/function details from its docstring For example, the docstring of sqlflow_models.DNNClassifier.__init__ is: '''DNNClassifier :param feature_columns: feature columns....
f5512ac471dc4fb926e940810b65bfd4bcb3ed56
637,229
def find_max_recursively(S, n): """Find the maximum element in a sequence S, of n elements.""" if n == 1: # reached the left most item return S[n-1] else: previous = find_max_recursively(S, n-1) current = S[n-1] if previous > current: return previous else...
26b430dbc31db2e7f34f94725f0c24188d1e2b58
637,230
def convert_to_color(rgb, color): """ convert from RGB to Color """ return color(rgb.red, rgb.green, rgb.blue)
f6d9182f4554752a20c44d0c0e7fab476a91692b
637,231
def is_child_node(node): """ Return `True` if the given node is a "child" node, `False` otherwise. """ if not node: return False return node.is_child is True and node.is_root is False
3e42dabc1b539f3990e7e53417066ae2b37d926d
637,232
def xor_string(string: str, xor_int_value=42): """Takes a given string and does an XOR operation on the converted ord() value of each character with the "xor_int_value", which by default is 42 Examples: >>> string2encode = 'Now is better than never.'\n >>> xor_string(string2encode)\n 'd...
4e3dd51cd49a6f3df9491dd86d76e6fcecf6fc38
637,233
import torch def sinc(input): """ Returns a new tensor whose elements correspond to the sinus cardinal of the elements of the input. Args: input (`torch.FloatTensor`): input tensor. Returns: (`torch.FloatTensor`): output tensor. """ output = torch.sin(input) / input outpu...
7239af0156f742a1ca99616391eefba395d59101
637,234
def x(z, a, b): """ convert from [-1, 1] (the integration range of Gauss-Legendre) to [a, b] (our general range) through a change of variables z -> x """ return 0.5*(b + a) + 0.5*(b - a)*z
0aedc721792fad8dc7fa2db4864a9013aec5876a
637,235
def voxel_to_world_coordinates(voxel_index, bbox, grid_shape): """Given a voxel, the bbox that encloses the scene and the shape of the grid, it computes the center of the voxel in world coordinates. Arguments: ---------- voxel_index: array(shape=(3, ), dtype=int32) The voxel indice...
5e97499068ed9fd898b0559a84406350a9f103d4
637,236
def is_match_filters(values: dict, filters: dict) -> bool: """ values is match filters or not :param values: :param filters: example: { "id": 1, "num": ["AND", ["GT", 1], ["LT", 1]] } all comparison operators: GT,GTE,LT,LTE,!EQ all logic operators: A...
09583a347e1cdea47277843bcaee7c14f187b30e
637,237
def validate_user_url(value): """Validate that a URL is a valid URL for a hydroshare user.""" err_message = '%s is not a valid url for hydroshare user' % value if value: url_parts = value.split('/') if len(url_parts) != 4: raise ValueError(err_message) if url_parts[1] != ...
5c7f3a1e91c3f5f0990bdda742cfd788961d63a1
637,238
def compute_veer(wind_a, height_a, wind_b, height_b): """ Compute veer between wind direction measurements Args: wind_a, wind_b(:obj:`array`): arrays containing the wind direction mean data; units of deg height_a, height_b(:obj:`array`): sensor heights (m) Returns: veer(:obj:`a...
f47d943bc267ac21174cb35e7560b72961dcdbbe
637,240
def get_linestyles(n, m=0): """ This function provides line styles for n x m lines being plotted :param n: :param m: :return: """ baselines = ['-', '--', '-.', ':'] * 10 basecolors = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00'] * 8 # https://colorbrewer2.or...
7dd0c8b5ccbc41a976fa9d28fdfdaf787144638a
637,241
import re def _ReplaceIndices(language, expression): """Replaces array access with underscored variable. For matrices: `variable[3,7]` becomes `variable_3_7` For vectors: `variable[3]` becomes `variable_3` The accessor for matrices is chosen according to the language (`[]` vs. `()`) """ #Ma...
6d8d546bcc4207ff18a1916bf56e0047cfcf6d36
637,242
def bdf_width(width: int) -> int: """Calculates the width in bits of each row in the BDF from the actual witdth of a character in pixels.""" # NOTE: Lines in BDF BITMAPs are always stored in multiples of 8 bits # (https://stackoverflow.com/a/37944252) return -((-width) // 8) * 8
c9d478d41ab94358524e384cf0c384994052626c
637,243
def EVI(red, nir, blue): """ Return the Enhanced Vegetation Index for a set of np.ndarrays EVI is calculated as: .. math:: 2.5 * \\frac{(NIR - RED)}{(NIR + C_1 * RED - C_2 * BLUE + L)} where: - :math:`RED` is the red band - :math:`NIR` is the near infrared band - :math...
96a4e64da0e6c97ee10d9ba0378c5605ccf1b1af
637,244
import re def is_valid_hash(value, algo): """Returns if the value is a valid hash for the corresponding algorithm.""" size = 2 * algo().digest_size return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value))
7879928b67504321da225346748801b9c6a56b30
637,245
def _rfr_fraction_ ( self , var1 , var2 ) : """Get correct estimate of fraction of two variables, taking into account correlations >>> r = ... >>> print r.fraction( 'S' , 'B' ) ## S/(S+B) """ if isinstance ( var1 , str ) : var1 = self.param ( var1 ) [1] if isinstance ( var2 , str ) : var2 ...
997982e2c3ee1cff742bc5654287d4e64988a773
637,246
def _is_valid_concurrency_to_instances(n, c, instance_count): """ Validates concurrency settings ok for number of instances :param n: :param c: :param instance_count: :return: """ if n < instance_count * 2: print("bees: error: the total number of requests must be at least %d (2x ...
edecb2cd9d60cbb262e5395a4ad43e571d92ae22
637,247
def zbar_bch15_5_encode(x): """ZBar's implementation of bch15_5_encode""" return ( (-(x & 1) & 0x0537) ^ (-(x >> 1 & 1) & 0x0A6E) ^ (-(x >> 2 & 1) & 0x11EB) ^ (-(x >> 3 & 1) & 0x23D6) ^ (-(x >> 4 & 1) & 0x429B) )
7dcb250dae1bca7921b13cd824a3571b222fc183
637,248
import math def flux_ratio(meas_x, meas_y): """ Calculate the flux ratio between two `heuslertools.mbe.flux_ratio.FluxMeasurement`s. The ratio is calculate with $$\\frac{J_X}{J_Y}=\\frac{BEP_X}{BEP_Y}\\cdot\\frac{\\eta_Y}{\\eta_X}\\cdot\\sqrt{\\frac{T_X M_Y}{T_Y M_X}}$$ """ return (meas_x.bep/...
b008dc81ac4e427cbdab0523376484da66be02f5
637,249
def getFileLocations(years, filings): """ Returns a list with the folder names where the data will be found """ fileLocations = list() for year in years: if filings == ['10-K']: fileLocations.append(year + 'q1/') # only valid if the user wants solely 10-K's as they are filed in Q1 ...
a3fb7b87c524e9c8a75a5931de8ba593e9b5720a
637,250
import os def get_path_fname() -> str: """ Return the file name that stores the repo locations. """ root = os.environ.get('XDG_CONFIG_HOME') or os.path.join( os.path.expanduser('~'), '.config') return os.path.join(root, 'gita', 'repo_path')
e45255acefa9c47c74c33950cb683feb5ff44660
637,251
def data_cleanup(sub_df): """ input: df[['time','lat', 'lng']]""" dff = sub_df.resample('1S', on='time').mean() dff = dff.interpolate(method='linear') return dff
952e5d3e0e3d5718106aed9d110fa35565e37656
637,252
import traceback import os def get_caller(): """Return the line and module of the caller function.""" tb = traceback.extract_stack()[-3] module = os.path.splitext(os.path.basename(tb[0]))[0].ljust(18) line = str(tb[1]).ljust(4) return "L:%s %s" % (line, module)
2ac8eaf070c131851dabd61a3a182b3ded487714
637,253
def stripquotes(s): """ Enforce to be a string and strip matching quotes """ return str(s).lstrip('"').rstrip('"')
be8d1a844065bf5615e0f0a48596d8771b20fd86
637,256
def get_st_index_of(pattern, line): """ A function used to get the first column of each benchmarked tool. """ size = len(line) for i in range(0, size): if pattern in line[i]: return i + 1 raise ValueError('\'' + pattern + '\' is not found in log files')
22c705856554dcb80d5fa515a39824003a7135e3
637,257
import sys def green(txt): """Return colorized (if the terminal supports it) or plain text.""" if sys.stdout.isatty(): return '\033[0;32m%s\033[0;0m' % txt return txt
4f39909646b3f89f67983883856d4a31ab1c5c52
637,258
import sys def get_options(parser): """ Define command line options.""" parser.add_option("-u", "--user", dest="username", default=None, help="User name.") parser.add_option("-o", "--outfile", dest="outfile", default=".scrobbler.log", help=...
31c99d83c78bedb0357c791a4283dcfbf98bfd48
637,259
def tuple_to_bool(value): """ Converts a value triplet to boolean2 values From a triplet: concentration, decay, threshold Truth value = conc > threshold/decay """ return value[0] > value[2] / value[1]
cf77add11c993078c8453b139ba05a758b2aff97
637,261
def normalize_module(module): """ Normalize a module name """ return module.lower()
8c27328afcf79c7564365d7e8c64c5b5ded21555
637,263
def _parse_prodigal_id_from_biopython(idval): """strips off prodigal gene annotations and returns the ID as it was in the contig file Args: idval (str): the ID value returned by Prodigal Returns: The ID value as fed to Prodigal """ return '_'.join(str(idval).split('_')[:-1])
29d3bbf2d3d8c0f6d7667f4e95aad8d9bf319211
637,264
import os def cycleDirectoriesOnly(aList, options): """cycleDirectoriesOnly() takes a list of items from a directory and purges anything from the list that is not a cycle directory. """ out = [] for i in aList: if (os.path.isdir(i) and os.path.exists(os.path.join(i, 'xml')) and ...
4a13311fe129399daa28ff7d6c4b50293940425d
637,265
import os def convert_bedgraph_to_bigwig(bg_file_path, chrom_sizes_path, conversion_tool_path="bedGraphToBigWig"): """ Method converts a bedGraph file into a bigWig file. :param bg_file_path: String containing path to bedGraph file :param chrom_sizes_path: String contai...
1877c733fa9395b79e7d16c0d6189fb4706df97d
637,266
def split_on_uppercase(s): """Split characters by uppercase letters. From: https://stackoverflow.com/a/40382663 """ string_length = len(s) is_lower_around = ( lambda: s[i - 1].islower() or string_length > (i + 1) and s[i + 1].islower() ) start = 0 parts = [] for i in range...
d61c533517f49689c42d922414aeb72d41951894
637,267
def impulseFactor(data): """ Impulse Factor: Parameters ---------- data: array-like 2D matrix of shape (time, data) Returns ------- impulseFactorData: 1D numpy array containing impulse factor value for a given signal Reference --------- Yiakopoulos, C. T., Gryllias, K. C., & Antoniadi...
5b63e3375a46806b7b3833261307153295c74fa1
637,268
def has_role_parent(task_block): """ Check if one of the parent of the task or block is a role :param task_block: :type task_block: :return: :rtype: """ parent = task_block._parent while parent: if parent._role: return True parent = parent._parent ret...
7c34bebd902e1ffd913014256ccd5ef6eda0a3a3
637,269
def sortBoxes(boxes): """Calculate coordinates for each box and sort in reading order""" for ent in boxes: ent['xmin'] = float(ent['x']) ent['ymin'] = float(ent['y']) ent['width'] = float(ent['width']) ent['height'] = float(ent['height']) ent['xmax'] = ent['xmin'] + ent['...
6a5f7e4f6cc9def8dcb759809e7f4802979a5cc6
637,270
import os import sys def detect_os(): """Detect os family: windows, macos or unix.""" if os.name in ('nt', 'dos', 'os2', 'ce'): return 'windows' if sys.platform == 'darwin': return 'macos' return 'unix'
a6c1215ac6f34ce079b839e7d9fa5f84deb4f3a6
637,271
def SetKineticCycleTime(time): """ This function will set the kinetic cycle time to the nearest valid value not less than the given value. The actual time used is obtained by GetAcquisitionTimings. Please refer to SECTION 5 – ACQUISITION MODES for further information. """ return None
c468025466dbb18bc13fd086343caeecd0489cda
637,272
def split_list_into_chunks(list_to_split, max_entries_per_list): """ Takes a list and splits it up into smaller lists """ chunks = [] for i in range(0, len(list_to_split), max_entries_per_list): chunk = list_to_split[i:i + max_entries_per_list] chunks.append(chunk) return chunk...
826e3745bb703ab567d5ad707c095cfea299113d
637,273
def set_new_rb_kpi_dictionary(region_names): """ Generates an empty dictionary which collects the parameters KPI-5, KPI-6, KPI-7, KPI-8 and KPI-9 for each region. It defined as 'Region Based KPI Dictionary'. """ rb_kpi_dict = dict() for region_name in region_names: rb_distance_trav...
cd1eaa51fc433659ebc1dbf184b20ce38e361d9a
637,274
def set_show_hit_test_borders(show: bool) -> dict: """Requests that backend shows hit-test borders on layers Parameters ---------- show: bool True for showing hit-test borders """ return {"method": "Overlay.setShowHitTestBorders", "params": {"show": show}}
32f27ca5e140a07bf76188780b2655d01f4b2f46
637,276
import os def expand_dir_path(path): """Return fully qualified pathname for the given directory path. """ savecwd = os.getcwd() os.chdir(path) cwd = os.getcwd() os.chdir(savecwd) return cwd
c1fe49e3ff4709500545355f3adeab72d84c4753
637,277
def groupify(data): """ Takes a dict with groups identified by ./ and turns it into a nested dict """ new = {} for key in data.keys(): if "./" in key: group, field = key.split("./") if group not in new: new[group] = {} new[group][field] = d...
59295a90203d8eb7a9af901ab3f62df3132fea27
637,278
def _BinaryElementwiseShape(op): """Returns same shape as both inputs to op. Args: op: Input operation. Returns: Shape of both inputs to `op`. """ return [op.inputs[0].get_shape().merge_with(op.inputs[1].get_shape())]
bf51d2d686772d34ca2dafa4cce7e4a4bdb4a278
637,279
def get_value(data, value): """Retrieve weather value.""" try: if value == "@mps": return round(float(data[value]) * 3.6, 1) return round(float(data[value]), 1) except (ValueError, IndexError, KeyError): return None
dddc1466b8be7c21a79f6bf15c23e6639a29dff5
637,280
def configuration_builder(build_configuration_builder): """ Basic Configuration Builder """ return build_configuration_builder()
bf0c3b27b8b9a41e53d0cb54113c06cd167b5a9e
637,281
def _intersect(rect1, rect2): """ Return True if the two rectangles rect1 and rect2 intersect. """ x1, y1, w1, h1 = rect1 x2, y2, w2, h2 = rect2 return (x1 + w1 > x2 and x2 + w2 > x1) and (y1 + h1 > y2 and y2 + h2 > y1)
ff06ae4d279716acae31823a7fa0021876f3db44
637,282
def part1(data): """ Check Valid Passwords """ return data
66ec08a13edff58c63e9e6f37134d3666ca6d2d3
637,283
def load_fb15k_triples(path): """ Loads the raw data from file provided. Args: path: path to the file Returns: triples """ with open(path, 'r') as f: triples = [line.strip('\n').split('\t') for line in f.readlines()] return triples
79a82130c1a61765f259efb3613a5dff3b338fd4
637,284
import argparse def _kv_pair(pair): """Convert a KEY=VALUE string to a 2-tuple of (KEY, VALUE). This is intended for usage with the type= argument to argparse. """ key, sep, value = pair.partition("=") if not sep: raise argparse.ArgumentTypeError( "Expected a KEY=VALUE pair, g...
45b27234b43987b855d506c6fb93d88dfd453ea0
637,285
def apply_update_rules(state, predecessor_node_lists, truth_tables): """ Update network state according to the update rule. :param state: current network state :param predecessor_node_lists: list of predecessor node lists :param truth_tables: list of dicts (key: tuple of predecessor node st...
2951f1f8df9c238af4e43965882384ed66d5584d
637,287
def parse_contour_file(filename): """Parse the given contour filename :param filename: filepath to the contourfile to parse :return: list of tuples holding x, y coordinates of the contour """ coords_lst = [] with open(filename, 'r') as infile: for line in infile: coords = ...
c8fc09dc91fa2b659be2ea0f63ee653670a4b513
637,288
def shade_rgb(rgb): """ Adjust shade of rgb by 25% (value 64 out of 256). See: https://stackoverflow.com/a/67963422/6929343 :param rgb: tuple of red, green, blue integers 0 to 255 :returns: tuple of red, green, blue integers 0 to 255 """ return tuple(i + 64 if i < 128 else i -...
effa618a8d62601f7cf4ec89b3960f4296ad64bd
637,289
def subset_by_iqr(df, column, iqr_mult=3): """Remove outliers from a dataframe by column, including optional whiskers, removing rows for which the column value are less than Q1-1.5IQR or greater than Q3+1.5IQR. Args: df (`:obj:pd.DataFrame`): A pandas dataframe to subset column (st...
ee34ca064c605fe1c1ff36131c8351dfe95321ef
637,290
import math def get_bounding_box(lat: float, lng: float, radius: float) -> str: """Get bounding box with length of radius * 2 and (lat, lng) as the centre""" offset = radius / 100.0 latMax = lat + offset latMin = lat - offset lngOffset = offset * math.cos(lat * math.pi / 180.0) lngMax = lng +...
85bbc550e75465633bdc441182da4b55c9a15291
637,291
from pathlib import Path def create_output_dir(dir_path: str) -> str: """Creates output directory if it doesn't exits Parameters ----------- dir_path: the output file directory Return ------- dir_path: the output file directory returned for later used """ if not Path(dir_path)...
750f50684b8f8b9fc08fd43a4c4068e9d6169ba2
637,292
def show_sticker_file_id(bot, update, session, chat, user): """Give the file id for a sticker.""" if update.message.reply_to_message is None: return "You need to reply to a sticker to use this command." message = update.message.reply_to_message if message.sticker is None: return "You ne...
4ce00f9b877259023337eeab3d4922b5cba86505
637,293
def menu(): """ Prompt the user with a set of possible actions and return the choice. :return: choice: the user's selected action """ print("What would you like to do?\n") print(" a) Make a deposit") print(" b) Make a withdrawal") print(" c) View balance") print(" d) Transfe...
2aba8e3dd5bcf807d44c305a1e79332e31a88240
637,294
def factorial(number: int) -> int: """ Calculate the factorial of specified number (n!). >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral val...
af7d0707742bdf9ff39119f7d3b8823b5f3c0bb4
637,295
import argparse def parse_args(): """set data directory path and, isobaric_pressure from [1000,925,850,700,600,500,400,300,250,200,150,100].""" parser = argparse.ArgumentParser() parser.add_argument("-d", "--dir", help="set directory name.\ This is the initial time.", type=str) ...
3b83a1ec41269ea302b2a2e943ba81d970019813
637,296
import csv def csv_to_list(csv_file): """ Function to read a csv file and convert the entries on each row to a list. """ csv_list = set() # Open CSV file for reading as provided to the function with open(csv_file, 'r', newline='') as input_file: input_reader = csv.reader(input_file) ...
a976bfc5da6f06dc43c0ce45ebfd7767f910c213
637,298
def create_function_from_source(function_source, imports=None): """Return a function object from a function source Parameters ---------- function_source : unicode string unicode string defining a function imports : list of strings list of import statements in string form that allow ...
2fa6c5ed6778270a4a2b1c2e02c0203a3d463e10
637,299
def simplify_http_accept_header(accept): """Parse an HTTP Accept header (RFC 2616) into a preferred value. The quality factors in the header determine the preference. Possible media-range parameters are allowed, but will be ignored. This function can also be used for the Accept-Charset, Accept-Enco...
9370a7dc9af20840a9e4f9a9826b65f8bae4f8db
637,300
from typing import List from typing import Tuple def fit_transform(*args: str) -> List[Tuple[str, List[int]]]: """ fit_transform(iterable) fit_transform(arg1, arg2, *args) """ if len(args) == 0: raise TypeError('expected at least 1 arguments, got 0') categories = args if isinstance(ar...
e7302c7a02cb7e99b16b8ed17cc917e0c8b4724d
637,301
import json def make_a_play (player_in): """ Make a play in the current game """ response = player_in.play_game_round (7 - len (player_in.game)) if (response.status_code == 201): player_in.game = json.loads (response.text)['game_state'] return True else: return Fals...
15dd3e9beb78fb25f9f387b60d50f5e03117bc17
637,302
def merge_fn1(seq, i, ht, key, count): """Merges new extra data to existing extra data in a node.""" if ht is None: return {key: count} if key in ht: ht[key] += count else: ht[key] = count return ht
858a7f316cf8c2500da66e3028cb6c5fc0a37fbb
637,304
def dfs_path_maker(node): """ Return a PuzzleNode that creates a path from the original puzzle to the solved puzzle. @type node: PuzzleNode @rtype: PuzzleNode """ while node.parent is not None: child = node node = node.parent node.children.append(child) return no...
7fca51b37ce96a99052322eb1ff6b2166741737b
637,305