content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Any def vgg16(pretrained:bool=False,progress:bool=True,**kwargs:Any) ->VGG: """ Args: pretrained(bool):是否加载预训练参数 progress(bool):是否显示下载数据的进度条 Return: 返回VGG模型 """ return _vgg("vgg16","D",False,pretrained,progress,**kwargs)
82d64394a705caa9e0a0c1e661078c9ea299fa05
3,656,746
def cy_gate(N=None, control=0, target=1): """Controlled Y gate. Returns ------- result : :class:`qutip.Qobj` Quantum object for operator describing the rotation. """ if (control == 1 and target == 0) and N is None: N = 2 if N is not None: return gate_expand_2toN(cy...
8927557d0afe096218acf1ac0283c5ec073e3f98
3,656,747
def sqf(f, *gens, **args): """ Compute square-free factorization of ``f``. **Examples** >>> from sympy import sqf >>> from sympy.abc import x >>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) 2*(1 + x)**2*(2 + x)**3 """ return _generic_factor(f, gens, args, method='sqf')
5f0267b7c314269e64c32951824346542e3e3452
3,656,748
def update_options_dpd2(dpd1_val): """ Updates the contents of the second dropdown menu based of the value of the first dropdown. :param dpd1_val: str, first dropdown value :return: list of dictionaries, labels and values """ all_options = [ strings.CITY_GDANSK, strings.CITY_GDY...
4a2d0494f04e3026b133f61a70757046f011b5f1
3,656,749
import csv def compute_min_paths_from_monitors(csv_file_path, delimiter='\t', origin_as=PEERING_ORIGIN): """ Inputs: csv_file_path, delimiter : csv file containing entries with the following format: |collector|monitor|as_path, and the delimiter used origin_as: the ASN you want to u...
6f0c1e26062213ea14af80a803c6e6ebd25c6543
3,656,750
def _blanking_rule_ftld_or3a(rule): """ See _blanking_rule_ftld_or2a for rules """ if rule == 'Blank if Question 1 FTDIDIAG = 0 (No)': return lambda packet: packet['FTDIDIAG'] == 0 elif rule == 'Blank if Question 3 FTDFDGPE = 0 (No)': return lambda packet: packet['FTDFDGPE'] == 0 elif ru...
cc0a925c7ad6ad72c4041d369f9a820c0a6a6b96
3,656,751
def compute_angular_differences(matrix, orientation1, orientation2, cutoff): """ Compute angular difference between two orientation ndarrays :param matrix: domain matrix :type matrix: np.ndarray :param orientation1: orientation as (x, y, z, 3) :type orientation1: np.ndarray ...
3ec860c484057de91eb306079328faff87a9b0e4
3,656,753
def await(*args): """Runs all the tasks specified in args, and finally returns args unwrapped. """ return _await(args)
1065986a6ac067222bf5c6ff47a395ab4d0c890e
3,656,754
def convert_action_move_exists(action, board, player_turn): """ Converts action index to chess.Move object. Assume the action key exists in map_action_uci :param action: :param board: :param player_turn: :return: """ move = chess.Move.from_uci(map_action_uci[action]) if player_t...
f4c508a99967d65b6f2f07159fe3003730b220a2
3,656,755
import pwd import win32api def _get_system_username(): """Return the current system user.""" if not win32: return pwd.getpwuid(getuid())[0] else: return win32api.GetUserName()
4dfdc93630d2c3940c7087fc2125f81f0e385d9f
3,656,757
import glob def _get_vmedia_device(): """Finds the device filename of the virtual media device using sysfs. :returns: a string containing the filename of the virtual media device """ sysfs_device_models = glob.glob("/sys/class/block/*/device/model") vmedia_device_model = "virtual media" for m...
e8f8e83b7bf0c73d10d8893a5b4b49670edba7ac
3,656,758
def convert_to_posixpath(file_path): """Converts a Windows style filepath to posixpath format. If the operating system is not Windows, this function does nothing. Args: file_path: str. The path to be converted. Returns: str. Returns a posixpath version of the file path. """ if ...
9a8e6559b7916ba7547f87ce3bba6b50362c7ded
3,656,759
def generateCards(numberOfSymb): """ Generates a list of cards which are themselves a list of symbols needed on each card to respect the rules of Dobble. This algorithm was taken from the french Wikipedia page of "Dobble". https://fr.wikipedia.org/wiki/Dobble :param numberOfSymb: Number of symbols needed on each c...
8f51c1f339d62b6fd88cb8d0fae692053bffc084
3,656,760
def match_facilities(facility_datasets, authoritative_dataset, manual_matches_df=None, max_distance=150, nearest_n=10, meters_crs='epsg:5070', reducer_fn=None): """Matches facilities. The da...
97f169ccda8cf0b26bfa423936d8b663e6237d22
3,656,762
def has_field_warning(meta, field_id): """Warn if dataset has existing field with same id.""" if meta.has_field(field_id): print( "WARN: Field '%s' is already present in dataset, not overwriting." % field_id ) print("WARN: Use '--replace' flag to overwrite existin...
1cc5016f8ffcce698bcb53dcf6f307b760d7df55
3,656,763
def volume(surface): """Compute volume of a closed triangulated surface mesh.""" properties = vtk.vtkMassProperties() properties.SetInput(surface) properties.Update() return properties.GetVolume()
1969e3c6245cd76c50cdea19be41165ff16f73fc
3,656,764
def simulate(): """ Simulate one thing """ doors = getRandomDoorArray() pickedDoor = chooseDoor() goatDoor, switchDoor = openGoatDoor(pickedDoor, doors) return doors[pickedDoor], doors[switchDoor]
607fc6d0bdb5d24dc68c371c81e9e7028a54631f
3,656,765
def fc_layer(x): """Basic Fully Connected (FC) layer with an activation function.""" return x
f26865e13065187363746b8bfe7d95ac221bf236
3,656,766
from typing import Dict import collections def get_slot_counts(cls: type) -> Dict[str, int]: """ Collects all of the given class's ``__slots__``, returning a dict of the form ``{slot_name: count}``. :param cls: The class whose slots to collect :return: A :class:`collections.Counter` counting the ...
7cb7c41c1d4f40aab1acd473f5e1238e4aefad44
3,656,767
def rot6d_to_axisAngle(x): """"Convert 6d rotation representation to axis angle Input: (B,6) Batch of 6-D rotation representations Output: (B,3) Batch of corresponding axis angle """ rotMat = rot6d_to_rotmat(x) return rotationMatrix_to_axisAngle(rotMat)
17b24e0bb7521baa56df034c4e59658d4320c4cf
3,656,768
import six def within_tolerance(x, y, tolerance): """ Check that |x-y| <= tolerance with appropriate norm. Args: x: number or array (np array_like) y: number or array (np array_like) tolerance: Number or PercentageString NOTE: Calculates x - y; may raise an error for incompat...
918b14e33aeca426e24151d7a1eda2d340423b4d
3,656,769
def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0): """ Integrate a Hermite_e series. Returns the Hermite_e series coefficients `c` integrated `m` times from `lbnd` along `axis`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The sca...
af1f024f4b6d60793fb3aa6ca2bcbe517c4b178f
3,656,770
def model_netradiation(minTair = 0.7, maxTair = 7.2, albedoCoefficient = 0.23, stefanBoltzman = 4.903e-09, elevation = 0.0, solarRadiation = 3.0, vaporPressure = 6.1, extraSolarRadiation = 11.7): """ - Description: * Title: NetRadi...
369fffe5eef94148baa8526421adbbac7c3477fd
3,656,771
def get_tagset(sentences, with_prefix): """ Returns the set of entity types appearing in the list of sentences. If with_prefix is True, it returns both the B- and I- versions for each entity found. If False, it merges them (i.e., removes the prefix and only returns the entity type). """ iobs =...
c0b00f7c5546bfc7fe10b2d4b35998b5dedeba21
3,656,772
def normpath(s: str) -> str: """Normalize path. Just for compatibility with normal python3.""" return s
30c528b11f75f52275b753c789e2e3d5bf71641c
3,656,774
def threshold_num_spikes( sorting, threshold, threshold_sign, sampling_frequency=None, **kwargs ): """ Computes and thresholds the num spikes in the sorted dataset with the given sign and value. Parameters ---------- sorting: SortingExtractor The sort...
37974060e23f8dbde2d3dd1246b0583ed16d4a87
3,656,775
def mad(stack, axis=0, scale=1.4826): """Median absolute deviation, default is scaled such that +/-MAD covers 50% (between 1/4 and 3/4) of the standard normal cumulative distribution """ stack_abs = np.abs(stack) med = np.nanmedian(stack_abs, axis=axis) return scale * np.nanmedian(np.abs(st...
c9425b8006476b11cc559a025597c5b620294b50
3,656,776
def _get_window(append, size=(1000, 600)): """ Return a handle to a plot window to use for this plot. If append is False, create a new plot window, otherwise return a handle to the given window, or the last created window. Args: append (Union[bool, PlotWindow]): If true, return the last ...
45ff89055db2caa442f55c80042820194554bed8
3,656,778
def _proxies_dict(proxy): """Makes a proxy dict appropriate to pass to requests.""" if not proxy: return None return {'http': proxy, 'https': proxy}
ce51015dc652c494dc89bb11e21f18803ba34c85
3,656,779
def _get_schedule_times(name, date): """ Fetch all `from_time` from [Healthcare Schedule Time Slot] :param name: [Practitioner Schedule] :param date: [datetime.date] :return: """ mapped_day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] time_slots = frap...
64de318f8bbe827e40566799172590f0e448a3d5
3,656,780
def delete(client, data, force=False): """ """ param = {'logical-router-port-id': get_id(client, data)} if force: param['force'] = True request = client.__getattr__(MODULE).DeleteLogicalRouterPort(**param) response, _ = request.result() return response
e573b962273f4ffc0ea4b0d5693329013fca4a6b
3,656,781
import warnings def z_standardization( spark, idf, list_of_cols="all", drop_cols=[], pre_existing_model=False, model_path="NA", output_mode="replace", print_impact=False, ): """ Standardization is commonly used in data pre-processing process. z_standardization standardizes the ...
962a7aa5721cc7d672c858d573af3c1d021e74d7
3,656,782
def event_stats(wit_df, wit_im, wit_area, pkey='SYSID'): """ Compute inundation event stats with given wit wetness, events defined by (start_time, end_time) and polygon areas input: wit_df: wetness computed from wit data wit_im: inundation event wit_area:...
f1bcef7604e15fc9b5a845ed45b976e22655d469
3,656,783
def upvote_book(book_id): """ Allows a user to upvote a book. The upvotes field on the book document is updated, as well as the booksUpvoted array on the user document and the upvotedBy array on the book document. """ user_to_update = mongo.db.users.find_one({"username": session["user"]}) ...
6a27c46e9540b871f4123c166d9cecaebc016c6b
3,656,784
import numpy def bottlegrowth_split_mig(params, ns): """ params = (nuB, nuF, m, T, Ts) ns = [n1, n2] Instantanous size change followed by exponential growth then split with migration. nuB: Ratio of population size after instantanous change to ancient population size nuF: Ratio o...
dd191a7246d6575b784e61d8e1def17c0f143a7d
3,656,785
def arch_to_macho(arch): """Converts an arch string into a macho arch tuple.""" try: arch = rustcall(lib.symbolic_arch_to_macho, encode_str(arch)) return (arch.cputype, arch.cpusubtype) except ignore_arch_exc: pass
2ffc1be349fc8438bc5b49bab1d9c79e8cbebdd3
3,656,786
def limit_ops_skeleton(**kwargs): """This function provides a skeleton for limit ops calculations""" group_phase = kwargs['group_phase'] tail = kwargs['tail'] loading_phase = kwargs['loading_phase'] final_phase = kwargs['final_phase'] grouped_df = limit_ops_general_groups( **group_phase...
fb2dd1da8f2229794705376e15076477160bce35
3,656,787
def xy2traceset(xpos, ypos, **kwargs): """Convert from x,y positions to a trace set. Parameters ---------- xpos, ypos : array-like X,Y positions corresponding as [nx,Ntrace] arrays. invvar : array-like, optional Inverse variances for fitting. func : :class:`str`, optional ...
7f4146600678cdb3699b239bf49a5d6062ef2a2e
3,656,788
import slate3k as slate import logging def leer_pdf_slate(ubicacion_archivo, password=None): """ Utiliza la librería slate3k para cargar un archivo PDF y extraer el texto de sus páginas. :param ubicacion_archivo: (str). Ubicación del archivo PDF que se desea leer. :param password: (str). Valor por d...
3e52c463238f1ecec30d34661eb8f53a6cf031a7
3,656,790
def gen_run_entry_str(query_id, doc_id, rank, score, run_id): """A simple function to generate one run entry. :param query_id: query id :param doc_id: document id :param rank: entry rank :param score: entry score :param run_id: run id """ return f'{query_id} Q0 {doc_id} {rank}...
657c59fea34e4aed2159337360c973dc99b53082
3,656,791
from pathlib import Path def remove_template(args, output_file_name): """ remove the arg to use template; called when you make the template :param args: :param output_file_name: :return: """ template_name = '' dir_name = '' template_found = False for i in args: if i.st...
652fa0112dd0b5287e1f98c5e70f84cacaa979c1
3,656,792
def replaceext(filepath, new_ext, *considered_exts): """replace extension of filepath with new_ext filepath: a file path new_ext: extension the returned filepath should have (e.g ".ext") considered_exts: Each is a case insensitive extension that should be considered a single extension and replace...
4e1abee01270921d01de1e75614612dcec8485d7
3,656,793
def textarea(name, content="", id=NotGiven, **attrs): """Create a text input area. """ attrs["name"] = name _set_id_attr(attrs, id, name) return HTML.tag("textarea", content, **attrs)
da85bdeb2d819eaa2e8109036087700afd270a21
3,656,794
def StretchContrast(pixlist, minmin=0, maxmax=0xff): """ Stretch the current image row to the maximum dynamic range with minmin mapped to black(0x00) and maxmax mapped to white(0xff) and all other pixel values stretched accordingly.""" if minmin < 0: minmin = 0 # pixel minimum is 0 if maxm...
5f511b4a8bd053d503618767fee06597f1688619
3,656,796
def get_database_uri(application): """ Returns database URI. Prefer SQLALCHEMY_DATABASE_URI over components.""" if application.config.get('SQLALCHEMY_DATABASE_URI'): return application.config['SQLALCHEMY_DATABASE_URI'] return '{driver}://{username}:{password}@{host}:{port}/{name}'\ .form...
6b04a9518798aa3392cdf41667e5edf1fdaa5125
3,656,798
from typing import OrderedDict def get_s_vol_single_sma(c: CZSC, di: int = 1, t_seq=(5, 10, 20, 60)) -> OrderedDict: """获取倒数第i根K线的成交量单均线信号""" freq: Freq = c.freq s = OrderedDict() k1 = str(freq.value) k2 = f"倒{di}K成交量" for t in t_seq: x1 = Signal(k1=k1, k2=k2, k3=f"SMA{t}多空", v1="其他",...
d4453ec1e52ee2c19448855e0011b6ac31d5755b
3,656,799
import torch def sampler(value, percentile): """Score based on sampling task model output distribution Args: value: The output of the task model percentile: the (sorted) index of the sample we use Returns: The percentile largest distance from the mean of the samples. """ s...
905665d5219df7737adaf2c7fd435cef3f3c7f1d
3,656,800
def gists_by(username, number=-1, etag=None): """Iterate over gists created by the provided username. .. deprecated:: 1.2.0 Use :meth:`github3.github.GitHub.gists_by` instead. :param str username: (required), if provided, get the gists for this user instead of the authenticated user. ...
b98f478dbac25c0334296da5055952a776af9d39
3,656,801
import pyspark def needs_spark(test_item): """ Use as a decorator before test classes or methods to only run them if Spark is usable. """ test_item = _mark_test('spark', test_item) try: # noinspection PyUnresolvedReferences except ImportError: return unittest.skip("Skipping te...
f4d40b7119f753162ed5f6377ebef3b42d2bf549
3,656,802
from typing import Generator def get_school_years_from_db() -> Generator: """Get all school years from the database. :return: iterable with all availabe school years """ session: db.orm.session.Session = Session() return (e[0] for e in set(session.query(Holiday.school_year).all()))
48651fab2364e03a2d18224c7a798d8754cca911
3,656,803
def get_api(context=None): """ This function tries to detect if the app is running on a K8S cluster or locally and returns the corresponding API object to be used to query the API server. """ if app.config.get("MODE") == "KUBECONFIG": return client.CustomObjectsApi(config.new_client_from_con...
89808a80c3ad4ae1260ffbb9611543b6e33298ee
3,656,804
def is_variant(title) -> bool: """ Check if an issue is variant cover. """ return "variant" in title.lower()
5e0bab3030c069d7726bbc8c9909f561ed139cb8
3,656,805
def _decode_common(hparams): """Common graph for decoding.""" features = get_input(hparams, FLAGS.data_files) decode_features = {} for key in features: if key.endswith("_refs"): continue decode_features[key] = features[key] _, _, _, references = seq2act_model.compute_logits( features, hpar...
a9eac81d9fe5e0480c679e41a61699b9e281fdd5
3,656,806
from typing import Tuple def _lex_single_line_comment(header: str) -> Tuple[str, str]: """ >>> _lex_single_line_comment("a=10") ('', 'a=10') >>> _lex_single_line_comment("//comment\\nb=20") ('', 'b=20') """ if header[:2] != "//": return "", header line_end_pos = header.find("\n...
4d562557db11c7279042e439a56cc7864fa259ef
3,656,807
def in_box(X, box): """Get a boolean array indicating whether points X are within a given box :param X: n_pts x n_dims array of points :param box: 2 x n_dims box specs (box[0, :] is the min point and box[1, :] is the max point) :return: n_pts boolean array r where r[idx] is True iff X[idx, :] is within...
8ee516937b3a19a27fed81cfee0ca19356cb5249
3,656,809
def test_partial_field_square(): """Fields that do not extend over the whole wall""" field = np.zeros((40, 40)) field[:10, 0] = 1 fields = {kw_field_map: field} walls = "L" assert func(fields, "s", walls=walls) == 0.25 field[:20, 0] = 1 assert func(fields, "s", walls=walls) == 0.5 fi...
94af1cf9e500ddddd16c9fea61eeb43874589b68
3,656,810
def get_empty_faceid(current_groupid, uuid, embedding, img_style, number_people, img_objid, forecast_result): """ 当softmax无结果时(无模型/预测置信度低)调用遍历数据库识别 :param current_groupid: :param uuid: :param embedding: :param img_style: :param number_people: :param img_objid: :retu...
265250564de0ac160c5f0110293fc52693edaeda
3,656,812
def dz_and_top_to_phis( top_height: xr.DataArray, dz: xr.DataArray, dim: str = COORD_Z_CENTER ) -> xr.DataArray: """ Compute surface geopotential from model top height and layer thicknesses""" return _GRAVITY * (top_height + dz.sum(dim=dim))
14e19781cdac7a743d26db7d29317ea33ae94517
3,656,813
import scipy def altPDF(peaks,mu,sigma=None,exc=None,method="RFT"): """ altPDF: Returns probability density using a truncated normal distribution that we define as the distribution of local maxima in a GRF under the alternative hypothesis of activation parameters ---------- peaks: float or list of floats lis...
0346d1efcad2a3f8e1548857c980fb6c92ea07f3
3,656,814
def implicit_quantile_network(num_actions, quantile_embedding_dim, network_type, state, num_quantiles): """The Implicit Quantile ConvNet. Args: num_actions: int, number of actions. quantile_embedding_dim: int, embedding dimension for the quantile input. network_type: named...
2782f94b2003dca0a8865298dab2dbb17ec4cb45
3,656,815
def get_waitlist(usercode): """ Запрос /api/waitlists/{usercode} - возвращает waitlist контент по usercode """ user_by_usercode = ( AppUsers.query.filter(AppUsers.usercode == usercode).one_or_none() ) if user_by_usercode is None: abort( 409, "Usercode {us...
0592d188020b967198c1cb052d1e4b3adbc1ed21
3,656,816
def not_empty(message=None) -> Filter_T: """ Validate any object to ensure it's not empty (is None or has no elements). """ def validate(value): if value is None: _raise_failure(message) if hasattr(value, '__len__') and value.__len__() == 0: _raise_failure(messag...
f1ee9b43936978dfbd81550b9931d0cc8800eef2
3,656,817
def temporal_affine_forward(x, W, b): """ Run a forward pass for temporal affine layer. The dimensions are consistent with RNN/LSTM forward passes. Arguments: x: input data with shape (N, T, D) W: weight matrix for input data with shape (D, M) b: bias with shape (M,) Outputs: ...
2eca1c3ef36eb8bdbcaaad88c3b2f1234227e2d4
3,656,818
def uniform_regular_knot_vector(n, p, t0=0.0, t1=1.0): """ Create a p+1-regular uniform knot vector for a given number of control points Throws if n is too small """ # The minimum length of a p+1-regular knot vector # is 2*(p+1) if n < p+1: raise RuntimeError("Too small n for a u...
e0e1bc9f2e2ea2e74d70c76d35479efebc42d2f7
3,656,819
def generateCM(labelValue, predictValue): """Generates the confusion matrix and rteturn it. Args: labelValue (np.ndarray): true values. predictValue (np.ndarray): predicted values. """ FPMtx = np.logical_and((labelValue <= 0), (predictValue > 0)) FPIndices = np.argwhere(FPMtx) FPNum = np.sum(FP...
3ea5751bb9c9153edf4fdce12512319b75f80484
3,656,820
def get_cosine_similarity(word2vec: Word2Vec) -> np.ndarray: """Get the cosine similarity matrix from the embedding. Warning; might be very big! """ return cosine_similarity(word2vec.wv.vectors)
b9a976de8faef0cd85265c4afdb80dd8720128f5
3,656,821
def get_bot_id() -> str: """ Gets the app bot ID Returns: The app bot ID """ response = CLIENT.auth_test() return response.get('user_id')
6dcf2121fb11fb4af1615c9d739923e86299cc0a
3,656,822
def _fetch_from_s3(bucket_name, path): """Fetch the contents of an S3 object Args: bucket_name (str): The S3 bucket name path (str): The path to the S3 object Returns: str: The content of the S3 object in string format """ s3 = boto3.resource('s3') bucket = s3.Bucket(bu...
3e284b653c046a826b92e82bf60e7e12547280b2
3,656,824
def inc_date(date_obj, num, date_fmt): """Increment the date by a certain number and return date object. as the specific string format. """ return (date_obj + timedelta(days=num)).strftime(date_fmt)
560d82b8e72614b8f9011ab97c10a7612d1c50b0
3,656,826
def recombine_edges(output_edges): """ Recombine a list of edges based on their rules. Recombines identical Xe isotopes. Remove isotopes. :param output_edges: :return: """ mol = Chem.MolFromSmiles(".".join(output_edges)) # Dictionary of atom's to bond together and delete if they come in ...
1bbce0bb315990f758aa47a0dae2dc34bff9fb2a
3,656,827
def excludevars(vdict, filters): """ Remove dictionary items by filter """ vdict_remove = dict() for filtr in filters: a = filtervars_sub(vdict, filtr) vdict_remove.update(a) vdict_filtered = vdict.copy() for key in vdict_remove.keys(): del vdict_filtered[key] re...
5050e946454c096a11c664d1a0910d2b2f7d985a
3,656,829
def make_laplace_pyramid(x, levels): """ Make Laplacian Pyramid """ pyramid = [] current = x for i in range(levels): pyramid.append(laplacian(current)) current = tensor_resample( current, (max(current.shape[2] // 2, 1), max(current.shape[3] // 2, 1))) ...
88b8c94a8f5ca3fda3329c0ac8fa871693c1482f
3,656,831
def create_component(ctx: NVPContext): """Create an instance of the component""" return ToolsManager(ctx)
24cf48073bb16233046abdde966c28c570cf16c0
3,656,832
def get_routing_table() -> RouteCommandResult: """ Execute route command via subprocess. Blocks while waiting for output. Returns the routing table in the form of a list of routes. """ return list(subprocess_workflow.exec_and_parse_subprocesses( [RouteCommandParams()], _get_route_com...
817d8350e7a2af514e3b239ec5d7dbc278fb7649
3,656,834
import array def xor_arrays(arr1, arr2): """ Does a XOR on 2 arrays, very slow""" retarr = array('B') for i in range(len(arr1)): retarr.append(arr1[i] ^ arr2[i]) return retarr
5ff978aa1a48a537a40132a5213b907fb7b14b4b
3,656,835
def delete_category(): """Delete category specified by id from database""" category = Category.query.get(request.form['id']) db.session.delete(category) db.session.commit() return ''
47347299dd39c6afa9fd8d1cd10e1dc0906f6806
3,656,836
def gen_dd(acc, amt): """Generate a DD (low-level)""" read() dd_num = dd_no() while dd_num in dds.keys(): dd_num = dd_no() dd = { 'ac_no': acc, 'amount': amt } return dd_num, dd
251a36131dae66f4d24dc2ce45db27f81da39845
3,656,837
def coranking_matrix(high_data, low_data): """Generate a co-ranking matrix from two data frames of high and low dimensional data. :param high_data: DataFrame containing the higher dimensional data. :param low_data: DataFrame containing the lower dimensional data. :returns: the co-ranking matrix of ...
7cc77cd5ef70d7adef9020cab6f33a5dbf290557
3,656,838
def gaussian_dist_xmu1xmu2_product_x(mu1,Sigma1,mu2,Sigma2): """Compute distribution of N(x|mu1,Sigma1)N(x|mu2,Sigma2)""" InvSigmaHat = np.linalg.inv(Sigma1) + np.linalg.inv(Sigma2) SigmaHat = np.linalg.inv(InvSigmaHat) muHat = np.dot(SigmaHat,np.linalg.solve(Sigma1, mu1) + np.linalg.solve(Sigma2,mu2)) ...
5eb50e98165bc77bc0754a93eef4f62b0665ea30
3,656,839
def default_marker_size(fmt): """ Find a default matplotlib marker size such that different marker types look roughly the same size. """ temp = fmt.replace('.-', '') if '.' in temp: ms = 10 elif 'D' in temp: ms = 7 elif set(temp).intersection('<>^vd'): ms = 9 else...
feebe9bdda47a2e041636f15c9b9595e5cd6b2cc
3,656,840
def vote_smart_candidate_rating_filter(rating): """ Filter down the complete dict from Vote Smart to just the fields we use locally :param rating: :return: """ rating_filtered = { 'ratingId': rating.ratingId, 'rating': rating.rating, 'timeSpan': rating.times...
f4fec92e46f58444abb8dab56f28acc7e670aab0
3,656,841
def get_syntax(view): """ get_syntax(view : sublime.View) -> str >>> get_syntax(view) 'newLISP' >>> get_syntax(view) 'Lisp' Retuns current file syntax/language """ syntax = view.settings().get('syntax') syntax = syntax.split('/')[-1].replace('.tmLanguage', '') return syntax
a5be75f51de105af63ce53df7c3b7094537d28f3
3,656,842
def random_otp(): """ :return: OTP for Event :return type: string """ try: all_events = Events.query.all() # Here Error if no Event all_holded_events = HoldedEvents.query.all() used_otps = set() for otp_ in all_events: used_otps.add(str(otp_.otp)) ...
e343addc9252de4ca9d69a344beea05254c9ebb0
3,656,843
def read_config(path): """Read the complete INI file and check its version number if OK, pass values to config-database """ return _read_config(path)
bbb95e5e02d54dd831082d556e19307109e1113d
3,656,844
def getPath(file): """Get the path of a source file. Use this to extract the path of a file/directory when the file could be specified either as a FileTarget, DirectoryTarget or string. @param file: The object representing the file. @type file: L{FileTarget}, L{DirectoryTarget} or C{basestring} """ asse...
b80e5f0ead8be98dd40bbd444bc8ae9201eb54ed
3,656,845
import torch def optical_flow_to_rgb(flows): """ Args: A tensor with a batch of flow fields of shape [b*num_src, 2, h, w] """ flows = flows.cpu().numpy() _, h, w = flows[0].shape rgbs = [] for i in range(len(flows)): mag, ang = cv2.cartToPolar(flows[i, 0, ...], flows[i, 1,...
d27074eab88f0f1181c5e1acae4839cbed984e17
3,656,846
from re import MULTILINE def get_motes_from_simulation(simfile, as_dictionary=True): """ This function retrieves motes data from a simulation file (.csc). :param simfile: path to the simulation file :param as_dictionary: flag to indicate that the output has to be formatted as a dictionary :return...
bbf09378a45cee9a96dca136bc7751ea9372eeac
3,656,847
def menu_bar(): """each mini-game has a menu bar that allows direct access to the main menu. This allows story mode to be bypassed after starting war, but the game state will not be saved""" pygame.draw.rect(SCREEN, TEAL, (0, 460, 640, 40)) menu_font = pygame.font.Font('freesansbold.ttf', 15) m...
0b5b16db2f53c1cbb45236512597d954bb28e7da
3,656,848
def merge_sort(a, p, r): """ merge sort :param a: a array to sort, a[p:r+1] need to be sorted :param p: index of array, p < r, if p >= r , the length of a is 1, return :param r: index of array, p < r, if p >= r , the length of a is 1, return """ if p < r: q = int((p + r) / 2) # ...
07aab16ea75cb01f2f1fb3ae32f1b1ac31c76cfb
3,656,849
def get_flow_graph(limit, period): """ :type limit int :type period int :rtype: list[dict] """ rows = ElasticsearchQuery( es_host=ELASTICSEARCH_HOST, period=period, index_prefix='logstash-other' ).query_by_string( query='kubernetes.labels.job-name:* AND ' ...
f51bb6aa6132303e2cd5ed3090507435739c0452
3,656,850
import re import time def upload(server_ip, share, username, password, domain, remote_path, local_path, verbose=True): """ Get file and folder on the remote file server. server_ip (str): This value is the ip smb server's ip. share (str): This value is the share file name. user...
552079181faa10b50c306b1ee9e02c190b9711a4
3,656,851
from typing import Union import platform def list_directory_command(api_client: CBCloudAPI, device_id: str, directory_path: str, limit: Union[int, str]): """ Get list of directory entries in the remote device :param api_client: The API client :param device_id: The device id :param d...
228d4884d2fd4f69e8c7a44d737bfeca7b40f753
3,656,852
def _hparams(network, random_seed): """ Global registry of hyperparams. Each entry is a (default, random) tuple. New algorithms / networks / etc. should add entries here. """ hparams = {} def _hparam(name, default_val, random_val_fn): """Define a hyperparameter. random_val_fn takes a Ra...
34ea9ac295f3150b870e8d1c7ce0f1b867f75122
3,656,853
def bidding_search(request): """ """ query = '' form = BiddingSearchForm(shop=request.shop, data=request.GET) if form.is_valid(): query = form.get_query() results = form.search() else: results = form.all_results() pager = Paginator(results, PAGE_SEARCH) ...
cda6c4ebccec88c40ae714cd81392946165b184f
3,656,854
def clean_code(code, code_type): """ Returns the provided code string as a List of lines """ if code_type.startswith(BOOTSTRAP): if code_type.endswith(CLEAN): return code.split("\n") code = code.replace("\\", "\\\\") if code_type.startswith(PERMUTATION): if code_type.end...
fff65103003a202a039fd4683da83735b0342a7a
3,656,855
def level(arr, l, ax=2, t=None, rounding=False): """ As level 1D but accepts general arrays and level is taken is some specified axis. """ return np.apply_along_axis(level1D, ax, arr, l, t, rounding)
80835140850dbf7883f9b4cb1f92543ee2253845
3,656,856
def updateStore(request, storeId): """ view for updating store """ if canViewThisStore(storeId, request.user.id): # get the corresponding store store = Store.objects.get(id=storeId) metadata = getFBEOnboardingDetails(store.id) if request.method == "POST": # Create a ...
8cb92e31f2dc59a28281c45d698a7d810b573587
3,656,857
def i(t, T, r, a, b, c): """Chicago design storm equation - intensity. Uses ia and ib functions. Args: t: time in minutes from storm eginning T: total storm duration in minutes r: time to peak ratio (peak time divided by total duration) a: IDF A parameter - can be calculated fro...
3d31d64502fc4590b1d83e0d3a32a5de9cae2a56
3,656,858
def get_primary_id_from_equivalent_ids(equivalent_ids, _type): """find primary id from equivalent id dict params ------ equivalent_ids: a dictionary containing all equivalent ids of a bio-entity _type: the type of the bio-entity """ if not equivalent_ids: return None id_rank...
489f9d431e553772f114f1e4a3a2577c831addda
3,656,859
def get_L_max_C(L_CS_x_t_i, L_CL_x_t_i): """1日当たりの冷房全熱負荷の年間最大値(MJ/d)(20c) Args: L_CS_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房顕熱負荷 (MJ/h) L_CL_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房潜熱負荷 (MJ/h) Returns: float: 1日当たりの冷房全熱負荷の年間最大値(MJ/d) """ # 暖冷房区画軸合算(暖冷房区画の次元をなくす) L_CS_x_t = np.sum(L...
2c5e769baacfec0d75e711b3493b07ab65796690
3,656,860