content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional def build_cluster_endpoint( domain_key: DomainKey, custom_endpoint: Optional[CustomEndpoint] = None, engine_type: EngineType = EngineType.OpenSearch, preferred_port: Optional[int] = None, ) -> str: """ Builds the cluster endpoint from and optional custom_endpoint an...
82136d78ea6edf68fc5c8bf92653be033649bdfd
3,636,808
import requests import re def get_community_pools(): """Get community pool coins Returns: List[dict]: A list of dicts which consists of following keys: denom, amount """ url = f"{BLUZELLE_PRIVATE_TESTNET_URL}:{BLUZELLE_API_PORT}/cosmos/distribution/v1beta1/community_pool" res...
c4a78e0a953933f453f7684e66aff2b39572f593
3,636,809
def rgb2bgr(x): """ given an array representation of an RGB image, change the image into an BGR representtaion of the image """ return(bgr2rgb(x))
c9412018e6595513c29da54f8179ff2a7c953d07
3,636,810
from datetime import datetime def draw_des1_plot(date, plot_A, plot_B): """ This function is to draw the plot of DES 1. """ #make up some data for the plot df = pd.DataFrame({'date': np.array([datetime.datetime(2020, 1, i+1) for i in range(12)]), ...
811f4d844bafe3d35287b774f61c9337a3163d47
3,636,811
def kolmogorov_smirnov_rank_test(gene_set, gene_list, adj_corr, plot=False): """ Rank test used in GSEA method. It measures dispersion of genes from gene_set over a gene_list. Every gene from gene_list has its weight specified by adj_corr, where adj_corr are gene weights (correlation with fenotype)...
6c38a40d18465729e544694bd4c61547b98076ea
3,636,812
import re async def segment_url(request: schemas.UrlSegmentationRequest) -> schemas.SegmentationResponse: """ This endpoint accept the URL of an image, and returns a SegmentationResponse. The endpoint will try to download the image at the given URL. Note: not all servers allow for non-browser user...
9cdec9a06946629d35a0dc882e27a9a218075d32
3,636,813
def generate_answers(session, model, word2id, qn_uuid_data, context_token_data, qn_token_data): """ Given a model, and a set of (context, question) pairs, each with a unique ID, use the model to generate an answer for each pair, and return a dictionary mapping each unique ID to the generated answer. ...
253e2ef5a4d03d6eccf418aae23373cd17e0c143
3,636,814
import cmath def _add_agline_to_dict(geo, line, d={}, idx=0, mesh_size=1e-2, n_elements=0, bc=None): """Draw a new Air Gap line and add it to GMSH dictionary if it does not exist Parameters ---------- geo : Model GMSH Model objet line : Object Line Object d : Dictionary ...
07f14b04cfb9f72d8150cfd39332ba2979cd3ae4
3,636,815
def mat_toeplitz_2d(h, x): """ Constructs a Toeplitz matrix for 2D convolutions Parameters ---------- h: list[list] A matrix of scalar values representing the filter x: list[list] A matrix of scalar values representing the signal Returns ------- list[list] A...
10ca8c25eb421aa34c0caf67a63b621a93de6d32
3,636,817
import unicodedata def fix_text_segment( text, *, fix_entities='auto', remove_terminal_escapes=True, fix_encoding=True, fix_latin_ligatures=True, fix_character_width=True, uncurl_quotes=True, fix_line_breaks=True, fix_surrogates=True, remove_control_chars=True, remove_b...
645bbbfb2f1da94b941e51c50ef7fd682ac6e823
3,636,818
import random def SSValues(MPKa,Rfa,r): """ Steady-State Values (Numerical solutions Linear) Input: Annual MPK and Rf Rates, r (repetition index) Output: Annual MPK and Rf Rates (Input), mu, gamma, SS Capital, SS Wage, SS Investment, Value function """ #Compute Parameters MPK =...
31e693da8878d84f6b619f0052a140bbf5307695
3,636,819
def simplify_junctures(graph, epsilon=5): """Simplifies clumps by replacing them with a single juncture node. For each clump, any nodes within epsilon of the clump are deleted. Remaining nodes are connected back to the simplified junctures appropriately.""" graph = graph.copy() max_quadrance = epsil...
b88e63d0ac5242e93d1d061c3eeed773d9a7c6bc
3,636,820
def sample_truncated_norm(clip_low, clip_high, mean, std): """ Given a range (a,b), returns the truncated norm """ a, b = (clip_low - mean) / std, (clip_high - mean) / std return int(truncnorm.rvs(a, b, mean, std))
de722881ce95b83239af74ba081539dfedca3363
3,636,821
def f(x): """ Approximated funhction.""" return x.mm(w_target)+b_target[0]
8a76358acd7d56aeb18c104198e253fda582652f
3,636,822
import requests from bs4 import BeautifulSoup def get_urls(): """ get all sci-hub-torrent url """ source_url = 'http://gen.lib.rus.ec/scimag/repository_torrent/' urls_list = [] try: req = requests.get(source_url) soups = BeautifulSoup(req.text, 'lxml').find_all('a') for sou...
e14f15ebc7e39393bd614183e1eccb8fc1933359
3,636,823
def getVariablesForCookie(request=None): """ returns dict with variables for cookie """ cookie_path = '/' portalurl = absoluteURL(getSite(), request) cookie_name = "%s%s"%('__zojax_comment_author_', md5(portalurl).hexdigest()) return dict(name=cookie_name, path=cookie_path)
ba6578036d69ceef45be1b583d8b52b699519823
3,636,824
import torch def logsumexp(x, dim): """ sums up log-scale values """ offset, _ = torch.max(x, dim=dim) offset_broadcasted = offset.unsqueeze(dim) safe_log_sum_exp = torch.log(torch.exp(x-offset_broadcasted).sum(dim=dim)) return safe_log_sum_exp + offset
53a12a2c91c6a0cae3fcae46a860801f05480abe
3,636,825
import requests def make_request(session, verb, endpoint, data={}, timeoutInSeconds=REQUEST_TIMEOUT_IN_SECONDS, max_retries=MAX_RETRIES): """ Make a REST request """ try: if verb is RequestVerb.post: r = session.post(url=endpoint, json=data, timeout=timeou...
5a0637a130a5f2c1c834ddfb61cccaceeeb5c3c9
3,636,826
def certificate_managed( name, days_remaining=90, append_certs=None, managed_private_key=None, **kwargs ): """ Manage a Certificate name Path to the certificate days_remaining : 90 Recreate the certificate if the number of days remaining on it are less than this number. The...
0d98b58b26bb8266bbd7817b3b8533940b7b5f33
3,636,827
from typing import Iterable from typing import Dict from typing import List def _unique_field_to_col_matching( rules: Iterable[Rule], field_to_matching_cols: Dict[str, List[int]] ) -> Dict[str, int]: """ Given a potential field to column matching this functions tries to determine a unique 1-to-1 matc...
b0f8f63eb86701605bc67140b91e2e67f368082a
3,636,828
import yaml import textwrap def minimal_config(): """Return YAML parsing result for (somatic) configuration""" return yaml.round_trip_load( textwrap.dedent( r""" static_data_config: reference: path: /path/to/ref.fa dbsnp: path: /path/to/d...
806da8976dea510997b6fea8d264ac2e7d619e75
3,636,829
def walk(n=1000, mu=0, sigma=1, alpha=0.01, s0=NaN): """ Mean reverting random walk. Returns an array of n-1 steps in the following process:: s[i] = s[i-1] + alpha*(mu-s[i-1]) + e[i] with e ~ N(0,sigma). The parameters are:: *n* walk length *s0* starting value, defaults ...
c87e06b2fc046ece6acbffaf982b9258272f81a6
3,636,830
def GetCLIInfoMgr(): """ Get the vmomi type manager """ return _gCLIInfoMgr
4adf784890a6c72cacd951f675350dd40d68c0d5
3,636,831
from datetime import datetime def pretty_date(time=False): """ Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc """ now = datetime.now() if type(time) is int: diff = now - datetime.fromtimes...
28be383e0064640f3781c781db06eb3a914205dd
3,636,832
def per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in cext.per_cpu_times(): user, nice, system, idle = cpu_t item = scputimes(user, nice, system, idle) ret.append(item) return ret
b43152c58323fc0d74ec8297e419622485bd7505
3,636,833
def cooldown(rate, per, type=commands.BucketType.default): """See `commands.cooldown` docs""" def decorator(func): if isinstance(func, Command): func._buckets = CooldownMapping(Cooldown(rate, per, type)) else: func.__commands_cooldown__ = Cooldown(rate, per, type) ...
c15bc00a7b71c95086088f5d42c09de350c148d5
3,636,834
def construct_psi_k2(theta, y, X, kappa = 30): """ Kappa-based filter for time-varying autoregressive component, based on Platteau (2021) """ #get parameter vector T = len(y) omega = theta[0] alpha = theta[1] beta = theta[2] #Filter Volatility psi = np.zeros(T) #i...
e020f7f437dbba96aac15a51491496f701995693
3,636,835
def calHoahaoSancai(tian_ge, ren_ge, di_ge): """ 三才五行吉凶计算 :return: :param tian_ge: 天格 :param ren_ge: 人格 :param di_ge: 地格 :return: """ sancai = getSancaiWuxing(tian_ge) + getSancaiWuxing(ren_ge) + getSancaiWuxing(di_ge) if sancai in g_sancai_wuxing_dict: data = g_sancai...
ea75055c3b2c749af9b97b8271aea2242de3c85f
3,636,836
def load_coeff_swarm_mio_internal(path): """ Load internal model coefficients and other parameters from a Swarm MIO_SHA_2* product file. """ with open(path, encoding="ascii") as file_in: data = parse_swarm_mio_file(file_in) return SparseSHCoefficientsMIO( data["nm"], data["gh"], ...
cbc2eac4a293ecf432c2520aef741c7499a9be70
3,636,837
def plot_trajectory_from_data(X : np.array, y : np.array, sample_n = 0, excludeY=True, ylabel=None, xlabel=None): """ Plots trajectory from data sample_n: sample index """ fig, ax = plt.subplots() dim = X.shape[2] for d in range(dim): trajectory = list(X[sample_n,:,d...
7bff6c0da9342501e0b230e423ca5a2201757f40
3,636,839
async def get_prices(database, match_id): """Get market prices.""" query = """ select timestamp::interval(0), extract(epoch from timestamp)::integer as timestamp_secs, round((food + (food * .3)) * 100) as buy_food, round((wood + (wood * .3)) * 100) as buy_wood, round((stone + (st...
3571006c37319135a3202622b73e7e2379ca93ee
3,636,841
def isChinese(): """ Determine whether the current system language is Chinese 确定当前系统语言是否为 中文 """ return SYSTEM_LANGUAGE == 'zh_CN'
8de1502c153189bc66774569fc00b2408d4ed694
3,636,844
def load_db(db): """ Load database as a dataframe. Extracts the zip files if necessary. The database is indexed by the user, session. """ if DEV_GENUINE == db or DEV_IMPOSTOR == db: extract_dev_db() if GENUINE == db or UNKNOWN == db: extract_test_db() return pd.read_csv(db, ind...
9ebab9118d7572575fc3b82bbb02bdf1de68e6f5
3,636,845
def _pool_tags(hash, name): """Return a dict with "hidden" tags to add to the given cluster.""" return dict(__mrjob_pool_hash=hash, __mrjob_pool_name=name)
de9a9e7faa4d4f9dd3bfe05cb26790ff8ae66397
3,636,848
from pathlib import Path def clusters_dictionary(): """ Read the column 'label' from final_dataframe.tsv' and return the clusters as a dictionary. If the column 'label' is not in final_dataframe.tsv', call k_means_clustering and perform the clustering. :return: a dictionary, where the key is the c...
6d47865a98a4b2136fd2ec9baf346a880ee8acfb
3,636,850
def apply_wet_day_frequency_correction(ds, process): """ Parameters ---------- ds : xr.Dataset process : {"pre", "post"} Returns ------- xr.Dataset Notes ------- [1] A.J. Cannon, S.R. Sobie, & T.Q. Murdock, "Bias correction of GCM precipitation by quantile mapping: How wel...
e974a19d537888b866cf3117524815559c28108a
3,636,852
def get_nb_build_nodes_and_entities(city, print_out=False): """ Returns number of building nodes and building entities in city Parameters ---------- city : object City object of pycity_calc print_out : bool, optional Print out results (default: False) Returns ------- ...
ff3b36dcd2ca7cd0be316b573f20a6dd16bd1c1d
3,636,853
def generate_pairs(agoals, props): """Forms all the pairs that are applicable to the current goals""" all_pairs = [] for i in range(0, len(agoals)): for j in range(i, len(agoals)): goal1, goal2 = agoals[i], agoals[j] all_pairs.extend(list(form_pairs(goal1, goal2, props))) ...
d0c7881682f057207db22cf5fb612f1a42d10c6d
3,636,854
def construct_aircraft_data(args): """ create the set of aircraft data :param args: parser argument class :return: aircraft_name(string), aircraft_data(list) """ aircraft_name = args.aircraft_name aircraft_data = [args.passenger_number, args.overall_length, ...
da77ae883d67879b9c51a511f46173eb5366aead
3,636,855
def Oplus_simple(ne): """ """ return ne
7476203cb99ee93dddcf9fda249f5532e908e40f
3,636,856
def lin_exploit(version): """ The title says it all :) """ kernel = version startno = 119 exploits_2_0 = { 'Segment Limit Privilege Escalation': {'min': '2.0.37', 'max': '2.0.38', 'cve': ' CVE-1999-1166', 'src': 'https://www.exploit-db.com/exploits/19419/'} } exploits_2_2 = { ...
499e21091fb508b26564d06ad119d8b8ea783443
3,636,857
async def get_device( hass: HomeAssistant, config_entry_id: str, device_category: str, device_type: str, vin: str, ): """Get a tesla Device for a Config Entry ID.""" entry_data = hass.data[TESLA_DOMAIN][config_entry_id] devices = entry_data["devices"].get(device_category, []) for d...
8a3be6e7d1a5f69790b98d07433af1b6e6fe1b16
3,636,858
def cartesian2complex(real, imag): """ Calculate the complex number from the cartesian form: z = z' + i * z". Args: real (float|np.ndarray): The real part z' of the complex number. imag (float|np.ndarray): The imaginary part z" of the complex number. Returns: z (complex|np.ndar...
1fd44bc0accff8c9f26edfa84f4fcfafb2323728
3,636,859
def compare_maps(ra_id, method_id, type_id, method_comp=None, type_comp=None): """Function to compare maps / or just print off a given map""" # Get the map map_one = GPVal.objects.filter(my_anal_id=ra_id, type_id=type_id, method_id=method_id) if meth...
57008a0ad144974a06ae0a12de8a8133924c50e9
3,636,860
def _row_reduce_list(mat, rows, cols, one, iszerofunc, simpfunc, normalize_last=True, normalize=True, zero_above=True, dotprodsimp=None): """Row reduce a flat list representation of a matrix and return a tuple (rref_matrix, pivot_cols, swaps) where ``rref_matrix`` is a flat list,...
a3791c303b483b158f766bacac73fd0ba63f5f18
3,636,861
import importlib def get_action_class(class_str): """Imports the action class. Args: class_str (str): A string action class. Returns: Action: A child class of Action. Raises: ActionImportError: If the class doesn't exist. """ (module_name, class_name) = class_str.rsplit('....
fdbf6f793d8a864b82f491a15c2a0268b14715b6
3,636,862
def rate_comments(request): """ Render a bloom page where respondents can rate comments by others. """ return render(request, 'rate-comments.html')
f87777be409d79abc6c9649ec6dbe6df8cdb2ab4
3,636,863
def gaussian2d(size=(32, 32), sigma=0.5): """ Generate a Gaussian kernel (not normalized). :param size: k x m size of the returned kernel :param sigma: standard deviation of the returned Gaussian :return: A tensor with the Gaussian kernel """ x, y = tf.meshgrid(tf.linspace(-1.0, 1.0, size[0...
4a27fffe68fb031e6f47304bece9e8cfffd7224b
3,636,864
def home(): """ List all users or add new user """ users = User.query.all() return render_template('home.html', users=users)
4fb67376f51d677c544ba745680bc9fefed0ced0
3,636,865
def vgg13_bn(**kwargs): """ VGG 13-layer model (configuration "B") with batch normalization """ model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) return model
3d1ac037754384cf37dbb35c1589cbbeebc3d698
3,636,866
def lr_insight_wr(): """Return 5-fold cross validation scores r2, mae, rmse""" steps = [('scaler', t.MyScaler(dont_scale='for_profit')), ('knn', t.KNNKeepDf())] pipe = Pipeline(steps) pipe.fit(X_raw) X = pipe.transform(X_raw) lr = LinearRegression() lr.fit(X, y) cv_results ...
6d98e5e92ba10e390e96b3494a9dedb2c118df69
3,636,867
import collections def complete_list_value(exe_context, return_type, field_asts, info, result): """ Complete a list value by completing each item in the list with the inner type """ assert isinstance(result, collections.Iterable), \ ('User Error: expected iterable, but did not find one ' + ...
bc5af63592ccf6e08bf8f7da14f7852b78ec1ff0
3,636,868
def projection_ERK(rkm, dt, f, eta, deta, w0, t_final): """Explicit Projection Runge-Kutta method.""" rkm = rkm.__num__() w = np.array(w0) # current value of the unknown function t = 0 # current time ww = np.zeros([np.size(w0), 1]) # values at each time step ww[:,0] = w.copy() tt = np.zeros...
137e81c1d4764cde38985d15d04716138b90ccab
3,636,869
def integer(name, value): """Validate that the value represents an integer :param name: Name of the argument :param value: A value representing an integer :returns: The value as an int, or None if value is None :raises: InvalidParameterValue if the value does not represent an integer """ if...
bcdb6e02944edc875e42a1e23209ec5002b205f6
3,636,870
def generate_Euler_Maruyama_propagators(): """ importer function function that creates two functions: 1. first function created is a kernel propagator (K) 2. second function returns the kernel ratio calculator """ # let's make the kernel propagator first: this is just a batched ULA move ...
d9bc844761e7f0d1689492ebc51159e64d64e4d9
3,636,871
def get_vtx_neighbor(vtx, faces, n=1, ordinal=False, mask=None): """ Get one vertex's n-ring neighbor vertices Parameters ---------- vtx : integer a vertex's id faces : numpy array the array of shape [n_triangles, 3] n : integer specify which ring should be got o...
58601345c35a96e4d0e58bfa2821dbc80f911c6c
3,636,872
def tolower(x: StringOrIter) -> StringOrIter: """Convert strings to lower case Args: x: A string or vector of strings Returns: Converted strings """ x = as_character(x) if is_scalar(x): return x.lower() return Array([elem.lower() for elem in x])
7b35e364aac78ce6e087aeeba9970e9981cdc7f0
3,636,875
import numpy import math def MWA_Tile_analytic(za, az, freq=100.0e6, delays=None, zenithnorm=True, power=False, dipheight=config.DIPOLE_HEIGHT, dip_sep=config.DIPOLE_SEPARATION, ...
7d1a8a2b8f02c5ae47bcc85302d670a9e3e4d413
3,636,876
import json def traindata(): """Generate Plots in the traindata page. Args: None Returns: render_template(render_template): Render template for the plots """ # read data and create visuals df_features = read_data_csv("./data/features...
513312785a8ba7621693c05606e457b535b39c90
3,636,877
def import_file(file_path, title, source_mime_type, dest_mime_type): """Imports a file with conversion to the native Google document format. Expects the env var GOOGLE_APPLICATION_CREDENTIALS to be set for credentials. Args: path (str): Path to file to import title(str): The title of th...
386994c49895accb1433879b43d0e7a9e0b37beb
3,636,878
def test_extract_requested_slot_from_text_with_not_intent(): """Test extraction of a slot value from text with certain intent """ # noinspection PyAbstractClass class CustomFormAction(FormAction): def slot_mappings(self): return {"some_slot": self.from_text(not_intent='some_intent')}...
a96deace8c9d291c3b67a13c250e84a519012fa7
3,636,879
def create_generic_io_object(ioclass, filename=None, directory=None, return_path=False, clean=False): """ Create an io object in a generic way that can work with both file-based and directory-based io objects If filename is None, create a filename. If return_path is Tr...
1f10537695f507f9ea0c9eec6834efd7c0d6d6fe
3,636,881
def select_channels(img_RGB): """ Returns the R' and V* channels for a skin lesion image. Args: img_RGB (np.array): The RGB image of the skin lesion """ img_RGB_norm = img_RGB / 255.0 img_r_norm = img_RGB_norm[..., 0] / ( img_RGB_norm[..., 0] + img_RGB_norm[..., 1] + img_RGB_nor...
7daacf660c30702b8cbbe6da5da97937d11c0c0a
3,636,882
def upper_case(string): """ Returns its argument in upper case. :param string: str :return: str """ return string.upper()
bbf3fc8b856d466ec73229145443566d85a3457a
3,636,883
import json def repositoryDefinitions(): """ Load repositoryDefinitions page """ i_d = wmc.repository.get_definition_details() p_d = json.dumps(i_d, indent=4) + " " msg = Markup(JSONtoHTML(p_d)) return render_template('repositoryDefinitions.html', data=msg)
a4325e962a81421b4a35c4919d1fa637ae267a0a
3,636,884
def available_adapter_names(): """Return a string list of the available adapters.""" return [str(adp.name) for adp in plugins.ActiveManifest().adapters]
b5674e901de02bc9e2b94cb9fa8b0885b197cb21
3,636,885
def count_sort(seq): """ perform count sort and return sorted sequence without affecting the original """ counts = defaultdict(list) for elem in seq: counts[elem].append(elem) result = [] for i in range(min(seq), max(seq)+1): result.extend(counts[i]) return result
a035592a9a258f138f0064f4f733f405ee2b75d0
3,636,888
def detect_overrides(cls, obj): """ For each active plugin, check if it wield a packet hook. If it does, add make a not of it. Hand back all hooks for a specific packet type when done. """ res = set() for key, value in cls.__dict__.items(): if isinstance(value, classmethod): ...
55b7299c6239050dd94e8e4ffc3484f987c60125
3,636,889
def morningCalls(): """localhost:8080/morningcalls""" session = APIRequest.WebServiceSafra() return session.listMorningCalls()
181d491ddd9549ff8cb3b15c66201ee6b9a88249
3,636,890
def resize_image(img, h, w): """ resize image """ image = cv2.resize(img, (w, h), interpolation=cv2.INTER_NEAREST) return image
f4e1c8f24abb44714d3894a255b32d50e72e09b5
3,636,891
from typing import Dict def _parse_pars(pars) -> Dict: """ Takes dictionary of parameters, converting values to required type and providing defaults for missing values. Args: pars: Parameters dictionary. Returns: Dictionary of converted (and optionally validated) parameters. ...
cda13c228f7764718ca0becceae3d721ba111eda
3,636,892
def _get_base_class_names_of_parent_and_child_from_edge(schema_graph, current_location): """Return the base class names of a location and its parent from last edge information.""" edge_direction, edge_name = _get_last_edge_direction_and_name_to_location(current_location) edge_element = schema_graph.get_edge...
7860208cb305745f5c62aec664acd60a57715f48
3,636,893
from typing import Callable def projection( v: GridVariableVector, solve: Callable = solve_fast_diag, ) -> GridVariableVector: """Apply pressure projection to make a velocity field divergence free.""" grid = grids.consistent_grid(*v) pressure_bc = boundaries.get_pressure_bc_from_velocity(v) q0 = grid...
e20ff776603be0faef2d63e29c58f99c255ec19d
3,636,894
def a07_curve_function(curve: CustomCurve): """Computes the embedding degree (with respect to the generator order) and its complement""" q = curve.q() if q.nbits()>300: return {"embedding_degree_complement":None,"complement_bit_length":None} l = curve.order() embedding_degree = curve.embeddi...
1f06c9c4425e7d24241d425cfbd9a764d6589963
3,636,895
def _horizontal_metrics_from_coordinates(xcoord,ycoord): """Return horizontal scale factors computed from arrays of projection coordinates. Parameters ---------- xcoord : xarray dataarray array of x_coordinate used to build the grid metrics. either plane_x_coord...
a366c37172bed098607e4c5c7194812d3d82141f
3,636,896
def ultosc( df, high, low, close, ultosc, time_period_1=7, time_period_2=14, time_period_3=28, ): """ The Ultimate Oscillator (ULTOSC) by Larry Williams is a momentum oscillator that incorporates three different time periods to improve the overbought and oversold signals....
d6f69906bb09e3a7075339cd4a6554d5336f6caa
3,636,897
def mating(child_id, parent1, parent2, gt_matrix): """ Given the name of a child and two parents + the genotype matrices, mate them """ child_gen = phase_parents(parent1, parent2, gt_matrix) parent1.add_children(child_id) parent2.add_children(child_id) child = Person(child_id) child.se...
9962eb24ff175b0b2d77a787dbc50a342ed4a202
3,636,898
def _tmp( generator_reconstructed_encoded_fake_data, encoded_random_latent_vectors, real_data, encoded_real_data, generator_reconstructed_encoded_real_data, alpha=0.7, scope="anomaly_score", add_summaries=False): """anomaly score. See https://arx...
181bd45d23e14585072917d2ad707f13f13b7d4f
3,636,899
def get_key_metrics_fig(confirmed_ser, recovered_ser, deaths_ser, metric_type): """ Return key metrics graph object figure Parameters ---------- confirmed_ser: pandas.Series Confirmed pandas series objects with index=dates, values=number of cases r...
a11130a21d124c2bf44a02d9c3c58bcde5a326cb
3,636,900
from typing import List def pr_curve(results: List[TrecEvalResults]) -> plt: """ Create a precision-recall graph from trec_eval results. :param results: A list of TrecEvalResults files. :return: a matplotlib plt object """ names = [r.run_id for r in results] iprec = [[r.results['ipre...
90f1e3234304fa7966b93ebdc76235e5356002e6
3,636,902
def plotData(datalist, part = "real", progressive = True, color = None, clip = False, tcutoff = None): """Plot real or imaginary parts of a given list of functions. arguments: datalist (list of tuples, each tuple of form (xlist,ylist)): data to plot; xlist should be real numbers, ylist can be comp...
5e328c19fe63389d7f2d55e5fd5d75d2dd5d7c24
3,636,903
def train_and_test(model, dataset, robustness_tests=None, base_config_dict=None, save_model=True): """ Train a recommendation model and run robustness tests. Args: model (str): Name of model to be trained. dataset (str): Dataset name; must match the dataset's folder name located in 'data_pat...
3681bc732b2b39837c871267f4659825105d6e2b
3,636,904
def total_cost(content_cost, style_cost, alpha, beta): """Return a tensor representing the total cost.""" return alpha * content_cost + beta * style_cost
98d42bd8d62dc8cd7110b2f5eb9a9a4e4eb6bc65
3,636,905
def create_command_using_pip_action( num_bash_entries=10, uninstall_use_creation_time=False, skip=0): """Create commands using latest pip action.""" valid_pip_commands = get_valid_pip_history(num_bash_entries)[skip:] assert valid_pip_commands, 'No undoable pip commands.' last_valid_pip_command =...
5ba22f63d33c1ae60ec3a93590965453885e5e29
3,636,906
def extract_word_pos_sequences(form, unknown_category, morpheme_splitter=None, extract_morphemes=False): """Return the unique word-based pos sequences, as well as (possibly) the morphemes, implicit in the form. :param form: a form model object :param morpheme_splitter: callable that splits a strings into i...
e08c285910c4da2f827f81ac65abc2ee3d62b1dc
3,636,907
def model_test(Py, Px_y, testDataArr, testLabelArr): """ 模型测试 @Args: Py: 先验概率分布 Px_y: 条件概率分布 testDataArr: 测试集数据 testLabelArr: 测试集标签 @Returns: 准确率 @Riase: """ # 错误值 errorCnt = 0 # 循环遍历测试集中的每一个样本 for i in range(len(testDataArr...
f1e06725511750c79e34dc528728aab8cebc7c34
3,636,908
from typing import Optional import torch def int2c2e(shortname: str, wrapper: LibcintWrapper, other: Optional[LibcintWrapper] = None) -> torch.Tensor: """ 2-centre 2-electron integrals where the `wrapper` and `other1` correspond to the first electron, and `other2` corresponds to another electr...
1f5b6c70c8373c885103d6deb7cba77ea8d0aa73
3,636,909
def send_group_membership_request(request, group_id, template='group_send_request.html'): """ Send membership request to the administrator of a private group. """ if request.method == 'POST': form = GroupMembershipRequestForm(request.POST) if form.is_valid(): group = Grou...
22324765a915e1677fb6abab41dfa214fcc05d40
3,636,910
def _dataset_type_dir(signer): """Returns the directory name of the corresponding dataset type. There is a `TFRecord` file written for each of the 25 signers. The `TFRecord` files of the first 17 signers are assigned to the train dataset, the `TFRecord` files of the next 4 signers are assigned to the valid...
515fd2e0871cf9549f3f724da0b45bb07f09e24b
3,636,912
def _merge_blanks(src, targ, verbose=False): """Read parallel corpus 2 lines at a time. Merge both sentences if only either source or target has blank 2nd line. If both have blank 2nd lines, then ignore. Returns tuple (src_lines, targ_lines), arrays of strings sentences. """ merges_done = [] #...
fe5f765022b2b4de5320272701148cc9f8e691b8
3,636,913
import codecs def get_line(file_path, line_rule): """ 搜索指定文件的指定行到指定行的内容 :param file_path: 指定文件 :param line_rule: 指定行规则 :return: """ s_line = int(line_rule.split(',')[0]) e_line = int(line_rule.split(',')[1][:-1]) result = [] # with open(file_path) as file: file = codecs.o...
a6ccda48f8083e5ff6827306f4abd7f19e8d445c
3,636,914
def _generate_odd_sequence(sequence_id: int, start_value: int, k_factor: int, max_iterations: int): """ This method generates a Collatz sequence containing only odd numbers. :param sequence_id: ID of the sequence. :param start_value: The integer value to start with. The value...
d886631d153531fafa2cd9b15be621df9746a909
3,636,915
def _is_unique_rec_name(info_name): """ helper method to see if we should use the uniqueness recommendation on the fact comparison """ UNIQUE_INFO_SUFFIXES = [".ipv4_addresses", ".ipv6_addresses", ".mac_address"] UNIQUE_INFO_PREFIXES = ["fqdn"] if info_name.startswith("network_interfaces.lo...
cba744e1e5b6a9612363d2ca12d4751e1894c8ad
3,636,917
def initialized(): """ Connection finished initializing? """ return __context__["netmiko_device"].get("initialized", False)
6ca85744478bdb17ac99ce827825cde1db8bae3a
3,636,918
def n_round(a, b): """safe round""" element_round = np.vectorize(np.round) return element_round(a, intify(b))
2c38e1585b71d5717ea3cc560521b8a006ceeee3
3,636,919
def _json_view_params(shape, affine, vmin, vmax, cut_slices, black_bg=False, opacity=1, draw_cross=True, annotate=True, title=None, colorbar=True, value=True): """ Create a dictionary with all the brainsprite parameters. Returns: params """ # Set color pa...
50ea71a5a99facf4c472f0c18984d84e23b8e301
3,636,920
from typing import List from datetime import datetime def get_timestamps_from_df_data(df) -> List[datetime.datetime]: """Get a list of timestamp from rows of a DataFrame containing raw data. """ timestamps = [] for index, row in df.iterrows(): year = int(row["dteday"][:4...
21f985ebf28d6f5819635a13294e8db0544a292b
3,636,921
def select(var_name, attr_name=None): """ Return attribute(s) of a variable given the variable name and an optional field name, or list of attribute name(s) :param var_name: Name of the variable we're interested in. :param attr_name: A string representing the name of the attribute whose value we want to...
22b65439ff4dc831c2fb334595b0f0cd2e764b67
3,636,923
import re def _parseWinBuildTimings(logfile): """Variant of _parseBuildTimings for Windows builds.""" res = {'Compile': re.compile(r'\d+>Time Elapsed (\d+):(\d+):([0-9.]+)'), 'Test running': re.compile(r'.*?\.+.*?([0-9.]+) sec')} times = dict([(k, 0.0) for k in res]) for line in logfile: ...
0473c426d29bb7fe44ff3384f81962f121c11afa
3,636,924
def get_malid(anime: AnimeThemeAnime) -> int: """ Returns anime theme of resource. """ for resource in anime['resources']: if resource["site"] == "MyAnimeList": return resource['external_id']
a745f95e73e8e061d98100e314faf5a662d69693
3,636,926