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 |
|---|---|---|---|---|
main.py | #!/share/apps/python-2.7.2/bin/python
import foldx, re, shutil, random, os, math, sys, glob, pyros
from Bio import *
import Bio.PDB as PDB
#runs with python main.py human random num_fixed selection both 10000000 .00983 10 0 0 0 kept_mutants.txt all_mutants_tried.txt
#yeast effective pop size, real temp.
def main... |
score_ob.cleanUp(['*energies*'])
def write_line(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_ke... | prefix, count, all_kept_mutants, all_mutants_tried, exists = does_file_exist(prefix, i, count, all_kept_mutants, all_mutants_tried)
if not exists:
continue
if available_mutations == 'random':
(mutation_code, site) = generate_mutation_code(prefix, which_chain)
... | conditional_block |
main.py | #!/share/apps/python-2.7.2/bin/python
import foldx, re, shutil, random, os, math, sys, glob, pyros
from Bio import *
import Bio.PDB as PDB
#runs with python main.py human random num_fixed selection both 10000000 .00983 10 0 0 0 kept_mutants.txt all_mutants_tried.txt
#yeast effective pop size, real temp.
def main... | (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 | #!/share/apps/python-2.7.2/bin/python
import foldx, re, shutil, random, os, math, sys, glob, pyros
from Bio import *
import Bio.PDB as PDB
#runs with python main.py human random num_fixed selection both 10000000 .00983 10 0 0 0 kept_mutants.txt all_mutants_tried.txt
#yeast effective pop size, real temp.
def main... | 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 | #!/share/apps/python-2.7.2/bin/python
import foldx, re, shutil, random, os, math, sys, glob, pyros
from Bio import *
import Bio.PDB as PDB
#runs with python main.py human random num_fixed selection both 10000000 .00983 10 0 0 0 kept_mutants.txt all_mutants_tried.txt
#yeast effective pop size, real temp.
def main... |
#Run main program
if __name__ == '__main__':
main()
| return (chain.get_id() in self.chain_letters) | identifier_body |
Tetris.go | package main
import (
"fmt"
"math/rand"
"os"
"os/exec"
"time"
)
var (
colSize int = 10
rowSize int = 20
//
shapeO = [][]int{
{1, 1},
{1, 1}}
shapeL = [][]int{
{0, 0, 1},
{1, 1, 1},
{0, 0, 0}}
shapeJ = [][]int{
{1, 0, 0},
{1, 1, 1},
{0, 0, 0}}
shapeS = [][]int{
{0, 1, 1},
{1, 1, 0},
{... | (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 | package main
import (
"fmt"
"math/rand"
"os"
"os/exec"
"time"
)
var (
colSize int = 10
rowSize int = 20
//
shapeO = [][]int{
{1, 1},
{1, 1}}
shapeL = [][]int{
{0, 0, 1},
{1, 1, 1},
{0, 0, 0}}
shapeJ = [][]int{
{1, 0, 0},
{1, 1, 1},
{0, 0, 0}}
shapeS = [][]int{
{0, 1, 1},
{1, 1, 0},
{... | 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 | package main
import (
"fmt"
"math/rand"
"os"
"os/exec"
"time"
)
var (
colSize int = 10
rowSize int = 20
//
shapeO = [][]int{
{1, 1},
{1, 1}}
shapeL = [][]int{
{0, 0, 1},
{1, 1, 1},
{0, 0, 0}}
shapeJ = [][]int{
{1, 0, 0},
{1, 1, 1},
{0, 0, 0}}
shapeS = [][]int{
{0, 1, 1},
{1, 1, 0},
{... |
//
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 | package main
import (
"fmt"
"math/rand"
"os"
"os/exec"
"time"
)
var (
colSize int = 10
rowSize int = 20
//
shapeO = [][]int{
{1, 1},
{1, 1}}
shapeL = [][]int{
{0, 0, 1},
{1, 1, 1},
{0, 0, 0}}
shapeJ = [][]int{
{1, 0, 0},
{1, 1, 1},
{0, 0, 0}}
shapeS = [][]int{
{0, 1, 1},
{1, 1, 0},
{... |
fmt.Println("\033[m")
}
fmt.Print("\033[1m||\033[m")
for j := range arr[0] {
// fmt.Print(arr[i][j]," ") //for print out 0, 1 (real board)
if arr[i][j] == 0 && i == len(arr)-1 {
fmt.Print("\033[1m_ \033[m")
} else {
fmt.Print(Color[arr[i][j]])
}
}
if i == 1 {
fmt.Println("\033[1m||... | {
fmt.Print("\033[1m_ ")
} | conditional_block |
ui.rs | use super::*;
use std::rc::Rc;
use std::cell::RefCell;
use std::cmp::{min, max};
use stdweb::web;
use stdweb::unstable::TryInto;
use nalgebra::{Vector2};
use time_steward::{DeterministicRandomId};
use steward_module::{TimeSteward, ConstructibleTimeSteward, Accessor, simple_timeline};
use self::simple_timeline::{q... | (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 | use super::*;
use std::rc::Rc;
use std::cell::RefCell;
use std::cmp::{min, max};
use stdweb::web;
use stdweb::unstable::TryInto;
use nalgebra::{Vector2};
use time_steward::{DeterministicRandomId};
use steward_module::{TimeSteward, ConstructibleTimeSteward, Accessor, simple_timeline};
use self::simple_timeline::{q... | }
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 | use super::*;
use std::rc::Rc;
use std::cell::RefCell;
use std::cmp::{min, max};
use stdweb::web;
use stdweb::unstable::TryInto;
use nalgebra::{Vector2};
use time_steward::{DeterministicRandomId};
use steward_module::{TimeSteward, ConstructibleTimeSteward, Accessor, simple_timeline};
use self::simple_timeline::{q... |
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 | use super::*;
use std::rc::Rc;
use std::cell::RefCell;
use std::cmp::{min, max};
use stdweb::web;
use stdweb::unstable::TryInto;
use nalgebra::{Vector2};
use time_steward::{DeterministicRandomId};
use steward_module::{TimeSteward, ConstructibleTimeSteward, Accessor, simple_timeline};
use self::simple_timeline::{q... | {
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 | // Copyright 2015 - 2016 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | 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.TagSets, item.fetchErr... |
c.getAllTagsCacheMutex.Unlock()
}
| random_line_split |
cached.go | // Copyright 2015 - 2016 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | 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 | // Copyright 2015 - 2016 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
// 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 | // Copyright 2015 - 2016 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... | (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 | //! Useful functions and macros for writing figments.
//!
//! # `map!` macro
//!
//! The `map!` macro constructs a [`Map`](crate::value::Map) from key-value
//! pairs and is particularly useful during testing:
//!
//! ```rust
//! use figment::util::map;
//!
//! let map = map! {
//! "name" => "Bob",
//! "age" =>... | }
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 | //! Useful functions and macros for writing figments.
//!
//! # `map!` macro
//!
//! The `map!` macro constructs a [`Map`](crate::value::Map) from key-value
//! pairs and is particularly useful during testing:
//!
//! ```rust
//! use figment::util::map;
//!
//! let map = map! {
//! "name" => "Bob",
//! "age" =>... |
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 | //! Useful functions and macros for writing figments.
//!
//! # `map!` macro
//!
//! The `map!` macro constructs a [`Map`](crate::value::Map) from key-value
//! pairs and is particularly useful during testing:
//!
//! ```rust
//! use figment::util::map;
//!
//! let map = map! {
//! "name" => "Bob",
//! "age" =>... | <'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 | #![feature(collections)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate parser_combinators;
// TODO:
// - Benchmarks
// - Cache of last piece
// - merge consecutive insert, delete
// - snapshots
// - Allow String, &str, &[u8], and Vec<u8> as parameter to insert, append
/// A... |
}
#[cfg(not(test))]
fn main() {
env_logger::init().unwrap();
info!("starting up");
//let mut text = Text::new();
let mut args = std::env::args();
args.next().unwrap();
let s = args.next().unwrap();
let cmd = Command::parse(&s);
println!("{:?}", cmd);
}
| {
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 | #![feature(collections)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate parser_combinators;
// TODO:
// - Benchmarks
// - Cache of last piece
// - merge consecutive insert, delete
// - snapshots
// - Allow String, &str, &[u8], and Vec<u8> as parameter to insert, append
/// A... |
}
}
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 | #![feature(collections)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate parser_combinators;
// TODO:
// - Benchmarks
// - Cache of last piece
// - merge consecutive insert, delete
// - snapshots
// - Allow String, &str, &[u8], and Vec<u8> as parameter to insert, append
/// A... | }
/// 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 | #![feature(collections)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate parser_combinators;
// TODO:
// - Benchmarks
// - Cache of last piece
// - merge consecutive insert, delete
// - snapshots
// - Allow String, &str, &[u8], and Vec<u8> as parameter to insert, append
/// A... | (&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 | use num_bigint::{BigInt, ToBigUint};
use num_traits::{Zero, One, Pow};
use std::collections::{BinaryHeap, HashSet, HashMap, VecDeque};
use std::cmp::{max, Ordering};
use std::hash::Hash;
use std::ops;
use std::fmt;
use crate::ast::{AST, as_int};
pub fn to_usize(n : &BigInt) -> Result<usize, String> {
match ToBig... | }
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 | use num_bigint::{BigInt, ToBigUint};
use num_traits::{Zero, One, Pow};
use std::collections::{BinaryHeap, HashSet, HashMap, VecDeque};
use std::cmp::{max, Ordering};
use std::hash::Hash;
use std::ops;
use std::fmt;
use crate::ast::{AST, as_int};
pub fn to_usize(n : &BigInt) -> Result<usize, String> {
match ToBig... |
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 | use num_bigint::{BigInt, ToBigUint};
use num_traits::{Zero, One, Pow};
use std::collections::{BinaryHeap, HashSet, HashMap, VecDeque};
use std::cmp::{max, Ordering};
use std::hash::Hash;
use std::ops;
use std::fmt;
use crate::ast::{AST, as_int};
pub fn to_usize(n : &BigInt) -> Result<usize, String> {
match ToBig... | (&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 | import logging
import re
from datetime import datetime
from pathlib import Path
from urllib.parse import urlencode, urlsplit
from xml.parsers.expat import ExpatError
from xmlrpc.client import Error as XMLRPCError
from xmlrpc.client import ServerProxy
import pytz
from ..baseclient import BaseClient
from ..bencode impo... |
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 | import logging
import re
from datetime import datetime
from pathlib import Path
from urllib.parse import urlencode, urlsplit
from xml.parsers.expat import ExpatError
from xmlrpc.client import Error as XMLRPCError
from xmlrpc.client import ServerProxy
import pytz
from ..baseclient import BaseClient
from ..bencode impo... | (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 logging
import re
from datetime import datetime
from pathlib import Path
from urllib.parse import urlencode, urlsplit
from xml.parsers.expat import ExpatError
from xmlrpc.client import Error as XMLRPCError
from xmlrpc.client import ServerProxy
import pytz
from ..baseclient import BaseClient
from ..bencode impo... | 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 | import logging
import re
from datetime import datetime
from pathlib import Path
from urllib.parse import urlencode, urlsplit
from xml.parsers.expat import ExpatError
from xmlrpc.client import Error as XMLRPCError
from xmlrpc.client import ServerProxy
import pytz
from ..baseclient import BaseClient
from ..bencode impo... |
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 | //! A generic MIO server.
use error::{MioResult, MioError};
use handler::Handler;
use io::{Ready, IoHandle, IoReader, IoWriter, IoAcceptor};
use iobuf::{Iobuf, RWIobuf};
use reactor::Reactor;
use socket::{TcpSocket, TcpAcceptor, SockAddr};
use std::cell::RefCell;
use std::collections::{Deque, RingBuf};
use std::rc::Rc;... | 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 | //! A generic MIO server.
use error::{MioResult, MioError};
use handler::Handler;
use io::{Ready, IoHandle, IoReader, IoWriter, IoAcceptor};
use iobuf::{Iobuf, RWIobuf};
use reactor::Reactor;
use socket::{TcpSocket, TcpAcceptor, SockAddr};
use std::cell::RefCell;
use std::collections::{Deque, RingBuf};
use std::rc::Rc;... | {
// 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 | //! A generic MIO server.
use error::{MioResult, MioError};
use handler::Handler;
use io::{Ready, IoHandle, IoReader, IoWriter, IoAcceptor};
use iobuf::{Iobuf, RWIobuf};
use reactor::Reactor;
use socket::{TcpSocket, TcpAcceptor, SockAddr};
use std::cell::RefCell;
use std::collections::{Deque, RingBuf};
use std::rc::Rc;... |
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 | //! A generic MIO server.
use error::{MioResult, MioError};
use handler::Handler;
use io::{Ready, IoHandle, IoReader, IoWriter, IoAcceptor};
use iobuf::{Iobuf, RWIobuf};
use reactor::Reactor;
use socket::{TcpSocket, TcpAcceptor, SockAddr};
use std::cell::RefCell;
use std::collections::{Deque, RingBuf};
use std::rc::Rc;... | (&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 | package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"regexp"
"sort"
"strings"
"time"
"github.com/getsentry/sentry-go"
sentrygin "github.com/getsentry/sentry-go/gin"
"github.com/gin-gonic/gin"
redis "github.com/go-redis/redi... | 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 | package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"regexp"
"sort"
"strings"
"time"
"github.com/getsentry/sentry-go"
sentrygin "github.com/getsentry/sentry-go/gin"
"github.com/gin-gonic/gin"
redis "github.com/go-redis/redi... | 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 | package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"regexp"
"sort"
"strings"
"time"
"github.com/getsentry/sentry-go"
sentrygin "github.com/getsentry/sentry-go/gin"
"github.com/gin-gonic/gin"
redis "github.com/go-redis/redi... | 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 | package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"regexp"
"sort"
"strings"
"time"
"github.com/getsentry/sentry-go"
sentrygin "github.com/getsentry/sentry-go/gin"
"github.com/gin-gonic/gin"
redis "github.com/go-redis/redi... | {
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", path, err)
return ""
}
title := strings.Replace(string(line), "# ", "", -1)
return title
}
// VisitedArticle is for reme... | 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 | import logging
from typing import List, Tuple, Union
import albumentations
import keras
import numpy as np
from bfgn.data_management.scalers import BaseGlobalScaler
_logger = logging.getLogger(__name__)
ADDITIONAL_TARGETS_KEY = "image_{}"
class BaseSequence(keras.utils.Sequence):
feature_scaler = None
re... |
def sample_custom_augmentations_constructor(num_features: int, window_radius: int) -> albumentations.Compose:
"""
This function returns a custom augmentations object for use with sequences via the load_sequences function in
data_core.py. Please note that these augmentations have only been tested with RGB... | 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 | import logging
from typing import List, Tuple, Union
import albumentations
import keras
import numpy as np
from bfgn.data_management.scalers import BaseGlobalScaler
_logger = logging.getLogger(__name__)
ADDITIONAL_TARGETS_KEY = "image_{}"
class BaseSequence(keras.utils.Sequence):
feature_scaler = None
re... |
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 | import logging
from typing import List, Tuple, Union
import albumentations
import keras
import numpy as np
from bfgn.data_management.scalers import BaseGlobalScaler
_logger = logging.getLogger(__name__)
ADDITIONAL_TARGETS_KEY = "image_{}"
class BaseSequence(keras.utils.Sequence):
feature_scaler = None
re... | (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 | import logging
from typing import List, Tuple, Union
import albumentations
import keras
import numpy as np
from bfgn.data_management.scalers import BaseGlobalScaler
_logger = logging.getLogger(__name__)
ADDITIONAL_TARGETS_KEY = "image_{}"
class BaseSequence(keras.utils.Sequence):
feature_scaler = None
re... | 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 | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | (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 | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
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 | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
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 | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | * 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 | # -*- coding: utf-8 -*-
"""
Copyright 2015 Brookhaven Science Assoc.
as operator of Brookhaven National Lab.
"""
# supported RPC call version
PVER=0
import re
import logging
from functools import reduce
_log = logging.getLogger("carchive.classic")
import time, math
try:
from xmlrpc.client import Fault
except Im... | (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 | # -*- coding: utf-8 -*-
"""
Copyright 2015 Brookhaven Science Assoc.
as operator of Brookhaven National Lab.
"""
# supported RPC call version
PVER=0
import re
import logging
from functools import reduce
_log = logging.getLogger("carchive.classic")
import time, math
try:
from xmlrpc.client import Fault
except Im... |
elif len(plan)==0:
# requested range is earlier than first recorded sample.
_log.warn("Query plan empty. No data in or before request time range.")
defer.returnValue(0)
_log.debug("Using plan of %d queries %s", len(plan), map(lambda a,b,c:(a,b,self.__rarchs[c]), pl... | 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 | # -*- coding: utf-8 -*-
"""
Copyright 2015 Brookhaven Science Assoc.
as operator of Brookhaven National Lab.
"""
# supported RPC call version
PVER=0
import re
import logging
from functools import reduce
_log = logging.getLogger("carchive.classic")
import time, math
try:
from xmlrpc.client import Fault
except Im... | """
"""
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 | # -*- coding: utf-8 -*-
"""
Copyright 2015 Brookhaven Science Assoc.
as operator of Brookhaven National Lab.
"""
# supported RPC call version
PVER=0
import re
import logging
from functools import reduce
_log = logging.getLogger("carchive.classic")
import time, math
try:
from xmlrpc.client import Fault
except Im... | enumAsInt=enumAsInt, displayMeta=displayMeta)
defer.returnValue(N)
def _nextraw(self, partcount, pv, plan, Ctot, Climit,
callback, cbArgs, cbKWs, chunkSize,
enumAsInt, displayMeta=False):
sofar = partcount + Ctot
if len(plan... | callback=callback, cbArgs=cbArgs,
cbKWs=cbKWs, chunkSize=chunkSize, | random_line_split |
app.js | //WorldStats
//My first real project
//Started 4-11-15
/** Packages to install with NPM
bcrypt -- for password encryption (but require in user.js file)
body-parser -- for response handling
ejs -- for view files
express
express-session
method-override -- to enable PUT/PATCH and DELETE verbs
pg
pg-hstore
request
sequeli... | ;
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 | //WorldStats
//My first real project
//Started 4-11-15
/** Packages to install with NPM
bcrypt -- for password encryption (but require in user.js file)
body-parser -- for response handling
ejs -- for view files
express
express-session
method-override -- to enable PUT/PATCH and DELETE verbs
pg
pg-hstore
request
sequeli... | 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 | //! interfacing with the `instruments` command line tool
use std::fmt::Write;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use anyhow::{anyhow, Result};
use cargo::core::Workspace;
use semver::Version;
use crate::opt::AppConfig;
/// Holds available templates.
pub struct Template... | () -> 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 | //! interfacing with the `instruments` command line tool
use std::fmt::Write;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use anyhow::{anyhow, Result};
use cargo::core::Workspace;
use semver::Version;
use crate::opt::AppConfig;
/// Holds available templates.
pub struct Template... |
Ok(trace_filepath)
}
/// get the tty of th current terminal session
fn get_tty() -> Result<Option<String>> {
let mut command = Command::new("ps");
command.arg("otty=").arg(std::process::id().to_string());
Ok(String::from_utf8(command.output()?.stdout)?
.split_whitespace()
.next()
... | {
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 | //! interfacing with the `instruments` command line tool
use std::fmt::Write;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use anyhow::{anyhow, Result};
use cargo::core::Workspace;
use semver::Version;
use crate::opt::AppConfig;
/// Holds available templates.
pub struct Template... |
/// Return the template name abbreviation if available.
fn abbrev_name(template_name: &str) -> Option<&str> {
match template_name {
"Time Profiler" => Some("time"),
"Allocations" => Some("alloc"),
"File Activity" => Some("io"),
"System Trace" => Some("sys"),
_ => None,
... | {
match template_name {
"time" => "Time Profiler",
"alloc" => "Allocations",
"io" => "File Activity",
"sys" => "System Trace",
other => other,
}
} | identifier_body |
instruments.rs | //! interfacing with the `instruments` command line tool
use std::fmt::Write;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use anyhow::{anyhow, Result};
use cargo::core::Workspace;
use semver::Version;
use crate::opt::AppConfig;
/// Holds available templates.
pub struct Template... | "Time Profiler" => Some("time"),
"Allocations" => Some("alloc"),
"File Activity" => Some("io"),
"System Trace" => Some("sys"),
_ => None,
}
}
/// Profile the target binary at `binary_filepath`, write results at
/// `trace_filepath` and returns its path.
pub(crate) fn profile... | /// 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 | //! Fullscreen Window Manager
//!
//! Implement the [`WindowManager`] trait by writing a simple window manager
//! that displays every window fullscreen. When a new window is added, the
//! last window that was visible will become invisible.
//!
//! [`WindowManager`]: ../../cplwm_api/wm/trait.WindowManager.html
//!
//!... |
}
/// Try this yourself
fn get_screen(&self) -> Screen {
self.screen
}
/// Try this yourself
fn resize_screen(&mut self, screen: Screen) {
self.screen = screen
}
}
#[cfg(test)]
mod a_fullscreen_wm_tests {
include!("a_fullscreen_wm_tests.rs");
}
| {
Err(FullscreenWMError::UnknownWindow(window))
} | conditional_block |
a_fullscreen_wm.rs | //! Fullscreen Window Manager
//!
//! Implement the [`WindowManager`] trait by writing a simple window manager
//! that displays every window fullscreen. When a new window is added, the
//! last window that was visible will become invisible.
//!
//! [`WindowManager`]: ../../cplwm_api/wm/trait.WindowManager.html
//!
//!... |
/// Try this yourself
fn cycle_focus(&mut self, dir: PrevOrNext) {
// You will probably notice here that a `Vec` is not the ideal data
// structure to implement this function. Feel free to replace the
// `Vec` with another data structure.
// Do nothing when there are no window... | {
// 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 | //! Fullscreen Window Manager
//!
//! Implement the [`WindowManager`] trait by writing a simple window manager
//! that displays every window fullscreen. When a new window is added, the
//! last window that was visible will become invisible.
//!
//! [`WindowManager`]: ../../cplwm_api/wm/trait.WindowManager.html
//!
//!... | /// 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 | //! Fullscreen Window Manager
//!
//! Implement the [`WindowManager`] trait by writing a simple window manager
//! that displays every window fullscreen. When a new window is added, the
//! last window that was visible will become invisible.
//!
//! [`WindowManager`]: ../../cplwm_api/wm/trait.WindowManager.html
//!
//!... | (&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 | #[macro_use]
extern crate include_dir;
pub mod cosmogony;
mod country_finder;
pub mod file_format;
mod hierarchy_builder;
mod mutable_slice;
pub mod zone;
pub mod zone_typer;
pub use crate::cosmogony::{Cosmogony, CosmogonyMetadata, CosmogonyStats};
use crate::country_finder::CountryFinder;
use crate::file_format::Out... |
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 | #[macro_use]
extern crate include_dir;
pub mod cosmogony;
mod country_finder;
pub mod file_format;
mod hierarchy_builder;
mod mutable_slice;
pub mod zone;
pub mod zone_typer;
pub use crate::cosmogony::{Cosmogony, CosmogonyMetadata, CosmogonyStats};
use crate::country_finder::CountryFinder;
use crate::file_format::Out... | (
reader: impl std::io::BufRead,
format: OutputFormat,
) -> Result<Cosmogony, Error> {
match format {
OutputFormat::JsonGz => {
let r = flate2::read::GzDecoder::new(reader);
serde_json::from_reader(r).map_err(|e| failure::err_msg(e.to_string()))
}
OutputFormat... | load_cosmogony | identifier_name |
lib.rs | #[macro_use]
extern crate include_dir;
pub mod cosmogony;
mod country_finder;
pub mod file_format;
mod hierarchy_builder;
mod mutable_slice;
pub mod zone;
pub mod zone_typer;
pub use crate::cosmogony::{Cosmogony, CosmogonyMetadata, CosmogonyStats};
use crate::country_finder::CountryFinder;
use crate::file_format::Out... |
_ => 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 | #[macro_use]
extern crate include_dir;
pub mod cosmogony;
mod country_finder;
pub mod file_format;
mod hierarchy_builder;
mod mutable_slice;
pub mod zone;
pub mod zone_typer;
pub use crate::cosmogony::{Cosmogony, CosmogonyMetadata, CosmogonyStats};
use crate::country_finder::CountryFinder;
use crate::file_format::Out... | }
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 | /*
--- Day 12: Subterranean Sustainability ---
The year 518 is significantly more underground than your history books implied. Either that, or
you've arrived in a vast cavern network under the North Pole.
After exploring a little, you discover a long tunnel that contains a row of small pots as far as
you can see to ... | (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 | /*
--- Day 12: Subterranean Sustainability ---
The year 518 is significantly more underground than your history books implied. Either that, or
you've arrived in a vast cavern network under the North Pole.
After exploring a little, you discover a long tunnel that contains a row of small pots as far as
you can see to ... | let result = convert_state_str_to_vec("#..##");
let mut expected = vec![true, false, false, true, true];
for _ in 0..OFFSET {
expected.insert(0, false);
}
for _ in 0..OFFSET {
expected.push(false);
}
assert_eq!(result, expected)
}
#[test]
fn test_convert_strs_to_combina... | .collect()
}
#[test]
fn test_convert_state_str_to_vec() { | random_line_split |
main.rs | /*
--- Day 12: Subterranean Sustainability ---
The year 518 is significantly more underground than your history books implied. Either that, or
you've arrived in a vast cavern network under the North Pole.
After exploring a little, you discover a long tunnel that contains a row of small pots as far as
you can see to ... |
fn main() {
let mut input_combinations = get_input_combinations();
let mut combinations_map = convert_strs_to_combinations_map(&mut input_combinations);
let mut state_vector = convert_state_str_to_vec(INITIAL_STATE);
let mut final_state_20 =
get_new_state_after_n_generations(&mut state_vector, &mut combi... | {
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 | /*
--- Day 12: Subterranean Sustainability ---
The year 518 is significantly more underground than your history books implied. Either that, or
you've arrived in a vast cavern network under the North Pole.
After exploring a little, you discover a long tunnel that contains a row of small pots as far as
you can see to ... | 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 | use crate::{cargo::Source, util, Krate};
use anyhow::{Context, Error};
use bytes::Bytes;
use reqwest::Client;
use std::path::Path;
use tracing::{error, warn};
use tracing_futures::Instrument;
pub(crate) enum KrateSource {
Registry(Bytes),
Git(crate::git::GitSource),
}
impl KrateSource {
pub(crate) fn len(... | 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 | use crate::{cargo::Source, util, Krate};
use anyhow::{Context, Error};
use bytes::Bytes;
use reqwest::Client;
use std::path::Path;
use tracing::{error, warn};
use tracing_futures::Instrument;
pub(crate) enum KrateSource {
Registry(Bytes),
Git(crate::git::GitSource),
}
impl KrateSource {
pub(crate) fn len(... |
/// Writes .cache entries in the registry's directory for all of the specified
/// crates. Cargo will write these entries itself if they don't exist the first
/// time it tries to access the crate's metadata, but this noticeably increases
/// initial fetch times. (see src/cargo/sources/registry/index.rs)
fn write_cac... | {
// 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 | use crate::{cargo::Source, util, Krate};
use anyhow::{Context, Error};
use bytes::Bytes;
use reqwest::Client;
use std::path::Path;
use tracing::{error, warn};
use tracing_futures::Instrument;
pub(crate) enum KrateSource {
Registry(Bytes),
Git(crate::git::GitSource),
}
impl KrateSource {
pub(crate) fn len(... | (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 | #!/usr/bin/env python2.7
import couchdb
import re
import math
from collections import defaultdict, Counter, OrderedDict
import unicodedata
import csv
import copy
import click
from time import time
from datetime import datetime
from genologics.config import BASEURI, USERNAME, PASSWORD
from genologics.lims import Lims... | main() | conditional_block | |
repooler.py | #!/usr/bin/env python2.7
import couchdb
import re
import math
from collections import defaultdict, Counter, OrderedDict
import unicodedata
import csv
import copy
import click
from time import time
from datetime import datetime
from genologics.config import BASEURI, USERNAME, PASSWORD
from genologics.lims import Lims... | ():
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 | #!/usr/bin/env python2.7
import couchdb
import re
import math
from collections import defaultdict, Counter, OrderedDict
import unicodedata
import csv
import copy
import click
from time import time
from datetime import datetime
from genologics.config import BASEURI, USERNAME, PASSWORD
from genologics.lims import Lims... |
#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 | #!/usr/bin/env python2.7
import couchdb
import re
import math
from collections import defaultdict, Counter, OrderedDict
import unicodedata
import csv
import copy
import click
from time import time
from datetime import datetime
from genologics.config import BASEURI, USERNAME, PASSWORD
from genologics.lims import Lims... | 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 | #!/usr/bin/python
# coding: utf-8
#----------------------------------------------------------
#
# Light Painting Programm for NeoPixel Strip
#
# Based on several examples found on the Adafruit Learning System
# Thanks to Tony DiCola , Phillip Burgess and others
#
# This version adapted and expanded by Peter K. ... |
#-------------------------------------------
# ***** 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 | #!/usr/bin/python
# coding: utf-8
#----------------------------------------------------------
#
# Light Painting Programm for NeoPixel Strip
#
# Based on several examples found on the Adafruit Learning System
# Thanks to Tony DiCola , Phillip Burgess and others
#
# This version adapted and expanded by Peter K. ... | 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 | #!/usr/bin/python
# coding: utf-8
#----------------------------------------------------------
#
# Light Painting Programm for NeoPixel Strip
#
# Based on several examples found on the Adafruit Learning System
# Thanks to Tony DiCola , Phillip Burgess and others
#
# This version adapted and expanded by Peter K. ... |
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 | #!/usr/bin/python
# coding: utf-8
#----------------------------------------------------------
#
# Light Painting Programm for NeoPixel Strip
#
# Based on several examples found on the Adafruit Learning System
# Thanks to Tony DiCola , Phillip Burgess and others
#
# This version adapted and expanded by Peter K. ... | (strip):
global gamma_a
if debug: print "Draw colorwipe3, color and then fade"
max=255
for i in range(striplen):
color=Color(max,0,0)
# print max, gamma_a[max]
strip.setPixelColor(i, color)
bright=255
for z in range (15):
# if debug: print "bright %d" % brigh... | colorWipe3 | identifier_name |
python_module.py | # # -*- coding:utf-8 -*-
import sys
print('\n---------------------module:__builtin__--------------------')
print(vars())
print(dir(sys.modules['__builtin__']))
print('\n---------------------module:time--------------------')
import time
print(time.asctime()) # 返回时间格式:Sun May 7 21:46:15 2017
print(time.time()) ... | <gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
'''
# xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml
import xml.etree.ElementTree as ET
fpxml = open('xmltest.xml', 'w+')
fpxml.write(xmlstr)
fpxml.close()
tree = ... | <rank updated="yes">69</rank>
<year>2011</year>
| random_line_split |
python_module.py | # # -*- coding:utf-8 -*-
import sys
print('\n---------------------module:__builtin__--------------------')
print(vars())
print(dir(sys.modules['__builtin__']))
print('\n---------------------module:time--------------------')
import time
print(time.asctime()) # 返回时间格式:Sun May 7 21:46:15 2017
print(time.time()) ... | # 返回所有子节点信息
item_list = config.items('bitbucket.org')
print(item_list) # 列出所有子节点详细信息
val = config.get('topsecret.server.com','host port')
print(val) # 返回单个子节点信息
val2 = config.getint('topsecret.server.com','host port')
print(val2)
# 删除'bitbucket.org'
sec = con... | int(options) | conditional_block |
retransmission.rs | //! Retransmission is covered in section 6.3 of RFC 4960.
//!
//! 1. Perform round-trip time (RTT) measurements from the time a TSN is sent until it is
//! acknowledged.
//! a) A measurement must be made once per round-trip, but no more. I interpret this to mean
//! that only one measurement may be in prog... | 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 | //! Retransmission is covered in section 6.3 of RFC 4960.
//!
//! 1. Perform round-trip time (RTT) measurements from the time a TSN is sent until it is
//! acknowledged.
//! a) A measurement must be made once per round-trip, but no more. I interpret this to mean
//! that only one measurement may be in prog... |
/// "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 | //! Retransmission is covered in section 6.3 of RFC 4960.
//!
//! 1. Perform round-trip time (RTT) measurements from the time a TSN is sent until it is
//! acknowledged.
//! a) A measurement must be made once per round-trip, but no more. I interpret this to mean
//! that only one measurement may be in prog... | (&mut self) {
// We have received acknowledgement of the receipt of the measurement TSN, so calculate the
// RTT and related variables.
let (_, rtt_start) = self.rtt_measurement.take().unwrap(); // Caller verifies Some(_).
let rtt = rtt_start.elapsed();
let min = Duration::from_... | complete_rtt_measurement | identifier_name |
file.rs | //! File operations
//!
//! - read, pread, readv
//! - write, pwrite, writev
//! - lseek
//! - truncate, ftruncate
//! - sendfile, copy_file_range
//! - sync, fsync, fdatasync
//! - ioctl, fcntl
//! - access, faccessat
use super::*;
use linux_object::{process::FsInfo, time::TimeSpec};
impl Syscall<'_> {
/// Reads... | : 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 | //! File operations
//!
//! - read, pread, readv
//! - write, pwrite, writev
//! - lseek
//! - truncate, ftruncate
//! - sendfile, copy_file_range
//! - sync, fsync, fdatasync
//! - ioctl, fcntl
//! - access, faccessat
use super::*;
use linux_object::{process::FsInfo, time::TimeSpec};
impl Syscall<'_> {
/// Reads... | 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 | //! File operations
//!
//! - read, pread, readv
//! - write, pwrite, writev
//! - lseek
//! - truncate, ftruncate
//! - sendfile, copy_file_range
//! - sync, fsync, fdatasync
//! - ioctl, fcntl
//! - access, faccessat
use super::*;
use linux_object::{process::FsInfo, time::TimeSpec};
impl Syscall<'_> {
/// Reads... | 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 | //! File operations
//!
//! - read, pread, readv
//! - write, pwrite, writev
//! - lseek
//! - truncate, ftruncate
//! - sendfile, copy_file_range
//! - sync, fsync, fdatasync
//! - ioctl, fcntl
//! - access, faccessat
use super::*;
use linux_object::{process::FsInfo, time::TimeSpec};
impl Syscall<'_> {
/// Reads... | 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 | package cluster
import (
"context"
"encoding/json"
errors2 "errors"
"fmt"
"reflect"
"github.com/rancher/rancher/pkg/kontainer-engine/logstream"
"github.com/rancher/rancher/pkg/kontainer-engine/types"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/api/errors"
)
const (
PreCreating = "Pre-Creating"
C... | 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 | package cluster
import (
"context"
"encoding/json"
errors2 "errors"
"fmt"
"reflect"
"github.com/rancher/rancher/pkg/kontainer-engine/logstream"
"github.com/rancher/rancher/pkg/kontainer-engine/types"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/api/errors"
)
const (
PreCreating = "Pre-Creating"
C... | (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 | package cluster
import (
"context"
"encoding/json"
errors2 "errors"
"fmt"
"reflect"
"github.com/rancher/rancher/pkg/kontainer-engine/logstream"
"github.com/rancher/rancher/pkg/kontainer-engine/types"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/api/errors"
)
const (
PreCreating = "Pre-Creating"
C... |
// 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.Er... | {
// 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 | package cluster
import (
"context"
"encoding/json"
errors2 "errors"
"fmt"
"reflect"
"github.com/rancher/rancher/pkg/kontainer-engine/logstream"
"github.com/rancher/rancher/pkg/kontainer-engine/types"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/api/errors"
)
const (
PreCreating = "Pre-Creating"
C... |
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 | /**
* HttpBox - http functions
*
*
* JavaScript
*
* @author Sergii Beskorovainyi <bsa2657@yandex.ru>
* @license MIT <http://www.opensource.org/licenses/mit-license.php>
* @link https://github.com/bsa-git/vuetify-nuxt-start/
*/
import qs from 'qs'
import useragent from 'express-useragent'
class HttpBox ... |
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 | /**
* HttpBox - http functions
*
*
* JavaScript
*
* @author Sergii Beskorovainyi <bsa2657@yandex.ru>
* @license MIT <http://www.opensource.org/licenses/mit-license.php>
* @link https://github.com/bsa-git/vuetify-nuxt-start/
*/
import qs from 'qs'
import useragent from 'express-useragent'
class HttpBox ... | 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 | /**
* HttpBox - http functions
*
*
* JavaScript
*
* @author Sergii Beskorovainyi <bsa2657@yandex.ru>
* @license MIT <http://www.opensource.org/licenses/mit-license.php>
* @link https://github.com/bsa-git/vuetify-nuxt-start/
*/
import qs from 'qs'
import useragent from 'express-useragent'
class HttpBox ... | () {
return useragent.parse(this.request.headers['user-agent']);
}
}
export default HttpBox
| getUserAgent | identifier_name |
http.class.js | /**
* HttpBox - http functions
*
*
* JavaScript
*
* @author Sergii Beskorovainyi <bsa2657@yandex.ru>
* @license MIT <http://www.opensource.org/licenses/mit-license.php>
* @link https://github.com/bsa-git/vuetify-nuxt-start/
*/
import qs from 'qs'
import useragent from 'express-useragent'
class HttpBox ... | else {
postData = qs.parse(body);
}
resolve(postData)
})
})
}
/**
* Get UserAgent info for server
* {
"isMobile":false,
"isDesktop":true,
"isBot":false,
"isIE":false,
"isChrome":... | {
postData = JSON.parse(body);
} | conditional_block |
generator.go | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
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 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | {
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 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | 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 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.