file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
chat.py
def output_with_rewrite(self, msg): if self.outmutex.acquire(1): sys.stdout.write('\r'+' '*(len(get_line_buffer())+len(self.START))+'\r') print msg sys.stdout.write(self.START+get_line_buffer()) sys.stdout.flush() self.outmutex.release() @...
ip = self.users[name] self.mutex.release() return ip def has_name(self, name): ret = False if self.mutex.acquire(1): ret = name in self.users self.mutex.release() return ret def clear(self): if self.mutex.acquire(1): ...
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
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
if self.outmutex.acquire(1): print msg self.outmutex.release() @classmethod def set_start(self, start): self.START = start @classmethod def reset_start(self): self.START = self.INIT @classmethod def close_notice(self): self.anoun = False...
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
def output_with_rewrite(self, msg): if self.outmutex.acquire(1): sys.stdout.write('\r'+' '*(len(get_line_buffer())+len(self.START))+'\r') print msg sys.stdout.write(self.START+get_line_buffer()) sys.stdout.flush() self.outmutex.release() @...
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
`json:"cookbook_versions"` } // New creates a new environment, returning an error if the environment already // exists or you try to create an environment named "_default". func New(name string) (*ChefEnvironment, util.Gerror) { if !util.ValidateEnvName(name) { err := util.Errorf("Field 'name' invalid") err...
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
return verr } } else { if jsonEnv["chef_type"].(string) != "environment" { verr = util.Errorf("Field 'chef_type' invalid") return verr } } jsonEnv["cookbook_versions"], verr = util.ValidateAttributes("cookbook_versions", jsonEnv["cookbook_versions"]) if verr != nil { return verr } for k, v := rang...
AllEnvironments
identifier_name
environment.go
`json:"cookbook_versions"` } // New creates a new environment, returning an error if the environment already // exists or you try to create an environment named "_default". func New(name string) (*ChefEnvironment, util.Gerror) { if !util.ValidateEnvName(name) { err := util.Errorf("Field 'name' invalid") err.SetS...
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
{ verr = util.Errorf("Field 'json_class' invalid") return verr } } jsonEnv["chef_type"], verr = util.ValidateAsFieldString(jsonEnv["chef_type"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["chef_type"] = e.ChefType } else { return verr } } else { if jsonEnv["chef_type"]....
{ return e.Name }
identifier_body
baconian.rs
"H" => '\u{1D43b}', "I" => '\u{1D43c}', "J" => '\u{1D43d}', "K" => '\u{1D43e}', "L" => '\u{1D43f}', "M" => '\u{1D440}', "N" => '\u{1D441}', "O" => '\u{1D442}', "P" => '\u{1D443}', "Q" => '\u{1D444}', "R" => '\u{1D445}', "S" ...
/// 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
S" => '\u{1D446}', "T" => '\u{1D447}', "U" => '\u{1D448}', "V" => '\u{1D449}', "W" => '\u{1D44a}', "X" => '\u{1D44b}', "Y" => '\u{1D44c}', "Z" => '\u{1D44d}', // Using Mathematical Sans-Serif Italic "a" => '\u{1D622}', "b" => '\u{1D623}', ...
essage = "Hell
identifier_name
baconian.rs
{1D449}', "W" => '\u{1D44a}', "X" => '\u{1D44b}', "Y" => '\u{1D44c}', "Z" => '\u{1D44d}', // Using Mathematical Sans-Serif Italic "a" => '\u{1D622}', "b" => '\u{1D623}', "c" => '\u{1D624}', "d" => '\u{1D625}', "e" => '\u{1D626}', "f...
assert_eq!(cipher_text, b.encrypt(message).unwrap());
random_line_split
cifuzz_test.py
'example_crash_fuzzer' # An example fuzzer that does not trigger a crash. # Binary is a modified version of example project's do_stuff_fuzzer. It is # created by removing the bug in my_api.cpp. EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer' # A fuzzer to be built in build_fuzzers integration tests. EXAMPLE_BUILD_...
unittest.main()
conditional_block
cifuzz_test.py
# 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. """Tests the functionality of the cifuzz module.""" import os import sys import tempfile import unittest from unittest import mock # pylint: ...
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
# 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. """Tests the functionality of the cifuzz module.""" import os import sys import tempfile import unittest from unittest import mock # pylint: ...
(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
# 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. """Tests the functionality of the cifuzz module.""" import os import sys import tempfile import unittest from unittest import mock # pylint: ...
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
(&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
)) => { bufs[read] = chunk.bytes; read += 1; } res => return (if read == 0 { None } else { Some(read) }, res.err()).into(), } } }) } /// Convenience method to read all remaining data into...
#[error("connection lost")] ConnectionLost(#[from] ConnectionError), /// The stream has already been stopped, finished, or reset #[error("unknown stream")]
random_line_split
recv_stream.rs
/// This takes an `FnMut` closure that takes care of the actual reading process, matching /// the detailed read semantics for the calling function with a particular return type. /// The closure can read from the passed `&mut Chunks` and has to return the status after /// reading: the amount of data read...
{ 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
encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Change fr...
(&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
check encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Chan...
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
encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Change fr...
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
sconn := tls.Client(conn.conn, tlsConfig) if err := sconn.Handshake(); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after handshake error failed: %s", cerr.Error()) } return nil, err } if host.TLSName != "" && !tlsConfig.InsecureSkipVerify { if err := sc...
initInflater
identifier_name
connection.go
// timeouts socketTimeout time.Duration deadline time.Time // duration after which connection is considered idle idleTimeout time.Duration idleDeadline time.Time // connection object conn net.Conn // to avoid having a buffer pool and contention dataBuffer []byte compressed bool inflater io.ReadCl...
// 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
// timeouts socketTimeout time.Duration deadline time.Time // duration after which connection is considered idle idleTimeout time.Duration idleDeadline time.Time // connection object conn net.Conn // to avoid having a buffer pool and contention dataBuffer []byte compressed bool inflater io.ReadCl...
} 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
// timeouts socketTimeout time.Duration deadline time.Time // duration after which connection is considered idle idleTimeout time.Duration idleDeadline time.Time // connection object conn net.Conn // to avoid having a buffer pool and contention dataBuffer []byte compressed bool inflater io.ReadCl...
return nil, err } return newConn, nil } // 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 *ClientPolic...
{ 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
() { // 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
y: 20}; // Constructor as functions let m3 = Message::Write("Hello World!".to_string()); } fn match_() { let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!...
f.is_valid() } }
identifier_body
main.rs
v2); } fn take_ownership(v: Vec<i32>) -> i32 { // nothing happens v[0] } fn reference_and_borrowing() { let v = vec![1, 2, 3]; take_reference(&v); println!("v[0] is {}", v[0]); // Mutable reference let mut x = 5; { let y = &mut x; *y += 1; } println!("Mutable ...
for i in &v2 { println!("A reference to {}", i);
random_line_split
pipes.ts
="CreditCard number"> <div style="margin: 8px;"> <strong> {{num | formattingCreditCardNumber:num}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">Account number:</label> <input type="text" [(ngModel)]=...
} } } /-----------------------------------------------------------------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
="CreditCard number"> <div style="margin: 8px;"> <strong> {{num | formattingCreditCardNumber:num}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">Account number:</label> <input type="text" [(ngModel)]=...
(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
="CreditCard number"> <div style="margin: 8px;"> <strong> {{num | formattingCreditCardNumber:num}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">Account number:</label> <input type="text" [(ngModel)]=...
} 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
="CreditCard number"> <div style="margin: 8px;"> <strong> {{num | formattingCreditCardNumber:num}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">Account number:</label> <input type="text" [(ngModel)]=...
} /*----------------------------------------------------------------------------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
// 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
// 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
timeouts). // // `dispatch_deadline` will be truncated to the nearest millisecond. The // deadline is an approximate deadline. DispatchDeadline *duration.Duration `protobuf:"bytes,12,opt,name=dispatch_deadline,json=dispatchDeadline,proto3" json:"dispatch_deadline,omitempty"` // Output only. The number of attempts ...
() 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
timeouts). // // `dispatch_deadline` will be truncated to the nearest millisecond. The // deadline is an approximate deadline. DispatchDeadline *duration.Duration `protobuf:"bytes,12,opt,name=dispatch_deadline,json=dispatchDeadline,proto3" json:"dispatch_deadline,omitempty"` // Output only. The number of attempts ...
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
exec("MATCH (n:CYPHER_QUERY) delete n"); //! ``` //! //! ## Execute multiple queries //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let mut query = graph.cypher().query() //! .with_s...
#[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
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") { try!(check_param_errors_for_rustc_serialize(&statements)); } let mut ...
{ 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
exec("MATCH (n:CYPHER_QUERY) delete n"); //! ``` //! //! ## Execute multiple queries //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let mut query = graph.cypher().query() //! .with_s...
(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
/// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI...
// 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
/// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI...
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
be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try...
random_line_split
text.rs
in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The ...
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
100000) % (max - min) + min; } public static randomNum(maxNum, minNum, decimalNum): number { var max = 0, min = 0; minNum <= maxNum ? (min = minNum, max = maxNum) : (min = maxNum, max = minNum); switch (arguments.length) { case 1: return Math.floor(Math.rando...
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
100000) % (max - min) + min; } public static randomNum(maxNum, minNum, decimalNum): number { var max = 0, min = 0; minNum <= maxNum
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
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
pointer accesses are checked. Undefined behavior /// can never occur as a result of malicious plugin input. pub struct PluginContext { inner: Inner, /// Whether the plugin is currently being invoked /// on the main thread. /// If this is `true`, then plugin functions are on the call stack. invokin...
random_line_split
context.rs
's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtrMut<T> { pub ptr: u64, pub _marker: PhantomData<*mut T>, } impl<T> PluginPtrMut<T> { pub fn as_native(&self) -> *mut T { self.ptr as usize as *mut T } /// # Safety /// A null point...
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
mut T>, } impl<T> PluginPtrMut<T> { pub fn as_native(&self) -> *mut T { self.ptr as usize as *mut T } /// # Safety /// A null pointer must be valid in the context it is used. pub unsafe fn null() -> Self { Self { ptr: 0, _marker: PhantomData, } }...
read_json
identifier_name
main.py
os.path.join(exp_path, args.version) checkpoint_path = os.path.join(exp_path, 'checkpoints') search_results_checkpoint_file_name = None checkpoint_path_file = os.path.join(checkpoint_path, args.version) util.build_dirs(exp_path) util.build_dirs(checkpoint_path) logger = util.setup_logger(name=args.version, log_file=l...
(): # 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
os.path.join(exp_path, args.version) checkpoint_path = os.path.join(exp_path, 'checkpoints') search_results_checkpoint_file_name = None checkpoint_path_file = os.path.join(checkpoint_path, args.version) util.build_dirs(exp_path) util.build_dirs(checkpoint_path) logger = util.setup_logger(name=args.version, log_file=l...
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
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
(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) elif args.attack_choice == 'GAMA': rs = evaluator._gama_whitebox(model, images, labels, epsilon=args....
ENV['stable_acc_history'] = []
conditional_block
printout7.js
// 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
= 5 a = ++a // a = 6 // a is set to the value after incrementing typeof 2 // returns 'number' typeof -3.14 // returns 'number' typeof 0xFF // returns 'number' typeof 123e-5 ...
interviewQuestion
identifier_name
printout7.js
const i10 = -1; } // creates a block scope console.log(i10); // expressions as arguments // unary operators +3 // returns 3 +'-3' // returns -3 +'3.14' // returns 3.14 +'3' ...
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
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
wh.diffTree = strings.Split(opts.MustDiff, ".") } return wh } func (wh *watchHandler) isDiff(op *opLog) bool { if op.OP == opDeleteValue { return true } var d interface{} = op.O for _, t := range wh.diffTree { md, ok := d.(map[string]interface{}) if !ok { return false } if d = md[t]; d == nil { ...
(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
wh.diffTree = strings.Split(opts.MustDiff, ".") } return wh } func (wh *watchHandler) isDiff(op *opLog) bool { if op.OP == opDeleteValue { return true } var d interface{} = op.O for _, t := range wh.diffTree { md, ok := d.(map[string]interface{}) if !ok { return false } if d = md[t]; d == nil { ...
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
: eventType = operator.Del case opUpdateValue: eventType = operator.Chg default: continue } // If SelfOnly is true means the watcher only concern the change of node itself, // and its eventType should be EventSelfChange. // Others such as children change, children add, children delete wil...
{ return fmt.Errorf("cannot set %s field value", name) }
conditional_block
watch.go
:= wh.ns() we := listener.wr.subscribe(ns) blog.Infof("mongodb watching | begin to watch: %s", ns) var ctx context.Context var cancel context.CancelFunc var op *opLog var eventsNumber uint for { if wh.opts.Timeout > 0 { ctx, cancel = context.WithTimeout(pCtx, wh.opts.Timeout) } else { ctx, cancel = ...
objectId, ok := opl.O2[opIdKey].(bson.ObjectId) if !ok { return false }
random_line_split
nodelib.py
('ascii', 'ignore')} for sd in self.node.script_deployments] s += '\n'.join( ['*{name}: {exit_status}\n{script}\n{stdout}\n{stderr}'.format(**sd) for sd in ascii_deployments]) return s def destroy(self): """Insure only destroyable nodes ...
"""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
.debug('get_driver %s' % config.get_driver) return config.get_driver() else: logger.debug('get_driver {0}@{1}'.format(userid, provider)) return libcloud.compute.providers.get_driver( config.PROVIDERS[provider])(userid, secret_key) def list_nodes(driver): logger.debug('list_...
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
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
else: logger.debug('get_driver {0}@{1}'.format(userid, provider)) return libcloud.compute.providers.get_driver( config.PROVIDERS[provider])(userid, secret_key) def list_nodes(driver): logger.debug('list_nodes') return [n for n in driver.list_nodes() if n.state != NodeState.TERM...
size_from_name
identifier_name
skipmap.go
(key int64) bool { return n.key < key } func (n *int64Node) equal(key int64) bool { return n.key == key } // NewInt64 return an empty int64 skipmap. func NewInt64() *Int64Map { h := newInt64Node(0, "", maxLevel) h.flags.SetTrue(fullyLinked) return &Int64Map{ header: h, } } // findNode takes a key and two max...
(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
(key int64) bool { return n.key < key } func (n *int64Node) equal(key int64) bool { return n.key == key } // NewInt64 return an empty int64 skipmap. func NewInt64() *Int64Map { h := newInt64Node(0, "", maxLevel) h.flags.SetTrue(fullyLinked) return &Int64Map{ header: h, } } // findNode takes a key and two max...
// 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
(key int64) bool { return n.key < key } func (n *int64Node) equal(key int64) bool { return n.key == key } // NewInt64 return an empty int64 skipmap. func NewInt64() *Int64Map { h := newInt64Node(0, "", maxLevel) h.flags.SetTrue(fullyLinked) return &Int64Map{ header: h, } } // findNode takes a key and two max...
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
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
unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if !dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { ...
{ assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); }
conditional_block
lib.rs
.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { ...
{ 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
(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
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()) }; if !dll.is_null() { Some(dll...
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
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
_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, # Operation 0x93=Read, 0xa3=Write 0x0b, ...
# 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
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
= dcb[15] if(dcb[16] == 0): info['program_mode'] = "2/5 mode" else: info['program_mode'] = "7 day mode" info['frost_protect_temperature'] = dcb[17] info['set_room_temp'] = dcb[18] info['floor_max_limit'] = dcb[19] info['floor_max_limit_enable'] = ...
if (options.parameter in info):
random_line_split
lib.rs
}; } // Small utility to log using python logger. macro_rules! warn { ($py:expr, $message:expr) => { $py.import("logging")? .call($py, "getLogger", ("to",), None)? .call_method($py, "warning", (&$message,), None)?; }; } ////////////////////////////////////////////////// // MODU...
// 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
_c = CStr::from_bytes_with_nul(b"cache\0").unwrap(); match c::lkr_cache_open(inner, path_c.as_ptr(), max_bytes) { 0 => { c::lkr_module_load(inner, cache_c.as_ptr()); Ok(Arc::new(Self { inner: Mutex::new(inner), ...
context_with_module
identifier_name
lib.rs
socket.send_to(&msg, &addr_set[0]).unwrap(); //! let mut buf = [0; 512]; //! let (amt, src) = socket.recv_from(&mut buf).unwrap(); //! // Pass the response back to the request //! req.consume(&buf[..amt], src) //! }, //! None => { //! break; /...
} } /// 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
socket.send_to(&msg, &addr_set[0]).unwrap(); //! let mut buf = [0; 512]; //! let (amt, src) = socket.recv_from(&mut buf).unwrap(); //! // Pass the response back to the request //! req.consume(&buf[..amt], src) //! }, //! None => { //! break; /...
/// 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
; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); ...
( &self, source: usize, sink: usize, dual: &mut [T],
refine_dual
identifier_name
e.rs
e.from != source && e.to != target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/r...
{ 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
; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); ...
} } 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
; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); ...
while v != source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v != source { self.g[prev_v[v]][prev_e[v]].cap -= c; let r...
{ 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
(such as encryption steps and keys) */ declare function DebugLog( this: { debugOutput: Writable; settings: ServerConfig }, level: number, str: string | NodeJS.ErrnoException, ...args: any[] ) export class StateObject<STATPATH = StatPathResult, T = any> { static parseURL(str: string): StateObjectUrl { l...
padLeft(t.getMonth() + 1, '00'), padLeft(t.getDate(), '00'), padLeft(t.getHours(), '00'), padLeft(t.getMinutes(), '00'), padLeft(t.getSeconds(), '00') ) const interval = setInterval(() => { this.log(-2, 'LONG RUNNING RESPONSE') this.log(-2, '%s %s ', this.req.method, t...
{ 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
dump (such as encryption steps and keys) */ declare function DebugLog( this: { debugOutput: Writable; settings: ServerConfig }, level: number, str: string | NodeJS.ErrnoException, ...args: any[] ) export class StateObject<STATPATH = StatPathResult, T = any> { static parseURL(str: string): StateObjectUrl { ...
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
(such as encryption steps and keys) */ declare function DebugLog( this: { debugOutput: Writable; settings: ServerConfig }, level: number, str: string | NodeJS.ErrnoException, ...args: any[] ) export class StateObject<STATPATH = StatPathResult, T = any> { static parseURL(str: string): StateObjectUrl { l...
() { 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
as well as build, then Compose names the built image with the webapp and optional tag specified in image: // // build: ./dir // image: webapp:tag // This results in an image named webapp and tagged tag, built from ./dir. //BuildWrapper handls YAML build which has 2 formats type BuildWrapper struct { BuildString stri...
{ // Produce Markdown output with embedded graph // graph.String() fmt.Print(graphString) }
identifier_body
docker-compose-dot.go
Wrapper VolumesFrom []string `yaml:"volumes_from,omitempty"` DependsOn []string `yaml:"depends_on,omitempty"` CapAdd []string `yaml:"cap_add,omitempty"` Build BuildWrapper Environment map[string]string } // https://docs.docker.com/compo...
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
Wrapper VolumesFrom []string `yaml:"volumes_from,omitempty"` DependsOn []string `yaml:"depends_on,omitempty"` CapAdd []string `yaml:"cap_add,omitempty"` Build BuildWrapper Environment map[string]string } // https://docs.docker.com/compo...
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
file: Dockerfile-alternate // args: // buildno: 1 // If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image: // // build: ./dir // image: webapp:tag // This results in an image named webapp and tagged tag, built from ./dir. //BuildWrapper handl...
consoleOutputStandardGraph
identifier_name
api.rs
we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler fo...
match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINV...
{ 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
but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handle...
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
we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler fo...
(&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
)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.a...
{ return EPROTO; }
conditional_block
switch.go
() { 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
If set to true, an error is propagated back to the input level. The default behavior is false, which will drop the message.`, ), docs.FieldAdvanced( "max_in_flight", "The maximum number of parallel message batches to have in flight at any given time. Note that if a child output has a higher `max_in_flight` th...
{ 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
0 { if lOutputs > 0 { return nil, errors.New("combining switch cases with deprecated outputs is not supported") } o.outputs = make([]types.Output, lCases) o.checks = make([]*mapping.Executor, lCases) o.continues = make([]bool, lCases) o.fallthroughs = make([]bool, lCases) } else { o.outputs = make([]t...
{ 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
switch.go
) { arr, ok := v.([]interface{}) return "field outputs is deprecated in favour of cases", ok && len(arr) == 0 }), ).Linter(func(ctx docs.LintContext, line, col int, value interface{}) []docs.Lint { if _, ok := value.(map[string]interface{}); !ok { return nil } gObj := gabs.Wrap(value) retry...
} if len(cConf.Check) > 0 { if o.checks[i], err = interop.NewBloblangMapping(mgr, cConf.Check); err != nil { return nil, fmt.Errorf("failed to parse case '%v' check mapping: %v", i, err) }
random_line_split