content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_json_objects_async(urls): """retrieve a dict with urls and corresponding jsons. The data is fetched asynchronously to speed up the process.""" pool = ThreadPool(processes=4) url_json_dicts = pool.map(request_url_json_dict_from_url, urls) pool.close() pool.join() return url_json_dict...
942a8f25235359e240812a20bd16e5265d84c351
56,100
def refine_peak(tsmap, pix): """Solve for the position and uncertainty of source assuming that you are near the maximum and the errors are parabolic Parameters ---------- tsmap : `~numpy.ndarray` Array with the TS data. Returns ------- The position and uncertainty of the source,...
102953098f6245bc31c65a1d7826fb76c182ffb2
56,101
import types from typing import Dict from typing import Any from typing import List def merge_two_reconstructions( r1: types.Reconstruction, r2: types.Reconstruction, config: Dict[str, Any], threshold: float = 1, ) -> List[types.Reconstruction]: """Merge two reconstructions with common tracks IDs....
82914428ec6d45a7627ce59c788df952d5e0ff29
56,102
def idtostr(obj, membre='id', defaut='0'): """renvoie id d'un objet avec la gestion des null @param obj: l'objet a interroger @param defaut: la reponse si neant ou inexistant @param membre: l'attribut a demander si pas neant""" try: if getattr(obj, membre) is not None: retour = s...
35cc093b054b1eaa1a0417530dc940fb79232c07
56,103
def draw_values(params, point=None, size=None): """ Draw (fix) parameter values. Handles a number of cases: 1) The parameter is a scalar 2) The parameter is an RV a) parameter can be fixed to the value in the point b) parameter can be fixed by sampling from the RV ...
8d436911003685301448edb9353ec0e533f4fccc
56,104
def duplicate_detection( spark, idf, list_of_cols="all", drop_cols=[], treatment=False, print_impact=False ): """ As the name implies, this function detects duplication in the input dataset. This means, for a pair of duplicate rows, the values in each column coincide. Duplication check is confined to th...
862bfe5b3fbb14576e323b48b7209633082ef632
56,105
import torch def warp_with_mask(x, flo, masked_flow): """ warp an image/tensor (im2) back to im1, according to the optical flow x: [B, C, H, W] (im2) flo: [B, 2, H, W] flow mask: [B, C, H, W] """ B, C, H, W = x.size() # mesh grid xx = torch.arange(0, W).view(1, -1).repeat(H, 1) ...
3bdcbe496a816f1d3370737e61fda6d795da8fb9
56,106
import base64 def send_command( service_account_json, project_id, cloud_region, registry_id, device_id, command): """Send a command to a device.""" # [START iot_send_command] print('Sending command to device') client = get_client(service_account_json) device_path = 'projects/{}/loc...
507cacc4d41bd9282e4948e1fd328f3b8f72a442
56,107
import random import os import copy def convert_to_tf_records(raw_data_dir): """Convert the yt8m dataset into TF-Record dumps.""" # Shuffle training records to ensure we are distributing classes # across the batches. random.seed(0) def make_shuffle_idx(n): order = list(range(n)) r...
70ace89caf695bf3f7879a5f683b18335b0b2d68
56,108
def infer_joint_centers( markers: TimeSeries, /, segment: str, *, sex: str = 'M', ) -> TimeSeries: """ Infer joint centers based on anthropometric data. This function is aimed to be used on static acquisitions in quasi-neutral position. For the pelvis: C...
a8386ae9396d1b921ee1a6c1cdcc0a939be1de4f
56,109
import requests def get_observer_group_member(group_id=None, output='List'): """Gets data on observers in a group. If no group is requested, all is retrieved. :param group_id: [int] :param output: [string] 'List' or 'Dict' :return: [list] of class ObserverGroupMember or dictionary ...
887d770b1d51d3fb39bad3e5fcf3bdb4305e67cb
56,110
def fixture_categories() -> DatasetCategories: """ categories """ return DatasetCategories(init_categories=["ROW", "COLUMN"])
2ccc199e54406d57efbbbbc8052851287fc7851b
56,111
def create_disk(disk_name, source_image, size_gb, project, zone, wait_for_completion=False): """Create a disk.""" api = _get_api() operation = api.disks().insert( body={ 'name': disk_name, 'sizeGb': size_gb, ...
16c55de94346bf36c75f11a36bc192dac54ed659
56,112
from typing import List import ast def is_getting_element_by_unpacking(targets: List[ast.expr]) -> bool: """Checks if unpacking targets used to get first or last element.""" if len(targets) != 2: return False first_item = ( isinstance(targets[1], ast.Starred) and _is_unused_variabl...
84560e48d042a97863f2ac8ed6545b587d79bdd6
56,113
def file_is_text(file): """ Vérifie qu'un fichier est au format texte et non binaire :param file: Chemin vers le fichier :return: Vrai si le fichier est au format texte, faux s'il est au format binaire """ textchars = bytearray([7, 8, 9, 10, 12, 13, 27]) + bytearray(range(0x20, 0x100)) is_pl...
6a49486aa05e8627e7a0f6504e5c9b86c050df81
56,114
def ssd_warp_gt(batch_bboxes, batch_labels, bg_class): """Translates Ground truth boxes and labels into the internal format. :param batch_bboxes: Bbox coordinates :param batch_labels: Bbox labels :param bg_class: ID of background label :return: List of boxes """ assert batch_bboxes.shape[0...
8b1f15eee23d44065548bc9ed807d5114a000955
56,115
import os import requests def download_file(url, local_filename=None, chunk_size=1024, overwrite=False): """ Download the file at the given URL to the specified local location. This function is adapted from: https://stackoverflow.com/questions/16694907 Parameters ---------- url: string T...
65db8e5fd23d7fb4d02d35947b978dbff87bb96e
56,116
import functools import inspect def try_except(text: str): """ Decorator to wrap code into try except with log. Based on try except Based on Logging :param text: the exception title to show in log file :return: return the expected result if no exception, else return None. """ def decorat...
d2d6892fcdfd14c0e3d313ea0ee858c3c909f5c0
56,117
def on_color(clip, size=None, color=(0, 0, 0), pos=None, col_opacity=None): """ Returns a clip made of the current clip overlaid on a color clip of a possibly bigger size. Can serve to flatten transparent clips (ideal for previewing clips with masks). :param size: size of the final clip. By de...
1c50288c82d8148152109706c729f595c64cfea8
56,118
import typing def pretty_repr( src: typing.Any, indent: int = 0, no_indent_start: bool = False, max_indent: int = 20, indent_step: int = 4, ) -> str: """Make human readable repr of object. :param src: object to process :type src: typing.Any :param indent: start indentation, all ne...
5f65beab2f8c04197a62f5aecf379b59475407fd
56,119
def geoEro(*args): """ Function renamed. Use: r = geoErode(...) """ return geoErode(*args)
5a8253eee8dca470751fda8bfec52c8a01eba266
56,120
def EdgeDetect(clip, mode="kirsch", lthr=0, hthr=255, multi=1): """ Generates edge mask based on convolution kernel. The result of the convolution is then thresholded with lthr and hthr. Args: mode (string) - Chooses a predefined kernel used for the mask computing. Vaild...
037f6d89dc712b2e31c97cd4a73e98044409db9c
56,121
from sys import executable import subprocess def run_extension(path=None, **kwargs): """ USTやラベルを加工する外部ソフトを呼び出す。 """ # path = path.strip('"') if path is None: return None # パスに含まれるエイリアスを展開 path = parse_extension_path(path) if not exists(path): raise ValueError(f'指定されたファ...
f613330812f44603b71de517256283118537d3e2
56,122
def modifies(repo, subset, x): """``modifies(pattern)`` Changesets modifying files matched by pattern. """ # i18n: "modifies" is a keyword pat = getstring(x, _("modifies requires a pattern")) return checkstatus(repo, subset, pat, 0)
a28af7d2872527b5b2116151398ee1c7a0ce10d4
56,123
import sys import os def get_default_home_dir(): """ Return the home directory (valid on linux and windows) """ if sys.platform != 'win32': return os.path.expanduser('~') def valid(path): if path and os.path.isdir(path): return True return False def env(name): ...
d7d6ead0552b43c80fa4eae02fa4bc62ca3159a6
56,124
def tnr(label, prediction): """calculate true negative rate between label and prediction TNR = TN / (TN + FP) Parameters ---------- label : tensor tensor of shape [batch_size, height, width, depth] containing the ground truth label prediction : tensor tensor of shape [batch_size...
a1947f3e271d32080acd894efd6f3611397d08b8
56,125
def newrelics(draw): """TODO support all optional args""" metric = draw(ascii()) filter = draw(filters()) return flow.Newrelic(metric, filter=filter)
9398d9fba03baa1d087183326ebedd9d80a8a6be
56,126
def transform_editor_features(metadata): """Transform editor-related features into metadata; editor uses are expressed as proportions of n_total_chgset, a proportion of local change sets is computed as a new feature and an ecdf transformation is applied on n_chgset and n_total_chgset Parameters...
0dbbd52f1909cd3ac750715867ae8886e7927c97
56,127
def SceneShadowManagerEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
8471344512601902ffe0a61627603c1a5fbbad30
56,128
def invert_windows(windows, start=None, stop=None): """ Select all of the time except that covered by the given windows. You can use this to define a baseline time period that is far enough from key events: # select all time in the series excluding any 500 ms window after an induced spike baseline_...
ab0f534f933a805414155ddae652833ac5d63ab0
56,129
import os def to_credit_rating_list_parallel(uni_id_list: list) -> list: """ """ futures = [] credit_rating_list = [] pool = Pool(os.cpu_count()) for i, uni_id in enumerate(uni_id_list): futures.append(pool.apply_async(func=to_credit_rating, args=(uni_id,))) pool.close() po...
551e47865372fdfda05f7e2d9c5df6ce4ac4ab27
56,130
def formatIntervalSeconds2(oSeconds): """ Flexible input version of formatIntervalSeconds for use in WUI forms where data is usually already string form. """ if isinstance(oSeconds, (int, long)): return formatIntervalSeconds(oSeconds); if not isString(oSeconds): try: ...
05c33963b9dc333193bd313544a5096074c9aa44
56,131
def staging_gateway(request, server_authority, superdomain, manager, gateway_options, gateway_environment): """Deploy tls apicast gateway. We need APIcast listening on https port""" kwargs = dict( name=blame(request, "tls-gw"), manager=manager, server_authority=server_authority, ...
553e20a44cddab33c5d40994b2d50b2a4c831a8f
56,132
from bs4 import BeautifulSoup import re def update_bnc_words(xml_path): """ Function to extract words from one XML file. input: xml_path (str): path to BNC XML file returns set of all words in file at xml_path """ with open(xml_path) as f: content = f.read() ...
06ca257ea85edf63f242061f162c1c8dce99967f
56,133
from typing import List def admission_control(data: List[DataPoint]) -> List[DataPoint]: """ :rtype: list :param list data: :return: """ final_data = [] for dp in data: if isinstance(dp.sample, str) and len(dp.sample.split(',')) == 20: final_data.append(dp) if ...
73bb0e8794df1e7fea5c99cc3471228d2ac15b79
56,134
def generate_ei(N, pE=0.8): """ E/I signature. Parameters ---------- N : int Number of recurrent units. pE : float, optional Fraction of units that are excitatory. Default is the usual value for cortex. """ assert 0 <= pE <= 1 Nexc = int(pE*N) Ninh = N - Nex...
1231968940fb0d913a55b84d42fc5d4eb2575427
56,135
from typing import Dict def create_login_internal_config(app: Application, storage: AsyncpgStorage) -> Dict: """ Creates compatible config to update login.cfg.cfg object """ login_cfg = app[APP_CONFIG_KEY].get(CONFIG_SECTION_NAME, {}) # optional! smtp_cfg = app[APP_CONFIG_KEY][SMTP_SECTION] ...
e2f3e171c03846df856c37e645d469a94d302242
56,136
def hotfilm_velocity(veff1, veff2, k1=0.3, k2=0.3): """For a pair effective velocities from wire 1 and 2, calculates u and w components.""" un = np.sqrt((veff1**2 - k1**2 * veff2**2) / (1 - k1**2 * k2**2)) ut = np.sqrt((veff2**2 - k2**2 * veff1**2) / (1 - k1**2 * k2**2)) u = (ut + un) / np.sqrt(2.) ...
2251c524fa7ddf541e53d36e98a10f126820b7ed
56,137
def parse_oldrefs(matchobj): """Parse existing references. """ global oldreferences fullref = matchobj.group(0) no = matchobj.group(1) ref = matchobj.group(2) if ref is not None and ref is not '': oldreferences[ref] = no return ''
08cc1283e37e28add21aa52a9fb93d325689a6f7
56,138
def plotitem1(framesoln, plotitem, current_data, gridno): #================================================================== """ Make a 1d plot for a single plot item for the solution in framesoln. The current_data object holds data that should be passed into aftergrid or afteraxes if these functions ...
4177b0f90eb22082e701734575976d1d5601ba96
56,139
import torch def pad_collate(data): """Creates mini-batch tensors from the list of tuples (src_seq, trg_seq).""" def pad_sequences(sequences): sequences = [torch.LongTensor(s) for s in sequences] lengths = torch.LongTensor([len(seq) for seq in sequences]) padded_seqs = torch.zeros(len(...
bb84d62e90418de7ac57974d69ac985a49cf5d35
56,140
def number_normalization(value, fromvalue, tovalue): """数値を範囲内の値に正規化する。 value: 正規化対象の数値。 fromvalue: 範囲の最小値。 tovalue: 範囲の最大値+1。 """ if 0 == tovalue: return value if tovalue <= value or value < fromvalue: value -= (value // tovalue) * tovalue if value < fromvalue: v...
912c515991246204ebc4d5eae8ffedb1c6d5823b
56,141
def node_count(): """Count the number of nodes with each label. Use this before migration and after migration to verify no unwanted nodes have been created. :returns: Mapping of label to counts. :rtype: dict """ counts = {} labels = [] driver = get_neo4j() for model_name, klass...
fd309bdd858c319f2e7da9e32e4368b45c7a3af2
56,142
def preprocessing(list_sentences, targets, max_len=60, max_batch=64): """ """ dict_sentences = {length: [] for length in range(2, max_len)} dict_targets = {length: [] for length in range(2, max_len)} bag_of_sentences = [ tokenization(sentence) for sentence in list_sentences...
4034ff54efe912027301d3d4a81589fcdb74bbdd
56,143
import math def controlled_integer_increment_phase(control_list, increment, target): """ The controlled version of integer_increment_phase. """ d = len(target) program = Program() for i in range(0, d): y = math.pi * increment / (2 ** (d - 1 - i)) gate = PHASE(y, target[i]) ...
16f711f4f561a33c15f75256b92578cfbb8b852a
56,144
from typing import Union import torch def lasso_cd_weight_update( x: FloatTensor, r: FloatTensor, j: int, w_j: Union[float, FloatTensor], col_l2: float, lmb: float, ) -> float: """ Returns new weight for lasso coordinate descent weight update. See the README section for the deriva...
911b34f661a8f117821551b5f8560512d26add88
56,145
import getpass import os def encrypt(message): """ Encrypts a string using AES-256 (CBC) encryption A random initialization vector (IV) is padded as the initial 16 bytes of the string The encrypted message will be padded to length%16 = 0 bytes (AES needs 16 bytes block sizes) """ return messag...
8d0df24ee297bdfad070cf0134a03d5c4f4eed87
56,146
def sets_diff(self: list, other: list, name: str, loc: str) -> list: """ Function to compare the sets of two lists. Returns a list of diff strings containing name and location. :param self: list :param other: list :param name: str :param loc: str :return: list[str] """ diffs = []...
04a295051f409f7748fca00ade9e509a74bcd188
56,147
def verify_mods(rel, subj, obj, mods, spatial_parser): """ Function returns all models in which the given relation, subject and object holds. The function can therefore be used to remove models corresponding to indeterminacies that turn out to be false. """ if PRINT_VERIFICATION: print("...
264482b5daf06a6a57901577f7a353dc3b2b6de2
56,148
import requests def get_profile(login): """Get the GitHub profile from login""" print("get profile for %s" % (login,)) try: profile = get("https://api.github.com/users/%s" % login).json() except requests.exceptions.HTTPError: return dict(name=login, avatar_url=LOGO_URL, html_url="") ...
661f737ba6146fdf38f7f70eb3c32341a6cb02f0
56,149
def sep_results(blends=None,no_blends=None,path=None): """blends= blended images no_blends= non blended images""" runner = Run_Sep() flags_b, sep_res_b = runner.process(blends) #We retrieve sep predictions and positions of blends flags_nb, sep_res_nb = runner.process(no_blends) #Compute accu...
2310ee308549421c0737f0f83dca5547b23e3a2d
56,150
from typing import Any from typing import Union from typing import List import re def _format_url( url: Any, col: str, remove_auth: Union[bool, List[str]], split: bool, errors: str ) -> Any: """ This function formats the input value "url" The last two components of the returned tuple hold the followi...
2b68f493b9e604cbb402590ccb55795a98d5e4db
56,151
def get_dt_df(df): """Return a new DataFrame containing only the columns from `df` that contain date-times. Columns containing mixed values where more than `fuzz_percent` of the values are parsable as date-times, are included. In mixed value columns, The NaT (not a time) rows are filled in with interpol...
59abbc53595cb99f28236fe0661473be2c613687
56,152
def crop_address(place): """ Crops address and returns new variant >>> crop_address("Jo's Cafe, San Marcos, Texas, USA") ' San Marcos, Texas, USA' >>> crop_address("San Marcos, Texas, USA") ' Texas, USA' >>> crop_address(" Texas, USA") ' USA' """ place = place.split(",") pla...
05cd88900d04ac7bca8dd45beb416ec7aa72c2f1
56,153
from commands import wtf def fixture_wtf(): """Fixture for wtf tests.""" message = Message() kwargs = dict(user=message.user, channel=message.channel, message=message) text = wtf.get_def(**kwargs) return message, text
1a079a91a85e348c77148a67c93c0f69fc7233ed
56,154
def hamming_w(x, N, ft_compensated=False): """ Specific Hamming FT window function. If ``ft_compensated==True``, multiply the window function by a compensating factor to preserve power in the spectrum. """ return gen_hamming_w(x,N,0.54,0.46,ft_compensated=ft_compensated)
ec6ebaba69c4904e4e0fff2a4a8d47ece6b8e58d
56,155
def caculate_matmul_shape(matrix_A_dim, matrix_G_dim, split_dim): """get matmul shape""" split_dimA = split_dim split_dimG = split_dim if matrix_A_dim % split_dim == 0: batch_w = matrix_A_dim // split_dim else: if matrix_A_dim < split_dim: batch_w = 1 split_di...
54a036103a97b739d00c3bd416e7dc49b1cba9e2
56,156
def percolation_finder(m, max_num_percolation=6): """ Step 3 percolation finder """ walks = { 'walk': [] } # Name binding def redundancy_index(v): n = len(v) occurrence_vector = [v.count(i) for i in range(n)] return max(occurrence_vector) - 1 + occurrence_vector.count(0) * ...
16f33deb1bbf1e28fab268228e9690c6acad07bc
56,157
def RenderPassStartDependenciesVector(builder, numElems): """This method is deprecated. Please switch to Start.""" return StartDependenciesVector(builder, numElems)
ff2216b9e80302f2f97aea9ce97a4adf2ee783c1
56,158
def check_for_ambiguous_sta(db, stalist, collection='arrival', verbose=False, verbose_attributes=None): """ Scans db.collection for any station in the list of station codes defined by the list container stalist. By default ...
183dbfc58e3333bb814ad51f2751eccfc23265f8
56,159
def get_response_date(): """ Date of response to include in responses :return: the current time, correctly formatted """ # return datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") return DateFormat.now()
939e8c0253cd8d8fa9b9238a6d5c7b2cbd4d086e
56,160
def wrong_sign(qs): """Check if instance @qs has a tag indicating that it is a wrong sign. The 'wrong-sign-tag' is defined in the database and is Signbank-implementation dependent; The particular value used by a signbank must be specified in [sWrongSignTag] above """ # Initialise boolean return ...
b49a9671a138b11046f61bc39f438b4bc09551ae
56,161
def volume_to_length(volume, cell_radius): """ get cell length from volume, using the following equation for capsule volume, with V=volume, r=radius, a=length of cylinder without rounded caps, l=total length: V = (4/3)*PI*r^3 + PI*r^2*a l = a + 2*r """ pi = np.pi cylinder_length = (volum...
e355e0799a0072a1bfeb5cb43c347b7b9cdefb66
56,162
def FindInfo(mnemonic,addressmode, operand): """Figure out which opcode to use for this instruction based on addressing mode. The text doesn't definitively determine the addressing mode, so use the text along with what is available for that mnemonic to decide which mode to pick. """ if operand ...
0dd27d5ca512f96c14da8092755248669ea93087
56,163
import itertools def downsample_fasta_islice(fasta_path, n=10): """ BLAST is the slowest step in this analysis. This function returns every nth sequence. So if fasta_path points to a fasta file with 1000 sequences and n = 10, a file with 1000/10 sequences is written. That file's name is returned....
6a8241a0a90568331512c29dfb33396cdc16fb4e
56,164
import numpy import tempfile def train_and_predict( csv_file_name=_DATA_FILE, training_steps=200, estimator_config=None, export_directory=None): """Train and predict using a custom time series model.""" # Construct an Estimator from our LSTM model. categorical_column = tf.feature_column.categorical_colu...
71b3b1cb00e27df062809022630781efbb7a0822
56,165
import code def simulate_gen(simobject, Ndet, pixelsize, detz, k=None, settings="double", maximg=_np.inf, detangles=(0, 0), *args, **kwargs): """ returns an array of simulated wavefields parameters: simobject: a simobject whose get() returns an Nx4 array with atoms in the first and (x,y,z,phase) of ea...
7ba4314ef50f3825c8ec6ee1a57821e4c6239e90
56,166
import os def env_var_to_list(env_var, separator=";"): """ Converts an environment variable like PATH, that has paths separated by a ";" into a list of paths :param : (str) name of environment variable. Such as PATH or PYTHONPATH :return: (list) """ if env_var not in os.environ.keys(): ...
660c3a13e0fdb708a5f40aa357f88300e754b9fe
56,167
def genDict(linebuffer, titlebuffer, f, original_path, typebuffer, githubUrl): """Puts the function info into a dict Also add pygments and hardcode github url info """ lexer = get_lexer_by_name("scheme", stripall=True) result = highlight(linebuffer, lexer, HtmlFormatter()) url = f.replace(original_path, githubUrl...
b5536ec535bcf2fc7a22150069742613947e14af
56,168
def scorethreshold(source,logit=None): """ Check that this variable has the appropriate format and reformat otherwise ---------- source : str Source of the contact list ("deepmetapsicov" or "psicov") logit : str, optional If not none, it activates the logging. The default is None. ...
b56e6e26bdd8b960b25b789cd067257afd489ad8
56,169
def randint(low: int, high: int, shape: _ShapeType, dtype: mindspore.dtype = mindspore.int8) -> Tensor: """Return random integers from `low` (inclusive) to `high` (exclusive).""" outputs_np = np.random.randint(low, high, size=shape) outputs = Tensor(outputs_np, dtype=dtype) return outputs
7c5c041bc99ff86f7702a9afad88faae4309dc0e
56,170
def states_id(id): """ method to render state ids """ state_all = storage.all('State') try: state_id = state_all[id] return render_template( '9-states.html', state_id=state_id, condition="state_id") except: return render_template('9...
f034e77ea8e83de200939cdcee2a2fd2c580df08
56,171
import sqlite3 from typing import List from typing import Any def get_data(conn: sqlite3.Connection, table_name: str, columns: List[str], start: int = None, end: int = None, ) -> List[List[Any]]: """ Get data from the columns of a table. All...
1760f64a63094e14c6bf22c3199a549c02c4bc4e
56,172
import requests def get_gitlab_tags(proj_id): """ obtain tags from Gitlab :param proj_id: project id in Gitlab :return: list """ result = [] r = requests.get("{}/projects/{}/repository/tags".format(gitlab_api_url, proj_id), headers={"PRIVATE-TOKEN": gitlab_token}) ...
69b0b8213cfe7e3ea35d0393dfa8ab1f94309b12
56,173
import json def compare_reload_data(inid, src_dir, site_dir): """Load the original csv and compare to reloading the JSON you wrote out which = 'edges' or 'data' """ csv_path = input_path(inid, ftype='data', src_dir=src_dir) jsn_path = output_path(inid, ftype='comb', format='json', site_dir=site_d...
6b6ce47c203fc433f9bd5657802ff8086587b99d
56,174
def _is_integer(value): """Check if a value is a Python or NumPy integer instance.""" return isinstance(value, (int, np.integer))
67a5bed37ecd41a151eed9210b61e3b9d29b945c
56,175
def getMoreInfoOfCurrentRestaurant(update: Update, context: CallbackContext) -> int: """Fetches in-depth details of the current restaurant and shows them to the user.""" verifyChatData(update=update, context=context) query = update.callback_query query.answer() # Getting the current restaurant and...
690413608c25d0e5d23c07bcd055a9fb87937263
56,176
def GetBedSwapMessage( PrimaryID1, VisitID1, PrimaryID2, VisitID2 ): """ Create a bedswap message (A17) which switches the location of 2 patients. Parameters: PrimaryID1 - The first patient's Primary Patient ID that stays with the patient forever VisitID1 - The first patient...
03cd50aa8433061ecf8696b69abfecbea06e3b14
56,177
async def get_member_roles(compass_id: int, api: ci.CompassInterface = Depends(ci_user)): """Gets roles for the member given by `compass_id`.""" logger.debug(f"Getting /{{compass_id}}/roles for {api.user.membership_number}") async with error_handler: return api.people.roles(compass_id, only_voluntee...
dcd0acf0860973552622aea3353cf74dc9eb13d8
56,178
def spatial_mean(yarray, w=5): """ Spatial mean over rows and columns """ wh = int(w / 2.0) yarray = np.pad(yarray.copy(), ((0, 0), (w, w), (w, w)), mode='reflect') ymean = np.zeros(yarray.shape, dtype='float64') ymask = np.where(yarray > 0, 1, 0).astype('uint8') ycount = np.zeros(ya...
dfa9eb93b6307f4af82334c0bdf25a3a0a03ed27
56,179
def make_fooling_image(X, target_y, model): """ Generate a fooling image that is close to X, but that the model classifies as target_y. Inputs: - X: Input image, a numpy array of shape (1, 224, 224, 3) - target_y: An integer in the range [0, 1000) - model: Pretrained SqueezeNet model R...
79ca10bc4ad90fd609c625dc5927b7b7aeb3c237
56,180
def validate_overlap(periods, datetime_range=False): """ Receives a list with DateRange or DateTimeRange and returns True if periods overlap. This method considers that the end of each period is not inclusive: If a period ends in 15/5 and another starts in 15/5, they do not overlap. This is the ...
bae96eb890063e4d27af0914e7fcd1348d1340a7
56,181
def find_primes_sieve(upper_bound): """ Returns all primes up to upper_bound (exclusive) using the sieve of Eratosthenes. The numbers are returned as a list. Example: find_primes(7) -> [2, 3, 5] """ # 1 marks a potential prime number, 0 marks a non-prime number # indexes 0 and 1 are not tou...
236cbd0cdf2eee2cda91ae3d2d240a9548a920dc
56,182
def get_lesson_attachments(lesson_id): """ Get attachments for a lesson """ # pylint: disable=E1101 lesson_attachments = Attachment.objects.filter(lesson=lesson_id) result = [] for attachment in lesson_attachments: url = attachment.attached_file.url result.append({'title': at...
f4f03675b56d07a545d1d2bbae27493cb7f14279
56,183
def aggregate_loader(data_path): """Load the data from the given hdf5 file""" # with pd.HDFStore(data_all[0]['analysis_path']) as h: with pd.HDFStore(data_path) as h: # get a list of the existing keys keys = h.keys() # if it's only one key, just load the file if len(keys) == ...
00be112655e71bb6d681f58419606ecb34867465
56,184
def new_category(): """ View new group route function that returns a page with a form to create a category """ form = CategoryForm() if form.validate_on_submit(): name = form.name.data new_category = PitchCategory(name = name) new_category.save_category() retur...
69a90621792ce3c07cf5dd92f09af21fbc196e94
56,185
from pathlib import Path def get_dump(): """Helper for creating and returning a dump Path""" dump = Path("pyinseq/tests/dump") if not dump.exists(): dump.mkdir() return dump
d34d149c6de235e58cbee222067b8023afcf8f93
56,186
from typing import List def fix_column_types( source: Source, interface: redshift.Interface, drop_table: bool ) -> None: # check what happens to the dict over multiple uses """ Verifies the column names are not too long. Verifies the column data matches any predefined types. Generates an appropri...
a643a79a49b73e6da0ae700f662bc214a05364d6
56,187
from typing import MutableMapping import itertools from typing import Set from typing import Hashable def is_adjacency(item: object) -> bool: """Returns whether 'item' is an adjacency list. Args: item (object): instance to test. Returns: bool: whether 'item' is an adjacency list. ...
792597c0f9678c737e21e8fc690098168e7e7f0f
56,188
import warnings def drop_duplicate_cols(df: pd.DataFrame, warn: bool = True) -> pd.DataFrame: """ Drop duplicate columns from pandas DataFrame :param df: pandas DataFrame :param warn: Whether to trigger a warning if duplicate columns are dropped :return: pandas DataFrame without the duplicates co...
d127e925ac79206a48d5aaac7d9f6d5781a3c23b
56,189
def line_of_sight_integrate( radial_distances: np.ndarray, get_emission_func: EmissionFunction, observer_position: np.ndarray, earth_position: np.ndarray, unit_vectors: np.ndarray, freq: float, ) -> np.ndarray: """Returns the integrated Zodiacal emission for a component (Trapezoidal). P...
29e0f7397efd7a54547ddfd346b3ecfd2c5188af
56,190
import tempfile def sv56(x, sr, ndb=-26): """Run sv56 gain normalization Args: x (array): waveform sr (int): Sampling rate ndb (int): Gain level in dB Return array: gain-normalized waveform """ assert x.dtype == np.int16 with tempfile.TemporaryDirectory() as f...
ad6fc138457bed2be376b7d92ba3d373da46e886
56,191
import click def remote_option(help): """`REMOTE` is the name of a configured remote. Use ``guild remotes`` to list available remotes. For information on configuring remotes, see ``guild remotes --help``. """ assert isinstance(help, str), "@remote_option must be called with help" def wr...
643ba728e99d81956780e62c09489396476ba341
56,192
def handle_add_vote(data) -> None: """Takes an info dictionary of the form: { 'channel': channel_id, 'vote': vote_id, 'option': option_id } """ channel_id = data['channel'] vote_id = data['vote'] option_id = data['option'] if not verify_valid_option(channel_id, vote_id, option_id): ...
18ff788bd121f0032e3cd59c5c8807d2bb46e933
56,193
def get_edge_between_verts_colour(veering_colours, tetrahedron, v0, v1): """returns the veering direction (colour) for the given edge, between v0, v1""" edge_index = get_edge_between_verts_index( tetrahedron, v0, v1) return direction_to_col[ veering_colours[edge_index] ]
84373ac2b9a3d13250cdbe7ea853fc10bd3970c4
56,194
import copy def mutually_exclusive_group(group): """Decorator function for mutually exclusive :mod:`argparse` arguments. Args: group (list of tuples): A list of the standard :mod: `argparse` arguments which are mutually exclusive. Each argument is represented as a tuple of its...
c6875840371c9a6fb6060c7148b734248a6f0b41
56,195
import argparse def get_arguments(): """Get needed options for the cli parser interface""" usage = """DSStoreParser CLI tool. v{}""".format(__VERSION__) usage = usage + """\n\nSearch for .DS_Store files in the path provided and parse them.""" argument_parser = argparse.ArgumentParser( formatte...
4eac1372c258c441a68e702aed6da9ba1ff18bb8
56,196
def SCExAO_DM(empty_lamda, grid_size, PASSVALUE): """ propagates instantaneous complex E-field thru Subaru from the DM through SCExAO this function is called a 'prescription' by proper uses PyPROPER3 to generate the complex E-field at the pupil plane, then propagates it through SCExAO 50x50 DM, ...
da21567abec030830ad43093c8e1306edf6eb4f6
56,197
def async_setup(hass, config): """Track the state of the sun.""" if config.get(CONF_ELEVATION) is not None: _LOGGER.warning( "Elevation is now configured in home assistant core. " "See https://home-assistant.io/docs/configuration/basic/") sun = Sun(hass, get_astral_location(...
27566afd924dcc973ac15eecc403dab642ac5846
56,198
from .verbose_output import print_to_terminal def generate_2d_parametermap(self, spectrum_parameter): """ Create a 2D map of a given spectral parameter Parameters ---------- scouseobject : Instance of the scousepy class """ map = np.zeros(self.scouseobject.cube.shape[1:]) map[:] = np...
6aaeb852bb1987040d3e09fe234792853523d749
56,199