file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
rpc.rs | use std::future::Future;
use std::net::{Ipv4Addr, SocketAddr};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use bytes::{Bytes, BytesMut};
use futures::{SinkExt, Stream, StreamExt};
use orion::aead::streaming::StreamOpener;
use orion::aead::SecretKey;
use tokio::net::{TcpListener, TcpStream};
use tokio... |
pub(crate) fn process_worker_message(state: &mut WorkerState, message: ToWorkerMessage) -> bool {
match message {
ToWorkerMessage::ComputeTask(msg) => {
log::debug!("Task assigned: {}", msg.id);
let task = Task::new(msg);
state.add_task(task);
}
ToWorker... | {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let state = state_ref.get();
if !state.has_tasks() && !state.reservation {
let elapsed = state.last_task_finish_time.elapsed();
if elapsed > idle_timeout {
... | identifier_body |
rpc.rs | use std::future::Future;
use std::net::{Ipv4Addr, SocketAddr};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use bytes::{Bytes, BytesMut};
use futures::{SinkExt, Stream, StreamExt};
use orion::aead::streaming::StreamOpener;
use orion::aead::SecretKey;
use tokio::net::{TcpListener, TcpStream};
use tokio... | use crate::internal::common::WrappedRcRefCell;
use crate::internal::messages::worker::{
FromWorkerMessage, StealResponseMsg, TaskResourceAllocation, TaskResourceAllocationValue,
ToWorkerMessage, WorkerOverview, WorkerRegistrationResponse, WorkerStopReason,
};
use crate::internal::server::rpc::ConnectionDescript... | use crate::internal::common::resources::map::ResourceMap;
use crate::internal::common::resources::{Allocation, AllocationValue}; | random_line_split |
rpc.rs | use std::future::Future;
use std::net::{Ipv4Addr, SocketAddr};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use bytes::{Bytes, BytesMut};
use futures::{SinkExt, Stream, StreamExt};
use orion::aead::streaming::StreamOpener;
use orion::aead::SecretKey;
use tokio::net::{TcpListener, TcpStream};
use tokio... |
}
ToWorkerMessage::Stop => {
log::info!("Received stop command");
return true;
}
}
false
}
/// Runs until there are messages coming from the server.
async fn worker_message_loop(
state_ref: WorkerStateRef,
mut stream: impl Stream<Item = Result<BytesMut, ... | {
state.reset_idle_timer();
} | conditional_block |
rpc.rs | use std::future::Future;
use std::net::{Ipv4Addr, SocketAddr};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use bytes::{Bytes, BytesMut};
use futures::{SinkExt, Stream, StreamExt};
use orion::aead::streaming::StreamOpener;
use orion::aead::SecretKey;
use tokio::net::{TcpListener, TcpStream};
use tokio... | (idle_timeout: Duration, state_ref: WrappedRcRefCell<WorkerState>) {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let state = state_ref.get();
if !state.has_tasks() && !state.reservation {
let elapsed = state.last_task_fini... | idle_timeout_process | identifier_name |
mopac_qr.py | """
Version 2012/08/20, Torsten Kerber
Contributors:
Torsten Kerber, Ecole normale superieure de Lyon:
Paul Fleurat-Lessard, Ecole normale superieure de Lyon
based on a script by Rosa Bulo, Ecole normale superieure de Lyon
This work is supported by Award No. UK-C0017, made by King Abdullah
University of Science a... | (self,command):
"""
execute <command> in a subprocess and check error code
"""
from subprocess import Popen, PIPE, STDOUT
if command == '':
raise RuntimeError('no command for run_command :(')
# print 'Running: ', command #debug
proc = Popen([command], ... | run_command | identifier_name |
mopac_qr.py | """
Version 2012/08/20, Torsten Kerber
Contributors:
Torsten Kerber, Ecole normale superieure de Lyon:
Paul Fleurat-Lessard, Ecole normale superieure de Lyon
based on a script by Rosa Bulo, Ecole normale superieure de Lyon
This work is supported by Award No. UK-C0017, made by King Abdullah
University of Science a... | for key in kwargs:
if key in self.bool_params:
self.bool_params[key] = kwargs[key]
elif key in self.int_params:
self.int_params[key] = kwargs[key]
elif key in self.str_params:
self.str_params[key] = kwargs[key]
elif key in self.fl... | self.atoms = atoms_new.copy()
self.run()
def run_qr(self, atoms_new, **kwargs): | random_line_split |
mopac_qr.py | """
Version 2012/08/20, Torsten Kerber
Contributors:
Torsten Kerber, Ecole normale superieure de Lyon:
Paul Fleurat-Lessard, Ecole normale superieure de Lyon
based on a script by Rosa Bulo, Ecole normale superieure de Lyon
This work is supported by Award No. UK-C0017, made by King Abdullah
University of Science a... |
elif key in self.int_params:
self.int_params[key] = kwargs[key]
elif key in self.str_params:
self.str_params[key] = kwargs[key]
elif key in self.float_params:
self.float_params[key] = kwargs[key]
else:
raise... | self.bool_params[key] = kwargs[key] | conditional_block |
mopac_qr.py | """
Version 2012/08/20, Torsten Kerber
Contributors:
Torsten Kerber, Ecole normale superieure de Lyon:
Paul Fleurat-Lessard, Ecole normale superieure de Lyon
based on a script by Rosa Bulo, Ecole normale superieure de Lyon
This work is supported by Award No. UK-C0017, made by King Abdullah
University of Science a... | self.int_params['nproc'] = nproc | identifier_body | |
manager.go | package pipermail
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/LF-Engineering/da-ds/build"
"github.com/LF-Engineering/dev-analytics-libraries/auth0"
"github.com/LF-Engineering/dev-analytics-libraries/slack"
"github.com/LF-Engineering/dev-analytics-libraries/... | ESCacheURL: esCacheURL,
ESCacheUsername: esCacheUsername,
ESCachePassword: esCachePassword,
AuthGrantType: authGrantType,
AuthClientID: authClientID,
AuthClientSecret: authClientSecret,
AuthAudience: authAudience,
Auth0URL: auth0... | AffBaseURL: affBaseURL, | random_line_split |
manager.go | package pipermail
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/LF-Engineering/da-ds/build"
"github.com/LF-Engineering/dev-analytics-libraries/auth0"
"github.com/LF-Engineering/dev-analytics-libraries/slack"
"github.com/LF-Engineering/dev-analytics-libraries/... | {
u, err := url.Parse(targetURL)
if err != nil {
return "", err
}
path := u.Path
if strings.HasPrefix(path, "/") {
path = strings.TrimPrefix(path, "/")
}
if strings.HasSuffix(path, "/") {
path = strings.TrimSuffix(path, "/")
}
path = strings.ReplaceAll(path, "/", "-")
return path, nil
} | identifier_body | |
manager.go | package pipermail
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/LF-Engineering/da-ds/build"
"github.com/LF-Engineering/dev-analytics-libraries/auth0"
"github.com/LF-Engineering/dev-analytics-libraries/slack"
"github.com/LF-Engineering/dev-analytics-libraries/... | () error {
lastActionCachePostfix := "-last-action-date-cache"
status := make(map[string]bool)
status["doneFetch"] = !m.Fetch
status["doneEnrich"] = !m.Enrich
fetchCh := m.fetch(m.fetcher, lastActionCachePostfix)
var err error
if status["doneFetch"] == false {
err = <-fetchCh
if err == nil {
status["do... | Sync | identifier_name |
manager.go | package pipermail
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/LF-Engineering/da-ds/build"
"github.com/LF-Engineering/dev-analytics-libraries/auth0"
"github.com/LF-Engineering/dev-analytics-libraries/slack"
"github.com/LF-Engineering/dev-analytics-libraries/... |
for _, message := range raw {
data = append(data, elastic.BulkData{IndexName: fmt.Sprintf("%s-raw", m.ESIndex), ID: message.UUID, Data: message})
}
// set mapping and create index if not exists
_, err = m.esClientProvider.CreateIndex(fmt.Sprintf("%s-raw", m.ESIndex), PipermailRawMapping)
if err != nil {... | {
from = &raw[len(raw)-1].ChangedAt
} | conditional_block |
main.py | from env import CausalEnv
from metrics import *
from enco_model import *
from enco_training import *
from heuristics import *
from policy import MLP, GAT
import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from typing import Tuple
from collections import defaultdict
import json
f... |
def train(args, env, obs_dataloader, device, policy=None):
# initialize model of the causal structure
model, adj_matrix = init_model(args, device)
# initialize optimizers
model_optimizer = torch.optim.Adam(model.parameters(), lr=args.lr_model, betas=args.betas_model)
... | """Executes a causal discovery algorithm on synthetic data from a sampled
DAG, using a specified heuristic for choosing intervention variables.
Args:
args: Object from the argument parser that defines various settings of
the causal structure and discovery process.
"""
# ini... | identifier_body |
main.py | from env import CausalEnv
from metrics import *
from enco_model import *
from enco_training import *
from heuristics import *
from policy import MLP, GAT
import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from typing import Tuple
from collections import defaultdict
import json
f... |
def init_model(args: argparse.Namespace, device) -> Tuple[MultivarMLP, AdjacencyMatrix]:
"""Initializes a complete model of the causal structure, consisting of a
multivariable MLP which models the conditional distributions of the causal
variables, and gamma and theta values which define the adjacency ... | return log_probs_lst, reward_lst
| random_line_split |
main.py | from env import CausalEnv
from metrics import *
from enco_model import *
from enco_training import *
from heuristics import *
from policy import MLP, GAT
import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from typing import Tuple
from collections import defaultdict
import json
f... |
def train(args, env, obs_dataloader, device, policy=None):
# initialize model of the causal structure
model, adj_matrix = init_model(args, device)
# initialize optimizers
model_optimizer = torch.optim.Adam(model.parameters(), lr=args.lr_model, betas=args.betas_model)
... | train(args, env, obs_dataloader, device, policy) | conditional_block |
main.py | from env import CausalEnv
from metrics import *
from enco_model import *
from enco_training import *
from heuristics import *
from policy import MLP, GAT
import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from typing import Tuple
from collections import defaultdict
import json
f... | (args: argparse.Namespace, dag: CausalDAG=None, policy=None):
"""Executes a causal discovery algorithm on synthetic data from a sampled
DAG, using a specified heuristic for choosing intervention variables.
Args:
args: Object from the argument parser that defines various settings of
... | main | identifier_name |
srt.rs | use std::{
fmt::{self, Display, Formatter},
{collections::BTreeMap, convert::TryFrom, time::Duration},
};
use bitflags::bitflags;
use bytes::{Buf, BufMut};
use log::warn;
use crate::{options::SrtVersion, packet::PacketParseError};
/// The SRT-specific control packets
/// These are `Packet::Custom` types
#[de... | (&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyingMaterialMessage")
.field("pt", &self.pt)
.field("key_flags", &self.key_flags)
.field("keki", &self.keki)
.field("cipher", &self.cipher)
.field("auth", &self.auth)
.finish... | fmt | identifier_name |
srt.rs | use std::{
fmt::{self, Display, Formatter},
{collections::BTreeMap, convert::TryFrom, time::Duration},
};
use bitflags::bitflags;
use bytes::{Buf, BufMut};
use log::warn;
use crate::{options::SrtVersion, packet::PacketParseError};
/// The SRT-specific control packets
/// These are `Packet::Custom` types
#[de... |
}
| {
let salt = b"\x00\x00\x00\x00\x00\x00\x00\x00\x85\x2c\x3c\xcd\x02\x65\x1a\x22";
let wrapped = b"U\x06\xe9\xfd\xdfd\xf1'nr\xf4\xe9f\x81#(\xb7\xb5D\x19{\x9b\xcdx";
let km = KeyingMaterialMessage {
pt: PacketType::KeyingMaterial,
key_flags: KeyFlags::EVEN,
kek... | identifier_body |
srt.rs | use std::{
fmt::{self, Display, Formatter},
{collections::BTreeMap, convert::TryFrom, time::Duration},
};
use bitflags::bitflags;
use bytes::{Buf, BufMut};
use log::warn;
use crate::{options::SrtVersion, packet::PacketParseError};
/// The SRT-specific control packets
/// These are `Packet::Custom` types
#[de... |
/// from https://github.com/Haivision/srt/blob/2ef4ef003c2006df1458de6d47fbe3d2338edf69/haicrypt/hcrypt_msg.h#L121-L124
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum CipherType {
None = 0,
Ecb = 1,
Ctr = 2,
Cbc = 3,
}
/// The SRT handshake object
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pu... | }
} | random_line_split |
play_blackjack.py | # -*- coding: utf-8 -*-
"""
Black Jack
Version: Alpha 0.1
Created on Wed Jan 2 23:41:46 2019
@author: Jason Bubenicek
"""
import random
from IPython.display import clear_output
import os
from colorama import init
init()
from colorama import Fore
PLAYERS = []
HOUSE = []
def cls():
# https://... | if this Hand is in BUST state or not.
'''
if self.hand_total() > 21:
self.busted = True
return True
else:
self.busted = False
return False
def show_hand(self):
for card in self.cards:
print(card.card_line1... | # sum the hand again to see if it is 21 or less. This will be repeated
# if there are more Aces in the hand and the sum total remains over 21.
aces -= 1
hand_value -= 10
if hand_value <= 21:
# print(f"NOT BUST: Hand value i... | conditional_block |
play_blackjack.py | # -*- coding: utf-8 -*-
"""
Black Jack
Version: Alpha 0.1
Created on Wed Jan 2 23:41:46 2019
@author: Jason Bubenicek
"""
import random
from IPython.display import clear_output
import os
from colorama import init
init()
from colorama import Fore
PLAYERS = []
HOUSE = []
def cls():
# https://... | # These lists will be used to populate the Deck
suits = [("Hearts","Red",0),("Diamonds","Red",1),("Clubs","Black",2),("Spades","Black",3)]
names = [("Two",2,"2"),("Three",3,"3"),("Four",4,"4"),("Five",5,"5"),("Six",6,"6"),("Seven",7,"7"),("Eight",8,"8"),("Nine",9,"9"),("Ten",10,"10"),("Jack",10,"J"),("Quee... | identifier_name | |
play_blackjack.py | # -*- coding: utf-8 -*-
"""
Black Jack
Version: Alpha 0.1
Created on Wed Jan 2 23:41:46 2019
@author: Jason Bubenicek
"""
import random
from IPython.display import clear_output
import os
from colorama import init
init()
from colorama import Fore
PLAYERS = []
HOUSE = []
def cls():
# https://... | view the deck, first (y/n)?") == "y":
d.show_deck()
input("Press any key to continue.")
# Generate a list of Hands one for each players
playing_hands = []
for hand_id in range(0,len(PLAYERS)):
playing_hands.append(Hand(f"{PLAYERS[hand_id].name}", 20))
... | y:
bet = int(input(f"{player_hand.player}, how much would you like to bet? ($20 to $100)?"))
except:
print("You must enter a numeric value between 20 and 100.")
bet = 0
player_hand.amount_bet = bet
def play():
# Get the Deck ... | identifier_body |
play_blackjack.py | # -*- coding: utf-8 -*-
"""
Black Jack
Version: Alpha 0.1
Created on Wed Jan 2 23:41:46 2019
@author: Jason Bubenicek
"""
import random
from IPython.display import clear_output
import os
from colorama import init
init()
from colorama import Fore
PLAYERS = []
HOUSE = []
def cls():
# https://... | print(self.card_line3)
print(self.card_line4)
print(self.card_line5)
print(self.card_line6)
print(self.card_line7)
class Deck():
# Create a blank list to hold the cards that are
# added to this Deck
# cards = []
# These lists will be used to... | def show_card(self):
print(self.card_line1)
print(self.card_line2)
| random_line_split |
mod.rs | //! # Day 19: Go With The Flow
//!
//! With the Elves well on their way constructing the North Pole base, you turn
//! your attention back to understanding the inner workings of programming the
//! device.
//!
//! You can't help but notice that the device's opcodes don't contain any flow
//! control like jump instructi... | (reg: &mut Register) -> Addr {
if reg[4] % reg[5] == 0 {
reg[0] = reg[5] + reg[0];
}
reg[2] = reg[4];
reg[1] = 0;
12
}
#[cfg(test)]
mod tests;
| optimized | identifier_name |
mod.rs | //! # Day 19: Go With The Flow
//!
//! With the Elves well on their way constructing the North Pole base, you turn
//! your attention back to understanding the inner workings of programming the
//! device.
//!
//! You can't help but notice that the device's opcodes don't contain any flow
//! control like jump instructi... | //! bound to register 0 in this program. This is not an instruction, and so
//! the value of the instruction pointer does not change during the processing
//! of this line.
//! * The instruction pointer contains 0, and so the first instruction is
//! executed (seti 5 0 1). It updates register 0 to the current i... | //! In detail, when running this program, the following events occur:
//!
//! * The first line (#ip 0) indicates that the instruction pointer should be | random_line_split |
mod.rs | //! # Day 19: Go With The Flow
//!
//! With the Elves well on their way constructing the North Pole base, you turn
//! your attention back to understanding the inner workings of programming the
//! device.
//!
//! You can't help but notice that the device's opcodes don't contain any flow
//! control like jump instructi... | ,
}
}
#[inline]
fn _trace(ip: Addr, Instruction { opcode, a, b, c }: Instruction, reg: &Register) {
match opcode {
AddR => println!("{:02}: {} {} {} {} : {} ", ip, opcode, a, b, c, reg),
AddI => println!("{:02}: {} {} {} {} : {} ", ip, opcode, a, b, c, reg),
MulR => println!("{:02}: {} ... | { 0 } | conditional_block |
outputschedule.py | # -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
def roundOffCheck(val, target):
if abs(val - target) < 10.*utils.machine_epsilon*target:
return target
return val
| for output in self.outputs:
output.save(datafile, meshctxt) | identifier_body |
outputschedule.py | # -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... | (self):
return [o.name() for o in self.outputs]
def reset(self, time0, continuing):
# Reset all output schedules, and advance them to the first
# time after time0 (which is the earliest time in the current
# evolution).
self.finished.clear()
self.nexttimes = utils.Ord... | names | identifier_name |
outputschedule.py | # -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... | if firsttime is None:
firsttime = time
if time != firsttime:
return False
return True
def getByName(self, name):
for o in self.outputs:
if o.name() == name:
return o
raise ValueError("No such scheduled output... | random_line_split | |
outputschedule.py | # -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
if firsttime is None:
firsttime = time
if time != firsttime:
return False
return True
def getByName(self, name):
for o in self.outputs:
if o.name() == name:
return o
raise ValueError("No such scheduled outpu... | return False | conditional_block |
dynamic_model_python_basic.py | #-*- coding: utf-8 -*-
#
# Copyright 2013-2014 Antoine Drouin (poinix@gmail.com)
#
# This file is part of PAT.
#
# PAT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, ... |
def name(self):
return "Fixed Wing Python Basic ({:s})".format(self.P.name)
def reset(self, X0=None):
if X0<>None: self.X = X0
else: self.X = np.array([0., 0., 0., 68., 0., 0., 0., 0., 0., 0., 0., 0.])
return self.X
def run(self, dt, U):
foo, self.X = scipy.integr... | print "Info: Dynamic fixed wing basic"
dm.DynamicModel.__init__(self)
if params == None: params="../config/Rcam_single_engine.xml"
self.X = np.zeros(DynamicModel.sv_size)
self.P = Param(params)
self.reset() | identifier_body |
dynamic_model_python_basic.py | #-*- coding: utf-8 -*-
#
# Copyright 2013-2014 Antoine Drouin (poinix@gmail.com)
#
# This file is part of PAT.
#
# PAT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, ... |
if legend<>None:
plt.legend(legend, loc='best')
if U<>None:
ax = figure.add_subplot(5, 3, 13)
ax.plot(time, 100*U[:, 0])
pu.decorate(ax, title="$d_{th}$", ylab="%")
ax = figure.add_subplot(5, 3, 14)
ax.plot(time, pu.d... | ax = plt.subplot(nrow, 3, i+1)
plt.plot(time, data)
pu.decorate(ax, title=title, ylab=ylab) | conditional_block |
dynamic_model_python_basic.py | #-*- coding: utf-8 -*-
#
# Copyright 2013-2014 Antoine Drouin (poinix@gmail.com)
#
# This file is part of PAT.
#
# PAT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, ... | (self, Xe, Ue):
A,B = pu.num_jacobian(Xe, Ue, self.P, dyn)
return A, B
def state_str(self):
return """pos: {:-.2f}, {:-.2f}, {:-.2f} m
vel: {:-.2f} m/s, alpha {:-.2f}, beta {:-.2f} deg
att: {:-.2f}, {:-.2f}, {:-.2f} deg
""".format(self.X[sv_x], self.X[sv_y], self... | get_jacobian | identifier_name |
dynamic_model_python_basic.py | #-*- coding: utf-8 -*-
#
# Copyright 2013-2014 Antoine Drouin (poinix@gmail.com)
#
# This file is part of PAT.
#
# PAT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, ... | Xdot = dyn(X, 0., U, P)
Xdot_ref = [va*math.cos(gamma), 0., -va*math.sin(gamma), 0., 0., 0., 0., 0., 0., 0., 0., 0.]
return np.linalg.norm(Xdot - Xdot_ref)
p0 = [0.2, pu.rad_of_deg(2.), pu.rad_of_deg(0.)]
thr_e, ele_e, alpha_e = scipy.optimize.fmin_powell(err_func, p0, disp=debug, ftol=... |
def err_func((throttle, elevator, alpha)):
X=[0., 0., -h, va, alpha, 0., 0., gamma+alpha, 0., 0., 0., 0.]
U = np.zeros(P.input_nb)
U[0:P.eng_nb] = throttle; U[P.eng_nb+iv_de] = elevator | random_line_split |
ibazel_test.go | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appl... |
m.signalChan <- syscall.SIGTERM
<-m.doTermChan
m.terminated = true
m.didTermChan <- struct{}{}
}
func (m *mockCommand) Kill() {
if !m.started {
panic("Sending kill signal before terminating")
}
m.signalChan <- syscall.SIGKILL
}
func (m *mockCommand) assertTerminated(t *testing.T) {
select {
case <-m.didTerm... | {
panic("Terminated before starting")
} | conditional_block |
ibazel_test.go | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appl... | (t *testing.T) {
log.SetTesting(t)
i := &IBazel{}
err := i.setup()
if err != nil {
t.Errorf("Error creating IBazel: %s", err)
}
i.sigs = make(chan os.Signal, 1)
defer i.Cleanup()
osExitChan := make(chan int, 1)
osExit = func(i int) {
osExitChan <- i
}
cmd := &mockCommand{
signalChan: make(chan sysc... | TestHandleSignals_SIGINTNormalTermination | identifier_name |
ibazel_test.go | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appl... |
func assertOsExited(t *testing.T, osExitChan chan int) {
select {
case exitCode := <-osExitChan:
assertEqual(t, 3, exitCode, "Should have exited ibazel")
case <-time.After(time.Second):
t.Errorf("It should have os.Exit'd")
debug.PrintStack()
}
}
func assertNotOsExited(t *testing.T, osExitChan chan int) {
se... | {
if !reflect.DeepEqual(want, got) {
t.Errorf("Wanted %s, got %s. %s", want, got, msg)
debug.PrintStack()
}
} | identifier_body |
ibazel_test.go | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appl... | // Yet another ctrl-c terminates ibazel
i.sigs <- syscall.SIGINT
i.handleSignals()
assertOsExited(t, osExitChan)
}
func TestHandleSignals_SIGINTHitLimitTermination(t *testing.T) {
log.SetTesting(t)
i := &IBazel{}
err := i.setup()
if err != nil {
t.Errorf("Error creating IBazel: %s", err)
}
i.sigs = make(c... | cmd.assertSignal(t, syscall.SIGKILL)
cmd.doTermChan <- struct{}{}
cmd.assertTerminated(t)
assertNotOsExited(t, osExitChan)
| random_line_split |
ym.rs | use core::time::Duration;
use core::num::NonZeroU32;
use core::fmt;
use core::ops::Range;
use chrono::NaiveDateTime;
pub mod flags;
pub mod effects;
mod parse;
mod player;
use flags::*;
use effects::*;
pub const MAX_DD_SAMPLES: usize = 32;
pub const MFP_TIMER_FREQUENCY: u32 = 2_457_600;
const DEFAULT_CHIPSET_FREQUE... |
/// Returns the song duration.
pub fn song_duration(&self) -> Duration {
let seconds = self.frames.len() as f64 / self.frame_frequency as f64;
Duration::from_secs_f64(seconds)
}
/// Returns the AY/YM chipset clock frequency.
#[inline]
pub fn clock_frequency(&self) -> f32 {
... | {
self.chipset_frequency = chipset_frequency;
self.frame_frequency = frame_frequency;
self
} | identifier_body |
ym.rs | use core::time::Duration;
use core::num::NonZeroU32;
use core::fmt;
use core::ops::Range;
use chrono::NaiveDateTime;
pub mod flags;
pub mod effects;
mod parse;
mod player;
use flags::*;
use effects::*;
pub const MAX_DD_SAMPLES: usize = 32;
pub const MFP_TIMER_FREQUENCY: u32 = 2_457_600;
const DEFAULT_CHIPSET_FREQUE... | (&self) -> Duration {
let seconds = self.frames.len() as f64 / self.frame_frequency as f64;
Duration::from_secs_f64(seconds)
}
/// Returns the AY/YM chipset clock frequency.
#[inline]
pub fn clock_frequency(&self) -> f32 {
self.chipset_frequency as f32
}
/// Returns the... | song_duration | identifier_name |
ym.rs | use core::time::Duration;
use core::num::NonZeroU32;
use core::fmt;
use core::ops::Range;
use chrono::NaiveDateTime;
pub mod flags;
pub mod effects;
mod parse;
mod player;
use flags::*;
use effects::*;
pub const MAX_DD_SAMPLES: usize = 32;
pub const MFP_TIMER_FREQUENCY: u32 = 2_457_600;
const DEFAULT_CHIPSET_FREQUE... | /// uses one of the 40 predefined samples.
///
/// * The effect starts when the highest bit (7) of the `Volume voice C` register (10) is 1.
/// * The sample number is taken from the lowest 7 bits of the `Volume voice C` register (10).
/// * The effect frequency is calculated by `(2457600 / 4) / X`, where `X` is the uns... | random_line_split | |
coprocessor.rs | // Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | {
let mut rows = vec![];
let mut seek_key = r.take_start();
loop {
trace!("seek {:?}", seek_key);
let mut nk = try!(snap.scan(Key::from_raw(seek_key.clone()), 1));
if nk.is_empty() {
debug!("no more data to scan");
return Ok(rows);
}
let (key, ... | identifier_body | |
coprocessor.rs | // Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | } else {
let h = box_try!((&*value).read_i64::<BigEndian>());
Datum::I64(h)
};
let data = box_try!(datum::encode_value(&datums));
let handle_data = box_try!(datum::encode_value(&[handle]));
let mut row = Row::new();
row.set_handle(handle_data);
... | return Ok(rows);
}
let mut datums = box_try!(table::decode_index_key(&key));
let handle = if datums.len() > info.get_columns().len() {
datums.pop().unwrap() | random_line_split |
coprocessor.rs | // Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (req: Request,
ch: SendCh,
token: Token,
msg_id: u64,
end_point: &SnapshotEndPoint) {
let cb = box move |r| {
let mut resp_msg = Message::new();
resp_msg.set_msg_type(MessageType::CopResp);
resp_msg.set_cop_resp(r);
... | handle_request | identifier_name |
ReviewIntangibleAssets.js | //资产基础信息维护列表
//所有元素选择器
var selector = {
$grid: function () { return $("#jqxTable") },
$btnSearch: function () { return $("#btnSearch") },
$btnReset: function () { return $("#btnReset") },
$EditPermission: function () { return $("#EditPermission") }
}; //selector end
var isEdit = false;
var vguid = "";
... | ength == 0) {
arr.push("Default");
}
var dataAdapter = new $.jqx.dataAdapter(arr);
$("#SubmitYearMonth").jqxComboBox({ selectedIndex: 0, source: dataAdapter, width: 198, height: 33 });
$("#SubmitYearMonth").jqxComboBox({ itemHeight: 33 });
$("#SubmitYearMonth input").... | var m = d.getMonth() - i;
var y = d.getFullYear();
if (m <= 0) {
m = m + 12;
y = y - 1;
}
m = (m < 10 ? "0" + m : m);
arr.push(y.toString() + "-" + m.toString());
}
debugger;
if (arr.l | conditional_block |
ReviewIntangibleAssets.js | //资产基础信息维护列表
//所有元素选择器
var selector = {
$grid: function () { return $("#jqxTable") },
$btnSearch: function () { return $("#btnSearch") },
$btnReset: function () { return $("#btnReset") },
$EditPermission: function () { return $("#EditPermission") }
}; //selector end
var isEdit = false;
var vguid = "";
... | margin-left:7px ;margin-top: 7px;'>";
checkBox += "</div>";
return checkBox;
}
function renderedFunc(element) {
var grid = selector.$grid();
element.jqxCheckBox();
element.on('change', function (event) {
var checked = element.jqxCheckBox('checked');
... | e='z-index: 999; | identifier_name |
ReviewIntangibleAssets.js | //资产基础信息维护列表
//所有元素选择器
var selector = {
$grid: function () { return $("#jqxTable") },
$btnSearch: function () { return $("#btnSearch") },
$btnReset: function () { return $("#btnReset") },
$EditPermission: function () { return $("#EditPermission") }
}; //selector end
var isEdit = false;
var vguid = "";
... | element.jqxCheckBox();
element.on('change', function (event) {
var checked = element.jqxCheckBox('checked');
if (checked) {
var rows = grid.jqxDataTable('getRows');
for (var i = 0; i < rows.length; i++) {
grid.jqxDataTable('sele... | var grid = selector.$grid(); | random_line_split |
ReviewIntangibleAssets.js | //资产基础信息维护列表
//所有元素选择器
var selector = {
$grid: function () { return $("#jqxTable") },
$btnSearch: function () { return $("#btnSearch") },
$btnReset: function () { return $("#btnReset") },
$EditPermission: function () { return $("#EditPermission") }
}; //selector end
var isEdit = false;
var vguid = "";
... | ields:
[
{ name: "checkbox", type: null },
{ name: 'VGUID', type: 'string' },
{ name: 'OrderNumber', type: 'string' },
{ name: 'PayItem', type: 'string' },
{ name: 'VehicleModel', type: 'string' },
... | success: function (msg) {
switch (msg.Status) {
case "0":
jqxNotification("提交失败!", null, "error");
break;
case "1":
jqxNotification("提交成功!", null, "success");
... | identifier_body |
__main__.py | # Copyright 2014 devbliss GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | ():
# check if pwd is repository root in order to run makefile hooks properly
rev_parse = git('rev-parse --show-toplevel', pipe=True).strip()
if os.path.abspath(rev_parse) != os.path.abspath(os.getcwd()):
print('You need to run this command from the toplevel'
' of the working tree.', f... | check_repo_toplevel | identifier_name |
__main__.py | # Copyright 2014 devbliss GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
def release(version):
if not re.match(r'^\d+\.\d+\.\d+$', version):
print('Invalid version number', file=sys.stderr)
sys.exit(2)
git('fetch --quiet origin')
branch = git('rev-parse --abbrev-ref HEAD', pipe=True)
if not is_repository_clean():
print('Error: Repository is not c... | if branch_name == 'finish':
print('You are creating a branch "{branch_type}/{branch_name}". '
'Did you mean to type "git devbliss finish"?'.format(**locals()))
print('You can delete this branch with "git devbliss delete'
' {branch_type}/{branch_name}"'.format(**locals()))
... | identifier_body |
__main__.py | # Copyright 2014 devbliss GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | try:
git('checkout --quiet -b {branch_type}/{branch_name}'.format(
**locals()))
except subprocess.CalledProcessError:
git('checkout --quiet {branch_type}/{branch_name}'.format(
**locals()))
git('push --set-upstream origin {branch_type}/{branch_name}'.format(
*... | print('You can delete this branch with "git devbliss delete'
' {branch_type}/{branch_name}"'.format(**locals()))
git('checkout --quiet master')
git('pull --quiet origin master') | random_line_split |
__main__.py | # Copyright 2014 devbliss GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
else:
print('Warning: No Makefile found. All make hooks have been skipped.',
file=sys.stderr)
def branch(branch_type, branch_name):
if branch_name == 'finish':
print('You are creating a branch "{branch_type}/{branch_name}". '
'Did you mean to type "git devbliss fin... | os.system(
'{env_vars} make {hook} || echo "Warning: Makefile has no target'
' named {hook}"'.format(**locals()))
if not is_repository_clean():
git('commit --quiet -am "Ran git devbliss {hook} hook"'.format(
**locals())) | conditional_block |
server.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (&self) -> Result<(), Error> {
let head = self.chain.head()?;
self.p2p.peers.check_all(head.total_difficulty, head.height);
Ok(())
}
/// Number of peers
pub fn peer_count(&self) -> u32 {
self.p2p
.peers
.iter()
.connected()
.count()
.try_into()
.unwrap()
}
/// Start a minimal "stratum" ... | ping_peers | identifier_name |
server.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
/// The head of the block header chain
pub fn header_head(&self) -> Result<chain::Tip, Error> {
self.chain.header_head().map_err(|e| e.into())
}
/// The p2p layer protocol version for this node.
pub fn protocol_version() -> ProtocolVersion {
ProtocolVersion::local()
}
/// Returns a set of stats about thi... | {
self.chain.head().map_err(|e| e.into())
} | identifier_body |
server.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | };
let disk_usage_bytes = WalkDir::new(&self.config.db_root)
.min_depth(1)
.max_depth(3)
.into_iter()
.filter_map(|entry| entry.ok())
.filter_map(|entry| entry.metadata().ok())
.filter(|metadata| metadata.is_file())
.fold(0, |acc, m| acc + m.len());
let disk_usage_gb = format!("{:.*}", 3, (... | let header_stats = ChainStats {
latest_timestamp: header.timestamp,
height: header.height,
last_block_h: header.hash(),
total_difficulty: header.total_difficulty(), | random_line_split |
server.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
},
p2p::Seeding::DNSSeed => seed::default_dns_seeds(),
_ => unreachable!(),
};
connect_thread = Some(seed::connect_and_monitor(
p2p_server.clone(),
seed_list,
config.p2p_config.clone(),
stop_state.clone(),
)?);
}
// Defaults to None (optional) in config file.
// This transl... | {
return Err(Error::Configuration(
"Seeds must be configured for seeding type List".to_owned(),
));
} | conditional_block |
genesis.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: kira/tokens/genesis.proto
package types
import (
fmt "fmt"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Er... |
if m.TokenBlackWhites == nil {
m.TokenBlackWhites = &TokensWhiteBlack{}
}
if err := m.TokenBlackWhites.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipGenesis(dAtA[iNdEx:])
if err != nil {
return err
}
... | {
return io.ErrUnexpectedEOF
} | conditional_block |
genesis.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: kira/tokens/genesis.proto
package types
import (
fmt "fmt"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Er... | Rates []*TokenRate `protobuf:"bytes,2,rep,name=rates,proto3" json:"rates,omitempty"`
TokenBlackWhites *TokensWhiteBlack `protobuf:"bytes,3,opt,name=tokenBlackWhites,proto3" json:"tokenBlackWhites,omitempty"`
}
func (m *GenesisState) Reset() { *m = GenesisState{} }
func (m *GenesisState) Strin... |
type GenesisState struct {
Aliases []*TokenAlias `protobuf:"bytes,1,rep,name=aliases,proto3" json:"aliases,omitempty"` | random_line_split |
genesis.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: kira/tokens/genesis.proto
package types
import (
fmt "fmt"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Er... | () {}
func (*GenesisState) Descriptor() ([]byte, []int) {
return fileDescriptor_d3cbd9121e22d5d1, []int{0}
}
func (m *GenesisState) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo... | ProtoMessage | identifier_name |
genesis.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: kira/tokens/genesis.proto
package types
import (
fmt "fmt"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Er... |
var xxx_messageInfo_GenesisState proto.InternalMessageInfo
func (m *GenesisState) GetAliases() []*TokenAlias {
if m != nil {
return m.Aliases
}
return nil
}
func (m *GenesisState) GetRates() []*TokenRate {
if m != nil {
return m.Rates
}
return nil
}
func (m *GenesisState) GetTokenBlackWhites() *TokensWhi... | {
xxx_messageInfo_GenesisState.DiscardUnknown(m)
} | identifier_body |
util.js | const dateFormat = require('dateformat');
const randomstring = require("randomstring");
const queryString = require('query-string');
const $ = require('jquery');
const md5 = require('md5');
const sprintf = require('sprintf-js').sprintf
export const UUID = {
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12)
... | } else {
ret += chr;
}
}
return ret;
},
getQueries(query = undefined) {
return UrlUtil.parseQuery(query)
},
getQuery(key, defaultValue = null, query = undefined) {
const param = UrlUtil.parseQuery(query)
if (key in param) {
... | ret += asc2str(parseInt("0x" + asc));
i += 2;
}
| conditional_block |
util.js | const dateFormat = require('dateformat');
const randomstring = require("randomstring");
const queryString = require('query-string');
const $ = require('jquery');
const md5 = require('md5');
const sprintf = require('sprintf-js').sprintf
export const UUID = {
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12)
... | export const FormatUtil = {
telephone(number) {
if (!number) {
return null
}
// console.log('before',number);
[/\+86/g, /\+/g, / /g, /\(/g, /\)/g, /-/g, /(/g, /)/g, / /g, /"/g, /;/g, /\t/g].forEach(o => {
number = number.replace(o, '')
})
// co... | random_line_split | |
util.js | const dateFormat = require('dateformat');
const randomstring = require("randomstring");
const queryString = require('query-string');
const $ = require('jquery');
const md5 = require('md5');
const sprintf = require('sprintf-js').sprintf
export const UUID = {
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12)
... | bean,beanNewValue可以是部分字段
* @param bean
* @param beanNewValue
*/
update(bean, beanNewValue) {
if (!bean || !beanNewValue) {
return
}
Object.keys(beanNewValue).map(o => {
bean[o] = beanNewValue[o]
})
},
/**
* 判断两个Bean是否相等,注意键值的顺序也要一样
... |
return
}
Object.keys(bean).map(o => {
bean[o] = valuePool[o]
})
},
/**
* 使用 beanNewValue 更新 | identifier_body |
util.js | const dateFormat = require('dateformat');
const randomstring = require("randomstring");
const queryString = require('query-string');
const $ = require('jquery');
const md5 = require('md5');
const sprintf = require('sprintf-js').sprintf
export const UUID = {
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12)
... | {
let ret = "";
const strSpecial = "!\"#$%&'()*+,/:;<=>?[]^`{|}~%";
let tt = "";
for (let i = 0; i < str.length; i++) {
let chr = str.charAt(i);
let c = str2asc(chr);
tt += chr + ":" + c + "n";
if (parseInt("0x" + c) > 0x7f) {
... | ode(str) | identifier_name |
fileopentypeenum.go | package pathfileops
import (
"fmt"
"os"
"reflect"
"strings"
)
// mFileOpenTypeIntToString - This map is used to map enumeration values
// to enumeration names stored as strings for Type FileOpenType.
var mFileOpenTypeIntToString = map[int]string{}
// mFileOpenTypeStringToInt - This map is used to map enumera... | // for this type.
//
func (fOpenType FileOpenType) IsValid() error {
fOpenType.checkInitializeMaps(false)
_, ok := mFileOpenTypeIntToString[int(fOpenType)]
if !ok {
ePrefix := "FileOpenType.IsValid() "
return fmt.Errorf(ePrefix+
"Error: Invalid FileOpenType! Current FileOpenType='%v'",
fOpe... | // this method will return an error. If the FileOpenType is 'valid',
// this method will return a value of 'nil'.
//
// This is a standard utility method and is not part of the valid enumerations | random_line_split |
fileopentypeenum.go | package pathfileops
import (
"fmt"
"os"
"reflect"
"strings"
)
// mFileOpenTypeIntToString - This map is used to map enumeration values
// to enumeration names stored as strings for Type FileOpenType.
var mFileOpenTypeIntToString = map[int]string{}
// mFileOpenTypeStringToInt - This map is used to map enumera... |
var ok bool
var idx int
if caseSensitive {
if !strings.HasPrefix(valueString, "Type") {
valueString = "Type" + valueString
}
idx, ok = mFileOpenTypeStringToInt[valueString]
if !ok {
return FileOpenType(0),
fmt.Errorf(ePrefix+
"'valueString' did NOT MATCH a FileO... | {
return result,
fmt.Errorf(ePrefix+
"Input parameter 'valueString' is INVALID! valueString='%v' ", valueString)
} | conditional_block |
fileopentypeenum.go | package pathfileops
import (
"fmt"
"os"
"reflect"
"strings"
)
// mFileOpenTypeIntToString - This map is used to map enumeration values
// to enumeration names stored as strings for Type FileOpenType.
var mFileOpenTypeIntToString = map[int]string{}
// mFileOpenTypeStringToInt - This map is used to map enumera... |
// ReadOnly - File opened for 'Read Only' access
func (fOpenType FileOpenType) TypeReadOnly() FileOpenType { return FileOpenType(os.O_RDONLY) }
// WriteOnly - File opened for 'Write Only' access
func (fOpenType FileOpenType) TypeWriteOnly() FileOpenType { return FileOpenType(os.O_WRONLY) }
// ReadWrite - File opene... | { return -1 } | identifier_body |
fileopentypeenum.go | package pathfileops
import (
"fmt"
"os"
"reflect"
"strings"
)
// mFileOpenTypeIntToString - This map is used to map enumeration values
// to enumeration names stored as strings for Type FileOpenType.
var mFileOpenTypeIntToString = map[int]string{}
// mFileOpenTypeStringToInt - This map is used to map enumera... | () FileOpenType { return FileOpenType(os.O_RDONLY) }
// WriteOnly - File opened for 'Write Only' access
func (fOpenType FileOpenType) TypeWriteOnly() FileOpenType { return FileOpenType(os.O_WRONLY) }
// ReadWrite - File opened for 'Read and Write' access
func (fOpenType FileOpenType) TypeReadWrite() FileOpenType { re... | TypeReadOnly | identifier_name |
activeTopicPage.js | /**满立减
* Created by xiuxiu on 2016/4/11.
*/
require([
'jquery',
'h5/js/common/data',
'h5/js/common',
'h5/js/common/loadImage',
'h5/js/common/nexter',
'h5/js/common/goods',
'h5/js/common/cart',
'h5/js/common/weixin',
'h5/js/common/url',
'h5/js/common/banner',
'h5/js/common/t... | identifier_body | ||
activeTopicPage.js | /**满立减
* Created by xiuxiu on 2016/4/11.
*/
require([
'jquery',
'h5/js/common/data',
'h5/js/common',
'h5/js/common/loadImage',
'h5/js/common/nexter',
'h5/js/common/goods',
'h5/js/common/cart',
'h5/js/common/weixin',
'h5/js/common/url',
'h5/js/common/banner',
'h5/js/common/t... | gid = view.data('id'),
item = Cart.query(gid) || Cart.create(Goods.query(gid));
if (item) {
item.add({
btn: btn,
start: function(newCount) {
btn.addClass('adding');
view.find('.count').text(newCount);
... | ds'),
| identifier_name |
activeTopicPage.js | /**满立减
* Created by xiuxiu on 2016/4/11.
*/
require([
'jquery',
'h5/js/common/data',
'h5/js/common',
'h5/js/common/loadImage',
'h5/js/common/nexter',
'h5/js/common/goods',
'h5/js/common/cart',
'h5/js/common/weixin',
'h5/js/common/url',
'h5/js/common/banner',
'h5/js/common/t... | view: view,
},_isapp).always(function(res) {
item.count > 0 ? view.find('.count').text(item.count).css({visibility: "visible"}) : view.find('.count').css({visibility: "hidden"});
refreshCart();
}).fail(function(json) {
if (item.go... | }
});
},
count: 1, | random_line_split |
activeTopicPage.js | /**满立减
* Created by xiuxiu on 2016/4/11.
*/
require([
'jquery',
'h5/js/common/data',
'h5/js/common',
'h5/js/common/loadImage',
'h5/js/common/nexter',
'h5/js/common/goods',
'h5/js/common/cart',
'h5/js/common/weixin',
'h5/js/common/url',
'h5/js/common/banner',
'h5/js/common/t... | init();
}) | });
}
}
function refreshCart() {
Common.getCartCount();
Common.isLogin && Cart.ready(function() {
// renderSmallCart();
// refreshListCount();
});
}
| conditional_block |
main.go | package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
)
var (
Token string
Color = 0x009688
//Icons = "https://kittyhacker101.tk/Static/KatBot"
Icons = "https://cdn.disco... | if err != nil {
log.Fatal(err)
}
var mystatus shortStatusResult
err = json.Unmarshal([]byte(bodyBytes), &mystatus)
if err != nil {
fmt.Println("unmarshal error: ")
fmt.Println(err)
}
var returnText = ""
if mystatus.State == "on" {
returnText = Emojis["laseron"] + " **" + strings.ToUpper(myst... | resp, err := client.Do(req)
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body) | random_line_split |
main.go | package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
)
var (
Token string
Color = 0x009688
//Icons = "https://kittyhacker101.tk/Static/KatBot"
Icons = "https://cdn.disco... |
//====
func checkIfDeviceExists(device string) bool {
// get all the device names and store in an array
i := 0
devicearray := make([]string, len(DeviceMap))
for k := range DeviceMap {
devicearray[i] = k
i++
}
for _, a := range devicearray {
if strings.ToLower(a) == strings.ToLower(device) {
return tr... | {
fmt.Println("starting handlerLaser2")
queries := r.URL.Query()
fmt.Printf("queries = %q\n", queries)
if APITOKEN != queries.Get("api") {
fmt.Fprintf(webprint, "%s", "ERROR: Invalid API")
return
}
var returnText = ""
switch strings.ToLower(queries.Get("action")) {
case "off":
returnText = Emojis["eeht... | identifier_body |
main.go | package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
)
var (
Token string
Color = 0x009688
//Icons = "https://kittyhacker101.tk/Static/KatBot"
Icons = "https://cdn.disco... |
if m.Content == "!laser backlight on" {
s.ChannelMessageSend(m.ChannelID, backlight("on"))
}
if m.Content == "!laser backlight off" {
s.ChannelMessageSend(m.ChannelID, backlight("off"))
}
if m.Content == "!laser fullstatus" {
s.ChannelMessageSend(m.ChannelID, fullStatus())
}
if m.Content == "!laser he... | {
return
} | conditional_block |
main.go | package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
)
var (
Token string
Color = 0x009688
//Icons = "https://kittyhacker101.tk/Static/KatBot"
Icons = "https://cdn.disco... | (mystate string) string {
fmt.Println("starting backlight")
url := fmt.Sprintf("http://192.168.10.135/backlight?api=%s&state=%s", DEVICEAPITOKEN, mystate)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal("NewRequest: ", err)
return "ERROR"
}
client := &http.Client{}
client.Timeout = tim... | backlightold | identifier_name |
hkdf_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
#[test]
fn test_hkdf_prf_output_length() {
let testdata = hashmap! {
HashType::Sha1 => 20,
HashType::Sha256 => 32,
HashType::Sha512 => 64,
};
for (hash, length) in testdata {
let prf = HkdfPrf::new(
hash,
&[
0x01, 0x02, 0x03, 0x04, 0x... | {
assert!(
HkdfPrf::new(
HashType::Sha256,
&[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10
],
&[]
)
.is_ok(),
"Expected HkdfPrf::new to work empty salt"
... | identifier_body |
hkdf_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | &[]
)
.is_ok(),
"Expected HkdfPrf::new to work with SHA512"
);
assert!(
HkdfPrf::new(
HashType::Sha1,
&[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10
... | 0x0f, 0x10
], | random_line_split |
hkdf_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | else {
assert_ne!(
res, tc.okm,
"Computed HKDF {:?} PRF and invalid expected for test case {} ({}) match",
hash, tc.case.case_id, tc.case.comment
);
}
}
}
}
}
#[test]... | {
assert_eq!(
res, tc.okm,
"Computed HKDF {:?} PRF and expected for test case {} ({}) do not match",
hash, tc.case.case_id, tc.case.comment
);
} | conditional_block |
hkdf_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | () {
for hash in &[HashType::Sha1, HashType::Sha256, HashType::Sha512] {
let hash_name = format!("{:?}", hash);
let filename = format!("testvectors/hkdf_{}_test.json", hash_name.to_lowercase());
println!("wycheproof file '{}' hash {}", filename, hash_name);
let bytes = tink_tests::wy... | test_hkdf_prf_wycheproof_cases | identifier_name |
config.rs | //! Tendermint configuration file types (with serde parsers/serializers)
//!
//! This module contains types which correspond to the following config files:
//!
//! - `config.toml`: `config::TendermintConfig`
//! - `node_key.rs`: `config::node_key::NodeKey`
//! - `priv_validator_key.rs`: `config::priv_validator_key::Pri... | (String);
impl AsRef<str> for CorsMethod {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl fmt::Display for CorsMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.0)
}
}
/// HTTP headers allowed to be sent via CORS to the RPC API
// TODO(tarc... | CorsMethod | identifier_name |
config.rs | //! Tendermint configuration file types (with serde parsers/serializers)
//!
//! This module contains types which correspond to the following config files:
//!
//! - `config.toml`: `config::TendermintConfig`
//! - `node_key.rs`: `config::node_key::NodeKey`
//! - `priv_validator_key.rs`: `config::priv_validator_key::Pri... |
let key = parts[0].to_owned();
let value = parts[1].to_owned();
if levels.insert(key, value).is_some() {
return Err(err!(
ErrorKind::Parse,
"duplicate log level setting for: {}",
level
));
... | {
return Err(err!(ErrorKind::Parse, "error parsing log level: {}", level));
} | conditional_block |
config.rs | //! Tendermint configuration file types (with serde parsers/serializers)
//!
//! This module contains types which correspond to the following config files:
//!
//! - `config.toml`: `config::TendermintConfig`
//! - `node_key.rs`: `config::node_key::NodeKey`
//! - `priv_validator_key.rs`: `config::priv_validator_key::Pri... | }
/// Mechanism to connect to the ABCI application: socket | grpc
#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum AbciMode {
/// Socket
#[serde(rename = "socket")]
Socket,
/// GRPC
#[serde(rename = "grpc")]
Grpc,
}
/// Tendermint `config.toml` file's `[rpc]... | Plain,
/// JSON
#[serde(rename = "json")]
Json, | random_line_split |
wvc_data.py | import torch
import torch.utils.data as data
from PIL import Image
import logging, os
import numpy as np
import lmdb
import cv2
from torchvision import transforms
import random
import itertools
from webvision import config as wv_config
from torchvision.transforms import functional as trans_func
_logger = logging.getL... |
class JigsawTransform:
def __init__(self, grid_size=3, patch_size=64):
self.grid_size = grid_size
self.patch_size = patch_size
def __call__(self, img):
w, h = img.size
crops = []
for c_i, c_j in itertools.product(range(self.grid_size), range(self.grid_size)):
... | return self.num_samples | identifier_body |
wvc_data.py | import torch
import torch.utils.data as data
from PIL import Image
import logging, os
import numpy as np
import lmdb
import cv2
from torchvision import transforms
import random
import itertools
from webvision import config as wv_config
from torchvision.transforms import functional as trans_func
_logger = logging.getL... | self.class_freq = -1*np.ones(5000)
self.sample_weight = np.ones(self.img_labels.size, np.float)
_logger.info("Webvision {} dataset read with {} images".format(split, len(self.img_ids)))
def __getitem__(self, index):
img_id = self.img_ids[index]
label = self.img_labe... | # assert self.class_freq.size == 5000
self.sample_weight = self.img_labels.size / (self.class_freq[self.img_labels] + 1e-6)
else: | random_line_split |
wvc_data.py | import torch
import torch.utils.data as data
from PIL import Image
import logging, os
import numpy as np
import lmdb
import cv2
from torchvision import transforms
import random
import itertools
from webvision import config as wv_config
from torchvision.transforms import functional as trans_func
_logger = logging.getL... | (self, grid_size=3, patch_size=64):
self.grid_size = grid_size
self.patch_size = patch_size
def __call__(self, img):
w, h = img.size
crops = []
for c_i, c_j in itertools.product(range(self.grid_size), range(self.grid_size)):
# find patch coordinates
t... | __init__ | identifier_name |
wvc_data.py | import torch
import torch.utils.data as data
from PIL import Image
import logging, os
import numpy as np
import lmdb
import cv2
from torchvision import transforms
import random
import itertools
from webvision import config as wv_config
from torchvision.transforms import functional as trans_func
_logger = logging.getL... |
else:
self.class_freq = -1*np.ones(5000)
self.sample_weight = np.ones(self.img_labels.size, np.float)
_logger.info("Webvision {} dataset read with {} images".format(split, len(self.img_ids)))
def __getitem__(self, index):
img_id = self.img_ids[index]
label ... | self.class_freq = np.bincount(self.img_labels)
# assert self.class_freq.size == 5000
self.sample_weight = self.img_labels.size / (self.class_freq[self.img_labels] + 1e-6) | conditional_block |
eeglab2hadoop.py | #!/oasis/scratch/csd181/mdburns/python/bin/python
# Copyright (C) 2012 Matthew Burns <mdburns@ucsd.edu>
from datetime import datetime
import helpers
import helpers.float_open as fop
from scipy import stats, zeros, ones, signal
from scipy.io import loadmat, savemat
import numpy as np
from numpy import array
import os
... |
if raw_data is None:
continue
print(filename + ': identifying outliers')
artifact_indexes = find_artifact_indexes(eeg, ica_act)
eeg['artifact_indexes'] = artifact_indexes;
f=open('..\\artifact_indexes', 'w')
pickle.dump(artifact_indexes,f)
f.close()... | continue | conditional_block |
eeglab2hadoop.py | #!/oasis/scratch/csd181/mdburns/python/bin/python
# Copyright (C) 2012 Matthew Burns <mdburns@ucsd.edu>
from datetime import datetime
import helpers
import helpers.float_open as fop
from scipy import stats, zeros, ones, signal
from scipy.io import loadmat, savemat
import numpy as np
from numpy import array
import os
... |
"""
compile_data: input_str is the path to your imput files, with the character '?' inserted where you want to specify different values.
For instance: 'X:\RSVP\exp?\realtime\exp?_continuous_with_ica' with substitute = range(44,61) will process files
'X:\RSVP\exp44\realtime\exp44_continuous_with_ica.set' ... all the w... | """
from: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/auc.py
Computes the tied rank of elements in x.
This function computes the tied rank of elements in x.
Parameters
----------
x : list of numbers, numpy array
Returns
-------
score : list of numbers
... | identifier_body |
eeglab2hadoop.py | #!/oasis/scratch/csd181/mdburns/python/bin/python
# Copyright (C) 2012 Matthew Burns <mdburns@ucsd.edu>
from datetime import datetime
import helpers
import helpers.float_open as fop
from scipy import stats, zeros, ones, signal | import numpy as np
from numpy import array
import os
import sys
import pickle
import argparse
import base64
import gc
import multiprocessing as mp
from hadoop.io import SequenceFile, Text
NUMFOLDS = 5
NUM_SAMPLES = 0
SAMPLE_RATE = 0
NUM_EVENTS = 0
NUM_POINTS = 0
pool=None
def get_eeg(path, file_name):
print 'get... | from scipy.io import loadmat, savemat | random_line_split |
eeglab2hadoop.py | #!/oasis/scratch/csd181/mdburns/python/bin/python
# Copyright (C) 2012 Matthew Burns <mdburns@ucsd.edu>
from datetime import datetime
import helpers
import helpers.float_open as fop
from scipy import stats, zeros, ones, signal
from scipy.io import loadmat, savemat
import numpy as np
from numpy import array
import os
... | (input_str, substitute, outputpath=''):
temp = input_str.rpartition(os.sep)
path_temp = temp[0]
file_temp = temp[2]
f=open(outputpath+os.sep+'manifest.txt','w')
if outputpath is not '':
try:
os.mkdir(outputpath)
except: pass
ica_key, ica_val, raw_key, raw_val = Tex... | create_file_manifest | identifier_name |
instream.rs | extern crate libsoundio_sys as raw;
use super::error::*;
use super::format::*;
use super::sample::*;
use super::util::*;
use std::marker::PhantomData;
use std::os::raw::{c_double, c_int};
use std::ptr;
use std::slice;
/// This is called when an instream has been read. The `InStreamUserData` struct is obtained
/// fr... | }
// TODO: Can pause() be called from the read callback?
/// If the underlying backend and device support pausing, this pauses the
/// stream. The `write_callback()` may be called a few more times if
/// the buffer is not full.
///
/// Pausing might put the hardware into a low power state ... | } | random_line_split |
instream.rs | extern crate libsoundio_sys as raw;
use super::error::*;
use super::format::*;
use super::sample::*;
use super::util::*;
use std::marker::PhantomData;
use std::os::raw::{c_double, c_int};
use std::ptr;
use std::slice;
/// This is called when an instream has been read. The `InStreamUserData` struct is obtained
/// fr... |
/// Get latency in seconds due to software only, not including hardware.
pub fn software_latency(&self) -> f64 {
unsafe { (*self.instream).software_latency as _ }
}
/// Return the number of channels in this stream. Guaranteed to be at least 1.
pub fn channel_count(&self) -> usize {
... | {
assert!(self.read_started);
self.frame_count
} | identifier_body |
instream.rs | extern crate libsoundio_sys as raw;
use super::error::*;
use super::format::*;
use super::sample::*;
use super::util::*;
use std::marker::PhantomData;
use std::os::raw::{c_double, c_int};
use std::ptr;
use std::slice;
/// This is called when an instream has been read. The `InStreamUserData` struct is obtained
/// fr... | (&mut self) -> Result<()> {
match unsafe { raw::soundio_instream_start(self.userdata.instream) } {
0 => Ok(()),
x => Err(x.into()),
}
}
// TODO: Can pause() be called from the read callback?
/// If the underlying backend and device support pausing, this pauses the
... | start | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2020, CS GROUP - France, http://www.c-s.fr
#
# This file is part of EODAG project
# https://www.github.com/CS-SI/EODAG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of... | >>> sanitize('name with multiple spaces')
'name_with_multiple_spaces'
>>> sanitize('âtre fête île alcôve bûche çà génèse où Noël ovoïde capharnaüm')
'atre_fete_ile_alcove_buche_ca_genese_ou_Noel_ovoide_capharnaum'
>>> sanitize('replace,ponctuation:;signs!?byunderscorekeeping-hyphen.dot_and_undersco... | 'productName' | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2020, CS GROUP - France, http://www.c-s.fr
#
# This file is part of EODAG project
# https://www.github.com/CS-SI/EODAG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of... | rs(dirpath):
"""Create a directory in filesystem with parents if necessary"""
try:
os.makedirs(dirpath)
except OSError as err:
# Reraise the error unless it's about an already existing directory
if err.errno != errno.EEXIST or not os.path.isdir(dirpath):
raise
def updat... | ` `n` times with `args`"""
return starmap(func, repeat(args, n))
def makedi | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2020, CS GROUP - France, http://www.c-s.fr
#
# This file is part of EODAG project
# https://www.github.com/CS-SI/EODAG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of... | (self):
return "FloatRange(%r, %r)" % (self.min, self.max)
def slugify(value, allow_unicode=False):
"""Copied from Django Source code, only modifying last line (no need for safe
strings).
source: https://github.com/django/django/blob/master/django/utils/text.py
Convert to ASCII if 'allow_unic... | __repr__ | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2020, CS GROUP - France, http://www.c-s.fr
#
# This file is part of EODAG project
# https://www.github.com/CS-SI/EODAG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of... | elif (
extend_list_values
and isinstance(old_dict[k], list)
and isinstance(v, list)
):
old_dict[k].extend(v)
elif v:
old_dict[k] = v
else:
old_dict[k] = v
return old_dict
def dict_items_recu... | update_nested_dict(
old_dict[k], v, extend_list_values=extend_list_values
)
| conditional_block |
02.代码实现-06Tensorflow-01Cifar10-01基本网络.py | '''
输入数据->卷积层1->激活层1->池化层1->卷积层2->激活层2->池化层2->非线性全连接层1->非线性全连接层2->全连接层3->SoftMax->Optimizer
输入数据: 24 * 24 * 3 (cifar10的图片都是32*32*3的,需要处理成24*24*3)
卷积层1:5*5 卷积核个数为K1 步长为1,输出为24 * 24 * K1
激活层1:ReLU
池化层1:3*3 步长为2,输出为12 * 12 * K1
卷积层2:5*5 卷积核个数为K2 步长为1,12 * 12 * K2
激活层2:ReLU
池化层2:3*3 步长为2 输出为6 * 6 * K2
非线性全连接层1:神经元个数200(这一层... | accuracy_score = correct_predicted / total_examples
print('--------->Accuracy on Test Examples: ', accuracy_score)
results_list.append(['Accuracy on Test Examples: ', accuracy_score])
results_file = open('../logs/SummaryFiles/02.代码实现-06Tensorflow-02Cifar100-01读取数据集.csv',... | correct_predicted += np.sum(predictions) | random_line_split |
02.代码实现-06Tensorflow-01Cifar10-01基本网络.py | '''
输入数据->卷积层1->激活层1->池化层1->卷积层2->激活层2->池化层2->非线性全连接层1->非线性全连接层2->全连接层3->SoftMax->Optimizer
输入数据: 24 * 24 * 3 (cifar10的图片都是32*32*3的,需要处理成24*24*3)
卷积层1:5*5 卷积核个数为K1 步长为1,输出为24 * 24 * K1
激活层1:ReLU
池化层1:3*3 步长为2,输出为12 * 12 * K1
卷积层2:5*5 卷积核个数为K2 步长为1,12 * 12 * K2
激活层2:ReLU
池化层2:3*3 步长为2 输出为6 * 6 * K2
非线性全连接层1:神经元个数200(这一层... | batches-tfrecords/train_package.tfrecords', batch_size=batch_size,
img_shape=[32,32,3])
return images, labels
'''
获取评估测试集
'''
def get_undistored_eval_batch(eval_data, data_dir, batch_size):
if not data_dir:
raise ValueError('Please supply a data_dir')
data_dir = os.path.join(data_dir, 'cifa... | _out, pool=tf.nn.max_pool, k=3, stride=2, padding='SAME')
with tf.name_scope('Conv2d_2'): # 卷积层2
weights = WeightsVariable(shape=[5, 5, conv1_kernel_num, conv2_kernel_num], name_str='weights', stddev=5e-2)
biases = BiasesVariable(shape=[conv2_kernel_num], name_str='biases', init_value=0.0)
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.