file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
client_conn.rs | self.process_common_message(common),
ClientToWriteMessage::WaitForHandshake(tx) => {
// ignore error
drop(tx.send(Ok(())));
Ok(())
}
}
}
}
impl<I> Conn<ClientTypes<I>>
where
I: AsyncWrite + AsyncRead + Send + 'static,
{
fn pro... | {
warn!("invalid headers: {:?}: {:?}", e, headers);
self.send_rst_stream(stream_id, ErrorCode::ProtocolError)?;
return Ok(None);
} | conditional_block | |
cassandra.go | instance of the Cassandra publisher
// Client is not initiated until the first data publish happends.
func NewCassandraPublisher() *CassandraPublisher {
return &CassandraPublisher{}
}
// CassandraPublisher defines Cassandra publisher
type CassandraPublisher struct {
client *cassaClient
}
// GetConfigPolicy returns... | {
errorMsg := fmt.Sprintf("Invalid data type for a key %s", key)
err := errors.New(errorMsg)
log.Error(err)
} | conditional_block | |
cassandra.go | data
func Meta() *plugin.PluginMeta {
return plugin.NewPluginMeta(name, version, pluginType, []string{plugin.SnapGOBContentType},
[]string{plugin.SnapGOBContentType}, plugin.RoutingStrategy(plugin.StickyRouting), plugin.ConcurrencyCount(1))
}
// NewCassandraPublisher returns an instance of the Cassandra publisher
... | handleErr | identifier_name | |
cassandra.go | Meta {
return plugin.NewPluginMeta(name, version, pluginType, []string{plugin.SnapGOBContentType},
[]string{plugin.SnapGOBContentType}, plugin.RoutingStrategy(plugin.StickyRouting), plugin.ConcurrencyCount(1))
}
// NewCassandraPublisher returns an instance of the Cassandra publisher
// Client is not initiated until... | func handleErr(e error) {
if e != nil { | random_line_split | |
cassandra.go | Rule.Description = "Path to the CA certificate for the Cassandra server"
config.Add(caPathRule)
certPathRule, err := cpolicy.NewStringRule(certPathRuleKey, false, "")
handleErr(err)
certPathRule.Description = "Path to the self signed certificate for the Cassandra client"
config.Add(certPathRule)
connectionTimeo... | {
logger := log.WithFields(log.Fields{
"plugin-name": name,
"plugin-version": version,
"plugin-type": pluginType.String(),
})
// default
log.SetLevel(log.WarnLevel)
if debug, ok := config["debug"]; ok {
switch v := debug.(type) {
case ctypes.ConfigValueBool:
if v.Value {
log.SetLevel(log.D... | identifier_body | |
gmssl_test.go | iv
}
// SMS4-CBC Encrypt/Decrypt
func TestSMS4CBC(t *testing.T) {
/* Generate random key and IV */
key := randomKey()
iv := randomIV()
rawContent := []byte("hello")
encrypt, err := gmssl.NewCipherContext(gmssl.SMS4, key, iv, true)
PanicError(err)
ciphertext1, err := encrypt.Update(rawContent)
PanicError(err)
... | MQ4wDAYDVQQDDAVQS1VDQTAeFw0xNzA2MDEwMDAwMDBaFw0yMDA2MDEwMDAwMDBa
MEYxCzAJBgNVBAYTAkNOMQswCQYDVQQIDAJCSjEMMAoGA1UECgwDUEtVMQswCQYD
VQQLDAJDQTEPMA0GA1UEAwwGYW50c3NzMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0D
QgAEHpXtrYNlwesl7IyPuaHKKHqn4rHBk+tCU0l0T+zuBNMHAOJzKNDbobno6gOI
EQlVfC9q9 | /* Certificate */
certpem := `-----BEGIN CERTIFICATE-----
MIICAjCCAaigAwIBAgIBATAKBggqgRzPVQGDdTBSMQswCQYDVQQGEwJDTjELMAkG
A1UECAwCQkoxCzAJBgNVBAcMAkJKMQwwCgYDVQQKDANQS1UxCzAJBgNVBAsMAkNB | random_line_split |
gmssl_test.go | ]string{
{"rsa_keygen_bits", "2048"},
{"rsa_keygen_pubexp", "65537"},
}
rsa, err := gmssl.GeneratePrivateKey("RSA", rsaArgs, nil)
PanicError(err)
rsaPem, err := rsa.GetPublicKeyPEM()
PanicError(err)
fmt.Println(rsaPem)
}
func TestEngineCommands(t *testing.T) {
engines := gmssl.GetEngineNames()
for _, engi... | BenchmarkSM2Sign | identifier_name | |
gmssl_test.go | iv
}
// SMS4-CBC Encrypt/Decrypt
func TestSMS4CBC(t *testing.T) | PanicError(err)
plaintext := make([]byte, 0, len(plaintext1)+len(plaintext2))
plaintext = append(plaintext, plaintext1...)
plaintext = append(plaintext, plaintext2...)
if string(plaintext) != string(rawContent) {
t.Fatalf("decrypt result should be %s, but got %s", rawContent, plaintext)
}
fmt.Printf("sms4_cb... | {
/* Generate random key and IV */
key := randomKey()
iv := randomIV()
rawContent := []byte("hello")
encrypt, err := gmssl.NewCipherContext(gmssl.SMS4, key, iv, true)
PanicError(err)
ciphertext1, err := encrypt.Update(rawContent)
PanicError(err)
ciphertext2, err := encrypt.Final()
PanicError(err)
ciphertext ... | identifier_body |
gmssl_test.go |
}
// SMS4-CBC Encrypt/Decrypt
func TestSMS4CBC(t *testing.T) {
/* Generate random key and IV */
key := randomKey()
iv := randomIV()
rawContent := []byte("hello")
encrypt, err := gmssl.NewCipherContext(gmssl.SMS4, key, iv, true)
PanicError(err)
ciphertext1, err := encrypt.Update(rawContent)
PanicError(err)
ci... |
fmt.Printf("sms4_cbc(%s) = %x\n", plaintext, ciphertext)
}
func TestSMS4ECB(t *testing.T) {
key := randomKey()
rawContent := []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}
ciphertext, err := gmssl.CipherECBenc(rawContent, key)
PanicError(err)
fmt.Print... | {
t.Fatalf("decrypt result should be %s, but got %s", rawContent, plaintext)
} | conditional_block |
mod.rs | SubscriptionCursor},
};
pub use crate::nakadi_types::Error;
mod typed;
pub use typed::*;
/// Information on the current batch passed to a `BatchHandler`.
///
/// The `frame_id` is monotonically increasing for each `BatchHandler`
/// within a stream(same `StreamId`)
/// as long a s a dispatch strategy which keeps th... | )?,
}
Ok(())
}
}
/// A factory that creates `BatchHandler`s.
///
/// # Usage
///
/// A `BatchHandlerFactory` can be used in two ways:
///
/// * It does not contain any state it shares with the created `BatchHandler`s.
/// This is useful when incoming data is partitioned in a way that a... | event_type_partition.partition() | random_line_split |
mod.rs | SubscriptionCursor},
};
pub use crate::nakadi_types::Error;
mod typed;
pub use typed::*;
/// Information on the current batch passed to a `BatchHandler`.
///
/// The `frame_id` is monotonically increasing for each `BatchHandler`
/// within a stream(same `StreamId`)
/// as long a s a dispatch strategy which keeps th... | (&self) -> Option<&EventTypeName> {
self.event_type_and_partition().0
}
pub fn partition(&self) -> Option<&PartitionId> {
self.event_type_and_partition().1
}
pub fn event_type_and_partition(&self) -> (Option<&EventTypeName>, Option<&PartitionId>) {
match self {
Hand... | event_type | identifier_name |
ebest.py | ] = row_res
self.waiting = False
def query(res, send, cont=False, timeout=10):
""" Query 요청
@arg res[str]`t1102` 사용할 res 파일명
@arg send[dict] 전송할 데이터
{
'Block1': [{'Field1': 'Value1', 'Field2': 'Value2'}, {...}, {...}],
'Block2': {'Fi... | n', 'high', 'low | identifier_name | |
ebest.py | list(send.values())[0]
if not (
isinstance (send_first_value, list) or
isinstance (send_first_value, dict)
):
send = { '{}InBlock'.format(res): send }
# 전송할 데이터를 설정
for block in send.keys():
if isinstance(send[block], dict):
for (k, v) in send[block].ite... | conditional_block | ||
ebest.py | 그인 실패 : {}'.format(msg))
def OnDisconnect(self):
""" 서버와의 연결이 끊어졌을 때 실행되는 함수
"""
self.waiting = False
logger.info('[*] 서버와의 연결이 끊어졌습니다')
_session = DispatchWithEvents('XA_Session.XASession', _SessionHandler)
def login(
server=None,
username=None,
password=... |
self.subscribed_keys.append(key)
def unsubscirbe(self, key=None):
if key is None:
self._instance.UnadviseRealData()
else:
if key not in self.subscr | identifier_body | |
ebest.py | ' : _session.GetAcctNickname(acc_no)
})
return accounts
def account(index=0):
""" 계좌번호
@arg index[*int=0] 불러올 계좌의 순번
"""
return _session.GetAccountList(index)
""" Query
"""
_query_status = {}
class _QueryHandler:
def __init__(self):
self.response = {}
s... | cts_time = ' '
while True:
response = query('t8412', {
'shcode': shcode, | random_line_split | |
rbac_utils.py | License for the specific language governing permissions and limitations
# under the License.
from contextlib import contextmanager
import sys
import time
from oslo_log import log as logging
from oslo_log import versionutils
from oslo_utils import excutils
from tempest import clients
from tempest.common import cr... | (cls):
if not CONF.patrole.enable_rbac:
deprecation_msg = ("The `[patrole].enable_rbac` option is "
"deprecated and will be removed in the S "
"release. Patrole tests will always be enabled "
"following inst... | skip_rbac_checks | identifier_name |
rbac_utils.py | License for the specific language governing permissions and limitations
# under the License.
from contextlib import contextmanager
import sys
import time
from oslo_log import log as logging
from oslo_log import versionutils
from oslo_utils import excutils
from tempest import clients
from tempest.common import cr... |
admin_role_id = None
rbac_role_id = None
@contextmanager
def override_role(self, test_obj):
"""Override the role used by ``os_primary`` Tempest credentials.
Temporarily change the role used by ``os_primary`` credentials to:
* ``[patrole] rbac_test_role`` before test executio... | """Constructor for ``RbacUtils``.
:param test_obj: An instance of `tempest.test.BaseTestCase`.
"""
# Intialize the admin roles_client to perform role switching.
admin_mgr = clients.Manager(
credentials.get_configured_admin_credentials())
if test_obj.get_identity_vers... | identifier_body |
rbac_utils.py | License for the specific language governing permissions and limitations
# under the License.
from contextlib import contextmanager
import sys
import time
from oslo_log import log as logging
from oslo_log import versionutils
from oslo_utils import excutils
from tempest import clients
from tempest.common import cr... |
if not rbac_role_id:
missing_roles.append(CONF.patrole.rbac_test_role)
msg += " Following roles were not found: %s." % (
", ".join(missing_roles))
msg += " Available roles: %s." % ", ".join(list(role_map.keys()))
raise rbac_exceptions.Rbac... | missing_roles.append(CONF.identity.admin_role) | conditional_block |
rbac_utils.py | License for the specific language governing permissions and limitations
# under the License.
from contextlib import contextmanager
import sys
import time
from oslo_log import log as logging
from oslo_log import versionutils
from oslo_utils import excutils
from tempest import clients
from tempest.common import cr... |
:param test_obj: instance of :py:class:`tempest.test.BaseTestCase`
:param toggle_rbac_role: Boolean value that controls the role that
overrides default role of ``os_primary`` credentials.
* If True: role is set to ``[patrole] rbac_test_role``
* If False: role is set ... | random_line_split | |
lib.rs | use std::num::ParseIntError;
use std::{error, iter};
use std::fmt;
use serde_json;
use serde_with::{ serde_as, DefaultOnError };
use crate::ParseError::MissingNode;
use lazy_static::lazy_static; // 1.3.0
use regex::Regex;
use serde::{Deserializer, Deserialize, Serialize, de};
use serde_json::{Error, Value};
use web_s... | use peg;
use chrono::NaiveDate; | random_line_split | |
lib.rs | )
}
}
}
// Everything from the end of the keypad down to depth, as truncated
// For forex -> chi -> states -> etc
// keypath = [CHI], depth = 1 => chi at root, all of the states under it, and nothing else
fn subtree_for_node<T: AsRef<str>>(&self, key_path: &[T], depth: u32) -> ... | {
match self {
Node::Line((name, _)) => re.is_match(name),
_ => false,
}
} | identifier_body | |
lib.rs | fn | (&self) -> Box<dyn Iterator<Item = &T> + '_> {
match self {
SingleOrMany::None => Box::new(iter::empty()),
SingleOrMany::Single(elem) => Box::new(iter::once(elem)),
SingleOrMany::Many(elems) => Box::new(elems.iter()),
}
}
}
#[wasm_bindgen]
#[derive(Deserialize, D... | values | identifier_name |
lib.rs | ize(depth - 1)).collect::<Vec<D3Node>>();
let values = stream.iter().map(|x| x.children_value()).collect::<Vec<f64>>();
let total: f64 = values.iter().sum();
let mut keptTotal: f64 = 0.0;
let mut kept: Vec<D3Node> = stream.iter().enumerate(... | {
// create list
seen.push(name);
map.insert(name.to_string(), serde_json::Value::Array(vec![prior.clone(), object.clone()]));
} | conditional_block | |
prepareApply-submit-list.component.ts | }
taxrateTotalFun=function(){//税率相关值 计算
if (typeof(this.rate) == "undefined" || this.rate == null) {
this.windowService.alert({ message: "税率未选择", type: "warn" });
} else {
this._purchaseData.taxAmount = Number((this._purchaseData.untaxAmount * (1 + Number(this.rate))).toFixe... | len--; | random_line_split | |
prepareApply-submit-list.component.ts | ;//币种
@Input() purchaseRequisitioIid:'';//采购申请id
@Input() isSubmit=false;//是否提交
@Input() set setHasContract(value){//读入预下采购申请类型 有合同-true,无合同-false
this.hasContract=value;
if(value){//有合同
this.clospanNum=12;
}else{
this.clospanNum=11;
}
}
@Input... | }
}
CheckIndeterminate(v) {//检查是否全选
this.fullCheckedIndeterminate = v;
}
calculateTotal(index) {//改变数量和单价时
let item = this._purchaseData.procurementList[index];
if (item.Count && item.Price) {
let num = item.Count * item.Price;
item.Amount = Number... | y(this.contractList) != window.localStorage.getItem("prepareContractList")) {//合同列表变化
this.contractList = JSON.parse(window.localStorage.getItem("prepareContractList"));
if(this.contractList && this.contractList.length){
this.contractListLength=this.contractList.length;
... | identifier_body |
prepareApply-submit-list.component.ts | this.onPurchaseDataChange.emit(this._purchaseData);
break;
case "currencyChange":
this.currencyDiffeFun();
break;
case "numberChange":
this.numAmount = 0;
this._purchaseData.untaxAmount = 0;
... | em:"",
index:""
}
let len=this.contractList.length;
let i;let item;
for(i=0;i<len;i++){
item=this.contractList[i];
if(item.SC_Code==scCode){
list.em=item;
list.index=i;
return list;
| conditional_block | |
prepareApply-submit-list.component.ts | 0;
this._purchaseData.taxAmount = 0;
this._purchaseData.foreignAmount = 0;
this.tempAmountPrice=0;
this._purchaseData.procurementList.forEach(item => {
if (item.Count) {
this.numAmount = Number(this.numAmount + ... | identifier_name | ||
action.go |
// DisplayMode is the configured display mode
func (a *Action) DisplayMode() string {
return a.Display
}
// AggregateResultJSON receives a JSON reply and aggregate all the data found in it
func (a *Action) AggregateResultJSON(jres []byte) error {
res := make(map[string]interface{})
err := json.Unmarshal(jres, &r... | {
output, ok := a.Output[o]
return output, ok
} | identifier_body | |
action.go | .Output[o]
return output, ok
}
// DisplayMode is the configured display mode
func (a *Action) DisplayMode() string {
return a.Display
}
// AggregateResultJSON receives a JSON reply and aggregate all the data found in it
func (a *Action) AggregateResultJSON(jres []byte) error {
res := make(map[string]interface{})
... | }
converted, err := ValToDDLType(input.Type, v)
if err != nil {
return result, warnings, fmt.Errorf("invalid value for '%s': %s", kname, err)
}
w, err := a.ValidateInputValue(kname, converted)
warnings = append(warnings, w...)
if err != nil {
return result, warnings, fmt.Errorf("invalid value for ... | random_line_split | |
action.go | .Output[o]
return output, ok
}
// DisplayMode is the configured display mode
func (a *Action) DisplayMode() string {
return a.Display
}
// AggregateResultJSON receives a JSON reply and aggregate all the data found in it
func (a *Action) AggregateResultJSON(jres []byte) error {
res := make(map[string]interface{})
... |
}
}
return result, warnings, nil
}
// ValidateRequestJSON receives request data in JSON format and validates it against the DDL
func (a *Action) ValidateRequestJSON(req json.RawMessage) (warnings []string, err error) {
reqdata := make(map[string]interface{})
err = json.Unmarshal(req, &reqdata)
if err != nil {... | {
result[iname] = input.Default
} | conditional_block |
action.go | .Output[o]
return output, ok
}
// DisplayMode is the configured display mode
func (a *Action) DisplayMode() string {
return a.Display
}
// AggregateResultJSON receives a JSON reply and aggregate all the data found in it
func (a *Action) AggregateResultJSON(jres []byte) error {
res := make(map[string]interface{})
... | (results map[string]interface{}) {
for _, k := range a.OutputNames() {
_, ok := results[k]
if ok {
continue
}
if a.Output[k].Default != nil {
results[k] = a.Output[k].Default
}
}
}
// RequiresInput reports if an input is required
func (a *Action) RequiresInput(input string) bool {
i, ok := a.Input[... | SetOutputDefaults | identifier_name |
bg.js | urls.push(url);
sample_urls.push(sampUrl);
urls_downloaded.push(false);
}
// called by some of the context menu options.
function addToList(info, tab) {
var url;
var type;
if(info.menuItemId == con1) // image
{
url = info.srcUrl;
listPush(url);
}
}
function addFromThumbnai... | () {
stopDownloadsFlag = true;
for(var i = dlItems.length-1 ; i >= 0 ; i-- )
{
if(dlItems[i].state != "complete")
chrome.downloads.cancel(dlItems[i]);
}
}
// recursive helper. Downloads til the end, but does 1 at a time. Uses dlItems array to help if downloads
// need to be cancele... | stopDownloads | identifier_name |
bg.js | .push(url);
sample_urls.push(sampUrl);
urls_downloaded.push(false);
}
// called by some of the context menu options.
function addToList(info, tab) {
var url;
var type;
if(info.menuItemId == con1) // image
{
url = info.srcUrl;
listPush(url);
}
}
function addFromThumbnails(in... |
// same as above, but with the parameter as the list.
function downloadEnclosed(these_urls) {
stopDownloadsFlag = false;
dlItems.length = 0;
downloadHelper(these_urls, 0);
}
// Boolean flag that lets user stop downloads (communicates to inside the callback in downloadHelper)
var stopDownloadsFlag = fals... | {
stopDownloadsFlag = false;
dlItems.length = 0;
downloadHelper(urls, 0);
} | identifier_body |
bg.js | urls.push(url);
sample_urls.push(sampUrl);
urls_downloaded.push(false);
}
// called by some of the context menu options.
function addToList(info, tab) {
var url;
var type;
if(info.menuItemId == con1) // image
{
url = info.srcUrl;
listPush(url);
}
}
function addFromThumb... | random_line_split | ||
panel.go | p.thirdIndex)
if dateLen == 0 || !date.Before(p.dates[dateLen-1]) {
p.dates = append(p.dates, date)
p.values = append(p.values, value)
} else {
insertP := sort.Search(dateLen, func(i int) bool {
return p.dates[i].After(date)
})
newDates := make([]time.Time, dateLen+1)
newValues := make([][][]float64, ... | n data on index
func (p *TimePanel) IGet(i int) *DataFrame {
if p == nil {
return nil
}
if i < 0 {
i += p.Length()
}
if i < 0 || i >= len(p.dates) {
return nil
}
return NewDataFrame(p.values[i], p.secondIndex, p.thirdIndex)
}
//IDate return date on index
func (p *TimePanel) IDate(i int) time.Time {
if p ... | et retur | identifier_name |
panel.go | , p.thirdIndex)
if dateLen == 0 || !date.Before(p.dates[dateLen-1]) {
p.dates = append(p.dates, date)
p.values = append(p.values, value)
} else {
insertP := sort.Search(dateLen, func(i int) bool {
return p.dates[i].After(date)
})
newDates := make([]time.Time, dateLen+1)
newValues := make([][][]float64,... | until; i++ {
p.values[i] = nil
p.dates[i] = time.Time{}
}
p.values = p.values[until:]
p.dates = p.dates[until:]
}
//Get get the first DataFrame one big or equal to date
func (p *TimePanel) Get(date time.Time) (*DataFrame, time.Time) {
i := sort.Search(len(p.dates), func(i int) bool {
return !p.dates[i].Bef... | ntil int) {
if until < 0 {
until = 0
}
if until > p.Length() {
until = p.Length()
}
for i := 0; i < | identifier_body |
panel.go | , p.thirdIndex)
if dateLen == 0 || !date.Before(p.dates[dateLen-1]) {
p.dates = append(p.dates, date)
p.values = append(p.values, value)
} else {
insertP := sort.Search(dateLen, func(i int) bool {
return p.dates[i].After(date)
})
newDates := make([]time.Time, dateLen+1)
newValues := make([][][]float64,... | tHead cut value head until
func (p *TimePanel) CutHead(until time.Time) {
i := sort.Search(len(p.dates), func(i int) bool {
return !p.dates[i].Before(until)
})
p.ICutHead(i)
}
//ICutHead cut value head until
func (p *TimePanel) ICutHead(until int) {
if until < 0 {
until = 0
}
if until > p.Length() {
until ... | .thirdIndex,
}
}
//Cu | conditional_block |
panel.go | , p.thirdIndex)
if dateLen == 0 || !date.Before(p.dates[dateLen-1]) {
p.dates = append(p.dates, date)
p.values = append(p.values, value)
} else {
insertP := sort.Search(dateLen, func(i int) bool {
return p.dates[i].After(date)
})
newDates := make([]time.Time, dateLen+1)
newValues := make([][][]float64,... | if j > len(p.dates) {
j = len(p.dates)
}
if i > j {
i = j
}
return &TimePanel{
values: p.values[i:j],
dates: p.dates[i:j],
secondIndex: p.secondIndex,
thirdIndex: p.thirdIndex,
}
}
//CutHead cut value head until
func (p *TimePanel) CutHead(until time.Time) {
i := sort.Search(len(p.dates)... | //ISlice get port of TimePanel result >=i <j
func (p *TimePanel) ISlice(i, j int) TimePanelRO {
if i < 0 {
i = 0
} | random_line_split |
iter.rs | is u32 not usize because it is not reasonable to
/// have more than u32::MAX strings in a program, and it is widely used
/// - recommend variable name `id` or `string_id`
#[derive(Eq, PartialEq, Clone, Copy, Hash)]
pub struct IsId(NonZeroU32);
impl IsId {
pub(super) const POSITION_MASK: u32 = 1 << 31;
pub... | get_file_id | identifier_name | |
iter.rs | fn add(self, rhs: Position) -> Span {
debug_assert!(rhs.0 >= self.end.0, "invalid span + position");
Span{ start: self.start, end: rhs }
}
}
// use `span += position` to update span
impl AddAssign<Position> for Span {
fn add_assign(&mut self, rhs: Position) {
debug_assert!(rhs.0 >= sel... | fn get_endlines(content: &str) -> Vec<usize> {
content.char_indices().filter(|(_, c)| c == &'\n').map(|(i, _)| i).collect()
}
// this iterator is the exact first layer of processing above source code content,
// logically all location information comes from position created by the next function
//
// this iterato... | hasher.finish()
}
// get LF byte indexes | random_line_split |
iter.rs | fn add(self, rhs: Position) -> Span {
debug_assert!(rhs.0 >= self.end.0, "invalid span + position");
Span{ start: self.start, end: rhs }
}
}
// use `span += position` to update span
impl AddAssign<Position> for Span {
fn add_assign(&mut self, rhs: Position) {
debug_assert!(rhs.0 >= sel... |
}
// this is currently an u128, but I suspect that it can fit in u64
// for current small test until even first bootstrap version, the string id and span should be easily fit in u64
// for "dont-know-whether-exist very large program",
// considering these 2 ids increase accordingly, squash `u32::MAX - id` and span t... | {
f.debug_tuple("IsId").field(&self.0.get()).finish()
} | identifier_body |
settings_class.py | import DataStore, ParseError
from npc.util.functions import merge_data_dicts, prepend_namespace
from .tags import make_deprecated_tag_specs
from .helpers import quiet_parse
from .systems import System
import logging
logger = logging.getLogger(__name__)
class Settings(DataStore):
"""Core settings class
On in... | (self, key: str) -> System:
"""Get a system object for the given system key
Creates a System object using the definition from the given key. If the key does not have a
definition, returns None.
Args:
key (str): System key name to use
Returns:
System: Sy... | get_system | identifier_name |
settings_class.py | .util import DataStore, ParseError
from npc.util.functions import merge_data_dicts, prepend_namespace
from .tags import make_deprecated_tag_specs
from .helpers import quiet_parse
from .systems import System
import logging
logger = logging.getLogger(__name__)
class Settings(DataStore):
"""Core settings class
... | The sheet_path property is handled specially. If it's present in a type's yaml, then that value is
used. If not, a file whose name matches the type key is assumed to be the correct sheet contents file.
Args:
types_dir (Path): Path to look in for type definitions
system_k... | random_line_split | |
settings_class.py | .util import DataStore, ParseError
from npc.util.functions import merge_data_dicts, prepend_namespace
from .tags import make_deprecated_tag_specs
from .helpers import quiet_parse
from .systems import System
import logging
logger = logging.getLogger(__name__)
class Settings(DataStore):
"""Core settings class
... |
system_name = next(iter(loaded))
loaded_contents = loaded[system_name]
if "extends" in loaded_contents:
dependencies[loaded_contents["extends"]].append(loaded)
continue
self.merge_data(loaded, namespace="npc.systems")
def load_... | continue | conditional_block |
settings_class.py | .util import DataStore, ParseError
from npc.util.functions import merge_data_dicts, prepend_namespace
from .tags import make_deprecated_tag_specs
from .helpers import quiet_parse
from .systems import System
import logging
logger = logging.getLogger(__name__)
class Settings(DataStore):
"""Core settings class
... | if file_key:
file_version = loaded.get("npc", {}).pop("version", None)
self.versions[file_key] = file_version
self.loaded_paths[file_key] = settings_file
self.merge_data(loaded, namespace)
def load_systems(self, systems_dir: Path) -> None:
"""Parse and ... | """Open, parse, and merge settings from another file
This is the primary way to load more settings info. Passing in a file path that does not exist will
result in a log message and no error, since all setting files are technically optional.
The file_key for any given file should be unique. The... | identifier_body |
index.js | = {
orderInfo: '{\"busi_partner\":\"101001\",\"dt_order\":\"20170303105801\",\"money_order\":\"0.01\",\"no_order\":\"20170303105753974138\",\"notify_url\":\"http://114.80.125.5:8181/payment/lianlian/tradeNotifyUrl.action\",\"oid_partner\":\"201408071000001546\",\"risk_item\":\"{\\\"delivery_cycle\\\":\\\"other\\\",... | etNet | identifier_name | |
index.js | 8350950",
noncestr: "1hl3lw1k1cC7jGAw",
partnerid: "1221847901",
prepayid: "wx20170301144909d8287b83680576459167",
package: "Sign=WXPay"
}
jsb("wxPay", option, param, cf);
}
var aliPay = function(option, cf) {
var param = {
orderInfo: 'partner="2088501903418573"&seller_id="etao@111.com.cn"&out... | } | random_line_split | |
index.js | 20170301164415605369&ORDERREQTRANSEQ=20170301164415605369&ORDERTIME=20170301164416&ORDERVALIDITYTIME=&CURTYPE=RMB&ORDERAMOUNT=29.0&SUBJECT=纯支付&PRODUCTID=04&PRODUCTDESC=APP翼支付&CUSTOMERID=20170301164415605369&SWTICHACC=false&SIGN=EDE379054221B625D9A6C772955EEE8D&PRODUCTAMOUNT=29.0&ATTACHAMOUNT=0.00&ATTACH=77&ACCOUNTID=&U... | JSON.stringify(o))
}
function fillweb(o) {
console.log("通知网页取值" + JSON.stringify(o))
}
function webchange() {
}
function nativeBack() {
console.log("我从native界面返回了 刷新不刷新 看你自己的业务逻辑吧")
}
function callba | identifier_body | |
read_state.rs | {
/// A read operation which advances the buffer, and reads from it.
ConsumingRead,
/// A read operation which reads from the buffer but doesn't advance it.
PeekingRead,
}
impl Default for ReadIsPeek {
fn default() -> Self {
ReadIsPeek::ConsumingRead
}
}
impl ReadIsPeek {
/// Ret... | ReadIsPeek | identifier_name | |
read_state.rs | start_rewriting_index + relative_add_index;
stallone::debug!(
"Inserting byte into stream",
stream_change_data: StreamChangeData = stream_change_data,
start_rewriting_index: usize = start_rewriting_index,
add_index: usize = add_index,
... | if !just_rewritten_bytes.is_empty() { | random_line_split | |
read_state.rs |
}
impl ReadIsPeek {
/// Return `PeekingRead` if the [`libc::MSG_PEEK`] bit is set in `flags.`
/// Otherwise, return `ConsumingRead`.
pub fn from_flags(flags: libc::c_int) -> Self {
if (flags & libc::MSG_PEEK) == 0 {
ReadIsPeek::ConsumingRead
} else {
ReadIsPeek::Pee... | {
ReadIsPeek::ConsumingRead
} | identifier_body | |
read_state.rs | This buffer stores any rewritten bytes which have either been peeked, or didn't fit in the
// user's buffer and need to be saved for a future call to `rewrite_readv`.
rewritten_bytes: Vec<u8>,
}
impl ReadState {
pub fn new(rewriter: Box<dyn IncomingRewriter + Send>) -> Self {
Self {
re... |
if let Some(relative_remove_index) = stream_change_data.remove_byte {
let remove_index = start_rewriting_index + relative_remove_index;
stallone::debug!(
"Removing byte from stream",
stream_change_data: StreamChangeData = stream_change_data,
... | {
let add_index = start_rewriting_index + relative_add_index;
stallone::debug!(
"Inserting byte into stream",
stream_change_data: StreamChangeData = stream_change_data,
start_rewriting_index: usize = start_rewriting_index,
add_index... | conditional_block |
init.ts | {
name: locale.LABEL_COMPONENT,
template: '@arco-design/arco-template-react-component',
},
'react-block': {
name: locale.LABEL_BLOCK,
template: '@arco-design/arco-template-react-block',
},
'react-page': {
name: locale.LABEL_PAGE,
template: '@arco-design/arco-template-react-page',
},
... |
/**
* Ask the meta information of the material
*/
async function inquiryMaterialMeta(meta: { [key: string]: any })
: Promise<{
name: string;
title: string;
description: string;
version: string;
category?: string[];
}> {
let pkgNamePrefix = 'rc';
let categories = [];
switch (meta.type) {
case 'vu... | 'list',
name: 'type',
message: template ? locale.TIP_SELECT_TYPE_OF_MATERIAL : locale.TIP_SELECT_TYPE_OF_PROJECT,
choices: Object.entries(MATERIAL_TYPE_MAP)
.filter(([key]) => {
if (template) {
return TYPES_MATERIAL.indexOf(key) > -1;
}
return (
... | identifier_body |
init.ts | {
name: locale.LABEL_COMPONENT,
template: '@arco-design/arco-template-react-component',
},
'react-block': {
name: locale.LABEL_BLOCK,
template: '@arco-design/arco-template-react-block',
},
'react-page': {
name: locale.LABEL_PAGE,
template: '@arco-design/arco-template-react-page',
},
... | ork dependencies of the current warehouse
if (isForMonorepo) {
try {
const pathGitRoot = getGitRootPath();
const { dependencies, devDependencies } =
fs.readJsonSync(path.resolve(pathGitRoot, 'package.json')) || {};
if ((dependencies && dependencies.react) || (devDependencies && devDepend... | o get the framew | identifier_name |
init.ts | ': {
name: locale.LABEL_COMPONENT,
template: '@arco-design/arco-template-react-component',
},
'react-block': {
name: locale.LABEL_BLOCK,
template: '@arco-design/arco-template-react-block',
},
'react-page': {
name: locale.LABEL_PAGE,
template: '@arco-design/arco-template-react-page',
},... | framework = answer.framework.toLowerCase();
}
return framework;
}
/**
* Get the template to create Arco Pro
*/
async function getAr | type: 'list',
name: 'framework',
message: locale.TIP_SELECT_FRAMEWORK,
choices: ['React', 'Vue'],
}); | random_line_split |
imdb_lstm_chen.py | izers import SGD, RMSprop, Adagrad
# from keras.utils import np_utils
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import MaskedLayer, Recurrent
from keras import activations, initializations
from k... | http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf
Learning to forget: Continual prediction with LSTM
http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015
Supervised sequence labelling with recurrent neural networks
http://www.... | """
Self-defined LSTM layer
optimized version: Not using mask in _step function and tensorized computation.
Acts as a spatiotemporal projection,
turning a sequence of vectors into a single vector.
Eats inputs with shape:
(nb_samples, max_sample_length (samples shorter t... | identifier_body |
imdb_lstm_chen.py | import SGD, RMSprop, Adagrad
# from keras.utils import np_utils
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import MaskedLayer, Recurrent
from keras import activations, initializations
from keras.... |
def _step(self,
Y_t, # sequence
h_tm1, c_tm1, # output_info
R): # non_sequence
# h_mask_tm1 = mask_tm1 * h_tm1
# c_mask_tm1 = mask_tm1 * c_tm1
G_tm1 = T.dot(h_tm1, R)
M_t = Y_t + G_tm1
z_t = self.input_activation(M_t... | self.set_weights(weights) | conditional_block |
imdb_lstm_chen.py |
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import MaskedLayer, Recurrent
from keras import activations, initializations
from keras.utils.theano_utils import shared_zeros
from keras.datasets import imdb
class LSTMLayer(Recurrent):
"""
Self-defined LSTM layer
optimiz... | random_line_split | ||
imdb_lstm_chen.py | import SGD, RMSprop, Adagrad
# from keras.utils import np_utils
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import MaskedLayer, Recurrent
from keras import activations, initializations
from keras.... | (self, train=False):
X = self.get_input(train)
# mask = self.get_padded_shuffled_mask(train, X, pad=0)
mask = self.get_input_mask(train=train)
ind = T.switch(T.eq(mask[:, -1], 1.), mask.shape[-1], T.argmin(mask, axis=-1)).astype('int32')
max_time = T.max(ind)
X = X.dimshu... | get_output | identifier_name |
demuxer.rs | found by a demuxer.
NewPacket(Packet),
/// A new stream is found by a demuxer.
NewStream(Stream),
/// More data are needed by a demuxer to complete its operations.
MoreDataNeeded(usize),
/// Event not processable by a demuxer.
///
/// Demux the next event.
Continue,
/// End of F... |
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::data::packet::Packet;
use std::io::SeekFrom;
struct DummyDes {
d: Descr,
}
struct DummyDemuxer {}
impl Demuxer for DummyDemuxer {
fn read_headers(
&mut self,
buf: &mut dyn Buffered,
... | {
None
} | conditional_block |
demuxer.rs | found by a demuxer.
NewPacket(Packet),
/// A new stream is found by a demuxer.
NewStream(Stream),
/// More data are needed by a demuxer to complete its operations.
MoreDataNeeded(usize),
/// Event not processable by a demuxer.
///
/// Demux the next event.
Continue,
/// End of F... | {
d: Descr,
}
struct DummyDemuxer {}
impl Demuxer for DummyDemuxer {
fn read_headers(
&mut self,
buf: &mut dyn Buffered,
_info: &mut GlobalInfo,
) -> Result<SeekFrom> {
let len = buf.data().len();
if 9 > len {
... | DummyDes | identifier_name |
demuxer.rs | is found by a demuxer.
NewPacket(Packet),
/// A new stream is found by a demuxer.
NewStream(Stream),
/// More data are needed by a demuxer to complete its operations.
MoreDataNeeded(usize),
/// Event not processable by a demuxer.
///
/// Demux the next event.
Continue,
/// End o... | }
if let Event::MoreDataNeeded(size) = event {
return Err(Error::MoreDataNeeded(size));
}
if let Event::NewPacket(ref mut pkt) = event {
if pkt.t.timebase.is_none() {
if let Some(st) = self
... | self.info.streams.push(st.clone()); | random_line_split |
demuxer.rs | by a demuxer.
NewStream(Stream),
/// More data are needed by a demuxer to complete its operations.
MoreDataNeeded(usize),
/// Event not processable by a demuxer.
///
/// Demux the next event.
Continue,
/// End of File.
///
/// Stop demuxing data.
Eof,
}
/// Used to implemen... | {
let demuxers: &[&'static dyn Descriptor<OutputDemuxer = DummyDemuxer>] = &[DUMMY_DES];
demuxers.probe(b"dummy").unwrap();
} | identifier_body | |
parser.go | .next() // consume closing '"'
txt := &ast.ParsedText{
Opener: pos,
Depth: 0,
Delim: ast.QuoteDelimiter,
Values: values,
Closer: p.pos,
}
return txt
case token.StringLBrace:
return p.parseText(0)
default:
p.errorExpected(p.pos, "string literal")
p.advance(stmtStart)
return &ast.BadExp... | {
if p.trace {
defer un(trace(p, "Declaration"))
}
switch p.tok {
case token.Preamble:
return p.parsePreambleDecl()
case token.Abbrev:
return p.parseAbbrevDecl()
case token.BibEntry:
return p.parseBibDecl()
default:
pos := p.pos
p.errorExpected(pos, "entry")
p.advance(entryStart)
return &ast.Bad... | identifier_body | |
parser.go | }
// add comment group to the comments list
comments = &ast.TexCommentGroup{List: list}
p.comments = append(p.comments, comments)
return
}
// Advance to the next non-comment token. In the process, collect
// any comment groups encountered, and remember the last lead and
// line comments.
//
// A lead comment is ... | var stmtStart = map[token.Token]bool{
token.Abbrev: true,
token.Comment: true,
token.Preamble: true,
token.BibEntry: true,
token.Ident: true,
}
var entryStart = map[token.Token]bool{
token.Abbrev: true,
token.Comment: true,
token.Preamble: true,
token.BibEntry: true,
}
// isValidTagName returns true... | }
}
}
| random_line_split |
parser.go | token.Illegal:
txt = &ast.BadExpr{From: p.pos, To: p.pos}
case token.StringLBrace: // recursive case
opener := p.pos
p.next()
values := make([]ast.Expr, 0, 2)
for p.tok != token.StringRBrace {
text := p.parseText(depth + 1)
if _, ok := text.(*ast.BadExpr); ok {
p.next()
return text
}
va... | {
doc := p.leadComment
key := p.parseIdent() // parses both ident and number
switch p.tok {
case token.Assign:
// It's a tag.
if !isValidTagName(key) {
p.error(key.Pos(), "tag keys must not start with a number")
}
p.next()
var val ast.Expr
if key.Name == "url" && p.tok.IsStringLiteral() {... | conditional_block | |
parser.go | Opener: pos,
Depth: 0,
Delim: ast.QuoteDelimiter,
Values: values,
Closer: p.pos,
}
return txt
case token.StringLBrace:
return p.parseText(0)
default:
p.errorExpected(p.pos, "string literal")
p.advance(stmtStart)
return &ast.BadExpr{
From: pos,
To: p.pos,
}
}
}
func (p *parser)... | parseFile | identifier_name | |
DisWavenet.py | 25,47.95.32.212:2226,47.95.32.212:2227,"
"47.95.32.225:2222,47.95.32.225:2223,47.95.32.225:2224,47.95.32.225:2225,47.95.32.225:2226,"
"47.95.33.5:2222,47.95.33.5:2223,47.95.33.5:2224,47.95.33.5:2225,47.95.33.5:2226,"
... | _id=FLAGS.task_index,
total_num_replicas=len(
| conditional_block | |
DisWavenet.py | =worker_device,
ps_device="/job:ps/cpu:0",
cluster=cluster
)
):
# 数据路径
data_path = "/root/mickey21/wavenet/"
compute_sample_num,sample_rate=FLAGS.compute_sample_num,FLAGS.sample_rate
batch_size,n_mfcc=FLAGS.batch_size,FLAGS.n_mfcc
n_epoch=FLAGS.n_epoch
# join()连接两个路径或这更多的路径
... | random_line_split | ||
DisWavenet.py | all parameters of a tensorflow graph
'''
if mode == 'all':
num = np.sum([np.product([xi.value for xi in x.get_shape()]) for x in model.var_op])
elif mode == 'trainable':
num = np.sum([np.product([xi.value for xi in x.get_shape()]) for x in model.var_trainable_op])
else:
raise Ty... | erate(sequences):#强转为枚举类
indices.extend(zip([n] * len(seq), range(len(seq))))
values.extend(seq)
indices = np.asarray(indices, dtype=np.int64)
values = np.asarray(values, dtype=dtype)
shape = np.asarray([len(sequences), np.asarray(indices).max(0)[1] + 1], dtype=np.int64)
return [indice... | identifier_body | |
DisWavenet.py | lues = []
for n, seq in enumerate(sequences):#强转为枚举类
indices.extend(zip([n] * len(seq), range(len(seq))))
values.extend(seq)
indices = np.asarray(indices, dtype=np.int64)
values = np.asarray(values, dtype=dtype)
shape = np.asarray([len(sequences), np.asarray(indices).max(0)[1] + 1], dt... | dices = []
va | identifier_name | |
db_transaction.rs | , BlockHeader},
proof_of_work::Difficulty,
transactions::{
transaction::{TransactionInput, TransactionKernel, TransactionOutput},
types::HashOutput,
},
};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Error, Formatter};
use strum_macros::Display;
use tari_crypto::tari_utilitie... | }
| random_line_split | |
db_transaction.rs | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CO... | (&mut self, delete: DbKey) {
self.operations.push(WriteOperation::Delete(delete));
}
/// Inserts a transaction kernel into the current transaction.
pub fn insert_kernel(&mut self, kernel: TransactionKernel, update_mmr: bool) {
let hash = kernel.hash();
self.insert(DbKeyValuePair::Tr... | delete | identifier_name |
db_transaction.rs | , BlockHeader},
proof_of_work::Difficulty,
transactions::{
transaction::{TransactionInput, TransactionKernel, TransactionOutput},
types::HashOutput,
},
};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Error, Formatter};
use strum_macros::Display;
use tari_crypto::tari_utilitie... | {
match self {
DbValue::Metadata(MetadataValue::ChainHeight(_)) => f.write_str("Current chain height"),
DbValue::Metadata(MetadataValue::AccumulatedWork(_)) => f.write_str("Total accumulated work"),
DbValue::Metadata(MetadataValue::PruningHorizon(_)) => f.write_str("Pruning h... | identifier_body | |
proc_cr10x_wq_v1.py | in sw:
m = re.search(REAL_RE_STR, s)
if m:
csi.append(float(m.groups()[0]))
if len(csi)==14:
# get sample datetime from data
yyyy = csi[1]
yday = csi[2]
(MM, HH) = math.modf(csi[3]/100.)
MM = math.ceil(MM*100.)... | ('cond', NC.FLOAT, ('ntime',)),
('turb', NC.FLOAT, ('ntime',)), | random_line_split | |
proc_cr10x_wq_v1.py | nsamp=nsamp+1
N = nsamp
data = {
'dt' : numpy.array(numpy.ones((N,), dtype=object)*numpy.nan),
'time' : numpy.array(numpy.ones((N,), dtype=long)*numpy.nan),
'wtemp' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
'cond' : numpy.array(numpy.ones((N,), dtype=fl... | """
From FSL (CSI datalogger program files):
"""
import numpy
from datetime import datetime
from time import strptime
import math
# get sample datetime from filename
fn = sensor_info['fn']
sample_dt_start = filt_datetime(fn)
# how many samples
nsamp = 0
for l... | identifier_body | |
proc_cr10x_wq_v1.py | how many samples
nsamp = 0
for line in lines:
m=re.search("^1,", line)
if m:
nsamp=nsamp+1
N = nsamp
data = {
'dt' : numpy.array(numpy.ones((N,), dtype=object)*numpy.nan),
'time' : numpy.array(numpy.ones((N,), dtype=long)*numpy.nan),
'wtemp' : numpy.... |
sample_str = '%04d-%03d %02d:%02d' % (yyyy, yday, HH, MM)
# if sensor_info['utc_offset']:
# sample_dt = scanf_datetime(sample_str, fmt='%m-%d-%Y %H:%M:%S') + \
# timedelta(hours=sensor_info['utc_offset'])
# else:
... | yday=yday+1
HH = 0. | conditional_block |
proc_cr10x_wq_v1.py | many samples
nsamp = 0
for line in lines:
m=re.search("^1,", line)
if m:
nsamp=nsamp+1
N = nsamp
data = {
'dt' : numpy.array(numpy.ones((N,), dtype=object)*numpy.nan),
'time' : numpy.array(numpy.ones((N,), dtype=long)*numpy.nan),
'wtemp' : numpy.arra... | (platform_info, sensor_info, data):
#
#
title_str = sensor_info['description']+' at '+ platform_info['location']
global_atts = {
'title' : title_str,
'institution' : 'Unversity of North Carolina at Chapel Hill (UNC-CH)',
'institution_url' : 'http://nccoos.unc.edu',
'ins... | creator | identifier_name |
step1_L1_ProdLike_PF.py | 3B2-EA45-9A12-BECFF07760FC.root'),
# fileNames = cms.untracked.vstring('file:/data/cerminar/Phase2HLTTDRWinter20DIGI/SingleElectron_PT2to200/GEN-SIM-DIGI-RAW/PU200_110X_mcRun4_realistic_v3_ext2-v2/F32C5A21-F0E9-9149-B04A-883CC704E820.root'),
secondaryFileNames = cms.untracked.vstring(),
# events... | overlap=0.25 # 0.3
getattr(process, 'l1pfProducer'+postfix+'Barrel').regions = cms.VPSet(
cms.PSet(
etaBoundaries = cms.vdouble(-1.5, -0.5, 0.5, 1.5),
etaExtra = cms.double(overlap),
phiExtra = cms.double(overlap),
phiSlices = cms.uint32(9)
)
)
... | identifier_body | |
step1_L1_ProdLike_PF.py | FULLMERGE'),
forceEventSetupCacheClearOnNewRun = cms.untracked.bool(False),
makeTriggerResults = cms.obsolete.untracked.bool,
numberOfConcurrentLuminosityBlocks = cms.untracked.uint32(1),
numberOfConcurrentRuns = cms.untracked.uint32(1),
numberOfStreams = cms.untracked.uint32(0),
numberOfThreads... | getattr(process, 'l1pfProducer'+postfix+D).useRelativeRegionalCoordinates = relativeCoordinates | conditional_block | |
step1_L1_ProdLike_PF.py | process.load('Configuration.StandardSequences.MagneticField_cff')
process.load('Configuration.StandardSequences.RawToDigi_Data_cff')
process.load('Configuration.StandardSequences.L1TrackTrigger_cff')
process.load('Configuration.StandardSequences.SimL1Emulator_cff')
process.load('Configuration.StandardSequences.EndOfPro... | process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.EventContent.EventContent_cff')
process.load('SimGeneral.MixingModule.mixNoPU_cfi')
process.load('Configuration.Geometry.GeometryExtended2026D49Reco_cff') | random_line_split | |
step1_L1_ProdLike_PF.py | cms.optional.untracked.allowed(cms.int32,cms.PSet)
)
# Input source
process.source = cms.Source("PoolSource",
# fileNames = cms.untracked.vstring('file:/data/cerminar/Phase2HLTTDRSummer20ReRECOMiniAOD/DoubleElectron_FlatPt-1To100/GEN-SIM-DIGI-RAW-MINIAOD/PU200_111X_mcRun4_realistic_T15_v1-v2/E2F32293-BA24-C646-80... | goRegional | identifier_name | |
suite.go | }
config.DefaultReporterConfig.SlowSpecThreshold = slowSpecThreshold
config.DefaultReporterConfig.Verbose = testing.Verbose()
reporters = append(reporters, gr.NewJUnitReporter(filepath.Join(reportsDir, fmt.Sprintf("%s.junit.xml", suiteId))))
RegisterFailHandler(Fail)
RunSpecsWithDefaultAndCustomReporters(t, fmt.S... | {
reportsDir := os.Getenv("REPORTS_DIR")
if reportsDir == "" {
reportsDir = filepath.Join("../", "build", "reports")
}
err := os.MkdirAll(reportsDir, 0700)
if err != nil {
t.Errorf("cannot create %s because %v", reportsDir, err)
}
reporters := make([]Reporter, 0)
slowSpecThresholdStr := os.Getenv("SLOW_SPE... | identifier_body | |
suite.go | reportsDir == "" {
reportsDir = filepath.Join("../", "build", "reports")
}
err := os.MkdirAll(reportsDir, 0700)
if err != nil {
t.Errorf("cannot create %s because %v", reportsDir, err)
}
reporters := make([]Reporter, 0)
slowSpecThresholdStr := os.Getenv("SLOW_SPEC_THRESHOLD")
if slowSpecThresholdStr == "" ... | }
_, found := os.LookupEnv("BDD_JX")
if !found {
_ = os.Setenv("BDD_JX", runner.Jx)
}
r := runner.New(cwd, &TimeoutSessionWait, 0)
version, err := r.RunWithOutput("--version")
if err != nil {
return errors.WithStack(err)
}
factory := cmd.NewFactory()
kubeClient, ns, err := factory.CreateKubeClient()
if... | cwd, err := os.Getwd()
if err != nil {
return errors.WithStack(err) | random_line_split |
suite.go | (t *testing.T, suiteId string) {
reportsDir := os.Getenv("REPORTS_DIR")
if reportsDir == "" {
reportsDir = filepath.Join("../", "build", "reports")
}
err := os.MkdirAll(reportsDir, 0700)
if err != nil {
t.Errorf("cannot create %s because %v", reportsDir, err)
}
reporters := make([]Reporter, 0)
slowSpecThre... | RunWithReporters | identifier_name | |
suite.go | Dir == "" {
reportsDir = filepath.Join("../", "build", "reports")
}
err := os.MkdirAll(reportsDir, 0700)
if err != nil {
t.Errorf("cannot create %s because %v", reportsDir, err)
}
reporters := make([]Reporter, 0)
slowSpecThresholdStr := os.Getenv("SLOW_SPEC_THRESHOLD")
if slowSpecThresholdStr == "" {
slow... |
bddTimeoutAppTests := os.Getenv("BDD_TIMEOUT_APP_TESTS")
if bddTimeoutAppTests == "" {
_ = os.Setenv("BDD_TIMEOUT_APP_TESTS", "60")
}
bddTimeoutSessionWait := os.Getenv("BDD_TIMEOUT_SESSION_WAIT")
if bddTimeoutSessionWait == "" {
_ = os.Setenv("BDD_TIMEOUT_SESSION_WAIT", "60")
}
bddTimeoutDevpod := os.Geten... | {
_ = os.Setenv("BDD_TIMEOUT_CMD_LINE", "1")
} | conditional_block |
run-performance-test.py | 2\n")
parameterFile.write("missed-cleavages=0\n")
parameterFile.write("allowed_missed_cleavage=0\n")
# Minimums
parameterFile.write("minimum_peaks=10\n")
parameterFile.write("min-peaks=10\n")
# Precursor selection rules.
parameterFile.write("precursor-window=3\n")
parameterFile.write("precursor-wi... |
else:
gnuplotFile.write("re")
gnuplotFile.write("plot \"%s\" using 1:0 title \"%s\" with lines lw 1\n"
% (dataFileName, seriesTitle))
gnuplotFile.write("set output\n")
gnuplotFile.write("replot\n")
gnuplotFile.close()
runCommand("gnuplot %s > plots/%s.png" % (gnuplot | firstOne = False | conditional_block |
run-performance-test.py | 2\n")
parameterFile.write("missed-cleavages=0\n")
parameterFile.write("allowed_missed_cleavage=0\n")
# Minimums
parameterFile.write("minimum_peaks=10\n")
parameterFile.write("min-peaks=10\n")
# Precursor selection rules.
parameterFile.write("precursor-window=3\n")
parameterFile.write("precursor-wi... |
# Create a gnuplot of a list of methods.
def makePerformancePlot(title, listOfMethods):
if not os.path.isdir("plots"):
os.mkdir("plots")
gnuplotFileName = "plots/%s.gnuplot" % title
gnuplotFile = open(gnuplotFileName, "w")
gnuplotFile.write("set output \"/dev/null\"\n")
gnuplotFile.write("set terminal p... | runCommand("join %s %s | awk -F \"~\" '{print $1 \" \" $2 \" \" $3}' | awk '{print $1 \"\t\" $2 \"\t\" $3 \"\t\" $4 \"\t\" $5}' | sort -n > %s.txt"
% (xData, yData, outputRoot), "")
gnuplotFileName = "%s.gnuplot" % outputRoot
gnuplotFile = open(gnuplotFileName, "w")
gnuplotFile.write("set output \"/... | identifier_body |
run-performance-test.py | 2\n")
parameterFile.write("missed-cleavages=0\n")
parameterFile.write("allowed_missed_cleavage=0\n")
# Minimums
parameterFile.write("minimum_peaks=10\n")
parameterFile.write("min-peaks=10\n")
# Precursor selection rules.
parameterFile.write("precursor-window=3\n")
parameterFile.write("precursor-wi... | (xData, xLabel, yData, yLabel, outputRoot):
runCommand("join %s %s | awk -F \"~\" '{print $1 \" \" $2 \" \" $3}' | awk '{print $1 \"\t\" $2 \"\t\" $3 \"\t\" $4 \"\t\" $5}' | sort -n > %s.txt"
% (xData, yData, outputRoot), "")
gnuplotFileName = "%s.gnuplot" % outputRoot
gnuplotFile = open(gnuplotFil... | makeScatterPlot | identifier_name |
run-performance-test.py | 2\n")
parameterFile.write("missed-cleavages=0\n")
parameterFile.write("allowed_missed_cleavage=0\n")
# Minimums
parameterFile.write("minimum_peaks=10\n")
parameterFile.write("min-peaks=10\n")
# Precursor selection rules.
parameterFile.write("precursor-window=3\n")
parameterFile.write("precursor-wi... | parameterFile.write("compute-sp=T\n")
parameterFile.write("overwrite=T\n")
parameterFile.write("peptide-list=T\n")
# Comet parameters
parameterFile.write("output_pepxmlfile=0\n")
parameterFile.write("add_C_cysteine=57.021464\n")
# parameterFile.write("num_threads=1\n") # Multithreaded sometimes dumps co... | # Other Crux parameters. | random_line_split |
user.go | }
defer resp.Body.Close()
_, err = io.Copy(newFile, resp.Body)
if err != nil {
log.Error("copy err(%v)", err)
return
}
return
}
//CreateDir 创建文件夹
func (d *Dao) CreateDir(path string) (err error) {
_, err = os.Stat(path)
defer func() {
if os.IsExist(err) {
err = nil
}
}()
if os.IsNotExist(err) {
e... | sex,
model.UserTypeUp, | random_line_split | |
user.go | (c context.Context, userDmg *model.UserDmg) (mid string, err error) {
conn := d.redis.Get(c)
defer conn.Close()
var b []byte
if b, err = json.Marshal(userDmg); err != nil {
log.Error("cache user dmg marshal err(%v)", err)
return
}
cacheKey := getUserDmgKey(userDmg.MID)
fmt.Println(cacheKey)
if _, err = conn... | CacheUserDmg | identifier_name | |
user.go | mg) (mid string, err error) {
conn := d.redis.Get(c)
defer conn.Close()
tag2 := strings.Join(userBbqDmg.Tag2, ",")
tag3 := strings.Join(userBbqDmg.Tag3, ",")
up := strings.Join(userBbqDmg.Up, ",")
cacheKey := getUserDmgKey(userBbqDmg.MID)
if err = conn.Send("HSET", cacheKey, "zone", tag2); err != nil {
log.Er... | 文件,hander回调
func (d *Dao) ReadLine(path string, handler func(string)) (err error) {
f, err := os.Open(path)
if err != nil {
log.Error("open path(%s) err(%v)", path, err)
return
}
defer f.Close()
buf := bufio.NewReader(f)
for {
line, err := buf.ReadString('\n')
if err != nil {
if err == io.EOF {
re... | t(path)
defer func() {
if os.IsExist(err) {
err = nil
}
}()
if os.IsNotExist(err) {
err = os.Mkdir(path, os.ModePerm)
}
return
}
// ReadLine 按行读取 | identifier_body |
user.go | , err)
return
}
defer f.Close()
buf := bufio.NewReader(f)
mids := make([]int64, 0, 50)
i := 0
for {
line, err := buf.ReadString('\n')
if err != nil {
if err == io.EOF {
err = nil
break
}
log.Error("read path(%s) err(%v)", path, err)
break
}
mid, _ := strconv.ParseInt(strings.TrimSpac... | Base get distinct mid list from table user_base
fun | conditional_block | |
lib.rs | ::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use indexmap::IndexSet;
use memmap2::{Mmap, MmapOptions};
/// The object that stores the parsed fasta index file. You can use it to map chromosome names to
/// indexes and lookup offsets for chr-start:end coordinates
#[derive(Debug, Clone... |
let (start_byte, stop_byte) = self.fasta_index.offset(tid, start, stop)?;
//println!("offset for chr {}:{}-{} is {}-{}", tid, start, stop, start_byte, stop_byte);
Ok(FastaView(&self.mmap[start_byte..stop_byte]))
}
/// Use tid to return a view of an entire chromosome.
///
/// R... | {
return Err(io::Error::new(
io::ErrorKind::Other,
"Invalid query interval",
));
} | conditional_block |
lib.rs | tid is the index of the chromosome (lookup with `Fai::tid` if necessary.
/// start, end: zero based coordinates of the requested range.
///
/// Returns an tuple (start, end) if successful. `io::Error` otherwise.
#[inline]
pub fn offset(&self, tid: usize, start: usize, stop: usize) -> io::Result<(us... | {
BaseCounts {
a: 0,
c: 0,
g: 0,
t: 0,
n: 0,
other: 0,
}
} | identifier_body | |
lib.rs | std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use indexmap::IndexSet;
use memmap2::{Mmap, MmapOptions};
/// The object that stores the parsed fasta index file. You can use it to map chromosome names to
/// indexes and lookup offsets for chr-start:end coordinates
#[derive(Debug, C... | let ioerr =
|e, msg| io::Error::new(io::ErrorKind::InvalidData, format!("{}:{}", msg, e));
chromosomes.push(FaiRecord {
len: p[1]
.parse()
.map_err(|e| ioerr(e, "Error parsing chr len in .fai"))?,
offset: p[2... |
name_map.insert(p[0].to_owned());
| random_line_split |
lib.rs | std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use indexmap::IndexSet;
use memmap2::{Mmap, MmapOptions};
/// The object that stores the parsed fasta index file. You can use it to map chromosome names to
/// indexes and lookup offsets for chr-start:end coordinates
#[derive(Debug, C... | (&self, tid: usize) -> io::Result<&String> {
self.name_map.get_index(tid).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Chromomsome tid was out of bounds")
})
}
/// Return the names of the chromosomes from the fasta index in the same order as in the
/// `.fai`. You can u... | name | identifier_name |
backend.rs | -> Result<Option<H::Out>, Self::Error> {
self.child_storage(storage_key, key).map(|v| v.map(|v| H::hash(&v)))
}
/// true if a key exists in storage.
fn exists_storage(&self, key: &[u8]) -> Result<bool, Self::Error> {
Ok(self.storage(key)?.is_some())
}
/// true if a key exists in child storage.
fn exists_ch... | -> (H::Out, Self::Transaction)
where
I1: IntoIterator<Item=(Vec<u8>, Option<Vec<u8>>)>,
I2i: IntoIterator<Item=(Vec<u8>, Option<Vec<u8>>)>,
I2: IntoIterator<Item=(Vec<u8>, I2i)>,
<H as Hasher>::Out: Ord,
{
let mut txs: Self::Transaction = Default::default();
let mut child_roots: Vec<_> = Default::default... | random_line_split | |
backend.rs | (&self, storage_key: &[u8], key: &[u8]) -> Result<Option<H::Out>, Self::Error> {
self.child_storage(storage_key, key).map(|v| v.map(|v| H::hash(&v)))
}
/// true if a key exists in storage.
fn exists_storage(&self, key: &[u8]) -> Result<bool, Self::Error> {
Ok(self.storage(key)?.is_some())
}
/// true if a key... | child_storage_hash | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.