file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
info.py
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import inspect import textwrap from six.moves import zip_longest import llnl.util...
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
use std::collections::{HashMap, HashSet}; use std::fmt; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use libc; use log::{error, info, warn}; use crate::{Data, ArcDataSlice}; use super::*; pub(super) struct LogFile { file_path: ...
(&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
use std::collections::{HashMap, HashSet}; use std::fmt; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use libc; use log::{error, info, warn}; use crate::{Data, ArcDataSlice}; use super::*; pub(super) struct LogFile { file_path: ...
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
use std::collections::{HashMap, HashSet}; use std::fmt; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use libc; use log::{error, info, warn}; use crate::{Data, ArcDataSlice}; use super::*; pub(super) struct LogFile { file_path: ...
file_id = entry.previous_entry_location.file_id; entry_block_offset = entry.previous_entry_location.offset as usize; } let get_data = |file_location: &FileLocation| -> Result<ArcData> { let d = files[file_location.file_id.0 as usize].0.read(file_location.offset as ...
{ break; // Cannot have an offset of 0 (first 16 bytes of the file are the UUID) }
conditional_block
log_file.rs
use std::collections::{HashMap, HashSet}; use std::fmt; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use libc; use log::{error, info, warn}; use crate::{Data, ArcDataSlice}; use super::*; pub(super) struct LogFile { file_path: ...
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
const NUM_PARTICLES = 0; const SIZE = 5; const SIZE_D2 = SIZE / 2.0; const STEPS = 4; const TTYPE_DRAG = 0; const TTYPE_TRIANGLE = 1; const TTYPE_SQUARE = 2; const GRID_SIZE = 40; var grid_w, grid_h; var grid = null; var particles = null; var constraints = null; var bodies = null; var physics = null; var initGrav...
() { 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
const NUM_PARTICLES = 0; const SIZE = 5; const SIZE_D2 = SIZE / 2.0; const STEPS = 4; const TTYPE_DRAG = 0; const TTYPE_TRIANGLE = 1; const TTYPE_SQUARE = 2; const GRID_SIZE = 40; var grid_w, grid_h; var grid = null; var particles = null; var constraints = null; var bodies = null; var physics = null; var initGrav...
function Constraint(p1, p2, l, pushing = true, canTear = false, tearMult = 1) { this.p1 = p1; this.p2 = p2; this.l = l; this.lSq = l * l; this.pushing = pushing; this.canTear = canTear; this.tearStr = l * tearMult; this.tearStrSq = this.lSq * tearMult; } function createTriangle(x, y, size) { let body = new ...
{ this.x = x; this.y = y; this.px = x; this.py = y; this.invmass = 0.3; }
identifier_body
sketch.js
const NUM_PARTICLES = 0; const SIZE = 5; const SIZE_D2 = SIZE / 2.0; const STEPS = 4; const TTYPE_DRAG = 0; const TTYPE_TRIANGLE = 1; const TTYPE_SQUARE = 2; const GRID_SIZE = 40; var grid_w, grid_h; var grid = null; var particles = null; var constraints = null; var bodies = null; var physics = null; var initGravi...
this.x = x; this.y = y; this.px = x; this.py = y; this.invmass = 0.3; } function Constraint(p1, p2, l, pushing = true, canTear = false, tearMult = 1) { this.p1 = p1; this.p2 = p2; this.l = l; this.lSq = l * l; this.pushing = pushing; this.canTear = canTear; this.tearStr = l * tearMult; this.tearStrSq = th...
function Particle(x, y) {
random_line_split
sketch.js
const NUM_PARTICLES = 0; const SIZE = 5; const SIZE_D2 = SIZE / 2.0; const STEPS = 4; const TTYPE_DRAG = 0; const TTYPE_TRIANGLE = 1; const TTYPE_SQUARE = 2; const GRID_SIZE = 40; var grid_w, grid_h; var grid = null; var particles = null; var constraints = null; var bodies = null; var physics = null; var initGrav...
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
$(function(){ searchBtn(); $("input[name=btSelectAll]").attr("style","height:16px;width:16px;"); $("input[name=btSelectAll]").css("verticalAlign","middle"); $('#headYearId').datetimepicker({ startView: 'decade', minView: 'decade', format: 'yyyy', maxViewM...
+ '/annual/findAll.do'}); bootbox.alert("提交成功!"); $('#myModalSearch').modal('hide'); }, error:function(xhr,status,e){ //服务器响应失败时的处理函数 bootbox.alert('服务器请求失败!'); } }); } }); } } /*获取选中的值*/ function getSelect...
$("#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
$(function(){ searchBtn(); $("input[name=btSelectAll]").attr("style","height:16px;width:16px;"); $("input[name=btSelectAll]").css("verticalAlign","middle"); $('#headYearId').datetimepicker({ startView: 'decade', minView: 'decade', format: 'yyyy', maxViewM...
}
return ""; }
random_line_split
annualSearchPage.js
$(function(){ searchBtn(); $("input[name=btSelectAll]").attr("style","height:16px;width:16px;"); $("input[name=btSelectAll]").css("verticalAlign","middle"); $('#headYearId').datetimepicker({ startView: 'decade', minView: 'decade', format: 'yyyy', maxViewM...
turn currentdate; }else{ return ""; } }
re
identifier_name
annualSearchPage.js
$(function(){ searchBtn(); $("input[name=btSelectAll]").attr("style","height:16px;width:16px;"); $("input[name=btSelectAll]").css("verticalAlign","middle"); $('#headYearId').datetimepicker({ startView: 'decade', minView: 'decade', format: 'yyyy', maxViewM...
//服务器响应失败时的处理函数 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
// Symmetric Icons #![allow(dead_code)] use array2d::*; // lambda, alpha, beta, gamma, omega, symmetry, scale const PRESETS: [[f32; 7]; 36] = [ [1.56, -1., 0.1, -0.82, -0.3, 3., 1.7], [-1.806, 1.806, 0., 1.5, 0., 7., 1.1], [2.4, -2.5, -0.9, 0.9, 0., 3., 1.5], [-2.7, 5., 1.5, 1., 0., 4., 1.], [-2....
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
// Symmetric Icons #![allow(dead_code)] use array2d::*; // lambda, alpha, beta, gamma, omega, symmetry, scale const PRESETS: [[f32; 7]; 36] = [ [1.56, -1., 0.1, -0.82, -0.3, 3., 1.7], [-1.806, 1.806, 0., 1.5, 0., 7., 1.1], [2.4, -2.5, -0.9, 0.9, 0., 3., 1.5], [-2.7, 5., 1.5, 1., 0., 4., 1.], [-2....
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
// Symmetric Icons #![allow(dead_code)] use array2d::*; // lambda, alpha, beta, gamma, omega, symmetry, scale const PRESETS: [[f32; 7]; 36] = [ [1.56, -1., 0.1, -0.82, -0.3, 3., 1.7], [-1.806, 1.806, 0., 1.5, 0., 7., 1.1], [2.4, -2.5, -0.9, 0.9, 0., 3., 1.5], [-2.7, 5., 1.5, 1., 0., 4., 1.], [-2....
} fn set_point(&mut self, x : usize, y : usize) { let icon = self.icon[(x,y)]; let color = self.get_color(icon); self.image[(x,y)] = color; self.icon[(x,y)] += 1; if icon >= 12288 { self.icon[(x,y)] = 8192 } } pub fn generate(&mut self, mod_disp : u32) -> bool ...
{ self.color_list[(col * self.speed) as usize] }
conditional_block
symm_icon.rs
// Symmetric Icons #![allow(dead_code)] use array2d::*; // lambda, alpha, beta, gamma, omega, symmetry, scale const PRESETS: [[f32; 7]; 36] = [ [1.56, -1., 0.1, -0.82, -0.3, 3., 1.7], [-1.806, 1.806, 0., 1.5, 0., 7., 1.1], [2.4, -2.5, -0.9, 0.9, 0., 3., 1.5], [-2.7, 5., 1.5, 1., 0., 4., 1.], [-2....
(&mut self) { self.speed = DEFAULT_SPEED; self.apcx = self.w as f32 / 2.; self.apcy = self.h as f32 / 2.; self.rad = if self.apcx > self.apcy {self.apcy} else {self.apcx}; self.k = 0; self.x = 0.01; self.y = 0.003; self.iter = 0; self.icon = Arra...
reset
identifier_name
component.rs
use crate::code::CodeObject; use crate::signatures::SignatureCollection; use crate::{Engine, Module, ResourcesRequired}; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use std::fs; use std::mem; use std::path::Path; use std::ptr::NonNull; use std::sync::Arc; use wasmtime_environ::component::{...
(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
use crate::code::CodeObject; use crate::signatures::SignatureCollection; use crate::{Engine, Module, ResourcesRequired}; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use std::fs; use std::mem; use std::path::Path; use std::ptr::NonNull; use std::sync::Arc; use wasmtime_environ::component::{...
/// 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
use crate::code::CodeObject; use crate::signatures::SignatureCollection; use crate::{Engine, Module, ResourcesRequired}; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use std::fs; use std::mem; use std::path::Path; use std::ptr::NonNull; use std::sync::Arc; use wasmtime_environ::component::{...
} pub(crate) fn runtime_info(&self) -> Arc<dyn ComponentRuntimeInfo> { self.inner.clone() } /// Creates a new `VMFuncRef` with all fields filled out for the destructor /// specified. /// /// The `dtor`'s own `VMFuncRef` won't have `wasm_call` filled out but this /// component m...
pub fn serialize(&self) -> Result<Vec<u8>> { Ok(self.code_object().code_memory().mmap().to_vec())
random_line_split
utils.ts
import $ from 'jquery' import 'bootstrap' import { Frame } from 'scenejs' import { createPopper, Placement } from '@popperjs/core' import domtoimage from 'dom-to-image' export default { /** * 把 selected作为一组,更新他们的grouped结构体 * @param selectedItems * @param isGrouped */ setSelectedItemAsGroup (designVm:an...
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
import $ from 'jquery' import 'bootstrap' import { Frame } from 'scenejs' import { createPopper, Placement } from '@popperjs/core' import domtoimage from 'dom-to-image' export default { /** * 把 selected作为一组,更新他们的grouped结构体 * @param selectedItems * @param isGrouped */ setSelectedItemAsGroup (designVm:an...
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
import $ from 'jquery' import 'bootstrap' import { Frame } from 'scenejs' import { createPopper, Placement } from '@popperjs/core' import domtoimage from 'dom-to-image' export default { /** * 把 selected作为一组,更新他们的grouped结构体 * @param selectedItems * @param isGrouped */ setSelectedItemAsGroup (designVm:an...
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] = this.deepMerge(result[key], val) } el...
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
import $ from 'jquery' import 'bootstrap' import { Frame } from 'scenejs' import { createPopper, Placement } from '@popperjs/core' import domtoimage from 'dom-to-image' export default { /** * 把 selected作为一组,更新他们的grouped结构体 * @param selectedItems * @param isGrouped */ setSelectedItemAsGroup (designVm:an...
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
#!/usr/bin/env python """ Kernel Probability Density Estimator Self-Organizing Map """ # python import re import os import sys import glob import time import numpy import shutil import subprocess # appion from appionlib import appionScript from appionlib import apXmipp from appionlib import apDisplay from appionlib im...
emancmd = ("proc2d %s %s list=%s average"% (self.instack, stackname, listname)) apEMAN.executeEmanCmd(emancmd, showcmd=True, verbose=False) ### create mrc emancmd = ("proc2d %s %s first=%d last=%d"% (stackname, listname+".mrc", count, count)) apEMAN.executeEmanCmd(emancmd, showcmd=False, v...
### create png shutil.copy("crap.png", listname+".png") else: ### average particles
random_line_split
kerdenSOM.py
#!/usr/bin/env python """ Kernel Probability Density Estimator Self-Organizing Map """ # python import re import os import sys import glob import time import numpy import shutil import subprocess # appion from appionlib import appionScript from appionlib import apXmipp from appionlib import apDisplay from appionlib im...
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
#!/usr/bin/env python """ Kernel Probability Density Estimator Self-Organizing Map """ # python import re import os import sys import glob import time import numpy import shutil import subprocess # appion from appionlib import appionScript from appionlib import apXmipp from appionlib import apDisplay from appionlib im...
#====================== 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
#!/usr/bin/env python """ Kernel Probability Density Estimator Self-Organizing Map """ # python import re import os import sys import glob import time import numpy import shutil import subprocess # appion from appionlib import appionScript from appionlib import apXmipp from appionlib import apDisplay from appionlib im...
(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
/*--- PROPIEDADES ---*/ var listaTarjetas = []; var tarjetaActual = null; var existeFoto = false; var existeSonido = false; var fondoActual = 1; // Esta variable contiene el id del fondo que está actualmente mostrándose en el formulario de nueva tarjeta var mostrarFavoritas = false; // Indica si se deben mostrar sola...
ne la traducción de un texto proporcionandole un idioma de origen y destino */ function TraduccionSugerida(event){ console.log("Hay conexion = "+hayConexion); console.log("Se ha traducido "+numTraducciones+" veces"); if (valorAnteriorTitulo != $('#inputTituloTarjeta').val() && hayConexion && (!liteVersion || (liteV...
ror: "+t,'',res_titulo_servidor_no_disponible,res_Aceptar); } estadoServidor=false; } } } }); } /* * Obtie
conditional_block
tarjetas.js
/*--- PROPIEDADES ---*/ var listaTarjetas = []; var tarjetaActual = null; var existeFoto = false; var existeSonido = false; var fondoActual = 1; // Esta variable contiene el id del fondo que está actualmente mostrándose en el formulario de nueva tarjeta var mostrarFavoritas = false; // Indica si se deben mostrar sola...
to. Intenta cargar la foto pasada como parámetro. Si lo consigue, la redimensiona para que se muestre * correctamente en la lista de tarjetas. Si no consigue cargarla, deja la imagen que esta en el identificador correspondiente. * * @param identificador id de la imagen donde cargará la foto * @param rutaFoto ru...
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
/*--- PROPIEDADES ---*/ var listaTarjetas = []; var tarjetaActual = null; var existeFoto = false; var existeSonido = false; var fondoActual = 1; // Esta variable contiene el id del fondo que está actualmente mostrándose en el formulario de nueva tarjeta var mostrarFavoritas = false; // Indica si se deben mostrar sola...
} } 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
/*--- PROPIEDADES ---*/ var listaTarjetas = []; var tarjetaActual = null; var existeFoto = false; var existeSonido = false; var fondoActual = 1; // Esta variable contiene el id del fondo que está actualmente mostrándose en el formulario de nueva tarjeta var mostrarFavoritas = false; // Indica si se deben mostrar sola...
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
extern crate chrono; extern crate id3; extern crate mp3_duration; extern crate regex; extern crate reqwest; use std::{ fs::{ read_dir, rename, }, io::{ Read, }, iter::{ repeat_with, }, path::{ Path, PathBuf, }, time::{ Duration...
( 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
extern crate chrono; extern crate id3; extern crate mp3_duration; extern crate regex; extern crate reqwest; use std::{ fs::{ read_dir, rename, }, io::{ Read, }, iter::{ repeat_with, }, path::{ Path, PathBuf, }, time::{ Duration...
} 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
extern crate chrono; extern crate id3; extern crate mp3_duration; extern crate regex; extern crate reqwest; use std::{ fs::{ read_dir, rename, }, io::{ Read, }, iter::{ repeat_with, }, path::{ Path, PathBuf, }, time::{ Duration...
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
extern crate chrono; extern crate id3; extern crate mp3_duration; extern crate regex; extern crate reqwest; use std::{ fs::{ read_dir, rename, }, io::{ Read, }, iter::{ repeat_with, }, path::{ Path, PathBuf, }, time::{ Duration...
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
use std::{ io::{self, Write}, ops::Range, cmp::min, iter::Peekable }; use crate::{ iface::{TerminalPlugin, FormatLike}, config }; use smallvec::{smallvec, SmallVec}; use terminfo::{expand, Database, capability as cap}; // pub const CORNER_SW: char = '╗'; const CORNER_SE: char = '╔'; const COR...
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
use std::{ io::{self, Write}, ops::Range, cmp::min, iter::Peekable }; use crate::{ iface::{TerminalPlugin, FormatLike}, config }; use smallvec::{smallvec, SmallVec}; use terminfo::{expand, Database, capability as cap}; // pub const CORNER_SW: char = '╗'; const CORNER_SE: char = '╔'; const COR...
t<(), io::Error> { self.out.flush() } fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> { self.out.write(buf) } } #[derive(Debug)] struct TextSegment { text: String, fmt: FormatLike, pre_calculated_length: usize, } impl TextSegment { pub fn new(text: impl Into<S...
Resul
identifier_name
terminal.rs
use std::{ io::{self, Write}, ops::Range, cmp::min, iter::Peekable }; use crate::{ iface::{TerminalPlugin, FormatLike}, config }; use smallvec::{smallvec, SmallVec}; use terminfo::{expand, Database, capability as cap}; // pub const CORNER_SW: char = '╗'; const CORNER_SE: char = '╔'; const COR...
)] 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
use std::{ io::{self, Write}, ops::Range, cmp::min, iter::Peekable }; use crate::{ iface::{TerminalPlugin, FormatLike}, config }; use smallvec::{smallvec, SmallVec}; use terminfo::{expand, Database, capability as cap}; // pub const CORNER_SW: char = '╗'; const CORNER_SE: char = '╔'; const COR...
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
// This file is part of the SORA network and Polkaswap app. // Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved. // SPDX-License-Identifier: BSD-4-Clause // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: ...
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
// This file is part of the SORA network and Polkaswap app. // Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved. // SPDX-License-Identifier: BSD-4-Clause // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: ...
(accounts: Vec<(AccountId, AssetId, Balance)>) -> Self { let permissioned_account_id = GetPswapDistributionAccountId::get(); Self { endowed_accounts: accounts, endowed_assets: vec![ ( common::XOR.into(), alice(), ...
with_accounts
identifier_name
mock.rs
// This file is part of the SORA network and Polkaswap app. // Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved. // SPDX-License-Identifier: BSD-4-Clause // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: ...
initial_permission_owners: self.initial_permission_owners, } .assimilate_storage(&mut t) .unwrap(); TokensConfig { endowed_accounts: self.endowed_accounts, } .assimilate_storage(&mut t) .unwrap(); AssetsConfig { endowe...
random_line_split
list_view_items.rs
use std::cell::Cell; use std::ptr::NonNull; use crate::aliases::WinResult; use crate::co; use crate::handles::HWND; use crate::msg::lvm; use crate::structs::{LVFINDINFO, LVHITTESTINFO, LVITEM, RECT}; use crate::various::WString; /// Exposes item methods of a [`ListView`](crate::gui::ListView) control. /// ...
(&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
use std::cell::Cell; use std::ptr::NonNull; use crate::aliases::WinResult; use crate::co; use crate::handles::HWND; use crate::msg::lvm; use crate::structs::{LVFINDINFO, LVHITTESTINFO, LVITEM, RECT}; use crate::various::WString; /// Exposes item methods of a [`ListView`](crate::gui::ListView) control. /// ...
// Static method because it's also used by ListViewColumns. // https://forums.codeguru.com/showthread.php?351972-Getting-listView-item-text-length const BLOCK: usize = 64; // arbitrary let mut buf_sz = BLOCK; let mut buf = buf; loop { let mut lvi = LVITEM::default(); lvi.iSubItem = column...
{
random_line_split
index.js
const landing_page_puzzlepiece_container = 'landing-page-puzzlepiece-container'; const drag_to_start_story_div = 'drag-to-start-story-div'; /** * Enable drag and drop using the Dragula library */ const draggables = dragula([ /** * Adding all the elements to the same dragula might actually allow * any p...
() { 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
const landing_page_puzzlepiece_container = 'landing-page-puzzlepiece-container'; const drag_to_start_story_div = 'drag-to-start-story-div'; /** * Enable drag and drop using the Dragula library */ const draggables = dragula([ /** * Adding all the elements to the same dragula might actually allow * any p...
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
const landing_page_puzzlepiece_container = 'landing-page-puzzlepiece-container'; const drag_to_start_story_div = 'drag-to-start-story-div'; /** * Enable drag and drop using the Dragula library */ const draggables = dragula([ /** * Adding all the elements to the same dragula might actually allow * any p...
async function copyCode() { // Read the basic_web_monetization_code.html file const codeText = await readFile(window.location.origin + '/a-web-monetization-story/' + 'samples/basic_web_monetization_code.html'); // Create hidden text area element to hold text, set the value and add it to the body cons...
{ 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
const landing_page_puzzlepiece_container = 'landing-page-puzzlepiece-container'; const drag_to_start_story_div = 'drag-to-start-story-div'; /** * Enable drag and drop using the Dragula library */ const draggables = dragula([ /** * Adding all the elements to the same dragula might actually allow * any p...
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
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Library to build `Custom_tag` OCaml values. use std::ffi::CStr; use std::ffi::CString; use std::mem::MaybeUninit; use std::ops::Der...
// a CustomBlockOcamlRep<T> created by T::to_ocamlrep. Such a pointer // would be aligned and valid. let custom_block_ptr = value as *mut CustomBlockOcamlRep<T>; let custom_block = unsafe { custom_block_ptr.as_mut().unwrap() }; // The `Rc` will be dropped here, and its reference...
// 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
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Library to build `Custom_tag` OCaml values. use std::ffi::CStr; use std::ffi::CString; use std::mem::MaybeUninit; use std::ops::Der...
<T: CamlSerialize>(value: usize) { let _: usize = catch_unwind(|| { // 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 /...
drop_value
identifier_name
lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Library to build `Custom_tag` OCaml values. use std::ffi::CStr; use std::ffi::CString; use std::mem::MaybeUninit; use std::ops::Der...
}
{ assert_eq!( align_of::<CustomBlockOcamlRep<u8>>(), align_of::<Value<'_>>() ); }
identifier_body
lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Library to build `Custom_tag` OCaml values. use std::ffi::CStr; use std::ffi::CString; use std::mem::MaybeUninit; use std::ops::Der...
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
''' CodeOfWar COSC 370 AI Battlecode Project Jennifer Mince, Carly Good, Matt Manoly, Zachary Taylor Code for Inspiration: https://github.com/AnPelec/Battlecode-2018/blob/master/Project%20Achilles/run.py ''' import battlecode as bc import random import sys import traceback import time from datetime import datetime i...
(): 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
''' CodeOfWar COSC 370 AI Battlecode Project Jennifer Mince, Carly Good, Matt Manoly, Zachary Taylor Code for Inspiration: https://github.com/AnPelec/Battlecode-2018/blob/master/Project%20Achilles/run.py ''' import battlecode as bc import random import sys import traceback import time from datetime import datetime i...
#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 can heal, heal...
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
''' CodeOfWar COSC 370 AI Battlecode Project Jennifer Mince, Carly Good, Matt Manoly, Zachary Taylor Code for Inspiration: https://github.com/AnPelec/Battlecode-2018/blob/master/Project%20Achilles/run.py ''' import battlecode as bc import random import sys import traceback import time from datetime import datetime i...
elif len(unit.structure_garrison()) >= 8 or gc.round() >= 748 or unit.health < unit.max_health: launch(unit) elif unit.unit_type == bc.UnitType.Factory: factoryProduce(unit) elif unit.unit_type == bc.UnitType.Worker: workerWork...
unloadRocket(unit)
conditional_block
run.py
''' CodeOfWar COSC 370 AI Battlecode Project Jennifer Mince, Carly Good, Matt Manoly, Zachary Taylor Code for Inspiration: https://github.com/AnPelec/Battlecode-2018/blob/master/Project%20Achilles/run.py ''' import battlecode as bc import random import sys import traceback import time from datetime import datetime i...
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
// Code that generates a test runner to run all the tests in a crate #![allow(dead_code)] #![allow(unused_imports)] use HasTestSignature::*; use std::iter; use std::slice; use std::mem; use std::vec; use log::debug; use smallvec::{smallvec, SmallVec}; use syntax_pos::{DUMMY_SP, NO_EXPANSION, Span, SourceFile, ByteP...
fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> { let test_attr = attr::find_by_name(&krate.attrs, "test_runner")?; test_attr.meta_item_list().map(|meta_list| { if meta_list.len() != 1 { sd.span_fatal(test_attr.span, "#![test_runner(..)] ac...
{ attr::contains_name(&i.attrs, "rustc_test_marker") }
identifier_body
test.rs
// Code that generates a test runner to run all the tests in a crate #![allow(dead_code)] #![allow(unused_imports)] use HasTestSignature::*; use std::iter; use std::slice; use std::mem; use std::vec; use log::debug; use smallvec::{smallvec, SmallVec}; use syntax_pos::{DUMMY_SP, NO_EXPANSION, Span, SourceFile, ByteP...
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
// Code that generates a test runner to run all the tests in a crate #![allow(dead_code)] #![allow(unused_imports)] use HasTestSignature::*; use std::iter; use std::slice; use std::mem; use std::vec; use log::debug; use smallvec::{smallvec, SmallVec}; use syntax_pos::{DUMMY_SP, NO_EXPANSION, Span, SourceFile, ByteP...
(&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
const config = require('../config.js') const models = require('../models') const { handleResponse, successResponse, errorResponseServerError } = require('../apiHelpers') const { sequelize } = require('../models') const { getRelayerFunds, fundRelayerIfEmpty } = require('../relay/txRelay') const { getEthRelayerFunds } = ...
let notifBlockDiff = discProvDbHighestBlock - highestBlockNumber let resp = { 'discProv': body.data, 'identity': highestBlockNumber, 'notifBlockDiff': notifBlockDiff, notificationJobLastSuccess, notificationEmailsJobLastSuccess, notificationAnnouncementsJobLastSuccess } ...
random_line_split
utils.py
#!/usr/bin/env python import os import sys import csv import numpy as np import theano import lasagne from sklearn.metrics import f1_score from multiprocessing import Pool theano.config.exception_verbosity = 'high' floatX = theano.config.floatX epsilon = np.float32(1e-6) one = np.float32(1) pf = np.float32(0.5) #...
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
#!/usr/bin/env python import os import sys import csv import numpy as np import theano import lasagne from sklearn.metrics import f1_score from multiprocessing import Pool theano.config.exception_verbosity = 'high' floatX = theano.config.floatX epsilon = np.float32(1e-6) one = np.float32(1) pf = np.float32(0.5) #...
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
#!/usr/bin/env python import os import sys import csv import numpy as np import theano import lasagne from sklearn.metrics import f1_score from multiprocessing import Pool theano.config.exception_verbosity = 'high' floatX = theano.config.floatX epsilon = np.float32(1e-6) one = np.float32(1) pf = np.float32(0.5) #...
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
#!/usr/bin/env python import os import sys import csv import numpy as np import theano import lasagne from sklearn.metrics import f1_score from multiprocessing import Pool theano.config.exception_verbosity = 'high' floatX = theano.config.floatX epsilon = np.float32(1e-6) one = np.float32(1) pf = np.float32(0.5) #...
(array_list, shift_size, axis): n_axes = len(array_list[0].shape) obj = [slice(None, None, None) for ii in range(n_axes)] obj[axis] = slice(shift_size, None, 1) obj = tuple(obj) pad_width = [(0, 0) for ii in range(n_axes)] pad_width[axis] = (0, shift_size) out_array_list = [np.pad(array[ob...
shift
identifier_name
pl.locales.ts
import { IHomeLocale } from '@app/abstractions'; import { SupportedLocalesEnum } from '@app/enums'; const language = SupportedLocalesEnum.POLISH; export const HomeLocalePolish: IHomeLocale = { metadata: { title: 'Tourney - Esports Discord Bot Obsługiwany przez AI', description: 'Organizuj i prowadź tysi...
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
#!/usr/local/bin/python '''Converts Cornell Grasping Dataset data into TFRecords data format using Example protos. The raw data set resides in png and txt files located in the following structure: dataset/03/pcd0302r.png dataset/03/pcd0302cpos.txt ''' import os import errno import traceback import itertools i...
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
#!/usr/local/bin/python '''Converts Cornell Grasping Dataset data into TFRecords data format using Example protos. The raw data set resides in png and txt files located in the following structure: dataset/03/pcd0302r.png dataset/03/pcd0302cpos.txt ''' import os import errno import traceback import itertools i...
(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
#!/usr/local/bin/python '''Converts Cornell Grasping Dataset data into TFRecords data format using Example protos. The raw data set resides in png and txt files located in the following structure: dataset/03/pcd0302r.png dataset/03/pcd0302cpos.txt ''' import os import errno import traceback import itertools i...
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
#!/usr/local/bin/python '''Converts Cornell Grasping Dataset data into TFRecords data format using Example protos. The raw data set resides in png and txt files located in the following structure: dataset/03/pcd0302r.png dataset/03/pcd0302cpos.txt ''' import os import errno import traceback import itertools i...
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
# Support module for FontLab scripts. __copyright__ = """ Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. """ __doc__ = """ Ad...
(baseFilePath, extension=kDefaultReportExtension): """ FInd the latest report matching the path and extension. Assume that the highest number is the most recent. """ n = 1 dir, file = os.path.split(baseFilePath) logsDir = os.path.join(dir, kDefaultLogSubdirectory) matchString = r"%s.%sv0*(\d+)$" % (file, extensi...
getLatestReport
identifier_name
AdobeFontLabUtils.py
# Support module for FontLab scripts. __copyright__ = """ Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. """ __doc__ = """ Ad...
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
# Support module for FontLab scripts. __copyright__ = """ Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. """ __doc__ = """ Ad...
numPattern = re.compile(file + "." + extension + r"v0*(\d+)$") fileList = os.listdir(dir) for file in fileList: match = numPattern.match(file) if match: num = match.group(1) num = eval(num) if num >= n: n = num + 1 if n > (10**kDefaultVersionDigits - 1): kDefaultVersionDigits = kDefau...
dir, file = os.path.split(baseFilePath)
random_line_split
AdobeFontLabUtils.py
# Support module for FontLab scripts. __copyright__ = """ Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. """ __doc__ = """ Ad...
# 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
#!/usr/bin/env python from __future__ import division import os import sys import ntpath import collections from dsa_seq_utils.Sequence import GapSequence from dsa_seq_utils.SeqReader import SeqReader from dsa_seq_utils.stats import calculate_median from dsa_seq_utils.utilities import log from dsa_seq_utils.utilities...
def write_hist_text_file(lengths, labels): """ Write a plain text file to current working directory. 1 ordered column of all histogram lengths. This is for input into statistical analysis software such as R. :param lengths: List of Lists of all gap lengths for each fasta. ...
""" 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
#!/usr/bin/env python from __future__ import division import os import sys import ntpath import collections from dsa_seq_utils.Sequence import GapSequence from dsa_seq_utils.SeqReader import SeqReader from dsa_seq_utils.stats import calculate_median from dsa_seq_utils.utilities import log from dsa_seq_utils.utilities...
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
#!/usr/bin/env python from __future__ import division import os import sys import ntpath import collections from dsa_seq_utils.Sequence import GapSequence from dsa_seq_utils.SeqReader import SeqReader from dsa_seq_utils.stats import calculate_median from dsa_seq_utils.utilities import log from dsa_seq_utils.utilities...
(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
#!/usr/bin/env python from __future__ import division import os import sys import ntpath import collections from dsa_seq_utils.Sequence import GapSequence from dsa_seq_utils.SeqReader import SeqReader from dsa_seq_utils.stats import calculate_median from dsa_seq_utils.utilities import log from dsa_seq_utils.utilities...
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
import turtle import math wn=turtle.Screen() t1=turtle.Turtle() t1.color("red") t1.shape("turtle") t1.penup() def ring(): ring = turtle.Turtle() ring.penup() ring.setpos(-300,300) ring.pendown() ring.pensize(3) #-300,300 -> 300,300 -> 300,-300 -> -300,-300 for s...
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
import turtle import math wn=turtle.Screen() t1=turtle.Turtle() t1.color("red") t1.shape("turtle") t1.penup() def ring():
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
import turtle import math wn=turtle.Screen() t1=turtle.Turtle() t1.color("red") t1.shape("turtle") t1.penup() def ring(): ring = turtle.Turtle() ring.penup() ring.setpos(-300,300) ring.pendown() ring.pensize(3) #-300,300 -> 300,300 -> 300,-300 -> -300,-300 for s...
"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
import turtle import math wn=turtle.Screen() t1=turtle.Turtle() t1.color("red") t1.shape("turtle") t1.penup() def ring(): ring = turtle.Turtle() ring.penup() ring.setpos(-300,300) ring.pendown() ring.pensize(3) #-300,300 -> 300,300 -> 300,-300 -> -300,-300 for s...
(): 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
from __future__ import print_function import numpy as np import chainer from chainer.functions.evaluation import accuracy from chainer.functions.loss import softmax_cross_entropy from chainer import link from chainer import reporter from chainer import optimizers import chainer.functions as F import chainer.links as L ...
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
from __future__ import print_function import numpy as np import chainer from chainer.functions.evaluation import accuracy from chainer.functions.loss import softmax_cross_entropy from chainer import link from chainer import reporter from chainer import optimizers import chainer.functions as F import chainer.links as L ...
# 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
from __future__ import print_function import numpy as np import chainer from chainer.functions.evaluation import accuracy from chainer.functions.loss import softmax_cross_entropy from chainer import link from chainer import reporter from chainer import optimizers import chainer.functions as F import chainer.links as L ...
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
from __future__ import print_function import numpy as np import chainer from chainer.functions.evaluation import accuracy from chainer.functions.loss import softmax_cross_entropy from chainer import link from chainer import reporter from chainer import optimizers import chainer.functions as F import chainer.links as L ...
(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
import asyncio import logging import pickle import warnings from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Any, Callable, Dict, Optional, Tuple from redis.asyncio import Redis from .constants import abort_jobs_ss, default_queue_name, in_progress_key_prefix, jo...
( 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) return d['f'], d['a'], d['k'], d['t'], d['et'] except Exception as e: raise...
deserialize_job_raw
identifier_name
jobs.py
import asyncio import logging import pickle import warnings from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Any, Callable, Dict, Optional, Tuple from redis.asyncio import Redis from .constants import abort_jobs_ss, default_queue_name, in_progress_key_prefix, jo...
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
import asyncio import logging import pickle import warnings from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Any, Callable, Dict, Optional, Tuple from redis.asyncio import Redis from .constants import abort_jobs_ss, default_queue_name, in_progress_key_prefix, jo...
): 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
import asyncio import logging import pickle import warnings from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Any, Callable, Dict, Optional, Tuple from redis.asyncio import Redis from .constants import abort_jobs_ss, default_queue_name, in_progress_key_prefix, jo...
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
package machineconfig import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "path/filepath" "text/template" "github.com/openshift-kni/performance-addon-operators/build/assets" "github.com/coreos/go-systemd/unit" igntypes "github.com/coreos/ignition/v2/config/v3_2/types" metav1 "k8s.io/apima...
// GetMachineConfigName generates machine config name from the performance profile func GetMachineConfigName(profile *performancev2.PerformanceProfile) string { name := components.GetComponentName(profile.Name, components.ComponentNamePrefix) return fmt.Sprintf("50-%s", name) } func getIgnitionConfig(profile *perf...
{ 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
package machineconfig import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "path/filepath" "text/template" "github.com/openshift-kni/performance-addon-operators/build/assets" "github.com/coreos/go-systemd/unit" igntypes "github.com/coreos/ignition/v2/config/v3_2/types" metav1 "k8s.io/apima...
(hugepagesSize string, hugepagesCount int32, numaNode int32) []*unit.UnitOption { return []*unit.UnitOption{ // [Unit] // Description unit.NewUnitOption(systemdSectionUnit, systemdDescription, fmt.Sprintf("Hugepages-%skB allocation on the node %d", hugepagesSize, numaNode)), // Before unit.NewUnitOption(syst...
GetHugepagesAllocationUnitOptions
identifier_name
machineconfig.go
package machineconfig import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "path/filepath" "text/template" "github.com/openshift-kni/performance-addon-operators/build/assets" "github.com/coreos/go-systemd/unit" igntypes "github.com/coreos/ignition/v2/config/v3_2/types" metav1 "k8s.io/apima...
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
package machineconfig import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "path/filepath" "text/template" "github.com/openshift-kni/performance-addon-operators/build/assets" "github.com/coreos/go-systemd/unit" igntypes "github.com/coreos/ignition/v2/config/v3_2/types" metav1 "k8s.io/apima...
crioConfig := &bytes.Buffer{} if err := profileTemplate.Execute(crioConfig, templateArgs); err != nil { return nil, err } return crioConfig.Bytes(), nil }
}
random_line_split
main.go
package fuzz import ( "context" "errors" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "regexp" "strconv" "sync" "time" "github.com/RedTeamPentesting/monsoon/cli" "github.com/RedTeamPentesting/monsoon/producer" "github.com/RedTeamPentesting/monsoon/recorder" "github.com/RedTeamPentesting/monso...
{ // 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
package fuzz import ( "context" "errors" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "regexp" "strconv" "sync" "time" "github.com/RedTeamPentesting/monsoon/cli" "github.com/RedTeamPentesting/monsoon/producer" "github.com/RedTeamPentesting/monsoon/recorder" "github.com/RedTeamPentesting/monso...
} } // 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
package fuzz import ( "context" "errors" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "regexp" "strconv" "sync" "time" "github.com/RedTeamPentesting/monsoon/cli" "github.com/RedTeamPentesting/monsoon/producer" "github.com/RedTeamPentesting/monsoon/recorder" "github.com/RedTeamPentesting/monso...
(ctx context.Context, g *errgroup.Group, opts *Options, args []string) error { // 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 er...
run
identifier_name
main.go
package fuzz import ( "context" "errors" "fmt" "log" "net/http" "net/url" "os" "path/filepath" "regexp" "strconv" "sync" "time" "github.com/RedTeamPentesting/monsoon/cli" "github.com/RedTeamPentesting/monsoon/producer" "github.com/RedTeamPentesting/monsoon/recorder" "github.com/RedTeamPentesting/monso...
var maxFrameRate uint if s, ok := os.LookupEnv("MONSOON_PROGRESS_FPS"); ok { rate, err := strconv.ParseUint(s, 10, 32) if err != nil { return fmt.Errorf("parse $MONSOON_PROGRESS_FPS: %w", err) } maxFrameRate = uint(rate) } term, cleanup, err := setupTerminal(ctx, g, maxFrameRate, logfilePrefix) defer...
{ return err }
conditional_block
resp.go
/* Copyright 2019 yametech. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
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
/* Copyright 2019 yametech. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
(f float64) Value { return StringValue(strconv.FormatFloat(f, 'f', -1, 64)) } // ArrayValue returns a RESP array. func ArrayValue(vals []Value) Value { return Value{Typ: '*', ArrayV: vals} } func formSingleLine(s string) string { bs1 := []byte(s) for i := 0; i < len(bs1); i++ { switch bs1[i] { case '\r', '\n': ...
FloatValue
identifier_name