content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def plot_heatmap(df, title=""): """ Plotly heatmap wrapper :param df: pd.DataFrame :param title: str """ fig = go.Figure( data=go.Heatmap(z=df.values, x=df.columns, y=df.index, colorscale="RdBu") ) fig.update_layout(template=_TEMPLATE, title=title, legend_orientation="h") ret...
46c3d362bdbe742b54ad09a56f4638ef1497bcc2
3,646,357
def shift_transactions_forward(index, tindex, file, pos, opos): """Copy transactions forward in the data file This might be done as part of a recovery effort """ # Cache a bunch of methods seek=file.seek read=file.read write=file.write index_get=index.get # Initialize, pv=z64...
c19009c15a04b4a55389b584fad1744ebde03187
3,646,360
def draw_disturbances(seed, shocks_cov, num_periods, num_draws): """Creates desired number of draws of a multivariate standard normal distribution.""" # Set seed np.random.seed(seed) # Input parameters of the distribution mean = [0, 0, 0] shocks_cov_matrix = np.zeros((3, 3), float) np.fill...
d467a1d5fde3eb32debca2711597ef24dc117aaa
3,646,361
def wheel(pos): """Generate rainbow colors across 0-255 positions.""" if pos>1280: pos = 1280 if pos <= 255: r = 255-pos g = 0 b = 255 else: pos = pos-256 if pos <= 255: r = 0 g = pos b = 255 else: p...
765df4262ce3b04fb8b06f9256ca51670e2f5bfb
3,646,363
def optimize_profile(diff_matrix, x_points, dc_init, exp_norm_profiles, display_result=True, labels=None): """ Fit the diffusion matrix Parameters ---------- diff_matrix : tuple tuple of (eigenvalues, eigenvectors) in reduced basis (dim n-1) x_points : 1-D array_li...
f2550f6fe4cb267559676d30ef0156ce528178cf
3,646,365
def getargsfromdoc(obj): """Get arguments from object doc""" if obj.__doc__ is not None: return getargsfromtext(obj.__doc__, obj.__name__)
d49510388be36a60259683f4560b1d01fe9f9bf6
3,646,366
def nms(dets, thresh): """Dispatch to either CPU or GPU NMS implementations.\ Accept dets as tensor""" return pth_nms(dets, thresh)
e6dbe7b44e1975c080e58d02d6e07ef22b2d3711
3,646,367
def QFont_from_Font(font): """ Convert the given Enaml Font into a QFont. Parameters ---------- font : Font The Enaml Font object. Returns ------- result : QFont The QFont instance for the given Enaml font. """ qfont = QFont(font.family, font.pointsize, font.weight...
bb62daf4d46315a7a55135894dc78e1d2898fee2
3,646,370
from typing import OrderedDict def _find_in_iterable_case_insensitive(iterable, name): """ Return the value matching ``name``, case insensitive, from an iterable. """ iterable = list(OrderedDict.fromkeys([k for k in iterable])) iterupper = [k.upper() for k in iterable] try: match = ite...
548c951b08fb07251fda1b8918282462c8d0351a
3,646,371
def predict_all_points(data, order, coefficients): """ :param data: input data to create least squares prediction of order(order) of :param order: order for least squares prediction :param coefficients: coefficients of LPC :return: returns estimation of entire data set. Will be of length (len(data) ...
4725c735241f439bf986743cafdee0e995373966
3,646,373
def _unpack(msg, decode=True): """Unpack and decode a FETCHed message dictionary.""" if 'UID' in msg and 'BODY[]' in msg: uid = msg['UID'] body = msg['BODY[]'] if decode: idate = msg.get('INTERNALDATE', None) flags = msg.get('FLAGS', ()) return (uid, IMAP4Message(body, uid, idate, flags)) else: r...
5c027dcd54d29f6d95647b66ad2d28998866dc3c
3,646,374
import logging def video_in(filename=INPUTPATH): """reads (max.20sec!) video file and stores every frame as PNG image for processing returns image name and image files (as np array?)""" #create video capture object cap = cv2.VideoCapture(filename) name = filename.split('/')[-1].split('.')[0] i...
cb82d7c6865c3bfe5f3f52f9cb7adc55a8d2e002
3,646,375
from typing import List def convert_all_timestamps(results: List[ResponseResult]) -> List[ResponseResult]: """Replace all date/time info with datetime objects, where possible""" results = [convert_generic_timestamps(result) for result in results] results = [convert_observation_timestamps(result) for resul...
f81121fcd387626a2baa0ecfb342d3381f6def7f
3,646,376
def convert(s): """ Take full markdown string and swap all math spans with img. """ matches = find_inline_equations(s) + find_display_equations(s) for match in matches: full = match[0] latex = match[1] img = makeimg(latex) s = s.replace(full, img) ...
684a6be3812aad8b602631c45af407ca878f9453
3,646,377
def _amplify_ep(text): """ check for added emphasis resulting from exclamation points (up to 4 of them) """ ep_count = text.count("!") if ep_count > 4: ep_count = 4 # (empirically derived mean sentiment intensity rating increase for # exclamation points) ep_amplifier = ep...
8f78a5f24aa22b5f2b4927131bfccf22ccc69ff3
3,646,379
def inline_singleton_lists(dsk): """ Inline lists that are only used once >>> d = {'b': (list, 'a'), ... 'c': (f, 'b', 1)} # doctest: +SKIP >>> inline_singleton_lists(d) # doctest: +SKIP {'c': (f, (list, 'a'), 1)} Pairs nicely with lazify afterwards """ dependencies = dict((...
a4c2a8b6d96d0bfac8e9ba88a4bed301c3054f0a
3,646,380
def vegasflowplus_sampler(*args, **kwargs): """Convenience wrapper for sampling random numbers Parameters ---------- `integrand`: tf.function `n_dim`: number of dimensions `n_events`: number of events per iteration `training_steps`: number of training_iterations Returns...
1b53d83bd010a8113640858d46d66c9c0ef76ff8
3,646,381
def remove_recalculated_sectors(df, prefix='', suffix=''): """Return df with Total gas (sum of all sectors) removed """ idx = recalculated_row_idx(df, prefix='', suffix='') return df[~idx]
54272933f72d45cf555f76086c809eba14713242
3,646,382
def unparse_headers(hdrs): """Parse a dictionary of headers to a string. Args: hdrs: A dictionary of headers. Returns: The headers as a string that can be used in an NNTP POST. """ return "".join([unparse_header(n, v) for n, v in hdrs.items()]) + "\r\n"
7c06127752d0c6be19894703ba95f2e827e89b8f
3,646,383
def modify_natoms(row, BBTs, fg): """This function takes a row of a pandas data frame and calculates the new number of atoms based on the atom difference indicated in itw functional groups BBTs : list of instances of BBT class fg : instance of the Parameters class (fg parameters) returns : n_atoms (...
2c2df3d2859d33128f982b936011c73bafb723bc
3,646,384
def recreate_cursor(collection, cursor_id, retrieved, batch_size): """ Creates and returns a Cursor object based on an existing cursor in the in the server. If cursor_id is invalid, the returned cursor will raise OperationFailure on read. If batch_size is -1, then all remaining documents on the curs...
1a4987715e35f1cf09ac3046c36c752289797ee6
3,646,385
def nut00b(date1, date2): """ Wrapper for ERFA function ``eraNut00b``. Parameters ---------- date1 : double array date2 : double array Returns ------- dpsi : double array deps : double array Notes ----- The ERFA documentation is below. - - - - - - - - - - ...
a5235543aca0d6de6e79878ac3db1d208d237a0d
3,646,386
def Join_Factors(*factor_data, merge_names=None, new_name=None, weight=None, style='SAST'): """合并因子,按照权重进行加总。只将非缺失的因子的权重重新归一合成。 Parameters: =========== factor_data: dataframe or tuple of dataframes merge_names: list 待合并因子名称,必须是data_frame中列的子集 new_name: str 合成因子名称 weight: lis...
95db1eda297cb8cb05a1db9b1fae9c25a034685f
3,646,387
from pathlib import Path def _check_for_file_changes(filepath: Path, config: Config) -> bool: """Returns True if a file was modified in a working dir.""" # Run 'git add' to avoid false negatives, as 'git diff --staged' is used for # detection. This is important when there are external factors that impact ...
c99da7e993e74f7dbe5789c48832afc59638762c
3,646,388
import time def wait_or_cancel(proc, title, message): """ Display status dialog while process is running and allow user to cancel :param proc: subprocess object :param title: title for status dialog :param message: message for status dialog :return: (process exit code, stdout output or None) ...
8b60e459523933ee205210d4761b6b7d9d8acbfb
3,646,389
def getg_PyInteractiveBody_one_in_two_out(): """Return a graph that has a PyInteractiveBody with one input and two outputs. """ @dl.Interactive( [("num", dl.Int(dl.Size(32)))], [('num_out', dl.Int(dl.Size(32))), ('val_out', dl.Bool())] ) def interactive_func(node: dl.PythonNode):...
31af32a5ece2f4c76635a8f37a0ac644c5f0e364
3,646,390
def batch_norm_relu(inputs, is_training): """Performs a batch normalization followed by a ReLU.""" # We set fused=True for a performance boost. inputs = tf.layers.batch_normalization( inputs=inputs, axis=FLAGS.input_layout.find('C'), momentum=FLAGS.batch_norm_decay, epsilon=FLAGS.batch_nor...
ab771b9d8747bc27d747dd9dce42a6bc9a1d59d3
3,646,391
def knn(points, p, k): """ Calculates the k nearest neighbours of a point. :param points: list of points :param p: reference point :param k: amount of neighbours :return: list of k neighbours """ return sorted(points, key=lambda x: distance(p, x))[:k]
e1a806cd4c16b5ecbf66301406dafeb2b12c46db
3,646,392
def ruleset_detail(request, slug): """ View for return the specific ruleset that user pass by using its slug in JSON format. :param request: WSGI request from user :return: Specific ruleset metadata in JSON format. """ # try to fetch ruleset from database try: ruleset = Ruleset.obje...
a122a2e20641a13d6a934c0261f199ff304ae622
3,646,393
import requests import json def send_slack_notification(message): """ Send slack notification Arguments: message {string} -- Slack notification message Returns: response {Response} -- Http response object """ response = requests.post( SLACK_WEBHOOK, data=json.d...
6c5f0e51c1bfce19ff9a4aec77c1e4c98cd359fa
3,646,394
def method_detect(method: str): """Detects which method to use and returns its object""" if method in POSTPROCESS_METHODS: if method == "rtb-bnb": return RemovingTooTransparentBordersHardAndBlurringHardBorders() elif method == "rtb-bnb2": return RemovingTooTransparentBord...
cb1dafba5a7c225c093ab602c6e383cb7f499bba
3,646,396
def approve_pipelines_for_publishing(pipeline_ids): # noqa: E501 """approve_pipelines_for_publishing # noqa: E501 :param pipeline_ids: Array of pipeline IDs to be approved for publishing. :type pipeline_ids: List[] :rtype: None """ return util.invoke_controller_impl()
585d4972955e240f146c3d06d5a181dcad36d111
3,646,397
def get_x(document_id, word2wid, corpus_termfrequency_vector): """ Get the feature vector of a document. Parameters ---------- document_id : int word2wid : dict corpus_termfrequency_vector : list of int Returns ------- list of int """ word_list = list(reuters.words(docu...
fca6e5a6071a6b48b83effb37d3b77a88ddf4046
3,646,398
def process_chain_of_trust(host: str, image: Image, req_delegations: list): """ Processes the whole chain of trust, provided by the notary server (`host`) for any given `image`. The 'root', 'snapshot', 'timestamp', 'targets' and potentially 'targets/releases' are requested in this order and afterwards ...
391024aeaa814f3159c8f45a925afce105b7b339
3,646,399
import struct def collect_js( deps, closure_library_base = None, has_direct_srcs = False, no_closure_library = False, css = None): """Aggregates transitive JavaScript source files from unfurled deps.""" srcs = [] direct_srcs = [] ijs_files = [] infos = [] ...
7a243401280646103522ed339ff20c35f05e031d
3,646,400
import termios import struct import fcntl def send_control(uuid, type, data): """ Sends control data to the terminal, as for example resize events """ sp = sessions[uuid] if type == 'resize': winsize = struct.pack("HHHH", data['rows'], data['cols'], 0, 0) fcntl.ioctl(sp['ptymaster...
262ef0ccffac80c0293d1446eb0e38e50b2ce687
3,646,401
def dgausscdf(x): """ Derivative of the cumulative distribution function for the normal distribution. """ return gausspdf(x)
e968f20ca28555eb50d5766440c5f3f47522c1ff
3,646,404
import tqdm def model_datasets_to_rch(gwf, model_ds, print_input=False): """convert the recharge data in the model dataset to a recharge package with time series. Parameters ---------- gwf : flopy.mf6.modflow.mfgwf.ModflowGwf groundwater flow model. model_ds : xr.DataSet datas...
b32442c508e17205737ddb8168fe323b57cfbb2f
3,646,406
from typing import List from datetime import datetime def create_events_to_group( search_query: str, valid_events: bool, group: Group, amount: int = 1, venue: bool = False, ) -> List[Event]: """ Create random test events and save them to a group Arguments: search_query {str} -...
31045c8f9311d677d766d87ed9fc1d6848cc210d
3,646,407
def alt_stubbed_receiver() -> PublicKey: """Arbitrary known public key to be used as reciever.""" return PublicKey("J3dxNj7nDRRqRRXuEMynDG57DkZK4jYRuv3Garmb1i98")
c07461fc060f9dc637e93cadd32604aae892f924
3,646,408
import base64 def create_api_headers(token): """ Create the API header. This is going to be sent along with the request for verification. """ auth_type = 'Basic ' + base64.b64encode(bytes(token + ":")).decode('ascii') return { 'Authorization': auth_type, 'Accept': 'applicatio...
41ba1e22898dab2d42dde52e4458abc40640e957
3,646,409
def _combine(bundle, transaction_managed=False, rollback=False, use_reversion=True): """ Returns one sreg and DHCP output for that SREG. If rollback is True the sreg will be created and then rolleback, but before the rollback all its HWAdapters will be polled for their DHCP output. """...
0171e804e4f10167d85e92608a09bca55308edfa
3,646,410
def get_node_session(*args, **kwargs): """Creates a NodeSession instance using the provided connection data. Args: *args: Variable length argument list with the connection data used to connect to the database. It can be a dictionary or a connection string. **kwargs...
bb992b7e49a698dfb7b54b1492616913a6b5df27
3,646,411
def edit_role(payload, search_term): """Find and edit the role.""" role = Role.query.get(search_term) # if edit request == stored value if not role: return response_builder(dict(status="fail", message="Role does not exist."), 404) try: if payload...
8690c8fc1c1aea5245d9cef540c355a2903a8484
3,646,413
def use_redis_cache(key, ttl_sec, work_func): """Attemps to return value by key, otherwise caches and returns `work_func`""" redis = redis_connection.get_redis() cached_value = get_pickled_key(redis, key) if cached_value: return cached_value to_cache = work_func() pickle_and_set(redis, k...
a2c631466aef18c7bb640b17e57421e257ad7314
3,646,414
def counting_sort(array, low, high): """Razeni pocitanim (CountingSort). Seradte zadane pole 'array' pricemz o poli vite, ze se v nem nachazeji pouze hodnoty v intervalu od 'low' po 'high' (vcetne okraju intervalu). Vratte serazene pole. """ counts = [0 for i in range(high - low + 1)] for elem i...
bd4ccccdb24786ec3f3d867afe1adf340c9e53b5
3,646,415
import re def normalize_archives_url(url): """ Normalize url. will try to infer, find or guess the most useful archives URL, given a URL. Return normalized URL, or the original URL if no improvement is found. """ # change new IETF mailarchive URLs to older, still available text .mail archive...
e8a5351af28338c77c3e94fdf2b81e22c7a6edfd
3,646,416
def getIsolatesFromIndices(indices): """ Extracts the isolates from the indices of a df_X. :param pandas.index indices: cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP :return dict: keyed by cn.KEY_ISOLATE_DVH, cn.KEY_ISOLATE_MMP values correspond to rows element in the index """ keys = [n for n in indice...
4e9200c722ce0c478d13eddcc799f4a8f7cab6db
3,646,418
def save_group_geo_org(user_id, group_id, area_id, org_unit_id): """Method for attaching org units and sub-counties.""" try: if org_unit_id: geo_org_perm, ctd = CPOVCUserRoleGeoOrg.objects.update_or_create( user_id=user_id, group_id=group_id, org_unit_id=org_unit_id, ...
ed7750760405e12f790454e247e54917184e7044
3,646,419
def tf_efficientnet_lite0(pretrained=False, **kwargs): """ EfficientNet-Lite0 """ # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2 kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnet_lite( 'tf_efficientnet_lite0', channel_multipli...
49ea1c68f168ad613222808e2fbb1ead52190243
3,646,420
import ast from typing import Optional def get_qualname(node: ast.AST) -> Optional[str]: """ If node represents a chain of attribute accesses, return is qualified name. """ parts = [] while True: if isinstance(node, ast.Name): parts.append(node.id) break eli...
0d08b25a50b7d159f5df3b0b17282725eb748f38
3,646,422
def traceUsage(addr, register, steps): """ Given a start address, a register which holds a value and the number of steps, this function disassembles forward #steps instructions and traces the value of <register> until it is used in a call instruction. It then returns the offset added to <register> and the addre...
78c805af660b5e98348de1bd1ae4b7ce9a57238b
3,646,423
def array3d (surface): """pygame.surfarray.array3d (Surface): return array Copy pixels into a 3d array. Copy the pixels from a Surface into a 3D array. The bit depth of the surface will control the size of the integer values, and will work for any type of pixel format. This function will temp...
a2079a540453d5ba69f5b10e292341ef6fcfb972
3,646,425
import torch def masked_kl_div(input, target, mask): """Evaluate masked KL divergence between input activations and target distribution. Parameters: input (tensor) - NxD batch of D-dimensional activations (un-normalized log distribution). target (tensor) - NxD normalized target distribution. ...
afdd704bac7caabd7d0cbbd2599af6c1a440ae1c
3,646,426
def find_peaks(ts, mindist=100): """ Find peaks in time series :param ts: :return: """ extreme_value = -np.inf extreme_idx = 0 peakvalues = [] peaktimes = [] find_peak = True idx = 0 for r in ts.iteritems(): # print(r) if find_peak: # look fo...
5f4dbf0b6c9e4e8961c14b1ba255ebcdf210c50b
3,646,428
def get_flanking_seq(genome, scaffold, start, end, flanking_length): """ Get flanking based on Blast hit """ for rec in SeqIO.parse(genome, "fasta"): if rec.id == scaffold: return str( rec.seq[int(start) - int(flanking_length) : int(end) + int(flanking_length)] ...
509002a7099ad62b0449e1c5de9a1a7dd875bc0c
3,646,430
import re def d(vars): """List of variables starting with string "df" in reverse order. Usage: d(dir()) @vars list of variables output by dir() command """ list_of_dfs = [item for item in vars if (item.find('df') == 0 and item.find('_') == -1 and item != 'dfs')] list_of_dfs.sort(key=lambda x:int(...
4961ae70a61e45b81e06e55ee9553ff61fd45d18
3,646,431
import inspect def get_class_namespaces(cls: type) -> tuple[Namespace, Namespace]: """ Return the module a class is defined in and its internal dictionary Returns: globals, locals """ return inspect.getmodule(cls).__dict__, cls.__dict__ | {cls.__name__: cls}
46f275bcc328d9ca87ffdebf616d42096705d3fb
3,646,432
from .io import select_driver def write_stream(path, sync=True, *args, **kwargs): """Creates a writer object (context manager) to write multiple dataframes into one file. Must be used as context manager. Parameters ---------- path : str, filename or path to database table sync : bool, default True Set to `Fal...
8e2274e102b60b139b6e40f425682d06268e10a5
3,646,433
from typing import Dict def diff( df: DataFrame, columns: Dict[str, str], periods: int = 1, axis: PandasAxis = PandasAxis.ROW, ) -> DataFrame: """ Calculate row-by-row or column-by-column difference for select columns. :param df: DataFrame on which the diff will be based. :param colum...
38ed83fc7e1847a2c9e31abb217990becc1bc04f
3,646,434
import base64 def decodeTx(data: bytes) -> Transaction: """Function to convert base64 encoded data into a transaction object Args: data (bytes): the data to convert Returns a transaction object """ data = base64.b64decode(data) if data[:1] != tx_flag: return None ...
da52e9dcb641d2986fa47d15f9da8d1edea28659
3,646,435
def create_package_from_datastep(table): """Create an importable model package from a score code table. Parameters ---------- table : swat.CASTable The CAS table containing the score code. Returns ------- BytesIO A byte stream representing a ZIP archive which can be importe...
0874f1a755ed73af09091a7c0f1b3fb3e5e861e4
3,646,436
def _test_diff(diff: list[float]) -> tuple[float, float, float]: """Последовательный тест на медианную разницу с учетом множественного тестирования. Тестирование одностороннее, поэтому p-value нужно умножить на 2, но проводится 2 раза. """ _, upper = seq.median_conf_bound(diff, config.P_VALUE / populat...
024d0eaba612361e4fef39839bfd31474d5be5a6
3,646,437
def get_repo_of_app_or_library(app_or_library_name): """ This function takes an app or library name and will return the corresponding repo for that app or library""" specs = get_specs() repo_name = specs.get_app_or_lib(app_or_library_name)['repo'] if not repo_name: return None return Rep...
72c0349354fdc11da3ff16f2dfa3126eb02fa381
3,646,438
from datetime import datetime def get_index_price_change_by_ticker(fromdate: str, todate: str, market: str="KOSPI") -> DataFrame: """입력된 기간동안의 전체 지수 등락률 Args: fromdate (str ): 조회 시작 일자 (YYMMDD) todate (str ): 조회 종료 일자 (YYMMDD) market (str, optional): 조회 시장 (KOSPI...
6d65ffeaccd1e5fe307e1e5387e413db3c2eb5fe
3,646,439
def axpy(alpha, x, y, stream=None): """y <- alpha*x + y """ global _blas if not isinstance(alpha, Number): raise ValueError('alpha is not a numeric type') validate_argument_dtype(x, 'x') validate_argument_dtype(y, 'y') if not _blas: _blas = Blas() _blas.stream = stream dtype = promote(...
10b8c46b1fc160d637241750c408957b8f184ee9
3,646,440
def _unenroll_get_hook(app_context): """Add field to unenroll form offering data removal, if policy supports.""" removal_policy = _get_removal_policy(app_context) return removal_policy.add_unenroll_additional_fields(app_context)
6c8e6a06d45fecfa8828ce8a24ca9e1e910b1e9c
3,646,441
from typing import Union def query_fetch_bom_df(search_key: str, size: int) -> Union[pd.DataFrame, None]: """Fetch and return bom dataframe of the article Runs recursive query on database to fetch the bom. """ # Recursive query raw_query = f"""WITH cte AS ( SELECT * FROM [{DB_NAM...
753f0378590df1c2b3e50f7bad8d2b15490ae488
3,646,442
def zscore(collection, iteratee=None): """Calculate the standard score assuming normal distribution. If iteratee is passed, each element of `collection` is passed through a iteratee before the standard score is computed. Args: collection (list|dict): Collection to process. iteratee (mix...
a813295f6cce309b936b94a9d70f082f435a4b89
3,646,443
from typing import Tuple def AND( *logicals: Tuple[func_xltypes.XlExpr] ) -> func_xltypes.XlBoolean: """Determine if all conditions in a test are TRUE https://support.office.com/en-us/article/ and-function-5f19b2e8-e1df-4408-897a-ce285a19e9d9 """ if not logicals: raise xlerror...
ebdc5c4f2c3cab31a78507923eded284eb679fd4
3,646,444
def check_mask(mask): """Check if mask is valid by its area""" area_ratio = np.sum(mask) / float(mask.shape[0] * mask.shape[1]) return (area_ratio > MASK_THRES_MIN) and (area_ratio < MASK_THRES_MAX)
a82f415d95ea07571da2aabeeddc6837b0a80f8d
3,646,445
def supported_estimators(): """Return a `dict` of supported estimators.""" allowed = { 'LogisticRegression': LogisticRegression, 'RandomForestClassifier': RandomForestClassifier, 'DecisionTreeClassifier': DecisionTreeClassifier, 'KNeighborsClassifier': KNeighborsClassifier, ...
1bb76e81252c3b959a376f23f2462d4faef234a9
3,646,446
from hiicart.gateway.base import GatewayError from hiicart.gateway.amazon.gateway import AmazonGateway from hiicart.gateway.google.gateway import GoogleGateway from hiicart.gateway.paypal.gateway import PaypalGateway from hiicart.gateway.paypal2.gateway import Paypal2Gateway from hiicart.gateway.paypal_adaptive.gateway...
c60e3e88cf6bb919208821d8ee214368d39dc7f6
3,646,447
import sqlite3 def execute_query(db, query): """get data from database """ result = [] with closing(sqlite3.connect(db)) as conn: conn.row_factory = sqlite3.Row cur = conn.cursor() for row in cur.execute(query): result.append({name: row[name] for name in row.keys()}...
75476c8a9f14751eb46fc2891ba5e7bddecd3c0e
3,646,448
def to_mgb_supported_dtype(dtype_): """get the dtype supported by megbrain nearest to given dtype""" if ( dtype.is_lowbit(dtype_) or dtype.is_quantize(dtype_) or dtype.is_bfloat16(dtype_) ): return dtype_ return _detail._to_mgb_supported_dtype(dtype_)
864b5bb7099771705ad478e5e89db8f3035f1c4f
3,646,450
def get_reset_state_name(t_fsm): """ Returns the name of the reset state. If an .r keyword is specified, that is the name of the reset state. If the .r keyword is not present, the first state defined in the transition table is the reset state. :param t_fsm: blifparser.BlifParser().blif.fsm ob...
c65ea80f94f91b31a179faebc60a97f7260675c4
3,646,451
def gridmake(*arrays): """ Expands one or more vectors (or matrices) into a matrix where rows span the cartesian product of combinations of the input arrays. Each column of the input arrays will correspond to one column of the output matrix. Parameters ---------- *arrays : tuple/list of np....
56c5375024170fbd599500c0603e0e3dcc7f53d4
3,646,452
import logging import math def pagerotate(document: vp.Document, clockwise: bool): """Rotate the page by 90 degrees. This command rotates the page by 90 degrees counter-clockwise. If the `--clockwise` option is passed, it rotates the page clockwise instead. Note: if the page size is not defined, an ...
37f0a9e726f490c357afb48ace49484cfcae84ce
3,646,453
import torch def gauss_reparametrize(mu, logvar, n_sample=1): """Gaussian reparametrization""" std = logvar.mul(0.5).exp_() size = std.size() eps = Variable(std.data.new(size[0], n_sample, size[1]).normal_()) z = eps.mul(std[:, None, :]).add_(mu[:, None, :]) z = torch.clamp(z, -4., 4.) ret...
5c4fa87c5287aae3727608a003c3c91c2ba5c1a9
3,646,456
def forward_pass(img, session, images_placeholder, phase_train_placeholder, embeddings, image_size): """Feeds an image to the FaceNet model and returns a 128-dimension embedding for facial recognition. Args: img: image file (numpy array). session: The active Tensorflow session. images_pl...
846c05a167e116ca4efbe3888486a3ee740d33ef
3,646,458
import urllib def check_url(url): """Returns True if the url returns a response code between 200-300, otherwise return False. """ try: req = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(req) return response.code in range(200, 209) except...
79f20eeb14724b728f020ff4c680e49f6a1a2473
3,646,459
def build_permutation_importance( data, data_labels, feature_names, model, metrics, repeats=100, random_seed=42 ): """Calculates permutation feature importance.""" pi_results = {} for metric in metrics: pi = sklearn.inspection.permutation_i...
3b0b87ddf53446156b20189dad7c3d0b3ae2a1c2
3,646,460
def _load_parent(collection, meta): """Determine the parent document for the document that is to be ingested.""" parent = ensure_dict(meta.get("parent")) parent_id = meta.get("parent_id", parent.get("id")) if parent_id is None: return parent = Document.by_id(parent_id, collection=collect...
2f53440fa9610f9e8ca494ec8ec27bf9d6a09273
3,646,461
import requests def get_latest_sensor_reading(sensor_serial, metric): """ Get latest sensor reading from MT sensor metrics: 'temperature', 'humidity', 'water_detection' or 'door' """ headers = { "Content-Type": "application/json", "Accept": "application/json", "X-Cisco-Mera...
88de9d770f3be91700e3c86ff6460e2fdaa35d01
3,646,462
def border_msg(msg: str): """ This function creates boarders in the top and bottom of text """ row = len(msg) h = ''.join(['+'] + ['-' * row] + ['+']) return h + "\n" + msg + "\n" + h
cdd9d17ba76014f4c80b9c429aebbc4ca6f959c3
3,646,463
def create_app(config_name='development'): """Returns flask app based on the configuration""" flask_app = Flask(__name__) flask_app.config.from_object(app_config[config_name]) flask_app.config['JSON_SORT_KEYS'] = False flask_app.url_map.strict_slashes = False flask_app.register_error_handler(400...
783edefb40c2f3cc0aefa0788b0c1c04d581aa39
3,646,464
def auto_merge_paths(data, auto_merge_distance, auto_close_paths=True): """ This function connects all paths in the given dataset, for which the start or endpoints are closer than auto_merge_distance. :param data: Should be a list or tuple containing paths, attributes, svg_attributes. :param auto_m...
34ec7d0b853a70159ebef6244236475375a3ca9d
3,646,465
def is_authorized(secure: AccessRestriction): """Returns authorization status based on the given access restriction. :param secure: access restriction :type secure: AccessRestriction :return: authorization status (``True`` or ``False``) """ if secure == AccessRestriction.ALL: return Tru...
e070ae5521db1079426b80b6ff8a3fc5c9a9ba09
3,646,466
def create_link_forum(**attrs): """Save a new link forum.""" link = build_link_forum(**attrs) link.save() return link
e94e1001e42f46cd1c1803fbff35d0eded89858e
3,646,467
def prepare_scan(): """ Returns a lexical scanner for HTSQL grammar. """ # Start a new grammar. grammar = LexicalGrammar() # Regular context. query = grammar.add_rule('query') # Whitespace characters and comments (discarded). query.add_token(r''' SPACE: [\s]+ | [#] [^\0\r...
ffc30354378a03f95be988b7ee62b01708795f41
3,646,469
def get_test_server(ctxt, **kw): """Return a Server object with appropriate attributes. NOTE: The object leaves the attributes marked as changed, such that a create() could be used to commit it to the DB. """ kw['object_type'] = 'server' get_db_server_checked = check_keyword_arguments( ...
03d754223274282b15aeb9b5cf636f6acd90024c
3,646,470
def keras_model(optimizer="Adamax", activation="softplus", units=32): """Function to create model, required for KerasClassifier""" model = Sequential() model.add(Dense(units, activation="relu", input_dim=2500)) model.add(Dense(2, activation=activation)) model.compile(loss="categorical_crossentropy",...
ccd1cc5652a207e3c4c2bc170d43fe22b4375c0b
3,646,471
def start_end_key(custom_cmp): """ Compare models with start and end dates. """ class K(object): """ Define comparison operators. http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/ """ def __init__(self, obj, *args): s...
b1d7b48cc3e9926b6138850ad3b8307adbb4f2f3
3,646,472
def get_previous_release_date(): """ Fetch the previous release date (i.e. the release date of the current live database) """ releases = Release.objects.all().order_by('-date') return str(releases[1].date)
764d90daaf5c60460f22e56063a40c261cb6b45e
3,646,473
def readLensModeParameters(calibfiledir, lensmode='WideAngleMode'): """ Retrieve the calibrated lens correction parameters """ # For wide angle mode if lensmode == 'WideAngleMode': LensModeDefaults, LensParamLines = [], [] with open(calibfiledir, 'r') as fc: # Read the...
51245aa19f32ebb31df5748e0b40022ccae01e24
3,646,474
def scale(boxlist, y_scale, x_scale, scope=None): """scale box coordinates in x and y dimensions. Args: boxlist: BoxList holding N boxes y_scale: (float) scalar tensor x_scale: (float) scalar tensor scope: name scope. Returns: boxlist: BoxList holding N boxes """ with...
adffbdce632470852e0499bb93915f93a7695d5a
3,646,475
import requests def fetch(uri: str, method: str = 'get', token: str = None): """:rtype: (str|None, int)""" uri = 'https://api.github.com/{0}'.format(uri) auth = app.config['GITHUB_AUTH'] headers = {'Accept': 'application/vnd.github.mercy-preview+json'} json = None if token: headers['A...
14cde2808108173e6ab86f3eafb4c8e35daf4b40
3,646,476
from typing import OrderedDict from typing import Mapping from typing import Sequence from typing import Container from typing import Iterable from typing import Sized def nested_tuple(container): """Recursively transform a container structure to a nested tuple. The function understands container types inher...
60dac69865d753b14558d7156e40703e26fb57a1
3,646,477
from typing import OrderedDict def _validate_args(func, args, kwargs): """Validate customer function args and convert them to kwargs.""" # Positional arguments validate all_parameters = [param for _, param in signature(func).parameters.items()] # Implicit parameter are *args and **kwargs if any(pa...
51d357d032dc0b26aeb32d1850b1a630bafab508
3,646,478
def _qual_arg(user_value, python_arg_name, gblock_arg_name, allowable): """ Construct and sanity check a qualitative argument to send to gblocks. user_value: value to try to send to gblocks python_arg_name: name of python argument (for error string) gbl...
7bf6717ee3dbeb533902773c86316d2bbdcd59a9
3,646,479