content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List from typing import Sequence from typing import Tuple def global_bspline_interpolation_first_derivatives( fit_points: List[Vec3], derivatives: List[Vec3], degree: int, t_vector: Sequence[float]) -> Tuple[List[Vec3], List[float]]: """ Interpolate the contr...
8325c3858da5fd13878d5859c554868862a0aa11
45,712
import csv def read_csv_as_list_dict(filename, separator, quote): """ Inputs: filename - name of CSV file separator - character that separates fields quote - character used to optionally quote fields Output: Returns a list of dictionaries where each item in the list corr...
2946b19a246d35761bfce4502209404f70ad70ee
45,714
def _getname(node: Node): """Get mpiexec name for forward and frechet.""" if node.step is not None: return f"_it{node.iter:05d}_ls{node.step:05d}" else: return f"_it{node.iter:05d}"
1fd3c02f4a4d8aa79482a54271a41d74970275c3
45,715
def get_plugin(plugin_name): """ _get_plugin_ Get the deploy plugin requested from the factory """ factory = pluggage.registry.get_factory( 'deploy', load_modules=['cirrus.plugins.deployers'] ) return factory(plugin_name)
91de511d884e460a587de909379e3b8b68b677e1
45,716
import logging def shift_display_orders(at_display_order): """ shift the display order in hpo_site_id_mappings_table when a new HPO is to be added. :param at_display_order: index where the display order :return: """ q = SHIFT_HPO_SITE_DISPLAY_ORDER.format( display_order=at_display_orde...
478f386cf6f7288ba6afa5f67c693f4e37067855
45,718
def get_species_list(request): """ Get list of distinct species labels """ species = models.ImageSet.objects.order_by().values_list('species', flat=True).distinct() return Response(sorted(list(species)))
73de7f3118e9434a0d718663ce3fc2313df16979
45,720
def encode(value): """ Encode Swarm. :param bytes value: a decoded content :return: the encoded content :rtype: str """ mhash = multihash.encode(multihash.from_hex_string(value), 'keccak-256') return make_cid(1, 'swarm-manifest', mhash).buffer
f6310d3e02e7a432461a32e886af42df28264896
45,721
import logging def process_raw_data(raw_data_filepath: str, processed_data_filepath: str) -> None: """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ logger = logging.getLogger(__name__) raw_data = pd.read_csv(ra...
e2b88d5585f732315fcae45fa67be45d887fab03
45,722
def _get_best_corrs(pvals_file): """extract sig motifs """ with h5py.File(pvals_file, "r") as hf: keys = sorted(hf["pvals"].keys()) for key_idx in range(len(keys)): key = "pvals/{}/correlations".format(keys[key_idx]) # get hgnc_ids and corr values with h5py.File(pvals_f...
d421792a62dfae440795ee35a6f46900bbb37b81
45,724
def l2_regularization(params): """Computes l2 regularization term for parameters.""" return jax.tree_util.tree_reduce(op.add, l2_norm(params))
2075debec96d14c34ac9f2a67c799c18597a5efb
45,725
def _read_epoch_encoder_file(metadata): """ Read in epochs from the ``epoch_encoder_file`` in ``metadata`` and return a dataframe. """ if metadata.get('epoch_encoder_file', None) is None: return None else: # data types for each column in the file dtypes = { ...
0f0356a6aec1640c6a35f73d7d08f479176470a0
45,728
from datetime import datetime def get_submission_data_from_pushshift(raw_submission): """Creates a submission object from a Pushshift Submission JSON Parameters: raw_submission (dict): Pushshift Submission instance Returns: dict: object with information about a submission, like body, author or...
0fa00524408623127d32fb6db89398285953ec9b
45,729
def google_webResults(input): """ google_webResults """ return google_webResults_soup(input)
b9402f3b6c3c183101e75d4eeece0c5c5da8f79f
45,730
def pyscv_refresh(*args): """ pyscv_refresh(py_this) -> bool """ return _ida_kernwin.pyscv_refresh(*args)
2c4e9f081e2ae45c35db65ad7f86a153dbe31b16
45,731
def get_auth_header(): """ Return the authentication header. """ return gazu.client.make_auth_header()
04ba9abb2a54b8b1df1db7bc5ac0c944d10961b5
45,732
from typing import Any from typing import List def default_input_mapping(data: Any) -> List[Tensor]: """Finds all tensors in a (nested) collection that have the same batch size. Args: data: a tensor or a collection of tensors (tuple, list, dict, etc.). Returns: A list of all tensors with...
f1f2344cc3364f286a1ea1e19746854a3810c0b8
45,733
from datetime import datetime def get_month_range(months=0, unbounded=False): """获取月的开始和结束时间. :param unbounded: 开区间 """ today = datetime.date.today() year_diff = (today.month + months) // 12 end = today.replace( month=(today.month + months) % 12 + 1, year=today.year + year_d...
1d7f3575c395433b2e632a1f135ddd063cee827c
45,734
from typing import Dict import pkgutil import io def _load_categories(filepath: str) -> Dict[str, str]: """Load data for domain category matching. Args: filepath: relative path to csv file containing domains and categories Returns: Dictionary mapping domains to categories """ data = pkgutil.get_da...
25ec3c4808d4a9624112e277c0597c868a12572c
45,735
def parse_data(format, need_shape=True, **kwargs): """An interface of data parser. Args: format (str): Data parser format. need_shape (bool): Whether need shape attributes. Default: True. Returns: obj (dict): Parsed data. Examples: {'img_names': ['COCO_val2014...
7690dfccf529e2eb849e6621b86636c76b489ad3
45,736
import time def extract_waveforms(ephys_file, ts, ch, t=2.0, sr=30000, n_ch_probe=385, dtype='int16', offset=0, car=True): """ Extracts spike waveforms from binary ephys data file, after (optionally) common-average-referencing (CAR) spatial noise. Parameters ---------- e...
86aa702197a74547b867fe30dec272c3cd3108b4
45,737
def users_groups(user, user_lookup_field, **kwargs): """List all groups belonging to a user""" user_obj = _okta_get("users", user, search=f"profile.{user_lookup_field} eq \"{user}\"") user_id = user_obj["id"] rv = okta_manager.call_okta(f"/users/{user_id}/groups", REST.get) rv.s...
b417b0c90251166b255688a32e58ec32ec7ce56b
45,738
def _previousSibling(self): """ Return the previous sibling NOTE: This is fairly inefficient. The reason that it has to be done this way is because Text nodes are a subclass of `unicode` which is an immutable object. This means that we can't have two references to the same Text object (i....
5b6976232e8cc7f7925fcf95df093706968f76d8
45,739
def file_mapper(json_: dict) -> File: """ Maps the json file response into a File object. :param json_: The json obtained from the endpoint call :type json_: dict :return: A File instance :rtype: :class:`vdx_helper.models.File` """ return File( file_hash=json_["file_hash"], ...
8303a4d3fbc4c5de861d987293c0cd2d7293bc7c
45,740
def will_boom(message: str) -> None: """ This task will indirectly raise an exception. """ return boom(message)
c38ad7b8459f2ea370e4bd2238ed7221c86f1499
45,741
def boolean(value): """ Translate the given value to a boolean object. Example: >>> boolean(True) True >>> boolean(0) False >>> boolean('false') False >>> boolean('yes') True """ if isinstance(value, bool): return value ...
63035a67edb4945cdbe400139c7d2492d8dcfc6b
45,742
def mppe_key_derivation_master_key(password_hash_hash, nt_response): """ RFC 3079 MPPE Key Derivation 3.4. Key Derivation Functions GetMasterKey :param password_hash_hash: :param nt_response: :return: master_key """ magic1 = "\x54\x68\x69\x73\x20\x69\x73\x20\x74\x68\x65\x20\x4d\x50\...
3b39b57d917d70afef2c42069dec3bdd61a2eca5
45,743
def commutator (proc1, proc2): """Returns the commutator of A and B, i.e. [A, B], i.e. A * B * A^-1 * B^-1.""" return proc1 + proc2 + invert_moves(proc1) + invert_moves(proc2)
b87c58c863165f8098377e750d00cbfdf1828521
45,744
import threading import multiprocessing import asyncio def test_PipeJsonRpcSendAsync_3(): """ Put multiple messages to the loop at once. The should be processed one by one. """ n_calls = 0 lock = threading.Lock() def method_handler1(): nonlocal n_calls with lock: n...
7fa1ae208cd0f6c505ad6ed0a916a8e3c20f1e22
45,745
import csv def readTsv(fileLines, d="\t"): """ convenience method for reading TSV file lines into csv.DictReader obj. """ reader = csv.DictReader(fileLines, delimiter=d) return reader
9da19510d787e393d6b00b9c0d64c405830ce5ce
45,746
def dispatch_unit_scada(file): """Extract generator dispatch data Params ------ file : bytes IO object Zipped CSV file of given MMSDM table Returns ------- df : pandas DataFrame MMSDM table in formatted pandas DataFrame """ # Columns to extract ...
1bd2e0ceb3aac226973f88c9b9edefcd57e4df8c
45,747
def _get_weights(Y, dist, weights): """Get the weights from an array of rankings and distances.""" sample_weight = get_weights(dist, weights) # Assign a constant value if applying a uniform weighting # to weigh the samples by the number of available classes sample_weight = sample_weight if sample_w...
9ef4f6d8d842bfec6370de1d33c3680dc848dca7
45,748
def credit(order_number, pnref=None, amt=None): """ Return funds that have been previously settled. :order_number: Order number :pnref: The PNREF of the authorization transaction to use. If not specified, the order number is used to retrieve the appropriate transaction. :amt: A custom ...
eb3c7063dda25d23ab6d2fbdc1859bd8d8771d69
45,749
import requests import pprint def get_location_data(location_list): """iterate through the list of locations and extract data from the API for each one. output the data in json format.""" location_data_json = {} address = 'http://unlock.edina.ac.uk/ws/search?name=' # address of API country_code = 'GB...
6c3eebe16018dae1c58cc381e47cfa8311e32388
45,750
def make_estimator(hparams): """Creates a TPU Estimator.""" generator = _get_generator(hparams) discriminator = _get_discriminator(hparams) if hparams.tpu_params.use_tpu_estimator: config = est_lib.get_tpu_run_config_from_hparams(hparams) return est_lib.get_tpu_estimator(generator, discriminator, hpara...
333a13c400bca1a6b04701bcedc29a1fc064b494
45,753
import time from re import I def predict(model, data, batch, org_shape, rate, gpu): """ 推論実行メイン部 [in] model: 推論実行に使用するモデル [in] data: 分割(I.cnv.split)されたもの [in] batch: バッチサイズ [in] org_shape: 分割前のshape [in] rate: 出力画像の拡大率 [in] gpu: GPU ID [out] img: ...
78e1391377cb0a3d38c3671ba2cf5c0fdf11faa6
45,754
from pathlib import Path def _gen_bids_layout( bids_dir, derivatives, pybids_database_dir, pybids_reset_database, pybids_config=None, ): """Create (or reindex) the BIDSLayout if one doesn't exist, which is only saved if a database directory path is provided """ # Set db dir to Non...
688c5979c97772c18230642964275805995dab5b
45,755
import requests from bs4 import BeautifulSoup def grep_candidate_papers(url): """scrape first 10 papers and choose one :param url: :return: target paper information (title, writer, year, citations, url, paper_id, snippet) """ html_doc = requests.get(url).text soup = BeautifulSoup(html_doc, "ht...
3c70ad55ca335cba3f80af6192de3ea5b3d8ff40
45,756
import re def friendly_filename(filename): """ Creates a 'friendly' filename based on the given filename. The transformation process is as follows: - Get everything after the last slash - Remove the extension - Convert slashes, underscores, bracket, pound to space - Convert consecutive spa...
54a2b65b8bcbc555cd203e72dc2a184b93e65aef
45,757
def has_double_letters(string): """Tests if a string contains forbidden text""" return check_for_contents(string, DOUBLE_LETTERS)
1280676d72a4fa7125ace9e6474a8c95d1c9ef3a
45,758
def preprocess_images_from_directory_val_separate(train_dir_path, test_dir_path, val_dir_path, label_mode, img_size, seed=45, batch_size=32, val_split=0.2, ): """ ...
3635d279f9e8f6be1e910c494b9c2b55142e36f9
45,759
def transform_matrix_for_non_uniform_scale( x_factor, y_factor, z_factor, allow_flipping=False, ret_inverse_matrix=False ): """ Create a transformation matrix that scales by the given factors along `x`, `y`, and `z`. Forward: [[ s_0, 0, 0, 0 ], [ 0, s_1, 0, 0 ], [ ...
8f9743d06aaafa1052b40fa3b0c210c068524956
45,760
def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'): """ Highway Network (cf. http://arxiv.org/abs/1505.00387). t = sigmoid(Wy + b) z = t * g(Wy + b) + (1 - t) * y where g is nonlinearity, t is transform gate, and (1 - t) is carry gate. """ with tf.variable_sco...
68a9905a699d9240352d0660c158c4f19cb644ea
45,761
import requests def test_labels_added(repo, pull_num, labels, session): """ Test whether the labels were added correctly (permissions etc.) :param repo: repository :param pull_num: number of pull request :param labels: labels that were added :param session: open github session ...
d6365022069567f193820b93206f91b636ceb4fc
45,762
from typing import Dict from typing import Any async def provider(cid: int) -> Dict[str, Any]: """获取漫画章节.""" link = f"https://www.manhuagui.com/comic/{cid}/" async with HTTPClient() as client: response = await client.get(link) dom = PyQuery(response.text) title = dom(".book-title h1").te...
659dc81541a8cae9b1155ee8f5fdc491f44135f0
45,763
def causal_numerator(qs, ks, vs): """Computes not-normalized FAVOR causal attention A_{masked}V. Args: qs: query_prime tensor of the shape [L,B,H,M]. ks: key_prime tensor of the shape [L,B,H,M]. vs: value tensor of the shape [L,B,H,D]. Returns: Not-normalized FAVOR causal attention A_{masked}V. ...
b5c3031a26583848b0e2f325475f79dbc6025f7a
45,764
def token_to_char_offset(e, candidate_idx, token_idx): """Converts a token index to the char offset within the candidate.""" c = e["long_answer_candidates"][candidate_idx] char_offset = 0 for i in range(c["start_token"], token_idx): t = e["document_tokens"][i] if not t["html_token"]: token = t["to...
e638dbd7e184d6d14168f926a617d0ab8448f960
45,766
def FixedRateBondAddRedemption(builder, redemption): """This method is deprecated. Please switch to AddRedemption.""" return AddRedemption(builder, redemption)
6b5176e77e4a984417f6b939a7cf989eef8ba0d3
45,767
def proto_dict(message, including_default_value_fields=False, preserving_proto_field_name=True): """Convert a proto message to a standard dict object""" return json_format.MessageToDict( message, including_default_value_fields=including_default_value_fields, ...
8ff6116c2d6e0812d2864394cf5a57c159da8e0f
45,768
def get_arrow(delta): """Create glyphicon chevron :param delta: change in rankings from previous week :return: html code for arrow """ # Define html snippets to build arrow code snu = ' <span class="text-success">' snd = ' <span class="text-danger">' ns = '</span>' up = '<span cla...
f580890245f9b136c39994183d1811f10e796987
45,769
def GetHighlightColour(): """Get the default highlight color @return: wx.Colour """ if wx.Platform == '__WXMAC__': if CARBON: if hasattr(wx, 'MacThemeColour'): color = wx.MacThemeColour(Carbon.Appearance.kThemeBrushFocusHighlight) return color ...
3b488ab64424ccf8348daa82d95e3d88365e2eb5
45,770
def different_ways_memoization(n): """Memoization implementation of different ways, O(n) time, O(n) max stack frames, O(n) pre-allocated space""" d = [0] * (n + 1) d[0] = 1 def different_ways_memoization_helper(k): if k < 0: return 0 if d[k] == 0: d[k] = differen...
e3d965e70904e6af150a45267c8b9ab95c903a9a
45,771
def get_mask_voxels(mask): """ Compute x,y,z coordinates of a binary mask Input: - mask: binary mask Output: - list of tuples containing the (x,y,z) coordinate for each of the input voxels """ indices = np.stack(np.nonzero(mask), axis=1) indices = [tuple(idx) for idx in indi...
8bc4c88c59bc746025d1335ac975d8c5344f1967
45,772
def __virtual__(): """ Only make this state available if the azurearm_resource module is available. """ if "azurearm_resource.resource_group_check_existence" in __salt__: return __virtualname__ return (False, "azurearm_resource module could not be loaded")
84a5de8e5d0297a29a01f3151aa46e0fd309b055
45,773
def video_list(request): """ */entry/videos* The entry interface's videos list. This view lists all videos, their description, and allows you to click on them to view/edit the video. """ message = "" if request.GET.get('success') == 'true': message = "Video deleted successfully...
24bc5e5d8946dc02f2fa1ecab5ef37f4529a8901
45,774
def check_status(r: Response) -> Response: """Check the status code of a response and return it.""" if not r.status_code == codes.ok: if r.url.startswith(BASE_ENDPOINT) and not r.json()["success"]: errors = "\n".join(f"{err['code']}: {err['message']}" for err in r.json()["errors"]) ...
c0a085f17602ebff4b2b5548d48104ca606477be
45,775
def get_execution_platform(command, filename): """ <Purpose> Returns the execution platform based on a best-guess approach using the specified command, as well as the a file's extension. The command takes precedence over the file extension. If the extension is not recognized, then it will be assum...
ceb6afab191269b032bc6122978f630682cac9ca
45,776
import io def _binary_to_string_handle(handle): """Treat a binary (bytes) handle like a text (unicode) handle (PRIVATE).""" try: # If this is a network handle from urllib, # the HTTP headers may tell us the encoding. encoding = handle.headers.get_content_charset() except AttributeE...
2f8f3a6c0c7e1518b10dd58084bc3daa7d2af7af
45,777
def list_of_combs(arr): """returns a list of all subsets of a list""" combs = [] for i in range(0, len(arr) + 1): listing = [list(x) for x in combinations(arr, i)] combs.extend(listing) return combs
5e5fa48ebfe6aeb45a9477ff59daed1f5b95c7a9
45,780
import requests def model_details(model_id): """ Summarize the model. Parameters ---------- model_id: str A valid id for a model in BiGG. """ response = requests.get(BASE_URL + "models/%s" % model_id) response.raise_for_status() return response.json()
ef69b637826aa1b64869cf65e2e50ef96aec2892
45,781
def unique_addons(addons_list): """Validate that an add-on is unique.""" single = set(addon[ATTR_SLUG] for addon in addons_list) if len(single) != len(addons_list): raise vol.Invalid("Invalid addon list on snapshot!") return addons_list
5968398235c0073134851070e2be3fbfaee42e6b
45,783
def signals(): """ Use this decorator to identify the enumeration within your observable class that defines the class' signals. """ # We need an inner function that actually adds the logger instance to the class. def add_signals(cls): # If the class doesn't already extend SignalsEnum... ...
1e1987d0535f173a8ec8989ec2129dea842bd841
45,784
def mod(x): """ Devuelve el modulo del vector x """ s = 0 for c in x: s += c**2 return sqrt(s)
2b4146ee27e40e8de49410880cd3d96d4ef51917
45,785
def calculate_heat_capacity(thm_dstr, temp): """ Calculate the Heat Capacity [Cp(T)] of a species using the coefficients of its NASA polynomial """ cfts = _coefficients_for_specific_temperature(thm_dstr, temp) if cfts is not None: heat_capacity = ( cfts[0] + (cft...
7b744b6bdb63fcac3db09ddb731b13006bf47c7e
45,786
from typing import Dict async def get_provider_icons(mass: MusicAssistant) -> Dict[str, str]: """Get Provider icons as base64 strings.""" return { prov.id: await get_provider_icon(prov.id) for prov in mass.get_providers(include_unavailable=True) }
82418f057f45bd869a3cc8a9311a61dfd25a93dd
45,787
def take(a, indices, axis=None, out=None, mode='raise'): """ Take elements from an array along an axis. When axis is not None, this function does the same thing as "fancy" indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. A call such ...
01093b9b44de0f78950f0f3b3a6ec50c683ff885
45,788
import random import string def get_random_string(): """ generates a random string """ random_string = ''.join( [random.choice(string.ascii_letters + string.digits) for n in range(32)] ) return random_string
1abcea093ded9a04bd7b35f29a0309452e72ab4d
45,790
def calc_slope_components(dem, dx): """Calculate finite slopes.""" # sx,sy = calcFiniteDiffs(elevGrid,dx) # calculates finite differences in X and Y direction using the # 2nd order/centered difference method. # Applies a boundary condition such that the size and location # of the grids in is t...
37405fb33b3a9d85bc5f19110304938dc6a92b8c
45,791
def merge_neighbor_dims(x, axis=0): """Merge neighbor dimension of x, start by axis""" if len(x.get_shape().as_list()) < axis + 2: return x shape = shape_list(x) shape[axis] *= shape[axis+1] shape.pop(axis+1) return tf.reshape(x, shape)
c6d3a79ab13f9a36246804d927ad440323400751
45,792
def matrix_transpose(matrix): """ function to transpose a matrix """ return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
bf2f2ba09a361f1cfd025b7f607e4f1a96705396
45,793
def from_xml(df, column): """ Takes a dataframe with XML-encoded bundles in the given column and returns a Java RDD of Bundle records. Note this RDD contains Bundle records that aren't serializable in Python, so users should use this class as merely a parameter to other methods in this module, l...
0d1f4791c15f6f0aaebb843f99c90d038d1685b3
45,794
def has_s_dismantlable_vertex(graph): """Returns whether a graph has s-dismantlable vertices Args: graph (networkx.classes.graph.Graph): graph Returns: If the graph has dominated vertices, returns a list which only element is the first s-dismantlable vertex. Otherwise, return False ...
a7a7df25218bd8e94b6431e28f2c62a0e168cbed
45,795
import time def evaluate(model, eval_fn, data_loader, batch_axis=0, max_steps=None, verbose=True, print_every=10): """Computes the loss and accuracy on the given dataset in test mode. Example of how to use the evaluation function: ``` def my_eval_fn(model, x, y): return evaluate_on_batch(...
e5313ec75f39f739aae27d51c27be90c9c87650c
45,796
def from_auto_ml(model, shape=None, dtype="float32", func_name="transform"): """ Import scikit-learn model to Relay. """ try: import sklearn # pylint: disable=unused-import except ImportError as e: raise ImportError("Unable to import scikit-learn which is required {}".format(e)) ...
373d474ec81d95235cb6edfa2767b8e4a675c7a0
45,797
import timeit def con_str(image): """Doing contrast stretch and count the time for processing Args: image: input image data (should be ndarray) returns: img_str: image after contrast stretch time_process: time for doing the processing """ start = timeit.default_timer() ...
1b8b19edbe4021bfa09c269d8216a16c1287367f
45,798
def text(): """Returns text equivalent of the W3C text""" return { "@context": "http://www.w3.org/ns/anno.jsonld", "type": "Annotation", "body": { "creator": "user", "type": "TextualBody", "value": "string" }, "generator": { ...
128e75331f178311738b472c1ad9f24a9689bdf4
45,799
def load_deputati(legislatura): """ Carica lista dei deputati NOTA: Include anche i deputati che si sono dimessi e quindi raggiunge un numero totale maggiore di 630. :param legislatura: url identificativo della legislatura. :return: lista di deputati con nome e cognome, ordinata per cogn...
e9a2b6b5104e9b85a78c1d8cbf6bd96f21b7e751
45,800
def create_connection(graph, node1, node2, linktype, propertydict=None, allow_dup=False): """ :param graph: :param node1: :param node2: :param linktype: :param propertydict: :return: """ graph = graphs[graph] anode = node1 bnode = node2 if isinstance(node1, dict): ...
d2224abe6be71c938358bb49dc4c00a179f8277a
45,801
def download_log(request, log_id): """ """ user = request.user # Check that the user is allowed to download the log if not (user.is_authenticated and (user.has_perm("jobs.view_joblog"))): return HttpResponse("Not authorized to view logs", status=401) try: log = JobLog.objects.g...
e9f4087df32b039f46a763c886e2d65a87cd3386
45,802
def build_keras_network(model_file: str) -> Network: """ Wrapper for the more low-level KerasNetwork classes. Figures out the backend and returns an istance of the appropriate class. Parameters ---------- model_file Path to the .h5 model file. Returns ------- """ curren...
da804e83654d4214f040edd41e976207d382a73c
45,803
def get_parser(identifier): """ :param identifier: :return: """ ret_parser = None for parser in BINSON_VALUES: if identifier in parser.identifiers(): ret_parser = parser.from_bytes break if not ret_parser: error_msg = 'Value 0x%02x' % identifier ...
7defa94bbc3e4d419bfe0faa0b05e6e47046eced
45,804
import numpy def approximate_quantum_error(error, *, operator_string=None, operator_dict=None, operator_list=None): """ Return an approximate QuantumError bases on the Hilbert-Schmidt metric. Currently this is only ...
c5989a313ba39a84b3b91f1c01debb3510eec2eb
45,805
def demo(sess, net, im_file, icdar_dir, oriented=False, ltrb=False): """Detect object classes in an image using pre-computed object proposals.""" # Load the demo image im = helper.read_rgb_img(im_file) # Detect all object classes and regress object bounds timer = Timer() timer.tic() scores...
80ee1a5fa88c71144940d650340bbbb1a1d0c9b1
45,806
def load_cam_ext(file): """ read camera txt file """ cam = np.empty((3, 4)) data = file.read().split() for i in range(3): for j in range(4): cam[i, j] = data[4 * i + j + 1] return cam
225ac897b3f47cf8efc22c46671e12ffc6a34ff6
45,807
def error_propagation( func: sp.Function, syms: tp.List[sp.Symbol], vals: np.ndarray, covar: np.ndarray = None, stds: np.ndarray = None) -> tp.Tuple[sp.Expr, sp.Expr]: """Error propagation for an arbitrary function""" if (covar is None) == (stds is None): raise Va...
8f9a8ad5a76c815d4cb8f90bf855da12cd442c4c
45,808
def get_db_config(): """ 获取服务器链接 :return: host, user, password, database, port, charset """ db_config = get_config() if "mysql" in db_config: host = db_config['mysql']['host'] user = db_config['mysql']['user'] password = db_config['mysql']['password'] database = ...
2307b5abbbc9a0fba194d97bb1b5533c71990553
45,809
from datetime import datetime from typing import List def phase_dates(base_sunday: datetime.date) -> List[datetime.datetime]: """ Test dates and times for the entire week of base_sunday. These are the times we will use as our message times for updating bell prices. """ sunday = relative_message_ti...
9a7975299d0e19888a2c926ff939313fd4736c81
45,810
def rejection_sampling(X, e, bn, N): """Estimar a distribuição de probabilidade da variável X dada Evidência e em BayesNet bn, usando N amostras. [Figura 14.14] Gera um ZeroDivisionError se todas as N amostras são rejeitadas, I.e., inconsistente com e.""" counts = {x: 0 for x in bn.variable_values(X...
1a66a9807ab2dcc47a9ac997583e8f9a9b5247a7
45,811
def get_valid_pbc(inputpbc): """ Return a list of three booleans for the periodic boundary conditions, in a valid format from a generic input. :raise ValueError: if the format is not valid. """ if isinstance(inputpbc, bool): the_pbc = (inputpbc, inputpbc, inputpbc) elif (hasattr(inp...
75ef8175debe6cca03d73fa7430a7bcd44a651ec
45,812
def test_negate_of_neg(): """Check functionality of unary neg operator.""" return """ fn main() { var a := -1; {dest} = -a; } """
7e66a38e74df011e19705821c1e33efea31b8eb5
45,813
def get_user_for_token(token, scope, max_age=None): """ Given a selfcontained token and a scope try to parse and unsign it. If max_age is specified it checks token expiration. If token passes a validation, returns a user instance corresponding with user_id stored in the incoming token. ...
2e0bd487cf0cf49ba88a55b56437c313468a8f87
45,814
import typing def redirect(url: str) -> typing.Callable: """ This function returns a decorator that redirects the request to the given url. """ html = f""" <!DOCTYPE html> <html> <p>Redirecting...</p> <p><a href="{url}">Click here if you are not redirected</...
5ead24898fba9e98fdb3a31c2bafb87f951f2479
45,816
import torch def bi_tempered_binary_logistic_loss(activations, labels, t1, t2, label_smoothing = 0.0, num_iters=5, reduction='mean'): """Bi-Tempered binary logistic loss. Args: activations: A tensor containing activations for class 1. labels: A tens...
1b1b7f6e738839eb2527f17d9765734f313fdb17
45,817
import torch def bucketize(tensor, bucket_boundaries): """Equivalent to numpy.digitize Notes ----- Torch does not have a built in equivalent yet. I found this snippet here: https://github.com/pytorch/pytorch/issues/7284 """ result = torch.zeros_like(tensor, dtype=torch.int32) for boun...
ee48e11de50e52278ddf940e32c04e330dceed97
45,819
import re import inspect def _get_task_path(wrapped, instance) -> str: """Get the synthetic URL path for a task, based on the `wrapt` parameters.""" funcname = wrapped.__name__ if funcname.startswith("_") and not funcname.endswith("_"): funcname = re.sub(r"^_+", repl="", string=funcname, count=1) ...
16ca96d29abddfa104afc5a0ec466e0bd1d202dc
45,820
def location_from_dictionary(d): """ Builds a *Location* object out of a data dictionary. Only certain properties of the dictionary are used: if these properties are not found or cannot be read, an error is issued. :param d: a data dictionary :type d: dict :returns: a *Location* instance ...
5bb064993a02e1368484a9a9e53e3a106b86f2ea
45,821
from typing import Mapping import inspect from typing import Tuple from typing import Any def assert_args_correct_typing( params: Mapping[str, inspect.Parameter], args: Tuple[Any], kwargs: Mapping[str, Any], join: bool = True, context: str = "", ) -> None: """ Applies :func:`output_if_args...
7955406cd44716094a0fbbb07002db30e92d0901
45,822
def get_task(username, m_wf_id, wf_id, task_id): """ Returns task identified by m_wf_id, wf_id, task_id. :query boolean pretty-print: Return formatted JSON response :statuscode 200: OK :statuscode 401: Authentication failure :statuscode 403: Authorization failure :statuscode 404: Not found...
e24e79ecc8fa18c90e8dd2cdc21ef39f1e796ff1
45,824
def requires_internet(func): """ Decorator for functions that require internet Parameters ---------- func: func Function that requires an active internet connection Returns ------- """ def inner(*args, **kwargs): if internet(): return func(*args, **kwargs) ...
97b84059361d2ca102c199c28ba33a053f5ac806
45,826
from emoji_data_python import emoji_short_names, EmojiChar from typing import cast import re def replace_colons(text: str, strip: bool = False) -> str: """Parses a string with colon encoded emoji and renders found emoji. Unknown emoji are left as is unless `strip` is set to `True` :param text: String of ...
08488e31bf93478ee0cb6f52ea8e544c2c2480f5
45,827
def check_feature_names(num_features, feature_names, active_features): """Check feature names for consistency and supply defaults if necessary. :param num_features: positive integer; number of features :param feature_names: list of strings or None; if not None, must have num_features elements :param ac...
d8b53139af08053dee24ae762b283fadb0709f78
45,828