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 |
|---|---|---|---|---|
call.rs | let fn_name = methods.iter().map(|method| &method.name).collect::<Vec<_>>();
let call_index = methods.iter().map(|method| method.call_index).collect::<Vec<_>>();
let new_call_variant_fn_name = fn_name
.iter()
.map(|fn_name| quote::format_ident!("new_call_variant_{}", fn_name))
.collect::<Vec<_>>();
let new_c... | {
let (span, where_clause, methods, docs) = match def.call.as_ref() {
Some(call) => {
let span = call.attr_span;
let where_clause = call.where_clause.clone();
let methods = call.methods.clone();
let docs = call.docs.clone();
(span, where_clause, methods, docs)
},
None => (def.item.span(), def.con... | identifier_body | |
call.rs | (def: &mut Def) -> proc_macro2::TokenStream {
let (span, where_clause, methods, docs) = match def.call.as_ref() {
Some(call) => {
let span = call.attr_span;
let where_clause = call.where_clause.clone();
let methods = call.methods.clone();
let docs = call.docs.clone();
(span, where_clause, methods, do... | expand_call | identifier_name | |
call.rs | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{
pallet::{
parse::call::{CallVariantDef, CallWeightDef},
Def,
},
COUNTER,
};
use proc_macro2::TokenStream as TokenStrea... | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, | random_line_split | |
server.js | and set the default language and text dir for arabic
const languages = require('./languages.js');
let language = 'arabic';
let text = languages[language];
let dir = 'rtl';
// object for the redirects pages
const langRedirects = {
'/addvolunteer': 'list',
'/orgform': 'login',
'/addrole': 'login'
};
// set the po... | // render form with error data and already filled in inputs
res.render('form', {
role: data,
error: errors,
prefilled: prefilled,
headline: text.formHeader
});
db.close();
});
}
});
} else... | const prefilled = [req.body]; | random_line_split |
crawler_sina.go | }
func getSinaFailedQueue(value string) string {
v, _ := global.RD.GetSETRandStringRm(SINA_SPIDER_FAILED)
return v
}
func checkSinaFailedQueue(value string) bool {
x, _ := global.RD.CheckSETString(SINA_SPIDER_FAILED, value)
return x > 0
}
func addSinaDataQueue(value map[string]interface{}) {
b, err := json.Marsha... | return x > 0
}
func addSinaFailedQueue(value string) {
global.RD.SetSETString(SINA_SPIDER_FAILED, value) | random_line_split | |
crawler_sina.go | global.RD.GetSETRandStringRm(SINA_SPIDER_DATA)
}
func getSinaData() map[string]interface{} {
d, err := getSinaDataQueue()
if err != nil {
global.Log.Warning("无数据", err.Error())
return nil
}
if d != "" {
m := map[string]interface{}{}
err = json.Unmarshal([]byte(d), &m)
if err == nil {
return m
}
}
... |
_, err := global.DB.InsertMap("sina_user_base_info", m)
if err != nil {
global.Log.Error("sina_user_base_info 数据保存失败:", err.Error())
} else {
if weibos != nil {
wb, err := convert.Obj2ListMap(weibos)
if err != nil {
global.Log.Error("weibo 数据转换[]map失败:", err.Error())
} el... | rt.ToString(m["desc"]) != "" {
m["mydesc"] = m["desc"]
}
delete(m, "desc") | identifier_body |
crawler_sina.go | 2, _ := a2.GetAttribute("href")
if href != "" {
getUserHref(href)
}
if href2 != "" {
getUserHref(href2)
}
}
}
}
func getUserHref(href string) {
if href != "" {
println("待抓url:", href)
global.Page.Navigate(href)
} else {
println("点击操作项")
}
eles, err := global.Page.Find(".follow_list").A... | tail
} else if strings.Contains(title, "性别") {
| conditional_block | |
crawler_sina.go | global.RD.GetSETRandStringRm(SINA_SPIDER_DATA)
}
func getSinaData() map[string]interface{} {
d, err := getSinaDataQueue()
if err != nil {
global.Log.Warning("无数据", err.Error())
return nil
}
if d != "" {
m := map[string]interface{}{}
err = json.Unmarshal([]byte(d), &m)
if err == nil {
return m
}
}
... | )
driver := agouti.ChromeDriver(agouti.ChromeOptions("args", []string{
"--start-maximized",
"--disable-infobars",
"--app=https://weibo.com/",
"--webkit-text-size-adjust"}))
driver.Start()
var err error
global.Page.Page, err = driver.NewPage()
if err != nil {
global.Log.Info(err.Error())
} else {
flog,... | ata( | identifier_name |
encoding.py | u"ed25519 signature"),
(b"spsig", 99, tb([13, 115, 101, 19, 63]), 64, u"secp256k1 signature"),
(b"p2sig", 98, tb([54, 240, 44, 52]), 64, u"p256 signature"),
(b"sig", 96, tb([4, 130, 43]), 64, u"generic signature"),
(b'Net', 15, tb([87, 82, 0]), 4, ... |
for bin_prefix, tz_prefix in tz_prefixes.items():
if data.startswith(bin_prefix): | random_line_split | |
encoding.py | 240, 44, 52]), 64, u"p256 signature"),
(b"sig", 96, tb([4, 130, 43]), 64, u"generic signature"),
(b'Net', 15, tb([87, 82, 0]), 4, u"chain id"),
]
operation_tags = {
'endorsement': 0,
'seed_nonce_revelation': 1,
'double_endorsement_evidence': 2,
'd... | """ Decode address or key_hash from bytes.
:param data: encoded address or key_hash
:returns: base58 encoded address
"""
tz_prefixes = {
b'\x00\x00': b'tz1',
b'\x00\x01': b'tz2',
b'\x00\x02': b'tz3'
}
for bin_prefix, tz_prefix in tz_prefixes.items():
if data.sta... | identifier_body | |
encoding.py | Base58 with checksum + validate binary prefix against known kinds and cut in the end.
:param v: Array of bytes (use string.encode())
:returns: bytes
"""
try:
prefix_len = next(
len(encoding[2])
for encoding in base58_encodings
if len(v) == encoding[1] and v.... | forge_base58 | identifier_name | |
encoding.py | 256k1 scalar"),
(b"GSp", 53, tb([5, 92, 0]), 33, u"secp256k1 element"),
(b"edsk", 98, tb([43, 246, 78, 7]), 64, u"ed25519 secret key"),
(b"edsig", 99, tb([9, 245, 205, 134, 18]), 64, u"ed25519 signature"),
(b"spsig", 99, tb([13, 115, 101, 19, 63]), 64, u"sec... | res = b'\x01' + address + b'\x00' | conditional_block | |
blockSelection.ts |
*
* @private
*/
private anyBlockSelectedCache: boolean | null = null;
/**
* Sanitizer Config
*
* @returns {SanitizerConfig}
*/
private get | (): SanitizerConfig {
return {
p: {},
h1: {},
h2: {},
h3: {},
h4: {},
h5: {},
h6: {},
ol: {},
ul: {},
li: {},
br: true,
img: {
src: true,
width: true,
height: true,
},
a: {
href: true,
},
... | sanitizerConfig | identifier_name |
blockSelection.ts | @returns {SanitizerConfig}
*/
private get sanitizerConfig(): SanitizerConfig {
return {
p: {},
h1: {},
h2: {},
h3: {},
h4: {},
h5: {},
h6: {},
ol: {},
ul: {},
li: {},
br: true,
img: {
src: true,
width: true,
height... | * Second cmd+a will select whole Block | random_line_split | |
blockSelection.ts |
*
* @private
*/
private anyBlockSelectedCache: boolean | null = null;
/**
* Sanitizer Config
*
* @returns {SanitizerConfig}
*/
private get sanitizerConfig(): SanitizerConfig {
return {
p: {},
h1: {},
h2: {},
h3: {},
h4: {},
h5: {},
h6: {},
... | .join('\n\n');
const textHTML = fakeClipboard.innerHTML;
e.clipboardData.setData('text/plain', textPlain);
e.clipboardData.setData('text/html', textHTML);
return Promise
.all(this.selectedBlocks.map((block) => block.save()))
.then(savedData => {
try {
e.clipboardDat... | {
/**
* Prevent default copy
*/
e.preventDefault();
const fakeClipboard = $.make('div');
this.selectedBlocks.forEach((block) => {
/**
* Make <p> tag that holds clean HTML
*/
const cleanHTML = clean(block.holder.innerHTML, this.sanitizerConfig);
const fragment ... | identifier_body |
blockSelection.ts | br: true,
img: {
src: true,
width: true,
height: true,
},
a: {
href: true,
},
b: {},
i: {},
u: {},
};
}
/**
* Flag that identifies all Blocks selection
*
* @returns {boolean}
*/
public get allBlocksSelected(): boolean {
... | {
this.needToSelectAll = true;
return;
} | conditional_block | |
day13.rs | //! Your notes (your puzzle input) consist of two lines. The first line is your
//! estimate of **the earliest timestamp you could depart on a bus**. The second
//! line lists the bus IDs that are in service according to the shuttle company;
//! entries that show `x` must be out of service, so you decide to ignore them... | (input: &str) -> (usize, Vec<Bus>) {
let mut it = input.lines();
let first_line = it.next().unwrap();
let second_line = it.next().unwrap();
let depart_time = first_line.parse::<usize>().unwrap();
let shuttles = second_line
.split(',')
.enumerate()
.filter_map(|(serial, x)| {... | parse_input | identifier_name |
day13.rs | . . . .
//! 930 . . . D .
//! 931 D . . . D
//! 932 . . . . .
//! 933 . . . . .
//! 934 . . . . .
//! 935 . . . . .
//! 936 ... | {
n += 1;
} | conditional_block | |
day13.rs | //!
//! Your notes (your puzzle input) consist of two lines. The first line is your
//! estimate of **the earliest timestamp you could depart on a bus**. The second
//! line lists the bus IDs that are in service according to the shuttle company;
//! entries that show `x` must be out of service, so you decide to ignore ... | //!
//! ```
//! time bus 7 bus 13 bus 59 bus 31 bus 19
//! 929 . . . . .
//! 930 . . . D .
//! 931 D . . . D
//! 932 . . . . .
//! 933 . . . . .
//! 934 . . ... | //!
//! Here, the earliest timestamp you could depart is `939`, and the bus IDs in
//! service are `7`, `13`, `59`, `31`, and `19`. Near timestamp `939`, these bus
//! IDs depart at the times marked `D`: | random_line_split |
day13.rs | for anyone that can
//! find the earliest timestamp such that the first bus ID departs at that time
//! and each subsequent listed bus ID departs at that subsequent minute. (The
//! first line in your input is no longer relevant.)
//!
//! For example, suppose you have the same list of bus IDs as above:
//!
//! `7,13,x... | {
let earliest = clac_contest(&TEST_ARRAY);
assert_eq!(earliest, 1068781);
} | identifier_body | |
parser.go | екс"`
Alias string `xml:"Псевдоним"`
CryptoClass string `xml:"КлассСредствЭП"`
PakAddress CenterAddress `xml:"Адрес"`
CryptoVersion string `xml:"СредстваУЦ"`
Keys []Key `xml:"КлючиУполномоченныхЛиц>Ключ"`
}
//Key структура содержащая информацию о Ключе СКЗИ
type ... | () == "exit status 45" {
fmt.Printf("error:%3scrl not valid:%s\n", " ", *cert)
return errors.New("CRLNVAL")
}
}
defer os.Remove(file)
return nil
}
/* func dumpUcsFingerptints(root *UcRoot, fingerFile *os.File) {
for _, uc := range root.Centers {
for _, pak := range uc.PAKs {
for _, key := range pak.Ke... | rr.Error | identifier_name |
parser.go | + cert.Footprint)
if err := installCertToContainer(&cert.CertData); err != nil {
panic(err)
}
fingerFile.WriteString(string(cert.Footprint) + "\n")
fmt.Printf("%-90sinstalled\n", string(cert.Serial))
}
}
}
}
}
func installCertToContainer(cert *[]byte) error {
file, _ := makeTemp... | гли сохранить временный файл со списком УЦ", err.Error())
}
ucListFile = "/tmp/__certParserTmp__uc_list"
*list = ucListFile
return ucListFile
}
*list = ucListFile
return ucListFile
}
*/
func main() {
runtime.GOMAXPROCS(2)
//loadOver | identifier_body | |
parser.go | екс"`
Alias string `xml:"Псевдоним"`
CryptoClass string `xml:"КлассСредствЭП"`
PakAddress CenterAddress `xml:"Адрес"`
CryptoVersion string `xml:"СредстваУЦ"`
Keys []Key `xml:"КлючиУполномоченныхЛиц>Ключ"`
}
//Key структура содержащая информацию о Ключе СКЗИ
type ... |
}
func installCertToContainer(cert *[]byte) error {
file, _ := makeTemp(cert)
cmd := exec.Command("/opt/cprocsp/bin/amd64/certmgr", "-inst", "-store=mRoot", "--file="+file)
if err := cmd.Run(); err != nil {
panic(err)
}
cmd = exec.Command("/opt/cprocsp/bin/amd64/certmgr", "-inst", "-store=mCA", "--file="+file... | }
}
} | random_line_split |
parser.go | procsp/bin/amd64/cryptcp", "-verify", "-errchain", "-f", certPath, certPath)
//var stderr bytes.Buffer
var stdout bytes.Buffer
//cmd.Stderr = &stderr
cmd.Stdout = &stdout
cmd.Run()
/*if err != nil {
log.Fatal(stderr.String())
return
}*/
fmt.Println(stdout.String())
}
func makeListInstalledCerts(listCaPath ... | log.Fatal("Cannot create fil | conditional_block | |
samplesheet.rs | entries: Vec::new(),
}
}
pub fn from_xlsx(xlsx: &str, db: &PgConnection) -> Result<Self> {
// open Excel workbook
let mut ss: Xlsx<_> = open_workbook(xlsx)?;
let sheetname = ss.sheet_names()[0].clone();
let sheet = ss.worksheet_range(&sheetname).unwrap()?;
... |
let basic_header = vec!["Sample", "run", "DNA nr", "primer set", "project", "LIMS ID", "cells"];
// extra_cols hashmap is not necessarily fully populated for every sample, so check all
let mut all_headers: Vec<String> = self.entries
.iter()
.map::<Vec<S... | identifier_body | |
samplesheet.rs | r.split('-').collect();
if parts.len() != 2 {
return None;
}
Some(format!(
"{:02}-{:05}",
parts[0].parse::<u32>().unwrap(),
parts[1].parse::<u32>().unwrap()
))
}
impl SampleSheetEntry {
pub fn _run_path(&self, db: &PgConnection) -> Result<PathBuf> {
use crat... | }
}
fn extract_from_zip(path: &Path, fastqs: &[String], targetdir: &Path, sample_prefix: Option<String>) -> Result<()> {
let zipfile = std::fs::File::open(path)?;
let mut zip = zip::ZipArchive::new(zipfile)?;
let prefix = sample_prefix.unwrap_or_else(|| String::from(""));
for f in fastqs {
... | SampleSheet {
entries: ss.into_iter().map(|s| s.into()).collect()
} | random_line_split |
samplesheet.rs | r.split('-').collect();
if parts.len() != 2 {
return None;
}
Some(format!(
"{:02}-{:05}",
parts[0].parse::<u32>().unwrap(),
parts[1].parse::<u32>().unwrap()
))
}
impl SampleSheetEntry {
pub fn _run_path(&self, db: &PgConnection) -> Result<PathBuf> {
use crat... | &self, db: &PgConnection) -> Result<Vec<String>> {
use crate::schema::fastq;
Ok(fastq::table.select(fastq::filename).filter(fastq::sample_id.eq(self.model.id)).load(db)?)
}
// generate a short but unique string representation of the run
// to keep samples with same characteristics in differ... | astq_paths( | identifier_name |
samplesheet.rs | = col_sample.map(|col| row[col].to_string());
let primer_set = col_primer_set.map(|col| row[col].to_string());
let lims_id = col_lims_id.map(|col| row[col].to_string().parse::<i64>().ok()).flatten();
let dna_nr = col_dna_nr.map(|col| row[col].to_string());
l... | e.model.dna_nr.as_ref().map(|s| s.clone()).unwrap_or(String::from("")) }, | conditional_block | |
mainwindow.py |
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from praxes.io import phynx
#logger = logging.getLogger(__file__)
class MainWindow(QtGui.QMainWindow):
"""
"""
def __init__(self, log_level=logging.CRITICAL, parent=None):
super(MainWindow, self... |
return self.fileModel.openFile(newfilename)
def toolActionTriggered(self):
self.statusBar.showMessage('Configuring...')
action = self.sender()
if action is not None and isinstance(action, QtGui.QAction):
tool = self._toolActions[action](self._currentItem, self)
... | newfilename = newfilename + '.h5' | conditional_block |
mainwindow.py |
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from praxes.io import phynx
#logger = logging.getLogger(__file__)
class MainWindow(QtGui.QMainWindow):
"""
"""
def __init__(self, log_level=logging.CRITICAL, parent=None):
super(MainWindow, self... | (self):
self.openFile()
@QtCore.pyqtSignature("bool")
def on_actionSpec_toggled(self, bool):
self.connectToSpec(bool)
def connectToSpec(self, bool):
if bool:
from praxes.instrumentation.spec.specinterface import ConnectionAborted
try:
from p... | on_actionOpen_triggered | identifier_name |
mainwindow.py |
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from praxes.io import phynx
#logger = logging.getLogger(__file__)
class MainWindow(QtGui.QMainWindow):
"""
"""
def __init__(self, log_level=logging.CRITICAL, parent=None):
super(MainWindow, self... |
@QtCore.pyqtSignature("")
def on_actionOpen_triggered(self):
self.openFile()
@QtCore.pyqtSignature("bool")
def on_actionSpec_toggled(self, bool):
self.connectToSpec(bool)
def connectToSpec(self, bool):
if bool:
from praxes.instrumentation.spec.specinterface im... | if self.expInterface is None: return
if self.expInterface.name == 'spec':
self.connectToSpec(False) | identifier_body |
mainwindow.py |
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from praxes.io import phynx
#logger = logging.getLogger(__file__)
class MainWindow(QtGui.QMainWindow):
"""
"""
def __init__(self, log_level=logging.CRITICAL, parent=None):
super(MainWindow, self... | QtGui.QFileDialog.getSaveFileName(
self,
'Save HDF5 File',
os.path.join(os.getcwd(), f+'.h5'),
'HDF5 files (*.h5 *.hdf5 *.hdf *.nxs)'
)
)
if h5_... | h5_filename = str( | random_line_split |
lib.rs | ::{error, info, warn};
use rocksdb::{checkpoint::Checkpoint, DB};
use tokio::time::{sleep, Duration};
use std::collections::HashSet;
use std::net::ToSocketAddrs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
const KEEP_NUM: u64 = 100;
const PRUNE_INTERVAL: u64 = 1000;
const GENESIS_NUMBER: u64 = 0;
// Adapted ... | match self
.get_block_by_number(tip_number + 1, use_hex_format)
.await
{
Ok(Some(block)) => {
self.change_current_epoch(block.epoch().to_rational());
if block.parent_hash() == tip... |
let mut prune = false;
if let Some((tip_number, tip_hash)) = indexer.tip().expect("get tip should be OK") {
tip = tip_number;
| random_line_split |
lib.rs | error, info, warn};
use rocksdb::{checkpoint::Checkpoint, DB};
use tokio::time::{sleep, Duration};
use std::collections::HashSet;
use std::net::ToSocketAddrs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
const KEEP_NUM: u64 = 100;
const PRUNE_INTERVAL: u64 = 1000;
const GENESIS_NUMBER: u64 = 0;
// Adapted fro... |
fn change_current_epoch(&self, current_epoch: RationalU256) {
self.change_maturity_threshold(current_epoch.clone());
let mut epoch = CURRENT_EPOCH.write();
*epoch = current_epoch;
}
fn change_m | {
if height % self.snapshot_interval != 0 {
return;
}
let mut path = self.snapshot_path.clone();
path.push(height.to_string());
let store = self.store.clone();
tokio::spawn(async move {
if let Err(e) = create_checkpoint(store.inner(), path) {
... | identifier_body |
lib.rs | listen_address: String,
rpc_thread_num: usize,
network_type: NetworkType,
extensions_config: ExtensionsConfig,
snapshot_interval: u64,
snapshot_path: PathBuf,
cellbase_maturity: RationalU256,
cheque_since: U256,
}
impl Service {
pub fn new(
store_path: &str,
listen_addr... | handle_raw_tx_pool | identifier_name | |
raw.go | for i, mo := range m.bufferedChunk.Values {
if ascending && mo.Time > timeBoundary {
ind = i
break
} else if !ascending && mo.Time < timeBoundary {
ind = i
break
}
}
// Add up to the index to the values
if chunkedOutput == nil {
chunkedOutput = &MapperOutput{
Name:... | {
if m.drained {
continue
}
chunkBoundary := false
if ascending {
chunkBoundary = m.bufferedChunk.Values[0].Time > timeBoundary
} else {
chunkBoundary = m.bufferedChunk.Values[0].Time < timeBoundary
}
// This mapper's next chunk is not for the next tagset, or the very first value of
... | conditional_block | |
raw.go | // Add up to the index to the values
if chunkedOutput == nil {
chunkedOutput = &MapperOutput{ | chunkedOutput.Values = m.bufferedChunk.Values[:ind]
} else {
chunkedOutput.Values = append(chunkedOutput.Values, m.bufferedChunk.Values[:ind]...)
}
// Clear out the values being sent out, keep the remainder.
m.bufferedChunk.Values = m.bufferedChunk.Values[ind:]
// If we emptied out all the valu... | Name: m.bufferedChunk.Name,
Tags: m.bufferedChunk.Tags,
CursorKey: m.bufferedChunk.key(),
} | random_line_split |
raw.go | .Expr.(*influxql.BinaryExpr); ok {
hasMath = true
} else if _, ok := f.Expr.(*influxql.ParenExpr); ok {
hasMath = true
}
}
if !hasMath {
return results
}
processors := make([]influxql.Processor, len(fields))
startIndex := 1
for i, f := range fields {
processors[i], startIndex = influxql.GetProcess... | { return append(m.selectFields, m.selectTags...) } | identifier_body | |
raw.go | (closing <-chan struct{}) <-chan *models.Row {
out := make(chan *models.Row, 0)
go e.execute(out, closing)
return out
}
func (e *RawExecutor) execute(out chan *models.Row, closing <-chan struct{}) {
// It's important that all resources are released when execution completes.
defer e.close()
// Open the mappers.
... | Execute | identifier_name | |
hcrml_parser.py | _filename()
# For output type 'hcr', write the binary repository file
if self.output_obj.type == 'hcr':
self.logger.info("Generating binary repository to '%s'" % outputfile)
writer = HcrWriter()
repo = self.output_obj.get_hcr_repository()
data = writ... |
def read_hcrml_setting(self,setting_elem):
ref = setting_elem.get('ref')
if ref == None or ref == '':
raise NoRefInHcrmlFileError("No ref in setting tag attribute implemented in hcrml file!")
else:
self.refs.append(ref)
type =... | category_uid = cat_elem.get('uid')
if category_uid == None or category_uid == '':
raise NoCategoryUIDInHcrmlFileError("No category uid attribute implemented in hcrml file!")
name = cat_elem.get('name')
if name == None or name == '':
raise NoCategoryNameInHcrmlFileError... | identifier_body |
hcrml_parser.py | def read_hcrml_output(self, ignore_includes=False):
output = Output()
# There should only be one <output> element, so use find()
out_elem = self.doc.find("{%s}output" % self.namespaces[0])
if out_elem != None:
version = out_elem.get('version')
rea... | __init__ | identifier_name | |
hcrml_parser.py | raise NoTypeDefinedInOutPutTagError("Type attribute missing in hcrml file")
if type not in ('hcr', 'header'):
raise InvalidTypeDefinedInOutPutTagError("Type attribute invalid in hcrml file: %s" % type)
output.version = version
output.re... | return result
def get_hcr_repository(self):
"""
Return a HcrRepository object created based on this output.
| random_line_split | |
hcrml_parser.py | mlImpl(resource_ref, configuration)
impl.output_obj = reader.read_hcrml_output()
impl.refs = reader.refs
return impl
@classmethod
def get_schema_data(cls):
return pkg_resources.resource_string('hcrplugin', 'xsd/hcrml.xsd')
def read_hcrml_output(self, ignore... | record.flags |= HcrRecord.FLAG_UNINITIALIZED | conditional_block | |
beerData.js | ['4.5 out of 7', 'Oatmeal Stout', '6%', '★ ★', 'beer4', 'A full-bodied oatmeal milk stout that starts off with a mild roasty flavor and smoothly transitions into sweet, cream and luscious.'],
// ['(512) Pecan Porter', 'Brown Porter', '6.8%', 30, 'coldsunny4'],
['(512) Pecan Porter',... | ['"Tractor Beam" Oatmeal Stout', 'Oatmeal Stout', '5.8%', '★ ★', 'beer4', 'No Description Provided'],
// ["48er's Porter", 'Brown Porter', '5.9%', 31, 'coldsunny5'],
["48er's Porter", 'Brown Porter', '5.9%', '★ ★', 'beer3', 'Flavor/Balance: Named after a group of Germans who settled... | random_line_split | |
stream_mock_test.go | .Itoa(id),
DiskHeartBeatInfo: blobnode.DiskHeartBeatInfo{DiskID: proto.DiskID(id)},
}
}
for _, id := range idcOtherID {
dataDisks[proto.DiskID(id)] = blobnode.DiskInfo{
ClusterID: clusterID, Idc: idcOther, Host: strconv.Itoa(id),
DiskHeartBeatInfo: blobnode.DiskHeartBeatInfo{DiskID: proto.DiskID(id)},
... | getBufSizes | identifier_name | |
stream_mock_test.go | )
blobSize = 1 << 22
streamer *Handler
memPool *resourcepool.MemPool
encoder map[codemode.CodeMode]ec.Encoder
proxyClient proxy.Client
allCodeModes CodeModePairs
cmcli clustermgr.APIAccess
volumeGetter controller.VolumeGetter
serviceController controller.ServiceController
cc ... |
if vuidController.Isblocked(args.Vuid) {
vuidController.block()
if rand.Intn(2) == 0 {
err = errors.New("get shard timeout")
} else {
err = errors.New("get shard Timeout")
}
return
}
buff := dataShards.get(args.Vuid, args.Bid)
if len(buff) == 0 {
return nil, 0, errNotFound
}
if len(buff) < int... | {
err = errors.New("get shard fake error")
if vuidController.IsBNRealError() {
err = randBlobnodeRealError(getErrors)
}
return
} | conditional_block |
stream_mock_test.go | )
blobSize = 1 << 22
streamer *Handler
memPool *resourcepool.MemPool
encoder map[codemode.CodeMode]ec.Encoder
proxyClient proxy.Client
allCodeModes CodeModePairs
cmcli clustermgr.APIAccess
volumeGetter controller.VolumeGetter
serviceController controller.ServiceController
cc ... | units = append(units, clustermgr.Unit{
Vuid: proto.Vuid(id),
DiskID: proto.DiskID(id),
Host: strconv.Itoa(id),
})
}
return
}(),
}}
proxyNodes := make([]clustermgr.ServiceNode, 32)
for idx := range proxyNodes {
proxyNodes[idx] = clustermgr.ServiceNode{
ClusterID: 1,
Name: ... | {
dataAllocs = make([]proxy.AllocRet, 2)
dataAllocs[0] = proxy.AllocRet{
BidStart: 10000,
BidEnd: 10000,
Vid: volumeID,
}
dataAllocs[1] = proxy.AllocRet{
BidStart: 20000,
BidEnd: 50000,
Vid: volumeID,
}
dataVolume = &proxy.VersionVolume{VolumeInfo: clustermgr.VolumeInfo{
VolumeInfoBas... | identifier_body |
stream_mock_test.go | idc = "test-idc"
idcOther = "test-idc-other"
allID = []int{1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012}
idcID = []int{1001, 1002, 1003, 1007, 1008, 1009}
idcOtherID = []int{1004, 1005, 1006, 1010, 1011, 1012}
clusterID = proto.ClusterID(1)
volumeID = proto.Vid(1)
... |
allocTimeoutSize uint64 = 1 << 40
punishServiceS = 1
minReadShardsX = 5
| random_line_split | |
stopper.go |
// the provided panic handler.
//
// When Stop() is invoked during stack unwinding, OnPanic is also invoked, but
// Stop() may not have carried out its duties.
func OnPanic(handler func(interface{})) Option {
return optionPanicHandler(handler)
}
// NewStopper returns an instance of Stopper.
func NewStopper(options .... | {
var lines []string
for location, num := range tm {
lines = append(lines, fmt.Sprintf("%-6d %s", num, location))
}
sort.Sort(sort.Reverse(sort.StringSlice(lines)))
return strings.Join(lines, "\n")
} | identifier_body | |
stopper.go | .mu.Unlock()
}
}
// Closer is an interface for objects to attach to the stopper to
// be closed once the stopper completes.
type Closer interface {
Close()
}
// CloserFn is type that allows any function to be a Closer.
type CloserFn func()
// Close implements the Closer interface.
func (f CloserFn) Close() {
f()
... |
// Call f.
defer s.Recover(ctx)
defer s.runPostlude(taskName)
return f(ctx)
}
// RunAsyncTask is like RunTask, except the callback is run in a goroutine. The
// method doesn't block for the callback to finish execution.
func (s *Stopper) RunAsyncTask(
ctx context.Context, taskName string, f func(context.Contex... | {
return errUnavailable
} | conditional_block |
stopper.go | "github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/util/caller"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/opentracing/opentracing-go"
)
const asyncTaskName... |
"github.com/cockroachdb/cockroach/pkg/roachpb" | random_line_split | |
stopper.go | .mu.Unlock()
}
}
// Closer is an interface for objects to attach to the stopper to
// be closed once the stopper completes.
type Closer interface {
Close()
}
// CloserFn is type that allows any function to be a Closer.
type CloserFn func()
// Close implements the Closer interface.
func (f CloserFn) Close() {
f()
... | (
ctx context.Context, cancels map[int]func(), cancelCh chan struct{},
) (context.Context, func()) {
var cancel func()
ctx, cancel = context.WithCancel(ctx)
s.mu.Lock()
defer s.mu.Unlock()
select {
case <-cancelCh:
// Cancel immediately.
cancel()
return ctx, func() {}
default:
id := s.mu.idAlloc
s.mu.... | withCancel | identifier_name |
pdd.go | // panic(err)
//}
//return p
}
func (self *Pdd)addSign(u *url.Values){
u.Set("client_id",self.Info.Client_id)
u.Set("timestamp",fmt.Sprintf("%d",time.Now().Unix()))
var li []string
for k,_ := range *u {
li = append(li,k)
}
sort.Strings(li)
sign := self.Info.Client_secret
for _,k :=range li {
sign+=k+u.... | {
j :=&Pdd{Info:sh}
//go func(){
// for _ = range j.DownChan{
// j.OrderDownSelf(func(db interface{}){
// err := OrderUpdate(db.(map[string]interface{})["order_id"].(string),db)
// if err != nil {
// fmt.Println(err)
// }
// })
// }
//}()
return j
//if !o {
// return p
//}
//var err error
/... | identifier_body | |
pdd.go | var err error
err = request.ClientHttp_(
PddUrl+"?"+u.Encode(),
"GET",nil,
nil,
func(body io.Reader,start int)error{
if start != 200 {
db,err := ioutil.ReadAll(body)
if err!= nil {
return err
}
return fmt.Errorf("%s",db)
}
return json.NewDecoder(body).Decode(&out)
})
if err != nil {
... | }
pid := (req.(map[string]interface{})["p_id_query_response"]).(map[string]interface{})
if pid["total_count"].(float64) >0 {
for _,p_ := range pid["p_id_list"].([]interface{}){
self.PddPid = append(self.PddPid,(p_.(map[string]interface{})["p_id"]).(string))
}
return nil
}
req = self.pidGenerate(1)
switch... | switch r := req.(type){
case error:
return r | random_line_split |
pdd.go | err error
err = request.ClientHttp_(
PddUrl+"?"+u.Encode(),
"GET",nil,
nil,
func(body io.Reader,start int)error{
if start != 200 {
db,err := ioutil.ReadAll(body)
if err!= nil {
return err
}
return fmt.Errorf("%s",db)
}
return json.NewDecoder(body).Decode(&out)
})
if err != nil {
fmt.... | () interface{}{
u := &url.Values{}
u.Add("type","pdd.ddk.goods.pid.query")
return self.ClientHttp(u)
}
func (self *Pdd)GoodsAppMini(words ...string)interface{}{
goodsid := words[0]
if len(self.PddPid) == 0 {
err := self.getPid()
if err != nil {
return err
}
}
u := &url.Values{}
u.Add("type","pdd.ddk.go... | pidQuery | identifier_name |
pdd.go | ]...)
// u.Add("generate_we_app","true")
//}
//if multi{
u.Add("multi_group","true")
if len(words)>1 {
u.Add("custom_parameters",words[1])
}
//}
db := self.ClientHttp(u)
res := db.(map[string]interface{})["goods_promotion_url_generate_response"]
if res == nil {
return nil
}
res_ := res.(map[string]inter... | t64(l_["order_receive_time"].(float64))
var ver time.Time
if l_["order_verify_time"] == nil {
ver = time.Unix(int64(l_["order_receive_time"].(float64)),0)
}else{
ver = time.Unix(int64(l_["order_verify_time"].(float64)),0)
}
y,m,d := ver.Date()
if d >15{
y,m,_ = ver.AddDat... | conditional_block | |
main.rs | and the handles to the interrupts.
fn get_int_method(
pcid_handle: &mut PcidServerHandle,
function: &PciFunction,
allocated_bars: &AllocatedBars,
) -> Result<(InterruptMethod, InterruptSources)> {
log::trace!("Begin get_int_method");
use pcid_interface::irq_helpers;
let features = pcid_handle.... | () {
// Daemonize
if unsafe { syscall::clone(CloneFlags::empty()).unwrap() } != 0 {
return;
}
let _logger_ref = setup_logging();
let mut pcid_handle =
PcidServerHandle::connect_default().expect("nvmed: failed to setup channel to pcid");
let pci_config = pcid_handle
.fet... | main | identifier_name |
main.rs | and the handles to the interrupts.
fn get_int_method(
pcid_handle: &mut PcidServerHandle,
function: &PciFunction,
allocated_bars: &AllocatedBars,
) -> Result<(InterruptMethod, InterruptSources)> {
log::trace!("Begin get_int_method");
use pcid_interface::irq_helpers;
let features = pcid_handle.... |
Err(error) => {
eprintln!("nvmed: failed to set default logger: {}", error);
None
}
}
}
fn main() {
// Daemonize
if unsafe { syscall::clone(CloneFlags::empty()).unwrap() } != 0 {
return;
}
let _logger_ref = setup_logging();
let mut pcid_handle ... | {
eprintln!("nvmed: enabled logger");
Some(logger_ref)
} | conditional_block |
main.rs | and the handles to the interrupts.
fn get_int_method(
pcid_handle: &mut PcidServerHandle,
function: &PciFunction,
allocated_bars: &AllocatedBars,
) -> Result<(InterruptMethod, InterruptSources)> {
log::trace!("Begin get_int_method");
use pcid_interface::irq_helpers;
let features = pcid_handle.... |
let bsp_cpu_id =
irq_helpers::read_bsp_apic_id().expect("nvmed: failed to read APIC ID");
let bsp_lapic_id = bsp_cpu_id
.try_into()
.expect("nvmed: BSP local apic ID couldn't fit inside u8");
let (vector, irq_handle) = irq_helpers::all... | use msi_x86_64::DeliveryMode;
use pcid_interface::msi::x86_64 as msi_x86_64;
let entry: &mut MsixTableEntry = &mut table_entries[0]; | random_line_split |
layout.py | " if y%2 == 0 else "VDD", y*self.row_height)
for y in range(self.num_words+3)
]
# Assemble the columns of the memory, which consist of bit arrays,
# welltaps, and the address decoder.
# Lower and upper bits.
lower_bits = [
Inst(
self, self.bitarray_cell,
"XBA%d" % i,
Vec(0, 0),
mx=True... | flip = wt.pos.x < self.addrdec.pos.x + 0.5*addrdec_width
x = wt.pos.x + welltap_width if flip else wt.pos.x
self.wiring.append(Inst(
self, self.welltap_bwire_cell, wt.name+"WB",
Vec(
x,
wt.pos.y + (self.num_words+2) * self.row_height
),
mx=flip,
my=True
))
# Gather ... | conditional_block | |
layout.py | , self.inst.size.y - 0.05e-6)
yield (self.inst.to_world(a), self.inst.to_world(b))
class Inst(object):
def __init__(self, layout, cell, name, pos, mx=False, my=False, index=None, size=None, stack=None, stack_step=None, stack_noflip=False, data=dict()):
super(Inst, self).__init__()
self.layout = layout
self.... | (columns):
x = 0
for col in columns:
col.pos.x = (x + col.size.x if col.mx else x)
x += col.size.x
return x
class Layout(object):
def __init__(self, macro):
super(Layout, self).__init__()
self.macro = macro
self.cells = list()
self.num_addr = macro.num_addr
self.num_bits = macro.num_bits
self.num_... | layout_columns | identifier_name |
layout.py | , self.inst.size.y - 0.05e-6)
yield (self.inst.to_world(a), self.inst.to_world(b))
class Inst(object):
def __init__(self, layout, cell, name, pos, mx=False, my=False, index=None, size=None, stack=None, stack_step=None, stack_noflip=False, data=dict()):
super(Inst, self).__init__()
self.layout = layout
self.... | cells = self.config["cells"]
self.rwckg_cell = Cell("rwckg", cells["rwckg"])
self.addrdec_cell = Cell("addrdec", cells["addrdec"], suffix=str(self.num_words))
self.bitarray_cell = Cell("bitarray", cells["bitarray"], suffix=str(self.num_words))
self.rareg_cell = Cell("rareg", cells["rareg"])
self.rareg_vwire... | def __init__(self, macro):
super(Layout, self).__init__()
self.macro = macro
self.cells = list()
self.num_addr = macro.num_addr
self.num_bits = macro.num_bits
self.num_words = 2**self.num_addr
self.name = "PS%dX%d" % (self.num_words, self.num_bits)
self.wiring = list()
with open(macro.techdir+"/config... | identifier_body |
layout.py | _cell,
"XBA%d" % i,
Vec(0, 0),
mx=True,
index=i,
size=bitarray_size
)
for i in range(self.num_bits_left)
]
upper_bits = [
Inst(
self, self.bitarray_cell,
"XBA%d" % (i + self.num_bits_left),
Vec(0, 0),
index=i + self.num_bits_left,
size=bitarray_size
)
for i in ... | self.wiring.append(Inst(
self, self.rareg_hwire_b_cell, wt.name+"WRAB",
Vec(x,t), | random_line_split | |
develop.ts | building index.html`, {})
indexHTMLActivity.start()
const directory = program.directory
const directoryPath = withBasePath(directory)
const workerPool = WorkerPool.create()
const createIndexHtml = async (activity: ActivityTracker): Promise<void> => {
try {
await buildHTML({
program,
... | schemaComposer: schemaCustomization.composer,
context: {},
customContext: schemaCustomization.context,
}),
customFormatErrorFn(err): unknown {
return {
...formatError(err),
stack: err.stack ? err.stack.split(`\n`) : [],
... | schema,
graphiql: false,
context: withResolverContext({
schema, | random_line_split |
develop.ts | index.html`, {})
indexHTMLActivity.start()
const directory = program.directory
const directoryPath = withBasePath(directory)
const workerPool = WorkerPool.create()
const createIndexHtml = async (activity: ActivityTracker): Promise<void> => {
try {
await buildHTML({
program,
stage: B... | ,
}
}
)
)
/**
* Refresh external data sources.
* This behavior is disabled by default, but the ENABLE_GATSBY_REFRESH_ENDPOINT env var enables it
* If no GATSBY_REFRESH_TOKEN env var is available, then no Authorization header is required
**/
const REFRESH_ENDPOINT = `/__refresh`
co... | {
return {
...formatError(err),
stack: err.stack ? err.stack.split(`\n`) : [],
}
} | identifier_body |
develop.ts | Pattern matching all endpoints with graphql or graphiql with 1 or more leading underscores
*/
const graphqlEndpoint = `/_+graphi?ql`
if (process.env.GATSBY_GRAPHQL_IDE === `playground`) {
app.get(
graphqlEndpoint,
graphqlPlayground({
endpoint: `/___graphql`,
}),
() => {}
... | prepareUrls | identifier_name | |
develop.ts | index.html`, {})
indexHTMLActivity.start()
const directory = program.directory
const directoryPath = withBasePath(directory)
const workerPool = WorkerPool.create()
const createIndexHtml = async (activity: ActivityTracker): Promise<void> => {
try {
await buildHTML({
program,
stage: B... |
})
)
.pipe(res)
})
})
}
await apiRunnerNode(`onCreateDevServer`, { app })
// In case nothing before handled hot-update - send 404.
// This fixes "Unexpected token < in JSON at position 0" runtime
// errors after restarting development server and
// cause automa... | {
const message = `Error when trying to proxy request "${req.originalUrl}" to "${proxiedUrl}"`
report.error(message, err)
res.sendStatus(500)
} | conditional_block |
mainga.py | highest_quality = 0
class Coordinates:
def __init__(self):
self.x1 = None
self.y1 = None
self.x2 = None
self.y2 = None
def setup_camera():
global mydll
global hCamera
global pbyteraw
global dwBufferSize
global dwNumberOfByteTrans
global dwFrameNo
globa... | import os
inner_rectangle = None
outer_rectangle = None
first_photo_taken = False | random_line_split | |
mainga.py | inner_rectangle = Coordinates()
inner_rectangle.x1 = coord.x1
inner_rectangle.y1 = coord.y1
inner_rectangle.x2 = coord.x2
inner_rectangle.y2 = coord.y2
plt.close()
def toggle_selector(event):
# print(' Key pressed.')
if event.key in ['p'] and t... | global inner_rectangle
global outer_rectangle
# print('next')
# print(coord.x1)
# print(coord.y1)
# print(coord.x2)
# print(coord.x2)
if inner_rectangle:
# draw outer rectangle
# print('coord', coord.x1)
if coord.x1:
outer_rectangle = Coordinates()
... | identifier_body | |
mainga.py | = open('request.txt', 'w+')
# proj = r'C:\dazzler\data\pythonwavefile.txt'
# fileh.write(proj)
# time.sleep(0.05)
# print('writing request')
# print(fileh.read())
# time.sleep(0.05)
# fileh.close()
# print('writing request.txt')
os.chdir(home)
ti... | toolbox.mutate(mutant)
del mutant.fitness.values | conditional_block | |
mainga.py | ():
global inner_rectangle
global outer_rectangle
# print('next')
# print(coord.x1)
# print(coord.y1)
# print(coord.x2)
# print(coord.x2)
if inner_rectangle:
# draw outer rectangle
# print('coord', coord.x1)
if coord.x1:
outer_rectangle = Coordinates()... | after_selection | identifier_name | |
offline.js | VVMxEzARBgNVBAgTCldhc2hpbmd0
// SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
// SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWlj
// SIG // cm9zb2Z0IFRpbWUtU3RhbXAgUENBMB4XDTEyMDEwOTIy
// SIG // MjU1OFoXDTEzMDQwOTIyMjU1OFowgbMxCzAJBgNVBAYT
// SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH
// SIG // EwdSZW... | // SIG // PLzYLTAZBgkrBgEEAYI3FAIEDB4KAFMAdQBiAEMAQTAf | random_line_split | |
offline.js | };
var showLinks = function () {
var allNavLinks = document.querySelectorAll("nav.page-nav a");
for (var i = 0; i < allNavLinks.length; i++) {
allNavLinks[i].style.display = "";
}
};
if (!navigator.onLine) {
hideLinksThatRequireOnline();
}
document.b... | var href = allNavLinks[i].getAttribute("href");
if (!offlinePages.test(href)) {
allNavLinks[i].style.display = "none";
}
}
| conditional_block | |
postgres.rs | };
use sql_schema_describer::{DescriberErrorKind, SqlSchema, SqlSchemaDescriberBackend};
use std::collections::HashMap;
use url::Url;
use user_facing_errors::{
common::DatabaseDoesNotExist, introspection_engine::DatabaseSchemaInconsistent, migration_engine, KnownError,
UserFacingError,
};
#[derive(Debug)]
pub(... | conn.raw_cmd(&drop_and_recreate_schema).await?;
Ok(())
}
async fn reset(&self, connection: &Connection) -> ConnectorResult<()> {
let schema_name = connection.connection_info().schema_name();
connection
.raw_cmd(&format!("DROP SCHEMA \"{}\" CASCADE", schema_name))
... | {
let mut url = Url::parse(database_str).map_err(|err| ConnectorError::url_parse_error(err, database_str))?;
strip_schema_param_from_url(&mut url);
let conn = create_postgres_admin_conn(url.clone()).await?;
let schema = self.url.schema();
let db_name = self.url.dbname();
... | identifier_body |
postgres.rs | };
use sql_schema_describer::{DescriberErrorKind, SqlSchema, SqlSchemaDescriberBackend};
use std::collections::HashMap;
use url::Url;
use user_facing_errors::{
common::DatabaseDoesNotExist, introspection_engine::DatabaseSchemaInconsistent, migration_engine, KnownError,
UserFacingError,
};
#[derive(Debug)]
pub(... |
temporary_database.raw_cmd(&create_schema).await?;
for migration in migrations {
let script = migration.read_migration_script()?;
tracing::debug!(
"Applying migration `{}` to temporary database.",
... | random_line_split | |
postgres.rs | };
use sql_schema_describer::{DescriberErrorKind, SqlSchema, SqlSchemaDescriberBackend};
use std::collections::HashMap;
use url::Url;
use user_facing_errors::{
common::DatabaseDoesNotExist, introspection_engine::DatabaseSchemaInconsistent, migration_engine, KnownError,
UserFacingError,
};
#[derive(Debug)]
pub(... | (&self, connection: &Connection) -> ConnectorResult<()> {
let schema_name = connection.connection_info().schema_name();
connection
.raw_cmd(&format!("DROP SCHEMA \"{}\" CASCADE", schema_name))
.await?;
connection
.raw_cmd(&format!("CREATE SCHEMA \"{}\"", sch... | reset | identifier_name |
postgres.rs | };
use sql_schema_describer::{DescriberErrorKind, SqlSchema, SqlSchemaDescriberBackend};
use std::collections::HashMap;
use url::Url;
use user_facing_errors::{
common::DatabaseDoesNotExist, introspection_engine::DatabaseSchemaInconsistent, migration_engine, KnownError,
UserFacingError,
};
#[derive(Debug)]
pub(... |
Err(err) => return Err(err.into()),
};
// Now create the schema
url.set_path(&format!("/{}", db_name));
let conn = connect(&url.to_string()).await?;
let schema_sql = format!("CREATE SCHEMA IF NOT EXISTS \"{}\";", &self.schema_name());
conn.raw_cmd(&schema... | {
database_already_exists_error = Some(err)
} | conditional_block |
shelllogger.py | new terminals are encountered.
escape_regex is a Regex filter to capture all escape sequences.
Modified from: http://wiki.tcl.tk/9673
"""
# Filter out control characters
# First, handle the backspaces.
for backspace in backspaces:
try:
while True:
ind = buf... | (self,buf):
self.logfile.write(buf)
def debug_log(self, buf, shell):
"""Record to the debug log"""
# Handle Shell output
if shell == True:
self.debugfile.write("<shell time=\" " + datetime.datetime.now().strftime("%H:%M:%S ") + "\" >" )
self.debugfile.write(... | write | identifier_name |
shelllogger.py | -8"?>\n')
self.logfile.write('<cli-logger machine="%s">\n\n' % socket.gethostname())
self.buffer = ''
self.cwd = os.getcwd()
self.state = BeginState(self)
self.debugfilename = debugfilename
self.isLinux = False
if self.debugfilename is not None:
self.d... | def next_state(self):
if self.saw_prompt: | random_line_split | |
shelllogger.py | 0
termios.tcsetattr(0, termios.TCSANOW, [raw_iflag, self.oflag,
self.cflag, raw_lflag,
self.ispeed, self.ospeed,
raw_cc])
def restore(self):
termios.tcsetattr... | self.logger = logger
self.seen_cr = False
self.program_invoked = None | identifier_body | |
shelllogger.py | new terminals are encountered.
escape_regex is a Regex filter to capture all escape sequences.
Modified from: http://wiki.tcl.tk/9673
"""
# Filter out control characters
# First, handle the backspaces.
for backspace in backspaces:
try:
while True:
ind = buf... |
else:
return os.path.expanduser('~/.shelllogger')
def start_recording(logfilename, debug):
# Check for recursive call
env_var = 'ShellLogger'
if os.environ.has_key(env_var):
# Recursive call, just exit
return
os.environ[env_var]='1'
print "ShellLogger enabled"
if... | return os.environ[env_var] | conditional_block |
LearningMachines2.py |
let me keep expanding the width. Only the
Variable width output for classifier.
Assign any function to a classifier node.
input width is fixed.
# TODO Need a better predictor.
"""
__author__ = 'Abhishek Rao'
# Headers
import numpy as np
from sklearn import svm
import math
import matplotlib.pyplot as plt... | :
""" A machine which stores both input X and the current output of bunch of classifiers.
API should be similar to scikit learn"""
def __init__(self, max_width, input_width, height):
"""
Initialize this class.
:rtype : object self
:param max_width: maximum data dimension in... | SimpleClassifierBank | identifier_name |
LearningMachines2.py |
let me keep expanding the width. Only the
Variable width output for classifier.
Assign any function to a classifier node.
input width is fixed.
# TODO Need a better predictor.
"""
__author__ = 'Abhishek Rao'
# Headers
import numpy as np
from sklearn import svm
import math
import matplotlib.pyplot as plt... |
self.current_working_memory[:input_number_samples, :input_feature_dimension] = x_pred
for classifier_i in self.classifiers_list:
predicted_value = classifier_i.predict(self.current_working_memory)
predicted_shape = predicted_value.shape
if len(predicted_shape) < 2:
... | print "Error in predict. Input dimension should be 2"
raise ValueError | conditional_block |
LearningMachines2.py |
let me keep expanding the width. Only the
Variable width output for classifier.
Assign any function to a classifier node.
input width is fixed.
# TODO Need a better predictor.
"""
__author__ = 'Abhishek Rao'
# Headers
import numpy as np
from sklearn import svm
import math
import matplotlib.pyplot as plt... | def fit(self, x_in, y, task_name='Default'):
"""
Adds a new classifier and trains it, similar to Scikit API
:param x_in: 2d Input data
:param y: labels
:return: None
"""
# check for limit reach for number of classifiers.
if self.classifiers_current_c... | random_line_split | |
LearningMachines2.py |
let me keep expanding the width. Only the
Variable width output for classifier.
Assign any function to a classifier node.
input width is fixed.
# TODO Need a better predictor.
"""
__author__ = 'Abhishek Rao'
# Headers
import numpy as np
from sklearn import svm
import math
import matplotlib.pyplot as plt... | new_classifier = ClassifierNode(
end_in_address=self.classifiers_out_address_start + self.classifiers_current_count,
out_address=[self.classifiers_out_address_start + self.classifiers_current_count + 1],
classifier_name=task_name)
self.classifiers_current_count += 1
... | """
Adds a new classifier and trains it, similar to Scikit API
:param x_in: 2d Input data
:param y: labels
:return: None
"""
# check for limit reach for number of classifiers.
if self.classifiers_current_count + self.classifiers_out_address_start \
... | identifier_body |
autoSuggest.js | ();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
if ( hasFocus++ > 1 && !select.visible(... | lt(row, row[0]) || row.value
};
}
}
| conditional_block | |
autoSuggest.js | case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
event.p... | }).focus(function(){
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
var fn = (arguments.length > 1) ? arguments[1] : null;
fu... | timeout = setTimeout(onChange, options.delay);
break;
} | random_line_split |
autoSuggest.js | KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
event.preven... | {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
}).bind("input", function() { //ronizhang:针对firefox中文输入bug的处理
if ( hasFocus++ > 1 ) {//&& !select.visible() ) {
onChange(0, true);
}
});
function selectCurrent() {
var selected = select.selected();
if( !selected... | unction" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
}).bind("unautocomplete", func... | identifier_body |
autoSuggest.js | KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
event.preven... | Value.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
$i... | previous | identifier_name |
Canviz.js | < keysLength; ++i) {
var key = keys[i];
Canviz.colors[key] = colors[key];
}
};
// Constants
var MAX_XDOT_VERSION = '1.6';
// An alphanumeric string or a number or a double-quoted string or an HTML string
var ID_MATCH = '([a-zA-Z\u0080-\uFFFF_][0-9a-zA-Z\u0080-\uFFFF_]*|-?(?:\\.\\d+|\\d+(?:\\.\\d*)?)|"(?:\\\... | } while (matches);
}
}
}
}
function xdotRound(n) {
var digits = 2;
var mult = Math.pow(10, digits);
return Math.round(mult * n) / mult;
}
var drawingWidth = this.width + 2 * this.paddingX;
var drawingHeight = this.height + 2 * this.padding | } | random_line_split |
Canviz.js |
this.container.appendChild(this.elements);
textModes.push('dom');
}
this.ctx = this.canvas.getContext('2d');
if (this.ctx.fillText) textModes.push('canvas');
this.setTextMode(textModes[0]);
this.setScale(1);
this.dashLength = 6;
this.dotSpacing = 4;
this.graphs = [];
this.images = {};
this.... | {
G_vmlCanvasManager.initElement(this.canvas);
this.canvas = document.getElementById(this.canvas.id);
} | conditional_block | |
Canviz.js | this.ctx = this.canvas.getContext('2d');
if (this.ctx.fillText) textModes.push('canvas');
this.setTextMode(textModes[0]);
this.setScale(1);
this.dashLength = 6;
this.dotSpacing = 4;
this.graphs = [];
this.images = {};
this.imagePath = '';
if (url) {
this.load(url, urlParams);
}
}
// Properti... | {
if (!(this instanceof Canviz)) return new Canviz(container, url, urlParams);
var textModes = this._textModes = [];
this.canvas = new Canvas(0, 0);
if (!Canviz.canvasCounter) Canviz.canvasCounter = 0;
this.canvas.id = 'canviz_canvas_' + ++Canviz.canvasCounter;
if (IS_BROWSER) {
this.canvas.style.positi... | identifier_body | |
Canviz.js | (container, url, urlParams) {
if (!(this instanceof Canviz)) return new Canviz(container, url, urlParams);
var textModes = this._textModes = [];
this.canvas = new Canvas(0, 0);
if (!Canviz.canvasCounter) Canviz.canvasCounter = 0;
this.canvas.id = 'canviz_canvas_' + ++Canviz.canvasCounter;
if (IS_BROWSER) {
... | Canviz | identifier_name | |
net.go | Read can be made to time out and
// return an Error with Timeout() == true after a fixed time limit; see
// SetDeadline and SetReadDeadline.
//
// Part of the net.Conn interface.
func (c *Conn) Read(b []byte) (n int, err error) {
fmt.Println("read (start)", b)
done := make(chan int)
callback := js.FuncO... | ResolveTCPAddr | identifier_name | |
net.go |
id int
// conn net.Conn
// noise *Machine
// readBuf bytes.Buffer
}
var _ net.Conn = (*Conn)(nil)
// Read reads data from the connection. Read can be made to time out and
// return an Error with Timeout() == true after a fixed time limit; see
// SetDeadline and SetReadDeadline.
//
// Part of the n... | // return c.noise.Flush(c.conn)
// }
// Close closes the connection. Any blocked Read or Write operations will be
// unblocked and return errors.
//
// Part of the net.Conn interface.
func (c *Conn) Close() error {
// TODO(roasbeef): reset brontide state?
// return c.conn.Close()
fmt.Println("closed c... | // //
// // NOTE: It is safe to call this method again iff a timeout error is returned.
// func (c *Conn) Flush() (int, error) { | random_line_split |
net.go | id int
// conn net.Conn
// noise *Machine
// readBuf bytes.Buffer
}
var _ net.Conn = (*Conn)(nil)
// Read reads data from the connection. Read can be made to time out and
// return an Error with Timeout() == true after a fixed time limit; see
// SetDeadline and SetReadDeadline.
//
// Part of the ne... |
// SetDeadline sets the read and write deadlines associated with the
// connection. It is equivalent to calling both SetReadDeadline and
// SetWriteDeadline.
//
// Part of the net.Conn interface.
func (c *Conn) SetDeadline(t time.Time) error {
// return c.conn.SetDeadline(t)
fmt.Println("set deadline", t)
... | {
// return c.conn.RemoteAddr()
fmt.Println("getting remote addr")
return nil
} | identifier_body |
padtwitch.py |
if self.stream_thread:
print('shutting down stream thread')
self.stream_thread.join()
self.stream_thread = None
print('done shutting down stream thread')
def __unload(self):
self._try_shutdown_twitch()
async def on_connect(self):
... | self.stream.disconnect() | conditional_block | |
padtwitch.py | enabled: bool):
self.getChannel(channel_name)['enabled'] = enabled
self.save_settings()
def getCustomCommands(self, channel_name: str):
return self.getChannel(channel_name)['custom_commands']
def addCustomCommand(self, channel_name: str, cmd_name: str, cmd_value: str):
... | self._maybe_print(
'got msg: #{} @{} -- {}'.format(msg['channel'], msg['username'], msg['message']))
return msg
elif len(data):
| random_line_split | |
padtwitch.py | , channel_name: str):
return self.getChannel(channel_name)['custom_commands']
def addCustomCommand(self, channel_name: str, cmd_name: str, cmd_value: str):
self.getCustomCommands(channel_name)[cmd_name] = cmd_value
self.save_settings()
def rmCustomCommand(self, channel_name: str... | twitch_receive_messages | identifier_name | |
padtwitch.py | _name):]
action_fn(channel, username, query)
return
for command_name, command_response in self.settings.getCustomCommands(channel).items():
if message.rstrip()[1:] == command_name:
self.stream.send_chat_message(channel, command_response)
... |
@commands.group(pass_context=True)
@checks.is_owner()
async def padtwitch(self, ctx):
"""Manage twitter feed mirroring"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
@padtwitch.command(pass_context=True)
async def setUserName(self, ctx, user_n... | cmd_name = query.strip()
self.settings.rmCustomCommand(channel, cmd_name)
self.stream.send_chat_message(channel, 'Done deleting ' + cmd_name) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.