content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def crc16x25(data: bytes, poly=0x8408): """ CRC-16-CCITT Algorithm """ data = bytearray(data) crc = 0xFFFF for b in data: cur_byte = 0xFF & b for _ in range(0, 8): if (crc & 0x0001) ^ (cur_byte & 0x0001): crc = (crc >> 1) ^ poly else: ...
da57bcc4e424ee5e05cde085c0950d6235737e77
631,254
def apply_mask(mixture, mask): """Apply mask""" return mixture * mask
3c436a4d59e5dff428addc4f8d86f995373cb251
631,255
import os def snr_exist(station,year,doy,snrEnd): """ given station name, year, doy, snr type returns whether snr file exists on your machine bizarrely snrEnd is a character string year and doy are integers, which makes sense! author: Kristine Larson """ xdir = os.environ['REFL_CODE']...
a20d8a6f90c62eacfeb1f1c682538e8b48697904
631,257
def mergedicts(dict1: dict, dict2: dict) -> dict: """Deep dicts merge.""" result = dict(dict1) result.update(dict2) for key, value in result.items(): if isinstance(value, dict) and isinstance(dict1.get(key), dict): result[key] = mergedicts(dict1[key], value) return result
d3dccecbf5a6e63da2f96c38a86548e3b1ee87eb
631,258
def get_table_c_3(): """表C.3 ガス給湯機効率の回帰係数a_std_u, b_std_u, c_std_u Args: Returns: list: ガス給湯機効率の回帰係数a_std_u, b_std_u, c_std_u """ table_c_3 = [ (0.0019, 0.0006, 0.0019, 0.0000, 0.0000, 0.0000, 0.0033), (0.0013, 0.0005, 0.0013, 0.0002, -0.0005, 0.0002, 0.0194), (0.653...
e5abfc42c7ee7f68f3e6e7685b0f9d8dc417d126
631,259
import re def check_gapped(sequence): """ Check for N in sequence. Return n(with N) or w(whole). """ w_regexp = re.compile('n|N') regexp_obj = w_regexp.search(sequence) if (regexp_obj): return True else: return False
127edd77645eacf7176b8dd23ee2358a0074c008
631,260
def vis_params_rgb(bands=['R', 'G', 'B'], minVal=0, maxVal=3000, gamma=1.4, opacity=None): """ Returns visual parameters for a RGB visualization :param bands: list of RGB bandnames, defaults to ['R', 'G', 'B'] :param minVal: value to map to RGB value 0, defaults to 0 :param maxVal: value to map to R...
7f86e7c22c7dced82a0b11a5033e9d18e2d47e93
631,261
import os def _get_config_dir(): """ Get the configuration root directory. See these URLs for reference: * http://blogs.msdn.com/b/patricka/archive/2010/03/18/ where-should-i-store-my-data-and-configuration-files-if-i-target-multiple-os-versions.aspx * https://specifications.freedesktop.org...
f316158480cf4fd0adff69218919130f2fd088a9
631,262
def nonzero(matrix, row): """ usage: >>> from scipy.sparse import csr_matrix >>> m = csr_matrix([[1, 0, 2], [3, 0, 0]]) >>> print nonzero(m, 0) set([0, 2]) >>> print nonzero(m, 1) set([0]) """ return set(matrix[row].indices)
197308cf9ed83124565444a5ac97dae14d805cb8
631,263
import gzip import pickle def load(filename): """ SOURCE: https://github.com/ucl-exoplanets/ExoGAN_public/blob/master/util.py Loads a compressed object from disk """ file = gzip.GzipFile(filename, 'rb') data = file.read() dict_ = pickle.loads(data, encoding='latin1') # Python 2 and 3 incom...
31a1597f0367f72df5ca651cb7f4fa0c7c56f22d
631,264
import math def qubits_needed(number_of_sides): """ The number of qubits needed for a die of n faces. """ return int(math.ceil(math.log(number_of_sides, 2)))
09f4c9dbc8a732097209943f0d19f22a006cd181
631,265
def isqrt(n: int) -> int: """ >>> isqrt(2) 2 """ p = 1 while p**2 <= n < (p+1)**2: p += 1 return p
6b453e36a1c4e18b6c279224588eaa4f5e5ec032
631,266
def get_sp_pred(pred_sp_idx, data): """get the prediction of supporting facts in original format Arguments: pred_sp_idx {[type]} -- [description] data {[type]} -- [description] """ pred = [] for p in pred_sp_idx: if p < len(data): pred.append([data[p].doc_tit...
2f28853eb37cc9d05d61c3e8ff645e586f802214
631,267
def asURN(epsg): """ convert EPSG code to OGC URN CRS ``urn:ogc:def:crs:epsg::<code>`` notation """ return "urn:ogc:def:crs:epsg::%d" % int(epsg)
a7de7b3526e8feb163479f1cf3dcb57ed3f9a03e
631,268
import os import csv def dataPreparation(file): """ Prepares the Data given a file for Machine Translation Task """ tsvFileName = os.path.join("irdataset/", os.path.basename(file).split(".")[0]+"Seq2seq.tsv") print (tsvFileName) tsvFile = open(tsvFileName, 'w', newline='\n') writer =...
50eb3f3170f1cec7a9c922b411a72f15bf99c908
631,269
import os import json def plugins_config(): """If the COOK_PLUGIN_JSON environment variable is set, returns its value, otherwise empty dict""" return json.loads(os.environ['COOK_PLUGIN_JSON']) if 'COOK_PLUGIN_JSON' in os.environ else {}
d937a5fccf6ce9cdb5d037e0d48d3839d67491a6
631,270
import string import random def random_string( length: int, characters: str = string.ascii_letters + string.digits ) -> str: """ Generates a random string of a given length from a given character set. Args: length: The length of the string to generate. characters: A string containing ...
5ebcb226dc4e03d09544fd0d6d09eee755db7cea
631,271
import os import re def file_list(directory, pattern): """return a sorted array of files in the given directory matching a specified regex. files in the returned array are specified relative to the location of the specified directory. """ files = os.listdir(directory) matched_files = sor...
80d0ee3c7eadac11e6d31aca80c0ccf4aa6798f9
631,272
import os def is_app_ready() -> bool: """ in some situations I had to start executing/doing some work as soon as the server starts. But due to django's special way of starting the server and if my work requires the use of models or anything related to the django's startup procedure i received app not ...
b4ad20ad773783931313b6ad84110eec0f64dbeb
631,273
import itertools def generate_layers_parameter(parameter_values): """Generate parameters list for layers parameter type.""" combinations = [] number_layers = parameter_values['number_layers'] number_units = parameter_values['number_units'] for i in number_layers: for combination in itertoo...
306f025d808d55ea7b5b59fa4c5ec9abd20e8c8e
631,274
def hIndex(df, query_txt, coluna_citacoes:str): """ Calcula hm """ df = df.query(query_txt).sort_values(by=[coluna_citacoes],ascending=False) df = df.reset_index(drop=True) df.index+= 1 df['ordem'] = [n for n in range(1, len(df)+1)] df['corte'] = abs(df[coluna_citacoes] - df['ordem']) r...
867ee8edc4b11757f510ab5f2c5bb3767f3a16f0
631,275
def do_nothing(caller, raw_string, **kwargs): """ Re-runs the current node """ return None
655764148b201f8a64b55cbd2040e830b24471b2
631,276
def sqlalchemy_session(wrapped_function): """ Decorator for creating, closeing and rolling back an sqlalchemy session. """ def decorator_function(self, *args, **kwargs): db_session = self.make_session() try: return wrapped_function(self, *args, db_session=db_session, **kwarg...
582cc263e93ecf8b4cedb3106a33c0efb472c0ab
631,277
def redshift(): """A default redshift to evaluate at. Not too high, not too low.""" return 15
de2276ae5465d3dbc621e9ca70c830fbdc3fd8e0
631,278
import re def _truncate_dates(date, file_date): """Truncate dates of different lengths and convert to integers. This allows to compare the dates chronologically. For example, this allows comparisons between the formats 'YYYY' and 'YYYYMM', and 'YYYYMM' and 'YYYYMMDD'. Warning ------- Thi...
11ad3ad7793aec5bbce4aa18c880ca9bf4759723
631,279
from pathlib import Path def get_config_dir() -> Path: """Returns the path to the config dir""" return Path(__file__).resolve().parent.parent / 'config'
4f1ea474da52c6c5d10c87bc5dedfbaf0a4441c4
631,280
def update_ecco_dataset_temporal_coverage_metadata(ecco_dataset): """ Adds high-level temporal coverage metadata to dataset object if the dataset object has 'time_bnds' coordinates Input ---------- ecco_dataset : an xarray dataset Output: ---------- ecco_dataset : d...
346c28742f85a5548c3d60dca73296f7589b9722
631,281
def merge(user, default): """Merges a user configuration with the default one. Merges two dictionaries, replacing default values of similar matching keys from user. Parameters: user (dict): A user defined dictionary default (dict): Returns: A new merged diction...
d55eb703b441c04b11c497e496197560acb094aa
631,282
def main(event: dict, context: dict) -> dict: """ Simple lambda handler to echo back responses :param event: A JSON-formatted document that contains data for a Lambda function to process. :param context: Provides methods and properties that provide information about the invocation, function, and ru...
9600e58e9212c6c3294b81629923fdc361d84d30
631,283
def setup_extra_parser(parser): """for dictknife.cliutils.extraarguments""" return parser
4ceac31f5a840a25a59840658b51c8814c6b4e18
631,284
def tuple_scale(tup: tuple, factor) -> tuple: """Return the tuple with each entry scaled by a factor and rounded.""" return tuple(round(i * factor, 5) for i in tup)
08b9267eafa2f18a849297d5d0b436de08ca80c1
631,285
def first_word(sentence): """Return first word of a string.""" try: return sentence.split(' ', 1)[0] except: return None
c7938a06b7f6ae4169b622863ed8285e173f34a0
631,286
def remove_if(rng, pred): """ Remove each element from `rng` for which `pred` evaluates to true by swapping them to the end of the sequence. The function returns the number of elements retained. """ j = 0 for i, x in enumerate(rng): if pred(x): continue if i != j...
9a449133f3eff0ef047b03b499b4a5b7b532a871
631,287
def c_linker_options(ctx, blacklist=[]): """Extracts flags to pass to $(CC) on link from the current context Args: ctx: the current context blacklist: Any flags starts with any of these prefixes are filtered out from the return value. Returns: A list of command line flags """ cpp = ctx.fra...
6a5aa9f820098523ad4243da174c3d96477eaa00
631,288
import socket import time def createChainId(): """ @return: chainId as a string suitable for spawning livetv Based on livetvchain.cpp:InitializeNewChain(...) Match format: live-zeus-2008-12-04T11:41:52 """ return "live-%s-%s" % (socket.gethostname(), time.strftime("%Y-%m-%dT%H:%M:%S", time.lo...
eab3f64588be878e5b631c8777add3cad5c4f969
631,289
def turnOff(array, a2d): """ function to turn off lights with given coordinates from array """ x1 = int(array[0]) y1 = int(array[1]) x2 = int(array[2]) y2 = int(array[3]) xmin = min(x1, x2) xmax = max(x1, x2) ymin = min(y1, y2) ymax = max(y1, y2) for i in range(xmin, xmax...
a139e896332d6928942e52026cb990cfeeb2fcbc
631,290
def stack_projection_args(cli_args): """ Converts the flat processing options into nested JSON Args: cli_args (dict): arguments parsed from the CLI Returns: dict: nested dictionary grouped by types/usage Example: >>> stack_projection_args({'target_projection': 'utm', 'zone': 1...
67101b35ac2d4210e7af15b4d8356b0095fcb60e
631,291
def validate_reviews(df): """ Enrich no review records with default review scores. """ df['first_review'].fillna(value='1991-01-01', inplace=True) df['last_review'].fillna(value='0', inplace=True) df['review_scores_rating'].fillna(value=0, inplace=True) df['review_scores_accuracy'].fillna(value...
752718cc50073c6fb66161e90003e06b74a21353
631,293
def sort_key_for_filenames(filename): """dummy sort key""" return filename
8771f7881333c0f21b91e6003b85c45ce5c6ee52
631,294
import argparse def read_args(): """Gestion des arguments""" parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", required=True, help="input image data folder") parser.add_argument("-o", "--output", required=True, help="output data folder") parser.add_argument( "-c", "-...
8f9f9c75b56007efd38ed9a59d1ba12f90ed4464
631,296
def success(): """ Entrypoint """ return "success"
f1dc1819f3bddc87641210b4634d2d62f537c39c
631,297
from datetime import datetime def _create_stack_id(name: str) -> str: """ Creates a stack name that should be unique within the region. Args: name (str): Name of the project for which to create the stack ID. Returns: (str): The generated stack name. """ dt_string = datetime.n...
c3de9b923df0ae3132f90a908c7cbe8ed92ee777
631,299
import os def set_wcs_output_directory(file_name, output_directory=""): """Returns the WCS output directory corresponding to the analyzed image. The name of the directory is the anme of the image with the suffix _wcs. Parameters ---------- file_name: str File name of the image. output...
6f998040028b0ea400e967e4d1a0c6eeb0cd8171
631,300
def parse_version(vers_string): """Parse a version string into its component parts. Returns a list of ints representing the version, or None on parse error.""" vers_string = vers_string.strip() vers_parts = vers_string.split('.') if len(vers_parts) != 4: return None try: major =...
46d96c48e03ab9e68362cfb850ba49ecf54ba49d
631,301
def single_label_accuracies(gold, silver, test_tokens, known_tokens, print_scores=True): """ Calculate accuracies for all, known and unknown tokens. Uses index of items seen during training. """ kno_corr, unk_corr = 0.0, 0.0 nb_kno, nb_unk = 0.0, 0.0 for gold_pre...
c22d9f99dbabcdd8f591b59d5ba5ebacce14767f
631,302
def matrix_block(M, rows, cols): """ Select a block of a matrix given by the row and column indices """ return M[rows,:][:,cols]
e797dc92cfa77eda7e1228e7bba01116ab87e901
631,304
import random def bootstrap_sample(data): """randomly sample len(data) elements with replacement""" return [random.choice(data) for _ in data]
787033910ee48618b36e7ad39cae13a58f4a3f0b
631,305
def nested_get(dictionary, keys): """Get nested fields in a dictionary""" to_return = dictionary.get(keys[0], None) for key in keys[1:]: if to_return: to_return = to_return.get(key, None) else: break return to_return
a01f04aae670f118c97808ab27933799b0613c56
631,306
def format_long_time(timespan): """ Formats a long timespan in a human-readable form with a precision of a 100th of a second. """ formatted_time = [] units = (('d', 24 * 60 * 60), ('h', 60 * 60), ('m', 60), ('s', 1)) for unit, length in units: value = int(timespan / length) ...
ddfd2d0351b48d3c2e221b54688bff96905f65eb
631,307
def overrides(interface_class): """ To be used as a decorator, it allows the explicit declaration you are overriding the method of class from the one it has inherited. It checks that the name you have used matches that in the parent class and returns an assertion error if not """ def over...
e5264baf1c5a5d97b354a4db3b3a49ccb580c082
631,308
def cmaps_forward_check(csp, var, value, assignment, removals): """check any unprinted e's cmap sum = 0""" unassigned_vals = list(set(range(len(csp.variables))).difference(assignment.values())) for val in unassigned_vals: if sum(csp.cmaps[val]) == 0: return False return True
762db4f50a89835d40fbace826c095223ef1fe9a
631,309
def convertParamters(params, proc, globParams): """ convert json of parameters to gaudi """ lines = [] lines.append("%s.OutputLevel = %s " % (proc.replace(".", "_"), params.get("Verbosity", globParams.get("Verbosity")))) lines.append("%s.ProcessorType = \"%s\" " % (proc.replace(".", "_"), params.get("type"))) ...
2fe9fa9fdb27d11ccf0ab6f0f8d695aa7f0a18f8
631,310
import sys def base_protolint_command() -> str: """ Return the base protolint command. :return: The base protolint command """ if sys.platform.startswith("win"): protolint_base_cmd = "protolint" # pragma: nocover else: protolint_base_cmd = "PATH=${PATH}:${GOPATH}/bin/:~/go/bi...
ccbf4219416c85cad2a995f31fc94248e82568af
631,311
def _build_param_docstring(param): """Builds param docstring from the param dict :param param: data to create docstring from :type param: dict :returns: string giving meta info Example: :: status (string) : Statuses to be considered for filter from_date (string) : Start date filter...
14b51d6966d0a5a5b8a185830f3d62585ae2d1d1
631,312
import torch from typing import Optional def _mul_add(a: torch.Tensor, b: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tensor: """Element-wise multiplication of two complex Tensors described through their real and imaginary parts. The result is added to the `out` tensor""" # check `out`...
e5fa90959758407b02cabb96a846ae2587899e89
631,313
def tokenize(text, space_only=False): """ :rtype text: List[str] """ if space_only is False: text = text.replace("-", " ").replace("_", " ") tokens = [token for token in text.split(" ") if token.strip()] return tokens
1c49e95dade2ffad027fa4c2949e6ffde9a73847
631,314
import uuid def create_api_release(client, resource_group_name, service_name, api_id, api_revision, release_id=None, if_match=None, notes=None): """Creates a new Release for the API.""" if release_id is None: release_id = uuid.uuid4().hex api_revision_to_release_and_make_current = "/apis/" + api_...
eaf1f76bf2fea685847ff732d5603f78ff307b2a
631,315
def predict(model, X, threshold = 0.3): """ desc: given an x dataframe, make a prediction using our model args: model (Sklearn.pipeline Pipeline) : Trained model we are going to evaluate X (pd.DataFrame): X values passed to model. returns: y (int) : 1 or 0, 1 for ...
1e2f21f9b602f5f82294e5af283b84a40e64afed
631,316
def mean(val_a, val_b): """ A function returning the mean of both values. This function is redeveloped so as to be called as choice_func in the function "values_as_slop()" (see below) in external projects. Parameters ---------- val_a : float First value. val_b : float Second...
6d5b1c776ae85b7b171c15305d142deeb21b1af4
631,317
def unlist(list_in): """ transform possible chain list into one-dim list :param list_in: :return: """ list_out = list() for ele in list_in: if type(ele) is list: list_out.extend(ele) else: if ele != '': list_out.append(ele) ...
32ffb41ff553f083fdfc417743ade9bf289da994
631,319
def get_dev_local_pipeline(): """Simple example pipeline""" b1 = [('$entry:e_01', 'pbsmrtpipe.tasks.dev_hello_world:0')] b2 = [('pbsmrtpipe.tasks.dev_hello_world:0', 'pbsmrtpipe.tasks.dev_hello_worlder:0'), ('pbsmrtpipe.tasks.dev_hello_world:0', 'pbsmrtpipe.tasks.dev_hello_garfield:0')] b3 =...
8933ddfbe1b9123c4fa6092e38283ebbbe559cf3
631,320
import numpy def euler_angles(r): """ Calculate the euler angles from a three dimensional rotation matrix. @param r: 3x3 Rotation matrix """ a = numpy.arctan2(r[2, 1], r[2, 0]) % (2 * numpy.pi) b = numpy.arctan2((r[2, 0] + r[2, 1]) / (numpy.cos(a) + numpy.sin(a)), r[2, 2]) % (2 * numpy.pi) ...
c22d7981bbe37b77e6b8080d93d781877b8e5b8e
631,322
def evaluate(labels, predictions): """ Given a list of actual labels and a list of predicted labels, return a tuple (sensitivity, specificity). Assume each label is either a 1 (positive) or 0 (negative). `sensitivity` should be a floating-point value from 0 to 1 representing the "true positive...
9f754488dc0c10da43b985a8c33d8ef681d3b873
631,323
def fact(n): """ Return 1, if n is 1 or below, otherwise, return n * fact(n-1). """ return 1 if n <= 1 else n * fact(n - 1)
d4365b2c3d4aaaf9039011eabb9b04f508048be6
631,324
import math def summe_teiler(integer): """gibt die Summe aller Teiler einer Zahl (ohne Zahl selber) aus benötigt: math""" i = 2 teiler = 1 while i <= math.sqrt(integer): if integer%i == 0: teiler = teiler + i+ integer/i i = i + 1 return teiler
3b49d88e9058f9315838b416f42b0226c0e90760
631,325
import tempfile def create_dir(basedir=''): """ Create a unique, temporary directory in /tmp where processing will occur Parameters ---------- basedir : str The PATH to create the temporary directory in. """ return tempfile.mkdtemp(dir=basedir)
02edbd021215d25a835e86e3566763733165e9b0
631,326
def set_response_headers_tween_factory(handler, registry): """Add additional response headers here""" def set_response_headers_tween(request): response = handler(request) response.headers['X-Request-URL'] = request.url # Setter automatically converts set back to tuple. # See: htt...
77a0099c4ae8d3e52dee83e8329795fa4b267df5
631,327
def convert_dict(dicts: dict) -> dict: """ Convert all the values in a dictionary to str and replace char. For example: <class 'torch.Tensor'>(unknow type) to torch.Tensor(str type). Args: dicts (`dict`): The dictionary to convert. Returns: (`dict`) The...
d73cf26d6dc0f5bab31277710c7188baafbce21f
631,328
def test_column_type(df): """test column type: input dataframe generated by pandas. output whether the every value in columns is the correct type""" for i in range(len(df.columns.values.tolist())): test_col = df[df.columns.values.tolist()[i]] length = len(test_col) for j in range...
19ab0baa86e97a6ad78b0ba3f43d03efdbf782f0
631,329
import argparse def get_parser(): """Get parser for command line arguments.""" parser = argparse.ArgumentParser(description="Extract a part of file for testing purpose") parser.add_argument("-i", "--input-file", dest="input", help="Fi...
50b942c6c0c0e39502e40997a1ab70faff81ed1d
631,330
def dimensions_match(matrix1, matrix2): """ This function checks if the orders of the given matrices match. Arguments: matrix1 {Matrix} - The first Matrix object matrix2 {Matrix} - The second Matrix object Returns: boolean-- True or False depending on if their orders match or not. """ ...
a7ce6a7894b4ec8ff6827e8b802c2227909d9c60
631,331
from pathlib import Path from typing import Optional from typing import Union from typing import Pattern from typing import List import re def get_all_files_in_directory( path: Path, pattern: Optional[Union[Pattern, str]] = None ) -> List[Path]: """ Returns all the files in a directory structure. For...
c1bc4f752125f287bf2fee3e8ab3f921f2e0a6a0
631,333
import argparse def create_parser(): """Create qtsass's cli parser.""" parser = argparse.ArgumentParser( prog='QtSASS', description='Compile a Qt compliant CSS file from a SASS stylesheet.', ) parser.add_argument( 'input', type=str, help='The SASS stylesheet fil...
e054cb6fb832adef7b4a7c4d0942ef2eb5d89b78
631,334
def run_on_nested_arrays2(a, b, func, **param): """run func on each pair of element in a and b: a and b can be singlets, an array, an array of arrays, an array of arrays of arrays ... The return value is a flattened array """ if isinstance(a, list): if not isinstance(b, list): ra...
2f2c4b5309df5fbfe2b97e39e1c58b43e1b699f4
631,335
import re def hasCarryOrBorrow(exp): """ Check expression to see if carry or borrow is required :param exp: math expression :return: True if carry/borrow is required; False otherwise """ sign = re.findall('(\d+)([+*/-])(\d+)', exp) if sign[0][1] == '/': return False elif sign[0...
d994214d13f6b4d9dc7e09ecb06bf1bd3c1dd851
631,337
def format_output(result): """Format output to preserve consistence in output""" formatted = "WPM: %-3s " % result["wpm"] formatted += "KPS: %-3s " % result["kps"] formatted += "Error: %%-3s " % result["error"] formatted += "Strokes: %d " % result["strokes"] return formatted
7488939497045ed86b586072b3fa6f9636417a76
631,338
import torch def face_area(vertices, faces): """ Computes area of each faces using cross product Args: vertices (torch.tensor): Vx3, xyz coordinates of vertices faces (torch.tensor): Fx3, index of vertices for each face Returns: (torch.tensor): F, area of each face """ ...
92c067949ee3c7c486ccf3a27b8ea2a3e2e60de3
631,339
def triangular_number(x: int) -> int: """ Get the xth triangular number """ return (x * (x + 1)) // 2
db640d26cfa4ba524c18bc443fc657758260f585
631,341
def mnet_kwargs(config, task_id, mnet): """Keyword arguments that should be passed to the main network. In particular, if batch normalization is used in the main network, then this function makes sure that the main network chooses the correct set if batch statistics in case they are checkpointed (i.e.,...
e922f70dfec3d247843c39ee6763443f65a2d4f7
631,342
from numbers import Number def dict_splicer(plot_dict,Ld,Lx): """Dictionary constructor for plotting Base-level function used by most other plotting functions to construct a list of dictionaries, each containing the passed arguments to the underlying plotting calls for each different dataset. Parameters ----...
14e5a1009ba14dcb861507c8f3f6a563a7889a25
631,343
def filter_group_minmax(dfg, col): """ Returns all rows equal to min in col """ return dfg[dfg[col] == dfg[col].min()]
4d29bbd34030e8ff7c538d632c43fc611328b690
631,344
import torch def tblr_to_xyxy(tblr, centers): """Convert [x1 y1 x2 y2] box format to [t, b, l, r] format. if center is not given, the center point is used""" assert len(centers) == len(tblr) # t, b, l, r = tblr.split(1, dim=1) ##true one b, t, l, r = tblr.split(1, dim=1) xmin = centers[:, 0].u...
94799f22eb926b33c8422fe9598a58ca64742542
631,345
def calc_bpe_exchange_current(K_standard_rate_constant, c_bulk_oxidized, c_bulk_reduced, alpha_transfer_coefficient=0.5): """ The exchange current density at a specific BPE location units: Coulombs/s*m2 Notes: K_standard_rate_constant: usually between 2 and 6 c_bulk (oxidized and reduced...
f09c19bab7f23762b9f20816eff57a6e20dbaf63
631,347
def sort_rfcs(rfcs, ordering): """Sorts the given list of Rfc instances in a specific order.""" if ordering == 'number-asc': return rfcs.order_by('number') elif ordering == 'number-desc': return rfcs.order_by('-number') elif ordering == 'title-asc': return rfcs.order_by('title')...
ab268fc45eb805466917bec928dde10680a8bfdb
631,348
def term_importance(*args): """ 複数のディクショナリの値同士を乗算する """ master = {} new_master = {} for noun_dict in args: for nouns, importance in noun_dict.items(): if nouns in master: new_master[nouns] = master[nouns] * importance else: new_mast...
ad49db8f255c9e729ab972f313f33eae4509b9cb
631,349
def safe_join(separator, values): """Safely join a list of values. :param separator: The separator to use for the string. :type separator: str :param values: A list or iterable of values. :rtype: str """ _values = [str(i) for i in values] return separator.join(_values)
e6ef01fe4bcdd5fa8ed34a922b896dc10ec7eda0
631,350
def hires_by_jobTitle(df): """" selects new hires by jobTitle """ jobTitle_list = ['Post-Doctoral Research Fellow', 'Staff Scientist', 'Research Techn II', 'Graduate Research Asst', 'Assistant Member', '...
24515400b35bd26c964520746435440aaba1c136
631,352
def get_requirements(): """This function keeps the requirements up to date with the most recent changes in the files, and reducing the human error chance.""" with open('requirements.txt') as file: return file.read()
63e4630cf6ff015991c8225ef3661ff0037b5429
631,353
from typing import List def keys_exists(multi_dict: dict, keys: List[str]) -> bool: """Check if multi-level dict has specific keys""" _multi_dict = multi_dict for key in keys: try: _multi_dict = _multi_dict[key] except KeyError: return False return True
1de1ef0060a6f0953335e7968de824e6880bcda6
631,355
def __dobjUrl__(dobj): """ transform the provided digital object to a consistent format the user may provide the full url or only the pid. this function will return the full url in form: '<https://meta.icos-cp.eu/objects/'+ dobj + '>' """ try: dobj = str(dobj)...
bf80d0c78ec6191cd0f9369dbf8146637b01a868
631,356
def numRunningSteps(stepsDict): """ takes a stepsDict and returns the current number of incomplete and running steps """ n = 0 for s in stepsDict: if not stepsDict[s].complete: if stepsDict[s].startTime != -1: n += 1 return n
c9959580f324ebcee46c5f9ba13ff3adede1d290
631,357
def qgis_raster_clip_raster_by_extent(processing, Input, PROJWIN, Output): """Functions clip raster by extent ---------- Notes ------- Returns: ------- None, the attribute table of Path_shpfile will be updated """ out = processing.run( "gdal:cliprasterbyextent", ...
e81114221dea04679e2b52974771bf090dceb802
631,358
import os def default_user_ignore_filter_path(config): """Return default user ignore filter path. :param config: A Config object :return: Path to a global ignore file """ try: return config.get((b'core', ), b'excludesFile') except KeyError: pass xdg_config_home = os.envir...
7fe8dbe09d86f384d82e124fbcc21718cfc19076
631,360
def wealth_taxes(wealth, params): """Calculate the wealth tax based on wealth and params. Args: wealth (pd.Series) params (pd.Series) Returns: pd.Series: the wealth taxes """ return params.wealth_tax * wealth
797b5c423a5749f3996498f3cb96d8205a986116
631,361
def get_event_type(tweet_id, labels_path, normal_tweets=[], mis_tweets=[]): """takes a tweet_id, and a groundtruth file path, then returns the type of this tweet either misinformation or normal""" if tweet_id in normal_tweets: return 'n' if tweet_id in mis_tweets: return 'm' reade...
49b34cccb1e6ace25b7e55624d6c717f06ef7d17
631,362
def fix_url(url): """Add http:// prefix to url if it doesn't have one.""" if "://" not in url: if url.startswith("//"): url = "http:" + url else: url = "http://" + url return(url)
332925f66415fb42c02d6677742859d0dd2955c3
631,363
import os import sys def python_bin_dir(): """ use sys.executable to determine the bin dir for the active python. """ return os.path.dirname(sys.executable)
2e25d5acaf3fd92bca3cbe224d4baa9a2d97c93f
631,364
def describe(a, b): """Displays an explanation of the instruction Args: a (str): The string of the first half of the description b (str): The string of the second half of the description Returns: str: The complete description """ instruction = a + b opcode = instructio...
ff8bb8f7b8de5f9bf0da0eccb9367191dfc2891d
631,365
def get_timecode(td): """Convert a timedelta to an ffmpeg compatible string timecode. A timecode has the format HH:MM:SS, with decimals if needed. """ seconds = td.total_seconds() hours = int(seconds // 3600) seconds %= 3600 minutes = int(seconds // 60) seconds %= 60 str_seconds,...
a5f8d14a1e42ffb1ea5403023c16268265b554c3
631,366
def array_hash(data, key, value): """ 获取一个DB对象的HASH结构 """ if not data or len(data) == 0: return {} result = {} for item in data: if isinstance(item, dict): attr = item.get(key, None) else: attr = getattr(item, key, None) if attr is None: ...
564d1e1d909f75956d87633e105ad153bc5cdf95
631,367