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 |
|---|---|---|---|---|
chart.js | google.charts.load('current', { packages: ['corechart'] });
//global variable for storing the ids of articles currently shown in author analytics page
var articlesShown = [];
var allArticleTitles = [];
var allArticletitlesWithRevisions = [];
//chart otpions
var options = {
'fontName':'Avenir',
'backgroundColor': ... | () {
var destination = 'getNewestArticles';
console.log('here');
$.get(destination, null, function (data) {
console.log(data);
$('#newestArticles').empty();
for (var x = 0; x < data.length; x++) {
var num = x + 1;
num = num + '. ';
var appendMe = $('<li>' + num + data[x]._id + '</li>');
$('#newes... | getNewestArticles | identifier_name |
chart.js | google.charts.load('current', { packages: ['corechart'] });
//global variable for storing the ids of articles currently shown in author analytics page
var articlesShown = [];
var allArticleTitles = [];
var allArticletitlesWithRevisions = [];
//chart otpions
var options = {
'fontName':'Avenir',
'backgroundColor': ... |
//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 | /*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package startcmd
import (
"crypto/tls"
"crypto/x509"
"database/sql"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/gorilla/mux"
"github.com/hype... |
func createFlags(startCmd *cobra.Command) {
startCmd.Flags().StringP(hostURLFlagName, hostURLFlagShorthand, "", hostURLFlagUsage)
startCmd.Flags().StringP(tlsSystemCertPoolFlagName, "", "", tlsSystemCertPoolFlagUsage)
startCmd.Flags().StringArrayP(tlsCACertsFlagName, "", []string{}, tlsCACertsFlagUsage)
startCmd.... | {
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 | /*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package startcmd
import (
"crypto/tls"
"crypto/x509"
"database/sql"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/gorilla/mux"
"github.com/hype... |
return ctx, nil
}
| {
return nil, fmt.Errorf("aries-framework - failed to get aries context : %w", err)
} | conditional_block |
start.go | /*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package startcmd
import (
"crypto/tls"
"crypto/x509"
"database/sql"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/gorilla/mux"
"github.com/hype... | (handler http.Handler) http.Handler {
return cors.New(
cors.Options{
AllowedMethods: []string{http.MethodGet, http.MethodPost},
AllowedHeaders: []string{"Origin", "Accept", "Content-Type", "X-Requested-With", "Authorization"},
},
).Handler(handler)
}
//nolint:deadcode,unused
func initDB(dsn string) (*sql.D... | constructCORSHandler | identifier_name |
start.go | /*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package startcmd
import (
"crypto/tls"
"crypto/x509"
"database/sql"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/gorilla/mux"
"github.com/hype... | }
// static frontend
router.PathPrefix(uiEndpoint).
Subrouter().
Methods(http.MethodGet).
HandlerFunc(uiHandler(parameters.staticFiles, http.ServeFile))
return nil
}
func addIssuerHandlers(parameters *adapterRestParameters, ariesCtx ariespai.CtxProvider, router *mux.Router) error {
// add issuer endpoints... | router.HandleFunc(handler.Path(), handler.Handle()).Methods(handler.Method()) | random_line_split |
parse.go | // Package types is a package that parses the GDNative headers for type definitions
// to create wrapper structures for Go.
package types
import (
"fmt"
"github.com/pinzolo/casee"
"io/ioutil"
"os"
"regexp"
"path/filepath"
"strings"
"github.com/godot-go/godot-go/cmd/gdnativeapijson"
)
var cTypeRegex = regexp.M... | (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 | // Package types is a package that parses the GDNative headers for type definitions
// to create wrapper structures for Go.
package types
import (
"fmt"
"github.com/pinzolo/casee"
"io/ioutil"
"os"
"regexp"
"path/filepath"
"strings"
"github.com/godot-go/godot-go/cmd/gdnativeapijson"
)
var cTypeRegex = regexp.M... |
// 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 | // Package types is a package that parses the GDNative headers for type definitions
// to create wrapper structures for Go.
package types
import (
"fmt"
"github.com/pinzolo/casee"
"io/ioutil"
"os"
"regexp"
"path/filepath"
"strings"
"github.com/godot-go/godot-go/cmd/gdnativeapijson"
)
var cTypeRegex = regexp.M... | 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 | // Package types is a package that parses the GDNative headers for type definitions
// to create wrapper structures for Go.
package types
import (
"fmt"
"github.com/pinzolo/casee"
"io/ioutil"
"os"
"regexp"
"path/filepath"
"strings"
"github.com/godot-go/godot-go/cmd/gdnativeapijson"
)
var cTypeRegex = regexp.M... |
type block int8
const (
externBlock block = iota
typedefBlock
localStructBlock
enumBlock
)
// findTypeDefs will return a list of type definition lines.
func findTypeDefs(content []byte) [][]string {
lines := strings.Split(string(content), "\n")
// Create a structure that will hold the lines that define the t... | {
// 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 | use std::{
path::Path,
sync::{Arc, Mutex},
};
use crate::{
projectile::{
Projectile,
ProjectileKind,
},
actor::Actor,
HandleFromSelf,
GameTime,
level::CleanUp,
};
use rg3d::{
physics::{RayCastOptions, Physics},
sound::{
source::Source,
buffer::Buff... | (&self) -> PoolIterator<Weapon> {
self.pool.iter()
}
pub fn iter_mut(&mut self) -> PoolIteratorMut<Weapon> {
self.pool.iter_mut()
}
pub fn get(&self, handle: Handle<Weapon>) -> &Weapon {
self.pool.borrow(handle)
}
pub fn get_mut(&mut self, handle: Handle<Weapon>) -> &m... | iter | identifier_name |
weapon.rs | use std::{
path::Path,
sync::{Arc, Mutex},
};
use crate::{
projectile::{
Projectile,
ProjectileKind,
},
actor::Actor,
HandleFromSelf,
GameTime,
level::CleanUp,
};
use rg3d::{
physics::{RayCastOptions, Physics},
sound::{
source::Source,
buffer::Buff... |
}
impl CleanUp for Weapon {
fn clean_up(&mut self, scene: &mut Scene) {
let SceneInterfaceMut { graph, .. } = scene.interface_mut();
graph.remove_node(self.model);
graph.remove_node(self.laser_dot);
}
}
pub struct WeaponContainer {
pool: Pool<Weapon>
}
impl WeaponContainer {
... | {
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 | use std::{
path::Path,
sync::{Arc, Mutex},
};
use crate::{
projectile::{
Projectile,
ProjectileKind,
},
actor::Actor,
HandleFromSelf,
GameTime,
level::CleanUp,
};
use rg3d::{
physics::{RayCastOptions, Physics},
sound::{
source::Source,
buffer::Buff... | }
impl Visit for WeaponContainer {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
visitor.enter_region(name)?;
self.pool.visit("Pool", visitor)?;
visitor.leave_region()
}
} | weapon.update(scene)
}
} | random_line_split |
weapon.rs | use std::{
path::Path,
sync::{Arc, Mutex},
};
use crate::{
projectile::{
Projectile,
ProjectileKind,
},
actor::Actor,
HandleFromSelf,
GameTime,
level::CleanUp,
};
use rg3d::{
physics::{RayCastOptions, Physics},
sound::{
source::Source,
buffer::Buff... |
WeaponKind::PlasmaRifle => {
Some(Projectile::new(ProjectileKind::Plasma, resource_manager, scene,
dir, pos, self.self_handle, weapon_velocity))
}
}
} else {
None
}
}
}
impl CleanUp... | {
Some(Projectile::new(ProjectileKind::Bullet, resource_manager, scene,
dir, pos, self.self_handle, weapon_velocity))
} | conditional_block |
unet3d.py | import argparse
import lbann
import lbann.models
import lbann.contrib.args
import lbann.contrib.launcher
import lbann.modules as lm
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,
... |
else:
environment['LBANN_KEEP_ERROR_SIGNALS'] = 1
lbann_args = ['--use_data_store']
# Run experiment
kwargs = lbann.contrib.args.get_scheduler_kwargs(args)
lbann.contrib.launcher.run(
trainer, model, data_reader, optimizer,
job_name=args.job_name,
environment=enviro... | environment['LBANN_KEEP_ERROR_SIGNALS'] = 0 | conditional_block |
unet3d.py | import argparse
| 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 | import argparse
import lbann
import lbann.models
import lbann.contrib.args
import lbann.contrib.launcher
import lbann.modules as lm
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,
... |
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 | import argparse
import lbann
import lbann.models
import lbann.contrib.args
import lbann.contrib.launcher
import lbann.modules as lm
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,
... | (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 | //! An interpreter for the rust-installer package format. Responsible
//! for installing from a directory or tarball to an installation
//! prefix, represented by a `Components` instance.
use crate::dist::component::components::*;
use crate::dist::component::transaction::*;
use crate::dist::temp;
use crate::errors::... |
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 | //! An interpreter for the rust-installer package format. Responsible
//! for installing from a directory or tarball to an installation
//! prefix, represented by a `Components` instance.
use crate::dist::component::components::*;
use crate::dist::component::transaction::*;
use crate::dist::temp;
use crate::errors::... | <'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 | //! An interpreter for the rust-installer package format. Responsible
//! for installing from a directory or tarball to an installation
//! prefix, represented by a `Components` instance.
use crate::dist::component::components::*;
use crate::dist::component::transaction::*;
use crate::dist::temp;
use crate::errors::... | 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 | //! An interpreter for the rust-installer package format. Responsible
//! for installing from a directory or tarball to an installation
//! prefix, represented by a `Components` instance.
use crate::dist::component::components::*;
use crate::dist::component::transaction::*;
use crate::dist::temp;
use crate::errors::... | 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 | import Vue from 'vue';
import VueResource from 'vue-resource';
// window.Vue = Vue;
Vue.use(VueResource);
import Alert from './components/Alert.vue';
// var Vue = require('vue');
// var VueResource = require('vue-resource');
// // window.Vue = Vue;
// Vue.use(VueResource);
// import Profile from './Profile.vue';
... | ,
methods: {
startTime: function () {
var min = this.$refs.min.$el,
sec = this.$refs.sec.$el,
hour = this.$refs.hour.$el;
var now = new Date(),
hValue = now.getHours(),
mValue = now.getMinutes(),
sValue =... | {
this.startTime()
} | identifier_body |
app.js | import Vue from 'vue';
import VueResource from 'vue-resource';
// window.Vue = Vue;
Vue.use(VueResource);
import Alert from './components/Alert.vue';
// var Vue = require('vue');
// var VueResource = require('vue-resource');
// // window.Vue = Vue;
// Vue.use(VueResource);
// import Profile from './Profile.vue';
... | () {
this.startTime()
},
methods: {
startTime: function () {
var min = this.$refs.min.$el,
sec = this.$refs.sec.$el,
hour = this.$refs.hour.$el;
var now = new Date(),
hValue = now.getHours(),
mValue = now.ge... | ready | identifier_name |
app.js | import Vue from 'vue';
import VueResource from 'vue-resource';
// window.Vue = Vue;
Vue.use(VueResource);
import Alert from './components/Alert.vue';
// var Vue = require('vue');
// var VueResource = require('vue-resource');
// // window.Vue = Vue;
// Vue.use(VueResource);
// import Profile from './Profile.vue';
... | 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 | import Vue from 'vue';
import VueResource from 'vue-resource';
// window.Vue = Vue;
Vue.use(VueResource);
import Alert from './components/Alert.vue';
// var Vue = require('vue');
// var VueResource = require('vue-resource');
// // window.Vue = Vue;
// Vue.use(VueResource);
// import Profile from './Profile.vue';
... |
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 | import pandas as pd
from messageLogs_functions import *
from byteUtils import *
from podStateAnalysis import *
from messagePatternParsing import *
from checkAction import *
def analyzeMessageLogsRev3(thisPath, thisFile, outFile):
# Rev3 uses the new checkAction code
# this replaces code used by New (rev2)
... | 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 | import pandas as pd
from messageLogs_functions import *
from byteUtils import *
from podStateAnalysis import *
from messagePatternParsing import *
from checkAction import *
def analyzeMessageLogsRev3(thisPath, thisFile, outFile):
# Rev3 uses the new checkAction code
# this replaces code used by New (rev2)
... |
# 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 | import pandas as pd
from messageLogs_functions import *
from byteUtils import *
from podStateAnalysis import *
from messagePatternParsing import *
from checkAction import *
def | (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 | import pandas as pd
from messageLogs_functions import *
from byteUtils import *
from podStateAnalysis import *
from messagePatternParsing import *
from checkAction import *
def analyzeMessageLogsRev3(thisPath, thisFile, outFile):
# Rev3 uses the new checkAction code
# this replaces code used by New (rev2)
... | 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 | import "./cockpit.html"
import "./cockpit_table.html"
// import "../common/navbar-position.html"
//import { ReactiveVar } from 'meteor/reactive-var';
let loguser;
let pro_id;
let _changeProject2;
let _this_btn;
let pagenum;
let limit=10;
let templ;
//显隐提示
function prompt(val, shObj) {
if | .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 | import "./cockpit.html"
import "./cockpit_table.html"
// import "../common/navbar-position.html"
//import { ReactiveVar } from 'meteor/reactive-var';
let loguser;
let pro_id;
let _changeProject2;
let _this_btn;
let pagenum;
let limit=10;
let templ;
//显隐提示
function prompt(val, shObj) {
if (!val) {
shObj.... | // 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 | import "./cockpit.html"
import "./cockpit_table.html"
// import "../common/navbar-position.html"
//import { ReactiveVar } from 'meteor/reactive-var';
let loguser;
let pro_id;
let _changeProject2;
let _this_btn;
let pagenum;
let limit=10;
let templ;
//显隐提示
function prompt(val, shObj) {
if (!val) {
shObj.... | 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 | import "./cockpit.html"
import "./cockpit_table.html"
// import "../common/navbar-position.html"
//import { ReactiveVar } from 'meteor/reactive-var';
let loguser;
let pro_id;
let _changeProject2;
let _this_btn;
let pagenum;
let limit=10;
let templ;
//显隐提示
function prompt(v | 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 | use crate::utility::location::Location;
use crate::exit_on_bad_config;
use origen_metal::{config, scrub_path};
use origen_metal::config::{Environment, File};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::om::glob::glob;
use std::process::exit;
use super::target;
const PUBLISHER_OPTIONS: &[&... |
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 | use crate::utility::location::Location;
use crate::exit_on_bad_config;
use origen_metal::{config, scrub_path};
use origen_metal::config::{Environment, File};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::om::glob::glob;
use std::process::exit;
use super::target;
const PUBLISHER_OPTIONS: &[&... | {
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 | use crate::utility::location::Location;
use crate::exit_on_bad_config;
use origen_metal::{config, scrub_path};
use origen_metal::config::{Environment, File};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::om::glob::glob;
use std::process::exit;
use super::target;
const PUBLISHER_OPTIONS: &[&... |
}
}
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 | use crate::utility::location::Location;
use crate::exit_on_bad_config;
use origen_metal::{config, scrub_path};
use origen_metal::config::{Environment, File};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::om::glob::glob;
use std::process::exit;
use super::target;
const PUBLISHER_OPTIONS: &[&... | 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 | // Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... | }
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 | // Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... |
// 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 | // Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... | (origin common.Hash, amount int, skip int, reverse bool) error {
rq := &distReq{
getCost: func(dp distPeer) uint64 {
peer := dp.(*peer)
return peer.GetRequestCost(GetBlockHeadersMsg, amount)
},
canSend: func(dp distPeer) bool {
return dp.(*peer) == pc.peer
},
request: func(dp distPeer) func() {
r... | RequestHeadersByHash | identifier_name |
client_handler.go | // Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... |
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 | /*
Tests for files.go
MIT licenced, please see LICENCE
RCL January 2020
*/
package files
import (
"io/ioutil"
"os"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
func ptime(ti string) time.Time {
tp, err := time.Parse("2006-01-02 15:04:05 -0700 MST", ti)
if err != nil {
panic(err)
}
return ... | 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 | /*
Tests for files.go
MIT licenced, please see LICENCE
RCL January 2020
*/
package files
import (
"io/ioutil"
"os"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
func ptime(ti string) time.Time {
tp, err := time.Parse("2006-01-02 15:04:05 -0700 MST", ti)
if err != nil {
panic(err)
}
return ... | (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 | /*
Tests for files.go
MIT licenced, please see LICENCE
RCL January 2020
*/
package files
import (
"io/ioutil"
"os"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
func ptime(ti string) time.Time {
tp, err := time.Parse("2006-01-02 15:04:05 -0700 MST", ti)
if err != nil {
panic(err)
}
return ... |
// 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 | /*
Tests for files.go
MIT licenced, please see LICENCE
RCL January 2020
*/
package files
import (
"io/ioutil"
"os"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
func ptime(ti string) time.Time {
tp, err := time.Parse("2006-01-02 15:04:05 -0700 MST", ti)
if err != nil {
panic(err)
}
return ... | {
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 | from tkinter import *
from tkinter.ttk import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import re
import datetime
import openpyxl
dict_regions_russia = {
'Планета Земля':-1,
'Без учета региона': 0,
'Европа': 111,
'СНГ': 166,
'Универ... | yxl.Workbook()
title_sheet = workbook.active
# filename = datetime.datetime.today().strftime("%Y-%m-%d-%H-%M-%S")
# выбираем активный лист и меняем ему название
title_sheet.title = "title"
if title_check.get() == True:
i = 1
for word in title_list:
cellref = title_sheet.cell(row=i,... | k = openp | identifier_name |
pars.py | from tkinter import *
from tkinter.ttk import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import re
import datetime
import openpyxl
dict_regions_russia = {
'Планета Земля':-1,
'Без учета региона': 0,
'Европа': 111,
'СНГ': 166,
'Универ... | title_sheet = workbook.active
# filename = datetime.datetime.today().strftime("%Y-%m-%d-%H-%M-%S")
# выбираем активный лист и меняем ему название
title_sheet.title = "title"
if title_check.get() == True:
i = 1
for word in title_list:
cellref = title_sheet.cell(row=i, column=1)
... |
# создаю новую книгу
workbook = openpyxl.Workbook() | random_line_split |
pars.py | from tkinter import *
from tkinter.ttk import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import re
import datetime
import openpyxl
dict_regions_russia = {
'Планета Земля':-1,
'Без учета региона': 0,
'Европа': 111,
'СНГ': 166,
'Универ... | et = workbook.active
# filename = datetime.datetime.today().strftime("%Y-%m-%d-%H-%M-%S")
# выбираем активный лист и меняем ему название
title_sheet.title = "title"
if title_check.get() == True:
i = 1
for word in title_list:
cellref = title_sheet.cell(row=i, column=1)
cellref.val... | ok()
title_she | identifier_body |
pars.py | from tkinter import *
from tkinter.ttk import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import re
import datetime
import openpyxl
dict_regions_russia = {
'Планета Земля':-1,
'Без учета региона': 0,
'Европа': 111,
'СНГ': 166,
'Универ... | ble=h3_check, onvalue=1, offvalue=0)
c6.pack(side=LEFT)
keywords_check = BooleanVar()
keywords_check.set(1)
c3 = Checkbutton(frame_3, text="keys", variable=keywords_check, onvalue=1, offvalue=0)
c3.pack(side=RIGHT)
lable_2 = Label(frame_4, text="Регион:")
lable_2.pack()
combo = Combobox(frame_4)
combo['values'] = ... | 1)
c6 = Checkbutton(frame_3, text="h3", varia | conditional_block |
openai.py | import os
from contextlib import contextmanager
from typing import Any, Callable, Dict, List
from pydantic import Field, validator, PositiveInt
from enum import Enum
import openai
from langchain.chat_models import AzureChatOpenAI, ChatOpenAI
from langchain.llms import AzureOpenAI, OpenAI
from langchain.llms.openai imp... |
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 | import os
from contextlib import contextmanager
from typing import Any, Callable, Dict, List
from pydantic import Field, validator, PositiveInt
from enum import Enum
import openai
from langchain.chat_models import AzureChatOpenAI, ChatOpenAI
from langchain.llms import AzureOpenAI, OpenAI
from langchain.llms.openai imp... | BaseLanguageModel: The model.
"""
model = available_models[self.model_name.value]
kwargs = model._lc_kwargs
secrets = {secret: getattr(model, secret) for secret in model.lc_secrets.keys()}
kwargs.update(secrets)
model_kwargs = kwargs.get("model_kwargs", {})
... | """Get the model from the configuration.
Returns: | random_line_split |
openai.py | import os
from contextlib import contextmanager
from typing import Any, Callable, Dict, List
from pydantic import Field, validator, PositiveInt
from enum import Enum
import openai
from langchain.chat_models import AzureChatOpenAI, ChatOpenAI
from langchain.llms import AzureOpenAI, OpenAI
from langchain.llms.openai imp... | """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 | import os
from contextlib import contextmanager
from typing import Any, Callable, Dict, List
from pydantic import Field, validator, PositiveInt
from enum import Enum
import openai
from langchain.chat_models import AzureChatOpenAI, ChatOpenAI
from langchain.llms import AzureOpenAI, OpenAI
from langchain.llms.openai imp... | (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 | /**
* Created by wanli on 2015/4/21.
*/
//页面加载
var OldData=null;
$(document.body).ready(function(){
d3.csv("../data/cashtrend.csv", function(csv) {
OldData=DataGroupManager(csv,"名称");
Refreshtrend();
});
});
//数据分组处理
function DataGroupManager(_Data,_GroupColumn){
var groupdata=[];//item:{... | 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 | /**
* Created by wanli on 2015/4/21.
*/
//页面加载
var OldData=null;
$(document.body).ready(function(){
d3.csv("../data/cashtrend.csv", function(csv) {
OldData=DataGroupManager(csv,"名称");
Refreshtrend();
});
});
//数据分组处理
function DataGroupManager(_Data,_GroupColumn){
var groupdata=[];//item:{... | style:{
color:"#666666",
fontFamily:"微软雅黑"
},
formatter:function(){
return this.value+1+"日";
}
}
},
yAxis:{
labels:{
style:{
... | },
credits:{enabled:false},
xAxis:{
labels:{ | random_line_split |
devicecash_trend.js | /**
* Created by wanli on 2015/4/21.
*/
//页面加载
var OldData=null;
$(document.body).ready(function(){
d3.csv("../data/cashtrend.csv", function(csv) {
OldData=DataGroupManager(csv,"名称");
Refreshtrend();
});
});
//数据分组处理
function DataGroupManager(_Data,_GroupColumn){
var groupdata=[];//item:{... | =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 | /**
* Created by wanli on 2015/4/21.
*/
//页面加载
var OldData=null;
$(document.body).ready(function(){
d3.csv("../data/cashtrend.csv", function(csv) {
OldData=DataGroupManager(csv,"名称");
Refreshtrend();
});
});
//数据分组处理
function DataGroupManager(_Data,_GroupColumn){
var groupdata=[];//item:{... | 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 | // Workflow written in SciPipe. // For more information about SciPipe, see: http://scipipe.org
package main
import (
"flag"
"fmt"
"runtime"
"strconv"
str "strings"
sp "github.com/scipipe/scipipe"
spc "github.com/scipipe/scipipe/components"
)
var (
maxTasks = flag.Int("maxtasks", 4, "Max number of local core... |
// --------------------------------------------------------------------------------
// JSON types
// --------------------------------------------------------------------------------
// JSON output of cpSign crossvalidate
// {
// "classConfidence": 0.855,
// "observedFuzziness": {
// "A": 0.253,
// ... | {
// --------------------------------
// 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 | // Workflow written in SciPipe. // For more information about SciPipe, see: http://scipipe.org
package main
import (
"flag"
"fmt"
"runtime"
"strconv"
str "strings"
sp "github.com/scipipe/scipipe"
spc "github.com/scipipe/scipipe/components"
)
var (
maxTasks = flag.Int("maxtasks", 4, "Max number of local core... | "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 | // Workflow written in SciPipe. // For more information about SciPipe, see: http://scipipe.org
package main
import (
"flag"
"fmt"
"runtime"
"strconv"
str "strings"
sp "github.com/scipipe/scipipe"
spc "github.com/scipipe/scipipe/components"
)
var (
maxTasks = flag.Int("maxtasks", 4, "Max number of local core... | () {
// --------------------------------
// 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 | // Workflow written in SciPipe. // For more information about SciPipe, see: http://scipipe.org
package main
import (
"flag"
"fmt"
"runtime"
"strconv"
str "strings"
sp "github.com/scipipe/scipipe"
spc "github.com/scipipe/scipipe/components"
)
var (
maxTasks = flag.Int("maxtasks", 4, "Max number of local core... |
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 | use crate::{BeaconChain, BeaconChainTypes};
use eth2_hashing::hash;
use lighthouse_bootstrap::Bootstrapper;
use merkle_proof::MerkleTree;
use rayon::prelude::*;
use slog::Logger;
use ssz::{Decode, Encode};
use state_processing::initialize_beacon_state_from_eth1;
use std::fs::File;
use std::io::prelude::*;
use std::path... |
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 | use crate::{BeaconChain, BeaconChainTypes};
use eth2_hashing::hash;
use lighthouse_bootstrap::Bootstrapper;
use merkle_proof::MerkleTree;
use rayon::prelude::*;
use slog::Logger;
use ssz::{Decode, Encode};
use state_processing::initialize_beacon_state_from_eth1;
use std::fs::File;
use std::io::prelude::*;
use std::path... | let creds = v.withdrawal_credentials.as_bytes();
assert_eq!(
creds[0], spec.bls_withdrawal_prefix_byte,
"first byte of withdrawal creds should be bls prefix"
);
assert_eq!(
&creds[1..],
&hash(&v.pubkey.as_ssz... | "validator balances should be max effective balance"
);
}
for v in &state.validators { | random_line_split |
beacon_chain_builder.rs | use crate::{BeaconChain, BeaconChainTypes};
use eth2_hashing::hash;
use lighthouse_bootstrap::Bootstrapper;
use merkle_proof::MerkleTree;
use rayon::prelude::*;
use slog::Logger;
use ssz::{Decode, Encode};
use state_processing::initialize_beacon_state_from_eth1;
use std::fs::File;
use std::io::prelude::*;
use std::path... | (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 | use crate::{BeaconChain, BeaconChainTypes};
use eth2_hashing::hash;
use lighthouse_bootstrap::Bootstrapper;
use merkle_proof::MerkleTree;
use rayon::prelude::*;
use slog::Logger;
use ssz::{Decode, Encode};
use state_processing::initialize_beacon_state_from_eth1;
use std::fs::File;
use std::io::prelude::*;
use std::path... |
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 | use std::io::{Read, Write, Result, BufRead, BufReader, BufWriter};
use std::fs::File;
use std::net::{TcpListener, TcpStream};
use std::mem::size_of;
use std::sync::Arc;
use std::sync::mpsc::{Sender, Receiver, channel};
use std::thread;
use std::thread::sleep_ms;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesEx... | {
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 | use std::io::{Read, Write, Result, BufRead, BufReader, BufWriter};
use std::fs::File;
use std::net::{TcpListener, TcpStream};
use std::mem::size_of;
use std::sync::Arc;
use std::sync::mpsc::{Sender, Receiver, channel};
use std::thread;
use std::thread::sleep_ms;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesEx... | // 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 | use std::io::{Read, Write, Result, BufRead, BufReader, BufWriter};
use std::fs::File;
use std::net::{TcpListener, TcpStream};
use std::mem::size_of;
use std::sync::Arc;
use std::sync::mpsc::{Sender, Receiver, channel};
use std::thread;
use std::thread::sleep_ms;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesEx... | {
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 | use core::marker::Sized;
use embedded_hal::{
blocking::{delay::*, spi::Write},
digital::v2::*,
};
/// All commands need to have this trait which gives the address of the command
/// which needs to be send via SPI with activated CommandsPin (Data/Command Pin in CommandMode)
pub(crate) trait Command: Copy {
... | /// Updates and displays the new frame.
fn update_and_display_new_frame(
&mut self,
spi: &mut SPI,
buffer: &[u8],
delay: &mut DELAY,
) -> Result<(), SPI::Error>;
/// Updates the old frame for a portion of the display.
#[allow(clippy::too_many_arguments)]
fn updat... |
/// Displays the new frame
fn display_new_frame(&mut self, spi: &mut SPI, _delay: &mut DELAY) -> Result<(), SPI::Error>;
| random_line_split |
traits.rs | use core::marker::Sized;
use embedded_hal::{
blocking::{delay::*, spi::Write},
digital::v2::*,
};
/// All commands need to have this trait which gives the address of the command
/// which needs to be send via SPI with activated CommandsPin (Data/Command Pin in CommandMode)
pub(crate) trait Command: Copy {
... | {
/// 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 | package controllers
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/bitly/go-simplejson"
"github.com/juju/errors"
"seater/models"
"seater/schema"
)
// Define controller constants
const (
TimestampLayout = time.RFC3339
PeriodDay = "d... | (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 | package controllers
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/bitly/go-simplejson"
"github.com/juju/errors"
"seater/models"
"seater/schema"
)
// Define controller constants
const (
TimestampLayout = time.RFC3339
PeriodDay = "d... |
// 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 | package controllers
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/bitly/go-simplejson"
"github.com/juju/errors"
"seater/models"
"seater/schema"
)
// Define controller constants
const (
TimestampLayout = time.RFC3339
PeriodDay = "d... | 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 | package controllers
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/bitly/go-simplejson"
"github.com/juju/errors"
"seater/models"
"seater/schema"
)
// Define controller constants
const (
TimestampLayout = time.RFC3339
PeriodDay = "d... |
return id
}
// CreateTask create task
func (c *SeaterController) CreateTask(t string, data *simplejson.Json) (task *models.Task, err error) {
if task, err = c.model.NewTask(t, data); err != nil {
err = errors.Annotatef(err, "failed to create task %s", t)
return
}
return
}
| {
c.BadRequestf("invalid id")
} | conditional_block |
app.js | const Influx = require('influx')
const express = require('express')
const http = require('http')
const os = require('os')
const path = require('path');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'vie... | return count;
}
/**
* 发送 POST 请求
*/
function postRequest(url, json, callback) {
var options = {
uri: url,
method: 'POST',
json: json,
};
request(options, callback);
}
// -- routers ------------------------------------------------------
app.get('/', function (req, res) {
setTimeout(() => res.e... | }
fs.writeFileSync(BLOCK_FILE, JSON.stringify(blocks)); | random_line_split |
app.js |
const Influx = require('influx')
const express = require('express')
const http = require('http')
const os = require('os')
const path = require('path');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'v... | {
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 |
const Influx = require('influx')
const express = require('express')
const http = require('http')
const os = require('os')
const path = require('path');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'v... | ILE));
blocks[sid] = {};
blocks[sid][uid] = until;
fs.writeFileSync(BLOCK_FILE, JSON.stringify(blocks));
res.redirect('/blockme?sid='+ sid+ '&uid='+ uid+ '&v=2');
});
/**
* 手动清理临时屏蔽报警过期项
*/
app.get('/cleanblocks', function (req, res) {
let c = cleanBlocks();
res.send(c+ ' expires cleaned!(see logs)');... | 数错误!');
}
let until = new Date().addHours(after);
let blocks = JSON.parse(fs.readFileSync(BLOCK_F | identifier_body |
app.js |
const Influx = require('influx')
const express = require('express')
const http = require('http')
const os = require('os')
const path = require('path');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'v... | 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': (level==1? '#FFAD46': '#F83A22');
let durat_str = formatDur... | arm(sensor, | identifier_name |
spamScore.js | const { Extendable } = require('klasa');
const config = require("../config");
const moment = require("moment");
const stringSimilarity = require("string-similarity");
const { Message, MessageEmbed } = require('discord.js');
module.exports = class extends Extendable {
constructor(...args) {
super(...args, ... | () {
return this._earnedSpamScore;
}
set earnedSpamScore (value) {
this._earnedSpamScore = value;
}
};
function getIndicesOf (searchStr, str, caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, ind... | earnedSpamScore | identifier_name |
spamScore.js | const { Extendable } = require('klasa');
const config = require("../config");
const moment = require("moment");
const stringSimilarity = require("string-similarity");
const { Message, MessageEmbed } = require('discord.js');
module.exports = class extends Extendable {
constructor(...args) {
super(...args, ... | 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 | const { Extendable } = require('klasa');
const config = require("../config");
const moment = require("moment");
const stringSimilarity = require("string-similarity");
const { Message, MessageEmbed } = require('discord.js');
module.exports = class extends Extendable {
constructor(...args) {
super(...args, ... | if (patternScore < 1) { scoreReasons[ "Repeating Patterns" ] = parseInt(((1 - patternScore) * 25) * (1 + (0.1 * (this.cleanContent ? this.cleanContent.length / 100 : 0)))) }
// Add 3 points for every profane word used; excessive profanity spam
config.profanity.map((word)... | 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 | const { Extendable } = require('klasa');
const config = require("../config");
const moment = require("moment");
const stringSimilarity = require("string-similarity");
const { Message, MessageEmbed } = require('discord.js');
module.exports = class extends Extendable {
constructor(...args) {
super(...args, ... |
};
function getIndicesOf (searchStr, str, caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
whil... | {
this._earnedSpamScore = value;
} | identifier_body |
artifacts.py | """
Detect Cube Sat and Processing Plant artifacts
"""
from datetime import timedelta
import os
from io import StringIO
from statistics import median
import cv2
import numpy as np
from pathlib import Path
from osgar.node import Node
from osgar.bus import BusShutdownException
from moon.moonnode import CAMERA_WIDTH, ... |
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 | """
Detect Cube Sat and Processing Plant artifacts
"""
from datetime import timedelta
import os
from io import StringIO
from statistics import median
import cv2
import numpy as np
from pathlib import Path
from osgar.node import Node
from osgar.bus import BusShutdownException
from moon.moonnode import CAMERA_WIDTH, ... | (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 | """
Detect Cube Sat and Processing Plant artifacts
"""
from datetime import timedelta
import os
from io import StringIO
from statistics import median
import cv2
import numpy as np
from pathlib import Path
from osgar.node import Node
from osgar.bus import BusShutdownException
from moon.moonnode import CAMERA_WIDTH, ... | 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 | """
Detect Cube Sat and Processing Plant artifacts
"""
from datetime import timedelta
import os
from io import StringIO
from statistics import median
import cv2
import numpy as np
from pathlib import Path
from osgar.node import Node
from osgar.bus import BusShutdownException
from moon.moonnode import CAMERA_WIDTH, ... |
# vim: expandtab sw=4 ts=4
| 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 | package main
// 3840 * 2160 = 8 294 400
import (
"github.com/SynthBrain/synthBrain/app"
)
func | () {
// 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 | package main
// 3840 * 2160 = 8 294 400
import (
"github.com/SynthBrain/synthBrain/app"
)
func main() {
// Create and run application
app.Create().Run()
}
//package main
//
//
//import (
// "flag"
// "github.com/SynthBrain/synthBrain/baseStruct"
// "github.com/SynthBrain/synthBrain/myGui"
// "github.com/g3n/engi... | // 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
// 3840 * 2160 = 8 294 400
import (
"github.com/SynthBrain/synthBrain/app"
)
func main() |
//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 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module contains the class TemporalHierarchicalModel class.
"""
import logging
from math import gcd
from typing import Dict, List, O... |
# pyre-fixme[2]: Parameter must be annotated.
def _predict_origin(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: Reconci... | """
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 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module contains the class TemporalHierarchicalModel class.
"""
import logging
from math import gcd
from typing import Dict, List, O... | "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 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module contains the class TemporalHierarchicalModel class.
"""
import logging
from math import gcd
from typing import Dict, List, O... | (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 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This module contains the class TemporalHierarchicalModel class.
"""
import logging
from math import gcd
from typing import Dict, List, O... |
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 | ### Hacked together by Johnson Thomas
### Annotation UI created in Streamlit
### Can be used for binary or multilabel annotation
### Importing libraries
from streamlit.hashing import _CodeHasher
from streamlit.report_thread import get_report_ctx
from streamlit.server.server import Server
import streamlit a... |
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 | ### Hacked together by Johnson Thomas
### Annotation UI created in Streamlit
### Can be used for binary or multilabel annotation
### Importing libraries
from streamlit.hashing import _CodeHasher
from streamlit.report_thread import get_report_ctx
from streamlit.server.server import Server
import streamlit a... | (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 | ### Hacked together by Johnson Thomas
### Annotation UI created in Streamlit
### Can be used for binary or multilabel annotation
### Importing libraries
from streamlit.hashing import _CodeHasher
from streamlit.report_thread import get_report_ctx
from streamlit.server.server import Server
import streamlit a... |
def gen_desc_save(composition, echo, shape, margin, echogenic_foci, ind_no,file_to_anot):
comp = composition.capitalize()
if echogenic_foci =="none":
echo_foc = "no calcification or comet tail artiacts"
else:
echo_foc = echogenic_foci
desc = comp + " " + echo + " " + shape + " thyroid nodule with " ... | 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 | ### Hacked together by Johnson Thomas
### Annotation UI created in Streamlit
### Can be used for binary or multilabel annotation
| 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 | import {fabric} from 'fabric';
import * as actions from './actions';
import * as cst from '../constants';
import {PlantView} from './plantView';
import {ScoreInput} from './scoring/input';
const DEFAULT_IMAGE_WIDTH = 28;
const DEFAULT_IMAGE_HEIGHT = 28;
const SCROLLBAR_WIDTH = 26;
const DEFAULT_USER_WIDTH = 6;
const... | 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 | import {fabric} from 'fabric';
import * as actions from './actions';
import * as cst from '../constants';
import {PlantView} from './plantView';
import {ScoreInput} from './scoring/input';
const DEFAULT_IMAGE_WIDTH = 28;
const DEFAULT_IMAGE_HEIGHT = 28;
const SCROLLBAR_WIDTH = 26;
const DEFAULT_USER_WIDTH = 6;
const... |
$(`#${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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.