file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
lib.rs | //! An Entity Component System for game development.
//!
//! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP.
#![allow(dead_code)]
#![feature(append,drain)]
use std::iter;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
use std::collections::hash_map::... |
pub fn set_family_relation(&mut self, family: &'static str, ent: Entity) {
match self.families.entry(family) {
Vacant(entry) => {entry.insert(vec!(ent));},
Occupied(entry) => {
let v = entry.into_mut();
if v.contains(&ent) { return; }
... | {
let mut idx: Option<usize> = None;
{
let vec = self.families.get_mut(family).expect("No such family");
let op = vec.iter().enumerate().find(|&(_,e)| *e == ent);
idx = Some(op.expect("Entity not found in this family").0);
}
if let Some(idx) = idx {
... | identifier_body |
chat.py | #!/usr/bin/python
#coding:utf8
#python 2.7.6
import threading
import socket
import time
import os
import sys
import signal
from readline import get_line_buffer
BUFSIZE = 1024
BACKPORT = 7789 #状态监听端口
CHATPORT = 7788 #聊天信息发送窗口
class Cmd():
START = '>> '
INIT = '>> '
outmutex = threading.Lock()
... | ():
def gettime(self):
return time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time()))
def getip(self):
ip = os.popen("/sbin/ifconfig | grep 'inet addr' | awk '{print $2}'").read()
ip = ip[ip.find(':')+1:ip.find('\n')]
return ip
def handlebc(self, data):
data =... | self.users = {}
self.ips = {}
self.mutex = threading.Lock()
def add_user(self, name, ip):
if self.mutex.acquire(1):
self.users[name] = ip
self.ips[ip] = name
self.mutex.release()
def has_ip(self, ip):
ret = False
if self.mutex.acquire... | identifier_body |
chat.py | #!/usr/bin/python
#coding:utf8
#python 2.7.6
import threading | import time
import os
import sys
import signal
from readline import get_line_buffer
BUFSIZE = 1024
BACKPORT = 7789 #状态监听端口
CHATPORT = 7788 #聊天信息发送窗口
class Cmd():
START = '>> '
INIT = '>> '
outmutex = threading.Lock()
anoun = True
@classmethod
def output_with_rewrite(self, msg):
... | import socket | random_line_split |
chat.py | #!/usr/bin/python
#coding:utf8
#python 2.7.6
import threading
import socket
import time
import os
import sys
import signal
from readline import get_line_buffer
BUFSIZE = 1024
BACKPORT = 7789 #状态监听端口
CHATPORT = 7788 #聊天信息发送窗口
class Cmd():
START = '>> '
INIT = '>> '
outmutex = threading.Lock()
... | f.listen.start()
self.chatting()
self.back.stop()
self.listen.stop()
sys.exit()
def main():
if len(sys.argv) < 2:
name = socket.getfqdn(socket.gethostname())
else:
name = sys.argv[1]
user_list = UserList()
s = Start(user_list, name)
s.start()
if __n... | if args[0] == 'quit':
if in_chat:
addr = 0
in_chat = False
Cmd.reset_start()
elif args[0] == 'exit':
self.cmd_exit()
elif args[0] == 'list':
... | conditional_block |
chat.py | #!/usr/bin/python
#coding:utf8
#python 2.7.6
import threading
import socket
import time
import os
import sys
import signal
from readline import get_line_buffer
BUFSIZE = 1024
BACKPORT = 7789 #状态监听端口
CHATPORT = 7788 #聊天信息发送窗口
class Cmd():
START = '>> '
INIT = '>> '
outmutex = threading.Lock()
... | r = (self.user_list.get_ip(name), CHATPORT)
Cmd.output('now chatting to ' + name+ \
" ,use ':quit' to quit CHAT mode")
Cmd.set_start(name + Cmd.INIT)
return (addr, False)
def chatting(self):
csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Cmd.output(... | add | identifier_name |
environment.go | /* Environments. */
/*
* Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>)
*
* 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... | found = true
}
} else {
ds := datastore.New()
var e interface{}
e, found = ds.Get("env", envName)
if e != nil {
env = e.(*ChefEnvironment)
}
}
if !found {
err := util.Errorf("Cannot load environment %s", envName)
err.SetStatus(http.StatusNotFound)
return nil, err
}
return env, nil
}
// Do... | }
found = false
} else { | random_line_split |
environment.go | /* Environments. */
/*
* Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>)
*
* 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... | () []*ChefEnvironment {
var environments []*ChefEnvironment
if config.UsingDB() {
environments = allEnvironmentsSQL()
} else {
envList := GetList()
for _, e := range envList {
en, err := Get(e)
if err != nil {
continue
}
environments = append(environments, en)
}
}
return environments
}
| AllEnvironments | identifier_name |
environment.go | /* Environments. */
/*
* Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>)
*
* 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... | else {
found = true
}
} else {
ds := datastore.New()
var e interface{}
e, found = ds.Get("env", envName)
if e != nil {
env = e.(*ChefEnvironment)
}
}
if !found {
err := util.Errorf("Cannot load environment %s", envName)
err.SetStatus(http.StatusNotFound)
return nil, err
}
return env, nil
... | {
var gerr util.Gerror
if err != sql.ErrNoRows {
gerr = util.CastErr(err)
gerr.SetStatus(http.StatusInternalServerError)
return nil, gerr
}
found = false
} | conditional_block |
environment.go | /* Environments. */
/*
* Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>)
*
* 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... |
// Index returns the environment's type so the indexer knows where it should go.
func (e *ChefEnvironment) Index() string {
return "environment"
}
// Flatten the environment so it's suitable for indexing.
func (e *ChefEnvironment) Flatten() map[string]interface{} {
return util.FlattenObj(e)
}
// AllEnvironments r... | {
return e.Name
} | identifier_body |
baconian.rs | //! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than
//! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605.
//!
//! Each character of the plaintext message is encoded as a 5-bit binary character.
//! These characters are then "hidden" in a decoy ... |
/// Encrypt a message using the Baconian cipher
///
/// * The message to be encrypted can only be ~18% of the decoy_text as each character
/// of message is encoded by 5 encoding characters `AAAAA`, `AAAAB`, etc.
/// * The italicised ciphertext is then hidden in a decoy text, where, for each '... | {
Baconian {
use_distinct_alphabet: key.0,
decoy_text: key.1.unwrap_or_else(|| lipsum(160)),
}
} | identifier_body |
baconian.rs | //! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than
//! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605.
//!
//! Each character of the plaintext message is encoded as a 5-bit binary character.
//! These characters are then "hidden" in a decoy ... | o";
let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n";
assert_eq!(cipher_text, b.encrypt(message).unwrap());
}
// Need to test that the traditional and use_distinct_alphabet codes give different results
#[test]
fn encrypt_trad_v_dist() {
let b_trad = Baconian::new(... | essage = "Hell | identifier_name |
baconian.rs | //! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than
//! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605.
//!
//! Each character of the plaintext message is encoded as a 5-bit binary character.
//! These characters are then "hidden" in a decoy ... | }
// Need to test that the traditional and use_distinct_alphabet codes give different results
#[test]
fn encrypt_trad_v_dist() {
let b_trad = Baconian::new((false, None));
let b_dist = Baconian::new((true, None));
let message = "I JADE YOU VERVENT UNICORN";
assert_ne!(
... | assert_eq!(cipher_text, b.encrypt(message).unwrap()); | random_line_split |
cifuzz_test.py | # 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 agreed to in writing, ... | unittest.main() | conditional_block | |
cifuzz_test.py | # 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 agreed to in writing, ... | commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
))
class CheckFuzzerBuildTest(unittest.TestCase):
"""Tests the check_fuzzer_build function in the cifuzz module."""
def test_correct_fuzzer_build(self):
"""Checks check_fuzzer_build function returns True for valid fuzzers."""
test... | 'not/a/dir', | random_line_split |
cifuzz_test.py | # 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 agreed to in writing, ... | (command, env_var_arg):
for idx, element in enumerate(command):
if idx == 0:
continue
if element == env_var_arg and command[idx - 1] == '-e':
return True
return False
self.assertTrue(command_has_env_var_arg(docker_run_command, 'CIFUZZ=True'))
class InternalGithubB... | command_has_env_var_arg | identifier_name |
cifuzz_test.py | # 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 agreed to in writing, ... |
self.assertTrue(command_has_env_var_arg(docker_run_command, 'CIFUZZ=True'))
class InternalGithubBuilderTest(unittest.TestCase):
"""Tests for building OSS-Fuzz projects on GitHub actions."""
PROJECT_NAME = 'myproject'
PROJECT_REPO_NAME = 'myproject'
SANITIZER = 'address'
COMMIT_SHA = 'fake'
PR_REF = ... | for idx, element in enumerate(command):
if idx == 0:
continue
if element == env_var_arg and command[idx - 1] == '-e':
return True
return False | identifier_body |
recv_stream.rs | use std::{
future::Future,
io,
pin::Pin,
task::{Context, Poll},
};
use bytes::Bytes;
use proto::{Chunk, Chunks, ConnectionError, ReadableError, StreamId};
use thiserror::Error;
use tokio::io::ReadBuf;
use crate::{
connection::{ConnectionRef, UnknownStream},
VarInt,
};
/// A stream that can on... | (&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> {
Read {
stream: self,
buf: ReadBuf::new(buf),
}
.await
}
/// Read an exact number of bytes contiguously from the stream.
///
/// See [`read()`] for details.
///
/// [`read()`]: RecvS... | read | identifier_name |
recv_stream.rs | use std::{
future::Future,
io,
pin::Pin,
task::{Context, Poll},
};
use bytes::Bytes;
use proto::{Chunk, Chunks, ConnectionError, ReadableError, StreamId};
use thiserror::Error;
use tokio::io::ReadBuf;
use crate::{
connection::{ConnectionRef, UnknownStream},
VarInt,
};
/// A stream that can on... | UnknownStream,
/// Attempted an ordered read following an unordered read
///
/// Performing an unordered read allows discontinuities to arise in the receive buffer of a
/// stream which cannot be recovered, making further ordered reads impossible.
#[error("ordered read after unordered read")]
... | #[error("connection lost")]
ConnectionLost(#[from] ConnectionError),
/// The stream has already been stopped, finished, or reset
#[error("unknown stream")] | random_line_split |
recv_stream.rs | use std::{
future::Future,
io,
pin::Pin,
task::{Context, Poll},
};
use bytes::Bytes;
use proto::{Chunk, Chunks, ConnectionError, ReadableError, StreamId};
use thiserror::Error;
use tokio::io::ReadBuf;
use crate::{
connection::{ConnectionRef, UnknownStream},
VarInt,
};
/// A stream that can on... |
}
/// Future produced by [`RecvStream::read_exact()`].
///
/// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact
#[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"]
struct ReadExact<'a> {
stream: &'a mut RecvStream,
buf: ReadBuf<'a>,
}
impl<'a> Future for ReadExact<'a>... | {
let this = self.get_mut();
ready!(this.stream.poll_read(cx, &mut this.buf))?;
match this.buf.filled().len() {
0 if this.buf.capacity() != 0 => Poll::Ready(Ok(None)),
n => Poll::Ready(Ok(Some(n))),
}
} | identifier_body |
conf.rs | use crate::ecies;
use crate::hash256::Hash256;
use crate::keys::{public_to_slice, sign, slice_to_public};
use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE};
use crate::util::secs_since;
use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey};
use std::str::FromStr;
use std::time::UNIX_EPOCH;
... | (&self) -> u128 {self.value}
fn gas_price(&self) -> u128 {self.gas_price}
fn encryption_conf(&self) -> Option<EncOpt> {
let mut rng = rand::thread_rng();
let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap();
let nonce: Hash256 = Hash256::random();
let secp = Secp25... | value | identifier_name |
conf.rs | use crate::ecies;
use crate::hash256::Hash256;
use crate::keys::{public_to_slice, sign, slice_to_public};
use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE};
use crate::util::secs_since;
use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey};
use std::str::FromStr;
use std::time::UNIX_EPOCH;
... |
fn gas(&self) -> u128 {self.gas}
fn value(&self) -> u128 {self.value}
fn gas_price(&self) -> u128 {self.gas_price}
fn encryption_conf(&self) -> Option<EncOpt> {
let mut rng = rand::thread_rng();
let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap();
let nonce... | fn secret(&self) -> Option<String> {self.secret.clone()}
fn crypto(&self) -> Option<String> {self.crypto.clone()}
fn password(&self) -> String {self.password.clone()}
fn out_address(&self) -> String {self.out_address.clone()} | random_line_split |
conf.rs | use crate::ecies;
use crate::hash256::Hash256;
use crate::keys::{public_to_slice, sign, slice_to_public};
use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE};
use crate::util::secs_since;
use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey};
use std::str::FromStr;
use std::time::UNIX_EPOCH;
... |
fn encryption_conf(&self) -> Option<EncOpt> { None }
fn version(&self, cfg: &Option<EncOpt>) -> Message;
}
impl Sender for Wallet {
fn in_address(&self) -> String {return self.in_address.clone();}
fn out_address(&self) -> String {return self.out_address.clone();}
fn outpoint_hash(&self) -> Hash25... | {0} | identifier_body |
connection.go | // Copyright 2014-2021 Aerospike, 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 t... | (enabled bool, length int) error {
ctn.compressed = enabled
ctn.inflater = nil
if ctn.compressed {
ctn.limitReader.N = int64(length)
r, err := zlib.NewReader(ctn.limitReader)
if err != nil {
return err
}
ctn.inflater = r
}
return nil
}
| initInflater | identifier_name |
connection.go | // Copyright 2014-2021 Aerospike, 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 t... | // the function will return a TIMEOUT error.
func (ctn *Connection) updateDeadline() error {
now := time.Now()
var socketDeadline time.Time
if ctn.deadline.IsZero() {
if ctn.socketTimeout > 0 {
socketDeadline = now.Add(ctn.socketTimeout)
}
} else {
if now.After(ctn.deadline) {
return types.NewAerospikeE... | return ctn.conn != nil
}
// updateDeadline sets connection timeout for both read and write operations.
// this function is called before each read and write operation. If deadline has passed, | random_line_split |
connection.go | // Copyright 2014-2021 Aerospike, 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 t... |
}
if err := ctn.conn.SetDeadline(socketDeadline); err != nil {
if ctn.node != nil {
atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1)
}
return err
}
return nil
}
// SetTimeout sets connection timeout for both read and write operations.
func (ctn *Connection) SetTimeout(deadline time.Time, socketTim... | {
socketDeadline = now.Add(time.Millisecond)
} | conditional_block |
connection.go | // Copyright 2014-2021 Aerospike, 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 t... |
// NewConnection creates a TLS connection on the network and returns the pointer.
// A minimum timeout of 2 seconds will always be applied.
// If the connection is not established in the specified timeout,
// an error will be returned
func NewConnection(policy *ClientPolicy, host *Host) (*Connection, error) {
addres... | {
newConn := &Connection{dataBuffer: bufPool.Get().([]byte)}
runtime.SetFinalizer(newConn, connectionFinalizer)
// don't wait indefinitely
if timeout == 0 {
timeout = 5 * time.Second
}
conn, err := net.DialTimeout("tcp", address, timeout)
if err != nil {
logger.Logger.Debug("Connection to address `%s` fail... | identifier_body |
main.rs | use std::cell::Cell;
fn main() {
variable_bindings();
functions();
primitive_types();
comments();
if_();
loops();
ownership();
reference_and_borrowing();
lifetimes();
mutability();
struct_();
enums();
match_();
patterns();
method_syntax();
vectors();
... | () {
// Booleans
let x: bool = false;
println!("x is {}", x);
// char, supports Unicode
let x: char = 'A';
println!("x is {}", x);
// Numeric values
// signed and fixed size
let x: i8 = -12;
println!("x is {}", x);
// unsigned and fixed size
let x: u8 = 12;
println!... | primitive_types | identifier_name |
main.rs | use std::cell::Cell;
fn main() {
variable_bindings();
functions();
primitive_types();
comments();
if_();
loops();
ownership();
reference_and_borrowing();
lifetimes();
mutability();
struct_();
enums();
match_();
patterns();
method_syntax();
vectors();
... |
// Inheritance
trait bar : foo {
fn is_good(&self);
}
// Deriving
#[derive(Debug)]
struct Foo;
println!("{:?}", Foo);
}
fn drop() {
// A special trait from Rust standard library. When things goes out of scope.
struct Firework {
strength: i32,
};
impl Drop... | f.is_valid() }
} | identifier_body |
main.rs | use std::cell::Cell;
fn main() {
variable_bindings();
functions();
primitive_types();
comments();
if_();
loops();
ownership();
reference_and_borrowing();
lifetimes();
mutability();
struct_();
enums();
match_();
patterns();
method_syntax();
vectors();
... | }
}
fn strings() {
// resizable, a sequence of utf-8 characters, not null terminated
// &str is a string slice, has fixed size.
let greeting = "Hello there."; // &'static str
let s = "foo
bar";
let s2 = "foo\
bar";
println!("{}", s);
println!("{}", s2);
let mut s = ... | for i in &v2 {
println!("A reference to {}", i); | random_line_split |
pipes.ts | /*---------------------------------------------------------------app.component.html---------------------------------------*/
<div class="container">
<div class="row">
<label class="col-sm-2">DOB:</label>
<input type="date" style="margin-left: 8px;" [(ngModel)]="birthdate">
... |
}
}
}
/-----------------------------------------------------------------showbalance.pipe.ts----------------------------------------------------/
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'showbalance'
})
export class ShowbalancePipe implements PipeTransform {
transfo... | {
return `Formateed credit card number ${value}`;
} | conditional_block |
pipes.ts | /*---------------------------------------------------------------app.component.html---------------------------------------*/
<div class="container">
<div class="row">
<label class="col-sm-2">DOB:</label>
<input type="date" style="margin-left: 8px;" [(ngModel)]="birthdate">
... | (value: string, bir:string): string
{
if(bir!=undefined)
{
var today= new Date();
const b =new Date(bir)
var diff_year=today.getFullYear()-b.getFullYear();
var diff_month=today.getMonth()-b.getMonth();
if(diff_month<0 || (diff_month===0 && today.getDate()<b.getDate())... | transform | identifier_name |
pipes.ts | /*---------------------------------------------------------------app.component.html---------------------------------------*/
<div class="container">
<div class="row">
<label class="col-sm-2">DOB:</label>
<input type="date" style="margin-left: 8px;" [(ngModel)]="birthdate">
... | }
if (parts.length)
{
return `Formatted credit card number ${parts.join(' ')}`
}
else
{
return `Formateed credit card number ${value}`;
}
}
}
}
/-----------------------------------------------------------------showbalan... | var parts = []
for (var i=0, len=match.length; i<len; i+=4) {
parts.push(match.substring(i, i+4))
| random_line_split |
pipes.ts | /*---------------------------------------------------------------app.component.html---------------------------------------*/
<div class="container">
<div class="row">
<label class="col-sm-2">DOB:</label>
<input type="date" style="margin-left: 8px;" [(ngModel)]="birthdate">
... |
}
/*----------------------------------------------------------------------------currencyconversion.pipe.ts---------------------------------*/
import { Pipe, PipeTransform } from '@angular/core';
import { from } from 'rxjs';
@Pipe({
name: 'currencyconverter'
})
export class CurrencyconverterPipe imple... | {
console.log(value)
if(value!=undefined)
{
if(value.length<19)
{
return ' '
}
else if(value==="8888-8888-8888-8888")
{
return 'you can withdraw 10,000 per day';
}
else{
return 'You enterd a invalid credt card number'
}
... | identifier_body |
task.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/tasks/v2beta3/task.proto
package tasks // import "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import duration "github.com/golang/protobuf/ptypes/d... |
// A unit of scheduled work.
type Task struct {
// Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].
//
// The task name.
//
// The task name must have the following format:
// `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`
//
// * `PROJE... | {
return fileDescriptor_task_e4ac2456a2f2128b, []int{0, 0}
} | identifier_body |
task.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/tasks/v2beta3/task.proto
package tasks // import "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import duration "github.com/golang/protobuf/ptypes/d... | // requests.
//
// The default and maximum values depend on the type of request:
//
// * For [HTTP tasks][google.cloud.tasks.v2beta3.HttpRequest], the default is
// 10 minutes.
// The deadline must be in the interval [15 seconds, 30 minutes].
//
// * For [App Engine tasks][google.cloud.tasks.v2beta3.AppEng... | random_line_split | |
task.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/tasks/v2beta3/task.proto
package tasks // import "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import duration "github.com/golang/protobuf/ptypes/d... | () int32 {
if m != nil {
return m.DispatchCount
}
return 0
}
func (m *Task) GetResponseCount() int32 {
if m != nil {
return m.ResponseCount
}
return 0
}
func (m *Task) GetFirstAttempt() *Attempt {
if m != nil {
return m.FirstAttempt
}
return nil
}
func (m *Task) GetLastAttempt() *Attempt {
if m != ni... | GetDispatchCount | identifier_name |
task.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/tasks/v2beta3/task.proto
package tasks // import "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import duration "github.com/golang/protobuf/ptypes/d... |
return Task_VIEW_UNSPECIFIED
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*Task) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _Task_OneofMar... | {
return m.View
} | conditional_block |
mod.rs | //! Provides structs used to interact with the cypher transaction endpoint
//!
//! The types declared in this module, save for `Statement`, don't need to be instantiated
//! directly, since they can be obtained from the `GraphClient`.
//!
//! # Examples
//!
//! ## Execute a single query
//! ```
//! # use rusted_cypher:... | #[cfg(not(feature = "rustc-serialize"))]
fn check_param_errors_for_rustc_serialize(_: &Vec<Statement>) -> Result<(), GraphError> {
Ok(())
}
fn send_query(client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>)
-> Result<Response, GraphError> {
if cfg!(feature = "rustc-serialize") {... |
Ok(())
}
| random_line_split |
mod.rs | //! Provides structs used to interact with the cypher transaction endpoint
//!
//! The types declared in this module, save for `Statement`, don't need to be instantiated
//! directly, since they can be obtained from the `GraphClient`.
//!
//! # Examples
//!
//! ## Execute a single query
//! ```
//! # use rusted_cypher:... |
}
| {
let cypher = get_cypher();
let statement1 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n");
let statement2 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n");
let query = cypher.query()
.with_statement(statement1)
.with_statement(statement2);
let res... | identifier_body |
mod.rs | //! Provides structs used to interact with the cypher transaction endpoint
//!
//! The types declared in this module, save for `Statement`, don't need to be instantiated
//! directly, since they can be obtained from the `GraphClient`.
//!
//! # Examples
//!
//! ## Execute a single query
//! ```
//! # use rusted_cypher:... | (client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>)
-> Result<Response, GraphError> {
if cfg!(feature = "rustc-serialize") {
try!(check_param_errors_for_rustc_serialize(&statements));
}
let mut json = BTreeMap::new();
json.insert("statements", statements);
... | send_query | identifier_name |
text.rs | //! This protocol is used to handle input and output of
//! text-based information intended for the system user during the operation of code in the boot
//! services environment. Also included here are the definitions of three console devices: one for input
//! and one each for normal output and errors.
use core::fmt;... | // Represents the foreground color black.
Black = 0x00,
/// Represents the foreground color blue.
Blue = 0x01,
/// Represents the foreground color green.
Green = 0x02,
/// Represents the foreground color cyan.
Cyan = 0x03,
/// Represents the foreground color red.
Red = 0x04,
/// ... | ndColor {
/ | identifier_name |
text.rs | //! This protocol is used to handle input and output of
//! text-based information intended for the system user during the operation of code in the boot
//! services environment. Also included here are the definitions of three console devices: one for input
//! and one each for normal output and errors.
use core::fmt;... | Executes the given function with the UTF16-encoded string.
///
/// `function` will get a UTF16-encoded null-terminated string as its argument when its called.
///
/// `function` may be called multiple times. This is because the string is converted
/// to UTF16 in a fixed size buffer to avoid allocations. As a consequen... | self.output_string(s).map_err(|_| fmt::Error).map(|_| ())
}
}
/// | identifier_body |
text.rs | //! This protocol is used to handle input and output of
//! text-based information intended for the system user during the operation of code in the boot
//! services environment. Also included here are the definitions of three console devices: one for input
//! and one each for normal output and errors.
use core::fmt;... | /// Represents the background color blue.
Blue = 0x10,
/// Represents the background color green.
Green = 0x20,
/// Represents the background color cyan.
Cyan = 0x30,
/// Represents the background color red.
Red = 0x40,
/// Represents the background color magenta.
Magenta = 0x50,... | random_line_split | |
text.rs | //! This protocol is used to handle input and output of
//! text-based information intended for the system user during the operation of code in the boot
//! services environment. Also included here are the definitions of three console devices: one for input
//! and one each for normal output and errors.
use core::fmt;... | function(buffer.as_ptr())?;
}
Ok(())
};
for character in string.chars() {
// If there is not enough space in the buffer, flush it
if current_index + character.len_utf16() + 1 >= BUFFER_SIZE {
flush_buffer(&mut buffer, current_index, warning)?;
}
... | *warning = function(buffer.as_ptr())?;
} else {
| conditional_block |
PubUtils.ts | import { Vec2, Prefab, instantiate, tween, Vec3, Node } from "cc";
//公用工具类
export class PubUtils {
/**
* 储存游戏数据
* @param game 游戏名字
* @param key 需要储存的key值
* @param data 数据
*/
public static SetGameLocalData(game: string, key: string, data: any) {
this.SetLocalData(game + key, d... | model[key] = parseFloat(json[key]);
break;
}
case 'array-int': {
let s = json[key] as string;
let arry = s.split(',');
for (let i = 0; i < arry.length; i++) {
model... | model[key] = parseInt(json[key]);
break;
}
case "float": { | random_line_split |
PubUtils.ts | import { Vec2, Prefab, instantiate, tween, Vec3, Node } from "cc";
//公用工具类
export class PubUtils {
/**
* 储存游戏数据
* @param game 游戏名字
* @param key 需要储存的key值
* @param data 数据
*/
public static SetGameLocalData(game: string, key: string, data: any) {
this.SetLocalData(game + key, d... | minNum, max = maxNum) : (min = maxNum, max = minNum);
switch (arguments.length) {
case 1:
return Math.floor(Math.random() * (max + 1));
case 2:
return Math.floor(Math.random() * (max - min + 1) + min);
case 3:
return parseFloat... | ? (min = | identifier_name |
PubUtils.ts | import { Vec2, Prefab, instantiate, tween, Vec3, Node } from "cc";
//公用工具类
export class PubUtils {
/**
* 储存游戏数据
* @param game 游戏名字
* @param key 需要储存的key值
* @param data 数据
*/
public static SetGameLocalData(game: string, key: string, data: any) {
this.SetLocalData(game + key, d... | localStorage.removeItem(key);
}
public static ClearGameLocalData(game: string, key: string) {
this.ClearLocalData(game + key);
}
public static Range(min: number, max: number): number {
return Math.floor(Math.random() * 100000) % (max - min) + min;
}
public static randomNum(m... |
if (key == null || key == "") return;
| identifier_body |
context.rs | use std::{
alloc::Layout,
cell::{Ref, RefMut},
marker::PhantomData,
mem::size_of,
panic::AssertUnwindSafe,
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
};
use anyhow::anyhow;
use bytemuck::{Pod, Zeroable};
use feather_common::Game;
use feather_ecs::EntityBuilder;
use quill_common::Co... | Ok(ptr)
}
/// Writes `data` to `ptr`.
///
/// # Safety
/// **WASM**: No concerns.
/// **NATIVE**: `ptr` must point to a slice
/// of at least `len` valid bytes.
pub unsafe fn write_bytes(&self, ptr: PluginPtrMut<u8>, data: &[u8]) -> anyhow::Result<()> {
let bytes = self.... | random_line_split | |
context.rs | use std::{
alloc::Layout,
cell::{Ref, RefMut},
marker::PhantomData,
mem::size_of,
panic::AssertUnwindSafe,
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
};
use anyhow::anyhow;
use bytemuck::{Pod, Zeroable};
use feather_common::Game;
use feather_ecs::EntityBuilder;
use quill_common::Co... |
pub fn init_with_instance(&self, instance: &Instance) -> anyhow::Result<()> {
match &self.inner {
Inner::Wasm(w) => w.borrow_mut().init_with_instance(instance),
Inner::Native(_) => panic!("cannot initialize native plugin context"),
}
}
/// Enters the plugin context... | {
Self {
inner: Inner::Native(native::NativePluginContext::new()),
invoking_on_main_thread: AtomicBool::new(false),
game: ThreadPinned::new(None),
id,
entity_builders: ThreadPinned::new(Arena::new()),
}
} | identifier_body |
context.rs | use std::{
alloc::Layout,
cell::{Ref, RefMut},
marker::PhantomData,
mem::size_of,
panic::AssertUnwindSafe,
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
};
use anyhow::anyhow;
use bytemuck::{Pod, Zeroable};
use feather_common::Game;
use feather_ecs::EntityBuilder;
use quill_common::Co... | <T: DeserializeOwned>(
&self,
ptr: PluginPtr<u8>,
len: u32,
) -> anyhow::Result<T> {
// SAFETY: we do not return a reference to these
// bytes.
unsafe {
let bytes = self.deref_bytes(ptr.cast(), len)?;
serde_json::from_slice(bytes).map_err(From:... | read_json | identifier_name |
main.py | import mlconfig
import argparse
import datetime
import util
import models
import dataset
import trades
import madrys
import mart
import time
import os
import torch
import shutil
import numpy as np
from trainer import Trainer
from evaluator import Evaluator
from torch.autograd import Variable
from auto_attack.autoattack... | ():
# Load Search Version Genotype
model = config.model().to(device)
genotype = None
# Setup ENV
data_loader = config.dataset().getDataLoader()
if hasattr(config, 'adjust_weight_decay') and config.adjust_weight_decay:
params = adjust_weight_decay(model, config.optimizer.weight_decay)
... | main | identifier_name |
main.py | import mlconfig
import argparse
import datetime
import util
import models
import dataset
import trades
import madrys
import mart
import time
import os
import torch
import shutil
import numpy as np
from trainer import Trainer
from evaluator import Evaluator
from torch.autograd import Variable
from auto_attack.autoattack... |
def train(starting_epoch, model, genotype, optimizer, scheduler, criterion, trainer, evaluator, ENV, data_loader):
print(model)
for epoch in range(starting_epoch, config.epochs):
logger.info("="*20 + "Training Epoch %d" % (epoch) + "="*20)
adjust_learning_rate(optimizer, epoch)
# Upd... | conv, fc = [], []
for name, param in model.named_parameters():
print(name)
if not param.requires_grad:
# frozen weights
continue
if 'fc' in name:
fc.append(param)
else:
conv.append(param)
params = [{'params': conv, 'weight_decay': l... | identifier_body |
main.py | import mlconfig
import argparse
import datetime
import util
import models
import dataset
import trades
import madrys
import mart
import time
import os
import torch
import shutil
import numpy as np
from trainer import Trainer
from evaluator import Evaluator
from torch.autograd import Variable
from auto_attack.autoattack... | parser.add_argument('--epsilon', default=8, type=float, help='perturbation')
parser.add_argument('--num_steps', default=20, type=int, help='perturb number of steps')
parser.add_argument('--step_size', default=0.8, type=float, help='perturb step size')
parser.add_argument('--train_eval_epoch', default=0.5, type=float, h... | parser.add_argument('--train', action='store_true', default=False)
parser.add_argument('--attack_choice', default='PGD', choices=['PGD', 'AA', 'GAMA', 'CW', 'none']) | random_line_split |
main.py | import mlconfig
import argparse
import datetime
import util
import models
import dataset
import trades
import madrys
import mart
import time
import os
import torch
import shutil
import numpy as np
from trainer import Trainer
from evaluator import Evaluator
from torch.autograd import Variable
from auto_attack.autoattack... |
if 'lip_history' not in ENV:
ENV['lip_history'] = []
trainer.global_step = ENV['global_step']
logger.info("File %s loaded!" % (filename))
if args.data_parallel:
print('data_parallel')
model = torch.nn.DataParallel(model).to(device)
logger.info("Starting Epo... | ENV['stable_acc_history'] = [] | conditional_block |
printout7.js |
for(var i1=0; i1<10; i1++) {
console.log( i1 );
}
console.log('i1 after loop: ' + i1);
function counter() |
// console.log('k after the loop ' + k);
// conditional block
if(true)
{
var i3 = 2;
}
console.log('i3: ' + i3);
// anonymous block
{
var i4 = 3;
}
console.log('i4: ' + i4);
{
let i5 = 5;
}
// console.log('i5: ' + i5);
if(true) {
let i6 = 8;
}
// console.log('i6: ' + i6);
for(let i7=0;i7<10;i7... | {
for(var i2=0;i2<10;i2++) {
console.log(i2);
}
} | identifier_body |
printout7.js |
for(var i1=0; i1<10; i1++) {
console.log( i1 );
}
console.log('i1 after loop: ' + i1);
function counter() {
for(var i2=0;i2<10;i2++) {
console.log(i2);
}
}
// console.log('k after the loop ' + k);
// conditional block
if(true)
{
var i3 = 2;
}
console.log('i3: ' + i3);
// anonymous block
{... | ( job ) {
var a = ' Do it!';
return function(name) {
if (job === 'designer') {
console.log( name + ', explain UXD!' + a);
}
else if( job === 'teacher' ) {
console.log( name + ', subjects?' + a);
}
else {
console.log( name + ', whatcha do?' + a);
}
}
}
interviewQuestion('designer')( 'Foofoo' );... | interviewQuestion | identifier_name |
printout7.js | for(var i1=0; i1<10; i1++) {
console.log( i1 );
}
console.log('i1 after loop: ' + i1);
function counter() {
for(var i2=0;i2<10;i2++) {
console.log(i2);
}
}
// console.log('k after the loop ' + k);
// conditional block
if(true)
{
var i3 = 2;
}
console.log('i3: ' + i3);
// anonymous block
{
... | this.calculateAge = function() {
console.log(2016 - this.yearOfBirth);
}
}
// instantiaton
var john = new Person('John', 1990, 'teacher');
// new : this points to the empty object
// NOT to the global Object
// task
var jane = new Person('Jane', 1991, 'designer');
var mark = new Person('Mark', 1948, 'reti... | var Person = function(name, yearOfBirth, job) {
this.name = name;
this.yearOfBirth = yearOfBirth;
this.job = job;
this.foo = null; | random_line_split |
printout7.js |
for(var i1=0; i1<10; i1++) |
console.log('i1 after loop: ' + i1);
function counter() {
for(var i2=0;i2<10;i2++) {
console.log(i2);
}
}
// console.log('k after the loop ' + k);
// conditional block
if(true)
{
var i3 = 2;
}
console.log('i3: ' + i3);
// anonymous block
{
var i4 = 3;
}
console.log('i4: ' + i4);
{
l... | {
console.log( i1 );
} | conditional_block |
watch.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... | (f func(*list.Element)) {
if wl == nil {
return
}
for e := wl.Front(); e != nil; e = e.Next() {
f(e)
}
}
type watcherRouter struct {
mutexLock sync.RWMutex
routeLock sync.RWMutex
mutex map[string]*sync.RWMutex
route map[string]*watcherList
}
func (wr *watcherRouter) getMutex(ns string) *sync.RWMut... | do | identifier_name |
watch.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... |
type watcherRouter struct {
mutexLock sync.RWMutex
routeLock sync.RWMutex
mutex map[string]*sync.RWMutex
route map[string]*watcherList
}
func (wr *watcherRouter) getMutex(ns string) *sync.RWMutex {
wr.mutexLock.RLock()
mutex := wr.mutex[ns]
wr.mutexLock.RUnlock()
if mutex == nil {
return wr.newMute... | {
if wl == nil {
return
}
for e := wl.Front(); e != nil; e = e.Next() {
f(e)
}
} | identifier_body |
watch.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... |
structFieldType := structFieldValue.Type()
val := reflect.ValueOf(value)
if structFieldType != val.Type() {
return errors.New("provided value type didn't match obj field type")
}
structFieldValue.Set(val)
return nil
}
var (
listenerPool map[string]*opLogListener
listenerPoolLock sync.RWMutex
)
// Sta... | {
return fmt.Errorf("cannot set %s field value", name)
} | conditional_block |
watch.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... | ns := strings.Split(opl.NS, ".")
if len(ns) < 2 {
return false
}
defer func() {
if r := recover(); r != nil {
// prevent bson.ObjectIdHex() panic, return false
}
}()
t := tank.Using(ns[0]).From(ns[1]).Filter(operator.BaseCondition.AddOp(operator.Eq, opIdKey, objectId)).Query()
if t.GetError() != nil {
... | objectId, ok := opl.O2[opIdKey].(bson.ObjectId)
if !ok {
return false
} | random_line_split |
nodelib.py | """Implementation of node listing, deployment and destruction"""
from __future__ import absolute_import
import datetime
import itertools
import json
import os
import re
import string
import libcloud.compute.providers
import libcloud.compute.deployment
import libcloud.compute.ssh
from libcloud.compute.types import No... | """Destroy all nodes matching specified name"""
matches = [node for node in list_nodes(driver) if node.name == name]
if len(matches) == 0:
logger.warn('no node named %s' % name)
return False
else:
return all([node.destroy() for node in matches]) | identifier_body | |
nodelib.py | """Implementation of node listing, deployment and destruction"""
from __future__ import absolute_import
import datetime
import itertools
import json
import os
import re
import string
import libcloud.compute.providers
import libcloud.compute.deployment
import libcloud.compute.ssh
from libcloud.compute.types import No... |
def merge_keyvals_into_map(keyvals, amap):
"""Merge list of 'key=val' strings into dict amap, warning of duplicate keys"""
for kv in keyvals:
k,v = kv.split('=')
if k in amap:
logger.warn('overwriting {0} with {1}'.format(k, v))
amap[k] = v
class Deployment(object):
... | amap[target] = source | conditional_block |
nodelib.py | """Implementation of node listing, deployment and destruction"""
from __future__ import absolute_import
import datetime
import itertools
import json
import os
import re
import string | import libcloud.compute.providers
import libcloud.compute.deployment
import libcloud.compute.ssh
from libcloud.compute.types import NodeState
import provision.config as config
from provision.collections import OrderedDict
logger = config.logger
def get_driver(secret_key=config.DEFAULT_SECRET_KEY, userid=config.DEFA... | random_line_split | |
nodelib.py | """Implementation of node listing, deployment and destruction"""
from __future__ import absolute_import
import datetime
import itertools
import json
import os
import re
import string
import libcloud.compute.providers
import libcloud.compute.deployment
import libcloud.compute.ssh
from libcloud.compute.types import No... | (size, sizes):
"""Return a size from a list of sizes."""
by_name = [s for s in sizes if s.name == size]
if len(by_name) > 1:
raise Exception('more than one image named %s exists' % size)
return by_name[0]
def image_from_name(name, images):
"""Return an image from a list of images. If th... | size_from_name | identifier_name |
skipmap.go | // Package skipmap is a high-performance, scalable, concurrent-safe map based on skip-list.
// In the typical pattern(100000 operations, 90%LOAD 9%STORE 1%DELETE, 8C16T), the skipmap
// up to 10x faster than the built-in sync.Map.
package skipmap
import (
"sync"
"sync/atomic"
"unsafe"
)
// Int64Map represents a ma... | (key int64, value interface{}) {
level := randomLevel()
var preds, succs [maxLevel]*int64Node
for {
nodeFound := s.findNode(key, &preds, &succs)
if nodeFound != nil { // indicating the key is already in the skip-list
if !nodeFound.flags.Get(marked) {
// We don't need to care about whether or not the node ... | Store | identifier_name |
skipmap.go | // Package skipmap is a high-performance, scalable, concurrent-safe map based on skip-list.
// In the typical pattern(100000 operations, 90%LOAD 9%STORE 1%DELETE, 8C16T), the skipmap
// up to 10x faster than the built-in sync.Map.
package skipmap
import (
"sync"
"sync/atomic"
"unsafe"
)
// Int64Map represents a ma... |
// findNodeDelete takes a key and two maximal-height arrays then searches exactly as in a sequential skip-list.
// The returned preds and succs always satisfy preds[i] > key >= succs[i].
func (s *Int64Map) findNodeDelete(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) int {
// lFound represents ... | {
x := s.header
for i := maxLevel - 1; i >= 0; i-- {
succ := x.loadNext(i)
for succ != nil && succ.lessthan(key) {
x = succ
succ = x.loadNext(i)
}
preds[i] = x
succs[i] = succ
// Check if the key already in the skipmap.
if succ != nil && succ.equal(key) {
return succ
}
}
return nil
} | identifier_body |
skipmap.go | // Package skipmap is a high-performance, scalable, concurrent-safe map based on skip-list.
// In the typical pattern(100000 operations, 90%LOAD 9%STORE 1%DELETE, 8C16T), the skipmap
// up to 10x faster than the built-in sync.Map.
package skipmap
import (
"sync"
"sync/atomic"
"unsafe"
)
// Int64Map represents a ma... |
nodeToDelete.flags.SetTrue(marked)
isMarked = true
}
// Accomplish the physical deletion.
var (
highestLocked = -1 // the highest level being locked by this process
valid = true
pred, succ, prevPred *int64Node
)
for layer := 0; valid && (layer <= topLayer); laye... | {
// The node is marked by another process,
// the physical deletion will be accomplished by another process.
nodeToDelete.mu.Unlock()
return nil, false
} | conditional_block |
skipmap.go | // Package skipmap is a high-performance, scalable, concurrent-safe map based on skip-list.
// In the typical pattern(100000 operations, 90%LOAD 9%STORE 1%DELETE, 8C16T), the skipmap
// up to 10x faster than the built-in sync.Map.
package skipmap
import (
"sync"
"sync/atomic"
"unsafe"
)
// Int64Map represents a ma... | next: make([]*int64Node, level),
}
n.storeVal(value)
return n
}
func (n *int64Node) storeVal(value interface{}) {
atomic.StorePointer(&n.value, unsafe.Pointer(&value))
}
func (n *int64Node) loadVal() interface{} {
return *(*interface{})(atomic.LoadPointer(&n.value))
}
// loadNext return `n.next[i]`(atomic)
fu... | func newInt64Node(key int64, value interface{}, level int) *int64Node {
n := &int64Node{
key: key, | random_line_split |
lib.rs | // This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
# Rust bindings library for Sciter engine.
[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rende... |
return ap;
}
/// Getting ISciterAPI reference, can be used for manual API calling.
///
/// Bypasses ABI compatability checks.
#[doc(hidden)]
#[allow(non_snake_case)]
pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI {
let ap = unsafe {
if cfg!(feature="extension") {
EXT_API.expect("Sciter API is not availabl... | {
assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature");
} | conditional_block |
lib.rs | // This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
# Rust bindings library for Sciter engine.
[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rende... |
/// Get a global variable by its path.
///
/// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable).
#[doc(hidden)]
pub fn get_variable(path: &str) -> dom::Result<Value> {
let ws = s2u!(path);
let mut value = Value::new();
let ok = (_API.SciterGetVariable)(std::ptr::null_mut()... | {
let ws = s2u!(path);
let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr());
if ok == dom::SCDOM_RESULT::OK {
Ok(())
} else {
Err(ok)
}
} | identifier_body |
lib.rs | // This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
# Rust bindings library for Sciter engine.
[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rende... | (permanent: bool) -> ::std::result::Result<ApiType, String> {
use std::ffi::CString;
use std::path::Path;
fn try_load(path: &Path) -> Option<LPCVOID> {
let path = CString::new(format!("{}", path.display())).expect("invalid library path");
let dll = unsafe { LoadLibraryA(path.as_ptr()) };
... | try_load_library | identifier_name |
lib.rs | // This component uses Sciter Engine,
// copyright Terra Informatica Software, Inc.
// (http://terrainformatica.com/).
/*!
# Rust bindings library for Sciter engine.
[Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine
with GPU accelerated rende... | Err(error) => panic!("{}", error),
}
}
}
#[cfg(all(feature = "dynamic", unix))]
mod ext {
#![allow(non_snake_case, non_camel_case_types)]
extern crate libc;
pub static mut CUSTOM_DLL_PATH: Option<String> = None;
#[cfg(target_os = "linux")]
const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ];
//... | match try_load_library(true) {
Ok(api) => api, | random_line_split |
heatmiser_wifi.py | #!/usr/bin/env python
# coding=utf-8
#
###############################################################################
# - heatmiser_wifi -
#
# Copyright 2020 by Joel Midstjärna (joel.midstjarna@gmail.com)
#
# A Heatmiser WiFi Thermostat communication library.
#
# Supported Heatmiser Thermostats are DT, DT-E, ... | self, dcb_start = 0x0, dcb_length = 0xffff):
''' dcb_length = 0xffff means the whole DCB. The Heatmiser v3 protocol
specification recommends that the whole DCB shall be read at once.
It seems that dcb_start > 0x0 has no effect.
'''
frame_list = [
0x93, ... | send_read_request( | identifier_name |
heatmiser_wifi.py | #!/usr/bin/env python
# coding=utf-8
#
###############################################################################
# - heatmiser_wifi -
#
# Copyright 2020 by Joel Midstjärna (joel.midstjarna@gmail.com)
#
# A Heatmiser WiFi Thermostat communication library.
#
# Supported Heatmiser Thermostats are DT, DT-E, ... |
# Read out and validate the frame length
frame_length = (frame[2] << 8) | frame[1]
if(frame_length != (len(frame) + 2)): #+2 since CRC has been removed
raise Exception("Invalid frame length in data received from Thermostat")
# Read out DCB start address... | aise Exception("Unknown type of message received from Thermostat")
| conditional_block |
heatmiser_wifi.py | #!/usr/bin/env python
# coding=utf-8
#
###############################################################################
# - heatmiser_wifi -
#
# Copyright 2020 by Joel Midstjärna (joel.midstjarna@gmail.com)
#
# A Heatmiser WiFi Thermostat communication library.
#
# Supported Heatmiser Thermostats are DT, DT-E, ... |
def _send_read_request(self, dcb_start = 0x0, dcb_length = 0xffff):
''' dcb_length = 0xffff means the whole DCB. The Heatmiser v3 protocol
specification recommends that the whole DCB shall be read at once.
It seems that dcb_start > 0x0 has no effect.
'''
fram... | elf.sock.close()
| identifier_body |
heatmiser_wifi.py | #!/usr/bin/env python
# coding=utf-8
#
###############################################################################
# - heatmiser_wifi -
#
# Copyright 2020 by Joel Midstjärna (joel.midstjarna@gmail.com)
#
# A Heatmiser WiFi Thermostat communication library.
#
# Supported Heatmiser Thermostats are DT, DT-E, ... | print(options.parameter + " = " + str(info[options.parameter]))
else:
sys.stderr.write("Error!\n"+
"Parameter '"+options.parameter+"' does not exist\n")
# Write value to one parameter in Thermostat
if(options.param_value != None):
param = options.para... | if (options.parameter in info): | random_line_split |
lib.rs | use cpython::{
py_class, py_exception, py_module_initializer, ObjectProtocol, PyClone, PyDrop, PyErr,
PyObject, PyResult, PySequence, PythonObject, exc::{TypeError}
};
use search::Graph;
use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap};
use std::convert::TryInto;
mod search;
#[cfg(feature = "p... | // and there are still errors. Raise with info from all of them.
let mut skip_edges = BTreeSet::new();
let mut errors = Vec::new();
'outer: for _ in 0..10 {
if let Some(edges) = self.graph(py).borrow().search(hash_in, &hash_var_in, hash_out, &hash_var_out, &skip_edges) {
... | }
// Retry a few times, if something breaks along the way.
// Collect errors.
// If we run out of paths to take or run out of reties, | random_line_split |
lib.rs | //! This crate wraps [libkres](https://knot-resolver.cz) from
//! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver,
//! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides
//! a generic interface for pushing/pulling DNS mes... | () {
let context = Context::new();
assert!(context.add_module("iterate").is_ok());
assert!(context.remove_module("iterate").is_ok());
}
#[test]
fn context_trust_anchor() {
let context = Context::new();
let ta = gen::RR::from_string(
". 0 IN DS 20326 8 2 E... | context_with_module | identifier_name |
lib.rs | //! This crate wraps [libkres](https://knot-resolver.cz) from
//! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver,
//! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides
//! a generic interface for pushing/pulling DNS mes... | }
}
/// Request wraps `struct kr_request` and keeps a reference for the context.
/// The request is not automatically executed, it must be driven the caller to completion.
pub struct Request {
context: Arc<Context>,
inner: Mutex<*mut c::lkr_request>,
}
/* Neither request nor context are thread safe.
* Bo... | } | random_line_split |
lib.rs | //! This crate wraps [libkres](https://knot-resolver.cz) from
//! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver,
//! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides
//! a generic interface for pushing/pulling DNS mes... |
/// Generate an outbound query for the request. This should be called when `consume()` returns a `Produce` state.
pub fn produce(&self) -> Option<(Bytes, Vec<SocketAddr>)> {
let mut msg = vec![0; 512];
let mut addresses = Vec::new();
let mut sa_vec: Vec<*mut c::sockaddr> = vec![ptr::nu... | {
let (_context, inner) = self.locked();
let from = socket2::SockAddr::from(from);
let msg_ptr = if !msg.is_empty() { msg.as_ptr() } else { ptr::null() };
unsafe { c::lkr_consume(*inner, from.as_ptr() as *const _, msg_ptr, msg.len()) }
} | identifier_body |
e.rs | use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[... | (
&self,
source: usize,
sink: usize,
dual: &mut [T],
pv: &mut [usize],
pe: &mut [usize],
) -> bool {
let n = self.g.len();
let mut dist = vec![self.cost_sum; n];
let mut vis = vec![false; n];
... | refine_dual | identifier_name |
e.rs | use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[... |
}
}
if !vis[sink] {
return false;
}
for v in 0..n {
if !vis[v] {
continue;
}
dual[v] -= dist[sink] - dist[v];
}
true
}
}
struct ... | {
dist[e.to] = dist[v] + cost;
pv[e.to] = v;
pe[e.to] = i;
que.push((std::cmp::Reverse(dist[e.to]), e.to));
} | conditional_block |
e.rs | use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[... | }
}
impl BoundedAbove for $ty {
#[inline]
fn max_value() -> Self {
Self::max_value()
}
}
impl Integral for $ty {}
)*
};
}
impl_integral!(i8, i16, i32, i64, i128, isize, ... | Self::min_value() | random_line_split |
e.rs | use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
#[... |
fn refine_dual(
&self,
source: usize,
sink: usize,
dual: &mut [T],
pv: &mut [usize],
pe: &mut [usize],
) -> bool {
let n = self.g.len();
let mut dist = vec![self.cost_sum; n];
let mut vis = vec!... | {
let n = self.g.len();
assert!(source < n);
assert!(sink < n);
assert_ne!(source, sink);
let mut dual = vec![T::zero(); n];
let mut prev_v = vec![0; n];
let mut prev_e = vec![0; n];
let mut flow = T::zero();
le... | identifier_body |
state-object.ts | import * as http from 'http'
import * as send from 'send'
import * as url from 'url'
import { Stream, Writable } from 'stream'
import { format } from 'util'
import { RequestEvent } from './request-event'
import { colors } from './constants'
import {
Config,
OptionsConfig,
ServerConfig,
ServerConfig_AccessOption... |
loglevel: number = DEBUGLEVEL
doneMessage: string[] = []
hasCriticalLogs: boolean = false
/**
* 4 - Errors that require the process to exit for restart
* 3 - Major errors that are handled and do not require a server restart
* 2 - Warnings or errors that do not alter the program flow but need to be... | {
this.req = this._req = ev2.request
this.res = this._res = ev2.response
this.hostLevelPermissionsKey = ev2.localAddressPermissionsKey
this.authAccountsKey = ev2.authAccountKey
this.treeHostIndex = ev2.treeHostIndex
this.username = ev2.username
this.settings = ev2.settings
this.debugOutp... | identifier_body |
state-object.ts | import * as http from 'http'
import * as send from 'send'
import * as url from 'url'
import { Stream, Writable } from 'stream'
import { format } from 'util'
import { RequestEvent } from './request-event'
import { colors } from './constants'
import {
Config,
OptionsConfig,
ServerConfig,
ServerConfig_AccessOption... | this._res.on('finish', () => {
clearInterval(interval)
if (this.hasCriticalLogs) this.eventer.emit('stateError', this)
else this.eventer.emit('stateDebug', this)
})
}
loglevel: number = DEBUGLEVEL
doneMessage: string[] = []
hasCriticalLogs: boolean = false
/**
* 4 - Errors that ... | const interval = setInterval(() => {
this.log(-2, 'LONG RUNNING RESPONSE')
this.log(-2, '%s %s ', this.req.method, this.req.url)
}, 60000)
| random_line_split |
state-object.ts | import * as http from 'http'
import * as send from 'send'
import * as url from 'url'
import { Stream, Writable } from 'stream'
import { format } from 'util'
import { RequestEvent } from './request-event'
import { colors } from './constants'
import {
Config,
OptionsConfig,
ServerConfig,
ServerConfig_AccessOption... | () {
return this.settings.tree[this.treeHostIndex].$mount
}
startTime: [number, number]
timestamp: string
body: string = ''
json: any | undefined
/** The StatPathResult if this request resolves to a path */
//@ts-ignore Property has no initializer and is not definitely assigned in the constructor.
... | hostRoot | identifier_name |
docker-compose-dot.go | package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"flag"
"log"
"github.com/awalterschulze/gographviz"
yaml "gopkg.in/yaml.v2"
)
//Graphvix formatting
//TODO: move to some sort of template.CSS
const (
fontname string = "Helvetica"
colorVolumes = "orange"
color... |
func consoleOutputMarkdown(graphString string) {
// Produce Markdown output with embedded graph
// graph.String()
fmt.Print("\n\n```viz\n\n")
fmt.Print(graphString)
fmt.Print("```\n\n")
}
func fileOutputMarkdown(outputFileFullPathBase string, graphString string) {
// Produce Markdown output with embedded graph
... | {
// Produce Markdown output with embedded graph
// graph.String()
fmt.Print(graphString)
} | identifier_body |
docker-compose-dot.go | package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"flag"
"log"
"github.com/awalterschulze/gographviz"
yaml "gopkg.in/yaml.v2"
)
//Graphvix formatting
//TODO: move to some sort of template.CSS
const (
fontname string = "Helvetica"
colorVolumes = "orange"
color... | func init() {
flag.BoolVar(&flagHelp, "help", false, "Displays usage Help.")
}
var flagNoLegend bool
func init() {
flag.BoolVar(&flagNoLegend, "noLegend", false, "Suppress output of legend.")
}
var flagOnlyLegend bool
func init() {
flag.BoolVar(&flagOnlyLegend, "onlyLegend", false, "Output only the legend.")
}
... | var flagHelp bool
| random_line_split |
docker-compose-dot.go | package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"flag"
"log"
"github.com/awalterschulze/gographviz"
yaml "gopkg.in/yaml.v2"
)
//Graphvix formatting
//TODO: move to some sort of template.CSS
const (
fontname string = "Helvetica"
colorVolumes = "orange"
color... |
if !flagOnlyLegend {
/** NETWORK NODES **/
for name := range data.Networks {
/** if external**/
var ename = name
if data.Networks[name].External != nil {
ename = data.Networks[name].External["name"]
} else {
ename = name
}
graph.AddNode(project, nodify(name), map[string]string{
"lab... | {
// Add legend
graph.AddSubGraph(project, "cluster_legend", map[string]string{"label": "Legend"})
graph.AddNode("cluster_legend", "legend_service",
map[string]string{"shape": "plaintext",
"fontname": fontname,
"label": "<<TABLE BORDER='0'>" +
"<TR><TD BGCOLOR='" + colorContainerName + "'>containe... | conditional_block |
docker-compose-dot.go | package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"flag"
"log"
"github.com/awalterschulze/gographviz"
yaml "gopkg.in/yaml.v2"
)
//Graphvix formatting
//TODO: move to some sort of template.CSS
const (
fontname string = "Helvetica"
colorVolumes = "orange"
color... | (graphString string) {
// Produce Markdown output with embedded graph
// graph.String()
fmt.Print(graphString)
}
func consoleOutputMarkdown(graphString string) {
// Produce Markdown output with embedded graph
// graph.String()
fmt.Print("\n\n```viz\n\n")
fmt.Print(graphString)
fmt.Print("```\n\n")
}
func fileO... | consoleOutputStandardGraph | identifier_name |
api.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
use super::dev_lock::LockReadGuard;
use super::drop_privileges::get_saved_ids;
use super::{AllowedIP, Device, Error, SocketAddr};
use crate::device::Action;
use crate::serialization::KeyBytes;
use crate::x25519;
use he... |
fn api_set_peer(
reader: &mut BufReader<&UnixStream>,
d: &mut Device,
pub_key: x25519::PublicKey,
) -> i32 {
let mut cmd = String::new();
let mut remove = false;
let mut replace_ips = false;
let mut endpoint = None;
let mut keepalive = None;
let mut public_key = pub_key;
let m... | {
d.try_writeable(
|device| device.trigger_yield(),
|device| {
device.cancel_yield();
let mut cmd = String::new();
while reader.read_line(&mut cmd).is_ok() {
cmd.pop(); // remove newline if any
if cmd.is_empty() {
... | identifier_body |
api.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
use super::dev_lock::LockReadGuard;
use super::drop_privileges::get_saved_ids;
use super::{AllowedIP, Device, Error, SocketAddr};
use crate::device::Action;
use crate::serialization::KeyBytes;
use crate::x25519;
use he... | Ok(mark) => match device.set_fwmark(mark) {
Ok(()) => {}
Err(_) => return EADDRINUSE,
},
Err(_) => return EINVAL,
},
"replac... | target_os = "fuchsia",
target_os = "linux"
))]
"fwmark" => match val.parse::<u32>() { | random_line_split |
api.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
use super::dev_lock::LockReadGuard;
use super::drop_privileges::get_saved_ids;
use super::{AllowedIP, Device, Error, SocketAddr};
use crate::device::Action;
use crate::serialization::KeyBytes;
use crate::x25519;
use he... | (&mut self, fd: i32) -> Result<(), Error> {
let io_file = unsafe { UnixStream::from_raw_fd(fd) };
self.queue.new_event(
io_file.as_raw_fd(),
Box::new(move |d, _| {
// This is the closure that listens on the api file descriptor
let mut reader = Bu... | register_api_fd | identifier_name |
api.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
use super::dev_lock::LockReadGuard;
use super::drop_privileges::get_saved_ids;
use super::{AllowedIP, Device, Error, SocketAddr};
use crate::device::Action;
use crate::serialization::KeyBytes;
use crate::x25519;
use he... |
let (key, val) = (parsed_cmd[0], parsed_cmd[1]);
match key {
"remove" => match val.parse::<bool>() {
Ok(true) => remove = true,
Ok(false) => remove = false,
Err(_) => return EINVAL,
},
"p... | {
return EPROTO;
} | conditional_block |
switch.go | package output
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/Jeffail/benthos/v3/internal/batch"
"github.com/Jeffail/benthos/v3/internal/bloblang/mapping"
"github.com/Jeffail/benthos/v3/internal/component/output"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/inter... | () {
Constructors[TypeSwitch] = TypeSpec{
constructor: fromSimpleConstructor(NewSwitch),
Summary: `
The switch output type allows you to route messages to different outputs based on their contents.`,
Description: `
Messages must successfully route to one or more outputs, otherwise this is considered an error and... | init | identifier_name |
switch.go | package output
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/Jeffail/benthos/v3/internal/batch"
"github.com/Jeffail/benthos/v3/internal/bloblang/mapping"
"github.com/Jeffail/benthos/v3/internal/component/output"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/inter... |
//------------------------------------------------------------------------------
// SwitchConfig contains configuration fields for the Switch output type.
type SwitchConfig struct {
RetryUntilSuccess bool `json:"retry_until_success" yaml:"retry_until_success"`
StrictMode bool ... | {
Constructors[TypeSwitch] = TypeSpec{
constructor: fromSimpleConstructor(NewSwitch),
Summary: `
The switch output type allows you to route messages to different outputs based on their contents.`,
Description: `
Messages must successfully route to one or more outputs, otherwise this is considered an error and th... | identifier_body |
switch.go | package output
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/Jeffail/benthos/v3/internal/batch"
"github.com/Jeffail/benthos/v3/internal/bloblang/mapping"
"github.com/Jeffail/benthos/v3/internal/component/output"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/inter... |
if test {
routedAtLeastOnce = true
outputTargets[j] = append(outputTargets[j], p.Copy())
if !o.continues[j] {
return nil
}
}
}
if !routedAtLeastOnce && o.strictMode {
return ErrSwitchNoConditionMet
}
return nil
}); checksErr != nil {
select {
cas... | {
var err error
if test, err = exe.QueryPart(i, trackedMsg); err != nil {
test = false
o.logger.Errorf("Failed to test case %v: %v\n", j, err)
}
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.