content
stringlengths
22
815k
id
int64
0
4.91M
def close_files(toor): """ Close Dataframes that are checked in main window. """ global answer, footer, ents2, li, thread_busy if not thread_busy: close_var = messagebox.askyesno("File_Pal_1.2", "Do you want to close checked files?") if close_var: for file in answ...
70,000
def test_interaction_edges_error(): """ Make sure an error is raised when someone tries to set node attributes in edges. """ lines = """ [ moleculetype ] GLY 1 [ atoms ] 1 P4 1 ALA BB 1 2 P3 1 ALA SC1 2 3 P2 1 ALA SC2 3 4 P2 1 ALA SC3 3 [ edges ] BB SC1 SC1 {"...
70,001
def get_builder(regulation, version, inline_applier, p_applier, s_applier): """ Returns an HTML builder with the appliers, and the regulation tree. """ builder = HTMLBuilder(inline_applier, p_applier, s_applier) builder.tree = get_regulation(regulation, version) return builder
70,002
async def test_tree_metadata(): """Test fixture for use in testing parameter tree metadata.""" test_tree_metadata = await AsyncParameterTreeMetadataTestFixture() yield test_tree_metadata
70,003
def get_fine_tune_model(symbol, arg_params, num_classes, layer_name, dtype='float32'): """ symbol: the pre-trained network symbol arg_params: the argument parameters of the pre-trained model num_classes: the number of classes for the fine-tune datasets layer_name: the layer name before the last full...
70,004
async def async_setup(hass, config): """Load the scripts from the configuration.""" hass.data[DOMAIN] = component = EntityComponent(_LOGGER, DOMAIN, hass) await _async_process_config(hass, config, component) async def reload_service(service): """Call a service to reload scripts.""" con...
70,005
def aes_decrypt(key, iv, content): """ AES解密 key,iv使用同一个 模式cbc 去填充pkcs7 :param key: :param content: :return: """ cipher = AES.new(key, AES.MODE_CBC, iv) # base64解码 encrypt_bytes = base64.b64decode(content) # 解密 decrypt_bytes = cipher.decrypt(encrypt_bytes) # ...
70,006
def Visualize_EMD(test_img,train_imgs,EMD_scores,SP_flow, folder,test_label,img_name, num_class=4,arrow_width_scale=2,per_arrows=0.10,title=None,class_names=None, lab=False,sp_overlay=True,train_imgs_names=None, cmap='binary', stacked=False, max_feat=None,min_feat=...
70,007
def get_comments(code, sleep=1): """获取股票code的雪球评论 :param str code: 股票代码,如 `600122` :param float sleep: 睡眠时间, 默认值为 1 :return: """ headers = get_header() sess = requests.Session() # 访问首页,获取cookies sess.get(XUEQIU_HOME, headers=headers, timeout=10) # 获取首页评论 symbol = make_symb...
70,008
def test_add_deserializer() -> None: """Test registration of a custom deserializer.""" with testConfig() as config: request = DummyRequest() config.include("pyramid_openapi3") config.pyramid_openapi3_add_deserializer("deserializer", lambda x: x) deserializer = request.registry...
70,009
def workflow_format() -> Tuple[IWorkflowConverter, List[str]]: """Plugin Hook for ``workflow export`` call. Can be used to export renku workflows in different formats. :returns: A tuple of the plugin itself and the output formats it supports. NOTE: a plugin can support multiple formats. ...
70,010
def has_same_base_dtype(df_1, df_2, columns=None): """Check if specified columns have the same base dtypes across both DataFrames. Args: df_1 (pd.DataFrame): first DataFrame. df_2 (pd.DataFrame): second DataFrame. columns (list(str)): columns to check, None checks all columns. Retu...
70,011
def upsample(zs, labels, sampling_kwargs, priors, hps): """Upsample given already generated upper-level codes""" sample_levels = list(range(len(priors) - 1)) zs = _sample(zs, labels, sampling_kwargs, priors, sample_levels, hps) return zs
70,012
def k_12(): """Define the k12 component of permeability tensor.""" return np.zeros((1, 1))
70,013
def tpath(request): """ Fixture that takes the value of the special test-specific folder for test run data and plots. Usually the <folder of the test>/tresults/test_name/ """ tpath_root, tpath_local = utilities.tpath_root_make(request) os.makedirs(tpath_root, exist_ok=True) os.utime(tpath_r...
70,014
def test_init_and_Popen(args: list, kwargs: dict, expected_result: Any): """Test SubprocessCommand with Popen""" cmd = SubprocessCommand(*args, **kwargs) assert cmd == expected_result cmd_proc = cmd.Popen() cmd_proc.communicate() assert cmd_proc.returncode == 0 proc = subprocess.Popen(*arg...
70,015
def test_run_no_timeout() -> None: """Timeout produces timeoutexpired.""" expected = (0, "success", "", "") assert run("sleep 2", timeout=3) == expected
70,016
def historical_limit(): """max days""" return 90
70,017
def get_dataloader(url_list, model_name=cfg.model_name, batch_size=cfg.batch_size, num_workers=cfg.num_workers): """Create and return an instance of dataloader Args: url_list (list): List of http(s) or S3 urls to fetch images from. model_name (str, optional): Model name, used for corresponding ...
70,018
def coxeter_matrix(t): """ This was deprecated in :trac:`17798` for :class:`CartanMatrix`. EXAMPLES:: sage: coxeter_matrix(['A', 4]) doctest:...: DeprecationWarning: coxeter_matrix() is deprecated. Use CoxeterMatrix() instead See http://trac.sagemath.org/17798 for details. ...
70,019
def HaveGoodGUI(): """Returns true if we currently have a good gui available. """ return "pywin.framework.startup" in sys.modules
70,020
def run_ralston(system, slope_func, **options): """Computes a numerical solution to a differential equation. `system` must contain `init` with initial conditions, and `t_end` with the end time. `system` may contain `t_0` to override the default, 0 It can contain any other parameters required by...
70,021
def __output_block_mtx(block_cell, nblock, ncell, block_ad_file, block_dp_file, _gzip = 0): """ @abstract Output block-cell AD & DP matrices to mtx file @param block_cell A dict of {reg_idx:{cell_idx:{ad:ad_depth, dp:dp_depth}, }} pairs [dict] @param nblock Number of total blocks [i...
70,022
def prep_im_for_blob(im, pixel_means, target_size, max_size): """Mean subtract and scale an image for use in a blob.""" im = im.astype(np.float32, copy=False) im -= pixel_means im_shape = im.shape #------------------------------------------------------------- interp_mode = cv2.INTER_LINEAR ...
70,023
def solve(capacities: List, waters: List) -> int: """Solve the question 1. See this module docstring. Parameters ---------- capacities : List the capacities of tankers. waters : List the amount of water in tankers. Returns ------- int the minimum number of tanke...
70,024
def restore_container(container_name, bookmark_name): """ Restores a container to a given JS bookmark container_name: Name of the container to restore bookmark_name: Name of the bookmark """ bookmark_params = JSTimelinePointBookmarkInput() bookmark_params.bookmark = get_obj_reference(dx_se...
70,025
def main(): """ main entry point for module execution """ argument_spec = dict( http=dict(aliases=['enable_http'], default=True, type='bool', setter='set_http'), http_port=dict(default=80, type='int', setter='set_http'), https=dict(aliases=['enable_https'], default=False, type='boo...
70,026
def _generate_data(): """Generate data examples.""" # pylint: disable=protected-access labels = tfds.features.ClassLabel(names=gtzan._CLASS_LABELS).names # pytype: disable=module-attr # pylint: enable=protected-access wav_file = fake_data_utils.get_random_wav_c1(duration=30, sample=22050) # .wav file has n...
70,027
def load_torchvision_data(dataname, valid_size=0.1, splits=None, shuffle=True, stratified=False, random_seed=None, batch_size = 64, resize=None, to3channels=False, maxsize = None, maxsize_test=None, num_workers = 0, transform=None, data=Non...
70,028
def class_names_from_csv(class_map_csv_text): """Returns list of class names corresponding to score vector.""" class_names = [] with tf.io.gfile.GFile(class_map_csv_text) as csvfile: reader = csv.DictReader(csvfile) for row in reader: class_names.append(row['display_name']) return class_names
70,029
def np_col_vec (init_list): """Generates a Numpy-compatible column vector.""" return np_row_vec (init_list).T
70,030
def _gcd(a, b): """ Return greatest common divisor using Euclid's Algorithm. """ if a == 0: return b if b == 0: return a while b: a, b = b, a % b return abs(a)
70,031
def index(request): """renders listing main page""" listings = Listing.objects.all().order_by( '-list_date').filter(is_published=True) paginator = Paginator(listings, 3) page_number = request.GET.get('page') paged_listing = paginator.get_page(page_number) context = { "listings...
70,032
def do_not_have_mysql(): """Checks if mysql exists on this platform""" for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, 'msql')): return True return False
70,033
async def call_async(call_id, func, *args, **kwargs): """ Spawns task in thread pool and reports the result (async) Args: call_id: custom identifier used by callback to report the result """ if debug: logger.debug( f'calling task {call_id}: {func}\nargs: {args}\nkwargs: ...
70,034
def dashStreamsReady(manifest_path): """Wait for DASH streams to be ready. Return True if the DASH manifest exists and each Representation has at least one segment in it. """ # Check to see if the DASH manifest exists yet. if not os.path.exists(manifest_path): return False # Waiting until every Rep...
70,035
def test_process_all_cloud(all_cloud_cube): """Test the process function with multi realization input cube that has all cloud occupying the field.""" expected_data = np.zeros(all_cloud_cube[0][0].shape) result = PLUGIN.process(all_cloud_cube) np.testing.assert_almost_equal(result.data, expected...
70,036
def test_1(rq, isse_path, **kwargs): """Function: test_1 Description: Test: Process message for restart of service. Arguments: (input) rq -> RabbitMQ Publisher instance (input) isse_path -> Directory path to the ISSE Guard directory. """ print(" Test: Process message for...
70,037
def has_func(obj, fun): """check if a class has specified function: https://stackoverflow.com/a/5268474 Args: obj: the class to check fun: specified function to check Returns: A bool to indicate if obj has funtion "fun" """ check_fun = getattr(obj, fun, None) return call...
70,038
def _make_interp_probe_count_for_dataset_standard_fn(probe_counts, cover_extension_scale=1.0/10): """Generate and return a function that interpolates probe count for a dataset. This operates only on the mismatches and cover_extension parameters. Args: probe_counts: dict giving number of pr...
70,039
def GenerateSimplePrediction(results, years): """Generates a simple prediction. results: results object years: sequence of times (in years) to make predictions for returns: sequence of predicted values """ n = len(years) inter = np.ones(n) d = dict(Intercept=inter, years=years, years2=...
70,040
def write_file_on_mismatched_content(desired_content, target, write): """ Write the contents to a new target. The copy is atomic, ensuring that the target file never exists with partial contents. The code avoids writing the file if the contents do not need to be updated. The return value is a boo...
70,041
def detr_load(): """ Loads the detr model using resnet50 Returns: the detr model pretrained on COCO dataset """ model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True) model.eval() return model
70,042
def is_string(s): """判断是否是字符串 """ return isinstance(s, basestring)
70,043
def _initialize_logging_file_config(config): """ Initialize logging using logging's "Configuration file format". (ref.: https://docs.python.org/3/howto/logging.html#configuring-logging) """ base_config = _find_logging_config(config) logging.config.fileConfig( base_config.get("logging-fil...
70,044
def download_chunks_to(names, chunks, folder: Path, progress_bar=True): """ Downloads all data segments specified in the 'chunks' list. Concurrent chunks are downloaded in parallel on multiple threads, starting at the first N chunks. This allows video playback before the whole strea...
70,045
def tff_cc_library_with_tf_runtime_deps(name, tf_deps = [], **kwargs): """A version of `cc_library` that links against TF statically or dynamically. Note that targets of this type will not work with pybind, due to conflicting symbols. Args: name: A unique name for this target. tf_deps: Lis...
70,046
def check_if_consistent(dfs, cast_info): """ checks name and types of columns of each dataframes in 'dfs', returns False, in case any one of them if found to be inconsistent, otherwise returns True. """ index_names = np.asarray([df.index.name if df.has_index() \ else No...
70,047
def _collapse_complexes(data): """Given a list or other iterable that's a series of (real, imaginary) pairs, returns a list of complex numbers. For instance, given this list -- [a, b, c, d, e, f] this function returns -- [complex(a, b), complex(c, d), complex(e, f)] The returned list is a...
70,048
def find_lottery_winner(root: SumTree, lottery_number: float) -> int: """ Find lottery winner index :param root: the root node of the sum tree :param lottery_number: float number in range of 0 to 1 :return: winner wallet index """ search_number = lottery_number * root.sum winner = root....
70,049
def calc_one_dissimilarity_cv(dataset, descriptor, i_des, j_des, method='euclidean', noise=None, weighting='number', prior_lambda=1, prior_weight=0.1, cv_descriptor=None, enforce_same=False): """ ...
70,050
def plot_horn(obs_svals, perm_samples, sval_cutoff): """ Visualization for Horn's Parallel Analysis. Histogram of null distribution. """ plt.hist(perm_samples, color='black') for sval in obs_svals: if sval > sval_cutoff: ls = '-' # alpha = 0.5 lw = 2 ...
70,051
def get_cron_time_samples(start,stop,samples): """Get a comma-separated samples as a string for cron jobs. Keyword arguments: start -- start integer to sample stop -- stop integer to sample samples -- number of samples Returns: string -- comma-separated list of samples from the s...
70,052
def round_up_to_odd(f): """round float to the nearest odd integer""" return np.asarray(np.round((f - 1) / 2) * 2 + 1, dtype=np.int64)
70,053
def backend_filter(cls): """ Verify that the type proper subclass of BackendModule. :type cls: type :rtype: bool :param cls: A class object :return: True if match, else false """ return issubclass(cls, BackendModule) and cls != BackendModule
70,054
def group_force_by_parameter_id( handler_force: openmm.Force, parameters: List[SMIRNOFFParameterType], parameter_map: Dict[str, List[Tuple[int, ...]]], ) -> Dict[str, openmm.Force]: """Partitions the parameters in a force into a separate force for each parameter id. Args: handler_force:...
70,055
def loadMtlFile(mtllib, texParams=None): """Load a material library file (*.mtl). Parameters ---------- mtllib : str Path to the material library file. texParams : list or tuple Optional texture parameters for loaded textures. Texture parameters are specified as a list of tu...
70,056
def main(): """Go Main Go""" os.chdir('baseline') for fn in glob.glob("*.met"): location = fn[:-4] output = open("%s.csv" % (location,), 'w') output.write("date,high[F],low[F],precip[inch],gdd[F]\n") for line in open(fn): line = line.strip() if (not li...
70,057
async def zwave_setup_ready(hass, zwave_setup): """Zwave setup and set network to ready.""" zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY await hass.async_start()
70,058
def test_stringTypeValidator_correct_values(value): """Check if proper string values are validated.""" # no exception is expected stringTypeValidator(value)
70,059
def find_sol(c, ws, memo): """ Finds an optimal solution for the given instance of the subset sum problem with weight capacity c and item weights ws, provided maximum total weights for subproblems are memoized in memo. """ sol = [] for n in reversed(range(len(ws))): if c >= ws[n] and...
70,060
def sign_up_page(): """Creates the signup page.""" global entry_config, win, login_frame, sign_up, image, signup_frame, signup_error, image, logo login_frame.destroy() sign_up_frame = tk.Frame(win, bg='#ffffff', height=768, width=1366) sign_up_frame.pack() sign_up_frame.pack_propagate(Fa...
70,061
def atomic(connection_name: Optional[str] = None) -> Callable[[F], F]: """ Transaction decorator. You can wrap your function with this decorator to run it into one transaction. If error occurs transaction will rollback. :param connection_name: name of connection to run with, optional if you have o...
70,062
def get_rectangle_information(form): """ Функция для формирования json с полигоном для отрисовки аналитики по области :param form: форма из POST запроса с координатами области (прямоугольника) и 6 основными фильтрами :return: json с полигоном и необходимой информацией """ rectangle_information =...
70,063
def distance(p0, p1): """calculate distance between two joint/3D-tuple in the XZ plane (2D)""" return math.sqrt((p0[0] - p1[0])**2 + (p0[2] - p1[2])**2)
70,064
def cut_traces(cntfile, annotation): """cut the tracedate from a matfile given Annotations args ---- cntfile: FileName the cntfile for cutting the data. must correspond in name to the one specified in the annotation annotation: Annotations the annotations specifying e.g. onsets as we...
70,065
def get_args(): """ Method to read the command line arguments and parse them """ parser = argparse.ArgumentParser( description="Split a playlist into multiple playlists" ) # Required arguments for the program parser.add_argument("-p", "--playlist_id", required=True, help="Playlist I...
70,066
def dict_raise_on_duplicates(ordered_pairs): """Reject duplicate keys.""" d = {} schemaOrg = False for k, v in ordered_pairs: if re.search(r"\s", k): # click.secho(k) click.secho("Please remove the whitespace(s) in property name " + k+ "the Validator wil...
70,067
def plot_radar_chart(data, line_labels, var_labels, **kwargs): """Make a radar chart. Input data is assumed to differ in variables along the columns and differ in observations/samples along the rows. Parameters ---------- data: sequence, one- or two-dimensional Data to plot. Must be so...
70,068
def cod_tapcode(mensagem: str, tipo_saida: int) -> str: # Tabela do tap code """Função para codificar em tap code""" tabela: list = [['A', 'B', 'C', 'D', 'E'], ['F', 'G', 'H', 'I', 'J'], ['L', 'M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T', 'U'], ...
70,069
def difference(df, cols, lag=1): """ Perform differencing on some columns in a dataframe. Input: ------ df: pandas dataframe containing the timeseries data. cols: list of strings indicating which columns to difference """ df2 = copy.deepcopy(df) # Difference based on the lag provid...
70,070
def regional_indicator(c: str) -> str: """Returns a regional indicator emoji given a character.""" return chr(0x1F1E6 - ord("A") + ord(c.upper()))
70,071
def reset_pw(username): """Reset a password""" password_new = ''.join(random.SystemRandom(). choice(string.ascii_uppercase + string.digits) for _ in range(6)) cursor, conn = db_sql.connect('users.db') sql = ("UPDATE users SET password = ? WHERE usern...
70,072
def loadSim(simdir, paramname='snapshot.param'): """ Loads a dustydiffusion simulation from a directory. In particular, this requires the runparameters to be saved in the directory. Returns ------- fs : list list of pynbody snapshots eps : fcn Estimate the dust fraction...
70,073
def main(): """ Main - program execute """ #datadir = '../data/' datadir = './' getunzipped('http://terrabrasilis.dpi.inpe.br/file-delivery/download/deter-amz/shape', datadir) # shapeaddrownumber(datadir + 'deter_public.shp', datadir + 'deter_all.shp' ) # shape_process(datadir + 'deter_public.shp', ...
70,074
def update_event_participant(event_id, participant_id): """Update an event participant's attendance""" if flask.request.method != "PUT": return flask.abort(405) # Return whether they're True or False based on what's in the request body return flask.jsonify({"attended": True})
70,075
def send_test_campaign(c: str = None, e: str = None): """ Send a test campaign """ client = get_client() if not c: global campaign_id c = campaign_id d = {"test_emails": [e], "send_type": "html", "settings": {"subject_line": "Found test"}} r = client.campaigns.actions.test(...
70,076
def _CreateFeed(client): """Creates the feed for DSA page URLs. Args: client: an AdWordsClient instance. Returns: A _DSAFeedDetails instance containing details about the created feed. """ # Get the FeedService. feed_service = client.GetService('FeedService', version='v201802') # Create operatio...
70,077
def parse_amount_string(amount: str) -> float: """ Parse strings like - '1.000,00-' - '1.000,00 S' - '23,23+' - '23,23 H' to the correct amount as float :param amount: The string of an amount :return: """ # Replace H and S amount = amount.replace("H", "+").repla...
70,078
def install(ctx, profile=None, debug=False): """ Install the latest available apk into currently available device (emulator or real device) """ import buildozer profile = profile or "" buildo = buildozer.Buildozer() buildo.config_profile = profile buildo._merge_config_profile() buil...
70,079
def test_vlan_tc3_send_invalid_vid(ptfadapter, vlan_ports_list, toggle_all_simulator_ports_to_rand_selected_tor): """ Test case #3 Send packets with invalid VLAN ID Verify no port can receive these packets """ logger.info("Test case #3 starting ...") invalid_tagged_pkt = build_icmp_packet(...
70,080
def custom_implicit_transformation(result, local_dict, global_dict): """Allows a slightly relaxed syntax. - Parentheses for single-argument method calls are optional. - Multiplication is implicit. - Symbol names can be split (i.e. spaces are not needed between symbols). - Functions can be ...
70,081
def model_core_from_theseus(models, alignment_file, var_by_res, work_dir=None): """ Only residues from the first protein are listed in the theseus output, but then not even all of them We assume the output is based on the original alignment so that where each residue in the first protein lines up ...
70,082
def fractal_sda(signal, scales=None, show=False): """Standardised Dispersion Analysis (SDA) SDA is part of a family of dispersion techniques used to compute fractal dimension. The standardised time series is divided in bins of different sizes and their standard deviation (SD) is calculated. The relatio...
70,083
def gemini_exchange_cycle(config_file: str, debug_mode: bool) -> None: """Perform bot cycles using Gemini as the exchange Args: config_file: Path to the JSON file containing credentials debug_mode: Are we running in debugging mode? """ # Load the configuration file config_pa...
70,084
def _randomize_dyads(network, keep, timeout): """ This function returns a network with the same nodes and edge number as the input network. Each edge is swapped rather than moved, so the degree distribution is preserved. :param network: NetworkX object in tuple, with first item in tuple being network n...
70,085
def reproject(geom, from_proj='EPSG:4326', to_proj='EPSG:26942'): """Project from ESPG:4326 to ESPG:26942.""" tfm = partial(pyproj.transform, pyproj.Proj(init=from_proj), pyproj.Proj(init=to_proj)) return ops.transform(tfm, geom)
70,086
def validate_xml(xml_to_check): """ validate the xml of the supplied input :param xml_to_check: bytes object which is the xml to be validated :return: True or False """ try: etree.parse(BytesIO(xml_to_check)) return True except etree.XMLSyntaxError: return False
70,087
def get_translation_dict_from_file(path, lang, app): """load translation dict from given path""" cleaned = {} if os.path.exists(path): csv_content = read_csv_file(path) for item in csv_content: if len(item)==3: # with file and line numbers cleaned[item[1]] = strip(item[2]) elif len(item)==2: ...
70,088
def write_numerical_base_acc(symo, inertia, beta_wrench, symmet=False): """ Write the base acceleration (6x1) vector to be computed numerically using numpy in the output file. """ # write strating comments symo.write_line("# SOLVE NUMERICALLY FOR BASE ACCELERATION - START") symo.write_line("...
70,089
def __scale_width(img, target_width): """__scale_width""" ow, oh = img.size # the size needs to be a multiple of this number, # because going through generator network may change img size # and eventually cause size mismatch error mult = 4 assert target_width % mult == 0, "the target width ...
70,090
def demo2(): """ 现在我们想要避免无谓的等待, 为了提高效率, 我们将使用 async. washing1/2/3() 本是 "普通函数", 现在我们用 async 把它们升级为 "异步函数". 注: 一个异步的函数, 有个更标准的称呼, 我们叫它 "协程" (coroutine). """ async def washing1(): sleep(3) print('washer1 finished') async def washing2(): sleep(2) pr...
70,091
def test_request_200(get_data): """Test that the Candles class sends a GET request and receives a successful response.""" assert get_data.r.status_code == 200
70,092
def validate_orcid_id(ctx, param, orcid_id: str): """ Check if valid ORCID iD, should be https://orcid.org/ + 16 digit in form: https://orcid.org/0000-0000-0000-0000. ctx and param are necessary `click` callback arguments """ if re.match(ORCID_ID_REGEX, orcid_id): return orcid_id...
70,093
def StageWheelForPackage(system, wheel_dir, wheel): """Finds the single wheel in wheel_dir and copies it to the filename indicated by wheel.filename. Returns the name of the wheel we found. """ dst = os.path.join(system.wheel_dir, wheel.filename) source_path = _FindWheelInDirectory(wheel_dir) util.LOGGER.d...
70,094
def _get_build_modes_for_base_path(base_path): """ Returns `get_build_modes_for_cell_and_base_path()` for the specified base_path """ return _get_build_modes_for_cell_and_base_path( config.get_current_repo_name(), base_path, )
70,095
def unique_chunks(lst, n): """ Returns unique chunks of length n from lst. """ if n < 1: return set() return {tuple(lst[i:i + n]) for i in range(0, len(lst), n)}
70,096
def query_turtle(sparql_query): """ Make a SPARQL query with turtle format response""" data = {'query': sparql_query, 'format': 'text/turtle'} auth = (settings.SPARQL_AUTH_USR, settings.SPARQL_AUTH_PWD) headers = {'Accept': 'text/turtle'} r = requests.post(settings.SPARQL_QUERY_URI, data=data, auth=...
70,097
def predict_note_auth(): """ BANK NOTES AUTHENTICATION This is using DOCSTRING for specifications. ---- parameters: - name : variance in: query type : number required : true - name : skewness in: query type : number required : t...
70,098
def mse(predicted, actual): """ Mean squared error of predictions. .. versionadded:: 0.5.0 Parameters ---------- predicted : ndarray Predictions on which to measure error. May contain a single or multiple column but must match `actual` in shape. actual : ndarray ...
70,099