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
//! jlrs is a crate that provides access to most of the Julia C API, it can be used to embed Julia //! in Rust applications and to use functionality from the Julia C API when writing `ccall`able //! functions in Rust. Currently this crate is only tested on Linux in combination with Julia 1.6 //! and is not compatible w...
/// results. The frame will preallocate `slots` slots. /// /// Example: /// /// ``` /// # use jlrs::prelude::*; /// # use jlrs::util::JULIA; /// # fn main() { /// # JULIA.with(|j| { /// # let mut julia = j.borrow_mut(); /// julia.scope_with_slots(1, |_global, frame| { /...
random_line_split
lib.rs
//! jlrs is a crate that provides access to most of the Julia C API, it can be used to embed Julia //! in Rust applications and to use functionality from the Julia C API when writing `ccall`able //! functions in Rust. Currently this crate is only tested on Linux in combination with Julia 1.6 //! and is not compatible w...
if !image_path.as_ref().exists() { let io_err = IOError::new(ErrorKind::NotFound, image_path_str); return Err(JlrsError::other(io_err))?; } let bindir = CString::new(julia_bindir_str).unwrap(); let im_rel_path = CString::new(image_path_str).unwrap(); j...
{ let io_err = IOError::new(ErrorKind::NotFound, julia_bindir_str); return Err(JlrsError::other(io_err))?; }
conditional_block
lib.rs
//! jlrs is a crate that provides access to most of the Julia C API, it can be used to embed Julia //! in Rust applications and to use functionality from the Julia C API when writing `ccall`able //! functions in Rust. Currently this crate is only tested on Linux in combination with Julia 1.6 //! and is not compatible w...
/// Creates a [`GcFrame`], calls the given closure, and returns its result. pub fn scope<T, F>(&mut self, func: F) -> JlrsResult<T> where for<'base> F: FnOnce(Global<'base>, &mut GcFrame<'base, Sync>) -> JlrsResult<T>, { unsafe { let page = self.get_init_page(); ...
{ uv_async_send(handle.cast()) == 0 }
identifier_body
moves.go
package main import "fmt" import "math" type Position struct { x, y int } type Move struct { x, y int // move relative to current position } type FullMove struct { pos Position move Move } // the result of applying a move type Turn struct { board Board lastMove FullMove } // MoveSeq contains a list of moves...
return } // removeCheckMoves gets rid of any moves that put the king under attack func removeCheckMoves(boards []Board, color PieceColor) []Board { newBoards := make([]Board, 0, len(boards)) for _, b := range boards { if len(GetPieces(b, Piece_King, color)) == 0 { // TODO: remove this, only here to debug ...
{ newx := pos.x + xDirection fullMove := FullMove{ pos, Move{ xDirection, yDirection } } if newx < 0 || newx > 7 { continue } enemyInfo := GetBoardAt(board, Position{ newx, newy }) isEnPassant := false if enemyInfo.piece != Piece_Empty { // normal capture if enemyInfo.color != info.color { new...
conditional_block
moves.go
package main import "fmt" import "math" type Position struct { x, y int } type Move struct { x, y int // move relative to current position } type FullMove struct { pos Position move Move } // the result of applying a move type Turn struct { board Board lastMove FullMove } // MoveSeq contains a list of moves...
(color PieceColor) map[Piece]MoveSeqs { m := make(map[Piece]MoveSeqs) // each sequence has to be in an order such that move n can only be done if // move n-1 is also possible (this takes care of collisions) // pawn dir := 1 if color == PieceColor_White { dir = -1 } m[Piece_Pawn] = MoveSeqs{ MoveSeq{ Move{0, di...
initMovesMap
identifier_name
moves.go
package main import "fmt" import "math" type Position struct { x, y int } type Move struct { x, y int // move relative to current position } type FullMove struct { pos Position move Move } // the result of applying a move type Turn struct { board Board lastMove FullMove } // MoveSeq contains a list of moves...
newBoards := make([]Board, 0, len(boards)) for _, b := range boards { if len(GetPieces(b, Piece_King, color)) == 0 { // TODO: remove this, only here to debug fmt.Println("DEBUG BOARD!!") DrawBoard(b) } kingPos := GetPieces(b, Piece_King, color)[0] if !isUnderAttack(b, kingPos, color) { newBoar...
// removeCheckMoves gets rid of any moves that put the king under attack func removeCheckMoves(boards []Board, color PieceColor) []Board {
random_line_split
moves.go
package main import "fmt" import "math" type Position struct { x, y int } type Move struct { x, y int // move relative to current position } type FullMove struct { pos Position move Move } // the result of applying a move type Turn struct { board Board lastMove FullMove } // MoveSeq contains a list of moves...
// removeCheckMoves gets rid of any moves that put the king under attack func removeCheckMoves(boards []Board, color PieceColor) []Board { newBoards := make([]Board, 0, len(boards)) for _, b := range boards { if len(GetPieces(b, Piece_King, color)) == 0 { // TODO: remove this, only here to debug fmt.Printl...
{ newMoves = moves yDirection := 1 if info.color == PieceColor_White { yDirection = -1 } newy := pos.y + yDirection if newy < 0 || newy > 7 { return } xDirections := []int{ -1, 1 } for _, xDirection := range xDirections { newx := pos.x + xDirection fullMove := FullMove{ pos, Move{ xDirection, yDirection ...
identifier_body
main.go
package main import ( "crypto/rand" "errors" "flag" "fmt" "go/build" "io/ioutil" "log" "math/big" "net/http" "os" "path/filepath" "runtime" "sort" "strings" "unicode/utf8" "github.com/remeh/sizedwaitgroup" "github.com/sirupsen/logrus" "iochen.com/v2gen/v2" "iochen.com/v2gen/v2/common/base64" "io...
else { err := ioutil.WriteFile(*FlagOut, bytes, 0644) if err != nil { logrus.Fatal(err) } else { if level > logrus.ErrorLevel { fmt.Printf("config has been written to %s\n", filepath.Clean(*FlagOut)) } } } } func version() string { return fmt.Sprintf("v2gen %s, V2Ray %s (%s %dcores %s/%s)", Ver...
{ fmt.Println(string(bytes)) return }
conditional_block
main.go
package main import ( "crypto/rand" "errors" "flag" "fmt" "go/build" "io/ioutil" "log" "math/big" "net/http" "os" "path/filepath" "runtime" "sort" "strings" "unicode/utf8" "github.com/remeh/sizedwaitgroup" "github.com/sirupsen/logrus" "iochen.com/v2gen/v2" "iochen.com/v2gen/v2/common/base64" "io...
Err error } type PingInfoList []*PingInfo func (pf *PingInfoList) Len() int { return len(*pf) } func (pf *PingInfoList) Less(i, j int) bool { if (*pf)[i].Err != nil { return false } else if (*pf)[j].Err != nil { return true } if len((*pf)[i].Status.Errors) != len((*pf)[j].Status.Errors) { return le...
random_line_split
main.go
package main import ( "crypto/rand" "errors" "flag" "fmt" "go/build" "io/ioutil" "log" "math/big" "net/http" "os" "path/filepath" "runtime" "sort" "strings" "unicode/utf8" "github.com/remeh/sizedwaitgroup" "github.com/sirupsen/logrus" "iochen.com/v2gen/v2" "iochen.com/v2gen/v2/common/base64" "io...
func version() string { return fmt.Sprintf("v2gen %s, V2Ray %s (%s %dcores %s/%s)", Version, vmess.CoreVersion(), runtime.Version(), runtime.NumCPU(), build.Default.GOOS, build.Default.GOARCH) } func ParseLinks(b []byte) ([]v2gen.Link, error) { s, err := base64.Decode(string(b)) if err != nil { return nil, er...
{ flag.Parse() /* LOG PART */ logger := logrus.New() if *FlagLog != "-" && *FlagLog != "" { file, err := os.Create(*FlagLog) if err != nil { logrus.Fatal(err) } defer file.Close() _, err = file.Write([]byte(version() + "\n")) if err != nil { panic("cannot write into log file") } logger.O...
identifier_body
main.go
package main import ( "crypto/rand" "errors" "flag" "fmt" "go/build" "io/ioutil" "log" "math/big" "net/http" "os" "path/filepath" "runtime" "sort" "strings" "unicode/utf8" "github.com/remeh/sizedwaitgroup" "github.com/sirupsen/logrus" "iochen.com/v2gen/v2" "iochen.com/v2gen/v2/common/base64" "io...
() int { return len(*pf) } func (pf *PingInfoList) Less(i, j int) bool { if (*pf)[i].Err != nil { return false } else if (*pf)[j].Err != nil { return true } if len((*pf)[i].Status.Errors) != len((*pf)[j].Status.Errors) { return len((*pf)[i].Status.Errors) < len((*pf)[j].Status.Errors) } return (*pf)[i]....
Len
identifier_name
round_trip.rs
use std::fmt::Debug; use tree_buf::prelude::*; mod common; use common::*; use std::collections::HashMap; use tree_buf::encode_options; use tree_buf::options; // Create this namespace to hide the prelude. This is a check that the hygenics do not require any types from tree_buf to be imported mod hide_namespace { us...
#[test] fn map_1_root() { let mut data = HashMap::new(); data.insert("test".to_owned(), 5u32); round_trip(&data, 10, 22); } #[test] fn map_n_root() { let mut data = HashMap::new(); data.insert("test3".to_owned(), 5u32); data.insert("test2".to_owned(), 5); data.insert("test1".to_owned(), 0...
{ // See also: 84d15459-35e4-4f04-896f-0f4ea9ce52a9 let data = HashMap::<u32, u32>::new(); round_trip(&data, 2, 8); }
identifier_body
round_trip.rs
use std::fmt::Debug; use tree_buf::prelude::*; mod common; use common::*; use std::collections::HashMap; use tree_buf::encode_options; use tree_buf::options; // Create this namespace to hide the prelude. This is a check that the hygenics do not require any types from tree_buf to be imported mod hide_namespace { us...
() { let mut data = HashMap::new(); data.insert("test3".to_owned(), 5u32); data.insert("test2".to_owned(), 5); data.insert("test1".to_owned(), 0); round_trip(&data, None, None); } #[test] fn maps_array() { let mut data = Vec::new(); for i in 0..5u32 { let mut h = HashMap::new(); ...
map_n_root
identifier_name
round_trip.rs
use std::fmt::Debug; use tree_buf::prelude::*; mod common; use common::*; use std::collections::HashMap; use tree_buf::encode_options; use tree_buf::options; // Create this namespace to hide the prelude. This is a check that the hygenics do not require any types from tree_buf to be imported mod hide_namespace { us...
// Show that this is much better than fixed, since this would be a minimum for exactly 0 schema overhead. assert_eq!(std::mem::size_of::<f64>() * data.len(), 400); } #[test] fn nested_float_vec() { round_trip(&vec![vec![10.0, 11.0], vec![], vec![99.0]], 24, 32); } #[test] fn array_tuple() { round_trip...
let options = encode_options! { options::LosslessFloat }; let binary = tree_buf::write_with_options(&data, &options); assert_eq!(binary.len(), 376);
random_line_split
chip8.rs
use rand::{Rng, thread_rng}; pub const PIXEL_W: u16 = 64; // width of CHIP-8 screen pub const PIXEL_H: u16 = 32; // height of CHIP-8 screen pub const FONT_LOCATION: u16 = 0x80; // location of font set in system RAM pub const CARTRIDGE_LOCATION: u16 = 0x200; // location in system RAM where game data should be l...
{ pub memory: [u8; 4096], // RAM pub reg: [u8; 16], // registers pub gfx: [u8; (PIXEL_W * PIXEL_H) as usize], // pixels stack: [u16; 16], // subroutine stack pub key: [u8; 16], // keypad idx: u16, // index register pc: u16, // program counter sp: u16, // s...
Chip8
identifier_name
chip8.rs
use rand::{Rng, thread_rng}; pub const PIXEL_W: u16 = 64; // width of CHIP-8 screen pub const PIXEL_H: u16 = 32; // height of CHIP-8 screen pub const FONT_LOCATION: u16 = 0x80; // location of font set in system RAM pub const CARTRIDGE_LOCATION: u16 = 0x200; // location in system RAM where game data should be l...
, // draw sprites at coordinate reg x, reg y (NOT X AND Y AS I ORIGINALLY DID) a width of 8 and height of z. // get z sprites from memory starting at location idx. (0xD, _, _, _) => { self.draw_flag = true; let mut pixel_unset = false; let sprites = &self.memory[self.idx as usize .. (self.idx + (z...
{ let rand_val: u8 = thread_rng().gen(); self.reg[_x] = yz & rand_val; self.pc += 2; }
conditional_block
chip8.rs
use rand::{Rng, thread_rng}; pub const PIXEL_W: u16 = 64; // width of CHIP-8 screen pub const PIXEL_H: u16 = 32; // height of CHIP-8 screen pub const FONT_LOCATION: u16 = 0x80; // location of font set in system RAM pub const CARTRIDGE_LOCATION: u16 = 0x200; // location in system RAM where game data should be lo...
current_sprite_bit, current_coordinate % PIXEL_W as usize, current_coordinate / PIXEL_W as usize ); } if self.gfx[current_coordinate % self.gfx.len()] & current_sprite_bit != 0 { // if the current byte/pixel is 1, and the sprite bit is 1, pixel_unset = true; // then t...
if super::DEBUG { println!("drawing pixel 0b{:b} at {}, {}",
random_line_split
mod.rs
//! Boa's implementation of ECMAScript's global `BigInt` object. //! //! `BigInt` is a built-in object that provides a way to represent whole numbers larger //! than the largest number JavaScript can reliably represent with the Number primitive //! and represented by the `Number.MAX_SAFE_INTEGER` constant. //! `BigInt`...
impl IntrinsicObject for BigInt { fn init(realm: &Realm) { let _timer = Profiler::global().start_event(Self::NAME, "init"); BuiltInBuilder::from_standard_constructor::<Self>(realm) .method(Self::to_string, "toString", 0) .method(Self::value_of, "valueOf", 0) .sta...
random_line_split
mod.rs
//! Boa's implementation of ECMAScript's global `BigInt` object. //! //! `BigInt` is a built-in object that provides a way to represent whole numbers larger //! than the largest number JavaScript can reliably represent with the Number primitive //! and represented by the `Number.MAX_SAFE_INTEGER` constant. //! `BigInt`...
(realm: &Realm) { let _timer = Profiler::global().start_event(Self::NAME, "init"); BuiltInBuilder::from_standard_constructor::<Self>(realm) .method(Self::to_string, "toString", 0) .method(Self::value_of, "valueOf", 0) .static_method(Self::as_int_n, "asIntN", 2) ...
init
identifier_name
mod.rs
//! Boa's implementation of ECMAScript's global `BigInt` object. //! //! `BigInt` is a built-in object that provides a way to represent whole numbers larger //! than the largest number JavaScript can reliably represent with the Number primitive //! and represented by the `Number.MAX_SAFE_INTEGER` constant. //! `BigInt`...
{ Ok(JsValue::new(modulo)) } } /// `BigInt.asUintN()` /// /// The `BigInt.asUintN()` method wraps the value of a `BigInt` to an unsigned integer between `0` and `2**(width) - 1`. /// /// [spec]: https://tc39.es/ecma262/#sec-bigint.asuintn /// [mdn]: https://developer.moz...
Ok(JsValue::new(JsBigInt::sub( &modulo, &JsBigInt::pow(&JsBigInt::new(2), &JsBigInt::new(i64::from(bits)))?, ))) } else
conditional_block
dhcpd.py
# Copyright 2013 James McCauley # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
""" Launch DHCP server Defaults to serving 192.168.0.1 to 192.168.0.253 network Subnet to allocate addresses from first First'th address in subnet to use (256 is x.x.1.0 in a /16) last Last'th address in subnet to use count Alternate way to specify last address to use ip IP to use for D...
identifier_body
dhcpd.py
# Copyright 2013 James McCauley # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
conn = core.openflow.getConnection(s.dpid) if not conn: continue if s.ports is None: return s port_no = conn.ports.get(port) if port_no is None: continue port_no = port_no.port_no for p in s.ports: p = conn.ports.get(p) if p is None: continue if p.port_...
continue
conditional_block
dhcpd.py
# Copyright 2013 James McCauley # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
(self, item): item = IPAddr(item) if item in self.removed: return False n = item.toUnsigned() mask = (1<<self.host_size)-1 nm = (n & mask) | self.network.toUnsigned() if nm != n: return False if (n & mask) == mask: return False if (n & mask) < self.first: return False if (n & mask) ...
__contains__
identifier_name
dhcpd.py
# Copyright 2013 James McCauley # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
else: raise RuntimeError("Cannot specify both last and count") self.removed = set() if self.count <= 0: raise RuntimeError("Bad first/last range") if first == 0: raise RuntimeError("Can't allocate 0th address") if self.host_size < 0 or self.host_size > 32: raise RuntimeError("Bad netwo...
self.last = (1 << self.host_size) - 2 elif last is not None: self.last = last elif count is not None: self.last = self.first + count - 1
random_line_split
WebGLCanvas.js
// // Copyright (c) 2014 Sam Leitch. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, co...
else { // Browser globals (root is window) root.WebGLCanvas = factory(); } }(this, function () { /** * This class can be used to render output pictures from an H264bsdDecoder to a canvas element. * If available the content is rendered using WebGL. */ function H264bsdCanvas(canvas, forceNoGL,...
{ // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); }
conditional_block
WebGLCanvas.js
// // Copyright (c) 2014 Sam Leitch. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, co...
(canvas, forceNoGL, contextOptions) { this.canvasElement = canvas; this.contextOptions = contextOptions; if(!forceNoGL) this.initContextGL(); if(this.contextGL) { this.initProgram(); this.initBuffers(); this.initTextures(); }; }; /** * Returns true if the canvas supports WebG...
H264bsdCanvas
identifier_name
WebGLCanvas.js
// // Copyright (c) 2014 Sam Leitch. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, co...
; /** * Returns true if the canvas supports WebGL */ H264bsdCanvas.prototype.isWebGL = function() { return this.contextGL; }; /** * Create the GL context from the canvas element */ H264bsdCanvas.prototype.initContextGL = function() { var canvas = this.canvasElement; var gl = null; var validCont...
{ this.canvasElement = canvas; this.contextOptions = contextOptions; if(!forceNoGL) this.initContextGL(); if(this.contextGL) { this.initProgram(); this.initBuffers(); this.initTextures(); }; }
identifier_body
WebGLCanvas.js
// // Copyright (c) 2014 Sam Leitch. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, co...
gl.vertexAttribPointer(vertexPosRef, 2, gl.FLOAT, false, 0, 0); var texturePosBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texturePosBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 0, 0, 0, 1, 1, 0, 1]), gl.STATIC_DRAW); var texturePosRef = gl.getAttribLocation(program, ...
var vertexPosRef = gl.getAttribLocation(program, 'vertexPos'); gl.enableVertexAttribArray(vertexPosRef);
random_line_split
thread_pool.rs
use std::marker::PhantomData; use std::sync::Arc; use std::thread::JoinHandle; use std::{iter, mem}; use crossbeam::atomic::AtomicCell; use crossbeam::deque::{Injector, Steal, Stealer, Worker}; use crossbeam::sync::{Parker, Unparker, WaitGroup}; use futures::task::{Context, Poll, Waker}; use futures::Future; use std::...
/// Compute a task in the `ThreadPool` pub fn compute<F>(&self, task: F) where F: StaticTaskFn, { self.thread_pool .compute(Task::new(self.task_group_id, task)); } /// Execute a bunch of tasks in a scope that blocks until all tasks are finished. /// Provides a ...
{ self.thread_pool.target_thread_count }
identifier_body
thread_pool.rs
use std::marker::PhantomData; use std::sync::Arc; use std::thread::JoinHandle; use std::{iter, mem}; use crossbeam::atomic::AtomicCell; use crossbeam::deque::{Injector, Steal, Stealer, Worker}; use crossbeam::sync::{Parker, Unparker, WaitGroup}; use futures::task::{Context, Poll, Waker}; use futures::Future; use std::...
(&self) -> usize { self.thread_pool.target_thread_count } /// Compute a task in the `ThreadPool` pub fn compute<F>(&self, task: F) where F: StaticTaskFn, { self.thread_pool .compute(Task::new(self.task_group_id, task)); } /// Execute a bunch of tasks in ...
degree_of_parallelism
identifier_name
thread_pool.rs
use std::marker::PhantomData; use std::sync::Arc; use std::thread::JoinHandle; use std::{iter, mem}; use crossbeam::atomic::AtomicCell; use crossbeam::deque::{Injector, Steal, Stealer, Worker}; use crossbeam::sync::{Parker, Unparker, WaitGroup}; use futures::task::{Context, Poll, Waker}; use futures::Future; use std::...
else { parked_threads.push(unparker.clone()); parker.park(); } } } pub fn create_context(&self) -> ThreadPoolContext { ThreadPoolContext::new(self, self.next_group_id.fetch_add(1)) } fn compute(&self, task: Task) { self.global_queue....
{ // TODO: recover panics task.call_once(); }
conditional_block
thread_pool.rs
use std::marker::PhantomData; use std::sync::Arc; use std::thread::JoinHandle; use std::{iter, mem}; use crossbeam::atomic::AtomicCell; use crossbeam::deque::{Injector, Steal, Stealer, Worker}; use crossbeam::sync::{Parker, Unparker, WaitGroup}; use futures::task::{Context, Poll, Waker}; use futures::Future; use std::...
#[test] fn scoped_vec() { const NUMBER_OF_TASKS: usize = 42; let thread_pool = ThreadPool::new(2); let context = thread_pool.create_context(); let mut result = vec![0; NUMBER_OF_TASKS]; context.scope(|scope| { for (chunk, i) in result.chunks_exact_mut(1).z...
} }); assert_eq!(result.load(Ordering::SeqCst), NUMBER_OF_TASKS); }
random_line_split
ffi.py
from .ctoybox import Game, State as FrameState, Input import numpy as np from PIL import Image import json from typing import Dict, Any, List, Tuple, Union, Optional def json_str(js: Union[Dict[str, Any], Input, str]) -> str: """ Turn an object into a JSON string -- handles dictionaries, the Input class, and...
def __exit__(self, exc_type, exc_value, traceback): self.__del__() def clone(self) -> 'State': """Quickly make a copy of this state; should be more efficient than saving the JSON.""" return State(self.sim, state=self.get_state().copy()) def get_state(self) -> FrameState: ...
self.__state = None self.sim = None
identifier_body
ffi.py
from .ctoybox import Game, State as FrameState, Input import numpy as np from PIL import Image import json from typing import Dict, Any, List, Tuple, Union, Optional def json_str(js: Union[Dict[str, Any], Input, str]) -> str: """ Turn an object into a JSON string -- handles dictionaries, the Input class, and...
def apply_action(self, action_input_obj: Input): """Takes an [ctoybox.Input][] action and applies it - unlike the ALE actions (which allow some permutations) this allows for fine-grained button pressing. This applies the action *k* times, where *k* based on the frameskip passed to the Toybox cons...
raise ValueError( "Expected to apply action, but failed: {0}".format(action_int) )
conditional_block
ffi.py
from .ctoybox import Game, State as FrameState, Input import numpy as np from PIL import Image import json from typing import Dict, Any, List, Tuple, Union, Optional def json_str(js: Union[Dict[str, Any], Input, str]) -> str: """ Turn an object into a JSON string -- handles dictionaries, the Input class, and...
(object): """ The Simulator is an instance of a game configuration. You can call new_game on it to begin. """ def __init__(self, game_name, sim=None): """ Construct a new instance. Parameters: game_name: one of "breakout", "amidar", etc. sim: option...
Simulator
identifier_name
ffi.py
from .ctoybox import Game, State as FrameState, Input import numpy as np from PIL import Image import json from typing import Dict, Any, List, Tuple, Union, Optional def json_str(js: Union[Dict[str, Any], Input, str]) -> str: """ Turn an object into a JSON string -- handles dictionaries, the Input class, and...
def get_lives(self) -> int: """Access the number of lives. Returns: The number of lives remaining in the current state.""" return self.rstate.lives() def get_level(self) -> int: """ Access the number of levels. Returns: The numb...
return self.rstate.score()
random_line_split
api.d.ts
/** * @packageDocumentation * @module API-EVM */ import { Buffer } from 'buffer/'; import BN from 'bn.js'; import AvalancheCore from '../../avalanche'; import { JRPCAPI } from '../../common/jrpcapi'; import { UTXOSet } from './utxos'; import { KeyChain } from './keychain'; import { Tx, UnsignedTx } from './tx'; impo...
* @param toAddresses The addresses to send the funds * @param fromAddresses The addresses being used to send the funds from the UTXOs provided * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs * @param asOf Optional. The timestamp to verify the transacti...
* @param destinationChain The chainid for where the assets will be sent.
random_line_split
api.d.ts
/** * @packageDocumentation * @module API-EVM */ import { Buffer } from 'buffer/'; import BN from 'bn.js'; import AvalancheCore from '../../avalanche'; import { JRPCAPI } from '../../common/jrpcapi'; import { UTXOSet } from './utxos'; import { KeyChain } from './keychain'; import { Tx, UnsignedTx } from './tx'; impo...
extends JRPCAPI { /** * @ignore */ protected keychain: KeyChain; protected blockchainID: string; protected blockchainAlias: string; protected AVAXAssetID: Buffer; protected txFee: BN; /** * Gets the alias for the blockchainID if it exists, otherwise returns `undefined`. ...
EVMAPI
identifier_name
Kooi_NPacific_1D.py
# created 19/12/19- North Pacific: Kooi et al. 2017 in 1D (depth) from parcels import FieldSet, ParticleSet, JITParticle, ScipyParticle, AdvectionRK4_3D, AdvectionRK4, ErrorCode, ParticleFile, Variable, Field, NestedField, VectorField, timer from datetime import timedelta as delta from datetime import datetime import...
(JITParticle): u = Variable('u', dtype=np.float32,to_write=False) v = Variable('v', dtype=np.float32,to_write=False) w = Variable('w',dtype=np.float32,to_write=True) temp = Variable('temp',dtype=np.float32,to_write=True) rho_sw = Variable('rho_sw',dtype=np.float32,to_write=False) kin_visc = Va...
plastic_particle
identifier_name
Kooi_NPacific_1D.py
# created 19/12/19- North Pacific: Kooi et al. 2017 in 1D (depth) from parcels import FieldSet, ParticleSet, JITParticle, ScipyParticle, AdvectionRK4_3D, AdvectionRK4, ErrorCode, ParticleFile, Variable, Field, NestedField, VectorField, timer from datetime import timedelta as delta from datetime import datetime import...
temp = Variable('temp',dtype=np.float32,to_write=True) rho_sw = Variable('rho_sw',dtype=np.float32,to_write=False) kin_visc = Variable('kin_visc',dtype=np.float32,to_write=False) sw_visc = Variable('sw_visc',dtype=np.float32,to_write=False) aa = Variable('aa',dtype=np.float32,to_write=True) mu_a...
class plastic_particle(JITParticle): u = Variable('u', dtype=np.float32,to_write=False) v = Variable('v', dtype=np.float32,to_write=False) w = Variable('w',dtype=np.float32,to_write=True)
random_line_split
Kooi_NPacific_1D.py
# created 19/12/19- North Pacific: Kooi et al. 2017 in 1D (depth) from parcels import FieldSet, ParticleSet, JITParticle, ScipyParticle, AdvectionRK4_3D, AdvectionRK4, ErrorCode, ParticleFile, Variable, Field, NestedField, VectorField, timer from datetime import timedelta as delta from datetime import datetime import...
else: w = 10.**(-3.76715 + (1.92944*math.log10(dstar)) - (0.09815*math.log10(dstar)**2.) - (0.00575*math.log10(dstar)**3.) + (0.00056*math.log10(dstar)**4.)) #------ Settling of particle ----- if delta_rho > 0: # sinks vs = (g * kin_visc * w * delta_rho)**(1./3.) else: #rises ...
w = (dstar**2.) *1.71E-4
conditional_block
Kooi_NPacific_1D.py
# created 19/12/19- North Pacific: Kooi et al. 2017 in 1D (depth) from parcels import FieldSet, ParticleSet, JITParticle, ScipyParticle, AdvectionRK4_3D, AdvectionRK4, ErrorCode, ParticleFile, Variable, Field, NestedField, VectorField, timer from datetime import timedelta as delta from datetime import datetime import...
""" Defining the fieldset""" depth = np.array(depth) S = np.transpose(np.tile(np.array(S_z),(len(lat),len(lon),len(time),1)), (2,3,0,1))*1000. # salinity (in Kooi equations/profiles, the salinity was in kg/kg so now converting to g/kg) T = np.transpose(np.tile(np.array(T_z),(len(lat),len(lon),len(time),1)),...
u = Variable('u', dtype=np.float32,to_write=False) v = Variable('v', dtype=np.float32,to_write=False) w = Variable('w',dtype=np.float32,to_write=True) temp = Variable('temp',dtype=np.float32,to_write=True) rho_sw = Variable('rho_sw',dtype=np.float32,to_write=False) kin_visc = Variable('kin_visc',dt...
identifier_body
main.rs
extern crate gl; extern crate imgui; extern crate imgui_opengl_renderer; extern crate imgui_sdl2; extern crate sdl2; /* @TODO: - Show line numbers! - Use traits to Send, Parse and Draw - Create a checkbox to enable debugging the parser, queries, etc; - Write a logger to use a imgui window */ use imgu...
fn start_process_thread( child: &mut Child, receiver: Receiver<String>, gdb_mutex: Arc<Mutex<debugger::DebuggerState>>, ) { let mut stdin = child.stdin.take().unwrap(); let stdout = child.stdout.take().unwrap(); use crate::debugger::DebuggerState; // Receiving commands and sending them t...
{ let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let ttf_context = sdl2::ttf::init().unwrap(); { let gl_attr = video_subsystem.gl_attr(); gl_attr.set_context_profile(sdl2::video::GLProfile::Core); gl_attr.set_context_version(3, 0); ...
identifier_body
main.rs
extern crate gl; extern crate imgui; extern crate imgui_opengl_renderer; extern crate imgui_sdl2; extern crate sdl2; /* @TODO: - Show line numbers! - Use traits to Send, Parse and Draw - Create a checkbox to enable debugging the parser, queries, etc; - Write a logger to use a imgui window */ use imgu...
else { imgui::sys::ImGuiDockNode_IsSplitNode(node) } } } const STEP_COMMANDS: [&str; 5] = [ "step\n", "-data-list-register-values x 0 1 2 3 4 5 6 7 8 9 10\n", "-stack-list-locals 1\n", r#" -data-disassemble -s $pc -e "$pc + 20" -- 0 "#, r#" -data-read-memor...
{ false }
conditional_block
main.rs
extern crate gl; extern crate imgui; extern crate imgui_opengl_renderer; extern crate imgui_sdl2; extern crate sdl2; /* @TODO: - Show line numbers! - Use traits to Send, Parse and Draw - Create a checkbox to enable debugging the parser, queries, etc; - Write a logger to use a imgui window */ use imgu...
ui::docked_window(&ui, &mut gdb, "Vars", right_down, |ui, gdb| { ui.columns(2, im_str!("A"), true); for (k, v) in &gdb.variables { ui.text(k); ui.next_column(); ui.text(v); ui.next_column(); } }); ...
} else { ui.text_colored([x, x, x, 1.0f32], &l); } } });
random_line_split
main.rs
extern crate gl; extern crate imgui; extern crate imgui_opengl_renderer; extern crate imgui_sdl2; extern crate sdl2; /* @TODO: - Show line numbers! - Use traits to Send, Parse and Draw - Create a checkbox to enable debugging the parser, queries, etc; - Write a logger to use a imgui window */ use imgu...
() -> Result<(), Error> { let (tx, rx) = channel(); let gdb_mutex = Arc::new(Mutex::new(debugger::DebuggerState::new())); let mut child = start_process(rx, Arc::clone(&gdb_mutex)); send_commands(&tx, &STARTUP_COMMANDS, 100); start_graphics(Arc::clone(&gdb_mutex), move || {}, &tx); child.kil...
main
identifier_name
trial.go
package internal import ( "context" "fmt" "regexp" "strconv" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/determined-ai/determined/master/internal/prom" "github.com/determined-ai/determined/master/internal/rm" "github.com/determined-ai/determined/master/internal/task" "github.com/determin...
// patchState decide if the state patch is valid. If so, we'll transition the trial. func (t *trial) patchState(ctx *actor.Context, s model.StateWithReason) error { switch { case model.TerminalStates[t.state]: ctx.Log().Infof("ignoring transition in terminal state (%s -> %s)", t.state, s.State) return nil case...
{ if exit.Err != nil { ctx.Log().WithError(exit.Err).Error("trial allocation failed") } t.allocationID = nil prom.DisassociateJobExperiment(t.jobID, strconv.Itoa(t.experimentID), t.config.Labels()) // Decide if this is permanent. switch { case model.StoppingStates[t.state]: if exit.Err != nil { return t...
identifier_body
trial.go
package internal import ( "context" "fmt" "regexp" "strconv" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/determined-ai/determined/master/internal/prom" "github.com/determined-ai/determined/master/internal/rm" "github.com/determined-ai/determined/master/internal/task" "github.com/determin...
} case model.StoppingStates[t.state]: switch { case t.allocationID == nil: ctx.Log().Info("stopping trial before resources are requested") return t.transition(ctx, model.StateWithReason{ State: model.StoppingToTerminalStates[t.state], InformationalReason: s.InformationalReason, })...
{ ctx.Log().WithError(err).Warn("could not terminate allocation after pause") }
conditional_block
trial.go
package internal import ( "context" "fmt" "regexp" "strconv" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/determined-ai/determined/master/internal/prom" "github.com/determined-ai/determined/master/internal/rm" "github.com/determined-ai/determined/master/internal/task" "github.com/determin...
(ctx *actor.Context, msg userInitiatedEarlyExit) error { switch msg.reason { case model.InvalidHP, model.InitInvalidHP: t.userInitiatedExit = &msg.reason // After a short time, force us to clean up if we're still handling messages. actors.NotifyAfter(ctx, InvalidHPKillDelay, model.StoppingKilledState) return ...
handleUserInitiatedStops
identifier_name
trial.go
package internal import ( "context" "fmt" "regexp" "strconv" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/determined-ai/determined/master/internal/prom" "github.com/determined-ai/determined/master/internal/rm" "github.com/determined-ai/determined/master/internal/task" "github.com/determin...
return task.DefaultService.StartAllocation( t.logCtx, ar, t.db, t.rm, specifier, ctx.Self().System(), func(ae *task.AllocationExited) { ctx.Tell(ctx.Self(), ae) }, ) }, launchRetries()) if err != nil { return err } t.allocationID = &ar.AllocationID return nil } const ( // InvalidHPKillDelay the ...
random_line_split
zhtta.rs
// // zhtta.rs // // Starting code for PS3 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.5 // To see debug! outputs set th...
} // TODO: Smarter Scheduling. fn dequeue_static_file_request(&mut self) { let req_queue_get = self.request_queue_arc.clone(); let stream_map_get = self.stream_map_arc.clone(); let cacheArc = self.cache.clone(); //Semaphore for counting tasks let s = Semaphore:...
}); notify_chan.send(()); // Send incoming notification to responder task.
random_line_split
zhtta.rs
// // zhtta.rs // // Starting code for PS3 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.5 // To see debug! outputs set th...
// TODO: Smarter Scheduling. fn dequeue_static_file_request(&mut self) { let req_queue_get = self.request_queue_arc.clone(); let stream_map_get = self.stream_map_arc.clone(); let cacheArc = self.cache.clone(); //Semaphore for counting tasks let s = Semaphore::new(...
{ // Save stream in hashmap for later response. let mut stream = stream; let peer_name = WebServer::get_peer_name(&mut stream); let (stream_port, stream_chan) = Chan::new(); stream_chan.send(stream); unsafe { // Use an unsafe method, because TcpStream in Rust ...
identifier_body
zhtta.rs
// // zhtta.rs // // Starting code for PS3 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.5 // To see debug! outputs set th...
(stream: Option<std::io::net::tcp::TcpStream>, path: &Path) { let mut stream = stream; let msg: ~str = format!("Cannot open: {:s}", path.as_str().expect("invalid path").to_owned()); stream.write(HTTP_BAD.as_bytes()); stream.write(msg.as_bytes()); } // TODO: Safe visitor counter...
respond_with_error_page
identifier_name
zhtta.rs
// // zhtta.rs // // Starting code for PS3 // Running on Rust 0.9 // // Note that this code has serious security risks! You should not run it // on any system with access to sensitive files. // // University of Virginia - cs4414 Spring 2014 // Weilin Xu and David Evans // Version 0.5 // To see debug! outputs set th...
} } fn get_peer_name(stream: &mut Option<std::io::net::tcp::TcpStream>) -> ~str { match *stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {pn.to_str()}, None => (~"") ...
{ let semaphore = s.clone(); semaphore.acquire(); // TODO: Spawning more tasks to respond the dequeued requests concurrently. You may need a semophore to control the concurrency. semaphore.access( || { //Sending ...
conditional_block
resourceSubscription.go
package rescache import ( "encoding/json" "errors" "github.com/resgateio/resgate/server/codec" "github.com/resgateio/resgate/server/reserr" ) type subscriptionState byte const ( stateSubscribed subscriptionState = iota stateError stateRequested stateCollection stateModel ) // Model represents a RES model ...
func (rs *ResourceSubscription) enqueueGetResponse(data []byte, err error) { rs.e.Enqueue(func() { rs, sublist := rs.processGetResponse(data, err) rs.e.mu.Unlock() defer rs.e.mu.Lock() if rs.state == stateError { for _, sub := range sublist { sub.Loaded(nil, rs.err) } } else { for _, sub := r...
{ subs := rs.subs c := int64(len(subs)) rs.subs = nil rs.unregister() rs.e.removeCount(c) rs.e.mu.Unlock() for sub := range subs { sub.Event(r) } rs.e.mu.Lock() }
identifier_body
resourceSubscription.go
package rescache import ( "encoding/json" "errors" "github.com/resgateio/resgate/server/codec" "github.com/resgateio/resgate/server/reserr" ) type subscriptionState byte const ( stateSubscribed subscriptionState = iota stateError stateRequested stateCollection stateModel ) // Model represents a RES model ...
return m.data, nil } // Collection represents a RES collection // https://github.com/resgateio/resgate/blob/master/docs/res-protocol.md#collections type Collection struct { Values []codec.Value data []byte } // MarshalJSON creates a JSON encoded representation of the collection func (c *Collection) MarshalJSON(...
{ data, err := json.Marshal(m.Values) if err != nil { return nil, err } m.data = data }
conditional_block
resourceSubscription.go
package rescache import ( "encoding/json" "errors" "github.com/resgateio/resgate/server/codec" "github.com/resgateio/resgate/server/reserr" ) type subscriptionState byte const ( stateSubscribed subscriptionState = iota stateError stateRequested stateCollection stateModel ) // Model represents a RES model ...
(e *EventSubscription, query string) *ResourceSubscription { return &ResourceSubscription{ e: e, query: query, subs: make(map[Subscriber]struct{}), } } // GetResourceType returns the resource type of the resource subscription func (rs *ResourceSubscription) GetResourceType() ResourceType { rs.e.mu.Lock()...
newResourceSubscription
identifier_name
resourceSubscription.go
package rescache import ( "encoding/json" "errors" "github.com/resgateio/resgate/server/codec" "github.com/resgateio/resgate/server/reserr" ) type subscriptionState byte const ( stateSubscribed subscriptionState = iota stateError stateRequested stateCollection stateModel ) // Model represents a RES model ...
// Create request subj := "get." + rs.e.ResourceName payload := codec.CreateGetRequest(rs.query) if t != nil { t.Add(func() { rs.e.cache.mq.SendRequest(subj, payload, func(_ string, data []byte, err error) { rs.e.Enqueue(func() { rs.resetting = false rs.processResetGetResponse(data, err) })...
rs.resetting = true
random_line_split
callgrind.ts
// https://www.valgrind.org/docs/manual/cl-format.html // // Larger example files can be found by searching on github: // https://github.com/search?q=cfn%3D&type=code // // Converting callgrind files into flamegraphs is challenging because callgrind // formatted profiles contain call graphs with weighted nodes and edge...
// This is the portion of the total time the given child spends within the // given parent that we'll attribute to this specific path in the call // tree. const ratio = callTreeWeight / callGraphWeightForFrame let selfWeightForFrame = callGraphWeightForFrame profile.enterFrame(fram...
}
random_line_split
callgrind.ts
// https://www.valgrind.org/docs/manual/cl-format.html // // Larger example files can be found by searching on github: // https://github.com/search?q=cfn%3D&type=code // // Converting callgrind files into flamegraphs is challenging because callgrind // formatted profiles contain call graphs with weighted nodes and edge...
private frameInfo(): FrameInfo { const file = this.filename || '(unknown)' const name = this.functionName || '(unknown)' const key = `${file}:${name}` return {key, name, file} } private calleeFrameInfo(): FrameInfo { const file = this.calleeFilename || '(unknown)' const name = this.call...
{ while (this.lineNum < this.lines.length) { const line = this.lines[this.lineNum++] if (/^\s*#/.exec(line)) { // Line is a comment. Ignore it. continue } if (/^\s*$/.exec(line)) { // Line is empty. Ignore it. continue } if (this.parseHeaderLine...
identifier_body
callgrind.ts
// https://www.valgrind.org/docs/manual/cl-format.html // // Larger example files can be found by searching on github: // https://github.com/search?q=cfn%3D&type=code // // Converting callgrind files into flamegraphs is challenging because callgrind // formatted profiles contain call graphs with weighted nodes and edge...
(line: string): boolean { const headerMatch = /^\s*(\w+):\s*(.*)+$/.exec(line) if (!headerMatch) return false if (headerMatch[1] !== 'events') { // We don't care about other headers. Ignore this line. return true } // Line specifies the formatting of subsequent cost lines. const fi...
parseHeaderLine
identifier_name
callgrind.ts
// https://www.valgrind.org/docs/manual/cl-format.html // // Larger example files can be found by searching on github: // https://github.com/search?q=cfn%3D&type=code // // Converting callgrind files into flamegraphs is challenging because callgrind // formatted profiles contain call graphs with weighted nodes and edge...
// totalWeightForFrame is the total weight for the given frame in the // entire call graph. const callGraphWeightForFrame = getOrElse(this.totalWeights, frame, () => 0) if (callGraphWeightForFrame === 0) { return } // This is the portion of the total time the given child s...
{ // This assumption about even distribution can cause us to generate a // call tree with dramatically more nodes than the call graph. // // Consider a function which is called 1000 times, where the result is // cached. The first invocation has a complex call tree and may take ...
conditional_block
seedData.js
const Photo = require('../models/photo') const User = require('../models/user') const Genre = require('../models/genre') const Comment = require('../models/comment') const data = async() => { User.collection.deleteMany({}) Genre.collection.deleteMany({}) Photo.collection.deleteMany({}) Comment.collect...
const comments = await Comment.insertMany([ {content: "First Comment random", photo: photos[0], user: rei}, {content: "Second Comment random", photo: photos[0], user: rei}, {content: "Third Comment random", photo: photos[1], user: leizl} ]) } // const createData = data() // console.log(...
{name: "Spotitube", description: "Pick your Poison", likes: 23, genre: genres[9], image: "https://techcrunch.com/wp-content/uploads/2016/07/spotify-over-youtube.png?w=730&crop=1", owner: rei}, ])
random_line_split
mesh_generator.rs
/* * MIT License * * Copyright (c) 2020 bonsairobo * Copyright (c) 2021 Robert Swain <robert.swain@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, in...
} else { chunk_meshes.entities.remove(&lod_chunk_key) }; if let Some((entity, _mesh)) = old_mesh { commands.entity(entity).insert(FADE_OUT); } } }
{ let mut render_mesh = Mesh::new(PrimitiveTopology::TriangleList); let MeshBuf { positions, normals, tex_coords, layer, indices, extent, } = mesh_buf;...
conditional_block
mesh_generator.rs
/* * MIT License * * Copyright (c) 2020 bonsairobo * Copyright (c) 2021 Robert Swain <robert.swain@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, in...
(&mut self, commands: &mut Commands, meshes: &mut Assets<Mesh>) { self.entities.retain(|_, (entity, mesh)| { clear_up_entity(entity, mesh, commands, meshes); false }); self.remove_queue.retain(|_, (entity, mesh)| { clear_up_entity(entity, mesh, commands, meshe...
clear_entities
identifier_name
mesh_generator.rs
/* * MIT License * * Copyright (c) 2020 bonsairobo * Copyright (c) 2021 Robert Swain <robert.swain@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, in...
pub fn is_empty(&self) -> bool { self.commands.is_empty() } pub fn len(&self) -> usize { self.commands.len() } pub fn clear(&mut self) { self.commands.clear(); } } // PERF: try to eliminate the use of multiple Vecs #[derive(Clone, Debug, Eq, PartialEq)] pub enum Mesh...
{ self.commands.push_front(command); }
identifier_body
mesh_generator.rs
/* * MIT License * * Copyright (c) 2020 bonsairobo * Copyright (c) 2021 Robert Swain <robert.swain@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, in...
) }); } } } LodChunkUpdate3::Merge(merge) => { for lod_key in merge.old_chunks.iter() { ...
create_mesh_for_chunk( lod_key, voxel_map, local_mesh_buffers, ),
random_line_split
mod.rs
use crate::audio::*; use crate::format; use id3; use lazy_static::lazy_static; use liblame_sys::*; use log::*; use regex::bytes; use sample; use std::*; mod index; use self::index::FrameIndex; /// This is the absolute maximum number of samples that can be contained in a single frame. const MAX_FRAME_SIZE: usize = 115...
(err: io::Error) -> Error { Error::IO(err) } } impl From<id3::Error> for Error { fn from(err: id3::Error) -> Error { Error::ID3(err) } } impl From<index::Error> for Error { fn from(err: index::Error) -> Error { Error::Index(err) } } #[cfg(all(test, feature = "unstable"))] ...
from
identifier_name
mod.rs
use crate::audio::*; use crate::format; use id3; use lazy_static::lazy_static; use liblame_sys::*; use log::*; use regex::bytes; use sample; use std::*; mod index; use self::index::FrameIndex; /// This is the absolute maximum number of samples that can be contained in a single frame. const MAX_FRAME_SIZE: usize = 115...
} impl<F, R> Seekable for Decoder<F, R> where F: sample::Frame<Sample = i16>, R: io::Read + io::Seek + 'static, { fn seek(&mut self, position: u64) -> Result<(), SeekError> { let i = self .frame_index .frame_for_sample(position) .ok_or(SeekError::OutofRange { ...
{ self.sample_rate }
identifier_body
mod.rs
use crate::audio::*; use crate::format; use id3; use lazy_static::lazy_static; use liblame_sys::*; use log::*; use regex::bytes; use sample; use std::*; mod index; use self::index::FrameIndex; /// This is the absolute maximum number of samples that can be contained in a single frame. const MAX_FRAME_SIZE: usize = 115...
$dyn(Box::from(Decoder { input, input_buf: [0; MAX_FRAME_BYTES], hip: init.hip, frame_index, sample_rate, buffers: init.buffers, next_frame: 0, ...
num_samples: Some(frame_index.num_samples()), tag: init.tag, }; macro_rules! dyn_type { ($dyn:path) => {
random_line_split
aws.go
package reconciler import ( "errors" "fmt" "net" "strings" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/networkop/cloudroutesync/pkg/route" "github.com/sirupsen/logrus" ...
time.Sleep(time.Duration(syncInterval) * time.Second) } } } } func (c *AwsClient) getRouteTable(filters []*ec2.Filter) (*ec2.RouteTable, error) { logrus.Debugf("Reading route table with filters: %+v", filters) input := &ec2.DescribeRouteTablesInput{ Filters: filters, } result, err := c.aws.DescribeR...
{ logrus.Infof("Failed to sync route table: %s", err) }
conditional_block
aws.go
package reconciler import ( "errors" "fmt" "net" "strings" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/networkop/cloudroutesync/pkg/route" "github.com/sirupsen/logrus" ...
(routes []*ec2.Route) []*ec2.Route { logrus.Debugf("Finding default route to internet GW") for _, route := range routes { if strings.HasPrefix(*route.GatewayId, "igw") { return []*ec2.Route{route} } } return nil } func filterRoutes(routes []*ec2.Route) (result []*ec2.Route) { logrus.Debugf("Filtering out r...
onlyDefaultRoute
identifier_name
aws.go
package reconciler import ( "errors" "fmt" "net" "strings" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/networkop/cloudroutesync/pkg/route" "github.com/sirupsen/logrus" ...
func (c *AwsClient) associateRouteTable() error { logrus.Debugf("Ensuring route table is associated") for _, assoc := range c.awsRouteTable.Associations { if *assoc.SubnetId == c.subnetID { logrus.Debugf("Route table is already associated, nothing to do") return nil } } logrus.Debugf("Associating rout...
{ OUTER: for prefix, nextHop := range rt.Routes { ip, _, err := net.ParseCIDR(prefix) if err != nil { logrus.Infof("Failed to parse prefix: %s", prefix) continue } for _, subnet := range awsReservedRanges { if subnet != nil && subnet.Contains(ip) { logrus.Debugf("Ignoring IP from AWS reserved ran...
identifier_body
aws.go
package reconciler import ( "errors" "fmt" "net" "strings" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/networkop/cloudroutesync/pkg/route" "github.com/sirupsen/logrus" ...
} wg.Wait() for _, err := range opErrors { logrus.Infof("Failed route operation: %s", err) } if len(toAdd)+len(toDelete) > 0 { logrus.Debug("Updating own route table") myRouteTable, err := c.getRouteTable( []*ec2.Filter{ { Name: aws.String("tag:name"), Values: aws.StringSlice([]string{un...
} }(route, &wg)
random_line_split
table.d.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Directionality } from '@angular/cdk/bidi'; import { CollectionViewer, DataSource } from '@angular/cdk/collect...
export declare class CdkTable<T> implements AfterContentChecked, CollectionViewer, OnDestroy, OnInit { protected readonly _differs: IterableDiffers; protected readonly _changeDetectorRef: ChangeDetectorRef; protected readonly _elementRef: ElementRef; protected readonly _dir: Directionality; private ...
* Uses the dataSource input to determine the data to be rendered. The data can be provided either * as a data array, an Observable stream that emits the data array to render, or a DataSource with a * connect function that will return an Observable stream that emits the data array to render. */
random_line_split
table.d.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Directionality } from '@angular/cdk/bidi'; import { CollectionViewer, DataSource } from '@angular/cdk/collect...
tlet { viewContainer: ViewContainerRef; elementRef: ElementRef; constructor(viewContainer: ViewContainerRef, elementRef: ElementRef); static ɵfac: ɵngcc0.ɵɵFactoryDef<FooterRowOutlet, never>; static ɵdir: ɵngcc0.ɵɵDirectiveDefWithMeta<FooterRowOutlet, "[footerRowOutlet]", never, {}, {}, never>; } /*...
mplements RowOu
identifier_name
strategy.py
from abc import ABCMeta, abstractmethod import pandas as pd import numpy as np from datetime import datetime from collections import deque from sortedcontainers import SortedList from bisect import bisect_left, bisect from analyser import * from profilehooks import profile import sys debug = False eps = 1e-10 tradeRat...
def getVolAvgPrice(self, opens, close, vol, left, right): ''' Computes the volume weighted price for the range [left, right) price = (open + close)/2 ''' avgPrice = (opens.iloc[left:right] + close.iloc[left:right])/2.0 volAvgPrice = (avgPrice * vol[left:right]).sum...
if (self.currSamples >= self.winSize): # Updating the queue and removing elements from the tree for stock in self.stockList: lastVal = self.gapQueue[stock].popleft() self.orderedGaps[stock].remove(lastVal) self.currSamples -= 1 for stock, gap ...
identifier_body
strategy.py
from abc import ABCMeta, abstractmethod import pandas as pd import numpy as np from datetime import datetime from collections import deque from sortedcontainers import SortedList from bisect import bisect_left, bisect from analyser import * from profilehooks import profile import sys debug = False eps = 1e-10 tradeRat...
order = pd.DataFrame(0, index = backData['open'].columns, columns = ['signal', 'qty', 'position']) opens = backData['open'][:currDay] close = backData['close'][:currDay] retVal = self.getReturn(self.retPeriod, opens) rollVol = self.getRollVol(self.volLookback, opens) a...
return rollVol def generateSignal(self, backData, currDay):
random_line_split
strategy.py
from abc import ABCMeta, abstractmethod import pandas as pd import numpy as np from datetime import datetime from collections import deque from sortedcontainers import SortedList from bisect import bisect_left, bisect from analyser import * from profilehooks import profile import sys debug = False eps = 1e-10 tradeRat...
(Strategy): def __init__(self, config): self.volLookback = config['VOL_LOOKBACK'] self.retPeriod = config['RET_PERIOD'] self.stdDevMethod = config['STD_DEV_METHOD'] self.lag = config['LAG'] # self.volLookback = volLookback # self.retPeriod = retPeriod ...
SimpleVol
identifier_name
strategy.py
from abc import ABCMeta, abstractmethod import pandas as pd import numpy as np from datetime import datetime from collections import deque from sortedcontainers import SortedList from bisect import bisect_left, bisect from analyser import * from profilehooks import profile import sys debug = False eps = 1e-10 tradeRat...
else: rollVol = np.std(retData) # print rollVol # return rollVol.iloc[-1] return rollVol def generateSignal(self, backData, currDay): order = pd.DataFrame(0, index = backData['open'].columns, columns = ['signal', 'qty', 'position']) opens = backData['o...
retData = retData ** 2 ewmRet = retData.ewm(span = period).mean() rollVol = np.sqrt(ewmRet) if (debug): print 'Before', retData print 'EWM', ewmRet.iloc[-1] print 'After ema:', rollVol.iloc[-1]
conditional_block
rectAreaLightShadow.ts
import { ElapsedTime } from '../three/timeUtility' import { Controls } from '../three/controls' import { DataGUI, Statistic } from '../three/uiUtility' import { LinearDepthRenderMaterial } from '../three/shaderUtility'; import { BoxUpdateHelper, boundingBoxInViewSpace, boxFromOrthographicViewVolume, g...
updateShadowBox(); }
random_line_split
rectAreaLightShadow.ts
import { ElapsedTime } from '../three/timeUtility' import { Controls } from '../three/controls' import { DataGUI, Statistic } from '../three/uiUtility' import { LinearDepthRenderMaterial } from '../three/shaderUtility'; import { BoxUpdateHelper, boundingBoxInViewSpace, boxFromOrthographicViewVolume, g...
const generalUiProperties = { 'light source': 'rectAreaLight', 'scene volume': sceneBoxHelper.visible, 'shadow volume': shadowBoxHelper.visible, 'debug shadow map': false, 'debug output': 'off', }; setLightSource(generalUiProperties['light source']); const d...
{ shadowDebugPlane = new THREE.Mesh( new THREE.PlaneGeometry(5, 5), new THREE.MeshBasicMaterial({ map: rectAreaLightAndShadow.shadowMapTexture }) ); shadowDebugPlane.position.x = -8; shadowDebugPlane.position.y = 3; shadowDebugPlane.visible = false; ...
conditional_block
test_sync.py
# Copyright 2018 New Vector Ltd # # 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 writin...
# Blow away caches (supported room versions can only change due to a restart). self.store.get_rooms_for_user_with_stream_ordering.invalidate_all() self.store.get_rooms_for_user.invalidate_all() self.store._get_event_cache.clear() self.store._event_ref.clear() # The roo...
self.get_success( self.hs.get_datastores().main.db_pool.simple_update( "rooms", keyvalues={"room_id": room_id}, updatevalues={"room_version": "unknown-room-version"}, desc="updated-room-version", ) ...
conditional_block
test_sync.py
# Copyright 2018 New Vector Ltd # # 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 writin...
login.register_servlets, room.register_servlets, ] def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None: self.sync_handler = self.hs.get_sync_handler() self.store = self.hs.get_datastores().main # AuthBlocking reads from the hs' config on init...
"""Tests Sync Handler.""" servlets = [ admin.register_servlets, knock.register_servlets,
random_line_split
test_sync.py
# Copyright 2018 New Vector Ltd # # 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 writin...
(self) -> None: """Rooms shouldn't appear under "joined" if a join loses a race to a ban. A complicated edge case. Imagine the following scenario: * you attempt to join a room * racing with that is a ban which comes in over federation, which ends up with an earlier stream_ord...
test_ban_wins_race_with_join
identifier_name
test_sync.py
# Copyright 2018 New Vector Ltd # # 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 writin...
"""Generate a sync config (with a unique request key).""" global _request_key _request_key += 1 return SyncConfig( user=UserID.from_string(user_id), filter_collection=Filtering(Mock()).DEFAULT_FILTER_COLLECTION, is_guest=False, request_key=("request_key", _request_key), ...
identifier_body
start-trip.js
import React, { Component } from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, hashHistory, Link } from 'react-router'; import $, { ajax } from 'jquery'; window.$ = $; import DatePicker from 'material-ui/lib/date-picker/date-picker'; import ReactDatePicker from 'react-date-picker'; i...
else{ console.log("else ran"); hashHistory.push('/itinerary'); } } freeDayHandler(){ console.log('free day added'); } dataHandler(data) { switch (this.action){ case 'add': this.addGameHandler(data); break; case 'get': ::this.getIteneraryHandler(data); // hashHistory....
{ let local_datetime = this.state.startDate; ajax({ url:'https://shielded-hollows-39012.herokuapp.com/selectgame', type: 'POST', data: {"local_datetime": local_datetime, "itinerary_id": Cookies.get('itinerary_id'), "game_number": id.id }, headers: { 'X-Auth-Token': Cookies.get('au...
conditional_block
start-trip.js
import React, { Component } from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, hashHistory, Link } from 'react-router'; import $, { ajax } from 'jquery'; window.$ = $; import DatePicker from 'material-ui/lib/date-picker/date-picker'; import ReactDatePicker from 'react-date-picker'; i...
getIteneraryHandler(id){ ///if a city has been clicked, add it to the trip, otherwise render the trip as is if(id.id){ let local_datetime = this.state.startDate; ajax({ url:'https://shielded-hollows-39012.herokuapp.com/selectgame', type: 'POST', data: {"local_datetime": local_datetim...
{ document.querySelector('.calendar').classList.add('calendar-hidden'); document.querySelector('#show-calendar').classList.remove('show-calendar'); let local_datetime = this.state.startDate; ////////////UNCOMMENT TO TEST BACKEND DATA ajax({ url:'https://shielded-hollows-39012.herokuapp.com/selec...
identifier_body
start-trip.js
import React, { Component } from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, hashHistory, Link } from 'react-router'; import $, { ajax } from 'jquery'; window.$ = $; import DatePicker from 'material-ui/lib/date-picker/date-picker'; import ReactDatePicker from 'react-date-picker'; i...
(){ let { citiesWithGames, startDate } = this.state; let gameDate = function(){ return moment(startDate).format('dddd, MMMM Do YYYY') === "Invalid date" ? "Click calendar to see available games" : moment(startDate).format('dddd, MMMM Do YYYY')} return( <div> <header> <Link to="/start-trip"><h1 id=...
render
identifier_name
start-trip.js
import React, { Component } from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, hashHistory, Link } from 'react-router'; import $, { ajax } from 'jquery'; window.$ = $; import DatePicker from 'material-ui/lib/date-picker/date-picker'; import ReactDatePicker from 'react-date-picker'; i...
<div className="game-choices"> <button onClick={() => this.action = 'add'}>Add selected game to trip</button> <div className="get-itinerary"> <button onClick={() => this.action = 'get'}>Finalize Trip</button> {/*<input type="submit" value="Add Another Game" name="action"/> ...
<div id='game-picker'></div> <SSF onData={::this.dataHandler}>
random_line_split
day3.rs
use { aoc_runner_derive::aoc, re_parse::{Error as ReParseError, ReParse, Regex}, serde_derive::Deserialize, std::{ cmp::max, mem::replace, ops::{Index, IndexMut}, slice::Iter as SliceIter, str::{FromStr, Split}, }, }; struct ClaimIterator<'s> { input: Spl...
} } let uncontested = claims .into_iter() .filter_map(|(c, uncontested)| if uncontested { Some(c) } else { None }) .collect::<Vec<_>>(); if uncontested.len() != 1 { panic!("Expected single remaining claim, got {:?}", uncontested); } uncontested[0].id } #[te...
{ (&mut claims[i]).1 = false; (&mut claims[j]).1 = false; }
conditional_block
day3.rs
use { aoc_runner_derive::aoc, re_parse::{Error as ReParseError, ReParse, Regex}, serde_derive::Deserialize, std::{ cmp::max, mem::replace, ops::{Index, IndexMut}, slice::Iter as SliceIter, str::{FromStr, Split}, }, }; struct ClaimIterator<'s> { input: Spl...
() { const CLAIM_TO_COMPARE_TO: &'static str = "#0 @ 2,2: 3x3"; let claim: Claim = CLAIM_TO_COMPARE_TO.parse().unwrap(); for other in &[ // Close but not touching "#0 @ 1,1: 1x1", "#0 @ 2,1: 1x1", "#0 @ 3,1: 1x1", "#0 @ 4,1: 1x1", "#0 @ 5,1: 1x1", "#0...
test_intersection
identifier_name
day3.rs
use { aoc_runner_derive::aoc, re_parse::{Error as ReParseError, ReParse, Regex}, serde_derive::Deserialize, std::{ cmp::max, mem::replace, ops::{Index, IndexMut}, slice::Iter as SliceIter, str::{FromStr, Split}, }, }; struct ClaimIterator<'s> { input: Spl...
let count = grid[(x, y)]; assert!(count != 0); if count > 1 { return false; } } } true }, ) .collect::<Vec<_>>(); ...
right, .. }| { for y in *top..*bottom { for x in *left..*right {
random_line_split
day3.rs
use { aoc_runner_derive::aoc, re_parse::{Error as ReParseError, ReParse, Regex}, serde_derive::Deserialize, std::{ cmp::max, mem::replace, ops::{Index, IndexMut}, slice::Iter as SliceIter, str::{FromStr, Split}, }, }; struct ClaimIterator<'s> { input: Spl...
#[aoc(day3, part2, square_iteration)] pub fn day3_part2_square_iteration(input: &str) -> usize { // OPT: Use ArrayVec for even more performance? Depends on max size. // OR OPT: Pre-allocating might be beneficial here, not sure how `size_hint` works for char // splits. let mut claims = ClaimIterator::n...
{ assert_eq!(day3_part1(HINT_INPUT), HINT_EXPECTED_PART1_OUTPUT); }
identifier_body
train.py
import os import random import re import json import glob import multiprocessing import argparse from importlib import import_module from pathlib import Path from typing import Union, List, Tuple from collections import defaultdict import pickle as pickle import numpy as np import pandas as pd import matplotlib as mp...
# Train NUM_EPOCHS = args.epochs SAVE_EVERY = args.save_every EVAL_EVERY = args.eval_every LOG_EVERY = args.log_every SAVE_TOTAL_LIMIT = args.save_total_limit LEARNING_RATE = args.lr LR_TYPE = args.lr_type DECAY_RATE = args.lr_weight_decay WARMUP_RATIO = args.lr_warmup_ratio ...
VAL_BATCH_SIZE = args.val_batch_size if args.val_batch_size else BATCH_SIZE MAX_PAD_LEN = args.max_pad_len
random_line_split
train.py
import os import random import re import json import glob import multiprocessing import argparse from importlib import import_module from pathlib import Path from typing import Union, List, Tuple from collections import defaultdict import pickle as pickle import numpy as np import pandas as pd import matplotlib as mp...
(parser): # Set random seed parser.add_argument('--seed', type=int, default=None, help="random seed (default: None)") parser.add_argument('--verbose', type=str, default="n", choices=["y", "n"], help="verbose (default: n)") # Container environment par...
parse_arguments
identifier_name
train.py
import os import random import re import json import glob import multiprocessing import argparse from importlib import import_module from pathlib import Path from typing import Union, List, Tuple from collections import defaultdict import pickle as pickle import numpy as np import pandas as pd import matplotlib as mp...
bel = [] with open('dict_label_to_num.pkl', 'rb') as f: dict_label_to_num = pickle.load(f) for v in label: num_label.append(dict_label_to_num[v]) return num_label ###################################### # DATA LOADER RELATED ###################################### # TODO: bucketed_batch_in...
""" validation을 위한 metrics function """ labels = pred.label_ids preds = pred.predictions.argmax(-1) probs = pred.predictions # calculate accuracy using sklearn's function f1 = klue_re_micro_f1(preds, labels) auprc = klue_re_auprc(probs, labels) acc = metrics.accuracy_score(labels, preds) #...
identifier_body
train.py
import os import random import re import json import glob import multiprocessing import argparse from importlib import import_module from pathlib import Path from typing import Union, List, Tuple from collections import defaultdict import pickle as pickle import numpy as np import pandas as pd import matplotlib as mp...
###################################### # KLUE SPECIFICS ###################################### def klue_re_micro_f1(preds, labels): """KLUE-RE micro f1 (except no_relation)""" label_list = ['no_relation', 'org:top_members/employees', 'org:members', 'org:product', 'per:title', 'org:alterna...
dirs = glob.glob(f"{path}*") matches = [re.search(rf"%s(\d+)" % path.stem, d) for d in dirs] i = [int(m.groups()[0]) for m in matches if m] n = max(i) + 1 if i else 2 path = f"{path}{n}" if not os.path.exists(path): os.mkdir(path) return path
conditional_block
InternetMonitorClient.ts
// smithy-typescript generated code import { getHostHeaderPlugin, HostHeaderInputConfig, HostHeaderResolvedConfig, resolveHostHeaderConfig, } from "@aws-sdk/middleware-host-header"; import { getLoggerPlugin } from "@aws-sdk/middleware-logger"; import { getRecursionDetectionPlugin } from "@aws-sdk/middleware-rec...
import { getRetryPlugin, resolveRetryConfig, RetryInputConfig, RetryResolvedConfig } from "@smithy/middleware-retry"; import { HttpHandler as __HttpHandler } from "@smithy/protocol-http"; import { Client as __Client, DefaultsMode as __DefaultsMode, SmithyConfiguration as __SmithyConfiguration, SmithyResolvedCon...
import { RegionInputConfig, RegionResolvedConfig, resolveRegionConfig } from "@smithy/config-resolver"; import { getContentLengthPlugin } from "@smithy/middleware-content-length"; import { EndpointInputConfig, EndpointResolvedConfig, resolveEndpointConfig } from "@smithy/middleware-endpoint";
random_line_split
InternetMonitorClient.ts
// smithy-typescript generated code import { getHostHeaderPlugin, HostHeaderInputConfig, HostHeaderResolvedConfig, resolveHostHeaderConfig, } from "@aws-sdk/middleware-host-header"; import { getLoggerPlugin } from "@aws-sdk/middleware-logger"; import { getRecursionDetectionPlugin } from "@aws-sdk/middleware-rec...
extends __Client< __HttpHandlerOptions, ServiceInputTypes, ServiceOutputTypes, InternetMonitorClientResolvedConfig > { /** * The resolved configuration of InternetMonitorClient class. This is resolved and normalized from the {@link InternetMonitorClientConfig | constructor configuration interface}. */ ...
InternetMonitorClient
identifier_name