content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def report_cursor() -> tuple[int, int] | None: """Get position of cursor""" print("\x1b[6n") chars = getch() posy, posx = chars[2:-1].split(";") if not posx.isdigit() or not posy.isdigit(): return None return int(posx), int(posy)
daf44e19af3c3644ed8d3f38f719a2123523025e
66,213
import builtins def iscallable(t): """True if type ``t`` is a code object that can be called""" return builtins.callable(t) and hasattr(t, '__call__')
9dc806eff1ebce90d9df8a3f3c53256ef73f0f66
66,216
def extract_body_schema(schema): """Return the body parameter schema from an operation schema.""" matching_body_schemas = filter_params_by_type(schema, 'body') # There can be only one body param return matching_body_schemas[0] if matching_body_schemas else None
1e9f3cc3d6b951148e25f7b48510a3597d5c08bf
66,217
def as_token(ctx: ParserRuleContext) -> str: """ Extract the token for an identifier from the context. Tokens can be: * ID - The name of a JSG definition * idref -- A reference to an existing JSG definition * LEXER_ID - The name of a match pattern definition * LEXER_ID_REF - A reference to an existi...
0ffa87ee71019f1f9e5b3774c1bfe94168d4c8a5
66,218
def calculate_cost(problem: np.ndarray, solution: np.ndarray, k: int) -> float: """ Calculates the overall cost as the L2 norm of the cost vector. :param problem: The problem matrix. :param solution: The solution vector. :param k: The number of folds. :return: The scalar cost. """ retur...
652130c94a48f0c99df6e2567f529ecc654970a1
66,219
import ast def matheval(expr, numtype=float): """ >>> matheval('2^6') 4 >>> matheval('2**6') 64 >>> matheval('1 + 2*3**(4^5) / (6 + -7)') -5.0 """ return eval_(ast.parse(expr, mode='eval').body, numtype)
26469e8f92f67f5a83645be4f06c550c50265264
66,220
def normalize(value, minimum, maximum): """min-max normalization""" if value < minimum: value = minimum if value > maximum: value = maximum return (value - minimum)/(maximum - minimum)
0c1318d71db43eeb27ff59ac743f8909279451b5
66,221
def _normalise_X(X): """Helper function to normalise X using the z-score standardisation""" # get the number of attributes and instances num_atts = X.shape[1] num_insts = X.shape[0] df = pd.DataFrame() for x in X.columns: col = X[x] data = [] for y in range(num_insts): ...
86ae2fef7558db4cdc22da62bce706cd9fce585d
66,222
def recursive_parse_xml_to_dict(xml): """Recursively parses XML contents to python dict. We assume that `object` tags are the only ones that can appear multiple times at the same level of a tree. Args: xml: xml tree obtained by parsing XML file contents using lxml.etree Returns: Python dictionary h...
f9f48396d1de1e21e0122261caff238a6ba82e32
66,223
import platform def _PathForExecutable(executable_name): """Fetches the executable from cloud storage, and returns its path.""" arch_name = platform.GetHostPlatform().GetArchName() return binary_manager.FetchPath(executable_name, arch_name, 'mac')
ec440a58e44231632c5a96d4ad9836385c0c5d29
66,224
def get_baseurl_from_request(request): """Use the request object to build a base url""" assert isinstance(request, HttpRequest),\ "request must be a django.http.HttpRequest object""" urlParts = urlparse(request.build_absolute_uri()) return '%s://%s' % (urlParts.scheme, urlParts.netloc)
a4e89c4694d3651968fccb3a57cf646a0151dfe0
66,225
def us30History( token="", version="stable", filter="", format="json", **timeseries_kwargs ): """Economic data https://iexcloud.io/docs/api/#economic-data Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-resu...
82338c790ce6416355dea0a3f67c38384b0b844e
66,227
from typing import Dict from typing import Any def new_from_at_rest(transaction_type_data: Dict[str, Any]) -> "TransactionTypeModel": """ Construct a transaction type model from at rest (cached storage) """ if transaction_type_data.get("version") == "1": # V1 custom indexes are not supported, ...
67068417bb683cfc4d20cdfcf0345f6ac7d8ac28
66,228
def load_object(module: str, name: str, *, raise_ex: bool = True) -> tp.Any: """Loads the specified object from the specified `module`. Parameters ---------- module : str The (full) name of the module to load the object from. name : str The name of the object to load from the given ...
a8ca051299a7368a7fb1a854e7e5539a63c8b74a
66,229
def validate_tokens_input(func): """check provide key and refresh token from the request and make sure they are all provide and valid""" def dec(request): try: key = request.data['key'] refresh_token = request.headers['Authorization'] if refresh_token == '': ...
57c89efc5c87684be175f0dc4aeec0362250e233
66,230
def sbar(Ss): """ calculate average s,sigma from list of "s"s. """ if type(Ss) == list: Ss = np.array(Ss) npts = Ss.shape[0] Ss = Ss.transpose() avd, avs = [], [] # D=np.array([Ss[0],Ss[1],Ss[2],Ss[3]+0.5*(Ss[0]+Ss[1]),Ss[4]+0.5*(Ss[1]+Ss[2]),Ss[5]+0.5*(Ss[0]+Ss[2])]).transpose(...
cb31f9703126eef4daa569281efad32a9e2542de
66,232
def resize(img, size, interpolation=cv2.INTER_LINEAR): """ resize """ if isinstance(size, int): h, w = img.shape[:2] # hwc min_hw = min(h, w) if size == min_hw: return img percent = float(size) / min_hw rw = int(round(w * percent)) rh = int(round(h ...
e6d0734808f051dea641438c112724420998bb2d
66,233
def _get_version(name): """Get a dataset version.""" if not has_dataset(name): return None return _data_path(name=name, return_version=True)[1]
088232676b1e5d5754b06d48ce3828b82599c430
66,234
def jobscript_get_exec_prefix(jg : JobGeneration): """ Prefix before executable Returns ------- string multiline text for scripts """ content = "" content += jg.runtime.get_jobscript_plan_exec_prefix(jg.compile, jg.runtime) return content
58f7ffede5369ea150e0f882b871bfba22683261
66,238
def get_log_dirs(parent_path,prog_name): """get logs paths""" ### high priority at the begin of the list ### low priority at the end of the list pathnames_list=[] pathnames_list.append( pathnames.get_log_dir(prog_name,PROG_PUBLISHER) ) pathnames_list.append( pathnames.join_pathname(parent_path,LOGS_DIRECTORY) ) ...
21501cd871d88811ae77f668385fe693ce4e2655
66,241
def get_valid_values(value, min_value, max_value): """Assumes value a string, min_value and max_value integers. If value is in the range returns True. Otherwise returns False.""" valid_values = [i for i in range(min_value, max_value + 1)] try: value = int(value) except ValueError: ...
4385f8328cfbe6497f7a723be37e54f0a86f9fbf
66,242
import torch def _spherical_harmonics_l0(xyz): """Compute the l=0 Spherical Harmonics Args: xyz : array (Nbatch,Nelec,Nrbf,Ndim) x,y,z, of (Point - Center) Returns Y00 = 1/2 \sqrt(1 / \pi) """ return 0.2820948 * torch.ones_like(xyz[..., 0])
83831d0a140d85dc356ae04bcbaeeda74c5a9fee
66,243
def sanitizeString(string: str) -> str: """ Sanitize a string to be safe for filenames Args: string: String to sanitize for filenames Returns: Version of input string safe for filenames """ return string.replace("|", "-").\ replace("/","-").\ replace("\\","-").\ ...
c0aefd6c7af0aca9c1bdd4071b9e76041731c183
66,244
def upload_lu(v_uuid, lu, io_handle, f_size, sha_chksum=None, upload_type=UploadType.IO_STREAM): """Uploads a data stream to an existing SSP Logical Unit. :param v_uuid: The UUID of the Virtual I/O Server through which to perform the upload. :param lu: LU Wrapper representi...
c240697565cf975a3542d493f91a9537753188e0
66,245
def top_1_acc(output, target): """ Computes the top 1 accuracy """ return top_k_acc(output, target, k=1)
3ae7d2faf996144ed112a8a752df94494777b7df
66,246
def add_DenseNet_convX_body(model, block_counts, dim_in, dim_inner, group_rate): """Add a DenseNet body from input data up through the res5 (aka conv5) stage. The final res5/conv5 stage may be optionally excluded (hence convX, where X = 4 or 5).""" freeze_at = cfg.TRAIN.FREEZE_AT assert freeze_at in...
9deb1898d37a77beffd47d3237954157af4b1faf
66,247
def index_all(elm, lst): """return list[int] all positions where elm appears in lst. Empty list if not found""" if type(list)!=list: lst=list(lst) return [i for i,e in enumerate(lst) if e==elm]
0db325714d6c8de5b1a1fbb516287c56931cf0a9
66,248
def ValueIteration(gamma=0.95, th=0.01): """ value iterationで全状態の価値評価する. はじめ,すべての状態は価値0とする. 以下の価値更処理をすべての状態に行う.何度も繰り返し,更新幅がth未満になったら終了. ・終了状態に遷移できたら,その状態の価値を1とする. ・遷移可能な状態のうち最大価値に割引率gammaをかけたものをその状態の価値とする. 繰り返しごとに終了状態に近いものから順に価値が伝搬していくイメージ. return:状態価値テーブルV """ actions = list(ran...
9422371711fdb01a26f1219870751edb63d8d4de
66,251
def _get_effective_credentials(cli_ctx, existing_credentials, account_name): """Returns AzureStorageCredentialInfo for the account :param models.AzureStorageCredentialsInfo existing_credentials: known credentials :param str account_name: storage account name :return models.AzureStorageCredentialsInfo: ...
dddcfcc98400ef30884320768e29f72d3623dba5
66,253
import logging def add_phab_project(project_information, project_columns): """Add a project on Phabricator. Parameters ---------- project_information : dict project_columns: dict """ logging.info("Adding Phabricator project.") name = project_information[project_columns["english_name"]...
9d21d281e110d41606461bc799a6071b2e47f1b7
66,254
def mixture_mse(params, targets, **kwargs): """Given log-unnormalized mixture weights for equi-spaced truncated Gaussians on the unit interval, return the likelihoods for targets. (Currently unused.) Args: params: N x d x 3*ncomp tensor of parameters of mixture model. targets: N x d x 1 ...
f6c908c8d518f1b35941915b58ff316f034c40c2
66,255
def socfaker_timestamp_current(): """ The current timestamp Returns: str: Returns the current timestamp in ISO 8601 format """ if validate_request(request): return { 'value': socfaker.timestamp.current }
833ab3b23194ef033065f340826dc21d4098ba4c
66,256
def get_lines(file_path): """ get all lines in file """ with open(file_path, encoding='utf-8') as data_file: lines = map(lambda line: line.strip(), data_file.readlines()) return lines
caf42286bc985c609076cb31432242552483a661
66,257
def str_of_max_length(length): """Validate that the value is a string with a max length.""" def validator(instance, attribute, value): instance_of(str)(instance, attribute, value) if len(value) > length: raise ValueError( '{0.name} must be at most {1} chars, ' ...
2b2dc062026b1c81f6b984669f169cd96bda57da
66,258
def version(server, component=None): """ Returns the version of the specified component. If *component* is None, then a list of all of the components available will be returned. :param CasparServer server: The :py:class:`~caspartalk.CasparServer` that the *amcp_command* will be sent to. :param str ...
642d80ede6afee88484095f631b1b194e32fac4b
66,259
from typing import Dict from typing import Any from typing import Optional from typing import List import logging def gather_gene_dict_from_contig( contig: str, variant_source: cyvcf2.VCFReader, config: Dict[str, Any], panelapp_data: PanelAppDict, singletons: bool, blacklist: Optional[List[str...
25219bc32531602c44db202bde350be9402c5b18
66,260
import socket def translate_addrmask(af, addr): """Validate IP address""" addr_mask = addr.split("/") try: socket.inet_pton(af, addr_mask[0]) except socket.error: raise BadRequestError("Invalid IP address") # Test v4 or v6 mask max_cidr_prefix = 32 if af == socket.AF_INET else...
bc2a20c5f7ee803cf908e8f710ce62bc3b5e1dea
66,263
import asyncio async def network_list(cluster_id: str): """Get All Virtual Network from cluster""" try: session = create_session( _id=cluster_id, get_xen_clusters=Settings.get_xen_clusters() ) networks = Network.get_all(session=session) __santilized_networks = awa...
85f4aa966ecb4e09221b48ce91d0cb03f4e73312
66,264
def train_dgcnn(graphs, graph_labels, n_epochs=50): """ Build and train DGCNN model """ generator = PaddedGraphGenerator(graphs=graphs) k = graphs[0].number_of_nodes() # the number of rows for the output tensor, no truncation # done here because all graphs have same number of nod...
3af30a8189f905a5c7b898b9013721d687cc5549
66,265
def modelSimilarity(ex_submodel, ex_ts, valid_new_submodel, new_ts, submod_type): """ This function calcualtes the evaluation measure for the run. ex_submodel = (DataFrame) either existing/expert demand_summary or hourly_profiles submodel valid_new_submodel = (DataFrame) output from dataIntegrity f...
cf1bb5076d52eec159100527718171f75582574f
66,266
def _GKEConnectNamespace(kube_client, project_id): """Returns the namespaces into which to install or update the connect agent. Connect namespaces are identified by the presence of the hub.gke.io/project label. If there are existing namespaces with this label in the cluster, then a list of all those namespaces...
d8d1e666fb28e4c44fd9880b7234dc5cd9cec637
66,267
import torch def lm_forward_step(data, model, args, timers, mems, eval_metric=None): """Forward step.""" # Get the batch. if timers is not None: timers('batch generator').start() if 'mask' in data: data['attention_mask'] = data.pop('mask') tokens, labels, loss_mask, attention_mask...
0db8ea0f3e7ebca0287e0fd0f1c68bd3fa848147
66,268
def load_vars(basepath, results, vault_password=None): """ Load variables from any potential yaml filename combinations of basepath, returning result. """ paths_to_check = [ "".join([basepath, ext]) for ext in C.YAML_FILENAME_EXTENSIONS ] found_paths = [] for path i...
721391474076e92e6b1ffd260d7630716e45d881
66,269
def print_pred(query, corpus, model): """Prints details about input query relative to a corpus and model: - The cleaned query text - The bag of words - Query topic predictions - Topics for individual words from the query.""" def word_topics(word_id): return(model.get_term_topics(wor...
90cf10e19a91ad7ceb545f47e74b2e50db2def7f
66,270
async def url_callback_func(fetcher, range_stream, url): """ Async function which puts the URL onto the storage class's list of values """ return CallbackMutatedClass.values.append(url)
0de9f98378ad3a18e4c4d7b0bc836b900938f6ca
66,271
import struct def short_string(value): """ Encode a string. :param value: Value to encode :type value: bytes or str or unicode :rtype: bytes :raises: TypeError """ if PYTHON3 and not isinstance(value, (bytes, str)): raise TypeError('bytes or str required') elif not PYTHON3 an...
95de1b4aa1e92a8a265913a9fc7b88940cb8e23f
66,272
def example_check_main_engine(app_configs=None, **kwargs): """ Check for existence of the "Main engine" component in the database """ # your check logic here errors = [] logger.info("Our check has been called :]") if not Component.objects.filter(title="Main engine").exists(): errors...
b65f2001a12e50da72ace09eff5e7ea71df0fcff
66,273
def shift_objects(data, solar_za, solar_az, sensor_za, sensor_az, h, num_workers): """ Shifts objects along x and y dimensions Args: data (DataArray): The data to shift. solar_za (Da...
59aca73ebf57f2911ab2d3a8a39643b8d570c690
66,274
def build_A_analytical(material_property_library, mesh, materials): """ While not intended for long term use, this function demonstrates that our steady state model matches the analytical solution. inputs: material_property_library contains relevant material data mesh contains the radial positions of ...
d3f9b0d46852b1664018b0a941b84c07818fd2e1
66,275
def earthsun_distance(unixtime, delta_t, numthreads=1): """ Calculates the distance from the earth to the sun using the NREL SPA algorithm described in [1]. Parameters ---------- unixtime : numpy array Array of unix/epoch timestamps to calculate solar position for. Unixtime is t...
8d06d5e61de386d987bec07af351420db87b2c10
66,276
def backward_prop(data, labels, params,lamb=0.0): """ return gradient of parameters """ W1 = params['W1'] b1 = params['b1'] W2 = params['W2'] b2 = params['b2'] ### YOUR CODE HERE h, y, cost = forward_prop(data,labels,params) y = y-labels gradW2 = h.T.dot(y) gradb2 = np.s...
578ddeea44398cfc1565195b1880728c0b3575e4
66,277
def list_available_networks(caller_id): """ @cmview_admin_cm @response{list(dict)} AvailableNetwork.dict property for each requested AvailableNetwork """ response = [] for network in AvailableNetwork.objects.all(): response.append(network.dict) return response
b8bcf54acbe85bed1e36968fed1c1cac4a122854
66,280
import logging def blocking_prob(n_servers, n_sources, total_traffic, alg=Algorithm.NEWTON, max_n_iters=1024, tol=pow(2, -24), **kwargs): """Blocking probability in the Engset model. Parameters ---...
36ce12e60589519270fffe2960f794835774b662
66,281
def update(): """ Update me """ req_data = request.get_json() data = personal_schema.load(req_data, partial=True) if error: return custom_response(error, 400) user = personalModel.get_one_student(g.user.get('id')) user.update(data) ser_user = personal_schema.dump(user) return custom_response(se...
049966c6877ef59f3bcd651736f4e69a8c466361
66,282
import select def win32select(r, w, e, timeout=None): """Win32 select wrapper.""" if not (r or w): # windows select() exits immediately when no sockets if timeout is None: timeout = 0.01 else: timeout = min(timeout, 0.001) sleep(timeout) return [...
d909eefa6576b41373869a3f5fa4c02245bfde7b
66,283
def rbf_svm_classify_roc(X_train, X_test, Y_train, Y_test): """ Parameters ---------- X_train : numpy.ndarray training feature vectors X_test : numpy.ndarray testing feature vectors Y_train : numpy.ndarray training set labels Y_test : numpy.ndarray test se...
a9da4c635f27d8ef7a324ecfa26e343db3fda6b5
66,284
def _sbprofile_colors(): """Return an iterator of colors good for the surface brightness profile plots. https://seaborn.pydata.org/generated/seaborn.color_palette.html#seaborn.color_palette """ _colors = sns.color_palette('Set1', n_colors=11, desat=0.75) colors = iter([ _colors[1], _colors[2], _col...
dd0d0f5fef44032d3fbcecaa35a267fddfa3e896
66,285
def dice_loss(y_true, y_pred, smooth=1e-6): """ Loss function base on dice coefficient. Parameters ---------- y_true : keras tensor tensor containing target mask. y_pred : keras tensor tensor containing predicted mask. smooth : float small real value used for avoiding di...
8f2011e60308a57d6abba71c4fce0cb042db1d24
66,287
def render_form(parser, token): """ render_form takes one argument in one of the following formats: {% render_build_form form_instance %} """ try: _, arg = token.split_contents() arg = "form=" + arg name, value = arg.split("=", 1) except ValueError: raise templa...
c32b91299700283a6ab5a5269f2f39a4856d5b44
66,288
def produce_phrases(file): """ Function, which implements all the magic with Markov's chains. As you can see, looks pretty easy:) @param file: input file, consisted of text to be converted into sensible phrases @return: "sensible phrases of MIPT teachers" """ with open(file, "r", enc...
e7ab6e22ce1fa5b8a01995b67159499fdbcdc280
66,289
from pathlib import Path import json def load_processing_unit(unit_path): """Load a :class:`ProcessingUnit` from a persisted processing unit directory""" unit_path = Path(unit_path) with (unit_path / "metadata.json").open(encoding="utf8") as f: metadata = json.load(f) unit = _get_unit_type...
15650de7c6724287d0e4ee0f204852e70da21320
66,290
def get_meraki_device_clients(org_name, device_name): """Query Meraki for Clients.""" dashboard = meraki.DashboardAPI(suppress_logging=True) return dashboard.devices.getDeviceClients(_name_to_serial(org_name, device_name))
9682132355feb59b943edf856fb0d5ff59bd5a97
66,291
def rec_to_bintable(arr, name=None): """ Construct an `astropy.io.fits.BinTableHDU` from a record array. Args: arr (`numpy.recarray`): The data array to write to a binary table. name (:obj:`str`, optional): The name for the binary table extension. Returns: ...
fd1aeda99cf3bb45a24b646afbf263610a19175d
66,292
import http def node_identifiers_post(auth, node, **kwargs): """Create identifier pair for a node. Node must be a public registration. """ if not node.is_public or node.is_retracted: raise HTTPError(http.BAD_REQUEST) if node.get_identifier('doi') or node.get_identifier('ark'): raise HT...
ab0d799b40925333476fd331a09b9a4b36143e0b
66,294
def getPluginsDisabled(): """ Return the names of plugin that were disabled. """ if not options: return () return tuple(set(options.plugins_disabled))
0feb34a7d4a840f3828a8f6939944d29de23b915
66,295
def match(pattern, text): """Match pattern against start of text; return longest match found or None.""" remainders = matchset(pattern, text) if remainders: shortest = min(remainders, key=len) return text[: len(text) - len(shortest)]
4bbe38e1f459a9e57cf13f3afb77edbdf110df7b
66,296
def getClasspathOptions(): """gets the classpath of the vmx86 distributions""" return mx.get_runtime_jvm_args(['VM', 'VMX86_LAUNCHER', 'CORE', 'POSIX'])
b53420a14a0fb6192a83e11fe7927b5a0fb6ef32
66,299
import socket def get_local_usable_addr(): """Get local usable IP and port Returns ------- str IP address, e.g., '192.168.8.12:50051' """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable sock.connect(('10.255.255.255'...
d7dfb57a755c5f96ae2e1e5864d5e6b66d45e2cd
66,300
def create_example_randomizer_cata() -> DomainRandomizer: """ Create the randomizer for the `CatapultSim` used for the 'illustrative example' in F. Muratore et al, 2019, TAMPI. :return: randomizer based on the nominal domain parameter values """ return DomainRandomizer( BernoulliDomainParam...
6909e7b28454a3343d92ac5a6ce3af680216a85b
66,301
def boost_with_rotation_to_lab(four_vecs, rot, inv_rot): """rotated back, boost the 4 vecs, rotate again very ugly.. """ arr = [] for fv, rotation, inv_rotation in zip(four_vecs, rot, inv_rot): e = fv.item(0) p = fv[:, [1, 2, 3]] p = inv_rotation * p.T fv = np.mat...
496748f52cc4689020e48d83ce9cde3426aea043
66,302
import itertools def powerset(iterable): """All *nonempty* subsets of an iterable. From itertools docs. powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) """ s = list(iterable) return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(1, len(s)+1))
875e4cacc9f1abf92604e89c7a6211e571150b69
66,303
import base64 def __decode(encoded, n): """ decode the string """ token = encoded.split(":")[0] for _ in range(0, n): token = base64.b64decode(token) return token
9ac3ba6da27ae255117b25c5f1c61f35d06c2c2e
66,304
def _exact_instance_filter(query, filters, legal_keys): """Applies exact match filtering to an Instance query. Returns the updated query. Modifies filters argument to remove filters consumed. :param query: query to apply filters to :param filters: dictionary of filters; values that are lists, ...
ffa8e827903e3400f1c0aa0273bb0714827891e0
66,305
import numpy def smooth_waterfall(arr,fwhm=4.0,unsharp=False): """ Smooth a waterfall plot. If unsharp set, remove the smoothed component Input array should have dimensions [timelen, nbolos] """ timelen,nbolos = arr.shape kernel = numpy.exp(-numpy.linspace(-timelen/2,timelen/2,timelen)*...
849b144a63b1209523e588724531e5cd24269e76
66,306
def load_graph_from_ckpt_file(weights_path): """ :param weights_path: :return: """ # construct compute graph input_tensor = tf.placeholder(dtype=tf.float32, shape=[1, 512, 512, 3], name='input_tensor') net = resnet_fcn.ResNetFCN(phase='test', cfg=CFG) prediction = net.inference( ...
91dfc03a5cf62b0624b97660b5daa6532beefeb0
66,307
from typing import Dict async def get_backend_auth_headers(session: ClientSession) -> Dict[str, str]: """ Authenticates with the OC Backend server :return: Authorization header containing the returned JWT """ async with session.post( f"{BACKEND_URL}/auth/login/", json={"email": B...
72e6d9bb9c8467f7e5cd1379b5ae3ad8b7aab64e
66,308
from typing import Tuple from typing import List def _get_package_names_for_distribution( distribution_path: str, ) -> Tuple[List[str], str]: """Get the top-level import names and project name for a given distribution file path Args: distribution_path: Path to the .whl, .tar.gz, or .zip file cont...
866046a8f23d5c80534cbb500fb875efd42c2fa7
66,309
def find_geom(geom, geoms): """ Returns the index of a geometry in a list of geometries avoiding expensive equality checks of `in` operator. """ for i, g in enumerate(geoms): if g is geom: return i
2c2c9c2230ae745b6a781337192c694ba4ba4c59
66,310
def calculate_saliency_map(model: Model, data: np.ndarray, c: int, dependencies=None, normalise=True) -> np.ndarray: """ https://arxiv.org/abs/1312.6034 - saliency maps https://arxiv.org/abs/1706.03825 - smoothed version Calculates saliency map / vanilla gradient for feedforward neural network. Calculat...
0e0f841995236ce0e2adf36960dc4232a0fd0333
66,311
from typing import List from typing import Tuple def cluster_state(m: int, n: int, inputs: List[Tuple[int,int]]=[]) -> BaseGraph: """Build a cluster state m qubits tall and n qubits wide. Optionally, give a list of grid positions which serve as inputs.""" g = Graph() vs = [[g.add_vertex(VertexType.Z, ...
09e338650bcc040f02db7b9d7ee6fc171137ed43
66,312
def add_two_numbers(value1: int, value2: int) -> int: """Method to add two add_two_numbers ARGUMENTS: Value1: first value Value2: second value """ try: return value1 + value2 except TypeError as error: print('Error at add_two_numbers()', error) exce...
de4c3b1bd5ebd69fd2ff1dbc63a411f875841d8e
66,313
def summary_table(params, proteins): """ Returns a string representing a simple summary table of protein classifcations. """ out = "" counts = {} for seqid in proteins: category = proteins[seqid]['category'] if category not in counts: counts[category] = 1 ...
1fa3f16f799964bf9f1c0f1c593020902ab2219f
66,314
def add_leading_zeroes( number, digits ): """ adds leading zeroes to fill up the digits. """ number = int( number ) string = str(number) i = 1 while i < digits: if number < 10 ** i: string = '0' + string i += 1 return string
4437a3f930f5947ae749f34a07edd1a68fc6e077
66,315
def instance_has_unpaused(instance, log_files, alarms, event_logs, alarm_history, start_datetime, end_datetime, action=False, guest_hb=False): """ Returns true if the instance has unpaused """ success, reason = instance_is_running(instance) if not ...
e8afd87130bad0a2a923c6c1555bab82694d85d2
66,316
def foreign_key(other_table, nullable=False): """ Declare a foreign key property, which will also create a foreign key column in the table with the name of the property. By convention the property name should end in "_fk". You are required to explicitly create foreign keys in order to allow for one-to-...
ff837bf20ab423772dce93dec88a9b83857cacb5
66,317
def propertize(fieldKeyName): """Transforms a string into an Python parameter name """ return stringcase.snakecase(fieldKeyName)
4b8b463953500ce0a3848e70709bbbda7817f4fd
66,318
from datetime import datetime def get_default_datetime(): """ A hook to help with mock data testing - put the default datetime right in the middle of the "current" term. """ if is_using_file_dao(): term = get_current_term() first_day = term.first_day_quarter default_date = ...
7b97bebb400653f91139ace6b5cdda1961a7f38f
66,319
def get_map(nmers, vocabulary, vectors=None, mapping='random'): """ Prep and get a map. """ N = len(nmers) W = len(vocabulary) if W < N: print 'ERROR: Not enough words.' return False if W > N: print 'There are', W, 'elements in the vocabulary and only', N, pri...
c6de0401bb1030fc4135c79c24ebbc894b7e1156
66,320
def diapreresnet110_cifar10(classes=10, **kwargs): """ DIA-PreResNet-110 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, de...
baf61449f48a25c85e98dcdeef6107652d676e7a
66,321
from typing import Sequence def pad_image_to_shape(img: npt.ArrayLike, new_shape: Sequence, mode: str = "constant"): """Pad all image axis up to specified shape.""" for i, dim in enumerate(img.shape): if dim < new_shape[i]: pad_size = (new_shape[i] - dim) // 2 img = pad_image(i...
87652efad525263b428be4347cab18c76cae30e0
66,322
import PIL def is_corrupt(jpegfile): """Returns None if the file is okay, returns an error string if the file is corrupt.""" # http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted/1401565#1401565 try: im = PIL.Image.open(jpegfile)...
bf0b284e2df49c079f1cc260d492aca963fba6a5
66,324
from apex import amp def train(args, train_dataset, model: PreTrainedModel, tokenizer: PreTrainedTokenizer) -> Tuple[int, float]: """ Train the model """ if args.local_rank in [-1, 0]: tb_writer = SummaryWriter() args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) def ...
89e16027e0eeef4d69323354977357b705375137
66,325
import math def is_valid_sample_rate(rate): # type: (Any) -> bool """ Checks the given sample rate to make sure it is valid type and value (a boolean or a number between 0 and 1, inclusive). """ # both booleans and NaN are instances of Real, so a) checking for Real # checks for the possib...
77542d10f7c379d565dcf3e66bc2cd5e22322d3f
66,326
import random def random_password(): """ 随机生成一个8位的数字的字符串 :return: """ password = "" for i in range(8): password += str(random.randint(0, 9)) return password
d7f83d4e01c79166d6b116c40622c82148252c30
66,327
import functools import time def log_service_time(func): """Loga o tempo para o serviço da requisição. Nenhuma exceção relacionada a medição deve causar erro no serviço da requisição. """ @functools.wraps(func) def wrapper(req): start_time = time.time() result = func(req) e...
588ce561ce7c47eb72fe207f116698b014c4bf0c
66,328
def partition_to_lists(items, predicate=bool): """ Partitions an iterable into two different lists - the first does not match the given condition, and the second does match the given condition. Args: items (iterable): An iterable of items to partition predicate (function): A function th...
1c2fe99b8ae7972738ca9028b65135bbfd1dab83
66,329
def on_board(i, j): """Return True if the location is on board >>> on_board(0,0) True >>> on_board(-1,17) False """ return 0 <= i < 8 and 0 <= j < 8
107f9e614c965b29c0c872738fd4ea5407971a29
66,330
def multiplicative_inverse(e, phi): """ Euclid's extended algorithm for finding the multiplicative inverse of two numbers """ d, next_d, temp_phi = 0, 1, phi while e > 0: quotient = temp_phi // e d, next_d = next_d, d - quotient * next_d temp_phi, e = e, temp_phi - quotient *...
9934f6e2f86ff0ef4165728d59f11ba0d1cad928
66,331
def check_contradiction(statement1, statement2): """ Check if two statements are contradictory ignoring the time dimension. :param statement1: the first statement :param statement2: the second statement :return: """ if not (statement1.arguments[0][0].startswith("e") and statement...
fa0a485d68ece3a6ead3c41a017b58926273f42d
66,332
def sort_models_by_encoding(models_list: list) -> list: """ Sort models by the encoding that will be used :param models_list: unsorted list of models :return: list of models sorted by encoding """ encodings = [get_mapping_name_to_class()[model_name].standard_encoding for model_name in models_l...
a45fea6ce8aa9f166340a0c1d181a1d06db1a7d9
66,333