content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import asyncio def pool_get_verifiers(pool_handle: PoolHandle) -> asyncio.Future: """Fetch the set of active verifiers for an opened pool instance.""" return do_call_async( "indy_vdr_pool_get_verifiers", pool_handle, return_type=lib_string, post_process=str, )
8c673a35e618529af719c550919002e870ab8f6d
3,605,300
def format_dir_list_recurse(curdir, search=""): """Format the list of directories.""" total = [] for item in curdir.contents: if isinstance(item, ListDir): total.extend(format_dir_list_recurse(item, search=search)) if item.used: total.append(item) elif...
7d0aa9bb99b2a5bc75729622c449b74a218758c9
3,605,301
def _load_config_file(config_file_path: str) -> Config: """Reformats and validates the config file """ parsed_config = _parse_config_file(config_file_path) reformatted_config = _reformat_dict(parsed_config["transient"]) reformatted_config["qemu_args"] = parsed_config["qemu"]["qemu-args"] trans...
2cb6fa16af3cd2d4ec6d4e038d4198cb429b91cd
3,605,302
def index(): """新闻首页""" #------------------获取用户登录信息------------------ #1.获取当前登录用户的id # user_id = session.get("user_id") # user = None # type:User # #2.查询用户对象 # if user_id: # try: # # 获取到用户对象 # user = User.query.get(user_id) # except Exception as e: ...
40581da5606ce87e43ca4e897106849214b16ebd
3,605,303
import os def quick_rw(mol, confId=0, step=1000, time_step=0.2, limit=0.1, shake=False, idx=None, tmp_clear=False, solver='lammps', solver_path=None, work_dir=None, omp=1, mpi=0, gpu=0, **kwargs): """ MD.quick_rw Geometry optimization by MD solver for random walk process Args: mo...
507b3aa03d934012544a2f5396e89f8bf49aa5e1
3,605,304
from typing import Dict def r_complex(params: Dict[str, float]) -> ComplexFloat: """ Reflection coefficient, derived from transmission coefficient Magnitude from |t|^2 + |r|^2 = 1 Phase from phase(t) - phase(r) = pi/2 """ r_amp = jnp.sqrt( ( 1. - params['t_amp']**2 ) ) r_ang = params['t_an...
eb4509814007c293b549dbe8b3eb6cfa8ed5f83d
3,605,305
def get_noam_schedule(optimizer, num_warmup_steps, model_size, last_epoch=1): """Creates a Noam (inverse square root) scheduler with linear warmup and encoder gradual unfreezing. :param optimizer: torch Optimizer where some param groups have 'group_type' key if group_type starts with 'encoder_' it will...
6b9a9c9bae0bbe16e2ba3f200270349173bce0c4
3,605,306
def isvalid(message): """Verifies that a message is valid. i.e. it's similar to: 'daily-0400/20140207041736'""" r = re.compile("^[^/]+/[0-9]+") return r.match(message)
5900e566780cc17c70a9239b374b77ea1eced83e
3,605,307
import os def fixture(filename: str) -> str: """Load fixture JSON data from disk.""" path = os.path.join(os.path.dirname(__file__), "fixtures", "smartthings", filename) with open(path, "r", encoding="utf8") as fp: return fp.read()
cd8b938b20832e2f0dc41a1027734d1a753698cb
3,605,308
def count_paths_of_type_source_fixed_target_free(source_id, source_type, rel_type_node_label_list, debug=False, limit=False): """ Given a fixed source node, look for targets along rel_type_node_label_list, counting the number of such paths for each target found :param source_id: id of source node (eg. OMIM:605724) ...
21556c9f8ab405ffa4514b578e7743ea48055a1a
3,605,309
def project_details(request, id): """ Show project details """ project = Project.objects.get(pk=id) voted = False if project.voters.filter(id=request.user.id).exists(): voted = True return render(request, "project_details.html", {"project": project, "voted": voted})
3fe5fef1fad53853310779cae7948e96e01f3d82
3,605,310
def target(func): """ This is a decorator function :param func: :return: """ def target_func(*original_args, **original_kwargs): # print 'before the func' # print original_kwargs retV = func(*original_args, **original_kwargs) if retV is None or retV == False: return False else: ...
0e77444acd4b3a2ba7efd49854a3c081a054d337
3,605,311
import turtle def new_horse(image_file): """(str) -> turtle Create a new horse where <image_file> is a valid shapename Returns a turtle object """ horse = turtle.Turtle() horse.hideturtle() horse.shape(image_file) return horse
8abd7ea09cfe3340c06250f430ee6f25b03f45aa
3,605,312
from sklearn.preprocessing import StandardScaler def process_XY(bigdf_subset): """ Takes dataframe containing amalgamated data, subsetted to get rid of NaNs, and outputs training & testing X and y """ #Creating X and y y = bigdf_subset['epa_meas'] X_raw = bigdf_subset.drop(columns=['epa_me...
db2858aaaf894217ec8522dff452897d7099ba61
3,605,313
def Recall(y_true, y_pred): """Recall metric. Only computes a batch-wise average of recall. Computes the recall, a metric for multi-label classification of how many relevant items are selected. """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K....
fde7fa088358915590e61f0c9bfcb2ed75e9ce73
3,605,314
import re def sort_simulations(df_ts, dyn_dend_order): """ Sorts the simulations in the dataframe according to the order in the list dyn_dend_order """ # Create a dictionary with the order of each simulation row in the plot dyn_dend_order_dict = { dyn_name : dyn_dend_order.index(dyn_name) for dy...
68ae24234698803e9f5dd861d7f5255f845401c7
3,605,315
import logging import statistics def getGenesUsed(t0tot, strainsUsed, all_df, minT0Gene, genesUsed, debug_print_bool=False): """ We create the variable genesUsed Args: t0tot: A Dataframe which contains datesetname: [sum1, sum2, ...] for datesetname in expsT0.keys(...
79263e06803d9f0258fe0e59bfb2a10be4ef9e56
3,605,316
def generate_chemicals_from_fragments(smiles_list, n=10): """ reconstruct chemicals from fragments Paramters ----------------- smiles_list: list of string list of smiles of fragments n: int number of chemicals to be generated Returns --------------- smiles_list: lis...
27ca6d17279765ef68121fdfdc33af7892644623
3,605,317
import random def rand_augment_both(im, mask,magnitude, ops, n_ops=2, prob=1.0,fill=(128,128,128),ignore_value=255): """Applies random augmentation to an image.""" ops = ops if ops else RANDAUG_OPS if ops=="full": ops=RANDAUG_OPS elif ops=="reduced": ops=RANDAUG_OPS_REDUCED else: ...
3eea1f502edc18019aa2f0df5ca8cb6b21dfa113
3,605,318
import csv def load_penetration(scenario, path): """ Load penetration forecast. """ output = {} with open(path, 'r') as source: reader = csv.DictReader(source) for row in reader: if row['scenario'] == scenario.split('_')[0]: output[int(row['year'])] = f...
23a9730e9d8ec524fe79eaf50c3adb2a1641d002
3,605,319
def table_pc(): """ Generate the final table without price and moving-average adjustments. Returns: nonadj_pc (pd.DataFrame) """ gross_premiums = premiums_data() gross_claims = claims_data() wealth = wealth_data() population = pop_data() gross_precl = pd.merge(gross_premium...
222e5ed59a7c85e043ad6556aa988012ba3f45ec
3,605,320
def get4Neighbors(img, i, j): """ Get the 4 neighbours for the pixel analysed. Parameters: img, image; i, row number; j, column number. Returns: neighbors, list of neighbors. """ N, M = img.shape neighbors = [] i...
e3765a34ad02b9cf8d1be19f6e0e03db20ea28df
3,605,321
def getAllSecurityGroups(roleArn=None): """ This function grabs each security group from each region and returns a list of the security groups. If a roleArn is provided, the role is assumed before monitoring """ session = getSession(roleArn) # defaults to local aws account if arn is None a...
31c8148899bf7b4cd751a78e5c4612e6c92b9e8b
3,605,322
def get_values(source, selection, lookup): """ Returns values for a selection of values after a lookup. :param source: The array of values to select from. :param selection: An array of keys, for the selection. :param lookup: The mapping to resolve actual indices of the value array from the sele...
fcb2b09b981a85ab64079cfeff8b3db77628a434
3,605,323
import os def default_log_path(): """ :return: The absolute path to the directory that contains Rally's log file. """ return os.path.join(os.path.expanduser("~"), ".rally", "logs")
28e51033d17de5a15079ab062c7169c51a65bf95
3,605,324
from typing import Union from typing import Optional from datetime import datetime import os def determine_source_date(workspace: Union[git.Repo, PathLike]) -> Optional[datetime]: """ Determine the date of most recent change to the sources in the given workspace """ try: if not isinstance(wor...
eda217e77e412e956ac388c1a32a124415776b07
3,605,325
import codecs import json import urllib def get_annotations(psm_row): """ Runs the Xi annotator to get the fragment annotation. """ if psm_row.SearchID > 10000: url = 'http://xi3.bio.ed.ac.uk/xiAnnotator/annotate/%s/85160-94827-76653-69142/%s/?peptide=%s&peptide=%s&link=%s&link=%s' % ( ...
d82063a94c8d222d0f1ccd5d82fb21b77ba8f066
3,605,326
def update_profile(): """User profile update.""" form = UserUpdateProfileForm() form.user_name.data = flask_login.current_user.name if form.validate_on_submit(): set_user_by_instance( db.session, user=flask_login.current_user, lastname=form.lastname.data, ...
d38e23596e2b8783901db018368d51c6a57a2095
3,605,327
def youtube_search(query, max_results, args): """Fetches youtube video links for the movie with title provided in query Fetches trailer url for movie with title in query and containing keywords "OFFICIAL" and "TRAILER" in the title. params: query: the keyword for the youtube search, for exampl...
3001b612bc156d67315e882f28aab704f8368eb5
3,605,328
import io import json import getpass import sys def load_credentials(login_arg, logger=None): """ Load credentials from JSON file Options: 1. '--api-server-login ./APIcredentials.json' 2. Load credentials from default config file '-C oasislmf.json' 3. Prompt for username...
225ba38044e8c84ab1f0c8aec7477e3450056c3f
3,605,329
def input_block(config, section): """Return the input block as a string.""" block = '' if section not in config: return '' for key in config[section]: value = config[section][key].strip() if value: block += '{} {}\n'.format(key, value) else: blo...
4f6ff5979c99171b390429bc6e90b325986d9f99
3,605,330
def fig3(data, lB_list, rho_p_fixed, rho_s_fixed, rho_p_varied, rho_s_varied, beads_2_M, kwargs, figsize=None, pad=3, vertical=True): """Plots Figure 3 of tie lines in polymer-salt plane.""" # formats figure if figsize is None: fig = plt.figure() else: fig = plt.figure(figsize=fi...
fdc51ec564ffa94941939b8b3288159679391faf
3,605,331
def broadcast_join_skewed(not_skewed_df, skewed_df, join_col, number_of_custs_to_broadcast): """ Suitable to perform a join in cases when one DF is skewed and the other is not skewed. splits both of the DFs to two parts according to the skewed keys. 1. Map-join: broadcasts the skewed-keys part of the no...
6e957d6210635faadecd1f78a4b7c0cd84f08b87
3,605,332
import os def get_working_dir(): """ Returns the base directory of the cartridge agent. :return: Base working dir path :rtype : str """ #"/path/to/cartridgeagent/modules/util/".split("modules") returns ["/path/to/cartridgeagent/", "/util"] return os.path.abspath(os.path.dirname(__file__))....
74fb1e3c792f51a9245a01353b1dbecb11a39e0c
3,605,333
def remove_suffix(string, suffix): """ This function removes the given suffix from a string, if the string does indeed end with the suffix; otherwise, it returns the original string. """ # Special case: if suffix is empty, string[:0] returns ''. So, test for a non-empty suffix. if suffix and str...
f5b0782333ecd5d6a9107f9412f131145612d3a2
3,605,334
import scipy def FindZeroDoubleExp(p, x0, yshift=0.0): """ Finds the zero point of a negative double exponential function. :return: roots """ roots = scipy.optimize.fsolve(doubleExponent, x0, args=(p, yshift)) return roots
40f7a4588ed76a5dcbad88cbff75cc61d31b5ce5
3,605,335
def parent_path(value: str) -> str: """Returns the parent configuration path from a configuration path.""" return CONFIG_SEPARATOR.join(value.split(CONFIG_SEPARATOR)[:-1])
6b8fecdbf0a2de3b22bbfd0a08f5d0bb65fb7c64
3,605,336
def optimize_pushes_pops(codes): """ This finds runs of push(es) followed by pop(s) and combines them into simpler, faster mov instructions. For example: push [bp+8] push 42 pop ax pop ax Will be turned into: mov ax, 42 mov ax, ds:[bp+8] """ optimized ...
522ac834c03e84093142f7f512158220c40cf2e5
3,605,337
def permutations(values): """Return a strategy which returns permutations of the collection "values".""" values = list(values) if not values: return just(()).map(lambda _: []) def build_permutation(swaps): initial = list(values) for i, j in swaps: initial[i], ini...
c295446d72af91c6545e700c9a2181b5ffc70379
3,605,338
def get_rebaser_factory(dvcs_type, rebasers=REBASERS): """Return implementation factory for dvcs_type""" return rebasers[dvcs_type]
407c70c878eda07ed5c2e23de7b5923655695bd9
3,605,339
def address(): """ RESTful controller to allow creating/editing of address records within contacts() """ # CRUD pre-process def prep(r): person_id = request.get_vars.get("person", None) if person_id: s3mgr.configure("pr_address", c...
20164702ec09c3ba1c09d7e22d174ed3f3bf8949
3,605,340
import re def get_gpm_orbit(gpmfile: str) -> int: """ Parameters: ----------- gpmfile: str GPM data file. Returns: -------- orbit: int GPM Granule Number. """ try: with h5py.File(gpmfile) as hid: grannb = [s for s in hid.attrs["FileHeader"].spli...
f8a56dcf27f335b5d39121331d8ea2bc59ff6ce6
3,605,341
def load_single_file_regression(directory, file_name, word_to_indices_map, nb_words=None): """ Loads a single file and returns a tuple of x vectors and y labels :param directory: dir :param file_name: file name :param word_to_indices_map: words to their indices :param nb_words: maximum word inde...
e971f76512b0aa67ce8842a9bf664df74c1b18cf
3,605,342
import ast import json def strtojson(intxt): """str to json function""" out = {} try: out = ast.literal_eval(intxt) except ValueError: out = json.loads(intxt) except SyntaxError as ex: raise Exception("SyntaxError: Failed to literal eval dict. Err:%s " % ex) from ex ret...
d4b1ba11dd6a064f46d4e07284b54f59072e15ef
3,605,343
def build_input_data(u_text, i_text, vocabulary_u, vocabulary_i): """ Maps sentences and labels to vectors based on a vocabulary. 就是把一个个review的单词换成vocab里的id """ l = len(u_text) u_text2 = {} for i in u_text.keys(): u_reviews = u_text[i] u = np.array([[vocabulary_u[word] for wo...
8b0aa34944357d061742b8c16350bf6717cb7458
3,605,344
def calculate_numerical(atoms, spring_constant, eq_len, time): """ Calculates the Newtonian using a form of Euler's Method. Returns the first atoms force, position, and velocity. :param atoms: [description] :type atoms: [type] :param spring_constant: [description] :type spring_constant: [type] ...
88383d7d73bae830f1b951816989292a298dd6bd
3,605,345
def _matrix_constrainer(support): """Helper for `constrainer` for matrix supports.""" constrainers = { Support.MATRIX_UNCONSTRAINED: identity_fn, Support.MATRIX_POSITIVE_DEFINITE: positive_definite, Support.MATRIX_LOWER_TRIL_POSITIVE_DEFINITE: lower_tril_positive_defi...
e7e8928d3756c73af96fd88bbb3e745e6884e2dd
3,605,346
def _fetch_development_fmri_participants(data_dir, url, verbose): """Helper function to fetch_development_fmri. This function helps in downloading and loading participants data from .tsv uploaded on Open Science Framework (OSF). The original .tsv file contains many columns but this function picks only...
13db7ae5839c9ad5c10f45d1828c92c2bf8cb888
3,605,347
import hashlib def git_hash_data(data, typ='blob'): """Calculate the git-style SHA1 for some data. Only supports 'blob' type data at the moment. """ assert typ == 'blob', 'Only support blobs for now' return hashlib.sha1(b'blob %d\0%s' % (len(data), data)).hexdigest()
b3195de0c04444a811308e8b2b79b5d136095ea8
3,605,348
def jaccard_index(a, b): """a and b must be binary!""" aaa = np.asarray(a) baa = np.asarray(b) u = aaa.copy() u[baa > 0] = 1 return float(np.sum(aaa * baa)) / u.sum()
bf944eeffa2606aba523a202edac5de81afc2049
3,605,349
from datetime import datetime def create_post(post_author, post_title, days, slug): """ Create a post with the given `post_text` and published the given number of `days` offset to now (negative for post published in the past, positive for post that have yet to be published). """ time = timezon...
e309e0a3df070891a7b3f4956d2cfdca845b0222
3,605,350
def db_batch_lookup(kind, entity_names): """Get multiple entities from the datastore Args: kind: GCP datastore entity kind. entity_names: entity names to find. Returns: The found entities if any. """ logger.info("In db_batch_lookup handler.") keys = [db.key(kind, entity_n...
9c2f8094861dfd724254f2f26f4310fbe7cdf4d4
3,605,351
def read_sa_cmd_helps_from_register_response(pdu: list) -> list: """Read TaiSEIA SA device supported commands from register response protocol data.""" register = SARegisterPacket.from_pdu(pdu) report = [] for service in register.services: _help = service.to_cmd_help() assert isinstance(_...
8876113bab72324899b71269a757ca2987e9a835
3,605,352
def fill_large_gaps(ds, shift): """ Fill up large gaps with load data from the previous week. This function fills gaps ragning from 3 to 168 hours (one week). """ shift = Delta(shift) nhours = shift / np.timedelta64(1, 'h') if (consecutive_nans(ds) > nhours).any(): logger.warning('T...
b983b032063747eef51a63e961f28fdb7741a343
3,605,353
def _vector_clock_equal(clock1, clock2): """ Compares two vector clocks, ignoring the timestamp field, which may be skewed. """ clock1_entries = dict((entry.node_id, entry.version) for entry in clock1.entries) clock2_entries = dict((entry.node_id, entry.version) for entry in clock2.entries) ret...
2402724d75f7e3b48b05764e056756bdb883ef2e
3,605,354
def random(options=('trapezoid', 'sin'), fractionwithextremelc=0.01, fractionwithrotation=None, fractionwithtrapezoid=None, fractionwithcustom=0.0, **kw): """ random() returns random Lightcurve. random() makes use of these keyword arguments: options=['trapezoid', 'sin'] (a li...
55133ebb6b329ae7b0773bb0dd6a939a268bc61e
3,605,355
def create_lattice(optics_mode=default_optics_mode, simplified=False): """Return lattice object.""" # -- selection of optics mode -- strengths = get_optics_mode(optics_mode=optics_mode) # -- shortcut symbols -- marker = _pyacc_ele.marker drift = _pyacc_ele.drift sextupole = _pyacc_ele.sextu...
074b1dc12099b56beb3c7affe5b1818469926e52
3,605,356
from typing import Dict from sys import path def read_graph(schema: tfgnn.GraphSchema, graph_dir: str, rcoll: PCollection) -> Dict[str, Dict[str, PCollection]]: """Read a universal graph given a schema. Args: schema: An instance of GraphSchema to read the graph of. graph_dir...
5fb7665ebdee8519ccf614d9a44212b2072f72e3
3,605,357
def npv_score(y_true, y_pred): """ A function provides npv given the prediction and the truth """ tn, _, fn, _ = confusion_matrix(y_true = y_true, y_pred = y_pred).ravel() return tn/(tn + fn)
0cc951f296fb5e23bc05df0963edb9602b3e650b
3,605,358
def load_data(filename_path, class_id_path, dataset_path, embeddings_path, size): """Loads the Dataset. """ class_id, filenames = load_class_ids_filenames(class_id_path, filename_path) embeddings = load_text_embeddings(embeddings_path) bbox_dict = load_bbox(dataset_path) x, y, embeds = [], [], [] for i, filena...
247a818ed5c08a3ddb2117ea1df5ec412da74195
3,605,359
async def root(): """ Show this docs """ return RedirectResponse(url='/docs')
de97f3eb111747044847b25aca8653ed0cb30e08
3,605,360
def Euler2Rotation(phi, theta, psi): """ Converts euler angles to rotation matrix (R_b^i, i.e., body to inertial) """ # only call sin and cos once for each angle to speed up rendering c_phi = np.cos(phi) s_phi = np.sin(phi) c_theta = np.cos(theta) s_theta = np.sin(theta) c_psi = np.c...
73890a603a5a0639e0cd9f57beb3f41232784dfc
3,605,361
from typing import OrderedDict def groupAddData(data, group_by="run.configuration,sample.description"): """ Addition of counts and monitor from different datasets, assuming all datasets were taken under identical conditions (except for count time) Groups by the metadata fields in "group_by" (comm...
8f4f44034a71bf7e92b059418a815dfe1d930241
3,605,362
import pickle from datetime import datetime def find_dex(sar_file, dex_list, dex_type): """ Find the corresponding DEX file for a given sar_file. :param sar_file: path to a SAR file :param dex_list: list of paths to DEX files :param dex_type: DEXA or DEXI :return: data contained in the corresp...
be5c53e33df1e4dd0f9fa9b73718dd3a548d5095
3,605,363
import select def latest_remote_checkpoints(db, user_id): """ Get the latest version of each file for the user. """ query_fields = [ remote_checkpoints.c.id, remote_checkpoints.c.path, ] query = select(query_fields).where( remote_checkpoints.c.user_id == user_id, )...
bc788a47bcb0e1812aa41849938a086c8c0b3d1f
3,605,364
import array def ReadTrans(filename, fh_info): """Read the self-energy index file Sigind and the local transformation matrix CF from a file""" fh = open(filename, 'r') data = fh.readlines() (n1,n2) = map(int, data[0].split()[:2]) Sigind=[] for i in range(n1): Sigind.append( map(i...
d9090e83ded597dfc86c96224b8dcb49cdb51068
3,605,365
import urllib import webbrowser import json def authenticate(scopes="public_profile"): """ Open browser to allow user to login, get authentication code, exchange to get (and return) access token. """ scopes = urllib.quote(scopes) LOGIN_URL = "https://www.facebook.com/dialog/oauth" \ ...
ad1fa4d0a1e6bb6c3ee336dc290215ccc48699b1
3,605,366
import os def get_filename(): """Return the full filename of the file currently debugged.""" return os.path.basename(gdb.current_progspace().filename)
f593bbefa546bc948f789906b82d8ab12baa2979
3,605,367
def wltc_class_pipeline(aug: autog.Autograph = None, **pipeline_kw) -> Pipeline: """ Pipeline to provide `p_m_ratio` (Annex 1, 2). .. graphtik:: :height: 600 :hide: :name: wltc_class_pipeline >>> pipe = wltc_class_pipeline() """ aug = aug or wio.make_autograph() ...
70c13592e1bbecc43a283fc3d6958c02135afad0
3,605,368
from pathlib import Path def db_init(db_file: Path) -> sessionmaker: """ Initializes the database and returns a session factory """ logger.info(f"Creating database file: {db_file}") engine = create_engine(f"sqlite:///{db_file}") Base.metadata.create_all(engine) return sessionmaker(bind=e...
4bf0c7a64d4d747459d858ffaf9fccf42e0aca83
3,605,369
import requests def submit_textarea(): """ Endpoint to create a new transaction via our application """ global errors name = request.form["name"] year = request.form["year"] brand = request.form["brand"] post_desc = request.form["description"] materials = request.form["materials"...
8496bbee086242ccc1bfdd2d37dce9088dcf85b2
3,605,370
def handle_response(response): """ Correct the response datatype if returned incorrectly :response Requests.models.Response: a response from the api :return: response ready for consumption from wrapper """ print data = response.json() if data['err_no'] == 0: return data['data'] ...
f18b26d2df8e6abf7625d1ad1153877eae6ecd64
3,605,371
import subprocess def video_length_seconds(videofile_path, binaries_ent=None): """ Get length of video in seconds. Args: binaries_ent: Dictionary with binaries and their path. videofile_path: Path to video file. Returns: Length of video in seconds. """ if binaries_ent is None: ...
76756352b22a27948cdc0ef0d5e883d6f2b0f69a
3,605,372
def presale_fund_collector(chain, presale_freeze_ends_at, team_multisig) -> Contract: """In actual ICO, the price is doubled (for testing purposes).""" args = [ team_multisig, presale_freeze_ends_at, to_wei("50", "ether"), # Minimum presale buy in is 50 ethers ] tx = { ...
93140948017c0bbefb44f66d73e1e4c33ea972bf
3,605,373
import os def get_workdir(iteration, workroot): """Find what is the root of the work-tree at a given iteration""" if workroot is None: workdir = None else: if iteration is None: myworkdir = 'noiter' else: try: myworkdir = '-'.join([str(it) fo...
817bd4d31cb50f9df14b2793c204b11f72b8bc37
3,605,374
from typing import Optional from typing import Tuple import warnings from sys import version def convert_keras_model( model: tf.keras.Model, *, # Require remaining arguments to be keyword-only. inference_input_type: tf.DType = tf.float32, inference_output_type: tf.DType = tf.float32, experimental...
39b163649f90b62cabf71a34b8718a514fa5663c
3,605,375
def check(token_fst,entries): """Return the list of conflicting attribute-value pairs between a treebank feature structure for a token and a list of dictionary entries for this token. If the structures unify with at least one entry, return the empty list. Otherwise return the inconsistencies collect...
0f8efc54ef07c3983cbb1b0112a0fdfc1a7f033f
3,605,376
def transpose(table): """Returns: copy of table with rows and columns swapped Precondition: table is a (non-ragged) 2d List""" new_table = [] n_row = len(table) n_col = len(table[0]) for col in range(n_col): each_col = [] for row in range(n_row): each_col.append(table...
11c74863d8b1941f1a74fb1c054f67b8dd2f22e8
3,605,377
import math def my_shaded_trace( fig: go.Figure, df: DataFrame, d: str, color: str, grps: list, key: str, col=None, row=None, show_legend=True ): """ Add a shaded trace to a plotly figure Parameters ---------- fig : go.Figure The figure to which the trace will be added df : DataFr...
66cd6b6bc88b6a40337366758895aa131ed09758
3,605,378
def resize_with_aspectratio(img, out_height, out_width, scale=87.5, inter_pol=cv2.INTER_LINEAR): """ resize image with aspect ratio """ height, width, _ = img.shape new_height = int(100. * out_height / scale) new_width = int(100. * out_width / scale) if height > width: w = new_width ...
01fd07c197e7f264f673f46dc301430f822268a4
3,605,379
def _algebraic_error(x_w_rotated, x_cam, weight): """Computes the residual of Umeyama in 3D. Args: x_w_rotated: The given 3D points rotated with the predicted camera. x_cam: the lifted 2D points y weight: Batch of non-negative weights of shape `(minibatch, num_point)`. `None`...
e1a09bccbc8af157630c70facd334e40d1ceca4d
3,605,380
def num_processes(): """ Return the number of MPI processes (not used for SpiNNaker, always returns 1) """ return 1
51bcd083a57cbce544b52cc1f1ef3772fb0d362c
3,605,381
def specgrid(params, fit): """ Calculate emission from each cell of a planetary grid, as a fraction of stellar flux, NOT accounting for visibility. Observer is assumed to be looking directly at each grid cell. For efficiency, never-visible cells are not calculated. Function returns a spectrum o...
69b66b9c73d8662aeca3238cb84f60923dee9272
3,605,382
import tqdm def calcSS(f, bs=20000, winSize=500000, cut=0,mcut=-1,hic=False): """ Calculation of correlation matrix insulation score, output as .bedGraph file. @param bs: bin size @param winSize: sliding matrix width half size @param cut: distance cutoff for PETs """ key, mat = parseIxy(f,...
05e7c041bf56cceb907aa30df798ab312c256a34
3,605,383
def hash_generator(token_to_id, tokens): """Generate hash for tokens in 'tokens' using 'token_to_id'. Args: token_to_id: dict. A dictionary which maps each token to a unique ID. tokens: list(str). A list of tokens. Returns: int. Hash value generated for tokens in 'tokens' using 'to...
d9a059e22ab8574fd3c49dfa594cd903edb64d8b
3,605,384
def ndsnap_regular(points, *grid_axes): """ Snap points to the 2d grid determined by grid_axes """ # https://stackoverflow.com/q/8457645/717525 snapped = [] for i, ax in enumerate(grid_axes): diff = ax[:, np.newaxis] ...
c2d9644c59877e04f1367a7ef5e95ad9de84be95
3,605,385
import uuid import random import base64 def create_captcha(): """ Generates a captcha image. Returns a tuple with a token and the base64 encoded image """ token = str(uuid.uuid4()) captchagen = ImageCaptcha(width=250, height=70) if random.randint(1, 50) == 1: captcha = random.choice( ...
0ba0405eb05748862fd363d29d2707b65dd3d7eb
3,605,386
from typing import Tuple def get_missingdays(station: int, tabname: str = "readings") -> Tuple[list, list]: """ Retrieves :param station: the station to assess :param tabname: name of the table where the readings are stored, defualts to "readings" :return: hit set with the data calculated and list...
d45616b0116f13a4b2ca08ccd03a8621c3451734
3,605,387
def search_for_entry(string_2_serch, file_in, nline=0): """ Extract from the input file (file_in) up to the line number nline (if declared) the value assigned to string_2_serch. Input: string_2_serch = string (or list of string) containing the variable to search (e.g. 'HEIGHT=') file_in = name o...
88e9eaf80848c035b7a10e1adea9b2bc5d9b7b7f
3,605,388
from io import StringIO import os def preprocess(input_file, output_file, defines=None, options=None, content_types_db=None, _preprocessed_files=None, _depth=0): """ Preprocesses the specified file. :param input_fil...
22859d18a00a3afec2cf992512b7cf0305d416d1
3,605,389
def get_hgnc_universe(ifh): """Extract all HGNC identifiers from iRefIndex data file @ifh@ and return them as a set""" header = parse_header(ifh) hgnc_set = set() for line in ifh: data = line.split("\t") hgncs = get_hgnc(header, data) for hgnc in hgncs: hgnc_set.add(hgnc) return hgnc_set
f8a3fecf8a580b8bd083ff29d62905ad1f9b57b2
3,605,390
def get_ucs_faults(): """ Get UCS Faults """ sev_critical = 0 sev_major = 0 sev_minor = 0 sev_warning = 0 handle = ucs_login() faults = handle.query_classid("FaultInst") for fault in faults: if fault.severity == 'critical': sev_critical += 1 elif fault.seve...
8ed809ad9479108b209b4514dc7cd633fe390c5b
3,605,391
def pack_varint(data): """Pack a VARINT for the protocol.""" return bytes([(0x40 * (i != data.bit_length() // 7)) + ((data >> (7 * i)) % 128) for i in range(1 + data.bit_length() // 7)])
1bdb283a787fc6b9e65e278d581b7654088ddf87
3,605,392
def update_user(): """ Edit user profile. """ error = None # CSRF is disabled because it prevented this from working and I couldn't figure out why it was missing # TODO: Figure out why CSRF token is missing and re-enable form = RegistrationForm(request.form, csrf_enabled=False) if form...
8d3cbb343ca945dde47f600ceeff7534289ee59a
3,605,393
def _graph_reduction(adj, x, g, f): """we can go ahead and remove any simplicial or almost-simplicial vertices from adj. """ as_list = set() as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)} while as_nodes: as_list.union(as_nodes) for n in as_nodes: ...
903c58e718d4f54c944f27b200000961d0dcd194
3,605,394
import re import six def parse_issuer_cred(issuer_cred): """ Given an X509 PEM file in the form of a string, parses it into sections by the PEM delimiters of: -----BEGIN <label>----- and -----END <label>---- Confirms the sections can be decoded in the proxy credential order of: issuer cert, issuer...
2df56219076f928b597bb16d0abb03bd8a61dc63
3,605,395
def iter_months_days(year, month_of_year=None, day_of_month=None, in_reverse=False): """Iterate over each day in each month of year. year is an integer specifying the year to use. month_of_year is an optional integer, specifying a start month. day_of_month is an optional integer, s...
33531898059220fa7855a7d0e2dedecf623a5c08
3,605,396
def get_ledger_accounts(): """ Returns all ledger accounts. :returns: String containing xml or an lxml element. """ return get_anonymous('getLedgerAccounts')
01b190f66dcb25d9a0db13129bb4a84af856e369
3,605,397
def svn_checksum_dup(*args): """svn_checksum_dup(svn_checksum_t checksum, apr_pool_t pool) -> svn_checksum_t""" return _core.svn_checksum_dup(*args)
ca6eb452f732ac1b0ba95facc1474f9174409639
3,605,398
import argparse def get_args() -> argparse.Namespace: """Gets arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '-cc', '--common-config', required=True, help='Path to common config file', ) parser.add_argument( '-m', '--method', ...
5e9f5c825804572e4f6eeeae5ab0a3aa5b0a0d82
3,605,399