content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def sin_potential2(z): """Modified sin potential.""" z = tf.transpose(z) logterm1 = tf.math.exp(-0.5 * ((z[1] - w1(z)) / 0.4) ** 2) logterm2 = tf.math.exp(-0.5 * ((z[1] - w1(z) + w3(z)) / 0.35) ** 2) term3 = 0.1 * tf.math.abs(z[0]) output = -1. * tf.math.log(logterm1 + logterm2) + term3 ret...
843f4ca43ab2f2e464d8759cae8a1504b32992d8
3,598,364
def map_crystal_to_sim(CRYS_PDB, SIM_PDB): """ Map resid of crystallographic water to resid of corresponding simulation water """ crys_molid = molecule.load('pdb', CRYS_PDB) sim_molid = molecule.load('pdb', SIM_PDB) # align_crys_to_sim_structures(crys_molid, sim_molid) # coordinate_selection = "noh and wate...
23989ed343b23dcc3a38120536bec36b81829206
3,598,365
def export_estimator_savedmodel(estimator, export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False, checkpoint_path=None, ...
161b0773c76550e62643454e932eb6c4755f7b1e
3,598,366
def fetch_w(*, wid): """Get all the files on a workspace""" workspace = Workspace.get_or_404(wid) if not ReadWorkspacePermission(wid).can(): raise APIException(status=codes.forbidden, title='Forbidden', detail='You are not authorized to read met...
7bb42d77c1d8a9111bcb9c648b1e1c4ed21b5922
3,598,367
def _extract_lr(labels_in, dat_type): """Pull out the L/R information from ROI label. Parameters ---------- labels_in : list of str ROI labels. dat_type : {'anat', 'elec'} Whether ROI label comes from anat or elec data. Returns ------- labels : list of str Clean...
0dd503dbc37bab9fec6b389a22b6561f725a6757
3,598,368
def _parse_raw_day(fragment): """ Taking all the info we need from the object Args: fragment: 'BeautifulSoup' objects contains day info ('div' with class 'col-md-6') Returns: tuple: (str, str, list): Tuple contains date, day and list of the lessons """ header = fragment.find_n...
0b236022889bffc2dbfa9479015dfa1545a2b4c0
3,598,369
import glob import platform def get_targetNames2(target, inputFolder): """ -> return the list of center or the list of date occuring in patient file present in data folder -> target is a string, could be: - center - date - disease """ listOfPatientFiles = glob.glob(str(inputFolder)+"/*.csv") listOfCente...
00945dd882fb28ed5b60f0f65371fada64ed45ac
3,598,370
import logging def list_to_dataframe(file_list): """ Convert a list of ctf files, that are named in the the standard format 'year_month_day_hours' to a pandas dataframe Args: file_list (list): a list of files Returns: pd.DataFrame: Pandas DataFrame containing a list of files """ ...
c33851e88c6ee6681ca727cbb880416733fcdfc4
3,598,372
def pull_courses(): """Retrieve list of JSON objects describing all the courses.""" # return query_endpoint('courses') return query_endpoint('accounts/1/courses')
aa362dd8888f6fdea33afa4fa60e849aa92ad651
3,598,373
def ev_annot_freq(bootstrap_rng=None): """Compute binned frequencies of event boundary annotations Parameters ---------- bootstrap_ng : Generator (from numpy.random.default_rng()) If provided, bootstrap resample event annotations Returns ------- ndarray Proportion of raters...
37d265c751dddbf6dfd3c8bd3780da5a860adb66
3,598,374
import torch def collect_samples( rand_init, queue, env, policy, custom_reward, mean_action, render, running_state, min_batch_size, ): """Helper function - Collect batch of action and log depends on the batch size Args: rand_init: random initialization for reproduc...
1a7da3a571f7ea7bb2ed739a4ddaaa1f98ee3664
3,598,375
def frame_id_unpack(frame_id): """Unpack given frame id and return a tuple of priority, reserved, data page, PDU format, PDU specific and source address. """ try: packed = bitstruct.pack('u29', frame_id) except bitstruct.Error: raise Error( 'Expected a frame id 0..0x1ff...
12e860863e6f9036a9bbf050bb2d7c4c1afd0ee1
3,598,376
import random import time import json def fetch_job_states(): """ dummy function returning random dictionaries with job names and job states for the purpose of simulating the actual long running tasks :return: """ job1 = [{'job_name': 'job1', 'job_state': 'running'}, {'job_name...
d872edb4ada47a59b0137ba45e3a0611ff99b0a8
3,598,377
from datetime import datetime def generate_download_signed_url_v4(bucket_name, blob_name, sa_name): """Generates a v4 signed URL for downloading a blob. Note that this method requires a service account key file. You can not use this if you are using Application Default Credentials from Google Compute ...
b742354de82ffe266ced5555b23c582031411373
3,598,378
import tokenize def simple_lesk(gloss: str, word: str): """":returns the sense most suited to the given word as per the Simple LESK Algorithm""" # converting everything to lowercase gloss = gloss.lower() word = word.lower() # obtaining tokens from the gloss gloss_tokens = tokenize(gloss, wor...
3fc717c83f0293d077392294fbed2a3e4aba0c42
3,598,379
from typing import Optional def check_change_full_name( user_profile: UserProfile, full_name_raw: str, acting_user: Optional[UserProfile] ) -> str: """Verifies that the user's proposed full name is valid. The caller is responsible for checking check permissions. Returns the new full name, which may ...
c1806233263024d8c6b18e079829e2ee0c0005c4
3,598,380
def get_course_exam_all(course_id, prev_years=False): """ Return a summary of information about all current exams in the course {id, course, name, description, start, duration, end, type} """ assert isinstance(course_id, int) assert isinstance(prev_years, bool) if prev_years: key = "...
b9822bbd4e060d1eae7ea72a98053e526d023d8c
3,598,381
import jinja2 def render_template(template_file, template_vars, searchpath="./templates/"): """ Render a jinja2 template """ templateLoader = jinja2.FileSystemLoader(searchpath=searchpath) template_env = jinja2.Environment(loader=templateLoader) template = template_env.get_template(template_fi...
d15f5d6e120a22ee5735dbf5b1f8c324a5cae861
3,598,382
def getAxes(): """ Get each of the axes over which the data is measured. """ df = load_file("atyeo_covid") df = df.filter(regex='SampleID|Ig|Fc|SNA|RCA', axis=1) axes = df.filter(regex='Ig|Fc|SNA|RCA', axis=1) axes = axes.columns.str.split(" ", expand = True) subject = df['SampleID'] subje...
5e2abcbd7458978378faa5865268c5721afd4645
3,598,383
def summarize_power(power_summary, sim_num, test, colors): """Generates a dataframe describing a power calculation run Please note, this function is primarily designed for use with the simulation notebooks. Parameters ---------- power_summary : dict A dictionary summarizing the power s...
46c5d051193d2c87d1a1301f8c06217b5c33551e
3,598,384
def head(r, t, h0, Q, delz, K, S): """ Compute the head around a pumping well according to the THEIS model. Source: SHEMAT-Book Clauser2003, section 2.6.1, p.57. Parameters ---------- r : float Distance from well [m] t : float time [s] h0 : float Undisturbed he...
7409211ddff0905ce4b07cad2176ef87609e4aee
3,598,385
def pagerank_weighted(graph, damping=0.85): """Get dictionary of `graph` nodes and its ranks. Parameters ---------- graph : :class:`~gensim.summarization.graph.Graph` Given graph. damping : float Damping parameter, optional Returns ------- dict Nodes of `graph` ...
4a6ee1c6ea3c402e84b5a3e246a66ff004e96aab
3,598,387
def crate_data_for_linear_regression_weighted(initial_proj_nodes, dict_intial_projections, dict_enode_enode_in, dict_enode_enode_out, dim, G): """ In order to find the best parameters to calculate a node's vector, we perform linear regression. In this function w...
8858589d1f8a6eea6d9036126d83b4b3ea1e6f90
3,598,388
from typing import Any from typing import List def search_commands(*args: Any) -> List[Any]: """Pass find_commands function from C.""" return actually_calls(args, find_commands)
f8471e6160ba2cd37f2ae99240f4db7f00a9bb86
3,598,389
def subtract(x, y): """Subtract two objects and return the result >>> from methods import subtract >>> subtract(2, 1) 1 """ return x - y
00fd9bff041879b372ab7b0d8aa536e3aecb8378
3,598,390
def query_for_user(user): """Queries for information about user from the database. :param user: Object User to query for. :return: Data about the user. """ database = connect_to_cloudsql() cursor = database.cursor() cursor.execute("SELECT * FROM Users WHERE username='" + user.username + "'"...
4b17b111efd9e4bc230fbcd9ff22637ce014b1f1
3,598,391
def RunDistributed(module_name, package_root, num_ps, num_workers, start_port, user_args=None): """Create a cluster configuration and start processes for the cluster. Args: module_name: str. Python module to use as t...
edab626aa6b09a1bb039da2d3db051e9d578859d
3,598,392
from operator import add from operator import concat def normalA(x, p, filters, scope=None): """Normal cell for NASNet-A (Fig. 4 in the paper)""" p = adjust(p, x, filters) h = relu(x) h = conv(h, filters, 1, scope='1x1') x1 = add(sconv(h, filters, 3, scope='left1'), h, name='add1') x2 = add(...
23908563b584db0fa66b4b24da3f050c2be45406
3,598,394
def DEFAULT_THRESHOLDING(phenotype): """ Threshold function for a phenotype for each gene, >0 becomes 1 and <0 becomes -1 """ # verification, sign declaration, return thresholded phenotype assert(phenotype.shape == (DEFAULT_GENE_NUMBER, 1)) def sign(x): return (1 if x > 0 else (-1 if x < 0 e...
bca278e17c96668f260fbfad004619c24881f5f0
3,598,395
def dict_sort(dictionary: dict) -> list: """Takes in a dictionary with integer values and outputs a list of the keys sorted by their associated values in descending order.""" return list(reversed(sorted(dictionary, key=dictionary.__getitem__)))
330e6033a9e511341e5d9216a385b366a09eed9c
3,598,396
import re def get_citation_form(attributes): """ Compute the citation form of a pronominal mention. Args: attributes (dict(str, object)): Attributes of the mention, must contain the key "tokens". Returns: str: The citation form of the pronoun, one of "i", "you", "he", "she", ...
2e02063ae0694e7ce76e3be8ce111d9550de7697
3,598,397
def SINH(df): """ 函数名:SINH 名称:双曲正弦函数,三角函数 python API real=SINH(close) :return: """ close = df['close'] return talib.SINH(close)
b40dd33fd7a41f5219dfb84631695435da4241a6
3,598,398
def completion_formatter_factory(subsec_precision=2): """ Formatter factory Parameters ---------- subsec_precision : int (Default : 2) The number of decimal digits for the second in the time formatting Return ------ :func:`completion_formatter` """ def completion_format...
91d3c28e59f78a5addf04247d35d2bd84dfefef9
3,598,399
def _design_knockoff_equi(exog): """ Construct an equivariant design matrix for knockoff analysis. Follows the 'equi-correlated knockoff approach of equation 2.4 in Barber and Candes. Constructs a pair of design matrices exogs, exogn such that exogs is a scaled/centered version of the input ma...
149252ad76664ded9f3ed344d54b8026ac3e4da0
3,598,400
def parse_int(value) -> int: """ this function is used to parse data from the DB into an integer. because a lot of the cells can be empty, we get None as the return type. This function makes sure we get 0 if the value is None or empty !!! IMPORTANT !!! This is to be added to values where we wou...
066e0a93436697bb31b91743faf851a752dd0e87
3,598,401
def converted_size(path, estimate=False): """Get size of converted raw image. The size of image converted to raw format can be growing up to the virtual size of the image. :param path: path to the image file. :param estimate: Whether to estimate the size by scaling the original size :r...
0357c63dc64d25dff71f970227946b480f52df6a
3,598,403
def asap(handlers, *, body, **kwargs): """ Execute one handler at a time, skip on failure, try the next one, retry after the full cycle. """ retryfn = lambda handler: get_retry_count(body=body, handler=handler) return sorted(handlers, key=retryfn)[:1]
82d956b0527ee5796669c9ec7a04cfc7a3feaba7
3,598,405
def distance_by_lowtemp(): """ """ q = text( """ select date(start_date) as start_date, avg(W.day_temp_min) as low_temp, sum(R.distance) as distance from rides R join ride_weather W on W.ride_id = R.id group by date(start_date) ...
483bf254a4948709a834a2351d048d43a4ad0aaf
3,598,406
def bitpos_from_mask(mask, lsb_pos=0, increment=1): """ Turn a decimal value (bitmask) into a list of indices where each index value corresponds to the bit position of a bit that was set (1) in the mask. What numbers are assigned to the bit positions is controlled by lsb_pos and increment, as explai...
d7938258c0f2dc523720bc82a48ecba1c2342223
3,598,407
def cli_arguments(): """Retrieve all CLI arguments provided by user.""" # First of all, we need to specify all command line flags that are # recognized by this tool. parser = ArgumentParser() parser.add_argument( "-c", "--count", dest="count", default...
c2b5a1da7b1a23ef9edd47cbb904909b39ef6c63
3,598,408
def moving_average(list): """ list의 평균을 return한다. input: list return: average(float) """ mysum = 0 for i in range(0, len(list)): mysum = mysum + list[i] return mysum / len(list)
d5602113e74a7ef0f0027ec5f6964b72680c3499
3,598,409
def pixelwise_predictor(feat, nc=3, n_layers=1, n_layerwise_steps=0, skip_feat=None, reuse=False, is_training=True): """Predicts texture images and probilistic masks. Args...
a700668bb7f513fc0ee59c5da2e656346ef8fb98
3,598,411
def _data_aug_fn(image, ground_truth, hin, win, hout, wout, hnei, wnei, parts, limbs, data_format="channels_first"): """Data augmentation function.""" #restore data ground_truth = cPickle.loads(ground_truth.numpy()) image=image.numpy() annos = ground_truth["kpt"] mask = ground_truth["mask"] ...
98f587ce6282ebcaf999a0945286ffc71b187c20
3,598,412
import numpy def _rolling_ball(tile, ball_radius: int, light_background: bool): """ Applies the rolling-ball algorithm to a single tile. Args: tile: A tile, usually from an ome.tif file. ball_radius: The radius of the ball to use for calculating the background. light_background: Wheth...
e629d51b6607c0113cc27427775a72449cad0f39
3,598,413
def quality_threshold(sample, cutoff=5, PBC=False, net_height=0, net_width=0): """ Run the complete clustering algorithm in one go and returns the clustered indices as a list. Args: sample (array): The input dataset cutoff (float, optional): The clustering cutoff distance. ...
bc9fd5def494431e6e58ecf2cfb9ea5691bffa14
3,598,414
def setup_metadata_controller(): """ Load metadata controller based on spell_type """ if app.metadata.spell_type == consts.spell_types.SNAP: return _setup_snap_metadata_controller() # This is the typical default for now return _setup_juju_metadata_controller()
59757cade58bd4134106a908272cbf1822d76933
3,598,415
from datetime import datetime def create_question(question_text, days): """ Creates a question with the given 'question_text' and published the given number of 'days' offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + d...
c541eb40f68eb9dd3b54eb1d8f96bc84f8a79269
3,598,416
def url_compose(camera): """ Compose URL string for the camera """ # rtsp://88.204.57.242:5533/user=admin&password=******&channel=1&stream=1.sdp? url: str = f'rtsp://{camera.ip_addr}:{camera.port}/user={camera.login}&password={camera.password}&channel=1&stream=0.sdp?' return url
62bf81b993e95a4c5ed7ca8362220cf16102c877
3,598,417
def pt2gen(t_arr, K, T, y0 = 0): """ generate y(t) of PT2 for t in t_arr Args: t_arr (list(float)): time array K (float): gain T (float): time-constant Returns: list(float): y(t) for t in t_arr """ return [pt2(t, K, T) + y0 for t in t_arr]
ae29779f491669f5f56dbafb209da6b1664014bc
3,598,418
def _select_deep(v, field, depth, record): """ field = {"name":name, "value":["attribute", "path"]} r[field.name]=v[field.value], BUT WE MUST DEAL WITH POSSIBLE LIST IN field.value PATH """ if hasattr(field.value, "__call__"): try: record[field.name] = field.value(wrap(v)) ...
27580452cd7d5e17172d817a8f1a407518c00fda
3,598,419
def filter_constant(vars): """Create T/F index for data with variance vars, F if variance constant. """ return vars != 0
57da83f60c42445903e8fd1442c60f7fd4e16bc6
3,598,420
import logging def _project_duals_op_for_layer(layer, dual_var_list): """Returns op that updates duals for a single layer.""" # Dual variable may not be required. if layer.dual_shape() is None: project_op = tf.no_op() else: try: project_op = layer.project_duals_op(dual_var_list[-1]) except (...
bfb3e11dd5caf6128f4f24d8e93678b4bed3f71c
3,598,421
def recent_blog_posts(author=None, limit=10, offset=0, asc=False, before=None): """ Get user's recent posts/recommendations """ if author and isinstance(author, (int, long)): author = User(author) if author and author.id != env.user.id: if author.get_profile('private') and not autho...
4a70c3be2ddd03c3550645b1ed00ddaa6550ead3
3,598,423
def optimal_amiRNA(dna_sequence): """ Id any seqs of 21 nt with T at nucleotide 1 and A or T at nucleotide 10 Input is the target (not the complement) optimal_RNAs --> [(amiRNA,*amiRNA)] """ dna_sequence.upper() dna_sequence = complement(dna_sequence) pos = 0 optimal_amiRNAs=[] ...
f900b92f96108e37e82f09e220631feeba480ace
3,598,425
import functools def input_function(is_train, embeddings): """An input function satisfying the tf.estimator API.""" # A dataset with keys `question`, `context`, `answer_start`, and `answer_end`. dataset = nq_long_dataset.get_dataset(is_train) dataset = dataset.map( functools.partial( preproce...
6ebb0fdfd3e54c6a142aff2373785e43b3315dfd
3,598,426
def calculate_proportion_dict(data, relevant_keys, percent=False, floor=0., underscore=True): """ General method to calculate proportions from absolute values provided as dictionaries. Args: data: Dictionary containing the absolute values relevant_keys: The keys of data from which proportio...
0c11cdb2d5efa73ee9bb8fa4e05cd55e0e3197cd
3,598,427
from plyfile import PlyData, PlyElement def loadCloudPLY(path): """ Loads a PLY file from the specified path. """ try: except: assert False, "Please install plyfile (pip install plyfile) to load PLY." # look for/load header file if one exists header, data = matchHeader(path) ...
c0460843d8efdfc8eeb00526e900a150a2e23985
3,598,428
def GetClientIdFlag(): """Anthos auth token client-id flag, specifies the ClientID is the id for OIDC client application.""" return base.Argument( '--client-id', required=False, help='ClientID is the id for OIDC client application.')
019f23808cdc20a25775ca5d4516ec6a9b4ecf3d
3,598,429
def get_first_package_name(name): """ Returns first package name. From `a.b.c` it returns `a`. :param str name: Full module name :return: First package name. :rtype: str """ return name.split(".")[0]
814b175356ef715af46f788dc9eac7e776884b30
3,598,430
def get_schlagworte_sorted(schlagworte): """ uebersetzt die gestemmten Schlagwoerter in die ursruenglichen Schlagwoerter """ items = [] for schlagwort in schlagworte.all(): items.append(get_schlagwort_by_stem(schlagwort)) items.sort() return items
a8df8e52821689aec70da56b258dcc299dc8a7f0
3,598,431
def _parse_url_work_relation(response): """ response is {'resource': 'https://imslp.org/wiki/7_Bagatelles,_Op.33_(Beethoven,_Ludwig_van)', 'relations': [{'source-credit': '', 'target-credit': '', 'type-id': '0cc8527e-ea40-40dd-b144-3b7588e759bf', 'type': 'download for free', 'end': None, 'direct...
4e36330be029846bc44c235dafb20e6dc9c5f58f
3,598,432
def run(): """Entrypoint function.""" logger.info("Scheduled scan for newer versions started") print("Scheduled scan for newer versions started") read_packages() get_repos() get_version_data(REPO_DATA, PACKAGE_DATA, NEW_VERSION_DATA, VERSION_DATA) get_version_data(REPO_DATA, TRANSITIVE_PACKA...
b24a69ef0609ba08ed5b52d204eaafdf73b62034
3,598,433
def get_edge_mask(poly, mask): """ Generate edge mask """ cv2.polylines(mask, [poly], True, [1]) return mask
481b91c8ea289df2cd388a93299e6cc94d6ef384
3,598,434
def merge_dicts(dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
bdd006b0a9ba641d1608bbf793953610de06f04c
3,598,435
def _checkXmlStructure(data): """ @summary: checks the structure of the xml to check if it is valid xml @param data: can be an xml string """ try: d = minidom.parseString(data) d = str(d.toxml()) return None except Exception as e: return str(e)
0462e375a3e45cc4da3ba9cc6e41597e7477587c
3,598,436
import urllib def embed_mp3(music_file, meta_tags): """Embed metadata to MP3 files.""" # EasyID3 is fun to use ;) audiofile = EasyID3(music_file) audiofile['artist'] = meta_tags['artists'][0]['name'] audiofile['albumartist'] = meta_tags['artists'][0]['name'] audiofile['album'] = meta_tags['alb...
76e8f9643ebdc9f7a90d0d78fc4a9987b82d5f19
3,598,437
def isint(value): """ To check if any variable can be converted to integer """ try: int(value) return True except ValueError: return False
9c8b3e4abe11e8c23fb6d28b92637ec885093f28
3,598,438
def test_np_print_2(): """ Feature: JIT Fallback Description: Support print. Expectation: No exception. """ class PrintNet(nn.Cell): def construct(self): x = np.array([1, 2, 3, 4, 5]) print("x: ", x) return Tensor(x) net = PrintNet() res = net...
075d70848ece95d314167014d0730b12f9967996
3,598,440
def hkcancor_to_ud(tag: str = None): """Map a part-of-speech tag from HKCanCor to Universal Dependencies. HKCanCor uses a part-of-speech tagset of over 100 tags (46 of which are described at http://compling.hss.ntu.edu.sg/hkcancor/). For applications that would benefit from a less granular part-of-spee...
56624cb18f6684f317f7caaa04f884bdf149282b
3,598,441
def to_array(x): """Convert the input to a numpy array""" if isinstance(x, pd.Series): return x.values return np.asarray(x)
77196a44a6580ebbfc1667c46c4edc8e9525c365
3,598,442
def example_two_by_two_data(): """load santa clara data to test two by two ei and plots""" sc_data = data.Datasets.Santa_Clara.to_dataframe() group_fractions = np.array(sc_data["pct_e_asian_vote"]) votes_fractions = np.array(sc_data["pct_for_hardy2"]) precinct_pops = np.array(sc_data["total2"]) ...
33d99d6b3804b77eab1486347d9f84943899f462
3,598,443
def is_russian(token): """ Returns true if the token contains only russian characters or punctuation, otherwise false. """ return any([c in RUS_ALPHABET_SET for c in token])
db880efa5de5a028c220ea075c925c02244099e9
3,598,445
def check(client: Client, args: Namespace) -> bool: """Checks whether the specified conditions are met.""" stats = client.stats(full=True) if args.max_players is not None and stats.num_players > args.may_players: return False if args.min_players is not None and stats.num_players < args.min_pl...
c129a5023359e5461cd214b0c713603bc8c066c6
3,598,446
def get_languages(*args, **kwargs): """ Wraps tesserocr.get_languages() with a fixed path parameter. """ return get_languages_(*args, path=get_tessdata_path(), **kwargs)
077903b485d112b0de09fe959398fa57f87975c4
3,598,447
def adjust_contrast_log(arr, gain): """ Adjust image contrast by scaling pixels to ``255*gain*log_2(1+v/255)``. Supported dtypes ---------------- * ``uint8``: yes; fully tested (1) (2) (3) * ``uint16``: yes; tested (2) (3) * ``uint32``: no; tested (2) (3) (8) * ``uint64...
5fd52969c2c2222f9d9ae20f2a2c42fcefe6582e
3,598,448
def largest_odd_factor(var_arr): """ Function that computes the larges odd factors of an array of integers Parameters ----------------- var_arr: numpy.array Array of integers whose largest odd factors needs to be computed Returns ------------ odd_d: numpy.array Array of...
408e94c6223dec5e529d69181a8f187b017fe5b6
3,598,449
def update_step(loss, config, clip_gradient=1., scope='optimizer'): """Computation of gradients and application of weight updates Optimizer can be supplied via config file, e.g. as "optimizer_params": {"learning_rate": 1e-3}, "optimizer": "'AdamOptimizer'" Parameters ------- loss : tensor ...
797d90163efc1ea21f8f7526a7ff022d4bcabff6
3,598,450
def set_ecr_repository_tags(ecr_repository_arn, resource_tags): """Applies a list of passed resource tags to the AWS ECR repository. Args: ecr_repository_arn: ECR repository identifier/ARN resource_tags: a list of key:string,value:string resource tag dictionaries Returns: Returns T...
3c49d7d1871ff46f84b64488329270da0f9d1445
3,598,452
import base64 import gzip def decode_base64_gzip_to_bytes(base64_gzip_data: str) -> bytes: """Decode Base64 GZIP into bytes.""" with BytesIO() as compressed_file: compressed_file.write(base64.b64decode(base64_gzip_data)) compressed_file.seek(0) with gzip.GzipFile(fileobj=compressed_fi...
a06b315281c1aae8e87e2d6bc5c403929012b534
3,598,453
import logging def download_script(script): """Download a script""" logging.info('[ROUTER]: Download script '+script) try: script = ScriptService.get_script(script, current_identity) return send_from_directory(directory=SETTINGS.get('SCRIPTS_FS'), filename=script.slug + '.tar.gz') exce...
345097cda32d80863771485c5045f3f7b9544ad3
3,598,454
import toml import yaml import json def mock_settings_file(request, monkeypatch, tmpdir, file_extension): """Temporarily write a settings file and return the filepath and the expected settings outcome.""" ext = file_extension p = tmpdir.mkdir("sub").join("settings" + ext) expected_result = {"testgrou...
4899ebbc9efbe31a931387d4a09dcb8c727eaf8d
3,598,456
def MathSolution(N): """Use sum of squares formula and sum of integers formula for O(1) solution""" sumOfSquares = N * (N+1) * (2*N + 1) // 6 squareOfSum = pow((N + 1) * N // 2, 2) diff = squareOfSum - sumOfSquares print("Math solution: ", diff) return diff
d30046150d95c3217bc446fc3c8e5f3a985f6c51
3,598,458
from typing import List def extract_urls_with_indices(text: str, extract_urls_without_protocol: bool = True) -> List[dict]: """ Extract valid URLs present in ``text`` along with their Unicode code point indices. >>> extract_urls_with_indices('http://twitter.com/これは日本語です。example.com中国語') [ { ...
1cc646a678a82512fed3cf984c698dffae8e1752
3,598,459
def error_handler(func): """Contain handler for json and error exception. Accept only one value (not tuple) and should be a dict/list Arguments: func {[type]} -- [description] Returns: [type] -- [description] """ @wraps(func) def wrapper(*args, **kwargs): try: ...
4d3dae44f42d31abc722104e8130132330ce00f1
3,598,460
import re def searchWalmart(query): """ The searchWalmart function scrapes walmart.com Parameters: query- search query for the product, currency- currency type entered by the user Returns a list of items available on walmart.com that match the product entered by the user """ qu...
01180517570d5ef7abc1b937cc3b1077bf22fed1
3,598,461
def get_months_range(start_date, end_date, keep_day=False): """ Returns a list of all months that are within start_date and end_date. Useful when we need to fill up missing months in a QuerySet where there were no results in that month and fill up those months with the value `0`. """ start_date ...
ac755beb085b8d696471bf316b1fe8d4479946e8
3,598,462
def integrator_interval(x, k): """ Compute the interval of an integrator system: dx = -k*x :param x: state interval :param k: gain interval, must be positive :return: interval for dx """ if x[0] >= 0: interval_gain = np.flip(-k, 0) elif x[1] <= 0: interval_gain = -k ...
0f6c3667ffff4e78d777a0b6e2220713ad0623e6
3,598,463
import requests def get_page(link): """ this thing takes a link and shoves back some html shit """ r = requests.get(link) r.raise_for_status() return r.content
913b96c8670e7d91da92aa00d53582d7eae33dbe
3,598,464
from typing import Iterable def _build_correction_str(iterator: Iterable) -> str: """ Creates madx commands (assignments) to run for correction""" last_type = '' text = '' for corr in iterator: if not _types_almost_equal(corr.type, last_type): text += f"\n!! {_nice_type(corr.type)}...
d460d1e265619235a71b815b98d8ac4d1200bbbd
3,598,465
def _start_daemon_and_get_client(wallet_name): """ Starts a daemon and create a client """ electrum_dir = _create_electrum_dir() # check if running already process_name = j.sal.process.getProcessByPort(RPC_PORT) if process_name and 'electrum' in process_name: print("Electrum daemon i...
1e3005adb5f554363dba97101a649d9005548d2c
3,598,467
from typing import Union from typing import Tuple def nonzero(x: Union[ivy.Array, ivy.NativeArray]) -> Tuple[ivy.Array]: """Returns the indices of the array elements which are non-zero. Parameters ---------- x input array. Must have a positive rank. If `x` is zero-dimensional, the function ...
627780d21c18c9a3c862341428202dd1587b60af
3,598,468
import signal import asyncio def cli_coro( signals=(signal.SIGHUP, signal.SIGTERM, signal.SIGINT), shutdown_func=None, ): """Decorator function that allows defining coroutines with click.""" def decorator_cli_coro(f): @wraps(f) def wrapper(*args, **kwargs): loop = asyncio....
b79b07071bd4c751805ced879fe354c5a45c78eb
3,598,470
def replicate_idx(head): """Return a list of indices representing replicate groups""" h = head g = h.groupby(['Sample Name', 'Measurement day']) idx = [i[1].index for i in g] return(idx)
ac5b80de8d15ef283185b0e93d495516695aa936
3,598,471
def get_plugin_instance(api_client, id, *args, **kwargs): # noqa: E501 """get_plugin_instance # noqa: E501 Get running plugin instance # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> response = await api....
ca74093c8fc963a7555a570b18b15f1bf7190ac0
3,598,472
def str2ascii(string: str) -> list: """Convert a string to a list of ascii-codes""" return [ord(i) for i in string]
a938b0c585e78a455721e9d17e8915b0769a025f
3,598,473
def rgbToHexColor(r, g, b): """Convert r, g, b to #RRGGBB.""" return f'#{int(r):02X}{int(g):02X}{int(b):02X}'
5cff9abc67c235a4f0fdf258ea555f018d80d1ad
3,598,474
import pathlib def within_dev_env(): """ detect whether we are within an ASMR dev environment. """ return pathlib.Path('/.ASMR_DEV_ENV').exists()
86430b29846435b03460b2676d41cea0ba4063e4
3,598,475
def numeric_to_traj(vals, trajname, coordnames, indepvar=None, indepvarname='t', indepdomain=None, all_types_float=True, discrete=True, event_times=None, event_vals=None): """Utility function to convert one or more numeric type to a Trajectory. Option to make the trajecto...
7241d75179a923873fe9439fd08bc068a4dee262
3,598,476
def find_nearest(array, value): """Gets the nearest element of array to a value.""" array = np.asarray(array) idx = np.nanargmin((np.abs(array - value))) return array[idx]
6b216d10c85a4f9b378f807d42cc3507814fac6e
3,598,477
def red(url): """Redirects user from short_url to long_url :Parameters: - 'url': Short URL used to query for and redirect to long URL On GET: Grabs URL Mapping from database and routes accordinly """ if request.method == 'GET': url_map = URLMap.query.filter_by(short_url=url).first() ...
75da6d78bfd754b1a3c8779e40b960fb903252c3
3,598,478