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 |
|---|---|---|---|---|
lib.rs |
fn default_layer(v: &i32, branch_factor: u16) -> u8 {
let mut layer = 0;
let mut v = *v;
if branch_factor == 16 {
while v != 0 && v & 0xf == 0 {
v >>= 4;
layer += 1
}
} else {
while v != 0 && v % branch_factor as i32 == 0 {
v /= branch_factor... | {
if *a < *b {
return -1;
} else if *a > *b {
return 1;
} else {
return 0;
}
} | identifier_body | |
MOS6502.py | 0):
self.bitwidth = bitwidth = 8 # 1 byte - 8 bits
self.regs = {'A': Register('A', bitwidth),
'X': Register('X', bitwidth),
'Y': Register('Y', bitwidth),
'PC': Register('PC', bitwidth * 2),
'S': Register('S', bitwidth),
... |
def push_word(self, value):
"""Push the given 16-bit word value onto the emulated CPU stack."""
self.push_byte((value & 0xFF00) >> 8)
return self.push_byte(value & 0xFF)
def pop_byte(self):
"""Return a byte value popped from the emulated CPU stack."""
reg_s = self.get_... | """Push the given byte value onto the emulated CPU stack."""
reg_s = self.get_register('S')
self.set_memory(reg_s + self.stack_base, value)
self.set_register('S', reg_s - 1)
return reg_s + self.stack_base - 1 | identifier_body |
MOS6502.py | 0
self.stack_base = 0x0100
self.ppu_mem = 0x2000
self.apu_mem = 0x4000
self.spr_dma = 0x4014
self.channels = 0x4015
self.ctrl1 = 0x4016
self.ctrl2 = 0x4017
self.nmi_vector = 0xFFFA
self.reset_vector = 0xFFFC
self.irq_brk_vector = 0xFFFE
... | random_line_split | ||
MOS6502.py | 0):
self.bitwidth = bitwidth = 8 # 1 byte - 8 bits
self.regs = {'A': Register('A', bitwidth),
'X': Register('X', bitwidth),
'Y': Register('Y', bitwidth),
'PC': Register('PC', bitwidth * 2),
'S': Register('S', bitwidth),
... | (self, address, size):
"""Return an arbitrarily sized region of the emulated memory space"""
mem = []
for i in range(0, size):
mem.append(self.read_memory(address+i))
return mem
def get_register(self, name):
"""Return the value of the given register (valid value... | get_memory | identifier_name |
MOS6502.py | self.memory = Memory()
self.past_memory = []
#self.symbMemory = z3Array('mem', z3.BitVecSort(bitwidth), z3.BitVecSort(8))
self.regs['PC'].set_value(0)
self.regs['S'].set_value(0)
self.cycle = 0
self.global_cycle = 0
self.nmi_flipflop = 0
self.st... | self.set_flag(flag, valid_flags[flag]) | conditional_block | |
icip_train_val.py | fasttext": "/home/wangkai/ICIP/feature/train/FastText_tags+des_20337.csv",
"tfidf": "/home/wangkai/ICIP/feature/train/Tfidf_tags+des_20337.csv",
"lsa": "/home/wangkai/ICIP/feature/train/LSA_tags+title+des_20337.csv",
"lda": "/home/wangkai/ICIP/feature/train/LDA_tags+title+des_20337.csv",
"wordchar": "/h... | columns
all_feature.drop(useless, axis=1, inplace=True)
print(all_feature)
return all_feature
def calssify_catboost(train, validate):
cat_features = ["UserId"]
# cat_features=[]
train_data = catboost.Pool(
train.iloc[:, 1:-31], train["label"], cat_features=cat_features)
validata_da... | .".format(feature_name))
feature = pd.read_csv(feature_path[feature_name])
print("feature: {}, len:{}".format(
feature_name, len(feature.columns)-1))
if i == 0:
all_feature = feature
else:
all_feature = pd.merge(all_feature, feature)
useless = text... | conditional_block |
icip_train_val.py | from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import train_test_split
random_seed = 2020
num_class = 50
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
all_popularity_filepath = "/home/wangkai/ICIP/feature/label/popularity_TRAIN_20337.csv"
cluster_center_filepath = "/home/... | from scipy import stats
from scipy.stats import spearmanr
from sklearn.cluster import KMeans | random_line_split | |
icip_train_val.py | fasttext": "/home/wangkai/ICIP/feature/train/FastText_tags+des_20337.csv",
"tfidf": "/home/wangkai/ICIP/feature/train/Tfidf_tags+des_20337.csv",
"lsa": "/home/wangkai/ICIP/feature/train/LSA_tags+title+des_20337.csv",
"lda": "/home/wangkai/ICIP/feature/train/LDA_tags+title+des_20337.csv",
"wordchar": "/h... | feature_list, flag="train"):
feature_path = train_feature_filepath if flag == "train" else test_feature_filepath
for i, feature_name in enumerate(feature_list):
print("Loading {} ...".format(feature_name))
feature = pd.read_csv(feature_path[feature_name])
print("feature: {}, len:{}".form... | df_popularity = pd.read_csv(all_popularity_filepath)
# 归一化
normalized_popularity = df_popularity.iloc[:, 1:].div(
df_popularity["Day30"], axis=0)
# 聚类的label
kmeans = KMeans(n_clusters=num_class, init="k-means++", n_init=100, max_iter=10000,
random_state=random_seed, n_jobs=-1... | identifier_body |
icip_train_val.py | fasttext": "/home/wangkai/ICIP/feature/train/FastText_tags+des_20337.csv",
"tfidf": "/home/wangkai/ICIP/feature/train/Tfidf_tags+des_20337.csv",
"lsa": "/home/wangkai/ICIP/feature/train/LSA_tags+title+des_20337.csv",
"lda": "/home/wangkai/ICIP/feature/train/LDA_tags+title+des_20337.csv",
"wordchar": "/h... | cat_features = ["UserId"]
# cat_features=[]
train_data = catboost.Pool(
train.iloc[:, 1:-31], train["label"], cat_features=cat_features)
validata_data = catboost.Pool(
validate.iloc[:, 1:-31], validate["label"], cat_features=cat_features)
model = catboost.CatBoostClassifier(iteration... | ain, validate):
| identifier_name |
offset.rs | Mut<'p, 'v, A>> for Offset<'p, 'v> {
#[inline(always)]
fn borrow(&self) -> &OffsetMut<'p, 'v, A> {
self.as_ref()
}
}
impl<'p, 'v, A> AsRef<OffsetMut<'p, 'v, A>> for Offset<'p, 'v> {
#[inline(always)]
fn as_ref(&self) -> &OffsetMut<'p, 'v, A> {
// SAFETY: #[repr(transparent)]
... | save | identifier_name | |
offset.rs | 1 && (raw >> 1) < Offset::MAX as u64 {
unsafe { Ok(blob.assume_valid()) }
} else {
Err(ValidateOffsetBlobError)
}
}
fn decode_blob<'a>(blob: ValidBlob<'a, Self>) -> Self {
blob.as_value().clone()
}
fn try_deref_blob<'a>(blob: ValidBlob<'a, Self>) -> Resu... |
}
/// Gets the `Offset` from a clean `OffsetMut`.
#[inline(always)]
pub fn get_offset(&self) -> Option<Offset<'p, 'v>> {
match self.kind() {
Kind::Offset(offset) => Some(offset),
Kind::Ptr(_) => None,
}
}
/// Gets the pointer from a dirty `OffsetMut`.
... | {
Kind::Ptr(unsafe { mem::transmute(self.inner) })
} | conditional_block |
offset.rs | b1 && (raw >> 1) < Offset::MAX as u64 {
unsafe { Ok(blob.assume_valid()) }
} else {
Err(ValidateOffsetBlobError)
}
}
fn decode_blob<'a>(blob: ValidBlob<'a, Self>) -> Self {
blob.as_value().clone()
}
fn try_deref_blob<'a>(blob: ValidBlob<'a, Self>) -> Res... | // SAFETY: #[repr(transparent)]
unsafe { &*(self as *const Self as *const _) }
}
}
*/
impl<'p, 'v> From<Offset<'p, 'v>> for usize {
fn from(offset: Offset<'p, 'v>) -> usize {
offset.get()
}
}
impl<'p, 'v> From<Offset<'p, 'v>> for OffsetMut<'p, 'v> {
fn from(inner: Offset<'p, 'v... | fn as_ref(&self) -> &OffsetMut<'p, 'v, A> { | random_line_split |
offset.rs |
fn decode_blob<'a>(blob: ValidBlob<'a, Self>) -> Self {
blob.as_value().clone()
}
fn try_deref_blob<'a>(blob: ValidBlob<'a, Self>) -> Result<&'a Self, ValidBlob<'a, Self>> {
Ok(blob.as_value())
}
fn encode_blob<W: WriteBlob>(&self, dst: W) -> Result<W::Ok, W::Error> {
tod... | {
let raw = u64::from_le_bytes(blob.as_bytes().try_into().unwrap());
if raw & 0b1 == 0b1 && (raw >> 1) < Offset::MAX as u64 {
unsafe { Ok(blob.assume_valid()) }
} else {
Err(ValidateOffsetBlobError)
}
} | identifier_body | |
glyph.rs | ,
pub colored: bool,
}
#[derive(Copy, Debug, Clone)]
pub struct QuadAtlasGlyph {
pub atlas_index: usize,
pub uv_bot: f32,
pub uv_left: f32,
pub uv_width: f32,
pub uv_height: f32,
pub top: i16,
pub left: i16,
pub width: i16,
pub height: i16,
pub colored: bool,
}
#[derive(Cop... | else {
rasterizer.load_font(&desc, size).unwrap_or_else(|_| regular)
}
};
// Load bold font.
let bold_desc = Self::make_desc(&font.bold(), Slant::Normal, Weight::Bold);
let bold = load_or_regular(bold_desc);
// Load italic font.
let italic_d... |
regular
} | conditional_block |
glyph.rs | {
pub rasterized: crossfont::RasterizedGlyph,
pub wide: bool,
pub zero_width: bool,
}
/// `LoadGlyph` allows for copying a rasterized glyph into graphics memory.
pub trait LoadGlyph {
/// Load the rasterized glyph into GPU memory.
fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> AtlasGlyp... | RasterizedGlyph | identifier_name | |
glyph.rs | , Clone)]
pub struct QuadAtlasGlyph {
pub atlas_index: usize,
pub uv_bot: f32,
pub uv_left: f32,
pub uv_width: f32,
pub uv_height: f32,
pub top: i16,
pub left: i16,
pub width: i16,
pub height: i16,
pub colored: bool,
}
#[derive(Copy, Debug, Clone)]
pub enum AtlasGlyph {
Grid... | key: crossfont::GlyphKey {
font_key: *font,
c: c as char, | random_line_split | |
main.go |
}
deps := &getpan.DependencyList{
Dependencies: make([]*getpan.Dependency, 0),
}
d1, _ := getpan.DependencyFromString("Parse::LocalDistribution", "")
d2, _ := getpan.DependencyFromString("JSON::XS", "")
deps.AddDependency(d1)
deps.AddDependency(d2)
if err := deps.Resolve(); err != nil {
log.Er... | {
log.Error("Error loading sources: %s", err)
os.Exit(1)
return
} | conditional_block | |
main.go | mapped[idx.Name][auth.Name[:1]]["**"][auth.Name] = auth
mapped[idx.Name]["*"][auth.Name[:2]][auth.Name] = auth
for _, pkg := range auth.Packages {
filemap[pkg.AuthorURL()] = idn
for _, prov := range pkg.Provides {
parts := strings.Split(prov.Name, "::")
log.Trace("PACKAGE: %s",... | help | identifier_name | |
main.go | 1)
go func() {
defer wg.Done()
load_index(idx, config.CacheDir+"/"+idx)
}()
}
// Load our primary index (this is the only index written back to)
wg.Add(1)
go func() {
defer wg.Done()
load_index(config.Index, config.CacheDir+"/"+config.Index)
}()
}()
update_indexes = func() {
wg.Wait(... | {
idx := session.Stash["index"]
switch idx {
case "CPAN":
go func() {
config.CPANStatus = "Downloading"
res, err := nethttp.Get("https://s3-eu-west-1.amazonaws.com/gopan/cpan_index.gz")
if err != nil {
log.Error("Error downloading index: %s", err.Error())
session.RenderException(500, errors.New(... | identifier_body | |
main.go | args[2],
"newindex": "",
"cpanmirror": "",
"importurl": "",
"fromdir": "",
}
if strings.HasPrefix(fname, "http://") || strings.HasPrefix(fname, "https://") {
log.Info("URL: %s", fname)
extraParams["importurl"] = fname
request, err := newFormPostRequest(config.RemoteHost+"/import?str... | mapped[idx.Name]["*"]["**"][auth.Name] = auth
// combos
if _, ok := mapped[idx.Name][auth.Name[:1]]["**"]; !ok {
mapped[idx.Name][auth.Name[:1]]["**"] = make(map[string]*gopan.Author)
}
if _, ok := mapped[idx.Name]["*"][auth.Name[:2]]; !ok {
mapped[idx.Name]["*"][auth.Name[:2]] = m... | }
if _, ok := mapped[idx.Name]["*"]["**"]; !ok {
mapped[idx.Name]["*"]["**"] = make(map[string]*gopan.Author)
} | random_line_split |
sourcemap.rs | 898b45172a637.js",
"e2ac0bea41202dc9.js",
"f01d9f3c7b2b2717.js",
"f15772354efa5ecf.js",
"f17ec9517a3339d9.js",
"fa5b398eeef697a6.js",
"fa9eaf58f51d6926.js",
"faa4a026e1e86145.js",
"fada2c7bbfabe14a.js",
"fb8db7a71f3755fc.js",
"fbde237f11796df9.js",
"fd5ea844fcc07d3d.js",
... | {
true
} | identifier_body | |
sourcemap.rs | 09637.js",
"c85bc4de504befc7.js",
"c8689b6da6fd227a.js",
"cda499c521ff60c7.js",
"d4b898b45172a637.js",
"e2ac0bea41202dc9.js",
"f01d9f3c7b2b2717.js",
"f15772354efa5ecf.js",
"f17ec9517a3339d9.js",
"fa5b398eeef697a6.js",
"fa9eaf58f51d6926.js",
"faa4a026e1e86145.js",
"fada2c7... | SourceMapConfigImpl | identifier_name | |
sourcemap.rs | 6fedbf6759.js",
"2dc0ded5a1bff643.js",
"547fa50af16beca7.js",
"547fa50af16beca7.js",
"8c8a7a2941fb6d64.js",
"9e98dbfde77e3dfe.js",
"d9eb39b11bc766f4.js",
"f9888fa1a1e366e7.js",
"78cf02220fb0937c.js",
// TODO(kdy1): Non-ascii char count
"58cb05d17f7ec010.js",
"4d2c7020de650d40... | "38284ea2d9914d86.js",
"3b57183c81070eec.js",
"3bbd75d597d54fe6.js",
"3c1e2ada0ac2b8e3.js",
"3e1a6f702041b599.js",
"3e3a99768a4a1502.js",
"3e69c5cc1a7ac103.js",
"3eac36e29398cdc5.js",
"3ff52d86c77678bd.js",
"43023cd549deee77.js",
"44af28febe2288cc.js",
"478ede4cfe7906d5.j... | "32b635a9667a9fb1.js",
"36224cf8215ad8e4.js",
"37e4a6eca1ece7e5.js", | random_line_split |
cloudevents.go | 重均衡,默认:10s
// 该值必须在broker配置`group.min.session.timeout.ms`与`group.max.session.timeout.ms`之间
Timeout time.Duration `mapstructure:"timeout"`
} `mapstructure:"session"`
Heartbeat struct {
// kafka协调者预期的心跳间隔,用于确保消费者session处于活跃状态,值必须小于session.timeout,默认:3s
// 一般建议设置为session.timeout的3分之一
Interval tim... | if s.Producer.Retry.Max != 0 {
c.Producer.R | conditional_block | |
cloudevents.go | :"isolation_level"`
} `mapstructure:"consumer"`
// 标识该消费者
ClientID string `mapstructure:"client_id"`
// 机柜标识,见 'broker.rack'
RackID string `mapstructure:"rack_id"`
// 默认:256
ChannelBufferSize int `mapstructure:"chnnel_buffer_size"`
Version string `mapstructure:"version"`
}
// Parse 解析为 https://pk... | identifier_body | ||
cloudevents.go | struct {
// 最大重试次数,默认:3
Max int `mapstructure:"max"`
} `mapstructure:"retry"`
} `mapstructure:"offsets"`
// 消费隔离级别,ReadUncommitted 或 ReadCommitted,默认:ReadUncommitted
// ReadUncommitted: 可以读取到未提交的数据(报错终止前的数据)
// ReadCommitted: 生产者已提交的数据才能读取到
IsolationLevel int8 `mapstructure:"isolation_level"`
} ... | saramaConfig,
c.CloudEvents.KafkaSarama.Topic)
if err != nil {
return err
} | random_line_split | |
cloudevents.go | // 重试失败之间等待间隔,等同于jvm的:retry.backoff.ms,默认值:100ms
Backoff time.Duration `mapstructure:"backoff"`
} `mapstructure:"retry"`
} `mapstructure:"producer"`
// 消费者相关配置
Consumer struct {
Group struct {
Session struct {
// 当broker端未收到消费者的心跳包,超过该时间间隔,则broker认为该消费者离线,将进行重均衡,默认:10s
// 该值必须在broker配置`group.mi... | .Byte | identifier_name | |
smf.go | s.createBarsUntil(pos, change.AbsPos, num, denom)
}
num, denom = change.Num, change.Denom
b := s.AddBar(change.AbsPos, num, denom)
pos = b.EndPos()
}
s.createBarsUntil(pos, s.lastPos, num, denom)
s.RenumberBars()
}
func (s *Song) findBar(pos uint64) (bar *Bar) {
for _, b := range s.Bars {
if pos >= b.A... | (w *writer.SMF) error {
tempo := float32(120.0)
var pos uint64
for _, b := range s.Bars {
for _, p := range b.Positions {
if p.Tempo != 0 && p.Tempo != tempo {
absPos := p.AbsTicks()
delta := uint32(absPos - pos)
w.SetDelta(delta)
w.Write(meta.Tempo(p.Tempo))
tempo = p.Tempo
pos = absPo... | writeTempoTrack | identifier_name |
smf.go | .No && m.Message != nil {
delta := ticks - lastTick
if tr.Channel < 0 {
panic(fmt.Sprintf("channel for content track no %v (%s) is -1, but content tracks must have channels", tr.No, tr.Name))
}
w.SetChannel(uint8(tr.Channel))
w.SetDelta(uint32(delta))
w.Write(m.Message)... |
return nil
}
| random_line_split | |
smf.go | .createBarsUntil(pos, change.AbsPos, num, denom)
}
num, denom = change.Num, change.Denom
b := s.AddBar(change.AbsPos, num, denom)
pos = b.EndPos()
}
s.createBarsUntil(pos, s.lastPos, num, denom)
s.RenumberBars()
}
func (s *Song) findBar(pos uint64) (bar *Bar) {
for _, b := range s.Bars {
if pos >= b.Abs... |
}
fmt.Fprintf(&bf, "\n")
for _, b := range s.Bars {
_ = b
fmt.Fprintf(&bf, "----------- #%v %v/%v --------------\n", b.No, b.TimeSig[0], b.TimeSig[1])
for _, p := range b.Positions {
tempo := ""
if p.Tempo != 0 {
tempo = fmt.Sprintf("%0.2f", tempo)
}
var frac float64
if p.Fraction[1] > ... | {
fmt.Fprintf(&bf, " %s[%v] | ", t.Name, t.Channel)
} | conditional_block |
smf.go | Ticks,
TempoBPM: m.FractionalBPM(),
}
s.scannedTempoChanges = append(s.scannedTempoChanges, tc)
default:
if msg != nil {
tm := &TrackMessage{}
tm.Message = msg
tm.TrackNo = t.No
tm.AbsPos = p.AbsoluteTicks
s.scannedMessages = append(s.scannedMessages, tm)
t.WithContent = true
if chMsg, is... | {
l := float64(b.Song.ticksPerQN*4*uint32(b.TimeSig[0])) / float64(b.TimeSig[1])
return uint64(math.Round(l))
} | identifier_body | |
audio.rs | : {:#?}", &input_info);
// Construct the input stream parameters.
let latency = input_info.default_low_input_latency;
let input_params = pa::StreamParameters::<f32>::new(def_input, CHANNELS, INTERLEAVED, latency);
let def_output = pa.default_output_device()?;
let output_info = pa.device_info(def_o... | /// Stream of samples from an audio device
pub struct AudioSampleStream<'c> {
channel: Receiver<f32>,
demod: Demodulate<'c>,
}
impl<'c> AudioSampleStream<'c> {
fn new(channel: Receiver<f32>, sample_rate: f32, config: &'c Config) -> Self {
Self {
channel,
demod: Demodulate::n... | random_line_split | |
audio.rs | : {:#?}", &input_info);
// Construct the input stream parameters.
let latency = input_info.default_low_input_latency;
let input_params = pa::StreamParameters::<f32>::new(def_input, CHANNELS, INTERLEAVED, latency);
let def_output = pa.default_output_device()?;
let output_info = pa.device_info(def_o... |
}
}
Ok(())
}
pub fn start_audio<'c>(
tx_receiver: Receiver<Complex<f32>>,
config: &'c Config,
) -> Result<(std::thread::JoinHandle<()>, AudioSampleStream<'c>), Error> {
// For the microphone
let (rx_sender, rx_receiver) = std::sync::mpsc::channel::<f32>();
let sample_rate = config.... | {
break;
} | conditional_block |
audio.rs | : {:#?}", &input_info);
// Construct the input stream parameters.
let latency = input_info.default_low_input_latency;
let input_params = pa::StreamParameters::<f32>::new(def_input, CHANNELS, INTERLEAVED, latency);
let def_output = pa.default_output_device()?;
let output_info = pa.device_info(def_o... | <'c> {
config: &'c Config,
/// Number of carrier samples to skip per baseband sample
to_skip: usize,
/// Sample rate of the audio signal
sample_rate: f32,
/// Total number of (audio) samples transmitted so far
num_samps: u64,
/// Average of the sample so far
samp_avg: Complex<f32>,
}... | Demodulate | identifier_name |
tests.rs | 02\xf0hi"[..],
Error::Literal { len: 4, src_len: 2, dst_len: 2 }
);
// A literal whose length is too big, requires 1 extra byte to be read,
// src is too short to read the full literal.
testerrored!(
err_lit_big2b,
&b"\x02\xf0hi\x00\x00\x00"[..],
Error::Literal {
len: 105, // because 105 == 'h' ... | {
return TestResult::discard();
} | conditional_block | |
tests.rs | Error::CopyRead { len: 4, src_len: 2 }
);
testerrored!(
err_copy3d,
&b"\x11\x00a\x3f\x00\x00\x00"[..],
Error::CopyRead { len: 4, src_len: 3 }
);
// A copy operation whose offset is zero.
testerrored!(
err_copy_offset_zero,
&b"\x11\x00a\x01\x00"[..],
Error::Offset { offset: 0, dst_pos: 1 }
);
... | depress | identifier_name | |
tests.rs | _bytes!("../data/alice29.txt"));
testtrip!(data_txt2, include_bytes!("../data/asyoulik.txt"));
testtrip!(data_txt3, include_bytes!("../data/lcet10.txt"));
testtrip!(data_txt4, include_bytes!("../data/plrabn12.txt"));
testtrip!(data_pb, include_bytes!("../data/geo.protodata"));
testtrip!(data_gaviota, include_bytes!("..... |
// Miscellaneous tests.
#[test]
fn small_copy() {
use std::iter::repeat;
for i in 0..32 {
let inner: String = repeat('b').take(i).collect();
roundtrip!(format!("aaaa{}aaaabbbb", inner).into_bytes());
}
}
#[test]
fn small_regular() {
let mut i = 1;
while i < 20_000 {
let m... | {
let data = include_bytes!("../data/Mark.Twain-Tom.Sawyer.txt.rawsnappy");
let data = &data[..];
assert_eq!(data, &*press(&depress(data)));
} | identifier_body |
tests.rs | };
match Decoder::new().decompress(d, &mut buf) {
Err(ref err) if err == &$err => {}
Err(ref err) => panic!(
"expected decompression to fail with {:?}, \
but got {:?}",
$err, err
),
Ok(n) => {
... | vec![0; decompress_len(d).unwrap()] | random_line_split | |
learn.rs | ReceiverStream;
use optic_diff_engine::streams;
use optic_diff_engine::{analyze_undocumented_bodies, EndpointCommand, SpecCommand};
use optic_diff_engine::{
BodyAnalysisLocation, HttpInteraction, SpecChunkEvent, SpecEvent, SpecIdGenerator,
SpecProjection, TrailObservationsResult,
};
pub const SUBCOMMAND_NAME: &'s... |
}
EndpointBody::Response(response_body) => {
let response_id = ids.response();
response_body.commands.push(SpecCommand::from(
EndpointCommand::add_response_by_path_and_method(
response_id.clone(),
response_body.path_id.clone(),
response_body.met... | {
request_body
.commands
.push(SpecCommand::from(EndpointCommand::set_request_body_shape(
request_id,
body_descriptor.root_shape_id.clone(),
body_descriptor.content_type.clone(),
false,
)));
} | conditional_block |
learn.rs | ReceiverStream;
use optic_diff_engine::streams;
use optic_diff_engine::{analyze_undocumented_bodies, EndpointCommand, SpecCommand};
use optic_diff_engine::{
BodyAnalysisLocation, HttpInteraction, SpecChunkEvent, SpecEvent, SpecIdGenerator,
SpecProjection, TrailObservationsResult,
};
pub const SUBCOMMAND_NAME: &'s... | body_descriptor.content_type.clone(),
false,
)));
}
}
EndpointBody::Response(response_body) => {
let response_id = ids.response();
response_body.commands.push(SpecCommand::from(
EndpointCommand::add_response_by_path_and_method(
... | request_body
.commands
.push(SpecCommand::from(EndpointCommand::set_request_body_shape(
request_id,
body_descriptor.root_shape_id.clone(), | random_line_split |
learn.rs | ReceiverStream;
use optic_diff_engine::streams;
use optic_diff_engine::{analyze_undocumented_bodies, EndpointCommand, SpecCommand};
use optic_diff_engine::{
BodyAnalysisLocation, HttpInteraction, SpecChunkEvent, SpecEvent, SpecIdGenerator,
SpecProjection, TrailObservationsResult,
};
pub const SUBCOMMAND_NAME: &'s... | {
commands: Vec<SpecCommand>,
status_code: u16,
#[serde(skip)]
path_id: String,
#[serde(skip)]
method: String,
#[serde(flatten)]
body_descriptor: Option<EndpointBodyDescriptor>,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct EndpointBodyDescriptor {
content_type: ... | EndpointResponseBody | identifier_name |
provision_spec.go | .AddCephVersionLabelToJob(c.clusterInfo.CephVersion, job)
err = c.clusterInfo.OwnerInfo.SetControllerReference(job)
if err != nil {
return nil, err
}
// override the resources of all the init containers and main container with the expected osd prepare resources
c.applyResourcesToAllContainers(&podSpec.Spec, cep... | {
volumeMounts = append(volumeMounts, getPvcMetadataOSDBridgeMount(osdProps.metadataPVC.ClaimName))
configuredDevices = append(configuredDevices,
config.ConfiguredDevice{
ID: fmt.Sprintf("/srv/%s", osdProps.metadataPVC.ClaimName),
StoreConfig: config.NewStoreConfig(),
})
} | conditional_block | |
provision_spec.go | VCWalInitContainer("/wal", osdProps))
}
} else {
podSpec.Spec.NodeSelector = map[string]string{v1.LabelHostname: osdProps.crushHostname}
}
job := &batch.Job{
ObjectMeta: metav1.ObjectMeta{
Name: k8sutil.TruncateNodeNameForJob(prepareAppNameFmt, osdProps.crushHostname),
Namespace: c.clusterInfo.Name... | marshalledDevices, err := json.Marshal(configuredDevices)
if err != nil {
return v1.Container{}, errors.Wrapf(err, "failed to JSON marshal configured devices for node %q", osdProps.crushHostname)
}
envVars = append(envVars, dataDevicesEnvVar(string(marshalledDevices)))
} else if osdProps.selection.DeviceFil... | {
envVars := c.getConfigEnvVars(osdProps, k8sutil.DataDir, true)
// enable debug logging in the prepare job
envVars = append(envVars, setDebugLogLevelEnvVar(true))
// only 1 of device list, device filter, device path filter and use all devices can be specified. We prioritize in that order.
if len(osdProps.devic... | identifier_body |
provision_spec.go | VCWalInitContainer("/wal", osdProps))
}
} else {
podSpec.Spec.NodeSelector = map[string]string{v1.LabelHostname: osdProps.crushHostname}
}
job := &batch.Job{
ObjectMeta: metav1.ObjectMeta{
Name: k8sutil.TruncateNodeNameForJob(prepareAppNameFmt, osdProps.crushHostname),
Namespace: c.clusterInfo.Name... | podMeta := metav1.ObjectMeta{
Name: AppName,
Labels: map[string]string{
k8sutil.AppAttr: prepareAppName,
k8sutil.ClusterAttr: c.clusterInfo.Namespace,
OSDOverPVCLabelKey: osdProps.pvc.ClaimName,
},
Annotations: map[string]string{},
}
cephv1.GetOSDPrepareAnnotations(c.spec.Annotations).ApplyToO... | }
k8sutil.RemoveDuplicateEnvVars(&podSpec)
| random_line_split |
provision_spec.go | WalInitContainer("/wal", osdProps))
}
} else {
podSpec.Spec.NodeSelector = map[string]string{v1.LabelHostname: osdProps.crushHostname}
}
job := &batch.Job{
ObjectMeta: metav1.ObjectMeta{
Name: k8sutil.TruncateNodeNameForJob(prepareAppNameFmt, osdProps.crushHostname),
Namespace: c.clusterInfo.Namesp... | (osdProps osdProperties, copyBinariesMount v1.VolumeMount, provisionConfig *provisionConfig) (v1.Container, error) {
envVars := c.getConfigEnvVars(osdProps, k8sutil.DataDir, true)
// enable debug logging in the prepare job
envVars = append(envVars, setDebugLogLevelEnvVar(true))
// only 1 of device list, device fi... | provisionOSDContainer | identifier_name |
lib.rs | make_tuple ($first, $next), $($rest,)*)
);
(
$ty:ident < $($ty_params:ty),+ >;
limited {$($limited:ident: $limited_from:expr => $limited_to:expr),+}
limited_min {$($limited_min:ident: $limited_min_from:expr => $limited_min_to:expr),*}
unlimited {$($unlimited:ident: $unlimited_fr... | darken | identifier_name | |
lib.rs | //! use palette::{Srgb, Pixel};
//!
//! // This works for any (even non-RGB) color type that can have the
//! // buffer element type as component.
//! let color_buffer: &mut [Srgb<u8>] = Pixel::from_raw_slice_mut(&mut image_buffer);
//! ```
//!
//! * If you are getting your colors from the GPU, in a game or other graph... | println!("ok")
} | random_line_split | |
lib.rs | to = $limited_min_to;
let diff = to - from;
let $limited_min = (1..11).map(|i| to + (i as f64 / 10.0) * diff);
)*
$(
let from = $unlimited_from;
let to = $unlimited_to;
let diff = to - f... | {
T::from_f64(c)
} | identifier_body | |
chord.js | Bn.push(paper.rect(legendArea[0] + 10, legendArea[1] + 10 + (20 + 3) * i, 180, 20).attr({
"fill": "#ebebeb",
"stroke": "none"
//"r": 3
}).hide());
//色框
paper.rect(legendArea[0] + 10 + 3, legendArea[1] + 10 + (20 + 3) * i + 6, 16, 8).attr({
"fill": this.getColor... | };
var mouseoverChord = function () {
floatTag.html('<div style="text-align: center;margin:auto;color:#ffffff">' + this.data('text') + '</div>');
floatTag.css({
"visibility": "visible"
});
that.underBn.forEach(function (d) {
d.hide();
| //fade(this.data("donutIndex"), 0.6);
that.underBn[index].hide();
| conditional_block |
chord.js | Bn.push(paper.rect(legendArea[0] + 10, legendArea[1] + 10 + (20 + 3) * i, 180, 20).attr({
"fill": "#ebebeb",
"stroke": "none"
//"r": 3
}).hide());
//色框
paper.rect(legendArea[0] + 10 + 3, legendArea[1] + 10 + (20 + 3) * i + 6, 16, 8).attr({
"fill": this.getColor... |
//添加透明效果
var mouseOverDonut = function () {
floatTag.html('<div style = "text-align: center;margin:auto;color:'
//+ jqNode.color
+
"#ffffff" + '">' + this.data('text') + '</div>');
floatTag.css({
"visibility": "visible"
});
that.underBn.forEach(fu... | random_line_split | |
provision.go | provisionFile = args[1]
// Load the provided provisioner file
if _, err := os.Stat(provisionFile); err != nil {
SetError(fmt.Errorf("Could not read PROVISIONER '%s' , error: %v", provisionFile, err), 1)
return
}
b, err := ioutil.ReadFile(provisionFile)
if err != nil {
SetError(fmt.Errorf("Could not... |
err = initKernels()
if err != nil {
SetError(err, 13)
return
}
f, err := ioutil.TempFile(os.TempDir(), "vorteil.disk")
if err != nil {
SetError(err, 14)
return
}
defer os.Remove(f.Name())
defer f.Close()
err = vdisk.Build(context.Background(), f, &vdisk.BuildArgs{
WithVCFGDefaults: ... | {
SetError(err, 12)
return
} | conditional_block |
provision.go | provisionFile = args[1]
// Load the provided provisioner file
if _, err := os.Stat(provisionFile); err != nil {
SetError(fmt.Errorf("Could not read PROVISIONER '%s' , error: %v", provisionFile, err), 1)
return
}
b, err := ioutil.ReadFile(provisionFile)
if err != nil {
SetError(fmt.Errorf("Could not... | () {
f := provisionCmd.Flags()
f.StringVarP(&flagKey, "key", "k", "", "vrepo authentication key")
f.StringVarP(&provisionName, "name", "n", "", "Name of the resulting image on the remote platform.")
f.StringVarP(&provisionDescription, "description", "D", "", "Description for the resulting image, if supported by th... | init | identifier_name |
provision.go | provisionFile = args[1]
// Load the provided provisioner file
if _, err := os.Stat(provisionFile); err != nil {
SetError(fmt.Errorf("Could not read PROVISIONER '%s' , error: %v", provisionFile, err), 1)
return
}
b, err := ioutil.ReadFile(provisionFile)
if err != nil {
SetError(fmt.Errorf("Could not... | f.StringVarP(&provisionPassPhrase, "passphrase", "s", "", "Passphrase used to decrypt encrypted provisioner data.")
}
var provisionersCmd = &cobra.Command{
Use: "provisioners",
Short: "Helper commands for working with Vorteil provisioners",
Long: ``,
Example: ``,
}
var provisionersNewCmd = &cobra.Comman... | f.BoolVarP(&provisionReadyWhenUsable, "ready-when-usable", "r", false, "Return successfully as soon as the operation is complete, regardless of whether or not the platform is still processing the image.") | random_line_split |
provision.go | provisionFile = args[1]
// Load the provided provisioner file
if _, err := os.Stat(provisionFile); err != nil {
SetError(fmt.Errorf("Could not read PROVISIONER '%s' , error: %v", provisionFile, err), 1)
return
}
b, err := ioutil.ReadFile(provisionFile)
if err != nil {
SetError(fmt.Errorf("Could not... |
var provisionersCmd = &cobra.Command{
Use: "provisioners",
Short: "Helper commands for working with Vorteil provisioners",
Long: ``,
Example: ``,
}
var provisionersNewCmd = &cobra.Command{
Use: "new",
Short: "Add a new provisioner.",
}
var (
provisionersNewPassphrase string
// Google Cloud Platf... | {
f := provisionCmd.Flags()
f.StringVarP(&flagKey, "key", "k", "", "vrepo authentication key")
f.StringVarP(&provisionName, "name", "n", "", "Name of the resulting image on the remote platform.")
f.StringVarP(&provisionDescription, "description", "D", "", "Description for the resulting image, if supported by the p... | identifier_body |
NumberPicker.js | (obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && ... | _interopRequireWildcard | identifier_name | |
NumberPicker.js | ") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = h... |
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSy... | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
NumberPicker.js | function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var ... | else if (key === 'ArrowUp') {
event.preventDefault();
increment(event);
}
});
const handleChange = (rawValue, originalEvent = null) => {
let nextValue = clamp(rawValue, min, max);
if (value !== nextValue) (0, _WidgetHelpers.notify)(onChange, [nextValue, {
rawValue,
originalEven... | {
event.preventDefault();
decrement(event);
} | conditional_block |
NumberPicker.js | });
exports.default = void 0;
var _classnames = _interopRequireDefault(require("classnames"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _uncontrollable = require("uncontrollable");
var _Button = _interopRequireDefault(require("./But... | random_line_split | ||
imgur.js | canvas'),
ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < srcOrientation && srcOrientation < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.heig... |
readPic(this.files[i]);
}
| conditional_block | |
imgur.js | (image, orientation = 1) {
var base64result = image.replace(/^data:image\/[a-z]+;base64,/, "");
console.log("Image is less than 4MB")
queryVisionAPI(base64result);
}
// Sends the image to Imgur to be stored and then Vision.
// Use if image is greater than 4MB.
// Requires a base64Image string with the prep... | sendImageDirect | identifier_name | |
imgur.js | ": `Client-ID ${apiKey.imgur_client_id}`
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function(response) {
var res = JSON.parse(response);
console.log(res);
queryVisionAPI(r... | switch (srcOrientation) {
case 2:
ctx.transform(-1, 0, 0, 1, width, 0);
break;
case 3:
ctx.transform(-1, 0, 0, -1, width, height);
break;
case 4:
ctx.transform(1, 0, 0, -1, 0, height);
... | {
console.log("Transforming image, please wait");
var img = new Image();
img.onload = function() {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
// set proper canvas dimensions befor... | identifier_body |
imgur.js | != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return callback(-1);
};
reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
};
//from https://stackoverflow.com/a/40867559/8630411
//Resets the orientation of an base64 image url string
// based on the orientation f... | $(this).css('color', '#31708f');
var files = event.originalEvent.dataTransfer.files;
console.log(files.length === 0); | random_line_split | |
Model.py | -59D特征
ninetyDf, woe_ninety, iv_ninety = custom_bins(self.data.Label, self.data['90D'], cut_ninety) # 90D特征
sixtyDf, woe_sixty, iv_sixty = custom_bins(self.data.Label, self.data['60-89D'], cut_sixty) # 60-89D特征
ageDf, cut_age, woe_age, iv_age = optimal_bins(self.data.Label, self.data.Age, n=1... | def train(self):
warnings.filterwarnings('ignore') # 忽略弹出的warnings
data = pd.read_csv('datasets/cs-training.csv')
data = data.iloc[:, 1:] # 舍弃Unnamed: 0列 | random_line_split | |
Model.py | # 根据传入的数据信息构造一个字典
dic = {"Label": 1, "90D": info_list[0], "RevolvingRatio": info_list[1], '30-59D': info_list[2],
'60-89D': info_list[3], 'Age': info_list[4]}
# print(self.data)
# 插入要预测的信息
self.data = self.data[['Label', '90D', 'RevolvingRatio', '30-59D', '60-89D', 'A... | )
| identifier_name | |
Model.py | 边界值列表
:return: 统计值、woe值、iv值
"""
r = 0
total_bad = Y.sum()
total_good = Y.count() - total_bad
# 等距分箱
df1 = pd.DataFrame({'X': X, 'Y': Y, 'bin': pd.cut(X, binList)})
df2 = df1.groupby('bin', as_index=True)
r, p = stats.spearmanr(df2.mean().X, df2.mean().Y)
# 计算woe值和iv值
df3 = pd... | "
:param Y: 目标变量
:param X: 待分箱特征
:param binList: 分箱 | conditional_block | |
Model.py | [ninf, 414, 1209, 2518, pinf]
# 计算统计值、woe 和iv
thirtyDf, woe_thirty, iv_thirty = custom_bins(self.data.Label, self.data['30-59D'], cut_thirty) # 30-59D特征
ninetyDf, woe_ninety, iv_ninety = custom_bins(self.data.Label, self.data['90D'], cut_ninety) # 90D特征
sixtyDf, woe_sixty, iv_sixty = ... | 四舍五入并保留一位小数点
self.data.loc[(self.data['MonthlyIncome'].isnull()), 'MonthlyIncome'] = pred # 填补缺失值
# Dependents特征处理
self.data['Dependents'].fillna(self.data['Dependents'].mode()[0], inplace=True) # 这里采用众数填充
# 处理百分比类异常值
# RevolvingRatio特征
ruulDf = self.data[self.data['Rev... | identifier_body | |
ledger.go | rlib.GetAccountActivity(bid, lid, &lm.Dt, dt)
return bal, lm
}
// LMStates is an array of strings describing the meaning of the states a Ledger Marker can have.
var LMStates = []string{
"open", "closed", "locked", "initial",
}
// getLedgerGrid returns a list of ARs for w2ui grid
// wsdoc {
// @Title list ARs
// ... | active := "active"
if 1 == acct.Status {
active = "inactive"
}
posts := "yes"
if acct.AllowPost == 0 {
posts = "no"
}
bal, lm := GetAccountBalance(acct.BID, acct.LID, &dt)
state := "??"
j := int(lm.State)
if 0 <= j && j <= 3 {
state = LMStates[j]
}
var lg = LedgerGrid{
Recid: ... | {
funcname := "getLedgerGrid"
var (
err error
g SearchLedgersResponse
)
rows, err := rlib.RRdb.Prepstmt.GetLedgersForGrid.Query(d.BID, d.wsSearchReq.Limit, d.wsSearchReq.Offset)
if err != nil {
fmt.Printf("%s: Error from DB Query: %s\n", funcname, err.Error())
SvcGridErrorReturn(w, err, funcname)
retu... | identifier_body |
ledger.go | URL /v1/ars/:BUI
// @Method GET
// @Synopsis Get Account Rules
// @Description Get all ARs associated with BID
// @Desc By default, the search is made for receipts from "today" to 31 days prior.
// @Input WebGridSearchRequest
// @Response SearchLedgersResponse
// wsdoc }
func getLedgerGrid(w http.ResponseWriter, ... | // "AR.ARID",
// "AR.Name",
// "AR.ARType", | random_line_split | |
ledger.go | (bid, lid int64, dt *time.Time) (float64, rlib.LedgerMarker) {
lm := rlib.GetRALedgerMarkerOnOrBeforeDeprecated(bid, lid, 0, dt) // find nearest ledgermarker, use it as a starting point
bal, _ := rlib.GetAccountActivity(bid, lid, &lm.Dt, dt)
return bal, lm
}
// LMStates is an array of strings describing the meaning... | GetAccountBalance | identifier_name | |
ledger.go | rlib.GetAccountActivity(bid, lid, &lm.Dt, dt)
return bal, lm
}
// LMStates is an array of strings describing the meaning of the states a Ledger Marker can have.
var LMStates = []string{
"open", "closed", "locked", "initial",
}
// getLedgerGrid returns a list of ARs for w2ui grid
// wsdoc {
// @Title list ARs
// ... |
g.Status = "success"
g.Total = int64(len(g.Records))
w.Header().Set("Content-Type", "application/json")
SvcWriteResponse(&g, w)
}
// // SvcFormHandlerAR formats a complete data record for a person suitable for use with the w2ui Form
// // For this call, we expect the URI to contain the BID and the ARID as follow... | {
SvcGridErrorReturn(w, err, funcname)
return
} | conditional_block |
client.go | to start command: %s\n", err)
}
}
func (wp *wsPty) Stop() {
wp.Pty.Close()
wp.Cmd.Wait()
}
var cmdFlag string
var messageData interface{}
func init() {
flag.StringVar(&cmdFlag, "cmd", "/bin/bash", "command to execute on slave side of the pty")
}
func main() {
wp := wsPty{}
wp.Start()
var conHd = make(map[... | enResult, _ := ParseString(args[0])
messageData = DecryptWithAES("asdasdasdasdasd", enResult)
//fmt.Println(cmd)
//wp.Pty.Write([]byte(cmd))
})
} else if messageData == "cmd" {
fmt.Println("wqeqweqwqw")
} else {
// fmt.Println("qweqwerrrrtytyyyqwwetrtyutuiop")
// decodeBytes, e... | fmt.Println("pppppppppppppppppppppppppppp")
fmt.Println(conHd["1"])
sub.On("message", func(args ...interface{}) { | random_line_split |
client.go | to start command: %s\n", err)
}
}
func (wp *wsPty) Stop() {
wp.Pty.Close()
wp.Cmd.Wait()
}
var cmdFlag string
var messageData interface{}
func init() {
flag.StringVar(&cmdFlag, "cmd", "/bin/bash", "command to execute on slave side of the pty")
}
func main() { | p := wsPty{}
wp.Start()
var conHd = make(map[string]*websocket.Conn)
fmt.Println(RsaEncrypt([]byte("aiyouwei")))
var Header http.Header = map[string][]string{
"moja": {"ccccc, asdasdasdasd"},
"terminal": {"en-esadasdasdwrw"},
"success": {"dasdadas", "wdsadaderew"},
"ticket": {RsaEncrypt([]byte("aiy... |
w | identifier_name |
client.go | start command: %s\n", err)
}
}
func (wp *wsPty) Stop() {
wp.Pty.Close()
wp.Cmd.Wait()
}
var cmdFlag string
var messageData interface{}
func init() {
flag.StringVar(&cmdFlag, "cmd", "/bin/bash", "command to execute on slave side of the pty")
}
func main() {
wp := wsPty{}
wp.Start()
var conHd = make(map[str... | uestHeader http.Header) {
stopper := make(chan bool)
go s.startRead(conn, stopper)
go s.startWrite(conn, stopper)
select {
case <-stopper:
go s.reconnect(stateReady, requestHeader)
conn.Close()
case <-s.closeChan:
conn.Close()
}
}
func (s *socketClient) startRead(conn protocol.Conn, stopper chan bool) {
... | e()
}
}
}
func (s *socketClient) start(conn protocol.Conn, req | conditional_block |
client.go | to start command: %s\n", err)
}
}
func (wp *wsPty) Stop() {
wp.Pty.Close()
wp.Cmd.Wait()
}
var cmdFlag string
var messageData interface{}
func init() {
flag.StringVar(&cmdFlag, "cmd", "/bin/bash", "command to execute on slave side of the pty")
}
func main() {
wp := wsPty{}
wp.Start()
var conHd = make(map[... | } else {
s.emit(m.Event, m.Payloads...)
}
| p, err := conn.Read()
if err != nil {
s.emit(EventError, err)
close(stopper)
return
}
switch p.Type {
case protocol.PacketTypeOpen:
h, err := p.DecodeHandshake()
if err != nil {
s.emit(EventError, err)
} else {
go s.startPing(h, stopper)
}
case protocol.PacketTypePing:
s.outCha... | identifier_body |
contfilter.go | .Errorf("malformed edit distance tag: %s", edit_tag)
}
edit_dist, err := strconv.Atoi(edit_tag[5:])
if err != nil {
return 0, 0, fmt.Errorf("failed to parse edit dist: %s", edit_tag)
}
return match_len, edit_dist, nil
}
func OpenLogger() {
if args.LogFilename == "" {
logger = log.New(os.Stderr, "", 0)
} els... |
out := BamWriter{}
outfp, err := out.Open(args.Output)
if err != nil {
logger.Fatal(err)
}
io.WriteString(outfp, header)
reads_kept := 0
read_mates_kept := 0
total_reads := 0
total_read_mates := 0
ercc := 0
considered := 0
too_short := 0
too_diverged := 0
err = func() error {
defer scanner.Done()... | {
logger.Fatal(err)
} | conditional_block |
contfilter.go | .Errorf("malformed edit distance tag: %s", edit_tag)
}
edit_dist, err := strconv.Atoi(edit_tag[5:])
if err != nil {
return 0, 0, fmt.Errorf("failed to parse edit dist: %s", edit_tag)
}
return match_len, edit_dist, nil
}
func OpenLogger() {
if args.LogFilename == "" {
logger = log.New(os.Stderr, "", 0)
} els... |
func main() {
var kept_percent float64
flag.Parse()
contamination := flag.Args()
startedAt := time.Now()
if len(contamination) == 0 {
logger.Println("must specify at least one contamination mapping BAM file")
os.Exit(1)
}
if args.Output == "" {
logger.Println("must specify -output file")
os.Exit(1)
}... | } | random_line_split |
contfilter.go | .Errorf("malformed edit distance tag: %s", edit_tag)
}
edit_dist, err := strconv.Atoi(edit_tag[5:])
if err != nil {
return 0, 0, fmt.Errorf("failed to parse edit dist: %s", edit_tag)
}
return match_len, edit_dist, nil
}
func OpenLogger() {
if args.LogFilename == "" {
logger = log.New(os.Stderr, "", 0)
} els... | if args.Sample == "" {
scanner.OpenStdin()
} else {
if err := scanner.OpenBam(args.Sample); err != nil {
logger.Fatal(err)
}
}
reads_found := make([]int, len(contamination))
reads_filtered := make([]int, len(contamination))
contScanners := make([]BamScanner, len(contamination))
rejected := make([]bool,... | {
var kept_percent float64
flag.Parse()
contamination := flag.Args()
startedAt := time.Now()
if len(contamination) == 0 {
logger.Println("must specify at least one contamination mapping BAM file")
os.Exit(1)
}
if args.Output == "" {
logger.Println("must specify -output file")
os.Exit(1)
}
OpenLogger... | identifier_body |
contfilter.go | .Errorf("malformed edit distance tag: %s", edit_tag)
}
edit_dist, err := strconv.Atoi(edit_tag[5:])
if err != nil {
return 0, 0, fmt.Errorf("failed to parse edit dist: %s", edit_tag)
}
return match_len, edit_dist, nil
}
func OpenLogger() {
if args.LogFilename == "" {
logger = log.New(os.Stderr, "", 0)
} els... | () {
logger.Println("command:", strings.Join(os.Args, " "))
blob, err := json.MarshalIndent(args, "", " ")
if err != nil {
logger.Fatal("failed to marshal arguments")
}
logger.Println(string(blob))
}
func MatchesErcc(mate1, mate2 []string) bool {
return args.Ercc &&
(strings.Contains(mate1[2], "ERCC") || ... | LogArguments | identifier_name |
autogen.py | =[])
# fix the name of the function pointer
typedecl = self._find_typedecl(newnode)
typedecl.declname = self.ctx_name()
return toC(newnode)
def trampoline_def(self):
# static inline HPy HPyModule_Create(HPyContext ctx, HPyModuleDef *def) {
# return ctx->ctx_Modu... | (self, filename):
self.ast = pycparser.parse_file(filename, use_cpp=True)
#self.ast.show()
self.collect_declarations()
def get(self, name):
for d in self.declarations:
if d.name == name:
return d
raise KeyError(name)
def collect_declarations(... | __init__ | identifier_name |
autogen.py | =[])
# fix the name of the function pointer
typedecl = self._find_typedecl(newnode)
typedecl.declname = self.ctx_name()
return toC(newnode)
def trampoline_def(self):
# static inline HPy HPyModule_Create(HPyContext ctx, HPyModuleDef *def) {
# return ctx->ctx_Modu... |
def ctx_impl_name(self):
return '(HPy){CONSTANT_%s}' % (self.name.upper(),)
def ctx_decl(self):
return toC(self.node)
def trampoline_def(self):
return None
def ctx_pypy_type(self):
return 'struct _HPy_s'
def pypy_stub(self):
return ''
class FuncDeclVis... | return self.name | identifier_body |
autogen.py | =[])
# fix the name of the function pointer
typedecl = self._find_typedecl(newnode)
typedecl.declname = self.ctx_name()
return toC(newnode)
def trampoline_def(self):
# static inline HPy HPyModule_Create(HPyContext ctx, HPyModuleDef *def) {
# return ctx->ctx_Modu... |
result = '%s(%s)' % (pyfunc, ', '.join(args))
if return_type == 'HPy':
result = '_py2h(%s)' % result
return result
#
lines = []
w = lines.append
pyfunc = self.cpython_name
if not pyfunc:
raise ValueError(f"Cannot ge... | if toC(p.type) == 'HPyContext':
continue
elif toC(p.type) == 'HPy':
arg = '_h2py(%s)' % p.name
else:
arg = p.name
args.append(arg) | conditional_block |
autogen.py | =[])
# fix the name of the function pointer
typedecl = self._find_typedecl(newnode)
typedecl.declname = self.ctx_name()
return toC(newnode)
def trampoline_def(self):
# static inline HPy HPyModule_Create(HPyContext ctx, HPyModuleDef *def) {
# return ctx->ctx_Modu... | def collect_declarations(self):
v = FuncDeclVisitor(convert_name)
v.visit(self.ast)
self.declarations = v.declarations
def gen_ctx_decl(self):
# struct _HPyContext_s {
# int ctx_version;
# HPy h_None;
# ...
# HPy (*ctx | return d
raise KeyError(name)
| random_line_split |
appStore.ts | //喜欢的音乐列表
@observable playHistorys: any[] //播放历史
@observable audio: any //audio
@observable songReady: boolean //歌曲是否已经准备好了播放
@observable currentTime: number //歌曲播放的时间
@observable isShowPlaylist: boolean //是否显示播放列表
@observable lyric: any //歌词
@observable playingLyric: string /... | * 获取歌曲歌词
* @param id
* @returns {Promise.<void>}
*/
@action
getLyric = async (id) => {
const res = await get(`/lyric?id=${id}`)
runInAction(() => {
this.lyric = res ? new Lyric(res, this.handler) : null
this.lyric && this.lyric.play()
})
}
... | /** | random_line_split |
appStore.ts | 的音乐列表
@observable playHistorys: any[] //播放历史
@observable audio: any //audio
@observable songReady: boolean //歌曲是否已经准备好了播放
@observable currentTime: number //歌曲播放的时间
@observable isShowPlaylist: boolean //是否显示播放列表
@observable lyric: any //歌词
@observable playingLyric: string //正在播放... |
@action
setStore = (obj) => {
if (Object.prototype.toString.call(obj) !== '[object Object]') {
return
}
for (let [key, va
lue] of Object.entries(obj)) {
this[key] = value
}
}
@action
setSheetSongs = (obj) => {
this.sheetSongs = obj
... | m => item.name).join('/')
song.image = song.al ? song.al.picUrl : ''
song.url = `https://music.163.com/song/media/outer/url?id=${song.id}.mp3`
song.duration = (song.dt / 1000) || (song.duration) / 1000 || 0
}
return song
}
/**
* 获取播放时间的百分比
* @return... | identifier_body |
appStore.ts | 喜欢的音乐列表
@observable playHistorys: any[] //播放历史
@observable audio: any //audio
@observable songReady: boolean //歌曲是否已经准备好了播放
@observable currentTime: number //歌曲播放的时间
@observable isShowPlaylist: boolean //是否显示播放列表
@observable lyric: any //歌词
@observable playingLyric: string //正在... | this.songReady = false
}
/**
* 暂停/播放音乐
*/
@action
togglePlay = () => {
clearTimeout(this.errorTimer)
if (this.playing) {
this.audio && this.audio.pause()
} else {
this.audio && this.audio.play()
}
this.lyric && this.lyric.togg... | }
this.currentIndex = currentIndex
| conditional_block |
appStore.ts | andSider: boolean //侧边栏是否展开
@observable playing: boolean //歌曲是否正在播放
@observable playlist: any[] //播放列表
@observable mode: number //播放模式
@observable currentIndex: number //当前播放歌曲索引
@observable isFullScreen: boolean //是否全屏播放音乐
@observable likeSongs: any[] //喜欢的音乐列表
@observable play... | le isExp | identifier_name | |
qt_events.py |
#@+node:ekr.20110605121601.18540: *3* filter.eventFilter & helpers
def eventFilter(self, obj, event):
"""Return False if Qt should handle the event."""
c, k = self.c, self.c.k
#
# Handle non-key events first.
if not g.app:
return False # For unit tests, but ... | """Ctor for LeoQtEventFilter class."""
super().__init__()
self.c = c
self.w = w # A leoQtX object, *not* a Qt object.
self.tag = tag
# Debugging.
self.keyIsActive = False
# Pretend there is a binding for these characters.
close_flashers = c.config.getStri... | identifier_body | |
qt_events.py | ])
layout_events = [
(e.Type.ChildAdded, 'child-added'), # 68
(e.Type.ChildRemoved, 'child-removed'), # 71
(e.Type.DynamicPropertyChange, 'dynamic-property-change'), # 170
(e.Type.FontChange, 'font-change'), # 97
(e.Type.LayoutRequest, ... | focus_d.get(et) or et
g.trace(f"None {t}")
| conditional_block | |
qt_events.py | # pylint: disable=no-member
key_events.extend([
(e.Type.InputMethodQuery, 'input-method-query'), # 207
])
layout_events = [
(e.Type.ChildAdded, 'child-added'), # 68
(e.Type.ChildRemoved, 'child-removed'), # 71
(e.Type.DynamicPropert... | g.trace(f"{t:20} {w.__class__}")
return
if w is None: | random_line_split | |
qt_events.py | (self, obj, event):
"""Return False if Qt should handle the event."""
c, k = self.c, self.c.k
#
# Handle non-key events first.
if not g.app:
return False # For unit tests, but g.unitTesting may be False!
if not self.c.p:
return False # Startup.
... | eventFilter | identifier_name | |
list.rs | use kas::geom::Rect;
/// A generic row widget
///
/// See documentation of [`List`] type.
pub type Row<W> = List<Horizontal, W>;
/// A generic column widget
///
/// See documentation of [`List`] type.
pub type Column<W> = List<Vertical, W>;
/// A row of boxed widgets
///
/// This is parameterised over handler messag... | use crate::{AlignHints, Directional, Horizontal, Vertical};
use crate::{CoreData, Layout, TkAction, Widget, WidgetCore, WidgetId}; | random_line_split | |
list.rs | /// A row of boxed widgets
///
/// This is parameterised over handler message type.
///
/// See documentation of [`List`] type.
pub type BoxRow<M> = BoxList<Horizontal, M>;
/// A column of boxed widgets
///
/// This is parameterised over handler message type.
///
/// See documentation of [`List`] type.
pub type BoxCol... | (&mut self, mgr: &mut Manager) {
if !self.widgets.is_empty() {
mgr.send_action(TkAction::Reconfigure);
}
self.widgets.clear();
}
/// Append a child widget
///
/// Triggers a [reconfigure action](Manager::send_action).
pub fn push(&mut self, mgr: &mut Manager, wid... | clear | identifier_name |
list.rs | /// A row of boxed widgets
///
/// This is parameterised over handler message type.
///
/// See documentation of [`List`] type.
pub type BoxRow<M> = BoxList<Horizontal, M>;
/// A column of boxed widgets
///
/// This is parameterised over handler message type.
///
/// See documentation of [`List`] type.
pub type BoxCol... |
#[inline]
fn core_data_mut(&mut self) -> &mut CoreData {
&mut self.core
}
#[inline]
fn widget_name(&self) -> &'static str {
"List"
}
#[inline]
fn as_widget(&self) -> &dyn Widget {
self
}
#[inline]
fn as_widget_mut(&mut self) -> &mut dyn Widget {
... | {
&self.core
} | identifier_body |
my-orders.js | { value: 'title', label: 'Título' },
{ value: 'responsible', label: 'Responsável' },
{ value: 'status', label: 'Status' },
{ value: 'order_date', label: 'Data do pedido' },
];
const itemsPerPage = 5;
const getTechnologyDataGrid = (order, openModal, setCurrentOrder) => {
const {
id,
status,
created_at,
tec... |
return router.push({
pathname,
query,
});
};
return (
<Container>
<Protected>
<UserProfile />
{currentOrder ? (
<OrderMessages
isBuyer
currentOrder={currentOrder}
backToList={() => setCurrentOrder(null)}
/>
) : (
<MainContentContainer>
{orders.length... | const shouldOrderAsc = order === orderEnum.DESC && currentSort.by !== orderBy;
query.order = shouldOrderAsc ? orderEnum.ASC : order;
query.orderBy = orderBy; | random_line_split |
database.py | None) # skip headers
kwargs['update'].rows_created = sum(1 for row in reader)
kwargs['update'].save()
if os.path.isfile(temp_file_path):
os.remove(temp_file_path)
def upsert_query(table_name, row, primary_key, ignore_conflict=False):
fields = ', '.join(row.keys())
upsert_... | status.page = page = paginator.page(page_num)
status.cur_idx = page.start_index() - 1
progress_callback(status) | random_line_split | |
database.py | cursor % settings.BATCH_SIZE == 0:
logger.debug("Diff cursor at: {}".format(cursor))
if not found:
count = count + 1
if count % settings.BATCH_SIZE == 0:
logger.debug('Performed csv diff on {} records'.format(count))
yield li... |
def copy_query(table_name, columns):
return 'COPY {table_name} ({fields}) FROM STDIN WITH (format csv)'.format(table_name=table_name, fields=columns)
def build_row_values(row):
t_row = tuple(row.values())
return tuple(None if x == '' else x for x in t_row)
def build_pkey_tuple(row, pkey):
tup = t... | fields = ', '.join(['{key} = %s'.format(key=key) for key in row.keys()])
keys = ' AND '.join(['{key} = %s'.format(key=key) for key in primary_key.split(', ')])
sql = 'UPDATE {table_name} SET {fields} WHERE({pk});'
return sql.format(table_name=table_name, fields=fields, pk=keys) | identifier_body |
database.py | cursor = cursor + 1
# if cursor % settings.BATCH_SIZE == 0:
logger.debug("Diff cursor at: {}".format(cursor))
if not found:
count = count + 1
if count % settings.BATCH_SIZE == 0:
logger.debug('Performed csv diff on {} r... | if count == -1:
count = count + 1
yield list(csv.reader(StringIO(new_row), delimiter=',', quotechar='"',
doublequote=True, quoting=csv.QUOTE_ALL, skipinitialspace=True))[0]
continue
found = False
# search for... | conditional_block | |
database.py | cursor % settings.BATCH_SIZE == 0:
logger.debug("Diff cursor at: {}".format(cursor))
if not found:
count = count + 1
if count % settings.BATCH_SIZE == 0:
logger.debug('Performed csv diff on {} records'.format(count))
yield li... | (model, rows, batch_size, update=None, ignore_conflict=False):
table_name = model._meta.db_table
primary_key = model._meta.pk.name
""" Inserts many row, all in the same transaction"""
rows_length = len(rows)
with connection.cursor() as curs:
try:
starting_count = model.objects.c... | batch_upsert_rows | identifier_name |
image_processor_2.0.py | _color = (255,0,0)
possible_target_color = (0,255,0)
#used to judge whether a polygon side is near vertical or near horizontal, for filtering out shapes that don't match expected target characteristics
vert_threshold = math.tan(math.radians(90-20))
horiz_threshold = math.tan(math.radia... |
def process(self):
if enable_dashboard:
self.camera_saturation = int(SmartDashboard.GetNumber(camera_saturation_title)
self.angle_to_robot = int(SmartDashboard.GetNumber(angle_to_robot_title)
self.camera_offset_postion = int(SmartDashboard.GetNumber(camera_offset_position_title)
self... | while True:
if self.img is not None:
self.process()
if self.img_path is None:
rval, self.img = self.vc.read() #might set to None
else:
self.img = imread(self.img_path) | identifier_body |
image_processor_2.0.py | _color = (255,0,0)
possible_target_color = (0,255,0)
#used to judge whether a polygon side is near vertical or near horizontal, for filtering out shapes that don't match expected target characteristics
vert_threshold = math.tan(math.radians(90-20))
horiz_threshold = math.tan(math.radia... | (self, img_path):
self.img_path = img_path
self.layout_result_windows(self.h,self.s,self.v)
self.vc = VideoCapture(0)
SmartDashboard.PutNumber(angle_to_robot_title, self.angle_to_robot)
SmartDashboard.PutNumber(camera_offset_position_title, self.camera_offset_position)
SmartDashboard.PutNumber(... | __init__ | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.