content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cancel_job(request): # pylint: disable=unused-argument """Handler for `cancel_job/` request.""" if not job_ids: print('No jobs are running, nothing to cancel!') else: job_id = job_ids.popleft() print('CANCELING JOB:', job_id) long_job.cancel(job_id) return django.htt...
365b305b88329cf394f3b7d36c6cd3e02121b5a1
29,832
def LO_solver_multiprocessing(H,N,dis, args,pipe): """ Allows to solve the Hamiltonian using several CPUs. Parameters ---------- H: arr Discretized Lutchyn-Oreg Hamiltonian built with Lutchyn_builder. N: int or arr Number of sites. If it is an ar...
b4738ababdd47a9dc633760dbc3ee7f29744e1e3
29,833
def _clip_grad(clip_type, clip_value, grad): """ Clip gradients. Inputs: clip_type(int): The way to clip, 0 for 'value', 1 for 'norm'. clip_value(float): Specifies how much to clip. grad (tuple[Tensor]): Gradients. Outputs: tuple[Tensor], clipped gradients. """ ...
998003fa6ef24e917af55cdd831034cafceeed74
29,834
def lightness_correlate(A, A_w, c, z): """ Returns the *Lightness* correlate :math:`J`. Parameters ---------- A : numeric or array_like Achromatic response :math:`A` for the stimulus. A_w : numeric or array_like Achromatic response :math:`A_w` for the whitepoint. c : numeric...
2692225728d9621ac427cedafcb18c9fe014d4ac
29,835
def fetch_file_from_guest(module, content, vm, username, password, src, dest): """ Use VMWare's filemanager api to fetch a file over http """ result = {'failed': False} tools_status = vm.guest.toolsStatus if tools_status == 'toolsNotInstalled' or tools_status == 'toolsNotRunning': result['fail...
6906573831b9889f82a7015c3a6ba9e82ca1cdea
29,837
def ReadFile(filename): """ description: Read program from file param {*} filename return {*} file """ input_file = open(filename, "r") result = [] while True: line = input_file.readline() if not line: break result.append(line) for line_index in ra...
fd7d7faab401f335579719f6e015bf7b9d82c2e2
29,839
def item_url(item): """Return a Markdown URL for the WCAG item.""" fragment = item["id"].split(":")[1] return url(item["handle"], f"https://www.w3.org/TR/WCAG21/#{fragment}")
d670da65ef794116ae5ccd650f3618e7c6a5dc45
29,840
def gen_nested_prop_getter(val_name, throws, klass): """ generates a nested property getter, it actually returns an _Internal object """ def _internal(self): try: getattr(self, val_name) except AttributeError: setattr(self, val_name, klass()) ...
54f766ae1dfcbc0e491355a4c741ccbadff6d26f
29,841
import numpy import scipy def quad_genz_keister(order, dist, rule=24): """ Genz-Keister quadrature rule. Examples: >>> abscissas, weights = quad_genz_keister( ... order=1, dist=chaospy.Iid(chaospy.Uniform(0, 1), 2)) >>> abscissas.round(2) array([[0.04, 0.04, 0.04, ...
f4d4590f2910ea82e5e824a47be196f82bdd5da3
29,842
def get_maf(variant): """ Gets the MAF (minor allele frequency) tag from the info field for the variant. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ return variant.INFO.get("MAF")
1d25f577a3cec14b8d05095d320fad6584484718
29,843
import glob def check_channels(file_path_address: str, image_type: str): """Manual verifier to determine which images to further clean or remove. This checks to see if there is a consistent third dimension in each of the images. Paramters: --------- file_path_address: str Address of where...
6d7307dbc103fd74a21e6fbb5193c4aaebc1fd35
29,844
import heapq def break_large_contigs(contigs, break_t, verbose=False): """Break large contigs in half until all contigs are under the size threshold.""" # initialize a heapq of contigs and lengths contig_heapq = [] for ctg in contigs: ctg_len = ctg.end - ctg.start heapq.heappush(contig_heapq, (-...
82b039abd675303def8360acf9814426af50e503
29,845
def create_content(address, owner, content): """ Create a new page with some content. Args: address (str): the new page's absolute address. owner (Account): the owner of the page to be created. content (str): the Markdown content of the first revision. Returns: page (Pa...
229df67cc230d39d7b6d0a129ee91d9a2f0246dd
29,846
def update_op_dims_mapping_by_default_dist_impl(op_dist_attr): """Each operator has a default distributed operator, only allowed to be sharded in batch dimension.""" changed = False op_desc = op_dist_attr.get_owner_op().desc # The following statement will be replaced by a more elegent way if op_desc...
75f226ff4902cd935abadd60b16874929d35883c
29,847
import random import torch def perturb_box(box, min_iou=0.5, sigma_factor=0.1): """ Perturb the input box by adding gaussian noise to the co-ordinates args: box - input box min_iou - minimum IoU overlap between input box and the perturbed box sigma_factor - amount of perturbation, re...
1b1e7cb831d52be0b96b69d68817c678865447d2
29,848
import statistics def coverageCalc(coverageList,minCov): """Function parsing coverageList for :param coverageList: List of pacbam coverage information :param minCov: Int of minimum passing coverage :return: covCount: Int of bases with coverage minCovC...
e20dc1e1f0b6f7e328501afe9921455a705f196a
29,849
def truncate_top_k_2(x, k): """Keep top_k highest values elements for each row of a numpy array Args: x (np.Array): numpy array k (int): number of elements to keep for each row Returns: np.Array: processed array """ s = x.shape # ind = np.argsort(x)[:, : s[1] - k] i...
1e84987b01d4cbab9c97174886c87d88e541f380
29,850
def permute_dimensions(x, pattern): """Permutes axes in a tensor. # Arguments pattern: should be a tuple of dimension indices, e.g. (0, 2, 1). # Returns A tensor. """ return KerasSymbol(mx.sym.transpose(x.symbol, axes=pattern))
3665221ec55a01dcf2eaa3f51d716d08f09eed60
29,852
import copy def relaxStructure(s, operation): """ Performs a gulp relaxation (either relaxation of unit cell parameters only, or both unit cell and atomic positions. s: structure_class operation: string Specifies the gulp calculation to execute. Returns ------- s : structure_...
ccc8a2fe75d11693030fea6771bb127e3fc9ebcd
29,853
import time def dos_gaussian_shift(energies, dos_total, projections, nGridpoints, smearing): """ Produces a single gaussian function then shifts the gaussian around the grid Advantages: + Very fast compared to other methods Disadvantages: - Produces an edge effect, energy range should be larger than required -...
ff1ea14a96c217083eba01a5cde7deb668e1267d
29,854
def temp_h5_file(tmpdir_factory): """ a fixture that fetches a temporary output dir/file for a test file that we want to read or write (so it doesn't clutter up the test directory when the automated tests are run)""" return str(tmpdir_factory.mktemp('data').join('test.h5'))
23ca5e58aa7afadcd18394bfa7ea6aa3a48c412e
29,855
def get_day_name(date): """ returns the day name for a give date @param date datatime @return month name .. faqref:: :tag: python :title: Récupérer le nom du jour à partir d'une date .. runpython:: :showcode: import date...
1e6b67d5b853156d5e6a8624c9644a08ebb4ee20
29,856
def get_samples(n_samples, data, labels=None, use_random_transpose=False): """Return some random samples of the training data.""" indices = np.random.choice(len(data), n_samples, False) if np.issubdtype(data.dtype, np.bool_): sample_data = data[indices] * 2. - 1. else: sample_data = data...
7a9fc5256b438619af8e366802fc54db196536d7
29,857
from typing import Union import torch import collections from typing import Callable def apply_to_tensor( x: Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes], func: Callable ) -> Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes]: """Apply a function on a ...
53f966bfbd6b68efa2bfeb72b8c34e38be008196
29,858
def status(): """ Returns a page showing the number of unprocessed certficate-requests. """ result = db.session.query(Request).filter(Request.generation_date == None).count() return render_template('status.html', requests=result)
9e04e870a4d3d707da078e5681c145726ba563c2
29,859
def weak_connect(sender, signal, connector, attr, idle=False, after=False): """ Function to connect some GObject with weak callback """ wc = WeakCallback(connector, attr, idle) if after: wc.gobject_token = sender.connect_after(signal, wc) else: wc.gobject_token = sender.conn...
e18ba634c039cfb2d03649c76d1aad02f216c653
29,860
def load_user(id): """ Provides login_manager with a method to load a user """ return User.get_by_id(int(id))
3aca05c0bf6ad62401c442ba813a8a8a646dabe4
29,861
def _compute_min_dfc(fnrs, fprs, thresholds, p_target, c_miss, c_fa): """ Computes the minimum of the detection cost function. The comments refer to equations in Section 3 of the NIST 2016 Speaker Recognition Evaluation Plan. :param fnrs: the list of false negative rates :param fprs: the list of fa...
23931070ad23f2dc8b1fdc63d0e4635f9fede535
29,862
def parse_rsync_url(location): """Parse a rsync-style URL.""" if ':' in location and '@' not in location: # SSH with no user@, zero or one leading slash. (host, path) = location.split(':', 1) user = None elif ':' in location: # SSH with user@host:foo. user_host, path ...
fc315c1a6b376cbb83b047246fee51ae936b68ef
29,863
import random def generate_address_street(): """Concatenate number, street, and street sufix.""" number = random.randint(1, 9999) street = last_names[random.randint(0, len(last_names) - 1)] suffix = address_street_suffix[random.randint(0, len(address_street_suffix) - 1)] return "{0} {1} {2}".forma...
a7dafb282d1d0abb25ad6cb44ba6f2e0a9e190dd
29,865
def try_all_eliza_transformations(doc): """ Try to do eliza transformation for all the functions and add the transformed string to the responses list """ responses = [] question = ask_do_you_like_to(doc) if question: responses.append(question) question = rephrase_question(doc) ...
3a76b9a1fc422e8db1e02f41dd286ce385d09213
29,866
def get_jwt_subject(): """Returns a the subject from a valid access tokekn""" token = get_token_auth_header() payload = verify_decode_jwt(token) if "sub" not in payload: abort(401) return payload["sub"]
a7f8bf3989dbdc1a0894d63d6fdc58e5c07356f4
29,867
import functools def api(function): """ Decorator of API functions that protects user code from unknown exceptions raised by gRPC or internal API errors. It will catch all exceptions and throw InternalError. :param function: function to be decorated :return: decorated function """ @f...
1e023eed5986224967c6057962576afc4c84adb2
29,868
def mock_signal_receiver(signal, wraps=None, **kwargs): """ Taken from mock_django as importing mock_django created issues with Django 1.9+ Temporarily attaches a receiver to the provided ``signal`` within the scope of the context manager. The mocked receiver is returned as the ``as`` target o...
d3f0a481609bf9491b159a7331e1fffc3a5bf92e
29,869
import urllib def is_valid_cover(cover_metadata): """Fetch all sizes of cover from url and evaluate if they are valid.""" syndetics_urls = build_syndetic_cover_urls(cover_metadata) if syndetics_urls is None: return False try: for size in ["small", "medium", "large"]: resp ...
b41aa1f558d1080fc1a3a2d03180417b38b92931
29,870
def setup_go_func(func, arg_types=None, res_type=None): """ Set up Go function, so it know what types it should take and return. :param func: Specify Go function from library. :param arg_types: List containing file types that function is taking. Default: None. :param res_type: File type that functio...
05f48f4dfecdf0133613f76f235b1e82f14bc5a9
29,871
import ctypes def xonly_pubkey_tweak_add( xonly_pubkey: Secp256k1XonlyPubkey, tweak32: bytes ) -> Secp256k1Pubkey: """ Tweak an x-only public key by adding the generator multiplied with tweak32 to it. Note that the resulting point can not in general be represented by an x-only pubkey because ...
727b84ec239bb19d83fa9fe4e72b08ea17972e31
29,873
from typing import Optional def get_organisms_df(url: Optional[str] = None) -> pd.DataFrame: """Convert tab separated txt files to pandas Dataframe. :param url: url from KEGG tab separated file :return: dataframe of the file :rtype: pandas.DataFrame """ df = pd.read_csv( url or ensure...
4b28571848076a785ae773410c70102e5a83d096
29,874
import random def split(dataset: Dataset, count: int, shuffle=False): """Datasetを指定個数に分割する。""" dataset_size = len(dataset) sub_size = dataset_size // count assert sub_size > 0 indices = np.arange(dataset_size) if shuffle: random.shuffle(indices) return [ dataset.slice(indic...
d4f50f617fb65499190c7c5e014178d548a7dccb
29,876
import pathlib def load_fixture(filename): """Load a fixture.""" return ( pathlib.Path(__file__) .parent.joinpath("fixtures", filename) .read_text(encoding="utf8") )
f1382161ad6226cd585a2ecbbe08dc486b3a5f2d
29,877
import re def natural_sort(l): """ From http://stackoverflow.com/a/4836734 """ def convert(text): return int(text) if text.isdigit() else text.lower() def alphanum_key(key): return [convert(c) for c in re.split('([0-9]+)', key)] return sorted(l, key=alphanum_key)
c1cd34aa4c9ea2323cb311d9af6f141aa85abef2
29,878
import inspect def is_verifier(cls): """Determine if a class is a Verifier that can be instantiated""" return inspect.isclass(cls) and issubclass(cls, Verifier) and \ not inspect.isabstract(cls)
83cd18155f23631f2e1dac1ec1eac07a5017809d
29,879
def get_bleu_score(references, hypothesis): """ Args: references: list(list(list(str))) # examples: list(examples) hypothesis: list(list(list(str))) # hypotheses: list(list(str)) """ hypothesis = [hyp[0][0] for hyp in hypothesis] return 100.0 * bleu_score.corpus_ble...
a2a17186555564a02acedf5540aedce0b1a14cd1
29,882
def load_json_link_index(out_dir, link): """check for an existing link archive in the given directory, and load+merge it into the given link dict """ link = { **parse_json_link_index(out_dir), **link, } link.update({ 'history': link.get('history') or {}, }) c...
58c034daa7305e06407af9cf226ff939544ee961
29,884
def relative_phase(input_phase: float, output_phase: float) -> float: """ Calculates the relative phase between two phases. :param input_phase: the input phase. :param output_phase: the output phase. :return: the relative phase. """ phi = output_phase - input_phase if phi < -np.pi: ...
d912754fe060582e5ffe9dc3aad0286b80ee945a
29,885
def jaccard_similarity(x, y): """ Returns the Jaccard Similarity Coefficient (Jarccard Index) between two lists. From http://en.wikipedia.org/wiki/Jaccard_index: The Jaccard coefficient measures similarity between finite sample sets, as is defined as the size of the intersection divided by th...
81cf0c882ff4b06e79b102abb2d8f13755b68873
29,887
def align_address_to_size(address, align): """Align the address to the given size.""" return address + ((align - (address % align)) % align)
9496c969e257fb3c00ecddf8e941ddb0bd41155e
29,888
import shlex def tokenizer_word(text_string, keep_phrases=False): """ Tokenizer that tokenizes a string of text on spaces and new lines (regardless of however many of each.) :param text_string: Python string object to be tokenized. :param keep_phrases: Booalean will not split "quoted" text :retur...
940f716072e9b2ce522c9854b2394327fbd1e934
29,889
def getiso(): """Get iso level of sensor..""" global camera maxtint = 4 iso = float(camera.analog_gain) # get current ambient brightness 0..8 iso = (iso * maxtint) # adjust buy max tint level iso = (256 - (maxtint * 8)) + iso # clear - max tint + ISO tint return int(iso)
45fa48897cd297232fde00cbe49d7717608466ed
29,890
from typing import Union from typing import Sequence from typing import List from typing import Dict def get_manual_comparisons(db: cosem_db.MongoCosemDB, cropno: Union[None, str, int, Sequence[Union[str, int]]] = None, mode: str = "across_setups") -> \ Li...
fc4a62d09f9df289b08a249d70875ce6ca19ed39
29,892
def draw_circle(center_x:float, center_y:float, radius:float = 0.3, segments:int = 360, fill:bool=False): """ Returns an Object2D class that draws a circle Arguments: center_x : float : The x cord for the center of the circle. center_y : float : The y cord for the center of the circle. radius : flo...
78caa0cbb25df7c947053a10d54f7ae3fd2fc8b2
29,893
def weighted_mean(values, weights): """Calculate the weighted mean. :param values: Array of values :type values: numpy.ndarray :param weights: Array of weights :type weights: numpy.ndarray :rtype: float """ weighted_mean = (values * weights).sum() / weights.sum() return weighted_me...
886d7cff1555c40b448cda03e08620a0e2d69ede
29,894
def shared_cluster(): """Create a shared cluster""" global _shared_cluster if _shared_cluster is None: cluster = PseudoHdfs4() atexit.register(cluster.stop) try: cluster.start() except Exception, ex: LOG.exception("Failed to fully bring up test cluster: %s" % (ex,)) # Fix config t...
fd51186f8d46ae236b3f4220750ab0f412354669
29,895
import reprlib def _format_args(args): """Format function arguments. Special case for a single parameter: ('hello',) is formatted as ('hello'). """ # use reprlib to limit the length of the output args_repr = reprlib.repr(args) if len(args) == 1 and args_repr.endswith(',)'): args_repr ...
a54f06358b629340c1f16ecc86eff15b8fca3bd3
29,896
import requests import logging import json def request(config, url_params={}): """Wrapper for sending GET to Facebook. Args: config: YAML object of config file. url_params: Dictionary of parameters to add to GET. Returns: HTTP response or error. """ host = HOST + f"/{config['user_id']}/" ...
e4ef9315170ab7d1c7e39645bde46b6cbb9f9de9
29,897
import miniupnpc def setup(hass, config): """Register a port mapping for Home Assistant via UPnP.""" upnp = miniupnpc.UPnP() hass.data[DATA_UPNP] = upnp upnp.discoverdelay = 200 upnp.discover() try: upnp.selectigd() except Exception: _LOGGER.exception("Error when attempti...
ca5d7d90efb849412e2256dab3516deca1531539
29,898
def load_formatted_objects_json(fp): """A function to load formatted object data data. The function assumes the input json is of the form: [ { id: <number>, regions : [ { x: <number>, ...
2647f2c2cfc7530998361b19693ea6e187bf64f1
29,899
from datetime import datetime def _event_last_observed(event: EventsV1Event) -> datetime.datetime: """ Returns the last time an event was observed """ if event.series: series_data: EventsV1EventSeries = event.series return series_data.last_observed_time if event.event_time: ...
c8a26c067df0375923b3aa57afaa48f5c5fc0cf8
29,900
import numpy def bytes(length): """Returns random bytes. .. seealso:: :func:`numpy.random.bytes` """ return numpy.bytes(length)
44055f168dbd9e6b2e2481f8d57b9edef0110430
29,901
def init_json(): """ This function init the JSON dict. Return : Dictionnary """ data_json = {} data_json['login'] = "" data_json['hash'] = "" data_json['duration'] = 0 data_json['nbFiles'] = 0 data_json['nbVirus'] = 0 data_json['nbErrors'] = 0 data_json['uuidUsb'] = "" ...
9411f3a525df9e68f53fba94da679bd8d5b34013
29,902
def django_popup_view_field_javascript(): """ Return HTML for django_popup_view_field JavaScript. Adjust url in settings. **Tag name**:: django_popup_view_field_javascript **Usage**:: {% django_popup_view_field_javascript %} """ temp = loader.get_template('django_popup_view...
f2cf0631139ade2044aa577f906b4b8568b33713
29,903
def apply_filters(row): """Applies filters to the input data and returns transformed row.""" return {k: COLUMN_FILTERS.get(k, lambda x: x)(v) for k,v in row.items()}
2f31dda70bedc35f8b1b66e5906c38c5d3202e2b
29,905
def save_convergence_statistics( inputs, results, dmf=None, display=True, json_path=None, report_path=None ): """ """ s = Stats(inputs, results) if display: s.report() if report_path: with open(report_path, "w") as f: s.report(f) if json_path is not None: with...
e06891c917abc3678e8fbcf0ff81cae46ac2e04a
29,906
def max_size(resize_info): """ リサイズ情報から結合先として必要な画像サイズを計算して返す :param resize_info: リサイズ情報 :return: width, height """ max_w, max_h = 0, 0 for name, info in resize_info.items(): pos = info['pos'] size = info['size'] max_w = max(max_w, pos[0] + size[0]) max_h = max...
1e28f993b3b0fac077f234b6388a2d9042396f6b
29,908
def get_thru(path, specs=range(10), cameras='brz'): """Calculate the throughput in each camera for a single exposure. See https://github.com/desihub/desispec/blob/master/bin/desi_average_flux_calibration and DESI-6043. The result includes the instrument throughput as well as the fiber acceptance los...
ec123a4f8843fcd5eb4aef87bf77b936687c544d
29,909
def quicksort(lyst): """This is a quicksort """ def partition_helper(lyst, first, last): pivot = lyst[first] left = (first + 1) right = last done = False while not done: while left <= right and lyst[left] <= pivot: left += 1 whi...
33385c01b877a86a2970f33dc4d0bd9d456dc983
29,910
def status_parameter_error(): """Returns the value returned by the function calls to the library in case of parameter error. """ r = call_c_function(petlink32_c.status_parameter_error, [{'name': 'return_value', 'type': 'int', 'value': None}]) return r.return_value
fbbdcd85fde27f200c1c749e03234baa8d725f1d
29,911
def df_to_dict(df: DataFrame) -> list[dict]: """DataFrame 转 dict""" # 拿到表头,转换为字典结构 head_list = list(df.columns) list_dic = [] for i in df.values: a_line = dict(zip(head_list, i)) list_dic.append(a_line) return list_dic
c52e628a78e2bd863a4a9926e739bff53195910a
29,912
def parse_describeprocess(html_response): """Parse WPS DescribeProcess response. Parameters ---------- html_response : string xml document from a DescribeProcess WPS request. Returns ------- out : list of dict 'identifier' : ProcessDescription -> ows:Identifier 'inp...
80f7e866424ffa8cbdae2a94d31f6044722648c6
29,913
def variational_implicit_step(system, dt, p, x, z, t): """ For Lagrangian functions of the form L(j) = 1/(2h^2) (x_{j+1} - x_j)^2 - 1/2 (V(x_j) + V(x_{j+1})) - 1/2 (F(z_j) + F(z_{j+1})) """ tnew = t + dt xnew = ( x + (dt - 0.5 * dt ** 2 * system.Fz(z, t)) * p - 0.5 * dt ** 2 * system.Vq...
c32e13ae37873983a3a88b91e7f0bfdf7ba9d043
29,914
def _validate_time_mode(mode, **kwargs): """Validate time mode.""" return mode
e30fd9071bde102b4986fe9ef846a812f7c08ff7
29,916
def flatten() -> GraphBuilder: """ dl.flatten layer builder """ def graph_builder(prev_layer: Metadata) -> Metadata: metadata = {} init_regularized_nodes(metadata, prev_layer) graph = prev_layer['graph'] metadata['units'] = (np.prod(prev_layer['units']),) metadata...
bf00faa00f5059c33887acafb0665ae37dc970e8
29,917
def _important() -> str: """Returns a query term matching messages that are important.""" return 'is:important'
dced06645f5311b321d42cd3892627df5b30faec
29,918
async def root(): """ Dependency is "static". Value of Depends doesn't get passed into function we still get redirected half the time though """ return {"message": "Hello World"}
6d3b634444240275f56d30aa0c1fe3b3bb84ce24
29,919
from typing import Hashable import encodings def line_width(et: pd.DataFrame, lw_by: Hashable): """Default edge line width function.""" if lw_by is not None: return encodings.data_linewidth(et[lw_by], et[lw_by]) return pd.Series([1] * len(et), name="lw")
064f90d4974f64d9be99090c77cf24d30a34a9f0
29,920
def run_state_machine(ctx, callback): """Run the libmongocrypt state machine until completion. :Parameters: - `ctx`: A :class:`MongoCryptContext`. - `callback`: A :class:`MongoCryptCallback`. :Returns: The completed libmongocrypt operation. """ while True: state = ctx.sta...
37da937db46bea8e7952e72753ab27543215f8fe
29,921
def remove_na_arraylike(arr): """ Return array-like containing only true/non-NaN values, possibly empty. """ if is_extension_array_dtype(arr): return arr[notna(arr)] else: return arr[notna(lib.values_from_object(arr))]
e89d3218d053852ddbc553223d035c71615f7c21
29,922
def conv_nested(image, kernel): """A naive implementation of convolution filter. This is a naive implementation of convolution using 4 nested for-loops. This function computes convolution of an image with a kernel and outputs the result that has the same shape as the input image. Args: ima...
acfa5f275bc15a39357390ac356f7ee681dbf31a
29,923
def getLatest(df): """ This get the data of the last day from the dataframe and append it to the details """ df_info = df.iloc[:,0:5] df_last = df.iloc[:,-1] df_info['latest'] = df_last return df_info
f42cae0552a4ac791d3499fa2ca1417a80a970ac
29,924
import time def setup_camera(is_fullscreen = True): """ Setup the PiCam to default PSVD settings, and return the camera as an object. Keyword Arguments: is_fullscreen -- Boolean value. True for fullscreen, false for window. """ # ensure that camera is correctly installed and...
301d046541c0463e8e3ab58fe429a3c47cbd960e
29,925
def CalculateGearyAutoMutability(ProteinSequence): """ #################################################################################### Calculte the GearyAuto Autocorrelation descriptors based on Mutability. Usage: result=CalculateGearyAutoMutability(protein) Input: protein is a pure protein sequenc...
a9a7f92d742736f7a66c8bdc06980f393922ea4a
29,926
def hamming_distance(a, b): """ Returns the hamming distance between sequence a and b. Sequences must be 1D and have the same length. """ return np.count_nonzero(a != b)
fe895c87867999159c57f23f96eab9d7b41edb8e
29,928
def generate_url(mbid, level): """Generates AcousticBrainz end point url for given MBID. """ return ACOUSTIC_BASE + mbid + level
96fe05dc3274730196dbc764c3e8f58f32b81a5f
29,930
from typing import Sequence from typing import List def averaged_knots_unconstrained(n: int, p: int, t: Sequence[float]) -> List[ float]: """ Returns an averaged knot vector from parametrization vector `t` for an unconstrained B-spline. Args: n: count of control points - 1 p: degree ...
6da79c699a3420270efc938a6f0de659d4886060
29,931
def converge_launch_stack(desired_state, stacks): """ Create steps that indicate how to transition from the state provided by the given parameters to the :obj:`DesiredStackGroupState` described by ``desired_state``. See note [Converging stacks] for more information. :param DesiredStackGroupSta...
3f615b38d3e303a63873f3dc8ed2d3699460f3b8
29,932
def strip_long_text(text, max_len, append=u'…'): """Returns text which len is less or equal max_len. If text is stripped, then `append` is added, but resulting text will have `max_len` length anyway. """ if len(text) < max_len - 1: return text return text[:max_len - len(append)] + append
02ce128f1de1dbeb2a2dcef5bc2b6eb8745322d3
29,934
import typing import numpy def function_rescale(data_and_metadata_in: _DataAndMetadataLike, data_range: typing.Optional[DataRangeType] = None, in_range: typing.Optional[DataRangeType] = None) -> DataAndMetadata.DataAndMetadata: """Rescale data and update intensity calibra...
e312ee866c142b6d2166c450831ce5308d263aaa
29,935
def svn_diff_parse_next_patch(*args): """ svn_diff_parse_next_patch(svn_patch_file_t patch_file, svn_boolean_t reverse, svn_boolean_t ignore_whitespace, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t """ return _diff.svn_diff_parse_next_patch(*args)
49c2797c2798a0870cbc68e6ffe917d353cf41bb
29,936
def Sub(inputs, **kwargs): """Calculate A - B. Parameters ---------- inputs : list of Tensor The inputs, represent A and B respectively. Returns ------- Tensor The output tensor. """ CheckInputs(inputs, 2) arguments = ParseArguments(locals()) output = Tens...
9da04c8898bb58db0db49eb46bb69b3591f6c99d
29,937
def psf_1d(x, *p): """[summary] Arguments: x {[type]} -- [description] Returns: [type] -- [description] """ A, x0, alpha, C = p r = (x - x0) * alpha y = np.zeros(r.shape) y[r!=0] = A * (2 * special.j1(r[r!=0]) / r[r!=0])**2 y[r==0] = A return y + ...
06b5d6a56db19ebc7d43b1d4a95805559e549273
29,938
from datetime import datetime import time def arrow_format(jinja_ctx, context, *args, **kw): """Format datetime using Arrow formatter string. Context must be a time/datetime object. :term:`Arrow` is a Python helper library for parsing and formatting datetimes. Example: .. code-block:: html+jin...
739a1b97499a614dfabe9321ccd18126d1ebcad9
29,941
def jsonify_query_result(conn, query): """deprecated""" res = query.all() #res = conn.execute(query) #return [dict(r) for r in res] return [r._asdict() for r in res]
ca11226c6f6fc731089f1d257db02a6cb83bd145
29,942
def _postfix_queue(token_expr): """ Form postfix queue from tokenized expression using shunting-yard algorithm. If expression have function, then presence of arguments for that function added before function token. If function have few arguments then RPN algorithm will pop them from stack until...
777c87bf1c4ac123f65e4061c1e5e72f5abe90d9
29,943
def get_from_list_to_examples(task_proc): """ Return a function that converts 2d list (from csv) into example list This can be different between DataProcessors """ if isinstance(task_proc, DefaultProcessor): return lambda l: task_proc._create_examples(l, "test") else: raise NotIm...
e42d050074b9f83127cca95261d5b1300a5b453a
29,944
from pathlib import Path import yaml def read_rules(rule_file=None): """Read rule from rule yaml file. Args: rule_file (str, optional): The path of rule yaml file. Defaults to None. Returns: dict: dict object read from yaml file """ default_rule_file = Path(__file__).parent / 'ru...
24def1cb09f1ecc464d38b866397d9821ac24293
29,945
from pymatgen.core.structure import Structure def localized_rattle( structure: Structure, defect_coords: np.array, stdev: float = 0.25, ): """ Given a pymnatgen structure, it applies a random distortion to the coordinates of the atoms in a radius 5 A from defect atom. Ran...
35be05f136c5f1050394a0ac335ad281c0e855c3
29,946
def calculate_jaccard(set_1, set_2) -> float: """Calculate the jaccard similarity between two sets. :param set set_1: set 1 :param set set_2: set 2 """ intersection = len(set_1.intersection(set_2)) smaller_set = min(len(set_1), len(set_2)) return intersection / smaller_set
eddb25b2fdc0dd5b5d2505fc52cb1353ce74f89d
29,947
def bad_request(e) -> 'template': """Displays a custom 400 error handler page.""" return render_template('error_handler.html', code = 400, message = "Bad request", url = url_for('main.profile_page'), back_to = 'Profile Page'), 400
e9f302cea41e6a3b51044be28850b948153170e7
29,948
def quarter_of_year(datetimes): """Return the quarter of the year of given dates.""" return ((_month_of_year(datetimes) - 1) // 3 + 1).astype(int)
49f3d8d63f9cc5c73b2c0c6cf9859c8be53e567e
29,949
def runner_entrypoint(args): """ Run bonobo using the python command entrypoint directly (bonobo.commands.entrypoint). """ return entrypoint(args)
f1eda845fa442d831f12b501a45dff3c91297f2a
29,950