content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
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
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
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 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 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 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
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
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
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
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
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
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
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
from typing import Optional def get_volume(name: Optional[str] = None, namespace: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVolumeResult: """ ## Example Usage ```python import pulumi import pulumi_harvester as harvester ub...
528dfb0432b30b40037b86a234e83c8327eb5206
3,653,901
def both_block_num_missing(record): """ Returns true of both block numbers are missing :param record: dict - The record being evaluated :return: bool """ rpt_block_num = record.get("rpt_block_num", "") or "" rpt_sec_block_num = record.get("rpt_sec_block_num", "") or "" # True, if neithe...
63e2fdaef78dbc3c6560a4b015ed022583f30d05
3,653,902
def jsonize(v): """ Convert the discount configuration into a state in which it can be stored inside the JSON field. Some information is lost here; f.e. we only store the primary key of model objects, so you have to remember yourself which objects are meant by the primary key values. """ ...
1aa7954c0089726b7707e0180b35a12d679c286b
3,653,904
def clean_kaggle_movies(movies_df): """ Clean the Kaggle movie data with the following steps: 1. Drop duplicate rows 2. Filter out adult videos and drop unnecessary columns 3. Recast columns to appropriate data types Parameters ---------- movies_df : Pandas dataframe Kaggle mov...
05d5a0eb965b26cdc04dcfb9f3a76690d272389c
3,653,905
def make_shift_x0(shift, ndim): """ Returns a callable that calculates a shifted origin for each derivative of an operation derivatives scheme (given by ndim) given a shift object which can be a None, a float or a tuple with shape equal to ndim """ if shift is None: return lambda s, d, i...
e6b01e43c8bf73ba21a9bdfcd27a93db9ccb7478
3,653,907
def one_zone_numerical(params, ref_coeff, num_molecules=1e-9): """Returns one zone reactor exit flow.""" time = np.array(params[0], dtype=float) gradient = np.array(params[1], dtype=float) gridpoints = int(params[2]) step_size, area = float(params[3]), float(params[4]) solu = odeint( ...
4eb17f9684d1d12175bf85d15bada4178074de8a
3,653,909
import re def get_all_event_history_links(): """From ufcstat website finds all completed fights and saves the http into the current working directory """ url = "http://www.ufcstats.com/statistics/events/completed?page=all" href_collection = get_all_a_tags(url) #Add all links to list that hav...
ab452c66460f18b5d55ce2be2e22877f07e959d5
3,653,910
def plot_book_wordbags(urn, wordbags, window=5000, pr = 100): """Generate a diagram of wordbags in book """ return plot_sammen_vekst(urn, wordbags, window=window, pr=pr)
12a03c70316d3920419f85cd2e4af87c7a16f0f8
3,653,912
def map_line2citem(decompilation_text): """ Map decompilation line numbers to citems. This function allows us to build a relationship between citems in the ctree and specific lines in the hexrays decompilation text. Output: +- line2citem: | a map keyed with line numbers, holdin...
86c8a24f769c7404560bb63c34f2b60ff3a097da
3,653,913
def from_dict(params, filter_func=None, excludes=[], seeds=[], order=2, random_seed=None): """Generates pair-wise cases from given parameter dictionary.""" if random_seed is None or isinstance(random_seed, int): return _from_dict(params, filter_func, excludes, seeds, order, random_seed) ...
d9ecd0528340adbe874afa70d3a9309e53ff87cc
3,653,914
def ensure_min_topology(*args, **kwargs): """ verifies if the current testbed topology satifies the minimum topology required by test script :param spec: needed topology specification :type spec: basestring :return: True if current topology is good enough else False :rtype: bool """ ...
364e7b3c166b725fd73846e1814bd3b7ab92ad96
3,653,915
def encode_mode(mode): """ JJ2 uses numbers instead of strings, but strings are easier for humans to work with CANNOT use spaces here, as list server scripts may not expect spaces in modes in port 10057 response :param mode: Mode number as sent by the client :return: Mode string """ if...
db83c419acb299284b7b5338331efc95051115a5
3,653,916
import random def randclust(SC, k): """ cluster using random """ # generate labels. labels = np.array([random.randint(0,k-1) for x in range(SC.shape[1])]) # compute the average. S, cats = avg_cat(labels, SC) # return it. return S, labels, cats
42530495959977c1289fa6bdc2089747a246d210
3,653,918
def get_domains_by_name(kw, c, adgroup=False): """Searches for domains by a text fragment that matches the domain name (not the tld)""" domains = [] existing = set() if adgroup: existing = set(c['adgroups'].find_one({'name': adgroup}, {'sites':1})['sites']) for domain in c['domains'].find({}, {'domain': 1, '...
6ecaf4ccf1ecac806fb621c02282bf46929459ce
3,653,919
def read_bbgt(filename): """ Read ground truth from bbGt file. See Piotr's Toolbox for details """ boxes = [] with open(filename,"r") as f: signature = f.readline() if not signature.startswith("% bbGt version=3"): raise ValueError("Wrong file signature") rects...
25cfe28de9ed67ca0888da5bf27d01a803da8690
3,653,920
def measure(G, wire, get_cb_delay = False, meas_lut_access = False): """Calls HSPICE to obtain the delay of the wire. Parameters ---------- G : nx.MultiDiGraph The routing-resource graph. wire : str Wire type. get_cb_delay : Optional[bool], default = False Determines...
7db83ff5084798100a00d79c4df13a226a2e55a8
3,653,921
def live_ferc_db(request): """Use the live FERC DB or make a temporary one.""" return request.config.getoption("--live_ferc_db")
f0540c8e3383572c5f686ea89011d9e1ab0bf208
3,653,923
from typing import Optional async def get_eth_hash(timestamp: int) -> Optional[str]: """Fetches next Ethereum blockhash after timestamp from API.""" try: this_block = w3.eth.get_block("latest") except Exception as e: logger.error(f"Unable to retrieve latest block: {e}") return Non...
f7f8cd70857d8bb84261685385f59e7cfd048f4c
3,653,924
import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl def extract_url_dataset(dataset,msg_flag=False): """ Given a dataset identifier this function extracts the URL for the page where the actual raw data resides. """ # Ignore SSL certificate errors ctx = s...
06ec2dd6bea4c264fe9590663a28c7c92eed6a49
3,653,926
def test_encrypt_and_decrypt_one(benchmark: BenchmarkFixture) -> None: """Benchmark encryption and decryption run together.""" primitives.encrypt = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_encrypt primitives.decrypt = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_decrypt def encrypt_and_decr...
fdd15ca362b983e5f7e28632434c2cbe1ab983ac
3,653,927
def MPI_ITOps(mintime = 5, maxtime = 20, cap = 60): """ Returns a costOfLaborValue object suitable to attach to a sim or other event Time is in hours """ timeDist = LogNormalValue(maxtime, mintime, cap) costDist = LogNormalValue(235, 115, 340) team = costOfLaborValue("IT I&O Team", timeDist,...
829c702d31a585fc18f81eea01c87f32c2458ea6
3,653,928
import json def load_private_wallet(path): """ Load a json file with the given path as a private wallet. """ d = json.load(open(path)) blob = bytes.fromhex(d["key"]) return BLSPrivateHDKey.from_bytes(blob)
9c98be3b3891eaab7b62eba32b426b78ae985880
3,653,929
import json def format_parameters(parameters: str) -> str: """ Receives a key:value string and retuns a dictionary string ({"key":"value"}). In the process strips trailing and leading spaces. :param parameters: The key-value-list :return: """ if not parameters: return '{}' pair...
95f115b9000d495db776798700cfdf35209cfbd4
3,653,930
def downvote_question(current_user, question_id): """Endpoint to downvote a question""" error = "" status = 200 response = {} question = db.get_single_question(question_id) if not question: error = "That question does not exist!" status = 404 elif db.downvote_question(curre...
a7bba2a9608d25b3404f22ca2f283486f205f0ad
3,653,931
def get_new_generation(generation: GEN, patterns: PATTERNS) -> GEN: """Mutate current generation and get the next one.""" new_generation: GEN = dict() plant_ids = generation.keys() min_plant_id = min(plant_ids) max_plant_id = max(plant_ids) for i in range(min_plant_id - 2, max_plant_id + 2): ...
a0908c9c7570814ca86d3b447425e7b75cdbfde2
3,653,932
def ell2tm(latitude, longitude, longitude_CM, ellipsoid = 'GRS80'): """ Convert ellipsoidal coordinates to 3 degree Transversal Mercator projection coordinates Input: latitude: latitude of a point in degrees longitude: longitude of a point in degrees longitude_CM: central meridi...
b6e1361df8b51e188bbc7a49557dbe8f14905df3
3,653,933
def Format_Phone(Phone): """Function to Format a Phone Number into (999)-999 9999)""" Phone = str(Phone) return f"({Phone[0:3]}) {Phone[3:6]}-{Phone[6:10]}"
8e46c35bca9d302d86909457c84785ad5d366c15
3,653,934
from sets import Set def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" startState = problem.getStartState() if problem.isGoalState(startState): return [] # Each element in the fringe stor...
429c45bff701bbd2bb515be6d8a0f538183941d3
3,653,935
def _stack_add_equal_dataset_attributes(merged_dataset, datasets, a=None): """Helper function for vstack and hstack to find dataset attributes common to a set of datasets, and at them to the output. Note:by default this function does nothing because testing for equality may be messy for certain types; t...
acfeb1e7ca315aa7109731427ce6f058b2fceb6d
3,653,936