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 |
|---|---|---|---|---|
chart.js | Update]').click(function () {
getTopRevs();
getBotRevs();
});
$('[name=chartUpdate]').click(function () {
var whichChart = $('[name=chartSelector]').val();
if (whichChart == "In Total") {
drawPie('#myChart');
} else {
drawBar('#myChart');
}
});
});
}
function getAuthorAnalyticsPage()... |
//Create event handler seperately
function handleEvent(idVal){
var elementGetter = '#entryID' + idVal;
$(elementGetter).click(function(){
$(".timestamp").remove();
console.log(elementGetter)
var newdestination = 'getTimestamps?authorName=' + data[idVal]._id + "&title=" + data[idVal].user;... | {
var appnedMe = $("<tr class='articleEntry' id= '" + "entryID" + x + "'>" + '<td>' + data[x].user + '</td>' + "<td>" + data[x]._id + "</td>" + '<td>' + data[x].count + '</td>' + '</tr>');
$('#articleList').append(appnedMe);
var temp = '#entryID' + x;
// $(temp).click(function(x){ //Get timestamps
... | conditional_block |
start.go | = "Use system certificate pool." +
" Possible values [true] [false]. Defaults to false if not set." +
" Alternatively, this can be set with the following environment variable: " + tlsSystemCertPoolEnvKey
tlsSystemCertPoolEnvKey = "ADAPTER_REST_TLS_SYSTEMCERTPOOL"
tlsCACertsFlagName = "tls-cacerts"
tlsCACertsF... | return tlsSystemCertPool, tlsCACerts, nil
}
func createFlags(startCmd *cobra.Command) {
startCmd.Flags().StringP(hostURLFlagName, hostURLFlagShorthand, "", hostURLFlagUsage)
startCmd.Flags().StringP(tlsSystemCertPoolFlagName, "", "", tlsSystemCertPoolFlagUsage)
start | {
tlsSystemCertPoolString, err := cmdutils.GetUserSetVarFromString(cmd, tlsSystemCertPoolFlagName,
tlsSystemCertPoolEnvKey, true)
if err != nil {
return false, nil, err
}
tlsSystemCertPool := false
if tlsSystemCertPoolString != "" {
tlsSystemCertPool, err = strconv.ParseBool(tlsSystemCertPoolString)
if er... | identifier_body |
start.go | err != nil {
return nil, err
}
return &didCommParameters{
inboundHostInternal: inboundHostInternal,
inboundHostExternal: inboundHostExternal,
dbPath: dbPath,
}, nil
}
func getTLS(cmd *cobra.Command) (bool, []string, error) {
tlsSystemCertPoolString, err := cmdutils.GetUserSetVarFromString(cm... | {
return nil, fmt.Errorf("aries-framework - failed to get aries context : %w", err)
} | conditional_block | |
start.go | oidcProviderURLFlagName, oidcProviderEnvKey, true)
if err != nil {
return nil, err
}
staticFiles, err := cmdutils.GetUserSetVarFromString(cmd, staticFilesPathFlagName, staticFilesPathEnvKey, true)
if err != nil {
return nil, err
}
mode, err := cmdutils.GetUserSetVarFromString(cmd, modeFlagName, modeEnvKey,... | constructCORSHandler | identifier_name | |
start.go | {}
// ListenAndServe starts the server using the standard Go HTTP server implementation.
func (s *HTTPServer) ListenAndServe(host string, router http.Handler) error {
return http.ListenAndServe(host, router)
}
// GetStartCmd returns the Cobra start command.
func GetStartCmd(srv server) *cobra.Command {
startCmd := ... | router.HandleFunc(handler.Path(), handler.Handle()).Methods(handler.Method()) | random_line_split | |
parse.go | // Definitions in the given headers and definitions
// with the given name will not be added to the returned list of type definitions.
// We'll need to manually create these structures.
func parseGodotHeaders(
packagePath string,
constructorIndex ConstructorIndex,
methodIndex MethodIndex,
excludeHeaders, excludeStr... | (typeLines []string, headerName string) gdnativeapijson.GoTypeDef {
// Create a structure for our type definition.
typeDef := gdnativeapijson.GoTypeDef{
CHeaderFilename: headerName,
Properties: []gdnativeapijson.GoProperty{},
}
// Small function for splitting a line to get the uncommented line and
// get... | parseTypeDef | identifier_name |
parse.go | // Definitions in the given headers and definitions
// with the given name will not be added to the returned list of type definitions.
// We'll need to manually create these structures.
func parseGodotHeaders(
packagePath string,
constructorIndex ConstructorIndex,
methodIndex MethodIndex,
excludeHeaders, excludeStr... |
// Find all of the type definitions in the filename file
// fmt.Println("Parsing File ", path, "...")
foundTypesLines := findTypeDefs(content)
// After extracting the lines, we can now parse the type definition to
// a structure that we can use to build a Go wrapper.
for _, foundTypeLines := range ... | {
panic(err)
} | conditional_block |
parse.go | // Definitions in the given headers and definitions
// with the given name will not be added to the returned list of type definitions.
// We'll need to manually create these structures.
func parseGodotHeaders(
packagePath string,
constructorIndex ConstructorIndex,
methodIndex MethodIndex,
excludeHeaders, excludeStr... | tdMap[typeDef.CName] = typeDef
} else {
index[relPath] = map[string]gdnativeapijson.GoTypeDef{
typeDef.CName: typeDef,
}
}
}
}
}
return nil
})
if err != nil {
panic(err)
}
return index
}
func parseTypeDef(typeLines []string, headerName string) gdnativeapijson.GoTyp... | // Only add the type if it's not in our exclude list.
if !strInSlice(typeDef.CName, excludeStructs) && !strInSlice(typeDef.CHeaderFilename, excludeHeaders) {
if tdMap, ok := index[relPath]; ok { | random_line_split |
parse.go | // Definitions in the given headers and definitions
// with the given name will not be added to the returned list of type definitions.
// We'll need to manually create these structures.
func parseGodotHeaders(
packagePath string,
constructorIndex ConstructorIndex,
methodIndex MethodIndex,
excludeHeaders, excludeStr... | }
// If the type definition is a single line, handle it a little differently
if len(typeLines) == 1 {
// Extract the comment if there is one.
line, comment := getComment(typeLines[0])
// Check to see if the property is a pointer type
if strings.Contains(line, "*") {
line = strings.Replace(line, "*", "",... | {
// Create a structure for our type definition.
typeDef := gdnativeapijson.GoTypeDef{
CHeaderFilename: headerName,
Properties: []gdnativeapijson.GoProperty{},
}
// Small function for splitting a line to get the uncommented line and
// get the comment itself.
getComment := func(line string) (def, commen... | identifier_body |
weapon.rs | ,
WeaponKind::PlasmaRifle => 2
}
}
pub fn new(id: u32) -> Result<Self, String> {
match id {
0 => Ok(WeaponKind::M4),
1 => Ok(WeaponKind::Ak47),
2 => Ok(WeaponKind::PlasmaRifle),
_ => return Err(format!("unknown weapon kind {}", id))
... | iter | identifier_name | |
weapon.rs | Light,
},
base::{BaseBuilder, AsBase},
},
core::{
pool::{
Pool,
PoolIterator,
PoolIteratorMut,
Handle,
},
color::Color,
visitor::{
Visit,
VisitResult,
Visitor,
},
m... | Some(Projectile::new(ProjectileKind::Plasma, resource_manager, scene,
dir, pos, self.self_handle, weapon_velocity))
}
}
} else {
None
}
| {
if self.ammo != 0 && time.elapsed - self.last_shot_time >= 0.1 {
self.ammo -= 1;
self.offset = Vec3::new(0.0, 0.0, -0.05);
self.last_shot_time = time.elapsed;
self.play_shot_sound(resource_manager, sound_context);
let (dir, pos) = {
... | identifier_body |
weapon.rs | : Handle<Node>,
offset: Vec3,
dest_offset: Vec3,
last_shot_time: f64,
shot_position: Vec3,
owner: Handle<Actor>,
ammo: u32,
definition: &'static WeaponDefinition,
}
pub struct WeaponDefinition {
model: &'static str,
shot_sound: &'static str,
ammo: u32,
}
impl HandleFromSelf<Wea... | weapon.update(scene)
}
} | random_line_split | |
weapon.rs | ,
},
base::{BaseBuilder, AsBase},
},
core::{
pool::{
Pool,
PoolIterator,
PoolIteratorMut,
Handle,
},
color::Color,
visitor::{
Visit,
VisitResult,
Visitor,
},
math::... |
WeaponKind::PlasmaRifle => {
Some(Projectile::new(ProjectileKind::Plasma, resource_manager, scene,
dir, pos, self.self_handle, weapon_velocity))
}
}
} else {
None
}
| {
Some(Projectile::new(ProjectileKind::Bullet, resource_manager, scene,
dir, pos, self.self_handle, weapon_velocity))
} | conditional_block |
unet3d.py | ".format(self.name))
# The last convolution
self.lastconv = lm.Convolution3dModule(
3, 1, stride=1, padding=0, activation=None,
bias=False,
name="{}_lconv".format(self.name))
def forward(self, x):
self.instance += 1
x_concat = []
for i i... | environment['LBANN_KEEP_ERROR_SIGNALS'] = 0 | conditional_block | |
unet3d.py | from lbann.core.util import get_parallel_strategy_args
class UNet3D(lm.Module):
"""The 3D U-Net.
See:
\"{O}zg\"{u}n \c{C}i\c{c}ek, Ahmed Abdulkadir, Soeren S. Lienkamp,
Thomas Brox, and Olaf Ronneberger. "3D U-Net: learning dense volumetric
segmentation from sparse annotation." In International c... | import lbann
import lbann.models
import lbann.contrib.args
import lbann.contrib.launcher
import lbann.modules as lm | random_line_split | |
unet3d.py | self.name = (name if name
else "unet3d_module{0}".format(UNet3D.global_count))
# The list of ([down-conv filters], [up-conv filters], deconv filters)
self.BLOCKS = [
([32, 64], [64, 64], 128), # bconv1_down, bconv3_up, deconv3
([64, 128], [128, 128]... |
def forward(self, x):
self.instance += 1
x = self.conv(x)
x = lbann.BatchNormalization(
x,
weights=self.bn_weights,
statistics_group_size=-1,
name="{}_bn_instance{}".format(
self.name,
self.instance))
i... | super().__init__()
self.name = kwargs["name"]
self.activation = None if "activation" not in kwargs.keys() \
else kwargs["activation"]
kwargs["activation"] = None
self.conv = lm.Convolution3dModule(*args, **kwargs)
bn_scale = lbann.Weights(
initializer=lb... | identifier_body |
unet3d.py | self.name = (name if name
else "unet3d_module{0}".format(UNet3D.global_count))
# The list of ([down-conv filters], [up-conv filters], deconv filters)
self.BLOCKS = [
([32, 64], [64, 64], 128), # bconv1_down, bconv3_up, deconv3
([64, 128], [128, 128], 256),... | (learn_rate):
# TODO: This is a temporal optimizer copied from CosomoFlow.
adam = lbann.Adam(
learn_rate=learn_rate,
beta1=0.9,
beta2=0.999,
eps=1e-8)
return adam
if __name__ == '__main__':
desc = ('Construct and run the 3D U-Net on a 3D segmentation dataset.'
... | create_unet3d_optimizer | identifier_name |
package.rs | Package {
fn contains(&self, component: &str, short_name: Option<&str>) -> bool {
self.components.contains(component)
|| if let Some(n) = short_name {
self.components.contains(n)
} else {
false
}
}
fn install<'a>(
&self,
... |
pub fn handle(&mut self, unpacked: tar::Unpacked) {
if let tar::Unpacked::File(f) = unpacked {
self.n_files.fetch_add(1, Ordering::Relaxed);
let n_files = self.n_files.clone();
self.pool.execute(move || {
drop(f);
... | {
// Defaults to hardware thread count threads; this is suitable for
// our needs as IO bound operations tend to show up as write latencies
// rather than close latencies, so we don't need to look at
// more threads to get more IO dispatched at this stage in the process.
... | identifier_body |
package.rs | Package {
fn contains(&self, component: &str, short_name: Option<&str>) -> bool {
self.components.contains(component)
|| if let Some(n) = short_name {
self.components.contains(n)
} else {
false
}
}
fn install<'a>(
&self,
... | <'a> {
n_files: Arc<AtomicUsize>,
pool: threadpool::ThreadPool,
notify_handler: Option<&'a dyn Fn(Notification<'_>)>,
}
impl<'a> Unpacker<'a> {
pub fn new(notify_handler: Option<&'a dyn Fn(Notification<'_>)>) -> Self {
// Defaults to hardware thread count threads; th... | Unpacker | identifier_name |
package.rs | Package {
fn contains(&self, component: &str, short_name: Option<&str>) -> bool {
self.components.contains(component)
|| if let Some(n) = short_name {
self.components.contains(n)
} else {
false
}
}
fn install<'a>(
&self,
... | handler(Notification::DownloadContentLengthReceived(
prev_files as u64,
))
});
if prev_files > 50 {
println!("Closing {} deferred file handles", prev_files);
}
let buf: Vec<u8> = vec![0; prev_files];
... | let mut prev_files = self.n_files.load(Ordering::Relaxed);
self.notify_handler.map(|handler| { | random_line_split |
package.rs | Package {
fn contains(&self, component: &str, short_name: Option<&str>) -> bool {
self.components.contains(component)
|| if let Some(n) = short_name {
self.components.contains(n)
} else {
false
}
}
fn install<'a>(
&self,
... | else {
0o644
});
fs::set_permissions(dest_path, perm)
.chain_err(|| ErrorKind::ComponentFilePermissionsFailed)?;
}
Ok(())
}
#[cfg(windows)]
fn set_file_perms(_dest_path: &Path, _src_path: &Path) -> Result<()> {
Ok(())
}
#[derive(Debug)]
pub struct TarPackage<'a>(D... | {
0o755
} | conditional_block |
app.js | '],
computed: {
isUpgrade : function() {
return this.plan.price > this.active.price;
//this.plan.price
//this.active.price
}
},
methods: {
setActivePlan: function(){
... | {
this.startTime()
} | identifier_body | |
app.js | plan-template',
props:['plan','active'],
computed: {
isUpgrade : function() {
return this.plan.price > this.active.price;
//this.plan.price
//this.active.price
}
},
methods: {
... | ready | identifier_name | |
app.js | }
});
Vue.component('counter',{
template:'#counter-template',
props:['subject'],
data:function() {
return {
count:0
};
}
});
new Vue({
el: '#app3',
data: {
points: 50,
first: 'Xiajun',
last: 'Yan',
fullname: 'Xiajun Yan',
},
computed: {
s... | deleteTask: function(task) {
this.list.$remove(task);
},
clearCompleted: function(){
this.list = this.list.filter(this.isInProgress);
}
}
}
}
});
Vue.component('tasks',{
template: '#... | isInProgress:function(task) {
return !this.isCompleted(task);
},
| random_line_split |
app.js | }
});
Vue.component('counter',{
template:'#counter-template',
props:['subject'],
data:function() {
return {
count:0
};
}
});
new Vue({
el: '#app3',
data: {
points: 50,
first: 'Xiajun',
last: 'Yan',
fullname: 'Xiajun Yan',
},
computed: {
s... |
return 'A';
},
fullname: function() {
return this.first + ' ' + this.last;
},
},
watch:{
first:function(first){
this.fullname = first + ' ' + this.last;
},
last:function(last){
this.fullname = this.first + ' ' + last;
},
... | {
return 'B';
} | conditional_block |
analyzeMessageLogsRev3.py | read_file(filename)
# add quick and dirty fix for new Issue Reports (Aug 2019)
tempRaw = commands[-1]['raw_value']
lastRaw = tempRaw.replace('\nstatus:','')
commands[-1]['raw_value'] = lastRaw
# add more stuff and return as a DataFrame
df = generate_table(commands, radio_on_time)
# set u... | if actionSummary.get('Basal'):
subDict = actionSummary.get('Basal')
numberOfBasal = subDict['countCompleted']
else:
numberOfBasal = 0
if actionSummary.get('StatusCheck'):
subDict = actionSummary.get('StatusCheck')
numberOfStatusRequest... | numberOfBolus = subDict['countCompleted']
else:
numberOfBolus = 0
| random_line_split |
analyzeMessageLogsRev3.py | _file(filename)
# add quick and dirty fix for new Issue Reports (Aug 2019)
tempRaw = commands[-1]['raw_value']
lastRaw = tempRaw.replace('\nstatus:','')
commands[-1]['raw_value'] = lastRaw
# add more stuff and return as a DataFrame
df = generate_table(commands, radio_on_time)
# set up a f... |
# Extract items from actionSummary
if actionSummary.get('TB'):
subDict = actionSummary.get('TB')
numberOfTB = subDict['countCompleted']
numberScheduleBeforeTempBasal = subDict['numSchBasalbeforeTB']
numberTBSepLessThan30sec = subDict['numShortTB']
... | headerString = 'Who, finish State, Finish2, lastMsg Date, podOn (hrs), radioOn (hrs), radioOn (%), ' + \
'#Messages, #Completed, % Completed, #Send, #Recv, ' + \
'#Nonce Resync, #TB, #Bolus, ' \
'#Basal, #Status Check, ' + \
'#Schedule Before TempBasal, #TB Sp... | conditional_block |
analyzeMessageLogsRev3.py | (thisPath, thisFile, outFile):
# Rev3 uses the new checkAction code
# this replaces code used by New (rev2)
# deprecated: getPodSuccessfulActions
# deprecated: basal_analysis code (assumed perfect message order)
# This is time (sec) radio on Pod stays awake once comm is initiated
r... | analyzeMessageLogsRev3 | identifier_name | |
analyzeMessageLogsRev3.py | thisPerson, thisFinish, thisAntenna = parse_info_from_filename(thisFile)
thisFinish2 = 'Success' # default is 'Success'
if thisFinish == 'WIP':
thisFinish2 = 'WIP' # pod is still running
lastDate = last_command.date()
# Process df to generate the podState associated with every message
... | radio_on_time = 30
filename = thisPath + '/' + thisFile
# read the MessageLogs from the file
commands, podDict = read_file(filename)
# add quick and dirty fix for new Issue Reports (Aug 2019)
tempRaw = commands[-1]['raw_value']
lastRaw = tempRaw.replace('\nstatus:','')
commands[-1]['raw... | identifier_body | |
cockpit.js | .Pages = new Meteor.Pagination("Project",{
// perPage: 2,
// itemTemplate: "cockpit_table",
// //templateName: 'Project',
// //itemTemplate: 'cockpit'
// //sort: {
// // title: 1
// //},
// //filters: {
// // count: {
// // $gt: 10
// // }
// //},
// //availableSet... | (!val) {
shObj.show();
} else {
shObj.hide();
}
}
//this | identifier_body | |
cockpit.js | var totle = Project.find().count();
console.log(totle);
$('.M-box1').pagination({
totalData:totle,
showData:limit,
coping:true,
callback:function(api){
console.log(api.getCurrent());
pagenum=api.getCurrent();
... | // return bendiCT;
//},
//单条项目集合
editorTable: function () {
var _data = Template.instance().editorData.get();
return _data;
},
//周报是否勾选
isweekly: function (a) {
var pro=Project.find({_id:a}).fetch();
if(pro[0]){
if(pro[0].weekly==0)
... | // } | random_line_split |
cockpit.js | totle = Project.find().count();
console.log(totle);
$('.M-box1').pagination({
totalData:totle,
showData:limit,
coping:true,
callback:function(api){
console.log(api.getCurrent());
pagenum=api.getCurrent();
co... | an').hide();
});
//function base64_decode(base64str, file) {
// // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
// var bitmap = new Buffer(base64str, 'base64');
// // write buffer to file
... | }
$('#mengban').show();
Meteor.call('accPro', pro_id, state, function (error, res) {
$('#mengb | conditional_block |
cockpit.js | Obj) {
if (!val) {
shObj.show();
} else {
shObj.hide();
}
}
//this.Pages = new Meteor.Pagination("Project",{
// perPage: 2,
// itemTemplate: "cockpit_table",
// //templateName: 'Project',
// //itemTemplate: 'cockpit'
// //sort: {
// // title: 1
// //},
// //filter... | al, sh | identifier_name | |
config.rs | ::path::{Path, PathBuf};
use crate::om::glob::glob;
use std::process::exit;
use super::target;
const PUBLISHER_OPTIONS: &[&str] = &["system", "package_app", "upload_app"];
const BYPASS_APP_CONFIG_ENV_VAR: &str = "origen_app_bypass_config_lookup";
const APP_CONFIG_PATHS: &str = "origen_app_config_paths";
macro_rules! ... |
pub fn cmd_paths(&self) -> Vec<PathBuf> {
let mut retn = vec!();
if let Some(cmds) = self.commands.as_ref() {
// Load in only the commands explicitly given
for cmds_toml in cmds {
let ct = self.root.as_ref().unwrap().join("config").join(cmds_toml);
... | {
let mut unknowns: Vec<String> = vec![];
if let Some(p) = &self.publisher {
for (opt, _) in p.iter() {
if !PUBLISHER_OPTIONS.contains(&opt.as_str()) {
unknowns.push(opt.clone());
}
}
}
unknowns
} | identifier_body |
config.rs | ::path::{Path, PathBuf};
use crate::om::glob::glob;
use std::process::exit;
use super::target;
const PUBLISHER_OPTIONS: &[&str] = &["system", "package_app", "upload_app"];
const BYPASS_APP_CONFIG_ENV_VAR: &str = "origen_app_bypass_config_lookup";
const APP_CONFIG_PATHS: &str = "origen_app_config_paths";
macro_rules! ... | {
pub target: Option<Vec<String>>
}
impl CurrentState {
pub fn build(root: &PathBuf) -> Self {
let file = root.join(".origen").join("application.toml");
let mut s = config::Config::builder().set_default("target", None::<Vec<String>>).unwrap();
if file.exists() {
s = s.add_s... | CurrentState | identifier_name |
config.rs | ::path::{Path, PathBuf};
use crate::om::glob::glob;
use std::process::exit;
use super::target;
const PUBLISHER_OPTIONS: &[&str] = &["system", "package_app", "upload_app"];
const BYPASS_APP_CONFIG_ENV_VAR: &str = "origen_app_bypass_config_lookup";
const APP_CONFIG_PATHS: &str = "origen_app_config_paths";
macro_rules! ... |
}
}
if use_app_config!() {
let file = root.join("config").join("application.toml");
if file.exists() {
files.push(file);
}
} else {
// Bypass Origen's default configuration lookup - use only the enumerated conf... | {
log_error!(
"Config path {} either does not exists or is not accessible",
path.display()
);
exit(1);
} | conditional_block |
config.rs | ::path::{Path, PathBuf};
use crate::om::glob::glob;
use std::process::exit;
use super::target;
const PUBLISHER_OPTIONS: &[&str] = &["system", "package_app", "upload_app"];
const BYPASS_APP_CONFIG_ENV_VAR: &str = "origen_app_bypass_config_lookup";
const APP_CONFIG_PATHS: &str = "origen_app_config_paths";
macro_rules! ... | let mut slf = Self::build(config.root.as_ref().unwrap());
slf.apply_to(config);
}
}
}
#[derive(Debug, Deserialize)]
// If you add an attribute to this you must also update:
// * pyapi/src/lib.rs to convert it to Python
// * default function below to define the default value
// * add... | }
}
pub fn build_and_apply(config: &mut Config) {
if use_app_config!() { | random_line_split |
client_handler.go | , backend *LightEthereum) *clientHandler {
handler := &clientHandler{
checkpoint: checkpoint,
backend: backend,
closeCh: make(chan struct{}),
}
if ulcServers != nil {
ulc, err := newULC(ulcServers, ulcFraction)
if err != nil {
log.Error("Failed to initialize ultra light client")
}
handler.ulc ... | }
p.fcServer.ReceivedReply(resp.ReqID, resp.BV)
deliverMsg = &Msg{
MsgType: MsgReceipts,
ReqID: resp.ReqID,
Obj: resp.Receipts,
}
case ProofsV2Msg:
p.Log().Trace("Received les/2 proofs response")
var resp struct {
ReqID, BV uint64
Data light.NodeList
}
if err := msg.Decode(&re... | }
if err := msg.Decode(&resp); err != nil {
return errResp(ErrDecode, "msg %v: %v", msg, err) | random_line_split |
client_handler.go | backend *LightEthereum) *clientHandler {
handler := &clientHandler{
checkpoint: checkpoint,
backend: backend,
closeCh: make(chan struct{}),
}
if ulcServers != nil {
ulc, err := newULC(ulcServers, ulcFraction)
if err != nil {
log.Error("Failed to initialize ultra light client")
}
handler.ulc =... |
// runPeer is the p2p protocol run function for the given version.
func (h *clientHandler) runPeer(version uint, p *p2p.Peer, rw p2p.MsgReadWriter) error {
trusted := false
if h.ulc != nil {
trusted = h.ulc.trusted(p.ID())
}
peer := newPeer(int(version), h.backend.config.NetworkId, trusted, p, newMeteredMsgWrit... | {
close(h.closeCh)
h.downloader.Terminate()
h.fetcher.close()
h.wg.Wait()
} | identifier_body |
client_handler.go | ers && !p.Peer.Info().Network.Trusted {
return p2p.DiscTooManyPeers
}
p.Log().Debug("Light Ethereum peer connected", "name", p.Name())
// Execute the LES handshake
var (
head = h.backend.blockchain.CurrentHeader()
hash = head.Hash()
number = head.Number.Uint64()
td = h.backend.blockchain.GetTd(ha... | RequestHeadersByHash | identifier_name | |
client_handler.go | backend *LightEthereum) *clientHandler {
handler := &clientHandler{
checkpoint: checkpoint,
backend: backend,
closeCh: make(chan struct{}),
}
if ulcServers != nil {
ulc, err := newULC(ulcServers, ulcFraction)
if err != nil |
handler.ulc = ulc
log.Info("Enable ultra light client mode")
}
var height uint64
if checkpoint != nil {
height = (checkpoint.SectionIndex+1)*params.CHTFrequency - 1
}
handler.fetcher = newLightFetcher(handler)
handler.downloader = downloader.New(height, backend.chainDb, nil, backend.eventMux, nil, backend.... | {
log.Error("Failed to initialize ultra light client")
} | conditional_block |
files_test.go | No != expected.Pages[1].PageNo {
t.Errorf("Page two PageNo got %v wanted %v", rmf.Pages[1].PageNo, expected.Pages[1].PageNo)
}
if rmf.Pages[1].Identifier != expected.Pages[1].Identifier {
t.Errorf("Page two Identifier got %v wanted %v", rmf.Pages[1].Identifier, expected.Pages[1].Identifier)
}
if rmf.Pages[1].rm... | expected := RMFileInfo{
RmFS: &RmFS{
pdfPath: "fbe9f971-03ba-4c21-a0e8-78dd921f9c4c.pdf",
identifier: "fbe9f971-03ba-4c21-a0e8-78dd921f9c4c",
},
Version: 0,
VisibleName: "insert-pages",
LastModified: ptime("2022-09-09 14:13:39 +0100 BST"),
Orientation: "portrait",
Orig... | random_line_split | |
files_test.go | (t *testing.T) {
template := ""
rmf, err := RMFiler("../testfiles/cc8313bb-5fab-4ab5-af39-46e6d4160df3.pdf", template)
if err != nil {
t.Fatalf("Could not open file %v", err)
}
expected := RMFileInfo{
RmFS: &RmFS{
pdfPath: "cc8313bb-5fab-4ab5-af39-46e6d4160df3.pdf",
identifier: "cc8313bb-5fab-4ab5-a... | TestFilesXochitlWithPDF | identifier_name | |
files_test.go | != expected.Pages[1].PageNo {
t.Errorf("Page two PageNo got %v wanted %v", rmf.Pages[1].PageNo, expected.Pages[1].PageNo)
}
if rmf.Pages[1].Identifier != expected.Pages[1].Identifier {
t.Errorf("Page two Identifier got %v wanted %v", rmf.Pages[1].Identifier, expected.Pages[1].Identifier)
}
if rmf.Pages[1].rmPa... |
// https://stackoverflow.com/a/29339052
redirStdOut := func(log string) string {
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// debug!
rmf.Debug(log)
w.Close()
s, _ := ioutil.ReadAll(r)
r.Close()
os.Stdout = oldStdout
return string(s)
}
rmf.Debugging = false
s := redirStdOut("h... | {
t.Error("Page two second layer names not the same")
} | conditional_block |
files_test.go | y.OriginalPageCount ||
x.PageCount != y.PageCount {
t.Error("version, visiblename, orientation, originalpagecount or pagecount differ")
return false
}
if len(x.RedirectionPageMap) != len(y.RedirectionPageMap) {
t.Errorf("redirection length %d != %d", len(x.RedirectionPageMap), len(y.RedirectionPageMap)... | {
template := ""
rmf, err := RMFiler("../testfiles/version3.zip", template)
expected := "software version 3 not supported -- no rm metadata file found"
if !strings.Contains(err.Error(), expected) {
t.Errorf("v3 file should error with %s, not %v", expected, err)
}
pages := 0
for i := 0; i < rmf.PageCount; i+... | identifier_body | |
pars.py | :972,
'Урал' :52,
'Челябинская область' :11225,
'Челябинск' :56,
'Магнитогорск' :235,
'Снежинск' :11218,
'Курганская область' :11158,
'Курган' :53,
'Свердловская область' :11162,
'Екатеринбург' :54,
'Каменск-Уральский' :11164,
'Нижний Тагил' :11168,
'Новоуральск' :11170,
'Первоуральск' :11171,
'Тюменская... | k = openp | identifier_name | |
pars.py | 2,
'Урал' :52,
'Челябинская область' :11225,
'Челябинск' :56,
'Магнитогорск' :235,
'Снежинск' :11218,
'Курганская область' :11158,
'Курган' :53,
'Свердловская область' :11162,
'Екатеринбург' :54,
'Каменск-Уральский' :11164,
'Нижний Тагил' :11168,
'Новоуральск' :11170,
'Первоуральск' :11171,
'Тюменская обл... |
# создаю новую книгу
workbook = openpyxl.Workbook() | random_line_split | |
pars.py | рал' :52,
'Челябинская область' :11225,
'Челябинск' :56,
'Магнитогорск' :235,
'Снежинск' :11218,
'Курганская область' :11158,
'Курган' :53,
'Свердловская область' :11162,
'Екатеринбург' :54,
'Каменск-Уральский' :11164,
'Нижний Тагил' :11168,
'Новоуральск' :11170,
'Первоуральск' :11171,
'Тюменская область' ... | ok()
title_she | identifier_body | |
pars.py | 74,
'Уссурийск' :11426,
'Чукотский автономный округ' :10251,
'Анадырь' :11458,
'Камчатский край' :11398,
'Петропавловск-Камчатский' :78,
'Магаданская область' :11403,
'Магадан' :79,
'Сахалинская область' :11450,
'Южно-Сахалинск' :80,
'Хабаровский край' :11457,
'Хабаровск' :76,
'Комсомольск-на-Амуре' :11453
... | 1)
c6 = Checkbutton(frame_3, text="h3", varia | conditional_block | |
openai.py | : Any) -> Any:
new(args[0]) # args[0] is self
return old(*args, **kwargs)
return repl
def _async_wrap(old: Any, new: Any):
async def repl(*args, **kwargs):
new(args[0]) # args[0] is self
return await old(*args, **kwargs)
return repl
def _set_credentials(self):
opena... |
if model_name in openai_models["chat_completion"]:
available_deployments["chat_completion"][deployment.id] = deployment
elif model_name in openai_models["completion"]:
available_deployments["completion"][deployment.id] = deployment
... | model_name = model_aliases[model_name] | conditional_block |
openai.py | _API_KEY")
openai.api_base = os.environ.get("LLM_AZURE_OPENAI_API_BASE")
# os.environ.get("LLM_AZURE_OPENAI_API_VERSION")
openai.api_version = "2023-03-15-preview"
def _use_openai_credentials():
openai.api_type = "open_ai"
openai.api_key = os.environ.get("LLM_OPENAI_API_KEY")
openai.api_base =... | """Get the model from the configuration.
Returns: | random_line_split | |
openai.py | _key
api_type = "open_ai"
api_base = "https://api.openai.com/v1"
api_version = None
if hasattr(self, "openai_api_type"):
api_type = self.openai_api_type
if api_type == "azure":
if hasattr(self, "openai_api_base"):
api_base = self.openai_api_base
if hasattr(self,... | """OpenAI LLM configuration."""
model_name: OpenAIModel = Field(default=default_openai_model, # type: ignore
description="The name of the model to use.")
max_tokens: PositiveInt = Field(1024, description="""\
The maximum number of [tokens](https://platform.openai.com/tokeni... | identifier_body | |
openai.py | : Any) -> Any:
new(args[0]) # args[0] is self
return old(*args, **kwargs)
return repl
def | (old: Any, new: Any):
async def repl(*args, **kwargs):
new(args[0]) # args[0] is self
return await old(*args, **kwargs)
return repl
def _set_credentials(self):
openai.api_key = self.openai_api_key
api_type = "open_ai"
api_base = "https://api.openai.com/v1"
api_version = None
... | _async_wrap | identifier_name |
devicecash_trend.js | (){
fill = d3.scale.category20b();
w = $("#cloudchart").width();
h = $("#cloudchart").height();
words = [],max,scale = 1,complete = 0,
keyword = "",
tags,
fontSize,
maxLength = 30,
fetcher,
statusText ="";
layout = d3.layout.cloud()
.timeInte... | name==OldData[i].group){
rowdata=OldData[i].items;
break;
}
}
return rowdata;
}
function DeviceChange(_deviceName){
var _deviceitems=getdeviceinfo(_deviceName);
KPICompare(_deviceitems[0]);
DrawLineChart(_deviceitems);
}
//装置环比信息KPI
function KPICompare(_deviceinfo){
... | if(_device | identifier_name |
devicecash_trend.js | .abs(bounds[1].x - w / 2),
w / Math.abs(bounds[0].x - w / 2),
h / Math.abs(bounds[1].y - h / 2),
h / Math.abs(bounds[0].y - h / 2)) / 2 : 1;
words = data;
var text = vis.selectAll("text")
.data(words, function(d) { return d.text.toLowerCase(); });
text.transition()
.... | },
credits:{enabled:false},
xAxis:{
labels:{ | random_line_split | |
devicecash_trend.js | fill = d3.scale.category20b();
w = $("#cloudchart").width();
h = $("#cloudchart").height();
words = [],max,scale = 1,complete = 0,
keyword = "",
tags,
fontSize,
maxLength = 30,
fetcher,
statusText ="";
layout = d3.layout.cloud()
.timeInterval... | =0;i<OldData.length;i++){
if(_devicename==OldData[i].group){
rowdata=OldData[i].items;
break;
}
}
return rowdata;
}
function DeviceChange(_deviceName){
var _deviceitems=getdeviceinfo(_deviceName);
KPICompare(_deviceitems[0]);
DrawLineChart(_deviceitems);
}
//装... | me==OldData[i].group){
for(var j=0;j<OldData[i].items.length;j++){
tempvalue+=OldData[i].items[j][_cashcol];
}
break;
}
}
return tempvalue;
}
//获取装置信息
function getdeviceinfo(_devicename){
var rowdata=null;
for(var i | identifier_body |
devicecash_trend.js | fill = d3.scale.category20b();
w = $("#cloudchart").width();
h = $("#cloudchart").height();
words = [],max,scale = 1,complete = 0,
keyword = "",
tags,
fontSize,
maxLength = 30,
fetcher,
statusText ="";
layout = d3.layout.cloud()
.timeInterval... | ar rowdata=null;
for(var i=0;i<OldData.length;i++){
if(_devicename==OldData[i].group){
rowdata=OldData[i].items;
break;
}
}
return rowdata;
}
function DeviceChange(_deviceName){
var _deviceitems=getdeviceinfo(_deviceName);
KPICompare(_deviceitems[0]);
Draw... | e+=OldData[i].items[j][_cashcol];
}
break;
}
}
return tempvalue;
}
//获取装置信息
function getdeviceinfo(_devicename){
v | conditional_block |
train_models.go | CHRM2", "EDNRA", "MAOA", "LCK",
"PTGS2", "SLC6A2", "ACHE", "CNR2", "CNR1", "ADORA2A", "OPRD1", "NR3C1", "AR", "SLC6A4",
"OPRM1", "HTR1A", "SLC6A3", "OPRK1", "AVPR1A", "ADRB2", "DRD2", "KCNH2", "DRD1", "HTR2A",
"CHRM1",
},
"smallest1": []string{
"PDE3A",
},
"smallest3": []string{
"PDE3A", "SCN5A",... | // Show startup messages
// --------------------------------
sp.Info.Printf("Using max %d OS threads to schedule max %d tasks\n", *threads, *maxTasks)
sp.Info.Printf("Starting workflow for %s geneset\n", *geneSet)
// --------------------------------
// Initialize processes and add to runner
// -----------------... | {
// --------------------------------
// Parse flags and stuff
// --------------------------------
flag.Parse()
if *debug {
sp.InitLogDebug()
} else {
sp.InitLogAudit()
}
if len(geneSets[*geneSet]) == 0 {
names := []string{}
for n, _ := range geneSets {
names = append(names, n)
}
sp.Error.Fatalf(... | identifier_body |
train_models.go | CHRM2", "EDNRA", "MAOA", "LCK",
"PTGS2", "SLC6A2", "ACHE", "CNR2", "CNR1", "ADORA2A", "OPRD1", "NR3C1", "AR", "SLC6A4",
"OPRM1", "HTR1A", "SLC6A3", "OPRK1", "AVPR1A", "ADRB2", "DRD2", "KCNH2", "DRD1", "HTR2A",
"CHRM1",
},
"smallest1": []string{
"PDE3A",
},
"smallest3": []string{
"PDE3A", "SCN5A",... | "0.001",
}
replicates = []string{
"r1", "r2", "r3",
}
)
func main() {
// --------------------------------
// Parse flags and stuff
// --------------------------------
flag.Parse()
if *debug {
sp.InitLogDebug()
} else {
sp.InitLogAudit()
}
if len(geneSets[*geneSet]) == 0 {
names := []string{}
for... | gammaVals = []string{
"0.1",
"0.01", | random_line_split |
train_models.go | CHRM2", "EDNRA", "MAOA", "LCK",
"PTGS2", "SLC6A2", "ACHE", "CNR2", "CNR1", "ADORA2A", "OPRD1", "NR3C1", "AR", "SLC6A4",
"OPRM1", "HTR1A", "SLC6A3", "OPRK1", "AVPR1A", "ADRB2", "DRD2", "KCNH2", "DRD1", "HTR2A",
"CHRM1",
},
"smallest1": []string{
"PDE3A",
},
"smallest3": []string{
"PDE3A", "SCN5A",... | () {
// --------------------------------
// Parse flags and stuff
// --------------------------------
flag.Parse()
if *debug {
sp.InitLogDebug()
} else {
sp.InitLogAudit()
}
if len(geneSets[*geneSet]) == 0 {
names := []string{}
for n, _ := range geneSets {
names = append(names, n)
}
sp.Error.Fata... | main | identifier_name |
train_models.go | CHRM2", "EDNRA", "MAOA", "LCK",
"PTGS2", "SLC6A2", "ACHE", "CNR2", "CNR1", "ADORA2A", "OPRD1", "NR3C1", "AR", "SLC6A4",
"OPRM1", "HTR1A", "SLC6A3", "OPRK1", "AVPR1A", "ADRB2", "DRD2", "KCNH2", "DRD1", "HTR2A",
"CHRM1",
},
"smallest1": []string{
"PDE3A",
},
"smallest3": []string{
"PDE3A", "SCN5A",... |
sp.Error.Fatalf("Incorrect gene set %s specified! Only allowed values are: %s\n", *geneSet, str.Join(names, ", "))
}
runtime.GOMAXPROCS(*threads)
// --------------------------------
// Show startup messages
// --------------------------------
sp.Info.Printf("Using max %d OS threads to schedule max %d tasks\n"... | {
names = append(names, n)
} | conditional_block |
beacon_chain_builder.rs | ,
};
enum BuildStrategy<T: BeaconChainTypes> {
FromGenesis {
genesis_state: Box<BeaconState<T::EthSpec>>,
genesis_block: Box<BeaconBlock<T::EthSpec>>,
},
LoadFromStore,
}
pub struct BeaconChainBuilder<T: BeaconChainTypes> {
build_strategy: BuildStrategy<T>,
spec: ChainSpec,
log... |
let (_, mut proof) = tree.generate_proof(i, depth);
proof.push(Hash256::from_slice(&int_to_bytes32(i + 1)));
assert_eq!(
proof.len(),
depth + 1,
"Deposit proof should be correct len"
);
proofs.push(proof);
}
let deposits = datas
... | {
return Err(String::from("Failed to push leaf"));
} | conditional_block |
beacon_chain_builder.rs | _genesis_state(genesis_state, spec, log))
}
pub fn yaml_state(file: &PathBuf, spec: ChainSpec, log: Logger) -> Result<Self, String> {
let file = File::open(file.clone())
.map_err(|e| format!("Unable to open YAML genesis state file {:?}: {:?}", file, e))?;
let genesis_state = serde_... | "validator balances should be max effective balance"
);
}
for v in &state.validators { | random_line_split | |
beacon_chain_builder.rs | ,
};
enum BuildStrategy<T: BeaconChainTypes> {
FromGenesis {
genesis_state: Box<BeaconState<T::EthSpec>>,
genesis_block: Box<BeaconBlock<T::EthSpec>>,
},
LoadFromStore,
}
pub struct BeaconChainBuilder<T: BeaconChainTypes> {
build_strategy: BuildStrategy<T>,
spec: ChainSpec,
log... | (file: &PathBuf, spec: ChainSpec, log: Logger) -> Result<Self, String> {
let mut file = File::open(file.clone())
.map_err(|e| format!("Unable to open SSZ genesis state file {:?}: {:?}", file, e))?;
let mut bytes = vec![];
file.read_to_end(&mut bytes)
.map_err(|e| format!... | ssz_state | identifier_name |
beacon_chain_builder.rs | ,
};
enum BuildStrategy<T: BeaconChainTypes> {
FromGenesis {
genesis_state: Box<BeaconState<T::EthSpec>>,
genesis_block: Box<BeaconBlock<T::EthSpec>>,
},
LoadFromStore,
}
pub struct BeaconChainBuilder<T: BeaconChainTypes> {
build_strategy: BuildStrategy<T>,
spec: ChainSpec,
log... |
pub fn http_bootstrap(server: &str, spec: ChainSpec, log: Logger) -> Result<Self, String> {
let bootstrapper = Bootstrapper::connect(server.to_string(), &log)
.map_err(|e| format!("Failed to initialize bootstrap client: {}", e))?;
let (genesis_state, genesis_block) = bootstrapper
... | {
let file = File::open(file.clone())
.map_err(|e| format!("Unable to open JSON genesis state file {:?}: {:?}", file, e))?;
let genesis_state = serde_json::from_reader(file)
.map_err(|e| format!("Unable to parse JSON genesis state file: {:?}", e))?;
Ok(Self::from_genesi... | identifier_body |
networking.rs | {
pub graph: u64, // graph identifier
pub channel: u64, // index of channel
pub source: u64, // index of worker sending message
pub target: u64, // index of worker receiving message
pub length: u64, // number of bytes in message
}
impl MessageHeader {
// returns a... | MessageHeader | identifier_name | |
networking.rs | // rewind the reader
*bytes = original;
None
}
}
else { None }
}
fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
try!(writer.write_u64::<LittleEndian>(self.graph));
try!(writer.write_u64::<LittleEndian>(sel... | // we'll need more space / to read more at once. let's double the buffer!
if self.length >= self.buffer.len() / 2 {
self.buffer.extend(::std::iter::repeat(0u8).take(self.length));
}
// attempt to read some more bytes into our buffer
let read =... | random_line_split | |
networking.rs |
let read = self.reader.read(&mut self.buffer[self.length..]).unwrap_or(0);
self.length += read;
let remaining = {
let mut slice = &self.buffer[..self.length];
while let Some(header) = MessageHeader::try_read(&mut slice) {
let h_le... | {
let mut results: Vec<_> = (0..(addresses.len() - my_index as usize - 1)).map(|_| None).collect();
let listener = try!(TcpListener::bind(&addresses[my_index as usize][..]));
for _ in (my_index as usize + 1 .. addresses.len()) {
let mut stream = try!(listener.accept()).0;
let identifier = t... | identifier_body | |
traits.rs | Color::On as Black, prelude::*, primitives::{Line, PrimitiveStyle},
///};
///use epd_waveshare::{epd4in2::*, prelude::*};
///#
///# let expectations = [];
///# let mut spi = spi::Mock::new(&expectations);
///# let expectations = [];
///# let cs_pin = pin::Mock::new(&expectations);
///# let busy_in = pin::Mock::new(&exp... |
/// Displays the new frame
fn display_new_frame(&mut self, spi: &mut SPI, _delay: &mut DELAY) -> Result<(), SPI::Error>;
| random_line_split | |
traits.rs | {
/// The "normal" full Lookuptable for the Refresh-Sequence
#[default]
Full,
/// The quick LUT where not the full refresh sequence is followed.
/// This might lead to some
Quick,
}
pub(crate) trait InternalWiAdditions<SPI, CS, BUSY, DC, RST, DELAY>
where
SPI: Write<u8>,
CS: OutputPin,... | RefreshLut | identifier_name | |
base.go | err != nil {
c.TraceServerError(errors.Annotatef(err, "failed to begin database transaction"))
}
c.model = model
c.orm = model.Orm()
c.pagingResult = models.NewQueryParams()
}
// Finish ends transaction
func (c *SeaterController) Finish() {
defer c.execDeferrers()
err := c.endTransaction()
if err != nil {
... | (err error) {
c.traceJSONAbort(err, 500)
}
// Forbiddenf returns forbidden response with formatted message
func (c *SeaterController) Forbiddenf(format string, args ...interface{}) {
c.TraceForbiddenf(nil, format, args...)
}
// TraceForbiddenf traces error and returns forbidden response with formatted message
func ... | TraceServerError | identifier_name |
base.go | != nil {
c.TraceServerError(errors.Annotatef(err, "failed to begin database transaction"))
}
c.model = model
c.orm = model.Orm()
c.pagingResult = models.NewQueryParams()
}
// Finish ends transaction
func (c *SeaterController) Finish() {
defer c.execDeferrers()
err := c.endTransaction()
if err != nil {
c.T... |
// Accepted response an asynchronous resource
func (c *SeaterController) Accepted(data interface{}) {
c.Code(202)
c.jsonResp(data)
}
// Created response an asynchronous resource
func (c *SeaterController) Created(data interface{}) {
c.Code(201)
c.jsonResp(data)
}
// NoContent responses with code 204
func (c *Se... | {
c.Code(200)
c.jsonResp(data)
} | identifier_body |
base.go | err != nil {
c.TraceServerError(errors.Annotatef(err, "failed to begin database transaction"))
}
c.model = model
c.orm = model.Orm()
c.pagingResult = models.NewQueryParams()
}
// Finish ends transaction
func (c *SeaterController) Finish() {
defer c.execDeferrers()
err := c.endTransaction()
if err != nil {
... | s += fmt.Sprintf("%s\n", err)
e = err
}
c.BadRequestf("%s", e)
}
}
func (c *SeaterController) getInt64(key string, defs ...int64) (v int64, ok bool) {
if strv := c.Ctx.Input.Query(key); strv != "" {
val, err := strconv.ParseInt(strv, 10, 64)
if err != nil {
c.BadRequestf("invalid int64 argument %s: ... | s := "invalid parameters:\n"
var e interface{}
for _, err := range result.Errors() { | random_line_split |
base.go | Transaction()
if err != nil {
code = 500
msg = "Server Error"
}
body, err := json.Marshal(msgBody{Msg: msg})
if err != nil {
c.CustomAbort(500, `{"msg": "Unknown Error"}`)
}
c.CustomAbort(code, string(body))
}
// BadRequestf returns bad request response with formatted message
func (c *SeaterController) Ba... | {
c.BadRequestf("invalid id")
} | conditional_block | |
app.js | �数判断
let tms_a = parseInt(ALM_AFTER / INTV_MIN);
let tms_b = parseInt(ALM_BETWEEN / INTV_MIN) || 2;
let real_tms = sensor.exc_count-1; // 因为上面 ALM_AFTER 是累积, 所以 exc_count-1 再判断
if(real_tms < tms_a) {
return false;
}
else {
real_tms -= tms_a;
return (real_tms%tms_b == 0)? t... | }
fs.writeFileSync(BLOCK_FILE, JSON.stringify(blocks)); | random_line_split | |
app.js | {
if( timer) {
clearInterval(timer); timer = 0;
res? res.send('Timer stop.'): null;
}
else {
res? res.send('No timer.'): null;
}
}
/**
* 自动启动首次(分钟需5的倍数)
*/
function autoStart(enable) {
if(enable) {
let m1 = new Date().getMinutes();
let m2 = Math.ceil(m1/5)*5;
let df = (m2-m1)*1000*... | {
return false;
}
else {
real_tms -= tms_a;
return (real_tms%tms_b == 0)? true: false;
}
}
/*
if( check.exceed === 0 || check.level < ALARM_LEVEL) {
check.is_reset = (sensor.exc_count > 0);
setDuration(check, sensor.exc_count);
sensor.exc_count = 0;
//... | 再判断
if(real_tms < tms_a) | conditional_block |
app.js | ': '');
}
}
/**
* 发送报警
*/
function sendAlarm(sensor, check, users, blocks) {
let firstline = makeFirstline(sensor, check);
let curtime = new Date().formatTime('yyyy-MM-dd hh:mm');
let level = check.level;
let level_name = level==0? '通知': (level==1? '预警': '报警');
let level_color = level==0? '#16A765': (lev... | 数错误!');
}
let until = new Date().addHours(after);
let blocks = JSON.parse(fs.readFileSync(BLOCK_F | identifier_body | |
app.js | Start(MIN_SECS == 60);
/**
* 传感器检查流程
*/
function checkSensors() {
console.log('------ CheckSensors start '+ new Date().toLocaleString()+ '-------');
// 找出在线传感器
let onlines = sensors.filter(function(s) {
return !s.offline;
});
// 批量查询传感器
sensorBatchValues(onlines, function(err, sensors) {
if(e... | arm(sensor, | identifier_name | |
spamScore.js | = new MessageEmbed()
.setTitle(`Flagged message`)
.setDescription(`${this.cleanContent}`)
.setAuthor(this.author.tag, this.author.displayAvatarURL())
.setFooter(`Message channel **${this.channel.name}**`)
... | earnedSpamScore | identifier_name | |
spamScore.js | pliers
var afterFunction = () => {
// Start with a spam score multiplier of 0.5
// spam score 50% if less strict channel AND less strict role
// Spam score 100% if less strict channel OR less strict role
// Spam score 150% if neither less stric... | else if (/(.)\1\1\1\1\1\1\1\1\1\1/.test(this.cleanContent.toLowerCase())) {
score += 10;
scoreReasons[ "Repeating Characters" ] = 10
// 5 or more consecutive repeating characters = a little bit spammy. Add 5 score.
} else if (/(.)\1\1\1\1\1/.t... | {
score += 20;
scoreReasons[ "Repeating Characters" ] = 20
// 10 or more consecutive repeating characters = spammy. Add 10 score.
} | conditional_block |
spamScore.js | to the multiplier.
if (typeof this.member !== 'undefined') {
var lessStrict = false;
this.member.roles
.filter((role) => {
return this.guild.settings.antispamLessStrictRoles.indexOf(role.id) !== -1;
... | var patternScore = (this.cleanContent.length > 0 ? (newstring.length / this.cleanContent.length) : 1);
// Pattern score of 100% means no repeating patterns. For every 4% less than 100%, add 1 score. Multiply depending on content length.
score += parseInt(((1 - patternSco... | random_line_split | |
spamScore.js | .setFooter(`Message channel **${this.channel.name}**`)
.addField(`Total Spam Score`, `Base: ${score}; multiplier: ${multiplier}; total: ${score * multiplier}`)
.setColor(`#ff7878`);
for (var key in scoreReasons) ... | {
this._earnedSpamScore = value;
} | identifier_body | |
artifacts.py | -axis,
[0, 0, 0, CAMERA_FOCAL_LENGTH], # so that y-axis looks up
[0, 0, 1/0.42, 0]])
self.detectors = [
{
'artefact_name': 'cubesat',
'detector_type': 'classifier',
'classifier': cv2.C... |
def waitForImage(self):
self.left_image = self.right_image = None
while self.left_image is None or self.right_image is None:
self.time, channel, data = self.listen()
if channel == "left_image":
self.left_image = data
elif channel == "right_image"... | output = StringIO()
print(*args, file=output, **kwargs)
contents = output.getvalue().strip()
output.close()
# self.publish('stdout', contents)
print(contents) | identifier_body |
artifacts.py | -axis,
[0, 0, 0, CAMERA_FOCAL_LENGTH], # so that y-axis looks up
[0, 0, 1/0.42, 0]])
self.detectors = [
{
'artefact_name': 'cubesat',
'detector_type': 'classifier',
'classifier': cv2.C... | (self, *args, **kwargs):
# maybe refactor to Node?
output = StringIO()
print(*args, file=output, **kwargs)
contents = output.getvalue().strip()
output.close()
# self.publish('stdout', contents)
print(contents)
def waitForImage(self):
self.left_image = ... | stdout | identifier_name |
artifacts.py | x-axis,
[0, 0, 0, CAMERA_FOCAL_LENGTH], # so that y-axis looks up
[0, 0, 1/0.42, 0]])
self.detectors = [
{
'artefact_name': 'cubesat',
'detector_type': 'classifier',
'classifier': cv2... | return self.time
def run(self):
try:
dropped = 0
while True:
now = self.publish("dropped", dropped)
dropped = -1
timestamp = now
while timestamp <= now:
# this thread is always running but wa... | self.right_image = data | random_line_split |
artifacts.py | :
pass
def detect_and_publish(self, left_image, right_image):
results = self.detect(left_image, right_image)
for r in results:
self.publish('artf', r)
def detect(self, left_image, right_image):
results = []
limg = cv2.imdecode(np.frombuffer(left_image, ... | from unittest.mock import MagicMock
from queue import Queue
import argparse
import datetime
import sys
from osgar.bus import Bus
parser = argparse.ArgumentParser(description='Run artifact detection and classification for given JPEG image')
parser.add_argument('filename', help='JPEG filename... | conditional_block | |
main.go | () {
// Create and run application
app.Create().Run()
}
//package main
//
//
//import (
// "flag"
// "github.com/SynthBrain/synthBrain/baseStruct"
// "github.com/SynthBrain/synthBrain/myGui"
// "github.com/g3n/engine/app"
// "github.com/g3n/engine/camera"
// "github.com/g3n/engine/core"
// "github.com/g3n/engine/geo... | main | identifier_name | |
main.go | // app := app.App()
// scene := core.NewNode()
//
// // Set the scene to be managed by the gui manager
// gui.Manager().Set(scene)
//
// // Create SynthBrain struct
// synB := new(baseStruct.SynthBrain)
// //frameRater := synB.FrameRater
//
// // Create perspective camera
// cam := camera.New(1)
// cam.SetPosition(0, 0... | // // Create application and scene | random_line_split | |
main.go |
//package main
//
//
//import (
// "flag"
// "github.com/SynthBrain/synthBrain/baseStruct"
// "github.com/SynthBrain/synthBrain/myGui"
// "github.com/g3n/engine/app"
// "github.com/g3n/engine/camera"
// "github.com/g3n/engine/core"
// "github.com/g3n/engine/geometry"
// "github.com/g3n/engine/gls"
// "github.com/g3n/... | {
// Create and run application
app.Create().Run()
} | identifier_body | |
thm.py | .levels = sorted(levels, reverse=True)
m = self._get_m(levels)
# pyre-fixme[4]: Attribute must be annotated.
self.m = m
# pyre-fixme[4]: Attribute must be annotated.
self.freq = {k: int(m / k) for k in self.levels}
self.baseModels = baseModels
# pyre-fixme[4]: At... | elif method == "svar":
residuals = self._get_all_residuals()
ans = []
for k in levels:
ans.extend([np.nanmean(np.square(residuals[k]))] * freq[k])
return np.array(ans) + eps
elif method == "hvar":
res_matrix = self._get_residua... | """
Calculate W matrix.
Args:
method: Reconciliation method for temporal hierarchical model. Valid
methods include 'struc', 'svar', 'hvar', 'mint_sample', and
'mint_shrink'.
eps: Epsilons added to W for numerical stability.
Returns:
... | identifier_body |
thm.py | "Base model should be a BaseTHModel object but is "
f"{type(basemodel)}."
)
raise _log_error(msg)
levels = [bm.level for bm in baseModels]
if 1 not in levels:
raise _log_error("Model of level 1 is missing.")
i... | random_line_split | ||
thm.py | .levels = sorted(levels, reverse=True)
m = self._get_m(levels)
# pyre-fixme[4]: Attribute must be annotated.
self.m = m
# pyre-fixme[4]: Attribute must be annotated.
self.freq = {k: int(m / k) for k in self.levels}
self.baseModels = baseModels
# pyre-fixme[4]: At... | (self, steps: int, method="struc") -> Dict[int, np.ndarray]:
"""
Generate original forecasts from each base model (without time index).
Args:
steps: Number of forecasts for level 1.
methd: Reconciliation method.
Returns:
Dictionary of forecasts of ea... | _predict_origin | identifier_name |
thm.py | .levels = sorted(levels, reverse=True)
m = self._get_m(levels)
# pyre-fixme[4]: Attribute must be annotated.
self.m = m
# pyre-fixme[4]: Attribute must be annotated.
self.freq = {k: int(m / k) for k in self.levels}
self.baseModels = baseModels
# pyre-fixme[4]: At... |
elif method == "mint_shrink":
cov = np.cov(self._get_residual_matrix())
# get correlation matrix
sqrt = np.sqrt(np.diag(cov))
cor = (
(cov / sqrt).T
) / sqrt # due to symmetry, no need to transpose the matrix again.
mask ... | res_matrix = self._get_residual_matrix()
return np.nanvar(res_matrix, axis=1) + eps | conditional_block |
Thyroid annotator.py | def get_file_list(root_dir):
file_list = []
counter = 1
for root, directories, filenames in os.walk(root_dir):
for filename in filenames:
if any(ext in filename for ext in extensions):
file_list.append(os.path.join(root, filename))
counter += 1
... |
else:
set_index_in(state.input)
#update_choices(state.input,comp_list)
state.input = state.input + 1
update_choices(state.input)
if state.input > state.last_anot:
state.last_anot = state.input
if prev_button and state.active_project == True:
if state.input == 0:
e =Runtim... | e =RuntimeError('Reached end of images in the folder')
st.exception(e) | conditional_block |
Thyroid annotator.py | def get_file_list(root_dir):
file_list = []
counter = 1
for root, directories, filenames in os.walk(root_dir):
for filename in filenames:
if any(ext in filename for ext in extensions):
file_list.append(os.path.join(root, filename))
counter += 1
... | (ind_no,file_to_anot):
file_name = file_to_anot[ind_no]
im_file =re.sub("\\\\","\\\\\\\\", file_name)
loaded_image = Image.open(im_file)
return loaded_image
### Get just the image file name from the complete path string
def extract_basename(path):
basename = re.search(r'[^\\/]+(?=[\\/]?$)', path)
if b... | get_image | identifier_name |
Thyroid annotator.py | get_file_list(root_dir):
file_list = []
counter = 1
for root, directories, filenames in os.walk(root_dir):
for filename in filenames:
if any(ext in filename for ext in extensions):
file_list.append(os.path.join(root, filename))
counter += 1
re... |
if state.echo_list[ind_num] != None:
state.echo = state.echo_list[ind_num]
else:
state.echo = 0
if state.shape_list[ind_num] !=None:
state.shape = state.shape_list[ind_num]
else:
state.shape = 0
if state.marg_list[ind_num] != None:
state.margin = state.marg_list[ind_n... | state = _get_state()
def set_index_in(in_num):
state.comp_list[in_num] = get_index(comp_options, composition)
state.echo_list[in_num] = get_index(echo_options, echo)
state.shape_list[in_num]= get_index(shape_options, shape)
state.marg_list[in_num] = get_index(margin_options, margin)
state.foc... | identifier_body |
Thyroid annotator.py | from streamlit.hashing import _CodeHasher
from streamlit.report_thread import get_report_ctx
from streamlit.server.server import Server
import streamlit as st
from PIL import Image
import os
import pandas as pd
import re
### Creating a 3 column layout in streamlit
col1, col2, col3= st.beta_columns([3, 1,1]... |
### Importing libraries
| random_line_split | |
gardenView.js | idth, length) {
// From user dimensions, we calculate grid features, like the size in pixels of a meter
this.grid = {
userDimensions: {
width: width,
length: length
},
sizeMeter: ($(`#${this.containerSelector}`).width() - SCROLLBAR_WIDTH) / width,
horizontalLines: [],
... | nerate(w | identifier_name | |
gardenView.js | this.grid = {
userDimensions: {
width: width,
length: length
},
sizeMeter: ($(`#${this.containerSelector}`).width() - SCROLLBAR_WIDTH) / width,
horizontalLines: [],
verticalLines: []
}; |
$(`#${this.containerSelector}`).empty().append(`
<div class="row">
<div class="col-md-12">
<div style="height:400px; overflow: auto;">
<canvas
id="canvas-garden"
width=${this.grid.sizeMeter * width}
height=${this.grid.sizeMeter * length}... | random_line_split | |
gardenView.js | this.grid = {
userDimensions: {
width: width,
length: length
},
sizeMeter: ($(`#${this.containerSelector}`).width() - SCROLLBAR_WIDTH) / width,
horizontalLines: [],
verticalLines: []
};
$(`#${this.containerSelector}`).empty().append(`
<div class="row">
... | /* Populate garden with plants from imported data */
load(data) {
// By default, if no user dimensions saved, we generate a 6mx4m garden
const {width, length} = (typeof(data.garden.userDimensions) !== 'undefined')
? data.garden.userDimensions
: {width: DEFAULT_USER_WIDTH, length: DEFAULT_USER_LE... | img.set({
width: width,
height: height,
left: position.x,
top: position.y,
hasRotatingPoint: false,
lockRotation: true,
lockScalingFlip : true,
lockScalingX: true,
lockScalingY: true
});
const plant = this.plantFactory.buildPlant(idPlant);
let plantV... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.