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 |
|---|---|---|---|---|
copy_up.go | // Copyright 2018 The gVisor Authors.
//
// 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 agree... | (ctx context.Context, upper *Inode, lower *Inode, size int64) error {
// We don't support copying up for anything other than regular files.
if lower.StableAttr.Type != RegularFile {
return nil
}
// Get a handle to the upper filesystem, which we will write to.
upperFile, err := overlayFile(ctx, upper, FileFlags{... | copyContentsLocked | identifier_name |
call.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | {
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 | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | (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 | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | // 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 | const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const mongodb = require('mongodb');
const ObjectId = require('mongodb').ObjectID;
const favicon = require('serve-favicon');
const schema = require('./schemas/index.js');
const functions = require('./functions... | // 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 | package main
import (
"encoding/json"
"github.com/beewit/found/global"
"github.com/beewit/beekit/redis"
"time"
"github.com/sclevine/agouti"
"net/http"
"strings"
"github.com/sclevine/agouti/api"
"github.com/beewit/beekit/utils"
"github.com/beewit/beekit/utils/convert"
)
const (
SINA_SPIDER = "SINA_SP... | }
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 | package main
import (
"encoding/json"
"github.com/beewit/found/global"
"github.com/beewit/beekit/redis"
"time"
"github.com/sclevine/agouti"
"net/http"
"strings"
"github.com/sclevine/agouti/api"
"github.com/beewit/beekit/utils"
"github.com/beewit/beekit/utils/convert"
)
const (
SINA_SPIDER = "SINA_SP... |
_, 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 | package main
import (
"encoding/json"
"github.com/beewit/found/global"
"github.com/beewit/beekit/redis"
"time"
"github.com/sclevine/agouti"
"net/http"
"strings"
"github.com/sclevine/agouti/api"
"github.com/beewit/beekit/utils"
"github.com/beewit/beekit/utils/convert"
)
const (
SINA_SPIDER = "SINA_SP... | m["gender"] = detail
} else if strings.Contains(title, "性取向") {
m["sexorientation"] = detail
} else if strings.Contains(title, "感情状况") {
m["marriage"] = detail
} else if strings.Contains(title, "生日") {
m["birthday"] = detail
} else if strings.Contains(title, "血型") {
m["bloo... | tail
} else if strings.Contains(title, "性别") {
| conditional_block |
crawler_sina.go | package main
import (
"encoding/json"
"github.com/beewit/found/global"
"github.com/beewit/beekit/redis"
"time"
"github.com/sclevine/agouti"
"net/http"
"strings"
"github.com/sclevine/agouti/api"
"github.com/beewit/beekit/utils"
"github.com/beewit/beekit/utils/convert"
)
const (
SINA_SPIDER = "SINA_SP... | )
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 | import base58
import calendar
from datetime import datetime
def tb(l):
return b''.join(map(lambda x: x.to_bytes(1, 'big'), l))
base58_encodings = [
# Encoded | Decoded |
# prefix | len | prefix | len | Data type
(b"B", 51, tb([1, 52]), ... | return base58_encode(data[2:], tz_prefix).decode()
if data.startswith(b'\x01') and data.endswith(b'\x00'):
return base58_encode(data[1:-1], b'KT1').decode()
else:
return base58_encode(data[1:], tz_prefixes[b'\x00' + data[:1]]).decode()
def parse_contract(data: bytes):
""" Deco... |
for bin_prefix, tz_prefix in tz_prefixes.items():
if data.startswith(bin_prefix): | random_line_split |
encoding.py | import base58
import calendar
from datetime import datetime
def tb(l):
return b''.join(map(lambda x: x.to_bytes(1, 'big'), l))
base58_encodings = [
# Encoded | Decoded |
# prefix | len | prefix | len | Data type
(b"B", 51, tb([1, 52]), ... |
def parse_contract(data: bytes):
""" Decode contract (address + optional entrypoint) from bytes
:param data: encoded contract
:returns: base58 encoded address and entrypoint (if exists) separated by `%`
"""
res = parse_address(data[:22])
if len(data) > 22:
res += f'%{data[22:].decode... | """ 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 | import base58
import calendar
from datetime import datetime
def tb(l):
return b''.join(map(lambda x: x.to_bytes(1, 'big'), l))
base58_encodings = [
# Encoded | Decoded |
# prefix | len | prefix | len | Data type
(b"B", 51, tb([1, 52]), ... | (value: str) -> bytes:
""" Encode base58 string into bytes.
:param value: base58 encoded value (with checksum)
"""
return base58_decode(value.encode())
def forge_timestamp(value) -> int:
""" Encode timestamp into bytes.
:param value: unix timestamp in seconds (int)
"""
assert isinsta... | forge_base58 | identifier_name |
encoding.py | import base58
import calendar
from datetime import datetime
def tb(l):
return b''.join(map(lambda x: x.to_bytes(1, 'big'), l))
base58_encodings = [
# Encoded | Decoded |
# prefix | len | prefix | len | Data type
(b"B", 51, tb([1, 52]), ... |
else:
raise ValueError(value)
return res[1:] if tz_only else res
def parse_address(data: bytes):
""" 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\x... | res = b'\x01' + address + b'\x00' | conditional_block |
blockSelection.ts | /**
* @class BlockSelection
* @classdesc Manages Block selection with shortcut CMD+A
* @module BlockSelection
* @version 1.0.0
*/
import Module from '../__module';
import Block from '../block';
import * as _ from '../utils';
import $ from '../dom';
import Shortcuts from '../utils/shortcuts';
import SelectionUtils... | (): 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 | /**
* @class BlockSelection
* @classdesc Manages Block selection with shortcut CMD+A
* @module BlockSelection
* @version 1.0.0
*/
import Module from '../__module';
import Block from '../block';
import * as _ from '../utils';
import $ from '../dom';
import Shortcuts from '../utils/shortcuts';
import SelectionUtils... | */
if (inputs.length > 1 && !this.readyToBlockSelection) {
this.readyToBlockSelection = true;
return;
}
if (inputs.length === 1 && !this.needToSelectAll) {
this.needToSelectAll = true;
return;
}
if (this.needToSelectAll) {
/**
* Prevent default selection... | * Second cmd+a will select whole Block | random_line_split |
blockSelection.ts | /**
* @class BlockSelection
* @classdesc Manages Block selection with shortcut CMD+A
* @module BlockSelection
* @version 1.0.0
*/
import Module from '../__module';
import Block from '../block';
import * as _ from '../utils';
import $ from '../dom';
import Shortcuts from '../utils/shortcuts';
import SelectionUtils... |
/**
* select Block
*
* @param {number?} index - Block index according to the BlockManager's indexes
*/
public selectBlockByIndex(index?): void {
const { BlockManager } = this.Editor;
/**
* Remove previous focused Block's state
*/
BlockManager.clearFocused();
let block;
... | {
/**
* 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 | /**
* @class BlockSelection
* @classdesc Manages Block selection with shortcut CMD+A
* @module BlockSelection
* @version 1.0.0
*/
import Module from '../__module';
import Block from '../block';
import * as _ from '../utils';
import $ from '../dom';
import Shortcuts from '../utils/shortcuts';
import SelectionUtils... |
if (this.needToSelectAll) {
/**
* Prevent default selection
*/
event.preventDefault();
this.selectAllBlocks();
/**
* Disable any selection after all Blocks selected
*/
this.needToSelectAll = false;
this.readyToBlockSelection = false;
/**
... | {
this.needToSelectAll = true;
return;
} | conditional_block |
day13.rs | //! # --- Day 13: Shuttle Search ---
//!
//! Your ferry can make it safely to a nearby port, but it won't get much
//! further. When you call to book another ship, you discover that no ships
//! embark from that port to your vacation island. You'll need to get from the
//! port to the nearest airport.
//!
//! Fortunate... | (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 | //! # --- Day 13: Shuttle Search ---
//!
//! Your ferry can make it safely to a nearby port, but it won't get much
//! further. When you call to book another ship, you discover that no ships
//! embark from that port to your vacation island. You'll need to get from the
//! port to the nearest airport.
//!
//! Fortunate... |
}
}
earliest
}
fn main() -> Result<(), &'static str> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
return Err("not enough arguments");
}
let filename = &args[1];
println!("Load input file {}.", filename);
let input = fs::read_to_string(filename).... | {
n += 1;
} | conditional_block |
day13.rs | //! # --- Day 13: Shuttle Search ---
//!
//! Your ferry can make it safely to a nearby port, but it won't get much
//! further. When you call to book another ship, you discover that no ships
//! embark from that port to your vacation island. You'll need to get from the
//! port to the nearest airport.
//!
//! Fortunate... | //!
//! ```
//! 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 | //! # --- Day 13: Shuttle Search ---
//!
//! Your ferry can make it safely to a nearby port, but it won't get much
//! further. When you call to book another ship, you discover that no ships
//! embark from that port to your vacation island. You'll need to get from the
//! port to the nearest airport.
//!
//! Fortunate... |
}
| {
let earliest = clac_contest(&TEST_ARRAY);
assert_eq!(earliest, 1068781);
} | identifier_body |
parser.go | package main
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/xml"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"log/syslog"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/jlaffaye/ftp"
"github.com/nightlyone/lockfile"
)
//VERSION Версия д... | () == "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 | package main
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/xml"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"log/syslog"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/jlaffaye/ftp"
"github.com/nightlyone/lockfile"
)
//VERSION Версия д... | FTP("ftp.icvibor.ru:21")
//os.Exit(0)
var certPath = flag.String("certpath", "None", "путь до сертификата который проверяем (работаете только совместно c --testcert)")
var testCert = flag.Bool("testcert", false, "флаг указывающий на режим проверки сертификата")
var forceUpdate = flag.Bool("forceupdate", false, "фл... | гли сохранить временный файл со списком УЦ", 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 | package main
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/xml"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"log/syslog"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/jlaffaye/ftp"
"github.com/nightlyone/lockfile"
)
//VERSION Версия д... |
}
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 | package main
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/xml"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"log/syslog"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/jlaffaye/ftp"
"github.com/nightlyone/lockfile"
)
//VERSION Версия д... | e :", err)
}
//defer fingerFile.Close()
makeListOfUCS(&root)
if newer := checkXMLVersion(&root, &oldRoot); newer {
fmt.Println("У нас новая XML-ка, ну давайте запарсим и загрузим!")
//installCertByUcFile(*uclist, &root, fingerFile)
installAllCert(&root, fingerFile)
makeListInstalledCerts(listCaPath... | log.Fatal("Cannot create fil | conditional_block |
samplesheet.rs | //! This module contains tools to build sample sheets from lists of samples,
//! and to export sample sheets to ARResT-compatible formats.
use std::{collections::HashMap, convert::TryInto, fs::File, io::Write, path::{Path, PathBuf}};
use std::error::Error;
use crate::{models, vaultdb::MatchStatus};
use calamine::{Re... | }
|
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 | //! This module contains tools to build sample sheets from lists of samples,
//! and to export sample sheets to ARResT-compatible formats.
use std::{collections::HashMap, convert::TryInto, fs::File, io::Write, path::{Path, PathBuf}};
use std::error::Error;
use crate::{models, vaultdb::MatchStatus};
use calamine::{Re... | }
}
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 | //! This module contains tools to build sample sheets from lists of samples,
//! and to export sample sheets to ARResT-compatible formats.
use std::{collections::HashMap, convert::TryInto, fs::File, io::Write, path::{Path, PathBuf}};
use std::error::Error;
use crate::{models, vaultdb::MatchStatus};
use calamine::{Re... | &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 | //! This module contains tools to build sample sheets from lists of samples,
//! and to export sample sheets to ARResT-compatible formats.
use std::{collections::HashMap, convert::TryInto, fs::File, io::Write, path::{Path, PathBuf}};
use std::error::Error;
use crate::{models, vaultdb::MatchStatus};
use calamine::{Re... |
"primer set" => { e.model.primer_set.as_ref().unwrap_or(&String::from("")).to_string() },
"project" => { e.model.project.as_ref().map(|s| s.clone()).unwrap_or(String::from("")) },
"LIMS ID" => { e.model.lims_id.map(|i| i.to_string()).unwrap_or_els... | e.model.dna_nr.as_ref().map(|s| s.clone()).unwrap_or(String::from("")) }, | conditional_block |
mainwindow.py | """
"""
from __future__ import absolute_import
import logging
import sys
import os
from PyQt4 import QtCore, QtGui, uic
import praxes
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from praxes.io import phynx
#logger = logging.getLogger(__file__)
class MainWin... |
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 __future__ import absolute_import
import logging
import sys
import os
from PyQt4 import QtCore, QtGui, uic
import praxes
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from praxes.io import phynx
#logger = logging.getLogger(__file__)
class MainWin... | (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 __future__ import absolute_import
import logging
import sys
import os
from PyQt4 import QtCore, QtGui, uic
import praxes
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from praxes.io import phynx
#logger = logging.getLogger(__file__)
class MainWin... |
@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 __future__ import absolute_import
import logging
import sys
import os
from PyQt4 import QtCore, QtGui, uic
import praxes
from .ui import resources
from .phynx import FileModel, FileView, ExportRawCSV, ExportCorrectedCSV
from praxes.io import phynx
#logger = logging.getLogger(__file__)
class MainWin... | 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 | #![allow(clippy::mutable_key_type)]
use common::{anyhow::Result, NetworkType};
use core_extensions::{build_extensions, ExtensionsConfig, CURRENT_EPOCH, MATURE_THRESHOLD};
use core_rpc::{
CkbRpc, CkbRpcClient, MercuryRpc, MercuryRpcImpl, CURRENT_BLOCK_NUMBER, TX_POOL_CACHE,
USE_HEX_FORMAT,
};
use core_storage::... | 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 | #![allow(clippy::mutable_key_type)]
use common::{anyhow::Result, NetworkType};
use core_extensions::{build_extensions, ExtensionsConfig, CURRENT_EPOCH, MATURE_THRESHOLD};
use core_rpc::{
CkbRpc, CkbRpcClient, MercuryRpc, MercuryRpcImpl, CURRENT_BLOCK_NUMBER, TX_POOL_CACHE,
USE_HEX_FORMAT,
};
use core_storage::... |
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_maturity_threshold(&self, current_epoch: RationalU256) {
if current_epoch < self... | {
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 | #![allow(clippy::mutable_key_type)]
use common::{anyhow::Result, NetworkType};
use core_extensions::{build_extensions, ExtensionsConfig, CURRENT_EPOCH, MATURE_THRESHOLD};
use core_rpc::{
CkbRpc, CkbRpcClient, MercuryRpc, MercuryRpcImpl, CURRENT_BLOCK_NUMBER, TX_POOL_CACHE,
USE_HEX_FORMAT,
};
use core_storage::... | (ckb_client: &CkbRpcClient, raw_pool: RawTxPool) {
let mut input_set: HashSet<packed::OutPoint> = HashSet::new();
let hashes = tx_hash_list(raw_pool);
if let Ok(res) = ckb_client.get_transactions(hashes).await {
for item in res.iter() {
if let Some(tx) = item {
for input... | handle_raw_tx_pool | identifier_name |
raw.go | package tsdb
import (
"fmt"
"math"
"sort"
"time"
"github.com/influxdb/influxdb/influxql"
"github.com/influxdb/influxdb/models"
)
const (
// Return an error if the user is trying to select more than this number of points in a group by statement.
// Most likely they specified a group by interval without time b... |
// Protect against none of the mappers producing any output.
if chunkedOutput == nil {
continue
}
if ascending {
// Sort the values by time first so we can then handle offset and limit
sort.Sort(MapperValues(chunkedOutput.Values))
} else {
sort.Sort(sort.Reverse(MapperValues(chunkedOutput.Value... | {
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 | package tsdb
import (
"fmt"
"math"
"sort"
"time"
"github.com/influxdb/influxdb/influxql"
"github.com/influxdb/influxdb/models"
)
const (
// Return an error if the user is trying to select more than this number of points in a group by statement.
// Most likely they specified a group by interval without time b... | 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 | package tsdb
import (
"fmt"
"math"
"sort"
"time"
"github.com/influxdb/influxdb/influxql"
"github.com/influxdb/influxdb/models"
)
const (
// Return an error if the user is trying to select more than this number of points in a group by statement.
// Most likely they specified a group by interval without time b... |
// NextChunk returns the next chunk of data.
// Data is ordered the same as TagSets. Each chunk contains one tag set.
// If there is no more data for any tagset, nil will be returned.
func (m *RawMapper) NextChunk() (interface{}, error) {
var output *MapperOutput
for {
// All tagset cursors processed. NextChunk'i... | { return append(m.selectFields, m.selectTags...) } | identifier_body |
raw.go | package tsdb
import (
"fmt"
"math"
"sort"
"time"
"github.com/influxdb/influxdb/influxql"
"github.com/influxdb/influxdb/models"
)
const (
// Return an error if the user is trying to select more than this number of points in a group by statement.
// Most likely they specified a group by interval without time b... | (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 | #
# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
# All rights reserved.
# This component and the accompanying materials are made available
# under the terms of "Eclipse Public License v1.0"
# which accompanies this distribution, and is available
# at the URL "http://www.eclipse.org/legal/epl-... |
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 | #
# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
# All rights reserved.
# This component and the accompanying materials are made available
# under the terms of "Eclipse Public License v1.0"
# which accompanies this distribution, and is available
# at the URL "http://www.eclipse.org/legal/epl-... | (self):
self.file = None
self.type = None
self.version = None
self.read_only = None
self.categories = []
def get_hcr_records(self):
"""
Return a list of HcrRecord objects created based on this output object's categories.
"""
res... | __init__ | identifier_name |
hcrml_parser.py | #
# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
# All rights reserved.
# This component and the accompanying materials are made available
# under the terms of "Eclipse Public License v1.0"
# which accompanies this distribution, and is available
# at the URL "http://www.eclipse.org/legal/epl-... |
The type of this Output object should be 'hcr', otherwise and an exception is raised.
"""
if self.type != 'hcr':
raise RuntimeError("get_hcr_repository() called on an Output object with type '%s' (should be 'hcr')" % self.type)
return HcrRepository(sel... | return result
def get_hcr_repository(self):
"""
Return a HcrRepository object created based on this output.
| random_line_split |
hcrml_parser.py | #
# Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
# All rights reserved.
# This component and the accompanying materials are made available
# under the terms of "Eclipse Public License v1.0"
# which accompanies this distribution, and is available
# at the URL "http://www.eclipse.org/legal/epl-... |
if flag.Modifiable == '1': record.flags |= HcrRecord.FLAG_MODIFIABLE
if flag.Persistent == '1': record.flags |= HcrRecord.FLAG_PERSISTENT
result.append(record)
return result
class Output(object):
def __init__(self):
self.file... | record.flags |= HcrRecord.FLAG_UNINITIALIZED | conditional_block |
beerData.js | const beerData = {
// - 15, 16 - 35, 36 - 55, 56 - 75, 76 -
cold: { // Poter, Smoke Poter, Barrel-Aged Beer, Stout, Imperial Stout, Oatmeal Stout
sunny: [
// ['1772 Porter', 'Brown Porter', '4.6%', 26, 'coldsunny1'],
['1772 Porter', 'Brown Porter', '4.6%', ' ★ ★', 'beer3', 'A t... | ['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 | // Copyright 2022 The CubeFS Authors.
//
// 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 agree... | (size int) ec.BufferSizes {
sizes, _ := ec.GetBufferSizes(size, codemode.EC6P6.Tactic())
return sizes
}
func dataEqual(exp, act []byte) bool {
return crc32.ChecksumIEEE(exp) == crc32.ChecksumIEEE(act)
}
| getBufSizes | identifier_name |
stream_mock_test.go | // Copyright 2022 The CubeFS Authors.
//
// 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 agree... |
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 | // Copyright 2022 The CubeFS Authors.
//
// 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 agree... |
func initPool() {
memPool = resourcepool.NewMemPool(getDefaultMempoolSize())
}
func initEncoder() {
coderEC6P6, _ := ec.NewEncoder(ec.Config{
CodeMode: codemode.EC6P6.Tactic(),
EnableVerify: true,
})
coderEC6P10L2, _ := ec.NewEncoder(ec.Config{
CodeMode: codemode.EC6P10L2.Tactic(),
EnableVerify: ... | {
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 | // Copyright 2022 The CubeFS Authors.
//
// 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 agree... | 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 | // Copyright 2014 The Cockroach Authors.
//
// 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 ag... |
// RunningTasks returns a map containing the count of running tasks keyed by
// call site.
func (s *Stopper) RunningTasks() TaskMap {
s.mu.Lock()
defer s.mu.Unlock()
return s.runningTasksLocked()
}
func (s *Stopper) runningTasksLocked() TaskMap {
m := TaskMap{}
for k := range s.mu.tasks {
if s.mu.tasks[k] == ... | {
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 | // Copyright 2014 The Cockroach Authors.
//
// 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 ag... |
// 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 | // Copyright 2014 The Cockroach Authors.
//
// 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 ag... | "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 | // Copyright 2014 The Cockroach Authors.
//
// 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 ag... | (
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 | package shopping
import(
"fmt"
"sort"
"time"
"crypto/md5"
"io"
"io/ioutil"
"encoding/json"
//"strings"
//"bytes"
"github.com/zaddone/studySystem/request"
"net/url"
//"github.com/boltdb/bolt"
//"net/http"
//"regexp"
)
var (
PddUrl = "https://gw-api.pinduoduo.com/api/router"
//PddOrderDB *bolt.DB
//PddEr... |
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.Get(k)
}
sign+=self.Info.Client_... | {
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 | package shopping
import(
"fmt"
"sort"
"time"
"crypto/md5"
"io"
"io/ioutil"
"encoding/json"
//"strings"
//"bytes"
"github.com/zaddone/studySystem/request"
"net/url"
//"github.com/boltdb/bolt"
//"net/http"
//"regexp"
)
var (
PddUrl = "https://gw-api.pinduoduo.com/api/router"
//PddOrderDB *bolt.DB
//PddEr... | }
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 | package shopping
import(
"fmt"
"sort"
"time"
"crypto/md5"
"io"
"io/ioutil"
"encoding/json"
//"strings"
//"bytes"
"github.com/zaddone/studySystem/request"
"net/url"
//"github.com/boltdb/bolt"
//"net/http"
//"regexp"
)
var (
PddUrl = "https://gw-api.pinduoduo.com/api/router"
//PddOrderDB *bolt.DB
//PddEr... | () 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 | package shopping
import(
"fmt"
"sort"
"time"
"crypto/md5"
"io"
"io/ioutil"
"encoding/json"
//"strings"
//"bytes"
"github.com/zaddone/studySystem/request"
"net/url"
//"github.com/boltdb/bolt"
//"net/http"
//"regexp"
)
var (
PddUrl = "https://gw-api.pinduoduo.com/api/router"
//PddOrderDB *bolt.DB
//PddEr... |
page++
}
begin = end
if isOut {
break
}
}
self.Info.Update = begin.Unix()
return nil
//return openSiteDB(siteDB,self.Info.SaveToDB)
}
func (self *Pdd) getOrder(begin,end time.Time,page int)interface{}{
u := &url.Values{}
u.Add("type","pdd.ddk.order.list.increment.get")
u.Add("page_size","40")
u... | 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 | use std::convert::TryInto;
use std::fs::File;
use std::io::{ErrorKind, Read, Write};
use std::os::unix::io::{FromRawFd, RawFd};
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::{slice, usize};
use pcid_interface::{PciBar, PciFeature, PciFeatureInfo, PciFunction, PcidServerHandle};
use syscall::{
CloneF... | () {
// 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 | use std::convert::TryInto;
use std::fs::File;
use std::io::{ErrorKind, Read, Write};
use std::os::unix::io::{FromRawFd, RawFd};
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::{slice, usize};
use pcid_interface::{PciBar, PciFeature, PciFeatureInfo, PciFunction, PcidServerHandle};
use syscall::{
CloneF... |
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 | use std::convert::TryInto;
use std::fs::File;
use std::io::{ErrorKind, Read, Write};
use std::os::unix::io::{FromRawFd, RawFd};
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::{slice, usize};
use pcid_interface::{PciBar, PciFeature, PciFeatureInfo, PciFunction, PcidServerHandle};
use syscall::{
CloneF... |
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 | # Copyright (c) 2016 Fabian Schuiki
#
# This file implements layout generation for memory macros. Given a macro
# specification it generates a structure representing individual cells that can
# be used by other parts of the generator to derive the placement of subcells
# or the location of obstructions and pins.
impor... |
# Add the filler cells in the top row.
self.fillers = list()
for ba in self.bitarrays:
if ba.pos.x < self.raregs[0].pos.x - 0.5*bit_width or ba.pos.x > self.raregs[-1].pos.x + 0.5*bit_width:
self.fillers.append(Inst(
self, self.filler_cell, ba.name+"FILL",
Vec(
ba.pos.x,
(self.num... | 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 | # Copyright (c) 2016 Fabian Schuiki
#
# This file implements layout generation for memory macros. Given a macro
# specification it generates a structure representing individual cells that can
# be used by other parts of the generator to derive the placement of subcells
# or the location of obstructions and pins.
impor... | (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 | # Copyright (c) 2016 Fabian Schuiki
#
# This file implements layout generation for memory macros. Given a macro
# specification it generates a structure representing individual cells that can
# be used by other parts of the generator to derive the placement of subcells
# or the location of obstructions and pins.
impor... | 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 | # Copyright (c) 2016 Fabian Schuiki
#
# This file implements layout generation for memory macros. Given a macro
# specification it generates a structure representing individual cells that can
# be used by other parts of the generator to derive the placement of subcells
# or the location of obstructions and pins.
impor... | mx=flip
))
# Add the filler cells in the top row.
self.fillers = list()
for ba in self.bitarrays:
if ba.pos.x < self.raregs[0].pos.x - 0.5*bit_width or ba.pos.x > self.raregs[-1].pos.x + 0.5*bit_width:
self.fillers.append(Inst(
self, self.filler_cell, ba.name+"FILL",
Vec(
ba.p... | self.wiring.append(Inst(
self, self.rareg_hwire_b_cell, wt.name+"WRAB",
Vec(x,t), | random_line_split |
develop.ts | import url from "url"
import fs from "fs"
import openurl from "better-opn"
import chokidar from "chokidar"
import webpackHotMiddleware from "webpack-hot-middleware"
import webpackDevMiddleware from "webpack-dev-middleware"
import glob from "glob"
import express from "express"
import got from "got"
import webpack from ... | 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 | import url from "url"
import fs from "fs"
import openurl from "better-opn"
import chokidar from "chokidar"
import webpackHotMiddleware from "webpack-hot-middleware"
import webpackDevMiddleware from "webpack-dev-middleware"
import glob from "glob"
import express from "express"
import got from "got"
import webpack from ... | ,
}
}
)
)
/**
* 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 | import url from "url"
import fs from "fs"
import openurl from "better-opn"
import chokidar from "chokidar"
import webpackHotMiddleware from "webpack-hot-middleware"
import webpackDevMiddleware from "webpack-dev-middleware"
import glob from "glob"
import express from "express"
import got from "got"
import webpack from ... | (
protocol: `http` | `https`,
host: string,
port: number
): IPreparedUrls {
const formatUrl = (hostname: string): string =>
url.format({
protocol,
hostname,
port,
pathname: `/`,
})
const prettyPrintUrl = (hostname: string): string =>
url.format({
... | prepareUrls | identifier_name |
develop.ts | import url from "url"
import fs from "fs"
import openurl from "better-opn"
import chokidar from "chokidar"
import webpackHotMiddleware from "webpack-hot-middleware"
import webpackDevMiddleware from "webpack-dev-middleware"
import glob from "glob"
import express from "express"
import got from "got"
import webpack from ... |
})
)
.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 | import matplotlib.pyplot as plt
from ctypes import *
import numpy as np
from matplotlib.widgets import RectangleSelector
import matplotlib.patches as patch
import random
import numpy as np
from deap import base
from deap import creator
from deap import tools
import time
from scipy.interpolate import interp1d | 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 | import matplotlib.pyplot as plt
from ctypes import *
import numpy as np
from matplotlib.widgets import RectangleSelector
import matplotlib.patches as patch
import random
import numpy as np
from deap import base
from deap import creator
from deap import tools
import time
from scipy.interpolate import interp1d
import os... |
def toggle_selector(event):
# print(' Key pressed.')
if event.key in ['p'] and toggle_selector.rs.active:
# print(' RectangleSelector deactivated.')
toggle_selector.rs.set_active(False)
toggle_selector.rs.set_visible(False)
after_selection()
if event.key in ['r'] and togg... | 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 | import matplotlib.pyplot as plt
from ctypes import *
import numpy as np
from matplotlib.widgets import RectangleSelector
import matplotlib.patches as patch
import random
import numpy as np
from deap import base
from deap import creator
from deap import tools
import time
from scipy.interpolate import interp1d
import os... |
for mutant in offspring:
# mutate an individual with probabililty MUTPB2
if random.random() < MUTPB2:
# print('before: ', mutant)
tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2)
# print('after: ', mutant)
# exit(0... | toolbox.mutate(mutant)
del mutant.fitness.values | conditional_block |
mainga.py | import matplotlib.pyplot as plt
from ctypes import *
import numpy as np
from matplotlib.widgets import RectangleSelector
import matplotlib.patches as patch
import random
import numpy as np
from deap import base
from deap import creator
from deap import tools
import time
from scipy.interpolate import interp1d
import os... | ():
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 | (function () {
var offlinePages = /^\/(index|about|schedule|location).htm$/;
var hideLinksThatRequireOnline = function () {
var allNavLinks = document.querySelectorAll("nav.page-nav a");
for (var i = 0; i < allNavLinks.length; i++) {
var href = allNavLinks[i].getAttribute("href");... | // SIG // BgNVHSMEGDAWgBQOrIJgQFYnl+UlE/wq4QpTlVnkpDBQ
// SIG // BgNVHR8ESTBHMEWgQ6BBhj9odHRwOi8vY3JsLm1pY3Jv
// SIG // c29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9taWNyb3Nv
// SIG // ZnRyb290Y2VydC5jcmwwVAYIKwYBBQUHAQEESDBGMEQG
// SIG // CCsGAQUFBzAChjhodHRwOi8vd3d3Lm1pY3Jvc29mdC5j
// SIG // b20vcGtpL2NlcnRzL01pY3Jvc29mdFJvb3R... | // SIG // PLzYLTAZBgkrBgEEAYI3FAIEDB4KAFMAdQBiAEMAQTAf | random_line_split |
offline.js | (function () {
var offlinePages = /^\/(index|about|schedule|location).htm$/;
var hideLinksThatRequireOnline = function () {
var allNavLinks = document.querySelectorAll("nav.page-nav a");
for (var i = 0; i < allNavLinks.length; i++) {
| };
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 crate::{connect, connection_wrapper::Connection, error::quaint_error_to_connector_error, SqlFlavour};
use enumflags2::BitFlags;
use indoc::indoc;
use migration_connector::{ConnectorError, ConnectorResult, MigrationDirectory, MigrationFeature};
use quaint::{connector::PostgresUrl, error::ErrorKind as QuaintKind, pre... |
async fn reset(&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... | {
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 crate::{connect, connection_wrapper::Connection, error::quaint_error_to_connector_error, SqlFlavour};
use enumflags2::BitFlags;
use indoc::indoc;
use migration_connector::{ConnectorError, ConnectorResult, MigrationDirectory, MigrationFeature};
use quaint::{connector::PostgresUrl, error::ErrorKind as QuaintKind, pre... |
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 crate::{connect, connection_wrapper::Connection, error::quaint_error_to_connector_error, SqlFlavour};
use enumflags2::BitFlags;
use indoc::indoc;
use migration_connector::{ConnectorError, ConnectorResult, MigrationDirectory, MigrationFeature};
use quaint::{connector::PostgresUrl, error::ErrorKind as QuaintKind, pre... | (&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 crate::{connect, connection_wrapper::Connection, error::quaint_error_to_connector_error, SqlFlavour};
use enumflags2::BitFlags;
use indoc::indoc;
use migration_connector::{ConnectorError, ConnectorResult, MigrationDirectory, MigrationFeature};
use quaint::{connector::PostgresUrl, error::ErrorKind as QuaintKind, pre... |
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 | """
DISCLAIMER:
This code is not part of shellther. It is found here:
http://pydoc.net/Python/shelllogger/1.0.1/sl.shelllogger/
However, it does not seem to have any way of installing as a package, so it has
been repackaged here.
ShellLogger: Unix shell command invocation logger
Usage: shelllogger [-s, --sanitize... | (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 | """
DISCLAIMER:
This code is not part of shellther. It is found here:
http://pydoc.net/Python/shelllogger/1.0.1/sl.shelllogger/
However, it does not seem to have any way of installing as a package, so it has
been repackaged here.
ShellLogger: Unix shell command invocation logger
Usage: shelllogger [-s, --sanitize... | return BeginState(self.logger)
else:
return self
class ShellOutputNoOutputState(ShellOutputState):
"""
TODO: This is a dead state, which is clearly incorrect.
"""
def write_output_to_log(self,buf):
pass
def sanitize_file(infilename, outfilename):
"""Strip a... | def next_state(self):
if self.saw_prompt: | random_line_split |
shelllogger.py | """
DISCLAIMER:
This code is not part of shellther. It is found here:
http://pydoc.net/Python/shelllogger/1.0.1/sl.shelllogger/
However, it does not seem to have any way of installing as a package, so it has
been repackaged here.
ShellLogger: Unix shell command invocation logger
Usage: shelllogger [-s, --sanitize... |
def input_from_shell(self,buf):
if(buf.startswith('\x0D') or buf.startswith('\r')):
self.logger.isLinux = True
self.seen_cr = True
self.program_invoked = self.logger.buffer.split()[0]
self.logger.write('''<cli-logger-entry>
<invocation time="%f"
current-dire... | self.logger = logger
self.seen_cr = False
self.program_invoked = None | identifier_body |
shelllogger.py | """
DISCLAIMER:
This code is not part of shellther. It is found here:
http://pydoc.net/Python/shelllogger/1.0.1/sl.shelllogger/
However, it does not seem to have any way of installing as a package, so it has
been repackaged here.
ShellLogger: Unix shell command invocation logger
Usage: shelllogger [-s, --sanitize... |
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 | """ Version 3 of IRC (Infinite Recursive classifier). Based on the idea that each output is placed in a certain
location.
Let me try to solve a simpler problem first. Let me forget about the gate and do non stop recursive classification
step by step, one bye one.
Update. 19 May 2015. Let me stept this up. Instead of h... | :
""" 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 | """ Version 3 of IRC (Infinite Recursive classifier). Based on the idea that each output is placed in a certain
location.
Let me try to solve a simpler problem first. Let me forget about the gate and do non stop recursive classification
step by step, one bye one.
Update. 19 May 2015. Let me stept this up. Instead of h... |
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 | """ Version 3 of IRC (Infinite Recursive classifier). Based on the idea that each output is placed in a certain
location.
Let me try to solve a simpler problem first. Let me forget about the gate and do non stop recursive classification
step by step, one bye one.
Update. 19 May 2015. Let me stept this up. Instead of h... | 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 | """ Version 3 of IRC (Infinite Recursive classifier). Based on the idea that each output is placed in a certain
location.
Let me try to solve a simpler problem first. Let me forget about the gate and do non stop recursive classification
step by step, one bye one.
Update. 19 May 2015. Let me stept this up. Instead of h... |
def fit_custom_fx(self, custom_function, input_width, output_width, task_name):
"""
Push in a new custom function to classifiers list.
:param custom_function: The function that will be used to predict. Should take in a 2D array input and
give out a 2d array of same height and v... | """
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 | /**
* 搜索建议
* @author ronizhang
* 参数还可以定义:
* parse:解析json数据为此控件指定的格式的函数
* postParam:自定义的查询post参数
* 有一些搜索专用的项,jsonp部分不太通用
*/
(function($) {
$.fn.extend({
autocomplete: function(options) {
var isUrl = true;
options = $.extend({}, $.Autocompleter.defaults, {
url: options.dataUrl||null,
data: options.data|... | return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
... | lt(row, row[0]) || row.value
};
}
}
| conditional_block |
autoSuggest.js | /**
* 搜索建议
* @author ronizhang
* 参数还可以定义:
* parse:解析json数据为此控件指定的格式的函数
* postParam:自定义的查询post参数
* 有一些搜索专用的项,jsonp部分不太通用
*/
(function($) {
$.fn.extend({
autocomplete: function(options) {
var isUrl = true;
options = $.extend({}, $.Autocompleter.defaults, {
url: options.dataUrl||null,
data: options.data|... | }).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 | /**
* 搜索建议
* @author ronizhang
* 参数还可以定义:
* parse:解析json数据为此控件指定的格式的函数
* postParam:自定义的查询post参数
* 有一些搜索专用的项,jsonp部分不太通用
*/
(function($) {
$.fn.extend({
autocomplete: function(options) {
var isUrl = true;
options = $.extend({}, $.Autocompleter.defaults, {
url: options.dataUrl||null,
data: options.data|... | {
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 | /**
* 搜索建议
* @author ronizhang
* 参数还可以定义:
* parse:解析json数据为此控件指定的格式的函数
* postParam:自定义的查询post参数
* 有一些搜索专用的项,jsonp部分不太通用
*/
(function($) {
$.fn.extend({
autocomplete: function(options) {
var isUrl = true;
options = $.extend({}, $.Autocompleter.defaults, {
url: options.dataUrl||null,
data: options.data|... | 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 | // Require Path first to load the circular dependencies in the right order
var Path = require('./path/Path.js');
// Constants
var IS_BROWSER = typeof document != 'undefined';
var XDOT_DPI = 72;
// Constructor
function Canviz(container, url, urlParams) {
if (!(this instanceof Canviz)) return new Canviz(container, ur... | } 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.paddingY;
... | } | random_line_split |
Canviz.js | // Require Path first to load the circular dependencies in the right order
var Path = require('./path/Path.js');
// Constants
var IS_BROWSER = typeof document != 'undefined';
var XDOT_DPI = 72;
// Constructor
function Canviz(container, url, urlParams) {
if (!(this instanceof Canviz)) return new Canviz(container, ur... |
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 | // Require Path first to load the circular dependencies in the right order
var Path = require('./path/Path.js');
// Constants
var IS_BROWSER = typeof document != 'undefined';
var XDOT_DPI = 72;
// Constructor
function Canviz(container, url, urlParams) |
// Properties
Canviz.Path = Path;
Canviz.colors = {
fallback: {
black: '000000',
lightgrey: 'd3d3d3',
white: 'ffffff'
}
};
Canviz.addColors = function (colors) {
var keys = objectKeys(colors),
keysLength = keys.length;
for (var i = 0; i < keysLength; ++i) {
var key = keys[i];
Canviz.co... | {
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 | // Require Path first to load the circular dependencies in the right order
var Path = require('./path/Path.js');
// Constants
var IS_BROWSER = typeof document != 'undefined';
var XDOT_DPI = 72;
// Constructor
function | (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 | package main
import (
// "errors"
"net"
"time"
"fmt"
"syscall/js"
)
// TODO: this interface and its implementations should ideally be moved
// elsewhere as they are not Tor-specific.
// Net is an interface housing a Dial function and several DNS functions that
// allows us to abstract the impleme... | (network, address string) (*net.TCPAddr, error) {
return net.ResolveTCPAddr(network, address)
}
// // ProxyNet is an implementation of the Net interface that defines behaviour
// // for Tor network connections.
// type ProxyNet struct {
// // // SOCKS is the host:port which Tor's exposed SOCKS5 proxy is listen... | ResolveTCPAddr | identifier_name |
net.go | package main
import (
// "errors"
"net"
"time"
"fmt"
"syscall/js"
)
// TODO: this interface and its implementations should ideally be moved
// elsewhere as they are not Tor-specific.
// Net is an interface housing a Dial function and several DNS functions that
// allows us to abstract the impleme... | // 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 | package main
import (
// "errors"
"net"
"time"
"fmt"
"syscall/js"
)
// TODO: this interface and its implementations should ideally be moved
// elsewhere as they are not Tor-specific.
// Net is an interface housing a Dial function and several DNS functions that
// allows us to abstract the impleme... |
// 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 | from __future__ import print_function
import asyncio
from copy import deepcopy
from datetime import datetime
import errno
import os
import re
import socket
import threading
import time
from dateutil import tz
import discord
from discord.ext import commands
from __main__ import user_allowed, send_cmd_... |
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 | from __future__ import print_function
import asyncio
from copy import deepcopy
from datetime import datetime
import errno
import os
import re
import socket
import threading
import time
from dateutil import tz
import discord
from discord.ext import commands
from __main__ import user_allowed, send_cmd_... | self._maybe_print('other data: {}'.format(data))
else:
return None
def twitch_receive_messages(self):
"""
Call this function to process everything received by the socket
This needs to be called frequently enough (~10s) Twitch logs off
users no... | self._maybe_print(
'got msg: #{} @{} -- {}'.format(msg['channel'], msg['username'], msg['message']))
return msg
elif len(data):
| random_line_split |
padtwitch.py | from __future__ import print_function
import asyncio
from copy import deepcopy
from datetime import datetime
import errno
import os
import re
import socket
import threading
import time
from dateutil import tz
import discord
from discord.ext import commands
from __main__ import user_allowed, send_cmd_... | (self):
"""
Call this function to process everything received by the socket
This needs to be called frequently enough (~10s) Twitch logs off
users not replying to ping commands.
:return: list of chat messages received. Each message is a dict
with the keys ['ch... | twitch_receive_messages | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.