content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def to_dense(arr): """ Convert a sparse array to a dense numpy array. If the array is already a numpy array, just return it. If the array passed in is a list, then we recursively apply this method to its elements. Parameters ----------- arr : :obj:`numpy.ndarray`, :obj:`scipy.sparse...
1fa2ccdd184aa4155cfd121310d67e9e73ffff17
3,300
def output_results(results, way): """Helper method with most of the logic""" tails = way(results) heads = len(results) - tails result = ", ".join([["Heads", "Tails"][flip] for flip in results]) return result + f"\n{heads} Heads; {tails} Tails"
f60716004b11e115fe69a14b70957b5b66080dbc
3,301
def guess_init(model, focal_length, j2d, init_pose): """Initialize the camera translation via triangle similarity, by using the torso joints . :param model: SMPL model :param focal_length: camera focal length (kept fixed) :param j2d: 14x2 array of CNN joints :param init_pose: 72D vector o...
ce1ca89bc60500cc59441c97cf9d71ef3d9b528b
3,302
def TCnCom_Dump(*args): """ Dump(TCnComV const & CnComV, TStr Desc=TStr()) Parameters: CnComV: TCnComV const & Desc: TStr const & TCnCom_Dump(TCnComV const & CnComV) Parameters: CnComV: TCnComV const & """ return _snap.TCnCom_Dump(*args)
c2ce258a12074106e4c93e938dfa988b1bc29015
3,303
import os def roughness_convert(reference, invert) : """ Open an image and modify it to acomodate for the way Mitsuba Renderer interprets roughness. returns the reference for the image. """ # Conversion for Mitsuba : no value above .5, and if this is a glossinness map, do an inversion. # I'm doing a linear inve...
c40812d770b616b1cbdcc469ebe0e4c562b16d41
3,304
import functools def get_reparametrize_functions( params, constraints, scaling_factor=None, scaling_offset=None ): """Construct functions to map between internal and external parameters. All required information is partialed into the functions. Args: params (pandas.DataFrame): See :ref:`para...
a0d8f283bf44f66fb098c499a6b610174078b980
3,305
def gaussNewton(P, model, target, targetLandmarks, sourceLandmarkInds, NN, jacobi = True, calcId = True): """ Energy function to be minimized for fitting. """ # Shape eigenvector coefficients idCoef = P[: model.idEval.size] expCoef = P[model.idEval.size: model.idEval.size + model.expEval.size] ...
2b54080bf9f76a8a16e26c10f6209f55bcb0c57f
3,306
from re import T def arange(start, stop=None, step=1, dtype='int32'): """Creates a 1-D tensor containing a sequence of integers. The function arguments use the same convention as Theano's arange: if only one argument is provided, it is in fact the "stop" argument. """ return T.arange(start, st...
72f505d7f1928d4e35a7e183a30bdc8cddf2edd7
3,307
def create_attachable_access_entity_profile(infra, entity_profile, **args): """Create an attached entity profile. This provides a template to deploy hypervisor policies on a large set of leaf ports. This also provides the association of a Virtual Machine Management (VMM) domain and the physical network infrastructu...
96c711b8c5de52ca44483edcb478a829986e901a
3,308
from typing import Tuple from typing import List import csv def tensor_projection_reader( embedding_file_path: str, label_file_path: str ) -> Tuple[np.ndarray, List[List[str]]]: """ Reads the embedding and labels stored at the given paths and returns an np.ndarray and list of labels :para...
7e8cc804181ead221a283b4d8aa95a9e9b7d00ef
3,309
def xml_to_dict(xmlobj, saveroot=True): """Parse the xml into a dictionary of attributes. Args: xmlobj: An ElementTree element or an xml string. saveroot: Keep the xml element names (ugly format) Returns: An ElementDict object or ElementList for multiple objects """ if isins...
85428aaefc1f48881891ddd910daef1cc4f1547e
3,310
import torch import numpy def conve_interaction( h: torch.FloatTensor, r: torch.FloatTensor, t: torch.FloatTensor, t_bias: torch.FloatTensor, input_channels: int, embedding_height: int, embedding_width: int, hr2d: nn.Module, hr1d: nn.Module, ) -> torch.FloatTensor: """Evaluate ...
fadf03905ed5c822df0fe099cb439f481073d202
3,311
def index(): """Show Homepage""" return render_template("index.html")
f05985d10a9699783f6f3c4c4f88c8be48a0a7a9
3,312
import copy import logging def structure_standardization(smi: str) -> str: """ Standardization function to clean up smiles with RDKit. First, the input smiles is converted into a mol object. Not-readable SMILES are written to the log file. The molecule size is checked by the number of atoms (non-hydrogen)...
ba739eb6c2a822b3584badb2247ec97846c123e1
3,313
def with_input_dtype(policy, dtype): """Copies "infer" `policy`, adding `dtype` to it. Policy must be "infer" or "infer_float32_vars" (i.e., has no compute dtype). Returns a new policy with compute dtype `dtype`. The returned policy's variable dtype is also `dtype` if `policy` is "infer", and is `float32` if ...
32815d4499b57ed8623a55414ef7b6115c450726
3,314
import io import warnings def decode_object_based(effects): """ Reads and decodes info about object-based layer effects. """ fp = io.BytesIO(effects) version, descriptor_version = read_fmt("II", fp) try: descriptor = decode_descriptor(None, fp) except UnknownOSType as e: w...
6471f6f9987b1817f223fe02a5ba5923ddf8c0c8
3,315
def example_add(x: int, y: int): """ ... """ return x + y
88e835e872e2ef4eb54f721e3d556ee7f8db1bbc
3,316
from typing import Optional def inverse(text: str, reset_style: Optional[bool] = True) -> str: """Returns text inverse-colored. Args: reset_style: Boolean that determines whether a reset character should be appended to the end of the string. """ return set_mode("inverse", False) ...
4d8aceada756386348b68c13dabe4948b15986c3
3,317
def make(): """ hook function for entrypoints :return: """ return LocalFileSystem
7e48c7c4a9225f4bd3d7d430b6221005e2787e55
3,318
def configure(): """read configuration from command line options and config file values""" opts = parse_options() defaults = dict(v.split('=') for v in opts.S or []) with open(opts.config_file) as config: targets = read_config(config, defaults, opts.ignore_colon) if opts.T: return {o...
09c85e8fce3947ee54c1524545e14fe25a4d054e
3,319
def proper_loadmat(file_path): """Loads using scipy.io.loadmat, and cleans some of the metadata""" data = loadmat(file_path) clean_data = {} for key, value in data.items(): if not key.startswith("__"): clean_data[key] = value.squeeze().tolist() return clean_data
d7cbc547ab47235db2df80fdf2ca9decd3a4c42d
3,320
from typing import List def _get_time_total(responses: List[DsResponse]) -> List[str]: """Get formated total time metrics.""" metric_settings = { "name": "time_total", "type": "untyped", "help": "Returns the total time in seconds (time taken to request, render and download).", ...
641bff0a75d1f61afa7ad1d9e9058faee58c18b8
3,321
async def list_sessions( cache: Redis = Depends(depends_redis), ) -> ListSessionsResponse: """Get all session keys""" keylist = [] for key in await cache.keys(pattern=f"{IDPREFIX}*"): if not isinstance(key, bytes): raise TypeError( "Found a key that is not stored as b...
7fce8610a5c53317636da7e5408a582c10faff3c
3,322
def square(x, out=None, where=True, **kwargs): """ Return the element-wise square of the input. Args: x (numpoly.ndpoly): Input data. out (Optional[numpy.ndarray]): A location into which the result is stored. If provided, it must have a shape that the inp...
a59297f913433ec870a9eb7d8be5eea21a78cc41
3,323
def evaluate_tuple(columns,mapper,condition): """ """ if isinstance(condition, tuple): return condition[0](columns,mapper,condition[1],condition[2]) else: return condition(columns,mapper)
5200da50900329431db4ce657e79135534b8469e
3,324
import scipy def imread(path, is_grayscale=True): """ Read image using its path. Default value is gray-scale, and image is read by YCbCr format as the paper said. """ if is_grayscale: return scipy.misc.imread(path, flatten=True, mode='YCbCr').astype(np.float) else: return scipy...
b32e918583c7d4a3bc3e38994bc4aef7dfdc5206
3,325
def get_priority_text(priority): """ Returns operation priority name by numeric value. :param int priority: Priority numeric value. :return: Operation priority name. :rtype: str | None """ if priority == NSOperationQueuePriorityVeryLow: return "VeryLow" elif priority == NSOperat...
02986079f164672d58d7d5476e82463e1343ba9d
3,326
import posixpath def get_experiment_tag_for_image(image_specs, tag_by_experiment=True): """Returns the registry with the experiment tag for given image.""" tag = posixpath.join(experiment_utils.get_base_docker_tag(), image_specs['tag']) if tag_by_experiment: tag += ':' + e...
f45898d1f9adb74ca1133be05ab60da5de9df9e6
3,327
def call_pager(): """ Convenient wrapper to call Pager class """ return _Pager()
00cba0c47fc18417ab82ff41ae956961dcff9db4
3,328
def sign_in(request, party_id, party_guest_id): """ Sign guest into party. """ if request.method != "POST": return HttpResponse("Endpoint supports POST method only.", status=405) try: party = Party.objects.get(pk=party_id) party_guest = PartyGuest.objects.get(pk=party_guest_...
2672344a92fb0d029946bf30d1a0a89d33a24a0f
3,329
from datetime import datetime def mcoolqc_status(connection, **kwargs): """Searches for annotated bam files that do not have a qc object Keyword arguments: lab_title -- limit search with a lab i.e. Bing+Ren, UCSD start_date -- limit search to files generated since a date formatted YYYY-MM-DD run_t...
44273aa0f7441775258e0b390059cfe9778747e2
3,330
def isValidListOrRulename(word: str) -> bool: """test if there are no accented characters in a listname or rulename so asciiletters, digitis, - and _ are allowed """ return bool(reValidName.match(word))
ec826f31604f8dd43ba044e1f6ffbaaf758bdb88
3,331
def glyph_has_ink(font: TTFont, name: Text) -> bool: """Checks if specified glyph has any ink. That is, that it has at least one defined contour associated. Composites are considered to have ink if any of their components have ink. Args: font: the font glyph_name: The name of the ...
6450e2ec2ed7158f901c7e50999245042d880dce
3,332
async def async_setup_entry(hass, entry, async_add_entities): """ Set up n3rgy data sensor :param hass: hass object :param entry: config entry :return: none """ # in-line function async def async_update_data(): """ Fetch data from n3rgy API This is the place to pr...
e2dd956428eb377c56d104e49889760f6ba9b653
3,333
def main(): """ Process command line arguments and run the script """ bp = BrPredMetric() result = bp.Run() return result
b61a80ee805dfc2d6e146b24ae0564bb5cda6e83
3,334
def step(init_distr,D): """ """ for k in init_distr.keys(): init_distr[k] = D[init_distr[k]]() return init_distr
6270dd2818d2148e7d979d249fbb2a3a596dc2de
3,335
def from_json(data: JsonDict) -> AttributeType: """Make an attribute type from JSON data (deserialize) Args: data: JSON data from Tamr server """ base_type = data.get("baseType") if base_type is None: logger.error(f"JSON data: {repr(data)}") raise ValueError("Missing require...
eba662ed1c1c3f32a5b65908fae68d7dd41f89e3
3,336
def ftduino_find_by_name(name): """ Returns the path of the ftDuino with the specified `name`. :param name: Name of the ftDuino. :return: The path of the ftDuino or ``None`` if the ftDuino was not found. """ for path, device_name in ftduino_iter(): if device_name == name: re...
8a03d0b84dc9180fb2885d46fc8f1755cd2c6eed
3,337
import numbers def spectral_entropy (Sxx, fn, flim=None, display=False) : """ Compute different entropies based on the average spectrum, its variance, and its maxima [1]_ [2]_ Parameters ---------- Sxx : ndarray of floats Spectrogram (2d). It is recommended to work w...
533b388781e158b558ee38645271194adb414729
3,338
def _percentages(self): """ An extension method for Counter that returns a dict mapping the keys of the Counter to their percentages. :param self: Counter :return: a dict mapping the keys of the Counter to their percentages """ # type: () -> dict[any, float] length = float(sum(count for ...
752781a9697113ebf3297050649a7f4ba1580b97
3,339
def find_best_word_n(draw, nb_letters, path): """ """ lexicon = get_lexicon(path, nb_letters) mask = [is_word_in_draw(draw, word) for word in lexicon["draw"]] lexicon = lexicon.loc[mask] return lexicon
ff3e06e69e6c56f59cf278c10e6860c6d0529b87
3,340
import json def feature_reader(path): """ Reading the feature matrix stored as JSON from the disk. :param path: Path to the JSON file. :return out_features: Dict with index and value tensor. """ features = json.load(open(path)) features = {int(k): [int(val) for val in v] for k, v in featur...
959e37ae5a3b0b482d67e5e917211e2131b3c643
3,341
def locate_all_occurrence(l, e): """ Return indices of all element occurrences in given list :param l: given list :type l: list :param e: element to locate :return: indices of all occurrences :rtype: list """ return [i for i, x in enumerate(l) if x == e]
95b662f359bd94baf68ac86450d94298dd6b366d
3,342
def UVectorFromAngles(reflection): """ Calculate the B&L U vector from bisecting geometry angles """ u = np.zeros((3,), dtype='float64') # The tricky bit is set again: Busing & Levy's omega is 0 in # bisecting position. This is why we have to correct for # stt/2 here om = np.deg2rad...
fe282e8ac67e5fafb34c63e1745cb9b262602a7a
3,343
import numbers def to_pillow_image(img_array, image_size=None): """Convert an image represented as a numpy array back into a Pillow Image object.""" if isinstance(image_size, (numbers.Integral, np.integer)): image_size = (image_size, image_size) img_array = skimage.img_as_ubyte(img_array) ...
435bfe79afc59f1cbdd250ca9e1558de8921f7b6
3,344
from datetime import datetime import os def new_session_dir(rootdir, pid, sid): """ Creates a path to a new session directory. Example: <DATA_ROOT>/p0/session_2014-08-12_p0_arm1 """ date_str = datetime.date.today().strftime('%Y-%m-%d') session_dir = os.path.join( rootdir, ...
0dd3af50c7ad83478ab8be136b775c63aceca0c4
3,345
from typing import Iterator def seq_to_sentence(seq: Iterator[int], vocab: Vocab, ignore: Iterator[int]) -> str: """Convert a sequence of integers to a string of (space-separated) words according to a vocabulary. :param seq: Iterator[int] A sequence of integers (tokens) to be converted. :param vo...
2138bd3454c61b7e2a6e3dad25876fdcc4cabe4e
3,346
from skimage.exposure import histogram, match_histograms import gc def estimate_exposures(imgs, exif_exp, metadata, method, noise_floor=16, percentile=10, invert_gamma=False, cam=None, outlier='cerman'): """ Exposure times may be inaccurate. Estimate the correct values by fitting a linear system. :imgs: ...
db80a45dc30cea86a71688a56447ef0166bb49b2
3,347
def default_reverse(*args, **kwargs): """ Acts just like django.core.urlresolvers.reverse() except that if the resolver raises a NoReverseMatch exception, then a default value will be returned instead. If no default value is provided, then the exception will be raised as normal. NOTE: Any excep...
cadf9452c309adb4f2a865a3ea97ee2aca5b1acc
3,348
def get_company_periods_up_to(period): """ Get all periods for a company leading up to the given period, including the given period """ company = period.company return (company.period_set .filter(company=company, end__lte=period.end))
604814f60a58f9155a47faba62561f94d3197fb2
3,349
from typing import List def format_count( label: str, counts: List[int], color: str, dashed: bool = False ) -> dict: """Format a line dataset for chart.js""" ret = { "label": label, "data": counts, "borderColor": color, "borderWidth": 2, "fill": False, } if ...
40f5aee7ad5d66f57737345b7d82e45a97cf6633
3,350
def detect_ripples(eeg): """Detect sharp wave ripples (SWRs) from single channel eeg (AnalogSignalArray). """ # Maggie defines ripples by doing: # (1) filter 150-250 # (2) hilbert envelope # (3) smooth with Gaussian (4 ms SD) # (4) 3.5 SD above the mean for 15 ms # (5) full ripple ...
c92190ee6c31e6c1805841258224fa2aa7d4a749
3,351
def cymdtodoy(str): """cymdtodoy(str) -> string Convert a legal CCSDS time string with the date expressed as a month and day to a simple time string with the date expressed as a day-of-year.""" try: (year, mon, day, hour, min, sec) = cymdtoaymd(str) doy = aymdtodoy(year, mon, day, hour, min, sec) except...
a3f8af2bac6f2d11aad5ec87c22b9e6254256d26
3,352
def configured_hosts(hass): """Return a set of the configured hosts.""" """For future to use with discovery!""" out = {} for entry in hass.config_entries.async_entries(DOMAIN): out[entry.data[CONF_ADDRESS]] = { UUID: entry.data[UUID], CONF_ADDRESS: entry.data[CONF_ADDRESS...
04d24a8011a706d618699528129ba394ec54a590
3,353
import sys import importlib import os import torch def load_model(model_name, weights, model_paths, module_name, model_params): """Import model and load pretrained weights""" if model_paths: sys.path.extend(model_paths) try: module = importlib.import_module(module_name) creator =...
c23362011980d796a43bfd8125070b4fd35d76cf
3,354
def generate_keys(directory: str, pwd: bytes = None) -> (ec.EllipticCurvePrivateKey, ec.EllipticCurvePublicKey): """ Generate the public and private keys Generated keys have a default name, you should rename them This can be done with os.rename() :param directory: folder where the keys are made ...
28821be8d081e8c8369b889e3ce1a18336ab3c9f
3,355
import os import subprocess def test_notebooks(): """ Run all notebooks in the directories given by the list `notebook_paths`. The notebooks are run locally using [treon](https://github.com/ReviewNB/treon) and executed in each directory so that local resources can be imported. Returns: n...
4daec4eb274ef0c25e124704b77ace0a6e87b801
3,356
def get_storage_config_by_data_type(result_table_id): """ 根据rt_id获取存储配置列表 :param result_table_id:rtid :return: response:存储配置列表 """ return DataStorageConfig.objects.filter(result_table_id=result_table_id, data_type="raw_data")
12df282ece7176f003726dfb5ee1c1a1707ef6ad
3,357
from typing import List def separate_args(args: List[str]) -> (List[str], List[str]): """Separate args into preparser args and primary parser args. Args: args: Raw command line arguments. Returns: A tuple of lists (preparser_args, mainparser_args). """ preparser_args = [] if a...
49829516f6982d041386d95c20b0028034e066a9
3,358
def lookup_alive_tags_shallow(repository_id, start_pagination_id=None, limit=None): """ Returns a list of the tags alive in the specified repository. Note that the tags returned *only* contain their ID and name. Also note that the Tags are returned ordered by ID. """ query = (Tag .select(Tag.id, ...
a0970da049fb2fa7cd3cc69c459fb7917d8185c8
3,359
def getLesson(request): """ Get the JSON representation for a lesson. """ print("getLesson called...") lesson_id = None if 'lesson_id' in request.matchdict: lesson_id = request.matchdict['lesson_id'] if lesson_id is None: # This should return an appropriate error about not ...
d721ab060462368d9ce3af071faa7e0751b34984
3,360
def vector3d(mode,xdata,ydata,zdata,udata,vdata,wdata,scalardata=None,fig=None,zscale=500.,vector_color=(0,0,0),vector_cmap=None,alpha=1.0,vector_mode='2darrow', scale=1, spacing=8., set_view=None): """ fig: integer or string, optional. Figure key will plot data on corresponding mlab figure, if it exists, or cr...
dcffddd28f966c87801ae98b5da32fe06f5b9b08
3,361
def make_daysetting_from_data(data): """ Constructs a new setting from a given dataset. This method will automatically instantiate a new class matching the type of the given dataset. It will fill all values provided by the dataset and then return the created instance """ factory = { "color": Col...
d3f78fe67441e555d5b525ce1ca6cb334769942a
3,362
from typing import Optional def read_report(file) -> Optional[Report]: """ Reads the report meta-data section of the file. :param file: The file being read from. :return: The report section of the file. """ # Use a peeker so we don't read beyond the end of the header section pe...
557402ee57675fcc11a0a05da02d554c1b2f13db
3,363
def get_valid_segment(text): """ Returns None or the valid Loki-formatted urn segment for the given input string. """ if text == '': return None else: # Return the converted text value with invalid characters removed. valid_chars = ['.', '_', '-'] new_text = '' for c...
423c1764b590df635b0794bfe52a0a8479d53fbf
3,364
import os import json def get_aimpoint_offsets(): """ Get most recent aimpoint offset values :returns: tuple of dy_acis_i, dz_acis_i, dy_acis_s, dz_acis_s (arcsec) """ info_file = os.path.join(opt.data_root, 'info.json') with open(info_file, 'r') as fh: info = json.load(fh) proce...
08df0254ddb85f57a5b1be75aa2b1d4cf9224f3b
3,365
def mparse(filename, staticObstacleList=list(), **kwargs): """ Parses a map file into a list of obstacles @param filename The file name of the map file @return A list of obstacles """ polyList = kwargs.get("nodes", list()) obstacleList = list() try: if filename is not None: ...
ea62ff3e4f42ad9150be248c5a13d3c367f668b2
3,366
import typing import logging def install_pip_packages(python_executable: str, pip_packages: typing.List[str]) -> bool: """Install pip packages for the specified python. Args: python_executable: Python executable used to install pip packages. pip_packages: List of pip packages to ...
d8316fde5249def1b2d98aa5e247f3713ee40653
3,367
def sort_f_df(f_df): """Sorts f_df by s_idx first then by l_idx. E.g. for scenario 0, see all decision alternatives in order, then scenario 1, scenario 2, etc. Parameters ---------- f_df : pandas.DataFrame A dataframe of performance values, `f`, with indexes for the scenario, `...
ec82966a7a2fb417312198afe42109ed5883d31d
3,368
def get_empath_scores(text): """ Obtains empath analysis on the text. Takes the dictionary mapping categories to scores, which is produced by passing the text to empath, and returns the scores. Args: text: string containing text to perform empath analysis on Returns: A list of empa...
f68a55a2dc4ba98696e9df3f88aaacf73d81ff2d
3,369
def ending_counts(sequences): """Return a dictionary keyed to each unique value in the input sequences list that counts the number of occurrences where that value is at the end of a sequence. For example, if 18 sequences end with DET, then you should return a dictionary such that your_starting_...
c12bd2565649d373e86cef31f9e23856f4302fba
3,370
import json import logging def sqlite_insert(engine, table_name, data): """ Inserts data into a table - either one row or in bulk. Create the table if not exists. Parameters ---------- engine: sqlalchemy engine for sqlite uri: string data: dict Returns ------- bool "...
430e3109d233119043bc6c5f10ba966aa08992c1
3,371
def _fit_solver(solver): """ Call ``fit`` on the solver. Needed for multiprocessing. """ return solver.fit()
7007752777445d2cc6d476d7af1f83d6cdfe236b
3,372
import types def flatten(l): """ recursively turns any nested list into a regular list (using a DFS) """ res = [] for x in l: if (isinstance(x, types.ListType)): res += flatten(x) else: res.append(x) return res
5947566b7dfd1d03204c2a39f1e853ce812e18fe
3,373
def build_column_hierarchy(param_list, level_names, ts_columns, hide_levels=[]): """For each parameter in `param_list`, create a new column level with parameter values. Combine this level with columns `ts_columns` using Cartesian product.""" checks.assert_same_shape(param_list, level_names, axis=0) pa...
f19d4f93a0cfbc6ebe700285c8761c78ca5f9b1a
3,374
def gradient_descent(f, xk, delta = 0.01, plot=False, F = None, axlim = 10): """ f: multivariable function with 1 array as parameter xk : a vector to start descent delta : precision of search plot : option to plot the results or not F : the function f expressed with 2 arrays in argument (X,Y) re...
99b8da92c6df296c2d02b2f0d14f38b94ea87aef
3,375
def _get_cells(obj): """Extract cells and cell_data from a vtkDataSet and sort it by types.""" cells, cell_data = {}, {} data = _get_data(obj.GetCellData()) arr = vtk2np(obj.GetCells().GetData()) loc = vtk2np(obj.GetCellLocationsArray()) types = vtk2np(obj.GetCellTypesArray()) for typ in VT...
84f603d92e1548b6d9ebe33b31ac4277bed49281
3,376
def check_X(X, enforce_univariate=False, enforce_min_instances=1): """Validate input data. Parameters ---------- X : pd.DataFrame enforce_univariate : bool, optional (default=False) Enforce that X is univariate. enforce_min_instances : int, optional (default=1) Enforce minimum n...
2022cbccfaec72cc68e2d9692d96fb3241d9991a
3,377
def parse_amount(value: int) -> Decimal: """Return a scaled down amount.""" return Decimal(value) / Decimal(AMOUNT_SCALE_FACTOR)
66e7668ed5da3d451644de00dc98bfb2bf8745f0
3,378
def svn_ra_do_update2(*args): """ svn_ra_do_update2(svn_ra_session_t session, svn_ra_reporter3_t reporter, void report_baton, svn_revnum_t revision_to_update_to, char update_target, svn_depth_t depth, svn_boolean_t send_copyfrom_args, svn_delta_editor_t update_editor, void upda...
139fd5b8ea5b86ad70f056d5b53a86cc01ce3952
3,379
from jsonschemaplus.schemas import metaschema import string import array def resolve(schema, copy=False): """Resolve schema references. :param schema: The schema to resolve. :return: The resolved schema. """ _substitutions = {'%25': '%', '~1': '/', '~0': '~'} def _resolve_refs(schema, ro...
b410d2a7e165b988787ed3041a2eef13f35ea188
3,380
from ._sentiwords import tag def sentiwords_tag(doc, output="bag"): """Tag doc with SentiWords polarity priors. Performs left-to-right, longest-match annotation of token spans with polarities from SentiWords. Uses no part-of-speech information; when a span has multiple possible taggings in Senti...
c4769e82d9b9aff55f7d6e3de08188f5ba6501bb
3,381
def _GetCommandTaskIds(command): """Get a command's task ids.""" # A task count is the number of tasks we put in the command queue for this # command. We cap this number to avoid a single command with large run count # dominating an entire cluster. If a task count is smaller than a run count, # completed task...
98d6ac89e4f5569968740475eba924840170464f
3,382
import uuid import json def save_orchestrator_response(url, jsonresponse, dryrun): """Given a URL and JSON response create/update the corresponding mockfile.""" endpoint = url.split("/api/")[1].rstrip("/") try: path, identifier = endpoint.rsplit("/", maxsplit=1) except ValueError: path...
aab7d3e925d7b4d695832ba7aa45bd93b3824fb1
3,383
from operator import or_ def aggregate_responses(instrument_ids, current_user, patch_dstu2=False): """Build a bundle of QuestionnaireResponses :param instrument_ids: list of instrument_ids to restrict results to :param current_user: user making request, necessary to restrict results to list of pa...
4a829cceec49a583aa69676ec2847a60ce5979da
3,384
import math def compute_bleu(reference_corpus, translation_corpus, max_order=4, use_bp=True): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of references for each translation. Each reference should be tokenized into a list ...
e0978e3b05513c32ac55f72b298e8752eb887fb1
3,385
def flip(inputDirection: direction) -> direction: """ Chooses what part of the general pointer to flip, by DP%2 == CC rule, providing the following flow: (0,0) -> (0,1) (0,1) -> (1,1) (1,1) -> (1,0) (1,0) -> (2,0) (2,0) -> (2,1) (2,1) -> (3,1) (3,1) -> (3,0) (3,0) -> (0,0) :p...
44797849c14736de7380c5169e29bc9095f11a45
3,386
def save(request): """Update the column levels in campaign_tree table with the user's input from the data warehouse frontend.""" if any(request["changes"]): query = 'UPDATE campaign_tree SET ' query += ', '.join([f"""levels[{index + 1}] = trim(regexp_replace(%s, '\s+', ' ', 'g'))""" ...
7cc75024db3de8596bc685439d02a1023bfbae25
3,387
def _print_model(server, user_key, device_type_model): """ Print the model for a given device type :param device_type_model: Device type ID to print the model for """ name = None model = [] parameters = _get_parameters(server, user_key) parameters = parameters['deviceParams'] try: ...
b901cb21d39ac0fce1d8a60c3926d8b274ce5189
3,388
def parse_xiaomi(self, data, source_mac, rssi): """Parser for Xiaomi sensors""" # check for adstruc length i = 9 # till Frame Counter msg_length = len(data) if msg_length < i: _LOGGER.debug("Invalid data length (initial check), adv: %s", data.hex()) return None # extract frame ...
2891ecaa538f7eb2c70b9c9cf0073fc39f1cc3d8
3,389
def parse_ipv6_addresses(text): """.""" addresses = ioc_grammars.ipv6_address.searchString(text) return _listify(addresses)
6177bc5fcb3b6613e945a7c63931d88a12d372cd
3,390
def as_jenks_caspall_sampled(*args, **kwargs): """ Generate Jenks-Caspall Sampled classes from the provided queryset. If the queryset is empty, no class breaks are returned. For more information on the Jenks Caspall Sampled classifier, please visit: U{http://pysal.geodacenter.org/1.2/library/esda/m...
7a271d3c48b6d813cacc9502f214d2045d8accfe
3,391
def positive_dice_parse(dice: str) -> str: """ :param dice: Formatted string, where each line is blank or matches t: [(t, )*t] t = (0|T|2A|SA|2S|S|A) (note: T stands for Triumph here) :return: Formatted string matching above, except tokens are ...
5b266a4025706bfc8f4deabe67735a32f4b0785d
3,392
def fmt_title(text): """Article title formatter. Except functional words, first letter uppercase. Example: "Google Killing Annoying Browsing Feature" **中文文档** 文章标题的格式, 除了虚词, 每个英文单词的第一个字母大写。 """ text = text.strip() if len(text) == 0: # if empty string, return it return text ...
44474f8f92888904a56f63bdcf1031f2d7c472e1
3,393
def insn_add_off_drefs(*args): """ insn_add_off_drefs(insn, x, type, outf) -> ea_t """ return _ida_ua.insn_add_off_drefs(*args)
684af1cea2deafffc33b007f064a67fb89ffd54f
3,394
def lambda_handler(event, context): """Lambda function that responds to changes in labeling job status, updating the corresponding dynamo db tables and publishing to sns after a job is cancelled. Parameters ---------- event: dict, required API gateway request with an input SQS arn, output SQS arn ...
3640bded7316a573d0740084e8006a876bb7300c
3,395
from typing import Union def get_answer(question: Union[dns.message.Message, bytes], server: Union[IPv4Address, IPv6Address], port: int = 53, tcp: bool = False, timeout: int = pydnstest.mock_client.SOCKET_OPERATION_TIMEOUT) -> dns.message.Message: """Get...
95493396393ce09e4610fb32c063d0d9676b14ea
3,396
def intersectionPoint(line1, line2): """ Determining intersection point b/w two lines of the form r = xcos(R) + ysin(R) """ y = (line2[0][0]*np.cos(line1[0][1]) - line1[0][0]*np.cos(line2[0][1]))/(np.sin(line2[0][1])*np.cos(line1[0][1]) - np.sin(line1[0][1])*np.cos(line2[0][1])) x = (line1[0][0] - ...
f23ec1960de85b72724388747ec8157925eefae1
3,397
def _remove_keywords(d): """ copy the dict, filter_keywords Parameters ---------- d : dict """ return { k:v for k, v in iteritems(d) if k not in RESERVED }
0eb7ed59898c3ec323574d0068af745250aef63b
3,398
def build_trib_exp(trib_identifier, trib_key_field): """Establishes a SQL query expresion associating a given tributary id""" return '"{0}"'.format(trib_key_field) + " LIKE '%{0}%'".format(trib_identifier)
792d5e4237268410f050323ff1748246a5cdee5d
3,399