content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def get_js(options, working_directory): """ Returns the path of the local js folder :param working_directory: location of current directory :type working_directory: string :return: A dictionary containing relative links to the local js directory :rtype: dict of strings """ ...
9671a8fa4a0298d0673b59d50ca1536d38d68ace
639,817
def check_table_and_required_columns(existed_tables, target_table_id, required_columns): """ check target table is whether in existed_tables or not check required_columns are whether all in target table or not, including column type check return: table_existed -> bool, required_pass -> bool, error_msg -...
df64cc4c7015b50c08fe34ec1e4afdb4889c5c73
639,818
def nbAlternatives(instance): """ Returns the number of alternatives of the instance. :param instance: The instance. :type instance: preflibtools.instance.preflibinstance.PreflibInstance :return: The number of alternatives of the instance. :rtype: int """ return instance.nbAlternatives
2a03cb1c2718e7ecd82d7df3003805fa032cd01a
639,819
def do_selective_backprop( epoch: int, batch_idx: int, start_epoch: int, end_epoch: int, interrupt: int, ) -> bool: """Decide if selective backprop should be run based on time in training. Returns true if the current ``epoch`` is between ``start_epoch`` and ``end_epoch``. Recommend that...
cb5978058da64cab8f3af22acc66bbea1b850f4a
639,820
def extract_CA_coords(helices, model, verbose=False): """get CA coordinates for rach residue in each helix input: helix list, each helix is list of its residues in format (chain, ('', resnum, '')) output: list of helices, each helix is list of CA coords (Biopython Vector class) of its residues """ print('Extracti...
b62f3cc7564f6aa3f8d0eead4132c78e732af7ee
639,822
import typing from pathlib import Path def valid_voice_dir(voice_dir: typing.Union[str, Path]) -> bool: """Return True if directory exists and has an onnx file""" voice_dir = Path(voice_dir) return voice_dir.is_dir() and (len(list(voice_dir.glob("*.onnx"))) > 0)
7291a79e8f648251ef5ca3cb6b8c51cf6fe90b24
639,823
import os def _find_7zip(search_paths): """Try to find 7zip, and raise an error if not""" # pylint: disable=bare-except, unreachable for executable in search_paths: try: if not os.path.exists(executable): print(f"7Zip executable at '{executable}' does not exist.") ...
179e5efc0825b2731f2461a321d5cbd71040b127
639,824
def get_most_sold_item(df): """Return a tuple of the name of the most sold item and the number of units sold""" most_sold_df = df.groupby(['Item'])['Units'].sum() return (most_sold_df.idxmax(), most_sold_df.loc[most_sold_df.idxmax()]) pass
0e641279bc47c62b91a82c46749828e6e375e748
639,825
def get_input_commands(input_data): """extract instructions che from input text input data (str): plain text read from txt file""" input_lines = input_data.split("\n") result = [] for il in input_lines: if il != "": res = il.split(" ") result.append([res[0], int(res[1...
56bfef089e7f09b8d7fffd1e3bc580bfb10a1a99
639,826
def function1(a,b): """This is a function which will calculate average of two numbers.""" #docstrings average = (a+b)/2 #print(average) return average
3e4c40fd0cfa135dd8b6388c158df0f77e2a8f08
639,827
def prc_rerouted(XMLDataFrame, XMLDataFrameRef): """ Compute the % of rerouted vehicles """ # diffPaths = pd.concat( # [XMLDataFrame["itineraire"], XMLDataFrameRef["itineraire"]] # ).drop_duplicates(keep=False) # nChangedPaths = diffPaths.count() # nGeneratedVeh = XMLDataFrameRe...
33e6ac0f783ab7d049095a4d671af718913a23a1
639,828
def _isLinked(self): """Return True if another record links to this record""" if len( self._inx.iref_by_sect[self.uid].a.keys() ) == 0: return False for k in self._inx.iref_by_sect[self.uid].a.keys(): if len( self._inx.iref_by_sect[self.uid].a[k] ) > 0: return True return False
6241ec666bc422c51017397b279f208d8a1a2963
639,829
def test_data_path(): """Returns full path to the test data.""" # pylint: disable=line-too-long # pyformat: disable return '{pyglib_resource}waymo_open_dataset/utils/testdata/motion_data_one_example.tfrecord'.format(pyglib_resource='')
7ed3b3f28caa2df3e358c77fd4e1c3e68ecac245
639,832
import numpy def interp2(x, y, xp, yp, fp): """Interpolate a 2D complex array. :rtype : numpy.array """ f1r = numpy.zeros((len(xp), len(y))) f1i = numpy.zeros((len(xp), len(y))) for ixp in range(len(xp)): f1r[ixp, :] = numpy.interp(y, yp, numpy.real(fp[ixp, :])) f1i[ixp, :] = ...
e578ccddb3aa53711d30ea8a0ad2bc23703bb027
639,833
import argparse def construct_parser() -> argparse.ArgumentParser: """Constructs the cli parser""" parser = argparse.ArgumentParser() parser.add_argument("filepath", help="The filepath to the midi file to be analysed") parser.add_argument( "--generations", "-g", type=int, ...
8a09d8b935ca3d8bcaed7ef00a7a618fe23e090c
639,834
import hashlib def _md5_of_file(path): """Compute and return the MD5 sum of a flat file. The MD5 is returned as a hexadecimal string. """ md5 = hashlib.md5() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(4096), b''): md5.update(chunk) return md5.hexdigest(...
c73b38b2f33732a488edac92493dfa993f4a293c
639,835
def read_file(filename) -> str: """Read the contents of the file into a string :param filename: path to the file to be read :return: string will contents of the file """ with open(filename, 'r', encoding='utf-8') as file_content: return file_content.read()
f97462388e8eb488247aaf63705c2c9e66ae51eb
639,836
def _keep_going(steps, num_steps, episodes, num_episodes): """ Modified version. Determine whether we've collected enough data """ if num_episodes and num_steps: return episodes < num_episodes and steps < num_steps # if num_episodes is set, this overrides num_steps if num_episodes: ...
e9985dba15a2c1ba968fc9972cf907cf2aa63b54
639,837
def query_successful(api_response): """This function reviews the API response from the Community API to verify whether or not the call was successful. :param api_response: The response from the API in JSON format :type api_response: dict :returns: Boolean indicating whether or not the API call was succ...
278c8d15c3903d72056c3df49faec3fcfe8eb025
639,838
def crop_image_to_bounding_box(img, bnd_box): """Crops the given image to the given bounding box""" result = img[bnd_box[0][1] : bnd_box[1][1] + 1, bnd_box[0][0] : bnd_box[1][0] + 1] return result
27d5d780f9712d72e973cb3de816b04e2ab3ec72
639,839
def load_image_list(img_dir, list_file): """load image list""" list_file_path = list_file j = open(list_file_path, 'r') image_list = [] label = [] for line in j: items = line.split() image_list.append(items[0].strip()) label.append(items[1].strip()) return label, imag...
453e7bee56a042194a8c26aa195859d6cb566854
639,840
import numpy def get_list_of_points(ts): """ This function creates a list of angles based on the time series. This list is used for convert the time series to a polygon. Keyword arguments: timeseries : numpy.ndarray Your time series. Returns ------- lists: ...
600b2cd5679a7a2c1ef5576aa20316c3b67a19f2
639,841
from typing import Tuple import secrets import hmac import hashlib def get_nonce_and_hash() -> Tuple[str, str]: """ Get a secure random nonce and a hmac of that nonce """ nonce: str = secrets.token_hex(32) nonce_hash: str = hmac.HMAC( bytes.fromhex(nonce), digestmod=hashlib.sha256 ).he...
3ad700c8a7b731cb751699a1a2812cbcd0e1a44b
639,842
import torch def accuracy(y_pred: torch.Tensor, y: torch.Tensor) -> float: """ Return predictive accuracy. Parameters --- y_pred: torch.Tensor (BATCH, NUM_CLASS) Predicted values. y: torch.Tensor (BATCH,) Real class values. """ return (y_pred.argmax(dim=1) == y).float(...
ce109660d411afe31620bd5d4010276e93921ae3
639,843
def compute_stringency_index(npi_policy): """ npi_policy['npi_workplace_closing'] = 3 npi_policy['npi_school_closing'] = 3 npi_policy['npi_cancel_public_events'] = 2 npi_policy['npi_gatherings_restrictions'] = 4 npi_policy['npi_close_publ...
c64e7d76292e826811a4b295bf2f1167d20e51dd
639,844
import os import re def get_slots(infold, modes): """ Find a lost of unique slot types in training and testing data. We use a single slot type name both for starting and continuation tokes (not using B-, I- notation). """ slots = set() for mode in modes: path = f'{infold}/{mode}set' ...
d75129d87c024cb971b406c5c0891b62176426db
639,845
def min(self, parameter_min): """ It returns the minimum value of a parameter and the value's indexes. Parameters ---------- parameter_min: str Name of the parameter. Returns ------- min_dict: dict Dictionary with the following format: { ...
5f71e69bc1525ce94a626b742c2df7ef45b5e85a
639,846
def filter_files(filetypes, files): """Filters a list of files based on a list of strings.""" filtered_files = [] for file_to_filter in files: for filetype in filetypes: filename = file_to_filter if type(file_to_filter) == "string" else file_to_filter.basename if filename.endswith(filetype): ...
6ae6490dbabc7bb8e7c75bba777250d610f196da
639,848
def get_folder(): """ Get folder via user input. """ return input("Folder: ")
e891ad2b53b6d8e0233458888d173eb75d6e2f55
639,849
import six def python_2_unicode_compatible(cls): """ Class decorator that provides appropriate Python 2 __unicode__ and __str__ based upon Python 3' __str__. """ if six.PY2: cls.__unicode__ = cls.__str__ cls.__str__ = lambda self: self.__unicode__().encode('utf-8') return cls
43071f169d57ef8eeb3de04004c14524fe29eccb
639,850
def estimate_fuse_passengers(fus_nb, FLOORS_NB, PASS_PER_TOILET, cabin_area,\ MASS_PASS, pass_density): """ The function evaluates the number of passengers members on board in case of an unconventional aircraft with fuselage. Source : passengers density is defined averaging...
65385f644302acde58ed2cf575f119ec210bc1ed
639,851
from typing import Dict import requests def google_oauth2_info() -> Dict: """Return Google's spec for their OAuth endpoints.""" resp = requests.get("https://accounts.google.com/.well-known/openid-configuration") info = resp.json() return info
46e8c5c0fefbfbc18e6045560f5ebc7157726194
639,852
from datetime import datetime def get_last_request_position(access_log_path, last_request): """ Find the last position of a request with ip and timestamp in an access logfile. Used to find all requests which are not yet immported. There could be multiple requests with the same ip and timestamp, theref...
92f70314278cb79665a378db92248844a94655d7
639,853
import re def parse_cookie_file(cookiefile): """find "config" request on XHR""" try: f_in = open(cookiefile) requests_header = '\n'.join([line for line in (row.strip() for row in f_in) if line]) f_in.close() auth = re.findall(r'authorization:\sBearer\s(.*)', requests_header) ...
0192739e21c7c616ecad7461f44a9f5e58ef52d4
639,854
from typing import OrderedDict def events_v2_data(alert, routing_key, with_record=True): """Helper method to generate the payload to create an event using PagerDuty Events API v2 Args: alert (Alert): Alert relevant to the triggered rule routing_key (str): Routing key for this PagerDuty integr...
dcc80d5640bd969b757ce01f9100c86551760f36
639,855
import torch def get_lengths(seq, device): """ Get lengths of batch of sequences :param seq: batch x V x seq_len :return: """ # print(seq.size()) eos = torch.zeros(seq.size()[1], dtype=torch.float, device=torch.device('cuda:0')) lengths = [] for sentence in seq: for i, word...
00d19f6d2c5f238ea53f41c22c0340d18493c5e0
639,856
import math import requests def getBiome(x, z, dx, dz): """**Returns the chunk data.**""" x = math.floor(x / 16) z = math.floor(z / 16) url = f'http://localhost:9000/chunks?x={x}&z={z}&dx={dx}&dz={dz}' try: response = requests.get(url) except ConnectionError: return -1 ...
b572747e705d85a7c300261dcc6183a97f050a95
639,858
def index_chunks(chunks): """ Turns a chunks array into a dictionary keyed by chapter :param chunks: :return: """ dict = {} for chunk in chunks: if not chunk['chp'] in dict: dict[chunk['chp']] = [] dict[chunk['chp']].append(chunk['firstvs']) return dict
59cf23312cdb932b194f223ec0dd96d5400ac3ca
639,859
def calc_Cinv_network_linear(LengthNetwork, gV): """ calculate annualised network investment cost with a linearized function. :param LengthNetwork: total length of the network in [m] :pram gV: globalvar.py :returns InvCa: annualised investment cost of the thermal network :rtype InvCa: float ...
09b906f9f5cc6d9fcb93b4e7df4df9b8c5a60dc1
639,860
import logging def addFilesToWMBSInBulk(filesetId, workflowName, files, isDBS=True, conn=None, transaction=None): """ _addFilesToWMBSInBulk Do a bulk addition of files into WMBS. This is a speedup. Assumes files are full dao objects """ if not files: # Nothin...
b0f8d8bb39a167fef2077a58e1e23723efbb9aed
639,861
from typing import Dict from typing import List def dict_to_list(data: Dict[str, Dict]) -> List[Dict]: """Convert a dictionary to a list of 1-element dictionaries. """ return [{k: v} for k, v in data.items()]
fbc29d06963f25ab7a6472e3d27ba357ff314b09
639,862
def _rk12_step(func, y0, dt): """Improved Euler-Integration step to integrate dynamics. Args: func: Function handle to time derivative. y0: Current state. dt: Integration step. Returns: Next state. """ dy = func(y0) y_ = y0 + dt * dy return y0 + dt / 2. * (dy + func(y_))
dc138f371c1ddd75190449a80d8565f117ce2406
639,863
from pathlib import Path def fixture_fixtures_path() -> Path: """Path to dir with fixture files""" return Path("tests/fixtures")
f290a5c38bb6f5b4b79733e80f41e603e3382b75
639,864
def sequence(request): """ Just grabs a Y from the set of Ys """ Y = request.param return Y
1e75719095bb1985f84ea308bec87b1420c10521
639,865
import os def _get_crawler_docker_run_command(city: str) -> str: """Returns the docker run command needed to trigger the crawler. Parameters ---------- city: str City to crawl sights for. Returns ------- run_command: str Docker run command for the crawler. """ ret...
2296acf8f219ff05201dfdf387e855e95b7ffe05
639,866
def delta_sigmoid(z): """Calculates derivative of sigmoid function Arguments: z (torch.Tensor) - a tensor for which gradient sigmoid has to be calculated Returns: result (torch.Tensor) - sigmoid gradient tensor. Size same as input z """ grad_sigmoid = z * (1 - z) return g...
9311e0fba3a32e80f39cc92dcd09365fd169ed3e
639,867
def msg2dict(msg): """Convert a generic ROS message into a dictionary (un-nested) :param msg: ROS message to convert :rtype: dict """ return {k: getattr(msg, k) for k in msg.get_fields_and_field_types().keys()}
52803702efc2ea804337eb53f4c28782c3ffa424
639,868
import argparse def get_argument_parser(): """Define command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '--epiweek', type=int, help='week when predictions were submitted') return parser
f181aa7ea0ce28e61158f0f0ec07c435bbe34631
639,869
import numpy def schwefel(values): """Schwefel's (Sine Root) Function. May be used for visualization of the population fitness. """ if not len(values): return 0 return 1.0 / ( 418.9829 * len(values) - numpy.sum(numpy.multiply( values, numpy.sin(numpy.sqrt(numpy.fabs(va...
7a7028e33462326902f6914b4118bb723e7c69e9
639,870
def srcds_functional(**filter_): """Enable SRCDS functional testing for a test case This decorator will cause the test case to be parametrised with addresses for Source servers as returned from the master server. The test case should request a fixture called ``address`` which is a two-item tuple of...
7ce110aaccffcb0dd6a1e55d5613fcc5871f5aad
639,871
import difflib def get_close_matches_icase(word, possibilities, *args, **kwargs): """Case-insensitive version of difflib.get_close_matches""" lword = word.lower() lpos = {p.lower(): p for p in possibilities} lmatch = difflib.get_close_matches(lword, lpos.keys(), *args, **kwargs) return [lpos[m] fo...
42b211f41a004af1eb52761f126badb5f8187977
639,872
import requests import json def get_consul_svc(svc_endpoint, request_params, service): """ Since consul does not have concept of prefix for service, so we are using tags for this purpose. """ consul_data = requests.get(svc_endpoint, params=request_params) body = json.loads(consul_data.text) re...
b5a875d5b2eb32deab79c03330ffe0b89f864071
639,873
def select_markers(contours, hierarchy, verbose=False, very_verbose=False): """ Based off of Galen's code. This doesn't work. It returns nothing. """ markers = [] for i, contour in enumerate(contours): if very_verbose: print(f"i: {i}") print(f"hierarchy[0][i][2]:\n{hi...
c2b34a483d66c34b891f12c6acb5847ebd6e7a81
639,874
def distribution_function(yb, x): """" Modulate the parabolic distribution y= a(b-x)**2 +c fct. with the following boundary conditions: - 1. x=0: y == 3 : follows from the initial distribution function - 2. Int[0,1] == 1: normalization criteria - 3. x=1: y == yb, where yb is the tunable pa...
646822e05e5d2673bf13a8a4062b282addea8e12
639,875
def pascal2snake(string: str): """String Convert: PascalCase to snake_case""" return ''.join( word.title() for word in string.split('_') )
96a3aa31cbb13bdc0ac801909225e71d3094b947
639,877
import sqlite3 import sys def connect_to_db(dbname, verbose=False): """ Connect to the database :param dbname: the database file name :param verbose: print addtional output :return: the database connection """ try: conn = sqlite3.connect(dbname) except sqlite3.Error as e: ...
94c38a2f07f03dd6ec6f70dfb73b6a48e64d1c86
639,878
def data_classification_level(dsv): """Returns the data classification level of the calculated data sensitivity value.""" if dsv < 15: return 1 elif 15 <= dsv < 100: return 2 elif 100 <= dsv < 150: return 3 else: return 4
074c1f6432f73674462aa58d2ee361238bb308ef
639,879
def apply_styles(graph, styles): """ Apply the styles to a Graphviz graph. """ graph.graph_attr.update( ('graph' in styles and styles['graph']) or {} ) graph.node_attr.update( ('nodes' in styles and styles['nodes']) or {} ) graph.edge_attr.update( ('edges' in styl...
3c81d8778b81144de28e59a30bdc2fbf14af8358
639,880
import pickle def load_arrays(name): """Load arrays from file.""" with open(name, 'rb') as file: coords = pickle.load(file) edof = pickle.load(file) dofs = pickle.load(file) bdofs = pickle.load(file) elementmarkers = pickle.load(file) boundaryElements = pickle....
ffde1bc81dfe3121aef9cc70bfe00922e22d2d21
639,881
def from_dataclass(d): """ Обратная функция dacite.from_dict :param d: dataclass or dict """ if hasattr(d, "__dict__"): return from_dataclass(d.__dict__) for k, v in d.items(): if isinstance(v, list): for index, item in enumerate(v): if hasattr(item,...
3933e6710833d7fedf700a3e4830c56a2ac6f548
639,882
def get_el_lines_dets(el, *, ignore_trailing_lines=False): """ How long is the snippet of code that completely wraps up this element? If there are no "trailing lines" it is simple because the AST includes line numbers. We just get the min and max line number values. But if there are, these trailing ...
a026e605f94f810acd0c98d1d7e585f6433a3456
639,883
def read_translated_file(filename, data): """Read a file inserting data. Arguments: filename (str): file to read data (dict): dictionary with data to insert into file Returns: list of lines. """ if filename: with open(filename) as f: text = f.read().repl...
423f111730335b0fcf4d9178b3cd5e6cda4e0d1f
639,885
def not_better_than_after(minimal, n_iter): """Return a stop criterion that returns True if the error is not less than `minimal` after `n_iter` iterations.""" def inner(info): return info['n_iter'] > n_iter and info['loss'] >= minimal return inner
cccc50da383f53da61c35bf000d1ac7431ef3107
639,888
def int_or_None(val): """converter that casts val to int, or returns None if val is string 'None'""" if val == 'None': return None else: return int(val)
a385f16302edc98024680ced44e18e95c2c33795
639,889
def Fx(y,z): """ X Prime """ xt = -y - z return xt
4a55d2bb83fce5adba03aa04cde773ec8ff52adf
639,890
def MACD(DF,a,b,c): """function to calculate MACD typical values a = 12; b =26, c =9""" df = DF.copy() # Since changes will be made to our dataframe, its better we make changes to the copy of the data frame df["MA_Fast"]=df["Close"].ewm(span=a,min_periods=a).mean() df["MA_Slow"]=df["Close"]....
6eaac53c33652917b411faf48e4b10a37a9f8362
639,891
from operator import mul def vmul(V1,V2): """ Multiply the components of 2 vectors <div class=jython> VMUL (V1, V2) = [ u1*u2, v1*v2 ] </div> """ return mul(V1,V2)
3f1eeb18dbaf59a65bff9f68fdc658b1252d83cb
639,892
def create_test_partition(df, N_batch): """ Creates a partition of the dataset into a single test set. Parameters ---------- df : pandas dataframe Dataframe corresponding to the dataset. split_ratio : float Training sample percentage, must be between 0 and 1....
ef80c0beb7abdeb95d1344bb530b7ce47a3243f8
639,893
def dist_interval(v, mi, ma): """ Distance from v to interval [min,max] """ if v < mi: return mi - v if v > ma: return v - ma return 0
bf8329658c7e59469f2c48bdf1c4200a06edbb81
639,894
def prune_nones(mydict): """ Remove keys from `mydict` whose values are `None` :arg mydict: The dictionary to act on :rtype: dict """ # Test for `None` instead of existence or zero values will be caught return dict([(k, v) for k, v in mydict.items() if v != None and v != 'None'])
6b61303733a81781fb0e243178b8b549476b3727
639,895
import asyncio async def worker5(): """ worker5 :return: """ await asyncio.sleep(2) return 2 / 0
2c5e498f06acd285fb9a0c91e5ae94a8e61182d1
639,896
def str_to_act(env, actions): """ Simplifies specifying actions for the scripted part of the agent. Some examples for a string with a single action: 'craft:planks' 'camera:[10,0]' 'attack' 'jump' '' There should be no spaces in single actions, as we use spaces to ...
44b62aa04be845b00ad72678bf2402384483742d
639,898
def namedModule(name): """ Return a module given its name. """ topLevel = __import__(name) packages = name.split(".")[1:] m = topLevel for p in packages: m = getattr(m, p) return m
d588d30b7854f01ee64b6d6eb6455bb0bfff4719
639,899
def add_(string = ''): """ Add an _ if string is not empty """ s = '' if string: s = string + '_' return s
1f8f4c1e41eda3ae2d86338c8fd7077d6450eef4
639,900
def saturated_comp(data, threshold): """Clip the max intensity to lower intensity of saturated pixels.""" data[data > threshold] = threshold return data
08506160c72c2240878960490ef21c378b1d2b5b
639,901
def mkprop(fb, typeid, key, name='', vtype=None, master_property=None): """helper to create a new property """ if name == '': name = key wq = { 'create': 'unless_exists', 'id': None, 'type': '/type/property', 'name': name, 'schema': typeid, ...
dea2edc39a87e54405ab99757d131559043a5bd3
639,902
import json def load_json_schema(filename=None): """ Loads the given schema file """ if filename is None: return with open(filename) as schema_file: schema = json.loads(schema_file.read()) return schema
f313bba5e3549d5ae161e5ec7a962e92e4e2d96f
639,903
def proc_create_query(prname, prtext, argslist=None): """Base method for creating procedure with given name, body and args.""" prtext = prtext.replace("'", "''") TEMPLATE = """ CREATE OR REPLACE FUNCTION {prname}({argstext}) RETURNS VOID AS' {prtext}' LANGUAGE plpgsql; """ argstext =...
c767b5d30dae427d9b559313cfbede4618bfb5db
639,904
def get_game_ids(experiment_id): """ Get the games (train, eval) belonging to the given experiment ID. Training games will be randomized, where the evaluation games will not. """ if experiment_id in [1]: return [10000, ] * 10, \ [10000 + i for i in range(1, 21)] elif exper...
e8e9ace23a1d4a480ec506ce8fb865c13b223819
639,905
def dir_method(): """dir: List of accessible attributes and methods.""" class _ItemClass: def __dir__(self): return ['ghost_attribute'] + list(self.__dict__.keys()) def __getattr__(self, attribute): if attribute != 'ghost_attribute': raise AttributeError...
28578e1c1abdb554f0d2c5569b8215fdafb2e80e
639,906
from typing import Dict import re def hair_color(full_passports: Dict[str, str], key: str = "hcl") -> bool: """ hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f. """ if full_passports[key].startswith('#') and len(full_passports[key][1:]) == 6: match = re.findall(r'[0-9]...
c4321259892b6c9ca36aea2cc945f0c8cee52b6c
639,907
def yields_fracs_peaks_tobs(result): """ The result pkl with every lightcurve is too large to shuffle from hyperion to local This fcn is giving from my result data:the yields and fracs of detected SNe and the distribution of peak magnitudes for each lens and tobs """ ndetectSNe,snia,sncc = result[0]...
e19449d804697da9dec1dcbb48449161680ebeb4
639,908
from typing import Any from typing import Optional import operator def _ensure_int(item: Any, item_name: Optional[str] = None) -> int: """Ensure a variable is an integer. Parameters ---------- item : Any Item to check. item_name : str | None Name of the item to show inside the err...
329a7b0a2b190c858595b6cb43eea633f342ec30
639,909
import os import stat def file_is_link(path, st=None): """Check if a path is a symlink or Windows directory junction Args: st: known stat for the path for better performance """ if st is None: try: st = os.lstat(path) except (OSError, ValueError, AttributeError): ...
aec1427066a32ec8dd306d9f1c3d400468e406d5
639,910
import socket def get_ip_hostname(node): """ Takes in either a hostname or an IP address and returns (ip, hostname). Note if IP is given both values will be the same, i.e. we don't actually care about finding the hostname if user specified an IP""" if '.' in node: return (node, node) ...
902a017b08044c01d68a955afbaa3d7e79bc415a
639,911
def Total_Dots(link): """ Function to calculate the Total Number of Dots in a URL """ dot='.' count=0 for i in link: if i==dot: count+=1 return count
ca669c57c7d22743b2b530b77d31101d9cdb0a91
639,912
def kappa_no_prevalence_calc(overall_accuracy): """ Calculate kappa no prevalence. :param overall_accuracy: overall accuracy :type overall_accuracy : float :return: kappa no prevalence as float """ try: result = 2 * overall_accuracy - 1 return result except Exception: ...
d143b67eeff0de5f5b01d2129861437c5c33f463
639,913
def _GetAllocatorDumps(trace: dict) -> list: """Takes in a trace (as returned from |LoadTrace|), and returns the parts of it related to the allocators. Args: trace: Trace content as returned by LoadTrace. Returns: The parts of the trace related to allocator metrics. Note that these entries are tak...
c0f9c6ccb9ca1bf13fd8b6e83702fb63b91e99cc
639,914
import argparse def get_args(): """ Get command-line arguments """ parser = argparse.ArgumentParser( description="""Conditionals and Loops. Given two positive integers, a < b < 10000, this program returns the sum of all odd integers from a through b, inclusively.""", formatter...
09d7d8f2c1bdc3038871e89ab3c73f93ef99d08b
639,915
def binomVariance(n, p): """ The variance is the squared distance from the mean. See reference, I don't fully understand yet. This involves Burnoulli variables X and Y """ variance_of_Y = p * (1- p) variance_of_X = n * variance_of_Y print("variance of X = ", variance_of_X) return v...
77c6596811f0a7e4df4038c030fc6910ef0e64b9
639,916
def wdwd_obj(X, y, W, C, beta, offset, eta): """ Objective function for DWD. """ d = y * (X.dot(beta) + offset) + eta return sum(W / d) + C * sum(eta)
13a5e828c8b8c36cd9a7dc66238339cc5fa21493
639,917
def etree_to_dict(t): """Convert etree to dictionary""" d = {t.tag : map(etree_to_dict, t.iterchildren())} d.update(('@' + k, v) for k, v in t.attrib.iteritems()) d['text'] = t.text return d
b430058370124e1b5e1100d3b8269f9b6b613805
639,918
import hashlib def checksum(content): """ SHA256+MD5 196 characters """ sha256 = hashlib.sha256() md5 = hashlib.md5() sha256.update(content.strip()) md5.update(content.strip()) return sha256.hexdigest().lower() + md5.hexdigest().lower()
8c7655eeaaee044b449ab435f9d23adb15ae419e
639,919
def getprotseqfromdb(seqdb, locheader): """Parse the HMM hit protein sequence from the seqdb parameters ---------- seqdb filename, name of the seqdb file used for HMMering locheader >{recordnumber}_{loc}, header for each protein sequence returns ---------- ret = protein s...
79cce283bd12e9f44381402468272d1fdb0f896a
639,920
def _find_sa_sess(decorated_obj): """ The decorators will by default use sqlalchemy.db to find the SQLAlchemy session. However, if the function being decorated is a method of a a class and that class has a _sa_sess() method, it will be called to retrieve the SQLAlchemy session that ...
5c2bf6c12afa0022a6439b7359558d9daed85000
639,921
import os def find_allowed_durations(start_len, end_len, args): """Given the start and end duration, find a set of allowed durations spaced by args.factor%. Also write out the list of allowed durations and the corresponding allowed lengths (in frames) on disk. Returns ------- ...
b492db0d55919838601680c2b33a4240f5793d32
639,923
def Block_f(name, text): """ :param name: The "name" of this Block :param text: The "text" of this Block """ return '\\begin{block}{' + name + '}\n' + text + '\n\\end{block}\n'
6738bfca4d5a8ebc10d8bbcf57dab707ca1083af
639,924
from typing import BinaryIO def read_batch_from_end(byte_stream: BinaryIO, *, size: int, end_position: int) -> bytes: """ Reads batch from the end of given byte stream. >>> import io >>> byte_stream = io.BytesIO(b'Hello\\nWorld!'...
151be9c5b06bc36379f2848a9d995dd4b85f9aa3
639,925
def rivers_with_station(stations): """receives list of station obhjects and returns a list of names of rivers that have at least one station on""" rivers = set() for station in stations: rivers.add(station.river) return rivers
fdf415d5a3a88f6d4ac94069a623c38c48294b4d
639,926
def replace(node, **kw): """Equivalent to namedtuple's _replace. When **kw is empty simply returns node itself. >>> o = BinOp(Add(), NumberConstant(2), NumberConstant(3)) >>> o2 = replace(o, op=Sub(), left=NumberConstant(3)) >>> print(o, o2) (2 + 3) (3 - 3) """ if kw: vals =...
63f2872c08ce6a63f6280c9bf25d2deca4f5d932
639,927