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 |
|---|---|---|---|---|
raft.go | [prevLogIndex].Term
leaderCommit := rf.commitIndex
rf.mu.Unlock()
peerNum := len(rf.peers)
for i := 0; i < peerNum; i++ {
if i == rf.me {
continue
}
args := AppendEntriesArgs{term, rf.me, prevLogIndex, prevLogTerm, []Log{}, leaderCommit}
reply := AppendEntriesReply{}
go rf.sendAppendEntries(... |
rf.currentTerm = currentTerm
rf.votedFor = votedFor
rf.log = log
}
//
// example RequestVote RPC arguments structure.
// field names must start with capital letters!
//
type RequestVoteArgs struct {
// Your data here (2A, 2B).
Term int
CandidateID int
LastLogIndex int
LastLogTerm int
}
//
// exampl... | {
fmt.Fprintf(os.Stderr, "Peer #%d failed to decode state from persister, retrying...\n", rf.me)
count++
if count > 5 {
panic("Peer #%d failed to decode state from persister, abort\n")
}
} | conditional_block |
raft.go | .log[prevLogIndex].Term
leaderCommit := rf.commitIndex
rf.mu.Unlock()
peerNum := len(rf.peers)
for i := 0; i < peerNum; i++ {
if i == rf.me {
continue
}
args := AppendEntriesArgs{term, rf.me, prevLogIndex, prevLogTerm, []Log{}, leaderCommit}
reply := AppendEntriesReply{}
go rf.sendAppendEntr... | //
// save Raft's persistent state to stable storage,
// where it can later be retrieved after a crash and restart.
// see paper's Figure 2 for a description of what should be persistent.
// this function can only be called when `rf` holds the lock
func (rf *Raft) persist() {
// Your code here (2C).
// Example:
// w... | random_line_split | |
raft.go | ft) readPersist(data []byte) {
if data == nil || len(data) < 1 { // bootstrap without any state?
return
}
// Your code here (2C).
// Example:
// r := bytes.NewBuffer(data)
// d := labgob.NewDecoder(r)
// var xxx
// var yyy
// if d.Decode(&xxx) != nil ||
// d.Decode(&yyy) != nil {
// error...
// } els... | {
if ok := rf.peers[server].Call("Raft.AppendEntries", args, reply); !ok {
return
}
rf.mu.Lock()
defer rf.mu.Unlock()
// drop old reply
if args.Term != reply.Term {
return
}
if reply.Term > rf.currentTerm {
rf.currentTerm = reply.Term
rf.persist()
rf.state = FOLLOWER
return
}
if reply.Success { | identifier_body | |
raft.go | [prevLogIndex].Term
leaderCommit := rf.commitIndex
rf.mu.Unlock()
peerNum := len(rf.peers)
for i := 0; i < peerNum; i++ {
if i == rf.me {
continue
}
args := AppendEntriesArgs{term, rf.me, prevLogIndex, prevLogTerm, []Log{}, leaderCommit}
reply := AppendEntriesReply{}
go rf.sendAppendEntries(... | () {
// comes to power, initialize fields
rf.mu.Lock()
rf.state = LEADER
rf.votedFor = -1
peerNum := len(rf.peers)
for i := 0; i < peerNum; i++ {
rf.nextIndex[i] = len(rf.log) // leader last log index + 1
rf.matchIndex[i] = 0
}
rf.mu.Unlock()
go rf.startHeartBeat()
// leader work
for {
if rf.killed()... | leader | identifier_name |
dashboard.py | os.makedirs(ontology_dir, exist_ok=True)
# Launch the JVM using the robot JAR
py4j.java_gateway.launch_gateway(
jarpath='build/robot.jar', classpath='org.obolibrary.robot.PythonOperation', die_on_exit=True, port=25333)
# Activate gateway to JVM
gateway = JavaGateway()
robot_gateway = g... | parser = ArgumentParser(description='Create dashboard files')
parser.add_argument('ontology', type=str, help='Input ontology file')
parser.add_argument('registry', type=FileType('r'), help='Registry YAML file')
parser.add_argument('license', type=FileType('r'), help='License JSON schema')
parser.add_arg... | identifier_body | |
dashboard.py | if 'is_obsolete' in data and data['is_obsolete'] is 'true':
# do not run on obsolete ontologies
print('{0} is obsolete and will not be checked...'.format(namespace), flush=True)
sys.exit(0)
# ---------------------------- #
# RUN CHECKS
# ---------------------------- #
print('-... | 5: 'FP5 Scope',
6: 'FP6 Textual Definitions',
7: 'FP7 Relations',
8: 'FP8 Documented',
9: 'FP9 Plurality of Users', | random_line_split | |
dashboard.py | Helper for working with ontologies
io_helper = robot_gateway.IOHelper()
# Handle ontology file
big = namespace in BIG_ONTS
if not big:
# Load ontology as OWLOntology object
if not ontology_file:
ont_or_file = None
try:
ont_or_file = io_helper.loadOntology... | summary = 'INFO'
summary_comment = '{0} info messages'.format(info) | conditional_block | |
dashboard.py | ():
# ---------------------------- #
# PREPARE INPUT
# ---------------------------- #
# parse input args
parser = ArgumentParser(description='Create dashboard files')
parser.add_argument('ontology', type=str, help='Input ontology file')
parser.add_argument('registry', type=FileType('r'), he... | run | identifier_name | |
bench.rs | )]
pub struct TestBodySummary {
pub name: String,
pub summary: Summary,
}
/// The outcome of a test
#[derive(Clone)]
struct TestResult {
name: String,
grand_summary: Summary,
bodies_summary: Vec<TestBodySummary>,
}
/// The outcome of a test, without the name of the test
pub struct AnonymousTestRes... | {
unsafe { global_setup(&mut global_ctx) }
} | conditional_block | |
bench.rs | unsafe extern "C" fn(*mut TestCtx)>,
global_teardown: Option<unsafe extern "C" fn(TestCtx)>,
version: u64,
}
/// A named test body function
#[derive(Clone, Debug)]
pub struct TestBody {
pub name: String,
pub body_fn: TestBodyFn,
}
/// An individual test, with function pointers for each step
#[derive(C... | {
pub grand_summary: Summary,
pub bodies_summary: Vec<TestBodySummary>,
}
impl Default for AnonymousTestResult {
fn default() -> Self {
Self {
grand_summary: Summary::new(&[0.0]),
bodies_summary: vec![],
}
}
}
impl From<TestResult> for AnonymousTestResult {
... | AnonymousTestResult | identifier_name |
bench.rs | setup(&mut self) {}
fn teardown(&mut self) {}
fn bodies<'t>(&'t mut self) -> Vec<Box<dyn Fn(usize) -> Ret + 't>>;
}
impl TestBodiesBench {
#[inline]
fn body(&self, body_id: usize) {
unsafe { (self.bodies[body_id])(self.ctx) }
}
}
impl Runnable<()> for TestBodiesBench {
fn bodies<'t>(&... | let library_path = &test_suite.library_path; | random_line_split | |
bench.rs | <unsafe extern "C" fn(*mut TestCtx)>,
global_teardown: Option<unsafe extern "C" fn(TestCtx)>,
version: u64,
}
/// A named test body function
#[derive(Clone, Debug)]
pub struct TestBody {
pub name: String,
pub body_fn: TestBodyFn,
}
/// An individual test, with function pointers for each step
#[derive(... | .clone()
.iter()
.map(|body| body.body_fn)
.collect(),
};
let bench_result = bench_runner.bench(&mut test_bodies_bench);
let mut bodies_summary = vec![];
for (body_id, body) in (*test).bodies.iter().enumerate() {
let test_body_summary = TestBodySum... | {
let mut ctx: TestCtx = ptr::null_mut();
if let Some(setup) = (*test).setup_fn {
unsafe { setup(global_ctx, &mut ctx) }
}
let bench_runner = AdaptiveRunner::new(
config
.initial_round_size
.unwrap_or(DEFAULT_INITIAL_ROUND_SIZE),
config.min_sample_size.un... | identifier_body |
opmapi.rs | 25 = 0x8,
OPM_PROTECTION_STANDARD_EN300294_625I = 0x10,
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_525P = 0x20,
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_750P = 0x40,
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_1125I = 0x80,
OPM_PROTECTION_STANDARD_CEA805A_TYPEB_525P = 0x100,
OPM_PROTECTION_STANDARD_CEA805A_TY... | {
ulBusTypeAndImplementation & OPM_BUS_IMPLEMENTATION_MODIFIER_NON_STANDARD
} | identifier_body | |
opmapi.rs | _525I = 0x1,
OPM_PROTECTION_STANDARD_IEC61880_2_525I = 0x2,
OPM_PROTECTION_STANDARD_IEC62375_625P = 0x4,
OPM_PROTECTION_STANDARD_EIA608B_525 = 0x8,
OPM_PROTECTION_STANDARD_EN300294_625I = 0x10,
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_525P = 0x20,
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_750P = 0x40,
... | GetBusImplementation | identifier_name | |
opmapi.rs | 8b5ef5d1, 0xc30d, 0x44ff, 0x84, 0xa5, 0xea, 0x71, 0xdc, 0xe7, 0x8f, 0x13}
DEFINE_GUID!{OPM_SET_PROTECTION_LEVEL_ACCORDING_TO_CSS_DVD,
0x39ce333e, 0x4cc0, 0x44ae, 0xbf, 0xcc, 0xda, 0x50, 0xb5, 0xf8, 0x2e, 0x72}
ENUM!{enum __MIDL___MIDL_itf_opmapi_0000_0000_0001 {
OPM_OMAC_SIZE = 16,
OPM_128_BIT_RANDOM_NUMBER... | OPM_PROTECTION_STANDARD_CEA805A_TYPEA_525P = 0x20,
OPM_PROTECTION_STANDARD_CEA805A_TYPEA_750P = 0x40, | random_line_split | |
oauth.rs | state: String,
}
impl OAuthClient {
pub fn new() -> OAuthClient {
build_oauth_client()
}
pub fn get_access_token(&self) -> String {
if let token = self.oauth_token.as_ref().unwrap() {
return token.access_token.clone();
}
"".to_string()
}
}
fn build_oauth_cl... | {
fs::remove_file("access_token.rvp").expect("Could not remove file");
} | conditional_block | |
oauth.rs | _in: usize,
scope: String,
refresh_token: String,
}
#[derive(Debug)]
pub struct | {
client_id: String,
client_state: String,
authorization_link: String,
auth_state: OAuthState,
oauth_token: Option<OAuthToken>,
pub error_state: String,
pub code: String,
}
struct AuthBox {
has_error: bool,
error_msg: String,
code: String,
state: String,
}
impl OAuthClient... | OAuthClient | identifier_name |
oauth.rs | expires_in: usize,
scope: String,
refresh_token: String,
}
#[derive(Debug)]
pub struct OAuthClient {
client_id: String,
client_state: String,
authorization_link: String,
auth_state: OAuthState,
oauth_token: Option<OAuthToken>,
pub error_state: String,
pub code: String,
}
struct Au... | }
let auth_box = AuthBox {
has_error: true,
error_msg: "Reached timeout. User did not authorize usage of RPV in time".to_string(),
code: "".to_string(),
state: "".to_string(),
};
println!("Timeout during authentication");
tx_countdo... | for passed_seconds in 0..wait_time {
thread::sleep(Duration::from_secs(1)); | random_line_split |
make_index_file.py | (self):
return Path('run{:06d}-{:06d}'.format(self.obs_group[0], self.obs_group[1]))
@property
def _obs_folder(self):
return Path('run{:06d}'.format(self.obs_id))
def folder(self, step=None):
"""Create folder for a given step.
"""
if step is None:
return... | _obs_group_folder | identifier_name | |
make_index_file.py |
# Background modeling
BG_MODEL_DIR = OUT_DIR / 'background'
BG_MODEL_GROUPING = BG_MODEL_DIR / 'background_grouping.ecsv'
BG_MODEL_OFF_RUNS = BG_MODEL_DIR / 'background_runs.ecsv'
BG_MODEL_OFF_RUNS_GROUPED = BG_MODEL_DIR / 'background_runs_grouped.ecsv'
class Observation:
"""Helper functions ... | random_line_split | ||
make_index_file.py |
elif filetype == 'edisp':
return self.folder('irfs') / 'edisp_{:06d}.fits.gz'.format(self.obs_id)
elif filetype == 'psf_3gauss':
return self.folder('irfs') / 'psf_3gauss_{:06d}.fits.gz'.format(self.obs_id)
else:
raise ValueError('Invalid {} {}'.format(filetyp... | return self.folder('irfs') / 'aeff_{:06d}.fits.gz'.format(self.obs_id) | conditional_block | |
make_index_file.py | .gz'.format(self.obs_id)
elif filetype == 'psf_3gauss':
return self.folder('irfs') / 'psf_3gauss_{:06d}.fits.gz'.format(self.obs_id)
else:
raise ValueError('Invalid {} {}'.format(filetype))
def out_filename(self, filetype, format='old', dir=Location.OUT_DIR):
"""Name... |
class ListObservations:
def __init__(self, runlist_file, config):
self.observations = []
runlist = np.loadtxt(runlist_file, ndmin=2)
obs_ids = runlist[:, 0].astype(int)
telcodes = runlist[:, 1].astype(int)
for obs_id, telcode in zip(obs_ids, telcodes):
obs = Ob... | """Check if all out files exist"""
for filetype in self.filetypes:
filename = self.out_filename(filetype)
if not filename.is_file():
log.error('MISSING: {}'.format(filename))
return False
return True | identifier_body |
user-management.component.ts | import 'jspdf-autotable';
import { UserManagementService } from '../../services/user-management.service';
declare var $: any
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import { analyzeFile } from '@angular/compiler';
import { environment } from 'src/environments/environment';
const EXCEL_TY... | random_line_split | ||
user-management.component.ts | any = XLSX.write(wb, { bookType: 'csv', type: 'array' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
FileSaver.saveAs(data, 'Workflow_Input' + EXCEL_EXTENSION)... |
else {
this.BulkUploadDetailsForm.patchValue({ InputFile: { file: files.item(0) } });
}
import('xlsx').then(xlsx => {
let workBook = null;
let userdata = null;
const reader = new FileReader();
reader.onload = (event) => {
const dat... | {
this.Errormessage("Invalid file upload");
this.fileName = 'Choose File';
return false;
} | conditional_block |
user-management.component.ts | this.equalArray(usermgntHeader,this.headers)
if (!checkEqual) {
this.Errormessage("Header mismacth");
this.fileName = 'Choose File';
return false;
}
},
reader.readAsBinaryString(files.item(0));
});
}
catch (e) {... | {
debugger
this.currentUserId = user.id;
} | identifier_body | |
user-management.component.ts | er' },
{ field: 'assignto', header: 'assignto' },
];
this.Department();
this.Status()
this.OrderType();
}
public get getFields() {
return this.userManagementForm.controls;
}
equalArray(a, b) {
if (a.length === b.length) {
for (var i = 0; i < a.length; i++) {
if ... | exportPdf | identifier_name | |
connection.rs | payload::build_select_protocol(addr, port))?;
}
let key = encryption_key(&mut client)?;
let _ = client
.stream_ref()
.as_tcp()
.set_read_timeout(Some(Duration::from_millis(25)));
let mutexed_client = Arc::new(Mutex::new(client));
let thread_... | let crypted = {
let slice = &packet[HEADER_LEN..HEADER_LEN + len];
secretbox::seal(slice, &nonce, &self.key)
}; | random_line_split | |
connection.rs | _items = start_threads(Arc::clone(&mutexed_client), &udp)?;
info!("[Voice] Connected to: {}", info.endpoint);
let encoder = OpusEncoder::new(SAMPLE_RATE, Channels::Mono, CodingMode::Audio)?;
let soft_clip = SoftClip::new(Channels::Stereo);
// Per discord dev team's current recommenda... | set_speaking | identifier_name | |
connection.rs | _hello) => {
break received_hello;
},
VoiceEvent::Heartbeat(_) => continue,
other => {
debug!("[Voice] Expected hello/heartbeat; got: {:?}", other);
return Err(Error::Voice(VoiceError::ExpectedHandshake));
... | ,
};
// May need to force interleave/copy.
combine_audio(buffer, &mut mix_buffer, source_stereo, vol);
len = len.max(temp_len);
i += if temp_len > 0 {
1
} else {
sources.remove(i);
... | {
let buffer_len = if source_stereo { 960 * 2 } else { 960 };
match stream.read_pcm_frame(&mut buffer[..buffer_len]) {
Some(len) => len,
None => 0,
}
} | conditional_block |
connection.rs | _id,
})
}
#[allow(unused_variables)]
pub fn cycle(&mut self,
sources: &mut Vec<LockedAudio>,
receiver: &mut Option<Box<AudioReceiver>>,
audio_timer: &mut Timer)
-> Result<()> {
let mut buffer = [0i16; 960 * 2];
let ... | {
for i in 0..1920 {
let sample_index = if true_stereo { i } else { i/2 };
let sample = (raw_buffer[sample_index] as f32) / 32768.0;
float_buffer[i] = float_buffer[i] + sample * volume;
}
} | identifier_body | |
displayer.py | []
link_attributes = []
title_prefix = ''
title_postfix = ''
def __init__(self, the_json):
self.json = the_json
self.data = json.loads(self.json)
self.id = self.data['id']
self.prepare()
def __cmp__(self, other):
return cmp(self.id, other.id)
@property... | simple_fields = ['hostname',
'buildout_directory',
'configfile',
'server_names',
'proxy_port',
]
buildout = None
server = None
link_attributes = ['buildout',
'server',
... | class Nginx(Common):
subdir = 'sites'
template_name = 'nginx.html'
title_prefix = 'NGINX configuration of' | random_line_split |
displayer.py | link_attributes = []
title_prefix = ''
title_postfix = ''
def __init__(self, the_json):
self.json = the_json
self.data = json.loads(self.json)
self.id = self.data['id']
self.prepare()
def __cmp__(self, other):
return cmp(self.id, other.id)
@property
... | (Common):
subdir = 'sites'
template_name = 'nginx.html'
title_prefix = 'NGINX configuration of'
simple_fields = ['hostname',
'buildout_directory',
'configfile',
'server_names',
'proxy_port',
]
bu... | Nginx | identifier_name |
displayer.py | link_attributes = []
title_prefix = ''
title_postfix = ''
def __init__(self, the_json):
self.json = the_json
self.data = json.loads(self.json)
self.id = self.data['id']
self.prepare()
def __cmp__(self, other):
return cmp(self.id, other.id)
@property
... |
class Buildout(Common):
subdir = 'buildouts'
template_name = 'buildout.html'
title_prefix = 'Buildout directory'
simple_fields = ['hostname',
'directory',
'extends', # TODO: fix this: missing KGS here.
'version_control_system',
... | title = "Who worked on this?"
def __init__(self, vcs, url):
assert(vcs == 'git')
self.url = url
@property
def link(self):
return self.url + '/graphs/contributors' | identifier_body |
displayer.py | (view=self))
logger.info("Wrote %s", outfile)
@property
def fields(self):
result = []
for simple_field in self.simple_fields:
value = self.data.get(simple_field)
if value is None:
continue
if isinstance(value, list):
va... | utils.clear_directory_contents(os.path.join(
utils.html_dir(), subdir)) | conditional_block | |
models.py | )
# Many-to-Many auxiliary table of Bands and Songs
band_songs = db.Table('band_songs',
db.Column('band_id', db.Integer, db.ForeignKey('band.id'), nullable=False),
db.Column('song_id', db.Integer, db.ForeignKey('song.id'), nullable=False)
)
class User... | songs = db.relationship('Song', backref='user', lazy='dynamic', cascade="all, delete-orphan")
shows = db.relationship('Show', backref='user', lazy='dynamic', cascade="all, delete-orphan")
def __repr__(self):
return 'User {0} ({1})'.format(self.name, self.email)
@property
def password(self)... | confirmed = db.Column(db.Boolean, default=False)
bands = db.relationship('Band', backref='user', lazy='dynamic', cascade="all, delete-orphan") | random_line_split |
models.py | ('song.id'), nullable=False)
)
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
email = db.Column(db.String(64), unique=True, index=True, nullable=False)
password_hash = db.Co... | self.songs.remove(song) | identifier_body | |
models.py | )
# Many-to-Many auxiliary table of Bands and Songs
band_songs = db.Table('band_songs',
db.Column('band_id', db.Integer, db.ForeignKey('band.id'), nullable=False),
db.Column('song_id', db.Integer, db.ForeignKey('song.id'), nullable=False)
)
class User... | (self):
raise AttributeError('Password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def generate_... | password | identifier_name |
models.py | )
# Many-to-Many auxiliary table of Bands and Songs
band_songs = db.Table('band_songs',
db.Column('band_id', db.Integer, db.ForeignKey('band.id'), nullable=False),
db.Column('song_id', db.Integer, db.ForeignKey('song.id'), nullable=False)
)
class User... |
soup = getsoup(url)
article = soup.find('article')
html = str(article)
if 'e-chords' in url:
soup = getsoup(url)
pre = soup.find('pre', id='core')
# Remove Tab Div, keep raw tab
div = pre.find('div')
if div is not ... | url = 'https://www.' + url[10:] # So we don't have to deal with mobile URLs | conditional_block |
client.go | /147.75.94.115/udp/4001/quic/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt",
"/ip4/147.75.109.213/udp/4001/quic/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
"/ip4/147.75.109.29/udp/4001/quic/p2p/QmZa1sAxajnQjVM8WjWXoMbmPd7NsWhfKsPkErzpm9wGkp",
}
var bootstrappersTCP []*peer.AddrInfo
var bootstrappersUDP... |
// let identify get our observed addresses before starting
time.Sleep(time.Second)
err = c.connectToPeer(ci)
c.tracer.Connect(ci, err)
return err
}
func (c *Client) connectToPeer(ci *ClientInfo) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
err := c.host.Conn... | {
return fmt.Errorf("error connecting to bootstrappers: %w", err)
} | conditional_block |
client.go | 4/147.75.94.115/udp/4001/quic/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt",
"/ip4/147.75.109.213/udp/4001/quic/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
"/ip4/147.75.109.29/udp/4001/quic/p2p/QmZa1sAxajnQjVM8WjWXoMbmPd7NsWhfKsPkErzpm9wGkp",
}
var bootstrappersTCP []*peer.AddrInfo
var bootstrappersUD... | if !isRelayConn(conn) {
return nil
}
}
select {
case <-deadline:
break poll
case <-time.After(time.Second):
}
}
return fmt.Errorf("no direct connection to peer")
}
func (c *Client) connectToBootstrappers() error {
var pis []*peer.AddrInfo
if c.domain == "TCP" {
pis = bootstrappersTCP
} ... | for _, conn := range c.host.Network().ConnsToPeer(ci.Info.ID) { | random_line_split |
client.go | pi, err := parseAddrInfo(a)
if err != nil {
panic(err)
}
bootstrappersTCP = append(bootstrappersTCP, pi)
}
for _, a := range bootstrappersUDPString {
pi, err := parseAddrInfo(a)
if err != nil {
panic(err)
}
bootstrappersUDP = append(bootstrappersUDP, pi)
}
}
type Client struct {
host host... | {
// connect to relay and reserve slot
var rsvp *circuit.Reservation
var err error
for rsvp == nil {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
err = c.host.Connect(ctx, *c.relay)
cancel()
if err != nil {
log.Warnf("error connecting to relay: %s; will retry in 1min", err)
t... | identifier_body | |
client.go | 4/147.75.94.115/udp/4001/quic/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt",
"/ip4/147.75.109.213/udp/4001/quic/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
"/ip4/147.75.109.29/udp/4001/quic/p2p/QmZa1sAxajnQjVM8WjWXoMbmPd7NsWhfKsPkErzpm9wGkp",
}
var bootstrappersTCP []*peer.AddrInfo
var bootstrappersUD... | (ci *ClientInfo) error {
// check for existing connections first
for _, conn := range c.host.Network().ConnsToPeer(ci.Info.ID) {
if !isRelayConn(conn) {
return nil
}
}
err := c.connectToBootstrappers()
if err != nil {
return fmt.Errorf("error connecting to bootstrappers: %w", err)
}
// let identify ge... | Connect | identifier_name |
initializer.rs | Storage},
Component,
},
effect::{
announcements::{
ChainspecLoaderAnnouncement, ContractRuntimeAnnouncement, ControlAnnouncement,
},
requests::{
ConsensusRequest, ContractRuntimeRequest, LinearChainRequest, NetworkRequest,
RestRequest, StateSt... | (&self) -> Option<ReactorExit> | maybe_exit | identifier_name |
initializer.rs | {
None
}
}
}
impl From<StorageRequest> for Event {
fn from(request: StorageRequest) -> Self {
Event::Storage(storage::Event::StorageRequest(request))
}
}
impl From<ContractRuntimeRequest> for Event {
fn from(request: ContractRuntimeRequest) -> Self {
Event::Contrac... | NodeId::from(&self.network_identity)
}
}
}
} | random_line_split | |
initializer.rs | },
Component,
},
effect::{
announcements::{
ChainspecLoaderAnnouncement, ContractRuntimeAnnouncement, ControlAnnouncement,
},
requests::{
ConsensusRequest, ContractRuntimeRequest, LinearChainRequest, NetworkRequest,
RestRequest, StateStoreReque... |
}
impl From<NetworkRequest<NodeId, gossiper::Message<GossipedAddress>>> for Event {
fn from(_request: NetworkRequest<NodeId, gossiper::Message<GossipedAddress>>) -> Self {
unreachable!("no gossiper events happen during initialization")
}
}
impl From<ConsensusRequest> for Event {
fn from(_request:... | {
unreachable!("no linear chain events happen during initialization")
} | identifier_body |
getMultiTractTemplate.py | coaddName = pexConfig.Field(
doc="coadd name: typically one of 'deep', 'goodSeeing', or 'dcr'",
dtype=str,
default="deep",
)
warpType = pexConfig.Field(
doc="Warp type of the coadd template: one of 'direct' or 'psfMatched'",
dtype=str,
default="direct",
)
... |
self.log.info("Central skyMap tract %s" % (centralTractInfo.getId(),))
skyCorners = [expWcs.pixelToSky(pixPos) for pixPos in expBoxD.getCorners()]
tractPatchList = skyMap.findTractPatchList(skyCorners)
if not tractPatchList:
raise RuntimeError("No suitable tract found")
... | raise RuntimeError("No suitable tract found for central point") | conditional_block |
getMultiTractTemplate.py |
----------
exposure: `lsst.afw.image.Exposure`
an exposure for which to generate an overlapping template
sensorRef : TYPE
a Butler data reference that can be used to obtain coadd data
templateIdList : TYPE, optional
list of data ids (unused)
R... | """Return coadd name for given task config
Returns
-------
CoaddDatasetName : `string`
TODO: This nearly duplicates a method in CoaddBaseTask (DM-11985)
"""
warpType = self.config.warpType
suffix = "" if warpType == "direct" else warpType[0].upper() + warpType[1:]... | identifier_body | |
getMultiTractTemplate.py | coaddName = pexConfig.Field(
doc="coadd name: typically one of 'deep', 'goodSeeing', or 'dcr'",
dtype=str,
default="deep",
)
warpType = pexConfig.Field(
doc="Warp type of the coadd template: one of 'direct' or 'psfMatched'",
dtype=str,
default="direct",
)
... | (self, exposure, sensorRef, templateIdList=None):
"""Retrieve and mosaic a template coadd that overlaps the exposure where
the template spans multiple tracts.
The resulting template image will be an average of all the input templates from
the separate tracts.
The PSF on the tem... | run | identifier_name |
getMultiTractTemplate.py | coaddName = pexConfig.Field(
doc="coadd name: typically one of 'deep', 'goodSeeing', or 'dcr'",
dtype=str,
default="deep",
)
warpType = pexConfig.Field(
doc="Warp type of the coadd template: one of 'direct' or 'psfMatched'",
dtype=str,
default="direct",
)
... | patchInt = int(f"{patchInfo.getIndex()[0]}{patchInfo.getIndex()[1]}")
innerBBox = geom.Box2I(tractInfo._minimumBoundingBox(finalWcs))
if itract == 0:
# clip to image and tract boundaries
patchSubBBox.clip(finalBBox)
... | # Local patch information
patchSubBBox = geom.Box2I(patchInfo.getInnerBBox())
patchSubBBox.clip(coaddBBox) | random_line_split |
arm.py | _joint_limits(abs_input):
return False
self._position_joint_desired = np.copy(abs_input)
joint_positions = self._get_joint_positions_all(abs_input)
p.setJointMotorControlArray(self.body,
self.joints,
p.POSITION_C... | pose_ori = pose.copy()
if premultiply:
pose_tf = np.matmul(mat, pose_ori)
else:
pose_tf = np.matmul(pose_ori, mat) | random_line_split | |
arm.py | 0., 1.),
limits=None, tool_T_tip=np.eye(4), scaling=1.):
"""
:param urdf_file: URDF fileName.
:param pos: basePosition.
:param orn: baseOrientation in quaternion.
"""
# should connect to the PyBullet server first
self.body = p.loadURDF(urdf_file,... |
def get_joint_number(self) -> int:
""" Get the number of joints on the arm specified. """
return self.DoF
def dmove_joint(self, delta_pos: [list, np.ndarray]) -> [bool, np.ndarray]:
""" Incremental move in joint space.
"""
if not isinstance(delta_pos, np.ndarray):
... | """ Get the 'desired joint position' of the arm. """
return self._position_joint_desired | identifier_body |
arm.py | self.limits = limits
self.tool_T_tip = tool_T_tip # tool_T_tip offset
self.scaling = scaling # scaling factor
# update RCM pose and related transformations
self.wTr, self.rTw = None, None
self.update_rcm_pose()
# update EEF and TIP related transformations
... | pose_eef = get_pose_2d_from_matrix(pose_eef) | conditional_block | |
arm.py | self._position_joint_desired = np.copy(abs_input)
joint_positions = self._get_joint_positions_all(abs_input)
p.setJointMotorControlArray(self.body,
self.joints,
p.POSITION_CONTROL,
targetPosition... | _set_collision | identifier_name | |
user_controller.js | .9400
// // },
// // {
// // city : 'Chicago',
// // desc : 'This is the second best city in the world!',
// // lat : 41.8819,
// // long : -87.6278
// // },
// // {
// // city : 'Los Angeles',
// // desc : 'This city is live!',
// // lat : 34.0500... | else if($scope.newSpot.street.length < 5) {
$scope.error = {street: 'Invalid street'};
} else if (!$scope.newSpot.house_number.match(house_numberRegex)) { //if the house number entered does not match regex...
$scope.error = {house_number: 'Invalid house_number'};
} else if (!$scope.... | {
$scope.error = {contact: 'Invalid phone number'};
} | conditional_block |
user_controller.js | .9400
// // },
// // {
// // city : 'Chicago',
// // desc : 'This is the second best city in the world!',
// // lat : 41.8819,
// // long : -87.6278
// // },
// // {
// // city : 'Los Angeles',
// // desc : 'This city is live!',
// // lat : 34.0500... | (ts) {
let dataF = new Date(); dataF.setTime(ts);
let strDataF = dataF.toLocaleString();
return strDataF;
}
var firstdate = toDateStr($scope.newRenter.arriving_on)
var | toDateStr | identifier_name |
user_controller.js | 9400
// // },
// // {
// // city : 'Chicago',
// // desc : 'This is the second best city in the world!',
// // lat : 41.8819,
// // long : -87.6278
// // },
// // {
// // city : 'Los Angeles',
// // desc : 'This city is live!',
// // lat : 34.0500,... |
var firstdate = toDateStr($scope.newRenter.arriving_on)
var | {
let dataF = new Date(); dataF.setTime(ts);
let strDataF = dataF.toLocaleString();
return strDataF;
} | identifier_body |
user_controller.js | .9400
// // },
// // {
// // city : 'Chicago',
// // desc : 'This is the second best city in the world!',
// // lat : 41.8819,
// // long : -87.6278
// // },
// // {
// // city : 'Los Angeles',
// // desc : 'This city is live!',
// // lat : 34.0500... | }
$scope.geocode = function()
{
if($scope.newSpot.contact.length < 10) {
$scope.error = {contact: 'Invalid phone number'};
} else if($scope.newSpot.street.length < 5) {
$scope.error = {street: 'Invalid street'};
} else if (!$scope.newSpot.house_number.m... | random_line_split | |
rip_show_statistics_bd.pb.go | }
return ""
}
type RipShowStatisticsBd struct {
ReceivedPackets uint32 `protobuf:"varint,50,opt,name=received_packets,json=receivedPackets,proto3" json:"received_packets,omitempty"`
DiscardedPackets uint32 `protobuf:"varint,51,opt,name=discarded_packets,json=discardedPackets,proto3" json:"discarde... |
func (m *RipShowStatisticsBd) String() string { return proto.CompactTextString(m) }
func (*RipShowStatisticsBd) ProtoMessage() {}
func (*RipShowStatisticsBd) Descriptor() ([]byte, []int) {
return fileDescriptor_66227cbf5e51e264, []int{1}
}
func (m *RipShowStatisticsBd) XXX_Unmarshal(b []byte) error {
return xxx_... | { *m = RipShowStatisticsBd{} } | identifier_body |
rip_show_statistics_bd.pb.go | }
func (m *RipShowStatisticsBd_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_RipShowStatisticsBd_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_RipShowStatisticsBd_KEYS proto.InternalMessageInfo
func (m *RipShowStatisticsBd_KEYS) GetVrfName() string {
if m != nil {
return m.VrfName
}
return ""
}
type RipShowStati... | func (m *RipShowStatisticsBd_KEYS) XXX_Size() int {
return xxx_messageInfo_RipShowStatisticsBd_KEYS.Size(m) | random_line_split | |
rip_show_statistics_bd.pb.go | }
return ""
}
type RipShowStatisticsBd struct {
ReceivedPackets uint32 `protobuf:"varint,50,opt,name=received_packets,json=receivedPackets,proto3" json:"received_packets,omitempty"`
DiscardedPackets uint32 `protobuf:"varint,51,opt,name=discarded_packets,json=discardedPackets,proto3" json:"discarde... |
return 0
}
func (m *RipShowStatisticsBd) GetSentMessageFailures() uint32 {
if m != nil {
return m.SentMessageFailures
}
return 0
}
func (m *RipShowStatisticsBd) GetQueryResponses() uint32 {
if m != nil {
return m.QueryResponses
}
return 0
}
func (m *RipShowStatisticsBd) GetPeriodicUpdates() uint32 {
if ... | {
return m.SentMessages
} | conditional_block |
rip_show_statistics_bd.pb.go | }
return ""
}
type RipShowStatisticsBd struct {
ReceivedPackets uint32 `protobuf:"varint,50,opt,name=received_packets,json=receivedPackets,proto3" json:"received_packets,omitempty"`
DiscardedPackets uint32 `protobuf:"varint,51,opt,name=discarded_packets,json=discardedPackets,proto3" json:"discarde... | () ([]byte, []int) {
return fileDescriptor_66227cbf5e51e264, []int{1}
}
func (m *RipShowStatisticsBd) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_RipShowStatisticsBd.Unmarshal(m, b)
}
func (m *RipShowStatisticsBd) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_RipShowS... | Descriptor | identifier_name |
main.rs | {
#[structopt(
help = "The pattern to search for. Shall be a regular expression passed to regex crate."
)]
pattern: String,
#[structopt(help = "Root repo to grep")]
repo: Option<PathBuf>,
#[structopt(short, long, help = "Branch name")]
branch: Option<String>,
#[structopt(
... | Opt | identifier_name | |
main.rs | if given"
)]
all: bool,
#[structopt(short, long, help = "Depth to search into git commit history")]
depth: Option<usize>,
#[structopt(
short = "o",
long,
help = "Turn off showing matches to a file only once; the default behavior is that if the same file with the same name ha... | let blob = obj.peel_to_blob().ok()?;
if blob.is_binary() {
return None;
}
let ext = PathBuf::from(name).extension()?.to_owned();
if !self.settings.extensions.contains(&ext.to_ascii_lowercase()) {
retu... | random_line_split | |
main.rs | "Disable color coding for the output, default is to use colors in terminal"
)]
no_color_code: bool,
#[structopt(
short = "g",
long,
help = "Disable output grouping. Better for machine inputs"
)]
no_output_grouping: bool,
#[structopt(short, long, help = "Verbose flag")]
... | {
line_end = (i as usize).max(line_start);
break;
} | conditional_block | |
lib.rs | directly, but being able
//! to combine modes like this could be useful for workshops in which
//! participants work through test cases enabling one at a time. Trybuild was
//! originally developed for my [procedural macros workshop at Rust
//! Latam][workshop].
//!
//! [workshop]: https://github.com/dtolnay/proc-macr... | drop | identifier_name | |
lib.rs | test cases enabling one at a time. Trybuild was
//! originally developed for my [procedural macros workshop at Rust
//! Latam][workshop].
//!
//! [workshop]: https://github.com/dtolnay/proc-macro-workshop
//!
//! ```
//! #[test]
//! fn ui() {
//! let t = trybuild::TestCases::new();
//! t.pass("tests/01-parse-h... | {
self.runner.borrow_mut().run();
} | conditional_block | |
lib.rs | by the macro or errors detected by the Rust compiler in the
//! resulting expanded code, and compare against the expected errors to ensure
//! that they remain user-friendly.
//!
//! This style of testing is sometimes called *ui tests* because they test
//! aspects of the user's interaction with a library outside of w... | //! [`ref-cast`]: https://github.com/dtolnay/ref-cast
//!
//! ```console
//! error: RefCast trait requires #[repr(C)] or #[repr(transparent)]
//! --> $DIR/missing-repr.rs:3:10
//! |
//! 3 | #[derive(RefCast)]
//! | ^^^^^^^
//! ```
//!
//! Macros that consume helper attributes will want to check that unrec... | //! by a procedural macro. For example the derive macro from the [`ref-cast`]
//! crate is required to be placed on a type that has either `#[repr(C)]` or
//! `#[repr(transparent)]` in order for the expansion to be free of undefined
//! behavior, which it enforces at compile time:
//! | random_line_split |
twitter.py | .strip()
u = urlmap.get(title_search_term, None)
if u is not None:
source_path = Path(u['source_path'])
full_path = contentdir / source_path
add_syndication(full_path, orig_tweet_url, "twitter")
return True
else:
print("######## Unm... | print(mdfile)
# move it to notes, since it's not a photo
p = PostBuilder.from_mdfile(mdfile)
p.kind = "notes"
p.save()
# delete the old files
container = mdfile.parent
... | conditional_block | |
twitter.py | , stype):
with mdfile.open(encoding="UTF-8") as f:
try:
post = frontmatter.load(f)
except:
print("Error parsing file")
return
if post.get('syndicated') == None:
post['syndicated'] = []
else:
for s in post['syndicated']:
... | def process_tweet(d1):
orig_tweet_url = "https://twitter.com/%s/statuses/%s/" % (TWITTER_USERNAME, d1['id_str'])
if orig_tweet_url in urlmap:
og = urlmap.get(orig_tweet_url)
if og['source_path'].startswith('post\\') or og['source_path'].startswith('photos\\'):
# no need to process ... | print(d1["full_text"])
return True
return False
| random_line_split |
twitter.py | , stype):
with mdfile.open(encoding="UTF-8") as f:
try:
post = frontmatter.load(f)
except:
print("Error parsing file")
return
if post.get('syndicated') == None:
post['syndicated'] = []
else:
for s in post['syndicated']:
... |
# also process raw urls
raw_urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', d1["full_text"])
for raw_url in raw_urls:
if process_syn_url(d1, raw_url, raw_url):
return True
break
... | orig_tweet_url = "https://twitter.com/%s/statuses/%s/" % (TWITTER_USERNAME, d1['id_str'])
if orig_tweet_url in urlmap:
og = urlmap.get(orig_tweet_url)
if og['source_path'].startswith('post\\') or og['source_path'].startswith('photos\\'):
# no need to process further any tweets that are ... | identifier_body |
twitter.py | s/statuses/%s/" % (TWITTER_USERNAME, d1['id_str'])
url, no_errors = resolver.get_final_url(url)
if not no_errors:
print(d1["full_text"])
url = url.replace("www.instagram.com", "instagram.com")
url = url.replace("/roytang0400", "")
url = urldefrag(url)[0]
if url.find("instagram.com") >=... | cleanup_videos | identifier_name | |
lstm-english-french-word.py | import re
import collections
from sklearn.model_selection import train_test_split
import numpy as np
import tensorflow as tf
import time
from nltk.translate.bleu_score import sentence_bleu
from nltk.tokenize import RegexpTokenizer, word_tokenize
from keras.utils.np_utils import to_categorical
from keras import models
... | import os | random_line_split | |
lstm-english-french-word.py | , output_text = line.split('\t')
input_texts.append(input_text)
output_texts.append('{'+output_text+'}') # { denotes the start of sentence, } denotes the end of sentence
except ValueError:
print(line)
input_texts = input_texts[:SAMPLE]
output_texts = output_texts[:SAMPLE]
# Preprocess
def remove_b... | (num_list):
text = [output_index_word_dict[num] for num in num_list]
return ' '.join(text)
def pad_num_list(num_list, size):
return num_list + [0] * (size - len(num_list))
def input_text_to_x(input_text):
num_list = input_text_to_num(input_text)
return pad_num_list(num_list, input_max_size)
def o... | output_num_to_text | identifier_name |
lstm-english-french-word.py | , output_text = line.split('\t')
input_texts.append(input_text)
output_texts.append('{'+output_text+'}') # { denotes the start of sentence, } denotes the end of sentence
except ValueError:
print(line)
input_texts = input_texts[:SAMPLE]
output_texts = output_texts[:SAMPLE]
# Preprocess
def remove_b... |
# Tokenize input and output
input_text_list = [split_input_texts(input_text) for input_text in input_texts]
output_text_list = [split_output_texts(output_text) for output_text in output_texts]
# Count unique number of English words
input_text_flat_list = []
for input_text in input_text_list:
input_text_flat_list... | return [word.lower() for word in word_tokenize(text, language='french')] | identifier_body |
lstm-english-french-word.py |
except ValueError:
print(line)
input_texts = input_texts[:SAMPLE]
output_texts = output_texts[:SAMPLE]
# Preprocess
def remove_blank(word_list):
return [word for word in word_list if word.strip()]
def is_curly_bracket(string):
return string == '{' or string == '}'
def remove_blank_curly_bracket(word_li... | input_text, output_text = line.split('\t')
input_texts.append(input_text)
output_texts.append('{'+output_text+'}') # { denotes the start of sentence, } denotes the end of sentence | conditional_block | |
pypro.py | .subplot(212)
plt.pie(values, labels=parameters, colors=cols , startangle=90, shadow=True, explode=(0, 0, 0.1, 0), autopct='%1.1f%%') #(largest slice is popped out)
plt.title('Income Adequacy of females as percentages in the sample population')
plt.show() #graphs in same window depict the differences in income adequ... | print('let us see how much trust females have on the society as a score out of 10')
print(females)
print('let us see how much trust youngsters have on society as a score out of 10')
print(age_group_18_24)
print('let us see how much trust middle-aged people have on society as a score out of 10')
print(age_group_35_... | Europeans = pd.DataFrame({'People':[6.8], 'Health System':[7.1], 'Parliament':[6], 'Police':[8], 'Media':[4.5]})
#created dataframes using pandas to show how people from different catagories trusted the society
print("let us see how much trust males have on the society as a score out of 10")
print(males)
| random_line_split |
backup.py | ,0,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0],[0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,0],[0,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0],[0,1,0,1,1,1,1,1,1,0,1,1,1,0,1,1,1,0,1,0],[0,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0],[0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],[0,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0... | newcenter = (newx, int(newy))
# read the reference map for animation
map_ref = cv2.imread('/home/sunyue/catkin_ws/src/tracking/map.png')
cv2.circle(map_ref,newcenter,radius,(0,0,255),-5)
# SECOND transfer the real location to the 20x20 grid
gridx = newcenter[0]/20+1
gridy = newcenter[1]/20+1
# A*... | newy = 0.955*(center[1] - checky) | random_line_split |
backup.py | 1]
east = [current[0]+1,current[1]]
west = [current[0]-1,current[1]]
#print current
# calculate the heuristic
n_heuristic = math.sqrt(pow(north[0]-goal[0],2)+pow(north[1]-goal[1],2))
s_heuristic = math.sqrt(pow(south[0]-goal[0],2)+pow(south[1]-goal[1],2))
e_heuristic = math.sqrt(pow(east[0]-goal[... | ic = labyrinth_solver()
rospy.init_node('labyrinth_solver', anonymous=True)
try:
rospy.spin()
except KeyboardInterrupt:
print "Shutting down"
cv2.destroyAllWindows() | identifier_body | |
backup.py | while check!=0:
# generate the potential candidate
north = [current[0],current[1]-1]
south = [current[0],current[1]+1]
east = [current[0]+1,current[1]]
west = [current[0]-1,current[1]]
#print current
# calculate the heuristic
n_heuristic = math.sqrt(pow(north[0]-goal[0],2)+pow(north[1]-goal[... | main | identifier_name | |
backup.py | 0,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0],[0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,0],[0,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0],[0,1,0,1,1,1,1,1,1,0,1,1,1,0,1,1,1,0,1,0],[0,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0],[0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],[0,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,... |
path = np.array([current])
backup = np.array([[0,0,0,0]])
while check!=0:
# generate the potential candidate
north = [current[0],current[1]-1]
south = [current[0],current[1]+1]
east = [current[0]+1,current[1]]
west = [current[0]-1,current[1]]
#print current
# calculate the heuristic
n... | check = 100 | conditional_block |
utils_test.go | 1"
)
// -----------------------------------------------------------------------------
// Testing Timeouts
// -----------------------------------------------------------------------------
const (
// waitTick is the default timeout tick interval for checking on ingress resources.
waitTick = time.Second * 1
// ingre... |
return false
}
// -----------------------------------------------------------------------------
// Test.MAIN Utility Functions
// -----------------------------------------------------------------------------
// exitOnErrWithCode is a helper function meant | {
// once the route is torn down and returning 404's, ensure that we got the expected response body back from Kong
// Expected: {"message":"no Route matched with those values"}
b := new(bytes.Buffer)
_, err := b.ReadFrom(resp.Body)
require.NoError(t, err)
body := struct {
Message string `json:"message"`
... | conditional_block |
utils_test.go | ingressWait is the default amount of time to wait for any particular ingress resource to be provisioned.
ingressWait = time.Minute * 3
// httpcTimeout is the default client timeout for HTTP clients used in tests.
httpcTimeout = time.Second * 3
// environmentCleanupTimeout is the amount of time that will be given... | exitOnErrWithCode | identifier_name | |
utils_test.go | /v1"
)
// -----------------------------------------------------------------------------
// Testing Timeouts
// -----------------------------------------------------------------------------
const (
// waitTick is the default timeout tick interval for checking on ingress resources.
waitTick = time.Second * 1
// ing... | }
// -----------------------------------------------------------------------------
// Testing Utility Functions - HTTP Requests
// -----------------------------------------------------------------------------
// expect404WithNoRoute is used to check whether a given http response is (specifically) a Kong 404.
func exp... | }
return testCasesForFile, nil | random_line_split |
utils_test.go | manlabs/httpbin
httpBinImage = "kennethreitz/httpbin"
// ingressClass indicates the ingress class name which the tests will use for supported object reconciliation
ingressClass = "kongtests"
// elsewhere is the name of an alternative namespace
elsewhere = "elsewhere"
// controllerNamespace is the Kubernetes na... | {
if err == nil {
return
}
exitOnErrWithCode(err, ExitCodeEnvSetupFailed)
} | identifier_body | |
20.rs | : &Tile) -> bool {
assert!(self.map[pos].is_none());
let x = pos % self.dim;
let y = pos / self.dim;
if y > 0 && self.bottom_border(self.coord(x, y - 1)).map(|border| border !=
tile.borders.0).unwrap_or(false) {
... | println!("rouff with monsters {}, {} total", initial_roughness, monsters.len()); | random_line_split | |
20.rs | fn accepts(&self, pos: usize, tile: &Tile) -> bool | true
}
}
fn flipbits(mut bits: u16) -> u16 {
// careful, just the lowest 10 bits, not 16
// 0123456789
// 9876543210
let mut out = 0;
for _ in 0..(IMAGEDIM + 2) {
out <<= 1;
out |= bits & 1;
bits >>= 1;
}
out
}
// counting from the right, MSB is top
fn ... | {
assert!(self.map[pos].is_none());
let x = pos % self.dim;
let y = pos / self.dim;
if y > 0 && self.bottom_border(self.coord(x, y - 1)).map(|border| border !=
tile.borders.0).unwrap_or(false) {
return false;
... | identifier_body |
20.rs | fn | (&self, pos: usize, tile: &Tile) -> bool {
assert!(self.map[pos].is_none());
let x = pos % self.dim;
let y = pos / self.dim;
if y > 0 && self.bottom_border(self.coord(x, y - 1)).map(|border| border !=
tile.borders.0).unwrap... | accepts | identifier_name |
snapshot_cmd.rs | //! Snapshot and restoration commands.
//use std::time::Duration;
//use std::path::{Path, PathBuf};
//use std::sync::Arc;
//use client_traits::SnapshotClient;
//use hash::keccak;
//use snapshot::{SnapshotConfiguration, SnapshotService as SS};
//use snapshot::io::{SnapshotReader, PackedReader, PackedWriter};
//use sna... | // true,
// self.max_round_blocks_to_import,
// );
//
// client_config.snapshot = self.snapshot_conf;
//
// let restoration_db_handler = db::restoration_db_handler(&client_path, &client_config);
// let client_db = restoration_db_handler.open(&client_path)
// .map_err(|e| format!("Failed to open database {:?}"... | random_line_split | |
snapshot_cmd.rs | //! Snapshot and restoration commands.
//use std::time::Duration;
//use std::path::{Path, PathBuf};
//use std::sync::Arc;
//use client_traits::SnapshotClient;
//use hash::keccak;
//use snapshot::{SnapshotConfiguration, SnapshotService as SS};
//use snapshot::io::{SnapshotReader, PackedReader, PackedWriter};
//use sna... | {
pub cache_config: CacheConfig,
pub dirs: Directories,
pub spec: SpecType,
pub pruning: Pruning,
pub pruning_history: u64,
pub pruning_memory: usize,
pub tracing: Switch,
pub fat_db: Switch,
// pub compaction: DatabaseCompactionProfile,
pub file_path: Option<String>,
pub kind: Kind,
pub block_at: BlockId,
... | SnapshotCommand | identifier_name |
main.py |
GAMMA = 0.1 # Multiplicative factor for learning rate step-down
LOG_FREQUENCY = 5
# ----------------------------------
# Hyperparameters for grid search
BATCH_SIZE = 256 # Higher batch sizes allows for larger learning rates. An empirical heuristic suggests that, when changing
# the... |
else :
target_dataloader = test_dataloader # art_dataloader
### TRAIN
current_step = 0
accuracies_train = []
accuracies_validation = []
loss_class_list = []
loss_target_list = []
loss_source_list = []
# Start iterating over the epochs
for epoch in range(NUM_EPOCHS):
net.train(True)
print(f"--- Epoch {epoc... | target_dataloader = sketch_dataloader | conditional_block |
main.py | 1,
# 'giraffe': 2,
# 'guitar': 3,
# 'horse': 4,
# 'house': 5,
# 'person': 6}
# dimension of an image 3x227x227
# torch.Size([3, 227, 227])
# plot images distribution
plotImageDistribution(photo_dataset.targets, art_dataset.targets, cartoon_dataset.targets, sketch_dataset.targets, DATASETS_NAMES, CLASSES_NAMES, s... |
# Update Corrects
running_corrects += torch.sum(preds == labels.data).data.item()
| random_line_split | |
evaluate_offline.py | self.Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
try:
self.model = Darknet(model_def).to(self.device)
self.model.apply(weights_init_normal)
except ... | cv2.putText(img, label, p1, cv2.FONT_HERSHEY_SIMPLEX, 2.0,
self.class_colors[int(detect[-1])], 2)
return img
def add_layer2(self, img, detections, in_dim):
'''
直接在网络输入图片上叠加目标识别和分类效果
'''
img = img.cpu().squeeze(0).numpy().transp... | 输出图片大小
'''
h,w = img.shape[:2]
#print(h,w)
detections = detections[0].numpy()
#print(detections.shape)
diff_dim = int(np.abs(h - w)/2)
scaler = (h / in_dim) if h>w else (w / in_dim)
#print('scaler is: ',scaler)
#print(detections)
for i in r... | identifier_body |
evaluate_offline.py | etect[0]), int(detect[1]))
p2 = (int(detect[2]), int(detect[3]))
cv2.rectangle(img, p1, p2, dict_colors_of_class[int(detect[-1])],2)
cv2.putText(img, label, p1, cv2.FONT_HERSHEY_SIMPLEX, 1.0,
dict_colors_of_class[int(detect[-1])])
... |
yolodetect = YoloDetect(model_def=path_model_def, | random_line_split | |
evaluate_offline.py | etect[-1])],2)
cv2.putText(img, label, p1, cv2.FONT_HERSHEY_SIMPLEX, 1.0,
dict_colors_of_class[int(detect[-1])])
return img
def detect(self,frame):
'''
基础识别功能函数,输入frame,输出识别结果
'''
#print(f"detect.py,detect: {frame.shape}")
... | conditional_block | ||
evaluate_offline.py | a_config,
file_pretrained_weights,
path_detection_results,
img_size=416,
):
self.flag_show = False
self.frame = None
self.detections = [None]
#
data_config = parse_data_config... | dat | identifier_name | |
PMP.py | 224), torchvision.transforms.ToTensor()])),
# transform=transforms.Compose([
# transforms.Resize(224), # resnet默认图片输入大小224*224
# transforms.ToTensor(),
# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
# ])),
batch_size=args.batch_size, shuffle=True, **kwargs)
test_loader = t... | cuda:1
s_prev = self.seq2(s_prev)
ret.append(self.fc(s_prev.view(s_prev.size(0), -1)))
# B. s_next runs on cuda:0, which can run concurrently with A
s_prev = self.seq1(s_next).to('cuda:1')
s_prev = self.seq2(s_prev)
ret.append(self.fc(s_prev.view(s_prev.... | uns on | identifier_name |
PMP.py | , 1, 2), nn.ReLU(),
nn.MaxPool2d(2, 2))
self.conv2 = nn.Sequential(nn.Conv2d(6, 16, 5), nn.ReLU(),
nn.MaxPool2d(2, 2))
self.fc1 = nn.Sequential(nn.Linear(16 * 5 * 5, 120),
nn.BatchNorm1d(120), nn.ReL... | batch_size))
else: | random_line_split | |
PMP.py | 224), torchvision.transforms.ToTensor()])),
# transform=transforms.Compose([
# transforms.Resize(224), # resnet默认图片输入大小224*224
# transforms.ToTensor(),
# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
# ])),
batch_size=args.batch_size, shuffle=True, **kwargs)
test_loader = t... | /runs/PMP')
data_iter = iter(train_loader)
images, labels = data_iter.next()
images = images.cuda()
writer.add_graph(model, images)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
train_acc_i = []
train_acc_list = []
a = []
ac_list = []
... | s_prev = self.seq2(s_prev)
ret.append(self.fc(s_prev.view(s_prev.size(0), -1)))
return torch.cat(ret)
model = PipelineParallelResNet50()
if not args.no_tensorboard:
writer = SummaryWriter('. | conditional_block |
PMP.py | 224), torchvision.transforms.ToTensor()])),
# transform=transforms.Compose([
# transforms.Resize(224), # resnet默认图片输入大小224*224
# transforms.ToTensor(),
# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
# ])),
batch_size=args.batch_size, shuffle=True, **kwargs)
test_loader = t... | . s_prev runs on cuda:1
s_prev = self.seq2(s_prev)
ret.append(self.fc(s_prev.view(s_prev.size(0), -1)))
# B. s_next runs on cuda:0, which can run concurrently with A
s_prev = self.seq1(s_next).to('cuda:1')
s_prev = self.seq2(s_prev)
ret.append(self.fc(s_... | rev = self.seq1(s_next).to('cuda:1')
ret = []
for s_next in splits:
# A | identifier_body |
box.py | .un_set_glues)
@property
def natural_length(self):
# The natural width, x, of the box contents is determined by adding up
# the widths of the boxes and kerns inside, together with the natural
# widths of all the glue inside.
# I'm assuming this also applies to VBoxes, but adding... | return max(self.widths) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.