content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def DetermineServiceFromUrl(url): """Takes a DFA service's URL and returns the service name. Args: url: string The DFA service's URL. Returns: string The name of the service this URL points to. """ return url.split('/')[-1]
213e1a4dbb5eb3ed643e0ace300b4ac5b6c6c745
65,056
def tshark_read(device, capture_file, packet_details=False, filter_str=None): """Read the packets via tshark :param device: lan or wan... :type device: Object :param capture_file: Filename in which the packets were captured :type capture_file: String :param packet_details: output of packet tree...
8585248223410f771d7a90d3c59d2a1fbb3a221b
65,057
def is_prime(number): """如果是素数返回True. >>> is_prime(2) True >>> is_prime(42) False >>> is_prime(41) True """ # 小数的检查. if number < 10: return number in {2, 3, 5, 7} # 偶数. if not (number & 1): return False # 计算最少的回合数. k = get_primality_testing_rou...
8d7a4d27b17ebb12420a00c5771d2239c6a037a1
65,058
def pad_pkcs7(buf): """Appends PKCS7 padding to an input buffer. Parameters: buf - buffer to add padding Returns: buffer with PKCS7_PADDING Raises: No special exception handling """ padder = cryptography.hazmat.primitives.padding.PKCS7( cryptography.hazmat.primiti...
fae4acded6ae37c20d4b1838d9657fe72e1725ff
65,059
def list_detectors(client, aws_region): """ Lists the detectors in a given Account/Region Used to detect if a detector exists already :param client: GuardDuty client :param aws_region: AWS Region :return: Dictionary of AWS_Region: DetectorId """ detector_dict = client.list_detectors() ...
75413860f6974471b3be5cb8155fce76482f7fbe
65,060
import re def str_simplified(input_str: str) -> str: """ Remove leading/trailing whitespaces, simplify multiple whitespaces, unify newline characters Parameters ---------- input_str : str Returns ------- str input_str stripped if it is a string """ if not isin...
b9005bf5c3d01c971e3e17176a527eb1a23a1bf4
65,061
def wrapper(path, wrapped, ns=None, ns_map=None, idx=None): """ The function is used to map a class field to an XML element that is contained by a subelement. :param str path: full path to the `wrapped` element. Element names are separated by slashes :param wrapped: a wrapped element :param str ns:...
59cb0d644ce01dc2858650bf4d47967ffbad2261
65,062
def Find_2D_uc(Peaks, toll_angle=5, toll=0.10): """ Finds the best fitting unit cell for an image Input : SeqIma : sequence of images Output : - out : array of unit vectors of length : number_of_images_in_sequence*2 """ unit_vectors = find_all_2vectors(Peaks, toll_angle) #vecti = s...
d68307fb4447e3f218bcdef4990deeeda6514986
65,063
def _listify(x): """Ensure a scalar/list is returned as a list. Taken from https://stackoverflow.com/a/1416677/1467820 Copied from the pre-v1 hera_sim.rfi module. """ try: basestring except NameError: basestring = (str, bytes) if isinstance(x, basestring): return [...
51b6594af9e54025d1b91d73ff01dd2c6db85d9b
65,064
def open_dta(address): """Open any recent version dta file (versions 114, 115, 117) . Parameters ---------- Address of file, including file name and ".dta". Returns ------- Instance of sub-class of Dta, depending on dta file. """ with open(address, 'rb') as dta_file: ...
e675ecc5aae8d518c2a7bcff95b70da8c0c51e3c
65,065
def moveaxis(a, source, destination): """ Move axes of a tensor to new positions. Other axes remain in their original order. Parameters ---------- a : Tensor The tensor whose axes should be reordered. source : int or sequence of int Original positions of the axes to move. T...
cae4202c11f09f5b78290ecb9ab82c17a5cad1ce
65,066
def get_links_by_cve(cve, vul_db): """Get external links if they have mitigation info for a cve. Example: >>> from cve_links import get_links_by_cve >>> res = get_links_by_cve('CVE-1999-0002') [('http://www.securityfocus.com/bid/121', True)] Args: cve (string): cve ID ...
c1032bbf02c7c75c6b366c001bc0884e9bee04a2
65,067
def spark(): """spark Session factory""" spark_ = SparkSession \ .builder \ .appName("Detect dictionary and vocabulary") \ .getOrCreate() return spark_
7db051a2e88ebbabe14c8fa4e1a402edf7e4ad78
65,068
def softmax_crossentropy_with_logits(logits,reference_answers): """Bu fonksiyon softmax aktivasyon fonksiyonu ile modelin tahminleri ile olması gereken değerler arasındaki cross entropy'yi hesaplıyor. logits, modelin tahminlerini, reference_answers ise gerçek olması gereken değerleri ifade ediyor""" logits_for_...
da229dd55605a8d115d9a6bdbc38d89b5216f502
65,069
def rand_walk(start_point, step_size, num_iters, sigma = 1): """ Function to initiate a random walk from a starting point Inputs ------ start_point : vector(1-D Numpy array) Vector of the initial point of the walk step_size : float Size of random step num_iters : integer...
9253dfbf387e150b321ed4703cfcf360a1d235e8
65,070
def object_to_schema(obj: InDataT, **options) -> InDataT: """ Generate a node represents JSON schema object with type annotation added for given object node. :param obj: mapping object such like a dict :param options: Other keyword options such as: - ac_schema_strict: True if more strict (...
4d21e84b9b37795799627587d7e9068082802269
65,071
def read_lut(from_opened_input_file, bytes_of_lut_to_read: int, reverse_byte_ordering=False): """ :param from_opened_input_file: file handle to the LUT file, positioned at the beginning of the file :param bytes_of_lut_to_read: how many bytes to read; this is a product of the number of entries (4 bytes per) ...
56d8db742ced18127b90e8b38e2819ecf97beb9b
65,072
def approximate_kl(log_prob_new, log_prob_old, mask): """Computes the approximate KL divergence between the old and new log-probs. Args: log_prob_new: (B, T, C, A) log probs new log_prob_old: (B, T, C, A) log probs old mask: (B, T) Returns: Approximate KL. """ diff = log_prob_old - log_prob_...
205513d78b4a1482b158bf4239fde838b2d2309d
65,074
import math def get_sprites(X): """Generate a square sprite image with digits. Tensorflow supports sprite images up to 8192x8192 pixels. Given each of our digits is 20px*20px, we don't have to scale it down. """ width, height = IMAGE_WIDTH, IMAGE_HEIGHT digits_per_row = int(math.ceil(math.sqrt...
be4253bfbb5966605b7b95b34cf11f644774ced5
65,075
def plotyy( x1, y1, x2, y2, color1='b', color2='g', fun=None, **kwargs ): """ A work-alike of the Matlab (TM) function of the same name. This places two curves on the same axes using the same x-axis, but different y-axes. Call signature:: ax, h1, h2 = plotyy( x1, y2, x2, y2, color1='b', color...
f013e7e647f3eb94f40bb1a49cb7d5fec2bcf04d
65,076
def protected(): """ A protected endpoint. The auth_required decorator will require a header containing a valid JWT .. example:: $ curl http://localhost:5000/api/protected -X GET \ -H "Authorization: Bearer <your_token>" """ return {"message": f'protected endpoint (allowed user {...
4a970dfd726448ab090c3ae36a9b1f5ad5be2cf8
65,077
def filter_list(list_to_filter, attr, attr_value, list_type): """ Utility function to filter a given list based on the whether it has the given values for the given attributes. Keeps the objects where all the objects have the given attr_vals for the corresponding attrs. :param list_to_filter: The li...
04766fb7d64588c9407783aa9f0c5e055d2a3dbf
65,079
from scapy.libs.winpcapy import ( PCAP_ERRBUF_SIZE, pcap_open_live, pcap_compile, pcap_compile_nopcap, pcap_close ) from ctypes import create_string_buffer def compile_filter(filter_exp, # type: str iface=None, # type: Optional[Union[str...
6900d8aced81a1a04fbfc7c0f4dc6309c61419ec
65,080
def rates_nucleus(er, det: Detector, fx: Flux, efficiency=None, f=None, nsip=NSIparameters(), flavor='e', op=oscillation_parameters(), ffs=formfsquared, q2=False, **kwargs): """ calculating scattering rates per nucleus :param er: recoil energy :param det: detector :param fx: flux ...
a6c0ebcd1cab8acdc18a88013f33a07d61686e86
65,081
def all_3tours(ct, dists): """generates all 3-lenght tours from ct -> cities tuple""" tours = [] NCITIES = len(ct) for i in range(0, NCITIES): for j in range(i+1, NCITIES): for k in range(j+1, NCITIES): tours.append(tour(ct[i],ct[j],ct[k],dists)) return tours
d57d7491a62d09d9640345068a3987f18715fb1f
65,082
import copy import torch def dataProcessing(data_x, data_y, batch_size, training_ratio, validation_ratio, FM_indices, bool_norm=False): """ Data preprocessing. Parameters: ---------- data_x: 2D Array (nDOF x SampleNum). The deformation data (x SampleNum) of al...
6501dfb29d3b922843eb404cee0a2aa6df247dc4
65,083
from msrest.serialization import Deserializer from msrest.exceptions import DeserializationError def datetime_format(value): """Validate the correct format of a datetime string and deserialize.""" try: datetime_obj = Deserializer.deserialize_iso(value) except DeserializationError: message ...
8f635e60e4b9276cccedb8ee282afaea64c579fd
65,085
async def create_new_task(request): """Create a new task.""" required_fields = ["name", "administrators", "owners"] utils.validate_fields(required_fields, request.json) txn_key, txn_user_id = await utils.get_transactor_key(request) task_id = str(uuid4()) batch_list = Task().batch_list( ...
dc8f2a50ade50de9d07bbcac8acf14912f87961a
65,086
def combine(background_img, figure_img): """ :param background_img: str, the file path of the original background image. :param figure_img: str, the file path of the original figure image. :return: Replace the green background in figure imagine into the background imagine. """ bg = background_im...
a444ea43222ed892161edd9c8ddaf0ca1ca0f514
65,087
def runcommand(cosmology='WMAP5'): """ Example interface commands """ # Return the WMAP5 cosmology concentration predicted for # z=0 range of masses Mi = [1e8, 1e9, 1e10] zi = 0 print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi)) output = commah.run(cosmology=cosmology, zi=zi, ...
b0854c596218e91f78f84b67b917fa62ea7b4175
65,088
def do_include_raw(parser, token): """ Performs a template include without parsing the context, just dumps the template in. """ bits = token.split_contents() if len(bits) != 2: raise template.TemplateSyntaxError, "%r tag takes one argument: the name of the template to be included" % bits[0] template_name...
e324a73c33bf8861916a12107f5eb40c8b7cb32c
65,089
def build_dataset(cfg, target, default_args=None): """Build a dataset from config dict. Args: cfg (dict): Config dict. It should at least contain the key "type". target (str): Target name. One of : "train", "val", "test". default_args (dict, optional): Default initialization arguments. ...
432c9f67e5c740bcf2553c5d4f7cf93880920777
65,091
def to_json(MLClassifier): """ Returns an ML Classifier JSON object """ return ml_classifier_schema.dump(MLClassifier).data
0d4e56c4f0d8f2fe8a992f4acdf6b633ebcd7bdf
65,092
def convert(bsigs, grpkey, bldkey, msg=ffi.NULL, mgrkey=ffi.NULL): """ Converts a set of blinded group signatures, in schemes that support it. Optional parameters may be ignored in some schemes. Parameters: bsigs: An array containing the blinded group signatures. grpkey: The group key. ...
cce4639fa42bff7999c55ac5bc60355712c8e3b6
65,093
def get_colors(hists): """ Get colors of plotted objects from draw option :param hists: histograms :type hists: list :return: list of colors :rtype: list """ def get_color(hist): draw_option = hist.GetDrawOption() if isinstance(hist, ROOT.TEfficiency): return ...
e5af47ea7ee5904b42536b2abcb1891ec6d52bc1
65,095
def _instance_transfer(Xs, Xt, ys, psi, train_selection): """ Do the instance transfer. """ tol = 1e-10 # ns = 550, nt = 550 ns, _ = Xs.shape nt, _ = Xt.shape # neighbor trees target_tree = BallTree(Xt, leaf_size=16, metric='euclidean') source_tree = BallTree(Xs, leaf_size=16, metric=...
e58aa739600e6ac692bab993f19f2e2ab79c8434
65,096
def login_password_invalid(client, user): """Yield a function for this step""" def run_step(last_result): """Run the step""" user.set_password("password1") user.save() return assert_api_call( client, "psa-login-password", { "fl...
64f58705a164369caa655f2c134978214ff36a5c
65,097
def is_git_configured(): """Check if user.name and user.email is set globally in git This will also return false if git is not available at all. Returns: bool: True if it is set globally, False otherwise """ try: for attr in ["name", "email"]: shell.git("config", "--get...
5a3ee580266c1695f35c20a21fffdb248b56758b
65,098
def join(a, *p): """Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded.""" path = a for b in p: if b.startswith('/'): path = b elif path == '' or path.endswith('/'): ...
3c9588e6a89918e262e2469721516b88d48df92e
65,099
def parse_ff_port_status(data): """ Parse binary data (pb.FFPortStatus) """ msg = pb.FFPortStatus() msg.ParseFromString(data) return msg
3174abd3db86100877fc948c87585d53faa3494f
65,100
def normalize(point): """ Returns a new vector that has the same direction as vec, but has a length of one. """ if(point[0] == 0. and point[1] == 0.): return (0., 0.) return (point[0] / length(point), point[1] / length(point))
882bcc73b87098e5e420b4ced9009709cccf0971
65,101
import functools import logging def RPCWrapper(f): """A decorator for converting exceptions to rpc status messages. This decorator should be inserted below the rpcserver.Handler call to prevent normal exceptions from reaching the RCP layer. These expected exceptions are then encoded into the status message o...
1ec82c93054272540f48e26d9c956be10644f0d5
65,102
from itertools import combinations def Resilient(n): """ 12 -> 1 5 7 11 -> 2 3 4 6 8 9 10 -> {2 4 6 8 10 12} + {3 6 9 12} - {6 12} 1 - {[1/2 + 1/3] - 1/6} 4/11 = 0.36.. >>> Resilient(12) 0.36363636363636365 """ seq = mymath.factorLst(n) seq = [k for k, v in seq] r...
e10ca8ef9e8f12b7cfce5ae46a829c230d787b00
65,103
def get_http_exception_handler(app): """ # refer: https://stackoverflow.com/questions/29332056/global-error-handler-for-any-exception#44083675 Overrides the default http exception handler to return JSON. """ handle_http_exception = app.handle_http_exception @wraps(handle_http_exception) def ...
d981eec6cfc37e9f77778deb512a40c6bcc4bf3b
65,104
import base64 import pyDes def cdes(obj, deskey='12345678', desiv='abcdefgh', mode: int = 1, to_file: t.Union[str, Path] = None, desmode='CBC', despadmode='PAD_PKCS5'): """ des加密与解密(des mode: ECB or CBC) 使用示例: # 1)针对字符 obj = b'这是一个示例' deskey = b'asdfhjkl' # 8 by...
9308b01baeae37401765116993938cdf3d42574e
65,105
from SimPEG.PF import BaseMag def readUBCmagneticsObservations(obs_file): """ Read and write UBC mag file format INPUT: :param fileName, path to the UBC obs mag file OUTPUT: :param survey :param M, magnetization orentiaton (MI, MD) """ fid = open(obs_file,...
72970991000b9974fcd2701f019fd86564ba597c
65,106
def _decrypt( keys: list[int], salt: int, encoded_secret: int, key_size: int = 128 ) -> int: """Decryption with keys and salt""" key = salt for index, subkey in enumerate(keys): key ^= subkey << index + 1 key %= 2**key_size return _enc(key, key_size) ^ key ^ encoded_secret
e2afc8dfb87fdb529eebfad7c744e27ea50f5011
65,107
import time def spectra2moments(Z_spec, paraminfo, **kwargs): """ This routine calculates the radar moments: reflectivity, mean Doppler velocity, spectrum width, skewness and kurtosis from the level 0 spectrum files of the 94 GHz RPG cloud radar. Args: Z_spec (list of dicts): list containing ...
0089aec30738daf13df6e7fc79e19c9500e8be42
65,109
def plot_mag_map(fignum, element, lons, lats, element_type, cmap='coolwarm', lon_0=0, date="", contours=False, proj='PlateCarree', min=False,max=False): """ makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element a...
0627b785e4ca629f87f35b61623bdede8d09a54e
65,110
def scrub_response(response): """ Drop irrelevant headers. """ headers = response["headers"] for header in [ "CF-Cache-Status", "CF-RAY", "Cache-Control", "Connection", "Date", "Expect-CT", "NEL", "Report-To", "Server", ...
8f1a9f9499df1fbaf7147ccdda8c7854c4c638ec
65,111
def _fix_recession_reserve_data(df: pd.DataFrame) -> pd.DataFrame: """ Fix Recession Reserve data in the Finance Department. Note: Any class 900 spending in Finance should be labeled as "Recession Reserve". """ finance = df.query("dept_code == '35'").copy() finance_900 = finance["class_900"...
0d66de23d70e2e560fe73db57830a2010359d8b1
65,112
def check_necessary_conds(val_inf, muls): """ The necessary conditions for a rational solution to exist are as follows - i) Every pole of a(x) must be either a simple pole or a multiple pole of even order. ii) The valuation of a(x) at infinity must be even or be greater than or equal to 2....
58463ac2855d07eb36e1850cec3208d69d5a545c
65,113
def crossval_predict(estimator, cv, X, y, groups=None, X_new=None, new_index=None, test_avg=True, avg_type='auto', method='predict', scoring=None, n_jobs=None, verbose=0, n_digits=4, compact=False, train_score=False, target_func=None): """Get Out-of-Fol...
0d2b6d93e1316166480a662e84a45f1df2204506
65,114
def polygon(points, **kwargs): """Creates a polygon with given list points. Example: p1 = point(x=0, y=0) p2 = point(x=100, y=0) p3 = point(x=0, y=100) triangle = polygon([p1, p2, p3]) show(triangle) """ points_str = " ".join(f"{p.x},{p.y}" for p in points) ...
8e4c2d7502993cd5decbb2c10bd2d34524eb924c
65,115
def arrange_dlc_data(df): """ Restructure DLC dataframe """ scorer = df.keys()[0][0] bodyparts = df[scorer].columns.levels[0] data = {} for bp in bodyparts: data[bp] = df[scorer][bp] return data
26cfbe04ef2dc84d522e1e8c7f9db2a1ee3fe175
65,116
def get_rect_footprint(l_m=4.8, w_m=1.83): """ Get rectangular footprint of length (x, longitudinal direction) and width (y, lateral direction) l_m : length (default 4.8) w_m : width (default 1.83) Return Values ============= footprint_x : tuple of x coordinates of the footprint footpr...
dd40304c404226543023c1f81bca5aac81e70eec
65,117
import bz2 import struct def ReadPrefix(input_filename): """ Read the prefix of a graph data structure from disk @param input_filename: the filename where the graph data is stored """ assert (input_filename.endswith('.graph.bz2')) data = bz2.decompress(open(input_filename, 'rb').read()) ...
1c585963bb2387ad9de2b4bf7e53f7b642bafcb8
65,118
import codecs def detect_encoding(data): """Detect which UTF codec was used to encode the given bytes. The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big or little endian. Some editors or libraries may prepend a BOM....
69b7990fa4e7f9db5d84843162abb210b8792fd9
65,119
def _parse_source_file_list_blob_key(blob_key): """Parse the BLOB key for source file list. Args: blob_key: The BLOB key to parse. By contract, it should have the format: `${SOURCE_FILE_LIST_BLOB_TAG}.${run_id}` Returns: - run ID """ return blob_key[blob_key.index(".") + 1 :]
a7f5c7ccee1404e17b90cb6cd58922ec162d33e3
65,120
def get_ast(token): """ Recursively unrolls token attributes into dictionaries (token.children into lists). Returns: a dictionary of token's attributes. """ node = {} # Python 3.6 uses [ordered dicts] [1]. # Put in 'type' entry first to make the final tree format somewhat # ...
a5f4d32678f95e4af680239d5cf67ae947199d62
65,121
def rotaxis_nonfootflat(frame,ankle_JC): """Calculate the anatomically correct foot joint center and axis function for a non-flat foot. Takes in a dictionary of xyz positions & marker names and the ankle axis then calculates the anatomically correct foot axis for a non-flat foot. Markers used: RTO...
7e804948c273be87808f462ec23e643ac32e3d3c
65,122
def get_edges(da, dim, mode="edge", **kwargs): """Interpolate and extrapolate a data array at grid edges along the `dim` dimension(s) .. note:: Coordinates are linearly extrapolated Parameters ---------- da: xarray.DataArray dim: str, tuple Single or tuple of data-array or generic dime...
054773391d2b6a02ca3db350c2958edf561869f4
65,123
from typing import List def get_colnames(table: pd.DataFrame) -> List[str]: """ Get column names from a DataFrame. """ return list(table.columns)
7f5f6428c854332c0ad151faa615f85cc57b3f21
65,124
def get_primary( hostname, refresh_key, authorization_host, org_id, sddc_id, verify_ssl=True, cert=None, ): """ Retrieves the primary cluster in provided customer sddc UUID Please refer the `VMC Get primary cluster documentation <https://developer.vmware.com/docs/vmc/latest/vmc/...
9376db85d31aaa34e982c86b810035099fbe686e
65,125
def progteam_desc(request): """backend.about.urls: /about/progteam-desc Progteam team description. We assume there is only one description object lives in the table, and returns the first and only one. """ obj = ProgteamDesc.objects.first() return JsonResponse({ 'desc': obj.desc, })
d263223246aec29861df18f4731c021b2be707db
65,127
def invert(boolexpr): """invert >>> print invert('0=0') not (0=0) >>> print invert(invert('0=0')) 0=0 """ if isinstance(boolexpr, Not): return boolexpr.element else: return Not(boolexpr)
2d7cef12fc360f80485a3b032e190a98df4e4050
65,128
def prop_FC(csp, newVar=None): """ Do forward checking. That is check constraints with only one uninstantiated variable. Remember to keep track of all pruned variable,value pairs and return """ constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons() pruned = [] for...
3956cf0ae03a03c0dbc3504ab2ed2a20b8343d90
65,129
def t_rel_len2048_dropout15_tiny(): """Hparams for LM with relative attention, tiny transformer.""" # hparams = transformer.transformer_base() hparams = transformer.transformer_tiny() update_transformer_hparams_for_music(hparams) update_truncate_length(hparams, 2048) update_dropout(hparams, 0.15...
abaa85a14578f638f5e9be1faf5db952981fe404
65,130
def quick_sort(alist): """ 快速排序,不稳定,空间O(logn) 时间:最好O(nlogn),平均O(nlogn),最坏O(n^2) """ length = len(alist) if length <= 1: # print(alist) return alist low = 0 high = length - 1 mid_value = alist[0] while low < high: while low < high and alist[high] >= mid_val...
b284759dc021bc252fc2e3c77345eaf2b8415317
65,131
import requests import logging def group_nodes(group): """ :param group: group name :return: list of nodes """ try: api_url = get_apiurl() nodes_group = requests.get(f'{api_url}/groups/{group}').json() return nodes_group except Exception as e: logging.error('so...
698036ce4d55f2590d63a7ba73a5e3b396c3bc9a
65,134
def go_suffix_for_arch(arch: str, is_private: bool = False) -> str: """ Imagestreams and namespaces for the release controller indicate a CPU architecture and whether the release is part of the private release controller. using [-<arch>][-priv] as a suffix. This method calculates that suffix based o...
e3da6de620d571e89c00c05883080805eea76f33
65,135
def get_gpu_config(): """Share GPU memory between image preprocessing and inference.""" gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=_GPU_MEM_FRACTION) return tf.ConfigProto(gpu_options=gpu_options)
9310bd55863e3ecfb352af910c1e6fce1f9f81b4
65,136
def _construct_unicode(self, node): """Override the default string handling function to always return unicode objects. Required for Python 2.7. Thanks to: http://stackoverflow.com/questions/2890146/how-to-force-pyyaml-to-load-strings-as-unicode-objects """ return self.construct_scalar(node)
eed380a154fe5cfd313c6f61a0648862f7d07a0f
65,137
def chamnetv2_100(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """ ChamNet """ default_cfg = default_cfgs['chamnetv2_100'] model = _gen_chamnet_v2(1.0, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg return model
aa0c32fb82e387d18da15b6fa5e331f298d24411
65,138
def update_real_pred_150d(real_pred_150d, buffer): """@params: real_pred_150d: List[dict] buffer: dict: {"date": , "value0": , "value1": } Note: buffer has to be complete """ return real_pred_150d[1:] + [buffer]
1ef0c648c5f921a9b66e23f41cfd7cf53cf16c0b
65,139
def resnet50(num_classes=100): """ return a ResNet 50 object """ return ResNet(BottleNeck, [3, 4, 6, 3],num_classes=num_classes)
b2a1defb4eb3f1054f3d069250fa481df99d6d65
65,140
def get_recommendation_models(client: Client, id: int) -> dict: """Query for model info/data by recommendation ID.""" params = collect_parameters(request, optional=['type_id', 'include_data'], defaults={'include_data': False}) type_id = params.pop('type_id', None) include_data = params.pop('include_data...
71c6a22604279a56f2e9b81231ca47e7ce94e9e3
65,142
def get_lookup_coords(nrms=10, ninc=10, naz=36, ntheta=45): """ Return coordinate arrays corresponding to number of elements in each axis. Return lookup axes in the following order with ranges: rms: [0, 50] degrees inc: [0, 90] degrees az: [0, 360] degrees theta: [0, 90] deg...
c37a0285424769476fa4acb7eb18e073e1e34a47
65,143
def get_datapath(app, dpid): """ Get datapath object by dpid. Returns None on error. """ assert isinstance(dpid, (int, long)) return app.send_request(event.GetDatapathRequest(dpid=dpid))()
b096c02bbb2f212b5e7992478244eeb7a3f1da10
65,144
from datetime import datetime def now(): """Return a string representation of the current date/time. Returns: (str): current UTC time as a string """ return str(datetime.utcnow())[:19] + "Z"
93906571ce2b74846e73f1ec5f773589ce70e4bb
65,145
import pytz from datetime import datetime def current_year(time_zone: pytz.timezone = pytz.timezone("UTC")): """Return the current year""" now = datetime.now(time_zone) return now.strftime("%Y")
de116f0a95d8bb16de91e4b3c6582c9e583271d0
65,146
def execute( metric_id: str = None, ) -> list: """Returns node peers information. :param metric_id: Identifier of node metric. :returns: Node metrics information. """ endpoint = f"{pycspr.CONNECTION.address_rest}/{_API_ENDPOINT}" response = rest_client.get(endpoint).content.decode("ut...
675986fdc2781f4de508cd7c527b8bc3a319e319
65,147
def _check_pair(minterm1, minterm2): """ Checks if a pair of minterms differs by only one bit. If yes, returns index, else returns -1. """ index = -1 for x, (i, j) in enumerate(zip(minterm1, minterm2)): if i != j: if index == -1: index = x else: ...
8016c3aba245973729b0807dd08e27fc39f512a8
65,148
from datetime import datetime def get_date(date_long): """Convert longs to datetime.""" dt = None try: dt = datetime.datetime.fromtimestamp(date_long / 1e3) except (KeyError, TypeError, ValueError): try: dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(date_...
c831bd79b9a94b66b516c2805f4ce07ad215033a
65,149
import torch def lossmin(z): """ nh: number of nodes in each hidden layer nlh: number of hidden layers mom: momentum bs: mini-batch size lr: learning rate wd: weight-decay factor """ nh,nlh,mom,bs,lr,wd=z print('nh,nlh,mom,bs,lr,wd: '+str(z)) bs=int(bs) ltmin=[] for...
e35747ae0eee84a5dd696db983434a2b4d18c680
65,150
def convert_pandas_to_dask(df, npartitions=4, partition_size="100MB", *args, **kwargs): """ Convert a pandas dataframe to a distributed dask dataframe, enabling lazy evaluation that can be prompted using .compute() or .persist() """ dask_df = dd.from_pandas(df, npartitio...
13d980797930c301e4f366332a6b088e06154767
65,151
def calc_lnoverlaps(group_pars, star_pars, nstars): """Find the lnoverlaps given the parameters of a group Parameters ---------- group_pars : [npars] array Group parameters (internal encoding, 1/dX... no nstars) star_pars : dict stars: (nstars) high astropy table including columns a...
6aaeecfb1712134a4f5761c9a047763d572517b7
65,152
def shift_vort_to_T(array): """! Shift the array from vorticity points to the corresponding tracer point.""" shifted = (array[...,0:-1] + array[...,1:])/2 shifted = (shifted[...,0:-1,:] + shifted[...,1:,:])/2 return shifted
9408eb38cf667f2e48e31e7174e9e681bb27ed91
65,153
import io def usgs_gold_call(*, resp, year, **_): """ Convert response for calling url to pandas dataframe, begin parsing df into FBA format :param url: string, url :param resp: df, response from url call :param args: dictionary, arguments specified when running flowbyactivity.py ('yea...
a4d185c0f3e1fa3c0fbd6e3933c3b3997b369312
65,154
def total_sizeof(o, handlers={}, verbose=False): """ Returns the approximate memory footprint an object and its contents. Automatically finds the contents of the following builtin containers and their subclasses: tuple, list, deque, dict, set and frozenset. To search other containers, add handlers...
cabf0e1f37da0725b0b4f7551f4443e873a18345
65,155
def pad(val: str) -> str: """Pad base64 values if need be: JWT calls to omit trailing padding.""" padlen = 4 - len(val) % 4 return val if padlen > 2 else (val + "=" * padlen)
3ab1c91fde1522f15a766730f73e44c97dbeda1a
65,156
def display_users(): """ Function for displaying users """ return User.display_users()
485a921e3d37b31b425deb242575b2b158bd59b2
65,157
def non_zero_row(arr): """ 0. Empty row returns False. >>> arr = array([]) >>> non_zero_row(arr) False 1. Row with a zero returns False. >>> arr = array([1, 4, 3, 0, 5, -1, -2]) >>> non_zero_row(arr) False 2. Row...
7052dac96bbf359800c43e0b750e999fba5ef2e0
65,158
def softnms2(dets, Nt=0.3, sigma=0.5, thresh=0.001, method=2): """ py_cpu_softnms :param dets: boexs 坐标矩阵 format [y1, x1, y2, x2] :param Nt: iou 交叠门限 :param sigma: 使用 gaussian 函数的方差 :param thresh: 最后的分数门限 :param method: 使用的方法 :return: 留下的 boxes 的 index """ # indexes...
e647a06c62b5935087096492fc87e70426f92596
65,159
def get_prop_layers(unsig_data: dict) -> list: """Group properties by layer and return list of layers""" props = unsig_data.get("properties") multipliers = props.get("multipliers") colors = props.get("colors") rotations = props.get("rotations") distributions = props.get("distributions") re...
d5d95eade48df026d0c7be0dd3d500a0b7b3bb07
65,160
def get_meshes_from_nodes(nodes, search_child_node=False, full_path=False, mesh=True, nurbs=False): """ Function that returns polygon meshes from given nodes :param nodes: list(str) :param search_child_node: bool :param full_path: bool :param mesh: bool :param nurbs: bool :return: list(s...
d15e43348c8cd3ead002469e3b94a5721a23235e
65,161
def calc_elbo(sum_r2, n_jumps, r, n, A, B, n0, A0, B0, exp_log_occs, exp_inv_phi, exp_log_phi, identifiability_corr=True): """ Calculate the variational evidence lower bound for a particular mixture model. args ---- Most of the arguments are those produced internally by the ...
8e77c5d825a28d1721dbf3e47288e4209d8a1788
65,162
import re def ignore_stacktrace(crash_stacktrace): """Return whether the stacktrace needs to be ignored.""" # Filter crash based on search exclude pattern specified in job definition. search_excludes = environment.get_value('SEARCH_EXCLUDES') if search_excludes and re.search(search_excludes, crash_stacktrace)...
9eeb59ecb0df01e6a628743df4e68d6675c252be
65,164
def est_riskshrink_thresh(Wx, nv): """Estimate the RiskShrink hard thresholding level. # Arguments: Wx: np.ndarray. Wavelet transform of a signal. opt: dict. Options structure used for forward wavelet transform. # Returns: gamma: float. The RiskShrink hard thresholding est...
6769004c30a5e6c197814683d1910872d18b4675
65,165
def word_remove(text, wordlist): """ This function takes a list of text strings and a list of words. It returns the list of text strings with the words appearing in the wordlist removed. """ # Create new emoty list for the cleaned text clean_text = [] # Seperate ALL words from each other an...
8dac46d54345efedf7bb117af3e4eb67704c0f85
65,166