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 |
|---|---|---|---|---|
client_conn.rs | //! Single client connection
use std::io;
use std::result::Result as std_Result;
use std::sync::Arc;
use error;
use error::Error;
use result;
use exec::CpuPoolOption;
use solicit::end_stream::EndStream;
use solicit::frame::settings::*;
use solicit::header::*;
use solicit::StreamId;
use solicit::DEFAULT_SETTINGS;
u... |
let status_1xx = match headers_place {
HeadersPlace::Initial => {
let status = headers.status();
let status_1xx = status >= 100 && status <= 199;
if status_1xx && end_stream == EndStream::Yes {
warn!("1xx headers and end stream: ... | {
warn!("invalid headers: {:?}: {:?}", e, headers);
self.send_rst_stream(stream_id, ErrorCode::ProtocolError)?;
return Ok(None);
} | conditional_block |
cassandra.go | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2016 Intel Corporation
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 ... |
}
func getLogger(config map[string]ctypes.ConfigValue) *log.Entry {
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) {
... | {
errorMsg := fmt.Sprintf("Invalid data type for a key %s", key)
err := errors.New(errorMsg)
log.Error(err)
} | conditional_block |
cassandra.go | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2016 Intel Corporation
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 ... | (e error) {
if e != nil {
log.Fatalf("%s", e.Error())
}
}
func checkAssertion(ok bool, key string) {
if !ok {
errorMsg := fmt.Sprintf("Invalid data type for a key %s", key)
err := errors.New(errorMsg)
log.Error(err)
}
}
func getLogger(config map[string]ctypes.ConfigValue) *log.Entry {
logger := log.WithF... | handleErr | identifier_name |
cassandra.go | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2016 Intel Corporation
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 ... | log.Fatalf("%s", e.Error())
}
}
func checkAssertion(ok bool, key string) {
if !ok {
errorMsg := fmt.Sprintf("Invalid data type for a key %s", key)
err := errors.New(errorMsg)
log.Error(err)
}
}
func getLogger(config map[string]ctypes.ConfigValue) *log.Entry {
logger := log.WithFields(log.Fields{
"plugin... | func handleErr(e error) {
if e != nil { | random_line_split |
cassandra.go | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2016 Intel Corporation
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 ... | {
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 | /*
* Copyright 2020 The Hyperledger-TWGC Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/sour... | MQ4wDAYDVQQDDAVQS1VDQTAeFw0xNzA2MDEwMDAwMDBaFw0yMDA2MDEwMDAwMDBa
MEYxCzAJBgNVBAYTAkNOMQswCQYDVQQIDAJCSjEMMAoGA1UECgwDUEtVMQswCQYD
VQQLDAJDQTEPMA0GA1UEAwwGYW50c3NzMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0D
QgAEHpXtrYNlwesl7IyPuaHKKHqn4rHBk+tCU0l0T+zuBNMHAOJzKNDbobno6gOI
EQlVfC9q9uk9lO174GJsMLWJJqN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhC... | /* Certificate */
certpem := `-----BEGIN CERTIFICATE-----
MIICAjCCAaigAwIBAgIBATAKBggqgRzPVQGDdTBSMQswCQYDVQQGEwJDTjELMAkG
A1UECAwCQkoxCzAJBgNVBAcMAkJKMQwwCgYDVQQKDANQS1UxCzAJBgNVBAsMAkNB | random_line_split |
gmssl_test.go | /*
* Copyright 2020 The Hyperledger-TWGC Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/sour... | (b *testing.B) {
b.ReportAllocs()
/* SM2 key pair operations */
sm2keygenargs := [][2]string{
{"ec_paramgen_curve", "sm2p256v1"},
{"ec_param_enc", "named_curve"},
}
sm2sk, err := gmssl.GeneratePrivateKey("EC", sm2keygenargs, nil)
PanicError(err)
sm2pkpem, err = sm2sk.GetPublicKeyPEM()
PanicError(err)
sm2... | BenchmarkSM2Sign | identifier_name |
gmssl_test.go | /*
* Copyright 2020 The Hyperledger-TWGC Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/sour... |
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.Printf("ciphertext = %x\n", ciphertext)
plaintext, err := gmssl.C... | {
/* 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 | /*
* Copyright 2020 The Hyperledger-TWGC Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/sour... |
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 | //! Kit for creating a a handler for batches of events
//!
//! Start here if you want to implement a handler for processing of events
use std::fmt;
use std::time::{Duration, Instant};
pub use bytes::Bytes;
use futures::future::BoxFuture;
pub type BatchHandlerFuture<'a> = BoxFuture<'a, BatchPostAction>;
use crate::na... | )?,
}
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 | //! Kit for creating a a handler for batches of events
//!
//! Start here if you want to implement a handler for processing of events
use std::fmt;
use std::time::{Duration, Instant};
pub use bytes::Bytes;
use futures::future::BoxFuture;
pub type BatchHandlerFuture<'a> = BoxFuture<'a, BatchPostAction>;
use crate::na... | (&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 | import sys
import platform
assert sys.platform == 'win32', 'xingAPI는 Windows 환경에서 사용 가능합니다.'
assert platform.architecture()[0] == '32bit', 'xingAPI는 32bit 환경에서 사용 가능합니다.'
import os
import pandas as pd
import pytz
import re
import time
from datetime import date, datetime, timedelta
from getpass import getpass
from pyth... | ', 'close', 'volumn', 'value', 'jongchk', 'rate']]
return data
def transactions(shcode, interval, sdate=None, edate=None):
""" 거래내역
t8411 : 주식챠트(틱/n틱)
t8412 : 주식챠트(N분)
t8413 : 주식챠트(일주월)
t1305 : 기간별 주가 : 일주월
t4201 : 주식차트(종합) - 틱/분/일/주/월
@arg shcode[... | n', 'high', 'low | identifier_name |
ebest.py | import sys
import platform
assert sys.platform == 'win32', 'xingAPI는 Windows 환경에서 사용 가능합니다.'
assert platform.architecture()[0] == '32bit', 'xingAPI는 32bit 환경에서 사용 가능합니다.'
import os
import pandas as pd
import pytz
import re
import time
from datetime import date, datetime, timedelta
from getpass import getpass
from pyth... | conditional_block | ||
ebest.py | import sys
import platform
assert sys.platform == 'win32', 'xingAPI는 Windows 환경에서 사용 가능합니다.'
assert platform.architecture()[0] == '32bit', 'xingAPI는 32bit 환경에서 사용 가능합니다.'
import os
import pandas as pd
import pytz
import re
import time
from datetime import date, datetime, timedelta
from getpass import getpass
from pyth... | ibed_keys:
raise ValueError(f'{self._res}는 {key} 데이터를 수신하고 있지 않습니다.')
self._instnace.UnadviseRealDataWithKey(key)
@staticmethod
def listen(delay=.01):
while True:
PumpWaitingMessages()
time.sleep(delay)
""" Wrapper Functions
"""
def transactions... |
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 | import sys
import platform
assert sys.platform == 'win32', 'xingAPI는 Windows 환경에서 사용 가능합니다.'
assert platform.architecture()[0] == '32bit', 'xingAPI는 32bit 환경에서 사용 가능합니다.'
import os
import pandas as pd
import pytz
import re
import time
from datetime import date, datetime, timedelta
from getpass import getpass
from pyth... | 'ncnt': interval,
'qrycnt': 2000,
'nday': '0',
'sdate': sdate,
'edate': edate,
'cts_date': cts_date,
'cts_time': cts_time,
'comp_yn': 'Y'
}, len(data) > 0)
data = response['t8412OutBlock1'] + data
... | cts_time = ' '
while True:
response = query('t8412', {
'shcode': shcode, | random_line_split |
rbac_utils.py | # Copyright 2017 AT&T Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | (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 | # Copyright 2017 AT&T Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
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 | # Copyright 2017 AT&T Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
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 | # Copyright 2017 AT&T Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
: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 | #![feature(drain_filter)]
mod utils;
use wasm_bindgen::prelude::*; | 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 | #![feature(drain_filter)]
mod utils;
use wasm_bindgen::prelude::*;
use peg;
use chrono::NaiveDate;
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::Re... |
/// convert a function to serde's json
pub fn to_json(&self) -> serde_json::Value {
match self {
Node::Line((_, arr)) | Node::List(arr) => {
// Object if any element has a child
// List if none do
// Undefined if both
if let S... | {
match self {
Node::Line((name, _)) => re.is_match(name),
_ => false,
}
} | identifier_body |
lib.rs | #![feature(drain_filter)]
mod utils;
use wasm_bindgen::prelude::*;
use peg;
use chrono::NaiveDate;
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::Re... | (&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 | #![feature(drain_filter)]
mod utils;
use wasm_bindgen::prelude::*;
use peg;
use chrono::NaiveDate;
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::Re... |
} else {
map.insert(name.to_string(), object.clone());
}
}
/// In-place modify to be parseable.
/// See the comment above for countries for rationale.
/// Call on root.
pub fn raise(&mut self) {
if let Node::List(nodes) = self {
// Get the first coun... | {
// 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 | // 预下单采购申请页面-采购清单
import { Component, OnInit, Input, EventEmitter, Output, ElementRef,OnChanges,ViewChild,
AfterViewInit, DoCheck,SimpleChanges,ChangeDetectorRef} from '@angular/core';
import { NgForm, NgModel } from "@angular/forms";
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observab... | i--;
}
}
this.calculateTotalTax("numberChange");
this.onAmountMoney.emit();//发送事件获取新的审批人序列
}
hoverText(i){//select hover显示字段
return $("#materialSource"+i+" option:selected").text();
}
matchContract(name){//根据名称(MainContractCode) 匹配合同 (批量... | len--; | random_line_split |
prepareApply-submit-list.component.ts | // 预下单采购申请页面-采购清单
import { Component, OnInit, Input, EventEmitter, Output, ElementRef,OnChanges,ViewChild,
AfterViewInit, DoCheck,SimpleChanges,ChangeDetectorRef} from '@angular/core';
import { NgForm, NgModel } from "@angular/forms";
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observab... | * (1 + Number(this.rate))).toFixed(2));//含税总金额
}
}
currencyDiffeFun=function(){//币种变化时 重新辨别计算总额
if(!this.tempAmountPrice){//无总额 不计算
this.onPurchaseDataChange.emit(this._purchaseData);
return;
}
if(this.IsRMB){//人民币 情况
this._purchaseData.untaxA... | 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 | // 预下单采购申请页面-采购清单
import { Component, OnInit, Input, EventEmitter, Output, ElementRef,OnChanges,ViewChild,
AfterViewInit, DoCheck,SimpleChanges,ChangeDetectorRef} from '@angular/core';
import { NgForm, NgModel } from "@angular/forms";
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observab... | }
}
return "";//已选的已经不在合同列表中 则置空
}
//当数量或金额发生变化时,发送事件,获取审批流程
onPriceOrCountChange(){
this.onAmountMoney.emit();//发送事件
}
} | 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 | // 预下单采购申请页面-采购清单
import { Component, OnInit, Input, EventEmitter, Output, ElementRef,OnChanges,ViewChild,
AfterViewInit, DoCheck,SimpleChanges,ChangeDetectorRef} from '@angular/core';
import { NgForm, NgModel } from "@angular/forms";
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observab... | identifier_name | ||
action.go | package agent
import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"github.com/choria-io/go-choria/validator/ipaddress"
"github.com/choria-io/go-choria/validator/ipv4"
"github.com/choria-io/go-choria/validator/ipv6"
"github.com/choria-io/go-choria/validator/regex"
"github.c... |
// 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 | package agent
import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"github.com/choria-io/go-choria/validator/ipaddress"
"github.com/choria-io/go-choria/validator/ipv4"
"github.com/choria-io/go-choria/validator/ipv6"
"github.com/choria-io/go-choria/validator/regex"
"github.c... | }
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 | package agent
import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"github.com/choria-io/go-choria/validator/ipaddress"
"github.com/choria-io/go-choria/validator/ipv4"
"github.com/choria-io/go-choria/validator/ipv6"
"github.com/choria-io/go-choria/validator/regex"
"github.c... |
}
}
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 | package agent
import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"github.com/choria-io/go-choria/validator/ipaddress"
"github.com/choria-io/go-choria/validator/ipv4"
"github.com/choria-io/go-choria/validator/ipv6"
"github.com/choria-io/go-choria/validator/regex"
"github.c... | (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 |
var urls = [];
var sample_urls = [];
var urls_downloaded = [];
// should be used when wishing to push to the lists stored in this script.
function listPush(url, sampUrl)
{
if(url == null || urls.indexOf(url) != -1 || url.length === 0) // avoid duplicates and nulls
return;
if(sampUrl == null)
... | () {
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 |
var urls = [];
var sample_urls = [];
var urls_downloaded = [];
// should be used when wishing to push to the lists stored in this script.
function listPush(url, sampUrl)
{
if(url == null || urls.indexOf(url) != -1 || url.length === 0) // avoid duplicates and nulls
return;
if(sampUrl == null)
... |
// 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 | var urls = [];
var sample_urls = [];
var urls_downloaded = [];
// should be used when wishing to push to the lists stored in this script.
function listPush(url, sampUrl)
{
if(url == null || urls.indexOf(url) != -1 || url.length === 0) // avoid duplicates and nulls
return;
if(sampUrl == null)
s... | 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 | package gopandas
import (
"encoding/csv"
"errors"
"math"
"sort"
"strconv"
"strings"
"time"
"bytes"
"github.com/golang/protobuf/proto"
)
const DateKey = "date"
const SecondKey = "key"
//TimePanel represents wide format panel data, stored as 3-dimensional array with sorted date major index
type TimePanel st... | 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 | package gopandas
import (
"encoding/csv"
"errors"
"math"
"sort"
"strconv"
"strings"
"time"
"bytes"
"github.com/golang/protobuf/proto"
)
const DateKey = "date"
const SecondKey = "key"
//TimePanel represents wide format panel data, stored as 3-dimensional array with sorted date major index
type TimePanel st... | 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 | package gopandas
import (
"encoding/csv"
"errors"
"math"
"sort"
"strconv"
"strings"
"time"
"bytes"
"github.com/golang/protobuf/proto"
)
const DateKey = "date"
const SecondKey = "key"
//TimePanel represents wide format panel data, stored as 3-dimensional array with sorted date major index
type TimePanel st... | 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 | package gopandas
import (
"encoding/csv"
"errors"
"math"
"sort"
"strconv"
"strings"
"time"
"bytes"
"github.com/golang/protobuf/proto"
)
const DateKey = "date"
const SecondKey = "key"
//TimePanel represents wide format panel data, stored as 3-dimensional array with sorted date major index
type TimePanel st... | 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 | ///! source::iter: source code content iterator, with interner
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::ops::{Add, AddAssign};
use super::{SourceContext, SourceFile, FileId};
pub const EOF: char = ... | (&self) -> FileId {
FileId::new(self.files.len() as u32 + 1)
}
pub fn finish(mut self) {
let content_length = self.content.len();
self.content.truncate(content_length - 3);
self.files.push(SourceFile{
path: self.path,
endlines: get_endlines(&self.content)... | get_file_id | identifier_name |
iter.rs | ///! source::iter: source code content iterator, with interner
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::ops::{Add, AddAssign};
use super::{SourceContext, SourceFile, FileId};
pub const EOF: char = ... | 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 | ///! source::iter: source code content iterator, with interner
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::ops::{Add, AddAssign};
use super::{SourceContext, SourceFile, FileId};
pub const EOF: char = ... |
}
// 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 | """
Load and save settings info
"""
import yaml
from collections import defaultdict
from importlib import resources
from functools import cached_property
from pathlib import Path
from npc import __version__ as npc_version
from npc.util import DataStore, ParseError
from npc.util.functions import merge_data_dicts, prep... | (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 | """
Load and save settings info
"""
import yaml
from collections import defaultdict
from importlib import resources
from functools import cached_property
from pathlib import Path
from npc import __version__ as npc_version
from npc.util import DataStore, ParseError
from npc.util.functions import merge_data_dicts, prep... | 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 | """
Load and save settings info
"""
import yaml
from collections import defaultdict
from importlib import resources
from functools import cached_property
from pathlib import Path
from npc import __version__ as npc_version
from npc.util import DataStore, ParseError
from npc.util.functions import merge_data_dicts, prep... |
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 | """
Load and save settings info
"""
import yaml
from collections import defaultdict
from importlib import resources
from functools import cached_property
from pathlib import Path
from npc import __version__ as npc_version
from npc.util import DataStore, ParseError
from npc.util.functions import merge_data_dicts, prep... |
def load_systems(self, systems_dir: Path) -> None:
"""Parse and load all system configs in systems_dir
Finds all yaml files in systems_dir and loads them as systems. Special handling allows deep
inheritance, and prevents circular dependencies between systems.
Arg... | """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 | (function(window) {
'use strict';
var callBackList = [];
var callNavList=[];
var baseConfig = {
scheme: "gl://",
debuger: true
}
var postUrl = function(strUrl, param, callid) {
if(navigator.userAgent.match(/app_sdk/i) ? true : false) {
var c = document.createElement("div")
c.innerHTML = '<iframe s... | workStatus: getNetworkStatus,
getUserInfo: getUserInfo,
getLocationInfo: getLocationInfo,
getAppInfo: getAppInfo,
wxPay: wxPay,
aliPay: aliPay,
linkPay: linkPay,
yiQianBaoPay: yiQianBaoPay,
bestPay: bestPay,
pickImage: pickImage,
forbidPanBack: forbidPanBack,
networkReq: networkReq,
hideNavigati... | etNet | identifier_name |
index.js | (function(window) {
'use strict';
var callBackList = [];
var callNavList=[];
var baseConfig = {
scheme: "gl://",
debuger: true
}
var postUrl = function(strUrl, param, callid) {
if(navigator.userAgent.match(/app_sdk/i) ? true : false) {
var c = document.createElement("div")
c.innerHTML = '<iframe s... | jsb("hideTabbar", option, param, cf);
}
var goPay = function(option, cf) {
var param = {
topage: "bank",
animation: 0,
fixPage: false, //true:去特定页面 false:正常推出一个页面 默认false
params: {
paymentId: "AE233", //支付方式
isPOSOK: true, //是否支持pos机
isYiKaTongOK: true, //是否支持一卡通
isHuoDaoFuKuanOK: tru... | } | random_line_split |
index.js | (function(window) {
'use strict';
var callBackList = [];
var callNavList=[];
var baseConfig = {
scheme: "gl://",
debuger: true
}
var postUrl = function(strUrl, param, callid) {
if(navigator.userAgent.match(/app_sdk/i) ? true : false) {
var c = document.createElement("div")
c.innerHTML = '<iframe s... | ck(o) {
jsBridge.callback(o)
}
jsBridge.init();
export default jsBridge;
| 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 | use crate::{IncomingRewriter, StreamChangeData};
/// Is a given read operation "peek" or "consume"?
#[derive(Clone, Copy)]
pub enum | {
/// 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 | use crate::{IncomingRewriter, StreamChangeData};
/// Is a given read operation "peek" or "consume"?
#[derive(Clone, Copy)]
pub enum ReadIsPeek {
/// 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.
Pe... | stallone::debug!(
"Saving just-rewritten bytes that were peeked",
num_just_rewritten_bytes: usize = just_rewritten_bytes.len(),
);
}
self.rewritten_bytes.extend_from_slice(just_rewritten_bytes);
... | if !just_rewritten_bytes.is_empty() { | random_line_split |
read_state.rs | use crate::{IncomingRewriter, StreamChangeData};
/// Is a given read operation "peek" or "consume"?
#[derive(Clone, Copy)]
pub enum ReadIsPeek {
/// 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.
Pe... |
}
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 | use crate::{IncomingRewriter, StreamChangeData};
/// Is a given read operation "peek" or "consume"?
#[derive(Clone, Copy)]
pub enum ReadIsPeek {
/// 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.
Pe... |
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 | import path from 'path';
import fs from 'fs-extra';
import chalk from 'chalk';
import axios from 'axios';
import inquirer from 'inquirer';
import { initConfig } from '@arco-design/arco-cli-config';
import {
print,
confirm,
isGitStatusClean,
CONSTANT,
getGitRootPath,
getGlobalInfo,
} from '@arco-design/arco-... | : Promise<{
name: string;
title: string;
description: string;
version: string;
category?: string[];
}> {
let pkgNamePrefix = 'rc';
let categories = [];
switch (meta.type) {
case 'vue-component':
pkgNamePrefix = 'vc';
categories = CATEGORIES_COMPONENT;
break;
case 'react-compon... | '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 | import path from 'path';
import fs from 'fs-extra';
import chalk from 'chalk';
import axios from 'axios';
import inquirer from 'inquirer';
import { initConfig } from '@arco-design/arco-cli-config';
import {
print,
confirm,
isGitStatusClean,
CONSTANT,
getGitRootPath,
getGlobalInfo,
} from '@arco-design/arco-... | 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 | import path from 'path';
import fs from 'fs-extra';
import chalk from 'chalk';
import axios from 'axios';
import inquirer from 'inquirer';
import { initConfig } from '@arco-design/arco-cli-config';
import {
print,
confirm,
isGitStatusClean,
CONSTANT,
getGitRootPath,
getGlobalInfo,
} from '@arco-design/arco-... | framework = answer.framework.toLowerCase();
}
return framework;
}
/**
* Get the template to create Arco Pro
*/
async function getArcoDesignProConfig(): Promise<Partial<CreateProjectOptions>> {
// Config for Arco Pro
const question = [
{
type: 'list',
name: 'type',
message: locale.T... | type: 'list',
name: 'framework',
message: locale.TIP_SELECT_FRAMEWORK,
choices: ['React', 'Vue'],
}); | random_line_split |
imdb_lstm_chen.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Train a LSTM on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF+LogReg.
Notes:
- RNNs are tricky. Choice of batch size is important,
... |
class MeanPooling(MaskedLayer):
"""
Self-defined pooling layer
Global Mean Pooling Layer
"""
def __init__(self, start=1):
super(MeanPooling, self).__init__()
self.start = start
# def supports_masked_input(self):
# return False
def get_output_mask(self, tra... | """
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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Train a LSTM on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF+LogReg.
Notes:
- RNNs are tricky. Choice of batch size is important,
... |
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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Train a LSTM on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF+LogReg.
Notes:
- RNNs are tricky. Choice of batch size is important,
... | print(len(X_test), 'test sequences')
print("Pad sequences (samples x time)")
X_train = sequence.pad_sequences(X_train, maxlen=maxlen)
X_test = sequence.pad_sequences(X_test, maxlen=maxlen)
print('X_train shape:', X_train.shape)
print('X_test shape:', X_test.shape)
print('Build model (The output of the last timestep i... | random_line_split | |
imdb_lstm_chen.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Train a LSTM on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF+LogReg.
Notes:
- RNNs are tricky. Choice of batch size is important,
... | (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 | use crate::error::*;
use crate::buffer::Buffered;
use std::any::Any;
use std::io::SeekFrom;
use std::sync::Arc;
use crate::common::*;
use crate::data::packet::Packet;
use crate::stream::Stream;
/// Events processed by a demuxer analyzing a source.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Event {
/// A... |
}
}
#[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 | use crate::error::*;
use crate::buffer::Buffered;
use std::any::Any;
use std::io::SeekFrom;
use std::sync::Arc;
use crate::common::*;
use crate::data::packet::Packet;
use crate::stream::Stream;
/// Events processed by a demuxer analyzing a source.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Event {
/// A... | {
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 | use crate::error::*;
use crate::buffer::Buffered;
use std::any::Any;
use std::io::SeekFrom;
use std::sync::Arc;
use crate::common::*;
use crate::data::packet::Packet;
use crate::stream::Stream;
/// Events processed by a demuxer analyzing a source.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Event {
/// A... | }
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 | use crate::error::*;
use crate::buffer::Buffered;
use std::any::Any;
use std::io::SeekFrom;
use std::sync::Arc;
use crate::common::*;
use crate::data::packet::Packet;
use crate::stream::Stream;
/// Events processed by a demuxer analyzing a source.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Event {
/// A... |
use crate::buffer::*;
use std::io::Cursor;
#[test]
fn read_headers() {
let buf = b"dummy header";
let r = AccReader::with_capacity(4, Cursor::new(buf));
let d = DUMMY_DES.create();
let mut c = Context::new(d, r);
c.read_headers().unwrap();
}
#[test]
... | {
let demuxers: &[&'static dyn Descriptor<OutputDemuxer = DummyDemuxer>] = &[DUMMY_DES];
demuxers.probe(b"dummy").unwrap();
} | identifier_body |
parser.go | package parser
import (
"fmt"
goscan "go/scanner"
gotok "go/token"
"strings"
"github.com/jschaf/bibtex/ast"
"github.com/jschaf/bibtex/scanner"
"github.com/jschaf/bibtex/token"
)
// The parser structure holds the parser's internal state.
type parser struct {
file *gotok.File
errors goscan.ErrorList
scan... |
// ----------------------------------------------------------------------------
// Source files
func (p *parser) parseFile() *ast.File {
if p.trace {
defer un(trace(p, "File"))
}
// Don't bother parsing the rest if we had errors scanning the first token.
// Likely not a bibtex source file at all.
if p.errors... | {
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 | package parser
import (
"fmt"
goscan "go/scanner"
gotok "go/token"
"strings"
"github.com/jschaf/bibtex/ast"
"github.com/jschaf/bibtex/scanner"
"github.com/jschaf/bibtex/token"
)
// The parser structure holds the parser's internal state.
type parser struct {
file *gotok.File
errors goscan.ErrorList
scan... | 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 | package parser
import (
"fmt"
goscan "go/scanner"
gotok "go/token"
"strings"
"github.com/jschaf/bibtex/ast"
"github.com/jschaf/bibtex/scanner"
"github.com/jschaf/bibtex/token"
)
// The parser structure holds the parser's internal state.
type parser struct {
file *gotok.File
errors goscan.ErrorList
scan... |
closer := p.expectCloser(opener)
p.expectOptional(token.Comma) // trailing commas allowed
return &ast.BibDecl{
Type: entryType,
Doc: doc,
Entry: pos,
Key: bibKey,
ExtraKeys: extraKeys,
Tags: tags,
RBrace: closer,
}
}
func (p *parser) parseDecl() ast.Decl {
if p.trace {
... | {
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 | package parser
import (
"fmt"
goscan "go/scanner"
gotok "go/token"
"strings"
"github.com/jschaf/bibtex/ast"
"github.com/jschaf/bibtex/scanner"
"github.com/jschaf/bibtex/token"
)
// The parser structure holds the parser's internal state.
type parser struct {
file *gotok.File
errors goscan.ErrorList
scan... | () *ast.File {
if p.trace {
defer un(trace(p, "File"))
}
// Don't bother parsing the rest if we had errors scanning the first token.
// Likely not a bibtex source file at all.
if p.errors.Len() != 0 {
return nil
}
// Opening comment
doc := p.leadComment
p.openScope()
p.pkgScope = p.topScope
var decls ... | parseFile | identifier_name |
DisWavenet.py | # coding=utf-8
import tempfile
import numpy as np
import tensorflow as tf
import os
import math
import time
from tensorflow.examples.tutorials.mnist import input_data
import pickle
from model import Model
import datetime
"""
分布式布置Wavenet
"""
#将日志输出到某个文件
# def save(filename, contents):
# fh = open(filename, 'a')#w... | worker_spec),
use_locking=True)
train_op = rep_op.apply_gradients(gradient,
global_step=global_step)
init_token_op = rep_op.get_init_tokens_op()
chief_queue_run... | _id=FLAGS.task_index,
total_num_replicas=len(
| conditional_block |
DisWavenet.py | # coding=utf-8
import tempfile
import numpy as np
import tensorflow as tf
import os
import math
import time
from tensorflow.examples.tutorials.mnist import input_data
import pickle
from model import Model
import datetime
"""
分布式布置Wavenet
"""
#将日志输出到某个文件
# def save(filename, contents):
# fh = open(filename, 'a')#w... | """*******华丽分割线****************""" | random_line_split | |
DisWavenet.py | # coding=utf-8
import tempfile
import numpy as np
import tensorflow as tf
import os
import math
import time
from tensorflow.examples.tutorials.mnist import input_data
import pickle
from model import Model
import datetime
"""
分布式布置Wavenet
"""
#将日志输出到某个文件
# def save(filename, contents):
# fh = open(filename, 'a')#w... | 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 | # coding=utf-8
import tempfile
import numpy as np
import tensorflow as tf
import os
import math
import time
from tensorflow.examples.tutorials.mnist import input_data
import pickle
from model import Model
import datetime
"""
分布式布置Wavenet
"""
#将日志输出到某个文件
# def save(filename, contents):
# fh = open(filename, 'a')#w... | 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 | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | impl Display for DbKey {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
DbKey::Metadata(MetadataKey::ChainHeight) => f.write_str("Current chain height"),
DbKey::Metadata(MetadataKey::AccumulatedWork) => f.write_str("Total accumulated work"),
DbKey::M... | }
| random_line_split |
db_transaction.rs | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... | (&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 | // Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclai... |
}
impl Display for DbKey {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
DbKey::Metadata(MetadataKey::ChainHeight) => f.write_str("Current chain height"),
DbKey::Metadata(MetadataKey::AccumulatedWork) => f.write_str("Total accumulated work"),
DbKe... | {
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 | #!/usr/bin/env python
# Last modified: Time-stamp: <2010-12-09 16:14:19 haines>
"""
how to parse data, and assert what data and info goes into
creating and updating monthly netcdf files
parse data water quality data from ysi 6600 V2
collected on Campbell Scientific DataLogger (loggernet) (csi)
parser : sample date a... | ('ph', NC.FLOAT, ('ntime',)),
('do_mg', NC.FLOAT, ('ntime',)),
('do_sat', NC.FLOAT, ('ntime',)),
('battvolts', NC.FLOAT, ('ntime',)),
)
# subset data only to month being processed (see raw2proc.process())
i = data['in']
# var data
var_data = (
('lat... | ('cond', NC.FLOAT, ('ntime',)),
('turb', NC.FLOAT, ('ntime',)), | random_line_split |
proc_cr10x_wq_v1.py | #!/usr/bin/env python
# Last modified: Time-stamp: <2010-12-09 16:14:19 haines>
"""
how to parse data, and assert what data and info goes into
creating and updating monthly netcdf files
parse data water quality data from ysi 6600 V2
collected on Campbell Scientific DataLogger (loggernet) (csi)
parser : sample date a... |
def creator(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.ed... | """
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 | #!/usr/bin/env python
# Last modified: Time-stamp: <2010-12-09 16:14:19 haines>
"""
how to parse data, and assert what data and info goes into
creating and updating monthly netcdf files
parse data water quality data from ysi 6600 V2
collected on Campbell Scientific DataLogger (loggernet) (csi)
parser : sample date a... |
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 | #!/usr/bin/env python
# Last modified: Time-stamp: <2010-12-09 16:14:19 haines>
"""
how to parse data, and assert what data and info goes into
creating and updating monthly netcdf files
parse data water quality data from ysi 6600 V2
collected on Campbell Scientific DataLogger (loggernet) (csi)
parser : sample date a... | (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 | # Auto generated configuration file
# using:
# Revision: 1.19
# Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v
# with command line options: step1 --conditions auto:phase2_realistic_T15 -n 2 --era Phase2C9 --eventcontent FEVTDEBUGHLT -s RAW2DIGI,L1TrackTrigger,L1 --datatier FEVTDEBU... |
def doDumpFile(basename="DoubleElectron_PU200"):
goRegional(relativeCoordinates=True)
for det in "Barrel", "HGCal", "HGCalNoTK", "HF":
l1pf = getattr(process, 'l1pfProducer'+det)
l1pf.dumpFileName = cms.untracked.string(basename+"_"+det+".dump")
l1pf.genOrigin = cms.InputTag("genParti... | 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 | # Auto generated configuration file
# using:
# Revision: 1.19
# Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v
# with command line options: step1 --conditions auto:phase2_realistic_T15 -n 2 --era Phase2C9 --eventcontent FEVTDEBUGHLT -s RAW2DIGI,L1TrackTrigger,L1 --datatier FEVTDEBU... |
def doDumpFile(basename="DoubleElectron_PU200"):
goRegional(relativeCoordinates=True)
for det in "Barrel", "HGCal", "HGCalNoTK", "HF":
l1pf = getattr(process, 'l1pfProducer'+det)
l1pf.dumpFileName = cms.untracked.string(basename+"_"+det+".dump")
l1pf.genOrigin = cms.InputTag("genParti... | getattr(process, 'l1pfProducer'+postfix+D).useRelativeRegionalCoordinates = relativeCoordinates | conditional_block |
step1_L1_ProdLike_PF.py | # Auto generated configuration file
# using:
# Revision: 1.19
# Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v
# with command line options: step1 --conditions auto:phase2_realistic_T15 -n 2 --era Phase2C9 --eventcontent FEVTDEBUGHLT -s RAW2DIGI,L1TrackTrigger,L1 --datatier FEVTDEBU... | 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 | # Auto generated configuration file
# using:
# Revision: 1.19
# Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v
# with command line options: step1 --conditions auto:phase2_realistic_T15 -n 2 --era Phase2C9 --eventcontent FEVTDEBUGHLT -s RAW2DIGI,L1TrackTrigger,L1 --datatier FEVTDEBU... | (postfix="", relativeCoordinates=False):
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),
... | goRegional | identifier_name |
suite.go | package helpers
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/jenkins-x/jx-api/pkg/client/clientset/versioned"
cmd "github.com/jenkins-x/jx/v2/pkg/cmd/clients"
"github.com/jenkins-x/jx/v2/pkg/kube"
"github.com/onsi/ginkgo/config"
"k8s.io/client-go/kubernetes"
... |
var BeforeSuiteCallback = func() {
err := ensureConfiguration()
utils.ExpectNoError(err)
WorkDir, err := ioutil.TempDir("", TempDirPrefix)
Expect(err).NotTo(HaveOccurred())
err = os.MkdirAll(WorkDir, 0760)
Expect(err).NotTo(HaveOccurred())
Expect(WorkDir).To(BeADirectory())
AssignWorkDirValue(WorkDir)
}
var ... | {
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 | package helpers
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/jenkins-x/jx-api/pkg/client/clientset/versioned"
cmd "github.com/jenkins-x/jx/v2/pkg/cmd/clients"
"github.com/jenkins-x/jx/v2/pkg/kube"
"github.com/onsi/ginkgo/config"
"k8s.io/client-go/kubernetes"
... | }
_, 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 | package helpers
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/jenkins-x/jx-api/pkg/client/clientset/versioned"
cmd "github.com/jenkins-x/jx/v2/pkg/cmd/clients"
"github.com/jenkins-x/jx/v2/pkg/kube"
"github.com/onsi/ginkgo/config"
"k8s.io/client-go/kubernetes"
... | (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 | package helpers
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/jenkins-x/jx-api/pkg/client/clientset/versioned"
cmd "github.com/jenkins-x/jx/v2/pkg/cmd/clients"
"github.com/jenkins-x/jx/v2/pkg/kube"
"github.com/onsi/ginkgo/config"
"k8s.io/client-go/kubernetes"
... |
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 | #!/usr/bin/env python
# CREATE DATE: 11 March 2015
# AUTHOR: William Stafford Noble
# Derived from run-performance-test.sh.
# This script runs a performance test on the crux toolkit. Its usage
# and output are described in ./performance.html. The MS2 file comes
# from the PAnDA paper by Hoopman et al. (JPR 2009). E... |
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" % (gnuplotFile... | firstOne = False | conditional_block |
run-performance-test.py | #!/usr/bin/env python
# CREATE DATE: 11 March 2015
# AUTHOR: William Stafford Noble
# Derived from run-performance-test.sh.
# This script runs a performance test on the crux toolkit. Its usage
# and output are described in ./performance.html. The MS2 file comes
# from the PAnDA paper by Hoopman et al. (JPR 2009). E... |
# 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 | #!/usr/bin/env python
# CREATE DATE: 11 March 2015
# AUTHOR: William Stafford Noble
# Derived from run-performance-test.sh.
# This script runs a performance test on the crux toolkit. Its usage
# and output are described in ./performance.html. The MS2 file comes
# from the PAnDA paper by Hoopman et al. (JPR 2009). E... | (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 | #!/usr/bin/env python
# CREATE DATE: 11 March 2015
# AUTHOR: William Stafford Noble
# Derived from run-performance-test.sh.
# This script runs a performance test on the crux toolkit. Its usage
# and output are described in ./performance.html. The MS2 file comes
# from the PAnDA paper by Hoopman et al. (JPR 2009). E... | 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 | package dao
import (
"bufio"
"context"
"database/sql"
"encoding/json"
"fmt"
"go-common/app/job/bbq/video/conf"
"go-common/app/job/bbq/video/model"
video "go-common/app/service/bbq/video/api/grpc/v1"
acc "go-common/app/service/main/account/api"
xsql "go-common/library/database/sql"
"go-common/library/log"
"... | 0)
if err != nil {
log.Error("MergeUpInfo insert upinfo failed,err:%v", err)
return
}
} else {
log.Error("MergeUpInfo query sql failed,err:%v", err)
}
if err = d.db.QueryRow(ctx, "select id from user_statistics where mid = ?", mid).Scan(&id); err != nil {
if err == sql.ErrNoRows {
if _, err = d.d... | sex,
model.UserTypeUp, | random_line_split |
user.go | package dao
import (
"bufio"
"context"
"database/sql"
"encoding/json"
"fmt"
"go-common/app/job/bbq/video/conf"
"go-common/app/job/bbq/video/model"
video "go-common/app/service/bbq/video/api/grpc/v1"
acc "go-common/app/service/main/account/api"
xsql "go-common/library/database/sql"
"go-common/library/log"
"... | (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 | package dao
import (
"bufio"
"context"
"database/sql"
"encoding/json"
"fmt"
"go-common/app/job/bbq/video/conf"
"go-common/app/job/bbq/video/model"
video "go-common/app/service/bbq/video/api/grpc/v1"
acc "go-common/app/service/main/account/api"
xsql "go-common/library/database/sql"
"go-common/library/log"
"... | 文件,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 | package dao
import (
"bufio"
"context"
"database/sql"
"encoding/json"
"fmt"
"go-common/app/job/bbq/video/conf"
"go-common/app/job/bbq/video/model"
video "go-common/app/service/bbq/video/api/grpc/v1"
acc "go-common/app/service/main/account/api"
xsql "go-common/library/database/sql"
"go-common/library/log"
"... | c (d *Dao) SelMidFromUserBase(start int) (mids []int64, err error) {
var mid int64
rows, err := d.db.Query(context.Background(), _selMidFromUserBase, start)
if err != nil {
log.Error("SelMidFromUserBase failed, err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var s string
if err = rows.Scan(&s... | Base get distinct mid list from table user_base
fun | conditional_block |
lib.rs | #![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file ... |
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 | #![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file ... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fai() {
let ir = IndexedFasta::from_file("test/genome.fa").unwrap();
assert_eq!(ir.fai().names().len(), 3);
assert_eq!(ir.fai().tid("ACGT-25"), Some(2));
assert_eq!(ir.fai().tid("NotFound"), None);
assert_eq!(ir.... | {
BaseCounts {
a: 0,
c: 0,
g: 0,
t: 0,
n: 0,
other: 0,
}
} | identifier_body |
lib.rs | #![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file ... | 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 | #![doc(html_root_url = "https://docs.rs/faimm/0.4.0")]
//! This crate provides indexed fasta access by using a memory mapped file to read the sequence
//! data. It is intended for accessing sequence data on genome sized fasta files and provides
//! random access based on base coordinates. Because an indexed fasta file ... | (&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 | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... | -> (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 | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... | (&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.