file_name stringlengths 3 137 | prefix stringlengths 0 918k | suffix stringlengths 0 962k | middle stringlengths 0 812k |
|---|---|---|---|
partition.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module defines the partition data structure used for tracking equality among nonces.
use crate::nonce::Nonce;
use mirai_annotations::checked_verify;
use std::{
collections::{BTreeMap, BTreeSet},
usize::MAX,
};
#[deriv... |
}
| {
let mut nonce_to_id = BTreeMap::new();
for (id, nonce_set) in id_to_nonce_set.iter() {
for nonce in nonce_set {
nonce_to_id.insert(nonce.clone(), id.clone());
}
}
nonce_to_id
} |
shm_streams.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides an implementation of the audio_streams::shm_streams::ShmStream trait using the VioS
//! client.
//! Given that the VioS server doesn't emi... | (
buffer_size: usize,
num_channels: usize,
format: SampleFormat,
frame_rate: u32,
stream_id: u32,
direction: StreamDirection,
vios_client: Arc<VioSClient>,
client_shm: &SysSharedMemory,
) -> GenericResult<Box<dyn ShmStream>> {
let interval = Du... | new |
volume_language_attributes.py | from netapp.netapp_object import NetAppObject
class VolumeLanguageAttributes(NetAppObject):
"""
Information about the volume language settings.
"""
_language_code = None
@property
def language_code(self):
"""
The volume's language code (e.g. 'en_US').
<p>
Vo... | (self):
"""
The volume's fully-qualified language mapping, in the
form: 'LanguageCode (Full Name).'
<p>
Example: 'en_US (English (US)).'
<p>
Attributes: non-creatable, non-modifiable
"""
return self._language
@language.setter
def language(s... | language |
replica_proposal_quota.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, ... | (desc roachpb.RangeDescriptor) bool {
// The NodeLiveness range does not use a quota pool. We don't want to
// throttle updates to the NodeLiveness range even if a follower is falling
// behind because this could result in cascading failures.
return !bytes.HasPrefix(desc.StartKey, keys.NodeLivenessPrefix)
}
func (... | quotaPoolEnabledForRange |
byted-grinning-face-with-squinting-eyes.ts | /**
* @format
* @file BytedGrinningFaceWithSquintingEyes byted-grinning-face-with-squinting-eyes
* @author ็ฑ fe6 ่ชๅจ็ๆ
*/
import { IIconProps, IconWrapper } from '../runtime';
// ่ทๅ SVG ็ HTML ๅญ็ฌฆไธฒ
export const getIconBytedGrinningFaceWithSquintingEyesSvgHtml = (
props: IIconProps,
) => | `<?xml version="1.0" encoding="UTF-8"?>
<svg width="${props.size}" height="${props.size}" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="48" height="48" fill="white" fill-opacity="0.01"/>
<path d="M24 44C35.0457 44 44 35.0457 44 24C44 12.9543 35.0457 4 24 4C12.9543 4 4 12.9543 4 ... | |
kirin.go | package kirin
import (
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/lightninglabs/kirin/auth"
"github.com/lightninglabs/kirin/mint"
"github.com/lightninglabs/kirin/proxy"
"github.com/lightningnetwork/lnd/build"
"github.com/light... | (configFile string) (*config, error) {
cfg := &config{}
b, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(b, cfg)
if err != nil {
return nil, err
}
// Then check the configuration that we got from the config file, all
// required values need to be set at this poi... | getConfig |
ReScript.tsx | import React from "react"
import { Badge } from "../badge"
import type { BadgeProps } from "../badge" | const ReScript = (props: BadgeProps) => <Badge name="ReScript" {...props} backgroundColor="#E6484F" />
export default ReScript | |
main.go | // Copyright 2020 IBM Corp.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"flag"
"os"
kapps "k8s.io/api/apps/v1"
kbatch "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/fields"
kruntime "k8s.io/apimachinery/pkg/runtime"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
... |
return 0
}
// Main entry point starts manager and controllers
func main() {
var namespace string
var metricsAddr string
var enableLeaderElection bool
address := utils.ListeningAddress(listeningPort)
flag.StringVar(&metricsAddr, "metrics-bind-addr", address, "The address the metric endpoint binds to.")
flag.B... | {
setupLog.Error(err, "problem running manager")
return 1
} |
rand_test.go | // Copyright 2016 asana Author. 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... | (t *testing.T) {
bs0 := RandomCreateBytes(16)
bs1 := RandomCreateBytes(16)
t.Log(string(bs0), string(bs1))
if string(bs0) == string(bs1) {
t.FailNow()
}
bs0 = RandomCreateBytes(4, []byte(`a`)...)
if string(bs0) != "aaaa" {
t.FailNow()
}
}
| TestRand_01 |
list_key_detail_request.py | # coding: utf-8
import pprint
import re
import six
class ListKeyDetailRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the val... |
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ListKeyDetailRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not se... | |
mod.rs | use serde::{Deserialize, Serialize};
mod loader;
mod publication_store;
mod waking_state;
pub use loader::MessageLoader; | /// Keys used in persistence.
/// Ordered by offset
#[derive(Hash, Eq, Ord, PartialOrd, PartialEq, Clone, Debug, Deserialize, Serialize, Copy)]
pub struct Key {
offset: u64,
}
#[derive(Debug, thiserror::Error)]
pub enum PersistError {
#[error("Attempted to remove entry which does not exist")]
RemovalForMis... | pub use publication_store::PublicationStore;
pub use waking_state::{memory::WakingMemoryStore, StreamWakeableState};
|
f.py | """(Non-central) F distribution."""
import numpy
from scipy import special
from ..baseclass import Dist
from ..operators.addition import Add
class f(Dist):
"""F distribution."""
def __init__(self, dfn, dfd, nc):
Dist.__init__(self, dfn=dfn, dfd=dfd, nc=nc)
def _pdf(self, x, dfn, dfd, nc):
... | >>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))
[0.2 0.4 0.6 0.8]
>>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))
[0.2277 0.1572 0.0837 0.027 ]
>>> print(numpy.around(distribution.sample(4), 4))
[ 5.4212 1.5739 25.7656 3.5586]
... | >>> print(numpy.around(distribution.inv(q), 4))
[1.9336 2.9751 4.7028 8.8521] |
standard_information.rs | // Copyright 2021-2022 Colin Finck <colin@reactos.org>
// SPDX-License-Identifier: MIT OR Apache-2.0
use binread::io::{Cursor, Read, Seek};
use binread::{BinRead, BinReaderExt};
use crate::attribute::NtfsAttributeType;
use crate::attribute_value::{NtfsAttributeValue, NtfsResidentAttributeValue};
use crate::error::{Nt... | self.ntfs1_data.access_time
}
/// Returns the Class ID of the file, if stored via NTFS 3.x file information.
pub fn class_id(&self) -> Option<u32> {
self.ntfs3_data.as_ref().map(|x| x.class_id)
}
/// Returns the time this file was created.
pub fn creation_time(&self) -> NtfsTim... | |
privado.go | package constants
import (
"net"
"github.com/rxtreme8/gluetun/internal/models"
)
//nolint:lll
const (
PrivadoCertificate = "MIIFKDCCAxCgAwIBAgIJAMtrmqZxIV/OMA0GCSqGSIb3DQEBDQUAMBIxEDAOBgNVBAMMB1ByaXZhZG8wHhcNMjAwMTA4MjEyODQ1WhcNMzUwMTA5MjEyODQ1WjASMRAwDgYDVQQDDAdQcml2YWRvMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAg... | {Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-023.vpn.privado.io", IP: net.IP{23, 19, 225, 93}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-024.vpn.privado.io", IP: net.IP{23, 19, 225, 95}},
{Country: "United States", Region: "New Yo... | {Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-022.vpn.privado.io", IP: net.IP{23, 19, 225, 91}}, |
404.js | import React, { useState, useLayoutEffect } from "react";
// Components
import Layout from "../components/layout";
import SEO from "../components/seo";
// Images
import Astronaut from '../images/404/Astronaut-big.png'
import BalloonLost from '../images/404/Balloon Lost-big.png'
import BrokenClock from '../images/404/... | {fourOhFourParagraphText[pick]}
</p>
</div>
</Layout>
);
} | {fourOhFourHeadingText[pick]}
</h2>
<p className="font-sans text-lg subpixel-antialiased font-thin"> |
cat.count.js | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not u... | (opts) {
// eslint-disable-next-line no-unused-vars
const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
const acceptedQuerystring = [
'format',
'h',
'help',
's',
'v',
'pretty',
'human',
'error_trace',
'source',
'filter_path'
]
const snakeCase... | buildCatCount |
consumer_close.handler.rs | use crate::room::dto::consumer_close_request::ConsumerCloseRequest;
use crate::room::dto::consumer_close_response::ConsumerCloseResponse;
use crate::room::Room;
use actix::prelude::*;
///
/// This handler is used to serve user's request to close consumer stream.
///
impl Handler<ConsumerCloseRequest> for Room {
typ... | id: msg.id,
});
});
}
}
} | user_id: msg.producer_user_id, |
testutil.py | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | else:
raise TypeError('unrecognised type for field %s: type %s' %
(key, type(value)))
return result
def assertHasKeyWithValueAlmostEqual(self,
d,
key,
value,
... | raise TypeError('field %s was a list, but the first element had '
'unknown type %s' % key, type(value[0])) |
telemetryHelper.ts | import * as vscode from 'vscode';
import * as telemetryConnect from './telemetryConnect';
let telemetryconnect: telemetryConnect.telemetryConnect = require('../telemetryConnect.json');
// extension telemetry
import TelemetryReporter from 'vscode-extension-telemetry';
const extensionId = 'drewsk.demo-mode';
const ext... | {
public reporter: TelemetryReporter;
constructor(context:vscode.ExtensionContext) {
this.reporter = new TelemetryReporter(extensionId, extensionVersion, key);
context.subscriptions.push(this.reporter);
}
public sendTelemetry(eventName:string, stringObj:any, numericObj:any) {
... | telemetryHelper |
test_models.py | import pytest
from google_auth.users.models import User
pytestmark = pytest.mark.django_db
def test_user_get_absolute_url(user: User):
| assert user.get_absolute_url() == f"/users/{user.username}/" | |
index.d.ts | declare module 'input-event'; | ||
certificates.py | # Copyright 2018 VMware, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | (resource, event, trigger, **kwargs):
"""Delete client certificate and private key """
return v3_common_cert.delete_cert(cfg.CONF.nsx_p, **kwargs)
@admin_utils.output_header
def show_cert(resource, event, trigger, **kwargs):
"""Show client certificate details """
return v3_common_cert.show_cert(cfg.CO... | delete_cert |
lib.rs | // This file is part of Bit.Country.
// Copyright (C) 2020-2021 Bit.Country.
// SPDX-License-Identifier: Apache-2.0
// 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... |
fn do_transfer_spot(
spot_id: SpotId,
from: &T::AccountId,
to: &(T::AccountId, MetaverseId),
) -> Result<SpotId, DispatchError> {
Self::transfer_spot(spot_id, from, to)
}
fn check_approved(tally: &ContinuumSpotTally<T::AccountId>) -> bool {
let nay_ratio = tally.turnout.checked_div(tally.nays).unwrap_o... | {
ContinuumSpots::<T>::get(spot_id).ok_or(Error::<T>::SpotNotFound.into())
} |
suite.ts | /* tslint:disable */
/* eslint-disable */
/**
* Qase.io API
* Qase API Specification.
*
* The version of the OpenAPI document: 1.0.0
* Contact: support@qase.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class ... | *
* @export
* @interface Suite
*/
export interface Suite {
/**
*
* @type {number}
* @memberof Suite
*/
'id'?: number;
/**
*
* @type {string}
* @memberof Suite
*/
'title'?: string;
/**
*
* @type {string}
* @memberof Suite
*/
'des... |
/** |
idsextractor_jwt.go | // Copyright (c) 2018 Palantir Technologies. 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 require... |
bytes, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", "", "", fmt.Errorf("failed to decode JWT content %q as Base64 URL-encoded string: %v", parts[1], err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(bytes, &jsonMap); err != nil {
return "", "", "", fmt.Error... | {
return "", "", "", fmt.Errorf("JWT must have 3 '.'-separated parts, but had %d: %q", len(parts), jwtContent)
} |
inkscape_control.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import paste
import subprocess
from multiprocessing import Process
from pathlib import Path
import tkinter.messagebox as messagebox
from shutil import copy
from appdirs import user_config_dir
import logging as log
from globe import Globe as globe
from util impo... | ent is the title of the figure
# Second argument is the figure directory.
# """
# title = title.strip()
# file_name = title.replace(' ', '-').lower() + '.svg'
# figures = root + os.path.sep + 'figures'+os.path.sep
# figure_path = figures + file_name
# # If a file with this name already exi... | argum |
compression.rs | use cratesfyi::storage::{compress, decompress, CompressionAlgorithm};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
const ALGORITHM: CompressionAlgorithm = CompressionAlgorithm::Zstd;
pub fn criterion_benchmark(c: &mut Criterion) |
criterion_group!(compression, criterion_benchmark);
criterion_main!(compression);
| {
// this isn't a great benchmark because it only tests on one file
// ideally we would build a whole crate and compress each file, taking the average
let html = std::fs::read_to_string("benches/struct.CaptureMatches.html").unwrap();
let html_slice = html.as... |
volunteercontrol.go | package volunteercontrol
import (
"math"
"fmt"
"github.com/DCNT-developer/dcnt/electionsCore/messages"
. "github.com/DCNT-developer/dcnt/electionsCore/primitives"
)
var _ = fmt.Println
// VolunteerControl will keep a record of all votes
// for a given volunteer and produce the best vote
// possible.
type Volun... | }
func (a *VolunteerControl) Copy() *VolunteerControl {
b := NewVolunteerControl(a.Self, a.AuthSet.Copy())
if a.Volunteer != nil {
v := *a.Volunteer
b.Volunteer = &v
}
for k, v := range a.Votes {
b.Votes[k] = *v.Copy()
}
return b
} | |
stats.py | """
Training Statics Tools
A class for loading statistics related to a particular rutraiining session.
"""
import numpy as np
#from scipy import stats
import pandas as pd
import os
def | (s, start, end):
return (s.split(start))[1].split(end)[0]
def is_stat_file_version(file_name, version):
return file_name.startswith("stats_{}_gen".format(version)) and file_name.endswith(".h5")
class TrainingStates:
def __init__(self, versions, directory, verbose=True):
self.stats_files = self.get... | str_between |
crypto.ts | import * as crypto from 'crypto'; | }
}
export default new Crypto(); |
class Crypto {
hash(value: string) {
return crypto.createHash('sha256').update(value).digest('hex'); |
index.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.signature = signature;
exports.functionNameMetadata = functionNameMetadata;
exports.localNameMetadata = localNameMetadata;
exports.moduleMetadata = moduleMetadata;
exports.identifier = identifier;
exports.valtype = valtype;
exports.... |
if (sign == undefined) {
// TODO: Uncomment this when br_table and others has been done
//throw new Error("Invalid opcode: "+opcodeName);
return [object, object];
}
return sign[0];
}
function functionNameMetadata(value, index) {
return {
type: "FunctionNameMetadata",
value: value,
ind... | }
var sign = signatures[opcodeName]; |
attachment.go | // Copyright 2022 Google LLC. 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... | // 2.4 Imperative Request Planning
var ops []attachmentApiOperation
if create {
ops = append(ops, &createAttachmentOperation{})
} else {
for _, d := range diffs {
ops = append(ops, d.UpdateOp)
}
}
c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops)
// 2.5 Request Actuation
for _, op := ran... | }
}
}
|
repl_writer.rs | use crate::style::TextStyling;
use crate::{impl_colored_methods, ColorWriter};
use crossterm::cursor::MoveLeft;
use crossterm::execute;
use crossterm::style::Color;
use crossterm::terminal::{Clear, ClearType};
use std::fmt::Display;
pub struct ReplWriter {
writer: ColorWriter,
prompt_prefix: Option<String>
}
... |
execute!(
std::io::stderr(),
Clear(ClearType::CurrentLine),
MoveLeft(u16::MAX)
)
.unwrap();
self.write_prompt_prefix();
self.fg(fg).bg(bg).write(data);
}
impl_colored_methods! {
// Foreground Colors
fg red Red,
... | let fg = self.writer.fg.clone();
let bg = self.writer.bg.clone(); |
_field_common.py | import six
import sys
from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as o... | # `collections.namedtuple`, will work as expected, since we check
# `isinstance` and not `issubclass`.
if isinstance(type, (list, set, tuple)):
types = set(maybe_parse_many_user_types(type))
else:
types = set(maybe_parse_user_type(type))
invariant_function = wrap_invariant(in... | |
rpc.go | // Copyright 2019 Yunion
//
// 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 writi... | (prefix string) *RPCHandlers {
return &RPCHandlers{NewHandlers(prefix)}
}
func (h *RPCHandlers) AddGet(mf appsrv.MiddlewareFunc) *RPCHandlers {
h.AddByMethod(GET, mf, NewHP(rpcHandler, APIVer, "rpc"))
return h
}
func (h *RPCHandlers) AddPost(mf appsrv.MiddlewareFunc) *RPCHandlers {
h.AddByMethod(POST, mf, NewHP(r... | NewRPCHandlers |
test_regkey_controller.py | import json
import pytest
from sqlalchemy.sql import text as sa_text
from sqlalchemy.orm.session import sessionmaker
from opencdms.models.climsoft import v4_1_1_core as climsoft_models
from apps.climsoft.db.engine import db_engine
from apps.climsoft.schemas import regkey_schema
from datagen.climsoft import regkey as cl... |
def test_should_return_single_reg_key(client: TestClient, get_reg_key: climsoft_models.Regkey, get_access_token: str):
response = client.get(f"/climsoft/v1/reg-keys/{get_reg_key.keyName}", headers={
"Authorization": f"Bearer {get_access_token}"
})
assert response.status_code == 200
response_d... | response = client.get("/climsoft/v1/reg-keys", params={"limit": 5}, headers={
"Authorization": f"Bearer {get_access_token}"
})
assert response.status_code == 200
response_data = response.json()
assert len(response_data["result"]) == 5 |
dataset_factory.py | #
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Intel Corporation
#
# 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 app... | (name, split_name, dataset_dir, file_pattern=None, reader=None):
"""Given a dataset name and a split_name returns a Dataset.
Args:
name: String, the name of the dataset.
split_name: A train/test split name.
dataset_dir: The directory where the dataset files are stored.
file_pattern: The file patter... | get_dataset |
root.go | package cmd
import (
"os"
template "github.com/timmypotts/gk/templates"
"github.com/kujtimiihoxha/gk/fs"
"github.com/sirupsen/logrus"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Co... |
func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().Bool("testing", false, "If testing the generator.")
RootCmd.PersistentFlags().BoolP("debug", "d", false, "If you want to se the debug logs.")
RootCmd.PersistentFlags().BoolP("force", "f", false, "Force overide existing files without asking.")... | {
if err := RootCmd.Execute(); err != nil {
logrus.Error(err)
os.Exit(-1)
}
} |
models.py | def breast_cancer(x_train, y_train, x_val, y_val, params):
from keras.models import Sequential
from keras.layers import Dropout, Dense
from talos.model import lr_normalizer, early_stopper, hidden_layers
from talos.metrics.keras_metrics import matthews, precision, recall, f1score
model = Sequentia... | (x_train, y_train, x_val, y_val, params):
from keras.models import Sequential
from keras.layers import Dropout, Dense
from talos.model import lr_normalizer, early_stopper, hidden_layers
# note how instead of passing the value, we pass a dictionary entry
model = Sequential()
model.add(Dense(par... | iris |
lib.rs | // 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 may... | Ok(())
} | |
logger.rs | use crate::{
rpc::{rpc_log, streaming_message::Content, RpcLog, StreamingMessage},
worker::Sender,
};
use log::{Level, Log, Metadata, Record};
pub struct Logger {
level: Level,
sender: Sender,
}
impl Logger {
pub fn new(level: Level, sender: Sender) -> Logger {
Logger { level, sender }
... |
fn log(&self, record: &Record) {
if !self.enabled(record.metadata()) {
return;
}
let mut event = RpcLog {
level: match record.level() {
Level::Trace => rpc_log::Level::Trace,
Level::Debug => rpc_log::Level::Debug,
Lev... | {
metadata.level() <= self.level
} |
main.py | # %% [markdown]
# [](https://colab.research.google.com/github/jun-hyeok/SUP5001-41_Deep-Neural-Networks_2022Spring/blob/main/DNN_HW5/main.ipynb)
# %% [markdown]
# # DNN HW5 : #9
#
# 2022.03.23
# ๋ฐ์คํ
# %%
import numpy as np
import torch
import t... | x = F.relu(self.fc5(x))
x = F.relu(self.fc6(x))
x = F.relu(self.fc7(x))
x = F.relu(self.fc8(x))
x = F.relu(self.fc9(x))
x = F.sigmoid(self.fc10(x))
return x
# %%
nn10 = NN10()
optimizer10 = optim.SGD(nn10.parameters(), lr=0.1)
epochs = 10000
for epoch in range(e... | x = F.relu(self.fc3(x))
x = F.relu(self.fc4(x)) |
JobBrowserBFF_JSONRPCServer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import sys
import traceback
from getopt import getopt, GetoptError
from multiprocessing import Process
from wsgiref.simple_server import make_server
from JobBrowserBFF.jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError, \
JSO... | _proc = Process(target=httpd.serve_forever)
_proc.daemon = True
_proc.start()
else:
httpd.serve_forever()
return port
def stop_server():
global _proc
_proc.terminate()
_proc = None
if __name__ == "__main__":
try:
opts, args = getopt(sys.argv[1:], "", [... | port = httpd.server_address[1]
print("Listening on port %s" % port)
if newprocess: |
main.go | package p003
import (
"strconv"
"github.com/JustinKuli/project-euler/pkg/prime"
)
// Solve this problem:
// What is the largest prime factor of the number 600851475143?
func Solve() string | {
factors, err := prime.FactorsOf(uint64(600_851_475_143))
if err != nil {
return "Error"
}
return strconv.Itoa(int(factors[len(factors)-1]))
} | |
login.component.ts | import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NbAuthService, NbLoginComponent, NB_AUTH_OPTIONS } from '@nebular/auth';
import { environment } from './../../../environments/environment';
@Component({
selector: 'ngx-login',
templateUrl:... | ||
artifact-extract-task.ts | import * as yauzl from 'yauzl';
import { join } from 'path';
import mkdirp from 'mkdirp';
import { createWriteStream, existsSync } from 'fs';
import { IArtifact } from '../../artifact';
import { ArtifactTask } from '../artifact-task';
import { exists } from '../../../util';
export interface IArtifactExtractTaskProgres... |
file.openReadStream(entry, (err, readStream) => {
if (err) {
return reject(err);
}
if (!readStream) {
return reject(new Error('cannot open read str... | |
main.go | package main
import (
"fmt"
"os"
"os/user"
"github.com/ujuc/monkey/internal/repl"
)
func main() | {
user, err := user.Current()
if err != nil {
panic(err)
}
fmt.Printf("Hello %s! This is the Monkey programming language!\n", user.Username)
fmt.Printf("Feel free to type in commands\n")
repl.Start(os.Stdin, os.Stdout)
} | |
output.rs | //! # Convert from SCSS AST to CSS
use std::{io::Write, mem};
use codemap::CodeMap;
use crate::{
atrule::{
keyframes::{Keyframes, KeyframesRuleSet, KeyframesSelector},
media::MediaRule,
SupportsRule, UnknownAtRule,
},
error::SassResult,
parse::Stmt,
selector::{ComplexSelect... |
if body.is_empty() {
writeln!(buf, ";")?;
continue;
}
writeln!(buf, " {{")?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
... | } else {
write!(buf, "{}@{} {}", padding, name, params)?;
} |
confidant.py | # -*- coding: utf-8 -*-
'''
An SDB module for getting credentials from confidant.
Configuring the Confidant module
================================
The module can be configured via sdb in the minion config:
.. code-block:: yaml
confidant:
driver: confidant
# The URL of the confidant web service
url: '... | (key, profile=None):
'''
Read pillar data from Confidant via its API.
CLI Example:
salt myminion sdb.get 'sdb://confidant/credentials'
Valid keys are: credentials, credentials_metadata, result. credentials
returns a dict of joined credential_pairs, credentials_metadata returns a
dict ... | get |
Staff.js | import axios from 'axios';
import React, { Component } from "react";
class Staff extends Component {
constructor(props) {
super(props)
this.state = {
gallery: [],
};
}
componentDidMount() {
axios.get('http://localhost:8000/api/gallery/')
.then(res => {
t... | render(){
return(
this.state.gallery.map((ga, i) => {
return(
<OwlCarousel className="owl-carousel staff-carousel" items={4} margin={8} autoplay ={true}>
<div className="member" data-aos-delay={100}>
<div className="pic"><img src="assets/img/team/team-1.jpg" c... | }
|
logoHeader.tsx | import * as React from 'react';
import classNames from './logoHeader.classNames';
export enum LogoColors {
white = 'white',
gray = 'gray'
}
export interface LogoProps extends React.Props<any> {
logoColor?: LogoColors;
}
export const LogoHeader = (props: LogoProps) => (
<header className={classNames().root}>
... | src={`https://assets.onestore.ms/cdnfiles/external/uhf/long/9a49a7e9d8e881327e81b9eb43dabc01de70a9bb/images/microsoft-${props.logoColor || LogoColors.white}.png`}
/>
{props.children}
</header>); | |
eventos.js | /*var eventos = [
{ "idevento": 3,
"idlocal": 3,
"idesporte":2,
"idcategoria": 2,
"idmodalidade": -1,
"descricao": "Jogo de fulano vs etc",
"horario": "00:50",
"local": "maracanรฃ",
"data": "22/05/2016"
},
{
"idevento": 2,
"idlocal": 3,
"idesporte":2,
"idcategoria": 2,
"idmodalid... | },
{"data":"2016-08-07",
"conteudo": [{"idevento": 66,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-07 18:00:00","nome": "Arena da Amazonia","idlocal": 1}, {"idevento": 67,"idesporte": 24,"idmodalidade": -1,"idcategoria": 251,"data": "2016-08-07 16:00:00","nome": "Centro Aquรกtico Maria Lenk","idl... | },
{"data":"2016-08-06",
"conteudo": [{"idevento": 18,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 09:00:00","nome": "Centro Aquรกtico Maria Lenk","idlocal": 2}, {"idevento": 18,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 09:00:00","nome": "Centro Aquรกtico Maria L... |
lib.rs | // DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
//! This documentation was generated from *Container* crate version *3.1.0+20220215*, where *20220215* is the exact revision of the *container:v1* schema built by the [mako](http://www.makotemplates.org/) code ge... | //! let r = hub.projects().locations_clusters_start_ip_rotation(...).doit().await
//! let r = hub.projects().locations_clusters_update(...).doit().await
//! let r = hub.projects().locations_clusters_update_master(...).doit().await
//! let r = hub.projects().locations_operations_get(...).doit().await
//! let r = hub.pro... | //! let r = hub.projects().locations_clusters_set_network_policy(...).doit().await
//! let r = hub.projects().locations_clusters_set_resource_labels(...).doit().await |
nested_closures.rs | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Check that we can codegen various nesting structures of boxes and
// pointer to closures.
pub fn | () {
// Create a nested boxed once-callable closure
let f: Box<Box<dyn FnOnce(i32)>> = Box::new(Box::new(|x| assert!(x == 1)));
f(1);
// Create a pointer to a closure
let g = |x: f32, y: i32| {
assert!(x == 1.0);
assert!(y == 2)
};
let p: &dyn Fn(f32, i32) = &g;
p(1.0, 2... | main |
udp_linux_test.go | // +build linux testrareexceptions
package udpnofrag
import (
"net"
"reflect"
"syscall"
"testing"
"unsafe" |
func TestUdpSetNoFragment_negative(t *testing.T) {
assert.Equal(t, syscall.EINVAL, UDPSetNoFragment(&net.UDPConn{}))
conn, err := net.Dial("udp", "127.0.0.1:1")
udpConn := conn.(*net.UDPConn)
assert.NoError(t, err)
fd := (**struct{ a [65536]byte })((unsafe.Pointer)(reflect.ValueOf(unsafetools.FieldByName(udpConn,... |
"github.com/stretchr/testify/assert"
"github.com/xaionaro-go/unsafetools"
) |
visualize_court.py | import numpy as np
# import plotly
import plotly.graph_objects as go
def draw_plotly_half_court(fig, fig_width=600, margins=10):
# From: https://community.plot.ly/t/arc-shape-with-path/7205/5
def ellipse_arc(x_center=0.0, y_center=0.0, a=10.5, b=10.5, start_angle=0.0, end_angle=2 * np.pi, N=200, closed=False... |
fig_height = fig_width * (470*2 + 2 * margins) / (500 + 2 * margins)
fig.update_layout(width=fig_width, height=fig_height)
# Set axes ranges
fig.update_xaxes(range=[-250 - margins, 250 + margins])
fig.update_yaxes(range=[-52.5 - margins, 417.5+470 + margins])
# fig.update_xaxes(range=[ margi... | t = np.linspace(start_angle, end_angle, N)
x = x_center + a * np.cos(t)
y = y_center + b * np.sin(t)
path = f'M {x[0]}, {y[0]}'
for k in range(1, len(t)):
path += f'L{x[k]}, {y[k]}'
if closed:
path += ' Z'
return path |
tanh.go | package math32
// The original C code, the long comment, and the constants
// below were from http://netlib.sandia.gov/cephes/cmath/tanh.c,
// available from http://www.netlib.org/cephes/single.tgz.
// The go code is a simplified version of the original C.
// tanhf.c
//
// Hyperbolic tangent
//
//
//
// SYNOPSIS:
//
/... | {
const MAXLOG = 88.02969187150841
z := Abs(x)
switch {
case z > 0.5*MAXLOG:
if x < 0 {
return -1
}
return 1
case z >= 0.625:
s := Exp(z + z)
z = 1 - 2/(s+1)
if x < 0 {
z = -z
}
default:
if x == 0 {
return x
}
s := x * x
z = ((((-5.70498872745E-3*s+2.063... | |
images.py | # Copyright 2013-2020 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)
"""Manages the details on the images used in the build and the run stage."""
import json
import os.path
#: Global variable... | image_data = data()[image]
update = image_data['update']
install = image_data['install']
clean = image_data['clean']
return update, install, clean | Returns:
A tuple of (update, install, clean) commands.
""" |
build.py | # coding=utf-8
"""
Build tasks
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import json
import os
import subprocess
import sys
from pynt import task
from pyntcontrib import execute, safe_cd
from semantic_version import Version
PROJECT_N... |
# Default task (if specified) is run when no task is specified in the command line
# make sure you define the variable __DEFAULT__ after the task is defined
# A good convention is to define it at the end of the module
# __DEFAULT__ is an optional member
__DEFAULT__ = echo | """
Pure diagnostics
"""
print(args)
print(kwargs) |
2d_array.test.js | /******************************************************************************
*
* Copyright (c) 2020, the Regular Table Authors.
*
* This file is part of the Regular Table library, distributed under the terms
* of the Apache License 2.0. The full license can be found in the LICENSE
* file.
*
*/
describe("2d... | test("to (0, 1)", async () => {
const table = await page.$("regular-table");
await page.evaluate(async (table) => {
table._invalid_schema = true;
table.scrollToCell(0, 1, 3, 26);
await table.draw({invalid_viewport: true});
}, ta... | });
|
lolcats_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Benjamin Kampmann <ben.kampmann@googlemail.com>
"""
This is a Media Backend that allows you to access the cool and cute pictures
from lolcats.com. This is mainly meant as a Sample Media Backend... | self.item = DIDLLite.ImageItem(id, parent_id, self.name)
# each Item.item has to have one or more Resource objects
# these hold detailed information about the media data
# and can represent variants of it (different sizes, transcoded formats)
res = DIDLLite.Resource(self.locatio... | # case, we have an image. |
chmod.go | package wrfs
// Chmod is a file with a Chmod method.
type ChmodFile interface {
File
// Chmod changes the mode of the file to mode.
Chmod(mode FileMode) error
}
// ChmodFS is a file system with a Chmod method.
type ChmodFS interface {
FS
// Chmod changes the mode of the named file to mode.
// If the file is a... | {
if fsys, ok := fsys.(ChmodFS); ok {
return fsys.Chmod(name, mode)
}
// Open the file and attempt to call chmod on it.
file, err := fsys.Open(name)
if err != nil {
return err
}
defer safeClose(file, &err)
if file, ok := file.(ChmodFile); ok {
... | |
left_recursion.rs | extern crate peg;
peg::parser!(grammar foo() for str {
rule rec() = rec //~ ERROR left recursive rules create an infinite loop: rec -> rec
rule foo()
= "foo" foo
/ bar //~ ERROR left recursive rules create an infinite loop: bar -> foo -> bar
rule bar()
= "bar" bar
/ foo //... | () {}
| main |
orderedcollections.py | # Copyright (c) 2009 Raymond Hettinger
#
# 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,
# publish,... | Old items can be deleted with the remove() method.
The usual sequence methods are provided to support indexing, slicing,
length lookup, clearing, copying, forward and reverse iteration, contains
checking, item counts, item removal, and a nice looking repr.
Finding and indexing are O(log n) operati... |
Once found, an item's ordinal position can be located with the index() method.
New items can be added with the insert() and insert_right() methods. |
gloomy-utils.js | function gloomyAjaxUpdater()
{
var url = arguments[0];
var div = arguments[1];
var options = arguments[2] || {};
var spinner = options['spinner'] || null; | $(spinner).show();
$.ajax({
url: url,
cache: false,
type: type,
data: data,
success: function (html) {
$(div).html(html);
$(spinner).hide();
onsuccess();
... | var onsuccess = options['onsuccess'] || function() {};
var type = options['type'] || 'get';
var data = options['data'] || null;
|
window.rs | // Copyright 2016 Joe Wilm, The Alacritty Project 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 b... | (&self, title: &str) {
self.window().set_title(title);
}
#[inline]
pub fn set_mouse_cursor(&self, cursor: MouseCursor) {
self.window().set_cursor(cursor);
}
/// Set mouse cursor visible
pub fn set_mouse_visible(&mut self, visible: bool) {
if visible != self.mouse_visibl... | set_title |
filehound.go | package filehound
import (
"os"
"path/filepath"
"regexp"
"strings"
)
type filterFn func(path string, info os.FileInfo) bool
// Option is a filehound filter option
type Option func(*Filehound)
// Filehound will search for files apply zero or more file filters.
type Filehound struct {
root string
filters [... |
// Ext filters by one or more file extensions
func Ext(exts ...string) Option {
return func(f *Filehound) {
f.Filter(func(path string, info os.FileInfo) bool {
for _, ext := range exts {
if strings.HasPrefix(ext, ".") {
ext = ext[1:]
}
if filepath.Ext(path)[1:] == ext {
return true
}
... | {
return func(f *Filehound) {
f.root = root
}
} |
Resizeable.d.ts | import { ElementRef, EventEmitter } from '@angular/core';
export declare class | {
resizeEnabled: boolean;
minWidth: number;
maxWidth: number;
onResize: EventEmitter<any>;
private element;
private subscription;
private prevScreenX;
private resizing;
constructor(element: ElementRef);
onMouseup(): void;
onMousedown(event: any): void;
move(event: any): ... | Resizeable |
asset.rs | use anchor_lang::prelude::*;
use super::address::Category;
#[account]
pub struct Asset {
/// Community account, which this address belongs to |
/// Network account, which this address belongs to
pub network: Pubkey,
/// Asset mint account
pub mint: Pubkey,
/// Asset ID
pub asset_id: [u8; 32],
/// Seed bump for PDA
pub bump: u8,
/// ID of the associated case
pub case_id: u64,
/// Reporter account public key
... | pub community: Pubkey, |
img-placeholder.py | import sublime
import sublime_plugin
import re
completions = []
def plugin_loaded():
init_settings()
def init_settings():
get_settings()
sublime.load_settings('img-placeholder.sublime-settings').add_on_change('get_settings', get_settings)
def get_settings():
settings = sublime.load_settings('img-pla... |
return False
class imgHolder(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
syntax = view.settings().get('syntax')
before_text = before(view, locations[0]);
if is_trigger(before_text, syntax):
return (completions, sublime.INHIBIT_E... | return True |
process-stats-dir.py | #!/usr/bin/python
#
# ==-- process-stats-dir - summarize one or more Swift -stats-output-dirs --==#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014-2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://s... | return round((float(ran) / float(total)) * 100.0, 2)
# Return a JSON-formattable object of the form preferred by google chrome's
# 'catapult' trace-viewer.
def to_catapult_trace_obj(self):
return {"name": self.module,
"cat": self.jobkind,
"ph": "X", ... | total = self.driver_jobs_total() |
test.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::format_err;
use derivative::Derivative;
use fidl_fuchsia_hardware_audio::*;
use fuchsia_async as fasync;
use futures::{Future, StreamExt};
use ... |
}
#[derive(Clone)]
pub struct TestHandle(Arc<Mutex<TestStatus>>);
impl TestHandle {
pub fn new() -> Self {
Self(Arc::new(Mutex::new(TestStatus::default())))
}
pub fn status(&self) -> TestStatus {
self.0.lock().unwrap().clone()
}
pub fn is_started(&self) -> bool {
let loc... | {
if let Self::Started { dai_format, pcm_format } = *self {
*self = Self::Configured { dai_format, pcm_format };
}
} |
Maps.go | package main
import (
"fmt"
)
var Commands map[string]string
func main() {
fmt.Println("Demo for maps")
LinuxCommands();
for k, v := range Commands {
fmt.Println(k, "=>", v)
}
WindowsCommands();
for k, v := range Commands {
fmt.Println(k, "=>", v)
}
delete(Commands , "Dir")
fmt.Println("Delete key a... | "Dir" : "Show all files and folders in dir",
"cd" : "Change Directory",
"md" : "Make Directory",
}
} | func WindowsCommands(){
Commands = map[string]string{ |
users.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class | {
private url: string = "http://jsonplaceholder.typicode.com/users";
constructor(private http: Http) { }
getUsers(){
return this.http.get(this.url)
.map(res => res.json());
}
getUser(id){
return this.http.get(this.getUserUrl(id))
.map(res => res.json());
}
addUser(user){
retu... | UsersService |
cloudtrail.py | """
Copyright 2017-present, Airbnb 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, sof... |
if send_to_cloudwatch:
destination_arn = modules['cloudtrail'].get(
'cloudwatch_destination_arn',
'${{module.cloudwatch_{}_{}.cloudwatch_destination_arn}}'.format(cluster_name,
region)
)
mo... | module_info['kinesis_arn'] = '${{module.kinesis_{}.arn}}'.format(cluster_name)
module_info['event_pattern'] = json.dumps(event_pattern) |
doc.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 may not use ... |
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permiss... | with the License. You may obtain a copy of the License at |
PlaceholderCard.js | import React from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { withStyles } from "material-ui/styles";
import Typography from "material-ui/Typography";
import Card from "material-ui/Card";
const styles = () => ({ | justifyContent: "center",
},
tall: {
minHeight: 360,
},
});
class PlaceholderCard extends React.Component {
static propTypes = {
tall: PropTypes.bool,
...Card.propTypes,
};
static defaultProps = {
tall: false,
};
render() {
const { classes, tall, children, ...props } = this.pr... | root: {
display: "flex",
minHeight: 180,
alignItems: "center", |
post.controller.js | /**
* Seanica
*
* User: sean
* Date: 13/04/13
* Time: 10:57 PM
*
*/
define(['sf1','modules/post/post.models','modules/post/post.views','text!modules/post/post.templates.html','uirte'],
function(sf1, Model, View, template, RTE){
var anchorSelector = '#TemplateContainer';
_.templateSettings.va... | sf1.EventBus.trigger('post.getPostBySlugSuccess',response);
},
error:function(response){
sf1.log('error getting post: ' + response);
sf1.EventBus.trigger('post.getPostBySlugFailed');
}
... | success:function(response){
sf1.log('success getting post: ' + response); |
genesis_gas_schedule.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This file contains the starting gas schedule published at genesis.
use move_core_types::gas_schedule::GasCost;
use once_cell::sync::Lazy;
use vm::{
file_format::{
Bytecode, ConstantPoolIndex, FieldHandleIndex, FieldIns... | (Lt, GasCost::new(49, 1)),
(LdU8(0), GasCost::new(29, 1)),
(LdU64(0), GasCost::new(29, 1)),
(LdU128(0), GasCost::new(29, 1)),
(CastU8, GasCost::new(29, 1)),
(CastU64, GasCost::new(29, 1)),
(CastU128, GasCost::new(29, 1)),
(Abort, GasCost::new(39, 1)),
... | (CopyLoc(0), GasCost::new(41, 1)),
(StLoc(0), GasCost::new(28, 1)),
(Ret, GasCost::new(28, 1)), |
init_pointer.go | package main
import "fmt"
func main() { | var a = 26.9
var p = &a
fmt.Println("Value stored in variable a = ", a)
fmt.Println("Address of variable a = ", &a)
fmt.Println("Value stored in variable p = ", p)
} | |
CarsForSaleResultList.js | import React from 'react';
import CarForSaleCard from './CarForSaleCard';
import { connect } from 'react-redux';
import { Card } from 'semantic-ui-react';
class CarsForSaleResultList extends React.Component {
state = {
open: false
};
mapNewCars = (props) => {
let i = this.props.render_... | render_option: state.new_cars.render_option,
activeIndex: state.user.activeTab
};
}
const mapDispatchToProps = (dispatch) => ({
functionName: (param) => dispatch({ type: 'ACTION_NAME', param })
})
export default connect(mapStateToProps, mapDispatchToProps)(CarsForSaleResultList); | used_cars: state.used_cars.listings,
new_cars: state.new_cars.listings, |
interface.go | package filter
import (
"log"
"net"
"github.com/millken/tcpwder/config"
"github.com/millken/tcpwder/core"
"github.com/millken/tcpwder/firewall"
)
type FilterInterface interface {
Init(cf config.Server) bool
Connect(client net.Conn) error
Read(client net.Conn, rwc core.ReadWriteCount)
Write(client net.Conn, ... | Stop()
}
var filters = make(map[string]func() interface{})
type Filter struct {
cfg config.Server
filters map[string]FilterInterface
stop chan bool
}
func RegisterFilter(name string, filter func() interface{}) {
if filter == nil {
return
}
if _, ok := filters[name]; ok {
log.Fatalln("Register call... | |
jwt.go | package jwt
import (
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/ujjwalmishra/fodie/pkg/e"
"github.com/ujjwalmishra/fodie/pkg/util"
)
// JWT is jwt middleware
func JWT() gin.HandlerFunc | {
return func(c *gin.Context) {
var code int
var data interface{}
code = e.SUCCESS
token := c.Query("token")
if token == "" {
code = e.INVALID_PARAMS
} else {
_, err := util.ParseToken(token)
if err != nil {
switch err.(*jwt.ValidationError).Errors {
case jwt.Va... | |
models.py | from django.db import models
from django.utils import timezone
from django.db.models import Q
import asyncio
from ib_insync import IB, Stock, MarketOrder, util
from core.common import empty_append
from core.indicators import rel_dif
import vectorbtpro as vbt
import sys
import math
import pandas as pd
import numpy a... | s.all():
arr.append(action.symbol)
return arr
def __str__(self):
return self.name
def get_candidates(strategy, exchange):
s=Strategy.objects.get(name=strategy)
e=StockEx.objects.get(name=exchange)
c1 = Q(stock_ex=e)
c2 = Q(strategy=s)
return Candidates.o... | e()
def retrieve(self):
arr=[]
for action in self.action |
0002_auto_20210715_1151.py | # Generated by Django 2.2.24 on 2021-07-15 11:51
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='last_updated',
field=models.DateTimeField(auto_now=True, null=True),
),
migrations.AddField(
model_name='user',
... | |
message_id.py |
class MessageId:
"""The CAN MessageId of an PDU.
The MessageId consists of three parts:
* Priority
* Parameter Group Number
* Source Address
"""
def __init__(self, **kwargs): #priority=0, parameter_group_number=0, source_address=0):
"""
:param priority:
... |
@can_id.setter
def can_id(self, can_id):
"""Fill the MessageId with the information given in the 29 bit CAN-Id"""
self.source_address = can_id & 0xFF
self.parameter_group_number = (can_id >> 8) & 0x3FFFF
self.priority = (can_id >> 26) & 0x7
| """Transforms the MessageId object to a 29 bit CAN-Id"""
return (self.priority << 26) | (self.parameter_group_number << 8) | (self.source_address) |
utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import copy
import inspect
import logging.config
import os
import sys
import warnings
from dataclasses import dataclass
from os.path import dirname, join, normpath, realpath
from traceback import print_exc, print_exception
from types... |
def get_args_parser() -> argparse.ArgumentParser:
from .. import __version__
parser = argparse.ArgumentParser(add_help=False, description="Hydra")
parser.add_argument("--help", "-h", action="store_true", help="Application's help")
parser.add_argument("--hydra-help", action="store_true", help="Hydra'... | from hydra.core.plugins import Plugins
from hydra.plugins.completion_plugin import CompletionPlugin
completion_plugins = Plugins.instance().discover(CompletionPlugin)
completion_info: List[str] = []
for plugin_cls in completion_plugins:
assert issubclass(plugin_cls, CompletionPlugin)
... |
he.js | ๏ปฟ
CKEDITOR.plugins.setLang( 'placeholder', 'he',
{
placeholder :
{
title : 'ืืืคืืื ื ืฉืืืจ ืืงืื',
toolbar : 'ืฆืืจ ืฉืืืจ ืืงืื', | }
}); | text : 'ืชืืื ืฉืืืจ ืืืงืื',
edit : 'ืขืจืื ืฉืืืจ ืืงืื',
textMissing : 'ืฉืืืจ ืืืงืื ืืืื ืืืืื ืืงืกื.' |
affinity_test.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 may not use this fi... | assert.False(t, configured)
assert.NotNil(t, err)
}
func TestConfigureDisabledAffinityTraitFails(t *testing.T) {
affinityTrait, environment, _ := createNominalAffinityTest()
affinityTrait.Enabled = new(bool)
configured, err := affinityTrait.Configure(environment)
assert.False(t, configured)
assert.Nil(t, err)
... | |
node_modify_responses.go | // Code generated by go-swagger; DO NOT EDIT.
package cluster
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/netapp/trident/stora... | () *NodeModifyAccepted {
return &NodeModifyAccepted{}
}
/* NodeModifyAccepted describes a response with status code 202, with default header values.
Accepted
*/
type NodeModifyAccepted struct {
Payload *models.JobLinkResponse
}
func (o *NodeModifyAccepted) Error() string {
return fmt.Sprintf("[PATCH /cluster/node... | NewNodeModifyAccepted |
test.go | package main
import (
sw "./go-petstore"
"encoding/json"
"fmt"
)
func | () {
s := sw.NewPetApi()
// test POST(body)
newPet := (sw.Pet{Id: 12830, Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"})
jsonNewPet, _ := json.Marshal(newPet)
fmt.Println("newPet:", string(jsonNewPet))
s.AddPet(newPet)
// test POST(form)
s.UpdatePetWithForm(12830, ... | main |
actions.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | try {
await this.triggerAndDisposeAction(instantiationService, lifecycleService, descriptor, args);
} catch (error) {
notificationService.error(error);
}
};
}
private async triggerAndDisposeAction(instantiationService: IInstantiationService, lifecycleService: ILifecycleService, descriptor: SyncAct... | const instantiationService = accessor.get(IInstantiationService);
const lifecycleService = accessor.get(ILifecycleService);
|
app.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { JwtModule } from '@auth0/angular-jwt';
import { RoutingModule } from './routing.module';
import { SharedModule } from './shared/shared.module';
import { CatService } from './services/cat.service';
import { UserService } from './services/user.se... | { }
| AppModule |
Latex_generator.py | # Copyright (c) 2022, Leonardo Lamanna
# All rights reserved.
# This source code is licensed under the MIT-style license found in the
# LICENSE file in the root directory of this source tree.
import pandas as pd
import os
pd.options.display.max_colwidth = 100
def | (data_file, labels, tab_name, caption, header):
with open(tab_name + ".tex", "w") as f:
df = pd.read_excel(data_file, sheet_name="Summary")
df_restricted = df[labels]
f.write(df_restricted.to_latex(index=False, escape=False,
label="tab:{}".format(tab_n... | generate_latex_table |
model.py | import logging
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass, field
from typing import (
Callable,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union
)
from sciencebeam_trainer_delft.se... | (
tag_result: List[Tuple[str, str]]
) -> Iterable[Tuple[str, str]]:
tokens, labels = zip(*tag_result)
LOGGER.debug('tokens: %s', tokens)
LOGGER.debug('labels: %s', labels)
for tag, start, end in get_entities_including_other(list(labels)):
yield tag, ' '.join(tokens[start:end + 1])
def iter... | iter_entity_values_predicted_labels |
health.rs | use crate::cache::cache_operations::CacheResponse;
use crate::utils::context::Context;
use crate::utils::errors::ApiResult;
use rocket::response::content;
#[get("/health")]
pub fn health(context: Context) -> ApiResult<content::Json<String>> | {
CacheResponse::new(String::from("/health"))
.resp_generator(|| Ok(String::new()))
.execute(context.cache())
} | |
test_browser_play_youtube_video.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette.by import By
from gaiatest import GaiaTestCase
from gaiatest.apps.browser.app import Browser
from gaiate... | (self):
GaiaTestCase.setUp(self)
self.connect_to_network()
def test_play_youtube_video(self):
"""Confirm YouTube video playback
https://moztrap.mozilla.org/manage/case/6073/
"""
browser = Browser(self.marionette)
browser.launch()
browser.go_to_url(se... | setUp |
core.py | """
* SearchAThing.UnitTest, Copyright(C) 2015-2017 Lorenzo Delana, License under MIT
*
* The MIT License(MIT)
* Copyright(c) 2015-2017 Lorenzo Delana, https://searchathing.com
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "So... |
if __name__ == '__main__':
unittest.main()
| self.assertTrue(equals_tol(1e-6, to_deg(.21294), 12.200563))
self.assertTrue(equals_tol(1e-6, to_rad(140.3), 2.448697)) |
main.rs | // DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate ... |
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
... | {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("... |
client.py | # -*- coding: utf-8 -*-
# Copyright 2020 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... | (type):
"""Metaclass for the AlertPolicyService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
_transport_registry = (
OrderedDict()
) # type: Dict[str, Type[AlertPolicyServi... | AlertPolicyServiceClientMeta |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.