content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import pytz def GetUtcTime(dt, tz): """Converts from a local time to UTC using timezone translation. The returned time does not have any timezone information. This allows comparison with times coming from the datastore (which do not have timezone either). Args: dt: A datetime.datetime instance with no...
c652ebf9a010173fedaa7a9d4771bf03f8764888
629,780
def to1D(A): """ Matrix unrolling No side effect Different from A.reshape(1, -1) """ return A.ravel()
369a58e2dba28204a6d759d265de93e4719db781
629,781
import os def does_file_have_416_issue(file_path: str) -> bool: """Check to see if a file has an embedded '416 status' error in its tail Internet Archive servers can sometimes suddenly throw a 416 status ("Requested Range Not Satisfiable") on resumable / split downloads. When this occurs, sometimes the p...
4153b393921c9a1d0639bfb5ee3180bd3b17f3fa
629,782
def persistence(n): """ Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit. :param n: an integer value. :return: the numbers of times the dig...
5a7556c09b87a88ceffc330594e115662cbee141
629,783
def get_pet(self, pet_id): """ Get a pet. This is an example of how to use references and factored out definitions --- tags: - pets parameters: - in: path name: pet_id definitions: - schema: id: Pet required: - name - own...
a34b07f7728777fddad398dd7df36f4b9129b308
629,784
def concat_path(path, child): """Concat path with subfolder or file.""" newpath = path + "/" + child return newpath
1d31a4bc9e453377a05cc6f097142a103b3b11b2
629,785
def velocity(vo2): """ A regression equation relating VO2 with running velocity. Used in conjuction with the "vO2" equation to create the Jack Daniel's VDOT tables. Initially retrieved from "Oxygen Power: Performance Tables for Distance Runners" by Jack Daniels. J., Daniels, and J. Daniels. Conditioning fo...
7fb604ff63d7b54e943233a53c09e2b2851168b9
629,786
def GetTMIndex(iRes, posTM):# {{{ """Get index of TM helix given a residue position Return -1 if iRes is not within TM region """ for i in range(len(posTM)): (b, e) = posTM[i] if iRes >= b and iRes < e: return i return -1 # }}}
aded5661c6deea1b16d78f8ff0dbd3ab1f8a94d3
629,787
import re def get_valid_filename(s: str) -> str: """Return a filename-compatible version of the given string s :param s: String to be used as the base of the filename. You may also pass non-string objects that will however be able to convert to strings via the str operator. >...
a4c72b6b84452b5552fcfb10f7e96c9518c69649
629,789
def cpu_processing_time(cycles: int, freq: float): """ :param cycles :param freq: MHz :return: seconds """ return (cycles / (freq * pow(10, 6))) * pow(10, 3)
4b8fe7fd1b0f25b1cde270b129aa104b2a4652e2
629,790
import sys import time def timing(f, output_to=sys.stderr, **kwargs): """ Decorator to time function. """ def wrap(*args, **kwargs): time_start = time.time() ret = f(*args, **kwargs) #took = time.time() - time_start took = time.strftime("%H:%M:%S", time.gmtime(time.time() - tim...
7653fc6f4611b7170792c36c73b5c0576c15b054
629,791
def is_palindrome(test_string, test_string2): """ 5. Given test_string and test_string2 return True or False if one is palindrome of the other. Palindrome: Same string if read backwards. """ return test_string == test_string2[::-1]
572e9fd0f6821c1291441e4241db776464ee8afe
629,792
import os def file_exists(filename): """ Check if file exists """ if os.path.isfile(filename): return True return False
6f5b1b02239f41ef65dec249c6ee9548c85bda4a
629,793
from typing import List def get_map_center(ip_entities: list): """ Calculate median point between IP Entity locations. Parameters ---------- ip_entities: list A list of ip entities to get a center point from Returns ------- Tuple The Lattitude and Longitude calculated...
341b27cb892f922452d8115c255a8ec664a4c928
629,794
def subList(l, sl) : """return the index of sl in l or None""" lLen = len(l) slLen = len(sl) for i in range(lLen - slLen + 1): j = 0 while j < slLen and l[i + j] == sl[j]: j += 1 if j == slLen: return i return None
520966384a538989b662e490e86991a95661cb90
629,795
import time def date_to_str(): """ :return: String of current date in Y-M-D format """ ISOTIMEFORMAT = '%Y-%m-%d' string = '{}'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time()))) return string
a8acf5cb3c259d4f89ad0b2cfc839f8355991619
629,796
import torch def jitter_soma_depth(feats, scale=10): """" Apply jitter to soma depth. Args: feats: features per node scale: scale factor of jittering """ new_feats = feats.copy() new_feats[:, 1] += torch.randn(1).numpy() * scale return new_feats
188cb75555c330402c2b703ef9038de40eebd15c
629,797
def translate_name(name): """ Convert names with underscores into camelcase. For example: "num_rows" => "numRows" "very_long_json_name" => "veryLongJsonName" "build_GBM_model" => "buildGbmModel" "KEY" => "key" "middle___underscores" => "middleUnderscores" "_e...
3c79e7530c28ef47e8b88960908ffa2310e462b7
629,798
def calc_rank(someset, n): """ Calculates the rank of a subset `someset` of {1, 2, ..., `n`} in the ordering given by grey sequenccce of characteristic vectors. """ assoc_seq = [k + 1 in someset for k in range(n)] bit = False rank = 0 for k, x in enumerate(assoc_seq): bit ^= x rank += bit * 2**...
4b3a7a226d90a5431d7622788e1d84ab406b40c3
629,799
def BuildFileName(url): """Construct the file name from a given URL. Args: url: the given URL Returns: filename: the constructed file name """ filename = url.strip('\r\n\t \\/') filename = filename.replace('http://', '') filename = filename.replace(':', '_') filename = filename.replace('/', '_...
89f06c884b708a17981a7ce3f439fb6a022a627b
629,804
def xml_input_document(request): """Source ElectionDefinition XML to validate with XML Schema.""" document = request.param return document
0e78bce308b9d2e1b1f94f4bf1d1776f32c7d1d0
629,805
def _parse_suspected_cls(predator_result): """Parse raw suspected_cls into dict.""" if not predator_result: return None # The raw result contains some additional information that we don't need here. # Everything we're concerned with is a part of the "result" object included # with the response. predato...
0f4d72542fc138512d4bbfe3c997f8e9b940a96c
629,806
import uuid def get_uuid(key=None): """ 生成UUID :param key: 默认空 按照UUID-1方式生成,如果有值,者按照UUID-3规则生成。但是前提业务需保证key具有唯一性,如手机号 :return: """ ''' Python uuid 5种算法 1、uuid1()——基于时间戳 由MAC地址、当前时间戳、随机数生成。可以保证全球范围内的唯一性, 但MAC的使用同时带来安全性问题,局域网中可以使用IP来代替MAC。 2...
db29859cd123d2c852258420907c5958a3fd6e10
629,807
import re def is_string_valid_source_package_name(pkgname: str) -> bool: """ Check if a package name is debian compliant The source package name should be all in lower case, and can contain letters, digits, and dashes. Some other characters are also allowed. :param pkgname: string to check :...
3f0d4fa4d54fad4aac5a6df1a580497d7959a647
629,808
def list_multiply(*lists): """ Sums two lists of integers and multiplies them together >>> list_multiply([3,4],[3,4]) 49 >>> list_multiply([1,2,3,4],[10,20]) 300 >>> list_multiply([4,3,2,1],[50,50],[5,5,5]) 15000 """ total = 1 for l in lists: total *= sum(l) ...
8b1eedd47ff1d39f1c310dc6c662728711897e57
629,809
def _is_primitive(obj): """ Check if the given object is a primitive type Args: obj: the object to test Returns: True if the object is primitive i.e. hasn't a __dict__ attribute """ return not hasattr(obj, '__dict__')
b0ad6673f472d8e78d59ab9f7dd67eee557dbd8f
629,811
def real_basename(path): """Python's os.path.basename is not basename.""" if path.rsplit('/', 1)[1] is '': return None return path.rsplit('/', 1)[1]
6d36a20dec3d5732c56edc33d3f5bbe232464ab5
629,812
import logging def get_logger(name): """ Create new logger with the given name :param name: Name of the logger :return: Logger """ logger = logging.getLogger(name) return logger
80a7e545be7badd71277d38dbb202e70643f6ecb
629,815
def valid_color(color_value, range_min, range_max): """Checks that the color value is within the range of validity. Each polynomial fit has a different range of validity. We need to make sure that the color we are feeding in is inside that range. Args: color_value (float): B-V, V-I, or B-I col...
0dc353f9938f94bb6aa4f4330128c99222ffd1df
629,816
import re import random def choose(phenny, input): """.choose <red> <blue> - for when you just can't decide""" origterm = input.groups()[1] if not origterm: return phenny.say(".choose <red> <blue> - for when you just can't decide") c = re.findall(r'([^, ]+)', origterm) fate = random.choice...
e9432ea7fb89526ca33c299b493a0fb1ecdd365a
629,818
def depends_on(*args): """ Add a class dependency """ def wrap(cls): try: getattr(cls, '_dependencies') except AttributeError: cls._dependencies = [] for a in args: cls._dependencies.append(a) return cls return wrap
cc13de0706d2d12ccc295a4a2882197f17754f95
629,819
import math def complex_from_angle(phi, radius): """Return the complex number with argument 'phi' and absolute value 'radius'.""" return complex(math.cos(phi) * radius, math.sin(phi) * radius)
153c961d9095fcbb91226cb8430071efd63ab205
629,821
def get_item_length(obj, key): """ Template tag to return the length of item in gien dictionary """ val = "0" if obj and type(obj) == dict: val = len(obj.get(key, [])) return val
d8e547c2e2f2e89171f054e324b396309524d4c2
629,822
import time def get_sleep_time(): """get sleep time to next minutes""" now = int(time.time()) next_ts = now - now % 60 + 60 sleep_time = 60 - now % 60 return sleep_time, next_ts
63a0c8544abe6b2ef394bcae452832c846b9d398
629,823
def rst_headline(title, level): """ Format a markdown header line based on the level argument. The rst format for headings is generally of the form ==================== title for this thing ==================== """ level_char_list = ['#', '*', '=', '-', '^', '"'] try: level_c...
f889f74629d2921ef7b51f1515d493d42719da88
629,824
async def get_all_entities(entities): """Get all entities on the same dict. Watson API will return a list containing dictionaries for each, entity found. On large numbers of entities it becomes hard to get what we want, this function is meant to be an helper function to get all the entities into a ...
48256e4b519079106fe5bb165c64a27f3467d115
629,825
import dis def _instructions_in_getitem(x) -> list: """Get all instructions up to last CALL FUNCTION. """ instructions = list(dis.get_instructions(x)) return instructions[:-1]
3432d1f2a7d8f2d2b69bdf0ffd8c248896d9ddda
629,826
def convert_distance_to_probability(distances, a, b): """ convert distance representation into probability, as a function of a, b params """ return 1.0 / (1.0 + a * distances ** (2 * b))
b686cb7f0ed071c764f5b98e8131aed9ad1f9e7c
629,827
def wcs_ndim_types_units(request): """ Generate a wcs and the expected ndim, types, and units. """ ndim = {'gwcs_2d_spatial_shift': (2, 2), 'gwcs_2d_spatial_reordered': (2, 2), 'gwcs_1d_freq': (1, 1), 'gwcs_3d_spatial_wave': (3, 3), 'gwcs_4d_identity_units...
b2f4edab0c38a692d2af6aec87092acc2bb32777
629,829
def let_user_choose(first, second, separator='|'): """ This function append both value (as string) inserting a separator inbetween. :param first: First value. :param second: Second value. :param separator: Optional separator. :return: first + separator + second. >>> let_user_choose("first",...
4aedc0a2c860071c515cfd2e676032a4f3317a69
629,830
def duration(t): """ Give a nice short and readable string representation of a given time duration in seconds, e.g. how long it took to render the whole project. Usage ----- >>> timetag = duration(t) Parameters ---------- The time that has passed in seconds (int or float). ...
f037a8b88d939e192dd16d25c1189f8e730f66b0
629,831
def get_es_result(mode, current, best_so_far): """Returns true if monitored metric has been improved""" if mode == 'max': return current > best_so_far elif mode == 'min': return current < best_so_far
e3183d571fb148776713989bcbdd12d5c57d57d7
629,832
import copy def compensation_list_FTG(MFTG, BFTG, n): """Construct compensation list Parameters ---------- MFTG : list monomials to be shifted, for example, [[1], [2], [1, 3]] BFTG : list positions to shift monomials, for example, [3, 2, 3] n : int size of the NLFSR ...
940aa2d5d117b5062ed4b2950243e7c2a83fb2be
629,833
import sympy def is_multiplication_by_reciprocal(sympy_mul: sympy.Mul) -> bool: """Check if given sympy multiplication is of the form x * (1 / y).""" args = sympy_mul.args return len(args) == 2 and isinstance(args[1], sympy.Pow) and args[1].args[1] == -1
8bc7c11ca28ed681042747b0eff2b293e96a7e5d
629,834
def mle(y,out): """log对数损失函数,常见于logistic 回归,不实现""" return NotImplemented
23822599869213b7a8e2889cef15d469783336a3
629,835
import subprocess def call_dependency(libFullName): """ Determine all dependencies for a single library in the full absolute path """ action = '/usr/bin/otool' option = '-L' sub_call = [action, option, libFullName] return subprocess.Popen(sub_call , stdout=subprocess.PIPE)
5a02f938b90682b3f9b9342da906c4ce28364f60
629,836
import math def g(func_value, x): """ Defining derivative of function Inputs: 1.x : Input value 2.func_value : number indicator to show which of the 2 functions we choose Output: Function value """ if int(func_value) == 1 : return (3*x*x - 6*x - 1) elif int(func_value) ==...
ac6bd57803e7ceda54e592ef6ca3669cd507ae8f
629,837
def get_param(gates, sweepgate): """ Get qcodes parameter from scanjob argument """ if isinstance(sweepgate, str): return getattr(gates, sweepgate) else: # assume the argument already is a parameter return sweepgate
50b08ef2fcbcad3bac5a1d392eac44fbdc451a18
629,838
def filter_selected(list_values, value): """ Check if a value exists in a list. Parameters: list_values = A non-empty list. value = A value Returns: True if the value exists in the list. """ return value in list_values
0d0a707fc3b327a89cdc455b49a9aaf1b6090b2b
629,839
def _get_token_resource(client, resource, parsed_name, parsed_domain=None): """Peek into the user's auth token to get resource IDs Look into a user's token to try and find the ID of a domain, project or user, when given the name. Typically non-admin users will interact with the CLI using names. However...
4e63aa8a086df7d77b4bd30c183d6217eb5d9764
629,840
import copy def merge_qnodes(qnodes1: dict, qnodes2: dict) -> dict: """Merge qnodes: the keys must be the same and the values must be the same. If a key is unique to one nodes dict, then the node will be concatenated to the new nodes dictionary. If a particular key exists in both messages but the valu...
2a2c22ba8e3fcd5eaeaaf209a03dc9c3bec33744
629,841
import argparse def parse_args(): """Parse CLI Arguments""" parser = argparse.ArgumentParser() parser.add_argument( "okapi_url", help=( "url of your FOLIO OKAPI endpoint." "See settings->software version in FOLIO" ), ) parser.add_argument( "t...
fd669dea1fdc32c172d69a8b586e0a4c67eea999
629,842
import re def clearText(text): """ @param text: @return: @rtype: str """ return re.sub('[»«‒§—·•]', '', text).strip()
d8119c34fa56829c9142271b0cc38f84c255fa9e
629,843
def getshapesidedict() -> dict: """Returns a dictionary of side or polygon definitions for simple solids Returns: dictionary of side or polygon definitions for basic solids """ return {"tetrahedra":((2, 1, 0), (2, 3, 1), ...
7de3115012e041e50977ff82efe6f2138c625e26
629,844
def _filter(lst, func=None): """Filter a list according to a predicate. Takes a sequence [o1,o2,..] and returns a list contains those which are not `None` and satisfy the predicate `func(o)` :param lst: Input iterable (not a dictionary) :param func: Predicate function. If ``none``, this function a...
1782b133459be053310067c98e23a0e92ee46f67
629,845
def next_month_id(monthid): """ Return a month id that is one month ahead of the input. Argument: monthid - a valid month id in the format of YYYYMM """ month = monthid % 100 year = monthid // 100 if month == 12: year += 1 month = 1 else: month += 1 ...
099c49aed1e0e97787b061f0746b706cd08d24eb
629,846
def get_frame_index_int(image_file): """Returns an int-type index of the image file""" return int(image_file.split('_')[-1].split('.')[0])
c27fd9a1ee880b8edeb28671bd7a557128181f91
629,847
import sys import os def get_conda_env() -> str: """ Grab the name of the activate conda environment and returns it as a string. If there is no env, then an empty string is returned. """ # Check the list of python paths and grab the first path that has "envs" in it. # Assume we don't have a co...
1242826da1a38cfeb79d948686059f8b86720e99
629,848
import numpy import math def conf(x): """95% confidence interval""" lower = numpy.mean(x) - 1.96*numpy.std(x)/math.sqrt(len(x)) upper = numpy.mean(x) + 1.96*numpy.std(x)/math.sqrt(len(x)) return (lower,upper)
890bdaa188fc0f46546bc1c4bfcd928b2dd3fe3f
629,849
import math def rad2deg(rad): """radians -> degrees""" return math.degrees(rad)
ca7e150b708723c40c750b8e1f177df7ce900da2
629,850
import os def _calibration_prefix(params, nightname=None): """ Define the calibration database file prefix (using arg_night_name) :param params: parameter dictionary, ParamDict containing constants Must contain at least: NIGHTNAME: string, the folder within data raw directory ...
12fb451cc8ad4a85c72968626f4a2d5a75ca31d0
629,851
def find_free_game(games): """ finds the Free Game of the Day on MLB.TV :param games: list of GameData() objects :return: the free game's unique id: game_pk """ for game in games: if game.free == 'ALL': return game.game_pk
3edfb6e3285e19af3a1319e6d8bcfafd241ceac5
629,852
def _base64_len(length): """Converts a length in 8 bit bytes to a length in 6 bits per byte base64 encoding""" # Every 24 bits (3 bytes) becomes 32 bits (4 bytes, 6 bits encoded per byte) # End is padded with '=' to make the result a multiple of 4 units, trailing = divmod(length, 3) if trailing: ...
a3e0b182825413d2694c7dcb739c5569911a95a4
629,853
import random import socket def choose_vnc_port(): """ return available vnc port between 5900 to 5999. some copied from stack """ random_port = random.randint(5900, 5999) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: if s.connect_ex(('localhost', random_port)) != 0: ...
ae4bbce7e4600b1cb8057584434f69a570ba5f50
629,854
import yaml import logging def read_config(config_path: str) -> dict: """ Args: config_path: Path to the config file Returns: content: Returns content of config file """ with open(config_path) as config_file: content = yaml.safe_load(config_file) logging.info(f"yaml fi...
eb5806f61a2cac7d77fdf93efe101d4860504aab
629,855
from typing import Union from pathlib import Path from typing import List def get_files(path: Union[Path, str], extension='.wav') -> List[Path]: """ Get all files from all subdirs with given extension. """ path = Path(path).expanduser().resolve() return list(path.rglob(f'*{extension}'))
b7f1c8a7af34ecb90a00c5f126c6eba20e6a9ed4
629,857
def paginator(context, adjacent_pages=2): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. Required context variables: paged...
e2dc331786575dcd134e358beae81939139e5616
629,858
def skipForLogfile(fragment, msg): """Return a decorator that skips the test for logfiles containing fragment.""" def testdecorator(testfunc): def testwrapper(self, *args, **kwargs): if fragment in self.logfile.filename: self.skipTest(msg) else: te...
97b6f30ae870cff635229e1276d0a8a51ade8dc5
629,859
from typing import List from typing import Any def flatten_list_of_lists(list_of_lists: List[List[Any]]) -> List[Any]: """Flattens a list of lists.""" output = [] for one_list in list_of_lists: output += one_list return output
8b4dc6e38c50f510f210f804443a8a78f74894a9
629,861
def set_default(params, dict_default): """Set defaults for missing keys and add the key:value pairs to the dict.""" for key in dict_default: if key not in params: print("Setting a default value for " + str(key) + ": " + str(dict_default[key])) params[str(key...
4472da1e0ec8af72576b08d7fc96c0533681e7d1
629,862
import pathlib def parse_requirements(filename): """Load requirements from a pip requirements file.""" with pathlib.Path(filename).open() as fp: lines = (line.split('#')[0].strip() for line in fp) return [line for line in lines if line and not line.startswith('--')]
d2104307736a3899591506e64cb372cc21a7ceae
629,863
import typing import itertools def generate_permutations_with_replacement(width: int, seq_length: int) -> typing.List[typing.Tuple[int, ...]]: """ Generates a list containing all seq_length**width possible permutations :param width: The length of each combination. :param seq_length: The amount of eac...
628b2c3553173098bd58d51421226f7db814f458
629,864
def coarse_pos_e(tags): """ Coarse POS tags of Treebank corpus: N: Noun, V: Verb, A: Adjective, D: Adverb, Z: Pronoun, T: Determiner, E: Preposition, P: Postposition, U: Number, J: Conjunction, O: Punctuation, R: Residual, L: Classifier, I: Interjection >>> coarse_pos_e(['Nasp---', 'pers', 'pro...
93ac495c9f029108f07638abde797c98e31302a6
629,865
def cols_to_rename(df, dictionary): """Drop selected columns and return DataFrame. Args: df: Pandas DataFrame. dictionary: {'old_name1': 'new_name1', 'old_name2': 'new_name2'} Returns: Original DataFrame without dropped columns. """ df.rename(dictionary, axis=1, inplace=Tr...
84418bc0583bf2c6948179de0938b9ac7a6915eb
629,866
import inspect def get_calling_frame_variables( call_depth ): """ Uses the inspect module to get hold of the calling frames leading to this function, picks the frame 'call_depth' back (up the call stack), then gets the local and global variables as they exist in the scope of that caller function. ...
2c16075cb7560618bf1f43fe23cd22dd2d22ef10
629,867
def error_response(error_message: str) -> dict: """ Form an error REST api response dict. :param error_message: string error message :return: """ return { "success": False, "error": error_message, "data": None, }
43045e3c31a29e966da7f6f705d70c71a7af0cba
629,868
def remaining_G9_12_cap(k12): """ Remaining enrollment capacity available at the school. """ return (k12['G9_12_cap'] - k12['G9_12']).clip(0)
68d31e3b24ff3405b50cd53691be0f92baee0ba9
629,869
import argparse def hyphen_range(v): """ Returns a range from a given string including lower bounds and upper bounds. >>> hyphen_range("1-3") [1, 2, 3] >>> hyphen_range("foobar") Traceback (most recent call last): ... ArgumentTypeError: String must have 2 fields >>> hyphen_rang...
98e3899c6a309ead630e9a5e4bbbf3d6ebcce456
629,870
def mft_selected_objects_and_duplis(self, context): """Loop over (object, matrix) pairs (mesh only)""" listObjMatrix = [] for obj in self.drawOnObjects: if obj.type == 'MESH': listObjMatrix.append((obj, obj.matrix_world.copy())) if obj.dupli_type != 'NONE': obj.dupl...
06daff39b920065c4ad6c7509818391bf5858476
629,871
def _none_2_empty(text) -> str: """Translate None to empty string.""" if text is None: return "" return text
1235492bf3e4a8879de1fd3767503d2cdc9ddcea
629,873
def process_string(string: str) -> str: """Change escape sequences to the chars they match ex: process_string("\\\\n") -> "\\n\"""" replacements = [ ("\\\\", "\x00"), ("\\n", "\n"), ("\\t", "\t"), ("\\r", "\r"), ('\\"', '\"'), ("\\'", "'"), ("\x00", "\\"), ] for search, replace in replacements: str...
e7f2270be8126cb9484afd8e14668fc14e5288c4
629,874
from typing import Dict from typing import Any from typing import Tuple def resolve_pagination(query: Dict[str, Any]) -> Tuple[str, str]: """Solve the pagination of a DJANGO query.""" init = 0 limit = 0 for k, v in query.items(): if k.startswith("p_"): if k.endswith("l"): ...
9a0f3fbe712a6a5c0e4b64f6084484813b0fe3c9
629,875
def parse(query: str) -> str: """ Parse URL query into correct SQL syntax. :param query: SQL query pulled from URL argument. :return: Parsed query converted to valid SQL syntax. """ query_split = query.split("+") return " ".join(query_split)
2f7d990a3c06b632e4b7be2a4af9460bcf4838f8
629,876
def format_changes(changes): """ Format changes so it will look better. ref on changeset: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets-view.html """ parts = [] for change in changes: change_ = change["ResourceChange"] l...
7f4fac8b601411d637d02ec3a454129961b97e6f
629,877
def _make_style_str(styledict): """ Make an SVG style string from the dictionary. See also _parse_style_str also. """ s = '' for key in styledict.keys(): s += "%s:%s;"%(key, styledict[key]) return s
48da4f00570c49ba2283fd1dbe8d08ae1b25ee41
629,879
def is_all_fail(l): """从list下的dict拿出code!=0的(执行失败)数量""" return len(l) == len(list(filter(lambda x: x.get('code') != 0, l)))
5b9933551016ecfde083409603e68312d393b5b4
629,880
def fix_walletserver_url(url: str) -> str: """ Help guide users against including api version suffix in wallet server URL. """ for suffix in ["/api/v1/", "/api/v1", "/api/", "/api", "/"]: if not url.endswith(suffix): continue print( f'There\'s no need to add "{suf...
611b3ea7ffb4464e21d65bdd3c4405f423cb0517
629,881
def weigh(tower,all_towers): """ Find the total weight of a tower. """ if not tower.supports: return tower.weight return sum([weigh(t,all_towers) for t in all_towers if t.name in tower.supports]) + tower.weight
b30683f1e3910b7d5d312ade3634e9479efa6737
629,882
def relegated_teams(df): """Returns a list with teams who are relegated to lower category. The last two teams from each league relegated. Keyword arguments: df -- dataframe with the championship table""" relegation_list = [] # iterate over each row and check if its a relegation position. ...
9749c601d2c8654b23a4ced27ae99bf18196fb87
629,884
import torch def where(cond, x, y): """Return index by condition.""" return torch.where(cond, x, y)
105a1a2c6fb0c52d9bc71ff1b47c38989ccefe21
629,885
def chem_pot_cols(chems): """Return columns corresponding to the chemical potential :chems: str :returns: list str """ return ["param_chem_pot({})".format(c) for c in chems]
1728f0cff75d1cbb4f1134ad66707a835ee589bc
629,886
def annotated_frames(scribbles_data): """ Finds which frames have a scribble. # Arguments scribbles_data (dict): Scribble in the default format. # Returns list: Number of the frames that contain at least one scribble. """ scribbles = scribbles_data['scribbles'] frames_list = [i...
9b3a08879110beb4c9d2b6d43f871c030e4abe9f
629,887
def mdmre100(self, y_true, y_pred): """ Median magnitude of relative error, as percentage. """ return self.mdmre(y_true, y_pred) * 100
e3b3ec5bdf18cf0ef3faade56bda109c3df9c0fd
629,888
def find_fusion_energy_per_reaction(reactants: str) -> float: """Finds the average fusion energy produced per fusion reaction in joules from the fuel type. Args: reactants: the isotopes that are combined in the fusion even. Options are "DD" or "DT" Returns: The average energy...
8121802f096a027c885d7569149dafb4a6a70548
629,890
def window_bounds(i, n, wn): """Start and stop indices for a moving window. Parameters ---------- i : int Current index n : int Total number of points wn : int, odd Total window size Returns ------- start : int Start index stop : int Stop...
2a409322190b1ec362481a751e53ae6dbc2782f9
629,891
def compute(n): """ docstring """ coins = [1, 2, 5, 10, 20, 50, 100, 200] ways = [0] * (n+1) ways[0] = 1 # ways[n] how many ways to achive n for i in range(len(coins)): for j in range(coins[i], n+1): # 比如 coins[i] = 5, j = 13, ways[13] += ways[13 - 5 ] 即 ways[13] += ways...
447bf3458fcfe9eac61bfb13f3dd10b9f9bbe3a5
629,892
from typing import Optional def linear_search(numbers: list[int], target: int) -> Optional[int]: """Search a target from the input using linear search algorithm :param numbers: a collection with comparable items (not required to be sorted) :param target: item value to search :return: index of found i...
f082db3706a0f985bc551292334f31f027c9e8b1
629,893
def clipping(X, lo, hi): """ Helper function for clipping. Args: -- X: Pytorch tensor of shape (N, C, H, W) -- lo: list, lower bound for each channel -- hi: list, upper bound for each channel Returns: -- X: Pytorch tensor of shape (N, C, H, W) """ for c in range(3): X.d...
d4cc5d381f1b4cdc63828fdb45e31ccc70702c01
629,894
def human_answer_mug(agents, self_state, self_name, robot): """ @semantic_name: @param agents: @param self_state: @param self_name: @param cube: @return: @ontology_type cube: Cube """ for mug, h in self_state.isOwnedBy.items(): if h == self_name: return [[("hu...
bd4ce7c1e6f935ff8cbaa266d1b10897ab7ea654
629,895
def percentage(value): """Converts a fraction to a percentage.""" return '{:.0f}'.format(value * 100)
c4ae32eafec50f52b4021fc1a404295558a45d83
629,896