content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch def shuffle_tensor(input): """ Returns a new tensor whose elements correspond to a randomly shuffled version of the the elements of the input. Args: input (`torch.Tensor`): input tensor. Returns: (`torch.Tensor`): output tensor. """ return input[torch.randperm(in...
e7c3ff4180123de1fe6322296ba08863de9766a4
3,641,209
def relaunch_failed_jobs(tasks, spec_file, verbose=False): """ Relaunch jobs that are failed from the given list """ job_cnts = 0 # number of newly launched jobs for i, task in enumerate(tasks): job_id = str(task[-1]) # the last entry # Try to launch until succeed while True: ...
d78c250e1c6f10c60bb81aea077063f6f5b15b12
3,641,210
def intensityTriWave(coeff,L,ang): """Simulate the intensity observed a distance L from the grating. Standard Zernike coefficients, L, and the diffraction angle ang are used as input. """ k = 2*np.pi/405.e-6 #blue wavevector x,y = np.meshgrid(np.linspace(-1.1,1.1,1000),np.linspace(-1.1,1.1,1000)...
3b85a0d437fce65d8f164b31a3fc2e85fca33006
3,641,211
import requests import time import ast def do_auth_code_grant(fqdn, force_login=False, identity=None): """Perform an Oauth2 authorization grant consent flow.""" code_verifier, code_challenge = _gen_code() scope = (SCOPE_FORMAT.format(fqdn=fqdn)) host = GLOBUS_AUTH_HOST creds = _lookup_credentia...
0e5583d1d6a273e165f0d8d9bed82e3c9af491cd
3,641,212
import json def decode(serialized: str) -> Node: """Decode JSON as a `Node`""" node = json.loads(serialized) return dict_decode(node) if isinstance(node, dict) else node
b608b6c18c09d7061e09d722445ca1f50fd78b3f
3,641,213
def validate_duration_unit(recv_duration_unit): """Decapitalize and check in units_list""" units_list = DaysAndUnitsList.units_list recv_duration_unit = recv_duration_unit.lower() if recv_duration_unit in units_list: return True else: return False
784693ea8106c601b884a729ad2afd2a75b94ba2
3,641,214
def make_word_list1(): """Reads lines from a file and builds a list using append.""" t = [] fin = open('words.txt') for line in fin: word = line.strip() t.append(word) return t
7af7b0697557e8bba891d73bd8217860350b810e
3,641,215
def metropolis(data, likelihood, priors, samples=1000, par_init=None, width_prop=.5): """ Returns the posterior function of the parameters given the likelihood and the prior functions. Returns also the number of the accepted jumps in the Metropolis-Hastings algorithm. Notes: - <w...
3857e237390a8373eecbc575209e96d42b6ff614
3,641,217
def _get_single_spec_df(reference_dict, mapping_dict, spectrum): """Primary method for reading and storing information from a single spectrum. Args: reference_dict (dict): dict with reference columns to be filled in mapping_dict (dict): mapping of engine level column names to ursgal unified col...
3d286e9bc206c0b59364cf9ef6d861b5cde9e9d4
3,641,218
import re def in2func(inp): """Function converts input expression to a mathematical expression.""" # Validate Function if inp == "": raise ValueError( f"Enter a function to plot!") for char in re.findall("[a-zA-Z_]+", inp): if char not in allowed_inputs: # Error will commun...
d3bf2faaed00f7b57c5bcd5b2681c94846671793
3,641,219
from datetime import datetime def filter_posts(posts: list, parsing_date: datetime) -> list: """Отфильтровывает лишние посты, которые не входят в месяц парсинга""" res = [] for post in posts: post_date = datetime.fromtimestamp(post['date']) if post_date.month == parsing_date.month: ...
381d5cb37e4ae3439c335a7962352431ad3ca17c
3,641,220
import requests import re def parse_bing(): """ 解析bing网页的壁纸链接,采用正则表达式匹配 :return: IMG_info,IMG_url """ base_url = 'https://cn.bing.com/' language_parameter = '?mtk=zh-CN' # base_url = 'https://www.bing.com/?mkt=zh-CN' try: resp = requests.get(base_url+language_parameter, headers...
4a963514f385a931882a75f45be774cbab4428ff
3,641,221
def quadsum(*args, **kwargs): """Sum of array elements in quadrature. This function is identical to numpy.sum except that array elements are squared before summing and then the sqrt of the resulting sums is returned. The docstring from numpy.sum is reproduced below for convenience (copied 2014-12-...
ef842dab6258dc46b84098098115151a240f767b
3,641,222
import codecs def open_file(path): """open_file.""" return codecs.open(path, encoding='utf8').read()
f7fd375ea76e8e7872e465e89eea5c02f3396115
3,641,223
def get_api_status(): """Get API status""" return "<h4>API Is Up</h4>"
5c88fc39bc5a970c4d223d8fe87c4fa3ad473b50
3,641,224
def fgt_set_pressureUnit(pressure_index, unit): """Override the default pressure unit for a single pressure channel""" unit_array = (c_char * (len(unit)+1))(*([c_char_converter(c) for c in unit])) c_error = c_ubyte(lib.fgt_set_pressureUnit(c_uint(pressure_index), unit_array)) return c_error.value,
8b7b75ffc598f70e7bbf3e1742a7837bf71f474f
3,641,226
def create_alert_from_slack_message(payload, time): """ Create a new raw alert (json) from the new alert form in Slack """ alert_json = {} values = payload['view']['state']['values'] for value in values: for key in values[value]: if key == 'severity': alert_js...
1ae8b93a6b9f8bd7532ac193cb6dfde58bf8d409
3,641,228
def psd(buf_in, buf_out): """ Perform discrete fourier transforms using the FFTW library and use it to get the power spectral density. FFTW optimizes the fft algorithm based on the size of the arrays, with SIMD parallelized commands. This optimization requires initialization, so this is a factory ...
9573935fd0e80e3e1a53237334a46f21d94984ab
3,641,229
def get_cell_ids(num_celltypes=39): """get valid cell ids by removing cell types with missing data. Return: A cell id list. """ missing_ids = [8,23,25,30,32,33,34,35,38,39,17] return [item for item in list(range(1,num_celltypes+1)) if item not in missing_ids]
a7c8f881ad62af9c4287cd50b9b01118f724c4f8
3,641,230
def limit_data(): """Slice data by dolphot values and recovered stars in two filters""" fmt = '{:s}_{:s}' filter1, filter2 = filters.value.split(',') selected = data[ (np.abs(data[fmt.format(filter1, 'VEGA')]) <= 60) & (np.abs(data[fmt.format(filter2, 'VEGA')]) <= 60) & (data[fmt...
785d027c13a05b97f2b98526dd0762e95e4e0fd6
3,641,231
from typing import Dict from typing import Optional from typing import Callable def make_valance_getter( lexicon: Dict[str, float], lemmatize: bool = True, lowercase: bool = True, cap_differential: Optional[float] = C_INCR, ) -> Callable[[Token], float]: """Creates a token getter which return the ...
825e8bf624240e3628537dbcfc6a09af2d54cd83
3,641,233
import re def proper_units(text: str) -> str: """ Function for changing units to a better form. Args: text (str): text to check. Returns: str: reformatted text with better units. """ conv = { r"degK": r"K", r"degC": r"$^{\circ}$C", r"degrees\_celsius":...
5113d227db1a75ec8fa407c5f9edd5a897960d82
3,641,234
import re from datetime import datetime def coerce_number(value, convert = float): """ 将数据库字段类型转为数值类型 """ pattern = re.compile(r'^\d{4}(-\d\d){2}') format = '%Y-%m-%d %H:%M:%S' if isinstance(value, basestring) and pattern.match(value): #将字符串的日期时间先转为对象 try: mask = format[:le...
a36b3b8e814d722d6814a3306c692a8c7cbe28a5
3,641,235
def create_credential_resolver(): """Create a credentials resolver for Localstack.""" env_provider = botocore.credentials.EnvProvider() default = DefaultCredentialProvider() resolver = botocore.credentials.CredentialResolver( providers=[env_provider, default] ) return resolver
36426521d5928aec1cb7c01308afe3d60c3f9959
3,641,236
def does_algorithm_implementation_have_capabilities_to_execute_parameter(parameter_kisao_id, algorithm_specs): """ Determine if an implementation of an algorithm has the capabilities to execute a model langugae Args: parameter_kisao_id (:obj:`str`): KiSAO id for an algorithm parameter algorithm...
653712ae621bd014547e04009243cefe4c9eb8e1
3,641,237
def main(): """ This method allows the script to be run in stand alone mode. @return Exit code from running the script """ record = Record() result = record.Run() return result
5460a32b9202c133da9ca109f5f2784fe21d7ee2
3,641,238
def stamp_pixcov_from_theory(N,cmb2d_TEB,n2d_IQU=0.,beam2d=1.,iau=False,return_pow=False): """Return the pixel covariance for a stamp N pixels across given the 2D IQU CMB power spectrum, 2D beam template and 2D IQU noise power spectrum. """ n2d = n2d_IQU cmb2d = cmb2d_TEB assert cmb2d.ndim==4 ...
1ad8d5c2925f5e7ab5636348cbedbed1383c2963
3,641,239
def make_data_parallel(module, expose_methods=None): """Wraps `nn.Module object` into `nn.DataParallel` and links methods whose name is listed in `expose_methods` """ dp_module = nn.DataParallel(module) if expose_methods is None: if hasattr(module, 'expose_methods'): expose_methods ...
9992b8980f2cdec22e13f6805b4d02d3694c4b4a
3,641,240
def model_creator(model_dict, X_train, y_train, rd=None, rev=None): """Returns a SVM classifier""" # Load model based on model_dict clf = model_loader(model_dict, rd, rev) # If model does not exist, train a new SVM if clf is None: clf = model_trainer(model_dict, X_train, y_train, rd, rev) ...
6f962c898167d1466b80a074aa7289ff26b0c3e2
3,641,241
import torch def bert_predict(model, loader): """Perform a forward pass on the trained BERT model to predict probabilities on the test set. """ # Put the model into the evaluation mode. The dropout layers are disabled during # the test time. model.eval() all_logits = [] # For each ba...
602e219ce3fbed8afb86d11daf06ab09efe9c1b3
3,641,242
def eval_input_fn(training_dir, params): """Returns input function that feeds the model during evaluation""" return _input_fn('eval')
0bb40833dee0e7564d166b7aabb27a54d61cdf2d
3,641,243
def GNIs(features, labels, mode, params, config): """Builds the model function for use in an estimator. Arguments: features: The input features for the estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionary....
724b32981a3b79c6725e4a7c6add9ab0f5046647
3,641,244
def b58decode(v, length): """ decode v into a string of len bytes """ long_value = 0L for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base**i) result = '' while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + result ...
3a9d1d5da02c2174bcf0220de705a92a91cd0b18
3,641,245
def has_remove_arg(args): """ Checks if remove argument exists :param args: Argument list :return: True if remove argument is found, False otherwise """ if "remove" in args: return True return False
9b07fe70cecfbdf6e6e2274e5b3e715f903331c7
3,641,247
def supported_locales(prefix, parsed_args, **kwargs): """ Returns all supported locales. :param prefix: The prefix text of the last word before the cursor on the command line. :param parsed_args: The result of argument parsing so far. :param kwargs: keyword arguments. :returns list: list of all...
db6f73699120dc4b784b1f46ed7c9fbe4a3cc9a9
3,641,248
def generate_tool_panel_dict_for_tool_config( guid, tool_config, tool_sections=None ): """ Create a dictionary of the following type for a single tool config file name. The intent is to call this method for every tool config in a repository and append each of these as entries to a tool panel dictionary for...
8e976cf4d54212d0477ef4ae7d4fb1dd532363fa
3,641,249
def get_tmp_dir(): """get or create the tmp dir corresponding to each process""" tmp_dir = result_dir / "tmp" tmp_dir.mkdir(exist_ok=True) return tmp_dir
406962c5783dff1d23523bd5bd258b7bb18ed149
3,641,250
def get_logs(job_id, user, index): """get logs""" return instance().get_logs(job_id=job_id, user=user, log_index=int(index))
f2d959835c34ffec475d5e9da18e74feef13b5d9
3,641,251
def repeat_as_list(x: TensorType, n: int): """ :param x: Array/Tensor to be repeated :param n: Integer with the number of repetitions :return: List of n repetitions of Tensor x """ return [x for _ in range(n)]
cb4924909d93899a555c11bd70950c6cbb77cf85
3,641,252
def transition(x, concat_axis, nb_filter, dropout_rate=None, weight_decay=1E-4): """Apply BatchNorm, Relu 1x1Conv2D, optional dropout and Maxpooling2D :parameter x: keras model :parameter concat_axis: int -- index of contatenate axis :parameter nb_filter: int -- number of filters :parameter dropout...
30d89aca3a330dc6b04b4c9ee21a8620c8ba69f1
3,641,253
import torch def scale_params(cfg): """ Scale: * learning rate, * weight decay, * box_loss_gain, * cls_loss_gain, * obj_loss_gain according to: * effective batch size * DDP world size * image size * num YOLO output layers * nu...
a74472a5c5ce2a6b83eab0467c66b468226c222d
3,641,255
def get_model(args): """ Load model and move tensors to a given devices. """ if args.model == "lstm": model = LSTM(args) if args.model == "lstmattn": model = LSTMATTN(args) if args.model == "bert": model = Bert(args) if args.model == "lqt": model = LastQuery(a...
131a4e3d8832d9b0aa099c55f7a8851d3a8907ef
3,641,256
def convert_to_boolean(value): """Turn strings to bools if they look like them Truthy things should be True >>> for truthy in ['true', 'on', 'yes', '1']: ... assert convert_to_boolean(truthy) == True Falsey things should be False >>> for falsey in ['false', 'off', 'no', '0']: ... asser...
7cbf7a8fd601904c7aa8b685f6a3b3f5eaaa5c51
3,641,257
def getSampleBandPoints(image, region, **kwargs): """ Function to perform sampling of an image over a given region, using ee.Image.samp;e(image, region, **kwargs) Args: image (ee.Image): an image to sample region (ee.Geometry): the geometry over which to sample Returns: An ee.F...
4cfbc3c180b805abe52c718f81cc16c409693922
3,641,258
def updateRIPCount(idx,RIPtracker,addRev=0,addFwd=0,addNonRIP=0): """Add observed RIP events to tracker by row.""" TallyRev = RIPtracker[idx].revRIPcount + addRev TallyFwd = RIPtracker[idx].RIPcount + addFwd TallyNonRIP = RIPtracker[idx].nonRIPcount + addNonRIP RIPtracker[idx] = RIPtracker[idx]._replace(revRIPcoun...
7f83c547d9acd6c697174fffa1ccb3aec6e91a24
3,641,259
def serialize(obj): """ Return a JSON-serializable representation of an object """ cls = obj.__class__ cls_name = cls.__name__ module_name = cls.__module__ serializer = None if hasattr(obj, "to_serializable"): # The object implements its own serialization s = obj.to_serializable(...
3fd5449922808a1e1772b3937bca6736c63df9a2
3,641,260
async def async_unload_entry(hass, config_entry): """Unload a config entry.""" controller_id = CONTROLLER_ID.format( host=config_entry.data[CONF_CONTROLLER][CONF_HOST], site=config_entry.data[CONF_CONTROLLER][CONF_SITE_ID] ) controller = hass.data[DOMAIN].pop(controller_id) return aw...
2341f49794ecd9f9824330594cf3955bca117455
3,641,262
import operator def get_farthest_three_shots(gps_shots): """get three shots with gps that are most far apart""" areas = {} for (i, j, k) in combinations(gps_shots, 3): areas[(i, j, k)] = area(np.array(i.metadata.gps_position), np.array(j.metadata.gps_position), np.array(k.metadata.gps_position)) ...
697d87549bee0a8ff3adee30ceb7b41a24f3d66b
3,641,264
from operator import sub def __parse_entry(entry_line): """Parse the SOFT file entry name line that starts with '^', '!' or '#'. :param entry_line: str -- line from SOFT file :returns: tuple -- type, value """ if entry_line.startswith("!"): entry_line = sub(r"!\w*?_", '', entry_line) ...
1a645cb4dcaafaa4de1db7011d3ff54931b8123f
3,641,265
def _mut_insert_is_applied(original, mutated): """ Checks if mutation was caused by `mut_insert`. :param original: the pre-mutation individual :param mutated: the post-mutation individual :return: (bool, str). If mutation was caused by function, True. False otherwise. str is a message explaini...
f19bb092e1eefc14435f5bb90a030558980fed4c
3,641,266
from typing import Dict from typing import Any def remap_ids( mapping_table: Dict[Any, int] = {}, default: int = 0, dtype: DTypes = "i" ) -> Model[InT, OutT]: """Remap string or integer inputs using a mapping table, usually as a preprocess before embeddings. The mapping table can be passed in on input, ...
4380b9377930d6affac6703a0a1e656a916b45db
3,641,267
def get_text(cell): """ get stripped text from a BeautifulSoup td object""" return ''.join([x.strip() + ' ' for x in cell.findAll(text=True)]).strip()
08037cbe5d2058206de029417f03d211d350820f
3,641,268
import torch def test_augmentation(text, text_lengths, augmentation_class): """ test_augmentation method is written for augment input text in evaluation :param text: input text :param text_lengths: text length :param augmentation_class: augmentation class :return: """ augmentation_tex...
2f83ec9fa0afa110d05f05f52e85cae65a28c6f9
3,641,270
def selfintersection(linear_ring: Points): """ not support warp polygon. """ validate.linear_ring(linear_ring) if len(linear_ring) == 4: return ( abs( linear_ring[0][1] * (linear_ring[1][0] - linear_ring[2][0]) + linear_ring[1][1] * (linear_ring[2]...
d0b92d7796a3281a4481071f0b0666fdf79c6952
3,641,271
import math def ToMercPosition(lat_deg, num_tiles): """Calculate position of a given latitude on qt grid. LOD is log2(num_tiles) Args: lat_deg: (float) Latitude in degrees. num_tiles: (integer) Number of tiles in the qt grid. Returns: Floating point position of latitude in tiles relative to equat...
1ae7e7b2da9ec3ee20756ef7ffa13d99485aaea7
3,641,272
def conv3x3(in_planes, out_planes, stride=1, dilation=1, groups=1, bias=False): """2D 3x3 convolution. Args: in_planes (int): number of input channels. out_planes (int): number of output channels. stride (int): stride of the operation. dilation (int): dilation rate of the operation. ...
d5658d81f5fbc5d196418e4e4b005dbf7d3f20ae
3,641,273
def parse_hostnames(filename, hostnames): """Parses host names from a comma-separated list or a filename. Fails if neither filename nor hostnames provided. :param filename: filename with host names (one per line) :type filename: string :param hostnames: comma-separated list of host names :type hostnames: ...
b3fce0f3af7f59217fd18bfce53baec87784759f
3,641,275
def ssh(host, command, stdin=None): """Run 'command' (list) on 'host' via ssh. stdin is an string to send.""" return run([*SSH_COMMAND, ssh_user_host(host), *command], stdin=stdin)
9719aef39530e285d27a2e9dd5a7ceab09f3793e
3,641,276
def cart_step1_choose_type_of_order(request): """ This view is not login required because we want to display some summary of ticket prices here as well. """ special_fares = get_available_fares_for_type(TicketType.other) context = {"show_special": bool(special_fares)} return TemplateResponse(...
869941df96c750c0049f6ab5e50e5fad17679af2
3,641,278
def buildAndTrainModel(model, learningRate, batchSize, epochs, trainingData, validationData, testingData, trainingLabels, validationLabels, testingLabels, MODEL_NAME, isPrintModel=True): """Take the model and model parameters, build and train the model""" # Build and compile model # To use other optimi...
9e9170ccb817be6ec3908c16390d1afe4f96b2e7
3,641,279
def vflip(): """Toggle vertical flipping of camera image.""" # Catch ajax request with form data vflip_val = 'error' if request.method == 'POST': vflip_val = request.form.get('vflip') if vflip_val is not None: app.logger.info('Form brightness submitted: %s', vflip_val) ...
064280aadbdc53783d983caa66a52d294732be9e
3,641,280
def getGoalHistogramData(responses): """ Goal Completion histogram chart on project detail page. Return: {obj} Counts and % of each Goal Completion rating across given responses. """ try: snapshotResponses = responses.exclude(Q(primary_goal__isnull=True) | Q(primary_goal__name='')) respsnapshotResponsesCount =...
782c911f1a751ccf4c441874520f0cbc66b4a89c
3,641,281
def hookes_law(receiver_nodes, sender_nodes, k, x_rest): """Applies Hooke's law to springs connecting some nodes. Args: receiver_nodes: Ex5 tf.Tensor of [x, y, v_x, v_y, is_fixed] features for the receiver node of each edge. sender_nodes: Ex5 tf.Tensor of [x, y, v_x, v_y, is_fixed] features...
30182ed5e91e07affa4db117c9e24a9cf76e3646
3,641,282
def check_output_filepath(filepath): """ Check and return an appropriate output_filepath parameter. Ensures the file is a csv file. Ensures a value is set. If a value is not set or is not a csv, it will return a default value. :param filepath: string filepath name :returns: a string re...
63fcf697dbde9a62cc39311b4d234955520f6394
3,641,283
import re def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None): """Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match...
28705c7d1785853f99d544967e745a12a58321f0
3,641,284
def concat_chunked_data(jsons, f_src='c', *args, **kwargs): """ Takes chunks of data and combines them into a numpy array of shape trial x cells x time, concatendated over trials, and clips the trials at shortest frame number and fewest cells. Args and kwargs are passed to process_data. Args: ...
cfd978a1ac74d35d857e152e6051e88b05ccf495
3,641,285
def hmc_update(context, hmc_uuid, values, session=None): """Updates an existing HMC instance in the Database""" return IMPL.hmc_update(context, hmc_uuid, values, session)
943dd2359b2458429d60bb8c68ee20c40651b8fe
3,641,286
def _dense_difference(fun, x0, f0, h, one_sided, method): """ Calculates an approximation of the Jacobian of `fun`at the point `x0` in dense matrix form. NOTE: Inspired from: https://github.com/scipy/scipy/blob/master/scipy/optimize/_numdiff.py Parameters ---------- fun : callable Func...
47d840a70fe2b8d22bf9fec4fdbb0e5190dec2f2
3,641,287
def alternate( name, *functions ): """Construct a callable that functions as the first implementation found of given set of alternatives if name is a function then its name will be used.... """ if not isinstance( name, (bytes,unicode)): functions = (name,)+functions name = name.__name__...
5e751a5332c3e8e9e37f5544e9461c772bc525ac
3,641,288
from typing import Optional from typing import Callable def check_messenger(messenger: Optional[Callable]): """ Check that `messenger` is a `utipy.Messenger` object or `None`. In the latter case a `utipy.Messenger` with `verbose=False` is returned. Parameters ---------- messenger : `utipy.M...
b50bc38d5034e3d4d4d35d4532a504024008361f
3,641,289
import re def convert(s): """Take an input string s, find all things that look like SGML character entities, and replace them with the Unicode equivalent. Function is from: http://stackoverflow.com/questions/1197981/convert-html-entities-to-ascii-in-python/1582036#1582036 """ matches = re.findal...
0a25ee189ff107e5cd725bba1d1d20d6cb1c0f0c
3,641,290
def check_data_selection(race_id=None, category_index=None, racer_id=None): """Makes sure that we are trying to show data that is in the database.""" errors = [] if not race_id in Races.get_column('race_id'): race_id = Races.get_random_id() errors.append('race') categories = Races.get_c...
6d5b4eeaf1149fdac76e83bb94a6b6d482d0d280
3,641,291
def index(request): """ Root page view. Just shows a list of liveblogs. """ # Get a list of liveblogs, ordered by the date of their most recent # post, descending (so ones with stuff happening are at the top) liveblogs = Liveblog.objects.annotate( max_created=Max("posts__created") )....
518c64db21bd843dc34513c4d5677a18e5eac319
3,641,293
def model_fn_builder( bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings ): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument ...
088e636bf21caa316995dbd69b680dedd42ca21a
3,641,294
def strarray(*args): """strarray(strarray_t array, size_t array_size, int code) -> char""" return _idaapi.strarray(*args)
9dfb42d81d307a32f201f1b55a1ef81cbede7c27
3,641,295
def _single_value_set(target_list, value): """ Return true if this constraint has only one value and it is this one. """ return len(target_list) == 1 and target_list[0] == value
472ebe1aa9726c70642423d05fa55723496e9bc5
3,641,296
def get_positive_input(message, float_parse=False, allow_zero=False): """ Obtains and returns a positive int from the user. Preconditions: message: non-empty string float_parse: bool defaulted to False allow_zero: bool defaulted to False Parameters: message: The message that is printed whe...
17982ff069907464c70df7b6efb1f42d3811962e
3,641,297
def hellinger(p, q): """Compute Hellinger distance between 2 distributions.""" return np.linalg.norm(np.sqrt(p) - np.sqrt(q)) / np.sqrt(2)
f976a96af2e4acaf81961b93f2cfe7a868d912e3
3,641,298
def usd_currency(currency_df: pd.DataFrame, value: int, date: str) -> float: """ Compute VALUE/(USD/SYMBOL) Parameters ---------- currency_df : pd.DataFrame USD/SYMBOL df value : int Value of product date : str Currency quote day Returns --------- float ...
15ce0d8f9db3b5dc1e1a684dc27daa63d163853b
3,641,299
def svn_wc_adm_probe_retrieve(*args): """svn_wc_adm_probe_retrieve(svn_wc_adm_access_t associated, char path, apr_pool_t pool) -> svn_error_t""" return _wc.svn_wc_adm_probe_retrieve(*args)
2716094e31c596212b5ccd7833b9ae10ef52d44e
3,641,300
def flights_preclean(df): """ Input: Raw dataframe of Flights table. Output: Cleaned flights table: - Remove cancelled rows, made available in new dataframe "df_can" - Drop columns ['Unnamed: 0', 'branded_code_share', 'mkt_carrier', 'cancelled', 'cancellation_code', 'flights', 'ai...
61dcfa6afd6ec7dd0abb5525187938d6ab978996
3,641,301
def convert_spectral_kernel_quint(sequences, list_seq_to_id): """ Return a list seq of nb of time the seq in list_seq_to_id appear in sequence""" final = [] for j in range(len(sequences)): sequence = sequences[j] dico_appear = {seq: 0 for seq in list_seq_to_id} for i in range(len(seq...
49f727dd26822834bad2c9a448136288dc1c426c
3,641,302
def grad_of_marginal_fit(c, h, tau, epsilon): """Computes grad of terms linked to marginals in objective. Computes gradient w.r.t. f ( or g) of terms in https://arxiv.org/pdf/1910.12958.pdf, left-hand-side of Eq. 15 (terms involving phi_star) Args: c: jnp.ndarray, first target marginal (either a or b in...
38b6b57766c97f8eda72162b6919e48c235cd880
3,641,303
def SuggestField(**kwargs): """ Query 'foo' to get the TextField, or 'foo.raw' to get the KeywordField, or 'foo.suggest' to get the CompletionField. """ return fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField(), }, ...
57f673bbc310a22432178ee078c8f5eec2355e12
3,641,304
import math def distance_on_unit_sphere(FoLat, FoLng, ToLat, ToLng): """ Convert latitude and longitude to spherical coordinates in radians.""" phi1 = math.radians(90.0 - FoLat) phi2 = math.radians(90.0 - ToLat) theta1 = math.radians(FoLng) theta2 = math.radians(ToLng) """Compute spherical d...
98c9294697e36c5b45cd165ba96529187f2750de
3,641,305
import pandas # noqa def check_pandas_support(caller_name): """Raise ImportError with detailed error message if pandsa is not installed. Plot utilities like :func:`fetch_openml` should lazily import pandas and call this helper before any computation. Parameters ---------- caller_name : ...
f3d484bb3a5dbca43a81cca83b7343e1fcd7cbcf
3,641,306
def summarize_sequence(summary_type, hidden, d_model, n_head, d_head, dropout, dropatt, input_mask, is_training, initializer, scope=None, reuse=None): """Summarize hidden sequence into a vector.""" tf.logging.info("===== Sequence summary =====") tf.logging.info(" - ...
50dd0e72c15adfa522847cb822e897c9892cd1cf
3,641,308
def encode_line(line, vocab): """Given a string and a vocab dict, encodes the given string""" line = line.strip() sequence = [vocab.get(char, vocab['<UNK>']) for char in line] sequence_length = len(sequence) return sequence, sequence_length
feb14d86dd6c219d57cffc4cd9d90d16c4e9c987
3,641,309
import math def get_like_from_mats(ky_mat, l_mat, alpha, name): """ compute the likelihood from the covariance matrix :param ky_mat: the covariance matrix :return: float, likelihood """ # catch linear algebra errors labels = _global_training_labels[name] # calculate likelihood like ...
8fb7842547ecee25425bdaf920ff69d3386b920b
3,641,310
def engulfing(data: pd.DataFrame): """ engulfing Positive numbers are multi-side, negative numbers are short-side 0 is abnormal, meaning that the ratio of the absolute value of the current Candle up or down to the previous one is more than 10 times. For machine learning convenience, a floating point...
2974a62afa6b77ae2d8d02b35d7293362dd90927
3,641,312
def filter_matches(kp1, kp2, matches, ratio = 0.75): """ This function applies a ratio test :param kp1: raw keypoint 1 :param kp2: raw keypoint 2 :param matches: raw matches :param ratio: filtering ratio :return: filtered keypoint 1, filtered keypoint 2, keypoint pairs """ mkp1, mkp2...
a54d96e092019b9629852b1bf57511f9994aba46
3,641,314
import itertools def add_derived_columns( data: pd.DataFrame, differences: bool = True, second_differences: bool = True, multiplications: bool = True, rolling_means: int | None = 10, rolling_stds: int | None = 10, mean_distances: bool = True, ) -> pd.DataFrame: """This will create many...
080f3853f67ead678c55a3c95bf2a1c19614452c
3,641,315
from typing import List def parse_query( query: List[str], format, use_youtube, generate_m3u, lyrics_provider, threads, path_template, ) -> List[SongObject]: """ Parse query and return list containing song object """ songs_list = [] # Iterate over all search queries a...
a58e5bd6acf2c12de7eb7fae7824aab924188c26
3,641,316
def assert_address_book(address_book): """Fixture returning an object providing a custom address book asserts.""" return icemac.addressbook.testing.AddressBookAssertions(address_book)
fd9197472c86a59dd1c52dad14febe1a0b318c85
3,641,318
def make_shell_context(): """Open shell.""" db = get_db() return {"db": db, "Doi": Doi, "Url": Url, "FBRequest": FBRequest}
996988c06aa8039c7689126360ce0fea886ab392
3,641,319
import re def get_version(): """ Extracts the version number from the version.py file. """ VERSION_FILE = 'fleming/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError('Un...
b50df998254d83bd48d7a5c0863ba89b29ab529b
3,641,320
import math def distance(s1, s2): """ Euclidean distance between two sequences. Supports different lengths. If the two series differ in length, compare the last element of the shortest series to the remaining elements in the longer series. This is compatible with Euclidean distance being used as an u...
61c308da89b98b4bbde1bba690c86559fd5e1400
3,641,322
import re def valid_attribute(attr_filter_key, attr_filter_val, hit): """Validates the hit according to a filter attribute.""" if (attr_filter_key != "None") and (attr_filter_val != "None"): try: # If key for filtering is not correct or doesn't exist-> error # should be ignored...
c7480008f24e011f0803d82f1243a5d00c5a4030
3,641,324
def encrypt_message(kx, ky, message): """ Encrypts a message using ECC and AES-256 First generates a random AES key and IV with os.urandom() Then encrypts the original message with that key Then encrypts the AES key with the ECC key NOTE: This means that plaintext will not have the same cip...
e4bd462e8724a85ed0e183e048203ff23e349f34
3,641,326
def mirror_notes(key_position: int) -> int: """ 指定したキーポジションを反転させた値を返します 引数 ---- key_position : int -> キーポジション 戻り値 ------ int -> キーポジションを反転したときのキーポジション """ return 512 - key_position
03ad894eca67405bb79cbf6ea1ecef12b19958ed
3,641,328