content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def html_url(url: str, name: str = None, theme: str = "") -> str: """Create a HTML string for the URL and return it. :param url: URL to set :param name: Name of the URL, if None, use same as URL. :param theme: "dark" or other theme. :return: String with the correct formatting for URL """ i...
74a0d3eabce4f0a53e699567e25c9d09924e3150
18,137
def get_logger_messages(loggers=[], after=0): """ Returns messages for the specified loggers. If given, limits the messages to those that occured after the given timestamp""" if not isinstance(loggers, list): loggers = [loggers] return logger.get_logs(loggers, after)
d2c8ef6dc8f1ec0f4a5f7a1263b829f20e0dfa8b
18,138
def __dir__(): """IPython tab completion seems to respect this.""" return __all__
d1b0fe35370412a6c0ca5d323417e4e3d1b3b603
18,139
def run_iterations(histogram_for_random_words, histogram_for_text, iterations): """Helper function for test_stochastic_sample (below). Store the results of running the stochastic_sample function for 10,000 iterations in a histogram. Param: histogram_for_ran...
59bd4cefd03403eee241479df19f011915419f14
18,140
def GetFootSensors(): """Get the foot sensor values""" # Get The Left Foot Force Sensor Values LFsrFL = memoryProxy.getData("Device/SubDeviceList/LFoot/FSR/FrontLeft/Sensor/Value") LFsrFR = memoryProxy.getData("Device/SubDeviceList/LFoot/FSR/FrontRight/Sensor/Value") LFsrBL = memoryProxy.getData("De...
555c5cb1f6e68571848410096144a3184d22e28a
18,141
def norm(x, y): """ Calculate the Euclidean Distance :param x: :param y: :return: """ return tf.sqrt(tf.reduce_sum((x - y) ** 2))
67766f9e3c3a510a87eff6bdea7ddf9ec2504af3
18,142
def expand_key(keylist, value): """ Recursive method for converting into a nested dict Splits keys containing '.', and converts into a nested dict """ if len(keylist) == 0: return expand_value(value) elif len(keylist) == 1: key = '.'.join(keylist) base = dict() ...
ac8b4bac9b686396d5d117149fb45b8bde2ac238
18,143
def _linear_sum_assignment(a, b): """ Given 1D arrays a and b, return the indices which specify the permutation of b for which the element-wise distance between the two arrays is minimized. Args: a (array_like): 1D array. b (array_like): 1D array. Returns: array_like: Indi...
eeecff894e8bf29de66fa2560b8fdadbf3970d6d
18,144
def get_ingredients_for_slice_at_pos(pos, frame, pizza, constraints): """ Get the slice of pizza with its ingredients :param pos: :param frame: :param pizza: :param constraints: :return: """ def _get_ingredients_for_slice_at_pos(_pos, _frame, _pizza, _max_rows, _max_cols): if...
db1083695d6f9503b3005e57db47c15ac761a31d
18,145
def merge_data_includes(tweets_data, tweets_include): """ Merges tweet object with other objects, i.e. media, places, users etc """ df_tweets_tmp = pd.DataFrame(tweets_data) # Add key-values of a nested dictionary in df_tweets_tmp as new columns df_tweets = flat_dict(df_tweets_tmp) for ...
db8e8560bdb80bd4a57d4f0d69031e944511633f
18,146
def stringify(context, mapping, thing): """Turn values into bytes by converting into text and concatenating them""" if isinstance(thing, bytes): return thing # retain localstr to be round-tripped return b''.join(flatten(context, mapping, thing))
c4c4503160cab3ff6a78e2fb724fd283011ce0e7
18,147
import logging import json def extract_from_json(json_str, verbose=False): """A helper function to extract data from KPTimes dataset in json format :param: json_str: the json string :param: verbose: bool, if logging the process of data processing :returns: the articles and keywords for each article ...
b05120eee45a887cee5eac68febffe96fcf8d305
18,148
def split_data(data, split_ratio, data_type=DATA_TYPE_1): """ split data by type """ data_type_1 = data[data['LABEL'] == data_type] data_type_2 = data[data['LABEL'] != data_type] train_set = data.sample(frac=split_ratio, replace=False) test_set = data[~data.index.isin(train_set.index)] ...
2653ea65bbc6fa2c7c0db9ab29890f57d5254d3f
18,149
def sparse_amplitude_prox(a_model, indices_target, counts_target, frame_dimensions, eps=0.5, lam=6e-1): """ Smooth truncated amplitude loss from Chang et al., Overlapping Domain Decomposition Methods for Ptychographic Imaging, (2020) :param a_model: K x M1 x M2 :param indices_target: K...
9a2b7c0deb2eba58cebd6f7b2198c659c1915711
18,151
from typing import Dict from typing import Any from typing import List def schema_as_fieldlist(content_schema: Dict[str, Any], path: str = "") -> List[Any]: """Return a list of OpenAPI schema property descriptions.""" fields = [] if "properties" in content_schema: required_fields = content_schema...
b691e74ac36a0f3904bd317acee9b9344a440cdb
18,152
def shrink(filename): """ :param filename: str, the location of the picture :return: img, the shrink picture """ img = SimpleImage(filename) new_img = SimpleImage.blank((img.width+1) // 2, (img.height+1) // 2) for x in range(0, img.width, 2): for y in range(0, img.height, 2): ...
fad3778089b0d5f179f62fb2a40ec80fd3fe37d1
18,153
def eh_menor_que_essa_quantidade_de_caracters(palavra: str, quantidade: int) -> bool: """ Função para verificar se a string é menor que a quantidade de caracters informados @param palavra: A palavra a ser verificada @param quantidade: A quantidade de caracters que deseja verificar @return: Retorna T...
827469606b0b93b78b63686465decbbbc63b9673
18,154
import rasterstats as rs def buffer_sampler(ds,geom,buffer,val='median',ret_gdf=False): """ sample values from raster at the given ICESat-2 points using a buffer distance, and return median/mean or a full gdf ( if return gdf=True) Inputs = rasterio dataset, Geodataframe containing points, buffer dista...
8efde64c0ee49b11e484fd204cf70ae5ae322bf9
18,155
import re def extract_int(str, start, end): """ Returns the integer between start and end. """ val = extract_string(str, start, end) if not val is None and re.match('^[0-9]{1,}$', val): return int(val) return None
ec08c15592ea7e7ab9e4a0f476a97ba2127dda85
18,156
import re def get_pg_ann(diff, vol_num): """Extract pedurma page and put page annotation. Args: diff (str): diff text vol_num (int): volume number Returns: str: page annotation """ pg_no_pattern = fr"{vol_num}\S*?(\d+)" pg_pat = re.search(pg_no_pattern, diff) try:...
d9ca1a760f411352d8bcbe094ac622f7dbd33d07
18,157
def check_diamond(structure): """ Utility function to check if the structure is fcc, bcc, hcp or diamond Args: structure (pyiron_atomistics.structure.atoms.Atoms): Atomistic Structure object to check Returns: bool: true if diamond else false """ cna_dict = structure.analyse.pys...
ae082d6921757163cce3ddccbca15bf70621a092
18,158
from typing import Optional from typing import Union from typing import Dict from typing import Any from typing import List from typing import Tuple def compute_correlation( df: DataFrame, x: Optional[str] = None, y: Optional[str] = None, *, cfg: Union[Config, Dict[str, Any], None] = None, dis...
a8fb7f4e6cf34d584aba8e8fa9a7a7703fad8bad
18,159
def radix_sort(arr): """Sort list of numberes with radix sort.""" if len(arr) > 1: buckets = [[] for x in range(10)] lst = arr output = [] t = 0 m = len(str(max(arr))) while m > t: for num in lst: if len(str(num)) >= t + 1: ...
517ab99483ac1c6cd18df11dc1dccb4c502cac39
18,160
def resampling(w, rs): """ Stratified resampling with "nograd_primitive" to ensure autograd takes no derivatives through it. """ N = w.shape[0] bins = np.cumsum(w) ind = np.arange(N) u = (ind + rs.rand(N))/N return np.digitize(u, bins)
2f3d6ae173d5e0ebdfe36cd1ab6595af7452c191
18,162
import torch def integrated_bn(fms, bn): """iBN (integrated Batch Normalization) layer of SEPC.""" sizes = [p.shape[2:] for p in fms] n, c = fms[0].shape[0], fms[0].shape[1] fm = torch.cat([p.view(n, c, 1, -1) for p in fms], dim=-1) fm = bn(fm) fm = torch.split(fm, [s[0] * s[1] for s in sizes]...
bee6d8782b372c0fb3990eefa42d51c6acacc29b
18,163
def get_RF_calculations(model, criteria, calculation=None, clus="whole", too_large=None, sgonly=False, regionalonly=False): """ BREAK DOWN DATA FROM CALCULATION! or really just go pickle """ print(f'{utils.time_now()} - Criteria: {criteria}, calculation: {calculation}, clus: {clus}, sgonly: {sgonly}...
34b44b3a525bd7cee562a63d689fc21d5a5c2a4a
18,164
from plugin.helpers import log_plugin_error import importlib import pkgutil def get_modules(pkg, recursive: bool = False): """get all modules in a package""" if not recursive: return [importlib.import_module(name) for finder, name, ispkg in iter_namespace(pkg)] context = {} for loader, name,...
96c48ae86a01defe054e5a4fc948c2f9cfb05660
18,166
def TransformOperationHttpStatus(r, undefined=''): """Returns the HTTP response code of an operation. Args: r: JSON-serializable object. undefined: Returns this value if there is no response code. Returns: The HTTP response code of the operation in r. """ if resource_transform.GetKeyValue(r, 'st...
e840575ccbe468e6b3bc9d5dfb725751bd1a1464
18,167
import warnings def split_record_fields(items, content_field, itemwise=False): """ This functionality has been moved to :func:`split_records()`, and this is just a temporary alias for that other function. You should use it instead of this. """ warnings.warn( "`split_record_fields()` has be...
256efc34bced15c5694fac2a7c4c1003214a54c5
18,168
import scipy import numpy def prony(signal): """Estimates amplitudes and phases of a sparse signal using Prony's method. Single-ancilla quantum phase estimation returns a signal g(k)=sum (aj*exp(i*k*phij)), where aj and phij are the amplitudes and corresponding eigenvalues of the unitary whose phases...
50bbcd05b1e541144207762052de9de783089bad
18,170
def _check_alignment(beh_events, alignment, candidates, candidates_set, resync_i, check_i=None): """Check the alignment, account for misalignment accumulation.""" check_i = resync_i if check_i is None else check_i beh_events = beh_events.copy() # don't modify original events = np.z...
e4508e90f11bb5b10619d19066a5fb51c36365b3
18,171
def user_info(): """ 个人中心基本资料展示 1、尝试获取用户信息 user = g.user 2、如果用户未登录,重定向到项目首页 3、如果用户登录,获取用户信息 4、把用户信息传给模板 :return: """ user = g.user if not user: return redirect('/') data = { 'user': user.to_dict() } return render_template('blogs/user.html', data=da...
cb8d9c2081c8a26a82a451ce0f4de22fc1a43845
18,172
def build_config_tests_list(): """Build config tests list""" names,_,_,_ = zip(*config_tests) return names
df190ec4926af461f15145bc25314a397d0be52b
18,173
def annotate_filter(**decargs): """Add input and output watermarks to filtered events.""" def decorator(func): """Annotate events with entry and/or exit timestamps.""" def wrapper(event, *args, **kwargs): """Add enter and exit annotations to the processed event.""" funcna...
e1ce16e46f17948bdb1eae3ac8e5884fe6553283
18,175
def cplot(*args,**kwargs): """ cplot - Plot on the current graphe This is an "alias" to gcf().gca().plot() """ return(gcf().gca().plot(*args,**kwargs))
b7725569d19520c0e85f3a48d30800c3822cdac2
18,176
from datetime import datetime def need_to_flush_metrics(time_now): """Check if metrics need flushing, and update the timestamp of last flush. Even though the caller of this function may not successfully flush the metrics, we still update the last_flushed timestamp to prevent too much work being done in user ...
a2f50927a61eecee9448661f87f08a99caa4a22c
18,177
def create_instances_from_lists(x, y=None, name="data"): """ Allows the generation of an Instances object from a list of lists for X and a list for Y (optional). All data must be numerical. Attributes can be converted to nominal with the weka.filters.unsupervised.attribute.NumericToNominal filter. ...
310d72cb9fe5f65d85b19f9408e670426ebf7fdd
18,179
def median_filter_(img, mask): """ Applies a median filer to all channels """ ims = [] for d in range(3): img_conv_d = median_filter(img[:,:,d], size=(mask,mask)) ims.append(img_conv_d) return np.stack(ims, axis=2).astype("uint8")
2d7909b974572711901f84806009f237ecafaadf
18,181
def replace_lines(inst, clean_lines, norm_lines): """ Given an instance and a list of clean lines and normal lines, add a cleaned tier and normalized if they do not already exist, otherwise, replace them. :param inst: :type inst: xigt.Igt :param clean_lines: :type clean_lines: list[dict...
39f3fdcd40eafd32e071b54c9ab032104fba8c7c
18,182
from pathlib import Path def get_html(link: Link, path: Path) -> str: """ Try to find wget, singlefile and then dom files. If none is found, download the url again. """ canonical = link.canonical_outputs() abs_path = path.absolute() sources = [canonical["singlefile_path"], canonical["wget_...
3624e3df219cc7d6480747407ad7de3ec702813e
18,183
def normalization(X,degree): """ A scaling technique in which values are shifted and rescaled so that they end up ranging between 0 and 1. It is also known as Min-Max scaling ---------------------------------------- degree: polynomial regression degree, or attribute/feature number """ ...
9cdef8b4b7e7a31523311ce6f4a668c6039ad2a1
18,184
def get_tags_from_match(child_span_0, child_span_1, tags): """ Given two entities spans, check if both are within one of the tags span, and return the first match or O """ match_tags = [] for k, v in tags.items(): parent_span = (v["start"], v["end"]) if parent_relation(child_...
c7ad037d2c40b6316006b4c7dda2fd9d02640f6e
18,185
def _rfc822_escape(header): """Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline. """ lines = header.split('\n') header = ('\n' + 8 * ' ').join(lines) return header
1a3cd02b057742db00ed741c40947cf4e19d1a86
18,186
import socket def getCgiBaseHref(): """Return value for <cgiBaseHref/> configuration parameter.""" val = sciflo.utils.ScifloConfigParser().getParameter('cgiBaseHref') if val is None: val = "http://%s/sciflo/cgi-bin/" % socket.getfqdn() return val
62b5bc3d528c6db64ff8899c2847d2b0ecb4021d
18,187
def dijkstra(gph: GraphState, algo: AlgoState, txt: VisText, start: Square, end: Square, ignore_node: Square = None, draw_best_path: bool = True, visualize: bool = True) \ -> [dict, bool]: """Code for the dijkst...
cbc69734278e7ab4b0c609a1bfab5a9280bedee4
18,189
def nowIso8601(): """ Returns time now in ISO 8601 format use now(timezone.utc) YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] .strftime('%Y-%m-%dT%H:%M:%S.%f%z') '2020-08-22T17:50:09.988921+00:00' Assumes TZ aware For nanosecond use instead attotime or datatime64 in pandas or numpy ...
c5290e5a60f708f19d1cecf74c9cd927b4750ca3
18,191
def get_trip_data(tripdata_path, output_path, start=None, stop=None): """ Read raw tripdata csv and filter unnecessary info. 1 - Check if output path exists 2 - If output path does not exist 2.1 - Select columns ("pickup_datetime", "passenger_coun...
3aca0b89d1e747ae1ea3e5ea9f3fa0d63a5b9447
18,192
import urllib def _qparams2url(qparams): """ parse qparams to make url segment :param qparams: :return: parsed url segment """ try: if qparams == []: return "" assert len(qparams) == 4 num = len(qparams[0][1]) path="" for i in range(num): ...
ac416dd0dac87210fef5aa1bea97a60c84df60cf
18,193
import itertools def confusion_matrix(y_pred: IntTensor, y_true: IntTensor, normalize: bool = True, labels: IntTensor = None, title: str = 'Confusion matrix', cmap: str = 'Blues', show: bool =...
744642cde03696f6ecbccc6f702e3f9a3cb67451
18,194
def from_smiles(smiles: str) -> Molecule: """Load a molecule from SMILES.""" return cdk.fromSMILES(smiles)
a5315eeb9ffadff16b90db32ca07714fe1573cda
18,195
from typing import Dict from typing import Any def parse_template_config(template_config_data: Dict[str, Any]) -> EmailTemplateConfig: """ >>> from tests import doctest_utils >>> convert_html_to_text = registration_settings.VERIFICATION_EMAIL_HTML_TO_TEXT_CONVERTER # noqa: E501 >>> parse_template_con...
adea58fd8e8a16ec4fd48ef68aa2ff1c6356bd0d
18,196
import json def stringify_message(message): """Return a JSON message that is alphabetically sorted by the key name Args: message """ return json.dumps(message, sort_keys=True, separators=(',', ':'))
ccd51481627449345ba70fbf45d8069deca0f064
18,197
import numpy as np def compute_similarity_transform(X, Y, compute_optimal_scale=False): """ A port of MATLAB's `procrustes` function to Numpy. Adapted from http://stackoverflow.com/a/18927641/1884420 Args X: array NxM of targets, with N number of points and M point dimensionality Y: a...
10da3df241ec140de86b2307f9fc097b4f926407
18,198
def simplefenestration(idf, fsd, deletebsd=True, setto000=False): """convert a bsd (fenestrationsurface:detailed) into a simple fenestrations""" funcs = (window, door, glazeddoor,) for func in funcs: fenestration = func(idf, fsd, deletebsd=deletebsd, setto000=setto000) i...
b72e73a22756e80981d308b54037510354a5d327
18,199
from typing import TextIO from typing import Set def observe_birds(observations_file: TextIO) -> Set[str]: """Return a set of the bird species listed in observations_file, which has one bird species per line. >>> file = StringIO("bird 1\\nbird 2\\nbird 1\\n") >>> birds = observe_birds(file) >>> 'bird...
e3ea90e8da4488121ec1ae75c4aa116646db08f5
18,200
def convert_sheet(sheet, result_dict, is_enum_mode=False): """ 转换单个sheet的数据 Args: sheet: openpyxl.worksheet.worksheet.Worksheet result_dict: [dict]结果都存在这里, key为data_name,value为sheet_result is_enum_mode: [bool]是否为enum导表模式 Returns: bool, 是否成功 """ if is_enum_mode: ...
284f470844b6722941d0e4725e4c23b1473b08df
18,201
def bytes_to_int(b: bytes, order: str = 'big') -> int: """Convert bytes 'b' to an int.""" return int.from_bytes(b, order)
c959683787e03cc956b5abffc814f98cf4722397
18,203
def fit_model(params,param_names,lam_gal,galaxy,noise,gal_temp, feii_tab,feii_options, temp_list,temp_fft,npad,line_profile,fwhm_gal,velscale,npix,vsyst,run_dir, fit_type,output_model): """ Constructs galaxy model by convolving templates with a LOSVD given by a specified set of velocity parameters. ...
44cd0bc61a4472c6a5c3c7b190ee5be96f4bdb1a
18,204
import random def generate_numbers(): """ Function to generate 3 random digits to be guessed. Generate 3 random in a list in order to be compare to the user's digits. Return: str_digits (Array): List with 3 random digits converted to String """ # List comprehension to generate num...
8efd0f579a3a0b3dc5021cd762f9ad2f5774f6be
18,205
def get_media(): """Retrieves metadata for all of this server's uploaded media. Can use the following query parameters: * max: The maximum number of records to return * page: The page of records """ error_on_unauthorized() media = Upload.query.order_by(Upload.id) total_num = media.cou...
754417b47f5b9c28427b04ace88bf9ca5c9a5a47
18,206
def summate2(phasevec): """Calculate values b'(j^vec) for combining 2 phase vectors. Parameter: phasevec: tuple of two phasevectors Example: On input (([b_1(0),b_1(1),...,b_1(L-1)], L), ([b_2(0),b_2(1),...,b_2(L'-1)], L')) give output [b_1(0)+b_2(0), b_1(0)+b_2(1),..., b_1(1)+b_2(0),...,b_1(L-...
5150c2ee29a31438bf16104eaadeb85a01f54502
18,207
def makeTracker( path, args = (), kwargs = {} ): """retrieve an instantiated tracker and its associated code. returns a tuple (code, tracker). """ obj, module, pathname, cls = makeObject( path, args, kwargs ) code = getCode( cls, pathname ) return code, obj
bc23e21bb53357bcf74e6194656cfbea4b24c218
18,209
from typing import Tuple def get_anchor_generator(anchor_size: Tuple[tuple] = None, aspect_ratios: Tuple[tuple] = None): """Returns the anchor generator.""" if anchor_size is None: anchor_size = ((16,), (32,), (64,), (128,)) if aspect_ratios is None: aspect_ratios = ((0.5, 1.0, 2.0),) * le...
e9eef959c009062d5866558d00674c1afa033260
18,210
import torch def tensor_to_longs(tensor: torch.Tensor) -> list: """converts an array of numerical values to a tensor of longs""" assert tensor.dtype == torch.long return tensor.detach().cpu().numpy()
ba1788be8e353936cfc3d604d940b78a96990fd4
18,211
def test_fixed(SNRs): """ Fixed (infinite T1) qubit. """ fidelities = [] numShots = 10000 dt = 1e-3 for SNR in SNRs: fakeData = create_fake_data(SNR, dt, 1, numShots, T1=1e9) signal = dt*np.sum(fakeData, axis=1) fidelities.append(fidelity_est(signal)) return fidelities
70ca68f475beed73a47722c719811544ae1bfccb
18,212
def setup(app): """ Add the ``fica`` directive to the Sphinx app. """ app.add_directive("fica", FicaDirective) return { "version": __version__, "parallel_read_safe": True, "parallel_write_safe": True, }
996e568ab58634e64a845b34bf38082658b58889
18,213
from typing import Tuple import torch def get_binary_statistics( outputs: Tensor, targets: Tensor, label: int = 1, ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: """ Computes the number of true negative, false positive, false negative, true negative and support for a binary classification pro...
e0c81b404f6da77f40c1e4f3810d699fdef1e6a4
18,214
def threshold_and_mask(min_normed_weight, W, Mc, coords): # =np.arange(Wc.shape[0])*stride + start): """Normalize the weights W, threshold to min_normed_weight and remove diagonal, reduce DX and DY to the columns and rows still containing weights. Returns ------- coords : array_like the in...
78d361cf2125cd0d3ac1a3985933e39b09538b18
18,215
import csv def readCGcsv(filename, levels): """ Read a .csv file of a callgraph into a dictionary keyed by callgraph level. """ cgdict = {} with open(filename, "r") as cgcsv: cgreader = csv.DictReader(cgcsv) for row in cgreader: lvl = int(row['Level']) if (lvl < l...
ec5dbc3d064a0cf784bfd764b996eb36677642a9
18,216
def use_colors(tones, i=None): """ Use specific color tones for plotting. If i is specified, this function returns a specific color from the corresponding color cycle For custom color palettes generation check: http://colorbrewer2.org/#type=sequential&scheme=YlGnBu&n=8 Args: tones : 'hot' or 'co...
e36cce208c89178af8199662edb336c2455bdc37
18,217
def fill_form(forms, form): """Fills a given form given a set or known forms. :param forms: A set of known forms. :param form: The form to fill. :return: A mapping from form element IDs to suggested values for the form. """ forms = list(forms) new_form = {} def rec_fill_form(form, lab...
3e6c1f623facb67602fa5e057080a08d0de9926d
18,218
def integer_to_vector(x, options_per_element, n_elements, index_to_element): """Return a vector representing an action/state from a given integer. Args: x (int): the integer to convert. n_options_per_element(int): number of options for each element in the vector. n_elements (int): the n...
2649359d6a62b047f70bfe72f8403e8343a231ab
18,220
def samples_for_each_class(dataset_labels, task): """ Numbers of samples for each class in the task Args: dataset_labels Labels to count samples from task Labels with in a task Returns """ num_samples = np.zeros([len(task)], dtype=np.float32) i = 0 for label ...
96bc2c794fd955110864f59ddb96c5df1c33b8ed
18,221
def requiredOneInGroup(col_name, group, dm, df, *args): """ If col_name is present in df, the group validation is satisfied. If not, it still may be satisfied, but not by THIS col_name. If col_name is missing, return col_name, else return None. Later, we will validate to see if there is at least one...
de46a4ef2f3e45381644db41d617d8c4c0845877
18,222
def persist(session, obj, return_id=True): """ Use the session to store obj in database, then remove obj from session, so that on a subsequent load from the database we get a clean instance. """ session.add(obj) session.flush() obj_id = obj.id if return_id else None # save this before obj i...
a308931f418616417d10d3115b0f370352778533
18,223
from unittest.mock import patch def test_bittrex_query_asset_movement_int_transaction_id(bittrex): """Test that if an integer is returned for bittrex transaction id we handle it properly Bittrex deposit withdrawals SHOULD NOT return an integer for transaction id according to their docs https://bittrex.gi...
83e3ce3d8f82b159191c6b9068b54321d06bfa9a
18,224
from operator import sub def masker(mask, val): """Enforce the defined bits in the <mask> on <val>.""" ones = sub(r"[^1]", "0", mask) val |= int(ones,2) zeros = sub(r"[^0]", "1", mask) val &= int(zeros,2) return val
68b3edd542b295ca7aade0eb9829e310e4c0ed2d
18,226
def ct_lt_u32(val_a, val_b): """ Returns 1 if val_a < val_b, 0 otherwise. Constant time. :type val_a: int :type val_b: int :param val_a: an unsigned integer representable as a 32 bit value :param val_b: an unsigned integer representable as a 32 bit value :rtype: int """ val_a &= 0xf...
6816fd1e9633c0c3035d68ac657f3cb917f24527
18,227
import typing async def is_banned(ctx: Context, user: typing.Union[discord.Member, discord.User]) -> bool: """Returns true if user is in guild's ban list.""" bans = await ctx.guild.bans() for entry in bans: if entry.user.id == user.id: return True return False
2807e2d9a296afb360efe9abf9618e0ebe19e796
18,228
from typing import List def _create_transformation_vectors_for_pixel_offsets( detector_group: h5py.Group, wrapper: nx.NexusWrapper ) -> List[QVector3D]: """ Construct a transformation (as a QVector3D) for each pixel offset """ x_offsets = wrapper.get_field_value(detector_group, "x_pixel_offset") ...
1504193d1a7731740a607f77c94a810561142c57
18,229
import random def buildIterator(spec_name, param_spec, global_state, random_selection=False): """ :param param_spec: argument specification :param random_selection: produce a continuous stream of random selections :return: a iterator function to construct an iterator over possible values """ i...
d86d2af9499117614a11796c17eeccba16149092
18,230
def outlier_removal_mean(dataframe, colname, low_cut, high_cut): """Replace outliers with the mean on dataframe[colname]""" col = dataframe[colname] col_numerics = col.loc[ col.apply( lambda x: isinstance(x, (int, float)) and (x >= low_cut and x <= high_cut) ) ]...
03d40bb8098d4313e468d5b4a929756354a7732c
18,232
def non_repeating(value, counts, q): """Finds the first non-repeating string in a stream. Args: value (str): Latest string received in the string counts (dict): Dictionary of strings containing the counts to determine if string is repeated q (Queue): Container for all strings in stream ...
fc5ec025cffa0d7230d814d3677ae640cd652349
18,233
def auth_optional(request): """ view method for path '/sso/auth_optional' Return 200 reponse: authenticated and authorized 204 response: not authenticated 403 reponse: authenticated,but not authorized """ res = _auth(request) if res: #authenticated, but can be aut...
06416fdce6a652ca0cdc169c48219e685c13cdad
18,234
def is_pip_main_available(): """Return if the main pip function is available. Call get_pip_main before calling this function.""" return PIP_MAIN_FUNC is not None
3d4243bb4336fbc9eb9e93b2a1cf9ec4cc129c03
18,235
import torch def energy_target(flattened_bbox_targets, pos_bbox_targets, pos_indices, r, max_energy): """Calculate energy targets based on deep watershed paper. Args: flattened_bbox_targets (torch.Tensor): The flattened bbox targets. pos_bbox_targets (torch.Tensor): Bounding...
84bed4cc1a8bf11be778b7e79524707a49482b39
18,236
def dashtable(df): """ Convert df to appropriate format for dash datatable PARAMETERS ---------- df: pd.DataFrame, OUTPUT ---------- dash_cols: list containg columns for dashtable df: dataframe for dashtable drop_dict: dict containg dropdown list for dashtable """ ...
39897244f81a5c6ac0595aac7cb219f59d6c5739
18,237
def other_identifiers_to_metax(identifiers_list): """Convert other identifiers to comply with Metax schema. Arguments: identifiers_list (list): List of other identifiers from frontend. Returns: list: List of other identifiers that comply to Metax schema. """ other_identifiers = []...
986c98d5a557fb4fb75ed940d3f39a9a0ec93527
18,238
def enforce_excel_cell_string_limit(long_string, limit): """ Trims a long string. This function aims to address a limitation of CSV files, where very long strings which exceed the char cell limit of Excel cause weird artifacts to happen when saving to CSV. """ trimmed_string = '' ...
9b8bcf4590dc73425c304c8d778ae51d3e3f0bf3
18,239
def gaussian_blur(image: np.ndarray, sigma_min: float, sigma_max: float) -> np.ndarray: """ Blurs an image using a Gaussian filter. Args: image: Input image array. sigma_min: Lower bound of Gaussian kernel standard deviation range. sigma_max: Upper bound of Gaussian kernel standard ...
2fd31d016e4961c6980770e8dd113ae7ad45a6ed
18,240
def get_number_of_pcs_in_pool(pool): """ Retrun number of pcs in a pool """ pc_count = Computer.objects.filter(pool=pool).count() return pc_count
812de24ad2cbc738a10258f8252ca531ef72e904
18,241
from typing import List def get_used_http_ports() -> List[int]: """Returns list of ports, used by http servers in existing configs.""" return [rc.http_port for rc in get_run_configs().values()]
12982ff4d5b2327c06fef1cf874b871e2eee08c1
18,243
import io def get_img_from_fig(fig, dpi=180, color_cvt_flag=cv2.COLOR_BGR2RGB) -> np.ndarray: """Make numpy array from mpl fig Parameters ---------- fig : plt.Figure Matplotlib figure, usually the result of plt.imshow() dpi : int, optional Dots per inches of the image to save. Note...
dde9f35b78df436b30d4f9452b9964c93f924252
18,244
def split_data_by_target(data, target, num_data_per_target): """ Args: data: np.array [num_data, *data_dims] target: np.array [num_data, num_targets] target[i] is a one hot num_data_per_target: int Returns: result_data: np.array [num_data_per_target * num_targets...
d4425753b4d9892d2c593ec8e58e75bae0005c3d
18,245
def top_mutations(mutated_scores, initial_score, top_results=10): """Generate list of n mutations that improve localization probability Takes in the pd.DataFrame of predictions for mutated sequences and the probability of the initial sequence. After substracting the initial value from the values of the...
f574bf7f7569e3024a42866873c5bb589ff02095
18,246
def npmat4_to_pdmat4(npmat4): """ # updated from cvtMat4 convert numpy.2darray to LMatrix4 defined in Panda3d :param npmat3: a 3x3 numpy ndarray :param npvec3: a 1x3 numpy ndarray :return: a LMatrix3f object, see panda3d author: weiwei date: 20170322 """ return Mat4(npmat4[0, 0],...
7b58014d5d354aefac84786212b6ca190a983e48
18,247
import requests def is_at_NWRC(url): """ Checks that were on the NWRC network """ try: r = requests.get(url) code = r.status_code except Exception as e: code = 404 return code==200
b909a9087940eb70b569ea6c686ff394e84a6ed9
18,248
import torch def lmo(x,radius): """Returns v with norm(v, self.p) <= r minimizing v*x""" shape = x.shape if len(shape) == 4: v = torch.zeros_like(x) for first_dim in range(shape[0]): for second_dim in range(shape[1]): inner_x = x[first_dim][second_dim] ...
24bda333cdd64df9a0b4fa603211036bbdad7200
18,249
def _transform_index(index, func): """ Apply function to all values found in index. This includes transforming multiindex entries separately. """ if isinstance(index, MultiIndex): items = [tuple(func(y) for y in x) for x in index] return MultiIndex.from_tuples(items, names=index.na...
c642dd9330032ed784224b7ede6ee299b6d3ed67
18,250
def extractQualiTeaTranslations(item): """ # 'QualiTeaTranslations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Harry Potter and the Rise of the Ordinary Person' in item['tags']: return None i...
446b7f7598e118222c033bbfce074fa02340fd8e
18,251