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 |
|---|---|---|---|---|
info.py | " + print_variants.__doc__),
("--no-versions", "do not " + print_versions.__doc__),
("--phases", print_phases.__doc__),
("--tags", print_tags.__doc__),
("--tests", print_tests.__doc__),
("--virtuals", print_virtuals.__doc__),
]
for opt, help_comment in options:
s... | return s
@property
def lines(self):
if not self.variants:
yield " None"
else:
yield " " + self.fmt % self.headers
underline = tuple([w * "=" for w in self.column_widths])
yield " " + self.fmt % underline
yield ""
... | random_line_split | |
log_file.rs | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CRL Sweeper File: {}", self.file_path.as_path().display())
}
}
#[cfg(target_os="linux")]
fn open_synchronous_fd(path: &CString) -> libc::c_int {
const O_DIRECT: libc::c_int = 0x4000;
const O_DSYNC: libc::c_int = 4000;
unsafe {
... | fmt | identifier_name | |
log_file.rs |
impl Drop for LogFile {
fn drop(&mut self) {
unsafe {
libc::close(self.fd);
}
}
}
impl fmt::Display for LogFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CRL Sweeper File: {}", self.file_path.as_path().display())
}
}
#[cfg(target_os="li... | fd: libc::c_int,
pub len: usize,
pub max_size: usize,
pub file_uuid: uuid::Uuid
} | random_line_split | |
log_file.rs | if size < (16 + STATIC_ENTRY_SIZE as usize) {
// Initialize
seek(fd, 0, libc::SEEK_SET)?;
unsafe {
libc::ftruncate(fd, 0);
}
let u = uuid::Uuid::new_v4();
write_bytes(fd, &u.as_bytes()[..])?;
}
let file_uu... | {
break; // Cannot have an offset of 0 (first 16 bytes of the file are the UUID)
} | conditional_block | |
log_file.rs | }
fd
}
}
#[cfg(not(any(target_os="linux", target_os="macos")))]
fn open_synchronous_fd(path: &CString) -> libc::c_int {
unsafe {
libc::open(path.as_ptr(), libc::O_CREAT | libc::O_RDWR)
}
}
impl LogFile {
fn new(
directory: &Path,
file_id: FileId,
max_file_siz... |
fn seek(fd: libc::c_int, offset: i64, whence: libc::c_int) -> Result<usize> {
unsafe {
let sz = libc::lseek(fd, offset, whence);
if sz < 0 {
Err(Error::last_os_error())
} else {
Ok(sz as usize)
}
}
}
fn find_last_valid_entry(
fd: libc::c_int,
f... | {
let p: *const u8 = &s[0];
unsafe {
if libc::write(fd, p as *const libc::c_void, s.len()) < 0 {
return Err(Error::last_os_error());
}
libc::fsync(fd);
}
Ok(())
} | identifier_body |
sketch.js | p = new Particle(random() * width, random() * height);
p.px += random() * 2 - 1;
p.py += random() * 2 - 1;
particles.push(p);
}
constrainPoints();
}
function draw() {
background(125);
updateParticles();
for (let i = 0; i < STEPS; i++) {
updateConstraints();
for (let body1 of bodies) {
body1.c... | () {
let constToBeRemoved = [];
for (let i = 0; i < constraints.length; i++) {
let c = constraints[i];
if (!c.p1 || !c.p2)
continue;
let dx = c.p1.x - c.p2.x;
let dy = c.p1.y - c.p2.y;
if (dx == 0 && dy == 0) {
dx += Math.random() * 0.1;
dy += Math.random() * 0.1;
}
// let d = Math.sqrt((... | updateConstraints | identifier_name |
sketch.js | Points();
}
function draw() {
background(125);
updateParticles();
for (let i = 0; i < STEPS; i++) {
updateConstraints();
for (let body1 of bodies) {
body1.calculateBBox();
for (let body2 of bodies) {
if (body1 === body2)
continue;
if (physics.detectCollision(body1, body2))
physic... | {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.invmass = 0.3;
} | identifier_body | |
sketch.js | random() * 2 - 1;
p.py += random() * 2 - 1;
particles.push(p);
}
constrainPoints();
}
function draw() {
background(125);
updateParticles();
for (let i = 0; i < STEPS; i++) {
updateConstraints();
for (let body1 of bodies) {
body1.calculateBBox();
for (let body2 of bodies) {
if (body1 ===... | function Particle(x, y) { | random_line_split | |
sketch.js | = new Particle(random() * width, random() * height);
p.px += random() * 2 - 1;
p.py += random() * 2 - 1;
particles.push(p);
}
constrainPoints();
}
function draw() {
background(125);
updateParticles();
for (let i = 0; i < STEPS; i++) {
updateConstraints();
for (let body1 of bodies) {
body1.cal... |
if (showDebugText) {
fill(255);
text('Particles: ' + particles.length + ' | Constraints: ' + constraints.length, 12, 12);
text('Gravity: ' + gravity.x + ', ' + gravity.y, 12, 24);
text('FPS: ' + frameRate(), 12, 38);
text('Delta: ' + deltaTime, 12, 50);
text('Dragging: ' + pointDragging, 12, 64);
}
}
f... | {
fill(255, 255, 0);
for (let i = 0; i < particles.length; i++) {
rect(particles[i].x - SIZE_D2, particles[i].y - SIZE_D2, SIZE, SIZE);
}
} | conditional_block |
annualSearchPage.js | 服务器的参数为:pageSize,pageNumber
queryParams:queryParams,
singleSelect: false,
pageSize: basePage.pageSize,
pageList: basePage.pageList,
search: false, //不显示 搜索框
showColumns: false, //不显示下拉框(选择显示的列)
sidePagination: "server", //服务端请求
clickToSelect: true, //是否启用点击选中行
co... | $("#searchFileName").val(obj.fileName);
$("#searchYearId").val(obj.year);
$("#searchResume").val(obj.resume);
$("#searchRemarks").val(obj.remarks);
var afterName = '';
if(obj.fileUrl !='' && obj.fileUrl != nu... | identifier_body | |
annualSearchPage.js | }
}
$.commonReq({
url : rootPath + "/annual/selectById.do",
async : true,
data : {"id":id},
success : function(obj) {
debugger;
if(obj.data.status==1){
bootbox.alert('该文件已提交审核,无法对其操作!');
return;
}
$.commonReq({
url : rootPath + "/annual/deleteRegs.do",
asy... | return "";
} | random_line_split | |
annualSearchPage.js | box.alert('只能选中一行');
return;
}
}
$.commonReq({
url : rootPath + "/annual/selectById.do",
async : true,
data : {"id":id},
success : function(obj) {
debugger;
if(obj.data.status==1){
bootbox.alert('该文件已提交审核,无法对其操作!');
return;
}
$.commonReq({
url : rootPath ... | re | identifier_name | |
annualSearchPage.js | striped: true, //是否显示行间隔色
cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
pagination: true,
queryParamsType:'', //默认值为 'limit' ,在默认情况下 传给服务端的参数为:offset,limit,sort
// 设置为 '' 在这种情况下传给服务器的参数为:pageSize,pageNumber
queryParams:queryParams,
singleSel... | //服务器响应失败时的处理函数
bootbox.alert('服务器请求失败!');
}
});
}
}
function searchRegulations(id){
debugger;
var localhostPath = getRootPath1();
var rootPath = getRootPath();
$("#formUpdatesInfo").find("input").val("");
$("#submitBtn").show();
$('... | bootbox.alert("修改成功!");
},
error:function(xhr,status,e){
| conditional_block |
symm_icon.rs | 0., -12., 1., 0., 3., 0.7], [-1.86, 2., 0., 1., 0.1, 4., 1.2],
[-2.34, 2., 0.2, 0.1, 0., 5., 1.2], [2.6, -2., 0., 0.5, 0., 5., 1.3],
[-2.5, 5., -1.9, 1., 0.188, 5., 1.], [2.409, -2.5, 0., 0.9, 0., 23., 1.2],
[2.409, -2.5, -0.2, 0.81, 0., 24., 1.2], [-2.05, 3., -16.79, 1., 0., 9., 1.],
[-2.32, ... |
fn make_color(r : u32, g : u32, b : u32) -> u32 { (b << 16) | (g << 8) | r | 0xff00_0000 }
fn make_colora(a : u32, r : u32, g : u32, b : u32) -> u32 { (a << 24) | (b << 16) | (g << 8) | r }
fn get_rainbow(x : u32, y : u32) -> u32 {
match x {
0 => Self::make_color(0, y, 255),
... | {
self.lambda = lambda;
self.alpha = alpha;
self.beta = beta;
self.gamma = gamma;
self.omega = omega;
self.symmetry = if symmetry < 1. { 1 } else { symmetry as u32 };
self.scale = if scale == 0. {1.} else { scale };
self.reset();
} | identifier_body |
symm_icon.rs | 10., -12., 1., 0., 3., 0.7], [-1.86, 2., 0., 1., 0.1, 4., 1.2],
[-2.34, 2., 0.2, 0.1, 0., 5., 1.2], [2.6, -2., 0., 0.5, 0., 5., 1.3],
[-2.5, 5., -1.9, 1., 0.188, 5., 1.], [2.409, -2.5, 0., 0.9, 0., 23., 1.2],
[2.409, -2.5, -0.2, 0.81, 0., 24., 1.2], [-2.05, 3., -16.79, 1., 0., 9., 1.],
[-2.32,... | self.iter = 0;
self.color_list = vec![];
self.reset();
}
pub fn set_preset(&mut self, i : usize) {
let p = PRESETS[i % PRESETS.len()];
self.lambda = p[0];
self.alpha = p[1];
self.beta = p[2];
self.gamma = p[3];
self.omega = p[4];
self.symmetry = p[5] as u32;
... | self.image = Array2D::filled_with(0_u32, w, h);
self.icon = Array2D::filled_with(0_u32, w, h); | random_line_split |
symm_icon.rs | f32, alpha: f32, beta : f32, gamma : f32, omega : f32, symmetry : f32, scale : f32) {
self.lambda = lambda;
self.alpha = alpha;
self.beta = beta;
self.gamma = gamma;
self.omega = omega;
self.symmetry = if symmetry < 1. { 1 } else { symmetry as u32 };
self.scale ... | {
self.color_list[(col * self.speed) as usize]
} | conditional_block | |
symm_icon.rs | 0.0,
apcy : 0.0,
rad : 0.0,
color_list : vec![],
icon : Array2D::filled_with(0_u32, w, h),
image : Array2D::filled_with(0_u32, w, h),
x : 0.0,
y : 0.0,
k : 0,
};
s.set_preset(0);
s
}
pub fn set_size(&mut self, w : usize, h : usize) {
self.w = w;... | reset | identifier_name | |
component.rs | Function>,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct ComponentArtifacts {
info: CompiledComponentInfo,
types: ComponentTypes,
static_modules: PrimaryMap<StaticModuleIndex, CompiledModuleInfo>,
}
impl Component {
/// Compiles a new WebAssembly component from the in-memory wasm image
///... | (engine: &Engine, path: impl AsRef<Path>) -> Result<Component> {
let code = engine.load_code_file(path.as_ref(), ObjectKind::Component)?;
Component::from_parts(engine, code, None)
}
/// Performs the compilation phase for a component, translating and
/// validating the provided wasm binary t... | deserialize_file | identifier_name |
component.rs | Function>,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct ComponentArtifacts {
info: CompiledComponentInfo,
types: ComponentTypes,
static_modules: PrimaryMap<StaticModuleIndex, CompiledModuleInfo>,
}
impl Component {
/// Compiles a new WebAssembly component from the in-memory wasm image
///... |
/// Compiles a new WebAssembly component from the in-memory wasm image
/// provided.
//
// FIXME: need to write more docs here.
#[cfg(any(feature = "cranelift", feature = "winch"))]
#[cfg_attr(nightlydoc, doc(cfg(any(feature = "cranelift", feature = "winch"))))]
pub fn from_binary(engine: ... | {
match Self::new(
engine,
&fs::read(&file).with_context(|| "failed to read input file")?,
) {
Ok(m) => Ok(m),
Err(e) => {
cfg_if::cfg_if! {
if #[cfg(feature = "wat")] {
let mut e = e.downcast::<w... | identifier_body |
component.rs | /// Compiles a new WebAssembly component from a wasm file on disk pointed to
/// by `file`.
//
// FIXME: need to write more docs here.
#[cfg(any(feature = "cranelift", feature = "winch"))]
#[cfg_attr(nightlydoc, doc(cfg(any(feature = "cranelift", feature = "winch"))))]
pub fn from_file(engin... | pub fn serialize(&self) -> Result<Vec<u8>> {
Ok(self.code_object().code_memory().mmap().to_vec()) | random_line_split | |
utils.ts | Id}" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 10px; right: 10px;z-index:1051;opacity:1">
<div class="toast-header">
<img src="/img/logo.png" class="rounded mr-2" style="height: 16px">
<strong class="mr-auto">${title}</strong>
<button type="button" class="ml-2 mb-1 close n... | objs.forEach(obj => {
if (obj) {
Object.keys(obj).forEach(key => {
const val = obj[key]
if (this.isPlainObject(val)) {
// 递归
if (this.isPlainObject(result[key])) {
result[key] = this.deepMerge(result[key], val)
} else {
... | })
},
deepMerge (...objs) {
const result = Object.create(null) | random_line_split |
utils.ts | torage.setItem('jwt', jwt)
},
getJwt () {
return window.sessionStorage.getItem('jwt')
},
saveDesign (api, design, cb: any = null) {
const jwt = this.getJwt()
if (!design.pages || design.pages.length === 0) return
// console.log(design)
const files = {}
let fileCount = 0
const promise... | essionS | identifier_name | |
utils.ts | }" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 10px; right: 10px;z-index:1051;opacity:1">
<div class="toast-header">
<img src="/img/logo.png" class="rounded mr-2" style="height: 16px">
<strong class="mr-auto">${title}</strong>
<button type="button" class="ml-2 mb-1 close no-... | },
deepMerge (...objs) {
const result = Obj
ect.create(null)
objs.forEach(obj => {
if (obj) {
Object.keys(obj).forEach(key => {
const val = obj[key]
if (this.isPlainObject(val)) {
// 递归
if (this.isPlainObject(result[key])) {
result[key]... | r (const key in data) {
fd.append(key, data[key])
}
for (const file in files) {
fd.append(file, files[file])
}
$.ajax({
headers: {
token: this.getJwt()
},
method: 'post',
processData: false,
contentType: false,
url: url,
data: fd,
cross... | identifier_body |
utils.ts | }" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 10px; right: 10px;z-index:1051;opacity:1">
<div class="toast-header">
<img src="/img/logo.png" class="rounded mr-2" style="height: 16px">
<strong class="mr-auto">${title}</strong>
<button type="button" class="ml-2 mb-1 close no-... | dy').append(`
<div class="modal" tabindex="-1" role="dialog" id="${dialogId}">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header no-border">
<h5 class="modal-title ${title ? '' : 'd-none'}">${title}</h5>
... | gId}`).modal('hide')
$(`#${dialogId}`).remove()
}
}
window[dialogId + 'okCb'] = okCb
$('bo | conditional_block |
kerdenSOM.py | stackdata['path']['path']
uppath = os.path.abspath(os.path.join(path, ".."))
self.params['rundir'] = os.path.join(uppath, self.params['runname'])
#======================
def insertKerDenSOM(self, binned=None):
### Preliminary data
projectid = apProject.getProjectIdFromAlignStackId(self.params['alignstackid']... | emancmd = ("proc2d %s %s list=%s average"%
| ### create png
shutil.copy("crap.png", listname+".png")
else:
### average particles | random_line_split |
kerdenSOM.py | data['path']['path']
uppath = os.path.abspath(os.path.join(path, ".."))
self.params['rundir'] = os.path.join(uppath, self.params['runname'])
#======================
def insertKerDenSOM(self, binned=None):
### Preliminary data
projectid = apProject.getProjectIdFromAlignStackId(self.params['alignstackid'])
a... |
f.close()
if not partlist:
return []
partlist.sort()
return partlist
#======================
def runKerdenSOM(self, indata):
"""
From http://xmipp.cnb.csic.es/twiki/bin/view/Xmipp/KerDenSOM
KerDenSOM stands for "Kernel Probability Density Estimator Self-Organizing Map".
It maps a set of high dim... | partnum = int(sline)+1
partlist.append(partnum) | conditional_block |
kerdenSOM.py |
#======================
def insertKerDenSOM(self, binned=None):
### Preliminary data
projectid = apProject.getProjectIdFromAlignStackId(self.params['alignstackid'])
alignstackdata = appiondata.ApAlignStackData.direct_query(self.params['alignstackid'])
numclass = self.params['xdim']*self.params['ydim']
pat... | self.alignstackdata = appiondata.ApAlignStackData.direct_query(self.params['alignstackid'])
path = self.alignstackdata['path']['path']
uppath = os.path.abspath(os.path.join(path, ".."))
self.params['rundir'] = os.path.join(uppath, self.params['runname']) | identifier_body | |
kerdenSOM.py | data['path']['path']
uppath = os.path.abspath(os.path.join(path, ".."))
self.params['rundir'] = os.path.join(uppath, self.params['runname'])
#======================
def insertKerDenSOM(self, binned=None):
### Preliminary data
projectid = apProject.getProjectIdFromAlignStackId(self.params['alignstackid'])
a... | (self):
self.cluster_resolution = []
apDisplay.printMsg("Converting files")
### create crappy files
emancmd = ( "proc2d "+self.instack+" crap.mrc first=0 last=0 mask=1" )
apEMAN.executeEmanCmd(emancmd, showcmd=False, verbose=False)
emancmd = ( "proc2d crap.mrc crap.png" )
apEMAN.executeEmanCmd(emancmd, s... | createMontageByEMAN | identifier_name |
tarjetas.js | andeTarjeta').css("width"));
*/
}
catch (e){
console.log(e.message);
}
if (tarjetaActual.favorita == 1) {
$('#btnCambiarTarjetaFavorita').addClass("ui-btn-favorito");
/* TODO
actualizar la tarjeta en la base de datos
*/
}
else {
$('#btnCambiarTarjetaFavorita').removeClass("ui-btn-favorito"... | ror: "+t,'',res_titulo_servidor_no_disponible,res_Aceptar);
}
estadoServidor=false;
}
}
}
});
}
/*
* Obtie | conditional_block | |
tarjetas.js | break;
}
}
else {
ancho = anchoTablet;
}
var columna =1;
$.each(listaTarjetas, function(i, item) {
console.log("Comprobamos esta tarjeta para añadirla a la categoría ("+categoria.id+"): "+item.id+" con la categoria: "+item.categoria);
if ( ( (favoritas) && (item.favorita == 1) ) || ( (!favorit... | lListaTarjetas').html("");
var texto = "";
var letra = "";
var contador = 0;
var listaImagenesACargar = [];
if (favoritas)
$('#h1NombreCategoria').html(res_Favoritos)
mostrarFavoritas = favoritas;
if (activarPhoneGap){
switch(tipoDispositivo){
case "iPhone3":
ancho = anchoiPhone3;
break;
c... | identifier_body | |
tarjetas.js | }
}
else {
ancho = anchoTablet;
}
var columna =1;
$.each(listaTarjetas, function(i, item) {
console.log("Comprobamos esta tarjeta para añadirla a la categoría ("+categoria.id+"): "+item.id+" con la categoria: "+item.categoria);
if ( ( (favoritas) && (item.favorita == 1) ) || ( (!favoritas) && (ite... | case "tablet":
ancho = anchoTablet;
break; | random_line_split | |
tarjetas.js | a, favoritas){
$('#lblListaTarjetas').html("");
var texto = "";
var letra = "";
var contador = 0;
var listaImagenesACargar = [];
if (favoritas)
$('#h1NombreCategoria').html(res_Favoritos)
mostrarFavoritas = favoritas;
if (activarPhoneGap){
switch(tipoDispositivo){
case "iPhone3":
ancho = anchoiPh... | arListaTarjetas(categori | identifier_name | |
annotate.rs | Date,
};
use id3::{
frame::{
Picture,
PictureType,
},
Tag,
Timestamp,
Version,
};
use regex::{
Regex,
};
use crate::{
types::{
AlbumFull,
ClientWithToken,
SimpleError,
Track,
},
utils::{
get_with_retry,
},
whitelist::{
... | (
album_full: &AlbumFull,
client_with_token: &ClientWithToken,
) -> Result<Vec<TrackData>, SimpleError> {
let mut tracks = Vec::new();
let mut paging = album_full.tracks.clone();
while let Some(next_url) = paging.next {
tracks.append(&mut paging.items);
paging = get_with_retry(
... | get_tracks_data | identifier_name |
annotate.rs | Date,
};
use id3::{
frame::{
Picture,
PictureType,
},
Tag,
Timestamp,
Version,
};
use regex::{
Regex,
};
use crate::{
types::{
AlbumFull,
ClientWithToken,
SimpleError,
Track,
},
utils::{
get_with_retry,
},
whitelist::{
... | }
fn annotate_tags(
tags: &mut Tag,
file: &PathBuf,
track_data: TrackData,
album_image: &Vec<u8>,
) -> String {
lazy_static! {
static ref INVALID_FILE_CHRS: Regex = Regex::new(r"[^\w\s.\(\)]+").unwrap();
}
let mut new_name = format!(
"{} {}.mp3",
norm_track_numb... | tags.album().expect("error in writing tags"),
tags.artist().expect("error in writing tags"),
),
data: image.clone(),
}); | random_line_split |
annotate.rs | ,
};
use id3::{
frame::{
Picture,
PictureType,
},
Tag,
Timestamp,
Version,
};
use regex::{
Regex,
};
use crate::{
types::{
AlbumFull,
ClientWithToken,
SimpleError,
Track,
},
utils::{
get_with_retry,
},
whitelist::{
... |
if album_full.release_date_precision == "month" {
let date = NaiveDate::parse_from_str(
&album_full.release_date[..],
"%Y-%m",
)?;
year = date.year();
month = Some(date.month() as u8);
}
else if album_full.release_d... | {
let date = NaiveDate::parse_from_str(
&album_full.release_date[..],
"%Y",
)?;
year = date.year();
} | conditional_block |
annotate.rs | ,
};
use id3::{
frame::{
Picture,
PictureType,
},
Tag,
Timestamp,
Version,
};
use regex::{
Regex,
};
use crate::{
types::{
AlbumFull,
ClientWithToken,
SimpleError,
Track,
},
utils::{
get_with_retry,
},
whitelist::{
... |
fn expected_time(
file: &PathBuf,
track_data: &TrackData,
) -> bool {
let actual_duration = mp3_duration::from_path(file.as_path()).expect(
&format!("error measuring {}", file.display())[..],
);
let expected_duration = Duration::from_millis(
track_data.expected_duration_ms as u64,
... | {
if track_number < 10 {
return format!("0{}", track_number);
}
track_number.to_string()
} | identifier_body |
terminal.rs | (unused)]
use super::Color;
pub const TEXT_WHITE: Color = 251;
pub const CYAN: Color = 6;
pub const YELLOW: Color = 3;
pub const RED: Color = 1;
pub const BRIGHT_RED: Color = 9;
pub const BRIGHT_GREEN: Color = 10;
pub const LIGHT_GRAY: Color = 243;
pub const LESS_LIGHT_GRAY: Color =... | t_split_idx == 0 {
last_char_idx
} else {
last_split_idx
}
}
impl Terminal {
fn writer<W>(&self, out: W) -> TermWriter<W>
where W: Write
{
TermWriter {
terminal: self,
out
}
}
fn calculate_layout(&self) -> Vec<LineLayout> {
... | _split_idx = idx;
}
}
if las | conditional_block |
terminal.rs | text_segments: Default::default(),
error_segments: Default::default(),
terminfo
}
}
fn add_text_segment(&mut self, text: &str, fmt_args: FormatLike) {
self.text_segments.push(smallvec![TextSegment::new(text, fmt_args)]);
}
fn add_error_segment(&mut s... | Resul | identifier_name | |
terminal.rs | (unused)]
use super::Color;
pub const TEXT_WHITE: Color = 251;
pub const CYAN: Color = 6;
pub const YELLOW: Color = 3;
pub const RED: Color = 1;
pub const BRIGHT_RED: Color = 9;
pub const BRIGHT_GREEN: Color = 10;
pub const LIGHT_GRAY: Color = 243;
pub const LESS_LIGHT_GRAY: Color =... | )]
pub struct Terminal {
column_count: usize,
text_segments: SmallVec<[SmallVec<[TextSegment; 2]>; 2]>,
error_segments: Vec<(&'static str, String)>,
terminfo: Database,
}
impl TerminalPlugin for Terminal {
fn new(column_count: usize) -> Self {
let terminfo = Database::from_env().unwrap();... | rmatLike::*;
match fmt {
Text => color::TEXT_WHITE,
PrimaryText => color::JUNGLE_GREEN,
Lines => color::LIGHT_GRAY,
SoftWarning => color::ORANGE,
HardWarning => color::SIGNALING_RED,
Error => color::RED,
ExplicitOk => color::BRIGHT_GREEN,
Hidden => co... | identifier_body |
terminal.rs | (unused)]
use super::Color;
pub const TEXT_WHITE: Color = 251;
pub const CYAN: Color = 6;
pub const YELLOW: Color = 3;
pub const RED: Color = 1;
pub const BRIGHT_RED: Color = 9;
pub const BRIGHT_GREEN: Color = 10;
pub const LIGHT_GRAY: Color = 243;
pub const LESS_LIGHT_GRAY: Color =... | self.add_text_segment(text, fmt_args);
}
fn flush_to_stdout(&self, prompt_ending: &str) {
//TODO split into multiple functions
// - one for outputting text segments
// - one for outputting error segments
let layout = self.calculate_layout();
let stdout = io::st... | }
} | random_line_split |
mock.rs | Fixed,
FromGenericPair,
};
use currencies::BasicCurrencyAdapter;
use frame_support::traits::GenesisBuild;
use frame_support::weights::Weight;
use frame_support::{construct_runtime, parameter_types};
use frame_system;
use hex_literal::hex;
use permissions::Scope;
use sp_core::H256;
use sp_runtime::testing::Header;
... |
pub fn liquidity_provider_c() -> AccountId {
AccountId32::from([6u8; 32])
}
pub const DEX_A_ID: DEXId = common::DEXId::Polkaswap;
parameter_types! {
pub GetBaseAssetId: AssetId = common::XOR.into();
pub GetIncentiveAssetId: AssetId = common::PSWAP.into();
pub const PoolTokenAId: AssetId = common::As... | {
AccountId32::from([5u8; 32])
} | identifier_body |
mock.rs | AccountId = AccountId32;
pub type BlockNumber = u64;
pub type Amount = i128;
pub type AssetId = common::AssetId32<common::PredefinedAssetId>;
pub type TechAccountId = common::TechAccountId<AccountId, TechAssetId, DEXId>;
type TechAssetId = common::TechAssetId<common::PredefinedAssetId>;
type DEXId = common::DEXId;
typ... | with_accounts | identifier_name | |
mock.rs | : BlockNumber = 10;
pub const GetBurnUpdateFrequency: BlockNumber = 3;
pub const ExistentialDeposit: u128 = 0;
pub const TransferFee: u128 = 0;
pub const CreationFee: u128 = 0;
pub const TransactionByteFee: u128 = 1;
pub GetFee: Fixed = fixed_from_basis_points(30u16);
pub GetParliamentAccoun... | random_line_split | ||
list_view_items.rs | texts` is empty, or if the number of texts is greater than
/// the number of columns.
pub fn add<S: AsRef<str>>(&self,
texts: &[S], icon_index: Option<u32>) -> WinResult<u32>
{
if texts.is_empty() {
panic!("No texts passed when adding a ListView item.");
}
let mut lvi = LVITEM::default();
lvi... | (&self,
set: bool, item_indexes: &[u32]) -> WinResult<()>
{
let mut lvi = LVITEM::default();
lvi.stateMask = co::LVIS::SELECTED;
if set { lvi.state = co::LVIS::SELECTED; }
for idx in item_indexes.iter() {
self.hwnd().SendMessage(lvm::SetItemState {
index: Some(*idx),
lvitem: &lvi,
}... | set_selected | identifier_name |
list_view_items.rs | { index })?,
None => break,
};
}
Ok(())
}
/// Scrolls the list by sending an
/// [`LVM_ENSUREVISIBLE`](crate::msg::lvm::EnsureVisible) message so that an
/// item is visible in the list.
pub fn ensure_visible(&self, item_index: u32) -> WinResult<()> {
self.hwnd().SendMessage(lvm::EnsureVi... | {
| random_line_split | |
index.js | '),
document.getElementById('step-4-part-1-puzzlespot'),
document.getElementById('step-4-part-2-puzzlepiece-container'),
document.getElementById('step-4-part-2-puzzlespot')
]);
draggables.on('drag', function(el, source) {
// Hide the "drag to start" when the BEGIN puzzle piece is dragged
if (source... | () {
if (currentPageNum > 0) {
transitionToPage(currentPageNum - 1, true);
}
}
// showPage is used by transitionToPage and transitionToPageInURL
// not recommended to be called manually!
function showPage(nextPageNum, reverseAnimation = false) {
currentPageNum = nextPageNum;
const nextPageEl =... | transitionToPreviousPage | identifier_name |
index.js | '),
document.getElementById('step-4-part-1-puzzlespot'),
document.getElementById('step-4-part-2-puzzlepiece-container'),
document.getElementById('step-4-part-2-puzzlespot')
]);
draggables.on('drag', function(el, source) {
// Hide the "drag to start" when the BEGIN puzzle piece is dragged
if (source... | pageEl.id = `page-${pageElIdCounter}`;
pageElIdCounter++;
}
// The 'popstate' event is triggered when the user navigates toa new URL within the current website.
// For instance, this happens when the user presses the browser back button.
window.addEventListener('popstate', showPageInURL);
// Once website is lo... | let pageElIdCounter = 0;
for (const pageEl of pageEls) { | random_line_split |
index.js | '),
document.getElementById('step-4-part-1-puzzlespot'),
document.getElementById('step-4-part-2-puzzlepiece-container'),
document.getElementById('step-4-part-2-puzzlespot')
]);
draggables.on('drag', function(el, source) {
// Hide the "drag to start" when the BEGIN puzzle piece is dragged
if (source... | animatedEl.style.transitionDelay = `${delay}s`;
}
animatedEl.style.opacity = 1;
delay += 0.1;
}
const navEl = document.getElementsByClassName('nav-dot-container')[0];
// Hide the navigation element on the landing page and the thank you page
if (currentPageNum === 0 ... | {
currentPageNum = nextPageNum;
const nextPageEl = pageEls[nextPageNum];
nextPageEl.scrollIntoView();
let delay = 0;
const animatedEls = nextPageEl.querySelectorAll('.animate-in, .animate-out');
for (const animatedEl of animatedEls) {
const elIsAnimatingIn =
(animatedEl.cl... | identifier_body |
index.js | '),
document.getElementById('step-4-part-1-puzzlespot'),
document.getElementById('step-4-part-2-puzzlepiece-container'),
document.getElementById('step-4-part-2-puzzlespot')
]);
draggables.on('drag', function(el, source) {
// Hide the "drag to start" when the BEGIN puzzle piece is dragged
if (source... |
if (elIsAnimatingIn) {
animatedEl.style.transitionDuration = '0.2s';
animatedEl.style.transitionDelay = `${delay}s`;
}
animatedEl.style.opacity = 1;
delay += 0.1;
}
const navEl = document.getElementsByClassName('nav-dot-container')[0];
// Hide the n... | {
animatedEl.style.transitionDuration = '0s';
animatedEl.style.transitionDelay = '0s';
} | conditional_block |
lib.rs | *custom_block = MaybeUninit::new(CustomBlockOcamlRep(ops, Rc::clone(&self.0)));
block.build()
}
}
impl<T: CamlSerialize> FromOcamlRep for Custom<T> {
fn from_ocamlrep(value: Value<'_>) -> Result<Self, FromError> {
let rc = rc_from_value::<T>(value)?;
let rc = Rc::clone(rc);
... | // Safety: We trust here that CustomOperations structs containing this
// `drop_value` instance will only ever be referenced by custom blocks
// matching the layout of `CustomBlockOcamlRep`. If that's so, then this
// function should only be invoked by the OCaml runtime on a pointer to | random_line_split | |
lib.rs | for us to
// interpret `block_ptr` as a `&mut CustomBlockOcamlRep`.
let block_ptr = block_ptr as *mut MaybeUninit<CustomBlockOcamlRep<T>>;
let custom_block = unsafe { block_ptr.as_mut().unwrap() };
// Write the address of the operations struct to the first word, and the
// poin... | drop_value | identifier_name | |
lib.rs | }
/// }
/// ```
unsafe fn register();
/// Convert a value to an array of bytes.
///
/// The default implementation panics.
fn serialize(&self) -> Vec<u8> {
panic!(
"serialization not implemented for {:?}",
Self::type_identifier()
)
}
///... | {
assert_eq!(
align_of::<CustomBlockOcamlRep<u8>>(),
align_of::<Value<'_>>()
);
} | identifier_body | |
lib.rs | 0.get() - 1);
/// counter
/// }
///
/// fn counter_read(counter: Custom<Counter>) -> isize {
/// counter.0.get()
/// }
/// }
/// ```
///
/// From OCaml:
///
/// ```ocaml
/// type counter; (* abstract type *)
///
/// external counter_new : unit -> counter = "counter_new"
/// external counter_... |
let value_ptr = value.to_bits() as *const CustomBlockOcamlRep<T>;
// Safety: `value_ptr` is guaranteed to be aligned to
// `align_of::<Value>()`, and our use of `expect_block_size` guarantees
// that the pointer is valid for reads of `CUSTOM_BLOCK_SIZE_IN_WORDS *
// `size_of::<Value>()` bytes. Si... | {
return Err(FromError::UnexpectedCustomOps {
expected: ops as *const _ as usize,
actual: block[0].to_bits(),
});
} | conditional_block |
run.py | )
gc.queue_research(bc.UnitType.Worker)
gc.queue_research(bc.UnitType.Mage)
gc.queue_research(bc.UnitType.Mage)
gc.queue_research(bc.UnitType.Mage)
gc.queue_research(bc.UnitType.Healer)
gc.queue_research(bc.UnitType.Mage)
#method to move any unit
def move(unit):
#API returns any possible moves in list form
p... | ():
global safe_locations
component_num = 0
for i in range(marsHeight):
for j in range(marsWidth):
if (i, j) not in safe_locations:
temp_loc = bc.MapLocation(bc.Planet.Mars, i, j)
try:
if marsMap.is_passable_terrain_at(temp_loc):
... | find_locations_Mars | identifier_name |
run.py | )
gc.queue_research(bc.UnitType.Worker)
gc.queue_research(bc.UnitType.Mage)
gc.queue_research(bc.UnitType.Mage)
gc.queue_research(bc.UnitType.Mage)
gc.queue_research(bc.UnitType.Healer)
gc.queue_research(bc.UnitType.Mage)
#method to move any unit
def move(unit):
#API returns any possible moves in list form
p... | return
#Healer_heal finds units near the healer and attempts to heal them
def Healer_heal(unit):
global enemy_spawn, my_team, full_vision
location = unit.location
#find nearby units on team
nearby = gc.sense_nearby_units_by_team(location.map_location(), unit.attack_range(), my_team)
#if... | global num_healers, num_rangers, release_units, fight
garrison = unit.structure_garrison()
if num_rangers + num_healers > 15 or fight:
release_units = True
#If a unit is garrisoned, release them in an available spot.
if len(garrison) > 0 and release_units:
for dir in directions:
... | identifier_body |
run.py | #find nearby units on team
nearby = gc.sense_nearby_units_by_team(location.map_location(), unit.attack_range(), my_team)
#if can heal, heal
heal = False
if gc.is_heal_ready(unit.id):
lowest_health = unit
for other in nearby:
if other.health < lowest_health.health and other.... | unloadRocket(unit) | conditional_block | |
run.py | priority_healers = {
bc.UnitType.Worker : 4,
bc.UnitType.Knight : 3,
bc.UnitType.Healer : 2,
bc.UnitType.Ranger : 1,
bc.UnitType.Mage : 2
}
#a directions dictionary used to approach
approach_dir = {
(0,1) : bc.Direction.North,
(1,1) : bc.Direction.Northeast,
(1,0) : bc.Direction.East,
... | random_line_split | ||
test.rs | allow_dead_code_item);
ast::Item {
id,
ident,
attrs: attrs.into_iter()
.filter(|attr| {
!attr.check_name(... | {
attr::contains_name(&i.attrs, "rustc_test_marker")
} | identifier_body | |
test.rs | some_name;`. This needs to be
// unconditional, so that the attribute is still marked as used in
// non-test builds.
let reexport_test_harness_main =
attr::first_attr_value_str_by_name(&krate.attrs,
"reexport_test_harness_main");
// Do this here so th... | fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
self.depth += 1;
let item = noop_flat_map_item(i, self).expect_one("noop did something");
self.depth -= 1;
// Remove any #[main] or #[start] from the AST so it doesn't
// clash with the one we're g... |
impl MutVisitor for EntryPointCleaner { | random_line_split |
test.rs | some_name;`. This needs to be
// unconditional, so that the attribute is still marked as used in
// non-test builds.
let reexport_test_harness_main =
attr::first_attr_value_str_by_name(&krate.attrs,
"reexport_test_harness_main");
// Do this here so th... | (&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
let ident = i.ident;
if ident.name != keywords::Invalid.name() {
self.cx.path.push(ident);
}
debug!("current path: {}", path_name_i(&self.cx.path));
let mut item = i.into_inner();
if is_test_case(&... | flat_map_item | identifier_name |
healthCheck.js | maxBlockTime) maxBlockTime = block.timestamp
if (block.transactions.length) {
for (const tx of block.transactions) {
// If transaction is from audius account, determine success or fail status
if (RELAY_HEALTH_ACCOUNTS.has(tx.from)) {
const txHash = tx.hash
cons... | random_line_split | ||
utils.py | _path, obj, protocol=2):
"""
For python 3 compatibility, use protocol 2
"""
if not file_path.endswith('.pkl'):
file_path += '.pkl'
with open(file_path, 'wb') as opdwf:
pk.dump(obj, opdwf, protocol=protocol)
def unpickle(file_path):
with open(file_path, 'rb') as opdrf:
d... |
for start_idx in range(0, n - batchsize + 1, batchsize):
if shuffle:
excerpt = indices[start_idx:start_idx + batchsize]
else:
excerpt = slice(start_idx, start_idx + batchsize)
yield [inputs[excerpt] for inputs in inputs_list], \
targets[excerpt].reshape((... | indices = np.arange(n)
np.random.shuffle(indices) | conditional_block |
utils.py | (file_path, obj, protocol=2):
"""
For python 3 compatibility, use protocol 2
"""
if not file_path.endswith('.pkl'):
file_path += '.pkl'
with open(file_path, 'wb') as opdwf:
pk.dump(obj, opdwf, protocol=protocol)
def unpickle(file_path):
with open(file_path, 'rb') as opdrf:
... |
measures = measure_func(target, pred_binary)
return measures
def get_thresholds(pred, target, search_range, step_size, measure_func=f1,
n_processes=20):
'''
pred: np.array
prediction from a model
n x k 2D array, where n is the number of data and
k is the num... | pred_binary = ((prediction-threshold) > 0).astype(int) | random_line_split |
utils.py | _path, obj, protocol=2):
"""
For python 3 compatibility, use protocol 2
"""
if not file_path.endswith('.pkl'):
file_path += '.pkl'
with open(file_path, 'wb') as opdwf:
pk.dump(obj, opdwf, protocol=protocol)
def unpickle(file_path):
with open(file_path, 'rb') as opdrf:
d... |
def load_model(fp, network):
with np.load(fp) as f:
param_values = [f['arr_%d' % i] for i in range(len(f.files))]
lasagne.layers.set_all_param_values(network, param_values)
# Get thresholds
def f1_one(y_target, y_predicted):
'''
y_target, y_predicted:
1D binary array
'''
ret... | np.savez(fp, *lasagne.layers.get_all_param_values(network)) | identifier_body |
utils.py | _te = np.load(target_te_fp)
# append
X_tr_list.append(X_tr)
y_tr_list.append(y_tr)
X_te_list.append(X_te)
y_te_list.append(y_te)
X_va_list.append(X_va)
y_va_list.append(y_va)
y_tr = y_tr_list[0]
y_va = y_va_list[0]
y_te = y_te_list[0]
return X... | shift | identifier_name | |
pl.locales.ts | silniejszą i bardziej zabawną społeczność.',
},
uHostSection: {
heading: 'uHost, uHost AI-Assistant, and AI-Host',
content:
'Trzy główne tryby turniejowe dają Ci pełną swobodę w prowadzeniu gier.',
hostTypes: [
{
heading: 'uHost',
imageAlt: 'uHost',
content:
... | imageUrl:
'https://cdn.game.tv/images/meet-tourney/perk-tournaments.png',
imageAlt: 'Nagradzane Poziomy Turniejowe',
},
{
content:
'Streamujesz swoje turnieje? Idealnie, mamy dla Ciebie przygotoway plugin OBS.',
imageUrl: 'https://cdn.game.tv/images/meet-t... | content: 'Tourney nie byłby kompletny bez mnóstwa dodatków.',
perksList: [
{
content:
'Prowadzisz mnóstwo turniejów? Świetnie, mamy dla Ciebie system poziomów, który Cię wynagrodzi.', | random_line_split |
build_cgd_dataset.py | import median_filter
# progress bars https://github.com/tqdm/tqdm
# import tqdm without enforcing it as a dependency
try:
from tqdm import tqdm
except ImportError:
def tqdm(*args, **kwargs):
if args:
return args[0]
return kwargs.get('iterable', None)
from tensorflow.python.platfo... |
def _convert_to_example(filename, bboxes, image_buffer, height, width):
# Build an Example proto for an example
example = tf.train.Example(features=tf.train.Features(feature={
'image/filename': _bytes_feature(filename),
'image/encoded': _bytes_feature(image_buffer),
'image/height... | return tf.train.Feature(bytes_list=tf.train.BytesList(value=[v])) | identifier_body |
build_cgd_dataset.py | import median_filter
# progress bars https://github.com/tqdm/tqdm
# import tqdm without enforcing it as a dependency
try:
from tqdm import tqdm
except ImportError:
def tqdm(*args, **kwargs):
if args:
return args[0]
return kwargs.get('iterable', None)
from tensorflow.python.platfo... | (self, data_dir=None, dataset='all'):
'''Cornell Grasping Dataset - about 5GB total size
http:pr.cs.cornell.edu/grasping/rect_data/data.php
Downloads to `~/.keras/datasets/cornell_grasping` by default.
Includes grasp_listing.txt with all files in all datasets;
the feature csv f... | download | identifier_name |
build_cgd_dataset.py | import median_filter
# progress bars https://github.com/tqdm/tqdm
# import tqdm without enforcing it as a dependency
try:
from tqdm import tqdm
except ImportError:
def tqdm(*args, **kwargs):
if args:
return args[0]
return kwargs.get('iterable', None)
from tensorflow.python.platfo... | return self._sess.run(self._decode_png,
feed_dict={self._decode_png_data: image_data})
def _process_image(filename, coder):
# Decode the image
with open(filename) as f:
image_data = f.read()
image = coder.decode_png(image_data)
assert len(image.shape) == 3
... | self._sess = tf.Session()
self._decode_png_data = tf.placeholder(dtype=tf.string)
self._decode_png = tf.image.decode_png(self._decode_png_data, channels=3)
def decode_png(self, image_data): | random_line_split |
build_cgd_dataset.py | import median_filter
# progress bars https://github.com/tqdm/tqdm
# import tqdm without enforcing it as a dependency
try:
from tqdm import tqdm
except ImportError:
def tqdm(*args, **kwargs):
if args:
return args[0]
return kwargs.get('iterable', None)
from tensorflow.python.platfo... |
file_hash_np = np.column_stack([grasp_files, hashes])
with open(listing_hash, 'wb') as hash_file:
np.savetxt(hash_file, file_hash_np, fmt='%s', delimiter=' ', header='file_path sha256')
print('Hashing complete, {} contains each url plus hash, and will... | hashes.append(_hash_file(f)) | conditional_block |
AdobeFontLabUtils.py | 32all Python module from Mark Hammond. This can be found at:"
print " http://www.python.net/crew/mhammond/win32/Downloads.html"
print "or http://sourceforge.net/, and search for 'Python Windows Extensions."
else:
import Carbon.Evt
import Carbon.Events
modifiers = Carbon.Evt.GetCurrentKeyModifiers()
if... | getLatestReport | identifier_name | |
AdobeFontLabUtils.py | /Tools/osx" % (home)
os.environ["PATH"] = paths + fdkPath
if os.name == "nt":
p = os.popen("for %%i in (%s) do @echo. %%~$PATH:i" % (toolName))
log = p.read()
p.close()
log = log.strip()
if log:
toolPath = log
else:
p = os.popen("which %s" % (toolName))
log = p.read()
p.close()
log = log.st... |
def LoadGOADB(filePath):
""" Read a glyph alias file for makeOTF into a dict."""
global goadbIndex
finalNameDict = {}
productionNameDict = {}
goadbIndex = 0
gfile = open(filePath,"rb")
data = gfile.read()
gfile.close()
glyphEntryList = SplitLines(data)
glyphEntryList = CleanLines(glyphEntryList)
gly... | lineList = re.findall(r"([^\r\n]+)[\r\n]", data)
return lineList | identifier_body |
AdobeFontLabUtils.py | installed, and the system environment variable PATH
contains the path the to FDK sub-directory containing '%s'.""" % (toolName, toolName)
return toolPath # get reid of new-line
def checkControlKeyPress():
notPressed = 1
if os.name == "nt":
try:
import win32api
import win32con
keyState = win32api.GetAs... | dir, file = os.path.split(baseFilePath) | random_line_split | |
AdobeFontLabUtils.py | /Tools/osx" % (home)
os.environ["PATH"] = paths + fdkPath
if os.name == "nt":
p = os.popen("for %%i in (%s) do @echo. %%~$PATH:i" % (toolName))
log = p.read()
p.close()
log = log.strip()
if log:
toolPath = log
else:
p = os.popen("which %s" % (toolName))
log = p.read()
p.close()
log = log.st... |
# Add GOADB index value
if entry:
entry.append(goadbIndex)
goadbIndex = goadbIndex + 1
return entry
########################################################
# Misc utilities
########################################################
def RemoveComment(line):
try:
index = string.index(line, "#")
line = l... | entry.append("") | conditional_block |
gap_stats.py | _desired
if __name__ == "__main__":
usage = """
___________
Description:
Command line utility for analyzing gaps in a fasta file. One file can be analyzed, or up to 3 can be compared.
Use this tool to compare a genome assembly pre and post gap filling with tools such as PBJelly.
_____
Usage:
python gap_stats.py [... | plt.legend()
plt.title('Gap Length Histogram')
plt.xlabel('Gap Length (b)')
plt.ylabel('Frequency')
plt.savefig(os.getcwd() + '/gap_stats_hist.pdf')
def write_hist_text_file(lengths, labels):
"""
Write a plain text file to current working directory.
... | """
Save a matplotlib length histogram image to current working directory.
:param lengths: List of Lists of all gap lengths for each fasta.
:param labels: Labels to be used in the histogram image file.
"""
import matplotlib.pyplot as plt
# Find the max and min values for... | identifier_body |
gap_stats.py | ired
if __name__ == "__main__":
usage = """
___________
Description:
Command line utility for analyzing gaps in a fasta file. One file can be analyzed, or up to 3 can be compared.
Use this tool to compare a genome assembly pre and post gap filling with tools such as PBJelly.
_____
Usage:
python gap_stats.py [opti... |
def write_hist_img_file(lengths, labels):
"""
Save a matplotlib length histogram image to current working directory.
:param lengths: List of Lists of all gap lengths for each fasta.
:param labels: Labels to be used in the histogram image file.
"""
import matplotlib.... | for coordinates in bed_dict[header]:
out_file.write(
'%s\t%r\t%r\n' %(header[1:], coordinates[0], coordinates[1])
) | conditional_block |
gap_stats.py | ired
if __name__ == "__main__":
usage = """
___________
Description:
Command line utility for analyzing gaps in a fasta file. One file can be analyzed, or up to 3 can be compared.
Use this tool to compare a genome assembly pre and post gap filling with tools such as PBJelly.
_____
Usage:
python gap_stats.py [opti... | (info):
"""
Use info obtained in get_gap_info to write a summary stats csv file.
:param info: Dictionary where
key = fasta file
value = ordered dictionary containing all gap info from get_gap_info
"""
with open('gap_stats.txt', 'w') a... | write_gap_stats | identifier_name |
gap_stats.py | _desired
if __name__ == "__main__":
usage = """
___________
Description:
Command line utility for analyzing gaps in a fasta file. One file can be analyzed, or up to 3 can be compared.
Use this tool to compare a genome assembly pre and post gap filling with tools such as PBJelly.
_____
Usage:
python gap_stats.py [... | with open(os.getcwd() + '/' + ntpath.basename(hist_file_name), 'w') as out_file:
out_file.write(ntpath.basename(label) + '\n')
for length in sorted(lengths_list):
out_file.write(str(length) + '\n')
def get_gap_info(in_file):
"""
Given ... | :param lengths: List of Lists of all gap lengths for each fasta.
:param labels: Labels to be used in the histogram image file.
"""
for lengths_list, label in zip(lengths, labels):
hist_file_name = label[:label.rfind('.')] + '.all_lengths.txt' | random_line_split |
wk11_main.py |
def schoolLife():
survey = [["highly satisfactoty", "satisfaction", "dissatisfaction" ,"highly unsatisfactory"],
[13.1, 37.1, 8.7, 1.5],
[10.6, 34.6, 13.4, 1.9],
[27.1, 40.0, 2.9, 1.5],
[16.2, 37.8, 6.8, 0.8],
[11.4, 29.8, 14.... | t1.right(180)
t1.write("On the line") | conditional_block | |
wk11_main.py |
def turnright():
t1.right(45)
def turnleft():
t1.left(45)
def keyup():
t1.fd(100)
def turnback():
t1.right(180)
def mousegoto(x,y):
t1.setpos(x,y)
feedback()
def keybye():
wn.bye()
def addkeys():
wn.onkey(turnright,"Right")
w... | ring = turtle.Turtle()
ring.penup()
ring.setpos(-300,300)
ring.pendown()
ring.pensize(3)
#-300,300 -> 300,300 -> 300,-300 -> -300,-300
for side in range(4):
ring.fd(600)
ring.right(90)
ring.write(ring.pos())
ring.hideturtle() | identifier_body | |
wk11_main.py | arms when necessary. Freedom, by its nature, must be chosen, and defended by citizens, and sustained by the rule of ",
" law and the protection of minorities. And when the soul of a nation finally speaks, the institutions that arise may reflect customs and traditions very different from our own. America will... | "In America's ideal of freedom, the public interest depends on private character —on integrity, and tolerance toward others, and the rule of conscience in our own lives. ",
" Self-government relies, in the end, on the governing of the self. That edifice of character is built in families, supported by ... | " and make our society more prosperous and just and equal.",
| random_line_split |
wk11_main.py | ():
survey = [["highly satisfactoty", "satisfaction", "dissatisfaction" ,"highly unsatisfactory"],
[13.1, 37.1, 8.7, 1.5],
[10.6, 34.6, 13.4, 1.9],
[27.1, 40.0, 2.9, 1.5],
[16.2, 37.8, 6.8, 0.8],
[11.4, 29.8, 14.8, 4.9],
... | schoolLife | identifier_name | |
GAN_word_embedding.py |
print('done.')
lines=np.array(map(int, lines[:-1].split(',')))
# if desired the titles are shuffled
if shuffle:
endoftitles = [x for x in range(len(lines)) if lines[x] == dictionary.get('<eol>')]
startoftitles = [0] + list(np.add(endoftitles[:-1], 1))
idx = np.random.permutation... | lines = lines + line.replace(',0', '').replace('\n', '').replace('"', '') + ',' + str(
dictionary.get('<eol>')) + ',' | conditional_block | |
GAN_word_embedding.py | = [0] + list(np.add(endoftitles[:-1], 1))
idx = np.random.permutation(len(endoftitles))
endoftitles=[endoftitles[x] for x in idx]
startoftitles = [startoftitles[x] for x in idx]
lines = [lines[range(startoftitles[x], endoftitles[x] + 1)] for x in range(len(endoftitles))]
lines =... |
# classifier to compute loss based on softmax cross entropy and accuracy
class Classifier(link.Chain):
compute_accuracy = True
def __init__(self, predictor,
lossfun=softmax_cross_entropy.softmax_cross_entropy,
accfun=accuracy.accuracy):
super(Classifier, self).__ini... | dict_trans=w#(w-w.min())/(w-w.min()).max()
title_recon=''
for i in range(len(vec_)):
word_ = vec_.data[i]
word_ = np.tile(word_,(len(w),1))
dist_=np.sqrt(np.sum((dict_trans-word_)**2,1))
title_recon=title_recon+index2word[dist_.argmin()]+' '
return title_recon | identifier_body |
GAN_word_embedding.py | itles = [0] + list(np.add(endoftitles[:-1], 1))
idx = np.random.permutation(len(endoftitles))
endoftitles=[endoftitles[x] for x in idx]
startoftitles = [startoftitles[x] for x in idx]
lines = [lines[range(startoftitles[x], endoftitles[x] + 1)] for x in range(len(endoftitles))]
li... |
with self.init_scope():
self.predictor = predictor
def __call__(self, *args):
assert len(args) >= 2
x = args[:-1]
t = args[-1]
self.y = None
self.loss = None
self.accuracy = None
self.y = self.predictor(*x)
self.loss = self.lossfu... | self.y = None
self.loss = None
self.accuracy = None | random_line_split |
GAN_word_embedding.py | = [0] + list(np.add(endoftitles[:-1], 1))
idx = np.random.permutation(len(endoftitles))
endoftitles=[endoftitles[x] for x in idx]
startoftitles = [startoftitles[x] for x in idx]
lines = [lines[range(startoftitles[x], endoftitles[x] + 1)] for x in range(len(endoftitles))]
lines =... | (link.Chain):
compute_accuracy = True
def __init__(self, predictor,
lossfun=softmax_cross_entropy.softmax_cross_entropy,
accfun=accuracy.accuracy):
super(Classifier, self).__init__()
self.lossfun = lossfun
self.accfun = accfun
self.y = None
... | Classifier | identifier_name |
jobs.py | _ms
logger = logging.getLogger('arq.jobs')
Serializer = Callable[[Dict[str, Any]], bytes]
Deserializer = Callable[[bytes], Dict[str, Any]]
class ResultNotFound(RuntimeError):
pass
class JobStatus(str, Enum):
"""
Enum of job statuses.
"""
#: job is in the queue, time it should be run not yet r... | (
r: bytes, *, deserializer: Optional[Deserializer] = None
) -> Tuple[str, Tuple[Any, ...], Dict[str, Any], int, int]:
if deserializer is None:
deserializer = pickle.loads
try:
d = deserializer(r)
| deserialize_job_raw | identifier_name |
jobs.py | _ms
logger = logging.getLogger('arq.jobs')
Serializer = Callable[[Dict[str, Any]], bytes]
Deserializer = Callable[[bytes], Dict[str, Any]]
class ResultNotFound(RuntimeError):
pass
class JobStatus(str, Enum):
"""
Enum of job statuses.
"""
#: job is in the queue, time it should be run not yet r... |
async def abort(self, *, timeout: Optional[float] = None, poll_delay: float = 0.5) -> bool:
"""
Abort the job.
:param timeout: maximum time to wait for the job result before raising ``TimeoutError``,
will wait forever on None
:param poll_delay: how often to poll redis ... | """
Status of the job.
"""
async with self._redis.pipeline(transaction=True) as tr:
tr.exists(result_key_prefix + self.job_id) # type: ignore[unused-coroutine]
tr.exists(in_progress_key_prefix + self.job_id) # type: ignore[unused-coroutine]
tr.zscore(self._q... | identifier_body |
jobs.py | _ms
logger = logging.getLogger('arq.jobs')
Serializer = Callable[[Dict[str, Any]], bytes]
Deserializer = Callable[[bytes], Dict[str, Any]]
class ResultNotFound(RuntimeError):
pass
class JobStatus(str, Enum):
"""
Enum of job statuses.
"""
#: job is in the queue, time it should be run not yet r... | ):
self.job_id = job_id
self._redis = redis
self._queue_name = _queue_name
self._deserializer = _deserializer
async def result(
self, timeout: Optional[float] = None, *, poll_delay: float = 0.5, pole_delay: float = None
) -> Any:
"""
Get the result of... | redis: 'Redis[bytes]',
_queue_name: str = default_queue_name,
_deserializer: Optional[Deserializer] = None, | random_line_split |
jobs.py | _ms
logger = logging.getLogger('arq.jobs')
Serializer = Callable[[Dict[str, Any]], bytes]
Deserializer = Callable[[bytes], Dict[str, Any]]
class ResultNotFound(RuntimeError):
pass
class JobStatus(str, Enum):
"""
Enum of job statuses.
"""
#: job is in the queue, time it should be run not yet r... |
elif s is None:
raise ResultNotFound(
'Not waiting for job result because the job is not in queue. '
'Is the worker function configured to keep result?'
)
if timeout is not None and delay > timeout:
raise a... | info = deserialize_result(v, deserializer=self._deserializer)
if info.success:
return info.result
elif isinstance(info.result, (Exception, asyncio.CancelledError)):
raise info.result
else:
raise SerializationErro... | conditional_block |
machineconfig.go | fd = "/etc/crio/crio.conf.d"
crioRuntimesConfig = "99-runtimes.conf"
// OCIHooksConfigDir is the default directory for the OCI hooks
OCIHooksConfigDir = "/etc/containers/oci/hooks.d"
// OCIHooksConfig file contains the low latency hooks configuration
OCIHooksConfig = "99-low-latency-hooks.json"
ociTe... | if err != nil {
return nil, err
}
mc.Spec.Config = runtime.RawExtension{Raw: rawIgnition}
enableRTKernel := profile.Spec.RealTimeKernel != nil &&
profile.Spec.RealTimeKernel.Enabled != nil &&
*profile.Spec.RealTimeKernel.Enabled
if enableRTKernel {
mc.Spec.KernelType = MCKernelRT
} else {
mc.Spec.Kern... | {
name := GetMachineConfigName(profile)
mc := &machineconfigv1.MachineConfig{
TypeMeta: metav1.TypeMeta{
APIVersion: machineconfigv1.GroupVersion.String(),
Kind: "MachineConfig",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: profilecomponent.GetMachineConfigLabel(profile),
},
Spe... | identifier_body |
machineconfig.go | OCIHooksConfig file contains the low latency hooks configuration
OCIHooksConfig = "99-low-latency-hooks.json"
ociTemplateRPSMask = "RPSMask"
udevRulesDir = "/etc/udev/rules.d"
udevRpsRules = "99-netdev-rps.rules"
// scripts
hugepagesAllocation = "hugepages-allocation"
ociHooks = "low-... | GetHugepagesAllocationUnitOptions | identifier_name | |
machineconfig.go | = "/etc/crio/crio.conf.d"
crioRuntimesConfig = "99-runtimes.conf"
// OCIHooksConfigDir is the default directory for the OCI hooks
OCIHooksConfigDir = "/etc/containers/oci/hooks.d"
// OCIHooksConfig file contains the low latency hooks configuration
OCIHooksConfig = "99-low-latency-hooks.json"
ociTemp... |
rpsMask := "0" // RPS disabled
if profile.Spec.CPU != nil && profile.Spec.CPU.Reserved != nil {
rpsMask, err = components.CPUListToMaskList(string(*profile.Spec.CPU.Reserved))
if err != nil {
return nil, err
}
}
outContent := &bytes.Buffer{}
templateArgs := map[string]string{ociTemplateRPSMask: rpsMask... | {
return nil, err
} | conditional_block |
machineconfig.go | itionVersion,
},
Storage: igntypes.Storage{
Files: []igntypes.File{},
},
}
// add script files under the node /usr/local/bin directory
mode := 0700
for _, script := range []string{hugepagesAllocation, ociHooks, setRPSMask} {
dst := GetBashScriptPath(script)
content, err := assets.Scripts.ReadFile(fmt.... | }
| random_line_split | |
main.go | return cli.WithContext(func(ctx context.Context, g *errgroup.Group) error {
return run(ctx, g, &opts, args)
})
},
}
// AddCommand adds the 'run' command to cmd.
func AddCommand(c *cobra.Command) {
c.AddCommand(cmd)
fs := cmd.Flags()
fs.SortFlags = false
fs.StringSliceVarP(&opts.Range, "range", "r", nil, "... | {
// make sure the options and arguments are valid
if len(args) == 0 {
return errors.New("last argument needs to be the URL")
}
if len(args) > 1 {
return errors.New("more than one target URL specified")
}
err := opts.valid()
if err != nil {
return err
}
inputURL := args[0]
opts.Request.URL = inputURL... | identifier_body | |
main.go | }
return res, nil
}
func splitShell(cmds []string) ([][]string, error) {
var data [][]string
for _, cmd := range cmds {
args, err := shell.Split(cmd)
if err != nil {
return nil, err
}
if len(args) < 1 {
return nil, fmt.Errorf("invalid command: %q", cmd)
}
data = append(data, args)
}
return dat... | }
}
// make sure error messages logged via the log package are printed nicely
w := cli.NewStdioWrapper(term)
log.SetOutput(w.Stderr())
g.Go(func() error {
term.Run(ctx)
return nil
})
return term, cancel, nil
}
func setupResponseFilters(opts *Options) ([]response.Filter, error) {
var filters []response... |
// write copies of messages to logfile
term = &cli.LogTerminal{
Terminal: statusTerm,
Writer: logfile, | random_line_split |
main.go | Pipe)
if err != nil {
return err
}
opts.hidePattern, err = compileRegexps(opts.HidePattern)
if err != nil {
return err
}
opts.showPattern, err = compileRegexps(opts.ShowPattern)
if err != nil {
return err
}
return nil
}
var cmd = &cobra.Command{
Use: "fuzz [options] URL",
DisableF... | run | identifier_name | |
main.go | errgroup.Group) error {
return run(ctx, g, &opts, args)
})
},
}
// AddCommand adds the 'run' command to cmd.
func AddCommand(c *cobra.Command) {
c.AddCommand(cmd)
fs := cmd.Flags()
fs.SortFlags = false
fs.StringSliceVarP(&opts.Range, "range", "r", nil, "set range `from-to`")
fs.StringVar(&opts.RangeFormat... | {
return err
} | conditional_block | |
resp.go | return "Integer"
case '$':
return "BulkString"
case '*':
return "Array"
case 'R':
return "RDB"
}
}
// Value represents the data of a valid RESP type.
type Value struct {
Typ Type
IntegerV int
Str []byte
ArrayV []Value
Null bool
RDB bool
Size int
}
func (v Value) ReplInfo() ... | switch v.Typ {
default:
n, _ := strconv.ParseInt(v.String(), 10, 64)
return int(n)
case ':':
return v.IntegerV
}
}
// String converts Value to a string.
func (v Value) String() string {
if v.Typ == '$' {
return string(v.Str)
}
switch v.Typ {
case '+', '-':
return string(v.Str)
case ':':
return str... | }
// Integer converts Value to an int. If Value cannot be converted, Zero is returned.
func (v Value) Integer() int { | random_line_split |
resp.go | return "Integer"
case '$':
return "BulkString"
case '*':
return "Array"
case 'R':
return "RDB"
}
}
// Value represents the data of a valid RESP type.
type Value struct {
Typ Type
IntegerV int
Str []byte
ArrayV []Value
Null bool
RDB bool
Size int
}
func (v Value) ReplInfo() ... | (f float | FloatValue | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.