content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_role(): """Get the role of the current process""" return CUR_ROLE
dc4908bd5287952bd6ecd6a58f84e5e3007464e2
67,300
def generos(): """ Muestra las configuraciones para los generos """ grid = webgrid.WebGrid(crud) grid.datasource = db(db.generos).select() grid.pagesize = 20 #grid.fields = ['db.catmod.id', 'db.catmod.nombre', 'db.catmod.posicion'] #grid.filters = ['db.catmod.catmod', 'db.catmod.nombre']...
880ec4d7b5f9f7f848cc8d33c1a97a30adf72e99
67,301
def searcher(nlp: Language) -> TokenSearcher: """It returns a token searcher.""" return TokenSearcher(vocab=nlp.vocab)
26ec606d6eb2792be668f2fc0eb0ae09629591fc
67,302
def replace_value(data, value=0): """Replace specific values in array with NaN :param data: Array where values should be replaced :type data: NumPy.Array :param value: value inside array to be replaced with NaN, defaults to 0 :type value: int, optional :return: array with new values :rtype:...
501f7daca3942a9d28ebf95fb3285af77a4230d0
67,303
def random_csr(shape, density, sorted_): """ Generate a random qutip CSR matrix with the given shape, nnz density, and with indices that are either sorted or unsorted. The nnz elements will always be at least one (use data.csr.zeros otherwise). """ return qutip.core.data.CSR(random_scipy_csr(sh...
effe8ceb67e45ab08ff258f071c8109bc49dd853
67,304
import pickle def getScores(imgURLs, captionTexts, sep='\n'): """ The function """ modelpath = 'models/xgbr_1.pkl' model = pickle.load(open(modelpath, 'rb')) imgURLs = imgURLs.replace('\r','') captionTexts = captionTexts.replace('\r','') imgURLs = imgURLs.split(sep) captionTexts ...
5dd97f8c036cffbe31d1d954a12026e340c2126b
67,305
import socket def _get_vault_path(device_uuid, config): """Generate full vault path for a given block device UUID :param: device_uuid: String of the device UUID :param: config: configparser object of vaultlocker config :returns: str: Path to vault resource for device """ return '{}/{}/{}'.for...
d6b1aab6036f348560b8549584a4e0f4b51cb4bd
67,306
def prompt_timestamp(msg: str) -> NychthemeronTime: """Prompts the user to enter a timestamp to get a NychthemeronTime.""" while True: # Enter input loop. timestamp = input(msg) try: nt = parse_timestamp(timestamp) break # Exit the input loop if successful. exce...
161b93336fd97ea1f756de193a679716d5c26ea0
67,307
def slice2limits(slices): """ Create a tuple of min,max limits from a set of slices Parameters: * slices: list of slices Returns: Tuple of minimum and maximum indices """ mins = [s.start for s in slices] maxs = [s.stop-1 for s in slices] return mins,maxs
1196e67fea135fb3c363def9d5fe53a0ada9b0af
67,308
def get_element(traj_frag_molid, frame_idx, index): """ Parse atom label and return element Parameters ---------- traj_frag_molid: int Denotes trajectory id in VMD frame_idx: int Frame of simulation in trajectory fragment index: string VMD atom index Returns ...
90a73dab6a3c28d6d3338ebd61f742eab61fba2d
67,309
def init_correlation_wf(name="correlation_wf"): """ This workflow calculates betaseries correlations using a parcellation from an atlas. .. workflow:: :graph2use: orig :simple_form: yes from nibetaseries.workflows.analysis import init_correlation_wf wf = init_correlatio...
c35345fc0621a4bd3aa15c757f718d21b09f9e99
67,310
def solution(array, n_rotations): """ Returns the Cyclic Rotation of array with n_rotations positions to the right. """ n = len(array) n_rotations = n_rotations % n if n > 0 else 0 return array[n - n_rotations:] + array[:n - n_rotations]
6f5edc0c8ec3d0e58830466e61577e80a725a624
67,311
def lin_fall(x, max): """f(0)=1. Linear fall off. Hits 0 at max.""" return clip01((max - x) / x)
1f231f733551a61f34b7f94bcc3c09150a5e76f4
67,312
import uuid def get_promotion_lock(replica_set): """ Take a promotion lock Args: replica_set - The replica set to take the lock against Returns: A unique identifer for the lock """ lock_identifier = str(uuid.uuid4()) log.info('Promotion lock identifier is ' '{lock_identi...
e454a75ce7f85d28c1dcd42867bbc28ae967c121
67,313
import re def check_question(msg): """ 提问 :param msg: :return: """ return re.search('\?', msg) or re.search('?', msg) or re.search('吗?', msg)
3ac884d153a32586d5dfe197b597f6e125bed8eb
67,314
def count_all_problems_for_admin(): """Returns the number of all problems. Returns: The count. """ return _db.problems.find({}).count()
f80e032989735a75111dc3ab8c1db660ad72b2f7
67,315
def search_optimal_strike( table, v_cue=1, dt=0.02, dang=0.5, return_once_find=False, event_based=False, ): """Search optimal strike.""" simulate_func = simulate_event_based if event_based else simulate simulate_args = ({'return_once_pocket': True} if event_based...
8b04087c2470c0c5fd9f1f32cdd11c82b56de20f
67,316
import urllib def is_local(): """Returns True if called on a local development machine. Returns False if called on Google Cloud.""" global _is_local # pylint: disable=invalid-name if _is_local is not None: return _is_local try: # TODO(github.com/google/fuzzbench/issues/82): Get r...
c4f45483d82d14f183a7285492121d48c08dade1
67,317
def check_color(board: list, num=9) -> bool: """ Function check if in each color of board are unique elements. It there are function return True. False otherwise. >>> check_horizontal(["**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 12 *...
3a6e8418b227e8101f9a8d1338c79193da285bff
67,318
import yaml import json def load_data(file_path, use_yaml=True): """Load data from a given YAML file into a Python dictionary. :param file_path: path to your YAML file. :param use_yaml: use yaml or json :return: contents of the file as Python dict. """ with open(file_path, "r") as f: ...
b136e16cd614cfdb3ca791a6d64d513cf52dbf7c
67,319
import gettext def update(id): """Change user settings. --- post: summary: Change user settings description: > Update a role to change its display name, or to define a new login password. Users can only update roles they have write access to, i.e. their own. param...
8a084ac0a58a421e92447a51997ed3815df34a24
67,320
def load_n_z(block, sample='wl_number_density'): """ Load the n(z) profile in each bin as a 2d array """ num_den = sample n_z = [] N_zbins = block[num_den, 'nbin'] for i in range(1, N_zbins + 1): n_z += [block.get_double_array_1d(num_den, 'bin_%d' % i)] n_z = np.array(n_z) z = bloc...
a2a2db598f31bd3f931042e5bb5dfee1f356f322
67,321
import time def retry_on_exception_exponential_backoff(exceptions, initial_delay=0.1, total_delay=15, exponential_factor=2): """ Retries with exponential backoff. :param exceptions: The exceptions that we will catch and retry on. :type exceptions: list[Exception] :param initial_delay: num seconds...
c642c383e1f9ef6b82bb01761abd1b1efda1ce4f
67,322
def parallax_to_scale(p_meas, p_err, snr_lim=4.): """ Convert parallax flux density scalefactor `s ~ p**2`. Parameters ---------- p_meas : float Measured parallax. p_std : float Measured parallax error. snr_lim : float, optional The signal-to-noise ratio limit used...
64aa4290e5166787ac8f2f1de96e421fc9e183c4
67,323
def install_msaccess(dataset, file='access.mdb', table_name='[{db} {table}]', data_dir=DATA_DIR, debug=False, use_cache=True, force=False, hash_value=None): """Install d...
b157f6376e2080648fc8adc30a29864eac165e3d
67,324
def levenshtein_distance(s1: str, s2: str) -> int: """Returns the levenshtein distance between two strings""" # https://stackoverflow.com/a/32558749 if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2 + 1] for i1...
1b70d6e2b6241e8b0296c3698aae322bb081fe8c
67,325
from typing import Iterable def validate_multiple_choice_param( params: RequestParams, key: str, choices: Iterable ) -> RequestParams: """Verify that a multiple-choice request parameter contains valid value(s); if not, raise an error. **Used for endpoint-specific params.** Returns: Parame...
5986b2fbed3756137d11462a9c9551418342f926
67,326
def mqtt_client(axis_device) -> MqttClient: """Returns the mqtt_client mock object.""" return MqttClient(axis_device.vapix.request)
00568fe250132b5ec5fbcef87b3515780ed85cbf
67,327
import os def scm_install_package(source, for_qc=False, override=False): """ Compile the source code and generate a skeleton for production use. This method will take your active directory and :param source: s :param for_qc: :param override: `bool` ...
d2f6d494d48eaf7ff780848379004cae52920d41
67,328
from typing import Dict def loads(text: str) -> Dict: """ Parses a text in Gura format :param text: Text to be parsed :raise: ParseError if the syntax of text is invalid :return: Dict with all the parsed values """ return GuraParser().loads(text)
b7c9dc4d6a1c4fadba47b562c0a026d68e46acd3
67,329
def allocate_lan_networks(root, service, username, logger): """ Main logic for allocating lan networks for remote sites""" lan_pool = service.lan_pool # 10.16.0.0/16 pool_name = get_lan_pool_name(service) prefix = lan_pool.split('/')[0] # 10.16.0.0 prefix_len = lan_pool.split('/')[1] # 16 v...
8a973c8f78f4685311df643c813e3af2bbea464a
67,330
import math def flinn(stream, noise_thres=0): """ Computes the azimuth, incidence, rectilinearity and planarity after the eigenstructure decomposition method of [Flinn1965b]_. :param stream: ZNE sorted trace data :type stream: List of ZNE sorted numpy arrays :param noise_tresh: Variance of th...
63b6895ff3945be93494b2e4db801dc6d356dd3c
67,331
def _to_bool(value): """Simplified version of the bool filter. Avoids having a dependency on Ansible in unit tests. """ if value == 'yes': return True if value == 'no': return False return bool(value)
6e0da8b211ce638e19764a966c417841fafe2a5b
67,332
import click from datetime import datetime def upload(conf): """ Upload to remote and wipe out the local data. """ click.secho('UPLOAD SYNC IN PROGRESS - PLEASE DO NOT INTERRUPT - %s' % datetime.now(), fg='yellow') outcome = _clone(True, confDir = conf.confDir, confFiles = conf.confFiles, verbose = conf.v...
b3faf09469ad294071d09aaaa55b39653b88687f
67,333
import os def _process_single_file(file_path, language): """ Processes only one file from file_path and takes all items marked with language. Creates a .vtt file. Arguments: file_path: Path of file to process. language: The language of the file to process. Returns: None ...
d5d28ea48fa19a3038637695b6acf60deb3e7961
67,334
def get_mel(filename): """Process loaded audio to mel-spectrogram.""" audio, _ = load_wav_to_array(filename) audio_norm = audio / config.au_max_wav_value audio_norm = np.expand_dims(audio_norm, 0) melspec = _stft.mel_spectrogram(audio_norm) melspec = np.squeeze(melspec, 0) return melspec
f621821d61696d5f97a6ad203e9d31cd737fec70
67,335
import math def tan(x): """tan(x) Return the tangent of x.""" x = complex(x, 0) sr = math.sin(x.real) cr = math.cos(x.real) shi = math.sinh(x.imag) chi = math.cosh(x.imag) rs = sr * chi is_ = cr * shi rc = cr * chi ic = -sr * shi d = rc*rc + ic * ic real = (rs*rc ...
f2aedcff8f7fbce85169dab263163aa461367a53
67,336
from typing import Union from typing import Optional from typing import List from typing import Dict from pathlib import Path import json def compose_config( config_path: Union[str, PathLike], config_name: str, job_name: str, serialization_dir: Optional[Union[str, PathLike]] = None, config_overrid...
0284e10e9ef78e0c5a1c21b9619a95bb30c18440
67,337
def melted_power_ratio(index_df:PandasDf, power_df:PandasDf, freqs:list, selected_categories:list): """ Get power ratio and melt dataframe for seaborn plotting. Parameters ---------- index_df : PandasDf, experiment index power_df : PandasDf, contains pmat and frequency vectors for every row of ...
f427c2b5cab256f1101634d9f06e8bca6e3a9c46
67,338
def CreateInstanceDrbd8(nodes, fail=False): """Creates an instance using disk template 'drbd' on the given nodes. @type nodes: list of nodes @param nodes: nodes to be used by the instance @return: the created instance """ assert len(nodes) > 1 return _CreateInstanceByDiskTemplateRaw( ":".join(n.prim...
14205ca5d1a871247a3fd17ab946b3e6d8f8d037
67,339
def get_fn_at_x(xgrid, fn, at_x): """ Returns function at x Args: xgrid np.array(n_grid): Grid where function was evaluated fn np.array((n_samples,n_grid)): Multiple function evaluations at xgrid at_x float: Value closest to the desired function evaluation Returns: ...
5d70e4d720340c156a2c3987f2506523cb1c514e
67,340
def getNet(chrom, loops, genes, pdis=2000, gap=1): """ Get the enhancer/promoter network for one chromosome. """ #step 1 get merged anchors anchors = stichAnchors(chrom, loops, margin=gap) #step 2 annotate anchors nanchors = {} ts = np.array([[tss] for tss in genes.keys()]) tree = ...
ce367e200c0156302db7fd5e4f56e14f7c220be8
67,341
import requests def get_day_prices(date, rate=None): """ Get PVPC prices for specific date. Args: date: Datetime obj of date to recover information for. rate: Optional string. If None all available rates will be added to the answer. If one is selected just that will be return. ...
556431f368d14b24af7df1290b37359d08109d25
67,342
import random def get_best_move(board, scores): """ Function that computes the best move for the machine given the actual board state """ max_score = max(scores[row][col] for row, col in board.get_empty_squares()) candidates = [(row, col) for row, col in board.get_empty_squares() ...
afabd281ad1547b118cab10ccc912bdf4956f9c4
67,343
def kalman_filter(protein_at_observations,model_parameters,measurement_variance,derivative=True): """ Perform Kalman-Bucy filter based on observation of protein copy numbers. This implements the filter described by Calderazzo et al., Bioinformatics (2018). Parameters ---------- protein_at_obse...
68c0ee11edea65ddea3d6596887f0d0d5d8297b8
67,344
import requests def get_data(coin, currency, exchange): """ Fetch all time data from cryptocompare API :param coin: crypto coin (BTC, XRP...) :param currency: fiat (CAD, USD, EUR...) :param exchange: name of the exchange :return list[dict]: returns the all time data from the coin/currency prov...
5b6d48399974b2872e22b8e98b92c779799b1955
67,345
def recognize_speech_from_mic(recognizer, microphone,language): """Transcribe speech from recorded from `microphone`. Returns a dictionary with three keys: "success": a boolean indicating whether or not the API request was successful "error": `None` if no error occured, otherwise a str...
05156544e1c69fee866e17508e19b10dbee27faf
67,346
from typing import Dict def handle_response(res: Response) -> Dict[str, object]: """ Returns the sdk JSON response :param res: A string url endpoint. :type: str :return: Dict[str, object] """ try: json = res.json() except ValueError as e: handle_parse_error(e) if ...
2d326d81926ba2fbb44612bb76f56bc7406c6bba
67,347
def encode_tag_ref_str(self, node, parent=None, attr_index=None): """This function is the same as encode_string, except that when a halo reference string has zero length, the string doesnt actually exist. It's not just a delimiter character, the string isn't stored at all. To make it work, we instead re...
e6a3acc3691f122e3325fa70eb9ab427456e0edb
67,348
def vapour_pressure_deficit(es, ea): """ VPD - Vapour Pressure Deficit :param es: :param ea: calculated by vp_from_rhmin_rhmax() :return: """ return es - ea
cb1d22a236081b3de3f080f8f2e2acb64543620f
67,349
def get_pca_mean_and_pre_whitener_epochs(epochs, picks, decim, pre_whitener): """Aux method based on ica._fit_epochs from mne v0.15""" if picks is None: picks = _pick_data_channels(epochs.info, exclude='bads', with_ref_meg=False) # filter out all the channels the raw wouldn't have initialized ...
ed27c41fb68b83d2897dcd9ca7c3a6044ec454eb
67,350
def _run_vagrant_command(node_id, args=[], creds={}): """ args: A tuple of arguments to a vagrant command line. e.g. ['up', 'my_vm_name', '--no-provision'] """ cd = 'cd "{}/{}"'.format(HOST_NODES_DIR, node_id) command = ['vagrant'] + [arg for arg in args if arg is not None] return _host_ssh...
91822162ba28a4c6b9bbe9ba4328a2d956223696
67,351
async def _deleteIEXCloudAsync( url, token="", version="stable", filter="", format="json" ): """for iex cloud""" return await _deleteIEXCloudBaseAsync( base_url=_URL_PREFIX_CLOUD, url=url, token=token, version=version, format=format )
85bb12c86dbf2537cd8a129b31aad2644e79ddf2
67,352
def evolve_lindblad_discrete(evolution_time, initial_densities, system_eval_count, controls=None, cost_eval_step=1, costs=list(), hamiltonian=None, ...
f52b9bd15c6fd137f1f9b504f78c32577f2db198
67,353
import asyncio def get_next_valid_seq_number(address: str, client: SyncClient) -> int: """ Query the ledger for the next available sequence number for an account. Args: address: the account to query. client: the network client used to make network calls. Returns: The next val...
c3dd4d0427a39ba8e612a5689a1648567fd4276b
67,354
from pathlib import Path import logging def readMad_hdf5 (filename, paramstr): #timelims=None """@author: Michael Hirsch / Anna Stuhlmacher madrigal h5 read in function for the python implementation of GeoData for Madrigal Sondrestrom data Input: filename path to hdf5 file list of parameters to lo...
ed22f485e1cd9a7f155c03fa353250843534d1d7
67,355
from operator import concat def gumbel_sigmoid(logits, temperature, dtype=tf.float32, seed=0): """Gumbel Sigmoid Layer.""" logits = concat([logits, tf.zeros_like(logits)], 1) prob = gumbel_softmax(logits, temperature, dtype=dtype, seed=seed) return prob[:, 0]
57871305349c8582e67f156f497c2cf9f4370f22
67,356
def rfft(data, **kargs): """ rfft wrapper """ interface = fft_interface_select() return fft_interface_format(interface.rfft, data, **kargs)
e8a0bfa89e02a956a07c5701386a3b9b1455ec93
67,357
def purefa_argument_spec(): """Return standard base dictionary used for the argument_spec argument in AnsibleModule""" return dict( fa_url=dict(), api_token=dict(no_log=True), )
bc8302564bb397b523fde20a986465f3ecb496dd
67,358
def get_release_id(request): """Get the environment ID to release, from request. :param request: The falcon request object. :type request: :obj:`falcon.request` :return: The ID of the environment to release. :rtype: str """ return request.get_param("release")
c6d9aa4907ea0f150ac86930560fca59b7388484
67,359
def get_submission_relations(doc_id, submission_id): """ Get suggested mentions for a document. """ relations = [] for row in db.select(""" SELECT subject, relation, object, provenances, confidence FROM submission_relation WHERE doc_id = %(doc_id)s A...
0b3b3c8fa8766690d9abf4c942ccbe2eb85b63cf
67,360
def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos))
5f06ba50a29d680e992fcffc813d374eb6da4867
67,361
def train_GMM(data, cluster_num): """ 训练混合高斯模型 """ model = GaussianMixture(n_components=cluster_num, covariance_type='full') model.fit(data) return model
e58325939fbe8e3394b19528eb783cb87eb8938e
67,362
def pf_rcc(): """ pf(failed test t) is determined by the root cause param in the change where t fails root cause is localized through manual inspection """ freq = {} failures, misconfs = parsing_utils.failure_map() for img in failures: for t, rootcauses in failures[img][C_EFFECTIVE]...
e7cbf6b64b5c0d677be7bce0c3826c87f1c78c73
67,363
import logging def get_markers(img, mode): """Get initial labels for segmentation.""" assert img.ndim == 4 markers = np.zeros(img.shape[0:3], dtype=np.int16) if mode == 'DWI': # Based on absolute value thresholds (non-scaled image). bg, fg1, fg2 = np.percentile(img, 50), 1400, 1600 ...
eb31fa5a2549eba2bf03b3a3b86689c0808558e9
67,364
def sum_fun(x, backend): """ Base function for summing all elements in a tensor """ func = "sum" if backend == "tensorflow": backend = "tensorflow.math" func = "reduce_sum" return get_func(func, backend)(x)
6c5231f67ed3f464dd7bf3bbbe3b0ed6c6fb6740
67,365
import os def upload(): """Page for uploading of images""" form = UploadForm() if form.validate_on_submit() and 'upload' in request.files: for f in request.files.getlist('upload'): filename = secure_filename(f.filename) f.save(os.path.join(app.config['UPLOAD_PATH'], filenam...
e8c45b9bc02d088007c1a7a5271bfc8ffa5ec9d6
67,366
def measure_naptan_groups(gdf, naptan_column_name="LocalityName"): """[summary] this function measures the number of groups present within the given geodataframe, when groupbed the [default LocalityNames] Args: gdf ([type]): [description] naptan_column_name ([type]): [description] Ret...
725ce929fb19f0e2fdf051f6daf9c1d86e125d0f
67,367
def CreateParser(): """Expose _CreateParser publicly.""" # Name _CreateParser is needed for commandline library. return _CreateParser()
888ec2237c0e4bda8c44f5fece4f184f1e870e2c
67,368
def update_dataset(dataset_id: int, request: schemas.DatasetUpdate, db: Session = Depends(deps.get_db), current: model.User = Depends(deps.get_current_user)): """ Update a dataset. """ dataset = crud.dataset.get(db=db, id=dataset_id) if datase...
5a72a30b0a27cd9df97c6131cd76785fc5050504
67,369
def calculate_ts_stability_index_batch(ts, **kwargs): """Returns series with stability index calculated for every point of ts, where possible""" si_values = [] timestamps = [] for time, row in ts.iterrows(): ts_history = ts[:time].iloc[:-1] try: si_value = calculate_ts_stabil...
a9bfaa3e3d8393443c1113d5356616067795ca0b
67,370
import click import functools def ip_lookup_command(function): """Decorator that groups decorators common to ip and quick subcommand.""" @click.command() @click.argument("ip_address", callback=ip_addresses_parameter, nargs=-1) @click.option("-k", "--api-key", help="Key to include in API requests") ...
1da900e8fd96e486f58e10708c99e797a818905a
67,371
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV def _is_parameter_search_estimator(estimator): """ :return: `True` if the specified scikit-learn estimator is a parameter search estimator, such as `GridSearchCV`. `False` otherwise. """ parameter_search_estimators = [ ...
24a1c51cea98b36923d6ac827d1c4481d75bb460
67,372
from typing import Dict from typing import List import re def clean_utterance(utterance: Dict[str, str], remove_english: bool = False, english_words: set = None, punctuation: str = None, special_cases: List[str] = None) -> (List[str], int...
362b835ec894495d74c984b082bb173ca2e27e1a
67,373
def get_all_functiondef(root): """ Get all FunctionDef nodes :param root: :return: """ if root['name']=='FunctionDef': # block(FunctionDef) begin id begin_id=root['id'] end_id=get_end_id(root) return 'begin:%s,end:%s'%(begin_id,begin_id+end_id-1) else: ...
b6687059c958d49795f0d2fb521bd8ca488c5507
67,374
def bookmark_json(userkey, urlhash): """ Serialise bookmark to json """ try: bookmark = Bookmark.get( Bookmark.url_hash == urlhash, Bookmark.userkey == userkey, Bookmark.status == Bookmark.VISIBLE ) return jsonify(bookmark.to_dict()) except Bookmar...
30321366ee5a32484664599d9223ff56ee0768e9
67,375
from typing import Mapping def betaReduce(lhs, lhsEnv, rhs, rhsEnv): """β-reduction: (λV.M)N → M[V := N]""" exp = lhs.exp if isinstance(exp, Mapping): return (exp.exp, Env(Mapping(exp.var, clos(rhs, rhsEnv)), lhsEnv)) else: return (exp, Env(clos(rhs, rhsEnv), lhsEnv))
1bd36a551280721596e502be0db2e5aa0a0b6d8b
67,376
def _check_for_iocs(loop, context, indent): """ Check the variables modified in a loop to see if they were set to interesting IOCs. """ indent_str = " " * indent lhs_visitor = lhs_var_visitor() loop.accept(lhs_visitor) lhs_var_names = lhs_visitor.variables ioc_str = indent_str + "# C...
f9d4a8fa2e1953314cb422882a2eb6d1e1f7b7eb
67,377
import ssl import concurrent async def patch( uri: str, headers: t.Dict[str, str] = {}, body: t.Optional[bytes] = None, json: t.Union[t.Dict[str, t.Any], JsonApiData] = None, query: t.Dict[str, t.List[str]] = {}, timeout: t.Optional[float] = None, blocksize: int = 8192, datacls: t.Type...
32101f2a036ee846fdd8a0c5ed7873f5726a3bfe
67,378
def edit_orcid(request): """ Send a user to orcid.org for authorization to link to their ORCID account, then redirect them to views/auth_orcid to save their iD and other token information. Also provide the option to unlink their ORCID account from their account. """ if request.method == 'POST'...
2305ac8e38430919a807bdd0612115992b416065
67,379
import math def calculate_distance(psi, angle_in_degrees): """ Calculate the distance the mudball flies. """ angle_in_radians = math.radians(angle_in_degrees) distance = .5 * psi ** 2 * math.sin(angle_in_radians) * math.cos(angle_in_radians) return distance
47eb9acb71f5c11b26002ec38e37410db62c2e05
67,380
import json def clear_dataflow_run(dataflow_run_id:str): """ Clear an orphaned dataflow run. :param dataflow_run_id: :return: """ payload = {"orchAction": "clear_dataflow_run", "dataflow_run_id": dataflow_run_id} json_payload = json.dumps(payload) pickledJsonObj = __bo...
453fee04e72c54b7f2891f5e7f5b89d913778f42
67,381
def custom_path_fs_io_manager(init_context): """Built-in IO manager that allows users to custom output file path per output definition. It requires users to specify a base directory where all the step output will be stored in. It serializes and deserializes output values (assets) using pickling and stores ...
04aeaa321d0b998959401ca6190cc45385edae79
67,382
def sghmc_naive_nomh_noresample_multi(du_hat_func, epsilon, nt, m, M, V, theta_init, r_init, formula): """ This is a function to realize Naive Stochastic Gradient Hamiltonian Monte Carlo without Metropolis-Hastings correction in multidimensional cases without resampling procedure. """ B = 1/2*...
e704394e1f7f8960bea804e6f1a9188acc069ff5
67,383
import pathlib import json def load_json(filepath): """ Loads the metrics in a dictionary. :param log_dir: The directory in which the log is saved :param metrics_file_name: The name of the metrics file :return: A dict with the metrics """ if isinstance(filepath, pathlib.Path): fil...
1dd8ff7822228bc0173a66df626902a723338d55
67,384
def super_scrub(data): """Run words through a comprehensive list of filtering functions. Expects a dictionary with key "words" """ for technique in data['words']: data['words'][technique] = normalization.uniquify( normalization.remove_odd_sounding_words( normalizatio...
d81557232ac99b89d24144c5d44bd94d41340d87
67,385
from typing import Callable import random def choose(option1: Callable = lambda: None, option2: Callable = lambda: None): """ Randomly run either option 1 or option 2 :param option1: a possible function to run :param option2: another possible function to run :return: the result of the function ...
0f0ecbc945de9f6d5698cd86103265eccf5708e6
67,386
def compute_embeddings(encoder, data_batches): """Computes sequence embeddings according to a specified encoder.""" vectors = [] for batch in iter(data_batches): X, Y = batch X_embedded = encoder(X) for vec in np.array(X_embedded): vectors.append(vec) vectors = np.ar...
5c9d6e9bb617e43522044255948639c01d6b06a4
67,387
def while_array_parser(self, desc, node=None, parent=None, attr_index=None, rawdata=None, root_offset=0, offset=0, **kwargs): """ """ try: orig_offset = offset if node is None: parent[attr_index] = node = desc.get(NODE_CLS, self.node_cls)\ ...
365d8d115f4b677177f1214c78d4957a78745252
67,388
def get_all() -> [User]: """ Helper function to return all users :returns: all users. """ return User.objects.all()
79864d2a862610bed414f2ad7cebbee20055e638
67,389
def get_category(id): """ Get category. """ category = Category.query.get(id) if category is not None: response = {"category": category.to_dict()} return make_response(jsonify(response), 200) abort(404)
15e1030b4c3b6e5d00f7697cd7e392a5bc5fcd8d
67,390
def get_repo_service(): """Factory method that returns configured RepoService instance. If the service is not configured, returns None. Also acts as a mocking point for unit tests. """ cas_service = cas.get_cas_service() if not cas_service: # pragma: no cover return None return RepoService( ca...
75966851961208486c1d28e5051f30266dfe7d0d
67,391
from typing import List def search_etfs(to_search) -> List[str]: """Search for an etf string in list of ETFs Parameters ---------- to_search: str String to match Returns ------- matching_etfs: List[str] List of matching ETF names """ all_symbols, all_names = get_a...
f56972605a45c5308a311eef1dac5ea34736aa2d
67,392
def separable_hnn_siren(input_h_s=None, input_model=None): """ Separable Hamiltonian network using Siren network. :return: """ if input_h_s: h_s = input_h_s model = input_model else: network = SirenNet( dim_in=2, dim_hidden=100, dim_ou...
08a1ef7d25304fcbd1d5ef568a420b70e0da0464
67,393
async def update_password(username: str = Form(...), old_password: str = Form(...), new_password: str = Form(...)): """パスワードの更新""" res = search_username(cur=cur,username=username) if res == None: raise HTTPException(status_code = 400,detail="ユーザーが登録されていません。") if not verify_password(old_pass...
bbec78a71eaf91fa92eeb1dd6d0f19fb7b767f63
67,394
import time def num_to_str_data(str_date: int) -> str: """ num to str format :param str_date: time of int format :type str_date: int :return: format time :rtype: str """ str_date = str_date / 1000 str_date = time.localtime(str_date) strp_time = time.strftime("%Y-%m-%d %H:%M:%S"...
e3fb56132a9d365d7bbc89e11e010d0d1ed19ea9
67,395
def transform_response_to_context_format(data: dict, keys: list) -> dict: """ Transform API response data to suitable XSOAR context data. Remove 'x-ms' prefix and replace '-' to '_' for more readable and conventional variables. Args: data (dict): Data to exchange. keys (list): Keys to fi...
34f1a613654deb71581bcd33757b8741840ae44f
67,396
def GetsoftwareVersions(node, layers='core') : """Get the schema:softwareVersion(s) we find on this node (or [] ), within any of the specified layers.""" return GetTargets(Unit.GetUnit("softwareVersion", True), node, layers=layers )
851678659540482c4b289410f1e9407c97990fbc
67,397
from typing import List import re from typing import Iterator def txt_channel_finder(bot: Red, chaninfo: str) -> List[discord.TextChannel]: """ custom text channel finder """ _id_regex = re.compile(r"([0-9]{15,21})$") def _get_id_match(argument): return _id_regex.match(argument) matc...
f751af05bdcdf207a42fd08e77fc780e14478fef
67,398
import torch def calculate_gradcam_metrics(no_norm_gc_mask_numpy: torch.Tensor, segm: torch.Tensor): """ Measure gradcam metric @param segm - true mask, shape B x 3 x H x W @param no_norm_gc_mask_numpy - Grad-CAM output w/o normalization, shape B x 1 x H x W @return sum of gradcam attention of ev...
4d3ab9c9a694b88ef83efcc94271d21d0c1f8e17
67,399