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 |
|---|---|---|---|---|
spannerautoscaler_controller.go | .Error())
log.Error(err, "failed to start syncer")
return ctrlreconcile.Result{}, err
}
log.Info("replaced syncer", "namespaced name", sa)
return ctrlreconcile.Result{}, nil
}
log.V(1).Info("checking to see if we need to calculate processing units", "sa", sa)
if !r.needCalcProcessingUnits(&sa) {
retu... | }
| random_line_split | |
spannerautoscaler_controller.go | != nil {
r.recorder.Event(&sa, corev1.EventTypeWarning, "ServiceAccountRequired", err.Error())
log.Error(err, "failed to fetch service account")
return ctrlreconcile.Result{}, err
}
// If the syncer does not exist, start a syncer.
if !syncerExists {
log.V(2).Info("syncer does not exist, starting a new sync... | {
totalCPUProduct1000 := currentCPU * currentProcessingUnits
desiredProcessingUnits := maxInt(nextValidProcessingUnits(totalCPUProduct1000/targetCPU), currentProcessingUnits-scaledownStepSize*1000)
switch {
case desiredProcessingUnits < minProcessingUnits:
return minProcessingUnits
case desiredProcessingUnits... | identifier_body | |
spannerautoscaler_controller.go | scaleDownInterval time.Duration
clock utilclock.Clock
log logr.Logger
mu sync.RWMutex
}
var _ ctrlreconcile.Reconciler = (*SpannerAutoscalerReconciler)(nil)
type Option func(*SpannerAutoscalerReconciler)
func WithSyncers(syncers map[types.NamespacedName]syncer.Syncer) Option {
return func(r *SpannerAutosc... |
return ctrlreconcile.Result{}, nil
}
// TODO: move this to the defaulting webhook
if sa.Spec.ScaleConfig.ScaledownStepSize == 0 {
sa.Spec.ScaleConfig.ScaledownStepSize = defaultScaledownStepSize
}
log.V(1).Info("resource status", "spannerautoscaler", sa)
credentials, err := r.fetchCredentials(ctx, &sa)
... | {
s.Stop()
r.mu.Lock()
delete(r.syncers, nn)
r.mu.Unlock()
log.Info("stopped syncer")
} | conditional_block |
query.go | (i.e. index >= start) in unix epoch second
EpochStart *int64 `msgpack:"epoch_start,omitempty"`
// Nanosecond of the lower time predicate
EpochStartNanos *int64 `msgpack:"epoch_start_nanos,omitempty"`
// Upper time predicate (i.e. index <= end) in unix epoch second
EpochEnd *int64 `msgpack:"epoch_end,omitempty"`
... | } else {
// Query
resp, err = s.executeQuery(&reqs.Requests[i])
if err != nil {
return err
}
}
response.Responses = append(response.Responses, *resp)
}
return nil
}
func (s *DataService) executeSQL(sqlStatement string) (*QueryResponse, error) {
queryTree, err := sqlparser.BuildQueryTree(sqlSt... | return err
} | random_line_split |
query.go | should be from the lower
LimitFromStart *bool `msgpack:"limit_from_start,omitempty"`
// Array of column names to be returned
Columns []string `msgpack:"columns,omitempty"`
// Support for functions is experimental and subject to change
Functions []string `msgpack:"functions,omitempty"`
}
type MultiQueryRequest s... | {
return &QueryService{
catalogDir: catDir,
}
} | identifier_body | |
query.go | i.e. index >= start) in unix epoch second
EpochStart *int64 `msgpack:"epoch_start,omitempty"`
// Nanosecond of the lower time predicate
EpochStartNanos *int64 `msgpack:"epoch_start_nanos,omitempty"`
// Upper time predicate (i.e. index <= end) in unix epoch second
EpochEnd *int64 `msgpack:"epoch_end,omitempty"`
//... |
csm := io.NewColumnSeriesMap()
for _, ds := range resp.Responses { // Datasets are packed in a slice, each has a NumpyMultiDataset inside
nmds := ds.Result
for tbkStr, startIndex := range nmds.StartIndex {
cs, err := nmds.ToColumnSeries(startIndex, nmds.Lengths[tbkStr])
if err != nil {
return nil, er... | {
return nil, nil
} | conditional_block |
query.go | (i.e. index >= start) in unix epoch second
EpochStart *int64 `msgpack:"epoch_start,omitempty"`
// Nanosecond of the lower time predicate
EpochStartNanos *int64 `msgpack:"epoch_start_nanos,omitempty"`
// Upper time predicate (i.e. index <= end) in unix epoch second
EpochEnd *int64 `msgpack:"epoch_end,omitempty"`
... | (req *QueryRequest) (*QueryResponse, error) {
/*
Assumption: Within each TimeBucketKey, we have one or more of each category, with the exception of
the AttributeGroup (aka Record Format) and Timeframe
Within each TimeBucketKey in the request, we allow for a comma separated list of items, e.g.:
destination1.it... | executeQuery | identifier_name |
d05.go | .areas[k]
}
for k := range partialSolution.employeesByArea {
d.employeesByArea[k] = append(d.employeesByArea[k], partialSolution.employeesByArea[k]...)
}
for k, v := range partialSolution.salaryBySurname {
d.salaryBySurname.merge(k, v)
}
for k, v := range partialSolution.salaryByArea {
... | {
fmt.Printf("area_max|%s|%s %s|%.2f\n", d.areas[areaCode].name, byArea.salaries.biggest[i].name, byArea.salaries.biggest[i].surname, byArea.salaries.biggest[i].salary)
} | conditional_block | |
d05.go | e)
d.calculateSalaries(d.salaryBySurname, &surname, e)
d.calculateSalaries(d.salaryByArea, &area, e)
_, ok := d.employeesByArea[area]
if !ok {
d.employeesByArea[area] = []*employee{}
}
d.employeesByArea[area] = append(d.employeesByArea[area], e)
d.employeeCount++
}
// parseArea parses an area from the input... | }
wg.Done()
}()
wg.Wait() | random_line_split | |
d05.go | 16
)
// WARNING: DO NOT DO THIS AT HOME.
func unsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// newD05 creates a new `d05' value to be used as either a partial or global
// solution for the problem.
func newD05() *d05 {
return &d05{employeesByArea: map[string][]*employee{}, salaryByArea: ma... | (data []byte, block chan *d05) {
var start uint32
partialSolution := newD05()
openbracket := byte('{')
closedbracket := byte('}')
i := uint32(0)
var idx int
for {
if idx = bytes.IndexByte(data[i:], openbracket); idx == -1 {
break
}
start = i + uint32(idx)
i = start
if idx = bytes.IndexByte(data[i... | parseJSONBlock | identifier_name |
d05.go | 16
)
// WARNING: DO NOT DO THIS AT HOME.
func unsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// newD05 creates a new `d05' value to be used as either a partial or global
// solution for the problem.
func newD05() *d05 {
return &d05{employeesByArea: map[string][]*employee{}, salaryByArea: ma... |
// processEmployees receive an employee and updates the associated stats.
func (d *d05) processEmployee(e *employee) {
area := unsafeString(e.areaCode)
surname := unsafeString(e.surname)
d.updateSalaries(&d.salaries, e)
d.calculateSalaries(d.salaryBySurname, &surname, e)
d.calculateSalaries(d.salaryByArea, &are... | {
gs, ok := s[*key]
if !ok {
gs = &groupSalaryStats{}
s[*key] = gs
}
d.updateSalaries(&gs.salaries, e)
} | identifier_body |
tokens.rs | // {
OpenParen, // (
OpenSquare, // [
CloseAngle, // >
CloseCurly, // }
CloseParen, // )
CloseSquare, // ]
Colon, // :
Comma, // ,
Dot, // .
SemiColon, // ;
// Operator-like (single character)
At, ... | LessEquals, // <=
ShiftRight, // >>
GreaterEquals, // >=
// Operator-like (three characters)
ShiftLeftEquals,// <<=
ShiftRightEquals, // >>=
// Special marker token to indicate end of variable-character tokens
SpanEnd,
}
impl TokenKind {
/// Returns true if the next expecte... | OrEquals, // |=
EqualEqual, // ==
NotEqual, // !=
ShiftLeft, // << | random_line_split |
tokens.rs | // {
OpenParen, // (
OpenSquare, // [
CloseAngle, // >
CloseCurly, // }
CloseParen, // )
CloseSquare, // ]
Colon, // :
Comma, // ,
Dot, // .
SemiColon, // ;
// Operator-like (single character)
At, // @... | <'a> {
tokens: &'a Vec<Token>,
cur: usize,
end: usize,
}
impl<'a> TokenIter<'a> {
fn new(buffer: &'a TokenBuffer, start: usize, end: usize) -> Self {
Self{ tokens: &buffer.tokens, cur: start, end }
}
/// Returns the next token (may include comments), or `None` if at the end
/// of ... | TokenIter | identifier_name |
tokens.rs | // >>
GreaterEquals, // >=
// Operator-like (three characters)
ShiftLeftEquals,// <<=
ShiftRightEquals, // >>=
// Special marker token to indicate end of variable-character tokens
SpanEnd,
}
impl TokenKind {
/// Returns true if the next expected token is the special `TokenKind::SpanEnd` t... | {
debug_assert!(self.cur < self.end);
let token = &self.tokens[self.cur];
if token.kind.has_span_end() {
let span_end = &self.tokens[self.cur + 1];
debug_assert_eq!(span_end.kind, TokenKind::SpanEnd);
(token.pos, span_end.pos)
} else {
let ... | identifier_body | |
tokens.rs | Kind::BlockComment
}
/// Returns the number of characters associated with the token. May only be called on tokens
/// that do not have a variable length.
fn num_characters(&self) -> u32 {
debug_assert!(!self.has_span_end() && *self != TokenKind::SpanEnd);
if *self <= TokenKind::Equal {
... | {
self.cur += 1;
} | conditional_block | |
value_stability.rs | 0.07982762085055706],
[0.10588569388223945, -0.4734350111375454, -0.7392104908825501],
[0.11060237642041049, -0.16065642822852677, -0.8444043930440075]
]);
}
#[test]
fn unit_circle_stability() {
test_samples(2, UnitCircle, &[
[-0.9965658683520504f64, -0.08280380447614634],
[-0.9... | () {
// Gamma has 3 cases: shape == 1, shape < 1, shape > 1
test_samples(223, Gamma::new(1.0, 5.0).unwrap(), &[
5.398085f32, 9.162783, 0.2300583, 1.7235851,
]);
test_samples(223, Gamma::new(0.8, 5.0).unwrap(), &[
0.5051203f32, 0.9048302, 3.095812, 1.8566116,
]);
test_samples(223,... | gamma_stability | identifier_name |
value_stability.rs | 7.0).unwrap(), &[5.0f32, 11.0, 6.0, 5.0]);
test_samples(223, Poisson::new(7.0).unwrap(), &[9.0f64, 5.0, 7.0, 6.0]);
test_samples(223, Poisson::new(27.0).unwrap(), &[28.0f32, 32.0, 36.0, 36.0]);
}
#[test]
fn triangular_stability() {
test_samples(860, Triangular::new(2., 10., 3.).unwrap(), &[
5.7437... | 0.8134131062097899, | random_line_split | |
value_stability.rs |
}
impl<T: ApproxEq> ApproxEq for [T; 3] {
fn assert_almost_eq(&self, rhs: &Self) {
self[0].assert_almost_eq(&rhs[0]);
self[1].assert_almost_eq(&rhs[1]);
self[2].assert_almost_eq(&rhs[2]);
}
}
fn test_samples<F: Debug + ApproxEq, D: Distribution<F>>(
seed: u64, distr: D, expected: &... | {
self[0].assert_almost_eq(&rhs[0]);
self[1].assert_almost_eq(&rhs[1]);
} | identifier_body | |
slime_volleyball.js | () { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
SlimeVolleyball = (function(_super) {
__extends(SlimeVolleyball, _super);
SlimeVolleyball.name = 'SlimeVolleyball';
function SlimeVolleyball() {
return Slime... | ctor | identifier_name | |
slime_volleyball.js | ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
SlimeVolleyball = (function(_super) {
__extends(SlimeVolleyball, _super);
SlimeVolleyball.name = 'SlimeVolleyball';
function SlimeVolleyball() {
return SlimeVolleyball.__super__.constructor... | { this.constructor = child; } | identifier_body | |
slime_volleyball.js | .displayMsg += "\n You have 15 seconds each time to cross the road";
this.displayMsg += "\n\nClick anywhere to start";
this.keyState = {
left: false,
right: false,
up: false
};
if (!dontOverrideInput) {
this.world.handleInput = function() {
return _this.world.p1.handleInp... | return _this.handleMouseDown();
}, true);
};
SlimeVolleyball.prototype.refreshSprites = function() {
var gamepad, gamepadUI;
this.sprites = [];
this.sprites.push(this.bg, this.world.road, this.world.bushes, this.world.building1, this.world.building2, this.world.p1);
gamepad = new GamePad(... | }, true);
return canvas.addEventListener('touchstart', function() { | random_line_split |
text_layout_engine.rs | = *self;
node.set_width(width + lsDelta.unwrap_or(Scaled::ZERO));
node.set_glyph_count(total_glyph_count);
node.set_glyph_info_ptr(glyph_info as *mut _);
}
}
/// Stuff that should be added as XeTeXFontInst methods
trait FontInstance {
unsafe fn countGlyphs(font: *mut XeTeXFontInst) ->... | /// Only relevant if this engine actually uses graphite, hence default impl of { false }
unsafe fn initGraphiteBreaking(&mut self, _txt: &[u16]) -> bool { | random_line_split | |
text_layout_engine.rs | 16.s2 as isize) as CFDictionaryRef;
pub(crate) struct LayoutRequest<'a> {
// ```text
// let txtLen = (*node.offset(4)).b16.s1 as libc::c_long;
// let txtPtr = node.offset(6) as *mut UniChar;
// slice::from_raw_parts(txtPtr, txtLen)
// ```
pub text: &'a [u16],
// node.offset(1).b32.s1
pub... |
pub fn from_int(i: i32) -> Option<Self> {
Some(match i {
1 => GlyphEdge::Left,
2 => GlyphEdge::Top,
3 => GlyphEdge::Right,
4 => GlyphEdge::Bottom,
_ => return None,
})
}
}
#[enum_dispatch::enum_dispatch]
pub(crate) enum NativeFont {
... | {
match *self {
GlyphEdge::Left | GlyphEdge::Top => options.0,
GlyphEdge::Right | GlyphEdge::Bottom => options.1,
}
} | identifier_body |
text_layout_engine.rs | 16.s2 as isize) as CFDictionaryRef;
pub(crate) struct LayoutRequest<'a> {
// ```text
// let txtLen = (*node.offset(4)).b16.s1 as libc::c_long;
// let txtPtr = node.offset(6) as *mut UniChar;
// slice::from_raw_parts(txtPtr, txtLen)
// ```
pub text: &'a [u16],
// node.offset(1).b32.s1
pub... | (node: &'a NativeWord, justify: bool) -> LayoutRequest<'a> {
use crate::xetex_ini::FONT_LETTER_SPACE;
let text = node.text();
let line_width = node.width();
let f = node.font() as usize;
let letter_space_unit = FONT_LETTER_SPACE[f];
LayoutRequest {
text,
... | from_node | identifier_name |
bar_chart_from_csv.py | ="int",
help="size in Y dimension in px")
### display options
parser.add_option("--stack", dest="stack", action = "store_true", help="Stacked Bar Chart") ## bars in the same group go on top of each other
parser.add_option("--pair", dest="pair", action = "store_true", help="Paired Bar Chart") ## bars ... |
def bootstrap_error____old( data ):
x = np.array((data))
X = [] ## estimates
mean = np.mean(x)
for xx in xrange(1000): ## do this 1000 times
X.append( np.mean( x[np.random.randint(len(x),size=len(x))] ) )
conf = 0.95
plower = (1-conf)/2.0
pupper = 1-plower
lower_ci, upper_ci ... | if norm_cumul[i] > q:
return bins[i] | conditional_block |
bar_chart_from_csv.py | ="int",
help="size in Y dimension in px")
### display options
parser.add_option("--stack", dest="stack", action = "store_true", help="Stacked Bar Chart") ## bars in the same group go on top of each other
parser.add_option("--pair", dest="pair", action = "store_true", help="Paired Bar Chart") ## bars ... | :
Black = (0.0, 0.0, 0.0, 1.0)
DarkGray = (0.65, 0.65, 0.65, 1.0)
Gray = (0.75, 0.75, 0.75, 1.0)
LightGray = (0.85, 0.85, 0.85, 1.0)
VeryLightGray = (0.9, 0.9, 0.9, 1.0)
White = (1.0, 1.0, 1.0, 1.0)
Transparent = (0, 0, 0, 0)
Purple = (0.55, 0.0, 0.55, 1.0)
LightPurple = (0.8, 0.7, ... | Colors | identifier_name |
bar_chart_from_csv.py | ="int",
help="size in Y dimension in px")
### display options
parser.add_option("--stack", dest="stack", action = "store_true", help="Stacked Bar Chart") ## bars in the same group go on top of each other
parser.add_option("--pair", dest="pair", action = "store_true", help="Paired Bar Chart") ## bars ... |
mean_X = np.mean(X)
std_X = np.std(X)
## re-sample means are not guaranteed to be quite right.
## Conf 0.95, loc=sample mean, scale = (np.std(X, ddof=1)/np.sqrt(len(X)))
conf_int = stats.norm.interval(0.95, loc=mean_X, scale=stats.sem(X))
#toperr = (mean_X - conf_int[0])
#bo... | for xx in xrange(1000): ## do this 1000 times
X.append( np.mean( x[np.random.randint(len(x),size=len(x))] ) ) | random_line_split |
bar_chart_from_csv.py | )
def bootstrap_error( data, n_samples=None ):
x = np.array(data)
meanx = np.mean(x) #if debug:
try:
if (n_samples):
CIs = bootstrap.ci(data, scipy.mean, n_samples=n_samples)
else:
CIs = bootstrap.ci(data, scipy.mean) #, n_samples=1000)
err_siz... | p = pl.Rectangle((0,0), 1,1, fc=color)
return p | identifier_body | |
server.rs | job
/// progress and errors to clients.
/// todo: support aborting an in-progress job
pub(crate) struct PosServer {
providers: Vec<PosComputeProvider>, // gpu compute providers
pending_jobs: Vec<Job>, // pending
pub(crate) jobs: HashMap<u64, Job>, // in progress
pub(crate) config: Config... | impl Handler<AddJob> for PosServer {
async fn handle(&mut self, _ctx: &mut Context<Self>, msg: AddJob) -> Result<Job> {
let data = msg.0;
let job = Job {
id: rand::random(),
bits_written: 0,
size_bits: data.post_size_bits,
started: 0,
subm... | random_line_split | |
server.rs | Server {
providers: Vec<PosComputeProvider>, // gpu compute providers
pending_jobs: Vec<Job>, // pending
pub(crate) jobs: HashMap<u64, Job>, // in progress
pub(crate) config: Config, // compute config
pub(crate) providers_pool: Vec<u32>, // idle providers
job_status_subs... | {
self.pending_jobs.remove(idx);
} | conditional_block | |
server.rs | job
/// progress and errors to clients.
/// todo: support aborting an in-progress job
pub(crate) struct PosServer {
providers: Vec<PosComputeProvider>, // gpu compute providers
pending_jobs: Vec<Job>, // pending
pub(crate) jobs: HashMap<u64, Job>, // in progress
pub(crate) config: Config... | (&mut self, _ctx: &mut Context<Self>) {
info!("PosServer system service stopped");
}
}
impl Service for PosServer {}
impl Default for PosServer {
fn default() -> Self {
PosServer {
providers: vec![],
pending_jobs: vec![],
jobs: Default::default(),
... | stopped | identifier_name |
server.rs | ).unwrap(),
n: 512,
r: 1,
p: 1,
},
providers_pool: vec![],
job_status_subscribers: HashMap::default(),
}
}
}
#[message(result = "Result<()>")]
pub(crate) struct Init {
/// server base config - must be set when initializ... | {
// create channel for streaming job statuses
let (tx, rx) = mpsc::channel(32);
// store the sender indexed by a new unique id
self.job_status_subscribers.insert(rand::random(), tx);
// return the receiver
Ok(ReceiverStream::new(rx))
} | identifier_body | |
mod.rs | .01;
const PIECES: usize = 20;
const AGE_FACTOR: f64 = 1.0;
const MATURE_AGE: f64 = 0.01;
/// Higher-Level SoftBody
///
/// This is a wrapper struct providing some useful functions.
///
/// TODO: come up with a better name.
pub struct HLSoftBody<B = Brain>(ReferenceCounter<MutPoint<SoftBody<B>>>);
impl<B> From<SoftBo... | impl<B: Intentions> HLSoftBody<B> {
fn wants_primary_birth(&self, time: f64) -> bool {
let temp = self.borrow();
temp.get_energy() > SAFE_SIZE
&& temp.brain.wants_birth() > 0.0
&& temp.get_age(time) > MATURE_AGE
}
}
impl<B: NeuralNet + Intentions + RecombinationInfinite... | random_line_split | |
mod.rs | .01;
const PIECES: usize = 20;
const AGE_FACTOR: f64 = 1.0;
const MATURE_AGE: f64 = 0.01;
/// Higher-Level SoftBody
///
/// This is a wrapper struct providing some useful functions.
///
/// TODO: come up with a better name.
pub struct HLSoftBody<B = Brain>(ReferenceCounter<MutPoint<SoftBody<B>>>);
impl<B> From<SoftBo... |
}
impl<B> Clone for HLSoftBody<B> {
fn clone(&self) -> Self {
HLSoftBody(ReferenceCounter::clone(&self.0))
}
}
impl<B> PartialEq<HLSoftBody<B>> for HLSoftBody<B> {
fn eq(&self, rhs: &HLSoftBody<B>) -> bool {
ReferenceCounter::ptr_eq(&self.0, &rhs.0)
}
}
impl<B> HLSoftBody<B> {
//... | {
HLSoftBody(ReferenceCounter::new(MutPoint::new(sb)))
} | identifier_body |
mod.rs | .01;
const PIECES: usize = 20;
const AGE_FACTOR: f64 = 1.0;
const MATURE_AGE: f64 = 0.01;
/// Higher-Level SoftBody
///
/// This is a wrapper struct providing some useful functions.
///
/// TODO: come up with a better name.
pub struct HLSoftBody<B = Brain>(ReferenceCounter<MutPoint<SoftBody<B>>>);
impl<B> From<SoftBo... |
}
}
/// This function requires a reference to a `Board`.
/// This is usually impossible so you'll have to turn to `unsafe`.
pub fn return_to_earth(
&mut self,
time: f64,
board_size: BoardSize,
terrain: &mut Terrain,
climate: &Climate,
sbip: &mut ... | {
let force = combined_radius * COLLISION_FORCE;
let add_vx = (self_px - collider_px) / distance * force / self_mass;
let add_vy = (self_py - collider_py) / distance * force / self_mass;
// This is where self is needed to be borrowed mutably.
... | conditional_block |
mod.rs | .01;
const PIECES: usize = 20;
const AGE_FACTOR: f64 = 1.0;
const MATURE_AGE: f64 = 0.01;
/// Higher-Level SoftBody
///
/// This is a wrapper struct providing some useful functions.
///
/// TODO: come up with a better name.
pub struct | <B = Brain>(ReferenceCounter<MutPoint<SoftBody<B>>>);
impl<B> From<SoftBody<B>> for HLSoftBody<B> {
fn from(sb: SoftBody<B>) -> HLSoftBody<B> {
HLSoftBody(ReferenceCounter::new(MutPoint::new(sb)))
}
}
impl<B> Clone for HLSoftBody<B> {
fn clone(&self) -> Self {
HLSoftBody(ReferenceCounter::... | HLSoftBody | identifier_name |
wal.go | []raftpb.Entry, err error) {
w.mu.Lock()
defer w.mu.Unlock()
rec := &walpb.Record{}
decoder := w.decoder
var match bool
// 循环读出record记录
for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
switch rec.Type {
case entryType:
e := mustUnmarshalEntry(rec.Data)
if e.Index > w.start.Inde... | random_line_split | ||
wal.go | SizeBytes {
if mustSync {
return w.sync()
}
return nil
}
return w.cut()
}
func (w *WAL) saveEntry(e *raftpb.Entry) error {
b := pbutil.MustMarshal(e)
rec := &walpb.Record{Type: entryType, Data: b}
if err := w.encoder.encode(rec); err != nil {
return err
}
w.enti = e.Index
return nil
}
func (w *WAL... | rk to spawn a process while this is
// happening. The fds are set up as close-on-exec by the Go runtime,
// but there is a window between the fork and the exec where another
// process holds the lock.
if err := os.Rename(tmpdirpath, w.dir); err != nil {
if _, ok := err.(*os.LinkError); ok {
return w.renameWALU... | s will fo | identifier_name |
wal.go | SizeBytes {
if mustSync {
return w.sync()
}
return nil
}
return w.cut()
}
func (w *WAL) saveEntry(e *raftpb.Entry) error {
b := pbutil.MustMarshal(e)
rec := &walpb.Record{Type: entryType, Data: b}
if err := w.encoder.encode(rec); err != nil {
return err
}
w.enti = e.Index
return nil
}
func (w *WAL... | or {
if err := walpb.ValidateSnapshotForWrite(&e); err != nil {
return err
}
b := pbutil.MustMarshal(&e)
w.mu.Lock()
defer w.mu.Unlock()
rec := &walpb.Record{Type: snapshotType, Data: b}
if err := w.encoder.encode(rec); err != nil {
return err
}
// update enti only when snapshot is ahead of last index
... | lpb.Snapshot) err | conditional_block |
wal.go | Bytes {
if mustSync {
return w.sync()
}
return nil
}
return w.cut()
}
func (w *WAL) saveEntry(e *raftpb.Entry) error {
b := pbutil.MustMarshal(e)
rec := &walpb.Record{Type: entryType, Data: b}
if err := w.encoder.encode(rec); err != nil {
return err
}
w.enti = e.Index
return nil
}
func (w *WAL) sa... | sible the process will fork to spawn a process while this is
// happening. The fds are set up as close-on-exec by the Go runtime,
// but there is a window between the fork and the exec where another
// process holds the lock.
if err := os.Rename(tmpdirpath, w.dir); err != nil {
if _, ok := err.(*os.LinkError); ok... | err := os.RemoveAll(w.dir); err != nil {
return nil, err
}
// On non-Windows platforms, hold the lock while renaming. Releasing
// the lock and trying to reacquire it quickly can be flaky because
// it's pos | identifier_body |
car_type_management.js | val();
var car_type = $('#add_car_type').val();
// var car_picture = $('#user-photo').cropper('getCroppedCanvas', {
// width: 300,
| // height: 300
// }).toDataURL('image/png');
if(document.getElementById('user-photo').src == "") {
alert('请输入图片')
return
}
var car_picture = getBase64Image(document.getElementById('user-photo'))
var data = {
"car_name": car_name,
"car_brand": car_bran... | random_line_split | |
car_type_management.js | = {
"car_name": car_name
};
$.ajax({
type: "post",
url: "searchCarTypeServlet",
data: data,
dataType: "json",
success: function(json){
$('#car_info').bootstrapTable('load', json);
}
});
$('#search_text').val('');
}
functi... | photo'),$('#ph | identifier_name | |
car_type_management.js | var data = {
"car_name": car_name,
"car_brand": car_brand,
"daily_rent": daily_rent,
"car_deposit": car_deposit,
"car_type": car_type,
"car_picture": car_picture
};
$.ajax({
type: "post",
url: "addCarTypeServlet",
data: data,... | {
$('#add_car_type_form').data('bootstrapValidator').validate();
if(!$('#add_car_type_form').data('bootstrapValidator').isValid()){
return ;
}
$('#add_modal').modal('hide');
var car_name = $('#add_car_name').val();
var car_brand = $('#add_car_brand').val();
var daily_rent = $... | identifier_body | |
car_type_management.js | ();
var car_type = $('#add_car_type').val();
// var car_picture = $('#user-photo').cropper('getCroppedCanvas', {
// width: 300,
// height: 300
// }).toDataURL('image/png');
if(document.getElementById('user-photo').src == "") {
alert('请输入图片')
return
}
var... | itable: {
title: '输入所需押金',
type: 'text',
validate: function(v) {
if (!v) {
return '所需押金不能为空';
}
else if (parseFloat(v) < 0) {
return '所需押金不能小于0';
... | eposit',
title: '所需押金',
sortable: true,
ed | conditional_block |
calendar.rs |
// kstep ! time step since simulation start
// ktspd ! time steps per day
// kdatim(7) ! year,month,day,hour,min,weekday,leapyear
fn step2cal(kstep: Int, ktspd: Int, kdatim: &mut [Int; 7], mut cal: &mut Calendar) {
let mut iyea: Int; // current year of simulation
let mut imon: Int; // current month... | {
let mut idatim = [0; 7];
if cal.n_days_per_year == 365 {
step2cal(kstep, cal.ntspd, &mut idatim, cal);
return idatim[2] + cal.monaccu[idatim[1] as usize - 1];
} else {
step2cal30(kstep, cal.ntspd, &mut idatim, cal);
return idatim[2] + cal.n_days_per_month * (idatim[1] - 1)... | identifier_body | |
calendar.rs |
fn step2cal(kstep: Int, ktspd: Int, kdatim: &mut [Int; 7], mut cal: &mut Calendar) {
let mut iyea: Int; // current year of simulation
let mut imon: Int; // current month of simulation
let mut iday: Int; // current day of simulation
let mut ihou: Int; // current hour of simulation
let mut imin: Int;... | else {
// century year is not leap year
iy100 = (id400 - 1) / cal.ny100d; // century in segment [1,2,3]
id100 = (id400 - 1).rem(cal.ny100d);
if id100 < cal.ny004d - 1 {
iy004 = 0; // tetrade in century [0]
id004 = id100;
leap = false;
iy0... | {
// century year is leap year
iy100 = 0; // century in segment [0]
id100 = id400;
iy004 = id100 / cal.ny004d; // tetrade in century [0..24]
id004 = id100.rem(cal.ny004d);
leap = id004 <= cal.ny001d;
if leap {
iy001 = 0; // year in tetrade [0]
... | conditional_block |
calendar.rs |
fn step2cal(kstep: Int, ktspd: Int, kdatim: &mut [Int; 7], mut cal: &mut Calendar) {
let mut iyea: Int; // current year of simulation
let mut imon: Int; // current month of simulation
let mut iday: Int; // current day of simulation
let mut ihou: Int; // current hour of simulation
let mut imin: Int;... | (
ktspd: Int, // time steps per day
kyea: Int, // current year of simulation
kmon: Int, // current month of simulation
kday: Int, // current day of simulation
khou: Int, // current hour of simulation
kmin: Int, // current minute of simul... | cal2step | identifier_name |
calendar.rs | n_days_per_year: 360,
n_start_step: 0,
ntspd: 1,
solar_day: 86400.0, // sec
}
}
}
fn yday2mmdd(cal: &Calendar, mut kyday: &mut Int, mut kmon: &mut Int, mut kday: &mut Int) {
if cal.n_days_per_year == 365 {
*kmon = 1;
while *kyday > cal.mon... | ny001d: 365,
nud: 6,
n_days_per_month: 30, | random_line_split | |
pages.go | map[string]PageSession{},
}
}
func (psm *PageSessionManager) GetName() string {
return psm.routePath
}
func (psm *PageSessionManager) Wait() {
psm.waiter.Wait()
}
func (psm *PageSessionManager) Stop() {
psm.starter.Do(func() {
psm.canceler()
psm.waiter.Wait()
})
}
func (psm *PageSessionManager) S... |
psm.routes[pageRoute] = true
psm.rl.Unlock()
psm.onAddRoute(pageRoute, p)
}
func (psm *PageSessionManager) manage() {
defer psm.waiter.Done()
var ticker = time.NewTicker(psm.idleCheckInterval)
defer ticker.Stop()
doLoop:
for {
select {
case <-psm.ctx.Done():
return
case doFn := <-psm.doFunc:
doF... | {
psm.rl.Unlock()
return
} | conditional_block |
pages.go | map[string]PageSession{},
}
}
func (psm *PageSessionManager) GetName() string {
return psm.routePath
}
func (psm *PageSessionManager) Wait() {
psm.waiter.Wait()
}
func (psm *PageSessionManager) Stop() {
psm.starter.Do(func() {
psm.canceler()
psm.waiter.Wait()
})
}
func (psm *PageSessionManager) S... | (pageName string) (*PageSessionManager, error) {
var pageHandle = cleanAllSlashes(handlePath(pageName))
var prefixPage = cleanAllSlashes(handlePath(p.prefix, pageName))
p.sl.RLock()
var manager, exists = p.managers[prefixPage]
if !exists {
manager, exists = p.managers[pageHandle]
}
p.sl.RUnlock()
if !exists... | Get | identifier_name |
pages.go | map[string]PageSession{},
}
}
func (psm *PageSessionManager) GetName() string |
func (psm *PageSessionManager) Wait() {
psm.waiter.Wait()
}
func (psm *PageSessionManager) Stop() {
psm.starter.Do(func() {
psm.canceler()
psm.waiter.Wait()
})
}
func (psm *PageSessionManager) Start() {
psm.starter.Do(func() {
psm.waiter.Add(1)
go psm.manage()
})
}
type SessionStat struct {
PageName ... | {
return psm.routePath
} | identifier_body |
pages.go | : map[string]PageSession{},
}
}
func (psm *PageSessionManager) GetName() string {
return psm.routePath
}
func (psm *PageSessionManager) Wait() {
psm.waiter.Wait()
}
func (psm *PageSessionManager) Stop() {
psm.starter.Do(func() {
psm.canceler()
psm.waiter.Wait()
})
}
func (psm *PageSessionManager) ... | onNewPage *PageNotification
}
func WithPages(
ctx context.Context,
logger Logger,
prefix string,
theme *styled.Theme,
transport sabuhp.Transport,
notFound Handler,
) *Pages {
return NewPages(
ctx,
logger,
prefix,
DefaultMaxPageIdleness,
DefaultPageIdlenessChecksInterval,
theme,
transport,
notFo... | random_line_split | |
helpers.py | _batch_size
def iterate_eternally(indices):
def infinite_shuffles():
while True:
yield np.random.permutation(indices)
return itertools.chain.from_iterable(infinite_shuffles())
def grouper(iterable, n):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG... | m_batch = mixup_data(batch,index,lam)
class_logit , _ = model(m_batch)
if count == 0:
loss_sum = mixup_criterion(class_logit.double() , target_a , target_b , lam).mean()
else:
loss_sum += mixup_criterion(class_logit.double() ... | aug_images_l,target_l = next(train_loader_l)
target_l = target_l.to(args.device)
target_u = target_u.to(args.device)
target = torch.cat((target_l,target_u),0)
#Create the mix
alpha = args.alpha
index = torch.randperm(args.batch_size,devi... | conditional_block |
helpers.py | _batch_size
def iterate_eternally(indices):
def infinite_shuffles():
while True:
yield np.random.permutation(indices)
return itertools.chain.from_iterable(infinite_shuffles())
def grouper(iterable, n):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG... | outputs,_ = model(inputs)
prec1, prec5 = accuracy(outputs, targets, topk=(1, 5))
# measure accuracy and record loss
prec1, prec5 = accuracy(outputs, targets, topk=(1, 5))
meters.update('top1', prec1.item(), batch_size)
meters.update('e... | random_line_split | |
helpers.py | _size
def iterate_eternally(indices):
def infinite_shuffles():
while True:
yield np.random.permutation(indices)
return itertools.chain.from_iterable(infinite_shuffles())
def grouper(iterable, n):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3) ... |
def train_sup(train_loader, model, optimizer, epoch, global_step, args, ema_model = None):
# switch to train mode
model.train()
for i, (aug_images , target) in enumerate(train_loader):
target = target.to(args.device)
#Create the mix
alpha = args.alpha
i... | criterion = nn.CrossEntropyLoss(reduction='none').cuda()
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b) | identifier_body |
helpers.py | _batch_size
def iterate_eternally(indices):
def infinite_shuffles():
while True:
yield np.random.permutation(indices)
return itertools.chain.from_iterable(infinite_shuffles())
def grouper(iterable, n):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG... | (pred, y_a, y_b, lam):
criterion = nn.CrossEntropyLoss(reduction='none').cuda()
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)
def train_sup(train_loader, model, optimizer, epoch, global_step, args, ema_model = None):
# switch to train mode
model.train()
for i, (aug_imag... | mixup_criterion | identifier_name |
scriptgenerator.py | Type)
return
self.logMsg('diag', 'ScriptOutputGenerator::addMapping: map from',
baseType, '<->', refType)
if baseType not in self.mapDict:
baseDict = {}
self.mapDict[baseType] = baseDict
else:
baseDict = self.mapDict[baseType]... | """This creates the inverse mapping of nonexistent APIs in this
build to their aliases which are supported. Must be called by
language-specific subclasses before emitting that mapping."""
# Map from APIs not supported in this build to aliases that are.
# When there are multiple va... | identifier_body | |
scriptgenerator.py | (api, newapi):
"""Return the 'most official' of two related names, api and newapi.
KHR is more official than EXT is more official than everything else.
If there is ambiguity, return api."""
if api[-3:] == 'KHR':
return api
if newapi[-3:] == 'KHR':
return newapi;
if api[-3:... | mostOfficial | identifier_name | |
scriptgenerator.py | ). Values are
# the names of related entities (e.g. structs contain
# a list of type names of members, enums contain a list
# of enumerants belong to the enumerated type, etc.), or
# just None if there are no directly related entities.
#
# Collect the mappings, then emit ... | elif category == 'define':
self.defines[name] = None
elif category == 'basetype':
# Do not add an entry for base types that are not API types
# e.g. an API Bool type gets an entry, uint32_t does not
if self.a... | self.funcpointers[name] = None
elif category == 'handle':
self.handles[name] = None | random_line_split |
scriptgenerator.py | - API category - 'define', 'basetype', etc."""
dict = self.featureDictionary[feature][key]
if dict:
# Not clear why handling of command vs. type APIs is different -
# see interfacedocgenerator.py, which this was based on.
if key == 'command':
for re... | self.addName(self.typeCategory, name, 'consts')
self.consts[name] = None | conditional_block | |
process.go | }
// Lock around the shard that we are trying to modify.
//
// Since memcache is namespaced, we don't need to include the namespace in our
// lock name.
task := makeProcessTask(timestamp, endTime, shard, loop)
lockKey := fmt.Sprintf("%s.%d.lock", baseName, shard)
clientID := fmt.Sprintf("%d_%d_%s", timestamp.U... | return mutKeys, muts, nil
}
| random_line_split | |
process.go | s",
cfg.ProcessLoopDuration.String(), endTime)
}
// Lock around the shard that we are trying to modify.
//
// Since memcache is namespaced, we don't need to include the namespace in our
// lock name.
task := makeProcessTask(timestamp, endTime, shard, loop)
lockKey := fmt.Sprintf("%s.%d.lock", baseName, shard... | {
return nil, nil, me
} | conditional_block | |
process.go | ShardQuery(c context.Context, cfg *Config, shard uint64) *ds.Query {
low, high := expandedShardBounds(c, cfg, shard)
if low > high {
return nil
}
q := ds.NewQuery("tumble.Mutation").
Gte("ExpandedShard", low).Lte("ExpandedShard", high).
Project("TargetRoot").Distinct(true)
return q
}
// processShard is th... | {
q := ds.NewQuery("tumble.Mutation").Eq("TargetRoot", root)
if cfg.DelayedMutations {
q = q.Lte("ProcessAfter", clock.Now(c).UTC())
}
fetchAllocSize := cfg.ProcessMaxBatchSize
if fetchAllocSize < 0 {
fetchAllocSize = 0
}
toFetch := make([]*realMutation, 0, fetchAllocSize)
err := ds.Run(c, q, func(k *ds.Ke... | identifier_body | |
process.go | error during shard processing", transient.Tag)
case errCount > 0:
return errors.New("encountered non-transient error during shard processing")
}
now := clock.Now(c)
didWork := numProcessed > 0
if didWork {
// Set our last key value for next round.
err = mc.Set(c, mc.NewItem(c, t.lastKey).SetValue(s... | add | identifier_name | |
server-tcp.ts | , this.order5BooksService, this.exchangeService, this.arbitrageBalanceService,
this.tradeService, this.matrixService);
}
// запрещает ведение новых арбитражных сделок
stopArbitrage() {
this.avalableArbitrage = false;
console.log('Arbitrage stoped');
}
// разрешает ведение новых арбитражных сде... | generateOrderAfterCancel(message: any) {
const trades = this.parser.parseTrades(message);
if (trades) {
for (const trade of trades) {
this.orderService.updateStatusOrder(trade.arbitrageId, trade.typeOrder, trade.exchOrderId, 'cancelled', '');
const order: Order[] = this.parser.replaceCan... | }
| random_line_split |
server-tcp.ts | , this.order5BooksService, this.exchangeService, this.arbitrageBalanceService,
this.tradeService, this.matrixService);
}
// запрещает ведение новых арбитражных сделок
stopArbitrage() {
this.avalableArbitrage = false;
console.log('Arbitrage stoped');
}
// разрешает ведение новых арбитражных сде... | trade.typeOrder, trade.exchOrderId, 'cancelled', '');
const order: Order[] = this.parser.replaceCancelledOrderByNewOrder(trade);
if (order) {
console.log('generateOrderAfterCancel call sendOrdersToBot :');
this.sendOrdersToBot(order);
}
}
}
}
createTcpServer()... | Order(trade.arbitrageId, | identifier_name |
server-tcp.ts | (trade);
if (order) {
console.log('generateOrderAfterCancel call sendOrdersToBot :');
this.sendOrdersToBot(order);
}
}
}
}
createTcpServer() {
if (!this.server) {
this.startServer();
this.parser.startSaverOrderBooks();
} else if (!this.server.addres... | identifier_body | ||
server-tcp.ts | , this.order5BooksService, this.exchangeService, this.arbitrageBalanceService,
this.tradeService, this.matrixService);
}
// запрещает ведение новых арбитражных сделок
stopArbitrage() {
this.avalableArbitrage = false;
console.log('Arbitrage stoped');
}
// разрешает ведение новых арбитражных сде... | = await this.tradeService.findTrade(trade);
if (!sameTrade) {
console.log('sameTrade :', sameTrade);
const pureTrade = await this.parser.addNewArbitrageTrade(trade);
await this.arbitrageBalanceService.addNewTrade(pureTrade, trade.arbitrageId);
await this.parser.removeCheckerSentOrders(trade... | ) {
console.log(' 91 sendOrdersToBot( :');
await this.sendOrdersFromPromise(newOrder);
}
}
async countPureTrade(trade: Trade) {
const sameTrade | conditional_block |
projection_pushing.go | LHS
src := node.Inputs()[0]
return pushProjection(ctx, expr, src, inner, reuseCol, hasAggregation)
case *route:
return addExpressionToRoute(ctx, node, expr, reuseCol)
case *hashJoin:
return pushProjectionIntoHashJoin(ctx, expr, node, reuseCol, inner, hasAggregation)
case *join:
return pushProjectionIntoJo... | }
func pushProjectionIntoSemiJoin(
ctx *plancontext.PlanningContext,
expr *sqlparser.AliasedExpr,
reuseCol bool,
node *semiJoin,
inner, hasAggregation bool,
) (int, bool, error) {
passDownReuseCol := reuseCol
if !reuseCol {
passDownReuseCol = expr.As.IsEmpty()
}
offset, added, err := pushProjection(ctx, exp... | return 0, false, err
}
}
}
return offset, added, nil | random_line_split |
projection_pushing.go | inner, passDownReuseCol, hasAggregation)
if err != nil {
return 0, false, err
}
column := -(offset + 1)
if reuseCol && !added {
for idx, col := range node.cols {
if column == col {
return idx, false, nil
}
}
}
node.cols = append(node.cols, column)
return len(node.cols) - 1, true, nil
}
func pus... | {
if reuseCol {
if i := checkIfAlreadyExists(expr, rb.Select, ctx.SemTable); i != -1 {
return i, false, nil
}
}
sqlparser.RemoveKeyspaceFromColName(expr.Expr)
sel, isSel := rb.Select.(*sqlparser.Select)
if !isSel {
return 0, false, vterrors.VT12001(fmt.Sprintf("pushing projection '%s' on %T", sqlparser.St... | identifier_body | |
projection_pushing.go | vterrors.VT13001(fmt.Sprintf("push projection does not yet support: %T", node))
}
}
func pushProjectionIntoVindexFunc(node *vindexFunc, expr *sqlparser.AliasedExpr, reuseCol bool) (int, bool, error) {
colsBefore := len(node.eVindexFunc.Cols)
i, err := node.SupplyProjection(expr, reuseCol)
if err != nil {
return... | {
return 0, false, err
} | conditional_block | |
projection_pushing.go | HS
src := node.Inputs()[0]
return pushProjection(ctx, expr, src, inner, reuseCol, hasAggregation)
case *route:
return addExpressionToRoute(ctx, node, expr, reuseCol)
case *hashJoin:
return pushProjectionIntoHashJoin(ctx, expr, node, reuseCol, inner, hasAggregation)
case *join:
return pushProjectionIntoJoin... | (
ctx *plancontext.PlanningContext,
expr *sqlparser.AliasedExpr,
node *simpleProjection,
inner, hasAggregation, reuseCol bool,
) (int, bool, error) {
offset, _, err := pushProjection(ctx, expr, node.input, inner, true, hasAggregation)
if err != nil {
return 0, false, err
}
for i, value := range node.eSimplePr... | pushProjectionIntoSimpleProj | identifier_name |
app.js | });
var dataType = $('body').attr('data-type');
for (key in pageData) {
if (key == dataType) {
pageData[key]();
}
}
$('.tpl-switch').find('.tpl-switch-btn-view').on('click', function () {
$(this).prev('.tpl-switch-btn').prop("checked", function () {
... | random_line_split | ||
app.js | f9f9f9" : ""}, sleep);
$(this).animate({backgroundColor: "#e4e7f3"}, sleep);
$(this).siblings().animate({backgroundColor: "#e4e7f3"}, sleep);
$(this).attr("title", $(this).text());
prevTd = $(this);
});
}
return $table.bootstrapTable({
showHeader:... | conditional_block | ||
app.js | });
})
// ==========================
// 侧边导航下拉列表
// ==========================
$('.tpl-left-nav-link-list').on('click', function () {
$(this).siblings('.tpl-left-nav-sub-menu').slideToggle(80)
.end()
.find('.tpl-left-nav-more-ico').toggleClass('tpl-left-nav-more-ico-rotate');
})
// ============... | Year();
firstDate.setMonth((firstDate.getMonth() + 1));
var month = parse0(f | identifier_body | |
app.js | keyup", function (e) {
if (keyState) {
if (e.keyCode == 38) {
//向上
if ($prevLi != undefined) {
if ($prevLi.prev().get(0) == undefined) {
return;
}
$prevLi = $prevLi.prev();
... | 字串
args = {}, // 保存参数数据的对象
items = qs.length ? qs.split("&") : [], // 取得每一个参数项,
item = null,
len = items.length;
for (var i = 0; i < len; i++) {
item = items[i].split("=");
var name = decodeURIComponent(item[0]),
value = de... | / 获取url中"?"符后的 | identifier_name |
wsr98d_reader.rs | 2,
ny_speed: f32,
moments_mask: i64,
moments_size_mask: i64,
mis_filter_mask: i32,
sqi: f32,
sig: f32,
csr: f32,
log: f32,
cpa: f32,
pmi: f32,
dplog: f32,
#[br(count = 4)]
r: Vec<u8>,
dbt_mask: i32,
dbz_mask: i32,
v_mask: i32,
w_mask: i32,
dp_mask:... | / // let print_data: Vec<&f32> =
// // own_data.iter().filter(|d| d != &&crate::MISSING).collect();
// println!(
// "{:?} {:?} {:?} {:?} ",
// dd.el,
// dd.az,
// ddd.data_type.clone(),
... | conditional_block | |
wsr98d_reader.rs | beam_width_v: f32, //垂直波束宽
radar_version: i32, //雷达数据采集软件版本号
radar_type: u16, //1–SA
// 2–SB
// 3–SC
// 33–CA
// 34–CB
// 35–CC
// 36–CCJ
// 37–CD
// 65–XA
// 66–KA
// 67–W
antenna_gain: i16,
trans_loss: i16,
recv_loss: i16,
other_loss: i16,
#[br(... | let longtitude = h.longtitude;
let antena_height = h.antena_height;
let ground_height = h.ground_height;
let h: TaskInfo = cursor.read_le()?;
let start_date = h.start_date.clone();
let start_time = h.start_time.clone();
// dbg!(&h);
let cut_num = h.cut_num;
... | ude;
| identifier_name |
wsr98d_reader.rs | 7 - single PRF 单PRF
// 8 –linear 线性调频
// 9 - phase encoding 相位编码
prf1: f32,
prf2: f32,
deal_mod: i32,
az: f32,
elev: f32,
start_az: f32,
end_az: f32,
ang_res: f32,
scan_speed: f32,
log_res: i32,
dop_res: i32,
max_range1: i32,
max_range2: i32,
start_range:... | })
.collect();
} else {
own_data = dt_slice | random_line_split | |
user.go | _id"`
CreatedAt time.Time `json:"created_at"`
LoginID string `json:"login_id"`
AvatarURL string `json:"avatar_url"`
Enrollments []Enrollment `json:"enrollments"`
Locale string `json:"locale"`
EffectiveLocale string `json:"effective_locale"`
LastLogin ... | (opts ...Option) ([]*Course, error) {
return getCourses(u.client, u.id("/users/%d/courses"), optEnc(opts))
}
// FavoriteCourses returns the user's list of favorites courses.
func (u *User) FavoriteCourses(opts ...Option) ([]*Course, error) {
return getCourses(u.client, "/users/favorites/courses", optEnc(opts))
}
//... | Courses | identifier_name |
user.go | return getCourses(u.client, u.id("/users/%d/courses"), optEnc(opts))
}
// FavoriteCourses returns the user's list of favorites courses.
func (u *User) FavoriteCourses(opts ...Option) ([]*Course, error) {
return getCourses(u.client, "/users/favorites/courses", optEnc(opts))
}
// File will get a user's file by id
fun... | return resp.Body.Close()
}
func getUserFile(d doer, id int, userid interface{}, opts optEnc) (*File, error) {
f := &File{client: d} | random_line_split | |
user.go | "/users/%d/settings", u.ID)
}
// Courses will return the user's courses.
func (u *User) Courses(opts ...Option) ([]*Course, error) {
return getCourses(u.client, u.id("/users/%d/courses"), optEnc(opts))
}
// FavoriteCourses returns the user's list of favorites courses.
func (u *User) FavoriteCourses(opts ...Option) ... | {
return err
} | conditional_block | |
user.go | u.ID)
}
// Courses will return the user's courses.
func (u *User) Courses(opts ...Option) ([]*Course, error) {
return getCourses(u.client, u.id("/users/%d/courses"), optEnc(opts))
}
// FavoriteCourses returns the user's list of favorites courses.
func (u *User) FavoriteCourses(opts ...Option) ([]*Course, error) {
... | {
path := fmt.Sprintf("users/%d/colors/%s", u.ID, asset)
if hexcode[0] == '#' {
hexcode = hexcode[1:]
}
resp, err := put(u.client, path, params{"hexcode": {hexcode}})
if err != nil {
return err
}
return resp.Body.Close()
} | identifier_body | |
actions.py | vm import SVC
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
import pickle
from sklearn.metrics import classification_report
names=[]
phones=[]
ages=[]
symptoms=[]
sides=[]
intensities=[]
locations=[]
class ActionForm(FormAction):
def name(self) -> Text:
self.sn=0... | return [] #set returned details as slots | random_line_split | |
actions.py | random import randint
import datetime
import os
import yaml
import csv
import pickle
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
import string
from sklearn.svm import SVC
from sklearn.model_selection import train... | (
self,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> List[Dict]:
dispatcher.utter_message("Great! You're registered")
return []
def slot_mappings(self) -> Dict[Text,Union[Dict, List[Dict]]]:
return{
'name': ... | submit | identifier_name |
actions.py | return []
def slot_mappings(self) -> Dict[Text,Union[Dict, List[Dict]]]:
return{
'name': [self.from_entity(entity='name', intent='form_entry'),
self.from_text()],
'age': [self.from_entity(entity='age', intent='form_entry'),
self.from_text()],
... | number=tracker.get_slot("phone")
name=tracker.get_slot("name")
if number in phones:
dispatcher.utter_message(text="You're already registered")
else:
names.append(name)
dispatcher.utter_message(text="You're added to the list!")
return [] | identifier_body | |
actions.py | random import randint
import datetime
import os
import yaml
import csv
import pickle
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
import string
from sklearn.svm import SVC
from sklearn.model_selection import train... |
else:
for i in range(0,3):
num=probability_score.nlargest(3,'value')['variable'].index[i]
symptom_list.append(probability_score.nlargest(3,'value')['variable'][num])
buttons = [{'title': symptom_list[0], 'payload': '/picking_specialty'},{'title': ... | num=probability_score.nlargest(3,'value')['variable'].index[i]
symptom_list.append(probability_score.nlargest(3,'value')['variable'][num])
buttons = [{'title': symptom_list[0], 'payload': '/picking_specialty'}] | conditional_block |
suite.go | ModuleBalance(denom string) sdk.Int {
return suite.App.GetModuleAccountBalance(suite.Ctx, types.ModuleName, denom)
}
func (suite *Suite) FundAccountWithKava(addr sdk.AccAddress, coins sdk.Coins) {
ukava := coins.AmountOf("ukava")
if ukava.IsPositive() {
err := suite.App.FundAccount(suite.Ctx, addr, sdk.NewCoins(... | {
privKey, err := ethsecp256k1.GenerateKey()
if err != nil {
panic(err)
}
addr := common.BytesToAddress(privKey.PubKey().Address())
return addr, privKey
} | identifier_body | |
suite.go | We need to commit so that the ethermint feemarket beginblock runs to set the minfee
// feeMarketKeeper.GetBaseFee() will return nil otherwise
suite.Commit()
}
func (suite *Suite) Commit() {
_ = suite.App.Commit()
header := suite.Ctx.BlockHeader()
header.Height += 1
suite.App.BeginBlock(abci.RequestBeginBlock{
... | MustNewInternalEVMAddressFromString | identifier_name | |
suite.go | abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/tmhash"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
tmtime "github.com/tendermint/tendermint/types/time"
"github.com/tendermint/te... | random_line_split | ||
suite.go | validator, err := stakingtypes.NewValidator(valAddr, consPriv.PubKey(), stakingtypes.Description{})
suite.Require().NoError(err)
err = suite.App.GetStakingKeeper().SetValidatorByConsAddr(suite.Ctx, validator)
suite.Require().NoError(err)
suite.App.GetStakingKeeper().SetValidator(suite.Ctx, validator)
// add conve... | {
suite.ElementsMatch(expectedAttrs, possibleFailedMatch, "unmatched attributes on event of type %s", expectedEvent.Type)
} | conditional_block | |
# WAD SERVER TEST as MULTI-1.py | 18:24] = WAD pw
## # WAD[24:29] = WAD new Port number
##
## given_PW =
## State = 'protocal_initializing'
##
## ### SERVER TX PROTOCALL DATA PACKET
## serverTx_protocall = xx_code + str(private_port) + '/' + str(given_PW) + '/' + str(State) + '/'
##
## ### socket BIN... | prints = False
break | conditional_block | |
# WAD SERVER TEST as MULTI-1.py | # preset list
# 12000~24000 WAD
# 24000~36000 app
# 36000~48000 platform
Server_Rx_prot_len = 24
Server_TX_prot_len =
server_adr = getadr()
LIVE_WAD_list = []
x_code = '###WAD*#*' # Server Rx / WAD Tx
xx_code = '###WAD#*#' # Server Tx / WAD Rx
re_list = []
## WAD ##
# step 1
"""... | connectionSocket.send(server_Rx_wad)
def APP(port):
def Make_id_i():
global WAD_pinlist
type_WAD = 'i'
year_WAD = str((time.localtime(time.time()))[0])
pin_WAD = str(int(WAD_pinList[-1]) + 1)
if len(pin_WAD) > 4:
... | random_line_split | |
# WAD SERVER TEST as MULTI-1.py | # preset list
# 12000~24000 WAD
# 24000~36000 app
# 36000~48000 platform
Server_Rx_prot_len = 24
Server_TX_prot_len =
server_adr = getadr()
LIVE_WAD_list = []
x_code = '###WAD*#*' # Server Rx / WAD Tx
xx_code = '###WAD#*#' # Server Tx / WAD Rx
re_list = []
## WAD ##
# step 1
"""... | ():
global WAD_pinlist
type_WAD = 'i'
year_WAD = str((time.localtime(time.time()))[0])
pin_WAD = str(int(WAD_pinList[-1]) + 1)
if len(pin_WAD) > 4:
pin_WAD = pin_WAD[0:4]
ID_WAD = type_WAD + year_WAD[-2] + year_WAD[-1] + '0'*(4-len(pin_WAD)) + str(... | Make_id_i | identifier_name |
# WAD SERVER TEST as MULTI-1.py | # preset list
# 12000~24000 WAD
# 24000~36000 app
# 36000~48000 platform
Server_Rx_prot_len = 24
Server_TX_prot_len =
server_adr = getadr()
LIVE_WAD_list = []
x_code = '###WAD*#*' # Server Rx / WAD Tx
xx_code = '###WAD#*#' # Server Tx / WAD Rx
re_list = []
## WAD ##
# step 1
"""... |
def start_socket():
server_adr = getadr()
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind((server_adr, main_port))
serverSocket.listen(1)
connectionSocket, addr = serverSocket.accept()
##
### RETELLIGENCE WADING IN--on new thread
##class WADING(threading.Tread):
#... | pass | identifier_body |
AlfaReativo.py | essel(nome, c, lenght, arrival)
vessels.append(vessel)
break
#vessel1.printing()
#creating the yards
yard_location_1 = Yard("A",cargo2, 10, 100, 1, 15, True, 1)
yard_location_2 = Yard("B",cargo1, 20, 100, 1, 30, True, 1)
yard_location_3 = Yard("C",cargo2, 30, 100, 7, 15, True, 1)
yard_location_4 = Yard("D",carg... | for y i | conditional_block | |
AlfaReativo.py | printing(self):
print("Carga "+self.n)
class Vessel:
def __init__(self, name, cargo_type, lenght, arrival):
self.n = name
self.c_t = cargo_type
self.l = lenght
self.a = arrival
def printing(self):
print ("Vessel "+self.n)
#print (self.c_t, self.l, self.d)
#class Yard has the cargo type, the distanc... | n self.r
def | identifier_body | |
AlfaReativo.py | #creating the yards
yard_location_1 = Yard("A",cargo2, 10, 100, 1, 15, True, 1)
yard_location_2 = Yard("B",cargo1, 20, 100, 1, 30, True, 1)
yard_location_3 = Yard("C",cargo2, 30, 100, 7, 15, True, 1)
yard_location_4 = Yard("D",cargo1, 25, 100, 7, 30, False, 1)
yard_location_5 = Yard("E",cargo2, 35, 100, 1, 45, False, 1... | s.t = 1
for y in yards:
y.time = 1
def new_heuristic_2opt(vessels, sections, yards, alfaqqr): | random_line_split | |
AlfaReativo.py | f __init__(self, vessel, section, yard, beta, time):
self.s = section
self.y = yard
self.beta = beta
self.alfa = alfa
self.h_t = alfa + beta #handling time = tempo de load/unload da carga + tempo de transferencia da carga
self.v = vessel
self.s_t = time #starting time
self.c_t = ""
def printing(self):
... | n:
de | identifier_name | |
cpu.js | [CHIP8.r.PC];
nextOp <<= 8;
nextOp |= CHIP8_MEM[CHIP8.r.PC + 1];
CHIP8.r.PC += 2;
CHIP8.handleTimers();
DEBUGGER.report(nextOp, CHIP8.do(nextOp));
},
// Performs an opcode operation
// Needs to handle all 35 opcodes!
do: function(op) {
firstDigit = (op &... | switch (firstDigit) {
case 0x0:
// handle 0x0..
return CHIP8.handleOp0(op & 0xfff);
case 0x1:
// JUMP opcode (0x1NNN)
if ((op & 0x0fff) == CHIP8.r.PC - 0x2) {
CHIP8.r.PC = op & 0x0fff;
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.