content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import sys def query_yes_no(question, default="no"): """ Ask a yes/no question via raw_input() and return their answer. :param str question: a string that is presented to the user. :param str default: the presumed answer if the user just hits <Enter>. :return bool: True for "yes" or False for "no...
36f95aa7a52fbcb17dc351d86fda01a06dd8504e
3,642,800
def skeda_from_skedadict(line_dict, filing_number, line_sequence, is_amended): """ We can either pass the header row in or not; if not, look it up. """ line_dict['transaction_id'] = line_dict['transaction_id'][:20] line_dict['line_sequence'] = line_sequence line_dict['superseded_by_amendment'] =...
2e07efa96f93ef777185e48bb07787774d4e5180
3,642,801
from datetime import datetime def oracle_to_date(string2convert, fmt, nlsparam=None): """ https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm TO_DATE(char [, fmt [, 'nlsparam' ] ]) TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of DATE datatyp...
eeaee6289d43bd446fbf27ce25ed87555a116ae4
3,642,802
import re def replace_whitespace(s, rep=' '): """Replace any length white spaces in the given string with a replacement. Parameters ---------- s : str The string in which any length whitespaces should be replaced. rep : Optional[str] The string with which all whitespace should be ...
b583a627dda830275822f6276af33b58afb55f1e
3,642,803
from sys import prefix def add_s3_prefix(s3_bucket): """ Ensure a bucket has the s3:// prefix :param s3_bucket: string - The bucket name """ s3_prefix = 's3://' return prefix(s3_bucket, s3_prefix)
6c6c7738b2a7d8972ae01f06c9d5cfb5a4d53502
3,642,804
import aiohttp async def handle_xml_response(request): """ Faking response """ response = load_data("equipment_data.xml") return aiohttp.web.Response( content_type="text/xml", body=response )
d56526414469424483fc8461c29f3b9c9963e698
3,642,805
import this def plugin_prefs(parent, cmdr, is_beta): """ Return a TK Frame for adding to the EDMC settings dialog. """ global listbox frame = nb.Frame(parent) nb.Label(frame, text="Faction Name:").grid(row=0,column=0) nb.Label(frame, text="System Name").grid(row=0,column=1) factio...
25df93343750cdac60604e6f5f91f84b3d105a12
3,642,806
from typing import Concatenate def Conv1D_positive_r(x, kernel_size): """index of r is hard-coded to 2!""" out1 = Conv1D(1, kernel_size=kernel_size, padding='valid', activation='linear')(x) out2 = Conv1D(1, kernel_size=kernel_size, padding='valid', activation='linear')(x) out3 = Conv1D(1, kernel_size=...
b66db8e65007d6044ad711b4ac9e7e9f967ecd91
3,642,807
def remove_innermost_template_usage(raw_code: str) -> str: """ If the code does not include templates, should return the exact same code FIXME: check if any task is templated """ _temp_code = raw_code template_types = get_all_template_types(raw_code) _temp_code = replace_template_type(_temp_code, templat...
92aa5164277064045e3436588f87067ecf626f07
3,642,808
def decrypt(text, key): """Decrypt the supplied text and return the result. Args: text (str): The text to decrypt. key (str): The key with which to perform the decryption. """ return transform(text, key, True)
bb7fb87622a38c3eba9156d9a8678357e40adcb3
3,642,809
def psi_gauss_1d(x, a: float = 1.0, x_0: float = 0.0, k_0: float = 0.0): """ Gaussian wave packet of width a and momentum k_0, centered at x_0 :param x: mathematical variable :param a: Amplitude of pulse :param x_0: Mean spatial x of pulse :param k_0: Group velocity of pulse """ re...
278ffa7f15fd8c52346f5b232a89d40ee48c8843
3,642,810
def get(address, limit=LIMIT): """ Recursively dereferences an address. Returns: A list containing ``address``, followed by up to ``limit`` valid pointers. """ result = [] for i in range(limit): # Don't follow cycles, except to stop at the second occurrence. if result.co...
1a3b7122ede440ddee773d7e260430517181909d
3,642,811
import unittest def elemwise_checker(op, expected_f, gap=None, test_dtypes=None, grad_test=True, name=None, gap_grad=None): """Return the appropriate test class for the elemwise on sparse. :param op: Op to test. :expected_f: Function use to compare. This function must act ...
e2ed86b905c086bfd1ceda228b6d0e19ed99a444
3,642,812
import os import numpy def plot_segments(track_generator, get_figure=False, plot_3D=False): """Plot the characteristic track segments from an OpenMOC simulation. This method requires that tracks have been generated by a TrackGenerator. Each segment is colored by the ID of the unique FSR it is within. ...
d6e29c550b2c13d0287359974892867fcd3404ab
3,642,813
def find_availability_by_year(park, campground, year, months=range(1, 13)): """ Parameters ---------- park : str campground : str year : str months : list list of months as str or int. Default is `range(1, 13)` Returns ------- list list of weekend availability...
28e81b2382f2733d1cc024a221c11feaa5ae5653
3,642,814
def seconds(value=None, utc=True, **kwargs): """ Converts value to seconds. If value is timedelta or struc_time, it will be just converted to seconds. If value is datetime instance it will be converted to milliseconds since epoch (UTC). If value is number, it's assumed that it's in milliseconds, so it w...
aced764fc038b316ca0b772254b6c6a44f333d9e
3,642,815
def fix_mocov2_state_dict(state_dict): """ Ref: https://bit.ly/3cDfGVA """ new_state_dict = {} for k, v in state_dict.items(): if k.startswith("model.encoder_q."): k = k.replace("model.encoder_q.", "") new_state_dict[k] = v return new_state_dict
13471d6863eb14eb3248f6d6e1d6b5882c341ed0
3,642,816
def get_perspective(image, contours, ratio): """ This function takes image and contours and returns perspective of this contours. :param image: image, numpy array :param contours: contours, numpy array :param ratio: rescaling parameter to the original image :return: warped image """ poin...
237db75baa8b72314e095f435075e75b8aa126b0
3,642,817
import bz2 import os def processFilesOpen(filename, filetype='file', subname='', zptr=None, **kwargs): """ Open a file for processing. If it is a compressed file, open for decompression. :param filetype: 'zip' if this is a zip archive. :param filename: name of the file (if a...
7a5cbab72ccc6b31530cb517fe672d2a49af4564
3,642,818
from pathlib import Path def load_model_selector(folder_path): """Load information about stored model selection Parameters ---------- folder_path : str path where .model_selector_result files are stored Returns ------- ModelSelector Information about model selection for e...
1e977ca422c5004e510f4989f7778bd0ca95f4c0
3,642,819
def generate_expired_date(): """Generate a datetime object NB_DAYS_BEFORE_DELETING_LIVE_RECORDINGS days in the past.""" return timezone.now() - timedelta( days=settings.NB_DAYS_BEFORE_DELETING_LIVE_RECORDINGS )
8d6fb9aae4cd5065416ccea4ba17d11080d8ccbc
3,642,820
from typing import Dict def make_dummy_authentication_request_args() -> Dict[str, bytes]: """Creates a request to emulate a login request. Returns: Dict[str, bytes]: Authenticator dictionary """ def _make_dummy_authentication_request_args(): args = { "username": ["foobar"...
2e0919bac46a5140a72c02ee09c1ce3b1cb9269a
3,642,821
def add_experiment_images_to_image_info_csv(image_info_df, experiment_xml_file): """ Goes through the xml file of the experiment and adds the info of its images to the image info dataframe. If the gene name is missing in the experiment, then this experiment is considered invalid. :param image_info_df: ...
99b545cba5aeb53f9ba2af2a1a5bf3acb72c6fa7
3,642,822
from typing import Iterable from re import T from typing import Optional from typing import Callable from re import U from typing import Iterator def dedup(iterable: Iterable[T], key: Optional[Callable[[T], U]] = None) -> Iterator[T]: """ List unique elements. >>> tuple(dedup([5, 4, 3, 5, 3, 3])) (3,...
8334d08f926584b1c976c24bde180930124b78ba
3,642,823
def get_product(barcode): """ Return information of a given product. """ return utils.fetch('api/v0/product/%s' % barcode)
2cc298cf640b4aa742c51b5d076f0021660fe0d5
3,642,824
def knn_matcher(arr2, arr1, neighbours=2, img_id=0, ratio_threshold=0.75): """Computes the inlier matches for given descriptor ararys arr1 and arr2 Arguments: arr2 {np.ndarray} -- Image used for finding the matches (train image) arr1 {[type]} -- Image in which matches are found (test image) ...
6397938b3624e1f32426b429f809e60e6bb72b49
3,642,825
from typing import Optional def get_virtual_network_gateway_bgp_peer_status(peer: Optional[str] = None, resource_group_name: Optional[str] = None, virtual_network_gateway_name: Optional[str] = None, ...
ade144cd6ce8c6827c0631a5c795d4ef2fbcaf7f
3,642,826
import re import logging import sys def check_wrs2_tiles(wrs2_tile_list=[], path_list=[], row_list=[]): """Setup path/row lists Populate the separate path and row lists from wrs2_tile_list Filtering by path and row lists separately seems to be faster than creating a new path/row field and filteri...
3876cb4e96a5f82f919c770798fe9393c2655877
3,642,827
import pathlib def cat(file_path: str) -> str: """pathlib.Path().read_textのshortcut Args: file_path (str): filepath Returns: str: file内の文字列 Example: >>> cat('unknown.txt') """ file_path = pathlib.Path(file_path) if file_path.is_file(): return file_path.r...
17eef15686a97e62380d077d678f2993e02e6d5c
3,642,828
def _get_role_by_name(role_name): """ Get application membership role Args: role_name (str): role name. Returns: int: application membership role id. """ base_request = BaseRequest() settings = Settings() params = { 'filter': 'name', 'eq': role_n...
0599f6c9571345318be71b9f453f89d1439c64fa
3,642,829
def parse_filename(filename, is_adversarial=False, **kwargs): """Parse the filename of the experment result file into a dictionary of settings. Args: filename: a string of filename is_adversarial: whether the file is from experiments/GIB_node_adversarial_attack. """ if is_adversaria...
1972de5803a8eb0ff50438adbe0adee1597199a9
3,642,830
def WHo_mt(dist, sigma): """ Speed Accuracy model for generating finger movement time. :param dist: euclidian distance between points. :param sigma: speed-accuracy trade-off variance. :return: mt: movement time. """ x0 = 0.092 y0 = 0.0018 alpha = 0.6 x_min = 0.006 x_max = 0....
36d8b7e913df658b52f1f03617d0b9817091d0ef
3,642,831
def find_next_sibling_position(element, tag_type): """ Gets current elements next sibling's (chosen by provided tag_type) actual character position in html document :param element: Whose sibling to look for, type: An object of class bs4.Tag :param tag_type: sibling tag's type (e.g. p, h2, div, span etc...
9b912fd9b7d30e81d6b4c2fec0e0573017b51a83
3,642,832
import subprocess def CheckOutput(cmd, **kwargs): """Call subprocess.check_output to get output. The subprocess.check_output return type is "bytes" in python 3, we have to convert bytes as string with .decode() in advance. Args: cmd: String of command. **kwargs: dictionary of keyword...
b4eb9ac552124c56f76c0c684c2d515558307aa4
3,642,833
def one_hot(arr, n_class=0): """Change labels to one-hot expression. Args: arr [np.array]: numpy array n_class [int]: number of class Returns: oh [np.array]: numpy array with one-hot expression """ if arr is None: return None if isinstance(arr, list) or isinstan...
ba22f7f1f7d97d5d3989eff69c42bdce2ca34e87
3,642,834
def boost_nfw_at_R(R, B0, R_scale): """NFW boost factor model. Args: R (float or array like): Distances on the sky in the same units as R_scale. Mpc/h comoving suggested for consistency with other modules. B0 (float): NFW profile amplitude. R_scale (float): NFW profile scale radius. ...
a7e13f5309fa663b41c5eec1c8518f444ba86b5f
3,642,835
def get_swatches(root): """Get swatch elements in the SVG""" swatches = {} for node in descendants(root): if "hasAttribute" not in dir(node) or not node.hasAttribute("id"): continue classname = extract_class_name(node.getAttribute("id")) if classname: swatches...
2d9cd4ca2ff034d4200b242eaa5592311c250155
3,642,836
def chunks(l, n): """ Split list in chunks - useful for controlling memory usage """ if n < 1: n = 1 return [l[i:i + n] for i in range(0, len(l), n)]
d878aeb50bd42c9f5a2060f4bb2747aecb1a3b58
3,642,837
def UserLevelAuthEntry(val=None): """Provide a 2-tuple of user and level * user: string * level: oneof(ACCESS_LEVELS) currently: GUEST, USER, ADMIN """ if len(val) != 2: raise ValueError('UserLevelAuthEntry entry needs to be a 2-tuple ' '(name, ac...
e26c723a55d215c71d46d2e45e30b3a39d78723d
3,642,838
import tokenize def parseCookie(headers): """Bleargh, the cookie spec sucks. This surely needs interoperability testing. There are two specs that are supported: Version 0) http://wp.netscape.com/newsref/std/cookie_spec.html Version 1) http://www.faqs.org/rfcs/rfc2965.html """ cookies = []...
f12cfc5303f466eebe3f1b2731d22d02caf12b1d
3,642,839
import psutil import os def get_system_metrics(): """ For keys in fields >>> from serverstats import get_system_metrics >>> fields = dict() >>> dl = get_system_metrics() >>> _fields = { ... 'cpu': ['usage_percent', 'idle_percent', 'iowait', ... 'avg_load_15_min', 'avg_...
b612ada76bd829a76dfb35eb070e9788ef75ce78
3,642,840
def FilterKeptAttachments( is_description, kept_attachments, comments, approval_id): """Filter kept attachments to be a subset of last description's attachments. Args: is_description: bool, if the comment is a change to the issue description. kept_attachments: list of ints with the attachment ids for a...
89732832db557835a5dea1ef10229bfdd809d304
3,642,841
import os def scan_fixtures(path): """Scan for fixture files on the given path. :param path: The path to scan. :type path: str :rtype: list :returns: A list of three-element tuples; the app name, file name, and relative path. """ results = list() for root, dirs, files in os.walk(pat...
c85e8281a2f9005feb1801083138b55cb5079cf6
3,642,842
import json import os import _thread def invocations(): """Do an inference on a single batch of data. In this sample server, we take data as CSV, convert it to a pandas data frame for internal use and then convert the predictions back to CSV (which really just means one prediction per line, since there's ...
ab602a874d151869f000d6e0d4b8a5f085be6b7d
3,642,843
import piaplib.book.__main__ import piaplib.book.__main__ def main(argv=None): """The main event""" try: if 'piaplib.book.__main__' not in sys.modules: else: piaplib.book.__main__ = sys.modules["""piaplib.book.__main__"""] if piaplib.book.__main__.__name__ is None: raise ImportError("Failed to import pi...
61ce42c99b933f95596e6cde788890984f270fee
3,642,844
from datetime import datetime def today() -> date: """ **today** returns today's date :return present date """ return datetime.datetime.now().date()
b5c7b19d9ff02993ab63de2bebd3d7bcdd24da59
3,642,845
def get_word_size(word,font_size): """get's the dimansions of any given word for any giving font size""" Font=ImageFont.truetype(FONT, font_size) return Font.getsize(word)
5742f9ee4377d2f251f75acdfceb1c8c1884fde1
3,642,846
def get_id(asset, **kwargs): """Get an asset by the unique id. The key for the id must have 'id' in the name in the kwargs. Example:: get_id(Foo, foo_id=1) # works get_id(Foo, foo=1) # TypeError """ id_key = next(_parse_id(kwargs), None) if id_key is None: raise Typ...
d4c1864acca7aecaed91f550359e7d9541f0de2f
3,642,847
def put_study_document(request): """PUT method for editing an existing study. Adds "resource_type" -> "study" then calls generic `put_document`. See `finish_write_operation` for description of the response. """ request.matchdict['resource_type'] = 'study' return put_document(request)
244cfecf0f87187334ab599a477e1e3459f549c6
3,642,848
def create_command(input_file, columns_to_use, column_separator, output_file): """ This function creates the linux command to filter the columns and creating the output file :param input_file: A valid file path to raw data file :param columns_to_use: Indexes of the columns that needs to be filtered out ...
e14d88bf843190890827d2a157d02faf60917800
3,642,849
def _new_data_generated(dataset, datagen): """ Function to put augmented data in directories :param dataset: The path for the specified directory :param datagen: The augmented data :return: The new data to use for model """ new_data = datagen.flow_from_directory( dataset, tar...
659edb0eb32e5609c8a0ff11814c5c0d317b134c
3,642,850
def findOutNode( node, testFunc, fallback=... ): """ get node and all its parents, inner to outer order """ for out_node in getOutNodes( node ): if testFunc( out_node ): return out_node if fallback is not ...: return fallback raise Exception( 'cannot find out node' )
73a7f88dee12dd82edecaf173b6fecb48b2ce86b
3,642,851
import logging def lookup_cpe(vendor, product, cpe_type, cpe_table, remap): """Identify the correct vendor and product values for a CPE This function attempts to determine the correct CPE using vendor and product values supplied by the caller as well as a remapping dictionary for mapping these values...
5a6e2e735daa50d3d2a19022db002ebfc647335c
3,642,852
def main(): """main function of git learning """ return 'Google git'
a7296a18657643188ef58131fe012df6543f808e
3,642,853
import numpy import signal def SSIM(img1, img2, cs_map=False): """Return the Structural Similarity Map corresponding to input images img1 and img2 (images are assumed to be uint8) This function attempts to mimic precisely the functionality of ssim.m a MATLAB provided by the author's of SSIM ...
6fe795ac4818ec06db7ed3cd66f52a169dccbc24
3,642,854
def covariance(prices: np.ndarray) -> np.ndarray: """Calculate covariance matrix. Args: prices: Prices of market data. Returns: Covariance matrix. """ Q = np.cov(prices.T, ddof=0) return np.array(Q)
d0870a9ba6fdf58a0d4242f4c1638de7f05b738a
3,642,855
def fiveplates_clean_design_file(field, designID): """ string representation of targets_clean file for field within fiveplates_field_files zip file. Parameters ---------- field : str identifier of field, e.g. 'GG_010' """ return f'{field}_des{designID}_targets_clean.txt'
c6e5c60ad08aa3e4162700f3d48e58d35a57486e
3,642,856
import itertools def setup_figure(diff=False): """Set diff to True if you want an additional panel showing pair-wise differences in accuracy""" fig = plt.figure(figsize=(2*3.385, 2*3)) # two column figure for bio-informatics plt.subplots_adjust(left=0.15, bottom=0.1, right=0.98, top=0.93, wspace=0.05, hspace=0...
6c28eb8fd9f633029fad707bdfee8806fa6a3b72
3,642,857
def load_axon_morphometrics(morphometrics_file): """ :param morphometrics_file: absolute path of file containing the morphometrics (must be .csv, .xlsx or pickle format) :return: stats_dataframe: dataframe containing the morphometrics """ # If string, convert to Path objects morphometrics_f...
b89bdac95660fd6c6e84bfcace4125d2840347ca
3,642,858
def get_input_costs( inputs, cost_class="monetary", unit="billion_2015eur", mapping=COST_NAME_MAPPING, **kwargs ): """ Get costs used as model inputs """ costs = {} for var_name, var_data in inputs.data_vars.items(): if "costs" not in var_data.dims or not var_name.startswith("cost"):...
02671abda50889bd51fb91a5629b718882434745
3,642,859
import gettext def render_template(language, context, data, template): """Renders HTML display of metadata XML""" env = Environment(extensions=['jinja2.ext.i18n'], loader=FileSystemLoader(context.ppath)) env.install_gettext_callables(gettext, ngettext, newstyle=True) template_f...
6c19a53c1038681c2f5f4d014ec4ed2aae9a50af
3,642,860
def ht_26(): """Making one Hash table instance with 26 key val pairs inserted.""" ht = HashTable() count = 1 for char in letters: ht.set(char, count) count += 1 return ht
8ab9d1b887da2c9719a1b23d2817b66827b7cc3c
3,642,861
import time def get_session(uuid): """ Api.get_session method returns: [uuid, users, payload, state, ts] 200 -- session created 400 -- wrong arguments 403 -- wrong authorization 404 -- session not found 500 -- internal error """ conn = conn_get() session = database.get_ses...
5657a53dc60b8d8743ccaac79041208c11caa07c
3,642,862
from typing import Iterable import io def fetch_data( indicator: WorldBankIndicators, country_names: Iterable[str], fill_missing=None ) -> pd.DataFrame: """ Fetch data from the market_data_cache collection (not to be confused with the market_quote_cache collection) and ensure the specified countries a...
8f0778aa28acb4fefeaf1d889d1650994357a787
3,642,863
from . import authinfos def _(dbmodel, backend): """ get_backend_entity for Django DbAuthInfo """ return authinfos.DjangoAuthInfo.from_dbmodel(dbmodel, backend)
fa0529b038e4321b2f7e535afb82d16455ef4853
3,642,864
def wavelen_diversity_doppler_est(echo, prf, samprate, bandwidth, centerfreq): """Estimate Doppler based on wavelength diversity. It uses slope of phase of range frequency along with single-lag time-domain correlator approach proposed by [BAMLER1991]_. Parameters ...
d1fe5cb45b9e850fe4da83700fc061e715c76502
3,642,865
def _parse_line(line): """ Parse node string representation and return a dict with appropriate node values. """ res = {} if 'leaf' in line: res['is_leaf'] = 1 res['leaf_val'] = _parse_leaf_node_line(line) else: res['is_leaf'] = 0 res['feature'], res['threshold']...
014c6d2e9d61798d55af2725b79ff404f9aa7ff3
3,642,866
from typing import Optional def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> Optional[str]: """Generates a wrapper for richcompare dunder methods.""" # Sort for determinism on Python 3.5 matches = sorted([name for name in RICHCOMPARE_OPS if cl.has_method(name)]) if not matches: ...
cbbc66a22ee61ed869331fbecd59eb615588fd48
3,642,867
def display_credentials(): """ Function that displays all saved credentials """ return Credentials.display_credentials()
09e474a5b76ae3224571cf9d2d05ea5811e7fbf1
3,642,868
def render_diff_report(): """ Render a summary of the diffs found and/or changed. Returns a string. Dependencies: config settings: action, templates, report_order globals: diff_dict, T_NAME_KEY modules: nori """ if nori.core.cfg['action'] == 'diff': diff_report = ...
da02e6b9dee4424d217d0f0839938a1aff9250df
3,642,869
def get_step_handler_for_gym_env(gym_env_name: str, cfg: Configuration) -> StepRewardDoneHandler: """Return an example step handler for the given gym environemtn name, that uses the given config file.""" if gym_env_name == 'Acrobot-v1': handler = AcrobotStepHandler(cfg) elif gym_env_name == 'Ca...
51164ee7c3da5184f221d1e658c7e1ddc73585de
3,642,870
import os def get_post_ids() -> list: """ """ create_directory(WORK_PATH) list_of_files_and_folders = os.listdir(WORK_PATH) list_of_folders = [] for p in list_of_files_and_folders: path = f'{WORK_PATH}/{p}' if os.path.isdir(path): list_of_folders.append(p) lis...
45abeccb2af1edb382d720981d3e8b14c08133ca
3,642,871
import traceback def get_module(mod_name): """Import module and return.""" try: return import_module(mod_name) except ImportError: logger.error('Failed to import module "%s".' % mod_name) logger.error(traceback.format_exc()) raise
7cb81ff17f3d49bee3d53549e415c14ff4c13512
3,642,872
def sort_ranks(ranks): """Sort ranks by MAIN_RANKS order. Parameters ---------- ranks Ranks to sort Returns ------- Sorted ranks """ ret = False ranks = list(ranks) if not isinstance(ranks, list) else ranks if len(ranks) > 0: ret = [rank for rank in VA...
e86b985a83153c46f53d7d31f849d1c5c10a6d66
3,642,873
def formalize_rules(list_rules): """ Gives an list of rules where facts are separeted by coma. Returns string with rules in convinient form (such as 'If' and 'Then' words, etc.). """ text = '' for r in list_rules: t = [i for i in r.split(',') if i] text +=...
d8fbb024f38ae097efa42f95efe6b5d3b5adbd71
3,642,874
def filenames_to_labels(filenames, filename_label_dict): """Converts filename strings to integer labels. Args: filenames (List[str]): The filenames of the images. filename_label_dict (Dict[str, int]): A dictionary mapping filenames to integer labels. Returns: ndarray: Integer labels """ re...
7dad11665aa3858dac7cd91757367f4ab72629cb
3,642,875
def load_model(): """ 保存した提供されているモデルを読み込む Returns ---------- model 提供されたmodel tokernizre 提供されたヤツ(よくわかってない) """ with open(MODEL_DIR + 'model.pickle', 'rb') as f: model = pick.load(f) with open(MODEL_DIR + 'tokenizer.pickle', 'rb') as f: tokenizer = pic...
abea695c9e56af585e37694b8a022b8634ccfe79
3,642,876
from datetime import datetime def post(post_id): """View function for post page""" # Form object: `Comment` form = CommentForm() # form.validate_on_submit() will be true and return the # data object to form instance from user enter, # when the HTTP request is POST if form.validate_on_subm...
28a5e611e370a33a609cabb4d3ec827284911ccc
3,642,877
def pipe(val, *funcs): """Pipe a value through a sequence of functions I.e. ``pipe(val, f, g, h)`` is equivalent to ``h(g(f(val)))`` >>> double = lambda i: 2 * i >>> pipe(3, double, str) '6' """ if not funcs: raise PipeNotGivenAnyFunctions if any_is_async(funcs): return...
c2815c7842df2a1d1e07a628b613da0a8ffd35f5
3,642,878
def do_query(method, query, values): """Executes a query on a DFP API method, returning a list of results.""" # Trap exceptions here instead of in caller? statement = dfp.FilterStatement(query, values) data = [] while True: response = method(statement.ToStatement()) if 'results' in response: d...
3b53e992e4cb49b1814593147826f3d3b4e2bfa8
3,642,879
def markdown_format(text): """ The outside param 'name' is similar to "tag" (in 'usage') which it'll determines how you use it, e.g. {{ THING | FILTER }}. Just a reminder for tag, {% my_post_count %} for filter, {{ post.body | truncatewords:30 }} ...
663781e441b305a26bb0d85fb45302539159aa92
3,642,880
from typing import List def _find_tex_env_recursive(original_s: str, s: str, offset: int = 0, depth: int = 0) -> List: """ Find all environments. :param s: Latex string code :param offset: Offset applied to the search :return: Tuple of all commands """ tags = find_tex_commands(s, offset=o...
a92f25a19be59ab8f89540501bf2a7b9975c3ea9
3,642,881
from typing import Iterable from typing import List def group_by_instance_type( jobs: Iterable[JobConfiguration], ) -> List[List[JobConfiguration]]: """ Group job-configuration into different queues depending on which instance each job should be run. This returns a list of the different queues. >...
8c9baf76de4089972c87f7f71b66abec236e23d3
3,642,882
import scipy def integral_func(phi, th1, n): """ Used in computing the continuous hypersphere cap intersection below. """ return np.sin(phi)**(n-2) * scipy.special.betainc( (n-2)/2 , 1/2, 1-( (np.tan(th1))/(np.tan(phi)) )**2 )
f086da8f5086d13abfced0c05b41d419d4e7d6b0
3,642,883
def test_model(image_path, class_names, img_height, img_width): """测试你的模型""" img = keras.preprocessing.image.load_img(image_path, target_size=(img_height, img_width)) # 将图片加载为PIL格式 input_array = keras.preprocessing.image.img_to_array(img) # 将PIL映像实例转换为Numpy数组 input_array = np.array([input_array]) # 来...
5f661c231dbc459e9e6d24f9ddeecbed15dc0e0d
3,642,884
def order(order_id,complete): """ Charge completion return URL. Once the customer is redirected back to this site from the authorization page, we search for the charge based on the provided `order_id`. """ return render_template( "complete.html", order_id=order_id, comp...
c7d7d385c23ef24748d5b4e847aaf9acd2212cbd
3,642,885
import logging def load_dimension_subdag( parent_dag_name, task_id, redshift_conn_id, *args, **kwargs): """ A python function with arguments, which creates a dag :param parent_dag_name: imp ({parent_dag_name}.{task_id}) :param task_id: imp {task_id} :param redshift_...
d68348b51aef7ad38999b2383f41721a178af451
3,642,886
import os def get_ns_lns_ids_config_file(): """Reads node_id to host name mapping from one of the config files in the map""" assert exp_config.node_config_folder is not None and os.path.exists(exp_config.node_config_folder) files = os.listdir(exp_config.node_config_folder) # read mapping from any fil...
17e162aaf68ef4df8ba730c3104b57e99ee783be
3,642,887
import os import subprocess def find(name, environment=None, guess=None): """Finds a particular binary on this system. Attempts to find the binary given by ``name``, first checking the value of the environment variable named ``environment`` (if provided), then by checking the system path, then finall...
d3f8d4375804dc54e0187b6b3f8ab53b2120acd7
3,642,888
import random import string import os from datetime import datetime def upload_to(path): """ Generates unique ascii filename before saving. Supports strftime() formatting as django.db.models.FileField.upload_to does. Example: class SomeModel(models.Model): picture = models.ImageF...
4d3b9ff7f95d20bc4234ce27453ad582e6218a18
3,642,889
from typing import List def standardize_measurements_lastref(measurements: List[Measurement], remove_ref: bool = True) \ -> List[Measurement]: """ Sets the standardization of all measurement to the Reference Measurement before """ last_null_meas = None clean_measurements = [] for measurement ...
34c73375fcada6a19e9c7e876b252f44fc6f9415
3,642,890
import os import re def blg2texkey(filename): """Extract TeX keys from a .blg file.""" keys = [] if not os.path.exists(filename): LOGGER.error("File %s not found.", filename) return keys with open(filename, "r") as f: lines = f.readlines() # regexp to match 'Warning--I didn...
11eb2bbffbcb6052638a53b25ca60a2ace63f3a6
3,642,891
from typing import get_args import torch def build_train_valid_test_data_iterators( build_train_valid_test_datasets_provider): """XXX""" args = get_args() (train_dataloader, valid_dataloader, test_dataloader) = (None, None, None) print_rank_0('> building train, validation, and test datasets ...
1bf5c79519df289f88ab5372c6ccb963a77ce5cd
3,642,892
import os def get_lib_ver(library_path=""): """Returns the version of the Minipresto library. ### Parameters - `library_path`: The Minipresto library directory.""" version_file = os.path.join(library_path, "version") try: with open(version_file, "r") as f: for line in f: ...
e42b029762ca8e6baee12062464134f13ae71522
3,642,893
def width(): """Get console width.""" x, y = get() return x
a6090038a4c97e215e57e0f7966ec41c09682f90
3,642,894
import yaml def load_yaml_config(path): """returns the config parsed based on the info in the flags. Grabs the config file, written in yaml, slurps it in. """ with open(path) as f: config = yaml.load(f, Loader=yaml.FullLoader) return config
0ee100a6e4d25881f8b8ab4ced723f600e878e28
3,642,895
def convert_year(years, debug=False): """Example usage: db['date'] = cln.convert_year(db['date']) """ for i, yr in years.iteritems(): if debug: print(yr) print(type(yr)) if yr is None: years.set_value(i, np.nan) continue if is_int(yr): ...
605ab3d0554942de9a3ea46f35a304d6cd25a7ed
3,642,896
def home(request): """View function for home page of site.""" return laboratorio_list(request)
a06bcbdb2b7edb79ee1d30cd69329742b24f2f49
3,642,897
def scan_armatures(context): """ scans the selected objects or the scene for a source (regular) armature and a destination (Make Human) armature """ src = ( scan_for_armature(context.selected_objects) or scan_for_armature(context.scene.objects) ) dst = ( s...
a613c39767280919a684dcf8eaa4e537ffc2ebb3
3,642,898
def populate_instance(msg, inst): """ :param msg: contains the values to use to populate inst. :param inst: message class instance to populate. :return: an instance of the provided message class, with its fields populated according to the values in msg """ return _to_inst(msg, type(inst).__name_...
7a148629ad178be632c9388fc536e7fea02c44ed
3,642,899