content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import requests import json def fetch_entanglement_graph(host="proxy", port=8000, path="/dict"): """ Fetches the entanglement graph from a running instance of playcloud. Args: host(str, optional): Host of the playcloud instance port(int, optional): Port number of the listening playcloud instance path(str, optional): Path of the endpoint on the playcloud server that dumps the graph Returns: dict: The entanglement graph """ url = "http://{:s}:{:d}{:s}".format(host, port, path) req = requests.get(url) assert req.status_code == 200 graph = json.loads(req.text) return graph
6e5c522405d01809989ce354acce3816d65ca879
335,274
def format_BUILD_MAP_UNPACK_WITH_CALL(oparg): """The lowest byte of oparg is the count of mappings, the relative position of the corresponding callable f is encoded in the second byte of oparg.""" rel_func_pos, count = divmod(oparg, 256) return ("%d mappings, function at %d" % (count, count + rel_func_pos))
b7176dcdd412aa64cf73e055cc9f0f3efce3f6bf
576,628
def aggregate_norm_comparison(factor_df, M_matrix): """ Aggregate factor information with cosine similarity matrix, which contains the true norm. """ return factor_df.groupby(['kernel', 'factor', 'iter']).agg('sum').merge( M_matrix.set_index(['kernel', 'factor', 'iter']), left_index=True, right_index=True, suffixes=('_linear', '_factor') )
060dcd08e2147be49d40d04af802daf3286cfe02
99,018
def find_threshold_crossings(arr, _threshold): """ Find all indices at which a threshold is crossed from above and from below in an array. Used for finding indices to compute ap widths and half widths. """ #print("threshold = {}".format(_threshold)) ups = [] downs = [] for i, _ in enumerate(arr[:-1]): # Don't iterate on last element # Get crossings of threshold from below if arr[i] < _threshold: if arr[i+1] >= _threshold: ups.append(i) # Get crossings of threshold from above if arr[i] > _threshold: if arr[i+1] <= _threshold: downs.append(i) return ups, downs
907a6ab3f1c8e058f968064765168e399e497b4a
259,307
def process_cutoff_line(list_): """Process a cutoff line.""" cutoffs = [] for i in [1, 2]: if list_[i] == 'None': cutoffs += [None] else: cutoffs += [float(list_[i])] return cutoffs
4e7c22a5304901b35edddd2e27ccb11714186f02
332,549
def seven_seg(a: bool, b: bool, c: bool, d: bool, e: bool, f: bool, g: bool) -> str: """Given a set of 7 boolean values corresponding to each segment, returns a string representation of a 7 segment display. The display looks like this: _ |_| |_| And the mapping of the booleans is as follows: a fgb edc """ return ( (" _" if a else "") + "\n" + ("|" if f else " ") + ("_" if g else " ") + ("|" if b else "") + "\n" + ("|" if e else " ") + ("_" if d else " ") + ("|" if c else "") + "\n")
49ca9e4c3a98a7ac64744a968e90efa58a3f44a0
381,614
def truncate(s, eps): """ Find the smallest k such that sum(s[:k]**2) \geq 1-eps. """ mysum = 0.0 k=-1 while (mysum < 1-eps): k += 1 mysum += s[k]**2 return k+1
fc9b5984316e969961b496fd54425e4f52f025ff
704,032
def from_bytes(array: bytes) -> str: """Decodes the string from UTF-8.""" return array.decode("utf-8")
4782da935e9d849105c4116dabbb21abd67e047f
381,883
def bounds_check(values, lower, upper): """Perform a simple bounds check on an array. :param values: an array of values. :param lower: the lower bound of the valid range. :param upper: the upper bound of the valid range. :type values: array[float] :type lower: float :type upper: float :returns: mask - a boolean array that is True when values is between lower and upper. :rtype: array[bool] """ mask = (values >= lower) & (values <= upper) return mask
c99882cdbf33116e29ee80b9bd065893e236e076
424,085
def government_furloughing(t, states, param, t_start_compensation, t_end_compensation, b_s): """ A function to simulate reimbursement of a fraction b of the income loss by policymakers (f.i. as social benefits, or "tijdelijke werkloosheid") Parameters ---------- t : pd.timestamp current date param: float initialised value of b t_start_compensation : pd.timestamp startdate of compensation t_end_lockdown : pd.timestamp enddate of compensation b_s: float fraction of lost labor income furloughed to consumers under 'shock' Returns ------- b: float fraction of lost labor income compensated """ if t < t_start_compensation: return param elif ((t >= t_start_compensation) & (t < t_end_compensation)): return b_s else: return param
2ed0cc447df832290b59eb048b09bb8dd8373438
332,309
def handle_store(event): """Handle a C-STORE request event.""" # Decode the C-STORE request's *Data Set* parameter to a pydicom Dataset ds = event.dataset # Add the File Meta Information ds.file_meta = event.file_meta # Save the dataset using the SOP Instance UID as the filename ds.save_as(ds.SOPInstanceUID, write_like_original=False) # Return a 'Success' status return 0x0000
4bd11106e1bb7b2c17931a710daa7133d5e8e9e3
547,631
def check_parens(string, pairs="()"): """ Check a string for non-matching braces or other character pairs and return a list of failures, or an empty set if everything is OK. `if check_parens(string, brackets):` is a good way to find bad brackets in a string. Pairs should be a string of paired braces, such as "[]" or "{}[]<>()". If `pairs` is excluded, only checks parentheses. Checking pairs of quotes (where the opening and closing character is the same) is not supported; every character in `pairs` should be unique. The return value is a set of tuples of (character, depth, position). The function immediately returns with the first dangling closing character it finds, with the position it was found at in the string and a depth of -1. If the end of the string is reached and there are still dangling contexts, the set may have multiple values with varying positive depth for each opening character, but the position will be None. >>> check_parens("()") == set() True >>> check_parens("((()())())") == set() True >>> check_parens("[<><>]", "[]<>") == set() True >>> check_parens("))asdf]", "[]") == {(']', -1, 6)} True >>> check_parens("{{{(", "{}()") == {('(', 1, None), ('{', 3, None)} True >>> check_parens(check_parens.__doc__, "{}") == {('{', 5, None)} True >>> check_parens(check_parens.__doc__, "<>") == {('>', -1, 960)} True """ begins = {} ends = {} counters = [] it = iter(pairs) for begin, end in zip(it, it): begins[begin] = len(counters) ends[end] = len(counters) counters.append(0) for position, ch in enumerate(string): if ch in begins: counters[begins[ch]] += 1 elif ch in ends: index = ends[ch] counters[index] -= 1 if counters[index] < 0: return {(ch, -1, position)} return { (begin, counters[ct_idx], None) for begin, ct_idx in begins.items() if counters[ct_idx] }
35b05bd2560f1252f04257919f9f50cdcda9b53a
416,656
def count_model_parameters(model): """Count trainable parameters of a given model Args: model(object): torch model object Returns: trainable_parameters(int): number of trainable parameters """ return sum(p.numel() for p in model.parameters() if p.requires_grad)
17b32f0e37f9f47fca4de17ee4cfc27cbaa12b02
71,667
def intfs_only(s1code): """Given s1code, keep only interfaces (.h); ignore implementations (.f90).""" return [(l, f, c) for l, f, c in s1code if f.endswith(".h")]
2e43d16d87aa7b427f58622d973229c082e9a67d
633,449
def reciprocal_rank(sort_data): """ calculate reciprocal rank If our returned result is 0, 0, 0, 1, 1, 1 The rank is 4 The reciprocal rank is 1/4 Args: sort_data: List of tuple, (score, gold_label); score is in [0, 1], glod_label is in {0, 1} Return: reciprocal rank """ sort_label = [x[1] for x in sort_data] assert 1 in sort_label reciprocal_rank = 1. / (1 + sort_label.index(1)) return reciprocal_rank
9217533c2ff1dcca83e44c28a7851c25932fbba0
465,464
import re def remove_numbers(tweet): """ Replaces all numbers in a tweet with the word 'number'. INPUT: tweet: original tweet as a string OUTPUT: tweet with all numbers removed """ words = re.split(r'\s+', tweet) new_words = [] for word in words: if bool(re.search(r'\d', word)): new_words.append('number') else: new_words.append(word) return ' '.join(new_words)
833d94513f5e845149f788494ff50ee929c7d36d
383,325
def add_local_pi_info(data, pi_id, pi_name, location): """ Take a dictionary of data read from a sensor and add information relating to the pi from which the data was being collected Returns a dictionary with the extra information """ if data is not None: data['location'] = location data['piname'] = pi_name data['piid'] = pi_id return data
f8243068c247a78b24cb03732279680f86ea9dff
322,100
def exclude(values, quality_flags=None): """ Return a timeseries with all questionable values removed. All NaN values will be removed first and then iff `quality_flag` is set (not 0) the corresponding values will also be removed. Parameters ---------- values : pandas.Series Timeseries values. quality_flags : pandas.DataFrame Timeseries of quality flags. Default is None. Returns ------- pandas.Series : Timeseries of values excluding non-quality values. """ # Missing values bad_idx = values.isna() # Handle quality flags if quality_flags is not None: consolidated_flag = quality_flags.any(axis=1) bad_quality_idx = (consolidated_flag != 0) bad_idx = bad_idx | bad_quality_idx return values[~bad_idx]
cc6ef9b69b035854fc3bd28873b49c4f6742e5ca
354,359
import requests import json def get_request(url): """Simple GET Request. Args: url (str): URL with parameters to GET request to. Returns: dict: Dictionary form of a JSON response. """ r = requests.get(url) return json.loads(r.text)
732d6cd54be1e56e610ebec2a07dcd046ed8dbf1
543,098
def get_unicode_code_points(string): """Returns a string of comma-delimited unicode code points corresponding to the characters in the input string. """ return ', '.join(['U+%04X' % ord(c) for c in string])
dada87ad2fef1948fd899fc39bd1abe7c105ac6c
690,854
def coords_to_float(coord): """Convert a latitude or longitude coordinate from a string to a float, taking into account N, E, S, W. For example, '48.2S' to -48.2 Parameters ---------- coord : str The string form of the coordinate Returns ------- float The coordinate in float form """ if coord != None: if str(coord)[-1] == 'N' or str(coord)[-1] == 'E': return float(str(coord)[:-1]) elif str(coord)[-1] == 'S' or str(coord)[-1] == 'W': # removes the letter from '48.2S' and puts a negative return float(str(coord)[:-1]) * -1 else: return coord else: return coord
2eafa12802cd1932ce54419414287f0a8ed0dac0
601,307
import base64 def encode_str_for_draft(input_str): """ Given a string, return UTF-8 representation that is then base64 encoded. """ if isinstance(input_str, str): binary = input_str.encode('utf8') else: binary = input_str return base64.b64encode(binary)
a8010bf9dfeed5d145dfb0ad81a4cc3bd34c6bad
504,696
def processing_lines( lines: list, skip_lines: list = ["# Databricks notebook source\n"] ): """Apply logic to transform databricks specific lines to jupyter lines. Args: lines (list): contains each line of code skip_lines (list, optional): Lines to be skipped. Defaults to ["# Databricks notebook source\n"]. Returns: [list]: logic processed lines """ # filter out specific databricks lines filtered_lines = [line for line in lines if line not in skip_lines] # replace the databricks command for new cell with line break which is for jupyter processed_lines = [ "#%%" if line == "# COMMAND ----------\n" else line for line in filtered_lines ] if processed_lines[0] == "\n": processed_lines.pop(0) return processed_lines
5760c97410a1bfa3f464ee88c471d1c6c6687013
497,936
def andTruthTable() -> None: """And truth table. Prints a truth table for the and operator. Returns: None. Only prints out a table. """ print(" _______________________________\n", "|A and B | Evaluates to:|\n", "|_______________|______________|\n", "|False and False| False |\n", "|False and True | False |\n", "|True and False | False |\n", "|True and True | True |\n", "|_______________|______________|\n") return None
2e10a431932c304c9720a1599db1ea3e26f14505
382,220
from typing import Tuple def get_classes(config: dict) -> Tuple[str, str]: """ Return human readable model and dataset classes from the given config. :param config: configuration dict :return: a tuple of (model.class, dataset.class) """ return config['model']['class'], config['dataset']['class']
db3e49052ba2ee22e2ae4ddb9b214af454abf5a4
544,470
def tuple_or_list(target): """Check is a string object contains a tuple or list If a string likes '[a, b, c]' or '(a, b, c)', then return true, otherwise false. Arguments: target {str} -- target string Returns: bool -- result """ # if the target is a tuple or list originally, then return directly if isinstance(target, tuple) or isinstance(target, list): return target try: target = eval(target) if isinstance(target, tuple) or isinstance(target, list): return target except: pass return None
f29d4685b8e8bbb0c7e5c800a34a226782cdc7ae
679,866
import math def _getOS(box1, box2): """Compute orientation similarity between two 3D boxes""" angle_diff = box1['rotation_y'] - box2['rotation_y'] return (1 + math.cos(angle_diff)) / 2
1d41444885df4aab208ea344405062f96e026334
299,352
def base32_decode(base32_value: str) -> int: """ Convert base32 string to integer Example 'A' -> 10 """ return int(base32_value, 32)
3abebc1d84830a016c8beb880a3aedb14838c428
619,177
def _is_correct_task(task: str, db: dict) -> bool: """ Check if the current data set is compatible with the specified task. Parameters ---------- task Regression or classification db OpenML data set dictionary Returns ------- bool True if the task and the data set are compatible """ if task == "classification": return db['NumberOfSymbolicFeatures'] == 1 and db['NumberOfClasses'] > 0 elif task == "regression": return True else: return False
49790d8e2b7a16ee9b3ca9c8bc6054fde28b3b6f
4,641
def get_weight_op(weight_schedule): """Returns a function for creating an iteration dependent loss weight op.""" return lambda iterations: weight_schedule(iterations)
c3f4a01159a6a4b3ed309bf094b1821a542ada32
23,137
def load_html(starthtml, endhtml): """Load beginning and ending HTML to go in outpul file""" start_html = starthtml.read() end_html = endhtml.read() return(start_html, end_html)
6b67d50b44d59c56d2df4246ed49fd9570b43f34
545,437
def nice_number(num): """If num can be an int, make it an int.""" if int(num) == num: return int(num) else: return num
97e45021519b39c44f540d96204373a6d59690d0
564,180
import inspect def get_stack_level() -> int: """ Return the stack level in Python. """ return len(inspect.stack(0))
a6f66f9e548023a3536616df69cf75c24294a694
521,674
def get_smallest_divs(soup): """Return the smallest (i.e. innermost, un-nested) `div` HTML tags.""" return [ div for div in soup.find_all("div") if not div.find("div") and div.text.strip() ]
f3181c7f3cd5b4c82f060780e23dcf34028316e8
47,281
def namespace(api, name, description): """Return namespace name for the given module.""" return api.namespace( '/'.join(name.split('.')[3:]).replace('_', '-'), description=description )
0694a157a0d2d2c4e3aec83076c76f04fd5336d8
523,631
import random def get_tweet(in_file): """ Open up input file read all quotes into a list, return random quote """ possible = [] for tweet in in_file.read().split("DELIM"): possible.append(tweet.strip()) return random.choice(possible)
bff12f0ccf5d0a8d5297456b67eac861afc6d10b
244,060
def check_cloud(path: str): """Naive check to if the path is a cloud path""" if path.startswith("s3:"): return True return False
f622fd3b479a2bca7e2ed405c861a5ae528b65a8
572,298
from typing import List def has_class(rr_list: List) -> bool: """Determines if the list contains a resource class.""" return any(r_class in rr_list for r_class in ('IN', 'CS', 'CH', 'HS'))
f26be46349c9f586f3270193487df61963570bb2
303,209
import re def cleanse_column(column): """ Template function for cleansing column names. Columns beginning with / or _ will have these removed. Columns containing spaces, /, (, ), - will be replaced with underscores. Multiple _ in a row will be replaced with a single _ :param column: String column name from source system :return: Cleansed column name """ column = column.lower() if column.startswith("/"): column = column.replace("/", "", 1) if column.startswith('_'): column = column.replace('_', "", 1) # Replace all /,-,(,), blank spaces with _ p = re.compile(r'(/|-|\(|\)|\s)') column = p.sub('_', column) # After replacing values find any multiple _ and replace them with a single underscore p = re.compile(r'(_{2,})') column = p.sub('_', column) return column
7979c3a324500c5aa3a8e361d6cbf5efcd867334
340,913
def invert_dictionary(dictionary): """Invert a dictionary. NOTE: if the values of the dictionary are not unique, the function returns the one of the mappings Args: dictionary (dict): A dictionary Returns: dict: inverted dictionary Examples: >>> d = {"a": 1, "b": 2} >>> d_inv = invert_dictionary(d) >>> json.dumps(d_inv, sort_keys=True) '{"1": "a", "2": "b"}' """ return {v: k for k, v in dictionary.items()}
28f3aef9b4f377f40cb68f87277d34f2e2817eda
598,348
def collect_reducer_set(values): """Return the set of values >>> collect_reducer_set(['Badger', 'Badger', 'Badger', 'Snake']) ['Badger', 'Snake'] """ return sorted(list(set(values)))
c83e87711cf2f6543c3658493d9feb7f6d5f080a
364,936
def set_kwargs_from_dflt(passed: dict, dflt: dict) -> dict: """Updates ++passed++ dictionary to add any missing keys and assign corresponding default values, with missing keys and default values as defined by ++dflt++""" for key, val in dflt.items(): passed.setdefault(key, val) return passed
3c0555c3276a20adbbc08f1a398605c6e6d37bd9
658,608
def _VarsToLines(variables): """Converts |variables| dict to list of lines for output.""" if not variables: return [] s = ['vars = {'] for key, tup in sorted(variables.iteritems()): hierarchy, value = tup s.extend([ ' # %s' % hierarchy, ' "%s": %r,' % (key, value), '', ]) s.extend(['}', '']) return s
238db698f6027acc7855212b531f1c79a3ac137d
172,225
def register(name: str, registry: dict): """ Register a class or a function with name in registry. For example: CLS = {} @register("a", CLS) class A(object): def __init__(self, a=1): self.a = a cls_a = CLS['a'](1) In this way you can build class A given string 'a'. Args: name (str): the registering name of this class. registry (dict): a dict to register classess. """ def register_cls(cls): if name in registry: raise KeyError("{0} has already been registered!") else: registry[name] = cls return cls return register_cls
b1238babbbbc986cee1b1eaae6468ab027081467
647,197
def yesno(ans): """Convert user input (Yes or No) to a boolean""" ans = ans.lower() if ans == 'y' or ans == 'yes': return True else: return False
15f74a66ae82742cf74254db7f3dc1a6682dc38c
114,736
def step2_form_factory(mixin_cls, entry_form_class, attrs=None): """ Combines a form mixin with a form class, sets attrs to the resulting class. This is used to provide a common behavior/logic for all wizard content forms. """ if attrs is None: attrs = {} # class name is hardcoded to be consistent with the step 1 form. # this is meant to be used only in the context of the form wizard. class_name = 'WizardStep2Form' meta_class = type(entry_form_class) FormClass = meta_class(class_name, (mixin_cls, entry_form_class), attrs) return FormClass
5f51919f042642718815809d05493d55593627bd
347,628
def _join_type_and_checksum(type_list, checksum_list): """ Join checksum and their correlated type together to the following format: "checksums": [{"type":"md5", "checksum":"abcdefg}, {"type":"sha256", "checksum":"abcd12345"}] """ checksums = [ { "type": c_type, "checksum": checksum, } for c_type, checksum in zip(type_list, checksum_list) ] return checksums
7f09ee72c6f51ad87d75a9b5e74ad8ef4776323f
706,195
import logging def _loggerBySpec(logger): """Logger maybe a logger, logger name, or None for default logger, returns the logger.""" if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) return logger
f5a71eccdd53a30c725b602046effecb558738e6
404,955
def validate_token(token): """ Just a utility method that makes sure provided token follows a 'Bearer token' spec :param token: A JWT token to be validated :return: The token itself, None if not valid :rtype: str """ if token: # Token should be string with 'Bearer token' tokens = token.split(' ') # Make sure first token is Bearer if (len(tokens) == 2) and (tokens[0] == 'Bearer'): # Make sure token can be splitted by 3 using '.' elements = tokens[1].split('.') if len(elements) == 3: return tokens[1] else: raise Exception else: raise Exception else: return None
cbeb8733bba3a8c77a635e160e7b3ce0cf7323b6
207,218
from datetime import datetime import re def parse_nowcast(text): """ Parses the immediate aurora forecast. http://services.swpc.noaa.gov/text/aurora-nowcast-map.txt """ time = datetime.max # forecast time remains far in the future if time not found in the file data = [] for line in map(lambda l: l.decode('utf_8').strip(), text): if line: if not line.startswith('#'): for p in line.split(): data.append(int(p) if p != 'n/a' else 0) else: m = re.search('^# Product Valid At: (.*)', line) if m: time = datetime.strptime(m.group(1), '%Y-%m-%d %H:%M') return data, time
64255c019b89e62766eccb109b0320bbaa3d3f1d
232,973
def is_alarms_table(table): """ True if table of alarms notifications """ phrase = 'alarm' return phrase == table.short_title[:len(phrase)].lower()
9d6d2d5ff2bb34fd834ce57262b1f740aa28b023
606,547
from datetime import datetime def get_time_range(delta): """Return time range by delta.""" end = datetime.now().timestamp() start = end - delta return start, end
402c98aea6e961af0d8756be0c4833225468c562
311,121
def postprocess_data(raw_data, decoded): """ Remove generation artifacts and postprocess outputs :param raw_data: loaded data :param decoded: model outputs """ raw_data['target'] = [x.replace('\n', ' ') for x in raw_data['target']] raw_data['decoded'] = [x.replace('<n>', ' ') for x in decoded] return [dict(zip(raw_data, t)) for t in zip(*raw_data.values())]
1de79a3e6ef1e3d253f94b327c4bfde144d993e9
507,595
from typing import List import logging def is_method(string_method: str, methods: List[str]) -> bool: """ Test if string_method is a method in methods :param string_method: String to test :type string_method: string :param methods: list of available methods :type methods: list of strings :returns: True if string_method a method and False otherwise :rtype: bool """ if string_method in methods: return True logging.error('% is not in available methods : ', string_method + ', '.join(methods)) return False
f897c06320f67cd1dfcdcc294857fee1a5429e48
419,298
import socket def port_check(host, port, timeout=2): """ Perform a basic socket connect to 'host' on 'port'. Args: host: String of the host/ip to connect to port: integer of the port to connect to on 'host' timeout: integer indicating timeout for connecting. Default=2 Returns: Boolean whether the connection was successful or now """ skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) skt.settimeout(timeout) try: skt.connect((host, int(port))) skt.shutdown(socket.SHUT_RDWR) return True except Exception: ##pylint: disable=broad-except return False finally: skt.close()
743738cc2ccb712207a9df3889834c52a491cb45
527,180
def get_name_arg(argd, *argnames, default=None): """ Return the first argument value given in a docopt arg dict. When not given, return default. """ val = None for argname in argnames: if argd[argname]: val = argd[argname].lower().strip() break return val if val else default
df0e43032c99df127030d59b3d8393a1c82e60cd
231,968
def ebc_to_srm(ebc: float) -> float: """ Convert from European Brewing Convention (EBC) color system to Standard Reference Method (SRM) color system. """ return ebc / 1.97
cea03fa3688e5a9a23431e7802b8fe510c089f72
213,940
from typing import Iterable def check_all_dicts(iterable_dict: Iterable[dict]): """Check if Iterable contains all dictionaries Args: iterable_dict (Iterable[dict]): Iterable of dictionaries """ # Check if dict def check_dict(d): return isinstance(d, dict) # Check if all instances are type dict, return True or False all_dict = all(map(check_dict, iterable_dict)) # print(all_dict) if not all_dict: raise BaseException("Iterable has mixed types, expected Iterable[dictionaries]") return True
0e87989d600d303e9bdadf04725c398841bcd214
30,839
def replicaset_config(client): """ Return the replicaset config document https://docs.mongodb.com/manual/reference/command/replSetGetConfig/ """ rs = client.admin.command('replSetGetConfig') return rs
5d2b3e2801fa96b6186a24edb00d849285dd9045
166,900
def clog2(x): """Ceiling log 2 of x. >>> clog2(0), clog2(1), clog2(2), clog2(3), clog2(4) (0, 0, 1, 2, 2) >>> clog2(5), clog2(6), clog2(7), clog2(8), clog2(9) (3, 3, 3, 3, 4) >>> clog2(1 << 31) 31 >>> clog2(1 << 63) 63 >>> clog2(1 << 11) 11 """ x -= 1 i = 0 while True: if x <= 0: break x = x >> 1 i += 1 return i
e3cceb918d048fd796685fc43850d93369f82ef2
95,235
def nameAndVersion(aString): """Splits a string into the name and version number. Name and version must be seperated with a hyphen ('-') or double hyphen ('--'). 'TextWrangler-2.3b1' becomes ('TextWrangler', '2.3b1') 'AdobePhotoshopCS3--11.2.1' becomes ('AdobePhotoshopCS3', '11.2.1') 'MicrosoftOffice2008-12.2.1' becomes ('MicrosoftOffice2008', '12.2.1') """ for delim in ('--', '-'): if aString.count(delim) > 0: chunks = aString.split(delim) vers = chunks.pop() name = delim.join(chunks) if vers[0] in '0123456789': return (name, vers) return (aString, '')
79b5680c998313260f6f64bddc2ff9ee236453fd
408,481
import unicodedata import re def text_to_slug(value, joiner="-"): """ Normalize a string to a "slug" value, stripping character accents and removing non-alphanum characters. A series of non-alphanumeric characters is replaced with the joiner character. """ # Strip all character accents: decompose Unicode characters and then drop combining chars. value = "".join( c for c in unicodedata.normalize("NFKD", value) if not unicodedata.combining(c) ) # Replace all remaining non-alphanumeric characters with joiner string. Multiple characters get collapsed into a # single joiner. Except, keep 'xn--' used in IDNA domain names as is. value = re.sub(r"[^A-Za-z0-9.]+(?<!xn--)", joiner, value) # '-' in the beginning or end of string looks ugly. return value.strip(joiner)
dad52fc9e9a7781125d3c08495d421c3daa3750a
556,593
def qualified_column(column_name: str, alias: str = "") -> str: """ Returns a column in the form "table.column" if the table is not empty. If the table is empty it returns the column itself. """ return column_name if not alias else f"{alias}.{column_name}"
9920d71e94c0e17bd7a5ce5d0f5c4fabdacfab5e
124,197
def includes(collection, sought, start=None): """Is sought in collection, starting at index start? Return True/False if sought is in the given collection: - lists/strings/sets/tuples: returns True/False if sought present - dictionaries: return True/False if *value* of sought in dictionary If string/list/tuple and `start` is provided, starts searching only at that index. This `start` is ignored for sets/dictionaries, since they aren't ordered. >>> includes([1, 2, 3], 1) True >>> includes([1, 2, 3], 1, 2) False >>> includes("hello", "o") True >>> includes(('Elmo', 5, 'red'), 'red', 1) True >>> includes({1, 2, 3}, 1) True >>> includes({1, 2, 3}, 1, 3) # "start" ignored for sets! True >>> includes({"apple": "red", "berry": "blue"}, "blue") True """ if isinstance(collection, dict): return sought in collection.values() if start is None or isinstance(collection, set): return sought in collection return sought in collection[start:]
a786b7190cd684b4fae780edf9113a077ab9f12a
574,475
def im_fits_path(source, band, epoch, stoke, base_path=None): """ Function that returns path to im-file for given source, epoch, band and stokes parameter. :param base_path: (optional) Path to route of directory tree. If ``None`` then use current directory. (default: ``None``) """ return base_path + source + '/' + epoch + '/' + band.upper() + '/im/' +\ stoke.upper() + '/'
33e52dcb28fd98e290d3546e44208fbb9665f6a8
57,856
import importlib def class_name_to_type(classname): """ Turns the class name into a type. :param classname: the class name to convert (a.b.Cls) :type classname: str :return: the type :rtype: type """ p = classname.split(".") m = ".".join(p[:-1]) c = p[-1] return getattr(importlib.import_module(m), c)
3cf11ff27fb41f5fb2b65084d60a518f0965a741
319,440
def addDegrees(heading, change): """ Calculate a new heading between 0 and 360 degrees :param heading: Initial compass heading :param change: Degrees to add :return: New heading between 0 and 360 degrees """ heading += change return heading % 360
3af817cefb867706d4fd586e13a92b84b04f80b8
304,568
def complex_to_coord(num, flip=600): """ Transform a complex number to pygame coordinate. Parameters ---------- num : complex The complex number to transformm. flip : int, optional The height of the drawing, or the height of the original pygame window. That is, the maximum value that num.complex can have. Used to flip the coordinate over the x-axis to comply with how the pygame coordinate system works. The default is 600. Returns ------- x : float The x-coordinate. y : float The y-coordinate. """ x = num.real y = flip - num.imag return (x,y)
3d537f81f368db38f458f755a466c958c1c8150a
465,277
import math def mean(data): """ Calculates the mean of a data set Args: data: the list with the data """ n = len(data) if (n > 0) : result = math.fsum(data) / n return result
37af41822db8596c19b9cf3a3f97c96ad1cdf49b
144,707
def first4_last4_every_other_removed(seq): """With the first and last 4 items removed, and every other item in between""" return seq[4:-4:2]
8e12112d97f7be2a50ecd6159f1295d100809f67
495,455
import re def _check_if_item_allowed(item_name, allow_patterns, disallow_patterns): """ Check if an item with ``item_name`` is allowed based on ``allow_patterns`` and ``disallow_patterns``. Parameters ---------- item_name: str Name of the item. allow_patterns: list(str) Selected item should match at least one of the re patterns. If the value is ``[None]`` then all items are selected. If ``[]``, then no items are selected. disallow_patterns: list(str) Items are deselected based on re patterns in the list: if an item matches at least one of the patterns, it is deselected. If the value is ``[None]`` or ``[]`` then no items are deselected. Returns ------- boolean Indicates if the item is permitted based on ``allow_patterns`` and ``disallow_patterns``. """ item_is_allowed = False if allow_patterns: if allow_patterns[0] is None: item_is_allowed = True else: for pattern in allow_patterns: if re.search(pattern, item_name): item_is_allowed = True break if item_is_allowed: if disallow_patterns and (disallow_patterns[0] is not None): for pattern in disallow_patterns: if re.search(pattern, item_name): item_is_allowed = False break return item_is_allowed
6a14239913140130eb8ce0d12a797039a7625172
43,394
import fnmatch def _match_in_cache(cache_tree, list_of_names): """ :type cache_tree: defaultdict :description cache_tree: a defaultdict initialized with the tree() function. Contains names of entries in the kairosdb, separated by "." per the graphite convention. :type list_of_names: list :description list_of_names: list of strings, in order, that will be sought after in the cache tree. :rtype: list :return: A list of matches, possibly empty. Given a cache_tree, and a prefix, returns all of the values associated with that prefix, that is, the keys that reside under the prefix. """ head_item = list_of_names[0] # print "head_item is {0}".format(head_item) head_item_matches = [ m for m in cache_tree.keys() if fnmatch.fnmatch(m, head_item) ] if head_item not in cache_tree.keys(): # print "A" return [] # Empty List to signify we're done here elif len(list_of_names) == 1: # print "B" return cache_tree[head_item].keys() else: # print "C" tail_list = list_of_names[1:] return _match_in_cache(cache_tree[head_item], tail_list)
e559125f4b62a87956e0d30f5d8c3e4b2c7abef8
26,956
def get_corresponding_letter(index, sentence): """ Get the letter corresponding to the index in the given sentence :param index: the wanted index. :param sentence: the reference sentence. :return: the corresponding letter if found, 'None' otherwise. """ if index < len(sentence.letters): return sentence.letters[index] else: return None
4bc6df4228d2e8fc9fdd7ce2791c33d5f2a96257
673,829
def calDensityIG(MW, CoSp): """ calculate: density of ideal gas (IG) [kg/m^3] args: MW: molecular weight [kg/mol] CoSp: concentration species [mol/m^3] """ try: # density den = MW*CoSp return den except Exception as e: pass
34fa96a3425975e2d80ddbe24753148746a7ea67
218,694
def nested_select(d, v, default_selected=True): """ Nestedly select part of the object d with indicator v. If d is a dictionary, it will continue to select the child values. The function will return the selected parts as well as the dropped parts. :param d: The dictionary to be selected :param v: The indicator showing which part should be selected :param default_selected: Specify whether an entry is selected by default :return: A tuple of two elements, the selected part and the dropped part Examples: >>> person = {'profile': {'name': 'john', 'age': 16, 'weight': 85}, \ 'relatives': {'father': 'bob', 'mother': 'alice'}} >>> nested_select(person, True) ({'profile': {'name': 'john', 'age': 16, 'weight': 85}, 'relatives': {'father': 'bob', 'mother': 'alice'}}, {}) >>> nested_select(person, {'profile': False}) ({'relatives': {'father': 'bob', 'mother': 'alice'}}, {'profile': {'name': 'john', 'age': 16, 'weight': 85}}) >>> nested_select(person, {'profile': {'name': False}, 'relatives': {'mother': False}}) ({'profile': {'age': 16, 'weight': 85}, 'relatives': {'father': 'bob'}}, {'profile': {'name': 'john'}, 'relatives': {'mother': 'alice'}}) """ if isinstance(v, dict): assert isinstance(d, dict) choosed = d.__class__() dropped = d.__class__() for k in d: if k not in v: if default_selected: choosed.setdefault(k, d[k]) else: dropped.setdefault(k, d[k]) continue if isinstance(v[k], dict): assert isinstance(d[k], dict) child_choosed, child_dropped = nested_select(d[k], v[k]) if child_choosed: choosed.setdefault(k, child_choosed) if child_dropped: dropped.setdefault(k, child_dropped) else: if v[k]: choosed.setdefault(k, d[k]) else: dropped.setdefault(k, d[k]) return choosed, dropped else: other = d.__class__() if isinstance(d, dict) else None return (d, other) if v else (other, d)
84aa16adfb324fef8452966087cbf446d57893d2
11,575
def verify_user_prediction(user_inputs_dic: dict, correct_definition_dic: dict): """ Verifies user prediction json against correct json definition returns true if correct format, false if not """ if user_inputs_dic.keys() != correct_definition_dic.keys(): return False for user_key, user_value in user_inputs_dic.items(): possible_values = correct_definition_dic[user_key].keys() if user_value not in possible_values: return False return True
de1d2b579ab312929f64196467a3e08874a5be42
14,735
import codecs def hex(b): """Convert the given bytes to hexadecimal string representation. Parameters ---------- b : bytes The byte string to convert Returns ------- str Hexadecimal string """ return codecs.encode(b, "hex").decode("ascii")
0aa07627e97474ffa9af259197b6c5ff4042940a
426,158
import math def rad_to_deg(r): """Radians to degrees """ return r * 180.0 / math.pi
d993a2ee9549af0d629d107015f0cd86ca8854ab
470,229
import uuid def build_request_body(method, params): """Build a JSON-RPC request body based on the parameters given.""" data = { "jsonrpc": "2.0", "method": method, "params": params, "id": str(uuid.uuid4()) } return data
372df70bd17e78f01de5f0e537988072ac9716cc
699,892
from typing import Iterable from typing import Union from pathlib import Path from typing import Optional import re from typing import Collection from typing import Set def find_files( paths: Iterable[Union[str, Path]], include: Optional[re.Pattern], excludes: Optional[Collection[re.Pattern]], ) -> Set[Path]: """ Recurse any directories specified in 'paths', and include any files specified. For recursive searches, only include paths which match 'include'. For all paths, exclude any which match 'exclude'. """ final_paths: Set[Path] = set() for path in paths: p = Path(path) if p.is_dir(): final_paths.update( x for x in p.glob("**/*") if (not include or include.search(str(x))) ) elif p.is_file(): final_paths.add(Path(p)) for exclude in excludes or []: final_paths = {x for x in final_paths if not exclude.search(str(x))} return final_paths
15ebdf322ad05e6e21d2c2878e2591533befef82
312,132
def is_query_parameter_value(value) -> bool: """ Checks if a value is a query parameter value. :param value: The value to check. :return: True if the value is a query parameter value, False if not. """ # Must be a string or list of strings return isinstance(value, str) or (isinstance(value, list) and all(map(lambda sub: isinstance(sub, str), value)))
8e5b3b67e352532056b47a316b010111820aa806
308,224
import torch def concat_and_flatten(items): """ Concatenate feature vectors together in a way that they can be handed into a linear layer :param items A list of ag.Variables which are vectors :return One long row vector of all of the items concatenated together """ return torch.cat(items, 1).view(1, -1)
9dcbcbb21bcc995abd641feec6d227543e08c082
247,526
def parse_unit(unit): """Parse a unit string Parameters ---------- unit : str String describing a unit (e.g., 'mm') Returns ------- factor : float Factor that relates the base unit to the parsed unit. E.g., `parse_unit('mm')[0] -> 1e-3` baseunit : str Physical unit without the prefix. E.g., `parse_unit('mm')[1] -> 'm'` """ if unit is None or len(unit) == 0: return 1. unit_type = unit[-1] unit_scale = unit[:-1] mu1 = '\u00B5' mu2 = '\u03BC' unit_map = {'Y': 1E24, 'Z': 1E21, 'E': 1E18, 'P': 1E15, 'T': 1E12, 'G': 1E9, 'M': 1E6, 'k': 1E3, 'h': 1e2, 'da': 1E1, 'd': 1E-1, 'c': 1E-2, 'm': 1E-3, mu1: 1E-6, mu2: 1E-6, 'u': 1E-6, 'n': 1E-9, 'p': 1E-12, 'f': 1E-15, 'a': 1E-18, 'z': 1E-21, 'y': 1E-24} if len(unit_scale) == 0: return 1., unit_type else: return unit_map[unit_scale], unit_type
0ada612f10ac515651d6713e4a30cd6be4341b0a
595,331
def getTreeString(x, y, z, numLogs): """ Returns a Malmo string to use in the mission XML to create a tree. """ leavesHeight = y + 4 treeHeight = y + numLogs return """ <DrawingDecorator> <DrawSphere x="{x}" y="{yLeaves}" z="{z}" radius="3" type="leaves" /> <DrawLine x1="{x}" y1="{y}" z1="{z}" x2="{x}" y2="{yTreeHeight}" z2="{z}" type="log" /> </DrawingDecorator>""".format(x=x, y=y, z=z, yLeaves=leavesHeight, yTreeHeight=treeHeight)
204680a811a98843f38abcdf028387e84277add2
537,936
import json def nfa_json_importer(input_file: str) -> dict: """ Imports a NFA from a JSON file. :param str input_file: path+filename to JSON file; :return: *(dict)* representing a NFA. """ file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet] # value [Set of arriving states in states] for p in json_file['transitions']: transitions.setdefault((p[0], p[1]), set()).add(p[2]) nfa = { 'alphabet': set(json_file['alphabet']), 'states': set(json_file['states']), 'initial_states': set(json_file['initial_states']), 'accepting_states': set(json_file['accepting_states']), 'transitions': transitions } return nfa
a821e29a6e02b14f381e737550ac00c61da9509c
525,423
def calc_time_factor(start_breach, end_breach): """ calculates the fraction of island height to be reduced during simulation :param start_breach: start time (island should be inundated here) :param end_breach: end time :return: return the timing ratio """ total_time = abs(end_breach - start_breach) num_time_steps = total_time / 7.5 # current run timesteps every 7.5 seconds or so tf = 1 / num_time_steps # calculate how many steps it takes to reach 100% breach return tf
c57e91445674dce3f6ec58dd63c809d374cb84ad
361,729
def _replace_reserved_char(s): """Return the given string with all its brackets and # replaced by _.""" for c in '()[]{}#': s = s.replace(c, '_') return s
32b74b3a36577378ca23e8982e001595599f4c48
614,456
def after_request(response): """Define acceptable response headers.""" response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,POST') return response
709061cd1bae2dad04cc34170d745261d0223f1e
649,305
def merge_2_dictionnaries(dict1, dict2): """ Merge two dictionnaries together by adding the values """ result = dict1 for k, v in dict2.items(): result[k] = (result.get(k) or 0) + v return result
ca4e1834460bb27374f74532bde59627f9e99d51
245,738
def keys_as_sorted_list(dict): """ sorted keys of the dict :param dict: dict input :return: sorted key list """ return sorted(list(dict.keys()))
db8ba319724115a5b410eb7bad2847ef23d2977e
339,862
def nop(arch = None): """Returns a no operation instruction.""" if arch in ['i386', 'amd64']: return 'nop' elif arch in ['arm', 'thumb']: return 'orr r4, r4, r4' elif arch in ['mips']: return 'or $ra, $ra, $ra'
6afb0e4bcfff5e4cf34bd7a02d74e65bf7635473
288,380
def get_version(client): """Return ES version number as a tuple""" version = client.info()['version']['number'] return tuple(map(int, version.split('.')))
c4a5f3d3e4e6326b6a7f5eed20d3e3e5b3c408c8
60,677
def chunkify(lst, n): """ e.g. lst = range(13) & n = 3 return = [[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]] """ return [lst[i::n] for i in range(n)]
641faa77c32934c4d110357f47a2ce96ad687faa
209,554
def vsum(pos, delta): """Sums two vectors in tuple/list format""" return (pos[0]+delta[0],pos[1]+delta[1])
0a10a7cea9d3bfa9f939ed392c6c4aa36e1de589
390,627
def _split_header(code): """Extract the Implectus header from a generated code string.""" lines = code.splitlines() assert len(lines) > 3 assert lines[0].startswith("# # Autogenerated"), "Missing header" assert lines[1].startswith("# This file was"), "Missing header" assert lines[2].startswith("# edit `"), "Missing header" assert not lines[3], "Missing gap" return "\n".join(lines[:3]), "\n".join(lines[4:])
77873a071c747dff96f36f11514a8e1b8693daa9
230,980
import torch def mask_fill( fill_value: float, tokens: torch.Tensor, embeddings: torch.Tensor, padding_index: int, ) -> torch.Tensor: """ Function that masks embeddings representing padded elements. :param fill_value: the value to fill the embeddings belonging to padded tokens. :param tokens: The input sequences [bsz x seq_len]. :param embeddings: word embeddings [bsz x seq_len x hiddens]. :param padding_index: Index of the padding token. """ padding_mask = tokens.eq(padding_index).unsqueeze(-1) return embeddings.float().masked_fill_(padding_mask, fill_value).type_as(embeddings)
e89e2a0f807765694ff68109b7d1a5adfec0297b
670,567
import re def convert_to_lowercase_and_underscore(name): """ The Shared Memory is in CamelCase - convert the names to Python Standard lowercase with underscores http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case I have already changed the names in sim_info.py, so this function is no longer used """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
268e643e476c754b1bd785967e909d90351d5dee
558,403
import importlib def import_module(libname): """ Function import module using string representation """ return importlib.import_module(libname)
1fe10e5c655a363a45ea742e33dd9d23a221b178
120,350
def drop_info(df): """Takes a dataframe and drop rows whitout an splitted `info` length diferrent than four. Parameters ---------- df : The dataframe to search. Returns ------- The dataframe processed. """ before = df.shape print(f'Shape before dropping: {before}') # df.dropna(subset=['info']) df = df[df['info'].str.split(',').apply(len) == 4] after = df.shape print(f'Shape after dropping: {after}\n' + '-' * 10) print(f'Dropped: {before[0] - after[0]} rows\n') return df
fb18f874eaf925c6651aa912009749806fc0b1f4
586,733
def document_metas_from_data(document_data, claimant): """ Return a list of document meta dicts for the given document data. Returns one document meta dict for each document metadata claim in document_data. Each dict can be used to init a DocumentMeta object directly:: document_meta = DocumentMeta(**document_meta_dict) :param document_data: the "document" sub-object that the client POSTed to the API as part of a new or updated annotation :type document_data: dict :param claimant: the URI that the browser was at when this annotation was created (the top-level "uri" field of the annotation) :type claimant: unicode :returns: a list of zero or more document meta dicts :rtype: list of dicts """ def transform_meta_(document_meta_dicts, items, path_prefix=None): """Fill document_meta_dicts with document meta dicts for the items.""" if path_prefix is None: path_prefix = [] for key, value in items.items(): keypath = path_prefix[:] keypath.append(key) if isinstance(value, dict): transform_meta_(document_meta_dicts, value, path_prefix=keypath) else: if not isinstance(value, list): value = [value] type_ = ".".join(keypath) if type_ == "title": # We don't allow None, empty strings, whitespace-only # strings, leading or trailing whitespaces, or empty arrays # in document title values. value = [v.strip() for v in value if v and v.strip()] if not value: continue document_meta_dicts.append( {"type": type_, "value": value, "claimant": claimant} ) items = {k: v for k, v in document_data.items() if k != "link"} document_meta_dicts = [] transform_meta_(document_meta_dicts, items) return document_meta_dicts
a7060fe7b17f06e6bbf4ea2748315fec7392fbe8
143,419