content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import itertools import random def brutekeys(pinlength, keys="0123456789", randomorder=False): """ Returns a list of all possibilities to try, based on the length of s and buttons given. Yeah, lots of slow list copying here, but who cares, it's dwarfed by the actual guessing. """ allpossible = list(itertools.i...
42f659e37468073c42117d1f4d6235f08aedde59
3,653,800
def return_figures(): """Creates four plotly visualizations Args: None Returns: list (dict): list containing the four plotly visualizations """ df = query_generation('DE', 14) graph_one = [] x_val = df.index for energy_source in df.columns: y_val = df[energ...
c89fe79d12173bc0b167e43e81d3adf19e81eb7b
3,653,801
def create_central_storage_strategy(): """Create a CentralStorageStrategy, using a GPU if it is available.""" compute_devices = ['cpu:0', 'gpu:0'] if ( tf.config.list_logical_devices('GPU')) else ['cpu:0'] return tf.distribute.experimental.CentralStorageStrategy( compute_devices, parameter_device='cpu...
46cc64d6cb888f51513a2b7d5bb4e28af58b5a29
3,653,802
def ToolStep(step_class, os, **kwargs): """Modify build step arguments to run the command with our custom tools.""" if os.startswith('win'): command = kwargs.get('command') env = kwargs.get('env') if isinstance(command, list): command = [WIN_BUILD_ENV_PATH] + command else: command = WIN_...
30bdf2a1f81135150230b5a894ee0fa3c7be4fa4
3,653,803
def get_security_groups(): """ Gets all available AWS security group names and ids associated with an AWS role. Return: sg_names (list): list of security group id, name, and description """ sg_groups = boto3.client('ec2', region_name='us-west-1').describe_security_groups()['SecurityGroups']...
48a30454a26ea0b093dff59c830c14d1572d3e11
3,653,804
def traverseTokens(tokens, lines, callback): """Traverses a list of tokens to identify functions. Then uses a callback to perform some work on the functions. Each function seen gets a new State object created from the given callback method; there is a single State for global code which is given None in the co...
4fcdfc4505a0a3eb1ba10a884cb5fc2a2714d845
3,653,805
from typing import Any def publications_by_country(papers: dict[str, Any]) -> dict[Location, int]: """returns number of published papers per country""" countries_publications = {} for paper in papers: participant_countries = {Location(city=None, state=None, country=location.country) \ ...
7295fd9491d60956ca45995efc6818687c266446
3,653,806
def dequote(str): """Will remove single or double quotes from the start and end of a string and return the result.""" quotechars = "'\"" while len(str) and str[0] in quotechars: str = str[1:] while len(str) and str[-1] in quotechars: str = str[0:-1] return str
e6377f9992ef8119726b788c02af9df32c722c28
3,653,807
import numpy def uccsd_singlet_paramsize(n_qubits, n_electrons): """Determine number of independent amplitudes for singlet UCCSD Args: n_qubits(int): Number of qubits/spin-orbitals in the system n_electrons(int): Number of electrons in the reference state Returns: Number of indep...
408c9158c76fba5d118cc6603e08260db30cc3df
3,653,808
def variance(timeseries: SummarizerAxisTimeseries, param: dict): """ Calculate the variance of the timeseries """ v_mean = mean(timeseries) # Calculate variance v_variance = 0 for ts, value in timeseries.values(): v_variance = (value - v_mean)**2 # Average v_variance = len(timeseries.values) i...
9b8c0e6a1d1e313a3e3e4a82fe06845f4d996620
3,653,809
def setup_i2c_sensor(sensor_class, sensor_name, i2c_bus, errors): """ Initialise one of the I2C connected sensors, returning None on error.""" if i2c_bus is None: # This sensor uses the multipler and there was an error initialising that. return None try: sensor = sensor_class(i2c_bus...
62633c09f6e78b43fca625df8fbd0d20d866735b
3,653,810
def argparse_textwrap_unwrap_first_paragraph(doc): """Join by single spaces all the leading lines up to the first empty line""" index = (doc + "\n\n").index("\n\n") lines = doc[:index].splitlines() chars = " ".join(_.strip() for _ in lines) alt_doc = chars + doc[index:] return alt_doc
f7068c4b463c63d100980b743f8ed2d69b149a97
3,653,811
import ctypes def iterator(x, y, z, coeff, repeat, radius=0): """ compute an array of positions visited by recurrence relation """ c_iterator.restype = ctypes.POINTER(ctypes.c_double * (3 * repeat)) start = to_double_ctype(np.array([x, y, z])) coeff = to_double_ctype(coeff) out = to_double_ctype(...
82c32dddf2c8d0899ace56869679ccc8dbb36d22
3,653,812
import webbrowser def open_pep( search: str, base_url: str = BASE_URL, pr: int | None = None, dry_run: bool = False ) -> str: """Open this PEP in the browser""" url = pep_url(search, base_url, pr) if not dry_run: webbrowser.open_new_tab(url) print(url) return url
2f23e16867ccb0e028798ff261c9c64eb1cdeb31
3,653,813
def random_sparse_matrix(n, n_add_elements_frac=None, n_add_elements=None, elements=(-1, 1, -2, 2, 10), add_elements=(-1, 1)): """Get a random matrix where there are n_elements.""" n_total_elements = n * n n_diag_elements = n fra...
41ea01c69bd757f11bbdb8a259ec3aa1baabadc2
3,653,814
import uuid def is_uuid_like(val): """Returns validation of a value as a UUID. :param val: Value to verify :type val: string :returns: bool .. versionchanged:: 1.1.1 Support non-lowercase UUIDs. """ try: return str(uuid.UUID(val)).replace("-", "") == _format_uuid_string(va...
fc0b9618ede3068fe5946948dfbe655e64b27ba8
3,653,815
import argparse def is_positive_integer(value: str) -> int: """ Helper function for argparse. Raise an exception if value is not a positive integer. """ int_value = int(value) if int_value <= 0: raise argparse.ArgumentTypeError("{} is not a positive integer".format(value)) return int_value
4f5e2fd4e95e92b69bb8073daafbf8989037657b
3,653,816
from typing import List from typing import Tuple def merge_overlapped_spans(spans: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """ Merge overlapped spans Parameters ---------- spans: input list of spans Returns ------- merged spans """ span_sets = list() for span in...
0ea7f2a730274f7a98f25b8df22754ec79e8fce7
3,653,817
def network(dataframe, author_col_name, target_col_name, source_col_name=None): """ This function runs a Network analysis on the dataset provided. :param dataframe: DataFrame containing the data on which to conduct the activity analysis. It must contain at least an *author*, a *target* and a *sourc...
edb2942e1e92cad64609819994a4e10b1de85497
3,653,818
def get_cert_and_update_domain( zappa_instance, lambda_name, api_stage, domain=None, manual=False, ): """ Main cert installer path. """ try: create_domain_key() create_domain_csr(domain) get_cert(zappa_instance) create_chained_certificate() w...
8ce4d06af0d923165dbbe4c6cbb7617f8e20557f
3,653,819
def _ww3_ounp_contents(run_date, run_type): """ :param str run_type: :param run_date: :py:class:`arrow.Arrow` :return: ww3_ounp.inp file contents :rtype: str """ start_date = ( run_date.format("YYYYMMDD") if run_type == "nowcast" else run_date.shift(days=+1).format("...
fda73d25c39c5bd46d791e6745fa72a0285edcdc
3,653,820
import logging def EMLP(rep_in,rep_out,group,ch=384,num_layers=3): """ Equivariant MultiLayer Perceptron. If the input ch argument is an int, uses the hands off uniform_rep heuristic. If the ch argument is a representation, uses this representation for the hidden layers. Individual layer r...
aa4a1b1286ac1c96bedfe82813d9d24f36aabe96
3,653,821
def decompress(data): """ Decompress data in one shot. """ return GzipFile(fileobj=BytesIO(data), mode='rb').read()
db32cb2b9e2ddeb3a38901460d0882ceee9cab9e
3,653,822
import re def str_to_rgb(arg): """Convert an rgb string 'rgb(x,y,z)' to a list of ints [x,y,z].""" return list( map(int, re.match(r'rgb\((\d+),\s*(\d+),\s*(\d+)\)', arg).groups()) )
f8920373d5941fb231c1ae0d732fd04558615bc3
3,653,823
def vshift(x, shifts=0): """shift batch of images vertically""" return paddle.roll(x, int(shifts*x.shape[2]), axis=2)
cb00948cb58d3c2c13628d44cc36e6cd2ab487ee
3,653,824
def index(): """Shows book titles and descriptions""" tagid = request.query.tagid books = [] if tagid: try: tag = Tag.get(tagid) books = tag.books.all() except Tag.DoesNotExist: pass if not books: books = Book.all().order_by("title") return dict(books=book...
ae1fb3502f75a09577da489fe2488cbe78f699f7
3,653,825
import os import yaml def _GetExternalDataConfig(file_path_or_simple_spec, use_avro_logical_types=False, parquet_enum_as_string=False, parquet_enable_list_inference=False): """Returns a ExternalDataConfiguration from the file or specif...
44b30b8af9a95ea23be6cac071641cb5d4792562
3,653,826
import errno def _linux_iqn(): """ Return iSCSI IQN from a Linux host. """ ret = [] initiator = "/etc/iscsi/initiatorname.iscsi" try: with salt.utils.files.fopen(initiator, "r") as _iscsi: for line in _iscsi: line = line.strip() if line.star...
d7ae097a00c8df15208e91978d3acda1eaf8de62
3,653,827
def generate_file_storage_name(file_uri: str, suffix: str) -> str: """ Generate a filename using the hash of the file contents and some provided suffix. Parameters ---------- file_uri: str The URI to the file to hash. suffix: str The suffix to append to the hash as a part of the...
08087e86e1f70e0820cf9e3263c7a419de13ffcc
3,653,828
def mullerlyer_parameters(illusion_strength=0, difference=0, size_min=0.5, distance=1): """Compute Parameters for Müller-Lyer Illusion. Parameters ---------- illusion_strength : float The strength of the arrow shapes in biasing the perception of lines of unequal lengths. A positive sign ...
61631be407aa25608e1321f7e87e030bca9fa90d
3,653,829
def filter_for_corsi(pbp): """ Filters given dataframe for goal, shot, miss, and block events :param pbp: a dataframe with column Event :return: pbp, filtered for corsi events """ return filter_for_event_types(pbp, {'Goal', 'Shot', 'Missed Shot', 'Blocked Shot'})
9add922fe3aa4ded63b4032b8fe412bbc5611f3e
3,653,830
from typing import Dict from typing import Tuple import json import hashlib def upload(msg: Dict, public_key: bytes, ipns_keypair_name: str = '') -> Tuple[str, str]: """Upload encrypted string to IPFS. This can be manifest files, results, or anything that's been already encrypted. Optionally pi...
3dc1b12e57ce0054a1bf5b534f92ed7130187a53
3,653,831
def test_sakai_auth_url(oauth_mock): """ Test auth url retrieval for Sakai. Test that we can retrieve a formatted Oauth1 URL for Sakai """ def mock_fetch_token(mock_oauth_token, mock_oauth_token_secret): def mock_token_getter(mock_url): return { 'oauth_token': mo...
fc9321d5b88379fb08d40b8dadece1c3fb31b26a
3,653,832
from typing import Tuple from typing import List from typing import Iterable def nodes_and_groups(expr: Expression) -> Tuple[List[Expression], Iterable[List[int]]]: """ Returns a list of all sub-expressions, and an iterable of lists of indices to sub-expressions that are equivalent. Example 1: ...
bf5087fa5c4dd36e614c5e9227fd3337960dc9c6
3,653,833
def masterxprv_from_electrummnemonic(mnemonic: Mnemonic, passphrase: str = "", network: str = 'mainnet') -> bytes: """Return BIP32 master extended private key from Electrum mnemonic. Note that for a 'standard' mnemonic the derivation pat...
6642aba45eb72b5f366c52862ce07ddbf05d80f8
3,653,834
def release_(ctx, version, branch, master_branch, release_branch, changelog_base, force): """ Release a branch. Note that this differs from the create-release command: 1. Create a Github release with the version as its title. 2. Create a commit bumping the version of setup.py on top of t...
e7a9de4c12f3eb3dfe3d6272ccb9254e351641b9
3,653,835
def get_namedtuple_from_paramnames(owner, parnames): """ Returns the namedtuple classname for parameter names :param owner: Owner of the parameters, usually the spotpy setup :param parnames: Sequence of parameter names :return: Class """ # Get name of owner class typename = type(owner)....
4c0b2ca46e2d75d1e7a1281e58a3fa6402f42cf0
3,653,836
def readNotificationGap(alarmName): """ Returns the notificationGap of the specified alarm from the database """ cur = conn.cursor() cur.execute('Select notificationGap FROM Alarms WHERE name is "%s"' % alarmName) gapNotification = int(cur.fetchone()[0]) conn.commit() return gapNotificat...
afa7bd0e510433e6a49ecd48937f2d743f8977e4
3,653,837
def vertical_line(p1, p2, p3): """ 过点p3,与直线p1,p2垂直的线 互相垂直的线,斜率互为互倒数 :param p1: [x,y] :param p2: [x,y] :param p3: [x,y] :return: 新方程的系数[na,nb,nc] """ line = fit_line(p1, p2) a, b, c = line # ax+by+c=0;一般b为-1 # 以下获取垂线的系数na,nb,nc if a == 0.: # 原方程为y=c ;新方程为x=-nc na...
e1644edf7702996f170b6f53828e1fc864151759
3,653,838
def _get_value(key, entry): """ :param key: :param entry: :return: """ if key in entry: if entry[key] and str(entry[key]).lower() == "true": return True elif entry[key] and str(entry[key]).lower() == "false": return False return entry[key] ret...
93820395e91323939c8fbee653b6eabb6fbfd8eb
3,653,839
def calculate_bounded_area(x0, y0, x1, y1): """ Calculate the area bounded by two potentially-nonmonotonic 2D data sets This function is written to calculate the area between two arbitrary piecewise-linear curves. The method was inspired by the arbitrary polygon filling routines in vector software prog...
1cdf853a829e68f73254ac1073aadbc29abc4e2a
3,653,840
import requests def login(): """ Login to APIC-EM northbound APIs in shell. Returns: Client (NbClientManager) which is already logged in. """ try: client = NbClientManager( server=APIC, username=APIC_USER, password=APIC_PASSWORD, ...
8a4fd0122769b868dc06aeba17c15d1a2e0055a2
3,653,841
import numpy def transfocator_compute_configuration(photon_energy_ev,s_target,\ symbol=["Be","Be","Be"], density=[1.845,1.845,1.845],\ nlenses_max = [15,3,1], nlenses_radii = [500e-4,1000e-4,1500e-4], lens_diameter=0.05, \ sigmaz=6.46e-4, alpha = 0.55, \ tf_p=5960, tf_q...
3c25d701117df8857114038f92ebe4a5dee4097f
3,653,842
import logging import xml def flickrapi_fn(fn_name, fn_args, # format: () fn_kwargs, # format: dict() attempts=3, waittime=5, randtime=False, caughtcode='000'): """ flickrapi_fn Runs flickrapi fn_name ...
fcdb050824aa53ef88d0b879729e3e5444d221a7
3,653,843
def load_data(CWD): """ loads the data from a parquet file specified below input: CWD = current working directory path output: df_raw = raw data from parquet file as pandas dataframe """ folderpath_processed_data = CWD + '/data_sample.parquet' df_raw = pd.read_parquet(folderpath_processed_da...
8ba8d77b81e61f90651ca57b186faf965ec51c73
3,653,844
import subprocess def run_command(cmd): """Run command, return output as string.""" output = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0] return output.decode("ascii")
0996d76ab1980c2fad262f8fd227ac50772849d2
3,653,845
def http_body(): """ Returns random binary body data. """ return strategies.binary(min_size=0, average_size=600, max_size=1500)
5789dfc882db32eefb6c543f6fd494fe621b1b8e
3,653,846
def run(data_s: str) -> tuple[int, int]: """Solve the puzzles.""" results = [check(line) for line in data_s.splitlines()] part1 = sum(result.error_score for result in results) part2 = int(median(result.completion_score for result in results if result.ok)) return part1, part2
e5870924769b23300b116ceacae3b8b73d4643f3
3,653,847
import os import logging def _getRotatingFileHandler(filename, mode='a', maxBytes=1000000, backupCount=0, encoding='utf-8', uid=None, gid=None): """Get a :class:`logging.RotatingFileHandler` with a logfile which is readable+writable only by the given **uid** and **gid**. :para...
d6415f8b4e86dad0978e96ea8e07fefa1fdb3427
3,653,848
import functools def _inject(*args, **kwargs): """Inject variables into the arguments of a function or method. This is almost identical to decorating with functools.partial, except we also propagate the wrapped function's __name__. """ def injector(f): assert callable(f) @functoo...
40ba8ecd01880ebff3997bc16feb775d6b45f711
3,653,849
def frame_drop_correctors_ready(): """ Checks to see if the frame drop correctors 'seq_and_image_corr' topics are all being published. There should be a corrector topic for each camera. """ camera_assignment = get_camera_assignment() number_of_cameras = len(camera_assignment) number_of_c...
85c991de9cecd87cd20f7578e1201340d1a7f23a
3,653,850
from typing import List from typing import Dict from typing import Any import yaml def loads(content: str) -> List[Dict[str, Any]]: """ Load the given YAML string """ template = list(yaml.load_all(content, Loader=SafeLineLoader)) # Convert an empty file to an empty dict if template is None: ...
a2c455b40a0b20c4e34af93e08e9e9ae1bb9ab7d
3,653,851
def get_ndim_horizontal_coords(easting, northing): """ Return the number of dimensions of the horizontal coordinates arrays Also check if the two horizontal coordinates arrays same dimensions. Parameters ---------- easting : nd-array Array for the easting coordinates northing : nd-...
a35bf0064aff583c221e8b0c28d8c50cea0826aa
3,653,852
async def info(): """ API information endpoint Returns: [json] -- [description] app version, environment running in (dev/prd), Doc/Redoc link, Lincense information, and support information """ if RELEASE_ENV.lower() == "dev": main_url = "http://localhost:5000" else: ...
3404ac622711c369ae006bc0edba10f57e825f22
3,653,853
import json async def info(request: FasttextRequest): """ Returns info about the supervised model TODO - Add authentication :param request: :return: """ app: FasttextServer = request.app model: SupervisedModel = app.get_supervised_model() model_info = { "dimensions": model...
4c308839df53be7f074b1b3298d1535ff300df07
3,653,854
import torch def hard_example_mining(dist_mat, labels, return_inds=False): """For each anchor, find the hardest positive and negative sample. Args: dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N] labels: pytorch LongTensor, with shape [N] return_inds: whether to ...
15fd533cf74e6cd98ac0fa2e8a83b2734861b9ca
3,653,855
from datetime import datetime def trace(func): """Trace and capture provenance info inside a method /function.""" setup_logging() @wraps(func) def wrapper(*args, **kwargs): activity = func.__name__ activity_id = get_activity_id() # class_instance = args[0] class_insta...
8d624ef70ea4278141f8da9989b3d6787ec003c7
3,653,856
def broadcast_ms_tensors(network, ms_tensors, broadcast_ndim): """Broadcast TensorRT tensors to the specified dimension by pre-padding shape 1 dims""" broadcasted_ms_tensors = [None] * len(ms_tensors) for i, t in enumerate(ms_tensors): tensor = network.nodes[t] if len(tensor.shape) < broad...
28e017aab2389faff11f2daecc696a64f2024360
3,653,857
def get_rbf_gamma_based_in_median_heuristic(X: np.array, standardize: bool = False) -> float: """ Function implementing a heuristic to estimate the width of an RBF kernel (as defined in the Scikit-learn package) from data. :param X: array-like, shape = (n_samples, n_features), feature matrix :para...
0a9238b4ba2c3e3cc4ad1f01c7855954b9286294
3,653,858
def winter_storm( snd: xarray.DataArray, thresh: str = "25 cm", freq: str = "AS-JUL" ) -> xarray.DataArray: """Days with snowfall over threshold. Number of days with snowfall accumulation greater or equal to threshold. Parameters ---------- snd : xarray.DataArray Surface snow depth. ...
cef1fa5cf56053f74e70542250c64b398752bd75
3,653,859
def _check_whitelist_members(rule_members=None, policy_members=None): """Whitelist: Check that policy members ARE in rule members. If a policy member is NOT found in the rule members, add it to the violating members. Args: rule_members (list): IamPolicyMembers allowed in the rule. poli...
47f2d6b42f2e1d57a09a2ae6d6c69697e13d03a7
3,653,860
import re import uuid def get_mac(): """This function returns the first MAC address of the NIC of the PC without colon""" return ':'.join(re.findall('..', '%012x' % uuid.getnode())).replace(':', '')
95ebb381c71741e26b6713638a7770e452d009f2
3,653,861
async def get_clusters(session, date): """ :param session: :return: """ url = "%s/file/clusters" % BASE_URL params = {'date': date} return await get(session, url, params)
8ef55ba14558a60096cc0a96b5b0bc2400f8dbff
3,653,862
def extract_attributes_from_entity(json_object): """ returns the attributes from a json representation Args: @param json_object: JSON representation """ if json_object.has_key('attributes'): items = json_object['attributes'] attributes = recursive_for_attribute_v2(items) ...
d01886fac8d05e82fa8c0874bafc8860456ead0c
3,653,863
def get_config_with_api_token(tempdir, get_config, api_auth_token): """ Get a ``_Config`` object. :param TempDir tempdir: A temporary directory in which to create the Tahoe-LAFS node associated with the configuration. :param (bytes -> bytes -> _Config) get_config: A function which takes a ...
682bd037944276c8a09bff46a96337571a605f0e
3,653,864
from datetime import datetime def make_journal_title(): """ My journal is weekly. There's a config option 'journal_day' that lets me set the day of the week that my journal is based on. So, if I don't pass in a specific title, it will just create a new journal titled 'Journal-date-of-next-journal-day.md'. ""...
5bd855c0f3fe639127f48e4386cde59bca57c62f
3,653,865
def calc_base_matrix_1qutrit_y_01() -> np.ndarray: """Return the base matrix corresponding to the y-axis w.r.t. levels 0 and 1.""" l = [[0, -1j, 0], [1j, 0, 0], [0, 0, 0]] mat = np.array(l, dtype=np.complex128) return mat
7618021173464962c3e9366d6f159fad01674feb
3,653,866
def get_feature_names_small(ionnumber): """ feature names for the fixed peptide length feature vectors """ names = [] names += ["pmz", "peplen"] for c in ["bas", "heli", "hydro", "pI"]: names.append("sum_" + c) for c in ["mz", "bas", "heli", "hydro", "pI"]: names.append("mean_" + c) names.append("mz_ion"...
fbffe98af0cffb05a6b11e06786c5a7076449146
3,653,867
def vectorproduct(a,b): """ Return vector cross product of input vectors a and b """ a1, a2, a3 = a b1, b2, b3 = b return [a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1]
adb9e7c4b5150ab6231f2b852d6860cd0e5060a0
3,653,868
from typing import Optional import requests import json def get_tasks( id: Optional[str], name: Optional[str], completed: Optional[bool], comment: Optional[str], limit: Optional[str], ) -> str: """ :param id: This optional parameter accepts a string and response is filtered based on this value :param ...
aceacf01ea97440836b997ea631b83b2a3e9c198
3,653,869
def f_test_probability(N, p1, Chi2_1, p2, Chi2_2): """Return F-Test probability that the simpler model is correct. e.g. p1 = 5.; //number of PPM parameters e.g. p2 = p1 + 7.; // number of PPM + orbital parameters :param N: int Number of data points :param p1: int Number of para...
21cf7c9eb455309131b6b4808c498927c3d6e485
3,653,870
def validate_user(headers): """Validate the user and return the results.""" user_id = headers.get("User", "") token = headers.get("Authorization", "") registered = False if user_id: valid_user_id = user_id_or_guest(user_id) registered = valid_user_id > 1 else: valid_user...
331608df719d03afd57079d9baba3408b54e0efe
3,653,871
def load_csv_to_journal(batch_info): """Take a dict of batch and csv info and load into journal table.""" # Create batch for testing filename = batch_info['filename'] journal_batch_name = batch_info['journal_batch_name'] journal_batch_description = batch_info['journal_batch_description'] journa...
285d1113cad16d2d0cc7216f59d089a8f94e908c
3,653,872
def validate_guid(guid: str) -> bool: """Validates that a guid is formatted properly""" valid_chars = set('0123456789abcdef') count = 0 for char in guid: count += 1 if char not in valid_chars or count > 32: raise ValueError('Invalid GUID format.') if count != 32: ...
75fff17ee0ef2c1c080e2ef2ffb0272fd71d2921
3,653,873
def load_key_string(string, callback=util.passphrase_callback): # type: (AnyStr, Callable) -> RSA """ Load an RSA key pair from a string. :param string: String containing RSA key pair in PEM format. :param callback: A Python callable object that is invoked to acquire a passphr...
0ac6df63dd7ad42d8eaaa13df7e96caa311332d7
3,653,874
import os import tarfile def load_lbidd(n=5000, observe_counterfactuals=False, return_ites=False, return_ate=False, return_params_df=False, link='quadratic', degree_y=None, degree_t=None, n_shared_parents='median', i=0, dataroot=None, print_paths=True): ...
7e0b1ec7fb9780150db17ef5a10e0be479b7c6e3
3,653,875
def generate_iface_status_html(iface=u'lo', status_txt="UNKNOWN"): """Generates the html for interface of given status. Status is UNKNOWN by default.""" status = "UNKNOWN" valid_status = html_generator.HTML_LABEL_ROLES[0] if status_txt is not None: if (str(" DOWN") in str(status_txt)): status = "DOWN" valid...
c3d459720b5675c9a7d53fa77bb1d7bb6d3988f2
3,653,876
def is_a(file_name): """ Tests whether a given file_name corresponds to a CRSD file. Returns a reader instance, if so. Parameters ---------- file_name : str the file_name to check Returns ------- CRSDReader1_0|None Appropriate `CRSDReader` instance if CRSD file, `None` ...
e083a54becdbb86bbefdb7c6504d5cd1d7f81458
3,653,877
def Closure(molecules): """ Returns the set of the closure of a given list of molecules """ newmol=set(molecules) oldmol=set([]) while newmol: gen=ReactSets(newmol,newmol) gen|=ReactSets(newmol,oldmol) gen|=ReactSets(oldmol,newmol) oldmol|=newmol newmol=gen-oldmol return oldmol
7546a528a43465127c889a93d03fbe1eb83a7d63
3,653,878
import os def get_logs(repo_folder): """ Get the list of logs """ def get_status(path, depth, statuses): if depth == 3: for f in os.listdir(path): if f == STATUS_FILE_NAME: f = os.path.join(path,f) statuses.append(f) else: ...
b00910bc38264fcde2a6ccb37d538489d23d6a57
3,653,879
def get_celery_task(): """get celery task, which takes user id as its sole argument""" global _celery_app global _celery_task if _celery_task: return _celery_task load_all_fetcher() _celery_app = Celery('ukfetcher', broker=ukconfig.celery_broker) _celery_app.conf.update( CELE...
b1cf2aa6ccf462b8e391c8900ac9efaea0b62728
3,653,880
def plot_keras_activations(activations): """Plot keras activation functions. Args: activations (list): List of Keras activation functions Returns: [matplotlib figure] [matplotlib axis] """ fig, axs = plt.subplots(1,len(activations),figsize=(3*len(activations),5)...
3c10bd3a57531ef8a88b6b0d330c2ba7eaf0b35c
3,653,881
def hog_feature(image, pixel_per_cell=8): """ Compute hog feature for a given image. Important: use the hog function provided by skimage to generate both the feature vector and the visualization image. **For block normalization, use L1.** Args: image: an image with object that we want to d...
6509a46dd161f6bde448588314535cb5aeef5e8a
3,653,882
def create_parser() -> ArgumentParser: """ Helper function parsing the command line options. """ parser = ArgumentParser(description="torchx CLI") subparser = parser.add_subparsers( title="sub-commands", description=sub_parser_description, ) subcmds = { "describe": ...
515309ad03907f5e22d32e5d13744a5fd24bfd40
3,653,883
import re def process_word(word): """Remove all punctuation and stem words""" word = re.sub(regex_punc, '', word) return stemmer.stem(word)
bceb132e7afddaf0540b38c22e9cef7b63a27e8c
3,653,884
def no_autoflush(fn): """Wrap the decorated function in a no-autoflush block.""" @wraps(fn) def wrapper(*args, **kwargs): with db.session.no_autoflush: return fn(*args, **kwargs) return wrapper
c211b05ea68074bc22254c584765ad001ed38f67
3,653,885
import os def default_model(): """Get a path for a default value for the model. Start searching in the current directory.""" project_root = get_project_root() models_dir = os.path.join(project_root, "models") curr_dir = os.getcwd() if ( os.path.commonprefix([models_dir, curr_dir]) == m...
49220267018e422df3e72d3be942ae5e28022586
3,653,886
def int_to_ip(ip): """ Convert a 32-bit integer into IPv4 string format :param ip: 32-bit integer :return: IPv4 string equivalent to ip """ if type(ip) is str: return ip return '.'.join([str((ip >> i) & 0xff) for i in [24, 16, 8, 0]])
8ceb8b9912f10ba49b45510f4470b9cc34bf7a2f
3,653,887
def audit_work_timer_cancel(id): """ Cancel timer set. :param id: :return: """ work = Work.query.get(id) celery.control.revoke(work.task_id, terminate=True) work.task_id = None work.timer = None db.session.add(work) db.session.commit() return redirect(url_for('.audit_wo...
d05d76dbf31faa4e6b8349af7f698b7021fba50f
3,653,888
def team_pos_evolution(team_id): """ returns the evolution of position for a team for the season """ pos_evo = [] for week in team_played_weeks(team_id): try: teams_pos = [x[0] for x in league_table_until_with_teamid(week)] pos = teams_pos.index(int(team_id)) + 1...
2b1d5378663eadf1f6ca1abb569e72866a58b0aa
3,653,889
def ifft_method(x, y, interpolate=True): """ Perfoms IFFT on data. Parameters ---------- x: array-like the x-axis data y: array-like the y-axis data interpolate: bool if True perform a linear interpolation on dataset before transforming Returns ------- x...
d13e1519cbcec635bbf2f17a0f0abdd44f41ae53
3,653,890
import sys def getExecutable(): """ Returns the executable this session is running from. :rtype: str """ return sys.executable
87d842239f898554582900d879501b2a3457df8e
3,653,891
def run(namespace=None, action_prefix='action_', args=None): """Run the script. Participating actions are looked up in the caller's namespace if no namespace is given, otherwise in the dict provided. Only items that start with action_prefix are processed as actions. If you want to use all items in the...
83a575f633088dc44e1cfcce65efadfb6fda84cc
3,653,892
import os def get_file_with_suffix(d, suffix): """ Generate a list of all files present below a given directory. """ items = os.listdir(d) for file in items: if file.endswith(suffix): return file.split(suffix)[0] return None
1191868a4fd9b925f6f8ce713aba16d9b66f1a9a
3,653,893
def PolyMod(f, g): """ return f (mod g) """ return f % g
53b47e993e35c09e59e209b68a8a7656edf6b4ce
3,653,894
def policy_improvement(nS, nA, P, full_state_to_index, g=.75,t=0.05): """Iteratively evaluates and improves a policy until an optimal policy is found or reaches threshold of iterations Parameters: nS: number of states nA: number of actions P: transitional tuples given state and actio...
84373843a179bb2afda20427e24795fbb524ae2c
3,653,895
import torch def get_train_val_test_data(args): """Load the data on rank zero and boradcast number of tokens to all GPUS.""" (train_data, val_data, test_data) = (None, None, None) # Data loader only on rank 0 of each model parallel group. if mpu.get_model_parallel_rank() == 0: data_config = ...
c729262e71bb40c016c6b7a65deaba65f4db951e
3,653,896
def user_data_check(data_file): """ 1 - Check user data file, and if necessary coerce to correct format. 2 - Check for fold calculation errors, and if correct, return data frame for passing to later functions. 3 - If incorrect fold calculations detected, error message returned. :param d...
fc1b1d18a0e9a5a28674573cc2ab1c7cf9f08a03
3,653,897
import requests def get_modules(request: HttpRequest) -> JsonResponse: """Gets a list of modules for the provided course from the Canvas API based on current user A module ID has to be provided in order to access the correct course :param request: The current request as provided by django :return: A JSONResponse ...
d583779b075419dd67514bd50e709374fd4964bf
3,653,898
def create_workflow(session, workflow_spec=dict(), result_schema=None): """Create a new workflow handle for a given workflow specification. Returns the workflow identifier. Parameters ---------- session: sqlalchemy.orm.session.Session Database session. workflow_spec: dict, default=dict(...
1c3843a15d543fb10427b52c7d654abd877b3342
3,653,899