file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
consumer.go
package meter import ( "encoding/json" "github.com/pkg/errors" ) // consumer should be a component that process response and failure type consumer interface { processResponse(bg *background) next processFailure(bg *background, err error) next } // defaultConsumerType will continue test no matter what type defau...
{ d := &dynamicConsumer{} d.decision = failAction var err error d.check, _, err = makeComposable(check) if err != nil { return nil, err } d.success, _, err = makeComposable(s...
ims_token.go
/******************************************************************************* * IBM Confidential * OCO Source Materials * IBM Cloud Container Service, 5737-D43 * (C) Copyright IBM Corp. 2018, 2019 All Rights Reserved. * The source code for this program is not published or otherwise divested of * its trade sec...
(iamAccountID string, iamAccessToken *iam.AccessToken) provider.ContextCredentials { return provider.ContextCredentials{ AuthType: IAMAccessToken, IAMAccountID: iamAccountID, Credential: iamAccessToken.Token, } }
forIAMAccessToken
fake_api.py
# coding: utf-8 """ Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \...
(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): config = Configuration() if api_client: self.api_clien...
FakeApi
base.rs
use crate::back::metadata::create_compressed_metadata_file; use crate::back::write::{ compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen, }; use crate::common::{IntPredicate, RealPredicate...
| (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => { assert_eq!(bx.cx().type_is_sized(a), old_info.is_none()); let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b))); (bx.pointercast(src, ptr_ty), unsized_info(bx,...
) -> (Bx::Value, Bx::Value) { debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty); match (src_ty.kind(), dst_ty.kind()) { (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
test_vizplugin.py
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/gaogaotiantian/viztracer/blob/master/NOTICE.txt from contextlib import redirect_stdout import io from .cmdline_tmpl import CmdlineTmpl from viztracer import VizTracer from viztracer.vizplugin import VizPl...
(CmdlineTmpl): def test_basic(self): pl = MyPlugin() tracer = VizTracer(plugins=[pl]) tracer.start() tracer.stop() tracer.save() self.assertEqual(pl.event_counter, 4) self.assertEqual(pl.handler_triggered, True) def test_invalid(self): invalid_pl ...
TestVizPlugin
pe011.rs
//! This is a solution to [Project Euler Problem 11](https://projecteuler.net/problem=11). use std::cmp::max; use std::fmt::Display; use std::str; const DATA: &[u8] = include_bytes!("pe011-data.txt"); enum Direction { South, East, NorthEast, SouthEast, } struct Grid { data: Vec<Vec<usize>>, } i...
fn problem(n: usize) -> usize { let data: &str = str::from_utf8(DATA).unwrap(); let grid = Grid::from(data); // East going lines starting from column 0 let east = (0..n).map(|row_idx| grid.line(row_idx, 0, &Direction::East)); // South going lines starting from row 0 let south = (0..n).map(|c...
{ problem(20) }
controllers.js
(function() { 'use strict'; var mesosApp = angular.module('mesos'); function hasSelectedText() { if (window.getSelection) { // All browsers except IE before version 9. var range = window.getSelection(); return range.toString().length > 0; } return false; } // Invokes the pailer for...
$top.start(host, $scope); } $http.jsonp('/mesos/slave/' + $routeParams.slave_id + '/' + id + '/state.json?jsonp=JSON_CALLBACK') .success(function (response) { $scope.state = response; $scope.slave = {}; $scope.slave.frameworks = {}; $scope.slave.comp...
}; // Set up polling for the monitor if this is the first update. if (!$top.started()) {
imaplib2.py
#!/usr/bin/env python """Threaded IMAP4 client. Based on RFC 3501 and original imaplib module. Public classes: IMAP4 IMAP4_SSL IMAP4_stream Public functions: Internaldate2Time ParseFlags Time2Internaldate """ __all__ = ("IMAP4", "IMAP4_SSL"...
(self, **kw): """(typ, [data]) = noop() Send NOOP command.""" if __debug__: self._dump_ur(3) return self._simple_command('NOOP', **kw) def partial(self, message_num, message_part, start, length, **kw): """(typ, [data, ...]) = partial(message_num, message_part, start, lengt...
noop
ht16k33.py
class HT16K33: def __init__(self, i2, a = 0x70): self.i2 = i2 self.a = a self.command(0x21) # Clock on self.command(0x81) # Display on self.bright(15) self.load([0] * 16) def bright(self, n): assert 0 <= n < 16 self.command(0xe0 + n) ...
self.i2.start(self.a, 0) self.i2.write([0] + b128) self.i2.stop()
validate_secure_metadata.py
#!/usr/bin/env python3 # # Copyright (c) 2020, Somia Reality Oy # All rights reserved. # Installing dependencies: # # - Ubuntu/Debian: apt install python3-cryptography python3-jwcrypto # - Using pip: pip3 install cryptography jwcrypto from argparse import ArgumentParser from base64 import b64decode, urlsafe_b64de...
def unpadded_urlsafe_b64decode(unpadded_str): unpadded_bytes = unpadded_str.encode() padded_bytes = unpadded_bytes + (b"", None, b"==", b"=")[len(unpadded_bytes) & 3] return urlsafe_b64decode(padded_bytes) def main(): time_format = "%Y-%m-%dT%H:%M:%SZ" time_example = datetime.utcnow().strftime(...
block_len = AES.block_size // 8 assert len(iv_ciphertext) >= 2 * block_len assert (len(iv_ciphertext) % block_len) == 0 iv = iv_ciphertext[:block_len] ciphertext = iv_ciphertext[block_len:] algo = AES(key_bytes) mode = CBC(iv) c = Cipher(algo, mode, default_backend()) d = c.decrypto...
launcher.py
#!/usr/bin/env python # pylint: disable=invalid-name """The container launcher script that launches DMLC with the right env variable.""" import glob import sys import os import subprocess def unzip_archives(ar_list, env): for fname in ar_list: if not os.path.exists(fname): continue if f...
env['LIBHDFS_OPTS'] = env['DMLC_HDFS_OPTS'] elif 'LIBHDFS_OPTS' not in env: env['LIBHDFS_OPTS'] = '--Xmx128m' LD_LIBRARY_PATH = env['LD_LIBRARY_PATH'] if 'LD_LIBRARY_PATH' in env else '' env['LD_LIBRARY_PATH'] = LD_LIBRARY_PATH + ':' + ':'.join(library_path) # unzip the archives. i...
# setup hdfs options if 'DMLC_HDFS_OPTS' in env:
main.py
# this file was created by Chris Cozort # Sources: goo.gl/2KMivS # now available in github ''' Curious, Creative, Tenacious(requires hopefulness) Game ideas: Walls closing in on player ''' import pygame as pg import random from settings import * from sprites import * from os import path class Game: def __init_...
while waiting: self.clock.tick(FPS) for event in pg.event.get(): if event.type == pg.QUIT: waiting = False self.running = False if event.type ==pg.KEYUP: waiting = False def show_start_screen(...
# double buffering - renders a frame "behind" the displayed frame pg.display.flip() def wait_for_key(self): waiting = True
ogr_shape.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Shapefile driver testing. # Author: Frank Warmerdam <warmerdam@pobox.com> # ###############################################################...
gdaltest.post_reason('fail') print(f.GetGeometryRef().ExportToIsoWkt()) return 'fail' ds = None ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('/vsimem/ogr_shape_96.shp') return 'success' ############################################################################### # Tes...
f = lyr.GetNextFeature() if f.GetGeometryRef().ExportToIsoWkt() != 'POINT M (1 2 4)':
main.go
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
// [END recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_sync]
{ // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } req := &recommendationenginepb.WriteUserEventRequest{ // TODO:...
[id].tsx
import { NextApiRequest, NextApiResponse } from "next"; // eslint-disable-next-line import/no-anonymous-default-export export default (request: NextApiRequest, response: NextApiResponse) => { console.log(request.query); const users = [ { id: 1, name: 'João' },
{ id: 2, name: 'Diego' }, { id: 3, name: 'Lucas' }, { id: 4, name: 'Mathues' }, ] return response.json(users); }
txn_speed.rs
use diesel::PgConnection; use std::{collections::HashMap, thread::sleep, time::Duration}; use graph::prelude::anyhow; use graph_store_postgres::connection_pool::ConnectionPool; use crate::manager::catalog; pub fn run(pool: ConnectionPool, delay: u64) -> Result<(), anyhow::Error>
{ fn query(conn: &PgConnection) -> Result<Vec<(String, i64, i64)>, anyhow::Error> { use catalog::pg_catalog::pg_stat_database as d; use diesel::dsl::*; use diesel::sql_types::BigInt; use diesel::{ExpressionMeth...
nist_xray_tran_en_db_converter.py
import json import sys import os from tqdm import tqdm from mdf_refinery.validator import Validator from mdf_refinery.parsers.tab_parser import parse_tab # VERSION 0.3.0 # This is the converter for the NIST X-Ray Transition Energies Database # Arguments: # input_path (string): The file or directory where the data...
"email": "lawrence.hudson@nist.gov", "institution": "National Institute of Standards and Technology" }, # "author": , # "license": , "collection": "NIST X-Ray Transition Energies", "tags": ["Radiation", "Spectroscopy", "Re...
admission_test.go
/* Copyright 2015 The Kubernetes 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 applicable law or ag...
(t *testing.T) { namespaceObj := &api.Namespace{ ObjectMeta: api.ObjectMeta{ Name: "test", Namespace: "", }, Status: api.NamespaceStatus{ Phase: api.NamespaceActive, }, } store := cache.NewStore(cache.MetaNamespaceKeyFunc) store.Add(namespaceObj) fakeWatch := watch.NewFake() mockClient := &...
TestAdmission
cmp.rs
//! Functionality for ordering and comparison. //! //! This module contains various tools for ordering and comparing values. In //! summary: //! //! * [`Eq`] and [`PartialEq`] are traits that allow you to define total and //! partial equality between values, respectively. Implementing them overloads //! the `==` an...
fn lt(&self, other: &$t) -> bool { (*self) < (*other) } #[inline] fn le(&self, other: &$t) -> bool { (*self) <= (*other) } #[inline] fn ge(&self, other: &$t) -> bool { (*self) >= (*other) } #[inline] fn gt(&s...
fn partial_cmp(&self, other: &$t) -> Option<Ordering> { Some(self.cmp(other)) } #[inline]
main.rs
// Copyright 2019 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. // TODO Follow 2018 idioms #![allow(elided_lifetimes_in_paths)] use { anyhow::Error, component_manager_lib::{ builtin_environment::{Builti...
/// Loads component_manager's config. /// /// This function panics on failure because the logger is not initialized yet. fn build_runtime_config() -> RuntimeConfig { let args = match startup::Arguments::from_args() { Ok(args) => args, Err(err) => { panic!("{}\n{}", err, startup::Argume...
{ // Make sure we exit if there is a panic. Add this hook before we init the // KernelLogger because it installs its own hook and then calls any // existing hook. panic::set_hook(Box::new(|_| { println!("Panic in component_manager, aborting process."); // TODO remove after 4367...
mc-water.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use lumol::input::Input; use lumol::units; use std::path::Path; use std::sync::Once; static START: Once = Once::new(); mod utils; // This test only run a Monte Carlo simulation of water, but do not test // anythin...
{ START.call_once(::env_logger::init); let path = Path::new(file!()).parent() .unwrap() .join("data") .join("mc-water") .join("npt-ewald.toml"); let mut config = Input::new(p...
ald_npt()
device_handle_outlives_context.rs
extern crate libusb; fn main()
{ let mut handle = { let mut context = libusb::Context::new().unwrap(); let devices = context.devices().unwrap(); // ~ERROR: does not live long enough let mut dev = devices.iter().next().unwrap(); dev.open().unwrap() }; handle.active_configuration(); }
augmented-assignments-feature-gate.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut x = Int(0); x += 1; }
main
forecast-compare.component.ts
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core'; import { SelectionModel } from '@angular/cdk/collections'; import { MatTableDataSource } from '@angular/material/table'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { Top...
implements OnInit, AfterViewInit { @ViewChild('btnBar') btnBar: TopBtnGroupComponent; itemList = []; selectedItems = []; settings = {}; itemListB = []; selectedItemsB = []; settingsB = {}; count = 6; actionGroupConfig; filter: boolean = false; IsTosca: boolean; displayedColumns = ['Status', 'Sa...
ForecastCompareComponent
ToastAction.tsx
import { rem, themed } from '@heathmont/moon-utils'; import styled from 'styled-components'; const ToastAction = styled.p<{ actionColor: any }>( ({ actionColor, theme }) => ({
fontSize: rem(14), lineHeight: rem(20), fontWeight: theme.fontWeight.semibold, }) ); export default ToastAction;
display: 'block', color: themed('color', actionColor)(theme) || theme.colorNew.hit,
oslogin_test.go
// Copyright 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by appl...
(t *testing.T) { challengeResponseEnable := "ChallengeResponseAuthentication yes" authorizedKeysCommand := "AuthorizedKeysCommand /usr/bin/google_authorized_keys" authorizedKeysUser := "AuthorizedKeysCommandUser root" twoFactorAuthMethods := "AuthenticationMethods publickey,keyboard-interactive" matchblock1 := `Ma...
TestUpdateSSHConfig
main.js
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.ex...
(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized...
bnpCopyTo
mod.rs
use crate::{ binding_model, command, conv, device::life::WaitIdleError, hub::{Global, GlobalIdentityHandlerFactory, HalApi, Hub, Input, InvalidId, Storage, Token}, id, init_tracker::{ BufferInitTracker, BufferInitTrackerAction, MemoryInitKind, TextureInitRange, TextureInitTracker, Te...
fn dispose(self, device: &A::Device) { log::info!("Destroying {} command encoders", self.free_encoders.len()); for cmd_encoder in self.free_encoders { unsafe { device.destroy_command_encoder(cmd_encoder); } } } } /// Structure describing a logic...
{ self.free_encoders.push(encoder); }
status.ts
import { createLogger } from '@unly/utils-simple-logger'; import { NextApiRequest, NextApiResponse, } from 'next';
const logger = createLogger({ label: fileLabel, }); export const status = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => { try { configureReq(req); res.json({ appStage: process.env.NEXT_PUBLIC_APP_STAGE, appName: process.env.NEXT_PUBLIC_APP_NAME, appVersion: process....
import Sentry, { configureReq } from '../../utils/monitoring/sentry'; const fileLabel = 'api/status';
general_test.go
// Copyright 2019 The Go Language Server Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package protocol import ( "fmt" "path/filepath" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "go.lsp...
t.Parallel() var got TypeDefinitionRegistrationOptions if err := unmarshal([]byte(tt.field), &got); (err != nil) != tt.wantUnmarshalErr { t.Fatal(err) } if diff := cmp.Diff(got, tt.want); (diff != "") != tt.wantErr { t.Errorf("%s: wantErr: %t\n(-got, +want)\n%s", tt.name, tt.wantErr, dif...
for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) {
project.rs
use crate::options::{self, BuildOptions, Sanitizer}; use crate::utils::default_target; use anyhow::{anyhow, bail, Context, Result}; use std::collections::HashSet; use std::io::Read; use std::io::Write; use std::path::{Path, PathBuf}; use std::{ env, ffi, fs, process::{Command, Stdio}, time, }; pub struct F...
-> PathBuf { self.path().join("Cargo.toml") } /// Returns paths to the `coverage/<target>/raw` directory and `coverage/<target>/coverage.profdata` file. fn coverage_for(&self, target: &str) -> Result<(PathBuf, PathBuf)> { let mut coverage_data = self.path(); coverage_data.push("cove...
_path(&self)
FinalModelUUID.go
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: FBE // Version: 1.4.0.0 package fbe import "errors" // Fast Binary Encoding UUID final model type FinalModelUUID struct { // Final model buffer buffer *Buffer // F...
// Get the UUID value func (fm *FinalModelUUID) Get() (UUID, int, error) { if (fm.buffer.Offset() + fm.FBEOffset() + fm.FBESize()) > fm.buffer.Size() { return UUIDNil(), 0, errors.New("model is broken") } return ReadUUID(fm.buffer.Data(), fm.buffer.Offset() + fm.FBEOffset()), fm.FBESize(), nil } ...
return fm.FBESize() }
listeners.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: Pin<&mut Self>, cx: &mut Context) -> Poll<ListenersEvent<TTrans>> { // We remove each element from `listeners` one by one and add them back. let mut remaining = self.listeners.len(); while let Some(mut listener) = self.listeners.pop_back() { let mut listener_project = list...
poll
auth.ts
import { PLuginFunction, HttpError, Sact } from '@sact/core'; import { SessionReq, SessionRes, MemoryStore } from '@sact/session'; import { RedisStore } from '@sact/session/src'; import * as jwt from 'jsonwebtoken'; export interface Options { /** * secret for jwt token */ secret?: string; tokenName?: strin...
/** * Authenticate the user or throw a 401 status if failed * * ```typescript * await req.authenticateOrFail() // 👈 All you need to do, the user will then be available on req.user * ``` */ authenticateOrFail: () => Promise<void>; } const verify = ( token: string, secret: string ): Promise<{...
*/ authenticate: () => Promise<void>;
get_asa_full_config.py
#!/usr/bin/python3 # BY NOMO from netmiko import Netmiko from getpass import getpass from datetime import datetime from pprint import pprint import re import os import sys import socket # Vars config_dir = "/home/reponeg/logs/asa_configs" # Function for DNS resolution def
(hostname): try: socket.gethostbyname(hostname) return 1 # If lookup works except socket.error: return 0 # If lookup fails def getShowRun(connection_handle, context, dirname): output = connection_handle.send_command("changeto context " ...
hostnameLookup
forward.rs
use crate::{Error, Result}; use futures::FutureExt; use std::num::NonZeroUsize; use tokio::{ io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, net::TcpStream, }; async fn forward_reader_to_writer<R, W>(mut reader: R, mut writer: W) -> Result<()> where R: AsyncRead + Unpin, W: AsyncWrite + Unpin...
pub async fn forward_socket(client: TcpStream, server: TcpStream) -> Result<()> { let (client_reader, client_writer) = tokio::io::split(client); let (server_reader, server_writer) = tokio::io::split(server); let client_to_server = forward_reader_to_writer(client_reader, server_writer).fuse(); let ser...
{ let mut buf = vec![0u8; 4096]; let bytes_read = reader.read(&mut buf).await.map_err(Error::from_io_error)?; while let Some(count) = NonZeroUsize::new(bytes_read) { writer .write_all(&buf[0..count.get()]) .await .map_err(Error::from_io_error)?; } Ok(()...
test_tracker_stores.py
import pytest from rasa.core.channels.channel import UserMessage from rasa.core.domain import Domain from rasa.core.events import SlotSet, ActionExecuted, Restarted from rasa.core.tracker_store import ( TrackerStore, InMemoryTrackerStore, RedisTrackerStore, SQLTrackerStore, ) from rasa.utils.endpoints ...
expected = "postgresql://localhost:5005/mydb" assert ( str( SQLTrackerStore._get_db_url( dialect="postgresql", host="localhost", port=5005, db="mydb" ) ) == expected )
pagination.utils.ts
import { PaginationComponentOptions } from './pagination-component-options.model'; import { FindListOptions } from '../../core/data/find-list-options.model'; /** * Transform a PaginationComponentOptions object into a FindListOptions object * @param pagination The PaginationComponentOptions to transform * @param or...
(pagination: PaginationComponentOptions, original?: FindListOptions): FindListOptions { return Object.assign(new FindListOptions(), original, { currentPage: pagination.currentPage, elementsPerPage: pagination.pageSize }); }
toFindListOptions
openapi_generated.go
// +build !ignore_autogenerated /* Copyright 2019 The Tekton 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 l...
"apiversion": { SchemaProps: spec.SchemaProps{ Type: []string{"string"}, Format: "", }, }, "spec": { SchemaProps: spec.SchemaProps{ Ref: ref("github.com/tektoncd/triggers/pkg/apis/triggers/v1beta1.TriggerTemplateSpec"), }, }, }, }, }, Depende...
},
mod.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use collections::HashMap; use crate::recorder::localstorage::LocalStorage; use crate::RawRecords; pub mod cpu; pub mod summary; /// This trait defines a general framework that works at a certain frequency. Typically, /// it describes the recorder(sa...
fn thread_created(&mut self, _id: usize, _store: &LocalStorage) {} }
/// to be performed on all functions, and `SubRecorder` may wish to maintain /// a thread-related data structure by itself.
aws_ec2_test.go
package e2e_test import ( "context" "fmt" "io/ioutil" "net/http" "os" "strings" "github.com/solo-io/gloo/test/helpers" "github.com/solo-io/solo-kit/pkg/api/v1/resources" "github.com/aws/aws-sdk-go/aws/credentials" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/rotisserie/eris" gloov1 ...
Name: "listener", BindAddress: "::", BindPort: defaults.HttpPort, ListenerType: &gloov1.Listener_HttpListener{ HttpListener: &gloov1.HttpListener{ VirtualHosts: []*gloov1.VirtualHost{{ Name: "virt1", Domains: []string{"*"}, Routes: []*gloov1.Route{{ A...
Recipe.tsx
import { useEffect, useState } from "react"; import sanityClient from "../client"; interface IRecipe { title: string; recipeName: string; recipeDesc: string; recipeImage: { asset: { _id: string; url: string } }[]; recipeVideo: string; recipePart: string; recipeToDo: string; recipeIngredients: { ing...
<div className="divide-blue-600"> <h3 className="w-full text-3xl text-center">FREMGANGSMÅTE:</h3> <hr className="w-3/5 mx-auto mb-5" /> <iframe title="video" className="w-full h-[40rem] mb-16" src={codHead.recipeVideo}...
js.js
var inputAction = ""; var display = document.getElementById('display').value; //SAIDA PARA DISPLAY function output(){ var display = document.getElementById('display').value; if (display == "0"){display = "";} //LIMPAR TODOS OS CARACTERES if (inputAction == "limpar"){ display = "0" inputAction = ""...
output(); } function b5(){ inputAction = "5"; output(); } function b6(){ inputAction = "6"; output(); } function b7(){ inputAction = "7"; output(); } function b8(){ inputAction = "8"; output(); } function b9(){ inputAction = "9"; output(); } function b0(){ inputAction = "0"; output(...
inputAction = "4";
cli.py
# pylint: disable-msg=W0613,W0612,W0212,W0511,R0912,C0322,W0704 # W0511 = XXX (my own todo's) """ cli.py ====== Desc: Command-line tool for listing Python packages installed by setuptools, package metadata, package dependencies, and querying The Cheese Shop (PyPI) for Python package release information s...
(self, attribute): if not self.__dict__.has_key(attribute) or attribute == '__doc__': return getattr(self.stdout, attribute) return self.__dict__[attribute] def flush(self): """Bug workaround for Python 3.2+: Exception AttributeError: 'flush' in <yolk.cli.StdOut object....
__getattr__
function.rs
use super::{Context, IntoValue, Local, V8}; use V8::Function; impl Local<Function> { pub fn call( &mut self, context: Local<Context>, recv: &IntoValue, argv: Vec<&IntoValue>, ) -> Local<V8::Value> { let argc = argv.len() as i32;
.Call( context.into(), recv.into_value().into(), argc, argv.as_mut_ptr(), ) .to_local_checked() .unwrap() } } }
let mut argv: Vec<V8::Local<V8::Value>> = argv.iter().map(|&arg| arg.into_value().into()).collect(); unsafe { self.inner_mut()
process.rs
// Copyright 2012-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-MI...
match create_err { Some(err) => return Err(err), None => {} } // We close the thread handle because we don't care about keeping the // thread id valid, and we aren't keeping the thread handle around to be // able to close it later. We don't close the proc...
if err_fd != -1 { assert!(CloseHandle(si.hStdError) != 0); }
errors.rs
use std::convert::Into; use std::error::Error as StdError; use std::fmt; /// The kind of an error (non-exhaustive) #[derive(Debug)] pub enum ErrorKind { /// Generic error Msg(String), /// A loop was found while looking up the inheritance chain CircularExtend { /// Name of the template with the ...
Self { kind: ErrorKind::CircularExtend { tpl: tpl.to_string(), inheritance_chain }, source: None, } } /// Creates a missing parent error pub fn missing_parent(current: impl ToString, parent: impl ToString) -> Self { Self { kind: ErrorKind::Missing...
pub fn circular_extend(tpl: impl ToString, inheritance_chain: Vec<String>) -> Self {
VideoEncoderIncomingStreamTrack.js
const uuidV4 = require("uuid/v4"); const Native = require("./Native"); const EventEmitter = require("events").EventEmitter; class
{ /** * @ignore * @hideconstructor * private constructor */ constructor(id,receiver,source) { //Create new id this.id = id || uuidV4(); //Store track info this.media = "video"; this.receiver = receiver; //Attach counter this.counter = 0; //Create source map this.encodings = new Map(); ...
VideoEncoderIncomingStreamTrack
lib.rs
mod event; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::LookupMap; use near_sdk::{AccountId, env, near_bindgen, BorshStorageKey}; #[derive(BorshStorageKey, BorshSerialize)] enum StorageKey { Records } #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub str...
#[test] fn get_nonexistent_message() { let context = get_context(); testing_env!(context.build()); let contract = StatusMessage::default(); assert_eq!(None, contract.get_status(accounts(4))); } }
{ let context = get_context(); testing_env!(context.build()); let mut contract = StatusMessage::default(); contract.set_status("hello".to_string()); assert_eq!( "hello".to_string(), contract.get_status(accounts(2)).unwrap() ...
views.py
#!/usr/bin/env python
from snapshot import * from log import *
# coding=utf8 from flask import Blueprint running = Blueprint('running', __name__)
bitcoin_be_BY.ts
<TS language="be_BY" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Правы клік, каб рэдагаваць адрас ці метку</translation> </message> <message> <source>Create a new address</source> <tran...
<source>Copy amount</source> <translation>Капіяваць колькасць</translation> </message> <message> <source>Copy fee</source> <translation>Капіяваць камісію</translation> </message> <message> <source>Copy after fee</source> <translation>Капіяваць з выняткам к...
<message>
display.stories.tsx
import React from 'react'; import { storiesOf } from '@storybook/react'; import { Display } from './display'; import { Property } from 'interfaces/Property'; // import more addons const story = storiesOf('Products.Display', module); const mockProperty: Property[] = [ { name: 'Rumah 1', address: '...
price: 200, area: 125, }, { name: 'Rumah 2', address: 'Jalan apartment 2', propertyType: 'apartment', saleType: 'rent', imgs: [ { image: 'https://res.cloudinary.com/dsvdffre0/image/upload/v1597137791/jacques...
], description: 'Deskripsi bum bum bum', location: 'Penang',
markdown_it_extensions.py
# # VAZ Projects # # # Author: Marcelo Tellier Sartori Vaz <marcelotsvaz@gmail.com> from functools import partial import re from django.template import loader def linkAttributes( self, tokens, index, options, env ): ''' Add target and rel attributes to links. ''' tokens[index].attrSet( 'rel', 'noopener'...
cssClasses = match[1] identifiers = match[2] if not silent: state.line = startLine + 1 if identifiers.strip() == '*': images = markdownImages else: identifiers = { identifier.strip() for identifier in identifiers.split( ',' ) } images = [ image for image in markdownImages if image.identifier i...
return False
mklldeps.py
# Copyright 2013-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-MIT or ht...
(args): proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() if err: print("failed to run llconfig: args = `{}`".format(args)) print(err) sys.exit(1) return out for llconfig in sys.argv[4:]: f.write("\n") out = run...
run
preprocessing_images.py
#Copyright 2021 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
# #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 permissions and #limitations under the License. #...
# # https://www.apache.org/licenses/LICENSE-2.0
group.py
# # ⚠ Warning # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT # LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA...
taticmethod def from_layout(layout: typing.Any) -> "GroupSlotSpotMarket": spot_market: PublicKey = layout.spot_market maint_asset_weight: Decimal = round(layout.maint_asset_weight, 8) init_asset_weight: Decimal = round(layout.init_asset_weight, 8) maint_liab_weight: Decimal = round(l...
ress: PublicKey = address self.maint_asset_weight: Decimal = maint_asset_weight self.init_asset_weight: Decimal = init_asset_weight self.maint_liab_weight: Decimal = maint_liab_weight self.init_liab_weight: Decimal = init_liab_weight @s
sorting.go
//we sort numbers using a heap package heapsort var index int var size int = 10 var numbers [10]int var global_heap [1000]int var global_heapSize int func main(){ numbers[0] = 0 numbers[1] = 17 numbers[2] = 13 numbers[3] = 8 numbers[4] = 79 numbers[5] = 65 numbers[6] = 44 numbers[7] = 72 numbers[8] ...
sorted = append(sorted, global_heap[1]) global_heap[1] = global_heap[global_heapSize] global_heapSize-- keepLooping = true current = 1 for keepLooping { if current * 2 <= global_heapSize && global_heap[current] < global_heap[current*2] { temp = global_heap[current] global_...
for global_heapSize > 0 {
connector-line.ts
import { createElement, isNullOrUndefined, isObject, remove } from '@syncfusion/ej2-base'; import { Gantt } from '../base/gantt'; import * as cls from '../base/css-constants'; import { IGanttData, ITaskData, IConnectorLineObject, IPredecessor } from '../base/interface'; import { isScheduledTask } from '../base/utils'; ...
connectorObj.connectorLineId = 'parent' + parentId + 'child' + childId; connectorObj.milestoneParent = parentGanttRecord.isMilestone ? true : false; connectorObj.milestoneChild = childGanttRecord.isMilestone ? true : false; if (isNullOrUndefined(isScheduledTask(parentGant...
const childId: string = this.parent.viewType === 'ResourceView' ? childGanttRecord.taskId : childGanttRecord.rowUniqueID;
regexremapdotconfig_test.go
package atscfg /* * 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 * ...
}
{ t.Errorf("expected: regex remap to replace __RETURN__ with newline, actual: '%v'", txt) }
space.rs
use model::{Space, NewSpace}; use managers::db_manager::*; use schema::spaces::dsl::*; use diesel::{LoadDsl, FilterDsl, ExpressionMethods, ExecuteDsl}; use diesel::result::Error; use diesel::result::Error::{NotFound, DatabaseError}; use diesel::result::DatabaseErrorKind::UniqueViolation; use diesel; use std::ops::Deref...
.execute(db.deref()); None } }
diesel::delete(spaces.filter(public.eq(true)) .filter(name.eq(&space_name)))
strings.go
package conditions import ( "fmt" "reflect" "strings" shipper "github.com/bookingcom/shipper/pkg/apis/shipper/v1alpha1" ) func
(ci interface{}) string { if ci == nil || reflect.ValueOf(ci).IsNil() { return "" } var chunks []string switch c := ci.(type) { case *shipper.ApplicationCondition: chunks = []string{ fmt.Sprintf("%v", c.Type), fmt.Sprintf("%v", c.Status), c.Reason, c.Message, } case *shipper.ReleaseCondition: ...
CondStr
lib.deno.ns.d.ts
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. /// <reference no-default-lib="true" /> /// <reference lib="esnext" /> declare namespace Deno { /** A set of error constructors that are raised by Deno APIs. */ export const errors: { NotFound: ErrorConstructor; PermissionDenied: E...
* * Requires `allow-write` permission. */ export function chmodSync(path: string, mode: number): void; /** Changes the permission of a specific file/directory of specified path. * Ignores the process's umask. * * ```ts * await Deno.chmod("/path/to/file", 0o666); * ``` * * The mode is a s...
* * For a full description, see [chmod](#chmod) * * NOTE: This API currently throws on Windows
rdf.py
# !/usr/bin/env python # -*-coding:utf-8-*- """ @author: xhades @Date: 2017/12/28 """ # 随机森林分类器 import numpy as np from numpy import * from numpy import array, argmax from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import pickle from sklearn.ensemble import Random...
xFile, "rb") as file_r: X = pickle.load(file_r) X = reshape(X, (212841, -1)) # reshape一下 (212841, 30*128) # 读取label数据,并且encodig with open(yFile, "r") as yFile_r: labelLines = [_.strip("\n") for _ in yFile_r.readlines()] values = array(labelLines) labelEncoder = LabelEncoder() ...
open(
fabfile.py
from fabric.api import cd, env, lcd, local, hosts, prompt, run from fabric.decorators import runs_once import os import time env.runtime = 'production' env.hosts = ['newchimera.readthedocs.com', 'newbuild.readthedocs.com', 'newasgard.readthedocs.com'] env.user = 'docs' env.code_dir = '/home/...
@hosts(['newasgard.readthedocs.com', 'newchimera.readthedocs.com']) def postcommit_logs(): env.user = "docs" run("tail -F %s/logs/postcommit.log" % env.code_dir) @hosts(['newasgard.readthedocs.com', 'newchimera.readthedocs.com']) def cat_postcommit_logs(): env.user = "docs" run("cat %s/logs/postcommi...
env.user = "docs" run("tail -F %s/logs/*.log" % env.code_dir)
salesforceConnection.ts
import * as jsforce from 'jsforce'; import * as vscode from 'vscode'; import { SalesforceConfig } from './salesforceConfig'; import { l } from '../strings/Strings'; export class
{ private static validConnection: jsforce.Connection | undefined; private connection: jsforce.Connection; constructor(public config: SalesforceConfig) { const createConnection = () => { if (config.doValidation()) { this.connection = new jsforce.Connection({ loginUrl: config.getOrgani...
SalesforceConnection
template-param-usage-6.rs
/* automatically generated by rust-bindgen */ #![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)]
#[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct DoesNotUseTemplateParameter { pub x: ::std::os::raw::c_int, } pub type DoesNotUseTemplateParameter_ButAliasDoesUseIt<T> = T;
e.go
package e type S struct{} func (s *S) foo() { go func() { // want "no defer" println("foo") }() } func (s S) bar() { go func() { // want "no recover" defer func() { }() println("bar")
}() }
css.js
export default (function CrappyStyleSheets() { const prototype = {}; function property(name, value) { return [name, ':', value, ';'].join(''); } [ 'accelerator', 'animation', 'azimuth', 'background', 'background-attachment', 'background-color', ...
style: function Style(...properties) { pseudo_style.properties = properties; styles.push(pseudo_style); return constructor; } } }; return constructor; }()); ...