content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def likelihood(sent, ai, domain, temperature): """Computes likelihood of a given sentence according the giving model.""" enc = ai._encode(sent, ai.model.word_dict) score, _, _= ai.model.score_sent(enc, ai.lang_h, ai.ctx_h, temperature) return score
8332dfc8c2dba18a117768043dff67e632cc22ff
8,500
def simulator( theta, model="angle", n_samples=1000, delta_t=0.001, # n_trials max_t=20, no_noise=False, bin_dim=None, bin_pointwise=False, ): """Basic data simulator for the models included in HDDM. :Arguments: theta : list or numpy.array or panda.DataFrame ...
370e45499f85bd406a2f80230389dd6aa9866cf0
8,501
from pytato.utils import with_indices_for_broadcasted_shape from typing import Union def logical_not(x: ArrayOrScalar) -> Union[Array, bool]: """ Returns the element-wise logical NOT of *x*. """ if isinstance(x, SCALAR_CLASSES): # https://github.com/python/mypy/issues/3186 return np.lo...
922f7a0688590fad9492b7e654f97b2f34717ca8
8,502
def _build_xyz_pow(name, pref, l, m, n, shift=2): """ Builds an individual row contraction line. name = pref * xc_pow[n] yc_pow[m] * zc_pow[n] """ l = l - shift m = m - shift n = n - shift if (pref <= 0) or (l < 0) or (n < 0) or (m < 0): return None mul = " " if pref =...
0dbae02252b27845e795a586e2e28b58c948fa1d
8,503
def create_decode_network(width=width, height=height, Din=Din, Dout=Dout, d_range=d_range): """ data flow with traffic on: input IO -> tag horn -> (pre-fifo valve) -> FIFO -> (post-fifo valve) -> TAT -> AER_tx -> neurons -> AER_rx -> (neuron output valve) -> PAT ...
bce65caa463bea8a582426bfe9fac08617fca812
8,504
def canny(img, low_threshold, high_threshold): """Applies the Canny transform""" return cv2.Canny(img, low_threshold, high_threshold)
df3ede87458939e7648090517828e2056cd9cfd6
8,505
import os import subprocess def pscmd(item, pid=os.getpid()): """Invoke ps -o %(item)s -p %(pid)d and return the result""" pscmd = PSCMD if item == 'sid' and os.uname()[0] == 'AIX': pscmd = '/usr/sysv/bin/ps' if item == 'sid' and os.uname()[0] == 'Darwin': item = 'sess' assert pscm...
db9f5384984b74381cef2b34f5d9aa07acdefe83
8,506
def dGcthetalnorm(w: Wilson, cthetal): """Normalized distribution 1D cthetal""" return tauBp / Btaul * dGcthetal(w, cthetal)
b925c6dad2dd6327f3fe250771c19018ecedcf14
8,507
from typing import Optional def user_deposit_address_fixture( deploy_smart_contract_bundle_concurrently: FixtureSmartContracts, ) -> Optional[UserDepositAddress]: """ Deploy UserDeposit and fund accounts with some balances """ services_smart_contracts = deploy_smart_contract_bundle_concurrently.services_s...
496f27fd9576191e91ac90c6e17c2b07fae629ab
8,508
def vonNeumann(t, rho, H): """(quantum Liouville-)von Neumann equation""" H = H(t) rho = rho.reshape(H.shape) rho_dot = -1j*(np.dot(H, rho) - np.dot(rho, H)) return rho_dot.flatten()
e00f9cdadacf36ba40240018d4b1dac1a7ebbba3
8,509
import tqdm def conjure_categories(path): """ Look for all pngs in the path. They are generated by quicklook.py and organised into folders by resolution. Each resolution has a number of variables associated to it and each variable can have a number of vertical levels and lead times associated to ...
c36fdba3dd0ac159ee2178a0eda2a617356f0c52
8,510
def nicer_array(a, mm_cutoff=0.3): """ Returns a scaled array, the scaling, and a unit prefix Example: nicer_array( np.array([2e-10, 3e-10]) ) Returns: (array([200., 300.]), 1e-12, 'p') """ if np.isscalar(a): x = a elif len(a) == 1: x = a[0...
e5abe6b45a4c80d8eb84d9f9f5aed1b11f19684e
8,511
import uuid import pickle def build_playground(): """ build a playground based on user's input building and algorithm type input: userid, algorithm, target building output: none """ userid, building, algo_type = request.form['userid'], request.form['building'], request.form['algo_type'] us...
31b73b3c505d27dca07569dc95c31d78822da452
8,512
def menuItemDirective(_context, menu, for_, action, title, description=u'', icon=None, filter=None, permission=None, layer=IDefaultBrowserLayer, extra=None, order=0, item_class=None): """Register a single menu item.""" return menuItemsDirective(_...
9ca19bd71cef30db9f8cd2a1154154965cf31b7d
8,513
def getQueueStatistics (): """ Returns a 4-tuple containing the numbers of identifiers in the Crossref queue by status: (awaiting submission, submitted, registered with warning, registration failed). """ q = ezidapp.models.CrossrefQueue.objects.values("status").\ annotate(django.db.models.Count("status"...
2693365e24dc28b57ddbc8db5315779acee2d617
8,514
def assign_targeting_score_v2( base, manual_selected_objids=None, gmm_parameters=None, ignore_specs=False, debug=False, n_random=50, seed=123, remove_lists=None, low_priority_objids=None, **kwargs, ): """ Last updated: 05/19/2020 100 Human selection and Special targe...
88ab3ff423eb8d0ce64906d330e42b037ff8cad5
8,515
from typing import List from typing import Union def create_compressed_generator( original_generator: CompressorArg, compressed_cse_list: List[List[Union[List[uint64], List[Union[bytes, None, Program]]]]], ) -> BlockGenerator: """ Bind the generator block program template to a particular reference blo...
c2eb437caefa53452df61e1f5b4115ab4220a323
8,516
def run_mcmc(meas, x, nsamples, covm=None, scales=None): """ Sample the likelihood space with a Markov Chain Monte Carlo. :param meas: TemplateMeasurement measurement whose spectrum likelihood space is to be probe :param x: [float] parameter values where to start the chain :param co...
79f7806d3c5c84693dfbfcd6d4236734ec7921de
8,517
def get_vlan_list(dut, cli_type="click"): """ Get list of VLANs Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param dut: :param cli_type: :return: """ st.log("show vlan to get vlan list") rv = show_vlan_config(dut, cli_type=cli_type) vlan_list = list(set([eac['vid'] for...
5ce768bc8a30fa73fb2f4930384197535584de64
8,518
def begin_organization_creation_task(registered_id): """ Asynchronously create our tenant schema. Email owner when process completes. """ # Run the sub-routine for taking the OrganizationRegistration object # creating our Tenant from it. call_command('populate_organization', str(registered_id)) ...
fcaccc4e44def7a0d5ce83ac179899d0b288ac9c
8,519
import itertools def rewrite_blockwise(inputs): """Rewrite a stack of Blockwise expressions into a single blockwise expression Given a set of Blockwise layers, combine them into a single layer. The provided layers are expected to fit well together. That job is handled by ``optimize_blockwise`` ...
dc80aa6c55d3ac6fafe780e5c58f3961d5d92b66
8,520
def sort_drugs(processed_data, alpha_sort, **kwargs): """ Sorts all drug names, as primary keys of processed data dictionary. Sorting is governed by primary criteria of decreasing cost, then secondary criteria of alphabetical order. Secondary criteria ignores unsafe characters if "alpha_sort" is Tru...
aa3727dc52f0204c7c39807982a998cc03fabd2d
8,521
def log_k2ex_and_get_msg(ex, prefix, topology): """ LOG K2 exception and extracted message. Return NLS message """ LOG.exception(ex) detail = {} k2msg = _("None") if isinstance(ex, K2Error) and ex.k2response: detail['Request_headers'] = ex.k2response.reqheaders detail['Response_heade...
a1a827ac38980e593e58236ce8d60eb01b957050
8,522
def fetch_ticket(identifier): """Return data of ticket with given identifier as pandas dataframe.""" try: return pd.read_csv(f'./data/tickets/{identifier}.csv') except: return None
46d776eab0e7867dd14079147a6101c9b8fddfa5
8,523
import torch def dice_loss(logits, targets, smooth=1.0): """ logits: (torch.float32) shape (N, C, H, W) targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1} """ outputs = F.softmax(logits, dim=1) targets = torch.unsqueeze(targets, dim=1) targets = torch.zeros_like(logits).scatter_(dim=1, index=target...
4ac40e87fe048dbc3232bb82c7fa16d9c03a8439
8,524
def deltaG_methanogenesis_early_Earth(T, pCO2, pH2, pCH4): """ Equation: CO2 (g) + 4H2 (g) --> CH4 (g)+ 2H2O (l) Assumes bar, 1bar total pressure, for gases. T must be array (even if just 1 entry) """ R=8.314E-3 #kJ mol^-1 K^-1 deltaG_0=deltaG_F_PSat_T_CH4_g(T)+2.0*deltaG_F_PSat_T_H2O_l...
d54f15296a17a927f4e8f924b4620b2fdab4082a
8,525
import matplotlib.pyplot as plt import time def optimize_on_joints(j2d, model, cam, img, prior, try_both_orient, body_orient, n_betas=10, ...
2ce29fae66bd7898414194012a1b33e8768605b0
8,526
import math def make_axis_angle_matrix(axis, angle): """construct a matrix that rotates around axis by angle (in radians)""" #[RMS] ported from WildMagic4 fCos = math.cos(angle) fSin = math.sin(angle) fX2 = axis[0]*axis[0] fY2 = axis[1]*axis[1] fZ2 = axis[2]*axis[2] fXYM = axis[0]*axis...
1bef075e63b26559184025a69f47d8c1b6dccf1d
8,527
def get_agent_type_from_project_type(): """ use project type to determine agent type """ if 'METRIC' in if_config_vars['project_type']: if if_config_vars['is_replay']: return 'MetricFileReplay' else: return 'CUSTOM' elif if_config_vars['is_replay']: return 'Lo...
a2ea351fcba68dde4db2b9200636c937a58ab960
8,528
import traceback def close_server(is_rebooting = False): """ Close the Unity server and tell clients to react appropriately. Set `is_rebooting` to handle cases like domain reload when Unity is expected to come back shortly. Returns True if the server was closed by this call, False if it was already ...
77fbd9ecd8ed7489d4f5763c5bb417c7cb5ddb15
8,529
import types def dict_decode(node_dict: dict) -> Node: """Convert a dictionary to an `Entity` node (if it has a `type` item).""" if "type" not in node_dict: return node_dict node_type = node_dict.pop("type") class_ = getattr(types, node_type, None) if class_ is None: return node_...
00b790e431cdf080c0a6220c2913fd511983904d
8,530
from datetime import datetime def compute_purges(snapshots, pattern, now): """Return the list of snapshots to purge, given a list of snapshots, a purge pattern and a now time """ snapshots = sorted(snapshots) pattern = sorted(pattern, reverse=True) purge_list = [] max_age = pattern[0] ...
710a65ef7068d57470fb72ff171a1f1eb3480d65
8,531
import logging def design_partial_factorial(k: int, res: int) -> DataFrame: """ design_partial_factorial This function helps design 2 level partial factorial experiments. These experiments are often described using the syntax l**(k-p) where l represents the level of each factor, k represents the ...
a9c93cf696c33f0eb74cb092d1f340d5732dc994
8,532
from pathlib import Path import os import json def find_latest(message_ts: str, post_dir: Path) -> str: """Retrieves the latest POST request timestamp for a given message.""" latest_ts = message_ts for postfile in os.listdir(os.fsencode(post_dir)): if (filename := os.fsdecode(postfile)).endswith('...
5c5203cf1adc572cf7e9908dcd3c856de7c0f0da
8,533
def get_trending_queries(filename): """Extract trends from a file.""" f = open(filename, 'r') trend_tuples_list = [] for line in f: trend_tuples_list.append(tuple((line.strip()).split(','))) f.close() return trend_tuples_list
6f5828d4bf0092c0a43804ca7ffb9ee4aa67e607
8,534
def get_bio(x, lang='en'): """Get the one-sentence introduction""" bio = x.loc[16][lang] return bio
8c9ddabd2e6ada790af2b85a3fb656291f3ee5bd
8,535
import io def create_tf_example(filename, source_id, encoded_jpeg, annotations, resize=True): """ This function creates a tf.train.Example in object detection api format from a Waymo data frame. args: - filename [str]: name of the original tfrecord file - source_id [str]: original image s...
b757fc1e4d51fac5722eb170357ea36388d40d5d
8,536
import re def format_oids(oids_parameters): """ Format dictionary OIDs to ``cryptography.x509.oid.NameOID`` object list :param oids_parameters: CA Object Identifiers (OIDs). The are typically seen in X.509 names. Allowed keys/values: ``'country_name': str (two letters)``, ...
08641ffb1c431c13e23f2b9498ce1cb1a896f955
8,537
def Phases(*args): """Number of phases""" # Getter if len(args) == 0: return lib.Generators_Get_Phases() # Setter Value, = args lib.Generators_Set_Phases(Value)
d1610c5b2ab19cf2b3018850fe685bb9fcbc11ad
8,538
import requests def create_channel(logger: Logger, connection: komand.connection, team_id: str, channel_name: str, description: str) -> bool: """ Creates a channel for a given team :param logger: (logging.logger) :param conne...
6cdd37a7fdc131433f9f75ba10e523bc719a34aa
8,539
import sys def getMoveValue(board, table, depth, move): """ Sort criteria is as follows. 1. The move from the hash table 2. Captures as above. 3. Killers. 4. History. 5. Moves to the centre. """ # As we only return directly from transposition table if hashf == has...
31f530733908c39eace8a2b3d857b2b7c42b47be
8,540
def activate_user(username): """Activate a user account.""" user = annotator.credentials.find_one({'username': username}) if not user['active']: annotator.credentials.update_one(user, {'$set': {'active': True}}) flash("User {0} activated successfully".format(username), 'success') else: ...
58b70edc4a098a7409e1c2e62f9710b3da3c95af
8,541
def query_all(): """Queries all matches in Elasticsearch, to be used further for suggesting product names when a user is not aware of them. """ query_all = { "query": {"match_all": {}}, } return query_all
9d15297cf82d813ff0a0688f5c25e2ca6fa145d3
8,542
def _mesh_homogeneous_cell(cell_vect, mesh_path): """Generate a simple mesh for a homogeneous cell. cell_vect: np.array 2x2 colonnes = vecteurs periodicité """ name = mesh_path.stem geometry.init_geo_tools() geometry.set_gmsh_option("Mesh.MshFileVersion", 4.1) # Mesh.Algorithm = 6; Frontal...
98c63d7764bcca7baad81de1fe7c3fac16ff6ffd
8,543
async def async_setup_entry(hass, config_entry): """Initialize the sharkiq platform via config entry.""" ayla_api = get_ayla_api( username=config_entry.data[CONF_USERNAME], password=config_entry.data[CONF_PASSWORD], websession=hass.helpers.aiohttp_client.async_get_clientsession(), ) ...
c260e59ba86c72e84bef3f51d21b2500195b1a08
8,544
from typing import Dict from typing import Union from typing import Optional from typing import List from typing import Tuple from typing import cast from typing import Any import json def fetch_incidents(client: Client, max_incidents: int, last_run: Dict[str, Union[Optional[int], Optional[str]]],...
e273d69611331c9f2eb5b2c0c9c27e805c9d7e4f
8,545
import collections def extractWordFeatures(x): """ Extract word features for a string x. Words are delimited by whitespace characters only. @param string x: @return dict: feature vector representation of x. Example: "I am what I am" --> {'I': 2, 'am': 2, 'what': 1} """ # BEGIN_YOUR_CO...
dd5247dbf7ef69043b200acbefec996107de00f7
8,546
def delete_user(user_id): """ Delete user specified in user ID Note: Always return the appropriate response for the action requested. """ user = mongo_mgr.db.user.find_one({'_id': user_id}) if user: user.deleteOne({'_id': user_id}) result = {'id': user_id} else: resul...
b3244aeafcddd6c5be1d209c89ef7ed7969da989
8,547
from operator import and_ import logging def query_attention_one(**kwargs): """ 查询当前用户是否关注指定的物件 :param kwargs: {'user_id': user_id, 'object_id': object_id} :return: 0 or 1 """ session = None try: session = get_session() results = session.query(func.count('*')).filter(and_(A...
44db7006eec38c2524fe5a74dba46086c63c79c5
8,548
def _dict_empty_map_helper(values, empty, delim, av_separator, v_delimiter, parser): """ A helper to consolidate logic between singleton and non-singleton mapping. Args: values: The value to parse. empty: The empty representation for this value in CoNLL-U format. ...
cb5550eb606beb47f31236b827e78f2a7fc4ba40
8,549
import json def get_full_json(msa, component, sessionkey, pretty=False, human=False): """ Form text in JSON with storage component data. :param msa: MSA DNS name and IP address. :type msa: tuple :param sessionkey: Session key. :type sessionkey: str :param pretty: Print in pretty format ...
2b02bd3c30ee9986cc25ca2b4fa822dc483e52c6
8,550
def get_restricted_area(path1, path2, restricted_pos1, restricted_pos2, time_step): """Computes the restricted area and the start- and end-time steps for both agents. * start time-step: The first time step where an agent occupies a position within the restricted area. * end time-step...
39104a44e8d5354799e45feb1ba6371f3423fecc
8,551
import argparse from typing import List import os def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int: """ Boolean logic of config subparser triggering. """ args = config_subparser.parse_args(argv[1:]) if args.show_settings: print(settings_msg) return 0 ...
591cce029374a5063d101927fae7641e0ce6c422
8,552
def FR_highpass(freq: np.ndarray, hp_freq: float, trans_width: float) -> np.ndarray: """Frequency responce for highpass filter Parameters ---------- ``freq``: np.ndarray frequency array ``hp_freq``: float highpass frequency ``trans_width``: float widt...
a57058a3fdf257ee68efe0c99d668e4f5b4fbf60
8,553
def _rexec(params): """Start a subprocess shell to execute the specified command and return its output. params - a one element list ["/bin/cat /etc/hosts"] """ # check that params is a list if not isinstance(params, list) or len(params) == 0: return "Parameter must be a not empty list" command = p...
e8338dc94b177f5d39d5307a88da7aa040a3a7e1
8,554
def _get_compose_template(manifest): """ Build the service entry for each one of the functions in the given context. Each docker-compose entry will depend on the same image and it's just a static definition that gets built from a template. The template is in the artifacts folder. """ artifac...
659e28f97c76a386a20c85fadaa3d0bbd6d88a90
8,555
def _ParsePackageNode(package_node): """Parses a <package> node from the dexdump xml output. Returns: A dict in the format: { 'classes': { <class_1>: { 'methods': [<method_1>, <method_2>] }, <class_2>: { 'methods': [<method_1>, <method_2>] ...
89eefebb82848acad23a9703b87177f626fbbdf5
8,556
def greet(lang): """This function is for printing a greeting in some selected languages: Spanish, Swedish, and German""" if lang == 'es': return 'Hola' elif lang == 'ge': return 'Hallo' elif lang == 'sv': return 'Halla' else: return 'Hello'
dcbe0fb39e735666b36780ee8d06b457e0a9541e
8,557
def add_hook( show_original=False, show_transformed=False, predictable_names=False, verbose_finder=False, ): """Creates and adds the import hook in sys.meta_path""" callback_params = { "show_original": show_original, "show_transformed": show_transformed, "predictable_name...
efda58094ab2bb218dca8babcdbf0a74b97e0cd8
8,558
def correlate_two_dicts(xdict, ydict, subset_keys=None): """Find values with the same key in both dictionary and return two arrays of corresponding values""" x, y, _ = correlate_two_dicts_verbose(xdict, ydict, subset_keys) return x, y
93287a57c7bf4e8cb03384531ffbca9c6d6e7cfc
8,559
def find_gateways(unicast_gateway, session, apic) -> tuple: """Search for ACI Gateways and get configurations""" get_gateway = get_subnets(session, apic) aps = [] epgs = [] l3Outs = [] gateways = [] location, bridge_domain, uni_route, scope, unkwn_uni, tenant, bd_vrf, iplearn = None, "Doe...
7c2f841e9fd3822c03f8b4ea38581bcaba1b60d2
8,560
import torch def hamming_dist(y_true, y_pred): """ Calculate the Hamming distance between a given predicted label and the true label. Assumes inputs are torch Variables! Args: y_true (autograd.Variable): The true label y_pred (autograd.Variable): The predicted label Returns: ...
0edda102820626b824861ac0f05d4d77f5def432
8,561
def task_mo(): """Create bynary wheel distribution""" return { "actions": [ """pybabel compile -D todo -i frontend/po/eng/LC_MESSAGES/todo.po -o frontend/po/eng/LC_MESSAGES/todo.mo""" ], "file_dep": ["frontend/po/eng/LC_MESSAGES/todo.po"], "targets": ["frontend/po/eng...
e6403c08973b9c4bdb20de954236fc2df8a4d2f5
8,562
from typing import Tuple def tuple_action_to_int( action: Tuple[int, int], slot_based: bool, end_trial_action: bool ) -> int: """Converts tuple action to integer.""" stone, potion = action num_special_actions = 2 if end_trial_action else 1 if stone < 0: return stone + num_special_actions if slot_bas...
d1f616706910822670b0d14d6a19f3f9dbddf145
8,563
from datetime import datetime def PDM(signal=50, angle=0, n_points=1000, motion_slow=0, motion_size=75, box_size=8, point_size=0.05, point_speed=1, ITI=1000): """ Pattern Detection in Motion """ angle_rad = np.radians(angle) y_movement = np.sin(np.radians(angle))*point_speed x_movement = np.c...
ea94312477326c7d08a44eeeeba3a39a7adc147b
8,564
def warpImage(imIn, pointsIn, pointsOut, delaunayTri): """ 变换图像 参数: =========== imIn:输出图像 pointsIn:输入点 pointsOut:输出点: delaunayTri:三角形 返回值: ============ imgOut:变形之后的图像 """ pass h, w, ch = imIn.shape imOut = np.zeros(imIn.shape, dtype=imIn.dtype) for j in ...
f672cf4e6cad968c6f42747f128b436e9b00c466
8,565
import re def rmchars(value): """Remove special characters from alphanumeric values except for period (.) and negative (-) characters. :param value: Alphanumeric value :type value: string :returns: Alphanumeric value stripped of any special characters :rtype: string >>> import utils ...
63428103f7da4184c6d9f33a9d05b02ce17f2448
8,566
def ema(x): """ [Definition] 以period为周期的指数加权移动平均线 [Category] 技术指标 """ return 'ema(%s,%s)' %(x, pe.gen_param('ema', 'period'))
d5490340520f57c9083ae82d6fd1cadd2fc92208
8,567
from typing import Set def tokenized(phrase: str) -> Set[str]: """Split a phrase into tokens and remove stopwords.""" return set(normalize(phrase).split()) - STOPWORDS
3a01f5ea316de0f5b27506d1ff7f2358273616a2
8,568
def synthesize(pipeline_in, net, dev, res_alloc, output_dir, prefix="", override_ibits=0): """ Create an FPGA accelerator given a QNN and compute resource allocator. Returns an ExternalExecutionLayer wrapping the compiled simulation executable. pipeline_in : list of input layers res_alloc : function...
6ff887a9d5698ec82c3f15b26c5742bc2f36e56d
8,569
async def server_error(request, exc): """ Return an HTTP 500 page. """ template = '500.html' context = {'request': request} return templates.TemplateResponse(template, context, status_code=500)
a11be57885b0f0f9107b190bafdebc6f13908f84
8,570
def return_post(): """" Returns the post-processing plugins. :param: None :return: POST_PROCESSING_PLUGINS """ return POST_PROCESSING_PLUGINS
9c7469f8ec336217abdfdb46db8a0c511789a4bf
8,571
import typing import os def redis_uri() -> typing.Optional[str]: """Connection URI for Redis server.""" value = os.environ.get("REDIS_URI") if not value: log.warning('Optional environment variable "REDIS_URI" is missing') return value
2b66db79232ce9f203bb4963b284af2b8878be6a
8,572
import base64 def numpy_to_b64str(img): """ Converts a numpy array into a base 64 string Args: img (np.array): Returns: str: base 64 representation of the numpy array/image. """ img = img[..., ::-1] # flip for cv conversion _, img = cv2.imencode('.jpg', img) # strips he...
a6af378a26dd3adac08568f49a5d8d74954feddc
8,573
def lennard_jones(r, epsilon, sigma, index=(12, 6)): """ General pair potential resembling a Lennard Jones model. Default indexes values are for a typical LJ potential, also called 12-6 potential. Parameters ---------- r : float or np.ndarray Distance between interacting particles. It c...
c16856d1960f1b2542305e4048d8e9fe5e866210
8,574
def get_unique_name(x, mult=0, extra=''): """ Returns a unique key composed of inchikey and multiplicity >>> mol = get_mol('[O][O]') >>> get_unique_name(mol) 'MYMOFIZGZYHOMD-UHFFFAOYSA-N3' """ mol = get_mol(x, make3D=True) if mult == 0: mult = mol.spin return mol.write("inchi...
a9a58078fb2af1c0542dcf77f522154dd2c3a374
8,575
def get_individual_user(user_id: int) -> JSONResponse: """ Lists all information belonging to one user. :param user_id: the id of the user :return: status code and response data """ user = _get_db()["users"].find_one({"user_id": user_id}) return JSONResponse(status_code=status.HTTP_200_OK, c...
dfa8d5cdfa8dd8363c550c79d18924a0b5a5764b
8,576
from typing import Union from typing import List from typing import Optional from typing import Tuple def portfolio_averages( df: pd.DataFrame, groupvar: str, avgvars: Union[str, List[str]], ngroups: int = 10, byvars: Optional[Union[str, List[str]]] = None, cutdf: pd.DataFrame = None, wtva...
23c902aafd341a7bbd8e6fc8b005e3cdb5a10f82
8,577
import logging def TestQuery(): """Runs a test query against the measurement-lab BigQuery database. Returns: (string) The query results formatted as an HTML page. """ # Certify BigQuery access credentials. credentials = AppAssertionCredentials( scope='https://www.googleapis.co...
fa278ab9a92990aa9f97d0db8bddaf89c5ee974a
8,578
def get_zero_crossing_rate(y, get_mean=True): """ Compute the Zero Crossing Rate (ZCR) :param y: np.ndarray [shape=(n,)] Sampling rate of y :param get_mean: bool Whether to instead return the mean of ZCR over all frames :return: np.ndarray [shape=(1,t)] or float ZCR for each frame, or th...
782cd302acc69065d26837e45fb882714fa6b927
8,579
import argparse def parse_arguments(): """ Parse the command line arguments of the program. """ parser = argparse.ArgumentParser(description='Train or test the CRNN model.') parser.add_argument( "--train", action="store_true", help="Define if we train the model" )...
17988797aacdb4608860b640e89191d71a2c98b0
8,580
import math def UF9(x): """ adapted from https://github.com/Project-Platypus/Platypus/blob/master/platypus/problems.py """ nvars = len(x) count1 = 0 count2 = 0 count3 = 0 sum1 = 0.0 sum2 = 0.0 sum3 = 0.0 E = 0.1 for j in range(3, nvars+1): yj = x[j-1]...
577b36653517e09cef764528920773ea51c5ed60
8,581
import shlex import os import subprocess import traceback import sys def run_command(cmd_str, stdin=None, stdout_devnull=False): """ run command """ cmd = shlex.split(cmd_str) try: if stdout_devnull: # for pg_ctl command with open(os.devnull, 'w') as devnull: r...
0f59d8020012b69d70183592e6f7a585220e0c0b
8,582
def antiderivate(values, ax_val, index, Nper, is_aper, is_phys, is_freqs): """Returns the anti-derivate of values along given axis values is assumed to be periodic and axis is assumed to be a linspace Parameters ---------- values: ndarray array to derivate ax_val: ndarray axis v...
9280187e907e16f1b2b00a1e86acd43538adcbe4
8,583
def renumber_labels(label_img): """ Re-number nuclei in a labeled image so the nuclei numbers are unique and consecutive. """ new_label = 0 for old_label in np.unique(label_img): if not old_label == new_label: label_img[label_img == old_label] = new_label new_label += 1 ...
4a37f151ba5a4e3066ce3656903b587f38deafea
8,584
from typing import List from typing import Optional from typing import Any from pathlib import Path import os async def densenet_xgboost_action_localization( files: List[UploadFile] = File(...), weights_densenet: Optional[str] = "denseXgB_model_mylayer", weights_xgboost: Optional[str] = "recognition_xgboo...
fafa9cbfa8cde1a6b5b2723c59897dd76b162971
8,585
import logging def callback(): """ Extract the OAuth code from the callback and exchange it for an access token. """ smart_client = _get_smart() try: smart_client.handle_callback(request.url) except Exception as e: return """<h1>Authorization Error</h1><p>{}</p><p><a href="/logout">Start over</a></p>""".for...
3b54c66c726101c8b10ad85c4c5e211bb8a0ffc3
8,586
def __virtual__(): """ Return virtual name of the module. :return: The virtual name of the module. """ return __virtualname__
3f1a19fab2561ae1fb464d76a13e7a0b75af5c93
8,587
def getsamplev3(qcode): """Get a sample object of a given identifier in API V3 style Returns: A sample (v3) object """ scrit = SampleSearchCriteria() scrit.withCode().thatEquals(qcode) fetch_opt = SampleFetchOptions() fetch_opt.withProperties() fetch_opt.withSpace() result = a...
513de42ffd13f6b9abe74753e568e8db2fa473e3
8,588
def k892_distribution(mass): """Calculate normalized relativistic Breit-Wigner distribution value for K(892) at given mass""" if k892_distribution.norm is None: k892_distribution.norm = _norm(_k892_distribution_unnormalized) return _k892_distribution_unnormalized(mass) / k892_distribution.norm
38175808a7f9acf178604bf64935f0beeb3f7631
8,589
def ProcessMoleculesUsingSingleProcess(Mols, PAINSPatternMols, Writer, WriterFiltered): """Process and filter molecules using a single process.""" NegateMatch = OptionsInfo["NegateMatch"] OutfileFilteredMode = OptionsInfo["OutfileFilteredMode"] Compute2DCoords = OptionsInfo["OutfileParams"]["Comput...
fe81953ce311724005c27ea309aa238578c4fd1c
8,590
def UDiv(a: BitVec, b: BitVec) -> BitVec: """Create an unsigned division expression. :param a: :param b: :return: """ return _arithmetic_helper(a, b, z3.UDiv)
fb3e300a96afdbf17fa7e6fff02379790b2dfd02
8,591
def _pressure_level_widths(tro3_cube, ps_cube, top_limit=0.0): """Create a cube with pressure level widths. This is done by taking a 2D surface pressure field as lower bound. Parameters ---------- tro3_cube : iris.cube.Cube `Cube` containing `mole_fraction_of_ozone_in_air`. ...
53dd14f6e0b1fda249ecd10d0ad30cfb4e076d5a
8,592
def load_model_configurations(sender): """ Iterates through setting MODELS_CRUD_EVENT searching for the sender model configurations. :param sender: Django Model :return dict """ for model_config in settings.MODELS_CRUD_EVENT: model = model_config['model'] app, model = model.r...
e32d441de47f9bb1a78f93854e1c0436819c148b
8,593
from typing import Optional def get_user_by_private_or_public_nickname(nickname: str) -> Optional[User]: """ Gets the user by his (public) nickname, based on the option, whether his nickname is public or not :param nickname: Nickname of the user :return: Current user or None """ user: User = ...
1dc43337c8e1372a32ed471ef8285544107cd22b
8,594
def expose(window, context, name, monitor): """REST HTTP/HTTPS API to view tuples from a window on a stream. Embeds a Jetty web server to provide HTTP REST access to the collection of tuples in `window` at the time of the last eviction for tumbling windows, or last trigger for sliding windows. Example wit...
ca3cf81c91ee89210da6989fdecce727d44273a1
8,595
import re def get_order_args(): """ Get order arguments, return a dictionary { <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) } Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc' """ orders = {} for arg in request.args: re_match = re.findall...
a5e57f95479e15c8167434ff34c51cc80fc43f45
8,596
def version_info(): # pragma: no cover """ Get version of nameko_kafka package as tuple """ return tuple(map(int, __version__.split('.')))
8fe39c50a43e40a589abb51f56e2c7c503026712
8,597
def StrokePathCommandAddCapType(builder, capType): """This method is deprecated. Please switch to AddCapType.""" return AddCapType(builder, capType)
4e7f852cde4993994ab5f7cf3e1b57700eaff7d3
8,598
def process_images(dummy_request): """Downloads and processes all images uploaded before resize logic fix deployment""" global n_global_resized media_bucket = storage_client.bucket(MEDIA_BUCKET) process_global_images(db_pool, media_bucket) process_user_images(db_pool, media_bucket) retur...
ea3734ce797305f7305880b02d2696c3ca8a21c7
8,599