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
main.py
float(args[10]) dGt3 = float(args[11]) out_file = args[12] all_file = args[13] all_kept_mutants = [] all_mutants_tried = [] output_dict = {} count = 0 initialize_output_files(out_file, all_...
(out_file, line): output = open(out_file, 'a') output.write(line) output.close() def does_file_exist(prefix, i, count, all_kept_mutants, all_mutants_tried): file_exists = True if not os.path.isfile(prefix + '.pdb') and i > 0: all_kept_mutants = all_kept_mutants[0:-1] prefix = all_k...
write_line
identifier_name
main.py
float(args[10]) dGt3 = float(args[11]) out_file = args[12] all_file = args[13] all_kept_mutants = [] all_mutants_tried = [] output_dict = {} count = 0 initialize_output_files(out_file, all_...
continue #Declare the score parsing object score_ob = pyros.Scores() score_ob.parseAnalyzeComplex() #Grab the scores to be used in the probability calculations ids = score_ob.getIds() stab1 = [score_ob.getStability1()[0], score_ob...
score_ob.cleanUp(['*' + new_mutant_name[0:-4] + '*', '*energies*']) remaining_mutations.append(mutation_code)
random_line_split
main.py
ant_name[0:-4]) count += 1 to_file = str(count) + '.pdb' + '\t' + str(ids[1][0:-4]) + '\t' + str(count) + '\t' + str(stab1[1]) + '\t' + str(stab2[1]) + '\t' + str(binding[1]) + '\t' + str(probability) + '\n' write_line(all_file, to_file) if random.random() < probability...
return (chain.get_id() in self.chain_letters)
identifier_body
Tetris.go
}, {0, -2}, {1, -2}} //2->L case4 = [][]int{{-1, 0}, {-1, -1}, {0, 2}, {-1, 2}} //L->0 //for I Tetromino's case (clockwise direction) case1_i = [][]int{{-2, 0}, {1, 0}, {-2, -1}, {1, 2}} //0->R case2_i = [][]int{{-1, 0}, {2, 0}, {-1, 2}, {2, -1}} //R->2 case3_i = [][]int{{2, 0}, {-1, 0}, {2, 1}, {-1, -2}} //2-...
(board [][]int, Shape [][][]int) Block { randomNum := rand.Intn(len(Shape) - 1) randomShape := makeCopy(Shape[randomNum]) coordinateX := int(len(board[0])/2) - len(randomShape[0]) + 1 coordinateY := -2 block := Block{coordinateX, coordinateY, randomShape, randomNum, 0} block.reInit() return block } // func init...
randomBlock
identifier_name
Tetris.go
1}, {0, -2}, {1, -2}} //2->L case4 = [][]int{{-1, 0}, {-1, -1}, {0, 2}, {-1, 2}} //L->0 //for I Tetromino's case (clockwise direction) case1_i = [][]int{{-2, 0}, {1, 0}, {-2, -1}, {1, 2}} //0->R case2_i = [][]int{{-1, 0}, {2, 0}, {-1, 2}, {2, -1}} //R->2 case3_i = [][]int{{2, 0}, {-1, 0}, {2, 1}, {-1, -2}} //2...
if !checkCollision(land, *block) { flag = true break } else { block.x = tempX block.y = tempY } } } } else { if block.rotateType == 0 { //0->R for i := range case1_i { block.x += case1_i[i][0] block.y += case1_i[i][1] if !checkCollision(land, *block)...
block.y += case4[i][1]
random_line_split
Tetris.go
}, {0, -2}, {1, -2}} //2->L case4 = [][]int{{-1, 0}, {-1, -1}, {0, 2}, {-1, 2}} //L->0 //for I Tetromino's case (clockwise direction) case1_i = [][]int{{-2, 0}, {1, 0}, {-2, -1}, {1, 2}} //0->R case2_i = [][]int{{-1, 0}, {2, 0}, {-1, 2}, {2, -1}} //R->2 case3_i = [][]int{{2, 0}, {-1, 0}, {2, 1}, {-1, -2}} //2-...
// func checkCollision(land [][]int, block Block) bool { for i := range block.shape { for j := range block.shape[0] { if block.shape[i][j] != 0 { if block.x+j < 0 || block.x+j > colSize-1 || block.y+i > rowSize-1 { return true } else if block.x+j >= 0 && block.x+j <= colSize-1 && block.y+i <= rowSi...
{ newArray := make([][]int, len(arr)) for i := range arr { newArray[i] = make([]int, len(arr[0])) for j := range arr[0] { newArray[i][j] = arr[i][j] } } return newArray }
identifier_body
Tetris.go
j := 0 + i; j < len(block.shape[0]); j++ { //swap block.shape[j][i], block.shape[i][j] = block.shape[i][j], block.shape[j][i] } } } // func (block *Block) reverseColumn() { temp := 0 pivot := int(len(block.shape[0]) / 2) //swap column i with column len(block.shape)-1-i for i := range block.shape { for ...
{ fmt.Print("\033[1m_ ") }
conditional_block
ui.rs
game.display_center [0] as f64}, @{-game.display_center [1] as f64}); context.translate (@{game.display_radius as f64}, @{game.display_radius as f64}); } for object in Detector::objects_near_box (accessor, & get_detector (accessor), BoundingBox::centered (to_collision_vector (if game.display_radius > INITI...
(time: f64, game: Rc<RefCell<Game>>) { //let continue_simulating; { let mut game = game.borrow_mut(); let observed_duration = time - game.last_ui_time; let duration_to_simulate = if observed_duration < 100.0 {observed_duration} else {100.0}; let duration_to_simulate = (duration_to_simulate*(SECOND ...
main_loop
identifier_name
ui.rs
} pub fn draw_game <A: Accessor <Steward = Steward>>(accessor: &A, game: & Game) { let canvas_width: f64 = js! {return canvas.width;}.try_into().unwrap(); let scale = canvas_width/(game.display_radius as f64*2.0); js! { var size = Math.min (window.innerHeight, window.innerWidth); canvas.setAttribute ("w...
display_center: Vector::new (0, 0), display_radius: INITIAL_PALACE_DISTANCE*3/2, selected_object: None, }
random_line_split
ui.rs
game.display_center [0] as f64}, @{-game.display_center [1] as f64}); context.translate (@{game.display_radius as f64}, @{game.display_radius as f64}); } for object in Detector::objects_near_box (accessor, & get_detector (accessor), BoundingBox::centered (to_collision_vector (if game.display_radius > INITI...
if varying.awareness_range >0 && varying.object_type != ObjectType::Beast {js! { context.beginPath(); context.arc (@{center [0]},@{center [1]},@{varying.awareness_range as f64}, 0, Math.PI*2); context.lineWidth = @{0.3/scale}; context.stroke(); }} if let Some(home) = varying.home.as...
{js! { context.beginPath(); context.arc (@{center [0]},@{center [1]},@{varying.interrupt_range as f64}, 0, Math.PI*2); context.lineWidth = @{0.3/scale}; context.stroke(); }}
conditional_block
ui.rs
{}", varying.food/STANDARD_FOOD_UPKEEP_PER_SECOND,varying.food_cost/STANDARD_FOOD_UPKEEP_PER_SECOND)} else { format!("Food: ~{} ({} available)", varying.food/STANDARD_FOOD_UPKEEP_PER_SECOND, (varying.food - reserved_food(accessor, selected))/STANDARD_FOOD_UPKEEP_PER_SECOND)}}), $("<div>").text(@{format!("HP: {}/{...
{ let mut scores = [0; 2]; loop { let mut game = make_game(DeterministicRandomId::new (& (scores, 0xae06fcf3129d0685u64))); loop { game.now += SECOND /100; let snapshot = game.steward.snapshot_before (& game.now). unwrap (); game.steward.forget_before (& game.now); /*let teams_ali...
identifier_body
cached.go
KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cached import ( "errors" "sync" "time" "github.com/square/metrics/api" "github.com/square/metrics/log" "github.com/square/metrics/metric_metadata" "github.com/squa...
item.Lock() if item.Expiry.IsZero() || item.Expiry.Before(c.clock.Now()) { if item.inflight { item.Unlock() item.wg.Wait() // Make sure we have the lock to re-read item.Lock() defer item.Unlock() // If the request we were waiting on errored, we also errored return item.Tag
c.getAllTagsCacheMutex.Unlock() }
random_line_split
cached.go
KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cached import ( "errors" "sync" "time" "github.com/square/metrics/api" "github.com/square/metrics/log" "github.com/square/metrics/metric_metadata" "github.com/squa...
else { log.Warningf("Asked to update the tag set for %s but new expiry is earlier than current (%s vs %s)", metricKey, newExpiry.String(), item.Expiry.String()) } item.wg.Done() item.inflight = false return tagsets, nil } // GetAllTags uses the cache to serve tag data for the given metric. // If the cache ...
{ item.TagSets = tagsets item.Expiry = newExpiry item.Stale = startTime.Add(c.freshness) }
conditional_block
cached.go
KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cached import ( "errors" "sync" "time" "github.com/square/metrics/api" "github.com/square/metrics/log" "github.com/square/metrics/metric_metadata" "github.com/squa...
// CheckHealthy checks if the underlying MetricAPI is healthy func (c *metricMetadataAPI) CheckHealthy() error { return c.metricMetadataAPI.CheckHealthy() } // fetchAndUpdateCachedTagSet updates the in-memory cache (asusming the update // is newer than what is in the cache). Requires the caller hold the lock for th...
{ return c.metricMetadataAPI.GetMetricsForTag(tagKey, tagValue, context) }
identifier_body
cached.go
KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cached import ( "errors" "sync" "time" "github.com/square/metrics/api" "github.com/square/metrics/log" "github.com/square/metrics/metric_metadata" "github.com/squa...
(metrics []api.TaggedMetric, context metadata.Context) error { return c.metricMetadataAPI.(metadata.MetricUpdateAPI).AddMetrics(metrics, context) } // Config stores data needed to instantiate a CachedMetricMetadataAPI. type Config struct { Freshness time.Duration RequestLimit int TimeToLive time.Duration } /...
AddMetrics
identifier_name
util.rs
` and `path` do not share a common ancestor. `path` and `base` must be /// either both absolute or both relative; returns `None` if one is relative and /// the other absolute. /// /// ``` /// use std::path::Path; /// use figment::util::diff_paths; /// /// // Paths must be both relative or both absolute. /// assert_eq!(...
} comps.push(a); comps.extend(ita.by_ref()); break; } } } Some(comps.iter().map(|c| c.as_os_str()).collect()) } /// A helper to deserialize `0/false` as `false` and `1/true` as `true`. /// /// Serde's default deserializer for ...
(Some(a), Some(_)) => { comps.push(Component::ParentDir); for _ in itb { comps.push(Component::ParentDir);
random_line_split
util.rs
` and `path` do not share a common ancestor. `path` and `base` must be /// either both absolute or both relative; returns `None` if one is relative and /// the other absolute. /// /// ``` /// use std::path::Path; /// use figment::util::diff_paths; /// /// // Paths must be both relative or both absolute. /// assert_eq!(...
fn visit_u64<E: de::Error>(self, n: u64) -> Result<bool, E> { match n { 0 | 1 => Ok(n != 0), n => Err(E::invalid_value(Unexpected::Unsigned(n), &"0 or 1")) } } fn visit_i64<E: de::Error>(self, n: i64) -> Result<bool, E> { mat...
{ match val { v if uncased::eq(v, "true") => Ok(true), v if uncased::eq(v, "false") => Ok(false), s => Err(E::invalid_value(Unexpected::Str(s), &"true or false")) } }
identifier_body
util.rs
` and `path` do not share a common ancestor. `path` and `base` must be /// either both absolute or both relative; returns `None` if one is relative and /// the other absolute. /// /// ``` /// use std::path::Path; /// use figment::util::diff_paths; /// /// // Paths must be both relative or both absolute. /// assert_eq!(...
<'de, D: Deserializer<'de>>(de: D) -> Result<bool, D::Error> { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { type Value = bool; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("a boolean") } fn visit_str<E: de::Error>(self, v...
bool_from_str_or_int
identifier_name
main.rs
add_piece(&mut self, span: Span) -> Piece { self.pieces.push(PieceData { span: span, prev: SENTINEL, next: SENTINEL, } ); Piece((self.pieces.len() - 1) as u32) } /// Delete bytes between off1 (inclusive) and off2 (exclusive) pub fn delete(&mu...
{ let literal = between(char('/'), char('/'), many(satisfy(|c| c != '/')).map(Command::Insert)); let spaces = spaces(); spaces.with(char('i').with(literal)).parse(s) }
identifier_body
main.rs
} } impl AppendOnlyBuffer { /// Constructs a new, empty AppendOnlyBuffer. pub fn new() -> AppendOnlyBuffer { AppendOnlyBuffer { buf: Vec::with_capacity(4096) } } /// Append a slice of bytes. pub fn append(&mut self, bytes: &[u8]) -> Span { let off1 = self.b...
{ Some((Span::new(self.off1, self.off1+n), Span::new(self.off1+n, self.off2))) }
conditional_block
main.rs
. That is fine because we never free a piece anyway (unlimited undo /// for the win). #[derive(Debug, Copy, Clone, PartialEq, Eq)] struct Piece(u32); /// The actual data stored in a piece. /// We have one sentinel piece which is always stored at index 0 /// in the vector. It's span is also empty #[derive(Debug)] s...
} /// Iterator over all pieces (but never the sentinel) fn pieces(&self) -> Pieces { let next = self.get_piece(SENTINEL).next; Pieces { text: self, next: next, off: 0, } } /// Length of Text in bytes pub fn len(&self) -> usize { ...
l += len; p = self.get_piece(p).prev; } assert_eq!(l as usize, self.len());
random_line_split
main.rs
That is fine because we never free a piece anyway (unlimited undo /// for the win). #[derive(Debug, Copy, Clone, PartialEq, Eq)] struct Piece(u32); /// The actual data stored in a piece. /// We have one sentinel piece which is always stored at index 0 /// in the vector. It's span is also empty #[derive(Debug)] st...
(&mut self, piece1: Piece, piece2: Piece) { let Piece(p1) = piece1; let Piece(p2) = piece2; self.pieces[p1 as usize].next = piece2; self.pieces[p2 as usize].prev = piece1; } /// Find the piece containing offset. Return piece /// and start position of piece in text. ///...
link
identifier_name
math.rs
.clone() == other.n.clone() * self.d.clone(); } } impl PartialOrd for Rat { fn partial_cmp(&self, other : &Rat) -> Option<std::cmp::Ordering> { return (self.n.clone() * other.d.clone()).partial_cmp(&(other.n.clone() * self.d.clone())); } } impl Eq for Rat { } impl Ord for Rat { fn cmp(&self,...
} fn index_of(&mut self, v : AST) -> Option<usize> { match v { AST::Int(n) => if n < Zero::zero() { match to_usize(&-n) { Ok(m) => Some(2*m - 1), _ => None } } else { ...
} fn increasing(&self) -> bool { return false;
random_line_split
math.rs
() == other.n.clone() * self.d.clone(); } } impl PartialOrd for Rat { fn partial_cmp(&self, other : &Rat) -> Option<std::cmp::Ordering> { return (self.n.clone() * other.d.clone()).partial_cmp(&(other.n.clone() * self.d.clone())); } } impl Eq for Rat { } impl Ord for Rat { fn cmp(&self, other...
fn calc_nth(&mut self, n : usize) -> Result<Rat, String> { let mut res = Rat::from_usize(1); for (p,a) in prime_factor(BigInt::from(n), &mut self.ps) { let b = int_nth(to_usize(&a)?); let r = Rat::new(p.clone(), One::one()).pow(&b); // println!("{}: {}^({} => {}...
{ return Rationals { ps : PrimeSeq::new() }; }
identifier_body
math.rs
() == other.n.clone() * self.d.clone(); } } impl PartialOrd for Rat { fn partial_cmp(&self, other : &Rat) -> Option<std::cmp::Ordering> { return (self.n.clone() * other.d.clone()).partial_cmp(&(other.n.clone() * self.d.clone())); } } impl Eq for Rat { } impl Ord for Rat { fn cmp(&self, other...
(&self) -> bool { return false; } fn index_of(&mut self, v : AST) -> Option<usize> { let (mut n,d) = match v { AST::Int(n) => (n, One::one()), AST::Rat(Rat{n,d}) => (n,d), _ => return None }; let neg = n < Zero::zero(); if neg { ...
increasing
identifier_name
rtorrent.py
FailedToExecuteException from ..scgitransport import SCGITransport from ..torrent import TorrentData, TorrentFile, TorrentState from ..utils import ( calculate_minimum_expected_data, has_minimum_expected_data, map_existing_files, ) logger = logging.getLogger(__name__) def create_proxy(url): parsed =...
else: logger.debug(f"Creating Normal XMLRPC Proxy with url {url}") return ServerProxy(url) def bitfield_to_string(bitfield): """ Converts a list of booleans into a bitfield """ retval = bytearray((len(bitfield) + 7) // 8) for piece, bit in enumerate(bitfield): if bit:...
if parsed.netloc: url = f"http://{parsed.netloc}" logger.debug(f"Creating SCGI XMLRPC Proxy with url {url}") return ServerProxy(url, transport=SCGITransport()) else: path = parsed.path logger.debug(f"Creating SCGI XMLRPC Socket Proxy with socket file {...
conditional_block
rtorrent.py
FailedToExecuteException from ..scgitransport import SCGITransport from ..torrent import TorrentData, TorrentFile, TorrentState from ..utils import ( calculate_minimum_expected_data, has_minimum_expected_data, map_existing_files, ) logger = logging.getLogger(__name__) def create_proxy(url): parsed =...
(self): url = f"{self.identifier}+{self.url}" query = {} if self.session_path: query["session_path"] = str(self.session_path) if query: url += f"?{urlencode(query)}" return url @classmethod def auto_configure(cls, path="~/.rtorrent.rc"): ...
serialize_configuration
identifier_name
rtorrent.py
import FailedToExecuteException from ..scgitransport import SCGITransport from ..torrent import TorrentData, TorrentFile, TorrentState from ..utils import ( calculate_minimum_expected_data, has_minimum_expected_data, map_existing_files, ) logger = logging.getLogger(__name__) def create_proxy(url): p...
return ServerProxy(url, transport=SCGITransport()) else: path = parsed.path logger.debug(f"Creating SCGI XMLRPC Socket Proxy with socket file {path}") return ServerProxy("http://1", transport=SCGITransport(socket_path=path)) else: logger.debug(f"Creati...
if parsed.netloc: url = f"http://{parsed.netloc}" logger.debug(f"Creating SCGI XMLRPC Proxy with url {url}")
random_line_split
rtorrent.py
FailedToExecuteException from ..scgitransport import SCGITransport from ..torrent import TorrentData, TorrentFile, TorrentState from ..utils import ( calculate_minimum_expected_data, has_minimum_expected_data, map_existing_files, ) logger = logging.getLogger(__name__) def create_proxy(url):
def bitfield_to_string(bitfield): """ Converts a list of booleans into a bitfield """ retval = bytearray((len(bitfield) + 7) // 8) for piece, bit in enumerate(bitfield): if bit: retval[piece // 8] |= 1 << (7 - piece % 8) return bytes(retval) class RTorrentClient(BaseCl...
parsed = urlsplit(url) proto = url.split(":")[0].lower() if proto == "scgi": if parsed.netloc: url = f"http://{parsed.netloc}" logger.debug(f"Creating SCGI XMLRPC Proxy with url {url}") return ServerProxy(url, transport=SCGITransport()) else: path ...
identifier_body
server.rs
on_read(&mut self, reactor: &mut Reactor, c: &mut ConnectionState<St>, buf: RWIobuf<'static>) -> MioResult<()>; fn on_close(&mut self, _reactor: &mut Reactor, _c: &mut ConnectionState<St>) -> MioResult<()> { Ok(()) } } /// Global state for a server. pub struct Global<St> { /// This should really be a lock-fre...
global: Rc<Global<St>>, on_accept: fn(reactor: &mut Reactor) -> C) -> AcceptHandler<St, C> { AcceptHandler { accept_socket: accept_socket, global: global, on_accept: on_accept, } } } impl<St, C: PerClient<St>> Handl...
random_line_split
server.rs
match buf.into_vec() { Some(v) => { if v.len() == READBUF_SIZE { readbuf_pool.push(v); } }, _ => {}, } } #[inline(always)] pub fn state(&self) -> &St { &self.custom_state } } bitflags! { flags Flags...
{ // TODO(cgaebel): ipv6? udp? let socket: TcpSocket = try!(TcpSocket::v4()); let mut client = Some(client); let global = Rc::new(Global::new(())); reactor.connect(socket, connect_to, |socket| { tweak_sock_opts(&socket); Connection::new(socket, global.clone(), client.take().unw...
identifier_body
server.rs
_read(&mut self, reactor: &mut Reactor, c: &mut ConnectionState<St>, buf: RWIobuf<'static>) -> MioResult<()>; fn on_close(&mut self, _reactor: &mut Reactor, _c: &mut ConnectionState<St>) -> MioResult<()> { Ok(()) } } /// Global state for a server. pub struct Global<St> { /// This should really be a lock-free s...
let mut readbuf_pool = self.readbuf_pool.borrow_mut(); let mut ret = match readbuf_pool.pop() { None => RWIobuf::new(READBUF_SIZE), Some(v) => RWIobuf::from_vec(v), }; debug_assert!(ret.cap() == READBUF_SIZE); ret.set_limits_...
{ return RWIobuf::new(capacity); }
conditional_block
server.rs
_read(&mut self, reactor: &mut Reactor, c: &mut ConnectionState<St>, buf: RWIobuf<'static>) -> MioResult<()>; fn on_close(&mut self, _reactor: &mut Reactor, _c: &mut ConnectionState<St>) -> MioResult<()> { Ok(()) } } /// Global state for a server. pub struct Global<St> { /// This should really be a lock-free s...
(&mut self, reactor: &mut Reactor) -> MioResult<()> { match self.tick(reactor) { Ok(x) => Ok(x), Err(e) => { // We can't really use this. We already have an error! let _ = self.per_client.on_close(reactor, &mut self.state); Err(e) ...
checked_tick
identifier_name
main.go
env("SQLX_URL")) if err != nil { log.Fatalf("failed to connect to the db: %s", err) } } // InitializeRedis 初始化Redis func InitializeRedis() { opt, err := redis.ParseURL(os.Getenv("REDIS_URL")) if err != nil { log.Fatalf("failed to connect to redis db: %s", err) } // Create client as usually. redisClient = r...
sql", os.Get
identifier_name
main.go
a[i] } func (a Articles) Less(i, j int) bool { v := strings.Compare(a[i].Date, a[j].Date) if v <= 0 { return true } return false } // RandomN return n articles by random func (a Articles) RandomN(n int) Articles { if n <= 0 { return nil } length := len(a) pos := rand.Intn(length - n) return a[pos : po...
DirName: dirname, PubDate: pubDate, Description: desc, } } // LoadMDs 读取给定目录中的所有markdown文章 func LoadMDs(dirname string) Articles { files, err := ioutil.ReadDir(dirname) if err != nil { log.Fatalf("failed to read dir(%s): %s", dirname, err) return nil } var articles Articles for _, file := rang...
Date: dateString, Filename: filename,
random_line_split
main.go
[i] } func (a Articles) Less(i, j int) bool { v := strings.Compare(a[i].Date, a[j].Date) if v <= 0 { return true } return false } // RandomN return n articles by random func (a Articles) RandomN(n int) Articles { if n <= 0 { return nil } length := len(a) pos := rand.Intn(length - n) return a[pos : pos+...
sited) if err != nil { return "", ErrFailedToLoad } return string(b), nil } func getTopVisited(n int) []VisitedArticle { visitedArticles := []VisitedArticle{} articles, err := redisClient.ZRevRangeByScore(zsetKey, &redis.ZRangeBy{ Min: "-inf", Max: "+inf", Offset: 0, Count: int64(n), }).Result() if err !=...
e} b, err := json.Marshal(vi
conditional_block
main.go
a[i] } func (a Articles) Less(i, j int) bool { v := strings.Compare(a[i].Date, a[j].Date) if v <= 0 { return true } return false } // RandomN return n articles by random func (a Articles) RandomN(n int) Articles { if n <= 0 { return nil } length := len(a) pos := rand.Intn(length - n) return a[pos : po...
// ReadTitle 把标题读出来 func ReadTitle(path string) string { path = getFilePath(path) file, err := os.Open(path) if err != nil { log.Printf("failed to read file(%s): %s", path, err) return "" } line, _, err := bufio.NewReader(file).ReadLine() if err != nil { log.Printf("failed to read title of file(%s): %s", ...
to read file(%s): %s", path, err) return "" } reader := bufio.NewReader(file) reader.ReadLine() // 忽略第一行(标题) reader.ReadLine() // 忽略第二行(空行) desc := "" for i := 0; i < 3; i++ { line, _, err := reader.ReadLine() if err != nil && err != io.EOF { log.Printf("failed to read desc of file(%s): %s", path, err) ...
identifier_body
sequences.py
batch {} with {} items via sequence".format(index, self.batch_size)) raw_features, raw_responses, raw_weights = self._get_features_responses_weights(index) trans_features = [raw_feature.copy() for raw_feature in raw_features] trans_responses = [raw_response.copy() for raw_response in raw_respo...
current_array += 1 if current_array == len(self.features): break stop_ind = self.batch_size - batch_features.shape[0] batch_features = np.append( batch_features, (self.features[current_array])[sample_index:stop_ind, ...], axis=0 ...
current_array = 0 while current_array < len(self.cum_samples_per_array) - 1: if ( index * self.batch_size >= self.cum_samples_per_array[current_array] and index * self.batch_size < self.cum_samples_per_array[current_array + 1] ): break ...
identifier_body
sequences.py
{} with {} items via sequence".format(index, self.batch_size)) raw_features, raw_responses, raw_weights = self._get_features_responses_weights(index) trans_features = [raw_feature.copy() for raw_feature in raw_features] trans_responses = [raw_response.copy() for raw_response in raw_responses] ...
else: # This is for Keras sequence generator behavior return_value = (trans_features, trans_responses) return return_value def get_raw_and_transformed_sample( self, index: int ) -> Tuple[Tuple[List[np.array], List[np.array]], Tuple[List[np.array], List[np.array]...
return_value = ((raw_features, raw_responses), (trans_features, trans_responses))
conditional_block
sequences.py
{} with {} items via sequence".format(index, self.batch_size)) raw_features, raw_responses, raw_weights = self._get_features_responses_weights(index) trans_features = [raw_feature.copy() for raw_feature in raw_features] trans_responses = [raw_response.copy() for raw_response in raw_responses] ...
(self, index: int) -> Tuple[List[np.array], List[np.array], List[np.array]]: # start by finding which array we're starting in, based on the input index, batch size, # and the number of samples per array current_array = 0 while current_array < len(self.cum_samples_per_array) - 1: ...
_get_features_responses_weights
identifier_name
sequences.py
{} with {} items via sequence".format(index, self.batch_size)) raw_features, raw_responses, raw_weights = self._get_features_responses_weights(index) trans_features = [raw_feature.copy() for raw_feature in raw_features] trans_responses = [raw_response.copy() for raw_response in raw_responses] ...
return_value = ((raw_features, raw_responses), (trans_features, trans_responses)) else: # This is for Keras sequence generator behavior return_value = (trans_features, trans_responses) return return_value def get_raw_and_transformed_sample( self, index: i...
if return_raw_sample is True: # This is for BGFN reporting and other functionality
random_line_split
data.ts
'; /** Indicates a hourly frequency type */ export const HOUR = 'hour'; /** Indicates a daily frequency type */ export const DAY = 'day'; /** Indicates a weekly frequency type */ export const WEEK = 'week'; /** Indicates a monthly frequency type */ export const MONTH = 'month'; /** Interface for an <option> inside a <...
(masterType: string): Option[] { if (masterType) { if (MASTER_TYPES_REDUCED.has(masterType)) { return ACCELERATOR_TYPES_REDUCED; } return ACCELERATOR_TYPES; } return []; } /** * AI Platform Accelerator counts. * https://cloud.google.com/ai-platform/training/docs/using-gpus */ export const AC...
getAcceleratorTypes
identifier_name
data.ts
'; /** Indicates a hourly frequency type */ export const HOUR = 'hour'; /** Indicates a daily frequency type */ export const DAY = 'day'; /** Indicates a weekly frequency type */ export const WEEK = 'week'; /** Indicates a monthly frequency type */ export const MONTH = 'month'; /** Interface for an <option> inside a <...
export const DAYS_OF_WEEK: Option[] = [ { value: 'sundayRun', text: 'Sun' }, { value: 'mondayRun', text: 'Mon' }, { value: 'tuesdayRun', text: 'Tue' }, { value: 'wednesdayRun', text: 'Wed' }, { value: 'thursdayRun', text: 'Thur' }, { value: 'fridayRun', text: 'Fri' }, { value: 'saturdayRun', text: 'Sat'...
{ if (value === undefined) return undefined; return options.find(option => option.value === value); }
identifier_body
data.ts
'; /** Indicates a hourly frequency type */ export const HOUR = 'hour'; /** Indicates a daily frequency type */ export const DAY = 'day'; /** Indicates a weekly frequency type */ export const WEEK = 'week'; /** Indicates a monthly frequency type */ export const MONTH = 'month'; /** Interface for an <option> inside a <...
return []; } /** * AI Platform Accelerator counts. * https://cloud.google.com/ai-platform/training/docs/using-gpus */ export const ACCELERATOR_COUNTS_1_2_4_8: Option[] = [ { value: '1', text: '1' }, { value: '2', text: '2' }, { value: '4', text: '4' }, { value: '8', text: '8' }, ]; /** * Supported AI P...
{ if (MASTER_TYPES_REDUCED.has(masterType)) { return ACCELERATOR_TYPES_REDUCED; } return ACCELERATOR_TYPES; }
conditional_block
data.ts
'; /** Indicates a hourly frequency type */ export const HOUR = 'hour'; /** Indicates a daily frequency type */ export const DAY = 'day'; /** Indicates a weekly frequency type */ export const WEEK = 'week'; /** Indicates a monthly frequency type */ export const MONTH = 'month'; /** Interface for an <option> inside a <...
* if masterType is falsy. */ export function getAcceleratorTypes(masterType: string): Option[] { if (masterType) { if (MASTER_TYPES_REDUCED.has(masterType)) { return ACCELERATOR_TYPES_REDUCED; } return ACCELERATOR_TYPES; } return []; } /** * AI Platform Accelerator counts. * https://cloud.g...
]); /** * Returns the valid accelerator types given a masterType. Returns empty array
random_line_split
classic.py
(self, sevr): if sevr==0: return '' try: return self.severityInfo[sevr]['sevr'] except KeyError: return str(sevr) def status(self, stat): if stat==0: return '' try: return self.statusInfo[stat] except IndexE...
severity
identifier_name
classic.py
catch basic syntax errors re.compile(pattern) archs = self._archname2key(archs) _log.debug('Searching for %s in %s', pattern, archs) Ds = [None]*len(archs) for i,a in enumerate(archs): Ds[i] = self._proxy.callRemote('archiver.names', a, pattern).addErr...
F, L, K = breakDown[-1] LS, LN = L plan.append(((LS+1,0),(LS+2,0),K)) count=1 _log.debug("Returning last sample. No data in or after requested time range.")
conditional_block
classic.py
# map from key to name self.__rarchs = dict([(x['key'],x['name']) for x in archs]) def severity(self, sevr): if sevr==0: return '' try: return self.severityInfo[sevr]['sevr'] except KeyError: return str(sevr) def status(self, stat): ...
""" """ def __init__(self, proxy, conf, info, archs): self._proxy = proxy self.conf = conf if PVER < info['ver']: _log.warn('Archive server protocol version %d is newer then ours (%d).\n'+ 'Attempting to proceed.', info['ver'], PVER) self.descri...
identifier_body
classic.py
junk, A) in enumerate(Ds): for R in A: # Note: Order based on sorting by key name ens, es, ss, sns, pv = R.values() F = (ss, sns) L = (es, ens) if not rawTime: F, L = makeTime(F), ...
callback=callback, cbArgs=cbArgs, cbKWs=cbKWs, chunkSize=chunkSize,
random_line_split
app.js
"); //APP.USE for middleware elements app.use(bodyParser.urlencoded({extended: true})); //*** app.use(methodOverride("_method")); //*** app.use(express.static('public')); //the 'static' directory holds CSS files, images, etc. app.use(session({ //*** secret: 'only for Worldstats', resave: false, saveUniniti...
; var scoreKey = { "numCorrect":correctScore, "answerKey":answerMatrix }; return scoreKey; }; app.get('/nextquestion', function(req,res){ if (req.session.nextRound >= req.session.maxRounds) { //nextRound was already incremented in game.js -- so if nextRound is already beyond ...
{ if (playerAnswer[i] === fullAnswer[i][0]) { correctScore++; answerMatrix.push([fullAnswer[i][0],fullAnswer[i][1],"Correct"]); } else { answerMatrix.push([fullAnswer[i][0],fullAnswer[i][1],playerAnswer[i]]); } }
conditional_block
app.js
ejs"); //APP.USE for middleware elements app.use(bodyParser.urlencoded({extended: true})); //*** app.use(methodOverride("_method")); //*** app.use(express.static('public')); //the 'static' directory holds CSS files, images, etc. app.use(session({ //*** secret: 'only for Worldstats', resave: false, saveUnin...
var answerCountryandValue = req.session.countryAndValueData; for (var id in req.query) { playerAnswer.push(req.query[id]); // console.log("This is the answer value",id, req.query[id]); }; for (var i = 0; i < answerCountryandValue.length; i++) { correctAnswer.push(answerCountrya...
app.get('/answer', function(req,res){ console.log("Hello from answer page"); var playerAnswer = []; var correctAnswer = [];
random_line_split
instruments.rs
} } /// Prepare the Xcode Instruments profiling command /// /// If the `xctrace` tool is used, the prepared command looks like /// /// ```sh /// xcrun xctrace record --template MyTemplate \ /// --time-limit 5000ms \ /// --output path/to/tra...
() -> Result<TemplateCatalog> { let Output { status, stdout, stderr } = Command::new("xcrun").args(["xctrace", "list", "templates"]).output()?; if !status.success() { return Err(anyhow!( "Could not list templates. Please check your Xcode Instruments installation." )); } ...
parse_xctrace_template_list
identifier_name
instruments.rs
/// System Trace /// Time Profiler /// Zombies /// /// == Custom Templates == /// MyTemplate /// ``` fn parse_xctrace_template_list() -> Result<TemplateCatalog> { let Output { status, stdout, stderr } = Command::new("xcrun").args(["xctrace", "list", "templates"]).output()?; if !status.success() { ...
{ let stderr = String::from_utf8(output.stderr).unwrap_or_else(|_| "failed to capture stderr".into()); let stdout = String::from_utf8(output.stdout).unwrap_or_else(|_| "failed to capture stdout".into()); return Err(anyhow!("instruments errored: {} {}", stderr, stdout)); ...
conditional_block
instruments.rs
(["-t", template_name]); command.arg("-D").arg(trace_filepath); if let Some(limit) = time_limit { command.args(["-l", &limit.to_string()]); } Ok(command) } } } } /// Return the macOS version. /// /// This func...
{ match template_name { "time" => "Time Profiler", "alloc" => "Allocations", "io" => "File Activity", "sys" => "System Trace", other => other, } }
identifier_body
instruments.rs
command.args(["-l", &limit.to_string()]); } Ok(command) } } } } /// Return the macOS version. /// /// This function parses the output of `sw_vers -productVersion` (a string like '11.2.3`) /// and returns the corresponding semver struct `Version{major: 11, minor:...
/// Return the template name abbreviation if available. fn abbrev_name(template_name: &str) -> Option<&str> { match template_name {
random_line_split
a_fullscreen_wm.rs
, Debug, Clone)] pub struct FullscreenWM { /// A vector of windows, the first one is on the bottom, the last one is /// on top, and also the only visible window. pub windows: VecDeque<Window>, /// We need to know which size the fullscreen window must be. pub screen: Screen, /// Window that is fo...
{ Err(FullscreenWMError::UnknownWindow(window)) }
conditional_block
a_fullscreen_wm.rs
of data structure. But this is certainly not /// required. For more information, see the Hints & Tricks section of the /// assignment. /// /// # Example Representation /// /// The fullscreen window manager that we are implementing is very simple: it /// just needs to keep track of all the windows that were added and r...
{ // self.focused_window = window; match window { Some(i_window) => { match self.windows.iter().position(|w| *w == i_window) { None => Err(FullscreenWMError::UnknownWindow(i_window)), Some(i) => { // Set window t...
identifier_body
a_fullscreen_wm.rs
this annotation when you have implemented all methods, so you get // warned about variables that you did not use by mistake. // We import std::error and std::format so we can say error::Error instead of // std::error::Error, etc. use std::error; use std::fmt; use std::collections::VecDeque; // Import some types and t...
/// For more information about why you need this, read the documentation of /// the associated [Error] type of the `WindowManager` trait. /// /// In the code below, we would like to return an error when we are asked to /// do something with a window that we do not manage, so we define an enum /// `FullscreenWMError` wi...
} /// The errors that this window manager can return. ///
random_line_split
a_fullscreen_wm.rs
annotation when you have implemented all methods, so you get // warned about variables that you did not use by mistake. // We import std::error and std::format so we can say error::Error instead of // std::error::Error, etc. use std::error; use std::fmt; use std::collections::VecDeque; // Import some types and the Wi...
(&self) -> &'static str { match *self { FullscreenWMError::UnknownWindow(_) => "Unknown window", FullscreenWMError::WindowAlreadyManaged(_) => "Window Already Managed", } } } // Now we start implementing our window manager impl WindowManager for FullscreenWM { /// We use...
description
identifier_name
lib.rs
, ZoneIndex, ZoneType}; #[rustfmt::skip] pub fn is_admin(obj: &OsmObj) -> bool { match *obj { OsmObj::Relation(ref rel) => { rel.tags .get("boundary") .map_or(false, |v| v == "administrative") && rel.tags.get("admin_level").is_some() ...
pub fn build_cosmogony( pbf_path: String, with_geom: bool, country_code: Option<String>, ) -> Result<Cosmogony, Error> { let path = Path::new(&pbf_path); let file = File::open(&path).context("no pbf file")?; let mut parsed_pbf = OsmPbfReader::new(file); let (mut zones, mut stats) = if wi...
{ info!("creating ontology for {} zones", zones.len()); let inclusions = find_inclusions(zones); type_zones(zones, stats, country_code, &inclusions)?; build_hierarchy(zones, inclusions); zones.iter_mut().for_each(|z| z.compute_names()); compute_labels(zones); // we remove the useless zon...
identifier_body
lib.rs
(ref relation) = *obj { let next_index = ZoneIndex { index: zones.len() }; if let Some(zone) = zone::Zone::from_osm_with_geom(relation, &objects, next_index) { // Ignore zone without boundary polygon for the moment if zone.boundary.is_some() { ...
load_cosmogony
identifier_name
lib.rs
, ZoneIndex, ZoneType}; #[rustfmt::skip] pub fn is_admin(obj: &OsmObj) -> bool { match *obj { OsmObj::Relation(ref rel) =>
_ => false, } } pub fn get_zones_and_stats( pbf: &mut OsmPbfReader<File>, ) -> Result<(Vec<zone::Zone>, CosmogonyStats), Error> { info!("Reading pbf with geometries..."); let objects = pbf .get_objs_and_deps(|o| is_admin(o)) .context("invalid osm file")?; info!("reading pbf...
{ rel.tags .get("boundary") .map_or(false, |v| v == "administrative") && rel.tags.get("admin_level").is_some() }
conditional_block
lib.rs
, ZoneIndex, ZoneType}; #[rustfmt::skip] pub fn is_admin(obj: &OsmObj) -> bool { match *obj { OsmObj::Relation(ref rel) => { rel.tags .get("boundary") .map_or(false, |v| v == "administrative") && rel.tags.get("admin_level").is_some() ...
} Ok((zones, stats)) } fn get_country_code<'a>( country_finder: &'a CountryFinder, zone: &zone::Zone, country_code: &'a Option<String>, inclusions: &Vec<ZoneIndex>, ) -> Option<String> { if let Some(ref c) = *country_code { Some(c.to_uppercase()) } else { country_finder...
random_line_split
main.rs
...#....#.....#..#..#..#........... 2: ...##..##...##....#..#..#..##.......... 3: ..#.#...#..#.#....#..#..#...#.......... 4: ...#.#..#...#.#...#..#..##..##......... 5: ....#...##...#.#..#..#...#...#......... 6: ....##.#.#....#...#..##..##..##........ 7: ...#..###.#...##..#...#...#...#........ 8: ...#....##.#.#.#...
(state: &str) -> PlantsState { let mut result: PlantsState = state.chars().map(|x| x == '#').collect(); for _ in 0..OFFSET { result.insert(0, false); result.push(false); } result } fn get_id_for_combinations_map_item( combinations_map: &mut CombinationsMap, id: CombinationId, ch: char, ) -> Opt...
convert_state_str_to_vec
identifier_name
main.rs
s_to_combinations_map(combinations_strs: &mut Vec<String>) -> CombinationsMap { let mut combinations_map: CombinationsMap = HashMap::new(); let mut current_combination_id = 1; combinations_map.insert( 0, Combination::Branch(CombinationBranch { has_plant: None, empty: None, }), ); for...
.collect() } #[test] fn test_convert_state_str_to_vec() {
random_line_split
main.rs
...##...##..##.. 19: .#..###.#..#.#.#######.#.#.#..#.#...#.. 20: .#....##....#####...#######....#.#..##. The generation is shown along the left, where 0 is the initial state. The pot numbers are shown along the top, where 0 labels the center pot, negative-numbered pots extend to the left, and positive pots extend towa...
{ let mut sum: i64; let mut new_state: PlantsState = orig_state.clone(); let mut last_idx: i64 = 100; let mut diff_a = 0; let mut diff_b = 0; let mut diff_c; // the number 100 is a random high-enough number found empirically new_state = get_new_state_after_n_generations(&mut new_state, &mut combi...
identifier_body
main.rs
...#....#.....#..#..#..#........... 2: ...##..##...##....#..#..#..##.......... 3: ..#.#...#..#.#....#..#..#...#.......... 4: ...#.#..#...#.#...#..#..##..##......... 5: ....#...##...#.#..#..#...#...#......... 6: ....##.#.#....#...#..##..##..##........ 7: ...#..###.#...##..#...#...#...#........ 8: ...#....##.#.#.#...
else { PotState::Empty }; combinations_map.insert( prev_combination_id.unwrap(), Combination::Node(node_content), ); } combinations_map } fn get_result_for_combination_vec( combinations_map: &mut CombinationsMap, combination_vec: &mut PlantsState, ) -> Option<PotState> { let ...
{ PotState::HasPlant }
conditional_block
fetch.rs
} .instrument(tracing::debug_span!("fetch")) .await } pub async fn via_git(url: &url::Url, rev: &str) -> Result<crate::git::GitSource, Error> { // Create a temporary directory to fetch the repo into let temp_dir = tempfile::tempdir()?; // Create another temporary directory where we *may* checkout ...
Ok(()) }) .instrument(tracing::debug_span!("fetch")) .await??; let fetch_rev = rev.to_owned(); let temp_db_path = temp_dir.path().to_owned(); let checkout = tokio::task::spawn(async move { match crate::git::prepare_submodules( temp_db_path, submodule_dir....
repo.revparse_single(&fetch_rev) .with_context(|| format!("{} doesn't contain rev '{}'", fetch_url, fetch_rev))?;
random_line_split
fetch.rs
.instrument(tracing::debug_span!("fetch")) .await } pub async fn via_git(url: &url::Url, rev: &str) -> Result<crate::git::GitSource, Error> { // Create a temporary directory to fetch the repo into let temp_dir = tempfile::tempdir()?; // Create another temporary directory where we *may* checkout sub...
crate::git::with_fetch_options(&git_config, &url, &mut |mut opts| { repo.remote_anonymous(&url)? .fetch( &[ "refs/heads/master:refs/remotes/origin/master", "HEAD:refs/remotes/origin/HEAD", ], ...
{ // We don't bother to suport older versions of cargo that don't support // bare checkouts of registry indexes, as that has been in since early 2017 // See https://github.com/rust-lang/cargo/blob/0e38712d4d7b346747bf91fb26cce8df6934e178/src/cargo/sources/registry/remote.rs#L61 // for details on why car...
identifier_body
fetch.rs
(client: &Client, krate: &Krate) -> Result<KrateSource, Error> { async { match &krate.source { Source::Git { url, rev, .. } => via_git(&url.clone(), rev).await.map(KrateSource::Git), Source::Registry { registry, chksum } => { let url = registry.download_url(krate); ...
from_registry
identifier_name
repooler.py
1 laneTypeExpr = 0 counter = 0 for sample in lane_maps[ind]: if not sample == 'Undetermined': laneTypeExpr += clusters_expr[sample] for sample in lane_maps[ind]: act = clusters_expr[sample]/float(laneTypeExpr) ideal_ratios[ind][counter]...
main()
conditional_block
repooler.py
(): user = '' pw = '' couch = couchdb.Server('http://' + user + ':' + pw + '@tools.scilifelab.se:5984') return couch #Fetches the structure of a project def proj_struct(couch, project, target_clusters): db = couch['x_flowcells'] view = db.view('names/project_ids_list') fc_track = defaultdic...
connection
identifier_name
repooler.py
] = dict() if not lane in fc_track[project][fc]: fc_track[project][fc][lane] = dict() #Only counts samples for the given project, other samples are "auto-filled" if project in sample: fc_track[project][fc][lane][sample] = clusters else: ...
#Corrects volumes since conc is non-constant #Also normalizes the numbers #Finally translates float -> int without underexpressing anything def correct_numbers(lane_maps, clusters_expr, ideal_ratios, req_lanes, total_lanes): # Since some samples are strong and some weaksauce # 10% in ideal_ratios does not mea...
tempList = list() for k, v in lane_maps.items(): for index in xrange(1,len(v)): if not v[index] == 'Undetermined': tempList.append(v[index]) counter = Counter(tempList) for values in counter.itervalues(): if values > 1: raise Exception('Error: Th...
identifier_body
repooler.py
fc] = dict() if not lane in fc_track[project][fc]: fc_track[project][fc][lane] = dict() #Only counts samples for the given project, other samples are "auto-filled" if project in sample: fc_track[project][fc][lane][sample] = clusters else: ...
for values in counter.itervalues(): if values > 1: raise Exception('Error: This app does NOT handle situations where a sample' 'is present in lanes/well with differing structure!') #Corrects volumes since conc is non-constant #Also normalizes the numbers #Finally translates float ...
if not v[index] == 'Undetermined': tempList.append(v[index]) counter = Counter(tempList)
random_line_split
coltest4.py
) GPIO.setwarnings(False) GPIO.setup(red_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # red GPIO.setup(black_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # black GPIO.setup (led_rot, GPIO.OUT) # rote Led GPIO.setup (led_green, GPIO.OUT) # rote Led GPIO.output(led_rot, False) ...
#------------------------------------------- # ***** Function blink-led ************************** def blink_led(pin,anzahl): # blink led 3 mal bei start und bei shutdown for i in range(anzahl): GPIO.output(pin, True) sleep(0.1) GPIO.output(pin, False) sleep(0....
print "Waiting for Tastendruck..." while True: inpblack=1 inpred=1 inpblack=GPIO.input(black_button) # high if NOT pressed ! inpred=GPIO.input(red_button) # print "Button %d %d" % (inpblack, inpred) sleep(0.2) if not inpblack: return(BLACK) ...
identifier_body
coltest4.py
CM) GPIO.setwarnings(False) GPIO.setup(red_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # red GPIO.setup(black_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # black GPIO.setup (led_rot, GPIO.OUT) # rote Led GPIO.setup (led_green, GPIO.OUT) # rote Led GPIO.output(led_rot, False)...
return Color(gamma_a[255 - start * 3], 0, gamma_a[start * 3]) else: return Color(255 - start * 3, 0, start * 3) else: # print "%d: %d %d %d" % (start, 0, (start-170) * 3, 255 - (start-170) * 3) start -= 170 if how: if gamm...
if gamma:
random_line_split
coltest4.py
) GPIO.setwarnings(False) GPIO.setup(red_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # red GPIO.setup(black_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # black GPIO.setup (led_rot, GPIO.OUT) # rote Led GPIO.setup (led_green, GPIO.OUT) # rote Led GPIO.output(led_rot, False) ...
elif start < 170: # print "%d: %d %d %d" % (start, 255- (start-85) * 3, 0, (start-85)*3 ) start -= 85 if how: if gamma: return (gamma_a[255 - start * 3], 0, gamma_a[start * 3]) else: #forward return (255 - start * 3, 0...
return Color(start * 3, 255 - start * 3, 0)
conditional_block
coltest4.py
return Color(pos * 3, 255 - pos * 3, 0) elif pos < 170: pos -= 85 if how: return (255 - pos * 3, 0, pos * 3) else: return Color(255 - pos * 3, 0, pos * 3) else: pos -= 170 if how: return (0, pos * 3, 255 - pos * 3) ...
colorWipe3
identifier_name
python_module.py
.now() + datetime.timedelta(minutes= 30)) # 返回时间在当前时间上 +30 分钟 c_time = datetime.datetime.now() print(c_time) # 当前时间为 2017-05-07 22:52:44.016732 print(c_time.replace(minute=3,hour=2)) # 时间替换 替换时间为‘2017-05-07 02:03:18.181732’ print(datetime.timedelta) # 表示时间间隔,即两个时间点之间的长度 print (datetime....
<rank updated="yes">69</rank> <year>2011</year>
random_line_split
python_module.py
名。如果path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 print(os.path.exists('test')) # 判断path是否存在 print(os.path.isabs(os.getcwd())) # 如果path是绝对路径,返回True print(os.path.isfile('test')) # 如果path是一个存在的文件,返回True。否则返回False print(os.path.isdir(os.getcwd())) # 如果path是一个存在的目录,则返回True。否则返回Fals...
int(options)
conditional_block
retransmission.rs
_water_mark: TSN, } impl State { pub fn new(tx_high_water_mark: TSN) -> State { State { timer: None, measurements: Measurements::new(), tx_high_water_mark, } } } /// Use a trait to add retransmission functionality to Association. /// /// This is awkward, but...
if let Some(rtx_chunk) = rtx_chunk { // Re-transmit chunk println!("re-sending chunk: {:?}", rtx_chunk); association.send_chunk(Chunk::Data(rtx_chunk)); // E4) Restart timer association.rtx.timer = Some( association .resources .tim...
let rtx_chunk = association.data.sent_queue.front().map(|c| c.clone());
random_line_split
retransmission.rs
_mark: TSN, } impl State { pub fn new(tx_high_water_mark: TSN) -> State { State { timer: None, measurements: Measurements::new(), tx_high_water_mark, } } } /// Use a trait to add retransmission functionality to Association. /// /// This is awkward, but there...
/// "Mark" all unacknowledged packets for retransmission. #[allow(unused)] fn retransmit_all(association: &mut Association) { // Re-queue unacknowledged chunks let bytes = association .data .sent_queue .transfer_all(&mut association.data.send_queue); // Window accounting: Increase ...
{ // TODO: Don't retransmit chunks that were acknowledged in the gap-ack blocks of the most // recent SACK. // Re-queue unacknowledged chunks in the specified range. let bytes = association .data .sent_queue .transfer_range(&mut association.data.send_queue, f...
identifier_body
retransmission.rs
water mark. self.rtx.tx_high_water_mark = chunk_tsn; } // R1) On any transmission, start the rtx timer if it is not already running. if self.rtx.timer.is_none() { self.rtx.timer = Some(self.resources.timer.sleep(self.rtx.measurements.rto)) } } fn on_cum...
complete_rtt_measurement
identifier_name
file.rs
={:?}, count={}", fd, iov_ptr, iov_count); let mut iovs = iov_ptr.read_iovecs(iov_count)?; let proc = self.linux_process(); let file_like = proc.get_file_like(fd)?; let mut buf = vec![0u8; iovs.total_len()]; let len = file_like.read(&mut buf).await?; iovs.write_from_buf(&...
: UserInPtr<u8>, len: usize) -> SysResult { let path = path.as_c_str()?; info!("truncate: path={:?}, len={}", path, len); self.linux_process().lookup_inode(path)?.resize(len)?; Ok(0) } /// cause the regular file referenced by fd to be truncated to a size of precisely length byte...
(&self, path
identifier_name
file.rs
={:?}, count={}", fd, iov_ptr, iov_count); let mut iovs = iov_ptr.read_iovecs(iov_count)?; let proc = self.linux_process(); let file_like = proc.get_file_like(fd)?; let mut buf = vec![0u8; iovs.total_len()]; let len = file_like.read(&mut buf).await?; iovs.write_from_buf(&...
let mut bytes_written = 0; let mut rlen = read_len; while bytes_written < read_len { let write_len = out_file.write(&buffer[bytes_written..(bytes_written + rlen)])?; if write_len == 0 { info!( "copy_file_rang...
random_line_split
file.rs
:?}, count={}", fd, iov_ptr, iov_count); let mut iovs = iov_ptr.read_iovecs(iov_count)?; let proc = self.linux_process(); let file_like = proc.get_file_like(fd)?; let mut buf = vec![0u8; iovs.total_len()]; let len = file_like.read(&mut buf).await?; iovs.write_from_buf(&bu...
use the regular file referenced by fd to be truncated to a size of precisely length bytes. pub fn sys_ftruncate(&self, fd: FileDesc, len: usize) -> SysResult { info!("ftruncate: fd={:?}, len={}", fd, len); let proc = self.linux_process(); proc.get_file(fd)?.set_len(len as u64)?; Ok(0...
t path = path.as_c_str()?; info!("truncate: path={:?}, len={}", path, len); self.linux_process().lookup_inode(path)?.resize(len)?; Ok(0) } /// ca
identifier_body
file.rs
:?}, count={}", fd, iov_ptr, iov_count); let mut iovs = iov_ptr.read_iovecs(iov_count)?; let proc = self.linux_process(); let file_like = proc.get_file_like(fd)?; let mut buf = vec![0u8; iovs.total_len()]; let len = file_like.read(&mut buf).await?; iovs.write_from_buf(&bu...
flags -= OpenFlags::CLOEXEC; } file_like.set_flags(flags)?; Ok(0) } FcntlCmd::GETFL => Ok(file_like.flags().bits()), FcntlCmd::SETFL => { file_like.set_flags(OpenFlags::from_bi...
flags |= OpenFlags::CLOEXEC; } else {
conditional_block
cluster.go
Endpoint string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"` // Username for http basic authentication Username string `json:"username,omitempty" yaml:"username,omitempty"` // Password for http basic authentication Password string `json:"password,omitempty" yaml:"password,omitempty"` // Root CaCertificat...
RootCaCertificate: c.RootCACert, Username: c.Username, Password: c.Password, Version: c.Version, Endpoint: c.Endpoint, NodeCount: c.NodeCount, Metadata: c.Metadata, ServiceAccountToken: c.ServiceAccountToken, Status: c.St...
random_line_split
cluster.go
Endpoint string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"` // Username for http basic authentication Username string `json:"username,omitempty" yaml:"username,omitempty"` // Password for http basic authentication Password string `json:"password,omitempty" yaml:"password,omitempty"` // Root CaCertificat...
(ctx context.Context) error { // check if it is already created c.restore() var info *types.ClusterInfo if c.Status == Error { logrus.Errorf("Cluster %s previously failed to create", c.Name) info = toInfo(c) } if c.Status == Updating || c.Status == Running || c.Status == PostCheck || c.Status == Init { lo...
createInner
identifier_name
cluster.go
Endpoint string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"` // Username for http basic authentication Username string `json:"username,omitempty" yaml:"username,omitempty"` // Password for http basic authentication Password string `json:"password,omitempty" yaml:"password,omitempty"` // Root CaCertificat...
} // Update updates a cluster func (c *Cluster) Update(ctx context.Context) error { if err := c.restore(); err != nil { return err } if c.Status == Error { logrus.Errorf("Cluster %s previously failed to create", c.Name) return c.Create(ctx) } if c.Status == PreCreating || c.Status == Creating { logrus....
{ // check if it is already created c.restore() var info *types.ClusterInfo if c.Status == Error { logrus.Errorf("Cluster %s previously failed to create", c.Name) info = toInfo(c) } if c.Status == Updating || c.Status == Running || c.Status == PostCheck || c.Status == Init { logrus.Infof("Cluster %s alrea...
identifier_body
cluster.go
Endpoint string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"` // Username for http basic authentication Username string `json:"username,omitempty" yaml:"username,omitempty"` // Password for http basic authentication Password string `json:"password,omitempty" yaml:"password,omitempty"` // Root CaCertificate...
transformClusterInfo(c, info) return c.PostCheck(ctx) } func (c *Cluster) GetVersion(ctx context.Context) (*types.KubernetesVersion, error) { return c.Driver.GetVersion(ctx, toInfo(c)) } func (c *Cluster) SetVersion(ctx context.Context, version *types.KubernetesVersion) error { return c.Driver.SetVersion(ctx, ...
{ return err }
conditional_block
http.class.js
_OK: 200, HTTP_CREATED: 201, HTTP_ACCEPTED: 202, HTTP_NON_AUTHORITATIVE_INFORMATION: 203, HTTP_NO_CONTENT: 204, HTTP_RESET_CONTENT: 205, HTTP_PARTIAL_CONTENT: 206, HTTP_MULTI_STATUS: 207, // RFC4918 HTTP_ALREADY_REP...
getHeaders() { return this.request.headers } isGet() { return (this.request.method === 'GET') } isPost() { return (this.request.method === 'POST') } isPut() { return (this.request.method === 'PUT') } isDelete() { return (this.request.meth...
{ return this.request.method }
identifier_body
http.class.js
HTTP_OK: 200, HTTP_CREATED: 201, HTTP_ACCEPTED: 202, HTTP_NON_AUTHORITATIVE_INFORMATION: 203, HTTP_NO_CONTENT: 204, HTTP_RESET_CONTENT: 205, HTTP_PARTIAL_CONTENT: 206, HTTP_MULTI_STATUS: 207, // RFC4918 HTTP_ALREAD...
return (this.request.method === 'PUT') } isDelete() { return (this.request.method === 'DELETE') } isJson() { const contentType = this.request.headers['content-type']; return _.startsWith(_.trim(contentType), 'application/json'); } isXml() { const conten...
return (this.request.method === 'POST') } isPut() {
random_line_split
http.class.js
HTTP_UNPROCESSABLE_ENTITY: 422, // RFC4918 HTTP_LOCKED: 423, // RFC4918 HTTP_FAILED_DEPENDENCY: 424, // RFC4918 HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COL...
getUserAgent
identifier_name
http.class.js
, HTTP_METHOD_NOT_ALLOWED: 405, HTTP_NOT_ACCEPTABLE: 406, HTTP_PROXY_AUTHENTICATION_REQUIRED: 407, HTTP_REQUEST_TIMEOUT: 408, HTTP_CONFLICT: 409, HTTP_GONE: 410, HTTP_LENGTH_REQUIRED: 411, HTTP_PRECONDITION_FAILED: 412, ...
{ postData = JSON.parse(body); }
conditional_block
generator.go
information based on the information provided // in the pathway. type Generator struct { personGenerator *person.Generator patientClassGenerator patientClassGenerator allergyGenerator *codedelement.AllergyGenerator diagnosisGenerator diagnosisOrProcedureGenerator procedureGenerator diagnosisOrPro...
if doctor != nil { docWithSpecialty := g.doctors.GetByID(doctor.ID) if docWithSpecialty != nil && docWithSpecialty.Specialty != "" { p.PatientInfo.HospitalService = docWithSpecialty.Specialty } } return p } // NewDoctor returns a new doctor based on the Consultant information from the pathway. // If consu...
{ p.PatientInfo.PrimaryFacility = &ir.PrimaryFacility{ Organization: g.messageConfig.PrimaryFacility.OrganizationName, ID: g.messageConfig.PrimaryFacility.IDNumber, } }
conditional_block
generator.go
ir.Doctor { if c == nil { return g.doctors.GetRandomDoctor() } if doctor := g.doctors.GetByID(*c.ID); doctor != nil { return doctor } newDoctor := &ir.Doctor{ // A valid pathway.Consultant has all the fields set, so we can just dereference. ID: *c.ID, Surname: *c.Surname, Prefix: *c.Prefix,...
{ ag := cfg.AddressGenerator if ag == nil { ag = &address.Generator{Nouns: cfg.Data.Nouns, Address: cfg.Data.Address} } mrnGenerator := cfg.MRNGenerator if mrnGenerator == nil { mrnGenerator = &randomIDGenerator{} } placerGenerator := cfg.PlacerGenerator if placerGenerator == nil { placerGenerator = &ra...
identifier_body
generator.go
related information based on the information provided // in the pathway. type Generator struct { personGenerator *person.Generator patientClassGenerator patientClassGenerator allergyGenerator *codedelement.AllergyGenerator diagnosisGenerator diagnosisOrProcedureGenerator procedureGenerator diagno...
Organization: g.messageConfig.PrimaryFacility.OrganizationName, ID: g.messageConfig.PrimaryFacility.IDNumber, } } if doctor != nil { docWithSpecialty := g.doctors.GetByID(doctor.ID) if docWithSpecialty != nil && docWithSpecialty.Specialty != "" { p.PatientInfo.HospitalService = docWithSpecial...
// PD1.3 Patient Primary Facility field empty. This is achieved by leaving p.PatientInfo.PrimaryFacility nil. if g.messageConfig.PrimaryFacility != nil { p.PatientInfo.PrimaryFacility = &ir.PrimaryFacility{
random_line_split
generator.go
information based on the information provided // in the pathway. type Generator struct { personGenerator *person.Generator patientClassGenerator patientClassGenerator allergyGenerator *codedelement.AllergyGenerator diagnosisGenerator diagnosisOrProcedureGenerator procedureGenerator diagnosisOrPro...
(patientInfo *ir.PatientInfo, procedures []*pathway.DiagnosisOrProcedure) { patientInfo.Procedures = make([]*ir.DiagnosisOrProcedure, len(procedures)) g.setDiagnosesOrProcedures(patientInfo.Procedures, procedures, g.procedureGenerator) } func (g Generator) setDiagnosesOrProcedures(diagnosisOrProcedure []*ir.Diagnosi...
setProcedures
identifier_name
spannerautoscaler_controller.go
scaleDownInterval time.Duration clock utilclock.Clock log logr.Logger mu sync.RWMutex } var _ ctrlreconcile.Reconciler = (*SpannerAutoscalerReconciler)(nil) type Option func(*SpannerAutoscalerReconciler) func WithSyncers(syncers map[types.NamespacedName]syncer.Syncer) Option { return func(r *SpannerAuto...
(ctx context.Context, nn types.NamespacedName, projectID, instanceID string, credentials *syncer.Credentials) error { log := logging.FromContext
startSyncer
identifier_name