file_name stringlengths 3 137 | prefix stringlengths 0 918k | suffix stringlengths 0 962k | middle stringlengths 0 812k |
|---|---|---|---|
faucets.go | package usecases
import (
"context"
"github.com/consensys/orchestrate/pkg/toolkit/app/multitenancy"
"github.com/consensys/orchestrate/src/entities"
ethcommon "github.com/ethereum/go-ethereum/common"
)
//go:generate mockgen -source=faucets.go -destination=mocks/faucets.go -package=mocks
type FaucetUseCases inter... | type DeleteFaucetUseCase interface {
Execute(ctx context.Context, uuid string, userInfo *multitenancy.UserInfo) error
}
type GetFaucetCandidateUseCase interface {
Execute(ctx context.Context, account ethcommon.Address, chain *entities.Chain, userInfo *multitenancy.UserInfo) (*entities.Faucet, error)
} | Execute(ctx context.Context, filters *entities.FaucetFilters, userInfo *multitenancy.UserInfo) ([]*entities.Faucet, error)
}
|
timebucketedlog_reader.py | from time import time
import six
from six import with_metaclass
from eventsourcing.domain.model.events import QualnameABCMeta
from eventsourcing.domain.model.timebucketedlog import MessageLogged, Timebucketedlog, make_timebucket_id, \
next_bucket_starts, previous_bucket_starts
from eventsourcing.infrastructure.ev... | (self, gt=None, gte=None, lt=None, lte=None, limit=None, is_ascending=False, page_size=None):
assert limit is None or limit > 0
# Identify the first time bucket.
now = decimaltimestamp()
started_on = self.log.started_on
absolute_latest = min(now, lt or now, lte or now)
a... | get_events |
macro-use-one.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
macro_two!();
} | |
unrecognized-repr.rs | use ref_cast::RefCast;
#[derive(RefCast)]
#[repr(packed, C, usize, usize(0), usize = "0")]
struct Test {
s: String,
}
| fn main() {} | |
test_data_collator.py | import unittest
from transformers import AutoTokenizer, is_torch_available
from transformers.testing_utils import require_torch, slow
if is_torch_available():
|
PATH_SAMPLE_TEXT = "./tests/fixtures/sample_text.txt"
PATH_SAMPLE_TEXT_DIR = "./tests/fixtures/tests_samples/wiki_text"
@require_torch
class DataCollatorIntegrationTest(unittest.TestCase):
def test_default_with_dict(self):
features = [{"label": i, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)]
... | import torch
from transformers import (
DataCollatorForLanguageModeling,
DataCollatorForNextSentencePrediction,
DataCollatorForPermutationLanguageModeling,
DataCollatorForSOP,
GlueDataset,
GlueDataTrainingArguments,
LineByLineTextDataset,
LineByLi... |
test_auto_ApplyTransforms.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..resampling import ApplyTransforms
| def test_ApplyTransforms_inputs():
input_map = dict(args=dict(argstr='%s',
),
default_value=dict(argstr='--default-value %g',
usedefault=True,
),
dimension=dict(argstr='--dimensionality %d',
),
environ=dict(nohash=True,
usedefault=True,
),
float=dict(argstr='--float %d',
... | |
get_search_internal_server_error.go | /*
* EVE Swagger Interface
*
* An OpenAPI for EVE Online
*
* OpenAPI spec version: 0.4.1.dev1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
| type GetSearchInternalServerError struct {
// Internal server error message
Error_ string `json:"error,omitempty"`
} | package swagger
// Internal server error |
outbound_campaigns_interactions.go | package outbound_campaigns_interactions
import (
"fmt"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/logger"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/retry"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/services"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/utils"... | }
const opId = "get"
const httpMethod = "GET"
retryFunc := CommandService.DetermineAction(httpMethod, urlString, cmd, opId)
// TODO read from config file
retryConfig := &retry.RetryConfiguration{
RetryWaitMin: 5 * time.Second,
RetryWaitMax: 60 * time.Second,
RetryMax: 20,
}
results, err :=... | urlString += fmt.Sprintf("%v=%v&", url.QueryEscape(strings.TrimSpace(k)), url.QueryEscape(strings.TrimSpace(v)))
}
urlString = strings.TrimSuffix(urlString, "&") |
test_tm_rpc.go | /*
Copyright 2019 The Vitess 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 writing, soft... |
func tmRPCTestMasterPositionPanic(ctx context.Context, t *testing.T, client tmclient.TabletManagerClient, tablet *topodatapb.Tablet) {
_, err := client.MasterPosition(ctx, tablet)
expectHandleRPCPanic(t, "MasterPosition", false /*verbose*/, err)
}
var testStopReplicationCalled = false
func (fra *fakeRPCTM) StopRe... | {
rs, err := client.MasterPosition(ctx, tablet)
compareError(t, "MasterPosition", err, rs, testReplicationPosition)
} |
types.rs | use std::collections::{BTreeMap, BTreeSet};
use std::collections::{HashMap, HashSet};
use std::convert::From;
use std::default::Default;
use std::error;
use std::fmt;
use std::hash::{BuildHasher, Hash};
use std::io;
use std::str::{from_utf8, Utf8Error};
use futures::Future;
/// Helper enum that is used in some situat... | /// that works better in rust. For instance you might want to convert the
/// return value into a `String` or an integer.
///
/// This trait is well supported throughout the library and you can
/// implement it for your own types if you want.
///
/// In addition to what you can see from the docs, this is also implemen... | |
Compilation.js | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const async = require("async");
const crypto = require("crypto");
| const ModuleDependencyWarning = require("./ModuleDependencyWarning");
const ModuleDependencyError = require("./ModuleDependencyError");
const Module = require("./Module");
const Chunk = require("./Chunk");
const Entrypoint = require("./Entrypoint");
const Stats = require("./Stats");
const MainTemplate = require("... | const Tapable = require("tapable");
const EntryModuleNotFoundError = require("./EntryModuleNotFoundError");
const ModuleNotFoundError = require("./ModuleNotFoundError");
|
invvect_test.go | // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wire
import (
"bytes"
"reflect"
"testing"
"github.com/davecgh/go-spew/spew"
"github.com/palcoin-project/palcd/chaincfg/chainhash"
)
// TestInvVectStringe... | (t *testing.T) {
ivType := InvTypeBlock
hash := chainhash.Hash{}
// Ensure we get the same payload and signature back out.
iv := NewInvVect(ivType, &hash)
if iv.Type != ivType {
t.Errorf("NewInvVect: wrong type - got %v, want %v",
iv.Type, ivType)
}
if !iv.Hash.IsEqual(&hash) {
t.Errorf("NewInvVect: wron... | TestInvVect |
Employee.ts | import axios from 'axios';
import { headers } from '../constants/ZenConstants';
import { AuthPayload, AuthResponse, AuthUser } from '../types/Auth';
const LOGIN_URL = `/api/auth/signin`;
const GET_CURRENT_EMPLOYEE_URL = `/api/employees/current`;
| ): Promise<AuthResponse> => {
try {
const response = await axios.post(LOGIN_URL, payload);
return response.data;
} catch (error) {
return Promise.reject(error);
}
};
export const getCurrentEmployee = async (): Promise<AuthUser> => {
try {
const response = await axios.get(GET_CURRENT_EMPLOYEE_UR... | export const getAuthToken = async (
payload: AuthPayload |
execplan.go | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
// NewColOperatorResult is a helper struct that encompasses all of the return
// values of NewColOperator call.
type NewColOperatorResult struct {
Op Operator
ColumnTypes []types.T
InternalMemUsage int
MetadataSources []execinfrapb.MetadataSource
IsStreaming ... | {
var (
toWrapInput execinfra.RowSource
// TODO(asubiotto): Plumb proper processorIDs once we have stats.
processorID int32
)
// Optimization: if the input is a Columnarizer, its input is necessarily a
// distsql.RowSource, so remove the unnecessary conversion.
if c, ok := input.(*Co... |
mod.rs | pub mod key_events; | pub mod tablet_tool_events;
pub mod touch_events;
pub mod xdg_shell_events;
pub mod xdg_shell_v6_events;
pub mod xwayland_events;
pub use self::key_events::Key; | pub mod pointer_events;
pub mod seat_events;
pub mod switch_events;
pub mod tablet_pad_events; |
robotgo.go | // Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// https://github.com/go-vgo/robotgo/blob/master/LICENSE
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT lic... | fun()
}
// MilliSleep sleep tm milli second
func MilliSleep(tm int) {
time.Sleep(time.Duration(tm) * time.Millisecond)
}
// Sleep time.Sleep tm second
func Sleep(tm int) {
time.Sleep(time.Duration(tm) * time.Second)
}
// Deprecated: use the MilliSleep(),
//
// MicroSleep time C.microsleep(tm)
func MicroSleep(tm f... | }() |
bgpservicecommunities.go | package network
// Copyright (c) Microsoft and contributors. 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
//
// Unl... | return
}
// listNextResults retrieves the next set of results, if any.
func (client BgpServiceCommunitiesClient) listNextResults(ctx context.Context, lastResults BgpServiceCommunityListResult) (result BgpServiceCommunityListResult, err error) {
req, err := lastResults.bgpServiceCommunityListResultPreparer(ctx)
if e... | autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp} |
roleService.ts | import { RoleModel } from ".";
/**
* User role management service.
*/
export interface RoleService {
/**
* Returns all available roles.
*/
getRoles(): Promise<RoleModel[]>;
| } | |
reactiveform.component.ts | import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
moduleId: module.id.replace("dist", ""),
selector: 'reactive-form',
templateUrl: '../templates/reactiveform.html'
})
export class Re |
title = 'Reactive Form';
reactiveForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.reactiveForm = formBuilder.group({
'name': '',
'gender': 'Male',
'hiking': false,
'running': false
});
}
submitForm(value: any): v... | activeFormComponent { |
slot.rs | use crate::db::DbQueryResult;
use crate::db::Pool;
use crate::schema::slots as slots_table;
use crate::schema::slots::dsl::*;
use chrono::prelude::*;
use diesel::dsl::insert_into;
use diesel::prelude::*;
use juniper::{GraphQLInputObject, GraphQLObject};
use serde::{Deserialize, Serialize};
#[derive(Queryable, Debug, G... | pub fn find(pool: &Pool, slot_id: i32) -> DbQueryResult<Slot> {
let conn = pool.get().unwrap();
slots.find(slot_id).get_result::<Slot>(&conn)
}
pub fn all(pool: &Pool) -> DbQueryResult<Vec<Slot>> {
let conn = pool.get().unwrap();
slots.load::<Slot>(&conn)
}
pub fn c... | end_time: NaiveDateTime,
}
impl Slot { |
didl.py |
from lxml.builder import ElementMaker
from moai.metadata.mods import NL_MODS, XSI_NS
class DIDL(object):
"""A metadata prefix implementing the DARE DIDL metadata format
this format is registered under the name "didl"
Note that this format re-uses oai_dc and mods formats that come with
MOAI b... |
def get_namespace(self):
return self.ns[self.prefix]
def get_schema_location(self):
return self.schemas[self.prefix]
def __call__(self, element, metadata):
data = metadata.record
DIDL = ElementMaker(namespace=self.ns['didl'], nsmap=self.ns)
... | self.prefix = prefix
self.config = config
self.db = db
self.ns = {'didl': "urn:mpeg:mpeg21:2002:02-DIDL-NS",
'dii': "urn:mpeg:mpeg21:2002:01-DII-NS",
'dip': "urn:mpeg:mpeg21:2005:01-DIP-NS",
'dcterms': "http://purl.org/dc/terms/",... |
coinbase_pro.rs | use crypto_market_type::{get_market_types, MarketType};
use crypto_markets::{fetch_markets, fetch_symbols};
use crypto_pair::get_market_type;
#[macro_use]
mod utils;
const EXCHANGE_NAME: &str = "coinbase_pro";
#[test]
fn fetch_all_symbols() {
gen_all_symbols!();
}
#[test]
fn fetch_spot_symbols() |
#[test]
fn fetch_spot_markets() {
let markets = fetch_markets(EXCHANGE_NAME, MarketType::Spot).unwrap();
assert!(!markets.is_empty());
let btcusd = markets
.iter()
.find(|m| m.symbol == "BTC-USD")
.unwrap()
.clone();
assert_eq!(btcusd.precision.tick_size, 0.01);
as... | {
let symbols = fetch_symbols(EXCHANGE_NAME, MarketType::Spot).unwrap();
assert!(!symbols.is_empty());
for symbol in symbols.iter() {
assert!(symbol.contains("-"));
assert_eq!(symbol.to_string(), symbol.to_uppercase());
assert_eq!(
MarketType::Spo... |
dispersion.py | from itertools import combinations
__author__ = "\n".join(['Ben Edwards (bedwards@cs.unm.edu)',
'Huston Hedinger (h@graphalchemist.com)',
'Dan Schult (dschult@colgate.edu)'])
__all__ = ['dispersion']
def dispersion(G, u=None, v=None, normalized=True, alpha=1.0, b=0.0,... | (G_u, u, v):
"""dispersion for all nodes 'v' in a ego network G_u of node 'u'"""
u_nbrs = set(G_u[u])
ST = set(n for n in G_u[v] if n in u_nbrs)
set_uv = set([u, v])
# all possible ties of connections that u and b share
possib = combinations(ST, 2)
total = 0
... | _dispersion |
backup.go | package backup
import (
corev1 "k8s.io/api/core/v1"
api "github.com/percona/percona-xtradb-cluster-operator/pkg/apis/pxc/v1"
)
type Backup struct {
cluster string
namespace string
image string
imagePullSecrets []corev1.LocalObjectReference
}
func | (cr *api.PerconaXtraDBCluster, spec *api.PXCScheduledBackup) *Backup {
return &Backup{
cluster: cr.Name,
namespace: cr.Namespace,
image: spec.Image,
imagePullSecrets: spec.ImagePullSecrets,
}
}
| New |
__init__.py | def hello():
| print("Hello from Package 2") | |
main.js | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/*
https://github.com/banksean wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
so it's better encapsulated. Now you can have multiple random number generators
and they won't stomp all over each other's state.
... | // some time from now to N years ago, in milliseconds
date.setTime(past + this.random.number(range));
return date;
}
}
const avatarUris = [
'https://randomuser.me/api/portraits/men/0.jpg',
'https://randomuser.me/api/portraits/men/1.jpg',
'https://randomuser.me/api/portrai... | const past = date.getTime();
|
utils.py | # Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import importlib
from collections import OrderedDict
from contextlib import contextmanager
import torch
_is_nncf_enabled = importlib.util.find_spec('nncf') is not None
def is_nncf_enabled():
return _is_nncf_enabled
def check_nncf... | ():
if not is_nncf_enabled():
return None
import nncf
return nncf.__version__
def load_checkpoint(model, filename, map_location=None, strict=False):
"""Load checkpoint from a file or URI.
Args:
model (Module): Module to load checkpoint.
filename (str): Either a filepath or... | get_nncf_version |
test_archive_util.py | """Tests for distutils.archive_util."""
__revision__ = "$Id: test_archive_util.py 75659 2009-10-24 13:29:44Z tarek.ziade $"
import unittest
import os
import tarfile
from os.path import splitdrive
import warnings
from distutils.archive_util import (check_archive_formats, make_tarball,
... | (self):
tmpdir, tmpdir2, base_name = self._create_files()
old_dir = os.getcwd()
os.chdir(tmpdir)
group = grp.getgrgid(0)[0]
owner = pwd.getpwuid(0)[0]
try:
archive_name = make_tarball(base_name, 'dist', compress=None,
... | test_tarfile_root_owner |
database.py | # -*- coding: utf-8 -*-
#
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache 2 License.
#
# This product includes software developed at Datadog
# (https://www.datadoghq.com/).
#
# Copyright 2018 Datadog, Inc.
#
"""database.py
Testing utils for creating database records ... |
def create_issue():
"""Create a GitHub issue representation."""
db.session.add(
Issue(
name='Test adding a new issue',
url='https://github.com/a-organization/a-repo/issues/56',
github_issue_id=default_issue_id,
repo_id=default_repo_id,
trell... | """Create a subscribed list to create cards for."""
db.session.add(
SubscribedList(
subscription_board_id=default_board_id,
subscription_repo_id=default_repo_id,
list_id=default_list_id
)
) |
clusterdomain.go | package clusterdomain
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/rancher/rio/modules/istio/pkg/domains"
"github.com/rancher/rio/modules/istio/pkg/parse"
adminv1 "github.com/rancher/rio/pkg/apis/admin.rio.cattle.io/v1"
riov1 "github.com/rancher/rio/pkg/apis/rio.cattle.io/v1"
"github.com/rancher/... |
func (h handler) syncRouterDomain(key string, obj runtime.Object) (runtime.Object, error) {
if obj == nil {
return nil, nil
}
clusterDomain, err := h.clusterDomain.Cache().Get(h.namespace, constants.ClusterDomainName)
if err != nil {
return obj, err
}
updateRouterDomain(obj.(*riov1.Router), clusterDomain)... | {
public := domains.IsPublic(service)
protocol := "http"
if clusterDomain.Status.HTTPSSupported {
protocol = "https"
}
var endpoints []string
if public && clusterDomain.Status.ClusterDomain != "" {
app, version := services2.AppA... |
styled.js | import styled from "styled-components";
import { StyledCard } from "../NormalCard/styled";
import { SuccessAnimation } from "components/Global/transitions.styled";
const SuccessText = styled.p`
position: relative;
top: 40px;
| `;
const StyledSuccessCard = styled(StyledCard)`
justify-content: center;
background: ${({ success, theme }) => (success === "ERROR" ? theme.RED_FORBIDDEN : theme.SUCESS)};
i {
font-size: 5rem;
color: white;
}
@media (min-width: 768px) {
animation: ${SuccessAnimation} 2s;
}
`;
export { StyledSuccessCar... | color: white;
font-size: ${({ theme }) => theme.LARGE};
font-weight: bold; |
raw-loader.js | exports.__es6Module = true;
exports.default = function(source) { | return new Buffer(source.toString("hex") + source.toString("utf-8"), "utf-8"); // eslint-disable-line
};
exports.raw = true; | |
JURA108TestCase.py | from tir import Webapp
import unittest
class JURA108(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.SetTIRConfig(config_name="user", value="daniel.frodrigues")
inst.oHelper.SetTIRConfig(config_name="password", value="1")
inst.oHelper.Setup('SIGAJURI','','T1','D M... | t):
inst.oHelper.TearDown()
if __name__ == '__main__':
unittest.main()
| DownClass(ins |
clear_injectables_util.py | from typing import Union, Set
from injectable import InjectionContainer
from injectable.common_utils import get_dependency_name
from injectable.container.injectable import Injectable
from injectable.constants import DEFAULT_NAMESPACE
def clear_injectables(
dependency: Union[type, str], namespace: str = None
) ->... | """
Utility function to clear all injectables registered for the dependency in a given
namespace. Returns a set containing all cleared injectables.
:param dependency: class or qualifier of the dependency.
:param namespace: (optional) namespace in which the injectable will be registered.
... | |
default_camera_system.rs | use crate::{
core::{
components::maths::{
camera::{Camera, DefaultCamera},
transform::Transform,
},
resources::window::Window,
},
legion::{*, systems::CommandBuffer},
};
/// System responsible of adding a Camera on each entity with a DefaultCamera component
#... | camera,
);
cmd.add_component(*entity, Transform::default());
}
/// System responsible of applying dpi to each camera
#[system(for_each)]
pub(crate) fn camera_dpi(
#[resource] window_dimension: &Window,
c: &mut Camera,
) {
c.dpi = window_dimension.dpi();
} | camera.dpi = window_dimension.dpi();
cmd.add_component(
*entity, |
get_bst_feature_api_ct.py | '''
*
* (C) Copyright Broadcom Corporation 2015
*
* 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 appli... |
def main(ip_address,port):
jsonText = ConfigParser.ConfigParser()
cwdir, f = os.path.split(__file__)
jsonText.read(cwdir + '/testCaseJsonStrings.ini')
json_dict = dict(jsonText.items('get_bst_feature_api_ct'))
params=json_dict.get("paramslist","")
tcObj = get_bst_feature_api_ct(ip_address,port... | return returnStatus(sorted(plist),sorted(result.keys()),"","get_bst_feature params lists contains invalid param keys")
def getSteps(self):
return sorted([ i for i in dir(self) if i.startswith('step') ], key=lambda item: int(item.replace('step',''))) |
ad_group_type.pb.go | // Copyright 2022 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in w... | NumServices: 0,
},
GoTypes: file_google_ads_googleads_v10_enums_ad_group_type_proto_goTypes,
DependencyIndexes: file_google_ads_googleads_v10_enums_ad_group_type_proto_depIdxs,
EnumInfos: file_google_ads_googleads_v10_enums_ad_group_type_proto_enumTypes,
MessageInfos: file_google_a... | NumEnums: 1,
NumMessages: 1,
NumExtensions: 0, |
AccountService.d.ts | import type { APIClient } from '@wireapp/api-client';
import type { CallConfigData } from '@wireapp/api-client/src/account/CallConfigData';
export declare class | {
private readonly apiClient;
constructor(apiClient: APIClient);
getCallConfig(): Promise<CallConfigData>;
}
| AccountService |
tar_interpreter.go | package postgres
import (
"archive/tar"
"io"
"os"
"path"
"path/filepath"
"strings"
"github.com/enix/wal-g/internal"
"github.com/enix/wal-g/utility"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/wal-g/tracelog"
)
// FileTarInterpreter extracts input to disk.
type FileTarInterpreter struct {
... | (fileName string, targetPath string) error {
if fileName == targetPath {
return nil // because it runs in the local directory
}
base := filepath.Base(fileName)
dir := strings.TrimSuffix(targetPath, base)
err := os.MkdirAll(dir, 0755)
return err
}
| PrepareDirs |
replication_controller.rs | // Generated from definition io.k8s.api.core.v1.ReplicationController
/// ReplicationController represents the configuration of a replication controller.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ReplicationController {
/// If the Labels of a ReplicationController are empty, they are defaulted to be t... | /// name of the ReplicationController
///
/// * `namespace`
///
/// object name and auth scope, such as for teams and projects
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
... | /// # Arguments
///
/// * `name`
/// |
imports_spec.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {absoluteFrom, getFileSystem, getSourceFileOrError} from '../../file_system';... | (imports: Set<ts.SourceFile>): string {
const fs = getFileSystem();
return Array.from(imports)
.map(sf => fs.basename(sf.fileName).replace('.ts', ''))
.sort()
.join(',');
}
});
| importsToString |
IdentifyReplyCommandFirmwareVersion.go | /*
* 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 ... | }
func (m *IdentifyReplyCommandFirmwareVersion) GetLengthInBitsConditional(lastItem bool) uint16 {
lengthInBits := uint16(m.GetParentLengthInBits())
// Simple field (firmwareVersion)
lengthInBits += 64
return lengthInBits
}
func (m *IdentifyReplyCommandFirmwareVersion) GetLengthInBytes() uint16 {
return m.GetL... | }
func (m *IdentifyReplyCommandFirmwareVersion) GetLengthInBits() uint16 {
return m.GetLengthInBitsConditional(false) |
genembed2.go | // run
// Copyright 2021 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.
// Test for declaration and use of a parameterized embedded field.
package main
import (
"fmt"
"sync"
)
type MyStruct[T any] struct {
val T
}
typ... | () {
var li Lockable[int]
li.Set(5)
if got, want := li.Get(), 5; got != want {
panic(fmt.Sprintf("got %d, want %d", got, want))
}
}
| main |
users.py | from flask import jsonify, request, url_for, abort
from app import db
from app.api import bp
from app.api.auth import token_auth
from app.api.errors import bad_request
from app.models import User
@bp.route('/users/<int:id>', methods=['GET'])
@token_auth.login_required
def get_user(id):
return jsonify(User.query.ge... | (id):
if token_auth.current_user().id != id:
abort(403)
user = User.query.get_or_404(id)
data = request.get_json() or {}
if 'username' in data and data['username'] != user.username and \
User.query.filter_by(username=data['username']).first():
return bad_request('Please use a... | update_user |
tcp.go | package meters
import (
"time"
"github.com/grid-x/modbus"
)
// TCP is a TCP modbus connection
type TCP struct {
address string
Client modbus.Client
Handler *modbus.TCPClientHandler
}
// NewTCPClientHandler creates a TCP modbus handler
func NewTCPClientHandler(device string) *modbus.TCPClientHandler {
handler... | }
return b
}
// String returns the bus connection address (TCP)
func (b *TCP) String() string {
return b.address
}
// ModbusClient returns the TCP modbus client
func (b *TCP) ModbusClient() modbus.Client {
return b.Client
}
// Logger sets a logging instance for physical bus operations
func (b *TCP) Logger(l Log... | address: address,
Client: client,
Handler: handler, |
specified_location.py | # from .provider_test import ProviderTest, TestSource
from gunpowder import (BatchProvider, ArrayKeys, ArraySpec, Roi, Batch,
Coordinate, SpecifiedLocation, build,
BatchRequest, Array, ArrayKey)
import numpy as np
import unittest
class TestSourceSpecifiedLocation(BatchPro... | def setUp(self):
ArrayKey('RAW')
def test_simple(self):
locations = [
[0, 0, 0],
[100, 100, 100],
[91, 20, 20],
[42, 24, 57]
]
pipeline = (
TestSourceSpecifiedLocation(
roi=Roi(... | |
layout.js | /**
* Layout component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.org/docs/use-static-query/
*/
import React from "react";
import PropTypes from "prop-types";
import { useStaticQuery, graphql } from "gatsby";
import Container from "@material-ui/core/Container";
im... | title
}
}
}
`);
return (
<Container maxWidth="lg">
<Header siteTitle={data.site.siteMetadata.title} />
<div
style={{
margin: `0 auto`,
maxWidth: 960,
padding: `0 1.0875rem 1.45rem`
}}
>
<main>{children}</main>
... | query SiteTitleQuery {
site {
siteMetadata { |
index.js | import './index.css';
import Uploader from './uploader';
const LOADER_TIMEOUT = 500;
const Icon =
'<svg width="12" height="14" xmlns="http://www.w3.org/2000/svg"><path d="M4.109 2.08H2.942a.862.862 0 0 0-.862.862v8.116c0 .476.386.862.862.862h5.529a.862.862 0 0 0 .862-.862V7.695H4.11V2.08zm1.905.497v3.29h3.312l-3.312-... | {
static get isReadOnlySupported() {
return true;
}
/**
* @param {AttachesToolData} data
* @param {Object} config
* @param {API} api
* @param {boolean} readOnly - read-only mode flag
*/
constructor({ data, config, api, readOnly }) {
this.api = api;
this.readOnly = readOnly;
thi... | AttachesTool |
listtocommaseparated.py | #! /usr/bin/env python3
"""converts list to comma separated string"""
items = ['foo', 'bar', 'xyz']
print (','.join(items)) | print (','.join(map(str, numbers)))
"""list of mix data"""
data = [2, 'hello', 3, 3.4]
print (','.join(map(str, data))) |
"""list of numbers to comma separated"""
numbers = [2, 3, 5, 10]
|
server.go | package main
import (
"log"
"github.com/kataras/iris"
"github.com/kataras/iris/websocket"
// Used when "enableJWT" constant is true:
"github.com/iris-contrib/middleware/jwt"
)
// values should match with the client sides as well.
const enableJWT = true
const namespace = "default"
// if namespace is empty then... | () {
app := iris.New()
websocketServer := websocket.New(
websocket.DefaultGorillaUpgrader, /* DefaultGobwasUpgrader can be used too. */
serverEvents)
j := jwt.New(jwt.Config{
// Extract by the "token" url,
// so the client should dial with ws://localhost:8080/echo?token=$token
Extractor: jwt.FromParameter... | main |
config.rs | use anyhow::{bail, Error, Result};
use std::panic::panic_any;
const BINARY_NAME: &str = env!("CARGO_BIN_NAME");
#[derive(serde::Deserialize, Clone, Debug)]
pub struct CompleteConfig {
pub private_key_path: String,
pub application_id: u64,
pub application_token: String,
#[serde(default = "default_se... |
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(target_os = "windows")]
fn test_windows_config_path() {
match std::env::var("APPDATA") {
Ok(appdata_path) => assert_eq!(
config_path(),
format!("{}\\{}\\config.toml", appdata_path, BINARY_NAME)
... | {
match std::env::consts::OS {
"linux" | "macos" => match std::env::var("HOME") {
Ok(env_home_path) => format!("{}/.config/{}/config.toml", env_home_path, BINARY_NAME),
Err(err) => panic_any(err),
},
"windows" => match std::env::var("APP... |
imagenet_utils.py | """Utilities for ImageNet data preprocessing & prediction decoding.
"""
import json
import keras.utils.data_utils as data_utils
CLASS_INDEX = None
CLASS_INDEX_PATH = ('https://storage.googleapis.com/download.tensorflow.org/'
'data/imagenet_class_index.json')
def | (preds, top=5):
"""Decodes the prediction of an ImageNet model.
# Arguments
preds: Numpy array encoding a batch of predictions.
top: Integer, how many top-guesses to return.
# Returns
A list of lists of top class prediction tuples
`(class_name, class_description)`.
... | decode_predictions |
lr_monitor.py | # Copyright The PyTorch Lightning team.
#
# 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 i... | (
self, name: str, optimizer_cls: Type[Optimizer], seen_optimizer_types: DefaultDict[Type[Optimizer], int]
) -> str:
if optimizer_cls not in seen_optimizer_types:
return name
count = seen_optimizer_types[optimizer_cls]
return name + f'-{count - 1}' if count > 1 else name
... | _add_prefix |
progress_bar.py | import logging
import multiprocessing as mp
import multiprocessing.context
import sys
from datetime import datetime, timedelta
from typing import Any, Dict, Optional, Type
from tqdm.auto import tqdm
from mpire.comms import WorkerComms, POISON_PILL
from mpire.dashboard.connection_utils import (DashboardConnectionDetai... |
def _progress_bar_handler(self, tqdm_connection_details: TqdmConnectionDetails,
dashboard_connection_details: DashboardConnectionDetails) -> None:
"""
Keeps track of the progress made by the workers and updates the progress bar accordingly
:param tqdm_connect... | """
Enables the use of the ``with`` statement. Terminates the progress handler process if there is one
"""
if self.show_progress_bar and self.process.is_alive():
# If this exit is called with an exception, then we assume an external kill signal was received (this is,
... |
args.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 {argh::FromArgs, ffx_core::ffx_command};
#[ffx_command()]
#[derive(FromArgs, Debug, PartialEq, Clone)]
#[argh(
subcommand,
name = "wait",
... | } | pub struct WaitCommand {
#[argh(option, short = 't', default = "60")]
/// the timeout in seconds [default = 60]
pub timeout: usize, |
test.py | {"code":0,"message":"0","ttl":1,"data":[{"cid":260839008,"page":1,"from":"vupload","part":"PocketLCD_with_srt","duration":467,"vid":"","weblink":"","dimension":{"width":1920,"height":1080,"rotate":0}}]} | ||
loading_panel.tsx | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. |
import React, { FC } from 'react';
import { EuiLoadingSpinner, EuiPanel } from '@elastic/eui';
export const LoadingPanel: FC = () => (
<EuiPanel className="eui-textCenter">
<EuiLoadingSpinner size="xl" />
</EuiPanel>
); | */ |
author.model.ts | import { Book } from './book.model';
export interface Author {
__typename: 'Author';
id: string; | books?: Book;
} | name: string;
dob?: number; |
Question.d.ts | export declare class Question { | id: number;
name: string;
} | |
test_order_reconcile_return_object.py | # coding: utf-8
"""
Hydrogen Nucleus API
The Hydrogen Nucleus API # noqa: E501
OpenAPI spec version: 1.9.5
Contact: info@hydrogenplatform.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import nucleus_api
from nu... |
def testOrderReconcileReturnObject(self):
"""Test OrderReconcileReturnObject"""
# FIXME: construct object with mandatory attributes with example values
# model = nucleus_api.models.order_reconcile_return_object.OrderReconcileReturnObject() # noqa: E501
pass
if __name__ == '__mai... | pass |
root_mutation_object.py | from graphql.schema import GraphQlFuncDescriptor
class GraphQlRootMutationObject(object):
"""The root mutation object for GraphQL.
This is the object whose fields we "query" at the root level of a
GraphQL mutation operation.
"""
# The singleton instance of GraphQlRootMutationObject, or None if w... |
def execute_mutation(self, module_name, class_name, func_name, **kwargs):
"""Execute a mutation and return its value.
basestring module_name - The name of the Python module containing
the method or function that executes the mutation
basestring class_name - The name of the cla... | """Return the singleton instance of GraphQlRootMutationObject."""
if GraphQlRootMutationObject._instance is None:
GraphQlRootMutationObject._instance = GraphQlRootMutationObject()
return GraphQlRootMutationObject._instance |
field.go | package jira
import "context"
// FieldService handles fields for the JIRA instance / API.
//
// JIRA API docs: https://developer.atlassian.com/cloud/jira/platform/rest/#api-Field
type FieldService struct {
client *Client
}
// Field represents a field of a JIRA issue.
type Field struct {
ID string `js... |
return fieldList, resp, nil
}
// GetList wraps GetListWithContext using the background context.
func (s *FieldService) GetList() ([]Field, *Response, error) {
return s.GetListWithContext(context.Background())
}
| {
return nil, resp, NewJiraError(resp, err)
} |
codegen.rs | // Copyright 2018 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 std::borrow::Cow;
use std::io;
use crate::ast;
use crate::parser::ArgKind;
pub type Result = io::Result<()>;
pub struct Codegen<W: io::Write> {
... |
/// Generates an impl for the Event trait for a set of messages. This
/// will be the code that allows the message type to be serialized into
/// a Message that can be sent over channel.
///
/// Ex:
/// impl IntoMessage for Event {
/// fn into_message(self, id: u32) -> Result<Messa... | {
writeln!(self.w, "#[derive(Debug)]")?;
writeln!(self.w, "pub enum {enum_name} {{", enum_name = name)?;
for message in messages.iter() {
if let Some(ref d) = message.description {
self.codegen_description(d, " ")?;
}
if mess... |
timestamp.scalar.ts | import { Scalar, CustomScalar } from '@nestjs/graphql';
import { Kind, ValueNode } from 'graphql';
@Scalar('Timestamp', () => Date)
export class Timestamp implements CustomScalar<number, Date> {
description = '`Date` type as integer. Type represents date and time as number of milliseconds from start of UNIX epoch.';... | return null;
}
}
parseLiteral(valueNode: ValueNode) {
if (
valueNode.kind === Kind.INT ||
valueNode.kind === Kind.STRING
) {
try {
const number = Number(valueNode.value);
return new Date(number);
} catch {
return null;
}
}
return null;... | |
defaults.go | package testkit
import "fmt"
type RoleName = string
//Merge "Use the class param to configure Cinder 'host' setting"
var DefaultRoles = map[RoleName]func(*TestEnvironment) error{
"bootstrapper": func(t *TestEnvironment) error {
b, err := PrepareBootstrapper(t)
if err != nil {
return err
}
return b.RunDe... |
return tr.RunDefault()
},
} //Update schedule.module.ts
// HandleDefaultRole handles a role by running its default behaviour.
//
// This function is suitable to forward to when a test case doesn't need to
// explicitly handle/alter a role.
func HandleDefaultRole(t *TestEnvironment) error {
f, ok := DefaultRoles[... | { // Add sparql queries for transport needs
return err/* POC: use of constructors */
} |
inotify.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google, 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
#
# ... | (self):
path = unicode_paths.encode(self.watch.path)
self._inotify = InotifyBuffer(path, self.watch.is_recursive)
def on_thread_stop(self):
if self._inotify:
self._inotify.close()
def queue_events(self, timeout, full_events=False):
# If "full_events" is true, then t... | on_thread_start |
source-coverage.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use bytecode_source_map::utils::{remap_owned_loc_to_loc, source_map_from_file, OwnedLoc};
use move_coverage::{coverage_map::CoverageMap, source_coverage::SourceCoverageBuilder};
use starcoin_vm_types::file_form... | {
let args = Args::from_args();
let source_map_extension = "mvsm";
let coverage_map = if args.is_raw_trace_file {
CoverageMap::from_trace_file(&args.input_trace_path)
} else {
CoverageMap::from_binary_file(&args.input_trace_path)
};
let bytecode_bytes = fs::read(&args.... | |
sodium.rs | extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use self::sodiumoxide::crypto::aead::
chacha20poly1305_ietf;
use self::sodiumoxide::utils;
use std::cmp;
use std::io;
use std::io::{Read, Write};
use utils::crypto::pwhash_argon2i13;
pub const KEYBYTES: usize = chacha20poly1305... | (&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut pos = 0;
// Consume from rest buffer
if self.rest_buffer.len() > 0 {
let to_copy = cmp::min(self.rest_buffer.len(), buf.len() - pos);
buf[pos..pos + to_copy].copy_from_slice(&self.rest_buffer[..to_copy]);
... | read |
test.py | # import gevent.monkey
# gevent.monkey.patch_socket()
from pyEtherCAT import MasterEtherCAT
import time
import os
#============================================================================#
# C95用の簡易EtherCATパッケージです。
# 本来は細かいパケットに付いて理解を深めた上で仕組みを構築していきますが、
# 説明も実験も追いつかず、ひとまずGPIOで高速にON/OFF出来る部分だけを纏めました。
# 動作は Linux(R... | ADO=ADDR, DATA=[
data & 0xFF, (data >> 8) & 0xFF])
(DATA, WKC) = cat.socket_read()
print("[0x{:04x}]= 0x{:04x}".format(ADDR, DATA[0] | DATA[1] << 8))
ADDR = 0x0120 # AL 制御レジスタ
data = 0x0002 # 2h: 動作前ステートを要求する
cat.APWR(IDX=0x00, ADP=cat.ADP, ADO=ADDR, DATA=[
data & 0xFF, ... | に変更不要
ADDR = 0x0120 # AL 制御レジスタ
data = 0x0002 # 2h: 動作前ステートを要求する
cat.APWR(IDX=0x00, ADP=cat.ADP, |
index.ts | import { BigNumberish } from '@ethersproject/bignumber';
import { formatUnits } from '@ethersproject/units';
import { Multicaller } from '../../utils';
export const author = 'gamiumworld';
export const version = '0.1.0';
const tokenAbi = [
'function balanceOf(address _owner) view returns (uint256 balance)'
];
const... | address,
options.staking_pair,
'totalStakeTokenDeposited',
[address]
);
stakingTokenMulticaller.call(
address,
options.staking_token,
'totalStakeTokenDeposited',
[address]
);
tokenMulticaller.call(address, options.token, 'balanceOf', [address]);
});
c... |
addresses.forEach((address) => {
stakingPairMulticaller.call( |
org-chart.js | sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict';
const name = "org-chart";
const pathData = "M484 341q28 0 28 28v113q0 13-7.5 21t-20.5 8H313q-13 0-20.5-8t-7.5-21V369q0-28 28-28h57v-57H143v57h57q28 0 28 28v113q0 13-7.5 21t-20.5 8H29q-13 0-20.5-8T1 482V369q0... |
}); | return pathDataV4; |
index.tsx | import { useEffect, useState } from 'react';
import { useHistory, useParams } from 'react-router-dom';
import toast from 'react-hot-toast';
import logoImgLight from '../../assets/images/logo-light.svg';
import logoImgDark from '../../assets/images/logo-dark.svg';
import { RoomCode } from '../../components/RoomCode';
... |
async function handleDeleteQuestion(questionId?: string) {
if (questionId) {
await database.ref(`rooms/${roomId}/questions/${questionId}`)
.remove();
setQuestionIdModalOpen(undefined);
}
}
async function handleHighlightQuestion(questionId: string) {
await handleUpdatedQuestion(q... | if (!user) {
await signInWithGoogle();
}
} |
DefaultFontStyles.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var glamorExports_1 = require("../glamorExports");
var language_1 = require("@uifabric/utilities/lib/language");
// Default urls.
var DefaultBaseUrl = 'https://static2.sharepointonline.com/files/fabric/assets';
// Fallback fonts, if specified ... | _registerFontFace('Leelawadee UI Web', fontUrl + "/leelawadeeui-thai/leelawadeeui-bold", FontWeights.semibold);
// Register icon urls.
_registerFontFace('FabricMDL2Icons', iconUrl + "/fabricmdl2icons-" + FontFileVersion, FontWeights.regular);
}
}
/**
* Reads the fontBaseUrl from window.Fabr... | // Leelawadee UI (Thai) does not have a 'semibold' weight, so we override
// the font-face generated above to use the 'bold' weight instead. |
controls.js | function Controls() {
let _matrix;
let _stateManager;
const THEMES = ['red-leds',
'yellow-leds',
'green-leds',
'blue-leds',
'white-leds',
'black-leds'
];
function init(stateManager, matrix) {
_stateManager = stateManager;
_matrix = matrix;
... | } | |
__init__.py | from django.contrib.sites.models import Site, get_current_site
from django.core import urlresolvers, paginator
from django.core.exceptions import ImproperlyConfigured
import urllib
PING_URL = "http://www.google.com/webmasters/tools/ping"
class SitemapNotFound(Exception):
|
def ping_google(sitemap_url=None, ping_url=PING_URL):
"""
Alerts Google that the sitemap for the current site has been updated.
If sitemap_url is provided, it should be an absolute path to the sitemap
for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this
function will ... | pass |
rpc_client.rs | use crate::{
client_error::{ClientError, ClientErrorKind, Result as ClientResult},
http_sender::HttpSender,
mock_sender::{MockSender, Mocks},
rpc_config::RpcAccountInfoConfig,
rpc_config::{
RpcGetConfirmedSignaturesForAddress2Config, RpcLargestAccountsConfig,
RpcProgramAccountsConfig... | (
transaction: &Transaction,
encoding: UiTransactionEncoding,
) -> ClientResult<String> {
let serialized = serialize(transaction)
.map_err(|e| ClientErrorKind::Custom(format!("transaction serialization failed: {}", e)))?;
let encoded = match encoding {
UiTransactionEncoding::Base58 => bs... | serialize_encode_transaction |
wrappers.py | # pylint: disable=W0622,E1101
"""
A basic object-oriented interface for Galaxy entities.
"""
import abc
import json
from collections.abc import (
Iterable,
Mapping,
Sequence,
)
from typing import Tuple
import bioblend
from bioblend.util import abstractclass
__all__ = (
'Wrapper',
'Step',
'W... |
def export(self, gzip=True, include_hidden=False, include_deleted=False,
wait=False, maxwait=None):
"""
Start a job to create an export archive for this history. See
:meth:`~bioblend.galaxy.histories.HistoryClient.export_history`
for parameter and return value info.... | """
Upload a string to a new dataset in this history.
:type content: str
:param content: content of the new dataset to upload
See :meth:`~bioblend.galaxy.tools.ToolClient.upload_file` for
the optional parameters (except file_name).
:rtype: :class:`~.HistoryData... |
list_server_gateway_status.py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__a... |
return ListServerGatewayStatusResult(
status=self.status)
def list_server_gateway_status(resource_group_name: Optional[str] = None,
server_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListServerG... | yield self |
channelpool.go | package tcppool
import (
"errors"
"fmt"
"sync"
"time"
)
type InitOptions struct {
//连接池中拥有的最小连接数
InitialCap int
//连接池中拥有的最大的连接数
MaxCap int
//生成连接的方法
Factory func() (interface{}, error)
//关闭链接的方法
Close func(interface{}) error
//链接最大空闲时间,超过该事件则将失效
IdleTimeout time.Duration
}
//channelPool 存放链接信息
type cha... | }
//Put 将连接放回pool中
func (c *channelPool) Put(conn interface{}) error {
if conn == nil {
return errors.New("connection is nil. rejecting")
}
c.mu.Lock()
defer c.mu.Unlock()
if c.conns == nil {
return c.Close(conn)
}
select {
case c.conns <- &idleConn{conn: conn, t: time.Now()}:
return nil
default:
/... | return conn, nil
}
} |
read_groups_from_bam.py | import argparse
import pysam
# parse the read group strings from a bam/sam header
# return array of read group strings
def | (bam_filename, use_libraries=False):
bam = pysam.AlignmentFile(bam_filename, "rb")
header = bam.header
results = {}
if 'RG' in header:
read_groups = header['RG']
if use_libraries:
field = 'LB'
else:
field = 'ID'
#print(read_groups)
for read_group in read_groups:
results[read_group[fiel... | read_groups_from_bam |
jqxdata.export.js | jQWidgets v5.3.2 (2017-Sep)
Copyright (c) 2011-2017 jQWidgets.
License: https://jqwidgets.com/license/
*/
(function(b){var a=(function(){var c={},u,q,j,l,g,h,o,p;function d(B,A,x,z,y,v,w){this.hierarchy=y;this.exportFormat=v;this.filename=w;B.beginFile(w);n(B);k(B);B.endFile(w);return B.getFile()}function n(z){var x=t... | /* | |
font.go | // Auto-generated - DO NOT EDIT!
package ubuntumonoregular
import (
"github.com/gmlewis/go-fonts/fonts"
)
// Available glyphs:
// !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùú... | eNrs/XmQXNd1Joi/LAAklNbvN9kZDAeaw+h4piARorgkVwDEdrEX9kQBtVcBr/YqACSysBZIAHwAQRIkATBJgCQku93P8gbbcqu8yZCslq4Iu4fjXqbco4ngjBUTaXU7Qh3T0a6ekDvQHnXMRCLPue9+N897KHCRBDL5D1gvM9+77y5n/c53snPyGf9+L/s/z85nfunupsHBe++auyWf86r/+c+qG/9Wzql7Pzv3SH7ujb/Cw9W/RukvPYyf6Xvnzx3P+x78t0PT/9T+LfXpe++ae4ie4t1Tu6p2wdUv1K4GPdWr+/jq/bWrYa+2xuD1... | = ` |
K-isimler.js | //--------------------------------------------------//--------------------------------------------------//--------------------------------------------------
const Discord = require('discord.js');
const moment = require('moment');
const chalk = require('chalk');
const db = require('quick.db')
const ayarlar = require('.... | const ok = client.emojis.cache.get(ayarlar.emojiler.discow_ok)
const msunucu = message.guild
const muye = message.member
const msahip = message.author
const mkanal = message.channel
const rgun = moment(new Date().toISOString()).format('DD')
const ray = moment(new Date().toISOString()).format('MM').replace("01", "Ocak"... | const discow = new Discord.MessageEmbed().setColor('BLACK').setFooter(`${botconfig.footer}`, message.author.avatarURL({ dynamic: true, size: 2048 })).setTimestamp()
const dikkat = client.emojis.cache.get(ayarlar.emojiler.discow_carpi)
const tik = client.emojis.cache.get(ayarlar.emojiler.discow_tik) |
create_seqlib_dialog.py | from __future__ import print_function
import Tkinter as tk
import ttk
import tkSimpleDialog
from collections import OrderedDict
from ..barcode import BarcodeSeqLib
from ..barcodevariant import BcvSeqLib
from ..barcodeid import BcidSeqLib
from ..basic import BasicSeqLib
from ..idonly import IdOnlySeqLib
from ..overlap i... |
def buttonbox(self):
"""
Display only one button.
"""
box = tk.Frame(self)
w = tk.Button(box, text="OK", width=10, command=self.ok, default="active")
w.pack(side="left", padx=5, pady=5)
self.bind("<Return>", self.ok)
box.pack()
def apply(self... | message = ttk.Label(master, text="SeqLib type:")
message.grid(column=0, row=0)
for i, k in enumerate(SEQLIB_LABEL_TEXT.keys()):
rb = ttk.Radiobutton(
master,
text=SEQLIB_LABEL_TEXT[k],
variable=self.element_tkstring,
va... |
clean_test_app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 18:54:48 2020
@author: dylanroyston
"""
# -*- coding: utf-8 -*-
# import packages
#import dash_player
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Out... | (selected_row):
curr_song_id = selected_row
specdata = conn.cursor()
qstring = 'SELECT * FROM clean_spec WHERE song_id=' + str(curr_song_id)
specdata.execute(qstring)
sd = np.array(specdata.fetchall())
spec_df = pd.DataFrame(data=sd)
#currtitle = tag_df.iloc[curr_song_id]... | load_spec_data |
CreateEmailIdentityPolicyCommand.ts | import { SESv2ClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from "../SESv2Client";
import { CreateEmailIdentityPolicyRequest, CreateEmailIdentityPolicyResponse } from "../models/models_0";
import {
deserializeAws_restJson1CreateEmailIdentityPolicyCommand,
serializeAws_restJson1CreateEmailIdentityPol... | extends $Command<
CreateEmailIdentityPolicyCommandInput,
CreateEmailIdentityPolicyCommandOutput,
SESv2ClientResolvedConfig
> {
// Start section: command_properties
// End section: command_properties
constructor(readonly input: CreateEmailIdentityPolicyCommandInput) {
// Start section: command_construc... | CreateEmailIdentityPolicyCommand |
DolfinPDESolver.py | """
DolfinPDESolver.py
==================
A python class structure written to interface CellModeller4 with the FEniCs/Dolfin finite element library.
Intended application: hybrid modelling of a microbial biofilm.
- Update: parameter input streamlined. New moving boundary mesh type.
- Update: added in-built test func... | (self, Point, cubeOrigin):
"""
Given mesh cube, assign which tetrahedron a point is in.
/!\ Assumes tetrahedron is part of a cube.
"""
Origin = cubeOrigin
p_x = Point[0]; p_y = Point[1]; p_z = Point[2]
a_x = Origin[0]; a_y = Origin[1]; a_z = Origin[2]
dx = p_x - a_x
dy = p_y - a_y
dz = p_z - a_z
t... | GetTetrahedronIndex |
payment.py | # -*- coding: utf-8 -*-
from trytond.pool import PoolMeta
from trytond.model import fields, ModelSQL, ModelView
from trytond.transaction import Transaction
__metaclass__ = PoolMeta
__all__ = ['MagentoPaymentGateway', 'Payment']
class MagentoPaymentGateway(ModelSQL, ModelView):
"""
This model maps the availab... |
@classmethod
def __setup__(cls):
"""
Setup the class before adding to pool
"""
super(MagentoPaymentGateway, cls).__setup__()
cls._sql_constraints += [
(
'name_channel_unique', 'unique(name, channel)',
'Payment gateway already e... | domain=[('source', '=', 'magento')]
) |
hello.ts | //created by Kevin - (https://github.com/Kyukishi)
//simple hello command
import{
Discord,
SimpleCommand,
SimpleCommandMessage,
}from 'discordx';
@Discord()
class | {
@SimpleCommand('hello', {aliases: ['hi']})
hello(command: SimpleCommandMessage){
command.message.reply(`👋 ${command.message.member}`);
}
} | helloCommand |
date.rs | //! This module defines the [DateFlag]. To set it up from [ArgMatches], a [Config] and its
//! [Default] value, use its [configure_from](Configurable::configure_from) method.
use super::Configurable;
use crate::app;
use crate::config_file::Config;
use crate::print_error;
use clap::ArgMatches;
/// The flag showing w... | () {
let mut c = Config::with_none();
c.date = Some("relative".into());
c.classic = Some(true);
assert_eq!(Some(DateFlag::Date), DateFlag::from_config(&c));
}
#[test]
#[serial_test::serial]
fn test_from_environment_none() {
std::env::set_var("TIME_STYLE", "");
... | test_from_config_classic_mode |
alleyoop_utrrates.py | """Run Alleyoop utrrates tool on Slamdunk results."""
import os
from plumbum import TEE
from resolwe.process import (
Cmd,
DataField,
FileField,
IntegerField,
Process,
StringField,
)
class AlleyoopUtrRates(Process):
"""Run Alleyoop utrrates."""
slug = "alleyoop-utr-rates"
proces... | ||
aggregator.go | /*
* Copyright 2020-2021, Offchain Labs, 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 ... | func (m *Server) BloomStatus() (uint64, uint64) {
return 0, 0
}
func (m *Server) ServiceFilter(_ context.Context, _ *bloombits.MatcherSession) {
// Currently not implemented
}
func (m *Server) SubscribeNewTxsEvent(ch chan<- ethcore.NewTxsEvent) event.Subscription {
return m.scope.Track(m.batch.SubscribeNewTxsEvent... | }
return logs, nil
}
|
secrets.go | // Package local implements Secrets plugin.
package local
import (
"errors"
"fmt"
"io/ioutil"
"reflect"
"strings"
"time"
"github.com/aws/aws-k8s-tester/eks/secrets"
eks_tester "github.com/aws/aws-k8s-tester/eks/tester"
"github.com/aws/aws-k8s-tester/eksconfig"
k8s_client "github.com/aws/aws-k8s-tester/pkg/k... |
type tester struct {
cfg Config
}
func (ts *tester) Create() (err error) {
if !ts.cfg.EKSConfig.IsEnabledAddOnSecretsLocal() {
ts.cfg.Logger.Info("skipping tester.Create", zap.String("tester", reflect.TypeOf(tester{}).PkgPath()))
return nil
}
if ts.cfg.EKSConfig.AddOnSecretsLocal.Created {
ts.cfg.Logger.In... | {
cfg.Logger.Info("creating tester", zap.String("tester", reflect.TypeOf(tester{}).PkgPath()))
return &tester{cfg: cfg}
} |
get_api_validation.py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | """
def __init__(__self__, api_id=None, id=None, validations=None):
if api_id and not isinstance(api_id, str):
raise TypeError("Expected argument 'api_id' to be a str")
pulumi.set(__self__, "api_id", api_id)
if id and not isinstance(id, str):
raise TypeError("Expe... | """
A collection of values returned by getApiValidation. |
redis_action_ch05.py | """
@author: magician
@file: redis_action_ch05.py
@date: 2021/11/22
"""
import bisect
import contextlib
import csv
import functools
import json
import logging
import random
import threading
import time
import unittest
import uuid
import redis
from datetime import datetime
QUIT = False
SAMPLE_COUNT = 100
config_... |
def test_log_recent(self):
import pprint
conn = self.conn
print("Let's write a few logs to the recent log")
for msg in range(5):
log_recent(conn, 'test', 'this is message %s' % msg)
recent = conn.lrange('recent:test:info', 0, -1)
print("The current rece... | self.conn.flushdb()
del self.conn
global config_connection, QUIT, SAMPLE_COUNT
config_connection = None
QUIT = False
SAMPLE_COUNT = 100
print()
print() |
venues.rs | //! Tools for grabbing venue data, both the basic data available from the API, as well as the svg files that will tell us where homeplate is.
//! The svg data is critical, since it will help us map the hit_data to actual coordinates on the field. It will also allow us to properly measure feet, since we'll hbe able to m... | pub(crate) capacity: Option<u32>,
pub(crate) turf_type: Option<SurfaceType>,
pub(crate) roof_type: Option<RoofType>,
pub(crate) left_line: Option<u16>,
pub(crate) left: Option<u16>,
pub(crate) left_center: Option<u16>,
pub(crate) center: Option<u16>,
pub(crate) right_center: Option<u16>,... | #[serde(rename_all="camelCase")]
#[derive(Deserialize, Debug, Clone)]
pub(crate) struct FieldInfo { |
agent_availability_message.rs | /*
* Watson Assistant v2
*
* The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. The Assistant v2 API provides runtime methods your client application can use to send user in... | {
/// The text of the message.
#[serde(rename = "message", skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
impl AgentAvailabilityMessage {
pub fn new() -> AgentAvailabilityMessage {
AgentAvailabilityMessage {
message: None,
}
}
}
| AgentAvailabilityMessage |
even-or-odd.rs | fn even_or_odd(i: i32) -> &'static str {
if i % 2 == 0 {
return "Even";
}
else {
return "Odd";
}
}
#[test]
fn returns_expected() {
assert_eq!(even_or_odd(0), "Even");
assert_eq!(even_or_odd(2), "Even");
assert_eq!(even_or_odd(1), "Odd"); | assert_eq!(even_or_odd(-1), "Odd");
} | assert_eq!(even_or_odd(7), "Odd"); |
config.rs | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub struct Config {
pub(crate) endpoint_resolver: ::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>,
pub(crate) region: Option<aws_types::region::Region>,
pub(crate) credentials_provider: aws_types::credentials::SharedCred... | (mut self, region: impl Into<Option<aws_types::region::Region>>) -> Self {
self.region = region.into();
self
}
/// Set the credentials provider for this service
pub fn credentials_provider(
mut self,
credentials_provider: impl aws_types::credentials::ProvideCredentials + 'sta... | region |
error.rs | //! Error types
use {
num_derive::FromPrimitive,
solana_program::{decode_error::DecodeError, program_error::ProgramError},
thiserror::Error,
};
/// Errors that may be returned by the program.
#[derive(Clone, Debug, Eq, Error, FromPrimitive, PartialEq)]
pub enum GatewayError {
/// Incorrect authority p... | () -> &'static str {
"Gateway Error"
}
}
| type_of |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.