content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cache_mixin(cache, session): """CacheMixin factory""" hook = EventHook([cache], session) class _Cache(CacheMixinBase): _hook = hook _cache_client = cache _db_session = session return _Cache
79368b4cc2680ff95be520c9d877dcca5a6a1eef
3,639,000
def _read_output(path): """Read CmdStan output csv file. Parameters ---------- path : str Returns ------- Dict[str, Any] """ # Read data columns, data, comments = _read_output_file(path) pconf = _process_configuration(comments) # split dataframe to warmup and draws ...
aba1fe156de9f2fe9f595d5e5e64994b9eab539b
3,639,001
def linear_chance_constraint_noinit(a,M,N,risk,num_gpcpoly,n_states,n_uncert,p): """ Pr{a^\Top x + b \leq 0} \geq 1-eps Converts to SOCP """ a_hat = np.kron(a.T,M) a_dummy = np.zeros((n_states,n_states)) for ii in range(n_states): a_dummy[ii,ii] = a[ii,0] #print(a_dummy) ...
9b6421213f3f2251824a45fc04b69146cfeebbaa
3,639,002
import fastapi def patroni(response: responses.Response, session: sqlalchemy.orm.Session = fastapi.Depends(models.patroni.get_session)): """ Returns a health check for the reachability of the Patroni database. """ return db_health(response, session, 'Patroni')
fabaf09e2754e0e89ff17312e9a3f86d48972dc0
3,639,003
def authorization_code_grant_step1(request): """ Code grant step1 short-cut. This will return url with code. """ django_request = oauth2_request_class()(request) grant = CodeGrant(oauth2_server, django_request) return grant.authorization()
5227158127b5313b17c27fb0f351f8294faec840
3,639,004
async def activity( guild_id: int, discord_id: int, activity_input: DestinyActivityInputModel, db: AsyncSession = Depends(get_db_session), ): """Return information about the user their stats in the supplied activity ids""" user = await discord_users.get_profile_from_discord_id(discord_id) ...
25a2eb719648cbdb6161baa2b1de1570e07a42ea
3,639,005
def put_topoverlays(image, rects, alpha=0.3): """ a function for drawing some rectangles with random color Args: image: an opencv image with format of BGR rects: a list of opencv rectangle alpha: a float, blend level Return: An opencv image """ h, w, _ = image.shape im = np.ones(shape=image...
9f6cf0cfd33214503905a16384fade2976bad190
3,639,006
def extract_next_token(link): """Use with paginated endpoints for extracting token which points to next page of data.""" clean_link = link.split(";")[0].strip("<>") token = clean_link.split("?token=")[1] # token is already quoted we have to unqoute so it can be passed to params return unquote(t...
f0eae72cf8d99e816dfff1c6345f0a9b73abdd21
3,639,007
import urllib import json def get_host_country(host_ip): """Gets country of the target's IP""" country = 'NOT DEFINED' try: response_body = urllib.request.urlopen(f'https://ipinfo.io/{host_ip}').read().decode('utf8') response_data = json.loads(response_body) country = response_data...
05df2c54dd275c654631cb188cbfdaa0d8e15ed9
3,639,008
import traceback def astng_wrapper(func, modname): """wrapper to give to ASTNGManager.project_from_files""" print 'parsing %s...' % modname try: return func(modname) except ASTNGBuildingException, exc: print exc except Exception, exc: traceback.print_exc()
fbb1b3090bfc7b93258fbbcefea1a8d1463dded2
3,639,009
def clean(s): """Clean text!""" return patList.do(liblang.fixRepetedVowel(s))
d81f16dfb35b4f218af5017de1eef8a005d3e7de
3,639,010
import sys def filename(s, errors="strict"): """Same as force_unicode(s, sys.getfilesystemencoding(), errors) """ return force_unicode(s, sys.getfilesystemencoding(), errors)
bd8a178cc1216e04f95699418a90dbe52a2f708f
3,639,011
def elastic_transform(image, alpha=1000, sigma=30, spline_order=1, mode='nearest', random_state=np.random): """Elastic deformation of image as described in [Simard2003]_. .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", ...
ddabb6a15deba901398f799352216b2c89652296
3,639,012
import json def format_search_log(json_string): """ usage example {{ model_object|format_search_log }} """ query_json = json.loads(json_string) attributes_selected = sorted(query_json.get('_source')) context = {} context['attributes_selected'] = attributes_selected return attributes...
eb5aa21590474acaee7b2b94a1cfdc52c080d017
3,639,013
def set_variable(value,variable=None): """Load some value into session memory by creating a new variable. If an existing variable is given, load the value into the given variable. """ sess = get_session() if variable is not None: assign_op = tf.assign(variable,value) sess.run([assign...
8256a27c2a446e600e6cfe818c5e4c60e18f1d04
3,639,014
def matrix ( mtrx , i , j ) : """Get i,j element from matrix-like object >>> mtrx = ... >>> value = matrix ( m , 1 , 2 ) """ if isinstance ( mtrx , ROOT.TMatrix ) : if i < mtrx.GetNrows () and j < mtrx.GetNcols () : return mtrx ( i , j ) if callable ( mtrx ) : ...
1101d5bd4bf569f11ec7ee41700171906e58e743
3,639,015
def check_type(instance, *classes): """Check if object is instance of given class""" for klass in classes: if type(instance).__name__ == klass: return True for T in getmro(type(instance)): if T.__name__ == klass: return True return False
1761be42fd1a781ef5b6d94b42006fdcb2789e8b
3,639,016
def test_get_earth_imperative_solution(solar_system): """ ## Imperative Solution The first example uses flow control statements to define a [Imperative Solution]( https://en.wikipedia.org/wiki/Imperative_programming). This is a very common approach to solving problems. """ def get_planet...
f966886e3384547803106c404a21e2bb7ecd8fa9
3,639,017
import os def parse(request): """ A form that lets an authorized user import and the parse data files in the incoming directory. """ dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'incoming') if request.method == 'POST': parse_form = forms.Form(request.POST) i...
9645436986ae644db5f8537e2c6c1ebee1d91e94
3,639,018
import glob import tqdm def animate(map, time, phase0=0.0, res=75, interval=75): """ """ # Load the SPICE data ephemFiles = glob.glob('../data/TESS_EPH_PRE_LONG_2018*.bsp') tlsFile = '../data/tess2018338154046-41240_naif0012.tls' solarSysFile = '../data/tess2018338154429-41241_de430.bsp' ...
0fa39a0299a8d8cd75b0475f45e49caa731925a7
3,639,019
import functools def get_params_from_ctx(func=None, path=None, derive_kwargs=None): """ Derive parameters for this function from ctx, if possible. :param str path: A path in the format ``'ctx.arbitraryname.unpackthistomyparams'`` to use to find defaults for the function. Default: ...
9b1a24a17ec0653804752f08f43e7cf615de679e
3,639,020
def bresenham(points): """ Apply Bresenham algorithm for a list points. More info: https://en.wikipedia.org/wiki/Bresenham's_line_algorithm # Arguments points: ndarray. Array of points with shape (N, 2) with N being the number if points and the second coordinate representing the (x, y) ...
9c49edd9eda3113855582ec3cc35c4d40d056dd9
3,639,021
def radialBeamProfile_flatTop(x,y,a): """Top hat beam profile \param[in] x x-position for profile computation \param[in] y y-position for profile computation \param[in] a radial extension of flat-top component \param[in] R 1/e-width of beam profile \param[ou...
699d214c499d8cbcf1c0ed26a5d0d00cf2813f3f
3,639,022
def _split_data(x, y, k_idx, k, perm_indices): """Randomly and coordinates splits two indexable items. Splits items in accordiance with k-fold cross-validatoin. Arguments: x: [?] indexable item y: [?] indexable item k_idx: int index of the k-fold...
7e53d6a172335b7777887ed493ec41ecb6833461
3,639,023
def set_neighborhood(G, nodes): """Return a list of all neighbors of every node in nodes. Parameters ---------- G : NetworkX graph An undirected graph. nodes : An interable container of nodes in G. Returns ------- list A list containing all nodes that are a nei...
e6ce89162307fecead69c9bdc67bc9c9f8ff40e8
3,639,024
from typing import Any from typing import Optional def resolve_Log( parent: Any, info: gr.ResolveInfo, id: Optional[int] = None, uuid: Optional[str] = None, ) -> ENTITY_DICT_TYPE: """Resolution function.""" return resolve_entity(Log, info, id, uuid)
eecd46296e9d1c0ce55dc31ee1249b4c3b512b15
3,639,025
from typing import Union from pathlib import Path def _get_path_size(source: Union[Path, ZipInfo]) -> int: """ A helper method that returns the file size for the given source :param source: the source object to get the file size for. :return: the source's size. """ return source.stat().st_siz...
2981b2b88e776cfd2315785fea8ba1e1ec63c7cf
3,639,026
def get_graph_subsampling_dataset( prefix, arrays, shuffle_indices, ratio_unlabeled_data_to_labeled_data, max_nodes, max_edges, **subsampler_kwargs): """Returns tf_dataset for online sampling.""" def generator(): labeled_indices = arrays[f"{prefix}_indices"] if ratio_unlabeled_data_to_labeled_d...
da31aff7064c3516f95fb5597f2ee757ee35fa25
3,639,027
def check_comment_exists(comment_id_required=True): """ Decorator to check if a given comment exists. If it does not, it returns an HTTP 400 error. Must be called with (), and may pass the optional argument of whether the id is required. If the id is passed, it will be checked against entities of...
2c2dd4bd1149ee9f0e87b5d426211a3d5bba78c0
3,639,028
def GeoMoonState(time): """Calculates equatorial geocentric position and velocity of the Moon at a given time. Given a time of observation, calculates the Moon's position and velocity vectors. The position and velocity are of the Moon's center relative to the Earth's center. The position (x, y, z) comp...
50c523a2f838e7730546fac4e4b8ed2a13eefe0a
3,639,029
import platform def get_machine_name(): """ Portable way of calling hostname shell-command. Regarding docker containers: NOTE: If we are running from inside the docker-dev environment, then $(hostname) will return the container-id by default. For now we leave that behaviour. We ...
ae5a7090846164a97cafd07af4701dcfcc25070e
3,639,030
def pass_through_formatter(value): """No op update function.""" return value
202ea761db9e1fa858718c61df3a7fd18f02826c
3,639,031
from re import U def instantiate(decoder, model=None, dataset=None): """ Instantiate a full decoder config, e.g. handle list of configs Note that arguments are added in reverse order compared to encoder (model first, then dataset) """ decoder = utils.to_list(decoder) return U.TupleSequential(*[_in...
238b97eab9a653200d0f82b92342a64bbbbc6336
3,639,032
def un_normalize(stdevs, arrList): """ Return an arrayList with ith column multiplied by scalar stdevs[i] if stdevs[i] is not zero, and unmodified if it is zero. Args: stdevs: A list of numbers (should be the list output by normalize). arrList: A list of list of numbers that is the (nor...
a87aa89b2f591d46b077ea26d877f1d3459df2b3
3,639,033
import json def convert_graph(input_path): """ Converts a CRED-like graph into a graph format supported by the igraph library. The input graph must have been generated by cli2 CRED command (look for credResult.json) :param input_path: The path to the CRED graph to convert (credResult.json) """ ...
57037a662d033a422965f3efe13f321a5bf7f128
3,639,034
from typing import List def get_valid_classes_from_class_input( class_graph: class_dependency.JavaClassDependencyGraph, class_names_input: str) -> List[str]: """Parses classes given as input into fully qualified, valid classes. Input is a comma-separated list of classes.""" class_names = ...
e93edea9692ab9c461ed744a8727effbf705fdea
3,639,035
def us_ppop(ppop): """ Determines if the ppop is in a valid format to be in the US """ # return false if it's null or not 7 digits long if not ppop or len(ppop) != 7: return False ppop = ppop.upper() if ppop[:2] in g_state_by_code or ppop[:2] in g_state_code_by_fips: return True ...
afef4e7634034709f870379cd684a37a793c7ec5
3,639,036
def get_pygments_lexer(location): """ Given an input file location, return a Pygments lexer appropriate for lexing this file content. """ try: T = _registry[location] if T.is_binary: return except KeyError: if binaryornot.check.is_binary(location): ...
53521a3a8b297733cab9af444eff92a76d799a4d
3,639,037
def get_robotstxt_parser(url, session=None): """Get a RobotFileParser for the given robots.txt URL.""" rp = RobotFileParser() try: req = urlopen(url, session, max_content_bytes=MaxContentBytes, allow_errors=range(600)) except Exception: # connect or timeout errors a...
f838f8284b250133a1c5f0ca5d514756ff4f1eb0
3,639,038
def init_model(config, checkpoint=None, device='cuda:0'): """Initialize a model from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any we...
494cbcb012978d49905318d92c136bc7c6241a79
3,639,039
def estimate_period(time, y, y_err, clip=True, plot=True, **kwargs): """ Run a Lomb-Scargle Periodogram to find periodic signals. It's recommended to use the allesfitter.time_series functions sigma_clip and slide_clip beforehand. Parameters ---------- time : array of float e.g. time ar...
23cc58d910ff5541847fa4d5892979aa312d1609
3,639,040
def get_test_packages(): """Get a list of packages which need tests run. Filters the package list in the following order: * Check command line for packages passed in as positional arguments * Check if the the local remote and local branch environment variables have been set to specify a remote b...
302a3136ec84e81a68348e5ff1bffa9c916f36a1
3,639,041
def decoding_character(morse_character): """ Input: - morse_character : 문자열값으로 get_morse_code_dict 함수로 알파벳으로 치환이 가능한 값의 입력이 보장됨 Output: - Morse Code를 알파벳으로 치환함 값 Examples: >>> import morsecode as mc >>> mc.decoding_character("-") 'T' >>> mc.decoding_character(".") 'E' >>>...
29c3f99da372a713d349a0c7640403ae32c08aba
3,639,042
def SparsityParametersAddDimMetadata(builder, dimMetadata): """This method is deprecated. Please switch to AddDimMetadata.""" return AddDimMetadata(builder, dimMetadata)
5a7604ca44fbf3f2a1d520018269c472340511e5
3,639,043
def check_branch(payload, branch): """ Check if a push was on configured branch. :param payload: Payload from web hook. :param branch: Name of branch to trigger action on. :return: True if push was on configured branch, False otherwise. """ if "ref" in payload: if payload["ref"] == b...
88bd0ebae330ee169e97a40aee208b2f92ee4a32
3,639,044
from typing import Union def convert(q: Quantity, new_unit: Union[str, Unit], equivalencies=None) -> Quantity: """Convert quantity to a new unit. :raises InvalidUnit: When target unit does not exist. :raises InvalidUnitConversion: If the conversion is invalid. Customized to be a bit more universal t...
7d28a40d3da4a6189aeb9efb252f50088838a1f3
3,639,045
def randomized_pairwise_t_test(arr1, arr2, output=True): """ Perform a randomized pairwise t-test on two arrays of values of equal size. see Cohen, P.R., Empirical Methods for Artificial Intelligence, p. 168 """ # Make sure both arrays are the same length assert len(arr1) == len(arr2...
92ceb071fcc03dd952a15ffe08f2bd305c603a39
3,639,046
from typing import Dict from datetime import datetime import uuid def update_metadata(radar, longitude: np.ndarray, latitude: np.ndarray) -> Dict: """ Update metadata of the gridded products. Parameter: ========== radar: pyart.core.Grid Radar data. Returns: ======== metadata:...
ae4b26372221262426803f40394caa06245d5afb
3,639,047
import copy def idxsel2xsel(file, isel, dimensions, order): """ convert a index space selection object to an xSelect object """ if not isinstance(isel, idxSelect): raise TypeError('wrong argument type') xsel = {} xsel_size = {} xsel_dims = {} isarray = False interp = False ...
ff00a7705a9ae1f633e7ec19682367ccfea2b7bf
3,639,048
def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: """Return upload max transmission rate.""" return round(status.max_bit_rate[0] / 1000, 1)
e1c0a710131289e457f3c15da411a7f8d17fdfc7
3,639,049
def user_detail(request, id, format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = User.objects.get(id=id) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = UserSeriali...
9339c85cec0b271d5eeb8a1caec976992869174a
3,639,050
def _gsmooth_img(args): """ HELPER FUNCTION: private! Smooth an image with a gaussian in 2d """ img,kernel,use_fft,kwargs = args if use_fft: return convolve_fft(img, kernel, normalize_kernel=True, **kwargs) else: return convolve(img, kernel, normalize_kernel=True, **kwargs)
313a0c4475935665cb0e4c55bea343adf3a9fab4
3,639,051
import argparse def ParseArgs(): """Parses command line arguments. Returns: args from argparse.parse_args(). """ description = ( 'Handle Whale button click event.' ) parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, description=description) parser.add_arg...
304a453995de9586467756cbd9e974786033e794
3,639,052
def __logs_by_scan_id(scan_id, language): """ select all events by scan id hash Args: scan_id: scan id hash language: language Returns: an array with JSON events or an empty array """ try: logs = [] for log in send_read_query( "select hos...
26ef72dd2e0ed974a84f2ddc67e61fd90f769f17
3,639,053
def docs(): """Redirect to documentation on Github Route: /docs Methods: GET Return: redirect to webpage """ return redirect("https://kinsaurralde.github.io/ws_281x-lights/#/")
18fbbf2e4d53c66545bdf1129de5d1d4ac5944fd
3,639,054
def std(a, weights=None, axis=None, dtype=None, ddof=0, keepdims=False): """ Compute the weighted standard deviation along the specified axis. :param a: Array containing numbers whose standard deviation is desired. If `a` is not an array, a conversion is attempted. :param weights: Array contain...
758421b85657197413ab4fe2713bf18da2ac184a
3,639,055
import logging def createOneHourCandles(markets, database): """ Function that creates tables for one minute candles. :param database: :param markets: :return: """ conn = pymysql.connect(host='localhost', user='jan', password='17051982', da...
c800570a4dd17acb0b588064938ccf098e6c53bb
3,639,056
def coaddspectra(splist,plotsp=True,outf=None,sn_smooth_npix=10): """ Coadd spectra Parameters ---------- splist : list of XSpectrum1D objects List of spectra to coadd plotsp : bool If True, plot the coadded spectrum outf : str Output file sn_smooth_npix : float ...
1e0c312389f566a34cca878251b7d808968e175c
3,639,057
def get_rel_sim(relation, question, dataset): """ Get max cosine distance for relations :param relation: :param question: :return: """ query_ngrams = generate_ngrams(question) query_ngrams_vec = [get_avg_word2vec(phr, dataset) for phr in query_ngrams] relation_ngram = get_avg_word2ve...
63c313fac32ec2483979585c60cea916979aaf5d
3,639,058
def mk_request(bits, cn): """ Create a X509 request with the given number of bits in they key. Args: bits -- number of RSA key bits cn -- common name in the request Returns a X509 request and the private key (EVP) """ pk = EVP.PKey() x = X509.Request() rsa = RSA.gen_key(bits,...
f6ac4fe385caba149b85599fa6f48fc3d0dc7ccf
3,639,059
import re def nice(name): """Generate a nice name based on the given string. Examples: >>> names = [ ... "simple_command", ... "simpleCommand", ... "SimpleCommand", ... "Simple command", ... ] >>> for name in names: ... nice(...
ab96675423812a85744bb76e7f62d08bbbac2eea
3,639,060
def get_outputs(): """Get the available outputs, excluding outputs in the EXCLUDED_OUTPUTS variable.""" outputs = [] tree = connection.get_tree() for node in filter( lambda node: node.type == "output" and node.name not in EXCLUDED_OUTPUTS, tree ): workspaces = node.nodes[1].nodes ...
6db1ea83252a7a6f4fd7f731c206c5d4a738a282
3,639,061
def get_user_owner_mailboxes_tuples(user): """ Return owned mailboxes of a user as tuple """ return ((owned_mailbox.id, owned_mailbox.email_address) for owned_mailbox in get_user_owner_mailboxes_query(user))
e7db6658497678387f4a93237b686d29bc27d91f
3,639,062
def modinv(a, m): """Modular Multiplicative Inverse""" a = a % m g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m
9ddea93398f8c96f828a8efaea36f21f6b8dd13e
3,639,063
import socket def get_ip(): """Get the ip of the host computer""" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('1.1.1.1', 1)) IP = s.getsockname()[0] except Exception: IP = '127.0.0.1' finally: s.close() return IP
fb4f79eaa25573d7078f69c5d5ad71c51c9d1c44
3,639,064
def available_structure_info(): """ Lists available attributes for :func:`abagen.mouse.get_structure_info` """ return _STRUCTURE_ATTRIBUTES.copy()
14591c89c9f7212440da282f50408459692d1fc4
3,639,065
def centos(function): """Decorator to set the Linux distribution to CentOS 7""" def wrapper(*args, **kwargs): hpccm.config.g_linux_distro = linux_distro.CENTOS hpccm.config.g_linux_version = StrictVersion('7.0') return function(*args, **kwargs) return wrapper
9c54a7aac46bd30d490c625afa4392d5127a2be7
3,639,066
def Normalized2(p): """Return vector p normlized by dividing by its squared length. Return (0.0, 1.0) if the result is undefined.""" (x, y) = p sqrlen = x * x + y * y if sqrlen < 1e-100: return (0.0, 1.0) else: try: d = sqrt(sqrlen) return (x / d, y / d) ...
42cc78350f264226c624a81ca5b0bd6457d353b0
3,639,067
def findwskeyword(keyword, sol): """Find and return a value for a keyword in the list of the wavelength solution""" i = sol.index(keyword) j = sol[i:].index('\n') return sol[i:i + j].split('=')[1].strip()
b3cc028415d74ecfd7ec3868ae591d7b4d3b8860
3,639,068
import numpy from typing import Tuple from typing import Callable from typing import Union from typing import List def algorithm(array: numpy.array, start: Tuple[int, int], end: Tuple[int, int], heuristic: Callable = manhattan) -> Union[List, None]: """ Returns a list of all points, for the path...
9a91e27bc0dbe78f7b2801dbdfbef6747a845aa7
3,639,069
from . import logger def MFString(string_list): """ input a list of unicode strings output: a unicode string formed by encoding, enclosing each item in double quotes, and concatenating 27 Nov 2016: The complete case is as yet unimplemented, to avoid sending bad X3D into the world will ins...
a068c25ab157b5537ea47e625ca8ed9aecd0f4e5
3,639,070
def re_allocate_memory(ptr: VoidPtr, size: int)-> VoidPtr: """ Internal memory free ptr: The pointer which is pointing the previously allocated memory block by allocate_memory. size: The new size of memory block. """ return _rl.MemRealloc( ptr, _to_int(size) )
806c17a6863db3af8c5b42474fe05c624685757c
3,639,071
import json def get_task_manager(setup_file, **kwargs): """ Create a task manager of a correct type. Parameters ---------- setup_file : string File name of the setup file. kwargs : dict Additional kwargs. Returns ------- manager : TaskManager Created task mana...
a297937fd4520549df034a22739250461cbf2c0e
3,639,072
def format_time(time): """ Converts datetimes to the format expected in SAML2 XMLs. """ return time.strftime("%Y-%m-%dT%H:%M:%SZ")
03651b72aa0b177ac1ac3f1ccafdba6fe967a11a
3,639,073
def get_delivery_voucher_discount(voucher, total_price, delivery_price): """Calculate discount value for a voucher of delivery type.""" voucher.validate_min_amount_spent(total_price) return voucher.get_discount_amount_for(delivery_price)
8ede095730c1d29d01949dff47b4a2893d29720c
3,639,074
def has_admin_access(request): # type: (Request) -> bool """ Verifies if the authenticated user doing the request has administrative access. .. note:: Any request view that does not explicitly override ``permission`` by another value than the default :envvar:`MAGPIE_ADMIN_PERMISSION` wi...
54a109375c60354759d98177a2db275f627034b2
3,639,075
import os import errno def safe_remove(path: str) -> bool: """Removes a file or directory This will remove a file if it exists, and will remove a directory if the directory is empty. Args: path: The path to remove Returns: True if `path` was removed or did not exist, False ...
3f8388f03a38f5933c52323f64cffe189a6652f1
3,639,076
def model_selection(modelname, num_out_classes=2, pretrain_path=None): """ :param modelname, num_out_classes, pretrained, dropout: :return: model, image size """ return TransferModel(modelchoice=modelname, num_out_classes=num_out_classes, pretrain_pa...
ef80dd1c5c52bc0d090801ebb1d5e17f303e48ad
3,639,077
def stack1(x, filters, blocks, stride1=2, dilation=1, name=None): """A set of stacked residual blocks. # Arguments x: input tensor. filters: integer, filters of the bottleneck layer in a block. blocks: integer, blocks in the stacked blocks. stride1: default 2, stride of the firs...
43103a2bcad203b1b32f33e352960bdea8d526c9
3,639,078
def _CreateDynamicDisplayAdSettings(media_service, opener): """Creates settings for dynamic display ad. Args: media_service: a SudsServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. Returns: The dynamic display ad settings. """ image = _CreateImage(media_servic...
c79145ec39a7aed97eea7efe9145eab5c706b146
3,639,079
def contacts_per_person_normal_00x30(): """ Real Name: b'contacts per person normal 00x30' Original Eqn: b'10' Units: b'contact/Day' Limits: (None, None) Type: constant b'' """ return 10
1d0f7caaa4cceafbc34045b2983e388cd1169f8b
3,639,080
def _get_scripts_shell(script_file): # type: (pathlib.Path) -> str """ Returns the shell used in the passed script file. If no shell is recognized exception is raised. Depended on presence of shebang. Supported shells: Bash, Fish, Zsh :param script_file: :return: :raises exceptions.Unknow...
74332334d9b3caf1be720d656ca6e64f4971e35e
3,639,081
from shutil import which def is_cmd_tool(name): """ Check whether `name` is on PATH and marked as executable. From: https://stackoverflow.com/a/34177358 """ return which(name) is not None
a35f84f1bf46aedac488a31402996f075fbe80e2
3,639,082
import pickle def load_model(model: Model, language=()): """Load geo model and return as dict.""" log.info("Reading geomodel: %s", model) with open(model.path, "rb") as infile: m = pickle.load(infile) result = defaultdict(set) for _geonameid, l in list(m.items()): result[l["name"]...
af77d0e0835b8be6b7b87b142141f4c50082a0ae
3,639,083
def saml_metadata_generator(sp, validated=True, privacypolicy=False, tree=None, disable_entity_extensions=False): """ Generates metadata for single SP. sp: ServiceProvider object validated: if false, using unvalidated metadata privacypolicy: fill empty privacypolicy URLs with default value tree...
78f065fe7962e7221626c41b81b550ceaa9e7370
3,639,084
import logging import sqlite3 def import_from_afd(import_list, vlb_path, working_path, conn): """Imports an Armada Fleets Designer list into a Fleet object""" f = Fleet("Food", conn=conn) start = False obj_category = "assault" # shipnext = False for line in import_list.strip().split("\n"):...
65ca2daac7aa798f1bc768ae50409b06129d46c8
3,639,085
import re import os def CWPProfileToVersionTuple(url): """Convert a CWP profile url to a version tuple Args: url: for example, gs://chromeos-prebuilt/afdo-job/cwp/chrome/ R65-3325.65-1519323840.afdo.xz Returns: A tuple of (milestone, major, minor, timestamp) """ fn_mat = (CWP...
550a76de62482a0b5c1b631bd4484d6edafab106
3,639,086
def normalize_not_found(wrapped): """View decorator to make 404 error messages more readable""" def wrapper(context, request): # Replace incoming 404 with one that has a sensible message response = wrapped(_standard_not_found(), request) return response return wrapper
2a9a696c98b777e4f7295015840fbff6235092e7
3,639,087
import functools import os import concurrent def run(cfg, cfg2=None): """ Start preprocessing. """ # Read all log files generated by ebpf_ros2_* # TODO: convert addr and port to uint32, uint16 read_csv = functools.partial(pd.read_csv, dtype={ 'pid':'Int32', 'seqnum':'Int64', 'subscriber':'Int6...
1ce20090d3227feab3fb2cbb211798a518c6da38
3,639,088
def process_results(unprocessed, P, R, G): """Process the results returned by the worker pool, sorting them by policy and run e.g. results[i][j][k] are the results from policy i on run j on graph k. Parameters: - unprocessed: Unprocessed results (as returned by the worker pool) - P: number of po...
24c2854723b3fc33c3fee58595f84d789e861fbc
3,639,089
def make_inline_table(data): """Create an inline table from the given data.""" table = tomlkit.inline_table() table.update(data) return table
c70352de9a716ad5d3f1f33b33ea65c10ebc8f98
3,639,090
def _mi_dc(x, y, k): """ Calculates the mututal information between a continuous vector x and a disrete class vector y. This implementation can calculate the MI between the joint distribution of one or more continuous variables (X[:, 1:3]) with a discrete variable (y). Thanks to Adam Pocock, t...
35b1295739d9df390980db11b7f03976c5ada3de
3,639,091
def get_new_deals_intent_handler(handler_input): """ Purpose: Handler for getting new deals Args: handler_input (Dict): Input data from the Alexa Skill Return: alexa_reponse (Dict): Reponse for Alexa Skill to handle """ feed = get_slickdeals_feed(SLICKDEALS_URL) deal...
7c30af6414a99193d5a7f97f58285b06571c85fa
3,639,092
import argparse import os def make_parser(): """Returns the command-line argument parser for sage-spkg-uninstall.""" doc_lines = __doc__.strip().splitlines() parser = argparse.ArgumentParser( description=doc_lines[0], epilog='\n'.join(doc_lines[1:]).strip(), formatter...
09d03af43b1c1d37a73d319fccb400227e77fed6
3,639,093
def analyse_dataset(imgs, lbls, name=None): """Analyse labelled dataset # Arguments: imgs: ndarray, a set of images lbls: ndarray, labels for a set of images """ if name is not None: print('Dataset: {}'.format(name)) unique_lbl, counts = np.unique(lbls, return_counts=True) min_...
a6eabfab49b4bdc8590b64275ee2d0bcd19b9a0b
3,639,094
def transform(doc, *, sort_keys=False): """reorder""" heavy_defs = ["definitions", "schemas", "responses", "parameters", "paths"] r = make_dict() for k, v in doc.items(): if k in heavy_defs: continue r[k] = v for k in heavy_defs: if k in doc: r[k] = do...
3b939ac3185cdae147709bab1709dd1a39d426c9
3,639,095
from typing import Optional from typing import List def plot_card( box: str, title: str, data: PackedRecord, plot: Plot, events: Optional[List[str]] = None, commands: Optional[List[Command]] = None, ) -> PlotCard: """Create a card displaying a plot. Args: ...
fe1816d045bcf59cb28e29c90e517c79df82c621
3,639,096
def get_cluster_id(url): """ Google assign a cluster identifier to a group of web documents that appear to be the same publication in different places on the web. How they do this is a bit of a mystery, but this identifier is important since it uniquely identifies the publication. """ vals =...
95a5f554560fd219cd07cbd8c8e251e9c8bd4d5e
3,639,097
from typing import List def vol_allocation_factory(covs:List, pres:List=None)->[float]: """ Allocate capital between portfolios using either cov or pre matrices :param covs: List of covariance matrices :param pres: List of precision matrices :return: Capital allocation vector """ if pres is ...
82e707f6d79e0c2b02c5c6f5acb4c6cce130bd4c
3,639,098
import requests def get_inspection_page(**kwargs): """Fetch inspection data.""" url = KING_COUNTY_DOMAIN + DATA_PATH params = INSPECTION_PARAMS.copy() for key, val in kwargs.items(): print(key) if key in INSPECTION_PARAMS: params[key] = val resp = requests.get(url, para...
70c2b95ea6e829f4231c887a59f717a68ede9327
3,639,099