content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_experience_for_next_level(level: int) -> int: """Gets the amount of experience needed to advance from the specified level to the next one. :param level: The current level. :return: The experience needed to advance to the next level. """ return 50 * level * level - 150 * level + 200
d21b6e4bacccd9f9d79c5f7e71997027c306d545
587,020
def _m2m_rev_field_name(model1, model2): """Gets the name of the reverse m2m accessor from `model1` to `model2` For example, if User has a ManyToManyField connected to Group, `_m2m_rev_field_name(Group, User)` retrieves the name of the field on Group that lists a group's Users. (By default, this field is called `user_set`, but the name can be overridden). """ m2m_field_names = [ rel.get_accessor_name() for rel in model1._meta.get_fields() if rel.many_to_many and rel.auto_created and rel.related_model == model2 ] return m2m_field_names[0]
30f8b5d95b8e8741c227eeb8b0ffac6aea09c750
526,926
import math def mag_of(vals): """ Returns the magnitude of a list of vals by taking the square root of the sum of the square of the components. """ assert(type(vals) is list) return math.sqrt(sum([x*x for x in vals]))
cb4cf804241fe20edeaa0b8c8f4f02b381e04757
238,475
def per_capita(place_vals, place_pop, factor=1): """Calculate per capital stats for each place. Args: place_vals: a dictionary mapping each place to an observed value. place_pop: a dictionary mapping each place to its population for some year. factor: number of people in the per capita denominator. Default 1. Returns: dictionary of place to observed value per <factor> people. """ if factor: assert factor >= 1, 'Per capita factor must be greater than or equal to 1.' for dcid, val in place_pop.items(): if val < 0: raise ValueError('Population is for %s is %s' % (dcid, val)) place_vals = { dcid: factor * place_vals[dcid] / place_pop[dcid] for dcid in place_vals } return place_vals
1bb6fdb23e8305c8f961100812e4fb9c212b0061
541,901
import logging import pkgutil import importlib def page_loader(roots: list) -> dict: """ Reads page modules from subdirectories specified in the `roots` list, and returns them in a dictionary keyed by module.ROUTE. """ page_dict = {} for root in roots: for importer, package_name, _ in pkgutil.iter_modules([root]): full_package_name = "%s.%s" % (root, package_name) module = importlib.import_module(full_package_name) route = module.ROUTE logging.info(f'Page module "{package_name}" loaded at route "{route}"') if route in page_dict: raise RuntimeError( f'Page module "{package_name}" tried to load at already existing route "{route}"' ) page_dict[route] = module return page_dict
ddc992b67ae5b94510fc1c895f68ac6d7a61792d
429,300
def sat(Bars, Children): """ Arguments: Bars -- chocolate bars array Children-- children array Return: f -- flag. f=1 if the problem is satifiable, 0 Otherwise. S -- message satisfiable/not satisfiable Cp-- if there is an excess amount, create a "ghost" children to take up the excess units """ NB = sum(Bars) #Total number of available chocolate units NC = sum(Children) # Total number of requested chocolate units Cp= Children #initialize ng= len(Children) ex= NB-NC #excess units if ex == 0: S= "The problem is satisfiable" f=1 elif ex > 0: Cp = Children+[ex] # ass the "ghost" children if there is an excess supply ng= len(Cp) # Lenght of Cp. This is diffrent from -n- if there is a ghost S= "The problem is satisfiable" f=1 else : S="The problem is not satisfiable" # The problem cannot be satisfied if there is no enough supply f=0 return S, Cp, ng, f
e4369c300a2b9dbee78df5a02ebaea6b09cce0f5
503,129
def add_boundary_ummg(ummg: dict, boundary_points: list): """ Add boundary points list to UMMG in correct format Args: ummg: existing UMMG to augment boundary_points: list of lists, each major list entry is a pair of (lon, lat) coordinates Returns: dictionary representation of ummg """ formatted_points_list = [] for point in boundary_points: formatted_points_list.append({'Longitude': point[0], 'Latitude': point[1]}) # For GPolygon, add the first point again to close out formatted_points_list.append({'Longitude': boundary_points[0][0], 'Latitude': boundary_points[0][1]}) hsd = {"HorizontalSpatialDomain": {"Geometry": {"GPolygons": [ {'Boundary': {'Points': formatted_points_list}} ]} } } ummg['SpatialExtent'] = hsd return ummg
6274e3e04a73bbc42f33e89b46688c7f70c1ca26
659,443
from typing import Tuple from typing import Dict import re def _handle_compatibility(doc) -> Tuple[str, Dict[str, str]]: """Parse and remove compatibility blocks from the main docstring. Args: doc: The docstring that contains compatibility notes. Returns: A tuple of the modified doc string and a hash that maps from compatibility note type to the text of the note. """ compatibility_notes = {} match_compatibility = re.compile( r'[ \t]*@compatibility\(([^\n]+?)\)\s*\n' r'(.*?)' r'[ \t]*@end_compatibility', re.DOTALL) for f in match_compatibility.finditer(doc): compatibility_notes[f.group(1)] = f.group(2) return match_compatibility.subn(r'', doc)[0], compatibility_notes
24fe3a59e6df83dbb419eb3db199fc23341443ea
499,809
import random def random_choice(seq): """wrapper around random.choice that returns None if the sequence is empty""" return None if not seq else random.choice(seq)
40894aa9c7f03712756fecaaa32e09f0803d9da1
597,108
def page_not_found(e): """Return a custom 404 error.""" return '<h1>Sorry, nothing at this URL.<h1>', 404
f40fafec4a9df8a073d0efaf2fb2411531b1977a
634,146
def get_indexed_attestation_participants(spec, indexed_att): """ Wrapper around index-attestation to return the list of participant indices, regardless of spec phase. """ if spec.fork == "phase1": return list(spec.get_indices_from_committee( indexed_att.committee, indexed_att.attestation.aggregation_bits, )) else: return list(indexed_att.attesting_indices)
97f58350429209c803cfd32b4165de246900a9bf
167,806
def get_row_column(play, board): """ prompt for user input until its correct catch any letters or incomplete values in user input :param play - string, user command: :param board - object, board: :return row, column - int, locations on board in 2-D: """ # loop until there is valid user input while True: if type(play) == str: if play.lower() == 'q': quit() try: play_list = play.strip().split(',') row = int(play_list[0]) column = int(play_list[1]) # row index out of range if row < 1 or column < 1: print('Invalid position.') print('Try again.') print(board) play = input("Input a row then column separated by a comma (q to quit): ") else: return row, column except (TypeError, ValueError, IndexError): print('Incorrect input.') print('Try again.') print(board) play = input("Input a row then column separated by a comma (q to quit): ")
b6905eb5ad89ef83f3841378d309f49b72e48b7e
637,098
from typing import Match def gen_ruby_plain_text(match: Match) -> str: """Convert matched ruby tex code into plain text for bbs usage \ruby{A}{B} -> A(B) Also support | split ruby \ruby{椎名|真昼}{しいな|まひる} -> 椎名(しいな)真昼(まひる) """ return ''.join('{}({})'.format(*pair) for pair in zip(match['word'].split('|'), match['ruby'].split('|')))
480423c92d3a49d3e5b6d580e2771e6fa95482f4
446,925
def quacks_like_list(object): """Check if object is list-like""" return hasattr(object, '__iter__') and hasattr(object, 'append')
2bcef3b4265f439717452920a6cbe7af1916b05e
508,498
def mk_scan_mapper(condition_map, dflt=None): """Make function implementing an if/elif/.../else logic from a {bool_func: x, ...} map""" def scan_mapping(x): for condition, then in condition_map.items(): if condition(x): return then return dflt return scan_mapping
8787cf7783b124029ce28f908c5a49c25ef5de33
57,173
import torch from typing import OrderedDict def load_model_state_from_checkpoint(checkpoint_path, net=None, prefix='model.'): """ Load model weights from Pytorch Lightning trainer checkpoint. Parameters ---------- net: nn.Module Instance of the PyTorch model to load weights to checkpoint_path: str Path to PL Trainer checkpoint prefix: str Prefix used in LightningModule for model attribute. Returns ------- nn.Module """ if net is None: # create new instance model raise NotImplementedError trainer_checkpoint = torch.load(checkpoint_path, map_location=lambda storage, loc: storage) # chop off the prefix from LitModule, e.g. `self.model = model` model_checkpoint = OrderedDict(((key[len(prefix):] if key.startswith(prefix) else key, value) for key, value in trainer_checkpoint['state_dict'].items())) net.load_state_dict(model_checkpoint) return net
60f45a8d3231eb828ab7886ee66339fefdac8873
83,107
def count_lines_in_file(file, ignore_header=True): """ Counts number of records in a file. This assumes each record is defined in a single line. Similar but not limited to CSV files. By default, consider and ignores the header row (First row) from the count. Args: file - Path to file ignore_header - If True, ignores first line in count. If False, returns count of all lines in file """ count = sum(1 for _ in open(file)) if ignore_header: return count - 1 return count
6e915f3475862c61d7df92085ba410b19758f6c9
370,510
def is_parent(t, s): """Whether t is s's parent.""" return t is s.parent
4bab879707814f537c71a84e40b6dbeb94fd0c4a
114,294
def again_prompt() -> str: """Return the prompt request user character input.""" return f'\nTry again? (y/n): '
4bf7a9b5eb566129d2537e5a4d2d1dce04e4b5c9
188,966
from typing import Callable from typing import Iterable import threading def start_deamon(function: Callable, args: Iterable = ()) -> threading.Thread: """Start a deamon with the given function and arguments.""" thread = threading.Thread(target = function, args = args) thread.daemon = True thread.start() return thread
518b48c52b824b5a1277d1d893353d7bdaf4fe08
489,896
import hashlib def StrSha1(strIn): """Compute and return (as a string, hexdigest) the sha1 of the given input""" sha1 = hashlib.sha1() sha1.update(strIn) return sha1.hexdigest()
e8a5665341c385d067822c9e2b336f1f39a13148
215,098
def collectCleanedFields(form): """Collects all cleaned fields and returns them with the key_name. Args: form: The form from which the cleaned fields should be collected Returns: All the fields that are in the form's cleaned_data property are returned. If there is a key_name field, it is not included in the returned fields, instead, it is returned as the first element in the returned tuple. If no key_name field is present, None is returned as first value instead. """ fields = {} key_name = None if 'key_name' in form.cleaned_data: key_name = form.cleaned_data.pop('key_name') for field, value in form.cleaned_data.iteritems(): fields[field] = value return key_name, fields
b7f9f0e9315271063207f85a6338e776d2400c01
569,464
def psri(b3, b4, b6): """ Plant Senescence Reflectance Index (Merzlyak et al., 1999). .. math:: PSRI = (b4 - b3)/b6 :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b6: Red-edge 2. :type b6: numpy.ndarray or float :returns PSRI: Index value .. Tip:: Merzlyak, M.N.; Gitelson, A.A.; Chivkunova, O.B.; Rakitin, V.Y. 1999. \ Non-destructive optical detection of pigment changes during leaf \ senescence and fruit ripening. Physiologia Plantarum 106, 135-141. \ doi:10.1034/j.1399-3054.1999.106119.x. """ PSRI = (b4 - b3)/b6 return PSRI
3be121d6e0852a6a83d307773ffacf8fddec9f9d
698,122
def aggregate_current(sim): """ Calculate the time series of aggregate current of all EVSEs within a simulation. Args: sim (Simulator): A Simulator object which has been run. Returns: np.Array: A numpy ndarray of the aggregate current at each time. [A] """ return sim.charging_rates.sum(axis=0)
aefd05c071257fd9d7c1978cda18ee0ca8b72df3
159,211
def bankbase(bankindex, numbanks, prgbanksize, fix8000): """Calculate the base address of a PRG bank. bankindex -- the index of a bank (0=first) numbanks -- the total number of banks in the ROM prgbanksize -- the size in 1024 byte units of a bank, usually 8, 16, or 32 fix8000 -- if false, treat the first window ($8000) as switchable; if true, treat the last window as switchable """ if prgbanksize > 32: return 0 # for future use with Super NES HiROM numwindows = 32 // prgbanksize if fix8000: wndindex = min(bankindex, numwindows - 1) else: wndindex = max(0, bankindex + numwindows - numbanks) return 0x8000 + 0x400 * prgbanksize * wndindex
20a1816e1b00e78b43b94c283a7407a65b2ad76c
123,346
import math def get_tile_size(num_pixels, tile_size=400): """ num_pixels is the number of pixels in a dimension of the image. tile_size is the desired tile-size. """ # How many times can we repeat a tile of the desired size. num_tiles = int(round(num_pixels / tile_size)) # Ensure that there is at least 1 tile. num_tiles = max(1, num_tiles) # The actual tile-size. actual_tile_size = math.ceil(num_pixels / num_tiles) return actual_tile_size
a139fdb8f4548dd2f8576f116943473475294bae
686,613
import json def build_n1ql_request_body(query: str, *args, **kwargs) -> dict: """Build request body for N1QL REST API. Request body consists of ``statement`` key, ``args`` key (if using positional parameters), and any key prefixed with ``$`` (if using named parameters). See https://docs.couchbase.com/server/current/n1ql/n1ql-rest-api/index.html for reference. :params query: N1QL query string. :params *args: Positional parameters passed as ``args`` in request body. :params **kwargs: Named parameters passed as ``$``-prefixed parameter in request body. """ body = {"statement": query} if args: body["args"] = json.dumps(args or []) if kwargs: for k, v in kwargs.items(): body[f"${k}"] = json.dumps(v) return body
7fd3cd856c15af07ad3493184fe7d5e15ea01a6f
506,591
def norm(X, n=2): """Return the n-norm of vector X""" return sum([x**n for x in X])**(1/n)
101941824728e5eb28ce40d9ddae7a0f5c6acc5d
662,599
def multiset(target, key, value): """ Set keys multiple layers deep in a target dict. Parameters ------------- target : dict Location to set new keys into key : str Key to set, in the form 'a/b/c' will be available as target[a][b][c] = value value : any Will be added to target dictionary Returns ------------ target : dict The original dict object """ keys = key.split('/') current = target for i, key in enumerate(keys): last = i >= len(keys) - 1 if key not in current: if last: current[key] = value else: current[key] = {} current = current[key] return target
33f9049b7a55156de253f51f63a1873b2228b78c
506,413
import requests def http_test_client(application_settings): """ Returns an HTTP client that can send requests to local server.""" class HTTPClient(): def post(self, path, data=None): return requests.post( 'http://localhost:%s%s' % (application_settings['APP_PORT'], path), json=data ) def get(self, path): return requests.get('http://localhost:%s%s' % (application_settings['APP_PORT'], path)) return HTTPClient()
336b08252e97b66a0ad46224d24779d648d5440a
594,433
def bits_table_q() -> dict[int, int]: """The table of the maximum amount of information (bits) for the version Q. Returns: dict[int, int]: Dictionary of the form {version: number of bits} """ table = { 1: 104, 2: 176, 3: 272, 4: 384, 5: 496, 6: 608, 7: 704, 8: 880, 9: 1056, 10: 1232, 11: 1440, 12: 1648, 13: 1952, 14: 2088, 15: 2360, 16: 2600, 17: 2936, 18: 3176, 19: 3560, 20: 3880, 21: 4096, 22: 4544, 23: 4912, 24: 5312, 25: 5744, 26: 6032, 27: 6464, 28: 6968, 29: 7288, 30: 7880, 31: 8264, 32: 8920, 33: 9368, 34: 9848, 35: 10288, 36: 10832, 37: 11408, 38: 12016, 39: 12656, 40: 13328 } return table
f05afb73e21b83ac4ade35cde8b5d7d19c215672
541,232
def purity(rho): """ Calculate the purity of a quantum state Parameters --------- rho : quti.Qobj Quantum density matrix Returns --------- purity_rho : float The purity of rho(=1 if pure, <1 if not pure) """ purity_rho=(rho*rho).tr() return purity_rho
36f37f67a09fb4d3cbd223fca38580674d9400f3
262,087
def make_error_response(errors: list) -> dict: """Return a JSONAPI compliant error response.""" return {'errors': [dict(error) for error in errors]}
1abb9363cebed93ba9f10287bcbf632d4ef188d4
134,928
def _get_suggestions_index(name): """Returns suggestions index name for a regular index name.""" return f'df_suggestions_{name}'
4cd2294e89f05dfbefe65ff4604c43818880d6c9
10,580
def trim_from_start(s, substring): """Trims a substring from the target string (if it exists) returning the trimmed string. Otherwise returns original target string.""" if s.startswith(substring): s = s[len(substring) :] return s
a4d68169a50672159af939855734fabff1fd8426
46,373
def doubleclick(x, y, bombs, cal, flags): """ Shortcut for double click :param x: horizontal position of the click :param y: vertical position of the click :param bombs: list of bomb positions :param cal: number of the position :param flags: list of flags :return: status after the double click (0 for wrong judgment, 1 for right judgment, -1 for invalid double click), list of positions to expand (empty list for status 0 or -1) """ tests = [(m, n) for m in (x - 1, x, x + 1) for n in (y - 1, y, y + 1) if (m, n) not in flags] if cal == 9 - len(tests): for t in tests: if t in bombs: return 0, [] return 1, tests return -1, []
cf5fdc76b7af9d27a3b99fee53a454f59c5ff643
351,664
def self_affine_psd(q, pref, hurst, onedim=False): """Ideal self-affine power spectrum, dependent only on prefactor and Hurst exponent.""" exp = -2 * (hurst + 1) if onedim: exp = -1 - 2 * hurst return pref * q**exp
c8208ca4510085fab0c10eac5a63e885c5f1834a
77,314
def _deep_update(main_dict, update_dict): """Update input dictionary with a second (update) dictionary https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth Parameters ---------- main_dict: dict Input dictionary update_dict: dict Update dictionary Returns ------- updated_dict : dict Updated dictionary """ for key, val in update_dict.items(): if isinstance(val, dict): main_dict[key] = _deep_update(main_dict.get(key, {}), val) else: main_dict[key] = val # return updated main_dict return main_dict
864fb0c9bf970438284e9c539de166d7086b4499
192,356
def _CurrentRolesForAccount(project_iam_policy, account): """Returns a set containing the roles for `account`. Args: project_iam_policy: The response from GetIamPolicy. account: A string with the identifier of an account. """ return set(binding.role for binding in project_iam_policy.bindings if account in binding.members)
64bb0a51600778580016e3545fe7230949b46d63
39,627
def is_email_link(href=None): """Utility function to determine whether the supplied href attribute is an email link.""" print("email_link()") return href and 'mailto:' in href
44d785cd43cfb8ff7160baa78fab3597c1032f35
296,032
def fib_table_for(n): """ Returns: fibonacci list [a0, a1, ..., an] Parameter n: the position in the fibonacci sequence Precondition: n >= 0 is an int """ if n == 0: return [1] # if for n==1 is unnecessary fib = [1,1] for k in range(2,n): fib.append(fib[-1] + fib[-2]) return fib
8414d4894fff10e78130252ba74bc716cf4b1755
616,905
import math def rotation_matrix_to_euler_angle(R): """ Converts a rotation matrix to [yaw, pitch, roll] """ yaw = math.atan2(R[1, 0], R[0, 0]) pitch = math.atan2(-R[2, 0], math.sqrt(R[2, 1] ** 2 + R[2, 2] ** 2)) roll = math.atan2(R[2, 1], R[2, 2]) return yaw, pitch, roll
8e1f7c77496fabbb0478454940c6cb336d19a0ce
636,994
from string import Template def substitute(template, context): """ Performs string substitution. Args: template (str): The string to perform the substitution on. context (dict): A mapping of keys to values for substitution. Returns: str: The substituted string. """ template = Template(template) return template.safe_substitute(context)
387ea6a6e4ac5064eebe1afe7f73568a5096cb48
286,117
def truncate(content, length=100, suffix="..."): """ Smart string truncation """ if len(content) <= length: return content else: return content[:length].rsplit(" ", 1)[0] + suffix
1b4129390e3da4c1f6667e069fd0bad520eb393d
353,931
import math def circleconvert(amount, currentformat, newformat): """ Convert a circle measurement. :type amount: number :param amount: The number to convert. :type currentformat: string :param currentformat: The format of the provided value. :type newformat: string :param newformat: The intended format of the value. >>> circleconvert(45, "radius", "radius") 45 >>> circleconvert(45, "radius", "diameter") 90 >>> circleconvert(45, "radius", "circumference") 282.7433388230814 >>> circleconvert(45, "diameter", "diameter") 45 >>> circleconvert(45, "diameter", "radius") 22.5 >>> circleconvert(45, "diameter", "circumference") 141.3716694115407 >>> circleconvert(45, "circumference", "circumference") 45 >>> circleconvert(45, "circumference", "radius") 7.16197243913529 >>> circleconvert(45, "circumference", "diameter") 14.32394487827058 >>> circleconvert(45, "foo1", "foo2") Traceback (most recent call last): ... ValueError: Invalid old format provided. >>> circleconvert(45, "radius", "foo") Traceback (most recent call last): ... ValueError: Invalid new format provided. >>> circleconvert(45, "diameter", "foo") Traceback (most recent call last): ... ValueError: Invalid new format provided. >>> circleconvert(45, "circumference", "foo") Traceback (most recent call last): ... ValueError: Invalid new format provided. """ # If the same format was provided if currentformat.lower() == newformat.lower(): # Return the provided value return amount # If the lowercase version of the current format is 'radius' if currentformat.lower() == 'radius': # If the lowercase version of the new format is 'diameter' if newformat.lower() == 'diameter': # Return the converted value return amount * 2 # If the lowercase version of the new format is 'circumference' elif newformat.lower() == 'circumference': # Return the converted value return amount * 2 * math.pi # Raise a warning raise ValueError("Invalid new format provided.") # If the lowercase version of the current format is 'diameter' elif currentformat.lower() == 'diameter': # If the lowercase version of the new format is 'radius' if newformat.lower() == 'radius': # Return the converted value return amount / 2 # If the lowercase version of the new format is 'circumference' elif newformat.lower() == 'circumference': # Return the converted value return amount * math.pi # Raise a warning raise ValueError("Invalid new format provided.") # If the lowercase version of the current format is 'circumference' elif currentformat.lower() == 'circumference': # If the lowercase version of the new format is 'radius' if newformat.lower() == 'radius': # Return the converted value return amount / math.pi / 2 # If the lowercase version of the new format is 'diameter' elif newformat.lower() == 'diameter': # Return the converted value return amount / math.pi # Raise a warning raise ValueError("Invalid new format provided.") # Raise a warning raise ValueError("Invalid old format provided.")
4d31db1094588a157e829d08fa8cee4f7ea73355
530,185
def acc_score(y_true, y_pred): """ Calculate accuracy for the given predictions vector """ cnt_matches = 0 if len(y_true) == 0: return cnt_matches for true, pred in zip(y_true, y_pred): if true == pred: cnt_matches += 1 return cnt_matches / len(y_true)
c42d20722d15492b9da19466ce3374ac072a5943
247,376
def _get_time_units(ds): """Determine time units of dataset""" try: return ds.time.encoding["units"] except Exception: return ds.time.units return None
b7639bf4578728954a0a8d952eacf50e8f8ae72b
243,802
import unicodedata def remove_accents(text): """ Remove accents from a string """ try: text = text.decode("utf-8") except (UnicodeEncodeError, AttributeError): pass text = text.replace("’", "'") # accent used as apostrophe text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore") text = text.decode() return text
c45e5f3864cf91bcc56608f37bdb9e31fc9a0074
99,029
def list_to_string(lst): """Takes a list of items (strings) and returns a string of items separated by semicolons. e.g. list_to_string(['John', 'Alice']) #=> 'John; Alice' """ return "; ".join(lst)
05bace68ad7eee85aa599eaa5c589b8e9fc44a99
487,466
import torch def barycenter(P, T=None, dim=0): """ Returns the barycenters of the n-gons if a topology is provided, the barycenter of the input point set along the specified dimension otherwise Parameters ---------- P : Tensor the point set tensor T : LongTensor (optional) the topology tensor (default is None) dim : int (optional) the dimension along the barycenter is computed (default is 0) Returns ------- Tensor the barycenters tensor """ if T is None: return torch.mean(P, dim, keepdim=True) return torch.mean(P[T].permute(1, 0, 2), dim=1)
d3e9a4230b5d2bf18d826cda8b77071ee4094590
608,766
def read_cube_name_from_mdx(mdx): """ Read the cubename from a valid MDX Query :param mdx: The MDX Query as String :return: String, name of a cube """ mdx_trimed = ''.join(mdx.split()).upper() post_start = mdx_trimed.rfind("FROM[") + len("FROM[") pos_end = mdx_trimed.find("]WHERE", post_start) # if pos_end is -1 it works too cube_name = mdx_trimed[post_start:pos_end] return cube_name
cdd4511d6904383d1475432944b5c129177afc9e
404,216
import re def _is_private_name(name): """ Return true if the given variable name is considered private. Parameters ---------- name : str Variable name to check """ # e.g. __name__ is considered public. is_reserved_public_name = re.match(r"__[a-zA-Z0-9_]+__$", name) is not None return name.startswith("_") and not is_reserved_public_name
1232f6a52ffc9d07d7ed286771c3c75bc80db8b7
16,280
def get_dict_keys_from_val(d, val): """Get keys whose value in a dictionary match a given value. Args: d (dict): Dictionary from which to get keys. val (Any): Value whose matching keys will be extracted. Returns: List[Any]: List of keys whose values match ``val`` in ``d``. """ return [k for k, v in d.items() if v == val]
86628d098e4f8f2ac93c49419d73dfb163576c78
192,803
import struct def ntohl(integer): """ntohl(integer) -> integer Convert a 32-bit integer from network to host byte order.""" return struct.unpack("=I", struct.pack("!I", integer))[0]
2db027d2a39c62e9d78eafa9125681f3f460db2f
288,096
def range_cmp(lhs, rhs): """ A range compare function. :param lhs: The left hand side of the comparison. :type lhs: Rangeable :param rhs: The right hand side of the comparison. :type rhs: Rangeable :return: -1 if lhs is before rhs, 1 when after and 0 on overlap. :rtype: int The comparison function may be explained as:: Will return -1: |___lhs___| |___rhs___| Will return +1: |___rhs___| |___lhs___| Will return 0: |___lhs___| |___rhs___| """ if lhs.get_max_address() <= rhs.get_base_address(): return -1 elif lhs.get_base_address() >= rhs.get_max_address(): return 1 else: return 0
4b0f438aca6aec3afc4683b19a1045a41f0b5005
452,882
def lag_autocov(v, lag): """ Compute lag autocovariance of a vector """ tmp = 0 N = len(v)-lag for j in range(N): tmp += v[j]*v[j+lag] return tmp/N
4804216db765713cb549b3b537d2d42a09554bab
574,809
def get_data_array_extent(dataarray): """ Get the coordinate of the lower left corner and the coordinate of the upper right corner in map units. Parameters ---------- dataarray : xarray.DataArray The input datasource. Returns ------- extent : tuple of integers A tuple of ``(xmin, ymin, xmax, ymax)`` values. """ return (dataarray.coords['x'].min().item(), dataarray.coords['y'].min().item(), dataarray.coords['x'].max().item(), dataarray.coords['y'].max().item())
39800ea9cd24dfa0f027d4046b74e5336ebcfb6b
283,888
from pathlib import Path def setup_data_path(base_path): """ Ensure filesystem path for the data exists.""" _dpath = Path.joinpath(Path(base_path), "data") _dpath.mkdir(parents=True, exist_ok=True) return _dpath
fdf9afb5f740b0112bcc46f03d2e47cdd96fd7d7
257,040
import time def cutoff_test(depth, max_depth, max_time, time_start): """ Returns True if reached maximum depth or finished time False if search is to be continued """ if depth >= max_depth or time.time()-time_start >= max_time: return True return False
a6a04340010258ee16e8fa61d007644aebedfc37
235,047
def tile_is_solid(tid): """ Return whether a tile is solid or not based on its ID. Arguments: tid: the tile ID Returns: whether the tile is solid """ return tid in (2, 3, 5)
d72e526e9f40b0267fb6bdf5becb6e4a660b7c92
258,771
from bs4 import BeautifulSoup def html_extraction(text): """ Remove from the text html tags found on stack overflow data. :param text: string containing textual data mixed with specific html tags found on stack overflow data :return: a string in which specific html tags and it's content are removed and others tags are remove but not their content """ soup = BeautifulSoup(text, 'lxml') tags = ('a', 'div', 'code', 'blockquote') for tag in tags: for occurrence in soup.find_all(tag): _ = occurrence.extract() return " ".join(soup.text.split())
88e2f5d771e012f1f6320b00078af2d9d4b2a66c
103,912
def ConvertIndexListToSet(index_list): """Creates a set containing the indices of all '1' entries in the index list """ return set(i + 1 for i, j in enumerate(index_list) if j == 1)
78d0769de4b22aabd0d0ea2f906958a929da5299
10,452
import getpass def get_opal_password(opal_password, password_file): """ Retrieve the OPAL password form the user, either from the command line arguments, the file they specified or by asking them to input it :param opal_password: The actual password, if provided via the command line :param password_file: The file containing the password, if provided. :return: The password """ if opal_password: return opal_password if password_file: with open(password_file, 'r') as fd: password = fd.readlines()[0].strip() else: password = getpass.getpass(str("Enter your OPAL password: ")) return password
e6c13644c120beab3a629634c433343a43c92f00
54,704
def test_function_docs(arg): """ A function to test docs. :param arg: An argument. :return: A return value. """ return f"test_function_docs: {arg}"
26fb8c907a308e50dd41c0421abe8718c01132f2
589,786
def hours_to_minutes(hours: str) -> int: """Converts hours to minutes""" return int(hours) * 60
84057d6ed73fc20f06fb69741eb2c8bca9628548
607,256
def remove_junk_from_filestream( lines, banner="-----oOo-----", comment_chars=["#", "!", "*"] ): """ Removes comments, headers, and whitespace from a list of strings, parsed from a lagrit.out file. """ newlines = [] in_banner = False for line in lines: stripped = line.strip() if stripped == "": continue elif stripped[0] in comment_chars: continue elif banner in stripped: in_banner = not in_banner elif "log file: " in stripped: continue if not in_banner: newlines.append(stripped) return newlines[1:]
0dbbf081b3b473f31ae8becd5b3ecbb1d1bf0198
156,180
def progress_string(i, n): """ Helper to build progress string Parameters ---------- i : int current number n : int maximal number Returns ------- progress_str : str """ width = len(str(n)) string = "({0:{width}d}/{1:d})".format(i, n, width=width) return string
0c600d944bba960a8c4822180c3de3ae5f31e35a
484,606
def getopts(argument_list): """ Parses command line arguments from argv. :param argument_list: The command line input from the terminal, separated as a list. :return: Dictionary of argument name to value. """ opts = {} while argument_list: if argument_list[0][0] == '-': opts[argument_list[0].lstrip('-')] = argument_list[1] argument_list = argument_list[1:] return opts
f08d17c71c90755a05edb92d8201cc591567d9e7
211,132
def clock_to_seconds_remaining(clock_str): """Translates a clock string to a number of seconds remaining""" minutes, seconds = clock_str.split(":") return float(minutes) * 60 + float(seconds)
4f0e616f6d079d772eb0562a0a55c7119ff2e9e9
181,571
from typing import List def is_subseries(first: List[int], second: List[int]) -> bool: """ returns True if second is subseries of first Args: first (List[int]): source of subseries second (List[int]): series that will be checked against first series Returns: bool: True if second is subquery, False otherwise """ counter = 0 pivot = 0 for s in range(0, len(second)): for i in range(pivot, len(first)): if first[i] == second[s]: counter += 1 pivot = i break return counter == len(second)
e66925002f982a2c4a2a391991bb500899d17755
444,007
def stepsDictToTimeList(stepsDict): """stepsDictToTimeList() takes a dict of steps [stepsDict] and returns a list of all the runtimes of completed steps in seconds. """ cycleTimes = [] for c in stepsDict: if stepsDict[c].complete: cycleTimes.append(stepsDict[c].elapsedTime) return cycleTimes
8fffa64ff09340c7b5e1ff0459e4b0a1597fed69
426,636
def is_letter(char_code): """Return True if char_code is a letter character code from the ASCII table. Otherwise return False. """ if isinstance(char_code, str) or isinstance(char_code, bytes): char_code = ord(char_code) if char_code >= 65 and char_code <= 90: # uppercase letters return True if char_code >= 97 and char_code <= 122: # lowercase letters return True return False
26ddd52a7904346a0c487b776a77ac26eb8b50f8
76,561
import random def two_random_partitions(indices, p=0.5): """given a list of indices (indicating word positions) partition into two sets p is probability of entering set1 """ set1, set2 = set(), set() for idx in indices: if random.random() > (1.0 - p): set1.add(idx) else: set2.add(idx) return set1, set2
972bed2f37174d5b900edaccf0f37fcded972600
129,892
import pytz def toEpoch(timestamp): """Takes a datetime object and returns nanoseconds since epoch (UTC) """ return int(pytz.UTC.localize(timestamp).timestamp()*10**9)
6ad70a0f30c4ab076e002b517b0c02b9d640c65f
310,508
def read_all_words_from_file(source_file): """ Function for read all words from source file. :param source_file: str File with words. :return: List of words. """ if not isinstance(source_file, str): raise TypeError with open(source_file, 'rb') as f_in: words = [word.decode().strip() for word in f_in] return words
8ad8e679f1c1d1efe7797d3a0374a706f2d5327c
573,721
def make_space(space_padding=0): """ Return string with x number of spaces. Defaults to 0. """ space = '' for i in range(space_padding): space += ' ' return space
db846fdb426bc04526744daac8487e2a90320200
688,157
def comma_split(text: str): """ Returns a list of strings after splitting original string by commas Applied to KEYWORDS, CLASSIFIERS, and REQUIREMENTS """ return [x.strip() for x in text.split(",")]
bb9f34a0ffbdd1be0db184fc026de0abddabedf6
488,828
import codecs import csv def count_rows_in_delimited_file(filename, has_header=True, safe=True, delimiter=","): """ Simple and efficient utility function to provide the rows in a valid delimited file If a header is not present, set head_header parameter to False Added "safe" mode which will handle any NUL BYTE characters in delimited files It does increase the function runtime by approx 10%. Example: "non-safe" counting ~1 million records in a delimited file takes 9s using "safe mode", it now takes 10s """ with codecs.open(filename, "r") as f: if safe: row_count = sum(1 for row in csv.reader((line.replace("\0", "") for line in f), delimiter=delimiter)) else: row_count = sum(1 for row in csv.reader(f, delimiter=delimiter)) if has_header and row_count > 0: row_count -= 1 return row_count
5a5c7a1e4f2e530beae717bcae489f89d68a0cf8
314,879
def simContinue(state, timeLimit = None) : """Test if simulation should continue to next state: If time based: if simulation is after time limit If HP based: if enemy has HP left """ if timeLimit is not None : return state['timeline']['timestamp'] <= timeLimit else : return state['enemy']['hp'] > 0
5a5cb8a9724d1a06839a819c72c186a0ed47e3dc
53,190
from typing import Counter def flush_finder(hand): """ Takes a 5-card hand, concats, returns the most frequent symbol. If we get 5 matching suits, we have a flush, return list: [8, high card rank, 2nd rank, 3rd rank, 4th rank, 5th rank] """ suits = ''.join(hand) if Counter(suits).most_common(1)[0][1] == 5: cards = ''.join(hand)[::2] ranks = sorted(cards, reverse=True) return [8, ord(ranks[0]), ord(ranks[1]), ord(ranks[2]), ord(ranks[3]), ord(ranks[4])] else: return [0, 0, 0, 0, 0, 0]
07e089db41f83f83c88449abd9e5fa2cd1ac7254
152,297
from bs4 import BeautifulSoup def cur_game_status(doc): """ Return the game status :param doc: Html text :return: String -> one of ['Final', 'Intermission', 'Progress'] """ soup = BeautifulSoup(doc, "lxml") tables = soup.find_all('table', {'id': "GameInfo"}) tds = tables[0].find_all('td') status = tds[-1].text # 'End' - in there means an Intermission # 'Final' - Game is over # Otherwise - It's either in progress or b4 the game started if 'end' in status.lower(): return 'Intermission' elif 'final' in status.lower(): return 'Final' else: return 'Live'
74a60e969157e32e964e556513693f065410161e
265,966
def min_max(game_spec, board_state, side, max_depth, evaluation_func=None): """Runs the min_max_algorithm on a given board_sate for a given side, to a given depth in order to find the best move Args: game_spec (BaseGameSpec): The specification for the game we are evaluating evaluation_func (board_state -> int): Function used to evaluate the position for the plus player, If None then we will use the evaluation function from the game_spec board_state (3x3 tuple of int): The board state we are evaluating side (int): either +1 or -1 max_depth (int): how deep we want our tree to go before we use the evaluate method to determine how good the position is. Returns: (best_score(int), best_score_move((int, int)): the move found to be best and what it's min-max score was """ best_score = None best_score_move = None evaluation_func = evaluation_func or game_spec.evaluate moves = list(game_spec.available_moves(board_state)) if not moves: # this is a draw return 0, None for move in moves: new_board_state = game_spec.apply_move(board_state, move, side) winner = game_spec.has_winner(new_board_state) if winner != 0: return winner * 10000, move else: if max_depth <= 1: score = evaluation_func(new_board_state) else: score, _ = min_max(game_spec, new_board_state, -side, max_depth - 1, evaluation_func=evaluation_func) if side > 0: if best_score is None or score > best_score: best_score = score best_score_move = move else: if best_score is None or score < best_score: best_score = score best_score_move = move return best_score, best_score_move
8a626126b8255960d1c667ab6cc19e7f0a23d86b
545,630
import math def calc_distance(ij_start, ij_end, R): """" Calculate distance from start to end point Args: ij_start: The coordinate of origin point with (0,0) in the upper-left corner ij_end: The coordinate of destination point with (0,0) in the upper-left corner R: Map resolution (m/pixel) Return: The distance from origin to destination in meters """ return R*math.sqrt((ij_start[0]-ij_end[0])**2 + (ij_start[1]-ij_end[1])**2)
4242d8fe01f3d286f69aac2a9432726280271530
660,314
def dm2skin_normalizeWeightsConstraint(x): """Constraint used in optimization that ensures the weights in the solution sum to 1""" return sum(x) - 1.0
79024cb70fd6cbc3c31b0821baa1bcfb29317043
2,884
import dataclasses def has_default_factory(field) -> bool: """ Test if the field has default factory. >>> from typing import Dict >>> @dataclasses.dataclass ... class C: ... a: int ... d: Dict = dataclasses.field(default_factory=dict) >>> has_default_factory(fields(C)[0]) False >>> has_default_factory(fields(C)[1]) True """ return not isinstance(field.default_factory, dataclasses._MISSING_TYPE)
8458c059e401f66151bdee9b96dd4f1c844fa630
558,955
def get_child_entry(parent, key, default=None): """ Helper method for accessing an element in a dictionary that optionally inserts missing elements :param parent: The dictionary to search :param key: The lookup key :param default: A default value if key is missing on parent, if default is None missing elements are not filled :return: """ if key not in parent: if default is not None: parent[key] = default.copy() else: return None return parent[key]
b960ccf1ada3e93c60ea0abaffd0669de9b9f97b
276,026
def exec_fn(func): """Executes given function, returns {error,result} dict""" try: return {'result': func()} except Exception as error: # pylint: disable=broad-except return {'error': str(error)}
21a122f634833855413767013bbab03167f3ee86
615,470
def is_primitive(v): """ Checks if v is of primitive type. """ return isinstance(v, (int, float, bool, str))
d22607c0e2b93b82b1da6beb50de68668624dd71
3,687
def filterMonth(string, month): """ Filter month. """ if month in string: return True else: return False
25852ed839ce78b80661116ab1338aed7ada6bbf
306,900
import binascii def parse_object_id(value: str) -> bytes: """ Parse an object ID as a 40-byte hexadecimal string, and return a 20-byte binary value. """ try: binary = binascii.unhexlify(value) if len(binary) != 20: raise ValueError() except ValueError: raise ValueError("blob ID must be a 40-byte hexadecimal value") return binary
503b0cd21c445d1ce851dbdc8f47b493bc17b1f8
33,125
def should_deploy(branch_name, day_of_week, hour_of_day): """ Returns true if the code can be deployed. :param branch_name: the name of the remote git branch :param day_of_week: the day of the week as an integer :param hour_of_day: the current hour :return: true if the deployment should continue >>> should_deploy("hot-fix", 0, 10) True >>> should_deploy("hot-fix", 4, 10) #this branch can be deployed on Friday True >>> should_deploy("hot-fix", 5, 10) #this branch can be deployed on Saturday True >>> should_deploy("hot-fix", 6, 10) #this branch can be deployed on Sunday True >>> should_deploy("hot-fix", 0, 7) #this branch can be deployed before 8am True >>> should_deploy("hot-fix", 0, 16) #this branch can be deployed after 4pm True >>> should_deploy("master", 0, 10) True >>> should_deploy("master", 4, 10) #master cannot be deployed on Friday False >>> should_deploy("master", 5, 10) #master cannot be deployed on Saturday False >>> should_deploy("master", 6, 10) #master cannot be deployed on Sunday False >>> should_deploy("master", 0, 7) #master cannot be deployed before 8am False >>> should_deploy("master", 0, 16) #master cannot be deployed after 4pm False """ if branch_name == "master" and day_of_week >= 4: return False elif branch_name == "master" and (hour_of_day < 8 or hour_of_day >= 16): return False else: return True
8d8ba7657e9393d588c7019839acc859c56e63f9
62,210
def int2list(num,listlen=0,base=2): """Return a list of the digits of num, zero padding to produce a list of length at least listlen, to the given base (default binary)""" digits = []; temp = num while temp>0: digits.append(temp % base) temp = temp // base digits.extend((listlen-len(digits))*[0]) return digits
9f10135736aaaea2bf655774ea0a5453766e633f
674,873
def _is_ref(schema): """ Given a JSON Schema compatible dict, returns True when the schema implements `$ref` NOTE: `$ref` OVERRIDES all other keys present in a schema :param schema: :return: Boolean """ return '$ref' in schema
1f805929a6b28cf4fbe16714d300f3beffeb6e73
21,015
def get_userhandles(tokens): """ Extract userhandles from a set of tokens """ userhandles = [x for x in tokens if x.startswith("@")] return userhandles
c7be5b9de5a6186bf1d32c02eef32dd565d7ce4d
232,174
def _find_duplicates(iterable): """Returns a list of duplicate entries found in `iterable`.""" duplicates = [] seen = set() for item in iterable: if item in seen: duplicates.append(item) else: seen.add(item) return duplicates
f922cbbaf33d17d4647b5edced6cf057c366fdf1
225,446
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string int) returns: integer """ # TO DO... <-- Remove this comment when you code this function handLen = 0 for val in hand.values(): handLen = handLen + val return handLen ## return sum(hand.values()) "gives same result"
788917829149eca65f2c141eac051d1a4895c8ae
425,426
def temporal_plot_features(ax): """Set the temporal plot features""" ax.legend(loc=2) ax.set_xlabel('year') ax.set_ylabel('interhemispheric ocean\ntemperature difference (K)') ax.tick_params(top='off') ax.text(0.92, 0.08, '(a)', transform=ax.transAxes, fontsize=24, va='top') ax.axhline(y=0, color='0.5', linestyle='--', linewidth=0.5) ylim = ax.get_ylim() return ylim
b079cd124fb361591a7097079bd187f6ef9d8950
258,052
def sbi_addition(sbi_code): """Creates link to SBI-code explanation.""" base = "https://sbi.cbs.nl/cbs.typeermodule.typeerservicewebapi/content/angular/app/#/code?sbicode=" link = base+str(sbi_code) return link
76368f8ffb8090773101706c790d58a778cc1e68
610,439
import random def random_point_triangle(p0,p1,p2): """ Uniformally Picks a point in a triangle args: p0,p1,p2 (float,float) : absolute position of triangle vertex return: pr (float,float) : absolute position inside triangle """ # Unwraping Points x0,y0 = p0 x1,y1 = p1 x2,y2 = p2 # Picking and Adjusting Uniform Weights a0 = random.random() a1 = random.random() if a0+a1 > 1: a0, a1 = 1-a0, 1-a1 # Calculating Associated Point xr = a0*(x1-x0)+a1*(x2-x0)+x0 yr = a0*(y1-y0)+a1*(y2-y0)+y0 return (xr,yr)
af0fef3aa8bf5225e0e814503538acacf3b70969
216,890
def add_gctx_to_out_name(out_file_name): """ If there isn't a '.gctx' suffix to specified out_file_name, it adds one. Input: - out_file_name (str): the file name to write gctx-formatted output to. (Can end with ".gctx" or not) Output: - out_file_name (str): the file name to write gctx-formatted output to, with ".gctx" suffix """ if not out_file_name.endswith(".gctx"): out_file_name = out_file_name + ".gctx" return out_file_name
0cb90a0b6203a6162d8cdfb2c39daf8190a41a40
99,166