content
stringlengths
22
815k
id
int64
0
4.91M
def painel(request): """ Exibe o painel do usuário. """ return render(request, "lancamentos/painel.html")
6,700
def dialogue(bdg, activate_audio, activate_proximity, mode="server"): """ Attempts to read data from the device specified by the address. Reading is handled by gatttool. :param bdg: :return: """ ret = bdg.pull_data(activate_audio, activate_proximity) addr = bdg.addr if ret == 0: ...
6,701
def which(program, mode=os.F_OK | os.X_OK, path=None): """ Mimics the Unix utility which. For python3.3+, shutil.which provides all of the required functionality. An implementation is provided in case shutil.which does not exist. :param program: (required) string Name of program (can...
6,702
def q_statistic(y, c1, c2): """ Q-Statistic. Parameters ---------- y : numpy.array Target sample. c1 : numpy.array Output of the first classifier. c2 : numpy.array Output of the second classifier. Returns ------- float Return the Q-Statistic measur...
6,703
def nan_helper(y): """Helper to handle indices and logical indices of NaNs. Input: - y, 1d numpy array with possible NaNs Output: - nans, logical indices of NaNs - index, a function, with signature indices= index(logical_indices), to convert logical indices of NaNs to 'equ...
6,704
def lid_mle_amsaleg(knn_distances): """ Local intrinsic dimension (LID) estimators from the papers, 1. Amsaleg, Laurent, et al. "Estimating local intrinsic dimensionality." Proceedings of the 21th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining. ACM, 2015. 2. Ma, Xingjun,...
6,705
def _rebase_bv(bv: BinaryView, dbg: DebugAdapter.DebugAdapter) -> BinaryView: """Get a rebased BinaryView for support of ASLR compatible binaries.""" new_base = dbg.target_base() if core_ui_enabled() and new_base != bv.start: dbg.quit() raise Exception('[!] Can\'t do necessary rebase in GUI,...
6,706
def convert_parameters(child, text=False, tail=False, **kwargs): """ Get child text or tail :param child: :param text: :param tail: :return: """ p = re.compile(r'\S') # Remove empty info child_text = child.text if child.text else '' child_tail = child.tail if child.tail else ...
6,707
def extend_drag_table(): """ Make an extended table that covers a longer range of Reynolds numbers for each mach value. For low Reynolds values, this uses lower mach number coefficients, and for high Reynolds values it uses higher mach number coefficients. The coefficients are copied with an offse...
6,708
def plugin_unloaded(): """On plugin unloaded. """ events.broadcast("plugin_unloaded")
6,709
def Get_Country_Name_From_ISO3_Extended(countryISO): """ Creates a subset of the quick chart data for a specific country. The subset includes all those rows containing the given country either as the origin or as the country of asylum. """ countryName = "" # June-22 - This function has been u...
6,710
def individual_concentration(positions, base_capital): """ Print the individual concentration in the portfolio given existing positions and base capital :param positions: list of dict :param base_capital: int or float """ for i in positions: ticker = two.lookup_ticker(i['instrumentId'])[...
6,711
def to_cpu(x): """ Move cupy arrays (or dicts/lists of arrays) to CPU """ if len(sys.argv) > 1: if type(x) == dict: return {k:to_cpu(a) for (k, a) in x.items()} elif type(x) == list: return [to_cpu(a) for a in x] else: return cp.asnumpy(x) else: return x
6,712
def write_deltapack(statedir, chrootdir, version, manifest, previous_manifest, bundle_name): """Output deltapack to the statedir.""" out_path = os.path.join(statedir, "www", "update", version) delta_path = os.path.join(out_path, "delta") if not os.path.isdir(out_path): os.makedirs(out_path, exis...
6,713
def parse_mapfile(map_file_path): """Parse the '.map' file""" def parse_keyboard_function(f, line): """Parse keyboard-functions in the '.map' file""" search = re.search(r'(0x\S+)\s+(0x\S+)', next(f)) position = int( search.group(1), 16 ) length = int( search.group(2), 16 ) search = re.search(r'0x\S+\s+(\...
6,714
def thetaG(t,t1,t2): """ Return a Gaussian pulse. Arguments: t -- time of the pulse t1 -- initial time t2 -- final time Return: theta -- Scalar or vector with the dimensions of t, """ tau = (t2-t1)/5 to = t1 + (t2-t1)/2 thet...
6,715
def grouped(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n]
6,716
def test_backup_block_deletion(client, core_api, volume_name, set_backupstore_s3): # NOQA """ Test backup block deletion Context: We want to make sure that we only delete non referenced backup blocks, we also don't want to delete blocks while there other backups in progress. The reason for th...
6,717
def choose_string(g1, g2): """Function used by merge_similar_guesses to choose between 2 possible properties when they are strings. If the 2 strings are similar, or one is contained in the other, the latter is returned with an increased confidence. If the 2 strings are dissimilar, the one with the...
6,718
def WorkPath(): """ WorkPath 2016.04.09 L'utilisation de cette fonction permet d'utiliser des chemins d'accès relatifs entre scripts et dossiers Cette fonction détermine automatiquement où le script est lancé : Soit sur un pc en travail local ...
6,719
def update_alert_command(client: MsClient, args: dict): """Updates properties of existing Alert. Returns: (str, dict, dict). Human readable, context, raw response """ alert_id = args.get('alert_id') assigned_to = args.get('assigned_to') status = args.get('status') classification = a...
6,720
def create_payment(context: SagaContext) -> SagaContext: """For testing purposes.""" context["payment"] = "payment" return context
6,721
def test_plot_data(example_pm_data, modified_ansatz): """Load example data and test plotting.""" fitter = ThresholdFit(modified_ansatz=modified_ansatz) figure = plt.figure() fitter.plot_data(example_pm_data, "p_bitflip", figure=figure)
6,722
async def TwitterAuthURLAPI( request: Request, current_user: User = Depends(User.getCurrentUser), ): """ Twitter アカウントと連携するための認証 URL を取得する。<br> 認証 URL をブラウザで開くとアプリ連携の許可を求められ、ユーザーが許可すると /api/twitter/callback に戻ってくる。 JWT エンコードされたアクセストークンがリクエストの Authorization: Bearer に設定されていないとアクセスできない。<br> ""...
6,723
def post_sunday(request): """Post Sunday Details, due on the date from the form""" date_form = SelectDate(request.POST or None) if request.method == 'POST': if date_form.is_valid(): groups = DetailGroup.objects.filter(semester=get_semester()) details = settings.SUNDAY_DETAIL...
6,724
def reconstruct(lvl: Level, flow_dict: Dict[int, Dict[int, int]], info: Dict[int, NodeInfo]) -> List[List[int]]: """Reconstruct agent paths from the given flow and node information""" paths: List[List[int]] = [[]] * len(lvl.scenario.agents) start_flows = flow_dict[0] agent_starts = {agent.origin: i for ...
6,725
def test_single_agent() -> None: """ Create an environment and perform different action types to make sure the commands are translated correctly between griddly and enn wrappers """ env_cls = create_env( yaml_file=os.path.join(init_path, "env_descriptions/test/test_actions.yaml") ) e...
6,726
def add_aggregate_algo(ctx, data): """Add aggregate algo. The path must point to a valid JSON file with the following schema: \b { "name": str, "description": path, "file": path, "permissions": { "public": bool, "authorized_ids": list[str], ...
6,727
def run_with_reloader(root, *hotkeys): """Run the given application in an independent python interpreter.""" import signal signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) reloader = Reloader() try: if os.environ.get('TKINTER_MAIN') == 'true': for hotkey in hotkeys...
6,728
def arch_explain_instruction(bv, instruction, lifted_il_instrs): """ Returns the explanation string from explanations_en.json, formatted with the preprocessed instruction token list """ if instruction is None: return False, [] parsed = parse_instruction(bv, instruction, lifted_il_instrs) if len(...
6,729
def execute_tuning(data: Dict[str, Any]) -> dict: """Get configuration.""" from lpot.ux.utils.workload.workload import Workload if not str(data.get("id", "")): message = "Missing request id." mq.post_error( "tuning_finish", {"message": message, "code": 404}, ...
6,730
def get_subnet_mask(subnet: int, v6: bool) -> int: """Get the subnet mask given a CIDR prefix 'subnet'.""" if v6: return bit_not((1 << (128 - subnet)) - 1, 128) else: return bit_not((1 << (32 - subnet)) - 1, 32)
6,731
def show_notification_activity_relays(message, append=False): """ Show the notification on the Text Box Widget for the action on the relays :param message: The message to display :param append: Enable or disable notification append on the Text Area Widget :return: None """ if append: ...
6,732
def get_parser(): """Return base parser for scripts. """ parser = argparse.ArgumentParser() parser.add_argument('config', help='Tuning configuration file (examples: configs/tuning)') return parser
6,733
def cli( input_maps_directory, data_group, caps_directory, participants_tsv, gpu, n_proc, batch_size, # use_extracted_features, selection_metrics, diagnoses, multi_cohort, ): """Save the output tensors of a trained model on a test set. INPUT_MAPS_DIRECTORY is the MAP...
6,734
def arm_and_takeoff(aTargetAltitude, vehicle): """ Arms vehicle and fly to aTargetAltitude. """ print "Basic pre-arm checks" if vehicle.mode.name == "INITIALISING": print "Waiting for vehicle to initialise" time.sleep(1) while vehicle.gps_0.fix_type < 2: print "Waiting ...
6,735
def home(request): """return HttpResponse('<h1>Hello, Welcome to this test</h1>')""" """Le chemin des templates est renseigne dans "DIRS" de "TEMPLATES" dans settings.py DONC PAS BESOIN DE RENSEIGNER LE CHEMIN ABSOLU""" return render(request, "index.html")
6,736
def cd(path): """Context manager to switch working directory""" def normpath(path): """Normalize UNIX path to a native path.""" normalized = os.path.join(*path.split('/')) if os.path.isabs(path): return os.path.abspath('/') + normalized return normalized path = normpath(path) cwd = os.getc...
6,737
def validate_module_specific_inputs(scenario_id, subscenarios, subproblem, stage, conn): """ :param subscenarios: :param subproblem: :param stage: :param conn: :return: """ params = get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn) df = cursor_to_df(param...
6,738
def extract_commands(data, *commands): """Input function to find commands output in the "data" text""" ret = "" hostname = _ttp_["variable"]["gethostname"](data, "input find_command function") if hostname: for command in commands: regex = r"{}[#>] *{} *\n([\S\s]+?)(?={}[#>]|$)".forma...
6,739
def get_version() -> str: """ Returns the version string for the ufotest project. The version scheme of ufotest loosely follows the technique of `Semantic Versioning <https://semver.org/>`_. Where a minor version change may introduce backward incompatible changes, due to the project still being in activ...
6,740
async def clear_pending_revocations(request: web.BaseRequest): """ Request handler for clearing pending revocations. Args: request: aiohttp request object Returns: Credential revocation ids still pending revocation by revocation registry id. """ context: AdminRequestContext = ...
6,741
def verify_bpl_svcomp(args): """Verify the Boogie source file using SVCOMP-tuned heuristics.""" heurTrace = "\n\nHeuristics Info:\n" if args.memory_safety: if not (args.only_check_valid_deref or args.only_check_valid_free or args.only_check_memleak): heurTrace = "engage valid deference checks.\n" ...
6,742
def add_filter(field, bind, criteria): """Generate a filter.""" if 'values' in criteria: return '{0}=any(:{1})'.format(field, bind), criteria['values'] if 'date' in criteria: return '{0}::date=:{1}'.format(field, bind), datetime.strptime(criteria['date'], '%Y-%m-%d').date() if 'gte' in c...
6,743
def ireject(predicate, iterable): """Reject all items from the sequence for which the predicate is true. ireject(function or None, sequence) --> iterator :param predicate: Predicate function. If ``None``, reject all truthy items. :param iterable: Iterable to filter through. :yields: A ...
6,744
def test_do_auto_false(): """ """ Npts1, Npts2, Nran = 300, 180, 1000 with NumpyRNGContext(fixed_seed): sample1 = np.random.random((Npts1, 3)) sample2 = np.random.random((Npts2, 3)) randoms = [Nran] # result1 = wp_jackknife(sample1, randoms, rp_bins, pi_max, # period...
6,745
def construct_config_error_msg(config, errors): """Construct an error message for an invalid configuration setup Parameters ---------- config: Dict[str, Any] Merged dictionary of configuration options from CLI, user configfile and default configfile errors: Dict[str, Any] Di...
6,746
def isMSAADebugLoggingEnabled(): """ Whether the user has configured NVDA to log extra information about MSAA events. """ return config.conf["debugLog"]["MSAA"]
6,747
def _haversine_GC_distance(φ1, φ2, λ1, λ2): """ Haversine formula for great circle distance. Suffers from rounding errors for antipodal points. Parameters ---------- φ1, φ2 : :class:`numpy.ndarray` Numpy arrays wih latitudes. λ1, λ2 : :class:`numpy.ndarray` Numpy arrays wih ...
6,748
def differentiate_branch(branch, suffix="deriv"): """calculates difference between each entry and the previous first entry in the new branch is difference between first and last entries in the input""" def bud(manager): return {add_suffix(branch,suffix):manager[branch]-np.roll(manager[branch],1)} return bud
6,749
def etf_holders(apikey: str, symbol: str) -> typing.Optional[typing.List[typing.Dict]]: """ Query FMP /etf-holder/ API. :param apikey: Your API key. :param symbol: Company ticker. :return: A list of dictionaries. """ path = f"etf-holder/{symbol}" query_vars = {"apikey": apikey} retu...
6,750
def clean_visibility_flags(horizon_dataframe: pd.DataFrame) -> pd.DataFrame: """ assign names to unlabeled 'visibility flag' columns -- solar presence, lunar/interfering body presence, is-target-on-near-side-of-parent-body, is-target-illuminated; drop then if empty """ flag_mapping = { u...
6,751
def insert_content_tetml_word() -> None: """Store the parse result in the database table content_tetml_word.""" if not cfg.glob.setup.is_simulate_parser: cfg.glob.parse_result_page_words[cfg.glob.JSON_NAME_NO_LINES_IN_PAGE] = cfg.glob.parse_result_no_lines_in_page cfg.glob.parse_result_page_word...
6,752
def test_sp_mp2_rhf_fc(mtd, opts, h2o): """cfour/???/input.dat #! single point MP2/qz2p on water """ h2o = qcdb.set_molecule(h2o) qcdb.set_options(opts) g, jrec = qcdb.gradient(mtd, return_wfn=True, molecule=h2o) print(g) assert compare_arrays(rhf_mp2_fc, g, atol=1.0e-5) ## from ...
6,753
def calib(phase, k, axis=1): """Phase calibration Args: phase (ndarray): Unwrapped phase of CSI. k (ndarray): Subcarriers index axis (int): Axis along which is subcarrier. Default: 1 Returns: ndarray: Phase calibrated ref: [Enabling Contactless Detection of Mov...
6,754
def rescale_as_int( s: pd.Series, min_value: float = None, max_value: float = None, dtype=np.int16 ) -> pd.Series: """Cannot be converted to njit because np.clip is unsupported.""" valid_dtypes = {np.int8, np.int16, np.int32} if dtype not in valid_dtypes: raise ValueError(f"dtype: expecting [{va...
6,755
def format_headers(headers): """Formats the headers of a :class:`Request`. :param headers: the headers to be formatted. :type headers: :class:`dict`. :return: the headers in lower case format. :rtype: :class:`dict`. """ dictionary = {} for k, v in headers.items(): if isinstanc...
6,756
def read_analogy_file(filename): """ Read the analogy task test set from a file. """ section = None with open(filename, 'r') as questions_file: for line in questions_file: if line.startswith(':'): section = line[2:].replace('\n', '') continue...
6,757
def decode_field(value): """Decodes a field as defined in the 'Field Specification' of the actions man page: http://www.openvswitch.org/support/dist-docs/ovs-actions.7.txt """ parts = value.strip("]\n\r").split("[") result = { "field": parts[0], } if len(parts) > 1 and parts[1]: ...
6,758
def process_targets(targets): """Process cycle targets for sending.""" for subscription_id, subscription_targets in groupby( targets, key=lambda x: x["subscription_id"] ): try: process_subscription_targets(subscription_id, subscription_targets) except Exception as e: ...
6,759
def compute_norm(x_train, in_ch): """Returns image-wise mean and standard deviation per channel.""" mean = np.zeros((1, 1, 1, in_ch)) std = np.zeros((1, 1, 1, in_ch)) n = np.zeros((1, 1, 1, in_ch)) # Compute mean. for x in tqdm(x_train, desc='Compute mean'): mean += np.sum(x, axis=(0, 1...
6,760
def _nonempty_line_count(src: str) -> int: """Count the number of non-empty lines present in the provided source string.""" return sum(1 for line in src.splitlines() if line.strip())
6,761
def run(data, results_filepath, methods=None, combiner='summa'): """ Run COSIFER GUI pipeline. Args: data (pd.DataFrame): data used for inference. results_filepath (str): path where to store the results. methods (list, optional): inference methods. Defaults to None, a.k.a., ...
6,762
def geom_to_xml_element(geom): """Transform a GEOS or OGR geometry object into an lxml Element for the GML geometry.""" if geom.srs.srid != 4326: raise NotImplementedError("Only WGS 84 lat/long geometries (SRID 4326) are supported.") # GeoJSON output is far more standard than GML, so go through ...
6,763
def _validate_source(source): """ Check that the entered data source paths are valid """ # acceptable inputs (for now) are a single file or directory assert type(source) == str, "You must enter your input as a string." assert ( os.path.isdir(source) == True or os.path.isfile(source) == ...
6,764
def precision(y_true, y_pred): """Precision metric. Only computes a batch-wise average of precision. Computes the precision, a metric for multi-label classification of how many selected items are relevant. Parameters ---------- y_true : numpy array an array of true labels y_pred...
6,765
def get_validators(setting): """ :type setting: dict """ if 'validate' not in setting: return [] validators = [] for validator_name in setting['validate'].keys(): loader_module = load_module( 'spreadsheetconverter.loader.validator.{}', validator_name) ...
6,766
def main(): """ Executing relevant functions """ # Get Keyword Args for Prediction args = arg_parser() # Load categories to names json file with open(args.category_names, 'r') as f: cat_to_name = json.load(f) # Load model trained with train.py model = load_checkpo...
6,767
def _check_found(py_exe, version_text, log_invalid=True): """Check the Python and pip version text found. Args: py_exe (str or None): Python executable path found, if any. version_text (str or None): Pip version found, if any. log_invalid (bool): Whether to log messages if found invalid...
6,768
def unpack_binary_data(filename, obj_meta, object_index, obj_type, exclude_meta): """ Unpack binary data for Speakers or Conversations """ # unpack speaker meta for field, field_type in object_index.items(): if field_type == "bin" and field not in exclude_meta: with open(os.path....
6,769
def test_adap_aux_pop(): """ test to see if aux_critical is properly being stored in the adaptive storage """ ATS = AdapTrajStorage() ATS.aux = [[tuple((0,1)),tuple((2,3))]],[tuple((0, 1))], [tuple((2, 3))] aux_crit = ATS.list_aux_pop known_aux_crit = [[tuple((0, 1))]] assert np.array_eq...
6,770
def worker(remote, parent_remote, env_fn_wrapper): """ worker func to execute vec_env commands """ def step_env(env, action): ob, reward, done, info = env.step(action) if done: ob = env.reset() return ob, reward, done, info parent_remote.close() envs = [env_fn_w...
6,771
def greedysplit_general(n, k, sigma, combine=lambda a, b: a + b, key=lambda a: a): """ Do a greedy split """ splits = [n] s = sigma(0, n) def score(splits, sigma): splits = sorted(splits) return key(reduce(combine, (sigma(a, b) ...
6,772
def write_outputs_separate_dir(out_dir, file_name, input_image = None, pred_scene = None, pred_flare = None, pred_blend = None): """Writes various outputs to separ...
6,773
def public_assignment_get(assignment_id: str): """ Get a specific assignment spec :param assignment_id: :return: """ return success_response({ 'assignment': get_assignment_data(current_user.id, assignment_id) })
6,774
def recursion_detected(frame, keys): """Detect if we have a recursion by finding if we have already seen a call to this function with the same locals. Comparison is done only for the provided set of keys. """ current = frame current_filename = current.f_code.co_filename current_function = c...
6,775
def arg_parser(cmd_line=None, config=None): """ Parse the command line or the parameter to pass to the rest of the workflow :param cmd_line: A string containing a command line (mainly used for testing) :return: An args object with overrides for the configuration """ default_formatter = argpa...
6,776
def showdecmore(vec, fa): """ Supposedly for a 3d volume, but doesn't really work""" print('this doesn\'t work properly') mmontage( abs(vec) * tile(fa, (3,1,1,1)).transpose(1,2,3,0))
6,777
def createTable(cursor): """Creates specified table if it does not exist""" command = "CREATE TABLE IF NOT EXISTS leaderboard (username varchar(50) NOT NULL, score INT NOT NULL)" cursor.execute(command)
6,778
def menu_2(wavelength_list, absorption_list, epsilon_list, epsilon_mean_list, concentration_list): """Main functions are called by menu_2""" epsilon(absorption_list, epsilon_list, concentration_list) epsilon_mean(epsilon_list, epsilon_mean_list) menu(wavelength_list, absorption_list, epsilon_mean_li...
6,779
def ST_MinX(geom): """ Returns the minimum X value of the bounding envelope of a geometry """ geom = _strip_header(geom) j = _dumps(geom) return
6,780
def pars_to_blocks(pars): """ this simulates one of the phases the markdown library goes through when parsing text and returns the paragraphs grouped as blocks, as markdown handles them """ pars = list(pars) m = markdown.Markdown() bp = markdown.blockprocessors.build_block_parser(m) root = mark...
6,781
def extract_intersections_from_osm_xml(osm_xml): """ Extract the GPS coordinates of the roads intersections Return a list of gps tuples """ soup = BeautifulSoup(osm_xml) retval = [] segments_by_extremities = {} Roads = [] RoadRefs = [] Coordinates = {} for point in soup.o...
6,782
def spark_session(request): """Fixture for creating a spark context.""" spark = (SparkSession .builder .master('local[2]') .config('spark.jars.packages', 'com.databricks:spark-avro_2.11:3.0.1') .appName('pytest-pyspark-local-testing') .enableHive...
6,783
def _load_model_from_config(config_path, hparam_overrides, vocab_file, mode): """Loads model from a configuration file""" with gfile.GFile(config_path) as config_file: config = yaml.load(config_file) model_cls = locate(config["model"]) or getattr(models, config["model"]) model_params = config["model_params"...
6,784
def _get_assignment_node_from_call_frame(frame): """ Helper to get the Assign or AnnAssign AST node for a call frame. The call frame will point to a specific file and line number, and we use the source index to retrieve the AST nodes for that line. """ filename = frame.f_code.co_filename # Go up the AST f...
6,785
def test_close(test_mp, caplog): """Platform.close_db() doesn't throw needless exceptions.""" # Close once test_mp.close_db() # Close again, once already closed test_mp.close_db() assert caplog.records[0].message == \ 'Database connection could not be closed or was already closed'
6,786
def check_existing_user(username): """ a function that is used to check and return all exissting accounts """ return User.user_exist(username)
6,787
def test_simple_profiler_describe(caplog, simple_profiler): """Ensure the profiler won't fail when reporting the summary.""" simple_profiler.describe() assert "Profiler Report" in caplog.text
6,788
def createevent(): """ An event is a (immediate) change of the world. It has no duration, contrary to a StaticSituation that has a non-null duration. This function creates and returns such a instantaneous situation. :sees: situations.py for a set of standard events types """ sit = Situation(...
6,789
def _dump_multipoint(obj, fmt): """ Dump a GeoJSON-like MultiPoint object to WKT. Input parameters and return value are the MULTIPOINT equivalent to :func:`_dump_point`. """ coords = obj['coordinates'] mp = 'MULTIPOINT (%s)' points = (' '.join(fmt % c for c in pt) for pt in coords) ...
6,790
def do_inference(engine, pics_1, h_input_1, d_input_1, h_output, d_output, stream, batch_size, height, width): """ This is the function to run the inference Args: engine : Path to the TensorRT engine pics_1 : Input images to the model. h_input_1: Input in the host ...
6,791
def stage_files(input_dir, output_dir, n_files, rank=0, size=1): """Stage specified number of files to directory. This function works in a distributed fashion. Each rank will only stage its chunk of the file list. """ if rank == 0: logging.info(f'Staging {n_files} files to {output_dir}') ...
6,792
def make_import(): """Import(alias* names)""" return ast.Import(names=[make_alias()])
6,793
def watch(): """Watch bundles for file changes.""" _webassets_cmd('watch')
6,794
def preprocess( image: Union[np.ndarray, Image.Image], threshold: int = None, resize: int = 64, quantiles: List[float] = [.01, .05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99], reduction: Union[str, List[str]] = ['max', 'median', 'mean', 'min'] ) -> d...
6,795
def binary_distance(label1, label2): """Simple equality test. 0.0 if the labels are identical, 1.0 if they are different. >>> from nltk.metrics import binary_distance >>> binary_distance(1,1) 0.0 >>> binary_distance(1,3) 1.0 """ return 0.0 if label1 == label2 else 1.0
6,796
def fetch_collections_info(data): """Connect to solr_cloud status page and and return JSON object""" url = "{0}/admin/collections?action=CLUSTERSTATUS&wt=json".format(data["base_url"]) get_data = _api_call(url, data["opener"]) solr_cloud = {} if get_data is None: collectd.error("solr_collec...
6,797
def calc_commission_futures_global(trade_cnt, price): """ 国际期货:差别很大,最好外部自定义自己的计算方法,这里只简单按照0.002计算 :param trade_cnt: 交易的股数(int) :param price: 每股的价格(美元) :return: 计算结果手续费 """ cost = trade_cnt * price # 国际期货各个券商以及代理方式差别很大,最好外部自定义计算方法,这里只简单按照0.002计算 commission = cost * 0.002 return co...
6,798
def is_section_command(row): """CSV rows are cosidered new section commands if they start with <SECTION> and consist of at least two columns column. >>> is_section_command('<SECTION>\tSection name'.split('\t')) True >>> is_section_command('<other>\tSection name'.split('\t')) False >>> is_...
6,799