file_name stringlengths 3 137 | prefix stringlengths 0 918k | suffix stringlengths 0 962k | middle stringlengths 0 812k |
|---|---|---|---|
main.rs | use std::io;
use serde::{Deserialize, Serialize};
extern crate mtga_resources_locator;
use mtga_resources_locator::assets_data_dir;
mod client;
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "camelCase")]
struct Card {
title_id: i32, | struct MagicCard {
title: String,
cmc: i32
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Localization {
iso_code: String,
keys: Vec<LocalizationKey>
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct LocalizationKey {
id: i32... | cmc: i32
}
#[derive(Debug)] |
wiser_website_settings.py | # -*- coding: utf-8 -*-
# Copyright (c) 2019, Systematic and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class WiserWebsiteSettings(Document):
def | (self):
from frappe.website.render import clear_cache
clear_cache("index")
| on_update |
0005_auto_20170824_1644.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-24 08:44
from __future__ import unicode_literals
from django.db import migrations
class | (migrations.Migration):
dependencies = [
('dashboard2', '0004_auto_20170310_1811'),
]
operations = [
migrations.DeleteModel(
name='Config',
),
migrations.DeleteModel(
name='Machine',
),
migrations.DeleteModel(
name='Tag',
... | Migration |
service_list_item_component.tsx | import React from 'react';
import { textStyles, colors } from '../../application/styles';
import { HumanServiceData, Address } from '../../validation/services/types';
import { View, Text } from 'native-base';
import { TouchableOpacity } from 'react-native';
import { mapWithIndex } from '../../application/helpers/map_wi... | {appendCommaIfNotEmpty(address.address)}{address.city} {address.stateProvince} {address.postalCode || ''}
</Text>
</View>, physicalAddresses)
);
const appendCommaIfNotEmpty = (address: string): string => {
if (address.trim() === '') {
return '';
}
return `${addre... | <Text style={textStyles.listItemDetail}> |
sku_type.go | /*
Copyright (c) 2019 Red Hat, 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, software... |
return len(l.items)
}
// Empty returns true if the list is empty.
func (l *SKUList) Empty() bool {
return l == nil || len(l.items) == 0
}
// Get returns the item of the list with the given index. If there is no item with
// that index it returns nil.
func (l *SKUList) Get(i int) *SKU {
if l == nil || i < 0 || i >... | {
return 0
} |
air_frieght_transport.py | class FreightPlane:
| def __init__(self):
pass | |
mod.rs | // Copyright (c) 2019 Stefan Lankes, RWTH Aachen University
// 2020 Frederik Schulz, RWTH Aachen University
//
// 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. ... | NET_SEM.release();
}
pub fn netwait_and_wakeup(handles: &[usize], millis: Option<u64>) {
// do we have to wakeup a thread?
if handles.len() > 0 {
let mut guard = NIC_QUEUE.lock();
for i in handles {
if let Some(task) = guard.remove(i) {
core_scheduler().custom_wakeup(task);
}
}
}
let mut reset_n... |
pub fn netwakeup() { |
check_webuiadv_09_element_waiters.py | # This file is a part of Arjuna
# Copyright 2015-2020 Rahul Verma
# Website: www.RahulVerma.net
# 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... | (request, logged_in_wordpress):
# Should be validated in root element.
print(logged_in_wordpress.element(id="adminmenu").contains(tag="div"))
print(logged_in_wordpress.element(id="adminmenu").contains(id="something"))
@test
def check_contains_nested_locator_max_wait(request, logged_in_wordpress):
b = ... | check_contains_nested |
eth_confirmer.go | package bulletprooftxmanager
import (
"context"
"encoding/json"
"fmt"
"math/big"
"sort"
"strings"
"sync"
"time"
"github.com/smartcontractkit/chainlink/core/logger"
"github.com/smartcontractkit/chainlink/core/null"
"github.com/smartcontractkit/chainlink/core/services/eth"
"github.com/smartcontractkit/chain... | b *gorm.DB, address gethCommon.Address) (etxs []models.EthTx, err error) {
err = db.
Preload("EthTxAttempts", func(db *gorm.DB) *gorm.DB {
return db.Order("eth_tx_attempts.gas_price DESC")
}).
Joins("INNER JOIN eth_tx_attempts ON eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_tx_attempts.state = 'insufficien... | ndEthTxsRequiringResubmissionDueToInsufficientEth(d |
layout.tsx | import React from 'react'
import { Layout as AntdLayout, Menu } from 'antd'
import { Link } from 'react-router-dom'
import { HomeOutlined } from '@ant-design/icons'
const { Header, Content } = AntdLayout
export const Layout: React.FC = (props: any) => {
return (
<AntdLayout style={{ minHeight: '100vh' }}>
... | </Content>
</AntdLayout>
</AntdLayout>
)
} | }}
>
{props?.children} |
errors.go | package flowcontext
import (
"errors"
"strings"
"sync/atomic"
"github.com/kaspanet/kaspad/infrastructure/network/netadapter/router"
"github.com/kaspanet/kaspad/app/protocol/protocolerrors"
)
var (
// ErrPingTimeout signifies that a ping operation timed out.
ErrPingTimeout = protocolerrors.New(false, "timeout... |
if atomic.AddUint32(isStopping, 1) == 1 {
errChan <- err
}
}
// IsRecoverableError returns whether the error is recoverable
func (*FlowContext) IsRecoverableError(err error) bool {
return err == nil || errors.Is(err, router.ErrRouteClosed) || errors.As(err, &protocolerrors.ProtocolError{})
}
| {
if protocolErr := (protocolerrors.ProtocolError{}); !errors.As(err, &protocolErr) {
panic(err)
}
if errors.Is(err, ErrPingTimeout) {
// Avoid printing the call stack on ping timeouts, since users get panicked and this case is not interesting
log.Errorf("error from %s: %s", flowNam... |
baz.rs | #![allow(dead_code)]
use metered::{metered, ErrorCount, HitCount, InFlight, ResponseTime};
use thiserror::Error;
#[metered::error_count(name = LibErrorCount, visibility = pub)]
#[derive(Debug, Error)]
pub enum LibError {
#[error("I failed!")]
Failure,
#[error("Bad input")]
BadInput,
}
#[metered::erro... | #[metered(registry = BazMetricRegistry, /* default = self.metrics */ registry_expr = self.metric_reg, visibility = pub(self))]
#[measure(InFlight)] // Applies to all methods that have the `measure` attribute
impl Baz {
// This is measured with an InFlight gauge, because it's the default on the block.
#[measure]... | pub struct Baz {
metric_reg: BazMetricRegistry,
}
|
config.py | import os
from dotenv import load_dotenv, find_dotenv
#this will load all the envars from a .env file located in the project root (api)
load_dotenv(find_dotenv())
CONFIGURATION = {
"development": "config.DevConfig",
"testing": "config.TestConfig",
"production": "config.Config",
"default": "config.Conf... | (object):
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
SECRET_KEY = 'a secret'
SQLALCHEMY_TRACK_MODIFICATIONS = False
NRO_SERVICE_ACCOUNT = os.getenv('NRO_SERVICE_ACCOUNT', 'nro_service_account')
SOLR_BASE_URL = os.getenv('SOLR_BASE_URL', None)
SOLR_SYNONYMS_API_URL = os.getenv(... | Config |
packet.rs | /* Copyright 2021 Perry Lorier
*
* 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 agree... | tail: Tail<'a>,
}
impl<'a> Fragment<'a> {
fn len(&self) -> usize {
self.buffer.len() + self.tail.len()
}
fn partial_netsum(&self, current: u32) -> u32 {
self.tail
.partial_netsum(partial_netsum(current, &self.buffer))
}
fn netsum(&self) -> u16 {
finish_netsum... | #[derive(Clone, Debug)]
pub struct Fragment<'a> {
buffer: Vec<u8>, |
kalloc.rs | // Physical memory allocator, intended to allocate
// memory for user processes, kernel stacks, page table pages,
// and pipe buffers. Allocates 4096-byte pages.
use core;
use super::*;
use spinlock_mutex::*;
struct | {
next: Option<&'static mut Run>,
}
static mut freelist: Mutex<Option<&'static mut Run>> = Mutex::new(None);
// Initialization happens in two phases.
// 1. main() calls kinit1() while still using entrypgdir to place just
// the pages mapped by entrypgdir on free list.
// 2. main() calls kinit2() with the rest of... | Run |
create_map.py | #!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo Authors. 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 ... | d = distance(last_c_x, last_c_y, pos_c_x, pos_c_y)
total_length += d
d_left = distance(last_l_x, last_l_y, pos_l_x, pos_l_y)
total_left_length += d_left
d_right = distance(last_r_x, last_r_y, pos_r_x, pos_r_y)
total_right_length += d_right
... | |
preprocessing_squad.py | #!/usr/bin/env python
# coding: utf-8
import argparse
import json
from tqdm.auto import tqdm
from transformers import AutoTokenizer
def | (tokenizer, file_input, file_output):
with open(file_input, "r") as f:
data = json.load(f)["data"]
new_data = {}
for p in tqdm([p for d in data for p in d["paragraphs"]]):
for qas in p["qas"]:
question = tokenizer.tokenize(qas["question"])
answer_offsets_ = set()
... | pre_processing |
av0.rs | #![allow(non_snake_case)]
use libperl_sys::*;
pub fn | (ary: *const libperl_sys::av) -> *const *const SV {
(unsafe {(*ary).sv_u.svu_array})
as *const *const SV
}
| AvARRAY |
date_formatter.js | import moment from 'moment';
const DateFormatter = {
format(date) {
return moment(date).format('YYYY-MM-DD');
},
};
| export default DateFormatter; | |
cpuv2_test.go | /*
Copyright The containerd 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... | {
checkCgroupMode(t)
group := "/cpu-test-cg"
groupPath := fmt.Sprintf("%s-%d", group, os.Getpid())
var (
quota int64 = 10000
period uint64 = 8000
weight uint64 = 100
)
max := "10000 8000"
res := Resources{
CPU: &CPU{
Weight: &weight,
Max: NewCPUMax("... | |
apitestlib.go | // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package api4
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermos... | _, err := me.App.Srv.Store.User().VerifyEmail(ruser.Id, ruser.Email)
if err != nil {
return nil
}
utils.EnableDebugLogForTest()
return ruser
}
func (me *TestHelper) CreatePublicChannel() *model.Channel {
return me.CreateChannelWithClient(me.Client, model.CHANNEL_OPEN)
}
func (me *TestHelper) CreatePrivateChan... |
ruser.Password = "Pa$$word11" |
searching.py | from .errors import MultipleResults, NoResults
def equals(field, value):
"""Return function where input ``field`` value is equal to ``value``"""
return lambda x: x.get(field) == value
def contains(field, value):
return lambda x: value in x.get(field)
def startswith(field, value):
return lambda x: ... |
def exclude(func):
"""Return the opposite of ``func`` (i.e. ``False`` instead of ``True``)"""
return lambda x: not func(x)
def doesnt_contain_any(field, values):
"""Exclude all dataset whose ``field`` contains any of ``values``"""
return lambda x: all(exclude(contains(field, value))(x) for value in ... | """Return ``True`` is any of the function evaluate true"""
return lambda x: any(f(x) for f in funcs) |
mod.rs | //! Azure HTTP headers.
mod utilities;
pub use utilities::*;
use http::request::Builder;
use std::collections::HashMap;
/// A trait for converting a type into request headers
pub trait AsHeaders {
type Iter: Iterator<Item = (HeaderName, HeaderValue)>;
fn as_headers(&self) -> Self::Iter;
}
impl<T> AsHeaders ... |
}
/// View a type as an HTTP header.
///
/// Ad interim there are two default functions: `add_to_builder` and `add_to_request`.
///
/// While not restricted by the type system, please add HTTP headers only. In particular, do not
/// interact with the body of the request.
///
/// As soon as the migration to the pipeli... | {
match self {
Some(h) => h.as_headers(),
None => None.into_iter(),
}
} |
lib.rs | #![no_std]
use core::panic::PanicInfo;
#[panic_handler]
fn | (_info: &PanicInfo) -> ! {
loop {}
}
extern "C" {
fn SBPublish(msg: *const u8, len: usize);
// fn SBGetInt64(name: *const u8, strlen: usize) -> (i64, i32);
fn SBSetInt64(name: *const u8, strlen: usize, value: i64);
}
#[no_mangle]
pub extern "C" fn entry_point1() -> i32 {
let message = "Value has b... | panic |
cmd.go | package main
import (
"bytes"
"fmt"
"html/template"
"os"
"path"
"strings"
"github.com/spf13/afero"
"pkg.glorieux.io/mantra"
)
var fs = afero.NewOsFs()
var templates = template.New("").Funcs(template.FuncMap{
"Title": func(s string) string {
return strings.Title(s)
},
})
func init() |
func createApplication(name string) error {
fmt.Printf("Creating application %s...\n", name)
if exists, _ := afero.DirExists(fs, name); exists {
return fmt.Errorf("Directory named %s already exists", name)
}
err := fs.MkdirAll(name, os.ModeDir|os.ModePerm)
if err != nil {
return fmt.Errorf("Error creating %... | {
template.Must(templates.New("go.mod").Parse(`module {{ .Name }}
require (
pkg.glorieux.io/mantra v{{ .MantraVersion }}
)
`))
template.Must(templates.New("main").Parse(`package main
import (
"github.com/sirupsen/logrus"
"pkg.glorieux.io/mantra"
)
func main() {
log := logrus.New()
mantra.New(l... |
index.ts | import { Command, flags, Flags } from 'prisma-cli-engine'
import chalk from 'chalk'
import { prettyTime } from '../../util'
export default class | extends Command {
static topic = 'delete'
static description = 'Delete an existing service'
static group = 'db'
static flags: Flags = {
force: flags.boolean({
char: 'f',
description: 'Force delete, without confirmation',
}),
['env-file']: flags.string({
description: 'Path to .env ... | Delete |
fake_firewall.go | /*
Copyright AppsCode Inc. and Contributors
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... | } | if obj == nil {
return nil, err
}
return obj.(*v1alpha1.Firewall), err |
0002_auto_20201117_0251.py | # Generated by Django 3.0.5 on 2020-11-17 02:51
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('webapi', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='products',
name='capacities',
field=models.CharField(default='custom', max_length=128, verbose_name='容量'),
),
migrations.AddField(
m... | |
mod.rs | use ff::{Field, PrimeField};
mod dummy_engine;
use self::dummy_engine::*;
use std::marker::PhantomData;
use std::ops::{AddAssign, MulAssign, SubAssign};
use crate::{Circuit, ConstraintSystem, SynthesisError};
use super::{create_proof, generate_parameters, prepare_verifying_key, verify_proof};
struct XorDemo<Scalar... | // public inputs: a_0 = 1, a_1 = c
// aux inputs: a_2 = a, a_3 = b
// constraints:
// (a_0 - a_2) * (a_2) = 0
// (a_0 - a_3) * (a_3) = 0
// (a_2 + a_2) * (a_3) = (a_2 + a_3 - a_1)
// (a_0) * 0 = 0
// (a_1) * 0 = 0
// The evaluation domain is 8. The H query should... |
// This will synthesize the constraint system:
// |
rocrate.py | #!/usr/bin/env python
# Copyright 2019-2020 The University of Manchester, UK
# Copyright 2020 Vlaams Instituut voor Biotechnologie (VIB), BE
# Copyright 2020 Barcelona Supercomputing Center (BSC), ES
# Copyright 2020 Center for Advanced Studies, Research and Development in Sardinia (CRS4), IT
#
# Licensed under the Ap... | def datePublished(self):
return self.root_dataset.datePublished
@datePublished.setter
def datePublished(self, value):
self.root_dataset.datePublished = value
@property
def creator(self):
return self.root_dataset['creator']
@creator.setter
def creator(self, value):
... | def name(self, value):
self.root_dataset['name'] = value
@property |
const-err.rs | // Copyright 2012 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 ... | <T>(_: T) {
unimplemented!()
}
// Make sure that the two uses get two errors.
const FOO: u8 = [5u8][1];
//~^ ERROR constant evaluation error
//~| ERROR constant evaluation error
//~| index out of bounds: the len is 1 but the index is 1
fn main() {
black_box((FOO, FOO));
}
| black_box |
hexfile.py | #!/usr/bin/env python3
"""
Hexdump Utility
===============
A command line hexdump utility.
See the module's `Github homepage <https://github.com/risapav/ihex_analyzer>`_
for details.
"""
# pouzite kniznice
import struct
import codecs
# definovanie konstant
ROWTYPE_DATA = 0x00 # Data container
ROWTYPE_EOF = 0x01 # E... |
# konverzia z textoveho stringu na cislo velkosti Word
# data - textovy retazec data 4 znaky
def wordCnv(self, data):
buffer = codecs.decode(data, "hex")
return struct.unpack(">H", buffer[0:2])[0]
# konverzia z textoveho stringu na cislo velkosti DWord
# data - textovy retazec dat... | buffer = codecs.decode(data, "hex")
return struct.unpack(">B", buffer[0:1])[0] |
overlay.go | // SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2021 Hajime Hoshi
package hitsumabushi
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
)
type Option func(*config)
type config struct {
testPkgs []string
n... |
var reGoVersion = regexp.MustCompile(`go(\d+\.\d+)(\.\d+)?`)
// GenOverlayJSON generates a JSON file for go-build's `-overlay` option.
// GenOverlayJSON returns a JSON file content, or an error if generating it fails.
//
// Now the generated JSON works only for Arm64 so far.
func GenOverlayJSON(options ...Option) ([... | {
_, currentPath, _, _ := runtime.Caller(1)
return filepath.Dir(currentPath)
} |
02_weekend_or_work_day.py | day = input()
if day == "Monday" or day == "Tuesday" or day == "Wednesday" or day == "Thursday" or day == "Friday":
print("Work day")
elif day == "Saturday" or day == "Sunday":
|
else:
print("Error")
| print("Weekend") |
error.rs | /************************************************************************************************/
use crate::text::s;
use crate::text::Text::*;
/************************************************************************************************/
#[derive(Debug)]
pub struct | {
messages: Vec<String>,
}
/************************************************************************************************/
impl YasgError {
/*------------------------------------------------------------------------------------------*/
pub fn new(message: String) -> YasgError {
YasgError {
... | YasgError |
compiled.rs | // Copyright 2013 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 ... |
#[cfg(test)]
mod tests {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn test_veclens() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
... | {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1... |
war_print_class.py | '''
Copyright 2017, Fujitsu Network Communications, 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 w... | """Class that has methods to redirect prints
from stdout to correct console log files """
def __init__(self, console_logfile):
"""Constructor"""
self.get_file(console_logfile)
# self.write_to_stdout = write_to_stdout
self.stdout = sys.stdout
def get_file(self, console_lo... | |
server.go | package rest
import (
"net/http"
"time"
"log"
"fmt"
"github.com/gorilla/handlers"
)
const default_port = "8080"
var startTime time.Time
func StartServer() {
startTime = time.Now().UTC()
// Get Cloud Foundry assigned port
port := default_port
if port == "" {
port = default_port
log.Println(fmt.Sprintf... |
}
| {
log.Fatal(err.Error())
} |
filters.py | """
This file is licensed under the terms of the Apache License, Version 2.0. See the LICENSE file in the root of this
repository for complete details.
"""
# -----------------------------------------------------------------------
# FILTER MANIFEST
# -------------------------------------------... | return changes | |
uploadRoutes.ts | import path from 'path';
import express from 'express';
import multer from 'multer';
const router = express.Router();
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads/');
},
filename(req, file, cb) {
cb(null, `${file.fieldname}-${Date.now()}${path.extname(... |
if (extname && mimetype) {
return cb(null, true);
} else {
cb(Error('Images only!'));
}
}
const upload = multer({
storage,
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
},
});
router.post('/', upload.single('image'), (req, res) => {
res.send(`/${r... | function checkFileType(file: Express.Multer.File, cb: multer.FileFilterCallback) {
const filetypes = /jpg|jpeg|png/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype); |
Interval.py | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: flatbuf
import flatbuffers
class Interval(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsInterval(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Interval... | (builder): builder.StartObject(1)
def IntervalAddUnit(builder, unit): builder.PrependInt16Slot(0, unit, 0)
def IntervalEnd(builder): return builder.EndObject()
| IntervalStart |
handler.rs | use discord::{ChannelRef, State, Connection};
use discord::model::{Event};
use ansi_term::Colour;
pub fn | (connection: &mut Connection, state: &mut State) {
loop {
let event = match connection.recv_event() {
Ok(event) => event,
Err(error) => {
println!("{} Receive error: {:?}.", Colour::Red.paint("error"), error);
continue
}
};
state.update(&event);
match event {
... | handle_events |
mean_elliptical_slice.py | import torch
from .elliptical_slice import EllipticalSliceSampler
class MeanEllipticalSliceSampler(EllipticalSliceSampler):
def __init__(self, f_init, dist, lnpdf, nsamples, pdf_params=()):
|
def run(self):
self.f_sampled, self.ell = super().run()
#add means back into f_sampled
self.f_sampled = self.f_sampled + self.mean_vector.unsqueeze(1)
return self.f_sampled, self.ell | """
Implementation of elliptical slice sampling (Murray, Adams, & Mckay, 2010).
f_init: initial value of `f`
dist: multivariate normal to sample from to sample from
lnpdf: likelihood function
n_samples: number of samples
pdf_params: callable arguments for lnpdf
... |
catala_en.py | from pygments.lexer import RegexLexer, bygroups
from pygments.token import *
import re
__all__ = ['CatalaEnLexer']
class | (RegexLexer):
name = 'CatalaEn'
aliases = ['catala_en']
filenames = ['*.catala_en']
flags = re.MULTILINE | re.UNICODE
tokens = {
'root': [
(u'(@@)', bygroups(Generic.Heading), 'main__1'),
(u'(@)', bygroups(Generic.Heading), 'main__2'),
(u'([^\\/\\n\\r])',... | CatalaEnLexer |
src.rs | #![allow(non_snake_case, non_upper_case_globals)]
#![allow(non_camel_case_types)]
//! SRC
//!
//! Used by: imxrt1061, imxrt1062, imxrt1064
#[cfg(not(feature = "nosync"))]
pub use crate::imxrt106::peripherals::src::Instance;
pub use crate::imxrt106::peripherals::src::{RegisterBlock, ResetValues};
pub use crate::imxrt10... | GPR9: 0x00000000,
GPR10: 0x00000000,
};
#[cfg(not(feature = "nosync"))]
#[allow(renamed_and_removed_lints)]
#[allow(private_no_mangle_statics)]
#[no_mangle]
static SRC_TAKEN: AtomicBool = AtomicBool::new(false);
/// Safe access to SRC
///
/// This function returns `... | GPR5: 0x00000000,
GPR6: 0x00000000,
GPR7: 0x00000000,
GPR8: 0x00000000, |
recovery_cursor.py | # Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
from vdk.internal.builtin_plugins.connection.decoration_cursor import DecorationCursor
from vdk.internal.builtin_plugins.connection.decoration_cursor import ManagedOperation
from vdk.internal.builtin_plugins.connection.pep249.interfaces import PEP249Cu... |
def get_exception(self) -> Exception:
"""
Retrieve the original exception with which the SQL operation failed.
:return: Exception
"""
return self.__exception
def get_managed_operation(self) -> ManagedOperation:
"""
Retrieve an object that contains info... | super().__init__(native_cursor, log)
self.__exception = exception
self.__managed_operation = managed_operation
self.__decoration_operation_callback = decoration_operation_callback
self.__retries = 0 |
module_load.go | package modder
import (
"fmt"
"os"
"github.com/hofstadter-io/mvs/lib/parse/mappingfile"
"github.com/hofstadter-io/mvs/lib/parse/modfile"
"github.com/hofstadter-io/mvs/lib/parse/sumfile"
"github.com/hofstadter-io/mvs/lib/util"
)
func (m *Module) LoadModFile(fn string, ignoreReplace bool) error {
modBytes, err... |
// Pull in require info if not in replace
if req, ok := m.SelfDeps[rep.OldPath]; ok {
if rep.OldVersion == "" {
rep.OldVersion = req.NewVersion
}
}
m.SelfDeps[rep.OldPath] = rep
}
}
return nil
}
func (m *Module) LoadSumFile(fn string) error {
sumBytes, err := util.BillyReadAll(fn, m.FS... | return fmt.Errorf("Dependency %q replaced twice in %q", rep.OldPath, m.Module)
}
dblReplace[rep.OldPath] = rep |
pull.rs | use crate::helper::get_image_manager_instance;
use crate::{Handler, Result};
use async_trait::async_trait;
use clap::Args;
use log::LevelFilter;
/// Arguments for our `PullCommand`.
///
/// These arguments are parsed by `clap` and an instance of `PullCommand` containing
/// arguments is provided.
///
/// Example :
///... | {
/// The image to pull.
/// Example : registry.hub.docker.com/library/busybox
image: String,
/// By default, the image id will be generated by creating a unique hash for the image digest.
/// By using --name, you can provide a friendly identifier your image.
#[clap(long)]
name: Option<Stri... | PullCommand |
decoder.go | package simulation
import (
"bytes"
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/desmos-labs/desmos/x/profiles/types"
)
// NewDecodeStore returns a new decoder that unmarshals the KVPair's Value
// to the corresponding... | }
} | default:
panic(fmt.Sprintf("unexpected %s key %X (%s)", types.ModuleName, kvA.Key, kvA.Key))
} |
versions.ts | import { OpenshiftVersionOptionType, OpenshiftVersion } from '../../../common';
import { ClusterImageSetK8sResource } from '../../types/k8s/cluster-image-set'; | const match = /.+:(.*)-/gm.exec(releaseImage);
if (match && match[1]) {
return match[1];
}
return '';
};
// eslint-disable-next-line
const getSupportLevelFromChannel = (channel?: string): OpenshiftVersion['supportLevel'] => {
if (!channel) {
return 'custom';
}
if (channel.startsWith('fast')) {
... |
const getVersion = (releaseImage = '') => { |
lib.rs | //! Very minimal sqlite wrapper package built specifically for lod package manager and Unix systems. If you need complete box of sqlite database, consider using [rusqlite](https://github.com/rusqlite/rusqlite).
//!
//! ## Adding lib to the project
//! In your Cargo.toml:
//!
//! ```toml
//! [dependencies]
//! min-sqlit... | //! "{} did not successfully executed. The error status is: {:?}.",
//! sql_statement, status
//! );
//! }
//!
//! #[derive(Debug)]
//! struct Item {
//! id: i64,
//! name: String,
//! tag: String,
//! }
//!
//! fn main() {
//! let db = Database::open(Path::new("example.db")).unwrap(... | //! fn callback_function(status: SqlitePrimaryResult, sql_statement: String) {
//! println!( |
char.rs | // Copyright 2012-2014 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-MI... | /// let c = '7';
/// assert!(c.is_alphanumeric());
///
/// let c = '৬';
/// assert!(c.is_alphanumeric());
///
/// let c = 'K';
/// assert!(c.is_alphanumeric());
///
/// let c = 'و';
/// assert!(c.is_alphanumeric());
///
/// let c = '藏';
/// assert!(c.is_alphanumer... | /// |
findContentChildren.go | package main
import (
"fmt"
"sort"
)
/**
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj... |
func findContentChildren(g []int, s []int) int {
sort.Ints(g)
sort.Ints(s)
gi, si := 0, 0
for gi < len(g) && si < len(s) {
if g[gi] <= s[si] {
gi++
}
si++
}
return gi
}
func main() {
fmt.Println(findContentChildren([]int{10, 9, 8, 7}, []int{5, 6, 7}))
}
| {
for i := 0; i < len(arr)-1; i++ {
for j := i + 1; j < len(arr); j++ {
if arr[i] > arr[j] {
arr[i], arr[j] = arr[j], arr[i]
}
}
}
} |
group.go | // *** 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! ***
package resourcegroups
import (
"context"
"reflect"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v2/go/pulumi"
)
// Provides a Resou... | (ctx *pulumi.Context,
name string, args *GroupArgs, opts ...pulumi.ResourceOption) (*Group, error) {
if args == nil {
return nil, errors.New("missing one or more required arguments")
}
if args.ResourceQuery == nil {
return nil, errors.New("invalid value for required argument 'ResourceQuery'")
}
var resource ... | NewGroup |
oauth.go | // Copyright (c) Microsoft and contributors. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package iam
import (
"errors"
"log"
"net/http"
"net/url"
"os"
"github.com/Azure-Samples/azure-sdk-for-go-samples/he... |
// GetResourceManagementToken gets an OAuth token for managing resources using the specified grant type.
func GetResourceManagementToken(grantType OAuthGrantType) (adal.OAuthTokenProvider, error) {
if armToken != nil {
return armToken, nil
}
token, err := getToken(grantType, azure.PublicCloud.ResourceManagerEnd... | {
if helpers.DeviceFlow() {
return OAuthGrantTypeDeviceFlow
}
return OAuthGrantTypeServicePrincipal
} |
common.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can r... | },
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
}
},
"loggers": {
"django": {
"handlers":["null"],
"propagate": True,
"level":"INFO",
... | "console":{
"level":"DEBUG",
"class":"logging.StreamHandler",
"formatter": "simple", |
peer_test.go | // Copyright 2015 CoreOS, 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... | {
memb1 := etcdserver.Member{ID: 1, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8080"}}}
memb2 := etcdserver.Member{ID: 2, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8081"}}}
cluster := &fakeCluster{
id: 1,
mem... | |
package.py | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
# | # SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class PyNeurolab(PythonPackage):
"""Simple and powerfull neural network library for python"""
homepage = "http://neurolab.googlecode.com/"
pypi = "neurolab/neurolab-0.3.5.tar.gz"
version('0.3.5', sha256='96ec311988383c63... | |
resources.rs | #[derive(Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Resources {
pub cpus: u32,
}
impl Resources {
#[inline]
pub fn cpus(&self) -> u32 {
self.cpus
}
pub fn add(&mut self, resources: &Resources) {
self.cpus += resources.cpus;
}
pub fn remove(&m... | (reader: &::common_capnp::resources::Reader) -> Self {
Resources {
cpus: reader.get_n_cpus(),
}
}
pub fn to_capnp(&self, builder: &mut ::common_capnp::resources::Builder) {
builder.set_n_cpus(self.cpus);
}
#[inline]
pub fn is_subset_of(&self, resources: &Resourc... | from_capnp |
component_events.py | """
The events around component lifecycle creation.
"""
from typing import Generic
from ..internal_.identity_types import (
ParticipantId, ComponentId,
)
from ..internal_.bus_types import (
EventBus, EventId, EventCallback,
ListenerSetup,
)
from ..util.memory import T
from ..util.messages import UserMessag... | __slots__ = ('__request_id', '__category', '__error_msg',)
def __init__(
self, category: str, request_id: int,
error_msg: UserMessage
):
self.__request_id = request_id
self.__category = category
self.__error_msg = error_msg
@property
def request_id(s... | |
model_saver.py | import os
import torch
import torch.nn as nn
from collections import deque
from onmt.utils.logging import logger
from copy import deepcopy
def build_model_saver(model_opt, opt, model, fields, optim):
model_saver = ModelSaver(opt.save_model,
model,
model_... |
def _rm_checkpoint(self, name):
os.remove(name)
| real_model = (model.module
if isinstance(model, nn.DataParallel)
else model)
real_generator = (real_model.generator.module
if isinstance(real_model.generator, nn.DataParallel)
else real_model.generator)
... |
test_calculate.py | # CODING-STYLE CHECKS:
# pycodestyle test_calculate.py
import os
import json
from io import StringIO
import tempfile
import copy
import six
import pytest
import numpy as np
import pandas as pd
from taxcalc import Policy, Records, Calculator, Behavior, Consumption
RAWINPUTFILE_FUNITS = 4
RAWINPUTFILE_YEAR = 2015
RAWI... | (cps_subsample):
pol = Policy()
rec = Records.cps_constructor(data=cps_subsample, no_benefits=True)
calc1 = Calculator(policy=pol, records=rec)
calc2 = copy.deepcopy(calc1)
assert isinstance(calc2, Calculator)
def test_make_calculator_with_policy_reform(cps_subsample):
rec = Records.cps_constr... | test_make_calculator_deepcopy |
version_test.rs | // Copyright 2020-2021 The Datafuse Authors.
//
// SPDX-License-Identifier: Apache-2.0.
#[test]
fn test_version_function() -> anyhow::Result<()> {
use std::sync::Arc;
use common_datavalues::*;
use pretty_assertions::assert_eq;
use crate::udfs::*;
use crate::*;
#[allow(dead_code)]
struct | {
name: &'static str,
display: &'static str,
nullable: bool,
columns: Vec<DataColumnarValue>,
expect: DataArrayRef,
error: &'static str,
func: Box<dyn Function>,
}
let tests = vec![Test {
name: "version-function-passed",
display: "version... | Test |
randomData.py | #!/usr/bin/env https://github.com/Tandelajr/mr.tandela
# MIT License
#
# Copyright (C) 2020, Entynetproject. All Rights Reserved.
#
# 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 re... | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import json
import random
# Get random IP
def random_IP():
ip = []
for _ in range(0, 4):
ip.append(str(random.randint(1,255)))
... | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
HogDetector.py | import dlib
class HogDetector:
def __init__(self):
self.detector = dlib.get_frontal_face_detector()
def | (self, frame):
bboxes = []
# landmarks = []
dets = self.detector(frame, 1)
for k, d in enumerate(dets):
bboxes.append(
(d.left(), d.top(), d.right() - d.left(), d.bottom() - d.top())
)
# shape = self.predictor(frame, d)
# la... | detect |
threedtileloader.js | import * as vec2 from "./glmatrix/vec2.js";
import Cartesian3 from "../viewer/cesium/Core/Cartesian3.js";
import Transforms from "../viewer/cesium/Core/Transforms.js";
const b3dm = 0x6D643362;
const gltf = 0x46546c67;
export class | {
constructor(params) {
this.url = params.url;
this.refLatitude = params.refLatitude;
this.refLongitude = params.refLongitude;
this.callback = params.callback;
let cesiumMatrix = Transforms.eastNorthUpToFixedFrame(
Cartesian3.fromDegrees(this.refLongitude, this.refLatitu... | ThreeDTileLoader |
ode.py | r"""
This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper
functions that it uses.
:py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations.
See the docstring on the various functions for their uses. Note that partial
differential equations support is in ``pde.py``. Note t... |
def _nth_linear_match(eq, func, order):
r"""
Matches a differential equation to the linear form:
.. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0
Returns a dict of order:coeff terms, where order is the order of the
derivative on each term, and coeff is the coefficient of that ... | r"""
True if soln1 is found to be a special case of soln2 wrt some value of the
constants that appear in soln2. False otherwise.
"""
# The solutions returned by nth_algebraic should be given explicitly as in
# Eq(f(x), expr). We will equate the RHSs of the two solutions giving an
# equation ... |
nodebug.go | // Copyright (c) 2018 Timo Savola. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !((debug || indebug) && cgo)
// +build !debug,!indebug !cgo
package in
var (
debugPrinted bool
)
| debugPrinted = true
}
} | func debugPrintInsn([]byte) {
if !debugPrinted {
println("wag/internal/isa/amd64/in: debugPrintIn called in non-debug build") |
protection_container.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, overload
from ... import _utilities
fro... | (__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(ProtectionContainerArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
... | __init__ |
smart_pointer_multi_typedef_runme.go | package main
import . "./smart_pointer_multi_typedef"
func main() {
f := NewFoo()
b := NewBar(f)
s := NewSpam(b)
g := NewGrok(b)
s.SetX(3)
if s.Getx() != 3 {
panic(0)
}
g.SetX(4)
if g.Getx() != 4 {
panic(0)
} | } | |
pagerank.go | package pagerank
/*
Vector Vector
*/
type Vector map[string]float64
/*
Matrix Matrix
*/
type Matrix map[string]Vector
/*
Get Get
*/
func (matrix Matrix) Get(src string, dst string) float64 {
_, ok := matrix[src]
if !ok {
return 0
}
return matrix[src][dst]
}
/*
Set Set
*/
func (matrix Matrix) Set(src string, ... |
if currentScoreVector == nil {
currentScoreVector = Vector{}
}
if len(currentScoreVector) == 0 {
s := float64(1) / float64(len(stochasticMatrix))
for src := range stochasticMatrix {
currentScoreVector[src] = s
}
}
score := Vector{}
for src := range stochasticMatrix {
for dst := range stochasticMatr... | {
return Vector{}
} |
token_search.rs | use token_search::{Token, TokenSearchConfig, TokenSearchResults};
fn main() | {
match Token::all() {
Ok((_, outcome)) => {
let mut config = TokenSearchConfig::default();
config.tokens = outcome;
let results = TokenSearchResults::generate_with_config(&config);
println!("{}", serde_json::to_string(&results).unwrap());
}... | |
b.js |
r(function(){
function sph2cart(azimuth, elevation, r) {
r *= ((1/696000) * (6.955e5/149598000)); // Convert from km to AU
return [r*Math.cos(elevation)*Math.cos(azimuth),r*Math.cos(elevation)*Math.sin(azimuth),r*Math.sin(elevation)];
}
// Set graph
var width = 800,
height = 700,
padding = ... | (f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()} | r |
network.rs | // Copyright 2018 Parity Technologies (UK) Ltd.
//
// 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
// the rights to use, copy, modify, mer... | (&mut self, n: usize) -> &mut Self {
self.pool_limits.max_outgoing_per_peer = Some(n);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Dummy;
impl Executor for Dummy {
fn exec(&self, _: Pin<Box<dyn Future<Output=()> + Send>>) { }
}
#[test]
fn set_executor()... | set_outgoing_per_peer_limit |
remotewriter.go | // Diode Network Client
// Copyright 2019 IoT Blockchain Technology Corporation LLC (IBTC)
// Licensed under the Diode License, Version 1.0
package rpc
// remoteWriter Writes data to the remote end of a ConnectedPort
type remoteWriter struct {
port *ConnectedPort
}
// Write binary data to the connectionn
func (c *re... | }
return
} | if err == nil {
n = len(data) |
azuremachine_types.go | /*
Copyright 2019 The Kubernetes 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, ... | () {
SchemeBuilder.Register(&AzureMachine{}, &AzureMachineList{})
}
| init |
channel_test.go | package state
import (
"testing"
)
func TestNewChannel(t *testing.T) {
ch := NewChannel("#test1")
if ch.Name != "#test1" {
t.Errorf("Channel not created correctly by NewChannel()")
}
if len(ch.nicks) != 0 || len(ch.lookup) != 0 {
t.Errorf("Channel maps contain data after NewChannel()")
}
}
func TestAddNic... | (t *testing.T) {
ch := NewChannel("#test1")
nk := NewNick("test1")
cp := new(ChanPrivs)
ch.addNick(nk, cp)
ch.delNick(nk)
if len(ch.nicks) != 0 || len(ch.lookup) != 0 {
t.Errorf("Nick lists not updated correctly for del.")
}
if c, ok := ch.nicks[nk]; ok || c != nil {
t.Errorf("Nick test1 not properly remov... | TestDelNick |
10-es2015.8151dded4819fe86b6ee.js | (window.webpackJsonp=window.webpackJsonp||[]).push([[10],{eyxc:function(n,e,t){"use strict";t.r(e),t.d(e,"DistinctuntilchangedModule",(function(){return v}));var i=t("iInd");class c{constructor(){this.fruits=["banana","apple","apple","banana","banana"],this.expectedFruits=["banana","apple","banana"],this.code='const fr... | ||
board.py | from enum import IntEnum
class RentIdx(IntEnum):
DEFAULT = ONLY_DEED = RAILROAD_1 = UTILITY_1 = 0
GROUP_COMPLETE_NO_HOUSES = RAILROAD_2 = UTILITY_2 = 1
HOUSE_1 = RAILROAD_3 = 2
HOUSE_2 = RAILROAD_4 = 3
HOUSE_3 = 4
HOUSE_4 = 5
HOTEL = MAX = 6
HOUSE_TO_HOTEL = HOTEL - HOUSE_1 + 1
# Rep... | def __init__(self, csv_row):
if len(csv_row) != 19:
raise ValueError("Invalid CSV used to create board position")
self.owner = None
self.is_mortgaged = False
self.position = int(csv_row[0])
self.name = csv_row[1].strip()
self.property_group = int(csv_row[2... | |
generic_test.go | package validation
import (
"strings"
"testing"
"gobackend/pkg/validation/field"
)
func TestIsDNS1123Label(t *testing.T) {
goodValues := []string{
"a", "ab", "abc", "a1", "a-1", "a--1--2--b",
"0", "01", "012", "1a", "1-a", "1--a--b--2",
strings.Repeat("a", 63),
}
for _, val := range goodValues {
if msg... | badValues := []struct {
value int
min int
max int
}{{1, 2, 10}, {5, -4, 2}, {25, 100, 120}}
for _, val := range badValues {
if msgs := IsInRange(val.value, val.min, val.max); len(msgs) == 0 {
t.Errorf("expected errors for %#v", val)
}
}
}
func TestIsQualifiedName(t *testing.T) {
successCases := [... | |
specialPermutations.ts | /** Get permutations where no number can be in original position */
/** https://www.geeksforgeeks.org/count-derangements-permutation-such-that-no-element-appears-in-its-original-position/ */
export function specialPermutations (xs: number[]): number {
if (xs.length <= 1) {
console.log("xs: ", xs)
re... | } | |
model_pci_device_all_of.go | /*
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways ... |
return err
}
type NullablePciDeviceAllOf struct {
value *PciDeviceAllOf
isSet bool
}
func (v NullablePciDeviceAllOf) Get() *PciDeviceAllOf {
return v.value
}
func (v *NullablePciDeviceAllOf) Set(val *PciDeviceAllOf) {
v.value = val
v.isSet = true
}
func (v NullablePciDeviceAllOf) IsSet() bool {
return v.isS... | } |
static.go | package web
import (
"bytes"
"compress/gzip"
"encoding/base64"
"io/ioutil"
"net/http"
"os"
"path"
"sync"
"time"
)
type _escLocalFS struct{}
var _escLocal _escLocalFS
type _escStaticFS struct{}
var _escStatic _escStaticFS
type _escDir struct {
fs http.FileSystem
name string
}
type _escFile struct {
... | F+psbblgEjNU8UdgpPjvaiP8dzaFI8wGqQG6+yY4F/tBwFdmOcQ2GSKNAEyfH1m1NqHzOhOEVNtjCBCZ
4RsSJ7Vnj3aOe0Ok6i2XePd5p0AC3wMrSLJzaFOzArXbhoBoR5wewEsljuOzbPz+TVnnOA4LRavZGOSK
95FWfwOB5zl2+mNZzi0Qim0RCNis+X9lBsamYpmT18VbKut54ykXZ7ClgEHDRk+sTmHKxykcgwksXFJk
46yu0+qSCBFqQxk0uDjLqsyGiGUg51TJWQ4HRJWdAFZnsC8X8ElMTV6cJouSKgr+IREASjrNhv4iO... | |
multi_variables_v1.py | # Copyright 2019 The TensorFlow Authors. 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 applica... |
if __name__ == '__main__':
common_v1.do_test(Test())
| tf.compat.v1.enable_resource_variables()
tf.compat.v1.disable_eager_execution()
x = tf.constant([[1.0], [1.0], [1.0]])
y = tf.compat.v1.get_variable(
name='y',
shape=(1, 3),
initializer=tf.random_normal_initializer(),
trainable=True)
z = tf.compat.v1.get_variable(
name='z',
... |
__version__.py | # -*- coding: utf-8 -*-
"""Package info."""
__version__ = '0.1.0'
__title__ = 'jacoren'
__description__ = ''
__author__ = 'Piotr Kuszaj' | __all__ = ('platform', 'cpu', 'memory', 'disks') | __author_email__ = 'peterkuszaj@gmail.com'
__license__ = 'MIT' |
google.datastore.v1beta3.rs | /// A partition ID identifies a grouping of entities. The grouping is always
/// by project and namespace, however the namespace ID may be empty.
///
/// A partition ID contains several dimensions:
/// project ID and namespace ID.
///
/// Partition dimensions:
///
/// - May be `""`.
/// - Must be valid UTF-8 bytes.
///... | pub fn accept_gzip(mut self) -> Self {
self.inner = self.inner.accept_gzip();
self
}
#[doc = " Looks up entities by key."]
pub async fn lookup(
&mut self,
request: impl tonic::IntoRequest<super::LookupRequest>,
) -> Result<tonic::Re... | self
}
#[doc = r" Enable decompressing responses with `gzip`."] |
prefix.directive.ts | import { NgModule, Directive } from '@angular/core';
/**
* @hidden
*/
@Directive({
selector: 'igx-prefix,[igxPrefix]'
})
export class IgxPrefixDirective { }
/**
* @hidden
*/
@NgModule({
declarations: [IgxPrefixDirective],
exports: [IgxPrefixDirective]
})
export class | { }
| IgxPrefixModule |
latency.rs | use clack_common::extensions::*;
use clack_host::wrapper::HostWrapper;
use clap_sys::ext::latency::{clap_host_latency, clap_plugin_latency, CLAP_EXT_LATENCY};
#[repr(C)]
pub struct PluginLatency {
inner: clap_plugin_latency,
}
unsafe impl Extension for PluginLatency {
const IDENTIFIER: &'static [u8] = CLAP_EX... | fn get(&mut self) -> u32;
}
impl<'a, P: Plugin<'a>> ExtensionImplementation<P> for PluginLatency
where
P::MainThread: PluginLatencyImpl,
{
const IMPLEMENTATION: &'static Self = &PluginLatency {
inner: clap_plugin_latency {
get: Some(get::<P>),
... | |
satochip.ts | import { Transaction as EthTx, TxData } from 'ethereumjs-tx';
import { addHexPrefix, toBuffer, hashPersonalMessage } from 'ethereumjs-util';
import mapValues from 'lodash/mapValues';
import { translateRaw } from '@translations';
import { getTransactionFields } from '@services/EthService';
import { stripHexPrefixAndLow... | extends HardwareWallet {
public static isConnected: boolean;
public static resolveMap: Map<number, any>;
public static requestID: number;
public static ws: WebSocket;
public static reconnectInterval: number;
public static connect: any;
//why static?
public static getChainCode(dpath: string): Promise<C... | SatochipWallet |
__init__.py | from .visitor import TypeAnnotationVisitor
from .nodes import *
from .aliasreplacement import AliasReplacementVisitor
from .erasure import EraseOnceTypeRemoval
from .inheritancerewrite import DirectInheritanceRewriting
| from .pruneannotations import PruneAnnotationVisitor
from .rewriterulevisitor import RewriteRuleVisitor | |
yolo3.py | #! python
# ===============LICENSE_START=======================================================
# metadata-flatten-extractor Apache-2.0
# ===================================================================================
# Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
# =====================... | :returns: (DataFrame): DataFrame on successful decoding and export, None (or exception) otherwise
"""
list_items = []
dict_data = self.get_extractor_results(self.EXTRACTOR, "data.json")
for local_obj in dict_data: # traverse items
if "results" in local_obj or "mill... | - https://pjreddie.com/darknet/yolo/
:param: run_options (dict): specific runtime information |
frame-common.d.ts | import type { BackstackEntry, NavigationContext, NavigationEntry, NavigationTransition } from './frame-interfaces';
import { NavigationType } from './frame-interfaces';
import { Page } from '../page';
import { View, CustomLayoutView } from '../core/view';
import { Property } from '../core/properties';
export { Navigati... | extends CustomLayoutView {
static androidOptionSelectedEvent: string;
private _animated;
private _transition;
private _backStack;
private _navigationQueue;
actionBarVisibility: 'auto' | 'never' | 'always';
_currentEntry: BackstackEntry;
_animationInProgress: boolean;
_executingConte... | FrameBase |
base.py | import socket
from http import HTTPStatus
from urllib.request import Request, urlopen, ProxyHandler, build_opener
from urllib.parse import urlencode, unquote_plus, quote, quote_plus
from urllib.error import HTTPError, URLError
class ClientBase:
def __init__(self, nacos_host: str, api_level: str = 'v1'):
s... |
try:
url += '?' + _get_params_str()
req = Request(self.base_url + url, headers=headers, data=urlencode(data).encode(), method=method)
resp = urlopen(req)
response = resp.read()
resp.close()
return response
except HTTPError as e:
... | params_list = []
for key in params.keys():
value = params.get(key, None)
if value is not None:
if not isinstance(value, str):
value = str(value)
params_list.append(f'{key}={quote_plus(value)}')
... |
openstack_network_network_service.go | package network
import (
boshlog "github.com/cloudfoundry/bosh-utils/logger"
"github.com/rackspace/gophercloud"
)
const openstackNetworkNetworkServiceLogTag = "OpenStackNetworkNetworkService"
type OpenStackNetworkNetworkService struct {
networkService *gophercloud.ServiceClient
logger boshlog.Logger
}
... | {
return OpenStackNetworkNetworkService{
networkService: networkService,
logger: logger,
}
} | |
test-utils_test.go | /*
* MinIO Cloud Storage, (C) 2015, 2016, 2017, 2018 MinIO, 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 require... | return nil
}
// Sign given request using Signature V2.
func signRequestV2(req *http.Request, accessKey, secretKey string) error {
s3signer.SignV2(*req, accessKey, secretKey, false)
return nil
}
// Sign given request using Signature V4.
func signRequestV4(req *http.Request, accessKey, secretKey string) error {
// ... | // Save signature finally.
req.URL.RawQuery += "&Signature=" + url.QueryEscape(signature) |
count_calls.py | #! /usr/bin/env udb-automate
import sys
import textwrap
from undodb.udb_launcher import (
REDIRECTION_COLLECT,
UdbLauncher,
)
def main(argv):
# Get the arguments from the command line.
try:
recording, func_name = argv[1:]
except ValueError:
# Wrong number of arguments.
pr... | ).format(res=res),
file=sys.stderr,
)
# Exit this script with the same error code as UDB.
raise SystemExit(res.exit_code)
if __name__ == "__main__":
main(sys.argv) |
{res.output}
""" |
analysis.py | """ Usage:
<file-name> --in=IN_FILE --out=OUT_FILE [--debug]
"""
# External imports
import logging
import pdb
from pprint import pprint
from pprint import pformat
from docopt import docopt
from collections import defaultdict
from operator import itemgetter
from tqdm import tqdm
# Local imports
#=-----
def get_pr... |
if __name__ == "__main__":
# Parse command line arguments
args = docopt(__doc__)
inp_fn = args["--in"]
out_fn = args["--out"]
debug = args["--debug"]
if debug:
logging.basicConfig(level = logging.DEBUG)
else:
logging.basicConfig(level = logging.INFO)
prof_dict = defaul... | """
Calculate percentage.
"""
return (part / total) * 100 |
testvec_chanmsg.rs | use tor_bytes::Error as BytesError;
/// Example channel messages to encode and decode.
///
/// Except where noted, these were taken by instrumenting Tor
/// 0.4.5.0-alpha-dev to dump all of its cells to the logs, and
/// running in a chutney network with "test-network-all".
use tor_cell::chancell::{msg, ChanCmd};
use ... | () {
let cmd = ChanCmd::AUTHENTICATE;
assert_eq!(Into::<u8>::into(cmd), 131_u8);
let authentication =
hex!("4155544830303033ED6B2ACBAC868D87D1500505BF59196FD38DEF15E1078C46BF97C7EBCC26C2A26AAF7E6B8FF0C27AB8F0047426017D03A413D8C1D00077ED441112C3E88EEE535BA78B2FD74C3910C5FECBD700677DCA931F4B90EA5CD24D... | test_authenticate |
cache_test.go | // Copyright (c) 2020 Uber Technologies, Inc.
//
// 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 the rights
// to use, copy, modify, merge... | (t *testing.T) {
s := new(eventsCacheSuite)
suite.Run(t, s)
}
func (s *eventsCacheSuite) SetupSuite() {
}
func (s *eventsCacheSuite) TearDownSuite() {
}
func (s *eventsCacheSuite) SetupTest() {
s.Assertions = require.New(s.T())
s.logger = loggerimpl.NewLoggerForTest(s.Suite)
// Have to define our overridden ... | TestEventsCacheSuite |
employee-list.component.ts | import { Component } from "@angular/core";
@Component({
selector: "employee-list",
templateUrl: "app/employee/views/employee.list.html"
})
export class EmployeeListComponent {
title:string="Employee Portal";
subtitle:string="Displaying the list of employees";
employee:any={
| } | name: "Niranjan",
dept: "UI",
proj: "Angular"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.