content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def deserialize_graph(data): """De-serialize from the given json data.""" graph = import_class(data['module'], data['cls'])() graph._nodes = [] for node in data['nodes']: graph._nodes.append(deserialize_node(node)) nodes = {n.identifier: n for n in graph.nodes} for node in data['nodes']:...
277d34e6342b02f3794226a82a58e9b5442e0162
52,600
def normalCdf(x,mu=0.0,sigma=1.0): """ Computation of normal cdf @ In, x, list or np.array, x values @ In, mu, float, optional, mean @ In, sigma, float, optional, sigma @ Out, cdfReturn, list or np.array, cdf """ return stats.norm.cdf(x,mu,sigma)
89c55615ef280019ad9b0c22b0b782895625301b
52,601
def transform(codec): """ transform post """ if codec not in CODECS: return abort(404) return run(codec, request.get_data())
9a65c9b5ed2e8ee6e8bd6b6c0e6fbd9f164709c5
52,602
def largest_connected_component(H): """ A function to find the largest connected component of a hypergraph. Parameters ---------- H: Hypergraph object The hypergraph of interest Returns ------- set The largest connected component (a set of nodes) of the hypergraph. ...
cf5276958cb07e2280a170f7d7b570984a3ff670
52,603
import os def setup_args(args): """ Setup the args Args: args (ArgParse): args parsed by arg parser Returns: args (CoreclrArguments) """ coreclr_args = CoreclrArguments(args, require_built_core_root=False, require_built_product_dir=False, requ...
2a0fbb330080f0a0e00d011c5150f9ef7ebe13c6
52,604
import time def log_str(proc_str, start): """Create a preamble string for stdout.""" former = "[{:>4}".format(proc_str) latter = "] {:.2f}".format(round(time.time() - start, 3)) return former + latter
5f4f82e758cf87ff643a20928e5c0f7368ef537f
52,605
def authenticate_user_from_request(request): """ Given a request, attempt to authenticate based on Auth Header Scheme/Credentials Called via the middleware, etc """ # Step 1: Detect if we have an Auth Header raw_auth_header_val = request.headers.get('Authorization', None) if not raw_auth_he...
37f7c093bccd1380219e7cebef0fbefd1868a8c0
52,606
def linear_kernel(X, Y=None): """Compute linear Gram matrix between X and Y (or X) Parameters ---------- X: torch.Tensor of shape (n_samples_1, n_features) First input on which Gram matrix is computed Y: torch.Tensor of shape (n_samples_2, n_features), default None Second input on whic...
b1389059e755fa19bb26c88cf8c9f6ab39d51aec
52,607
def split_to_pieces(number, name, lang, doc_path): """ :param number: id number of document :param name: file name :param lang: language one of ENG, RUS, ESP, JAP, etc. :param doc_path: document path :return: pieces ids :structure: list(ObjectId Bson) """ if len(doc...
dd83163dfa19d1c1c74fbec581fd8677e42fd512
52,608
def hit(health): """Hits health for a random number between 1 and 10""" hit_value = random.randint(1, 10) print "hits for:", hit_value health = health - hit_value print "health now:", health return health
606a6b224eb2348b222623b1eddd5d8691648a91
52,609
from joblib import Parallel, delayed def parallel_func(func, n_jobs): """Return parallel instance with delayed function Util function to use joblib only if available Parameters ---------- func: callable A function n_jobs: int Number of jobs to run in parallel Returns ...
fcbe721ed91c49c12d4af534e75522c1ebe36688
52,610
def evaluate_task_accuracy(scenario, prediction_results, subclasses, null_label=NULL_LABEL): """ Evaluates the accuracy of the predictor for each task, where we consider the best possible performance as the ground truth. The best possible is the perfect labeling for current iteration. :param scenario: ...
3d704f25bef263a3c02f05fdc77b2f49c41d3fd6
52,611
def _graycode(bqm): """Get a numpy array containing all possible samples in a gray-code order""" # developer note: there are better/faster ways to do this, but because # we're limited in performance by the energy calculation, this is probably # more readable and easier. n = len(bqm.variables) ns...
7d8fc2c5d4ff71f98bd27869616af3a1f677b51c
52,612
def get_indices_of_line(l, angle, dist): """ Return indices in square matrix of <l>x<l> for Hough line defined by <angle> and <dist> """ # Get start and end points of line to traverse from angle and dist x0, y0, x1, y1 = get_extremes(angle, dist, l) # To ensure no lines are defined outside th...
a2ce1e5a000f59ff7cbc2ad92ca0796e705e7c19
52,613
def get_oaa_connection(agent): """return the LibOaa OAA connection for the specified agent, or None if none exists""" if _AGENT_OAA.has_key(agent): return _AGENT_OAA[agent] return None
58733faf0e64e96b4d116147d129773330e28346
52,614
def diaresnet18(**kwargs): """ DIA-ResNet-18 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' ...
25ef3967cbfcf0b15b580a21cea83eca3445d348
52,615
def mc_indices(context_vector, fns, mc = 50): """Return the indices of the @mc highest values of context_vector. @fns is just for reference. Not really optimized. """ # If the context vector has more nonzero elements than mc, only take the mc occurrences! if len(np.flatnonzero(context_vector)) > mc...
a3c995c589f00e3683946b684446fe46ea82e4a4
52,616
def split_date(dates): """ Split datetime64 dates into year, month, day components. """ y = dates.astype("<M8[Y]").astype(int) + 1970 m = dates.astype("<M8[M]").astype(int) % 12 + 1 d = (dates - dates.astype("<M8[M]")).astype("<m8[D]").astype(int) + 1 return y, m, d
7152dbdd1f839ef3c401de06631fb0a249c36642
52,617
from typing import Dict def random_random_crop(image: tf.Tensor, size: tf.Tensor, groundtruths: Dict[str, tf.Tensor], seed=None) -> (tf.Tensor, tf.Tensor): """Will `randomly` perform a random crop of a tensor to a given size. Slices a shape ...
24c57847f97874b3d9ea71a625e1a90b5ee09605
52,618
def flowless(hyper_list, T, weight=None): """ Implementation of greedy++ algorithm proposed in [1]. It efficiently compute almost densest subgraph without max flow. Parameters ---------- G: undirected, graph (networkx). T: int, number of iterations. weight: str that specify the edge att...
ab9298e5944a8f7f3180f1cea66867cda8349e7b
52,619
def getDmzProxySecurityActionValue( nodename, proxyname, action, ): """Gets an individual security value""" return getDmzProxySecurityActionLevelOrValue( nodename, proxyname, action, 'values' )
4b8ab7b23242fc4284a396be29e68aad42539a02
52,620
def get_left_right_spans(ribo): """ In counting number of reads going to each region (UTR5, CDS and UTR3), We artificially introduce two regions UTR5_junction: A region between UTR5 and CDS containing the start site [start_site - left_span, start_site + leftspan] UTR3_junction: ...
274b492c79b67403e5583d5bb7d7f2387029df3d
52,621
def filters_effect( ftype=None, cutoff_hz=None, sfreq=None, width_hz=None, ripple_db=None, window=None, ): """ Generate example filter input-output plots for pure sinewave data. Parameters ---------- key=val see :ref:`check_filter params() Parameters <filter_parameters_label>` R...
b609796ce53d23e0dd050ba4bf419691d3d06658
52,622
def _aggregate(y, aggfunc, weights): """Apply aggregation function by row. Parameters ---------- y : pd.DataFrame Multivariate series to transform. aggfunc : str Aggregation function used for transformation. weights : list of floats Weights to apply in aggregation. ...
e4ac01ecccbbda6f99ef36af364e9784cd9b347e
52,623
def create_session(engine): """ Create a session for accessing the DB. """ return sqla.orm.scoped_session( sqla.orm.sessionmaker( autocommit=False, autoflush=False, bind=engine ) )
05bec07e03e0bcb948e0bb2e94ede7cd7209e640
52,624
def firm_sim_load_firms(NAICS2012_to_NAICS2007): """ For now, just read FirmsandEstablishments.cvs file created by dev/NFM_Firmsynthesis.R """ data_dir = setting('data_dir', inject.get_injectable('data_dir')) table_list_name = 'firm_synthesis_tables' table_list = setting(table_list_name) a...
5c9eb6d32f9e21d7af83fea9ad163684e7f5ced3
52,625
from datetime import datetime def request(caller_id): """ Method requests single PublicIP address for caller. If caller's quota is exceeded, exception is raised. Otherwise caller obtains a new PublicIP address. @cmview_user @response{string} newly obtained PublicIP's address @raises{publ...
40fc150ffd5722309d00fd77a3ffceca0236c12f
52,626
def get_user_tweets(user_name): """Retrieve all (accessible) tweets from a given user name by stepping backward through the status paging""" all_tweets, lowest_id = _get_user_tweets_batch(user_name) while True: next_batch, lowest_id = _get_user_tweets_batch(user_name, lowest_id) all_tweets +...
e1bcbc82e8c579b2d45e201bb7ffd2a724ae2a82
52,627
def hex_to_chars(num): """ Convert the hex representation of the number to a correctly ordered string. Parameters ---------- val: int The integer representing the string. This is in reverse order. Ie. XXYYZZ -> chr(ZZ)chr(YY)chr(XX) Returns ------- str The actua...
2f87de04dc2442a125ed355b4d6ce2043138700d
52,628
def Split(l, indexes, axis=-1, merge_sublayers=False, name=""): """\ Split layer into a list of tensor layers. :param l: parent layer :param indexes: ``[20, 60] => [:20, 20:60, 60:]`` :param axis: which axis to split on (-1 = last) :merge_sublayers: merge layers symbolically (affects plotting)...
ac3d9ce5982e1139157586d37bc45d9a23ee9c86
52,629
import pickle def load(filename): """ Load a compressed pickle from disk """ return pickle.loads(_loads(filename))
a7cfb856b069c1d48dcfd71de6094a1cea6c160d
52,630
def hilbert(x, N=None, axis=-1): """ Compute the analytic signal, using the Hilbert transform. The transformation is done along the last axis by default. Parameters ---------- x : array_like Signal data. Must be real. N : int, optional Number of Fourier components. Default:...
483127445b3c482bb28b00be7d9c0a5055f6ca25
52,631
async def peer_detail(request): """ --- description: Show current peers, if {level} is set, include logs for {id} tags: - peers produces: - application/json parameters: - in: path name: peer_id description: peer id required: true type: string responses: ...
56f3aff3d6f809c1a614842427384e56dbe055c6
52,632
def interruptable_task(coro, loop=None): """ Turn the given coroutine into an interruptable task by turning it into an InterruptableFuture and returning it. :param coro: the coroutine that should be made interruptable :param loop: the event loop in which to run the coroutine, by default uses tornado.io...
784d352ae84a13c5e5d28c0a4d11b9570f0e77f1
52,633
def STALTA_picker_refraction(st, nsta=1e-3, nlta=4e-2, fc=50, nc=2, noise_mag=1e-25, SNR_window=5e-3): """The STA/LTA picker provides a first order good estimate of the arrival times for both the P- and S- wave. The STA/LTA picker uses :py:class:`obspy.signal.trigger.recursive_sta_lta`. :param st: ...
67b5ca6eb0cdeafdc9f2d85010b07b44f47bb297
52,634
def Roleta(): """Faz a parte da roleta. possibilidades: 100 a 950, de 50 em 50. dois 1000; duas 'passa a vez'; duas 'perdeu tudo', os resultados são equiprováveis; perdeu tudo == 0 passa a vez == 1 none -> int""" possibilidades = [0, 0, 1, 1, 1000, 1000] for i in range(100, 951, 50): # Ad...
69daff5fcc11b126c57733a400a38bbe60b3b4ef
52,635
import re def parse_trace_collection_time_range(collection, time_range, gmt=False, handles=None): """Parse a time range string, using a trace collection to disambiguate incomplete dates. Args: collection (TraceCollection): a babeltrace TraceCollection ...
64eaa8c904b94696d5bd9f8e4d5bd09532416d11
52,636
def lgr_validate_label(lgr, label, udata): """ Validate a label for an LGR. :param lgr: The LGR to use for variant generation. :param label: Label to validate. :param udata: The associated Unicode database. :return: CSV containing the label validation output. """ return _validate_label_...
1c71e77ecd87272fdf1c1d1a4b6ce90fd54cd6c1
52,637
def encodeDNA(seq_vec, maxlen=None, seq_align="start"): """Convert the DNA sequence into 1-hot-encoding numpy array # Arguments seq_vec: list of chars List of sequences that can have different lengths maxlen: int or None, Should we trim (subset) the resulting sequence. ...
6ef075f450aac10ea55a067e1e45252f4314621e
52,638
def sortedWrite(inTree): """ Write out a GLM from a tree, and order all tree objects by their key. Sometimes Gridlab breaks if you rearrange a GLM. """ sortedKeys = sorted(list(inTree.keys()), key=int) output = '' try: for key in sortedKeys: output += _dictToString(inTr...
e37e81e39c6c7212a1c046a7d6adae9ad16f9f0f
52,639
import string def callback(): """ 修改记录 """ # 检查用户权限 _common_logic.check_user_power() content = web_helper.get_form('content', '内容', is_check_special_char=False) # 防sql注入攻击处理 content = string_helper.filter_str(content, "'") # 防xss攻击处理 content = string_helper.clear_xss(content) ...
6ce2d9e6fbbb33d33639f6916d6dda91babbc435
52,640
import pathlib from typing import List from typing import Tuple from typing import Type from typing import cast def get_stripped_contextual_model(path: pathlib.Path = None, aliases_not_to_be_stripped: List[str] = None) -> Tuple[Type[OscalBaseModel], str]: """ Get the stripped...
425d03ee54a3c880779d42836073ba1e60e6f7f3
52,641
def validate_cypher(statement, raise_exception=False, exc_class=ValidationError): """ Checks if ``statement`` is a valid Cypher statement. :param statement: Cypher statement to parse. :type statement: str :param raise_exception: Raise ValidationError if not valid. :type raise_exception: boo...
b9c480a07e45b893e7396549d93c6e9b84a360f5
52,642
def strip_newlines(base): """Strip newlines from a string""" return base.replace("\n", "")
aad3fed8a66076cb5ed9c413af319f8aef60a42e
52,643
def fixture_log_output(): """Capture structlog log output for testing. Reference: https://www.structlog.org/en/stable/testing.html """ return structlog.testing.LogCapture()
2a6af8d42a1dafb48d9e73c41ba54bed9b6a4418
52,644
import numpy as np def calculate_g(lat): """calculate the gravitational acceleration with lat in degrees""" g0 = 9.780325 nom = 1.0 + 0.00193185 * np.sin(np.deg2rad(lat)) ** 2.0 denom = 1.0 - 0.00669435 * np.sin(np.deg2rad(lat)) ** 2.0 g = g0 * (nom / denom)**0.5 return g
41c3e4bfd1678279c2e39529cae0ab7a5602d10a
52,645
from scipy.stats import rankdata def weighted_correlation_rank(x, y, wt): """Calculatees the weighted spearman rank correlation""" x = rankdata(x) y = rankdata(y) return weighted_correlation(x, y, wt)
f4381084a2ccd84aeb76efef5b7417ff64fe29ea
52,646
import os import glob def get_auth(api_key_id=None, api_key_path=None, region=None, api_url=None, seer_auth=None, use_email=None, email=None, password=None, timeout=None): """ Get the correct Auth implementation based on passed parameters and the existence of config files. If seer_auth i...
96ff274fbc86b45f0033ba97c84b58afbd9cbd34
52,647
from typing import cast def riFromCSI(csi: str) -> str: """ Get the ri from an CSEBase resource by its csi. """ if (res := resourceFromCSI(csi)) is None: return None return cast(str, res.ri)
a14d83a476bc64b96038d071a78d9b6d81d25faa
52,648
def solr(request): """ Displays ils view for the MARC Batch App """ APP['view'] = 'solr' return direct_to_template(request, 'marc_batch/solr.html', {'app':APP, 'institution':INSTITUTION})
7fd4ab7b66ee6406f903c310b72e1e1d7508bd54
52,649
def process_failed(returncode, stdout): """Return True if the process failed.""" if returncode != 0: return True if 'badly_formatted' in stdout: return True return False
2d3c84872acf3bf6592316aa95c39e41a6da849e
52,650
def find_co_double_bonds(atoms, mol): """ looking for R | C=O | R """ CO_list = [] for _ in range(len(atoms)): name = atoms[_].get_atom_name() if name != 'C': continue nghs_c = atoms[_].get_ngh() nums_c, nghs_list_c = pa...
b0a1479da6cca778c7e58b3acf4c4f12ee347f51
52,651
def p2b_list_point2D(pylist, dtype): """ Converts a python list of feature descriptors stored in 64bit floats into a BoofCV compatible format :param pylist: Python list of 2d points :type pylist: list[(float,float)] :return: List of 2d points in BoofCV format """ java_list = gateway.jvm.java...
ec4b4cb3da04bed662c29472ce91d8c31e5750be
52,652
def transform_coords(c1, c2, out=None): """Return Coordinates by applying c1 to c2 from the left Parameters ---------- c1 : skrobot.coordinates.Coordinates c2 : skrobot.coordinates.Coordinates Coordinates c3 : skrobot.coordinates.Coordinates or None Output argument. If this valu...
719f8ff44f56ca624aee121cc21b0601fd6f2198
52,653
import difflib import tempfile import webbrowser def compare_fiff(fname_1, fname_2, fname_out=None, show=True, indent=' ', read_limit=np.inf, max_str=30, verbose=None): """Compare the contents of two fiff files using diff and show_fiff. Parameters ---------- fname_1 : str ...
bb68539693d318913f64acedef364e183c58e696
52,654
def interp1(x, xdata, ydata, silent=0): # --DC """DETERMINES y AS LINEAR INTERPOLATION OF 2 NEAREST ydata""" SI = argsort(xdata) # NEW numpy's take IS ACTING FUNNY # NO DEFAULT AXIS, MUST BE SET EXPLICITLY TO 0 xdata = xdata.take(SI, 0).astype(float).tolist() ydata = ydata.take(SI, 0).astype(fl...
111f9079b93d86d862861c144f99ef8c4841ab4d
52,655
from typing import Any from typing import Sequence def wrap_in_list(maybe_sequence:Any) -> Sequence: """ If `maybe_sequence` is not a sequence, then wrap it in a list See :func:`pyllars.validation_utils.is_sequence` for more details about what counts as a sequence. Parameters ---------- ...
1feecb4715c9c3278bacbea9332f1d3091f6e9d2
52,656
def evaluate_quadratic(J, g, s, diag=None): """Compute values of a quadratic function arising in least squares. The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s. """ if s.dim() == 1: Js = J.mv(s) q = Js.dot(Js) if diag is not None: q += s.dot(s * diag) e...
cde6067f22ef3a146b80fb5324c0c1a8ce2e65a4
52,657
def all_in_any(a, b): """return true if every item of 'a' is found inside 'b' else return false """ if len([x for x in a if x in b]) == len(a): return True else: return False
b9fa2ff3396d07a9c3a6c96bb82c047f8902fce9
52,658
import importlib def _get_upgrader_impl(service): """ Instantiate the MagmaUpgrader implementation to be used for magmad, as specified in the service YML config. Args: service (MagmaService): magmad service Returns: magma.magmad.upgrade.upgrader.Upgrader: specified upgrader insta...
580f09f49c723becbcd8c2b179f7e56d934ad5c9
52,659
def apply_stack(initial_msg): """ Execute the effect stack at a single site according to the following scheme: 1. For each ``Messenger`` in the stack from bottom to top, execute ``Messenger._process_message`` with the message; if the message field "stop" is True, stop; ...
6d73b17a2737674f660f2af63e0f2e75f18932cd
52,660
from typing import Optional from typing import Union async def check_name_and_abbreviation( db, ref_id: str, name: Optional[str] = None, abbreviation: Optional[str] = None ) -> Union[bool, str]: """ Check is a otu name and abbreviation are already in use in the reference identified by `ref_id`. Returns a ...
9810fb23b5933b6cdf84a169173f3221adbf3f5d
52,661
def get_test_data(suite): ############################################################################### """ For a given suite, returns (inherit, time, share, tests) """ raw_dict = _ALL_TESTS[suite] for key in raw_dict.keys(): expect(key in ["inherit", "time", "share", "tests"], "Unexpected...
4705152df2b863342163c077a99add064aca5c29
52,662
def slafbfiles(date): """Observation file locator stub .. note:: User-specified stub :param date: The verification date in string format ``'%Y%m%d'`` :returns: List of files """ files = ['slafb.nc'] return files
9a8476edc9694cc61466995c21c82b94b921f3fb
52,663
def expansionhunter_unclear_expected(): """:return: Returns dictionary with expected results for ExpansionHunter - UNCLEAR.""" return { "AR": ( "Unclear - repeat AR observed outside defined ranges (34/37). " "Normal range: 9 - 35. Expansion range: 38 - 62." ), "FM...
0e5f60482694b4ed3d9ceac573795194e8cac541
52,664
def create_temporay_element_type(name, attrs=()): """ """ if not attrs: bases = (TemporarySingleValueInternalElement,) else: if 'codeinfo' not in attrs: attrs = tuple((*attrs, 'codeinfo')) bases = (namedtuple(f'_{name}Base', attrs), TemporaryInternalElement) retur...
e97f25fa3c5713c2c8ff67a54355b024adef37a2
52,665
import urllib def enrich_url(base_url, client_doc) -> str: """ Add payment form API parameters for this client. """ url = base_url params = '' cl_name = make_client_name(client_doc, include_title=False) cl_street = client_doc.get('address', {}).get('street', ' ') cl_city = client_doc.g...
1fed11679ad838802c951715f8c1d056de7a2ac2
52,666
import psutil import subprocess import time def under_pebble(_function): """ decorator to spin up an external pebble server """ @wraps(_function) def _wrapper(*args, **kwargs): log.info("`pebble`: spinning up") log.info("`pebble`: PEBBLE_CONFIG : %s", PEBBLE_CONFIG) res = ...
c79b54376a2765c4d57767d761783c84a728e8e3
52,667
from typing import Callable def bind_raw(func: Callable[[bytes], HTTPHandler]) -> HTTPHandler: """Executes passed `func` on request body. Args: func (Callable[[bytes], HTTPHandler]): to run on request body. """ @handler def _handler(nxt: HTTPFunc, ctx: HTTPContext) -> Future[HTTPContext ...
bc685baec7dbe4f499f5928d0fe718a2af2eb435
52,668
def GetTask(task_guid, service_guid): """ Retrieve the detail of a task It is handler for GET /services/<service_guid>/task_list/<task_guid> """ return handlers.GetTaskHandler(task_guid, service_guid)
d2ae029581ca8d6f7017afa7f11c897900d54eef
52,669
from typing import Tuple def partially_decrypt( guardian_keys: ElectionKeyPair, elgamal: ElGamalCiphertext, extended_base_hash: ElementModQ, nonce_seed: ElementModQ = None, ) -> Tuple[ElementModP, ChaumPedersenProof]: """ Compute a partial decryption of an elgamal encryption :param elgama...
b2512a8d7424b2c15aa8b0f99d14f7c3ad75c102
52,670
def check_lowercase_prefix(node: ir.Node, module_prefixes: ModulePrefixLookup) -> bool: """check that node starts with the lower-case module prefixed followed by an underscore.""" if node.Name: for file in containing_modules(node): if file in module_prefixes: if not node....
d76c8829f9d9765c2061134bac8f6af1f8de29c1
52,671
def count_params(text): """Return number of parameters.""" return len(parse.parse_qs(text))
e1e87ad8a85f5d5db5d4128466b7e06765d97d20
52,672
import functools def GetJobDirFlag(upload_help=True, allow_local=False): """Get base.Argument() for `--job-dir`. If allow_local is provided, this Argument gives a str when parsed; otherwise, it gives a (possibly empty) ObjectReference. Args: upload_help: bool, whether to include help text related to obj...
7f85586119862b103a6e5a10bacf2144e943a607
52,673
def get_cl_source(name): """Get the source code for a openCL source file located in the chroma cuda directory at src/[name].""" with open('%s/%s' % (srcdir, name)) as f: source = f.read() return source
3f57d3dd55b410c9553f9a959e9d1a69aa0670a1
52,674
def beam2pix(header): """ Calculate the beam to pixel conversion ratio, which is used to convert between Jy/beam and Jy. Parameters ---------- header : fits header The header of the data. Returns ------- b2p : float The ratio of the beam size to the pixel size. ...
0e063438acec1ee808a43d82250ffa4e368d76e9
52,675
def add_user_favorites(itemid): """ Add item to user's favorite list. Args: itemid (int) – item id Status Codes: 201 Created – when favorite successfully created """ path = '/users/{}/favorites'.format(userid()) data = {'itemid': itemid} return post(path, data, auth=Tr...
1cc8a2c7fca39aa34f40dfeb9c882ee8b8c6f7ac
52,676
def decode_varint(stream: BytesIO) -> int: """ Decode bytes into int """ shift = 0 result = 0 while True: i = _read_one(stream) result |= (i & 0x7F) << shift shift += 7 if not (i & 0x80): break return result
31210521a8fce5815d43ca547d196c8a96accd1d
52,677
def get_linguist_projects(args, default_all=False): """ Get Linguist Projects """ worktree = get_linguist_worktree(args) project_args = args.projects pml_paths = list() project_names = list() for arg in project_args: if arg.endswith(".pml"): pml_paths.append(qisys.sh.to_nativ...
84f9659f50b76c04c6f5cf8e3e7fc9038f8e4941
52,678
def parse_opts_args(argv): """ parse options and arguments """ usage = "USAGE: find_class.py [options] class_name [[class_name] ...]" p = OptionParser(usage=usage) p.add_option('-v', '--verbose', dest='verbose', action='count', default=0, help='verbose output. specify twice for debug-l...
5806f8a14c7d5f9d87aef669353aa7a27e15ef2a
52,679
import gettext def bucketcall(queryfield="", name="", title="", sortby="", lastnamefirst=False, infotext="", description="", query="", alphabetical=False, insert_entries=None, page_url=""): """Bucket call helper.""" q_data = {"buckets": "%s.bucket" % queryfield} if query: ...
00fd3dff1e18dfc202230930788c764087c08183
52,680
def brute_force_mscs(seq: list) -> tuple: """Brute-force approach to compute the sum of all subsequences of seq. There are n + (n - 1) + (n - 2) + ... + 1 different subsequences. Time complexity: O(n³).""" _sum = _max = seq[0] start = end = 0 for i in range(0, len(seq)): for j in ran...
4b2aad5e443be80c65cb384cb6e1ba27dc63688a
52,681
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a # dummy metaclass for one level of class instantiation that replaces # itself with the actual metaclass. Because of internal type checks # we also need to make sure that ...
ccdd730769527a2839af9031c4fdfbf4eb87b796
52,682
from typing import List from pathlib import Path from typing import Union def expand_files( files: List[Path], extension: Union[str, List[str]] = ".sql", base_path: Path = Path("."), ) -> List[Path]: """ Expands the list of files or folders, with all SQL files in a folder as seperate files. ...
8243b80a7afaae0426308a1b447f4813eeb5f0c7
52,683
from typing import get_args import os def generate_launch_description(): """Launch file for gritsbot in Gazebo.""" # Get input arguments input_args = get_args() pos_y = '1.45' neg_y = '-1.45' def_z = '0.91' x_val = [ 0.3 * -1, 0.3 * -2, 0.3 * -3, 0.3 * -4, 0.3 * -5, 0.3 * ...
1addf08df93c87fac64957f4a3e6d63cbdeac08b
52,684
def f1_score_missing(y_true, y_pred, individual=False, micro=False): """ Compute the f1 score, accounting for missing labels in `y_true`. """ assert not (individual and micro) assert y_true.shape == y_pred.shape assert len(y_true.shape) == 2 if micro: # average over attributes usi...
71145d714e594943d31fb3486e2b355d2adc9469
52,685
import os def load_ply(ply_fpath: _PathLike) -> np.ndarray: """Load a point cloud file from a filepath. Args: ply_fpath: Path to a PLY file Returns: arr: Array of shape (N, 3) """ data = pyntcloud.PyntCloud.from_file(os.fspath(ply_fpath)) x = np.array(data.points.x)[:, np.newax...
b47374952e5e0fb8f3e4cbf9e0433a4c6101d495
52,686
def run(connection, reporter, object_list): """Run the reporter :class Reporter: for the give object list :class CheckObjectList:""" xml = Marshal().serialize(object_list) resp = connection.execute('POST', object_list.objtype.basepath, accept=CheckReportList.objtype.mimetype,...
e9e7f6e1e673de9dda1686f366084b4f755d1dae
52,687
def horizontal_flip(image_data, output_encoding=PNG): """Flip the image horizontally. Args: image_data: str, source image data. output_encoding: a value from OUTPUT_ENCODING_TYPES. Raises: Error when something went wrong with the call. See Image.ExecuteTransforms for more details. """ ima...
7c9bde12bea232c4e365daa1762b6a44a4334972
52,688
def split_page(encoded_inputs, max_seq_len=512): """ truncate is often used in training process """ for key in encoded_inputs: encoded_inputs[key] = paddle.to_tensor(encoded_inputs[key]) if encoded_inputs[key].ndim <= 1: # for input_ids, att_mask and so on encoded_inputs[key...
fda8e86d0e0c5cabb0fbbcca7f979f65eb3a223c
52,689
def _intToColor(color_number): """ legacy color support for converting integers to color objects based on the cadnano 2 file format Args: color_number (int): integer value of a RGB color Returns: Color: the :class:`Color` object """ return Color('#%0.6x' % (color_number))
b3873fb8ad54b6d120d4b1409550dc4139705286
52,690
def test_points(): """Test points of different styles with/without label and different label positions""" coordinate_system = cartesius.CoordinateSystem(bounds=(-.5, 5, -.5, 5)) # Without labels: coordinate_system.add(elements.Point((1, 4), style='.')) coordinate_system.add(elements.Point((2, 4), s...
849fcd43f7dcdb524aed7ee07b836fa604f649de
52,691
def obter_todas(possui_oferta: bool = None) -> dict: """Consulta a lista de todas as categorias que possuem ofertas dos lojistas parceiros da Lomadee. Parameters ---------- possui_oferta: bool, optional Quando "true" retorna apenas categorias que possuem ofertas. Returns ------- di...
d65523047a322e6bcf909a95df5995b2c0417045
52,692
def construct_M_h(tsp,H,dt,Stim): """ Performs preliminary processing of the spike trains, and returns the matrix corresponding to the post-spike filter. Parameters ---------- Stim : array_like Stimulus. tsp : array_like Spike ti...
379b1aaf9b57f66ef0d10580644ad97df44eccce
52,693
def vdowham(eta, vel_entrain, e_eff, r_eff): """ Calculate the velocity parameter of the contact problem according to Dowson-Hamrock. Parameters ---------- eta: ndarray, scalar The dynamic viscosity of the lubricant. vel_entrain: ndarray, scalar The entrainment velocity of ...
e8abfcc3d312ffce0c192a3b890fe8f3a6785e76
52,694
def rotate(set_of_points, pivot, rotation_matrix): """ set_of_points: numpy.matrix pivot: tuple(x, y, z) rotation_matrix: numpy.matrix """ return kb.translate(kb.translate(set_of_points, [-i for i in pivot])*rotation_matrix, pivot)
658e8e7d4c79d5a7df86aa3ce3e0a536a81512eb
52,695
import requests import logging def get_index_from_tags(session, tags): """ Construct a ModuleIndex object from the contents of the provided tags. :param session: A Koji session :param tags: A set of Koji tags from which module metadata should be pulled :return: A ModuleIndex object. Raises an exce...
fbe36279fa03170e03bbd2d9c148cd2e3334ac9a
52,696
def model_fn_builder(config): """Build the model for training.""" def model_fn(features, labels, mode, params): """Build the model for training.""" model = PretrainingModel(config, features, mode == tf.estimator.ModeKeys.TRAIN) print("Model is built!") tvars = tf.traina...
24f99a9bc14662c7d5c1a6e3f6ca5be0fa692b96
52,697
def set_content_type(headers, name): """根据文件名在headers里设置Content-Type。如果headers中已经存在Content-Type,则直接返回。""" headers = headers or {} if 'Content-Type' in headers: return headers content_type = content_type_by_name(name) if content_type: headers['Content-Type'] = content_type retu...
715650add69b91b1db6d506d20cd663c0626cc4f
52,698
def split_folds(X_train, y_train, num_folds): """Split up the training data into `num_folds` folds. The goal of the functions is to return training sets (features and labels) along with corresponding validation sets. In each fold, the validation set will represent (1/num_folds) of the data while the tr...
81cdbb17e2d9feeb536a26ac3bb8066a36aad375
52,699