file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
component.ts
// deno-lint-ignore no-explicit-any type Class<S> = new (...args: any[]) => S; const registry: { [name: string]: Class<BaseComponent> } = {}; const registeredElements: HTMLElement[] = []; export function Component(name: string) { return (ctor: Class<BaseComponent>) => { registry[name] = ctor; }; } export abs...
declare global { interface HTMLElement { component: BaseComponent; } } export function bootComponents() { function initializeComponents() { document.querySelectorAll<HTMLElement>(`[data-cmp]`).forEach((ctx) => { // do not initialize more than once if (!registeredElements.includes(ctx)) { ...
destructor(): void { } }
test_userid.py
import pytest import time from tests.live import testlib from pandevice import base class TestUserID_FW(object): """Tests UserID on live Firewall.""" def test_01_fw_login(self, fw, state_map): state = state_map.setdefault(fw) user, ip = testlib.random_name(), testlib.random_ip() fw.u...
def test_04_fw_logouts(self, fw, state_map): state = state_map.setdefault(fw) if not state.multi_user: raise Exception("User not logged in yet") fw.userid.logouts(state.multi_user) def test_05_register_str(self, fw, state_map): state = state_map.setdefault(fw) ...
fw.userid.logout(user, ip)
files.go
package filehandler import ( "bytes" "html/template" "os" "path/filepath" ) func check(e error) { if e != nil { panic(e) } } // CreateDirIfNotExist ... func CreateDirIfNotExist(dir string) { if _, err := os.Stat(dir); os.IsNotExist(err) { err = os.MkdirAll(dir, 0755) check(err) } } // GetAllFilePathsI...
(dirpath string) ([]string, error) { // Get all the .tmpl files in the directory. var paths []string extension := ".tmpl" err := filepath.Walk(dirpath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && filepath.Ext(path) == extension { paths = appen...
GetAllFilePathsInDirectory
transform_group_by_partial.rs
// Copyright 2020-2021 The Datafuse Authors. // // SPDX-License-Identifier: Apache-2.0. use std::any::Any; use std::collections::HashMap; use std::sync::Arc; use std::time::Instant; use bumpalo::Bump; use common_datablocks::DataBlock; use common_datablocks::HashMethod; use common_datablocks::HashMethodKind; use commo...
apply! { hash_method , DFUInt8ArrayBuilder, RwLock<HashMap<u8, (Vec<usize>, Vec<DataValue>), ahash::RandomState>> } } HashMethodKind::KeysU16(hash_method) => { apply! { hash_method , DFUInt16ArrayBuilder, RwLock<HashMap<u16, (Vec<us...
HashMethodKind::KeysU8(hash_method) => {
specs.py
# MIT License # This project is a software package to automate the performance tracking of the HPC algorithms # Copyright (c) 2021. Victor Tuah Kumi, Ahmed Iqbal, Javier Vite, Aidan Forester # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation...
(hardware_ids, rocm_versions): """Gets specification for all specified rocm hardwares""" specs_info = [] for rocm in rocm_versions: for hardw_id in hardware_ids: specs = model.get_specs(hardw_id, rocm) #returns dictionary if specs is not None: title = f'{rocm...
get_specs
extension.py
from waldur_core.core import WaldurExtension class PlaybookJobsExtension(WaldurExtension): class Settings:
WALDUR_PLAYBOOK_JOBS = { 'PLAYBOOKS_DIR_NAME': 'ansible_playbooks', 'PLAYBOOK_ICON_SIZE': (64, 64), } @staticmethod def django_app(): return 'waldur_ansible.playbook_jobs' @staticmethod def rest_urls(): from .urls import register_in retur...
build_requires_test.py
import unittest from nose_parameterized.parameterized import parameterized from conans.test.utils.tools import TestClient from conans.paths import CONANFILE tool_conanfile = """ import os from conans import ConanFile class Tool(ConanFile): name = "Tool" version = "0.1" def package_info(self): s...
(self, conanfile): client = TestClient() client.save({CONANFILE: tool_conanfile}, clean_first=True) client.run("export lasote/stable") client.save({CONANFILE: conanfile}, clean_first=True) client.run("export lasote/stable") client.run("install MyLib/0.1@lasote/stable --...
test_build_requires
squeezenet.py
import torch from torch import nn from torch.nn import functional as F import torchvision def main():
if __name__ == '__main__': main()
print('cuda device count: ', torch.cuda.device_count()) net = torchvision.models.squeezenet1_1(pretrained=True) #net.fc = nn.Linear(512, 2) net = net.eval() net = net.to('cuda:0') print(net) tmp = torch.ones(2, 3, 227, 227).to('cuda:0') out = net(tmp) print('squeezenet out:', out.sha...
unassociate_eip_address.go
package vpc //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distribut...
() (response *UnassociateEipAddressResponse) { response = &UnassociateEipAddressResponse{ BaseResponse: &responses.BaseResponse{}, } return }
CreateUnassociateEipAddressResponse
main.go
// // Copyright 2020 Verizon Media // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
signal.Notify(signals, os.Interrupt, syscall.SIGTERM) sig := <-signals log.Printf("Received signal %v, stopping rotation\n", sig) stop <- true }() err = <-errors if err != nil { log.Printf("%v\n", err) } } os.Exit(0) } // getAttestationData fetches attestation data for all the services mentio...
go func() { signals := make(chan os.Signal, 2)
random number generation.py
import random
x=random.random() print("The Random number is",round(x,3))
setup.py
#!/usr/bin/env python from os.path import join, dirname, abspath from setuptools import setup def read(rel_path): here = abspath(dirname(__file__)) with open(join(here, rel_path)) as fp: return fp.read() def get_version(rel_path): for line in read(rel_path).splitlines(): if line.startsw...
setup(name='robotframework-csvlibrary', version=get_version("CSVLibrary/__init__.py"), description='CSV library for Robot Framework', long_description=DESCRIPTION, long_description_content_type='text/markdown', author='Marcin Mierzejewski', author_email='<mmierz@gmail.com>', ur...
predict.py
from tensorflow.keras.models import load_model from clean import downsample_mono, envelope from kapre.time_frequency import STFT, Magnitude, ApplyFilterbank, MagnitudeToDecibel from sklearn.preprocessing import LabelEncoder import numpy as np from glob import glob import argparse import os import pandas as pd from tqdm...
if __name__ == '__main__': parser = argparse.ArgumentParser(description='Audio Classification Training') parser.add_argument('--model_fn', type=str, default='models/lstm.h5', help='model file to make predictions') parser.add_argument('--pred_fn', type=str, default='y_pred', ...
model = load_model(args.model_fn, custom_objects={'STFT': STFT, 'Magnitude': Magnitude, 'ApplyFilterbank': ApplyFilterbank, 'MagnitudeToDecibel': MagnitudeToDecibel}) # fi...
utils.py
""" Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. """ """ Collection of misc tools """ import sys import logging import inspect from ibapi.common import UNSET_I...
if orig_type is bool: n = False if n == 0 else True return n def ExerciseStaticMethods(klass): import types #import code; code.interact(local=dict(globals(), **locals())) for (_, var) in inspect.getmembers(klass): #print(name, var, type(var)) if type(var) == types.Func...
n = the_type(s or 0)
lib.rs
#![recursion_limit="128"] #![doc(html_root_url = "https://api.rocket.rs/master")] #![doc(html_favicon_url = "https://rocket.rs/images/favicon.ico")] #![doc(html_logo_url = "https://rocket.rs/images/logo-boxed.png")] #![warn(rust_2018_idioms)] //! # Rocket - Code Generation //! //! This crate implements the code gene...
/// /// 3. Data parameter, if any. /// /// If a data guard fails, the request is forwarded if the /// [`Outcome`] is `Forward` or failed if the [`Outcome`] is /// `Failure`. See [`FromTransformedData` Outcomes] for further detail. ...
/// /// If a path or query parameter guard fails, the request is /// forwarded.
mixin.py
class TransactionHooksDatabaseWrapperMixin(object): """ A ``DatabaseWrapper`` mixin to implement transaction-committed hooks. To use, create a package for your custom database backend and place a ``base.py`` module within it. Import whatever ``DatabaseWrapper`` you want to subclass (under some othe...
(self, *a, **kw): # a list of no-argument functions to run when the transaction commits; # each entry is an (sids, func) tuple, where sids is a list of the # active savepoint IDs when this function was registered self.run_on_commit = [] # Should we run the on-commit hooks the nex...
__init__
views.py
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def
(request): return HttpResponse('TEST URL')
index
lib.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { anyhow::Result, errors::{ffx_bail, ffx_error}, ffx_core::ffx_plugin, ffx_pdk_lib::groups::{ArtifactStore, ArtifactStoreEntry, Artifac...
let mut res = client .get(uri.clone()) .await .map_err(|e| ffx_error!(r#"Failed on http get for "{}": {}"#, uri, e))?; let status = res.status(); if status != StatusCode::OK { ffx_bail!("Cannot download meta.far. Status is {}. Uri is: {}.", status...
.map_err(|e| ffx_error!(r#"Parse Uri failed for "{}": {}"#, hostname, e))?; let client = new_https_client();
a_bit_of_everything.go
package server import ( "context" "fmt" "io" "strings" "sync" "github.com/golang/glog" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/duration" "github.com/golang/protobuf/ptypes/empty" examples "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" "github.com/grpc-ecosys...
() ABitOfEverythingServer { return &_ABitOfEverythingServer{ v: make(map[string]*examples.ABitOfEverything), } } func (s *_ABitOfEverythingServer) Create(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { s.m.Lock() defer s.m.Unlock() glog.Info(msg) var uuid string for...
newABitOfEverythingServer
bitcoin_es.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS language="es" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Mazebits</source> <translation>Acerca de Mazebits</translation> ...
<translation>Establecer tamaño mínimo de bloque en bytes (predeterminado: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Reducir el archivo debug.log al iniciar el clien...
</message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source>
data.rs
use Void; pub(crate) extern "C" fn data_new(d: *mut Void, size: u32) -> *const Void { // use libc
}
{ extern "C" { fn realloc(d: *mut Void, bytes: usize) -> *mut Void; } unsafe { realloc(d, size as usize) } }
brief.js
import predefinedPropTypes from '../../constants/prop-types/body' import PropTypes from 'prop-types' import React, { PureComponent } from 'react' import SeparationCurve from '../separation-curve' import styled from 'styled-components' import styles from '../../constants/css' import themeConst from '../../constants/them...
extends PureComponent { static propTypes = { className: PropTypes.string, data: PropTypes.arrayOf(predefinedPropTypes.elementData), } static defaultProps = { className: '', data: [], } _buildContentElement = (data, index) => { switch (data.type) { case 'unstyled': const ht...
Brief
experimentparam.py
import spacy from spacy.lang.en import English from spacy.util import minibatch, compounding from spacy.util import decaying class ExperimentParam: def __init__(self, TRAIN_DATA: list, max_batch_sizes: dict, model_type='ner', dropout_start: float = 0.6, dropout_end: float = 0.2, interval: float =...
(self): """ max_batch_sizes = Initialize with batch size 1, and compound to a maximum determined by your data size and problem type. {"tagger": 32, "parser": 16, "ner": 16, "textcat": 64} """ max_batch_size = self.max_batch_sizes[self.model_type] if len(self.TRA...
get_batches
newton_cg.rs
// Copyright 2018 Stefan Kroboth // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to thos...
} fn run() -> Result<(), Error> { // Define cost function let cost = Rosenbrock { a: 1.0, b: 100.0 }; // Define initial parameter vector // let init_param: Array1<f64> = Array1::from_vec(vec![1.2, 1.2]); let init_param: Array1<f64> = Array1::from_vec(vec![-1.2, 1.0]); // set up line search ...
{ let h = rosenbrock_2d_hessian(&p.to_vec(), self.a, self.b); Ok(Array::from_shape_vec((2, 2), h)?) }
dynamic.rs
//! Helper module which defines the [`Dynamic`] data type and the //! [`Any`] trait to to allow custom type handling. use crate::func::native::SendSync; use crate::{reify, ExclusiveRange, FnPtr, ImmutableString, InclusiveRange, INT}; #[cfg(feature = "no_std")] use std::prelude::v1::*; use std::{ any::{type_name, A...
) -> Self { match self.0 { #[cfg(not(feature = "no_closure"))] Union::Shared(cell, ..) => crate::func::native::shared_try_take(cell).map_or_else( #[cfg(not(feature = "sync"))] |cell| cell.borrow().clone(), #[cfg(feature = "sync")] ...
en(self
FileWord.ts
/** * @file FileWord 文件-word * @author Auto Generated by IconPark */ /* tslint:disable: max-line-length */ /* eslint-disable max-len */ import {ISvgIconProps, IconWrapper} from '../runtime'; export default IconWrapper('file-word', (props: ISvgIconProps) => ( '<?xml version="1.0" encoding="UTF-8"?>' + '<svg...
));
+ '<path d="M16.0083 20L19.0083 34L24.0083 24L29.0083 34L32.0083 20" stroke="' + props.colors[2] + '" stroke-width="' + props.strokeWidth + '" stroke-linecap="' + props.strokeLinecap + '" stroke-linejoin="' + props.strokeLinejoin + '"/>' + '</svg>'
compressed.py
"""Base class for sparse matrix formats using compressed storage.""" from __future__ import division, print_function, absolute_import __all__ = [] from warnings import warn import operator import numpy as np from scipy._lib._util import _prune_array from .base import spmatrix, isspmatrix, SparseEfficiencyWarning fr...
if isscalarlike(other): if np.isnan(other): warn("Comparing a sparse matrix with nan using != is" " inefficient", SparseEfficiencyWarning, stacklevel=3) all_true = self.__class__(np.ones(self.shape, dtype=np.bool_)) return all_true...
def __ne__(self, other): # Scalar other.
integ.job-poller.ts
import * as sfn from '@aws-cdk/aws-stepfunctions'; import * as cdk from '@aws-cdk/core'; import * as tasks from '../lib'; class JobPollerStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props: cdk.StackProps = {}) { super(scope, id, props); const submitJobActivity = new sfn.Activity(this, '...
new sfn.StateMachine(this, 'StateMachine', { definition: chain, timeout: cdk.Duration.seconds(30), }); } } const app = new cdk.App(); new JobPollerStack(app, 'aws-stepfunctions-integ'); app.synth();
.otherwise(waitX));
udac_example_dag.py
from datetime import datetime, timedelta from airflow import DAG from airflow.operators import ( StageToRedshiftOperator, LoadFactOperator, LoadDimensionOperator, DataQualityOperator, ) from airflow.operators.dummy_operator import DummyOperator from airflow.operators.postgres_operator import PostgresOp...
load_songplays_table >> dim_operators dim_operators + [load_songplays_table] >> run_quality_checks run_quality_checks >> end_operator
trace_service_grpc_transport.py
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
@property def channel(self): """The gRPC channel used by the transport. Returns: grpc.Channel: A gRPC channel object. """ return self._channel @property def batch_write_spans(self): """Return the gRPC stub for :meth:`TraceServiceClient.batch_write_...
"""Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If ...
contact.helper.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
* with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either expre...
Button.tsx
import { FC, MouseEventHandler } from 'react' import styles from './Button.module.scss' type ButtonPropsType = { action?: MouseEventHandler<HTMLButtonElement> } const Button: FC<ButtonPropsType> = ({ children, action }) => { return ( <button onClick={action} className={styles.btn}> {children} </but...
} export default Button
__init__.py
""" This module provides data loaders and transformers for popular vision datasets. """ from .mscoco import COCOSegmentation from .cityscapes import CitySegmentation from .ade import ADE20KSegmentation from .pascal_voc import VOCSegmentation from .pascal_aug import VOCAugSegmentation from .sbu_shadow import SBUSegmenta...
'robocup': RobocupSegmentation, } def get_segmentation_dataset(name, **kwargs): """Segmentation Datasets""" return datasets[name.lower()](**kwargs)
'coco': COCOSegmentation, 'citys': CitySegmentation, 'sbu': SBUSegmentation, 'ycb': YCBSegmentation,
Shape and Reshape.py
import numpy as np class Main: def __init__(self): self.li = list(map(int, input().split())) self.np_li = np.array(self.li)
if __name__ == '__main__': obj = Main() obj.output()
def output(self): print(np.reshape(self.np_li, (3,3)))
kendo.culture.sms-FI.min.js
/** * Kendo UI v2018.1.117 (http://www.telerik.com/kendo-ui) * Copyright 2018 Telerik AD. All rights reserved. ...
*/ !function(n){"function"==typeof define&&define.amd?define(["kendo.core.min"],n):n()}(function(){!function(n,m){kendo...
studentController.js
const Student = require("../Models/student"); const { createStudentSchema, createEnquirySchema, createEnrollmentSchema, updateStudentSchema, } = require("../validators/studentValidator"); // @route POST api/admin/students // @desc Create a student // @access Private exports.createStudent = async (req, res)...
return res.status(200).json(deletedStudent); } else { return res.status(400).json({ err: "Something went wrong" }); } } ); } catch (err) { return res.status(500).json({ err: "Internal Server Error" }); } }; // @route GET api/admin/students // @desc get list of a...
(err, deletedStudent) => { if (!err || null !== deletedStudent) {
gunicorn_application.py
"""Top-level gunicorn application for `routemaster serve`.""" from typing import Callable import gunicorn.app.base from routemaster.utils import WSGICallable class GunicornWSGIApplication(gunicorn.app.base.BaseApplication): """gunicorn application for routemaster.""" def __init__( self, ap...
def load_config(self) -> None: """ Load gunicorn configuration settings. Rather than grab these from a file we instead just set them to their known values inline. """ self.cfg.set('bind', self.bind) self.cfg.set('workers', self.workers) self.cfg.set...
self.application = app self.bind = bind self.debug = debug self.workers = workers self.post_fork = post_fork super().__init__()
unionWith.js
var convert = require('./convert'), func = convert('unionWith', require('../unionWith')); func.placeholder = require('./placeholder');
module.exports = func;
gerrit_test.go
// +build unit package gits_test import ( "fmt" "net/http" "net/http/httptest" "sort" "testing" "github.com/jenkins-x/jx/pkg/auth" "github.com/jenkins-x/jx/pkg/gits" "github.com/jenkins-x/jx/pkg/util" "github.com/stretchr/testify/suite" ) type GerritProviderTestSuite struct { suite.Suite mux *http....
func (suite *GerritProviderTestSuite) TearDownSuite() { suite.server.Close() }
{ if testing.Short() { t.Skip("skipping GerritProviderTestSuite in short mode") } else { suite.Run(t, new(GerritProviderTestSuite)) } }
app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component'; import { ProfileComponent } from './components/profile/profile.component'; const routes: Routes = [ { path: '', redirectTo: '...
{ }
AppRoutingModule
cmd.go
package cli import ( "github.com/filecoin-project/boost/cli/ctxutil" cliutil "github.com/filecoin-project/boost/cli/util" lcliutil "github.com/filecoin-project/lotus/cli/util" )
var DaemonContext = ctxutil.DaemonContext
var GetBoostAPI = cliutil.GetBoostAPI var GetFullNodeAPI = lcliutil.GetFullNodeAPI var ReqContext = ctxutil.ReqContext
client.go
package client import ( "bytes" "encoding/json" "errors" "fmt" "net/http" "net/url" ) type Client struct { Host string url *url.URL } type Job struct { Id int `json:"id,omitempty"` QueueName string `json:"queue_name,omitempty"` Category string `json:"category,omitempty"` Url...
c.url.Path = fmt.Sprintf("/routing/%s", name) req, err = http.NewRequest(http.MethodGet, c.url.String(), nil) if err != nil { return err } res, err = http.DefaultClient.Do(req) if err != nil { return nil } defer res.Body.Close() if res.StatusCode == http.StatusNotFound { if err := c.createRouting(name)...
{ if err := c.createQueue(name, &Queue{PollingInterval: 100, MaxWorkers: maxWorkers}); err != nil { return err } }
system.schema.js
const Ajv = require("../../wrapper/ajv-wrapper"); const PLANET_SCHEMA = { type: "object", properties: { localeName: { type: "string" }, resources: { type: "integer" }, influence: { type: "integer" }, destroyed: { type: "boolean", default: false }, trait: { ty...
{ constructor() { throw new Error("Static only"); } /** * Validate schema, returns error does not throw. * * @param {object} system attributes * @param {function} onError - takes the error as single argument * @returns {boolean} true if valid */ static validate(sy...
SystemSchema
useHashTable.ts
import * as anchor from "@project-serum/anchor"; import { useState } from "react"; import toast from "react-hot-toast"; import { MetadataProgram, Metadata } from "@metaplex/js"; const rpcHost = "https://still-solitary-paper.solana-mainnet.quiknode.pro/3556f36b7113ada207f0bc78ef72f446f1f3ecdf/"; const connection = new ...
( hash: string, metadataEnabled?: boolean ): Promise<any[]> { const metadataAccounts = await MetadataProgram.getProgramAccounts( connection, { filters: [ { memcmp: { offset: 1 + ...
fetchHashTable
docker_cli_logs_test.go
package main import ( "fmt" "io" "os/exec" "regexp" "strings" "time" "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/pkg/jsonmessage" "github.com/go-check/check" "github.com/gotestyourself/gotestyourself/icmd" ) // This used to wo...
(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) { buffer := make([]byte, chunkSize) for { var readBytes int readBytes, err = reader.Read(buffer) n += readBytes if err != nil { if err == io.EOF { err = nil } return } select { case <-stop: retur...
ConsumeWithSpeed
types.go
package types import ( "errors" "io" "io/ioutil" "os" "path/filepath" "strings" "github.com/docker/app/internal" "github.com/docker/app/types/metadata" "github.com/docker/app/types/settings" ) // SingleFileSeparator is the separator used in single-file app const SingleFileSeparator = "\n---\n" // AppSource...
} content[i] = d } return content, newErrGroup(errs) } func readFiles(files ...string) ([][]byte, error) { content := make([][]byte, len(files)) var errs []string for i, file := range files { d, err := ioutil.ReadFile(file) if err != nil { errs = append(errs, err.Error()) continue } content[i] =...
package.js
Package.describe({ name: 'templ:drop', version: '0.3.3', summary: 'Realy fully customizable, and reactive drops, dropdowns, tooltips and dropmenus for Meteor.', git: 'https://github.com/meteor-templ/drop', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use(...
api.addFiles('watch.js', 'client'); api.addFiles('Drop.html', 'client'); api.addFiles('Drop.js', 'client'); api.addFiles('Drops.html', 'client'); api.addFiles('Drops.js', 'client'); api.addFiles('body.html', 'client'); api.addFiles('helpers.js', 'client'); api.addFiles('Data.js', 'client'); api.addFil...
api.addFiles('class.js', 'client'); api.addFiles('triggers.js', 'client'); api.addFiles('instances.js', 'client');
exporter-spec.js
"use strict"; import { flushIframes, makeRSDoc, makeStandardOps } from "../SpecHelper.js"; describe("Core - exporter", () => { afterAll(flushIframes); async function getExportedDoc(ops) { const doc = await makeRSDoc(ops); const dataURL = await new Promise(resolve => { doc.defaultView.require(["core...
it("removes .removeOnSave elements", async () => { const ops = makeStandardOps(); ops.body = `<div class="removeOnSave" id="this-should-be-removed">this should be removed</div>`; const doc = await getExportedDoc(ops); expect(doc.getElementById("this-should-be-removed")).toBeFalsy(); expect(doc.qu...
return new DOMParser().parseFromString(docString, "text/html"); }
top.ts
import I18n = require('../interfaces.d'); declare var top:I18n.IFingerprint; top = { rank: -1, iso: 'top', name: 'Totonac, Papantla', trigrams: { akg: 0, 'an ': 1, lak: 2, ata: 3, ama: 4, aka: 5, ' na': 6, ala: 7, kan: 8, ' ka': 9, ini: 10, ' la': 11, ...
ila: 108, nan: 109, ', n': 110, akx: 111, 'n c': 112, 'um ': 113, 'ti ': 114, 'i l': 115, '. l': 116, 'u n': 117, kal: 118, apa: 119, 'n x': 120, 'g l': 121, ana: 122, ' ti': 123, tat: 124, 'u k': 125, 'i t': 126, tap: 1...
'i k': 106, '\'at': 107,
get_status.go
package cmd import ( "fmt" "net/http" "strings" "github.com/spf13/cobra" ) var ( getStatusCmd = &cobra.Command{ Use: fmt.Sprintf("%s [%s]", STATUS, strings.ToUpper(SERVICE)), Short: fmt.Sprintf("Retrieve current %s for a %s", STATUS, SERVICE), Long: fmt.Sprintf("Retrieve the current %s of a %s in Maria...
cxr.rs
/*! One-line description. More detailed description, with # Example */ use crate::forms::library::LibraryName; use crate::scheme::ID_LIB_SCHEME; use schemer_lang::eval::environment::Exports; // ------------------------------------------------------------------------------------------------ // Public Types // -----...
() -> Exports { Exports::default() } // ------------------------------------------------------------------------------------------------ // Implementations // ------------------------------------------------------------------------------------------------ // -------------------------------------------------------...
scheme_cxr_exports
Ad.js
const mongoose = require('mongoose') const schema = new mongoose.Schema({ name: { type: String }, items: [{ image: { type: String }, url: { type: String } }], })
module.exports = mongoose.model('Ad', schema)
app.go
package failover import ( "errors" "github.com/gorilla/mux" "github.com/siddontang/go/log" "net" "net/http" "sync" "time" ) var ( // If failover handler return this error, we will give up future handling. ErrGiveupFailover = errors.New("Give up failover handling") ) type BeforeFailoverHandler func(downMaste...
for master, g := range a.groups { if !a.masters.IsMaster(master) { delete(a.groups, master) g.Close() } } a.gMutex.Unlock() } func (a *App) checkMaster(wg *sync.WaitGroup, g *Group) { defer wg.Done() // later, add check strategy, like check failed n numbers in n seconds and do failover, etc. // now on...
wg.Wait() a.gMutex.Lock()
expr.rs
use super::diagnostics::SnapshotParser; use super::pat::{CommaRecoveryMode, RecoverColon, RecoverComma, PARAM_EXPECTED}; use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; use super::{ AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep, TokenExpe...
impl From<P<Expr>> for LhsExpr { /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`. /// /// This conversion does not allocate. fn from(expr: P<Expr>) -> Self { LhsExpr::AlreadyParsed(expr) } } impl<'a> Parser<'a> { /// Parses an expression. #[inline] pub fn pa...
FormTest.js
import request from '@/utils/request'; //get请求 export async function quer
ams) { //接口地址和参数应该可以一目了然了吧! return request(`/server/api/test222?${stringify(params)}`); } //post请求 // export async function query(params) { // return request('/server/api/getUserName', { // method: 'POST', // body: params, // }); // }
y(par
solana_nodes_controller.go
package web import ( "database/sql" "github.com/gin-gonic/gin" "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-solana/pkg/solana/db" "github.com/smartcontractkit/chainlink/core/services/chainlink" "github.com/smartcontractkit/chainlink/core/web/presenters" ) // ErrSolanaNotEnabled is returned ...
err = errors.Errorf("Solana chain %s must be added first", request.SolanaChainID) } return db.Node{}, err } return db.Node{ Name: request.Name, SolanaChainID: request.SolanaChainID, SolanaURL: request.SolanaURL, }, nil }) }
umychart.index.wechat.js
/* copyright (c) 2018 jones http://www.apache.org/licenses/LICENSE-2.0 开源项目 https://github.com/jones2000/HQChart jones_2000@163.com 指标基类及定制指标 */ import { JSCommonResource_Global_JSChartResource as g_JSChartResource, } from './umychart.resource.wechat.js' import { JSCommonComplier } from "....
标名字 this.UpdateUICallback; //数据到达回调 //默认创建都是线段 this.Create = function (hqChart, windowIndex) { for (var i in this.Index) { if (!this.Index[i].Name) continue; var maLine = new ChartLine(); maLine.Canvas = hqChart.Canvas; maLine.Name =...
//指
index.test.ts
import isPalindrome from '.'; describe('isPalindrome', () => { it('should check if string is palindrome', () => { expect.assertions(8); expect(isPalindrome('a')).toBe(true); expect(isPalindrome('aba')).toBe(true); expect(isPalindrome('Abba')).toBe(true); expect(isPalindrome('hello')).toBe(false)...
});
expect(isPalindrome('Madam')).toBe(true); expect(isPalindrome('AbBa')).toBe(true); expect(isPalindrome('')).toBe(true); });
retrieve_file.go
// Code generated by go-swagger; DO NOT EDIT. package files // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the generate command import ( "net/http" "github.com/go-openapi/runtime/middleware" ) // RetrieveFileHandlerFunc turns a function with the right sign...
res := o.Handler.Handle(Params) // actually handle the request o.Context.Respond(rw, r, route.Produces, route, res) }
{ // bind params o.Context.Respond(rw, r, route.Produces, route, err) return }
index.tsx
import React from 'react' import {Image, View} from 'react-native' import {styles} from './styles'; import DiscordSvg from '../../assets/discord.svg'
const {CDN_IMAGE} = process.env; type Props = { guildId: string; iconId: string | null; } export function GuildIcon({guildId, iconId }:Props) { const uri = `${CDN_IMAGE}/icons/${guildId}/${iconId}.png` return ( <View style={styles.container}> { iconId ? ...
cbt.go
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
} func doDeleteRow(ctx context.Context, args ...string) { if len(args) != 2 { log.Fatal("usage: cbt deleterow <table> <row>") } tbl := getClient().Open(args[0]) mut := bigtable.NewMutation() mut.DeleteRow() if err := tbl.Apply(ctx, args[1], mut); err != nil { log.Fatalf("Deleting row: %v", err) } } func d...
{ log.Fatalf("Deleting column family: %v", err) }
prices.go
package domain import ( "context" "fmt" "strings" "time" "github.com/telecoda/teletrada/proto" ) type Price struct { Base SymbolType As SymbolType Price float64 At time.Time Exchange string } type DaySummary struct { Base SymbolType As SymbolType OpenPrice ...
else { // only one symbol symbolTypes = make([]SymbolType, 1) symbolTypes[0] = SymbolType(req.Base) } resp.Prices = make([]*proto.Price, len(symbolTypes)) for i, symbolType := range symbolTypes { price, err := DefaultArchive.GetLatestPriceAs(symbolType, SymbolType(req.As)) if err != nil { return nil,...
{ // all prices symbolMap := DefaultArchive.GetSymbolTypes() symbolTypes = make([]SymbolType, len(symbolMap)) i := 0 for symbolType, _ := range symbolMap { symbolTypes[i] = symbolType i++ } }
_fragment.py
"""typy fragments""" __all__ = ("Fragment",) class Fragment(object):
def __init__(self): raise FragmentCannotBeInstantiated()
record.go
package schema import ( "encoding/json" "fmt" "strings" "github.com/actgardner/gogen-avro/v8/generator" ) type RecordDefinition struct { name QualifiedName aliases []QualifiedName fields []*Field doc string metadata map[string]interface{} } func NewRecordDefinition(name QualifiedName, aliases [...
items := rvalue.(map[string]interface{}) fieldSetters := "" for k, v := range items { field := r.FieldByName(k) fieldSetter, err := field.Type().DefaultValue(fmt.Sprintf("%v.%v", lvalue, field.GoName()), v) if err != nil { return "", err } fieldSetters += fieldSetter + "\n" } return fieldSetters, nil...
func (r *RecordDefinition) DefaultValue(lvalue string, rvalue interface{}) (string, error) {
zdump_v.py
""" ZdumpV - command ``/usr/sbin/zdump -v /etc/localtime -c 2019,2039`` =================================================================== The ``/usr/sbin/zdump -v /etc/localtime -c 2019,2039`` command provides information about 'Daylight Saving Time' in file /etc/localtime from 2019 to 2039. Sample content from com...
'Sun Mar 10 06:59:59 2019 UTC' >>> dst.get('local_time') datetime.datetime(2019, 3, 10, 1, 59, 59) >>> dst.get('local_time_raw') 'Sun Mar 10 01:59:59 2019 EST' >>> dst.get('isdst') 0 >>> dst.get('gmtoff') -18000 """ from datetime import datetime from insights.specs import Specs from...
datetime.datetime(2019, 3, 10, 6, 59, 59) >>> dst.get('utc_time_raw')
tmrouth.rs
#[doc = "Reader of register TMROUTH"] pub type R = crate::R<u16, super::TMROUTH>; #[doc = "Writer for register TMROUTH"] pub type W = crate::W<u16, super::TMROUTH>; #[doc = "Register TMROUTH `reset()`'s with value 0"] impl crate::ResetValue for super::TMROUTH { type Type = u16; #[inline(always)] fn
() -> Self::Type { 0 } } #[doc = "Reader of field `TIMEROUTHIGH`"] pub type TIMEROUTHIGH_R = crate::R<u16, u16>; #[doc = "Write proxy for field `TIMEROUTHIGH`"] pub struct TIMEROUTHIGH_W<'a> { w: &'a mut W, } impl<'a> TIMEROUTHIGH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)...
reset_value
repo.py
# coding: utf-8 from __future__ import absolute_import from google.appengine.ext import ndb import flask_restful import flask from api import helpers import auth import model import util from main import api_v1 @api_v1.resource('/repo/', endpoint='api.repo.list') class RepoListAPI(flask_restful.Resource): def g...
return helpers.make_response(repo_db, model.Repo.FIELDS)
helpers.make_not_found_exception('Repo %s not found' % repo_key)
validate.go
package main import ( "github.com/nlopes/slack" ) // ****************************************************************************** // Name : isSlackDescriptionValid // Description: Function to validate Slack Channel description before performing // updates // *********************************************...
(description []string) bool { if len(description) < 3 { return false } return true } // ****************************************************************************** // Name : isArgumentFormatValid // Description: Function to validate double quote symbols in slack command // arguments. To check that ...
isSlackDescriptionValid
05b_price_history_unadj.rs
use gurufocus_api as gfapi; use std::env; type PriceHistory = Vec<(String, f64)>; #[tokio::main] async fn
() { let token = env::var("GURUFOCUS_TOKEN").unwrap(); let gf_connect = gfapi::GuruFocusConnector::new(token); let stock = "NYSE:DIS"; let prices = gf_connect.get_unadj_price_hist(stock).await.unwrap(); let prices: PriceHistory = serde_json::from_value(prices).unwrap(); println!("Unadjusted Pr...
main
client.go
/* DNS-over-HTTPS Copyright (C) 2017-2018 Star Brilliant <m13253@hotmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation th...
(conf *config.Config) (c *Client, err error) { c = &Client{ conf: conf, } udpHandler := dns.HandlerFunc(c.udpHandlerFunc) tcpHandler := dns.HandlerFunc(c.tcpHandlerFunc) c.udpClient = &dns.Client{ Net: "udp", UDPSize: dns.DefaultMsgSize, Timeout: time.Duration(conf.Other.Timeout) * time.Second, } c....
NewClient
hashmap.go
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runtime // This file contains the implementation of Go's map type. // // A map is just a hash table. The data is arranged // into an array of buckets. ...
//go:linkname reflect_mapdelete reflect.mapdelete func reflect_mapdelete(t *maptype, h *hmap, key unsafe.Pointer) { mapdelete(t, h, key) } //go:linkname reflect_mapiterinit reflect.mapiterinit func reflect_mapiterinit(t *maptype, h *hmap) *hiter { it := new(hiter) mapiterinit(t, h, it) return it } //go:linkname...
{ mapassign1(t, h, key, val) }
setup.py
from __future__ import print_function import codecs import io import os from thecut.forms import __version__ from setuptools import setup, find_packages import sys here = os.path.abspath(os.path.dirname(__file__)) def read(*filenames, **kwargs): encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('s...
'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Development Status :: 5 - Production/Stable', 'Natural Langu...
analyse_play.py
################################################################################ # STD LIBS import sys # 3RD PARTY LIBS import numpy import pyaudio import analyse # USER LIBS import notes import timing from constants import * #####################################################################...
if __name__ == '__main__': main()
wrap_pystan.py
# pylint: disable=arguments-differ """Base class for PyStan wrappers.""" from ..data import from_pystan from .base import SamplingWrapper class PyStanSamplingWrapper(SamplingWrapper): """PyStan sampling wrapper base class. See the documentation on :class:`~arviz.SamplingWrapper` for a more detailed desc...
def sample(self, modified_observed_data): """Resample the PyStan model stored in self.model on modified_observed_data.""" fit = self.model.sampling(data=modified_observed_data, **self.sample_kwargs) return fit def get_inference_data(self, fit): """Convert the fit object return...
"""Select a subset of the observations in idata_orig. **Not implemented**: This method must be implemented on a model basis. It is documented here to show its format and call signature. Parameters ---------- idx Indexes to separate from the rest of the obser...
fees.dto.ts
import { Field, ObjectType, ID } from "@nestjs/graphql"; import { ObjectId } from 'mongoose'; @ObjectType()
@Field() monthlyFee: number @Field() Concession: number @Field() isPaid: boolean @Field() amountPaid: number @Field() date: Date }
export class FeesDto{ @Field(() => ID) studentId: ObjectId
loadavg_windows_test.go
//go:build windows // +build windows package loadavg import ( "testing" ) func TestGetLoadavg(t *testing.T)
{ loadavg, err := Get() if err == nil { t.Errorf("error should occur for Windows") } if loadavg != nil { t.Errorf("loadavg should be nil") } }
redisvalue.rs
use crate::RedisString; #[derive(Debug, PartialEq)] pub enum RedisValue { SimpleStringStatic(&'static str), SimpleString(String), BulkString(String), BulkRedisString(RedisString), StringBuffer(Vec<u8>), Integer(i64), Float(f64), Array(Vec<RedisValue>), Null, NoReply, // No reply...
(s: Vec<u8>) -> Self { RedisValue::StringBuffer(s) } } impl From<&RedisString> for RedisValue { fn from(s: &RedisString) -> Self { s.to_owned().into() } } impl From<&str> for RedisValue { fn from(s: &str) -> Self { s.to_owned().into() } } impl From<&String> for RedisValue ...
from
app.server.module.ts
import { NgModule } from '@angular/core'; import { ServerModule } from '@angular/platform-server'; import { AppModule } from './app.module'; import { AppComponent } from './app.component'; import { ServerTransferStateModule } from '../modules/transfer-state/server-transfer-state.module'; import { TransferState } from ...
} }
ngOnBootstrap = () => { this.transferState.inject();
mma.py
import logging import cvxpy as cvx import numpy as np from numpy.linalg import norm from tqdm import tqdm class MaxMarginAbbeel(object): """ implementation of (Abbeel & Ng 2004) two versions: available 1. max-margin (stable, computationally more heavy) 2. projection (simpler) """ def ...
# # def train_mma(pi_0, phi_sa_dim, task_desc, params, D, evaluator, ob_space=None, ac_space=None): # gym.logger.setLevel(logging.WARN) # # gamma = task_desc["gamma"] # horizon = task_desc["horizon"] # eps = params["eps"] # p = q = phi_sa_dim # adding action dim # phi = D["phi_fn"] # phi_...
"""linearly parametrize reward function. implements Sec. 3.1 from Abbeel, Ng (2004) Parameters ---------- W : weight Returns ------- TODO - think whether to do s, a or just s """ mu_e = self._mu_expert mu_im1 = mu_list[-...
mod.rs
mod lifeform; pub use self::lifeform::LifeformComponent; pub use self::lifeform::LifeformType; pub use self::lifeform::Orientation; pub use self::lifeform::get_rand_orientation; mod monster; pub use self::monster::Monster; mod player_action; pub use self::player_action::Action; mod outfits; pub use self::outfits::S...
pub use self::walk_animation::WalkAnimation; mod melee_animation; pub use self::melee_animation::MeleeAnimation; mod movement; pub use self::movement::Move;
mod walk_animation;
event.rs
use crate::types::{Block, BlockHash, BlockHeader}; use std::fmt::{Debug, Display};
GetBlockHashResult(BlockHash, BlockByHashResult<I>), GetBlockHeightResult(u64, BlockByHeightResult<I>), GetDeploysResult(DeploysResult<I>), StartDownloadingDeploys, NewPeerConnected(I), BlockHandled(Box<BlockHeader>), } #[derive(Debug)] pub enum DeploysResult<I> { Found(Box<BlockHeader>), ...
#[derive(Debug)] pub enum Event<I> { Start(I),
ca_test.go
// Copyright Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in wri...
maxCertTTL := time.Hour org := "test.ca.Org" const caNamespace = "default" client := fake.NewSimpleClientset() rootCertFile := "" rootCertCheckInverval := time.Hour rsaKeySize := 2048 caopts, err := NewSelfSignedIstioCAOptions(context.Background(), 0, caCertTTL, rootCertCheckInverval, defaultCertTTL, maxCe...
func TestCreateSelfSignedIstioCAWithoutSecret(t *testing.T) { caCertTTL := time.Hour defaultCertTTL := 30 * time.Minute
wxorx.rs
use super::super::{Error, Register, RISCV_MAX_MEMORY, RISCV_PAGES, RISCV_PAGESIZE}; use super::{ check_permission, round_page_down, round_page_up, Memory, FLAG_EXECUTABLE, FLAG_FREEZED, FLAG_WRITABLE, }; use bytes::Bytes; use std::marker::PhantomData; pub struct WXorXMemory<R: Register, M: Memory<R>> { in...
fn execute_load16(&mut self, addr: u64) -> Result<u16, Error> { check_permission(self, addr, 2, FLAG_EXECUTABLE)?; self.inner.execute_load16(addr) } fn load8(&mut self, addr: &R) -> Result<R, Error> { self.inner.load8(addr) } fn load16(&mut self, addr: &R) -> Result<R, Er...
{ if page < RISCV_PAGES as u64 { Ok(self.flags[page as usize]) } else { Err(Error::OutOfBound) } }
chunk.rs
use super::abstract_mut::FastAbstractMut; #[allow(missing_docs)] pub struct FastChunk<Storage> { pub(super) storage: Storage, pub(super) current: usize, pub(super) end: usize, pub(super) step: usize, } impl<Storage: FastAbstractMut> Iterator for FastChunk<Storage> { type Item = Storage::Slice; ...
None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let exact = (self.end - self.current + self.step - 1) / self.step; (exact, Some(exact)) } #[inline] fn fold<B, F>(mut self, mut init: B, mut f: F) -> B where Self: Sized, F...
} else {
NEWGUI.py
from tkinter import * from tkinter import ttk import tkinter.filedialog as fd import pandas as pd from LocalModelCommunication import LocalModelCommunication from APP import APP class GUI(object): def __init__(self): # overall self.tabControl = None self.tab_step1 = None self.tab_step2 = None self.tab_step3...
# frames def tab_import(self, root, tabControl): """ Load local data (csv file) """ self.tabControl = tabControl self.tab_step1 = root frame = Frame(root) frame.pack(side=TOP) Button(frame, text='Import Data', command=self.get_csv, width=16).pack(side=TOP) label_frame = ttk.LabelFrame(frame, text='...
self.tabControl.select(self.tab_step3) self.tabControl.forget(self.tab_step4) ## step 5
contoller_test.go
/* Copyright 2019 The hostpath provisioner operator Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
(cl client.Client) { scc := &secv1.SecurityContextConstraints{} nn := types.NamespacedName{ Name: "test-name", } err := cl.Get(context.TODO(), nn, scc) Expect(err).NotTo(HaveOccurred()) expected := &secv1.SecurityContextConstraints{ Groups: []string{}, TypeMeta: metav1.TypeMeta{ APIVersion: "security.ope...
verifyCreateSCC
eeMad_run.py
''' Created on 08.04.2019 @author: mort ipywidget interface to the GEE for IR-MAD ''' import ee, time, warnings, math import ipywidgets as widgets from IPython.display import display from ipyleaflet import (Map,DrawControl,TileLayer, basemaps,basemap_to_tiles, LayersCo...
): global m,center center = [51.0,6.4] osm = basemap_to_tiles(basemaps.OpenStreetMap.Mapnik) ews = basemap_to_tiles(basemaps.Esri.WorldStreetMap) ewi = basemap_to_tiles(basemaps.Esri.WorldImagery) dc = DrawControl(polyline={},circlemarker={}) dc.rectangle = {"shapeOptions": {"fillColor"...
un(
utils.py
from django.contrib.auth.models import User def get_anonymous_user(): """ Get the user called "anonymous" if it exist. Create the user if it doesn't exist This is the default concordia user if someone is working on the site without logging in first. """ try: return User.objects.get(us...
(request): accept_header = request.META.get("HTTP_ACCEPT", "*/*") return "application/json" in accept_header
request_accepts_json
test_enr.py
import base64 import pytest import rlp from eth_utils import ( decode_hex, to_bytes, ValidationError, ) from eth_utils.toolz import ( assoc, assoc_in, ) from p2p.discv5.enr import ( ENR, ENRSedes, UnsignedENR, ) from p2p.discv5.identity_schemes import ( IdentityScheme, V4Iden...
(): return MockIdentityScheme @pytest.fixture def identity_scheme_registry(mock_identity_scheme): registry = IdentitySchemeRegistry() registry.register(V4IdentityScheme) registry.register(mock_identity_scheme) return registry def test_mapping_interface(identity_scheme_registry): kv_pairs = {...
mock_identity_scheme
index.ts
import config from './config';
export * from './config'; export default config;
test-scheduler_registry.py
#!@PYTHON_EXECUTABLE@ #ckwg +28 # Copyright 2011-2013 by Kitware, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice,...
def __del__(self): if not self.ran_start: test_error("start override was not called") if not self.ran_wait: test_error("wait override was not called") if not self.ran_stop: test_error("stop override was not called") ...
self.ran_resume = True
qr.go
package main import ( "fmt" "os" "path" "github.com/odeke-em/rsc/qr" ) func main()
{ argv := []string{"github.com/odeke-em", "github.com/indragiek"} if len(os.Args[1:]) >= 1 { argv = os.Args[1:] } for _, url := range argv { code, err := qr.Encode(url, qr.Q) if err != nil { fmt.Fprintf(os.Stderr, "%s %v\n", url, err) continue } pngImage := code.PNG() base := path.B...
mock.py
# mock.py # Test tools for mocking and patching. # Copyright (C) 2007-2011 Michael Foord & the mock team # E-mail: fuzzyman AT voidspace DOT org DOT uk # mock 0.8.0 # http://www.voidspace.org.uk/python/mock/ # Released subject to the BSD License # Please see http://www.voidspace.org.uk/python/license.shtml # Scripts...
def assert_called_with(self, *args, **kwargs): """ assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock. """ if self.call_args is None: ra...
delattr(type(self), name) return object.__delattr__(self, name)
arbitrum_block_translator.go
package offchainreporting import ( "context" "fmt" "math/big" "sort" "sync" "time" "github.com/pkg/errors" "github.com/smartcontractkit/chainlink/core/logger" "github.com/smartcontractkit/chainlink/core/services/eth" "github.com/smartcontractkit/chainlink/core/store/models" "github.com/smartcontractkit/cha...
return l1 >= targetL1, nil }) if err != nil { return nil, nil, err } } // RIGHT EDGE // Second, use binary search again to find the smallest L2 block number for which L1 > changedInBlock // Now we can subtract one to get the largest L2 that corresponds to this L1 // This can be skipped if we know we ...
{ exactMatch = true }
permissions_test.go
/* Copyright 2021 Gravitational, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
func upsertLockWithPutEvent(ctx context.Context, t *testing.T, srv *TestAuthServer, lock types.Lock) { lockWatch, err := srv.LockWatcher.Subscribe(ctx) require.NoError(t, err) defer lockWatch.Close() require.NoError(t, srv.AuthServer.UpsertLock(ctx, lock)) select { case event := <-lockWatch.Events(): require...
{ t.Parallel() ctx := context.Background() srv, err := NewTestAuthServer(TestAuthServerConfig{ Dir: t.TempDir(), Clock: clockwork.NewFakeClock(), }) require.NoError(t, err) builtinRole := BuiltinRole{ Username: "node", Role: types.RoleNode, ...
error.handle.js
const errorTypes = require("../constants/errorTypes"); const errorHandler = (error, ctx) => { let status, message; // 判定error.message和errorType的值 switch (error.message) { case errorTypes.USERNAME_OR_PASSWORD_IS_REQUIRED: status = 400; //400:传入的请求参数有问题 message = "请求错误,请检查请求参数"; break; case errorTypes.US...
status = 400; //conflict冲突,409代表发生冲突 message = "密码不正确"; break; case errorTypes.UNAUTHORIZATION: status = 401; //未授权 message = "token授权无效,请先登录"; break; case errorTypes.UNPERMISSION: status = 401; //未授权 message = "您无权进行操作"; break; default: status = 404; message = "NOT FOUND"; bre...
mod.rs
use itertools::Itertools; use lsp_types::{ DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DocumentFilter, DocumentHighlight, DocumentHighlightParams, FoldingRange, FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, InitializeParams, InitializeResult, I...
impl CandyLanguageServer { async fn analyze_files(&self, inputs: Vec<Input>) { log::debug!("Analyzing file(s) {}", inputs.iter().join(", ")); let db = self.db.lock().await; log::debug!("Locked."); for input in inputs { let (hir, _mapping) = db.hir(input.clone()).unwrap()...
let db = self.db.lock().await; let tokens = db.semantic_tokens(params.text_document.uri.into()); Ok(Some(SemanticTokensResult::Tokens(SemanticTokens { result_id: None, data: tokens, }))) } }
utils.py
class QueryAsyncIterator: def __init__(self, query, callback=None): self.query = query self.sequence = None self._sequence_iterator = None self._callback = callback def __aiter__(self):
async def fetch_sequence(self) -> None: self.sequence = await self.query self._sequence_iterator = self.sequence.__iter__() if self._callback: await self._callback(self) async def __anext__(self): if self.sequence is None: await self.fetch_sequence() ...
return self
factory.go
package algo import ( "log" "sync" http_errors "github.com/abdybaevae/url-shortener/pkg/errors/http" repo "github.com/abdybaevae/url-shortener/pkg/repos/algo" num_srv "github.com/abdybaevae/url-shortener/pkg/services/number" ) type factory struct { mu *sync.Mutex repo repo.AlgoRepo store m...
f.store[strategy] = algoService return algoService, nil }
{ return nil, http_errors.ServerInternal }
make_pkg.py
""" Prepare transcriptiondata from the transcription sources. """ from uritemplate import URITemplate from clldutils.clilib import ParserError from csvw.dsv import UnicodeWriter from pyclts.commands.make_dataset import process_transcription_data try: from lingpy.sequence.sound_classes import token2class from l...
if not LINGPY: raise ParserError('lingpy must be installed to run this command!') def writer(*comps): return UnicodeWriter(args.repos.path('pkg', *comps), delimiter='\t') columns = ['LATEX', 'FEATURES', 'SOUND', 'IMAGE', 'COUNT', 'NOTE'] bipa = args.repos.bipa for src, rows in args...