content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def askcolor(color=None, **options): """Display dialog window for selection of a color. Convenience wrapper for the Chooser class. Displays the color chooser dialog with color as the initial value. """ if color: options = options.copy() options["initialcolor"] = color return ...
4da5e0fe65bca12758f176587abeabc70663c804
50,300
def query_suggestions(query_fields_and_values): """Queries for suggestions. Args: query_fields_and_values: list(tuple(str, str)). A list of queries. The first element in each tuple is the field to be queried, and the second element is its value. Returns: list(Sugges...
a622cef1ab33aff74209d1ffba4a71ec1c1a5319
50,301
def get_urls(listen_port=None): """ :param listen_port: if set, will not try to determine the listen port from other running instances. """ try: if listen_port: port = listen_port else: __, __, port = get_status() urls = [] ...
c08f74844459ab255eb77b80fc496dd01aca3d69
50,302
def oo_image_tag_to_rpm_version(version, include_dash=False): """ Convert an image tag string to an RPM version if necessary Empty strings and strings that are already in rpm version format are ignored. Also remove non semantic version components. Ex. v3.2.0.10 -> -3.2.0.10 v1.2...
cde9e7c54d3d6bc36dc85ad4adb64eae36ef1d11
50,303
def input_fn(mode, input_context=None): """A simple dataset builder function. This function creates a simple dataset for traning the auto encoder model below. Note that param `article_to_take` only available for `TRAIN` mode. """ max_charcode = 0x024F def to_sequence(article): # ...
d4a7c8c846c3d6474cf0d5f2344fe2ea1532c4ef
50,304
from operator import iadd def csum(arrays, dtype=None, ignore_nan=False): """ CUDA-enabled sum of stream of arrays. Arrays are summed along the streaming axis for performance reasons. Parameters ---------- arrays : iterable Arrays to be summed. ignore_nan : bool, optional ...
7ebb8f705b326885a0dacfbf2e5fb32f81525a88
50,305
def _split_and_load(batch, ctx_list): """Split data to 1 batch each device.""" new_batch = [] for _, data in enumerate(batch): if isinstance(data, (list, tuple)): new_data = [x.as_in_context(ctx) for x, ctx in zip(data, ctx_list)] else: new_data = [data.as_in_context(...
344fcafd5e0d83e4ce8a7131dc65a49eb18b9d86
50,306
def h3_show(ax, h3_data, cmap=None, norm=None, aspect=None, vmin=None, vmax=None, url=None, alpha=1.0, fill=0.0, **kwargs): """Plot H3 DGG data in a way friendly to projected maps. This is derived from Axes.imshow. Parameters ---------- ax : matplotlib Axes h3_data : dict mapping ...
00211045ff221573fe8a9852e9963cab9faa7a67
50,307
def _daofind_centroidfit(obj, kernel, axis): """ Find the source centroid along one axis by fitting a 1D Gaussian to the marginal x or y distribution of the unconvolved source data. Parameters ---------- obj : array_like The 2D array of the source cutout. kernel : `_FindObjKernel` ...
1125b906e28f910de35c502961a3c224d27f4405
50,308
def _GatherReturnElements(requested_return_elements, graph, results): """Returns the requested return elements from results. Args: requested_return_elements: list of strings of operation and tensor names graph: Graph results: wrapped TF_ImportGraphDefResults Returns: list of `Operation` and/or `...
42fd493538d28a9b63221a469aa7fbde046c6793
50,309
def get_series_val(series): """ Get value series """ # Create a clean timeseries list of (dt,val) tuples val = [float(vd['value']) for vd in series['values']] val = np.ma.masked_equal(val, -9999) val = np.ma.masked_equal(val, 0.0) return val
e6295979e506de61406378bc1a4660507ee38e0f
50,310
def get_embeds_portkey(list_of_dicts_of_metadata): """make and return portkey archive embeds for story metadata""" embeds_list = [] for data in list_of_dicts_of_metadata: data = data["story"] sid = data["id"] embed = Embed( title= data['title'], url= f"https:...
44db656c6dc16bc33eabcdb450283755d98f54e0
50,311
def shear_y_only_bboxes(image, bboxes, prob, level, replace): """Apply shear_y to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, shear_y, func_changes_bbox, level, r...
085bb3c0608f5a99b9661ded6e63718a798292c5
50,312
from typing import Tuple from typing import List def split_by_commas(maybe_s: str) -> Tuple[str, ...]: """Split a string by commas, but allow escaped commas. - If maybe_s is falsey, returns an empty tuple - Ignore backslashed commas """ if not maybe_s: return () parts: List[str] = [] ...
ca21e5103f864e65e5ae47b49c161e8527036810
50,313
def postscriptFullNameFallback(info): """ Fallback to *openTypeNamePreferredFamilyName openTypeNamePreferredSubfamilyName*. """ return "%s %s" % ( getAttrWithFallback(info, "openTypeNamePreferredFamilyName"), getAttrWithFallback(info, "openTypeNamePreferredSubfamilyName"), )
dcf166ee98374ca8391fc9758595592ff1df96ab
50,314
import hashlib def _normalize_and_hash(s): """Normalizes and hashes a string with SHA-256. Private customer data must be hashed during upload, as described at: https://support.google.com/google-ads/answer/7474263 Args: s: The string to perform this operation on. Returns: A norma...
a280ab613796443ee054db748329244856164080
50,315
import re def replace_flooded_chars(text): """replace 3 or more repetitions of any character patterns w/ 2 occurrences of the shortest pattern""" return re.sub(r'(.+?)\1\1+', r'\1\1', text)
1e7a4403cc55b155a4088185b701dd4f9ac95019
50,316
import json async def add_pack_member(request, pack_id): """Add a member to the roles of a pack""" log_request(request) required_fields = ["id"] validate_fields(required_fields, request.json) pack_id = escape_user_input(pack_id) conn = await create_connection() pack_resource = await packs...
a91cc5bc57111e930f4fdbe261c44859a8153d37
50,317
def dataset_currency_selection_currency_name_post(currencyName): # noqa: E501 """Selects a specific currency type The currency type should be either bitcoin, bitconnect, dash, ethereum, iota, litecoin, monero, nem, neo, numeraire, omisego, qtum, ripple, stratis, or waves # noqa: E501 :param currencyName:...
a48d8f75f4e00a053dc719aacac6109adeded0ea
50,318
def compress_G1(pt: G1Uncompressed) -> G1Compressed: """ A compressed point is a 384-bit integer with the bit order (c_flag, b_flag, a_flag, x), where the c_flag bit is always set to 1, the b_flag bit indicates infinity when set to 1, the a_flag bit helps determine the y-coordinate when decompressin...
6f718df6ed330c793996ca45bddf0f4efc67cedc
50,319
def pairwise_correlation(df): """docstring goes here""" metric = pd.DataFrame() for index_i, row_i in df.iterrows(): row_i_to_all_rows(df, index_i, row_i, metric) return metric
faac14cc26315f818d6fc7fd9a621e411325832a
50,320
import cgi import re def plaintext2html(text, container_tag=False): """ Convert plaintext into html. Content of the text is escaped to manage html entities, using cgi.escape(). - all \n,\r are replaced by <br /> - enclose content into <p> - 2 or more consecutive <br /> are consider...
5943942da1946073e3b79db87af3ac77ac943e03
50,321
def trend(data): """ Calcul de la pente. """ argmin = np.argmin(data) argmax = np.argmax(data) divider = (data[argmax] + data[argmin]) if divider == 0.0: return 0.0 if argmin < argmax: return (data[argmax] - data[argmin]) / (data[argmax] + data[argmin]) elif argmin...
354a1c5cec2ae9f9c767e5d90d4bb86ada6fce15
50,322
def getAtomType(atom, bonds): """ Determine the appropriate atom type for an :class:`Atom` object `atom` with local bond structure `bonds`, a ``dict`` containing atom-bond pairs. """ cython.declare(atomSymbol=str) cython.declare(molFeatureList=cython.list, atomTypeFeatureList=cython.list) ...
4db8d9bf8af148d89a9467a6ab2f3ad42ed6e3bc
50,323
def sim_poisson_pop(n_seconds, fs, n_neurons=1000, firing_rate=2): """Simulate a Poisson population. Parameters ---------- n_seconds : float Simulation time, in seconds. fs : float Sampling rate of simulated signal, in Hz. n_neurons : int, optional, default: 1000 Number ...
2bf8a52ce30a4b54cfa6abc87599066e14187984
50,324
def visualize_boxes_and_labels_on_image_array_V1(image, boxes, scores_step1, instance_masks=None, keypoints=None, ...
25a512e483510648fe28ab15a0b310d6c86bdfea
50,325
from typing import Any from typing import Coroutine def slash_default_member_permission(permission: "Permissions") -> Any: """ A decorator to permissions members need to have by default to use a command. Args: permission: The permissions to require for to this command """ def wrapper(fu...
0cb18723b83dcae7a0af299bb5fad4bcb0dded9b
50,326
from typing import Union from typing import Optional def create_or_update_move_stop_by_dist_time( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], dist_radius: Optional[float] = 30, time_radius: Optional[float] = 900, label_id: Optional[Text] = TRAJ_ID, new_label: Optional[Text] = SEG...
ad4d3af6ca6ec160f9f63dd0b11436bc42d4c472
50,327
def _build(tmplspec, *repls): """Create raw parsed tree from a template revset statement >>> _build(b'f(_) and _', (b'string', b'1'), (b'symbol', b'2')) ('and', ('func', ('symbol', 'f'), ('string', '1')), ('symbol', '2')) """ template = _cachedtree(tmplspec) return parser.buildtree(template, ('...
b3fd8edf518b12b3d0db26c0aae9affce72bc02b
50,328
def kalman_predict(m, P, A, Q): """Kalman filter prediction step""" m_p = A @ m P_p = A @ P @ A.T + Q return m_p, P_p
a43e644693d02e317f2ac67a36f0dc684e93f3d5
50,329
import os import array def _drive_status(device, handle_mix = 0): """ check the current disc in device return: no disc (0), audio cd (1), data cd (2), blank cd (3) """ CDROM_DRIVE_STATUS=0x5326 CDSL_CURRENT=( (int ) ( ~ 0 >> 1 ) ) CDROM_DISC_STATUS=0x5327 CDS_AUDIO=100 CDS_MIXED=10...
0f74a795850c91e57d8130ef30343e5a270c8354
50,330
def limit(df: pd.DataFrame, rows: int) -> pd.DataFrame: """Limit the number of rows in a data frame. Returns a data frame that contains at most the first n (n=rows) rows from the input data frame. Parameters ---------- df: pd.DataFrame Input data frame. rows: int Limit on number...
6ac5174684b419e2ed1b4ff1dc6ad07dbf7f75f7
50,331
def _fill_gaps(wires, out): """Fill 1-minute gaps.""" mask = np.array([[1, 0, 1]]) return np.logical_or( wires, ndimage.binary_hit_or_miss(wires, mask), out=out)
342be9cd556b14b982c5bd6e9e1153986f17abf5
50,332
def has_prefix(sub_s, dic): """ :param sub_s: (str) apart of word :return: (bool) if correct: True """ for word in dic: if word.startswith(sub_s): return True return False
ae87c8babc8c28a853ecef0c6814cc3b51af6a2e
50,333
def permission_denied(request): """Return the view for permission denied errors. Note that this is a bit buggy, we need to render the template and return te content. """ return TemplateResponse(request, '403.html').render()
61af39487eafb63ad2140785c17ee4a49b3f7dfa
50,334
def nansum(*args, **kwargs): """ This will check for numpy array first and call np.sum otherwise use builtin for isntance c={1,2,3} and sum(c) should work also """ args = _convert_cat_args(args) if isinstance(args[0], np.ndarray): return args[0].nansum(*args[1:], **kwargs) return...
68fa967b653da7615b688b570251ed463fd66ff3
50,335
def get_publictag(tagkey): """ Return tag and bookmarks in this public tag collection """ this_tag = PublicTag.get(PublicTag.tagkey == tagkey) bookmarks = Bookmark.select().where( Bookmark.userkey == this_tag.userkey, Bookmark.tags.contains(this_tag.tag), Bookmark.status == Bookmark....
3fd8b8d3cf7907f50c78cc1d9bf387cfbf6985bc
50,336
import os,imp def listmodules(package_name=''): """List modules in a package or directory""" package_name_os = package_name.replace('.','/') file, pathname, description = imp.find_module(package_name_os) if file: # Not a package return [] ret = [] for module in os.listdir(pathn...
d869d19ad3d36593d9cb6095b52de4fbf906fda0
50,337
def _get_window(point, image, radius, padding_value): """Extract a square 2d window around a given pixel in the image. If the point has coordinates (-1, -1), the window will be filled with `padding_value`. Args: point: The coordinates of the center point in the extracted window. image: The image to ex...
9d08b13f4e4923875f14288ef2ba2a5ae648a713
50,338
from typing import OrderedDict import collections def make_docs(*args, **kwargs): """Make the documents for a `Request` or `OpReply`. Takes a variety of argument styles, returns a list of dicts. Used by `make_prototype_request` and `make_reply`, which are in turn used by `MockupDB.receives`, `Reques...
0857fce27c9f0b954b81f75e95974e8cb99b797e
50,339
import os def read_description_file(dirpath): """Read the contents of a file in 'dirpath' called DESCRIPTION, if one exists. This returns the file text as a string, or None if no description was found.""" descr_path = os.path.join(dirpath, 'DESCRIPTION') if os.access(descr_path, os.R_OK): ...
e043d40466b6a1077c0873d3b24f343406d8b5fd
50,340
from operator import concat def Divider(clk, rst, io): """ A 32-bit divider. WARNING: the op_divs/op_divu signal must be asserted only one cycle. Keeping it asserted for more than one cycle will restart the operation. The operation can be aborted by asserting the reset sig...
8a135c193d87068b2858d5be7a1a08ce5e3d96d7
50,341
def is_probably_gzip(response): """ Determine if a urllib response is likely gzip'd. :param response: the urllib response """ return (response.url.endswith('.gz') or response.getheader('Content-Encoding') == 'gzip' or response.getheader('Content-Type') == 'application/x-gzip...
30ca3774f16debbac4b782ba5b1c4be8638fe344
50,342
def quat_to_SO3(quat): """ :param quat: (N, 4, ) or (4, ) np :return: (N, 3, 3) or (3, 3) np """ x = RotLib.from_quat(quat) R = x.as_matrix() return R
c5a315d87b65a56b68f89cb18ea52c90a967b682
50,343
from typing import List def word_tokenizer(text: str) -> List[Word]: """Return words from sentence. Removing stopwords and punctuation. do lowarcase e.g: "Hello World!" >> "hello", "world" """ return WORD_TOKENIZER(text)
d9f8094c73649871bafa7a01e596885049d2ed11
50,344
def l1_loss(inputs, target, reduction='none'): """ Computes l1 loss. Args: inputs(akg.tvm.Tensor): Supported data type is float16, float32. target(akg.tvm.Tensor): With same type as inputs. reduction(str): Default is 'none', could be 'sum' or 'mean', if 'mean', loss result will be d...
a72d4bec59cd0fdb860c526318ca330c5080a417
50,345
from typing import Optional import time import logging import os def run_main(argsin: Optional[Namespace] = None) -> int: """Run main process for average_nucleotide_identity.py script. :param argsin: Namespace, command-line arguments :param logger: logging object """ time0 = time.time() # ...
9a5707cfe7fa03455b1c9f97015578b5d62f1a8b
50,346
def correlated_uniforms(N,rho=0): """ This function generates N uniform random variables (0,1) that may or may not be correlated, default is independent; when rho=0""" # check the correlation has acceptable value if rho>1 or rho<-1: print("Error, correlation coefficient must be between -1 an...
39144a63ef309a704f2f27b3cd58ad851be453cf
50,347
def _create_observable_table(yaml_dict: dict): """ Creates an observable table from the observable block in the given yaml_dict. Arguments: yaml_dict Returns: observable_table: pandas data frame containing the observable table. (if observable block is not empty, else None)...
d359a8a192791c766a4312e3c2bc987288afc120
50,348
import random import math def buffon(needlesNbr, groovesLen, needlesLen): """Simulates Buffon's needle experiments.""" intersects = 0 for i in range(needlesNbr): y = random.random() * needlesLen / 2 angle = random.random() * math.pi z = groovesLen / 2 * math.sin(angle) if y <= z: intersects += 1 exp...
34bbb29346690b5d0ef519282699f0b3b82d93cb
50,349
import time import numpy def ucerf_classical(rupset_idx, ucerf_source, src_filter, gsims, monitor): """ :param rupset_idx: indices of the rupture sets :param ucerf_source: an object taking the place of a source for UCERF :param src_filter: a source filter returning the sites af...
067b43d05c45e200915e8323073b9c2e1e0dcce7
50,350
def SNRvsTPR(data, true_flags, flags): """ Calculates the signal-to-noise ratio versus true positive rate (recall). """ SNR = np.linspace(0.0, 4.0, 30) snr_tprs = [] data_ = np.copy(data) flags_ = np.copy(flags) true_flags_ = np.copy(true_flags) for snr_ in SNR: snr_map = np....
b2a0199bbcf69abc3eb83af2a69e44a0c3794f1c
50,351
def stringify(plaintext): """ Used to convert hex integers into a string when decrypting. :param plaintext: a hex integer number. :return: a ascii string. """ if len(plaintext) % 2 == 1: plaintext = '0' + plaintext lst = [] end = len(plaintext) // 2 for i in range(end): ...
ddab6a748b9194ce763fd82c38ee428a41a50c72
50,352
def get_new_snp(vcf_file): """ Gets the positions of the new snp in a vcf file :param vcf_file: py_vcf file :return: list of new snp """ new_snp = [] for loci in vcf_file: if "gff3_notarget" in loci.FILTER: new_snp.append(loci) return(new_snp)
1385a5552f9ad508f5373b2783d14938ab04b9c5
50,353
def map(data, settings): """ Returns a new DataFrame applying the expression to the specified column. :param data: A pandas's DataFrame; :param settings: A dictionary that contains: - function: A lambda function; - alias: New column name; :return: Returns pandas's DataFrame with th...
aa72e29e3858b3fb3c5c8cac083bc9465ece3e95
50,354
def my_function() -> dict: """Return a set of data into a dictionary""" hills_of_rome = { 'Aventine Hill': {'Latin': 'Aventinus', 'Height': 46.6, 'Italian': 'Aventino'}, 'Caelian Hill': {'Latin': r'Cælius', 'Height': 50...
2482a65efc45c9c7f30a12f20bef2ba069c37d0a
50,355
def forced_vibration_particular(vt, k, m, F0, Omega, zeta): """ Particualr solution to forced harmonic vibrations, , x=H0 sin(Omega t - Phi) """ omega0 = np.sqrt(k / m) H0, phi = forced_vibration_particular_cst(Omega/omega0, F0/k, zeta) x_particular = H0 * np.sin(Omega * vt + phi) ...
fdb0d69ba6fa3cb3de60c5b76ed8de4ce3af7c0f
50,356
def most_freq(neighbors): """ Returns the dominant color with the greater frequency Example: num_dominating = [paper, paper, paper, spock, spock, spock, spock, spock] Returns: spock """ return max(set(neighbors), key=neighbors.count)
09c041b27dbf55f6e862d73bde421a86ac265f42
50,357
from re import M def test5(): """ test graph mark for cnn1 with NaiveSGD optimizer """ num_classes = 1470 model = M.cnn1(num_classes=num_classes) inputs = FloatTensor([32, 3, 448, 448], name="data") weights = list(model.weights) mse_loss = nn.MSELoss() labels = FloatTensor([32, nu...
7d69f37c546f2f8f3df194cfa00ef904aed6f45e
50,358
import os def testing_guard(decorator_func): """ Decorator that only applies another decorator if the TESTING environment variable is not set. Args: decorator_func: The decorator function. Returns: Function that calls a function after applying the decorator if TESTING env...
3b8a6ba26fd537f1edd521391158c459c340b6d7
50,359
def create_scratch(request): """ Create a scratch """ ser = ScratchCreateSerializer(data=request.data) ser.is_valid(raise_exception=True) data = ser.validated_data platform = data.get("platform") compiler = data.get("compiler") if platform: if CompilerWrapper.platform_from...
233a4eee19e85e56c3da4fe1f924906b9f37d74d
50,360
import base64 def encrypt(password, key, challenge=None): """Encrypts password with a key and returns the base64 encoded string""" ciph = _get_ciph(key, challenge) return base64.b64encode(ciph.encrypt(password))
8591d9f94625a01334b5014d8c13e3c3f349e16c
50,361
def get_func_store() -> dict: """Returns a dictionary with Callable objects supported in our function store, indexed by their function names.""" return {o[0]: o[1] for o in getmembers(knowledge_horizons) if isfunction(o[1])}
89798e4cfdd1d6abb73defa8f894aafd27b4a691
50,362
from typing import Optional def _efficient_sample_matheron_rule( inducing_variable: InducingVariables, kernel: KernelWithFeatureDecomposition, q_mu: tf.Tensor, *, q_sqrt: Optional[TensorType] = None, whiten: bool = False, ) -> Sample: """ Implements the efficient sampling rule from :ci...
7bebad81435ccead2c3f26eac3fd430497741428
50,363
from typing import Tuple from typing import List def verify_contents_quiet(unicodestring:str, filename:str, book_code:str, lang_code:str) -> Tuple[List[str],str]: """ This is called by the USFM linter. """ global error_log error_log = [] # e...
315e6dbc84f5c33aebcb60d51b5ef54b6cea2d6a
50,364
def email2dict(msg: Message, include_all: bool = False) -> "MessageDict": """ Convert a `Message` object to a `dict`. All encoded text & bytes are decoded into their natural values. Need to examine a `Message` but find the builtin Python API too fiddly? Need to check that a `Message` has the conte...
18e0e1569c5b9d6b1e69024d5bcacf0a8f56926e
50,365
from datetime import datetime def greater_than_days_cutoff(timestamp, cutoff): """ Helper function to calculate if PR is past cutoff """ # Convert string to datetime object last_update = datetime.strptime(timestamp[0:22], '%Y-%m-%dT%H:%M:%S.%f') # Get the number of days since this PR has been la...
2dd1a9c01112d30a77ca2f5826db32d29f26d830
50,366
import subprocess import os def view(path, light=False, wait=True, page=0, fullscreen=False, zoom=0): """View document. path (str) light (bool) force to use DocuWorks Viewer Light. Note that DocuWorks Viewer is used if Light version is not avaiable. wait ...
b1b9ed3b9b422753003d77b791ed9a44f1e18aad
50,367
def expand_for_dithers(indict, verbose=True): """Expand a given dictionary to create one entry for each dither. Supports parallel observations. Moved here and modified from apt_inputs.py Parameters ---------- indict : dict dictionary of observations Returns ------- expand...
b5fb6b60b71de797f1413fc3eaa25361e2de1e3a
50,368
from datetime import datetime import json def download_trace(): """Provide the trace of the current exploration to be downloaded. Note: The file will be saved in the configured upload folder and WILL NOT be deleted afterwards. A trick is to use the /tmp directory for them to be automa...
27160550411f96e25805ebfee594a7d03ca04059
50,369
import requests def discover_oidc_provider_config(oidc_provider_config_endpoint, client_id, mccmnc): """ Make an HTTP request to the ZenKey discovery issuer endpoint to access the carrier’s OIDC configuration """ oidc_provider_config_url = '%s?client_id=%s&mccmnc=%s' % ( oidc_provider_...
b5fe999cbd8a2515d689b564d1de6df30c28bde3
50,370
def response_plain_text_ga(output, continuesession): """ create a simple json plain text response """ return { "payload": { 'google': { "expectUserResponse": continuesession, "richResponse": { "items": [ { ...
70ee09b3fc3e22ad626fb1a963a3f3f7c528008a
50,371
import token def NodeName(node): """Produce a string name for a given node. For a Leaf this is the token name, and for a Node this is the type. Arguments: node: a tree node Returns: Name as a string. """ # Nodes with values < 256 are tokens. Values >= 256 are grammar symbols. if node.type < 2...
305a494e57f731274ed1739bb6459a91b0d24191
50,372
from datetime import datetime def get_current_weather(): """ returns the lates entry from the weather table """ return Weather.query.with_entities(Weather.temp, Weather.weather_id).filter( Weather.created_at >= (datetime.now() - timedelta(days=2))).order_by( Weather.id.desc()).first()
918dcaf3d2ad9289dd4558de96ecdb9f46aa0b81
50,373
from typing import Union from typing import BinaryIO import hashlib import requests import os def get_hash(source: Union[str, bytes, BinaryIO], algorithm: str = 'md5', prefix: bool = False, fast: bool = False) -> str: """ Calculates the hash for an object. :param so...
a8c83693134a326709a0503904f03cb5c879b3ab
50,374
def _GetChangesForMask(config_sed_input): """Get changes to config and run scripts for MaskRCNN. Also update train_mlperf.py if nvprof is used. Args: config_sed_input: Input list of sed pairs for config_DGXA100.sh. Returns: config_sed_output: Output list of sed pairs for config_DGXA100.sh. """ co...
ac92385d605dc2a9b9b122e4fce0d7831ca72d87
50,375
def reportnulls(df): """ Takes a data frame and check de nulls and sum the resutls and organizes them from highest to lowest """ null_counts = df.isnull().sum().sort_values(ascending=False) # return count of null values return null_counts
a3dc20feeaaf0f3467de76812531f1d0b791dc01
50,376
import subprocess def generate_manifest_in_from_hg(): """Generate MANIFEST.in from 'hg manifest'""" print("generating MANIFEST.in from 'hg manifest'") cmd = r'''hg manifest | sed 's/\(.*\)/include \1/g' > MANIFEST.in''' return subprocess.call(cmd, shell=True)
5aaf5508d14f52646f7e5af33e83c54291046da7
50,377
from io import StringIO def decode(data): """ Decode a binary string into the original Python types. """ buffer = StringIO(data) try: value = decoder[buffer.read(1)](buffer) except KeyError as e: raise DecodeError("Type prefix not supported. (%s)" % e) return value
de9ecff37d228707aa48d418f658b7b976b6f215
50,378
def getConstrainedTargets(driver, constraint_type='parentConstraint'): """ Gets all the transforms the given driver is driving through the giving constraint type. Args: driver (PyNode): The transform that is driving the other transform(s) through a constraint. constraint_type (string): The...
4e94a4cf1e72012e2413f1889ec76ccd0a76800e
50,379
from typing import List from pathlib import Path def get_isbr2_nii_file_paths(dir_paths: List[Path], file_selector: str) -> List[Path]: """Returns all the .nii.gz file paths for a given file_selector type. Arguments: dir_paths: a list of sample dir paths, each directory holds a full scan file_...
fc04b9fa48e2d44c532344c36bdbdefe71f24f67
50,380
def divide_mnist_data(mnist): """ load mnist dataset input:None output:split these data into train valid and test data. """ mnist_X, mnist_y = shuffle(mnist.data, mnist.target, random_state=42) # normalize mnist_X = mnist_X/255.0 train_X, test_X, train_y, test_y = train_test_split(m...
5a212f5e3c1557b24071732978f97c938593cc79
50,381
def fillPixels(im, N=1): """ Fill in the dead pixels. If a dead pixel has a least 4 finite neighbour pixel, than replace the center pixel with a mean valuse of the neighbours """ X = im.shape[0]-1 Y = im.shape[1]-1 imcopy = np.copy(im) for n in range(N): # skip = int(np.floor((3+n...
6fc8dacc27a9c5f9be9ae399aba486370e38157d
50,382
def get_mac_table(netmiko_session, vdc=None): """Get mac-address-table""" mac_table = [] get_macs = 'show mac address-table' if vdc is not None: vdc_command = f"switchto vdc {vdc}" get_vdcs = send_command(netmiko_session, vdc_command) table = send_command(netmiko_session, get_macs...
aa695cf4741fa585ca60cb3bc979ebb0953f9dc5
50,383
def GetBoundaryVertexes( wire = None, tol = 1e-7, single = True, add = True, infa = True ): """ Description: Gets boundary vertexes from a wire and put them into a group. Arguments: # wire Description: The input wire. Type: Wire GUI selection: yes Selection by name: yes R...
c3c2b8c8acb76d8debb489ef70f2581303900937
50,384
def WgBin2DFunc(v1, v2, wgs, Nbin1, Nbin2): """ Calculate the weighted quantile by given bin numbers designed for 2D numpy array """ # Define the probabilities for the quantiles based on the number of bins pq1 = np.linspace(0,1.0,Nbin1+1) pq2 = np.linspace(0,1.0,Nbin2+1) # Calculat...
304b8287d57409a1eb10ce8df47a049598c4be85
50,385
def RunWithVMs(vms, extra_envs=None): """Run Horovod on the cluster. Args: vms: A list of worker VMs. extra_envs: A dictionary of environment variables. Returns: A list of sample.Sample objects. """ vm_util.RunThreaded(lambda vm: vm.RemoteCommand('rm -rf /tmp/models'), vms) master_vm = vms[0] ...
80a02f645620df81d9cd0411bffa3ca41655d7c8
50,386
def convert_length(length: float, from_unit: Unit, to_unit: Unit) -> float: """Changes length measurements between units Parameters ---------- length : float measurement to convert from_unit : Unit [description] to_unit : Unit [description] Returns ------- f...
0dbf914e4071f4e72b7c5b6ec89c3d9ffdf9f93c
50,387
def one_hot_encoder(batch_inds, num_categories): """Applies one-hot encoding from jax.nn.""" one_hots = jax.nn.one_hot(batch_inds, num_classes=num_categories) return one_hots
1e31331316163700512065e7e4abb3deea11db3d
50,388
def get_decks(f): """ Get card deck categories, colors and text contents from Excel file. Always loads the first sheet i.e. the active one """ wb = openpyxl.load_workbook(f.name) ws = wb.active # Pick up deck names from the first row decks = [] for j in range(1, ws.max_column+1): i = ws...
07b3e7fd01b46880b054c83eb42f4347d70ee777
50,389
import random def topic_sample( review_source: pd.DataFrame, sample_frame: dict, topic_number: int, sample_size: int = 5, ) -> list: """ Returns a sample of reviews for a given topic Args: review_source - Panda's dataframe: a dataframe with all of the relevant reviews samp...
13ad6b7ce2daa6239c0cb8ac5ad79731bedea005
50,390
from typing import Type def do_login(): """ @api {post} /cookbook/auth/login User Login @apiName authenticate @apiDescription Example of an authentication service using sqlite3 and the froggy framework. @apiGroup Authentication @apiParam {String} email=kermit@muppets.com Email of the use...
c6f0b72f20aa543407fc87d29600a9f62a5d7336
50,391
from typing import List from typing import Dict def directory_to_trainer_input(file_names: List[str], text_processor: TextProcessor) -> Dict[str, List]: """generate images from example caption_list""" captions_per_file: Dict[str, List] = {} for file_name in file_names: print('Load examples from:',...
f8c2035e54e6c9f6181925c0b162f88a311c942f
50,392
from datetime import datetime import os def add_livestream(request, key): """ Returns page to add a livestream VOD article """ data = { "title": "Tools", "file": File.objects.get(key=key), "today": str(datetime.now())[:10], "series_choices": Series.objects.all() } # Fi...
5f9fdbcc0ca3e4babd9def2de9b59510790f87ed
50,393
def get_num_gophers(blades, remainders, M): """Find no. of gophers given no. of blades and remainders.""" for i in range(1, M + 1): congruences = all([i % b == r for b, r in zip(blades, remainders)]) if congruences: return i return None
0467bd7a9ab56181b03c26f0048adf52b1cc8228
50,394
def adata_to_cluster_expression(adata, cluster_label, scale=True, add_density=True): """ Convert an AnnData to a new AnnData with cluster expressions. Clusters are based on `label` in `adata.obs`. The returned AnnData has an observation for each cluster, with the cluster-level expression equals to the average ...
076a153e8cf6671b5a5190eeb6fdcc5e060af6b2
50,395
import os def get_rosetta_features_root(): """ Get the path to Rosetta features directory through set ROSETTA3_DB env variable. :rtype: str """ return os.getenv('ROSETTA3')+"/../tests/features"
657bf62513e7b2f947605def8a198a6ca5c117ef
50,396
def rtaph_yap(ya, yb, yamc): """ For post-CSP data, 'wrap' the YA value for YA in [0,1]. From rtaph.c. :param ya: Y axis wiggle. :type ya: numpy.ndarray :param yb: Y axis coarse clock. :type yb: numpy.ndarray :param yamc: Raw Y detector position in FEE pixels. :type yamc: numpy.nda...
0655ab38e0dc9b45242371f4f55d3726bb7e6a75
50,397
def correct_drift(data: ForcData, config: Config) -> ForcData: """Correct the raw magnetization for drift. If the measurement space is Hc/Hb, dedicated drift points must have been measured. If the measurement is H/Hr, the last datapoint along each curve is used. In either case, the points used for drif...
9f20bc078b3c495fbabe668133d1e7ef1524d99c
50,398
def svn_prop_dup(*args): """svn_prop_dup( prop, apr_pool_t pool)""" return _core.svn_prop_dup(*args)
2cd5fabe2220c2501529e553246230e8a03ffc5f
50,399