content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import tensorflow as tf def deserialize_keras_activation(activation): """ serialize keras activation Args: activation (str, dict, or Activation object): activation to serialize Returns: Activation object """ if isinstance(activation, str): return tf.keras.activations.get(act...
e6fc4892a207b82ade82a13ac5fa49e313b46b6c
74,825
from API.BTC import get_btc_price import requests async def btc(): """ This give you the current price of Bitcoin.<br> <pre> :return: RAW<br> </pre> Example:<br> <br> <code> https://server1.majhcc.xyz/api/BTC </code> """ try: return get_btc_price() except Ex...
4c0eea0909c6a02b4923acf34efa1b2f8e516166
74,826
def RebuildGeomNodesToColPolys( incomingNodes ): """ Converts GeomNodes into CollisionPolys in a straight 1-to-1 conversion Returns a new NodePath containing the CollisionNodes """ parent = pm.NodePath( 'cGeomConversionParent' ) for c in incomingNodes: gni = 0 geomNode = c.n...
517dac8faf6ba7a80f4ac8f84254b00265fba23c
74,828
def quinton(matrix, figax=None, **kwargs): """ Quinton Plot for a given (square) matrix """ # set the matplotlib axis, or make one if not given if figax is None: fig, ax = plt.subplots(figsize=(4, 4)) else: fig, ax = figax # see if hilbert dimension is given, otherwise set ...
53bf12a17e750337d10fb848b494c10708dc2325
74,829
def strip_processor(): """remove spaces around all strings""" def apply_replace(row_set, row): def replace(cell): if isinstance(cell.value, basestring): cell.value = cell.value.strip() return cell return [replace(cell) for cell in row] return apply_rep...
1c39dcf7be5abd068169f0501593a4b01e1ccf5c
74,830
def get_admin_context(show_deleted=False, all_projects=False): """Create an administrator context. :param show_deleted: if True, will show deleted items when query db """ context = RequestContext(user_id=None, project=None, is_admin=True, ...
984489dd7ff18b4fbcddca0d7740c55765ed10e6
74,831
from typing import Dict from typing import Any def flow_information(flow: "prefect.Flow") -> dict: """ Get flow information Args: - flow ("prefect.Flow"): the flow whose attributes to retrieve Returns: - dict: a dictionary of informative flow attributes """ def _replace_valu...
bdb6aaf5bb59cef60336b0a8852e90251a0f2b3a
74,833
from typing import List from typing import Tuple def all_accuracy_average(accuracies: List[Tuple[Measures, Measures]]) -> Tuple[Measures_std, Measures_std]: """Return the average of all accuracies.""" return ( get_average([accuracy for accuracy, _ in accuracies]), get_average([total for _, tot...
040c19a3763f06feca2131d315c25c17bce419b6
74,834
def compute_dsc(predicted_map, target, no_class): """average DSC scores across subjects in a batch""" # to one-hot predicted_map = expand_as_one_hot(predicted_map.squeeze(1).long(), no_class).cpu().numpy() target = expand_as_one_hot(target.squeeze(1).long(), no_class).cpu().numpy() # DSC organs_...
89c3d923b445782229f5fed8b3c7e9088f0cceff
74,835
def pathGen(): """Classpath generator, \ works with SBT launcher to install dependencies and emit classpaths""" return Artifact("com.scleradb", "sclera-install-pathgen")
b8348753ec9ceb5971733d4f0c960789c18d20ec
74,836
import logging def get_links(url=None, headers=None, html_parser='html.parser'): """Scrape index/archives for links to blog posts to be scraped.""" # Defaults for testing. if url is None: url = DEFAULT_ARCHIVES if headers is None: headers = DEFAULT_HEADERS _, entry_content = get_e...
a6d4dfc8f87aed20d4c022039eb68146aa18d518
74,837
def exc_isinstance(exc_info, expected_exception, raise_not_implemented=False): """ Simple helper function as an alternative to calling `~.pytest.ExceptionInfo.errisinstance` which will take into account all the "causing" exceptions in an exception chain. Parameters ---------- exc_info : `py...
7e53dd94b7326faea1fe5accdc60b1b3b003f0af
74,838
from pathlib import Path def to_absolute_path(path): """ converts the specified path to be absolute path. if the input path is relative, it's interpreted as relative to the original working directory if it's absolute, it's returned as is :param path: :return: """ path = Path(path) ...
72c2be994c2fdbe53957f52f131788ace7befa11
74,839
def streaming_panoptic_quality(groundtruth_categories, groundtruth_instances, predicted_categories, predicted_instances, num_classes, max_instances_per_category, ...
77421fa9c381f471483215f0de782f22b1cefa3b
74,840
from datetime import datetime def timestampStr(): """ A simple timestamp function that returns the current date and time as a string. """ return datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
4beb8a9a7f620492c83d01d7dfa16d79dbd6b007
74,841
def g2c(tensor): """ Reshape from groups, channels to groups*channels """ if len(tensor.shape) == 5: b, c, g, h, w = tensor.shape tensor = tensor.reshape(b, c*g, h, w) return tensor
18517b066dfad91c9e8708fb94058b2780ddab9c
74,842
def getcallargs(*func_and_positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" func = func_and_posi...
5efc417bdd8b935316d30a5afb0c50117a6477a2
74,843
from pathlib import Path from unittest.mock import call def lint(): """get that linty fresh feeling""" def call_with_print(args): str_args = [a for a in args if isinstance(a, str)] paths = [a for a in args if isinstance(a, Path)] print(f"{len(paths)} paths:", " ".join(str_args)) ...
d6e6c694f93b7fe002e511ae01e505d6276b1f58
74,844
import json def get_s3_key(conn, bucket, key, filename): """ Return the key contents for a specific s3 object :param bucket: the bucket to connect to :param key: the key of the bucket object :param filename: the file name of the s3 object :returns: data in the form of a string or D...
36c3c9346b93f8a42d8f5db14b50cdcbc4eec9ec
74,845
def max_column_width(column): """ Max width of a column, looping over all column elements """ return column \ .apply(lambda x: len(str(x))) \ .max()
30dadff91586ed8c270a78aa44ab3fc875ef706e
74,846
import torch def dqn(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995): """Deep Q-Learning. Params ====== n_episodes (int): maximum number of training episodes max_t (int): maximum number of timesteps per episode eps_start (float): starting value of epsilo...
ba2e99e0aa5d8362072e54a2a555366b5dc4fd62
74,847
import math def get_frame_and_channel(event): """ Returns a tuple of (frame, channel) """ frame_float, channel_float = bpy.context.region.view2d.region_to_view( x=event.mouse_region_x, y=event.mouse_region_y ) return round(frame_float), math.floor(channel_float)
546184f9ad8765f692f48a789b2f220fbd627c79
74,848
from typing import List def readfile(filename: str) -> List[str]: """Wrote by: Nicholas Garth 101227727 Reads file from filename and returns a list of every line of the file >>> readfile(hi.txt) ['Hi'] """ infile = open(filename, "r",encoding="UTF-8") records = [] for line in infile: ...
5e71dd5b23221e509ee7d7feeff0241e0177298e
74,849
def ident_serie(stream: t.List[str]) -> t.List[AST]: """([a-zA-Z])+""" if [*filter(lambda s: not s.isalpha(), stream)]: raise SyntaxError("Unexpected character.") return [*map(AST, stream)]
8911f52c78dd8fc3bd6f778cad10e3c1d19a1c21
74,850
def getsdb(surface: Surface, x: Sequence4) -> float: """Get signed distance bound. Args: x: Position 4-vector. """ return surface.getsdb(x)
971c9355ce3b11da1e34ec0ccd67372bc2761469
74,851
from PyQt6.QtGui import QColor from typing import Tuple from typing import List from typing import Union def convert_stylemap_index_color( style: 'Styler', as_qt: bool = True, first_val: bool = True) -> Tuple[dict, dict]: """Convert (irow, icol) stylemap to dict of {col: {row: QColor(value...
16fcf01ac5dea138690bb2a7888ff2dffcecadf1
74,852
def function_2(x,y): """ Have function_3 do all the work """ return function_3(x,y)
8798c592b8132b9ba91cb9b68b8508d3df662841
74,853
def td_prediction(env, gamma, alpha, nA, total_episodes): """ 训练 """ V = defaultdict(float) for k in range(1, total_episodes + 1): current_state = env.reset() while True: prob_scores = get_action_policy(current_state) current_action = np.random.choice(np.arang...
5458d4c1abc9b5c70dd2ab57d1001e16ca20f5a2
74,854
import torch def collate_dataset(batch, test=False): """ Preprocessing for given batch. It will use for the Torch DataLoader(collate_fn=collate_dataset). Args: batch(Torch.Tensor) return: List(Torch.Tensor) """ drug_batch = [] protein_batch = [] y_batch =...
9eec71d5fe994bd6bb6742d2eb667ad0dda1bae1
74,855
import ssl import json def get_kubernetes_json(): # pragma: no cover """Get the status of the system, in JSON, from the kubernetes server.""" context = ssl.create_default_context() context.load_verify_locations( '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt') token = file('/var/run/se...
2a06711568c38105246be9347d845c587a752e6e
74,856
def CalculatePlatt(mol): """ Calculation of Platt number in a molecule Parameters: mol: RDKit molecule object Returns: Platt: Platt number """ cc = [x.GetBeginAtom().GetDegree() + x.GetEndAtom().GetDegree() - 2 for x in mol.GetBonds()] return sum(cc)
4a960308487fea60857a3ed2268efcd5342099d2
74,857
import http import requests def check_url_ssl(domain_name): """Check if the domain has a valid SSL certificate. :param domain_name: Domain name to check SSL for. :type domain_name: str :return: Returns `True` if valid, `False` otherwise :rtype: bool """ global url try: if "htt...
6f059d5fd333e3d7e9ec2aa919741b0a41470f8e
74,858
def mock_dbhelper(subscriptions_db_list) -> DBHelper: """Returns mock for DBHelper for get_subscription by name from database""" mock = DBHelper mock.get_all_subscriptions = MagicMock(return_value=subscriptions_db_list) return mock
7a8417066529717d43b8b88fa9cc7d4e86dafef3
74,859
def node_realtime_info(): """ :return: """ try: client_sys_info = {} fdfs_mon = os.popen("/usr/bin/fdfs_monitor /etc/fdfs/client.conf").read() fdfs_mon_tmp = fdfs_mon.split("Group") except Exception, e: log.info("error in execute node_realtime_info") fdfs_mon_...
67c6a556e8e39b7a273ae95602753dfc7615d30a
74,860
def is_boring(arr): """Given an array of pangrams, return True if any two of those pangrams are boring, False otherwise.""" arr = [s.lower() for s in arr] for i, j in permutations(arr, r=2): if set(i) == set(j) and ( i == j + "s" or j == i + "s" or i == j + "r" ...
663e65fa97ce416170297d8ab742d8455f717d3a
74,862
from typing import Dict import re def match_and_store_pin( config: DeviceConfiguration, signals: Dict[str, str], line: str ) -> bool: """Match and store a pin mapping. Args: config: Device configuration. signals: Signals name mapping. line: Line containing potential pin mapping. ...
fe2e7eaabb602dba21885b988e1f588c5eda90ff
74,864
def extract_extra_labels(metadata_dict): """Return the 'extra_labels' labels from metadata_dict, as a list.""" labels = metadata_dict.get('extra_labels', None) if labels: extra_labels = labels.split(', ') extra_labels = [label.lower() for label in extra_labels] else: extra_labels...
17fd8aaf4aabe9dcafeb23b741bd53d29629f3e5
74,865
def login(): """ Logs in User --- tags: - auth requestBody: content: application/json: schema: type: object properties: username: type: string ...
a6af393c9f1b2ab9ac991ca21654319f1dc60b8e
74,866
import base64 def deobfuscate(token: str) -> str: """ Consume an obfuscated token and return the unobfuscated password. """ binary = base64.b64decode(token) binary, (method, ciphertext_len) = pop(binary, 4, "HH") try: properties = METHODS[method] except IndexError: raise ...
e156b581036a393aac65b08144ea26a80841ea92
74,867
def verify_document(doc: list): """ A helper function to verify entire documents. Verifies messages being of correct length, embeds being valid and file links being non-mangled. :param doc: :return: """ result = [] for i, msg in enumerate(doc): if isinstance(msg, str): ...
8babd4003a9b33adee6ffc52b6e314190f6627f1
74,868
import logging def delete_gwlb(gwlb_arn): """ Deletes specified GWLB and its attached listeners. Accepts: - gwlb_arn: GWLB ARN. Usage: - delete_elb('gwlb-arn') """ logging.info("Deleting GWLB:") waiter = elbv2.get_waiter('load_balancers_deleted') try: response = elbv2...
f83851bf87286bd4f7dca8f09cb2e7d71cd1d18d
74,869
from datetime import datetime from typing import Literal def endof( dt: datetime, fmt: Literal[ "y", "fhoy", "shoy", "q", "fq", "sq", "tq", "foq", "m", "w", "d", "am", "pm" ], ) -> datetime: """ 参数:: dt: fmt: - y: 年 - fhoy: 上半年 - shoy:...
5ad6bcb195b05ed9ab25cfc88391162bee9f0cc3
74,870
def test_factory(): """Create a pomodoro test factory.""" test_factory = PomitoTestFactory() return test_factory
b5d4ce64f893ca78cb61b1c5038cbffd52ea0484
74,872
def french_to_english(french_text): """ Function To Translate French To English """ try: if len(french_text) >= 1: translation = language_translator.translate(french_text, model_id='fr-en').get_result() trans_list = translation["translations"] trans_dict = trans_list[...
8f06382c99e94076e142d2e85fc1f86f34e81448
74,873
def dumps(data, **kwargs): """ Write JSON encoded 'data' to a string. simplejson is useful here as it always returns unicode if ensure_ascii=False is used, unlike the standard library json, rather than being dependant on the input. We use also ensure_ascii=False to write unicode characters specifica...
ae832751f1fa5a498fee7b4a8282d7e9e348669e
74,876
def remove_trailing_hyphens(s): """ :param s: :return: """ arr = s.split('.') try: if arr[0][-1] == '-': arr[0] = arr[0][:-1] return '.'.join(arr) else: return s except: return s
412387e6d916322fdcf3a5fb6e61636cc93dba4b
74,877
import re def order(sentence): """Funciton to return a sentence in special ordering""" word_dict = {re.search(r'[0-9]', word).group(0): word for word in sentence.split()} return " ".join([sorted(word_dict.items())[i][1] for i in range(len(word_dict)) ])
6fc6569044d0fbf66de55d0c8eddc83cfaef677b
74,879
def get_hybrid_pressure_cube_list(): """Return list of cubes including hybrid pressure coordinate.""" cube_0 = get_hybrid_pressure_cube() cube_1 = get_hybrid_pressure_cube() cube_0.add_dim_coord(get_time_coord(0), 0) cube_1.add_dim_coord(get_time_coord(1), 0) cubes = CubeList([cube_0, cube_1]) ...
13ba9302eb9715b0f021e179341bd1037ddeace4
74,880
def get_cli_kwargs(**kwargs): """ Transform Python keyword arguments to CLI keyword arguments :param kwargs: Keyword arguments :return: CLI keyword arguments """ return ' '.join( [ f'--{k.replace("_", "-")} {str(v).replace(",", " ")}' for k, v in kwargs.items() ...
7357516968952e13d8fe2edf07dc51c3a29e7673
74,881
def Pow_sca_r(x_e, c_e, g, R0, R1, omega, epM): """Calculate the power scattered by an annulus with a 'circling' electron as exciting source inside and an electron moving on a slightly curved trajectory outside (vertical) The trajectory of the electron derives from a straight vertical trajectory in ...
a83ddf550e3415bdb50a60c3b8930b00fa160b1b
74,882
from typing import Optional def submit_spark_step( cluster_id: str, path: str, deploy_mode: str = "cluster", docker_image: Optional[str] = None, name: str = "my-step", action_on_failure: str = "CONTINUE", region: Optional[str] = None, boto3_session: Optional[boto3.Session] = None, ) ->...
cef099df11ad971c4669ccd2891f5a7900da9524
74,883
from datetime import datetime def _format_time(t): """Return time readable by humans.""" return datetime.datetime.fromtimestamp(t)
d51dc3550c1f781bc9647ac65d7d20877046fa3c
74,884
def calc_tf_idf(tf_matrix, idf_matrix): """ creates dict of doc dict, each doc dict has key:val pais of: word : tf*idf value :param tf_matrix: returned by calc_tf :param idf_matrix: returned by calc_idf :return: dict of dict with word and tf*idf score for each doc in corpus """ tf_idf_matrix...
0e69d66499121f0aad8f2991cabaa6fe643e841a
74,885
def zero_phase_cc(arr1, arr2): """ Sets avarage phase in array to reference array. Parameters ---------- arr1 : ndarray array to adjust phase arr2 : ndarray reference array Returns ------- arr : ndarray input array with adjusted phase """ # will set...
282c8af1a74a46a09732e758c7454ccdab9bfc7e
74,887
def resize_and_pad(filename, desired_size=IMAGE_SIZE): """ Resize this into an image of size (desired_size, desired_size), preserving aspect ratio and in the case of a non-square image, centering it and padding the smaller side. :param filename: image filename :param desired_size: width and...
651de3ba61a67e1f40bdb93adb0f5471490b9871
74,888
def find_active_sites(activeSites, targetName): """ Find an active site in a list of AS's given the name Input: list of active sites, name of target Output: list of indeces of matched active sites """ return [i for i, j in enumerate(activeSites) if j.name==targetName]
544cc215f378eccc5aaa655482c0b3c03fed8974
74,889
from typing import Any from typing import Optional def _property_or_drop_if_changed(*, name: str, value: Any, existing: Any, cardinality: Optional[Cardinality]) \ -> Optional[GraphTraversal]: """ You want to use _vertex_property or _edge_property. """ if _property_unchanged(value=value, existi...
fa20fdcb238a2c2bce361fb4d66f404744597fd7
74,890
def create_usable_bucket_on_s3(bucket_name, s3_client, iam_client): """Create an S3 bucket and a user/key-pair that can access it. Return info for the user/key-pair """ _create_bucket(bucket_name, s3_client) user_info = _create_user(bucket_name, iam_client) policy = _create_policy(bucket_name, ...
3e53099b313a5d11865ca908817e16c327be75c5
74,892
def deleteInstance(**kargs): """ delete Database Instance * Args : - instanceid(String, Required) : instanceid * Examples : * Ref : https://cloud.kt.com/portal/openapi-guide/database-ucloudDB-Instance """ my_apikey, my_secretkey = c.read_config() if not 'instanceid' in kargs: ...
7a7e8bed636cd2daea586e85523d516ee4587d17
74,894
def denoise(a): """Applies simple denoising to a classified raster. Denoising removes small clusters and fills nodata areas. Args: a (MaskedArray): 2D MaskedArray with 'uint8' type Returns: ndarray: Denoised data """ a = majority_vote(a, 2) a = fill_nearest_neighbor(a) ...
c05571886431067f6d7f260780dbb76940066abc
74,895
def check_num_samples(ins, batch_size=None, steps=None, steps_name='steps'): """Determine the number of samples provided for training and evaluation. The number of samples is not defined when running with `steps`, in which case the number of samples is set to `None`. Arguments: ins: List of tensors to b...
3a205ab0a8b316b268e723978cbe795533005bed
74,896
import time def get_network_time(ntp_server): """ Fonction pour récupérer l'heure à partir d'un server NTP Nom fonction: get_network_time() Paramètre: server, un server NTP Return: une date sous la forme : 'Jour Mois NumJour Heure:Min:Sec Année en UTC +0' """ # Création d'un client vi...
ff2f4687c8f4c8f8dd19bda58a6d82e2b0084854
74,897
def precision_k_chart(percentages, precision, title="Precision@K"): """Precision@k curve.""" source = pd.DataFrame({"x": percentages, "y": precision}) return line_chart( source, "Percentage of samples selected", "Precision", title=title)
da9da274795c704036d585d5ea0b2e2c421e9e04
74,898
def create_ext_gauss_bundle(grid): """ Creates a bundle of Gaussian sources. Parameters ---------- grid: nd array array holding 2d grid and axis for whole bundle Returns ------- bundle ndarray bundle of Gaussian sources """ bundle = np.array([gaussian_source(g) ...
e22d882f7dc73a7eee12f4978e32953035937caa
74,900
def user_login( *, db: Session = Depends(deps.get_db), user_data: UserLogin ) -> AccessToken: """Login the user by creating a client if it doesn't exist, and have that client generate a token""" user = FidesopsUser.get_by(db, field="username", value=user_data.username) if not user: raise HTTPEx...
11777dffa5c3b4ee72f877c814b76ff8c4c09471
74,901
def cost(W,X,Y,C): """ W = [K,D] K = number of classes, D = number of dimensions Y = true classes {1,...,10} """ [K,D] = W.shape [N,D] = X.shape if not hasattr(cost, "negInfMask"): cost.negInfMask = np.arange(N)*K + (Y - 1) # Y values are in {1,...,10} but array indices ...
b97f0b8ddeb82f8f487d48ec7c4a9064c7dbdeca
74,902
import math def sinc(x): """ Incomplete sine """ if (x == 0): return 1 else: pix = math.pi*x return (math.sin(pix)/pix)
9f5983fb37ea9c049cc8a77375dc59a9bb78474a
74,903
def slow_complex(m): """Convert matrix ``m`` of type ``QStateMatrix`` to complex The function returns a complex ``numpy`` array of appropriate shape containing the matrix represented by the input ``m``. This is a pathon implementation for testing the fast method ``m.complex()`` """...
afd2f93f5f3b4aa3d3279361f30d6ff4910f42a8
74,904
def _par_fad(group, block_path, morph_dim, max_order, **kwargs): """a wrapper for parallelization of fit_all_derivatives""" return ( fit_all_derivatives(group, idxs=range(max_order), **kwargs), block_path, morph_dim, )
17dea6a3810950413b652eea12c5477605f6ee4a
74,905
def _rpath(go, library, executable = None): """Returns the potential rpaths of a library, possibly relative to another file.""" if not executable: return [paths.dirname(library.short_path)] origin = go.mode.goos == "darwin" and "@loader_path" or "$ORIGIN" # Accomodate for two kinds of executab...
e4382ce24ccc60cc31992f8f4e4136214d89c3a1
74,906
def load_couch_server(config_file): """loads couch server with settings specified in 'config_file'""" try: db_conf = cl.load_config(config_file)['statusdb'] url = db_conf['username']+':'+db_conf['password']+'@'+db_conf['url']+':'+str(db_conf['port']) couch = couchdb.Server("http://" + ur...
6b91bf6a3fb98e165fd2aeccbf6d84089f18c982
74,907
def process(record: dict, key_ref: dict, country_ref: pd.DataFrame, who_coding: dict, prov_measure_filter: dict, no_update_phrase: dict): """ Unify individual dataset transformers. Applies different transformations for records from different datasets. Parameters ---------- record : dict ...
8af89ec1329e23721b890794d73de8109599f31c
74,908
def friends(): """ Returns friendships for given player. Parameters: `key`, `uuid` Example Response: ```json { 'success': True, 'records': [ { '_id': '************************', 'uuidSender': '********************************', ...
00873cc71183008be186665c306d625a03709176
74,909
def test_select_menu_list_OK(monkeypatch): """ select_menu_list()の正常系テスト """ result = [[None, '', '1', 'OASEメニュー1', 'パラメータシート(ホスト/オペレーション含む)', '1', 'ホスト用', '', '', 'OASE_MenuGroup(Host)', 'OASE_MenuGroup(Ref)', '', None, None, '2020/04/10 15:02:08', 'T_20200410150208611888', 'システム管理者'], [None, '', '2',...
57e9650d7f7c3b31a96217c82be8dfaa6c6d6bf7
74,910
def SpanForCommand(node): # type: (command_t) -> Int """ like word_.LeftMostSpanForWord """ if node.tag == command_e.Pipeline: return node.spids[0] # first | if node.tag == command_e.AndOr: return node.spids[0] # first && or || if node.tag == command_e.DoGroup: return node.spids[0] # do spi...
08591ca363963159ba4c11ca823c6397b8f6bf2f
74,911
import json def create_lattes(jwt): """Create new latte""" try: ingredients = json.dumps(request.json["ingredients"]) rawTitle = request.json["title"] validTitle = validate_none_word_input(rawTitle) latte = Latte(title=validTitle, ingredients=ingredients,) latte.insert(...
8ab14c9a212a6c0d06dfdb469380554c754cd4eb
74,912
from typing import Dict def get_email_to_names_table(email_to_names_filename: str) -> Dict[str, str]: """Get a mapping of emails to names from the input file. Args: email_to_names_filename: Path to file with emails and corresponding names, where each email-name pair is on a separate line an...
856ce53a0abee1721b60603c468e5b66a484f7c8
74,913
import re def hex2rgb(hexrgb:str) -> RGB: """hex2rgb('#RRGGBB') -> RGB(R, G, B) hex2rgb('#RGB') -> RGB(RR, GG, BB) """ if not isinstance(hexrgb, str): raise TypeError('hex2rgb argument must be str, not {0.__class__.__name__} ({0!r})'.format(hexrgb)) if re.match(r"^#[0-9A-Fa-f]{3}[Ff]?$", h...
f3fc68b720fd9f7a90c97c29794fcb58351ccd10
74,915
def get_k8_config(event, context): """Generate k8 config object from list of clusters as query input""" # /get-k8-config?cloud-infra.cloud&cloud-infra-2.net clusters = event['queryStringParameters'] results = _generate_cluster_config(clusters) return results
ae1dc52e296a76c9967e02d30a272bcaf65e60ed
74,916
def prepare_to_train_test_split(clean_dataframe: pd.DataFrame): """ Function which does feature engineering and splits cleaned dataframe to features and target variables ready to be used for One hot Encoding. :param clean_dataframe: pandas dataframe :return: pandas Dataframes : features, target ...
bdfa4ec4fae67e03440a3d71f3e47ea1ac2d3983
74,917
import asyncio def map(futures): """ Asynchronously map list of futures. :return: Return value of all futures, or raise exception. """ return run(asyncio.gather(*futures))
6cbdb10c4ca78773a622734a59a6bc984fafece5
74,918
def time_factor(time_step): """ Routine used for bias correction in exponential moving averages, as in (Kingma, Ba, 2015) """ global_step = 1 + tf.train.get_or_create_global_step() decay = 1.0 - 1.0 / time_step return 1.0 - tf.exp((tf.cast(global_step, tf.float32)) * tf.log(decay))
2bc137e60b43b69ed491f275e3b933370e4673e8
74,919
import requests def twitter_get_url(resource, request): """Step 1 of OAuth1 dance""" oauth = OAuth1(resource.consumer_key, client_secret=resource.client_secret, callback_uri=resource.callback_uri) r = requests.post(resource.request_token_url, auth=oauth) oauth_to...
a613288a3033d09e1bbd8ac801eec35366dcac3a
74,920
def sparse_to_networkx(graphs): """Convert adj matrices to networkx graphs.""" return [nx.from_scipy_sparse_matrix(g) for g in graphs]
ed1316577b49145d8eabc8ec73b719471f20a386
74,921
def task_cache_tools_plantuml(): """Cache tools - plantuml""" return {'actions': [(common.mkdir_p, [plantuml_path.parent]), f"wget -q -c -O {plantuml_path} {plantuml_url}"], 'uptodate': [plantuml_path.exists]}
efc4b160264d15c1b653a163a8ac2c3353f28ddd
74,922
def plot_tracking(image, tlwhs, obj_ids, scores=None, frame_id=0, fps=0., ids2=None, cls_id=0): """ :param image: :param tlwhs: :param obj_ids: :param scores: :param fram...
32eb080c1cf2a1610a0b164d1f0dae16a43a7fb4
74,924
from datetime import datetime def list_recent(): """ Show the page that lists recent background jobs :return: The HTML for the job listing page """ # Find matching job status records from_date = datetime.datetime.today().date() - datetime.timedelta(days=1) job_statuses = list_job_status(...
d02ac4678114dae83b5f150fbc57f46f8bd9354f
74,925
def replace2sql(definition_dict=None, **definition_kwargs): """Create REPLACE SQL statement based on definition. :param definition_dict: definition of REPLACE SQL statement as dictionary :param definition_kwargs: definition of REPLACE SQL statement as kwargs :return: raw SQL statement :rtype: str ...
f9c79069235a3d35d12c54cd15fdfe95892054f0
74,926
import logging def _WaitForPingToSucceed(stopwatch, vm, benchmark_spec): """Run a ping workload continuously until it succeeds.""" logging.info('\n Pinging until success...\n') # issue ping while it fails, until it succeeds retcode = 1 while retcode != 0 and stopwatch.ShouldContinue(): _, _, retcode = _...
e067e6c19dd5fcae93748e2e6726694fbd5f5f2f
74,927
def listing(site, callback=None): """ Get the information for a site, from XRootD or a cache. :param str site: The site name :param function callback: The callback function to pass to :py:func:`create.create_dirinfo` :returns: The site directory listing information ...
f65027bfd1ed93e8ae7adbdb037c6f832424717b
74,928
import numpy def observed_order_convergence(fields, grids, grid_ref, ratio): """Compute the observed order of convergence. Parameters ---------- fields : tuple of numpy.ndarray objects The field values on three consistently refined grids. grids : tuple of tuple of numpy.ndarray objects ...
a6b53c099a8de673c6dec76f69875cf98391eabb
74,929
import torch def scn_angle_mask(seq, angles=None, device=None): """ Inputs: * seq: (length). iterable of 1-letter aa codes of a protein * angles: (length, 12). [phi, psi, omega, b_angle(n_ca_c), b_angle(ca_c_n), b_angle(c_n_ca), 6_scn_torsions] Outputs: (L, 14) maps point to theta and dih...
0014694dab5d850280bb721be5ace4929aa47cdb
74,930
def from_recipient(recipient, lock=None): """ Create automatically a recipient condition based on any accepted pythonic value (combo). """ # define base condition if isinstance(recipient, ConditionBaseClass): condition = recipient else: condition = None if recipient == N...
f79a39c5949a370caff956a02b99a92fb87d2d89
74,931
from operator import sub def create_many_patients(request: ResearcherRequest, study_id=None): """ Creates a number of new users at once for a study. Generates a password and keys for each one, pushes data to S3 and the user database, adds users to the study they're supposed to be attached to, and returns...
af0051f7edb9397823244edbe1ab7c26f49de293
74,932
import json def _Stringify(value): # pylint: disable=invalid-name """Represents value as a JSON string if it's not a string.""" if value is None: return '' elif isinstance(value, (basestring, console_attr.Colorizer)): return value elif isinstance(value, float): return resource_transform.Transform...
4c2e3db66ac0e6aa2fe7d6ece79e6d02f0d456cf
74,933
def launch_request_handler(handler_input): """Handler for Skill Launch.""" # type: (HandlerInput) -> Response speech_text = INTENT_ANSWERS['launch'] return handler_input.response_builder.speak(speech_text).set_should_end_session( False).response
1871ea645821b7a391013a09888041e0dc29628e
74,934
def print_tb(traceback, limit=0, file=None): """Print up to *limit* stack trace entries from *traceback*. If *limit* is omitted or ``None``, all entries are printed. If *file* is omitted or ``None``, the output goes to ``sys.stderr``; otherwise it should be an open file or file-like object to ...
5d7fb403676aa7836430c1f6518b081d13c80e2c
74,935
def convert_potential_git_url(requirement, tokens, transform_with_token=False): """ Convert a potential Github URL to an git+https url that possibly identifies via an Oauth token. The Oauth identification allows for installation of private packages. :param requirement: The potential url to convert into ...
9a8f5d7789f9342316522795af54fc06e68a7032
74,936
import ssl from bs4 import BeautifulSoup def get_cve_info(cve): """Return venerability information from National Vulnerability Database by CVE code""" try: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE html = urlopen(CVE_LINK + cv...
5a70b5b4afbcc301268de5344d5c50385fe052b5
74,937
def tdop_term(): """Parser for an expression involving symbolic operators. tdop = top down operator precedence, which is how such expressions will eventually be handled. Here we just collect together the tokens in the expression for later handling. In the expression, there are no adjac...
fc28ee853d39fc01cabba08c5eb1ff9304333d93
74,938