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 |
|---|---|---|---|---|
routex.go | package routex
import (
"broker"
"encoding/json"
"fmt"
"github.com/googollee/go-pubsub"
"github.com/googollee/go-rest"
"logger"
"math/rand"
"model"
"net/http"
"net/url"
"notifier"
"os"
"routex/model"
"sync"
"time"
)
type RouteMap struct {
rest.Service `prefix:"/v3/routex" mime:"application/json"`
up... | (ctx rest.Context, identity model.Identity) {
id := rmodel.Identity{
Identity: identity,
Type: "identity",
Action: "update",
}
m.pubsub.Publish(m.identityName(identity), id)
}
func (m RouteMap) UpdateExfee(ctx rest.Context, invitations model.Invitation) {
var crossId int64
var action string
ctx.Bind(... | UpdateIdentity | identifier_name |
routex.go | package routex
import (
"broker"
"encoding/json"
"fmt"
"github.com/googollee/go-pubsub"
"github.com/googollee/go-rest"
"logger"
"math/rand"
"model"
"net/http"
"net/url"
"notifier"
"os"
"routex/model"
"sync"
"time"
)
type RouteMap struct {
rest.Service `prefix:"/v3/routex" mime:"application/json"`
up... | if err := ctx.BindError(); err != nil {
ctx.Return(http.StatusBadRequest, err)
return
}
endAt, err := m.breadcrumbsRepo.GetWindowEnd(userId, crossId)
if err != nil {
logger.ERROR("get user %d cross %d routex failed: %s", userId, crossId, err)
ctx.Return(http.StatusInternalServerError, err)
return
}
ret ... | random_line_split | |
routex.go | package routex
import (
"broker"
"encoding/json"
"fmt"
"github.com/googollee/go-pubsub"
"github.com/googollee/go-rest"
"logger"
"math/rand"
"model"
"net/http"
"net/url"
"notifier"
"os"
"routex/model"
"sync"
"time"
)
type RouteMap struct {
rest.Service `prefix:"/v3/routex" mime:"application/json"`
up... |
func (m RouteMap) UpdateExfee(ctx rest.Context, invitations model.Invitation) {
var crossId int64
var action string
ctx.Bind("cross_id", &crossId)
ctx.Bind("action", &action)
if err := ctx.BindError(); err != nil {
ctx.Return(http.StatusBadRequest, err)
return
}
if action != "join" && action != "remove" {
... | {
id := rmodel.Identity{
Identity: identity,
Type: "identity",
Action: "update",
}
m.pubsub.Publish(m.identityName(identity), id)
} | identifier_body |
Checker_ruleunit_test.js | /******************************************************************************
Copyright:: 2020- IBM, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.o... | else if (legacyExpectedInfo) {
let expectedInfo = {}
let actualInfo = {}
for (const item of legacyExpectedInfo) {
if (checker.engine.getRule(mapGToRule[item.ruleId])) {
expectedInfo[item.... | {
let filtReport = [];
for (const issue of report.results) {
delete issue.node;
delete issue.ruleTime;
delete issue.bounds;
if (expectedInfo.ruleIds.includes(is... | conditional_block |
Checker_ruleunit_test.js | /******************************************************************************
Copyright:: 2020- IBM, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org... | // }
// // In the case that the expected rule rule to be triggered is not triggered then throw error as this test failed
// else if (!(expected.ruleId in actualMap)) {
// expect(false).toB... | // expect(typeof (actualMap[expected.ruleId])).toEqual('undefined', "\nShould trigger NO violations, but triggered for rule: " + expected.ruleId + " with " + actualMap[expected.ruleId]); | random_line_split |
shows_data.js | exports.showsData = [
{
"id": 1,
"name": "Theatre",
"info": "Theatre is a collaborative form of performing art that uses live performers, usually actors or actresses, to present the experience of a real or imagined event before a live audience in a specific place, often a stage. The performe... | name: "Wicked",
price: 32.50,
hotelPoints: 470,
photo: "https://image.nuevayork.es/wp-content/uploads/2014/11/Wicked-on-Broadway-Tickets.png.webp",
description: "Wicked, the Broadway sensation, looks at what happened in the Land of Oz…but from a different angle. Long before Dorot... | random_line_split | |
tool.js | //生产环境
window.myDomain = 'http://ai.aiknowsclauses.com/';
const baseURL = 'https://back.aiknowsclauses.com/';
const appId = 'wx2e03c5129c077bde';
const umengId = 1268531919;
//测试环境
// window.myDomain = 'https://ai.aijkang.com/';
// const baseURL = 'https://aikcback.aijkang.com/';
// const appId = 'wx923490c114577ba3';... | on() {
// 获取当前时间戳(以s为单位)
var timestamp = Date.parse(new Date()) / 1000;
var jsapi_ticket = window.jsapi_ticket;
var nonceStr = createNonceStr();
function createNonceStr() {
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var str = "";
for (var i = 0; i < 16; i++) {
var rando... | 签名的方法
util.getJssdkSign = functi | conditional_block |
tool.js | //生产环境
window.myDomain = 'http://ai.aiknowsclauses.com/';
const baseURL = 'https://back.aiknowsclauses.com/';
const appId = 'wx2e03c5129c077bde';
const umengId = 1268531919;
//测试环境
// window.myDomain = 'https://ai.aijkang.com/';
// const baseURL = 'https://aikcback.aijkang.com/';
// const appId = 'wx923490c114577ba3';... | identifier_name | ||
tool.js | //生产环境
window.myDomain = 'http://ai.aiknowsclauses.com/';
const baseURL = 'https://back.aiknowsclauses.com/';
const appId = 'wx2e03c5129c077bde';
const umengId = 1268531919;
//测试环境
// window.myDomain = 'https://ai.aijkang.com/';
// const baseURL = 'https://aikcback.aijkang.com/';
// const appId = 'wx923490c114577ba3';... | on.nonceStr = nonceStr;
json.signature = signature;
return json;
}
// 禁止微信分享
util.shareDeny = function() {
//禁止分享配置
wx.config({
debug: false,
appId: 'wx0cad77c43b1d74ce',
timestamp: 123123213,
nonceStr: '123123123',
signature: '123123123',
jsApiList: [
'hideOptionMenu',
]
});
wx.ready(function()... | a = new Uint8Array(encodeUTF8(string));
var result = sha1(data);
var signature = Array.prototype.map.call(result, function(e) {
return (e < 16 ? "0" : "") + e.toString(16);
}).join("");
// return出去
var json = {}
json.timestamp = timestamp;
js | identifier_body |
tool.js | //生产环境
window.myDomain = 'http://ai.aiknowsclauses.com/';
const baseURL = 'https://back.aiknowsclauses.com/';
const appId = 'wx2e03c5129c077bde';
const umengId = 1268531919;
//测试环境
// window.myDomain = 'https://ai.aijkang.com/';
// const baseURL = 'https://aikcback.aijkang.com/';
// const appId = 'wx923490c114577ba3';... | }
let output=input.replace(/ /g,'').replace(/ /g,'');
return output;
})
Vue.prototype.$store = {
}
// 向浏览历史堆栈中追加一个空锚点,用于防止浏览器回退关闭
Vue.prototype.pushHistory = function() {
let state = {
title: 'title',
url: '#'
}
window.history.pushState(state, "title", "#");
util.shareDeny();
}
window.ajaxRetryTimes=2... | return input; | random_line_split |
tf.js | function printPage(grid) {
var tableStr = '<table cellpadding="0" cellspacing="0" width="100%" id="statisticByDay">';
var cm = grid.getColumnModel();
var colCount = cm.getColumnCount();
var temp_obj = new Array();
// 只下载没有隐藏的列(isHidden()为true表示隐藏,其他都为显示)
// 临时数组,存放所有当前显示列的下标
for ( var i = 0; i < colCount; i++) {... | cm : new Ext.grid.ColumnModel(this.gridCm),
dblclickToggle : this.dblclickToggle,
contextmenuToggle : this.contextmenuToggle
});
this.items = [ this.grid ];
Ext.tf.SimplePanel.superclass.initComponent.call(this);
} catch (e) {
//console.log(e);
throw e;
}
},
// public
load : functi... | gridConfigEx : this.gridConfigEx,
store : this.store, | random_line_split |
tf.js | function | (grid) {
var tableStr = '<table cellpadding="0" cellspacing="0" width="100%" id="statisticByDay">';
var cm = grid.getColumnModel();
var colCount = cm.getColumnCount();
var temp_obj = new Array();
// 只下载没有隐藏的列(isHidden()为true表示隐藏,其他都为显示)
// 临时数组,存放所有当前显示列的下标
for ( var i = 0; i < colCount; i++) {// 从第三列开始,因为我的第1、2... | printPage | identifier_name |
tf.js | function printPage(grid) {
var tableStr = '<table cellpadding="0" cellspacing="0" width="100%" id="statisticByDay">';
var cm = grid.getColumnModel();
var colCount = cm.getColumnCount();
var temp_obj = new Array();
// 只下载没有隐藏的列(isHidden()为true表示隐藏,其他都为显示)
// 临时数组,存放所有当前显示列的下标
for ( var i = 0; i < colCount; i++) {... | ch(form.find("name", refName), function(field) {
field.setValue(v);
});
}
return this;
},
onDestroy : function() {
Ext.destroy(this.win, this.panel);
Ext.tf.PopSelect.superclass.onDestroy.call(this);
},
edit : function() {
var grid = this.panel.grid;
var store = this.panel.store;
var view = g... | t.tf.PopSelect = Ext.extend(Ext.form.TriggerField, {
triggerClass : 'x-form-date-trigger',
readOnly : true,
initComponent : function() {
Ext.tf.PopSelect.superclass.initComponent(this);
},
/**
* Find ref element, set value
*/
setRefName : function(v) {
var refName = this.refName || ''; // If not refNam... | conditional_block |
tf.js | function printPage(grid) | + ".00" : ((v * 10 == Math.floor(v * 10)) ? v
+ "0" : v);
v = String(v);
var ps = v.split('.');
var whole = ps[0];
var sub = ps[1] ? '.' + ps[1] : '.00';
var r = /(\d+)(\d{3})/;
while (r.test(whole)) {
whole = whole.replace(r, '$1' + ',' + '$2');
}
v = whole + sub;
if (v.charAt(0) == '-') {
return '-' ... | {
var tableStr = '<table cellpadding="0" cellspacing="0" width="100%" id="statisticByDay">';
var cm = grid.getColumnModel();
var colCount = cm.getColumnCount();
var temp_obj = new Array();
// 只下载没有隐藏的列(isHidden()为true表示隐藏,其他都为显示)
// 临时数组,存放所有当前显示列的下标
for ( var i = 0; i < colCount; i++) {// 从第三列开始,因为我的第1、2列是分别是ro... | identifier_body |
index.go | package stored
import (
"bytes"
"errors"
"fmt"
"reflect"
"github.com/apple/foundationdb/bindings/go/src/fdb"
"github.com/apple/foundationdb/bindings/go/src/fdb/directory"
"github.com/apple/foundationdb/bindings/go/src/fdb/subspace"
"github.com/apple/foundationdb/bindings/go/src/fdb/tuple"
"github.com/mmcloug... |
// ClearAll will remove all data for specific index
func (i *Index) ClearAll() error {
_, err := i.object.db.Transact(func(tr fdb.Transaction) (ret interface{}, e error) {
i.doClearAll(tr)
return
})
return err
}
// Reindex will reindex index data
func (i *Index) Reindex() {
i.ClearAll()
object := i.object
... | {
start, end := i.dir.FDBRangeKeys()
tr.ClearRange(fdb.KeyRange{Begin: start, End: end})
} | identifier_body |
index.go | package stored
import (
"bytes"
"errors"
"fmt"
"reflect"
"github.com/apple/foundationdb/bindings/go/src/fdb"
"github.com/apple/foundationdb/bindings/go/src/fdb/directory"
"github.com/apple/foundationdb/bindings/go/src/fdb/subspace"
"github.com/apple/foundationdb/bindings/go/src/fdb/tuple"
"github.com/mmcloug... | hash = hash[0:i.Geo] // Cutting hash to needed precision
}
key = append(key, hash)
} else {
//key = tuple.Tuple{indexValue}
for _, field := range i.fields {
indexValue := input.Get(field)
key = append(key, field.tupleElement(indexValue))
}
}
}
return
}
func (i *Index) needValueStore() ... | hash := geohash.Encode(lat, long)
if i.Geo < 12 { | random_line_split |
index.go | package stored
import (
"bytes"
"errors"
"fmt"
"reflect"
"github.com/apple/foundationdb/bindings/go/src/fdb"
"github.com/apple/foundationdb/bindings/go/src/fdb/directory"
"github.com/apple/foundationdb/bindings/go/src/fdb/subspace"
"github.com/apple/foundationdb/bindings/go/src/fdb/tuple"
"github.com/mmcloug... | () bool {
if i.handle != nil {
return true
}
return false
}
// getOldKey is just an wrapper around getKey, except case when index has handle, when it can be dynamically changed
func (i *Index) getOldKey(tr fdb.Transaction, primaryTuple tuple.Tuple, oldObject *Struct) (tuple.Tuple, error) {
if i.needValueStore() ... | needValueStore | identifier_name |
index.go | package stored
import (
"bytes"
"errors"
"fmt"
"reflect"
"github.com/apple/foundationdb/bindings/go/src/fdb"
"github.com/apple/foundationdb/bindings/go/src/fdb/directory"
"github.com/apple/foundationdb/bindings/go/src/fdb/subspace"
"github.com/apple/foundationdb/bindings/go/src/fdb/tuple"
"github.com/mmcloug... |
// nil means should not index this object
if key == nil {
return nil
}
if i.Unique {
previousPromise := tr.Get(i.dir.Pack(key))
tr.Set(i.dir.Pack(key), primaryTuple.Pack()) // will be cancelled in case of error
previousBytes, err := previousPromise.Get()
if err != nil {
return err
}
if len(prev... | { // no need to delete any inex than
return nil
} | conditional_block |
main.go | package main
import (
"flag"
"io"
"io/ioutil"
"os"
"path"
"runtime"
"strconv"
"context"
"expvar"
"fmt"
"net"
"net/http"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"encoding/json"
"github.com/gorilla/mux"
"github.com/quentin-m/etcd-cloud-operator/pkg/etcd"
"github.com/signalfx/gateway/config"
... | forwardConfig.Server = manager.server
forwardConfig.Client = manager.client
forwardConfig.ClusterName = loadedConfig.ClusterName
forwardConfig.AdditionalDimensions = datapoint.AddMaps(loadedConfig.AdditionalDimensions, forwardConfig.AdditionalDimensions)
forwarder, err := loader.Forwarder(forwardConfig)
if ... | for idx, forwardConfig := range loadedConfig.ForwardTo {
logCtx := log.NewContext(logger).With(logkey.Protocol, forwardConfig.Type, logkey.Direction, "forwarder") | random_line_split |
main.go | package main
import (
"flag"
"io"
"io/ioutil"
"os"
"path"
"runtime"
"strconv"
"context"
"expvar"
"fmt"
"net"
"net/http"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"encoding/json"
"github.com/gorilla/mux"
"github.com/quentin-m/etcd-cloud-operator/pkg/etcd"
"github.com/signalfx/gateway/config"
... | {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
} | identifier_body | |
main.go | package main
import (
"flag"
"io"
"io/ioutil"
"os"
"path"
"runtime"
"strconv"
"context"
"expvar"
"fmt"
"net"
"net/http"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"encoding/json"
"github.com/gorilla/mux"
"github.com/quentin-m/etcd-cloud-operator/pkg/etcd"
"github.com/signalfx/gateway/config"
... |
case "join":
mgr.logger.Log(fmt.Sprintf("joining cluster with etcd server name: %s", mgr.ServerConfig.Name))
if mgr.client, err = etcd.NewClient(mgr.targetCluster, etcd.SecurityConfig{}, true); err == nil {
mgr.logger.Log(fmt.Sprintf("joining etcd cluster @ %s", mgr.client.Endpoints()))
if err = mgr.server... | {
if !isStringInSlice(mgr.AdvertisedClientAddress(), mgr.targetCluster) {
mgr.targetCluster = append(mgr.targetCluster, mgr.AdvertisedClientAddress())
}
mgr.client, err = etcd.NewClient(mgr.targetCluster, etcd.SecurityConfig{}, true)
} | conditional_block |
main.go | package main
import (
"flag"
"io"
"io/ioutil"
"os"
"path"
"runtime"
"strconv"
"context"
"expvar"
"fmt"
"net"
"net/http"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"encoding/json"
"github.com/gorilla/mux"
"github.com/quentin-m/etcd-cloud-operator/pkg/etcd"
"github.com/signalfx/gateway/config"
... | (numProcs *int, gomaxprocs func(int) int) {
if numProcs != nil {
gomaxprocs(*numProcs)
} else {
numProcs := runtime.NumCPU()
gomaxprocs(numProcs)
}
}
func (p *gateway) gracefulShutdown() (err error) {
p.logger.Log("Starting graceful shutdown")
totalWaitTime := p.tk.After(*p.config.MaxGracefulWaitTimeDuratio... | setupGoMaxProcs | identifier_name |
ntd_utils.py |
# metaDatasetGenerator imports
from core.config import cfg, cfgData, createFilenameID, createPathRepeat, createPathSetID
from datasets.imdb import imdb
# 'other' imports
import pickle
import numpy as np
import numpy.random as npr
import os.path as osp
import matplotlib
matplotlib.use("Agg")
from core.config import ... |
def genConfDl(modelParams,dataType,roidbTr,roidbTe,loaderSettings,ntdGameInfo):
X_train, X_test, y_train, y_test, X_idx = roidbToDlData(roidbTr,roidbTe,
ntdGameInfo['trainSize'],
ntdGameInfo['... | X_train, X_test, y_train, y_test, X_idx = roidbToSVMData(roidbTr,roidbTe,
ntdGameInfo['trainSize'],
ntdGameInfo['testSize'],
loaderSettin... | identifier_body |
ntd_utils.py |
# metaDatasetGenerator imports
from core.config import cfg, cfgData, createFilenameID, createPathRepeat, createPathSetID
from datasets.imdb import imdb
# 'other' imports
import pickle
import numpy as np
import numpy.random as npr
import os.path as osp
import matplotlib
matplotlib.use("Agg")
from core.config import ... | (modelParams,dataType,roidbTr,roidbTe,loaderSettings,ntdGameInfo):
X_train, X_test, y_train, y_test, X_idx = roidbToDlData(roidbTr,roidbTe,
ntdGameInfo['trainSize'],
ntdGameInfo['testSize'],
... | genConfDl | identifier_name |
ntd_utils.py |
# metaDatasetGenerator imports
from core.config import cfg, cfgData, createFilenameID, createPathRepeat, createPathSetID
from datasets.imdb import imdb
# 'other' imports
import pickle
import numpy as np
import numpy.random as npr
import os.path as osp
import matplotlib
matplotlib.use("Agg")
from core.config import ... |
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model
def roidbToFeatures(roidb,pyl... | if phase == 'train':
scheduler.step()
model.train(True) # Set model to training mode
else:
model.train(False) # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for data... | conditional_block |
ntd_utils.py | # metaDatasetGenerator imports
from core.config import cfg, cfgData, createFilenameID, createPathRepeat, createPathSetID
from datasets.imdb import imdb
# 'other' imports
import pickle
import numpy as np
import numpy.random as npr
import os.path as osp
import matplotlib
matplotlib.use("Agg")
from core.config import c... | print("{}: {}".format(setID,len(yIndicies[setID])))
if len(yIndicies[setID]) == 0: continue
dsIdx = dsIndicies[setID] # index for l_feat_te
testIndex = yIndicies[setID][0] # index for x_test
X_test[testIndex] = l_feat_te[setID][dsIdx] # replace sample content
X_idx[te... | yIndicies[setID] = list(np.where(y_test == setID)[0]) # find where the setID's are | random_line_split |
spacetime.rs | // Copyright 2020 WHTCORPS INC
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, sof... | (attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder {
existing.get(&attribute_id)
.map(AttributeBuilder::to_modify_attribute)
.unwrap_or_else(AttributeBuilder::default)
}
// Group mutations by impacted solitonId.
let mut builders: BTreeMap<SolitonI... | attribute_builder_to_modify | identifier_name |
spacetime.rs | // Copyright 2020 WHTCORPS INC
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, sof... | fn attribute_builder_to_modify(attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder {
existing.get(&attribute_id)
.map(AttributeBuilder::to_modify_attribute)
.unwrap_or_else(AttributeBuilder::default)
}
// Group mutations by impacted solitonId.
l... | /// This is suiBlock for producing a `AttributeMap` from the `schemaReplicant` materialized view, which does not
/// contain install and alter markers.
///
/// Returns a report summarizing the mutations that were applied.
pub fn update_attribute_map_from_causetid_triples(attribute_map: &mut AttributeMap, assertions: Ve... | random_line_split |
spacetime.rs | // Copyright 2020 WHTCORPS INC
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, sof... | / Update a `SchemaReplicant` in place from the given `[e a typed_value added]` quadruples.
///
/// This layer enforces that causetid assertions of the form [solitonId :edb/causetid ...] (as distinct from
/// attribute assertions) are present and correct.
///
/// This is suiBlock for mutating a `SchemaReplicant` from an... | {
fn attribute_builder_to_modify(attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder {
existing.get(&attribute_id)
.map(AttributeBuilder::to_modify_attribute)
.unwrap_or_else(AttributeBuilder::default)
}
// Group mutations by impacted solitonId.
... | identifier_body |
spacetime.rs | // Copyright 2020 WHTCORPS INC
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, sof... | }
}
Ok(SpacetimeReport {
attributes_installed: attributes_installed,
attributes_altered: attributes_altered,
causetIds_altered: BTreeMap::default(),
})
}
/// Update a `SchemaReplicant` in place from the given `[e a typed_value added]` quadruples.
///
/// This layer enforces t... | builder.validate_alter_attribute().context(DbErrorKind::BadSchemaReplicantAssertion(format!("SchemaReplicant alteration for existing attribute with solitonId {} is not valid", solitonId)))?;
let mutations = builder.mutate(entry.get_mut());
attributes_altered.insert(solitonI... | conditional_block |
make.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Automatically generated file for compiling doconce documents.
"""
import sys, glob, os, shutil, subprocess, codecs, re
logfile = 'tmp_output.log' # store all output of all operating system commands
f = open(logfile, 'w'); f.close() # touch logfile so it can be append... | options += ' --keep_pygments_html_bg'
options += ' --html_output="%(name)s-%(postfi)s'
cmd = 'doconce format html %(name)s %(options)s ' % vars()
system(cmd)
cmd = 'doconce slides_html %(name)s-%(postfi)s reveal --html_slide_theme=%(theme)s'
system(cmd)
def deck_slides(name, options='', postf... | ygment_styles
combinations = recommended_html_styles_and_pygment_styles()
options += ' --pygments_html_style=%s' % combinations['reveal'][theme][0]
if '--keep_pygments_html_bg' not in options:
| conditional_block |
make.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Automatically generated file for compiling doconce documents.
"""
import sys, glob, os, shutil, subprocess, codecs, re
logfile = 'tmp_output.log' # store all output of all operating system commands
f = open(logfile, 'w'); f.close() # touch logfile so it can be append... | ce source.
"""
dofile = "thebook"
#spellcheck()
common_options = '--encoding=utf-8 --examples_as_exercises '
# --- HTML ---
common_html_options = ' '
# HTML Bootstrap
bootstrap_options = ' --html_style=bootswatch_readable --html_code_style=inherit --html_pre_style=inherit --toc_dep... | ocon | identifier_name |
make.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Automatically generated file for compiling doconce documents.
"""
import sys, glob, os, shutil, subprocess, codecs, re
logfile = 'tmp_output.log' # store all output of all operating system commands
f = open(logfile, 'w'); f.close() # touch logfile so it can be append... |
def spellcheck():
for filename in glob.glob('*.do.txt'):
if not filename.startswith('tmp'):
cmd = 'doconce spellcheck -d .dict4spell.txt %(filename)s' % vars()
system(cmd)
def latex(name,
latex_program='pdflatex', # or 'latex'
options='--latex_code_style=vrb... | """Run system command cmd using subprocess module."""
print cmd
try:
output = subprocess.check_output(cmd, shell=True,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print """Command
%s
failed""" % cmd
print 'Return cod... | identifier_body |
make.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Automatically generated file for compiling doconce documents.
"""
import sys, glob, os, shutil, subprocess, codecs, re
logfile = 'tmp_output.log' # store all output of all operating system commands
f = open(logfile, 'w'); f.close() # touch logfile so it can be append... | system(cmd)
for filename in [name, '._%s000' % name]:
print(filename)
cmd = u"doconce replace 'Read' 'Перейти к первой главе' %s.html".encode('utf-8') % filename
system(cmd)
cmd = u"doconce subst '.*Next.*' '' %s.html".encode('utf-8') % filename... | cmd = u"doconce replace '← Prev' '← Предыдущая глава' %s".encode('utf-8') % filename
system(cmd)
cmd = u"doconce replace 'Next →' ' Следующая глава →' %s".encode('utf-8') % filename | random_line_split |
init.rs | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{get_app, Target};
use crate::helpers::{config::get as get_tauri_config, template::JsonMap};
use crate::Result;
use handlebars::{Context, Handlebars, Helper, HelperRes... | r: &Helper,
_: &Handlebars,
ctx: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
out
.write(
util::unprefix_path(app_root(ctx)?, get_str(helper))
.map_err(|_| {
RenderError::new("Attempted to unprefix a path that wasn't in the app root dir.")
})?
... | path(
helpe | identifier_name |
init.rs | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{get_app, Target};
use crate::helpers::{config::get as get_tauri_config, template::JsonMap};
use crate::Result;
use handlebars::{Context, Handlebars, Helper, HelperRes... | #[allow(unused_variables)] non_interactive: bool,
#[allow(unused_variables)] reinstall_deps: bool,
skip_targets_install: bool,
) -> Result<App> {
let current_dir = current_dir()?;
let tauri_config = get_tauri_config(None)?;
let tauri_config_guard = tauri_config.lock().unwrap();
let tauri_config_ = tauri_... |
pub fn exec(
target: Target,
wrapper: &TextWrapper, | random_line_split |
init.rs | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{get_app, Target};
use crate::helpers::{config::get as get_tauri_config, template::JsonMap};
use crate::Result;
use handlebars::{Context, Handlebars, Helper, HelperRes... |
map.insert("tauri-binary", binary.to_string_lossy());
map.insert("tauri-binary-args", &build_args);
map.insert("tauri-binary-args-str", build_args.join(" "));
let app = match target {
// Generate Android Studio project
Target::Android => match AndroidEnv::new() {
Ok(_env) => {
let app =... | {
if let Some(npm_execpath) = var_os("npm_execpath").map(PathBuf::from) {
let manager_stem = npm_execpath.file_stem().unwrap().to_os_string();
let is_npm = manager_stem == "npm-cli";
let is_npx = manager_stem == "npx-cli";
binary = if is_npm {
"npm".into()
} else if is_npx {
... | conditional_block |
init.rs | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{get_app, Target};
use crate::helpers::{config::get as get_tauri_config, template::JsonMap};
use crate::Result;
use handlebars::{Context, Handlebars, Helper, HelperRes... | (
helper: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
out: &mut dyn Output,
) -> HelperResult {
out
.write(
&get_str_array(helper, |s| s.to_string())
.ok_or_else(|| RenderError::new("`join` helper wasn't given an array"))?
.join(", "),
)
.map_err(Into::into... | .write(&handlebars::html_escape(get_str(helper)))
.map_err(Into::into)
}
fn join | identifier_body |
consensus.rs | // Copyright 2020 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | }
/// Difficulty calculation based on a Weighted Target Exponential Moving Average
/// of difficulty, using the ratio of the last block time over the target block time.
pub fn next_wtema_difficulty<T>(_height: u64, cursor: T) -> HeaderInfo
where
T: IntoIterator<Item = HeaderInfo>,
{
let mut last_headers = cursor.int... | let difficulty = max(MIN_DMA_DIFFICULTY, diff_sum * BLOCK_TIME_SEC / adj_ts);
HeaderInfo::from_diff_scaling(Difficulty::from_num(difficulty), sec_pow_scaling) | random_line_split |
consensus.rs | // Copyright 2020 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | (actual: u64, goal: u64, damp_factor: u64) -> u64 {
(actual + (damp_factor - 1) * goal) / damp_factor
}
/// limit value to be within some factor from a goal
pub fn clamp(actual: u64, goal: u64, clamp_factor: u64) -> u64 {
max(goal / clamp_factor, min(actual, goal * clamp_factor))
}
/// Computes the proof-of-work di... | damp | identifier_name |
consensus.rs | // Copyright 2020 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | else {
// should not get here
1
}
}
/// Calculate block overage based on height and claimed BTCUtxos
pub fn calc_block_overage(height: u64) -> u64 {
if height == 0 {
0
} else if height <= get_epoch_start(2) {
(REWARD1 * height) + get_overage_offset_start_epoch(1)
} else if height <= get_epoch_start(3) {
... | {
get_epoch_start(9) * REWARD8
+ get_epoch_start(8) * REWARD7
+ get_epoch_start(7) * REWARD6
+ get_epoch_start(6) * REWARD5
+ get_epoch_start(5) * REWARD4
+ get_epoch_start(4) * REWARD3
+ get_epoch_start(3) * REWARD2
+ get_epoch_start(2) * REWARD1
+ REWARD0
} | conditional_block |
consensus.rs | // Copyright 2020 The Grin Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... |
/// Number of blocks used to calculate difficulty adjustment by Damped Moving Average
pub const DMA_WINDOW: u64 = HOUR_HEIGHT;
/// Difficulty adjustment half life (actually, 60s * number of 0s-blocks to raise diff by factor e) is 4 hours
pub const WTEMA_HALF_LIFE: u64 = 4 * HOUR_SEC;
/// Average time span of the DM... | {
version == header_version(height)
} | identifier_body |
lib.rs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | contents.push(' ');
column += 1;
}
last_pos = pos;
}
column += token.node.len();
contents.push_str(&token.node);
}
return contents;
}
pub fn span_to_cpp_directive(ecx: &ExtCtxt, span: Span) -> String {
let codemap = ecx.parse... |
// Pad the code such that the token remains on the same column
while column < pos.col.0 { | random_line_split |
lib.rs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | <'a>(ecx: &ExtCtxt<'a>,
span: Span,
tts: &[TokenTree]) -> PResult<'a, Function<L>> {
let mut parser = ecx.new_parser_from_tts(tts);
let args = if parser.check(&token::OpenDelim(token::Paren)) {
Some(try!(Self::parse_args(ecx, &mut parser)))
... | parse | identifier_name |
server.rs | use std::thread;
use std::sync::mpsc;
use websocket;
use websocket::{Message, Sender, Receiver};
use websocket::server::sender;
use websocket::stream::WebSocketStream;
use websocket::message::CloseData;
use std::io::prelude::*;
use std::fs::{OpenOptions, File};
use std::net::Shutdown;
use rustc_serialize::json::{Json, ... | (json: &Json) -> Self {
json.as_string().unwrap().to_owned()
}
}
impl<T: FromJson> FromJson for Vec<T> {
fn from_json(json: &Json) -> Self {
json.as_array().unwrap().iter().map(|t| FromJson::from_json(t)).collect()
}
}
#[derive(Debug, Clone)]
pub struct Event {
pub changes: Changes,
... | from_json | identifier_name |
server.rs | use std::thread;
use std::sync::mpsc;
use websocket;
use websocket::{Message, Sender, Receiver};
use websocket::server::sender;
use websocket::stream::WebSocketStream;
use websocket::message::CloseData;
use std::io::prelude::*;
use std::fs::{OpenOptions, File};
use std::net::Shutdown;
use rustc_serialize::json::{Json, ... |
}
#[derive(Debug, Clone)]
pub struct Event {
pub changes: Changes,
pub session: String,
}
impl ToJson for Event {
fn to_json(&self) -> Json {
Json::Object(vec![
("changes".to_string(), Json::Array(
self.changes.iter().map(|&(ref view_id, ref view_changes)| {
... | {
json.as_array().unwrap().iter().map(|t| FromJson::from_json(t)).collect()
} | identifier_body |
server.rs | use std::thread;
use std::sync::mpsc;
use websocket;
use websocket::{Message, Sender, Receiver};
use websocket::server::sender;
use websocket::stream::WebSocketStream;
use websocket::message::CloseData;
use std::io::prelude::*;
use std::fs::{OpenOptions, File};
use std::net::Shutdown;
use rustc_serialize::json::{Json, ... | ("changes".to_string(), Json::Array(
self.changes.iter().map(|&(ref view_id, ref view_changes)| {
Json::Array(vec![
view_id.to_json(),
view_changes.fields.to_json(),
view_changes.insert.to_json(),
... | Json::Object(vec![ | random_line_split |
index.js | import { app, BrowserWindow, ipcMain, shell } from 'electron'
import Config from '../../static/js/config'
const Store = require('electron-store')
let store = new Store()
const path = require('path')
const { Parser } = require('m3u8-parser')
const fs = require('fs')
const async = require('async')
const dateFormat = req... | pTimeout, https: {rejectUnauthorized: false}}).catch((error) => { console.log(error) })
if(response == null || response.body == null || response.body == '')
{
return;
}
let parser = new Parser();
parser.push(response.body);
parser.end();
//并发 3 个线程下载
var tsQueues = async.queue(queue_callback, 3);
let count... | , timeout: htt | identifier_name |
index.js | import { app, BrowserWindow, ipcMain, shell } from 'electron'
import Config from '../../static/js/config'
const Store = require('electron-store')
let store = new Store()
const path = require('path')
const { Parser } = require('m3u8-parser')
const fs = require('fs')
const async = require('async')
const dateFormat = req... | else
{
key_uri = partent_uri + segment.key.uri;
}
}
await download (key_uri, that.dir, { filename: "aes.key" }).catch(console.error);
}
if(fs.existsSync( aes_path ))
{
try {
let key_ = fs.readFileSync( aes_path );
let iv_ = segment.key.iv != n... | random_line_split | |
index.js | import { app, BrowserWindow, ipcMain, shell } from 'electron'
import Config from '../../static/js/config'
const Store = require('electron-store')
let store = new Store()
const path = require('path')
const { Parser } = require('m3u8-parser')
const fs = require('fs')
const async = require('async')
const dateFormat = req... | .mkdirSync(dir, { recursive: true });
}
const response = await got(url, {headers: headers, timeout: httpTimeout, https: {rejectUnauthorized: false}}).catch((error) => { console.log(error) })
if(response == null || response.body == null || response.body == '')
{
return;
}
let parser = new Parser();
parser.push... | [];
if(!fs.existsSync(dir))
{
fs | conditional_block |
state.go | package views
import (
"errors"
"regexp"
"strings"
"sync"
"sync/atomic"
)
// excessStops is a regexp for matching more than one fullstops in the state address which then gets replaced into a single fullstop
var excessStops = regexp.MustCompile(`.\+`)
// ErrStateNotFound is returned when the state address is ina... | () States {
co := se.curr
if co == nil {
// return se.owner
return nil
}
return co.Engine().State()
}
// Partial renders the partial of the last state of the state address
func (se *StateEngine) Partial(addr string) error {
points, err := se.prepare(addr)
if err != nil {
return err
}
return se.trajec... | State | identifier_name |
state.go | package views
import (
"errors"
"regexp"
"strings"
"sync"
"sync/atomic"
)
// excessStops is a regexp for matching more than one fullstops in the state address which then gets replaced into a single fullstop
var excessStops = regexp.MustCompile(`.\+`)
// ErrStateNotFound is returned when the state address is ina... |
atomic.StoreInt64(&s.active, 0)
s.do.Lock()
if s.deactivator != nil {
s.deactivator()
}
s.do.Unlock()
}
// acceptable checks if the state matches the current point
func (s *State) acceptable(addr string, point string) bool {
if s.optionalValidator == nil {
if addr == point {
return true
}
return fal... | {
return
} | conditional_block |
state.go | package views
import (
"errors"
"regexp"
"strings"
"sync"
"sync/atomic"
)
// excessStops is a regexp for matching more than one fullstops in the state address which then gets replaced into a single fullstop
var excessStops = regexp.MustCompile(`.\+`)
// ErrStateNotFound is returned when the state address is ina... |
// UseActivator assigns the state a new active respone handler
func (s *State) UseActivator(so StateResponse) States {
s.ro.Lock()
s.activator = so
s.ro.Unlock()
return s
}
// OverrideValidator assigns an validator to perform custom matching of the state
func (s *State) OverrideValidator(so StateValidator) State... | {
s.do.Lock()
s.deactivator = so
s.do.Unlock()
return s
} | identifier_body |
state.go | package views
import (
"errors"
"regexp"
"strings"
"sync"
"sync/atomic"
)
// excessStops is a regexp for matching more than one fullstops in the state address which then gets replaced into a single fullstop
var excessStops = regexp.MustCompile(`.\+`)
// ErrStateNotFound is returned when the state address is ina... | func (se *StateEngine) getAddr(s States) string {
se.rw.RLock()
defer se.rw.RUnlock()
return se.states[s]
}
func (se *StateEngine) get(addr string) States {
se.rw.RLock()
defer se.rw.RUnlock()
for sm, ao := range se.states {
if ao != addr {
continue
}
return sm
}
return nil
}
func (se *StateEngin... | stop = true
})
}
}
| random_line_split |
mpsc.rs | //! A multi-producer, single-consumer, futures-aware, FIFO queue with back
//! pressure, for use communicating between tasks on the same thread.
//!
//! These queues are the same as those in `futures::sync`, except they're not
//! intended to be sent across threads.
use std::any::Any;
use std::cell::RefCell;
use std::... | (&mut self, msg: T) -> StartSend<T, SendError<T>> {
self.do_send(msg)
}
fn poll_complete(&mut self) -> Poll<(), SendError<T>> {
Ok(Async::Ready(()))
}
fn close(&mut self) -> Poll<(), SendError<T>> {
Ok(Async::Ready(()))
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut sel... | start_send | identifier_name |
mpsc.rs | //! A multi-producer, single-consumer, futures-aware, FIFO queue with back
//! pressure, for use communicating between tasks on the same thread.
//!
//! These queues are the same as those in `futures::sync`, except they're not
//! intended to be sent across threads.
use std::any::Any;
use std::cell::RefCell;
use std::... | ///
/// An unbounded buffer is used, which means that values will be buffered as
/// fast as `stream` can produce them, without any backpressure. Therefore, if
/// `stream` is an infinite stream, it can use an unbounded amount of memory, and
/// potentially hog CPU resources. In particular, if `stream` is infinite
/// ... | /// When `stream` has additional items available, then the `SpawnHandle`
/// will have those same items available. | random_line_split |
mpsc.rs | //! A multi-producer, single-consumer, futures-aware, FIFO queue with back
//! pressure, for use communicating between tasks on the same thread.
//!
//! These queues are the same as those in `futures::sync`, except they're not
//! intended to be sent across threads.
use std::any::Any;
use std::cell::RefCell;
use std::... |
}
impl<T> Stream for UnboundedReceiver<T> {
type Item = T;
type Error = ();
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
self.0.poll()
}
}
/// Creates an unbounded in-memory channel with buffered storage.
///
/// Identical semantics to `channel`, except with no limit to buff... | {
self.0.close();
} | identifier_body |
drafts.go | /*
* Copyright 2018-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | return *bp, nil
}
func (r RegistryBuildpackLoader) loadBuildpackImage(ref string, to io.Writer) error {
reference, err := name.ParseReference(ref)
if err != nil {
return fmt.Errorf("unable to parse reference for existing buildpack tag\n%w", err)
}
auth := authn.Anonymous
if r.GCRToken != "" {
auth = google.... | random_line_split | |
drafts.go | /*
* Copyright 2018-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
func (g GithubBuildpackLoader) fetchTOMLFile(org, repo, version, path string) ([]byte, error) {
fmt.Println("Fetching from org:", org, "repo:", repo, "version:", version, "path:", path)
body, _, err := g.GithubClient.Repositories.DownloadContents(
context.Background(),
org,
repo,
path,
&github.RepositoryC... | {
paths := []string{
"/buildpack.toml",
}
org = strings.ToUpper(strings.ReplaceAll(org, "-", "_"))
repo = strings.ToUpper(strings.ReplaceAll(repo, "-", "_"))
if p, found := os.LookupEnv(fmt.Sprintf("BP_TOML_PATH_%s_%s", org, repo)); found {
if !strings.HasSuffix(p, "/buildpack.toml") {
p = fmt.Sprintf("%s... | identifier_body |
drafts.go | /*
* Copyright 2018-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | (ref string, to io.Writer) error {
reference, err := name.ParseReference(ref)
if err != nil {
return fmt.Errorf("unable to parse reference for existing buildpack tag\n%w", err)
}
auth := authn.Anonymous
if r.GCRToken != "" {
auth = google.NewJSONKeyAuthenticator(r.GCRToken)
}
img, err := remote.Image(refer... | loadBuildpackImage | identifier_name |
drafts.go | /*
* Copyright 2018-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
}
return Buildpack{}, fmt.Errorf("unable to load buildpack.toml for %s", imgUri)
}
func (g GithubBuildpackLoader) LoadPackages(imgUri string) (Package, error) {
uris, err := g.mapURIs(imgUri)
if err != nil {
return Package{}, fmt.Errorf("unable to map URIs\n%w", err)
}
for _, uri := range uris {
uriPatte... | {
tomlBytes, err := g.fetchTOMLFile(org, repo, version, path)
if err != nil {
var apiErr *github.ErrorResponse
if errors.As(err, &apiErr) && apiErr.Response.StatusCode == 404 {
fmt.Println("skipping 404", apiErr)
continue
}
return Buildpack{}, fmt.Errorf("unable to fetch toml\n%w", err)
... | conditional_block |
utility.js | //............................................................................Send AjaxRequest Without Object/parameter
//...................................................Recommanded for Get Request
SendAjaxRequest = (ApiUrl, RequestType) =>
{
let ajaxConfig = {
url: ApiBaseUrl(ApiUrl),
type: Req... | return true;
}
//..........................Contact validation
let contact_validate = (value) => {
let contact = value
var regexPattern = new RegExp(/^\d{4}[- ]?\d{7}$/); // regular expression pattern
let isValid = regexPattern.test(contact);
if (!isValid) {
return false;
}
return... | return false;
}
| conditional_block |
utility.js | //............................................................................Send AjaxRequest Without Object/parameter
//...................................................Recommanded for Get Request
SendAjaxRequest = (ApiUrl, RequestType) =>
{
let ajaxConfig = {
url: ApiBaseUrl(ApiUrl),
type: Req... | ableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function (from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table... | ger(t | identifier_name |
utility.js | //............................................................................Send AjaxRequest Without Object/parameter
//...................................................Recommanded for Get Request
SendAjaxRequest = (ApiUrl, RequestType) =>
{
let ajaxConfig = {
url: ApiBaseUrl(ApiUrl),
type: Req... | },
error: (XMLHttpRequest, textStatus, errorThrown) => {
return errorThrown;
}
}
$.ajax(ajaxConfig)
}
//............................................................................Section Textbox/Labels/div handling
//..................return Textbox Value
let getTextboxV... | random_line_split | |
utility.js | //............................................................................Send AjaxRequest Without Object/parameter
//...................................................Recommanded for Get Request
SendAjaxRequest = (ApiUrl, RequestType) =>
{
let ajaxConfig = {
url: ApiBaseUrl(ApiUrl),
type: Req... | .........................................................................Section Days Name With Id's
//.................get today by using day id
let getToday = (day) => {
switch (day) {
case 1:
return "Monday"
break;
case 2:
return "Tuesday"
break;
... |
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function (from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (... | identifier_body |
Server.go | package server
import (
networkapi "github.com/juzi5201314/MineGopher/api/network"
raknetapi "github.com/juzi5201314/MineGopher/api/network/raknet"
"github.com/juzi5201314/MineGopher/api/player"
api "github.com/juzi5201314/MineGopher/api/server"
"github.com/juzi5201314/MineGopher/level"
"github.com/juzi5201314/M... | }
for _, session := range server.SessionManager.GetSessions() {
session.Tick()
}
for range server.LevelManager.GetLevels() {
//level.Tick()
}
server.tick++
}
func (server *Server) GetCommandManager() command {
return server.CommandManager
}
**/
func (server *Server) Tick() {
for _, p := range server.G... | if server.tick%20 == 0 {
server.QueryManager.SetQueryResult(server.GenerateQueryResult())
server.NetworkAdapter.GetRakLibManager().PongData = server.GeneratePongData() | random_line_split |
Server.go | package server
import (
networkapi "github.com/juzi5201314/MineGopher/api/network"
raknetapi "github.com/juzi5201314/MineGopher/api/network/raknet"
"github.com/juzi5201314/MineGopher/api/player"
api "github.com/juzi5201314/MineGopher/api/server"
"github.com/juzi5201314/MineGopher/level"
"github.com/juzi5201314/M... | () {
for _, p := range server.GetAllPlayer() {
p.Tick()
}
}
func (server *Server) mkdirs() {
os.Mkdir(server.playersPath, 0700)
os.Mkdir(server.pluginPath, 0700)
//os.Mkdir(server.behaviorPacksPath, 0700)
os.Mkdir(server.resourecePackPath, 0700)
os.Mkdir(server.worldsPath, 0700)
os.Mkdir(server.themePath, 07... | Tick | identifier_name |
Server.go | package server
import (
networkapi "github.com/juzi5201314/MineGopher/api/network"
raknetapi "github.com/juzi5201314/MineGopher/api/network/raknet"
"github.com/juzi5201314/MineGopher/api/player"
api "github.com/juzi5201314/MineGopher/api/server"
"github.com/juzi5201314/MineGopher/level"
"github.com/juzi5201314/M... |
func (server *Server) GetLevel(name string) *level.Level {
return server.levels[name]
}
func (server *Server) GetDefaultLevel() *level.Level {
return server.GetLevel(server.defaultLevel)
}
func (server *Server) GetPath() string {
return server.serverPath
}
func (server *Server) ScheduleRepeatingTask(fn func(), ... | {
return server.levels
} | identifier_body |
Server.go | package server
import (
networkapi "github.com/juzi5201314/MineGopher/api/network"
raknetapi "github.com/juzi5201314/MineGopher/api/network/raknet"
"github.com/juzi5201314/MineGopher/api/player"
api "github.com/juzi5201314/MineGopher/api/server"
"github.com/juzi5201314/MineGopher/level"
"github.com/juzi5201314/M... |
}()
return ticker
}
func (server *Server) ScheduleDelayedTask(fn func(), d time.Duration) *time.Timer {
return time.AfterFunc(d, fn)
}
/*
// GetMinecraftVersion returns the latest Minecraft game version.
// It is prefixed with a 'v', for example: "v1.2.10.1"
func (server *Server) GetMinecraftVersion() string {
r... | {
fn()
} | conditional_block |
stopwords.rs | use lazy_static::lazy_static;
use std::collections::{HashMap, HashSet};
lazy_static! {
/// ignore these as keywords
pub(crate) static ref STOPWORDS: HashSet<&'static str> = [
"a", "sys", "ffi", "placeholder", "app", "loops", "master", "library", "rs",
"accidentally", "additional", "adds", "against", "a... | } | ].iter().copied().collect(); | random_line_split |
rasterbackend.rs | use crate::aabb::*;
use crate::mesh::*;
use crate::picture::*;
use crate::zbuffer::*;
use std::f32::consts::PI;
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct RenderOptions {
pub view_pos: Vec3,
pub light_pos: Vec3,
pub light_color: Vec3,
pub ambient_color: Vec3,
pub model_color: ... | w0 * v0.y + w1 * v1.y + w2 * v2.y,
w0 * v0.z + w1 * v1.z + w2 * v2.z,
);
// fragment position in world space
let fp = Vec3::new(
w0 * v0m.x + w1 * v1m.x + w2 * v2m... | random_line_split | |
rasterbackend.rs | use crate::aabb::*;
use crate::mesh::*;
use crate::picture::*;
use crate::zbuffer::*;
use std::f32::consts::PI;
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct RenderOptions {
pub view_pos: Vec3,
pub light_pos: Vec3,
pub light_color: Vec3,
pub ambient_color: Vec3,
pub model_color: ... |
fn view_projection(&self, zoom: f32) -> Mat4 {
// calculate view projection matrix
let proj = glm::ortho(
zoom * 0.5 * self.aspect_ratio,
-zoom * 0.5 * self.aspect_ratio,
-zoom * 0.5,
zoom * 0.5,
0.0,
1.0,
);
l... | {
Self {
render_options: RenderOptions::default(),
width,
height,
aspect_ratio: width as f32 / height as f32,
}
} | identifier_body |
rasterbackend.rs | use crate::aabb::*;
use crate::mesh::*;
use crate::picture::*;
use crate::zbuffer::*;
use std::f32::consts::PI;
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct RenderOptions {
pub view_pos: Vec3,
pub light_pos: Vec3,
pub light_color: Vec3,
pub ambient_color: Vec3,
pub model_color: ... | (
&self,
mesh: impl IntoIterator<Item = Triangle> + Copy,
model_scale: f32,
aabb: &AABB,
timeout: Option<Duration>,
) -> Picture {
let start_time = Instant::now();
let mut pic = Picture::new(self.width, self.height);
let mut zbuf = ZBuffer::new(self.w... | render | identifier_name |
rasterbackend.rs | use crate::aabb::*;
use crate::mesh::*;
use crate::picture::*;
use crate::zbuffer::*;
use std::f32::consts::PI;
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct RenderOptions {
pub view_pos: Vec3,
pub light_pos: Vec3,
pub light_color: Vec3,
pub ambient_color: Vec3,
pub model_color: ... |
pic
}
}
fn edge_fn(a: &Vec2, b: &Vec2, c: &Vec2) -> f32 {
(c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x)
}
fn scale_for_unitsize(mvp: &Mat4, aabb: &AABB) -> f32 {
let edges = [
matmul(&mvp, &Vec3::new(aabb.lower.x, aabb.lower.y, aabb.lower.z)),
matmul(&mvp, &Vec3::new(aabb... | {
let margin = 3;
let text_to_height_ratio = 16;
let text = format!(
"{}x{}x{}",
aabb.size().x as i32,
aabb.size().y as i32,
aabb.size().z as i32
);
let text_size = pic.height() / text_to_height... | conditional_block |
mod.rs | use crate::{
data::{Key, Metakey, Value},
error::*,
Aggregator, AggregatorState, Backend, Handle, MapState, Reducer, ReducerState, ValueState,
VecState,
};
use rocksdb::{
checkpoint::Checkpoint, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, Options,
SliceTransform, WriteBatch, WriteOpt... | (&self, cf_name: &str, opts: Options) -> Result<()> {
if self.db().cf_handle(cf_name).is_none() {
self.db_mut().create_cf(cf_name, &opts)?;
}
Ok(())
}
}
fn common_options<IK, N>() -> Options
where
IK: Metakey,
N: Metakey,
{
let prefix_size = IK::SIZE + N::SIZE;
... | create_column_family | identifier_name |
mod.rs | use crate::{
data::{Key, Metakey, Value},
error::*,
Aggregator, AggregatorState, Backend, Handle, MapState, Reducer, ReducerState, ValueState,
VecState,
};
use rocksdb::{
checkpoint::Checkpoint, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, Options,
SliceTransform, WriteBatch, WriteOpt... |
checkpointer.create_checkpoint(checkpoint_path)?;
Ok(())
}
fn register_value_handle<'s, T: Value, IK: Metakey, N: Metakey>(
&'s self,
handle: &'s mut Handle<ValueState<T>, IK, N>,
) {
handle.registered = true;
let opts = common_options::<IK, N>();
s... | {
// TODO: add a warning log here
// warn!(logger, "Checkpoint path {:?} exists, deleting");
fs::remove_dir_all(checkpoint_path)?
} | conditional_block |
mod.rs | use crate::{
data::{Key, Metakey, Value},
error::*,
Aggregator, AggregatorState, Backend, Handle, MapState, Reducer, ReducerState, ValueState,
VecState,
};
use rocksdb::{
checkpoint::Checkpoint, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, Options,
SliceTransform, WriteBatch, WriteOpt... |
impl Backend for Rocks {
fn name(&self) -> &str {
self.name.as_str()
}
fn create(path: &Path, name: String) -> Result<Self>
where
Self: Sized,
{
let mut opts = Options::default();
opts.create_if_missing(true);
let path: PathBuf = path.into();
if !p... | {
let prefix_size = IK::SIZE + N::SIZE;
let mut opts = Options::default();
// for map state to work properly, but useful for all the states, so the bloom filters get
// populated
opts.set_prefix_extractor(SliceTransform::create_fixed_prefix(prefix_size as usize));
opts
} | identifier_body |
mod.rs | use crate::{
data::{Key, Metakey, Value},
error::*,
Aggregator, AggregatorState, Backend, Handle, MapState, Reducer, ReducerState, ValueState,
VecState,
};
use rocksdb::{
checkpoint::Checkpoint, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, Options,
SliceTransform, WriteBatch, WriteOpt... | }
checkpointer.create_checkpoint(checkpoint_path)?;
Ok(())
}
fn register_value_handle<'s, T: Value, IK: Metakey, N: Metakey>(
&'s self,
handle: &'s mut Handle<ValueState<T>, IK, N>,
) {
handle.registered = true;
let opts = common_options::<IK, N>();
... | // TODO: add a warning log here
// warn!(logger, "Checkpoint path {:?} exists, deleting");
fs::remove_dir_all(checkpoint_path)? | random_line_split |
index.ts | import transport from './transport'
import modules, { RokkaApi } from './apis'
import RokkaResponse, {
RokkaResponse as RokkaResponseInterface,
} from './response'
import { stringify } from 'query-string'
import FormData from 'form-data'
import user, {
ApiTokenGetCallback,
ApiTokenPayload,
ApiTokenSetCallback,
... | maxTimeout?: number // maximum milliseconds between retries (default: 10000)
randomize?: boolean // randomize time between retries (default: true)
agent?: any
}
}
interface RequestOptions {
headers?: object
noAuthHeaders?: boolean
fallBackToText?: boolean
form?: boolean
multipart?: boolean
fo... | minTimeout?: number // minimum milliseconds between retries (default: 1000) | random_line_split |
index.ts | import transport from './transport'
import modules, { RokkaApi } from './apis'
import RokkaResponse, {
RokkaResponse as RokkaResponseInterface,
} from './response'
import { stringify } from 'query-string'
import FormData from 'form-data'
import user, {
ApiTokenGetCallback,
ApiTokenPayload,
ApiTokenSetCallback,
... | ,
}
return Object.assign({}, modules(state))
}
| {
let uri = [options.host || state.apiHost, path].join('/')
if (
queryParams &&
!(
Object.entries(queryParams).length === 0 &&
queryParams.constructor === Object
)
) {
uri += '?' + stringify(queryParams)
}
const headers: {
'Api-V... | identifier_body |
index.ts | import transport from './transport'
import modules, { RokkaApi } from './apis'
import RokkaResponse, {
RokkaResponse as RokkaResponseInterface,
} from './response'
import { stringify } from 'query-string'
import FormData from 'form-data'
import user, {
ApiTokenGetCallback,
ApiTokenPayload,
ApiTokenSetCallback,
... | (
method: string,
path: string,
payload: any | null = null,
queryParams: {
[key: string]: string | number | boolean
} | null = null,
options: RequestOptions = {
noAuthHeaders: false,
fallBackToText: false,
forceUseApiKey: false,
noTokenRefresh:... | request | identifier_name |
index.ts | import transport from './transport'
import modules, { RokkaApi } from './apis'
import RokkaResponse, {
RokkaResponse as RokkaResponseInterface,
} from './response'
import { stringify } from 'query-string'
import FormData from 'form-data'
import user, {
ApiTokenGetCallback,
ApiTokenPayload,
ApiTokenSetCallback,
... |
if (
requestOptions.json &&
requestOptions.body &&
typeof requestOptions.body === 'object'
) {
requestOptions.body = JSON.stringify(requestOptions.body)
}
const t = transport(uri, requestOptions)
return t.then(
async (response: Response): Promise<... | {
const formData = payload.formData || {}
const requestData = new FormData()
requestData.append(payload.name, payload.contents, payload.filename)
Object.keys(formData).forEach(function (meta) {
requestData.append(meta, JSON.stringify(formData[meta]))
})
reque... | conditional_block |
test-checkpoint.py | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# Dependencies\n",
"from bs4 import BeautifulSoup\n",
"import requests\n",
"import pandas as pd\n",
"import pymongo\n",
"import time\n",
"import numpy as np\n",
"from s... | "source": [
"# Retrieve the parent divs for all headlines and preview text\n",
"results = soup.find_all(\"div\", class_=\"list_text\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
... | random_line_split | |
app.component.ts | import { Component } from '@angular/core';
import { MatFormFieldControl, MatFormField } from '@angular/material';
import { SearchService } from './search.service';
declare var google: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export c... |
async select(i) {
this.selectedNo = i;
var place = this.searchresults[i];
var newMarker = this.markers[i];
var me = this;
var img = './assets/images/service.jpg';
if( place.photos && place.photos.length > 0) {
img = place.photos[0].getUrl();
}
let placeDeatil : any = await me.getPla... | {
var me = this;
var pyrmont = new google.maps.LatLng(this.currentLat, this.currentLng);
var request = {
location: pyrmont,
radius: this.radius,
type: ['fitness'],
query: this.additionalFilter + ' ' + this.searchFitnessService
};
// this.isLoading = true;
this.searchresults = [];
var ... | identifier_body |
app.component.ts | import { Component } from '@angular/core';
import { MatFormFieldControl, MatFormField } from '@angular/material';
import { SearchService } from './search.service';
declare var google: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export c... | (value) {
if(value == "no") {return;}
// alert(this.additionalFilter);
this.search();
}
changedRadius(value){
if(value == "") {return;}
this.search();
}
async getPlacesDetails() {
var me = this;
var count = 0;
this.searchresults.forEach(async function(place) {
if(place.detail) ret... | onChangeAdditionalFilter | identifier_name |
app.component.ts | import { Component } from '@angular/core';
import { MatFormFieldControl, MatFormField } from '@angular/material';
import { SearchService } from './search.service';
declare var google: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export c... |
async getPlacesDetails() {
var me = this;
var count = 0;
this.searchresults.forEach(async function(place) {
if(place.detail) return true;
count ++;
var placeDetail = await me.getPlaceDetails(place.place_id);
place.detail = placeDetail;
});
if(count != 0) {
var timer = setTime... | if(value == "") {return;}
this.search();
} | random_line_split |
reading.rs | use crate::{protocols::ReturnableConnection, Pea2Pea};
use async_trait::async_trait;
use tokio::{
io::{AsyncRead, AsyncReadExt},
sync::mpsc,
time::sleep,
};
use tracing::*;
use std::{io, net::SocketAddr, time::Duration};
/// Can be used to specify and enable reading, i.e. receiving inbound messages.
/// ... |
}
| {
// don't do anything by default
Ok(())
} | identifier_body |
reading.rs | use crate::{protocols::ReturnableConnection, Pea2Pea};
use async_trait::async_trait;
use tokio::{
io::{AsyncRead, AsyncReadExt},
sync::mpsc,
time::sleep,
};
use tracing::*;
use std::{io, net::SocketAddr, time::Duration};
/// Can be used to specify and enable reading, i.e. receiving inbound messages.
/// ... | (&self, source: SocketAddr, message: Self::Message) -> io::Result<()> {
// don't do anything by default
Ok(())
}
}
| process_message | identifier_name |
reading.rs | use crate::{protocols::ReturnableConnection, Pea2Pea};
use async_trait::async_trait;
use tokio::{
io::{AsyncRead, AsyncReadExt},
sync::mpsc,
time::sleep,
};
use tracing::*;
use std::{io, net::SocketAddr, time::Duration};
/// Can be used to specify and enable reading, i.e. receiving inbound messages.
/// ... | buffer: &[u8],
) -> io::Result<Option<(Self::Message, usize)>>;
/// Processes an inbound message. Can be used to update state, send replies etc.
#[allow(unused_variables)]
async fn process_message(&self, source: SocketAddr, message: Self::Message) -> io::Result<()> {
// don't do anythin... | &self,
source: SocketAddr, | random_line_split |
reading.rs | use crate::{protocols::ReturnableConnection, Pea2Pea};
use async_trait::async_trait;
use tokio::{
io::{AsyncRead, AsyncReadExt},
sync::mpsc,
time::sleep,
};
use tracing::*;
use std::{io, net::SocketAddr, time::Duration};
/// Can be used to specify and enable reading, i.e. receiving inbound messages.
/// ... | else {
node.disconnect(addr);
break;
}
}
});
conn.tasks.push(inbound_processing_task);
// the task for reading messages from a stream
... | {
if let Err(e) = processing_clone.process_message(addr, msg).await {
error!(parent: node.span(), "can't process an inbound message: {}", e);
node.known_peers().register_failure(addr);
... | conditional_block |
lib.rs | // Copyright 2018 Torsten Weber
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according t... |
fn cause(&self) -> Option<&error::Error> {
match *self {
ReadError::Io(ref err) => Some(err),
ReadError::Nom(_) => None,
}
}
}
/// A struct for process information
///
/// This is the per process information contained in the `init` section
/// of `lhe` files.
/// When r... | {
match *self {
ReadError::Io(..) => &"Failed to read the lhe file with an IO error",
ReadError::Nom(..) => &"Failed to read the lhe file with a parse error",
}
} | identifier_body |
lib.rs | // Copyright 2018 Torsten Weber
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according t... | self.color_1,
self.color_2,
self.momentum.px,
self.momentum.py,
self.momentum.pz,
self.momentum.e,
self.mass,
self.proper_lifetime,
self.spin
)
}
}
#[cfg(test)]
impl Arbitrary for Particle {
fn a... | self.mother_2_id, | random_line_split |
lib.rs | // Copyright 2018 Torsten Weber
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according t... | (input: &[u8]) -> nom::IResult<&[u8], Particle> {
do_parse!(
input,
pdg_id: ws!(parse_i64) >> status: ws!(parse_i64) >> mother_1_id: ws!(parse_i64)
>> mother_2_id: ws!(parse_i64) >> color_1: ws!(parse_i64)
>> color_2: ws!(parse_i64) >> px: ws!(parse_f64) >... | read_lhe | identifier_name |
TEST.py | import sys
if not hasattr(sys, 'argv'):
sys.argv = ['']
from CNN import model as model
from UTILS import *
# from cnn_n import saveImg
from shutil import copyfile
tplt1 = "{0:^30}\t{1:^10}\t{2:^10}\t{3:^10}\t{4:^10}" #\t{4:^10}\t{5:^10}
tplt2 = "{0:^30}\t{1:^10}\t{2:^10}"
model_set = {
'''所用模型'''
"CNN2... | e:
print("Invalid Inputs.")
exit(0)
return original_ycbcr, gt_y, fileName_list
class Predict:
input_tensor = None
output_tensor = None
model = None
def __init__(self, model, modelpath):
self.graph = tf.Graph() # 为每个类(实例)单独创建一个graph
self.model = model
with... | _list = load_file_list(fileOrDir[0])
test_list = get_train_list(load_file_list(fileOrDir[0]), load_file_list(fileOrDir[1]))
for pair in test_list:
filesize = os.path.getsize(pair[0])
picsize = getWH(pair[0])[0]*getWH(pair[0])[0] * 3 // 2
numFrames = filesize // picsiz... | conditional_block |
TEST.py | import sys
if not hasattr(sys, 'argv'):
sys.argv = ['']
from CNN import model as model
from UTILS import *
# from cnn_n import saveImg
from shutil import copyfile
tplt1 = "{0:^30}\t{1:^10}\t{2:^10}\t{3:^10}\t{4:^10}" #\t{4:^10}\t{5:^10}
tplt2 = "{0:^30}\t{1:^10}\t{2:^10}"
model_set = {
'''所用模型'''
"CNN2... | n17, cnn27, cnn37, cnn47, cnn7, cnn57
if QP < 17:
R = cnn7.predict(file)
elif 17 <= QP < 27:
R = cnn17.predict(file)
elif 27 <= QP < 37:
R = cnn27.predict(file)
elif 37 <= QP < 47:
R = cnn37.predict(file)
elif 47 <= QP < 57:
R = cnn47.predict(file)
else:
... | dict(model,model_set["CNN_I_QP7"])
cnn17=Predict(model,model_set["CNN_I_QP17"])
cnn27=Predict(model,model_set["CNN_I_QP27"])
cnn37=Predict(model,model_set["CNN2_I_QP37"])
cnn47=Predict(model,model_set["CNN_I_QP47"])
cnn57 = Predict(model, model_set["CNN_I_QP57"])
def predict(file, QP, frame_t... | identifier_body |
TEST.py | import sys
if not hasattr(sys, 'argv'):
sys.argv = ['']
from CNN import model as model
from UTILS import *
# from cnn_n import saveImg
from shutil import copyfile
tplt1 = "{0:^30}\t{1:^10}\t{2:^10}\t{3:^10}\t{4:^10}" #\t{4:^10}\t{5:^10}
tplt2 = "{0:^30}\t{1:^10}\t{2:^10}"
model_set = {
'''所用模型'''
"CNN2... | self.graph = tf.Graph() # 为每个类(实例)单独创建一个graph
self.model = model
with self.graph.as_default():
self.input_tensor = tf.placeholder(tf.float32, shape=(1, None, None, 1))
#self.output_tensor = tf.make_template('input_scope', self.model)(self.input_tensor)
self.o... | model = None
def __init__(self, model, modelpath): | random_line_split |
TEST.py | import sys
if not hasattr(sys, 'argv'):
sys.argv = ['']
from CNN import model as model
from UTILS import *
# from cnn_n import saveImg
from shutil import copyfile
tplt1 = "{0:^30}\t{1:^10}\t{2:^10}\t{3:^10}\t{4:^10}" #\t{4:^10}\t{5:^10}
tplt2 = "{0:^30}\t{1:^10}\t{2:^10}"
model_set = {
'''所用模型'''
"CNN2... | if (isinstance(fileOrDir, str)):
original_ycbcr, gt_y, fileName_list = prepare_test_data(fileOrDir)
imgY = original_ycbcr[0][0]
elif type(fileOrDir) is np.ndarray:
imgY = fileOrDir
imgY = normalize(np.reshape(fileOrDir, (1, len(fileOrDir), len(fileOrDir[0]), 1)... | identifier_name | |
lib.rs | use byteorder::{ByteOrder, LittleEndian};
use num_derive::FromPrimitive;
use solana_program::{
account_info::next_account_info,
account_info::AccountInfo,
decode_error::DecodeError,
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
program_pack::{Pack, Sealed},
... |
if bet_amount == 0 {
msg!("Inavalid Bet");
return Err(DiceErr::InvalidBet.into());
}
let lucky_number:u8 = 20;
println!("Result {}", lucky_number);
let mut win_amount:u32 = 0;
if (1 == roll_type && lucky_number <= threshold) || (2 == roll_type && lucky_number >= threshold) {
... | {
msg!("Not Enough Balance");
return Err(DiceErr::NotEnoughBalance.into());
} | conditional_block |
lib.rs | use byteorder::{ByteOrder, LittleEndian};
use num_derive::FromPrimitive;
use solana_program::{
account_info::next_account_info,
account_info::AccountInfo,
decode_error::DecodeError,
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
program_pack::{Pack, Sealed},
... | let sysvar_account = next_account_info(accounts_iter)?;
let rent = &Rent::from_account_info(sysvar_account)?;
if !sysvar::rent::check_id(sysvar_account.key) {
msg!("Rent system account is not rent system account");
return Err(ProgramError::InvalidAccountData);
}
if !rent.is_exempt(pl... | }
// The account must be rent exempt, i.e. live forever | random_line_split |
lib.rs | use byteorder::{ByteOrder, LittleEndian};
use num_derive::FromPrimitive;
use solana_program::{
account_info::next_account_info,
account_info::AccountInfo,
decode_error::DecodeError,
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
program_pack::{Pack, Sealed},
... | {
#[error("Unexpected Roll Mode")]
UnexpectedRollMode,
#[error("Incrrect Threshold")]
IncorrectThreshold,
#[error("Incorrect Owner")]
IncorrectOwner,
#[error("Account Not Rent Exempt")]
AccountNotRentExempt,
#[error("Account Not Balance Account")]
AccountNotBalanceAccount,
#... | DiceErr | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.