content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Callable from typing import Any from typing import List import inspect def get_parameters( f: Callable[..., Any], allow_args: bool = False, allow_kwargs: bool = False ) -> List[str]: """Get names of function parameters.""" params = inspect.getfullargspec(f) if not allow_args and par...
218e187ae504ce18c0d240aee93480e275f4b8a4
70,400
def error_417(message = None): """JSON error handler for HTTP error 417""" if not isinstance(message, str) or len(message) < 1: message = 'Expectation Failed' return _error(code = 417, message = message)
d72965ccd49c9e8d679dadde74d2ab76a0ea005b
70,401
from typing import Optional from typing import Generator def barabasi_albert(num_nodes: int, num_edges: int, rng: Optional[Generator] = None) -> NDArray: """ Returns a graph sampled from the Barabasi-Albert (BA) model. The graph is built incrementally by adding `num_edges` arcs from a new node to already ...
c1df5d4dfd29a2c7eabc2159d611d2186415c1d8
70,402
import functools def split_and_combine_df(func=None, *, remove_type=False): """Split the data across sub state spaces and combine. This function groups the data according to the dense variables. `remove_type` is used to prevent grouping by types which might not be possible. """ def decorator_sp...
a472c9dff37dc2144b5938bdaf196fcb7cc2e514
70,403
import ctypes def get_output_console_level(p_state): """Returns the level up to which the Log is output to the console. The return value will be one of the integers defined above. """ return int(_Get_Output_Console_Level(ctypes.c_void_p(p_state)))
0363de51919b6e09a6de6ad905967d62878be448
70,404
def create_beam_node(instrument, bounds, visible=False): """Creates node for beam :param instrument: instrument object :type instrument: Instrument :param bounds: bounding box of the instrument scene :type bounds: BoundingBox :param visible: indicates node is visible :type visible: bool ...
b6d7476498f68d5bf90141f0d2123c21f8cef4a7
70,405
def svn_diff_mem_string_output_unified(*args): """ svn_diff_mem_string_output_unified(svn_stream_t output_stream, svn_diff_t diff, char original_header, char modified_header, char header_encoding, svn_string_t original, svn_string_t modified, apr_pool_t pool) -> svn_error_t """ re...
2f20e704eb848b338268fff01bcbfb82c3a843dd
70,406
def annotate_with_clonality(insertions): """Annotates an insertion dataframe with the clonality of insertions. The clonality of each insertion is calculated by dividing the support of the insertion by the support score of the strongest insertion in the same tumor. Parameters ---------- ins...
b78d770d0f295912859d375b0b974276e2704cf1
70,407
def _convertCtypeArrayToList(listCtype): """Returns a normal list from a ctypes list.""" return listCtype[:]
89a408b796f2aba2f34bc20942574986abd66cd2
70,408
def expr_len(e: Expression) -> int: """ Computes the number of nodes in the AST of `e`. :param e: The expression whose length is computed. :return: The length of the expression. """ return 1 + sum(map(expr_len, e.children()))
c26355a56ce94c2f18a57d59d92c0bfe154355a9
70,409
def read_datafile(filename): """ Reads a langmuir csv file with the format: time,header,Sweep voltage,Plasma voltage,Plasma temperature,Particles counter 2018-07-19 07:03:48,0x43434301,4.017525,4.1494875,291.78375,2 # Calibration 2018-07-19 07:03:48,0x43434302,4.0126375,3.470125000000...
6bf3f0ded56563086ccd8f39aaeab23d3a233369
70,410
def selectFood(): """Display caterering options""" t = TenativeBooking.loadFromSession() d = Dish.select().where(Dish.isDeleted == False) c = Caterer.select().where(Caterer.isDeleted == False) dishes = prefetch(d, c) return render_template('event/caterer.html', dishes=dishes, booking=t)
429e5e990f28a7954e50c3e440aa7d6bcbcb6eb8
70,411
from typing import List def get_cost_vector(counts: dict) -> List[float]: """ This function simply gives values that represent how far away from our desired goal we are. Said desired goal is that we get as close to 0 counts for the states |00> and |11>, and as close to 50% of the total counts for |01> and...
b7565de2e47ba99e93b387ba954fdc29f44805e8
70,412
def YcCbcCrc_to_RGB(YcCbcCrc, in_bits=10, in_legal=True, in_int=False, is_12_bits_system=False, **kwargs): """ Converts an array of *Yc'Cbc'Crc'* colour encoding values to the corresponding *RGB* array of lin...
b730dadfc38a1ad96f7ec0e795020b3239f1fcd8
70,413
import os def exists(fname): """Returns True if `fname` relative to `ROOT` exists""" return os.path.exists(os.path.join(ROOT, fname))
13d75f6f0af22fc283fa223a4005042a755cda9c
70,414
import sqlite3 def getradecrangedb(dbfile): """ Get RA/DEC ranges from database """ sqlite3.register_adapter(np.int16, int) sqlite3.register_adapter(np.int64, int) sqlite3.register_adapter(np.float64, float) sqlite3.register_adapter(np.float32, float) db = sqlite3.connect(dbfile, detect_types=...
84553ab1a284b253026f1ae6d99e9ad4d7922c63
70,415
def compute_rhat_regression(samples, n_chains): """A wrapper function for computing R-hat statistics for regression tasks. Args: samples: numpy array [n_chains * n_samples, n_vars], the samples taken from MCMC sampling. n_chains: int, the number of sampling chains. Return: ...
436655868282421b702fe8e156c1e765af553744
70,416
import torch def binary_loss_function(recon_x, x, z_mu, z_var, z_0, z_k, ldj, beta=1.): """ Computes the binary loss function while summing over batch dimension, not averaged! :param recon_x: shape: (batch_size, num_channels, pixel_width, pixel_height), bernoulli parameters p(x=1) :param x: shape (bat...
5009cc3c881f3b6b71495efe516dd038b9ca92f9
70,417
def update_create_front_page_groups(request_ctx, group_id, wiki_page_body, wiki_page_title=None, wiki_page_hide_from_students=None, wiki_page_editing_roles=None, wiki_page_notify_of_update=None, wiki_page_published=None, **request_kwargs): """ Update the title or contents of the front page :param reque...
64a6ecc66d6ec63c35c2d20e9610f9814dbd60d6
70,418
def default_copy(original_content): """Copy all fields of the original content object exactly as they are and return a new content object which is different only in its pk. NOTE: This will only work for very simple content objects. This will throw exceptions on one2one and m2m relationships. And it mig...
d0a6fca858e34b8a7ae26ed9693a894cf2b2473f
70,419
def build_normalized_request_string(ts, nonce, http_method, host, port, request_path, ext): """Implements the notion of a normalized request string as described in http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-02#section-3.2.1""" normalized_request_string = \ ts + '\n' + \ nonce +...
6a7f397738b852116cbaf249c846f58b482fdca1
70,420
def get_merged_coverage_eval(): """Merges and returns all active coverage data as a single dict. Returns: coverage eval dict. """ if not _coverage_eval: return {} coverage_eval_list = list(_coverage_eval.values()) merged_eval = deepcopy(coverage_eval_list.pop()) for coverage_eval in...
e4f5b227f7dab9ce50513bc29eec30172af7d77e
70,421
from operator import setitem def xmlparse(source, parsing_method=XMLParsingMethods.C_ELEMENTTREE, **kwargs): """Parses a XML document into a dictionary. Details about how the XML is converted into this dictionary (json) representation is described in reference [3] in the README. :param str,file-like...
155a1f44f3b0393235693626e53ce63a750fcce7
70,422
def print_exception( type=None, value=None, traceback=None, limit=LIMIT, as_html=False, with_filenames=False, stream=None ): """Print the exception to the given `stream`.""" info = format_exception( type, value, traceback, limit, as_html, with_filenames ) if stream is None: ...
ff6c184b40d6fba2ff197832a40456658d66ce04
70,423
def authenticate(f): """ Decorator for checking if a user is authenticated """ @wraps(f) def wrapper(self): """ :type self: RequestHandler """ try: self.request.session = Session.get(Session.secret == self.get_cookie('session')) f(self) ...
9814d4180cf0a11de7ede9d862a953b744d161a7
70,424
def _average_gradients(tower_grads): """Calculates average of gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. T...
67c143dbdae01ca1dfdeff345861e0e0aca0bc1c
70,425
from datetime import datetime def home(): """Show user info""" # Get today's date date_now = datetime.datetime.strptime(get_time(), "%Y-%m-%d %H:%M") # Get user event info events = db.execute("SELECT * FROM events WHERE event_id IN (SELECT event_id FROM event_members WHERE user_id = ?) ORDER BY ...
4b327ed7309909560ef59302a272ae4d8090c60a
70,426
import ast import re def extract_from_grid(field_soup, form_info): """Return list of Samples, extracted from grid portion of form xml. Arguments: field_soup (BeautifulSoup object): The soup of the grid field. form_info (api_types.CustomForm): dataclass holding information for the ...
2fbd16c4f288733011eac6f2f06e59c2666e690e
70,427
import os def get_env_setting(setting, default=None): """ Get the environment setting or return exception """ try: return os.environ[setting] except KeyError: if default: return default error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(e...
7d78702178b629ae00d2faa42ca4f55e710712e6
70,428
def instance_get_oper_state(vm_state, task_state, power_state): """ Convert the nfvi vm states to an instance operational state """ oper_state = nfvi_objs.INSTANCE_OPER_STATE.ENABLED if nova.VM_STATE.ERROR == vm_state: oper_state = nfvi_objs.INSTANCE_OPER_STATE.DISABLED elif nova.VM_ST...
831ccfd9cc6e67a52d144297f8e851a9c1ae4176
70,429
def _force_list(value): """If the value is not a list, make it one.""" if value is None: return [] try: if isinstance(value, basestring): raise TypeError() return list(value) except TypeError: return [value]
88a70d870a2c5c4a3c537b5b25247e852ed3af7c
70,430
import uuid def launch_v1(scan_id: uuid, probes: comma_separated_list = None, force: smart_boolean = False, mimetype_filtering: smart_boolean = True, resubmit_files: smart_boolean = True, ): """ Launch a scan. The request should be perf...
c82ab3545c7ad698d741e14ceb8c1531334f8429
70,431
import google.datalab.utils as du def batch_predict_async(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Local and cloud batch prediction. Args: training_dir: The output folder of training. prediction_i...
bc1da3a7a1c1f6dc28f96bfad326eaf212da2531
70,432
import sys def check_python_version(): """Check python version and return version info. Returns: int: 2 if Python version is 2.x 3 if >= 3.5 else raises. Raises: UnsupportedPython: If current python version is not supported. """ vi = sys.version_info ...
7cf326b9b5ccee1942fed1e6957b703d14001fb5
70,433
import sys def os_arch(): """ Return a tuple for the current the OS and architecture. """ if sys.maxsize > 2 ** 32: arch = '64' else: arch = '32' sys_platform = str(sys.platform).lower() if 'linux' in sys_platform: os = 'linux' elif'win32' in sys_platform: ...
0dd55b5a07ae853c700bd75ed43bab8d78da1dec
70,434
def make_sphere_a(): """ Create a sphere""" mesh_a = trimesh.creation.icosphere(subdivisions=1, radius=1.0) return mesh_a
69c034884c6280411764d86cadcb81308d957416
70,435
def title(): """ (None) -> None Function that loads the error page """ title = request.args.get('title') if title in TITLES: return render_template(f"books/{title}.html") else: return redirect(url_for(error))
32b9a317bcbb9905e63934b5ca61b2914da06865
70,436
from typing import Tuple def load_sets(directory, suffix: str = '', file_type: str = 'csv') -> Tuple[ pd.DataFrame, pd.DataFrame, pd.Series, pd.Series, pd.DataFrame ]: """ """ # Cater for empty suffix and not having a dangling underscore if suffix: suffix = f'_{suffix}...
8ac7357a9e994d1cf6e025baeac35a0369dbbfbd
70,437
def resnet101(**kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) return model
5e40c374f07025d07ff385a229c487851e6464ec
70,438
import json def load_game(file_name): """ Loads game information from a json file and populates the input layer of the LSTM Parameters ---------- file_name : str Name of json file to be parsed and converted to input layer Returns ------- list List of containing one el...
bc4da931ca469a32d544a988b103afe7f5c97981
70,439
def test_hard_requirements(): """ Returns any errors resulting from hard config requirement violations """ output = {} for k in hardRequirements: hardRequirements[k](output) return output
1805f54b58431840d80ffaef0b5d139299614176
70,440
from datetime import datetime import pytz import os def load_precip(): """ Load the 5 minute precipitation data into our ginormus grid """ printt("load_precip() called...") ts = 30 * 24 # 2 minute midnight = datetime.datetime(VALID.year, VALID.month, VALID.day, 12, 0) midnight = midnight.replace...
977869038c787bd590c6783b3c9ddc9c53a8447a
70,441
def Lt(left: Expr, right: Expr) -> BinaryExpr: """Less than expression. Checks if left < right. Args: left: Must evaluate to uint64. right: Must evaluate to uint64. """ return BinaryExpr(Op.lt, TealType.uint64, TealType.uint64, left, right)
f982a1386ded20da9b8c13355512e83e0a786809
70,442
import math def train_ann_test_batch(sess, ixs, data, summary_writer=None): #inputs: label_classifier, label_offset, label_coldensity """ Perform training and estimate accuracy,RMSE after every iteration training Parameters ---------- sess:tf.Session object ixs:np.ndarray, indices f...
510262cd46e0f9291fd7b3ad7978cf0e977009ac
70,443
def first_prime_greater_than(k: int) -> int: """ return the first prime greater than k Called by the InputParams constructor """ if k < 1: raise FuzzyError("k < 1") while True: k += 1 if isprime(k): return k
92a563b97987b526a6e3d01ee73475cb60df24b8
70,444
import pickle def to_bytes(graph: BELGraph, protocol: int = pickle.HIGHEST_PROTOCOL) -> bytes: """Convert a graph to bytes with pickle. Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable pickle, choose 0, 1, or 2. :param graph: A BEL gra...
5af28070f1a5eb4cf666c3014968dcf41f552251
70,445
import pickle import math def genr_item_univ(config: dict, size_res_path='data/item_size.pkl', cls_res_path='data/cls_item.pkl'): """Generate universe of items (queries). Generate and save result as <Item Size Table>. Item number and size range specified by params in config. Compute and save <Class Item...
c5716e03b43c178b9bdc44c79463ca33e8fef9a9
70,446
def authorize(*_, **kwargs): """OAuth2'orize.""" authorize_form = AuthorizeForm(request.form) if request.method == 'GET': client_id = kwargs.get('client_id') client = Client.query.filter_by(client_id=client_id).first() kwargs['client'] = client has_authorized_scopes = session...
91a3738537e88c325aa7f4e8d498f1175334525a
70,447
def trace_stream(stream_port, request_message = None, response_message = None): """Allows tracing the input stream within the resulting stream.""" s = stream_port expect_stream(stream_port) model = s.get_model() item_data_type = s.get_item_data_type() code = 'return $ traceStream ' code += e...
c7a9d7c26c25ac3c050f312bd5b827022f6c832a
70,448
from typing import List import os def setup_checkpointing( config: CheckpointingConfig, run_path: Text ) -> List[tf.keras.callbacks.Callback]: """Set up model checkpointing callbacks from config.""" callbacks = [] if config.initial_model: callbacks.append( ModelCheckpointOnEvent( ...
0602ea99a3798e1f29fe574b6ff412fde31b5e6a
70,449
import requests def get_mobility(city): """Gets the latest mobility data from city mapper Arguments: city {String} -- Which city to get data from Returns: Pandas Series -- Series of mobility index """ url = "https://www.data.gouv.fr/en/datasets/citymapper-mobility-index/" u...
ded9e90604b346ebdc8bc702d26c64cbe4b8050a
70,450
def rivers_with_station(stations): """Given list of stations (MonitoringStation object), return the names of the rivers that are being monitored""" # Collect all the names of the rivers in a set to avoid duplicate entries rivers = {station.river for station in stations} # Return a list for conveni...
c099af2eb0f869c6f1e3270ee089f54246779e2d
70,451
from typing import List def expand_time_windows(periods: List[TimeWindow]) -> List[pd.Timestamp]: """Return a list of days to exclude from a list of TimeWindows. Args: periods: List of time windows (first day, last day). Returns: days_exclude: a List of obtained by expanding the list in input. """ d...
1179926b7eb335be3e606db19b33bb819069f69c
70,452
def _clean_str(words): """ heavily borrowed from github https://github.com/LukeZhuang/Hierarchical-Attention-Network/blob/master/yelp-preprocess.ipynb :param sentence: is a str :return: """ words_collection = [] for word in words: if word in ['-lrb-', '-rrb-', '<sssss>', '-r', '...
7b69764bbdab2c5226163f31f365194a7cb1fac5
70,453
def from_text(text, origin=None, rdclass=dns.rdataclass.IN, relativize=True, zone_factory=Zone, filename=None, allow_include=False, check_origin=True, idna_codec=None): """Build a zone object from a master file format string. *text*, a ``str``, the master file format input. *or...
f78d8ea626029c25e819bfe4e61f36a2f2be6de3
70,454
from MoinMoin.widget import html def makeSelection(name, values, selectedval=None, size=1, multiple=False, enabled=True): """ Make a HTML <select> element named `name` from a value list. The list can either be a list of strings, or a list of (value, label) tuples. `selectedval` is the val...
5aea7545d4213915bd3fba9cf0b2908ad938cb40
70,455
def find_anagrams(s, diction): """ :param s: :param diction: :return: """ ans = [] permutation(s, '', len(s), ans, diction) return ans
a1ee705426963ea393479c366d6ff7e5a4a110a4
70,456
async def del_schema(event_type: str): """ Deletes event validation schema for given event type """ try: result = await storage.driver.validation_schema.del_schema(event_type) await storage.driver.validation_schema.refresh() except ElasticsearchException as e: raise HTTPExcep...
9167a0424ba7dd6a83f66f49835640b7fe44e795
70,457
import requests import json def pinterest_shares(url): """pinterest share count""" try: pinterest_url = 'http://api.pinterest.com/v1/urls/count.json?url=' \ + url response = requests.get(pinterest_url).text\ .replace('receiveCount(', '')\ ...
097a587778b1b21ceb84664b644cdbc6bb4619c3
70,458
import math def get_deltas(radians): """ gets delta x and y for any angle in radians """ dx = math.sin(radians) dy = -math.cos(radians) return dx, dy
032acb537373d0ee18b721f04c95e75bb1572b1b
70,459
def global_min_temp(year): """ Finds the minimum temperature from the minimum temperatures from all the observations for a given year from 1929 to 2009 inclusive. """ return sc.textFile(server_name + dir_name + str(year))\ .filter(lambda line: "STN" not in line)\ ...
8daad6ac0ac7f96ae672ae7ce8b0136f6c8e9a96
70,460
import logging def tok_sentence_to_vec(tok_sentences, vocabulary, model, normalize_sentence=1, normalize_word=True, alpha=1e-4, show_logs=0): """ Maps a list of tokenized sentences to their vectorial representation. > tok_sentences: List of tokenized sentences > vocabulary: Lis...
6634262922235a3e8f21648200257d22fa1626c2
70,461
from typing import Dict def mrr(benchmark: Dict, results: Dict, repo: str) -> float: """ Calculate the MRR of the prediction for a repo. :param benchmark: dictionary with the real libraries from benchmark. :param results: dictionary with the predicted libraries. :param repo: full name of the repo....
b057c93cc807244e4d5e8e94772877273ac1041c
70,462
from typing import Dict from typing import Optional from typing import Tuple from typing import Union from typing import cast def netlist( *, instances: Instances, connections: Dict[str, str], ports: Dict[str, str], models: Optional[Models] = None, settings: Optional[Settings] = None, defa...
add686735ddebe819e7d494f0feb78008248e10c
70,463
from datetime import datetime import time import requests import json def get_interlanguage_links(page_names, languages_of_interest={'it', 'nl'}, sleep=1, verbose=0): """ mapping of English page name to its equivalent pages in...
8bcd458dd9ae6fb857d57535897701c017d11252
70,464
from typing import Callable def is_similar_callables(t: Callable, s: Callable) -> bool: """Return True if t and s are equivalent and have identical numbers of arguments, default arguments and varargs. """ return (len(t.arg_types) == len(s.arg_types) and t.min_args == s.min_args and t.is_v...
861ae7265a7ad8e2b5b4c83d8e17a8c33195acf9
70,465
import hashlib def hashmd5mod(*args): """ .. function:: hashmd5mod(args, divisor) -> int Returns the *modulo* with divisor number of the MD5 hash of args. Numbers are converted to text before hashing is performed. Examples: >>> sql("select hashmd5mod(65, 3)") hashmd5mod(65, 3) -----...
13507127ab561a79b14ef5afac181760270226ba
70,466
def get_total_gpu_memory(units="Mb"): """Get the memory of the GPUs in the system Returns: list: List of strings with the GPU memory in Mb Examples: >>> get_total_gpu_memory() #doctest: +SKIP [16280.875] """ try: memory_list = [] for gpu in cuda.gpus...
848c208bc310ed641e441f096342326f6dc75905
70,467
def dictTagging(word, tag): """ Use language dictionaries to tag words """ global language_1_dicts global language_2_dicts global lang1 global lang2 dhin, den0, den1 = 0, 0, 0 word = word if word.lower() in language_1_dicts["hindict1"].keys(): dhin = 1 if word.low...
2a5fc15cbff2480c5c9e9336ac6a4feaa62112e1
70,468
def extract_dependencies(depends_content, exclude=None): """ Extract the Bazel project name from the BUILD file. :param set depends_content: The Bazel BUILD files merged content. :param str exclude: exclude self references. :returns: List of dependencies, otherwise None. :rtype: set """ ...
1d923a87f7ce7f5343242c756e5b0ab4bf59f90a
70,469
def hook_get_load_batch_query(table: str, start_index: int, end_index: int) -> str: """Returns the query that loads the BQ data. Here it's possible to filter just new customers or other customer groups. Args: table: A string representing the full path of the BQ table where th...
6a99cf04214a815249a01b6cf5040bdb93b73fb8
70,470
def soft_nms(boxes, scores, method, gaussian_sigma, linear_threshold, prune_threshold, topk_per_image): """ Performs soft non-maximum suppression algorithm on axis aligned boxes Args: boxes (Tensor[N, 5]): boxes where NMS will be performed. They are expected to be in (x_ctr, y_...
39c61258f913d6f943754c2f6a911d7bde577b5b
70,471
def getSourceDefaultSettings(sourceKind: str): """ Get the default settings for a given source type. :param sourceKind: String - Source kind. Also called "source id" in libobs terminology. """ return __createJSON("GetSourceDefaultSettings", {'sourceKind': sourceKind})
142f26c3e300b6f034f17ebfef4dba7d1eb1cb9e
70,472
def get_spearman_rho(word2id1, embeddings1, path, lower, word2id2=None, embeddings2=None): """ Compute monolingual or cross-lingual word similarity score. """ assert not ((word2id2 is None) ^ (embeddings2 is None)) word2id2 = word2id1 if word2id2 is None else word2id2 embedd...
25921c17209fea11ae95f7a62858eb90ae198b6d
70,473
def elf_segment_names(elf): """Return a hash of elf segment names, indexed by segment number.""" table = {} seg_names_sect = elf.find_section_named(".segment_names") if seg_names_sect is not None: names = seg_names_sect.get_strings()[1:] for i in range(len(names)): table[i...
4af46fb35c9808f8f90509417d52e7ce4eb2770e
70,474
def line_line_closest_points(A1, C1, A2, C2): """ >>> print line_line_closest_points(Ux,Ux,Uy,Uy) (Vec( 0.000000, 0.000000, 0.000000 ), Vec( 0.000000, 0.000000, 0.000000 )) >>> print line_line_closest_points(Ux,Uy,Uy,Uz) (Vec( 0.000000, 1.000000, 0.000000 ), Vec( 0.000000, 1.000000, 1.000000 )) ...
211d19b67fb56d00ae1276ebd62e9e979c4d5295
70,475
import base64 def create_nova_keypair(identity_service, amp_key_name): """Create a nova keypair to use with Amphora images to allow ssh access e.g. for debug purposes. """ pubkey = ch_core.hookenv.config('amp-ssh-pub-key') if not pubkey: ch_core.hookenv.log('No pub key provided - cannot cr...
08e299b631e2a4fbd86b1686823ace7229b75913
70,476
def load_data(args): """ Load dataset Args: args: arguments set by the user """ dst = args.dataset if dst == 'mnist': return load_mnist(args) if dst == 'fashion-mnist': return load_fmnist(args) if dst == 'cifar10': return load_cifar10(args) if dst ==...
9215008fb0545b79b3b8da14b21520908e1fe321
70,477
def segment_spectrum_batch(spectra_mat, w=50, dw=25): """ Segment multiple raman spectra into overlapping windows Args: spectra_mat (2D numpy array): array of input raman spectrum w (int, optional): length of window. Defaults to 50. dw (int, optional): step size. Defaults to 25. ...
956791e2957f4810726d1d94549f79f3d83c8d21
70,478
from pathlib import Path def _get_params() -> dict: """ Parse Commandline Arguments and return them as options. Returns: dict """ return EntryPointParameters( inputdir=dict( type=Path, required=True, help="Measurements path." ), ...
2a208207a09a2de87f51d5e5432893e4feeb5941
70,479
import pandas as pd import os def leukemia(path): """Acute Myelogenous Leukemia survival data Survival in patients with Acute Myelogenous Leukemia. The question at the time was whether the standard course of chemotherapy should be extended ('maintainance') for additional cycles. time: survival or censo...
d539586caae0c0acc1adf39d4153e9f47cffec58
70,480
def complete_annotation(program, dist_context=None): """ Complete annotation for the partial annotated program. Arguments: program: partial annotated program. dist_context: the distributed context is used to store distributed attributes for program. If not provided, the default one ...
5abb68e06243b935f0dec0070758390d3b513d7f
70,481
def generate_hashes(peaks, hash_style): """ Hash list structure: sha1_hash[0:30] time_offset [(e05b341a9b77a51fd26..., 32), ... ] """ peaks = list(peaks) if peak_sort: peaks = sorted(peaks, key=lambda x: x[1]) # print("Length of Peaks List is: {}".format(len(peaks))) i...
9d6919dac3e1910eb173028ad0cc0bef6c265c12
70,482
def _create_serialized_example(features, label): """Helper for creating a serialized Example proto.""" example = tf.train.Example(features=tf.train.Features(feature={ "features": _float_feature(features), "label": _int64_feature(label), })) return example.SerializeToString()
835558f340ee23bd8280e26de7b128c3ee824eed
70,483
from typing import Dict def sparsity_loss(X_hat_cf: tf.Tensor, X: tf.Tensor) -> Dict[str, tf.Tensor]: """ Default L1 sparsity loss. Parameters ---------- X_hat_cf Autoencoder counterfactual reconstruction. X Input instance Returns ------- L1 sparsity loss. ...
2ef5e83277b541506b030ca56c1690aad6f4d22b
70,484
def proxies_get_number(): """ 获取代理IP数量 :return: """ number_10 = redis_pool.redis_llen(GRADEKEY10) number_8 = redis_pool.redis_llen(GRADEKEY8) number_6 = redis_pool.redis_llen(GRADEKEY6) number_4 = redis_pool.redis_llen(GRADEKEY4) number_grade = redis_pool.redis_llen(GRADEKEY) # 使用完待...
1efff3b0cefa9b90d3d5674a66ce544d5eae7132
70,485
from typing import Union from typing import Tuple from typing import Dict from typing import List def rnns( draw, return_kwargs: bool = False ) -> Union[ st.SearchStrategy[rnn_pb2.RNN], st.SearchStrategy[Tuple[rnn_pb2.RNN, Dict]] ]: """Returns a SearchStrategy for RNN plus maybe the kwargs.""" kwargs ...
ebfbbb2c1e04a51f504a0bd9b278602f2ac045e2
70,486
def readvar(fni,varname,latrange=[],prange=[]): """reads variable from netcdf object in varname fni is a Dataset variable""" tsv = fni.variables[varname] ts=tsv[:] # try: # ts = np.array(ts,dtype='float32')*float(tsv.scale_factor)+float(tsv.add_offset) # except AttributeError: # x=0 # dummy statement tr...
2c987fa20c76911442cdcbba48f7b215350e0484
70,487
import time import email def date_time_string(timestamp=None): """Return the current date and time formatted for a message header.""" if timestamp is None: timestamp = time.time() return email.utils.formatdate(timestamp, usegmt=True)
0b2c319f341979b29ad6ca76eb6a93771e48e56e
70,488
def dot_product_attention_relative(q, k, v, bias, max_relative_position, dropout_rate=0.0, image_shapes=None, ...
211725c6a62c8258db6d6ec77c1bc726a5dccb90
70,489
from operator import add def do_query(documents, config_file=None, logger=None, context=None): """ Iterate through documents and count total size of document files in bytes. Returns result of form: {"total_size": total_size} :param documents: RDD of defoe.document.Document :type docu...
f505940b0c5b628bb2eea6c7bbbf3be28da41734
70,490
def get_bond(bond_id: str) -> Bond: """Return a specific bond. Args: bond_id (str): The bond id of the bond to fetch. Raises: HTTPException(400) if the bond does not exist. Returns: The requested bond.""" logger.info(f"Get bond: bond_id={bond_id}") try: bond: B...
d7883c89a4c625f71e2286787892a2c54ff2195a
70,491
import sys import os def find_cloudenv_secret_key(filename='.cloudenv-secret-key', raise_error_if_not_found=True): """ Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise """ # will work for .py files frame = sys._getframe(...
0e3dee7ae0d270c07a7cda9a5c8eb3da0f2c9946
70,492
def _convert_dtype_string(dtype): """Get the String from type. # Arguments dtype: Type. # Returns A stromg representation of a type. # Raises ValueError: if `dtype` is not supported. """ mapping = {np.float16: 'float16', np.float32: 'float32', ...
f49673e5f66b2f433c1932abaeaefe6a40f30dcc
70,493
import time import os def dmd_s(D_1,D_2,n_Modes, F_S, SAVE_T_DMD=False, FOLDER_OUT='./'): """ This method computes the Dynamic Mode Decomposition (DMD). https://youtu.be/8fhupzhAR_M -------------------------------------------------------------------------------------------------------------------- ...
3e8fa21344475751970a27470204817c6b0d1ecb
70,494
import os def map_one_param(param, context=None): """ Analyze the pattern in the given string and find out its transformed value. Available tags and replacement values: [CONF:xxxx] Value from the config dict in context.project_config for the key xxxx (dot notation is used for keys, e.g. ke...
91cc82082b7474d6f77b83943a8e8037d33712f2
70,495
def splitCubicAtT(pt1, pt2, pt3, pt4, *ts): """Split the cubic curve between pt1, pt2, pt3 and pt4 at one or more values of t. Return a list of curve segments. >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5)) ((0.0, 0.0), (12.5, 50.0), (31.25, 75.0), (50.0, 75.0)) ((50.0, 75.0), (6...
8e21ee2c71456b4bedd3304df83868e0471ef380
70,496
import zipfile def validate_zip(path_to_zip, raise_on_fail=True): """ validates a zip file :param path_to_zip: :param raise_on_fail: :return: """ log.debug('validate_zip: zip={}'.format(path_to_zip)) zip_ref = zipfile.ZipFile(path_to_zip, "r", zipfile.ZIP_DEFLATED) try: ret...
a612d23156fbee925f1b3956d9048a814bf8941c
70,497
def optimal_assignment_adv(adv_input): """ Calculate optimal assignment based on euclidean distance """ a_1 = calc_distance((adv_input[0], adv_input[1]), (adv_input[4], adv_input[5])) b_1 = calc_distance((adv_input[2], adv_input[3]), (adv_input[4], adv...
5b265f2601e123ad4a07b017d3da93460e3131e0
70,498
import os def get_csci_salt(): """Returns the appropriate salt for CSCI E-29 :rtype: bytes """ # Hint: use os.environment and bytes.fromhex raw_salt = os.getenv(SALT_ENV_VAR, default='') if not raw_salt: raise ValueError("Empty salt!") return bytes.fromhex(raw_salt)
78b14488479087d3b9f4ea232431ba5cc765bf3a
70,499