content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02): """ matrix factorization Reference: 代码参考 http://www.quuxlabs.com/wp-content/uploads/2010/09/mf.py_.txt 公式推导 https://hpu-yz.github.io/2019/07/23/%E6%8E%A8%E8%8D%90%E7%B3%BB%E7%BB%9F%E4%B9%8B%E7%9F%A9%E9%98%B5%E5%88%...
99622826e8b9d5f7e49cabd72a46ed396ed29f74
55,800
def intersection_recursive(a, b): """ Intersects a with b, only the matching portions are returned. That is to say they have the same terminal node also. Everything else is excluded/set to None. """ if a is None or b is None: return None if a == b: return a c_key = (id(...
a48c6b3e7a54a1907f13fc115c549e210843427d
55,801
def upload_from_dict(upload_dictionary: dict): """ The function converts a dictionary of Upload to a Upload object. :param upload_dict: A dictionary that contains the keys of a Upload. :type upload_dict: dict :rtype: ibmpairs.query.Upload :raises Exception...
519a241224f841d80a6722d4fdadc2e98fb67953
55,802
def get_user_github_account(user): """Get the user's Github social_auth model. Args: user (User): The user. Returns: SocialAuth: The user's SocialAuth 'github' object. Raises: GithubNotLinkedError: Raised if the user's account is not linked. """ try: return use...
b6c735794e5782458d09c3e8495d48514dd37cf5
55,803
def table_exists(db_conn, table_name): """ Checks if a table matching table_name exist in the database """ cur = db_conn.cursor() tn = (table_name,) cur.execute("select name from sqlite_master where type='table' and name=?", tn) result = cur.fetchone() if(result): return True ...
ffe60c445a03530910084d01a7a488e7229bda0b
55,804
def contagion_frequency(df_or_af_lst, cascade_threshold): """ For a given list of defaulted fractions from various simulation runs calculates the contagion frequency among the runs, where a global cascade is defined accoring to cadcade_threshold. """ return fraction(df_or_af_lst, lambda df: df >...
1cf7e4bd7a632429fe82278e1bb24bacf836cb85
55,805
import re def keywords_to_regex(keywords): """ Take keywords, return compiled regex. """ regex_parts = [] # Construct regex for keyword filter for keyword in keywords.split(','): # Strip leading or trailing spaces from keyword keyword = keyword.strip() keyword = keyword.repla...
2013ad4c0fc4579e2fb93d77f019ae347dbae07d
55,806
def normalize_none_str(string_or_none): """Returns '' IFF given value is None, passthrough otherwise. This function normalizes None to the empty string to facilitate string concatenation when a variable could be None. """ # TODO(prashanthr_) : Try to reuse this utility. Violates DRY return '' ...
ed96726b95e87ab61873363ba658b216c5a85dc5
55,807
def dmp_inner_gcd(f, g, u, K): """Computes polynomial GCD and cofactors of `f` and `g` in `K[X]`. """ if not u: return dup_inner_gcd(f, g, K) J, (f, g) = dmp_multi_deflate((f, g), u, K) h, cff, cfg = _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J...
92f52c665953d45877e1cc462a622fc534da5078
55,808
def parse_float(s, default=None, minimum=None): """ Parse a string as a float. If the argument is "falsey", `default` is returned. On error, an InvalidArg is raised. Arguments: s : String to parse. default : Default value, when a "falsey" argument is given. ...
ee97662b4fd3e9efa260af77967918829b1d78cd
55,809
def calulate_loss_of_life(List_V, t): """ For list of V values, calculate loss of life in hours t = Time Interval (min) """ L = 0 for V in List_V: L += (V * t) # Sum loss of life in minutes for each interval LoL = L / 60 # Calculate loss of life in hours return LoL
ee2499af737cca764aad0a2f13794a925a172b9e
55,810
def solve_l1_l2(A, b, x0, z0, w, nonneg, rho, gamma, tolerance, max_iters): """ Solves the problem :math:`\min \| x \|_1 + \\frac{1}{2 \\rho} \| A x - b \|_2^2` using ADMM This function implements eq 2.25 of the paper. """ times = A.times trans = A.trans mu = jnp.mean(jnp.abs(b)) mu_or...
f66145b1949fba7978e93ab9b3bf9c1061b1f03b
55,811
def mjds2lst(mjds, position=None): """ As mjd2lst(), but takes an argument in seconds rather than days. Args: mjds (float):Modified Julian Date (in seconds) position (casacore measure): Position for LST calcs """ return mjd2lst(mjds/SECONDS_IN_DAY, position)
e086be6f16dc2cb9dcc4ac1e2ad84669e2f5e291
55,812
import logging from datetime import datetime def get_job_info_from_readme(readme): """ Get job info from job's README file Job README files typically reside inside the job_dir. Parameters ---------- readme : str Path of the job README file Returns ------- dict Di...
caf3c637fb3dadcd464c718ccd687570f2614422
55,813
import json def select_orientation_source(data_path, max_ori_error=20.0, grv_only=True, use_ekf=True): """ Select orientation from one of gyro integration, game rotation vector or EKF orientation. Args: data_path: path to the compiled data. It should contain "data.hdf5" and "info.json". m...
dae7b2f733db18f0363c90a31dab23b7a748806e
55,814
def read_ctm(ctm_file, segments): """Read CTM from ctm_file into a dictionary of values indexed by the recording. It is assumed to be sorted by the recording-id and utterance-id. Returns a dictionary {recording : ctm_lines} where ctm_lines is a list of lines of CTM corresponding to the ...
db7e7284a79fb3794d76125dde49935b2106c491
55,815
def furthest_neighbor(tsp, untraveled_cities, current_city): """Given a set of city keys, find the key corresponding to the closest city""" distance_to_current_city = lambda city: calc_distance(tsp, current_city, city) return max(untraveled_cities, key=distance_to_current_city)
03081be989d88676bf29df5cfaf8045f29cf66aa
55,816
async def _test_sources(hass, config0): """Test that sources (i.e., apps) are handled correctly for Android TV and Fire TV devices.""" config = config0.copy() config[DOMAIN][CONF_APPS] = {"com.app.test1": "TEST 1"} patch_key, entity_id = _setup(config) with patchers.PATCH_ADB_DEVICE_TCP, patchers.p...
a131039d22472a9541305a7014c1850ecd63986c
55,817
def beta(x, _alpha, _beta, decimals=6): """ Returns probability density function for beta distribution .. math:: \\text{PDF} = \\frac{x^{\\alpha - 1}(1 - x)^{\\beta - 1}}{\\text{B}(\\alpha, \\beta)} .. math:: \\text{where } \\text{B}(\\alpha, \\beta) = \\frac{\\Gamma(\\alpha)\...
398f883ef3e6810aaeef39627e6c448b4efcf7f7
55,818
def to_hex(value, bit_count): """Converts an integer to a hexadecimal values with bit_count bits.""" return hex((value + (1 << bit_count)) % (1 << bit_count))
e7eaf89f7b5b43e6814a3d7faa5b2ef26320ac7d
55,819
def visualCoverage(patch, altMap, aziMap, pixelSize=2., closeIter=None, isPlot=False): """ get the visual response coverage of a cortical patch :param patch: :param altMap: :param aziMap: :param pixelSize: pixel size in visual space, deg :param closeIter: closer iteration for generating vis...
1609006e0db981aea05291100ed47ee8eee76eb8
55,820
def wait_for_confirmation(client, txid): """ Utility function to wait until the transaction is confirmed before proceeding. """ last_round = client.status().get('last-round') txinfo = client.pending_transaction_info(txid) while not (txinfo.get('confirmed-round') an...
8c3f4dbd8ba8a0881eacb328ce773bfd1deb2315
55,821
def disable_cache(f): """Dada una función que maneja una request HTTP, modifica los valores de los headers para deshabilitar el cacheo de respuestas. Args: f (function): Función utilizada para manejar un endpoint HTTP de flask. Returns: function: Endpoint con decorador aplicado. "...
2d6e0270a4b5165969cba1571c4c0144bac6b29d
55,822
def asymptote_n(force_zero=None, **kwargs): """Returns a fit function of the form y(x) = - a0 / x^(a1), where a0 and a1 are the fit parameters """ # noinspection PyUnusedLocal def anf(x, params, const_list, const_dict): a, n = params[0:2] return - a / x ** n return FitFun...
346883d6afcebe44040bc03dc78d6872bf0b1b85
55,823
def create_example(fp, commands, data_dir, trainable=True): """ :param fp: file path :param commands: list of labels :param data_dir: directory of audio files :param trainable: bool parameter for creating train set or test set and val set :return:mfcc, label """ file_path = fp if tr...
444bd87d3a0b0ce1b37a6bcba3825863787e01b4
55,824
def test_users(db_session): """Creates test users.""" return auth.test_users()
6a4df0289c7c75884b8de5f6854829f18009c1fc
55,825
def SplitPath(projects, path): """Common method to split SVN path into branch and filename sections. Since we have multiple projects, we announce project name as a branch so that schedulers can be configured to kick off builds based on project names. Args: projects: array containing modules we are inter...
660d24107f643ed4103c2923451a6b08804afb1d
55,826
from typing import Dict from typing import Any def test_nested_dataframe() -> None: """Test the output for a dataframe with nested values""" nested_data: Dict[str, Any] = { "data": [ { "time": "2020-05-01T22:00:00.000000000Z", "constituents": [ ...
6f1ca1d9c5fddaf0a6b4930d46ef11bc0df2ae97
55,827
def _make_fabber_progress_cb(worker_id, queue): """ Closure which can be used as a progress callback for the C API. Puts the number of voxels processed onto the queue """ def _progress_cb(voxel, nvoxels): percent = int(100*float(voxel)/nvoxels) if percent != _progress_cb.last_perce...
cf28b5aec687c566e1a8c88fb64549efc0a70c35
55,828
def trotz(theta, unit="rad", xyz=[0, 0, 0]): """ TROTZ Rotation about Z axis :param theta: rotation in radians or degrees :param unit: "rad" or "deg" to indicate unit being used :param xyz: the xyz translation, if blank defaults to [0,0,0] :return: homogeneous transform matrix trotz(THETA)...
b71adc6a5ab36e96a230bd6c07290bc8cd4b4aeb
55,829
def get_data_for_model(data_path, patient_list, window_len=60, divide_by_win=True, scaler=False): """ Returns: X, y - for all patient in list, ndarray of shape (n_records, n_features, n_channels=3) """ X_all_data = [] y_all_data = [] for patient in patient_list: X, y = get_...
70e20e28ed19a0a19dd82a9c84d4832c7be8ac13
55,830
def is_time(hms_in_24h:str): """ Check now is specify time """ return strftime('%H:%M:%S') == hms_in_24h
de062133bf5f03bc5edb7f35f1465eda23674bd2
55,831
import os def transmissionPredictedTESS( showSolarSystem=True, wideFormat=False, \ surveyModule='ACWG', showGrid=True, \ showStellarTrack=True, showNeptuneRadius=True, \ showJupiterRadius=True, crossHair=None, \ ...
78fbbeadb5bca60059983f3425ae9d2f97605ad4
55,832
def assert_keys_in_dict(allowable_keys, d): """ Checks that all keys in d are in allowable keys Args: allowable_keys: Set or List of allowable keys d: Dict Returns: Boolean if satisfied, None if correct/key that is not in allowable keys """ for k in d: if k not in allowa...
017fc447d22b755d8b8447f51f636e666ed72309
55,833
def get_credit_center(img): """ :returns: [0][1] [3][2] """ aspect = Fraction(*img.size) vw, vh = util.get_vwvh(img) if aspect == Fraction(16, 9): return (np.array((1095 / 12.8 * vw, 88 / 7.2 * vh)), np.array((1268 / 12.8 * vw, 87 / 7.2 * vh)), np.array((126...
d20191573f5ceca5eead06e123a4ebe46126c0d5
55,834
import six def iterate_dict(dictionary, parents=[]): """ This function iterates over one dict and returns a list of tuples: (list_of_keys, value) Usefull for looping through a multidimensional dictionary. """ ret = [] for key, value in six.iteritems(dictionary): if isinstance(value, d...
1e4b5443857d798b46c69077b0913c5974f1be93
55,835
from operator import index def divvy_blocks(bj, T, b): """ This computes the active blocks for each loop of randUTV. """ B1 = index[:bj] I2end = jnp.min([bj+b, T.shape[0]]) J2end = jnp.min([bj+b, T.shape[1]]) I2 = index[bj:I2end] J2 = index[bj:J2end] B3 = index[bj+b:] B2B3 = in...
1eacbd33c369ac503a2f0681778d7066d38363ca
55,836
def transform_images(images): """Transform images dumbly to make sure transforms work.""" assert images.shape == (N_TOP_IMAGES_PER_UNIT, *IMAGE_SHAPE) return images
e9355af3752bc3c10228aee67d1ff5efb14215f4
55,837
def load_cp(instream, where=None): """Load fonts from CP file.""" data = instream.read() fonts, _ = _parse_cp(data, 0, standalone=True) return fonts
9c16465a289694901a36c937aa8a357be0195cb0
55,838
import os def settings(setting_key=None, default_value=''): """ Get the instance by a key in application settings (config.yaml file) example: print(setttings('mysql.database')) """ config = Config().settings if not setting_key: return config env_var = str.replace(setting_key, "....
fd62bfe23a07370827ca5dd121cf416a1dd2b628
55,839
def validate_timeout(timeout: int): """ Validate request timeout. :param int timeout: number seconds of request timeout. :return int: timeout seconds number. """ if type(timeout) is not int or timeout < 0: msg = 'Timeout must be zero or positive integer number.' logger.error(f'[...
a0a7931ffaa2594b0407c0f2c0c8d598609131d9
55,840
import os def serve_file(full_uri): """ Provide ability to view or download files stored on the local filesystem """ if settings.REMOTE_REGISTRY: return HttpResponse(status=status.HTTP_503_SERVICE_UNAVAILABLE) full_uri = full_uri.replace('file://', '') if os.path.isfile(full_uri): ...
7f13b5ecb4a381fc4ed1e671dc37d7c96f07f3af
55,841
def _diff_visits(vis_1, vis_2): """Returns a numerical difference between two visits """ # First, we convert visits v = map(lambda x: 0 if(x in ['bl', 'sc', 'uns1', 'scmri', 'nv', 'f']) else int(x[1:]), [vis_1, vis_2]) # Then, we substract return np.absolute(v[0] - v[1])
a216271288939eae52429798d4743dc73764d215
55,842
def load_model_from_params_file(model): """ case 1: CHECKPOINT.RESUME = False and TRAIN.PARAMS_FILE is not none: load params_file case 2: CHECKPOINT.RESUME = True and TRAIN.PARAMS_FILE is not none: case 2a: if checkpoint exist: use checkpoint case 2b: if checkpoint not exist: use pa...
805f659b15f0c2d7f226151d0725c633bab74d50
55,843
def grey_opening(input, size = None, footprint = None, structure = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Multi-dimensional grey valued opening. Either a size or a footprint, or the structure must be provided. An output array can optionally be provided. The orig...
89249825b08cca1026fa85b668a51d5985dfc755
55,844
def Expand3D(x): """ Encodes the 93 bit morton code for a 31 bit number in the 3D space using a divide and conquer approach for separating the bits. Args: x (int): the requested 3D dimension Returns: int: 93 bit morton code in 3D Raises: Exception...
b4e14431c0a77122b4d0cb7ae9da11c96a51df0d
55,845
def experiment_tuple_to_key(experiment): """One of the experiment descriptors is unit'd -- strip unit.""" (scheme, dt, marginal, testsystem) = experiment return (scheme, dt / unit.femtosecond, marginal, testsystem)
cc5000baf3247f433b24e3efff99df2274641589
55,846
from datetime import datetime def atm_corr_image(imageInfo: dict) -> dict: """Retrieves atmospheric params from image. imageInfo is a dictionary created from an ee.Image object """ atmParams = {} # Python uses seconds, EE uses milliseconds: scene_date = datetime.datetime.utcfromtimestamp(imag...
4fb9578e994978aa08971d0f10555dcdef894b85
55,847
def pacf(x, lag=40): """ Partial autocorrelation function. pacf results in: [1, acf_lag_1, pacf_lag_2, pacf_lag_3] :param x: (array) :param lag: (int) """ y = [] # Partial auto correlation needs intermediate terms. # Therefore we start at index 3 for i in range(3, lag +...
df4ed601f1a2a47836b21bb04c15085fcad6d1ba
55,848
from sys import path def get_forms(): """ 1. Get required arguments 2. Get forms 3. Get room name 4. Render the response """ # 1. Get required arguments args = Eg006Controller.get_args() try: # 2. Get forms forms = Eg006Controller.get_forms(args) # 3. Get r...
eb47ce957d3effa589a276b9edb1b37a00fa769d
55,849
def GenerateIndicesForDifferentProcs(nprocs, loopsize): """ Generates a list that contains the elements of the loops that each rank will process. In the case that the number of processors does not divide the loop size, We divide the rest of the work amongst the first (loopsize % nprocs) processors. """ ra...
468c04292f7c42c26e69fd7732478be936d8a008
55,850
def zca_whiten((eigvals, eigvecs), centered_X): """Return the PCA of X but rotated back into the original vector space. See also fft_whiten.py """ pca_of_X = pca_whiten((eigvals, eigvecs), centered_X) return np_dot(pca_of_X, eigvecs.T)
116181130ff6920dc519f37385fc557bfba7181f
55,851
def taiwan_makeup_rule(holidays): """ This function attempts to implement what seems to be the Taiwan holiday observance rule since 2013. Notes ----- If a holiday falls on a Tuesday or Thursday, and extra holiday is observed on Monday/Friday to create a four day weekend. If a holiday falls...
fd3b8c132b3271d6836cdf32a827cac6be24e92c
55,852
import google def test_disable_retry_failed_jobs(sleep, client, job_retry_on_query): """ Test retry of job failures, as opposed to API-invocation failures. """ err = dict(reason="rateLimitExceeded") responses = [dict(status=dict(state="DONE", errors=[err], errorResult=err))] * 3 def api_reque...
ecfce5192ae4a4d1299dc4bb506aa8c6563a2177
55,853
from pathlib import Path def read(fname: str) -> str: """Read file starts from root directory.""" with (Path(__file__).resolve().parent / fname).open() as f: return f.read()
340d814777f1f0ef6d5b97d430b3313db5e0a5ca
55,854
def create_preprocessing_fn(): """ create_preprocessing_fn """ def preprocessing_fn(inputs): """ preprocessing_fn """ stn = tft.string_to_int(inputs['stn']) year = tft.string_to_int(inputs['year']) mo = tft.string_to_int(inputs['mo']) da = tft.string_to_int(inputs['da']...
037081304ce999e7df833348145ecf97e8a2647c
55,855
def get_service_list(manager=None): """Return a list of services managed by a machine :manager: Docker machine to use for command, otherwise local :returns: list of services """ client = get_docker_client(manager) return [s.name for s in client.services.list()]
cd91f801b8b1b83d3533aa0409acc5b5c5268a6b
55,856
def _unique_names(item): """ Compute the unique key for the given (namespaceless) item within a single collection. """ return item.metadata.name
6da786ae1adae29a143b1e171a7206b25b8e9556
55,857
def compare_models(ns, manual_mode=True, ignore_dihedrals=False, calc_sasa=False, record_best_indep_params=False): """Compare 2 models -- atomistic and CG models with plotting. ns requires: all_best_emd_dist_geoms (edited inplace) all_best_params_dist_geoms (edited inplace) atom_only ...
b2c8839e5bfb3de8cd4c21233ba7aa979d75fb92
55,858
def main(): """ Основной цикл узла ROS. @return: код завершения программы """ # Инициализируем узел ROS rospy.init_node("rc_reg_plotter") # Подписываемся на топики rospy.Subscriber("/pwm_output", CarPwmContol, pmw_motor_clb) rospy.Subscriber("/mavros/imu/data", Imu, imu_clb) ro...
f944fb00af38b5bdb9f684cada68e25abcbf5d28
55,859
from typing import Literal def link_to_external_kb(g, to_link, external_kb_id, system, confidence): """ Link an entity to something in an external KB. :param rdflib.graph.Graph g: The underlying RDF model :param rdflib.term.URIRef to_link: The entity to which to link :param str external_kb_id: A ...
7319ae1d8858bacfd108c6ba92b6bf1bc87bfda3
55,860
import yaml def parse_yaml(stream): """Parse a yaml stream into an nbt structure readable by nbt2yaml.""" return _yaml_deserialize(yaml.load(stream, Loader=yaml.FullLoader))
6e5af5f69994a0fc81982778f4975a153630ac95
55,861
async def redirect_index() -> RedirectResponse: """Redirect to login page. Returns: RedirectResponse: Redirects the root endpoint ``/`` url to login page. """ return RedirectResponse(url="/login", headers=RESET_HEADERS)
41d91fb2d9797fc528523fe932f2de1a68da24d8
55,862
def getAllPages(url, soup=None): """Gets all url's recusively""" ret = [url] soup = bs4.BeautifulSoup(getContent(url), parser) if not soup else soup nextPage = soup.find(getNextPage) if nextPage: print(SITE_ROOT + nextPage.a['href']) ret.extend(getAllPages(SITE_ROOT + nextPage.a['hre...
7f44238db8153e29dd5749112866ee7738cc3fb5
55,863
import io import six def _check_bytes(fd, mode): """ Checks whether a given file-like object is opened in binary mode. """ # On Python 3, doing fd.read(0) on an HTTPResponse object causes # it to not be able to read any further, so we do this different # kind of check, which, unfortunately, is...
1a627885f437fc1c9870b8c10ab5b9cb39b1580a
55,864
from .item_models import User def create_app(): """Creates instance of app with the default configurations.""" app = Flask(__name__) # Ensure templates are auto-reloaded app.config["TEMPLATES_AUTO_RELOAD"] = True # Configure session to use filesystem (instead of signed cookies) app.config["SES...
9e736c7e07201c6faa5f635d4156451f12220ba4
55,865
import os import re def ToPackage( env = None, package_drive_map = None, package = None, target = None, source = None, toemulator = True, dopycompile = ".pyc", pylibzip = None ): """Insert file into package. @param env: Environment. DefaultEnvironment() used i...
59566776cb4d45f95926661d1c2293e4d68370cd
55,866
def cross_corr(x, y, nlags, bad_flag): """ calculate cross correlations [lag, R_xy, P_xy] = cross_corr(x, y, nlags, bad_flag) input: x,y the data sets nlags are number of lags to process bad_flag is data value that indicates missing or bad data output: lag is lag f...
9bc483f46f18e602fc39055e597d7b75308013ac
55,867
from typing import Tuple def _get_val_model( arch: str, val_type: str, state_dim: str, fc_layers: Tuple, action_dim: int = None, activation: str = "relu", ): """ Returns Neural Network given specifications :param arch: Specifies type of architecture "mlp" for MLP layers ...
65b52d0d457e67dfb9772498852edb932f715f03
55,868
from typing import Dict from typing import List def get_info_by_id_command(collection_name: str): """ Decorator around actual commands, that returns command depends on `collection_name`. """ def get_info_by_id_for_collection(client: Client, args: Dict) -> List[CommandResults]: """ Thi...
85bb0fffe61e06844e507ca926a672fe70e4c8e8
55,869
def format_comment(req, comment): """ We collect source ids found in comment, retrieve the corresponding source objects from the database in a single query and then replace the ids with formatted source links. """ parts = [] sources = {} pos = 0 comment = comment.replace('~', ' ') fo...
3ca524da4e6ecd41678c839316765055922c676a
55,870
from typing import Dict import collections import torch def get_bn_accuracy_metrics(model: nn.Module, mean_dict: Dict, var_dict: Dict): """Determine how accurate the running_mean and running_var of the BatchNorms are. Note that, the test set should be shuffled during training, or these statistics won...
638140a53d1af274ba641bb849e357b3895aaaba
55,871
def find_ambiguous_entities(n_ambiguous, files, threshold=5, k_ann=2): """ Find ambiguous mentions of entities. :param n_ambiguous: int - how many ambiguous entities do you want? :param threshold: entity is counted ambiguous if there are at least two different annotations mentioned at lea...
2dc4156618f1b2cdee59b9a8b44e3474f303cd0a
55,872
import six def fix_axes3d_color(ax, col): """ Setting color to None must cycle through the available colors as per matplotlib's philosophy. In some recent versions this was still not implemented however. This function fixes the issue. The issue was fixed in April 2016, and the code below hacks ...
5aafcb8609188507bdd3601e8de51be4639f06a1
55,873
def calculate_gamma(grad, pgrad): """Return the 'gamma' factor in the conjugate gradient method according to Fletcher and Reeves.""" grad = np.hstack(grad) pgrad = np.hstack(pgrad) return (np.dot(grad,grad))/(np.dot(pgrad,pgrad))
e497ab1d62450a2621f64a38c7760ddf302e94c6
55,874
def create_drivers(env: simpy.Environment, num: int, map_grid: Grid) -> [Driver]: """ Creates n driver objects in the env Environment. The drivers will have randomly generated starting locations and each driver will be assigned to the nearest driver pool. :param env: simpy environment :para...
04a65a5adb9fd2a22287fbb1f2dde31c57d8ea47
55,875
def angle_derivs(xyz, iangles): """ Derivatives of the bond angles with respect to cartesian coordinates Parameters ---------- xyz : np.ndarray, shape=[n_atoms, 3] The cartesian coordinates of a single conformation. iangles : np.ndarray, shape=[n_angles, 3], dtype=int Each row i...
b051bfdb31e36765c5948a5d233ada03865846e5
55,876
def reshape_to_Nx3(data): """ change data's shape to (N, 3). Examples -------- >>> data = np.ones((3, 5, 3)) >>> data2 = reshape_to_Nx3(data) >>> data2.shape (15, 3) """ return np.reshape(data, (calc_tristimulus_array_length(data), 3))
dc025da3ce5a987d9579a965bc7a95ae4f0a0ebf
55,877
import logging async def build_get_txn_request(submitter_did: str, data: int) -> str: """ Builds a GET_TXN request. :param submitter_did: Id of Identity stored in secured Wallet. :param data: seq_no of transaction in ledger :return: Request result as json. """ ...
b90217927de1ae5f0173d9fc85cfcd61d03b4c9f
55,878
import math def _get_movements_8n(): """Get all possible 8-connectivity movements. - up - down - left - right - first diagonal (up-right) - second diagonal (up-left) - third diagonal (down-right) - fourth diagonal (down-left) :return: list of movements with cost [(dx, dy, movem...
27e9e286494ee69681d3d6a9423ec29a3d411792
55,879
def active_face_index(shape): """Array of face indices.""" return np.arange(active_face_count(shape))
e4b7cf37b592c08fc3ea695cfe029e0a5f01f32e
55,880
def publish_with_dtn(ni_name, destination, authority, hash_alg, ext_json, locs, scheme, full_put, file_name, rform, verbose): """ @brief Action a NetInf publish request using the HTTP convergence layer @param ni_name NIname object instance or None - ni URI to publish if ...
4cf6704b9b88a3173b85052a0e3ee7d17fa1cc7e
55,881
import re import argparse def reverse_dns(value: str) -> str: """Validate `--org` argument Parameters ---------- value : str Passed by the ArgumentParser object Returns ------- str Returns the value back to the ArgumentParser object Raises ------ argparse.Arg...
c143f36dec7bdba5e628200b9e3044bf3d45f9fb
55,882
def list_sum_by_group(l, group_index): """ Sums the elements of list keyed on `key_index`. The elements must be summable (i.e. e1 + e2 is allowed for all e1 and e2). All elements outside of key are summed on matching keys:: Returns: <list of summed and keyed elements> ...
6c40eb061c654deb0d0eef9b8989aa498032cac9
55,883
def get_domain_of_interface(name): """ Get domain containing network that is connected to given interface """ interface = get_interface(name) network = get_network(interface['network']) return get_domain(network['domain'])
b847da1ad737790a8e41ddb8aa364274d01d2b60
55,884
def readDataFile(data_file): """ Read an R-formatted data file and return a list of tuples containing x,y,z perturbtations. """ fmt_err = """ Data file does not have correct format! Data file should be R-formatted and have x_mean, y_mean, and z_mean columns! """ f = open(d...
0a7a271c7dc2ac9a5978be774b32f2dc3724d7cd
55,885
import json def get_info(info_type, fmt="JSON"): """ info_type - Commands|Menus|Preferences|Tracks|Clips|Envelopes|Labels|Boxes fmt - JSON(default)|LISP|Brief """ command = "GetInfo: Type=%s Format=%s" % (info_type, fmt) resp, status = do_command(command) if not status: raise Excep...
e44b264dcf3f8f69ba49bbad13bdb153fe6bf1fd
55,886
import os def exportCSV( filename, # type: String showHeaders, # type: bool dataset, # type: BasicDataset ): # type: (...) -> String """Exports the contents of a dataset as a CSV file, prompting the user to save the file to disk. Args: filename: A suggested filename to save as....
252cb97d4966593ba0d2041b66ad1ce0d435fa82
55,887
def zoom_cal2(f1,f2,L,Mhigh,Mlow): """ Two element finite conjugate zoom Try example zoom_cal2(40,60,400,-15,-2.5) ======================================================== input -------------------------------------------------------- f1: first element focal length f2: second element focal length Mhigh: high...
6d1a13439994481cd774d5a12f919090d6855307
55,888
def normalize_title(title: str, body: str) -> str: """Normalize the title if it spills over into the PR's body.""" if not (title.endswith("…") and body.startswith("…")): return title else: return title[:-1] + body[1:].partition("\n")[0].rstrip("\r")
ec3d560855abcd85afe35839a4af025a2b365b45
55,889
import os def read_pickle(path): """ Read an EntitySet from disk. Assumes EntitySet has been saved using :meth:`.to_pickle()`. Args: path (str): Path of directory where entityset is stored """ entityset_path = os.path.abspath(os.path.expanduser(path)) entityset = pd_read_pickle(os...
eba26306d1e571aae9f1b40756e7df09e385921d
55,890
def generate_grids_hyperbolic(p1, p2, N, scale=3.0): """Generate two mutually orthogonal circles from two points `p1`, `p2` on the ideal boundary. The first family (`para_grid`) consists of circles that are all tangent with the ideal boundary at `p`. The second family (`orth_grid`) consists of cir...
95539815efae135139a223ef2bed972a6bd0c40a
55,891
import math def set_up_molecules(mol, facet): """ Set up the molecules from the lithium Landscape for a facet. :return: """ # Define the line on which to place the Lithium center = facet.center normal = facet.normal / np.linalg.norm(facet.normal) endpoints = [center + LINE[0] * normal,...
c1a442b48a728d4fa3fbf1fda33b9f850635b02b
55,892
def simulate_user_experiments(ape_tabular, instance, nb_features_employed, farthest_distance, closest_counterfactual, growing_sphere, position_instances_in_sphere, nb_training_instance_in_sphere, only_anchors=False, only_lse=False): """ Function that generate a classic local surrog...
35181264ed665a8bf0920675ac355d6a16e84273
55,893
def createTexImage2dFromFile(imgFile, transpose=True): """Load an image from file directly into a texture. This is a convenience function to quickly get an image file loaded into a 2D texture. The image is converted to RGBA format. Texture parameters are set for linear interpolation. Parameters ...
666dad80eab12a9c3d0038c25e5ea2dbf1501937
55,894
def _linear_decay(value, origin, offset, scale, decay): """ https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html """ s = scale / (1 - decay) return max(0, (s - max(0, abs(value - origin) - offset)) / s)
9460624748cac35d97b5f3b51637fb41013958d2
55,895
def get_download_widget(): """Return Button widget.""" button = Button(label="Download selected data", button_type="success", width=40) return button
9fb4570fe2ab62a1ef3255257d03497094934346
55,896
import torch def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an i...
7d40782e8fd91c831cea227b6d817038c9023ab8
55,897
def activate_module(func) -> str: """Входная точка модуля""" active_func = settings["func"].get(func)["entry_point"] answer_module = None if active_func: answer_module = active_func() return answer_module
09347f52c1423c276c58b21160d049560eb7772e
55,898
from typing import Optional from typing import Tuple import datasets def get_task( name: str, mode: str = 'sqlite', cache_dir: Optional[str] = None ) -> Tuple[federated_data.FederatedData, federated_data.FederatedData, core_models.Model]: """Gets a standard task. Args: name: Name of th...
6ee1cb71c27a5d8c7a76054bcd138918b02fcced
55,899