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 |
|---|---|---|---|---|
gobuild.go | false
return false
}
if !dep.Compiled &&
(dep.Type == godata.LOCAL_PACKAGE ||
dep.Type == godata.UNKNOWN_PACKAGE && dep.Files.Len() > 0) {
if !compile(dep) {
pack.HasErrors = true
pack.InProgress = false
return false
}
}
}
// cgo files (the ones which import "C") can't be compiled... | runExec | identifier_name | |
sa_collection.py | raw_cookie_file = "../config/raw_cookie.txt"
user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' +
' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}
add_article = ("INSERT INTO articles"
"(articleID, ticker_symbol, publis... | 'comment_date': self.date,
'content': self.text.encode('ascii', errors='ignore').decode(),
'parentID': self.parentID,
'discussionID': self.discussionID
}
##################################
# #
# FILE FUNCTIONS #
# ... | 'commentID': self.commentID,
'userID': self.userID, | random_line_split |
sa_collection.py | raw_cookie_file = "../config/raw_cookie.txt"
user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' +
' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}
add_article = ("INSERT INTO articles"
"(articleID, ticker_symbol, publis... | (self):
"""
Returns json representation of an article (for writing
to the database).
"""
if self.valid:
return {
'articleID': self._id,
'ticker_symbol': self.ticker,
'published_date': self.pub_date,
'auth... | json | identifier_name |
sa_collection.py | raw_cookie_file = "../config/raw_cookie.txt"
user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' +
' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}
add_article = ("INSERT INTO articles"
"(articleID, ticker_symbol, publis... |
def try_add_article(art_json, cursor):
"""
Given an article json, tries to write that article to database.
"""
try:
cursor.execute(add_article, art_json)
except mysql.connector.errors.IntegrityError:
print("Duplicate Article")
def try_add_db(art_json, com_jsons, cursor, article_... | """
Given array of comment jsons, adds comments to database.
"""
if not com_jsons:
print("\t No comments found for " + article_id)
for c in com_jsons:
try:
cursor.execute(add_comment, c)
except mysql.connector.DatabaseError as err:
if not err.errno == 106... | identifier_body |
sa_collection.py | raw_cookie_file = "../config/raw_cookie.txt"
user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' +
' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}
add_article = ("INSERT INTO articles"
"(articleID, ticker_symbol, publis... |
return r
def get_comment_jsons(article_id, cookie):
"""
Returns all comments for the given article as array of
jsons.
"""
url = "https://seekingalpha.com/account/ajax_get_comments?id=%s&type=Article&commentType=" % article_id
r = safe_request(url, cookie)
comments = []
if r.statu... | try:
r = requests.get(url, cookies=cookie, headers=user_agent)
if r.status_code != 200:
print(r.status_code, "blocked")
count += 1
else:
break
except requests.exceptions.ConnectionError:
print("timeout", url)
... | conditional_block |
set.js | Charm"),
Necrogenesis: require("./Necrogenesis"),
Necroplasm: require("./Necroplasm"),
NevinyrralsDisk: require("./NevinyrralsDisk"),
NomadOutpost: require("./NomadOutpost"),
OathofDruids: require("./OathofDruids"),
Oblation: require("./Oblation"),
OpalPalace: require("./OpalPalace"),
OpentheVaults: req... | { window.mtgSets = {}; } | conditional_block | |
set.js | ment: require("./EverlastingTorment"),
EvolutionaryEscalation: require("./EvolutionaryEscalation"),
EvolvingWilds: require("./EvolvingWilds"),
ExecutionersCapsule: require("./ExecutionersCapsule"),
ExoticOrchard: require("./ExoticOrchard"),
FaerieArtisans: require("./FaerieArtisans"),
Farseek: require("./Fa... | SandsteppeCitadel: require("./SandsteppeCitadel"),
Sangromancer: require("./Sangromancer"), | random_line_split | |
utils.rs | .y;
}
}
#[no_mangle]
pub extern "C" fn get_hex_coord(
map: Option<&MaybeInvalid<Map>>,
hex_x: u16,
hex_y: u16,
end_x: &mut u16,
end_y: &mut u16,
angle: f32,
dist: u32,
) {
if let Some(map) = map.and_then(MaybeInvalid::validate) {
let end_hex = get_hex_in_path(
ma... | {
if( !player.IsPlayer() ) return false;
if( !isLoadedGMs )
LoadGMs( player, 0, 0, 0 );
if( player.StatBase[ ST_ACCESS_LEVEL ] < ACCESS_MODER && ( player.GetAccess() >= ACCESS_MODER || isPocketGM( player.Id ) ) )
player.StatBase[ ST_ACCESS_LEVEL ] = ACCESS_MODER;
return player.StatBase[ ST_ACCESS_LEVEL ] >= ACCESS_M... | random_line_split | |
utils.rs | ;
}
}
#[no_mangle]
pub extern "C" fn get_hex_coord(
map: Option<&MaybeInvalid<Map>>,
hex_x: u16,
hex_y: u16,
end_x: &mut u16,
end_y: &mut u16,
angle: f32,
dist: u32,
) {
if let Some(map) = map.and_then(MaybeInvalid::validate) {
let end_hex = get_hex_in_path(
map,... | er, rates: &MovingRates) -> f32 {
if cr.IsRuning {
rates.running
//} else if cr.is_walking() {
// rates.walking
} else {
rates.still
}
}
fn sense_mul(rates: &SenseRates, cr: &Critter, opponent: &Critter, look_dir: i8) -> f32 {
rates.dir... | (cr: &Critt | identifier_name |
utils.rs | ;
}
}
#[no_mangle]
pub extern "C" fn get_hex_coord(
map: Option<&MaybeInvalid<Map>>,
hex_x: u16,
hex_y: u16,
end_x: &mut u16,
end_y: &mut u16,
angle: f32,
dist: u32,
) {
if let Some(map) = map.and_then(MaybeInvalid::validate) {
let end_hex = get_hex_in_path(
map,... | enses: Vec<(f32, f32)> = config
.senses
.iter()
.map(|sense| {
let critter_rates = if self_is_npc {
&sense.npc
} else {
&sense.player
};
let basic_dist = basic_dist(critter_rates, cr_perception);
let sens... | ates.dir_rate[look_dir as usize]
* moving_rate(cr, &rates.self_moving)
* moving_rate(opponent, &rates.target_moving)
}
let s | identifier_body |
utils.rs | pub extern "C" fn is_gM(Critter& player)
{
if( !player.IsPlayer() ) return false;
if( !isLoadedGMs )
LoadGMs( player, 0, 0, 0 );
if( player.StatBase[ ST_ACCESS_LEVEL ] < ACCESS_MODER && ( player.GetAccess() >= ACCESS_MODER || isPocketGM( player.Id ) ) )
player.StatBase[ ST_ACCESS_LEVEL ] = ACCESS_MODER;
return playe... | , cr_hex, opp_hex, 0.0, dist) | conditional_block | |
token_flow.go | audience, err := url.Parse(caURL)
if err != nil {
return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "")
}
switch strings.ToLower(audience.Scheme) {
case "https", "":
var path string
switch tokType {
// default
case SignType, SSHUserSignType, SSHHostSignType:
path = "/1.0/sign"
// revocation tok... | }
| random_line_split | |
token_flow.go | return "", &ErrACMEToken{p.GetName()}
}
// JWK provisioner
prov, ok := p.(*provisioner.JWK)
if !ok {
return "", errors.Errorf("unknown provisioner type %T", p)
}
kid := prov.Key.KeyID
issuer := prov.Name
var opts []jose.Option
if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 {
op... | provisionerFilter | identifier_name | |
token_flow.go | , SSHUserSignType, SSHHostSignType:
path = "/1.0/sign"
// revocation token
case RevokeType:
path = "/1.0/revoke"
default:
return "", errors.Errorf("unexpected token type: %d", tokType)
}
audience.Scheme = "https"
audience = audience.ResolveReference(&url.URL{Path: path})
return audience.String(),... |
out, err := exec.Step(args...)
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
case *provisioner.GCP: // Do the identity request to get the token
sharedContext.DisableCustomSANs = p.DisableCustomSANs
return p.GetIdentityToken(subject, caURL)
case *provisioner.AWS: // Do the... | {
args = append(args, "--listen", p.ListenAddress)
} | conditional_block |
token_flow.go | , SSHUserSignType, SSHHostSignType:
path = "/1.0/sign"
// revocation token
case RevokeType:
path = "/1.0/revoke"
default:
return "", errors.Errorf("unexpected token type: %d", tokType)
}
audience.Scheme = "https"
audience = audience.ResolveReference(&url.URL{Path: path})
return audience.String(),... | switch p := p.(type) {
case *provisioner.JWK:
return p.Key.KeyID == kid
case *provisioner.OIDC:
return p.Client | {
// Filter by type
provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
switch p.GetType() {
case provisioner.TypeJWK, provisioner.TypeOIDC, provisioner.TypeACME:
return true
case provisioner.TypeGCP, provisioner.TypeAWS, provisioner.TypeAzure:
return true
default:
ret... | identifier_body |
recorder.go | ", 99.999},
{"-p99.99", 99.99},
{"-p99.9", 99.9},
{"-p99", 99},
{"-p90", 90},
{"-p75", 75},
{"-p50", 50},
}
// storeMetrics is the minimum interface of the storage.Store object needed by
// MetricsRecorder to provide status summaries. This is used instead of Store
// directly in order to simplify testing.
type s... | {
gauge := r.GetGauge(name)
if gauge == nil {
log.Errorf("Could not record status summaries: Store %d did not have '%s' gauge in registry.", storeID, name)
return nil, nil
}
gauges[name] = gauge
} | conditional_block | |
recorder.go | Prefix = "cr.node.%s"
// runtimeStatTimeSeriesFmt is the current format for time series keys which
// record runtime system stats on a node.
runtimeStatTimeSeriesNameFmt = "cr.node.sys.%s"
)
type quantile struct {
suffix string
quantile float64
}
var recordHistogramQuantiles = []quantile{
{"-max", 100},
{"-p... | timestampNanos: now,
}
recorder.record(&data)
// Record time series from store-level registries.
for storeID, r := range mr.mu.storeRegistries {
storeRecorder := registryRecorder{
registry: r,
format: storeTimeSeriesPrefix,
source: strconv.FormatInt(int64(storeID), 10),
timest... | {
mr.mu.Lock()
defer mr.mu.Unlock()
if mr.mu.desc.NodeID == 0 {
// We haven't yet processed initialization information; do nothing.
if log.V(1) {
log.Warning("MetricsRecorder.GetTimeSeriesData() called before NodeID allocation")
}
return nil
}
data := make([]ts.TimeSeriesData, 0, mr.mu.lastDataCount)
... | identifier_body |
recorder.go | Prefix = "cr.node.%s"
// runtimeStatTimeSeriesFmt is the current format for time series keys which
// record runtime system stats on a node.
runtimeStatTimeSeriesNameFmt = "cr.node.sys.%s"
)
type quantile struct {
suffix string
quantile float64
}
var recordHistogramQuantiles = []quantile{
{"-max", 100},
{"-p... | storeLevel[strconv.Itoa(int(id))] = reg
}
topLevel["stores"] = storeLevel
return json.Marshal(topLevel)
}
// GetTimeSeriesData serializes registered metrics for consumption by
// CockroachDB's time series system.
func (mr *MetricsRecorder) GetTimeSeriesData() []ts.TimeSeriesData {
mr.mu.Lock()
defer mr.mu.Unloc... | for id, reg := range mr.mu.storeRegistries { | random_line_split |
recorder.go | Prefix = "cr.node.%s"
// runtimeStatTimeSeriesFmt is the current format for time series keys which
// record runtime system stats on a node.
runtimeStatTimeSeriesNameFmt = "cr.node.sys.%s"
)
type quantile struct {
suffix string
quantile float64
}
var recordHistogramQuantiles = []quantile{
{"-max", 100},
{"-p... | (prefixFmt string, registry *metric.Registry) {
mr.nodeRegistry.MustAdd(prefixFmt, registry)
}
// AddStore adds the Registry from the provided store as a store-level registry
// in this recoder. A reference to the store is kept for the purpose of
// gathering some additional information which is present in store stat... | AddNodeRegistry | identifier_name |
sdkcallback.go | }
xylog.DebugNoId("forward request to %s", subj)
reply, err = nats_service.Request(subj, data, time.Duration(DefConfig.NatsTimeout)*time.Second)
if err != nil {
xylog.ErrorNoId("<%s> Error: %s", subj, err.Error())
return
} else {
if reply != nil {
resp = reply.Da... | rameterslice {
if parameterslice[k].key != "sign" {
keys = append(keys, parameterslice[k].key)
}
}
sort.Strings(keys) // 参数升序排序
for index, arg := range keys {
v, result := parameterslice.Get(arg)
if result {
uriStr = fmt.Sprintf("%s%s=%s", uriStr, arg... | identifier_body | |
sdkcallback.go | )
xylog.DebugNoId("req url :%v", r.RequestURI)
status = http.StatusOK
// uri, token = ProcessUri(uri)
// xylog.DebugNoId("uri=%s, token=%s, user agent=%s", uri, token, r.UserAgent())
// respData, err = ProcessHttpMsg(token, r)
respData, err = ProcessCallBackMsg(uri, r)
if err != xyerr... | error.ErrOK {
xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err)
err = xyerror.ErrOK
} else {
req.GoodsId = proto.Uint64(goodsId)
}
v = r.PostFormValue(CallParameter_Sandbox)
if v == "" {
xylog.ErrorNoId("get sandbox from parameterfail")
return nil, ... |
parameterSlice.Add(CallParameter_EXT, v)
goodsId, err = strconv.ParseUint(v, 10, 64)
if err != xy | conditional_block |
sdkcallback.go | )
xylog.DebugNoId("req url :%v", r.RequestURI)
status = http.StatusOK
// uri, token = ProcessUri(uri)
// xylog.DebugNoId("uri=%s, token=%s, user agent=%s", uri, token, r.UserAgent())
// respData, err = ProcessHttpMsg(token, r)
respData, err = ProcessCallBackMsg(uri, r)
if err != xyerr... | }
respone := &battery.SDKAddOrderResponse{}
err = proto.Unmarshal(respData, respone)
if err != nil {
resp = "unmarshal false"
return
}
if respone.Error.GetCode() != battery.ErrorCode_NoError {
resp = "add order fail"
return
}
resp = "ok"
return
}
/... | random_line_split | |
sdkcallback.go | error.ErrOK {
xylog.ErrorNoId("xyencoder.PbEncode failed : %v", err)
return
}
//进行加密
data, err = crypto.Encrypt(data)
if err != xyerror.ErrOK {
xylog.ErrorNoId("crypto.Encrypt failed : %v", err)
return
}
route = DefHttpPostTable.GetRoutePath(uri)
xylog.Debug... | := make([]stri | identifier_name | |
vjAnnotListTableView.js | ");
var checkedTbl = _mainControl_.checkedTable;
var objAdded = _mainControl_.objAdded;
for (var i=0; i<checkedTbl.selectedCnt; ++i) {
var curNode = checkedTbl.selectedNodes[i];
if (objAdded[curNode.seqID]) {
var curObj = objAdded[curNode.seqID]... | this.viewersArr.push(this.anotSubmitPanel);
} | random_line_split | |
vjAnnotListTableView.js | ObjList) this.referenceObjList = [];
if (!this.annotObjList) this.annotObjList = [];
var dsname = "dsAnnotList_table";
//this.annotTypeDS = this.vjDS.add("infrastructure: Folders Help", dsname, this.defaultAnnotUrl,0,"seqID,start,end,type,id\n");
this.annotTypeDS = this.vjDS.add("Loading annota... |
}
return 1;
}
function accumulateRows (viewer, node, ir,ic) {
var objAdded = _mainControl_.objAdded;
var range = "", seqID ="", type = "", id= "",strand = "+", checked = true;
if (viewer.myName && viewer.myName=="manualPanel")
{
seqID = view... | {
return dicPath[myArr[ia]];
} | conditional_block |
vjAnnotListTableView.js | 0; ia<myArr.length; ++ia) {
if (curPath.indexOf(myArr[ia])!=-1) {
return dicPath[myArr[ia]];
}
}
return 1;
}
function accumulateRows (viewer, node, ir,ic) {
var objAdded = _mainControl_.objAdded;
var range = "", seqID ="", type = "", i... | {
console.log("removing selected element");
var checkedTbl = _mainControl_.checkedTable;
var objAdded = _mainControl_.objAdded;
for (var i=0; i<checkedTbl.selectedCnt; ++i) {
var curNode = checkedTbl.selectedNodes[i];
if (objAdded[curNode.seqID]) {
... | identifier_body | |
vjAnnotListTableView.js | ObjList) this.referenceObjList = [];
if (!this.annotObjList) this.annotObjList = [];
var dsname = "dsAnnotList_table";
//this.annotTypeDS = this.vjDS.add("infrastructure: Folders Help", dsname, this.defaultAnnotUrl,0,"seqID,start,end,type,id\n");
this.annotTypeDS = this.vjDS.add("Loading annota... | (dicPath, curPath) {
var myArr = Object.keys(dicPath);
for (var ia=0; ia<myArr.length; ++ia) {
if (curPath.indexOf(myArr[ia])!=-1) {
return dicPath[myArr[ia]];
}
}
return 1;
}
function accumulateRows (viewer, node, ir,ic) {
va... | checkDirection | identifier_name |
fifo.rs | 00 dataset. We will use these joinable keys for understanding
// incremental execution.
const TEST_JOIN_RATIO: f64 = 0.01;
fn create_fifo_file(tmp_dir: &TempDir, file_name: &str) -> Result<PathBuf> {
let file_path = tmp_dir.path().join(file_name);
// Simulate an infinite environment via a F... | (
#[values(true, false)] unbounded_file: bool,
) -> Result<()> {
// Create session context
let config = SessionConfig::new()
.with_batch_size(TEST_BATCH_SIZE)
.with_collect_statistics(false)
.with_target_partitions(1);
let ctx = SessionContext::wit... | unbounded_file_with_swapped_join | identifier_name |
fifo.rs | ) = file.write_all(line.as_bytes()) {
if e.raw_os_error().unwrap() == 32 {
let interval = Instant::now().duration_since(ref_time);
if interval < broken_pipe_timeout {
thread::sleep(Duration::from_millis(100));
continue;
... | {
JoinOperation::RightUnmatched
} | conditional_block | |
fifo.rs | 00 dataset. We will use these joinable keys for understanding
// incremental execution.
const TEST_JOIN_RATIO: f64 = 0.01;
fn create_fifo_file(tmp_dir: &TempDir, file_name: &str) -> Result<PathBuf> {
let file_path = tmp_dir.path().join(file_name);
// Simulate an infinite environment via a F... | }
// This test provides a relatively realistic end-to-end scenario where
// we swap join sides to accommodate a FIFO source.
#[rstest]
#[timeout(std::time::Duration::from_secs(30))]
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
async fn unbounded_file_with_swapped_join(
... | }
}
return Err(DataFusionError::Execution(e.to_string()));
}
Ok(()) | random_line_split |
gpt.go |
return p, nil
}
func MustParseGUID(guid string) GUID {
p, err := ParseGUID(guid)
if err != nil {
panic(err)
}
return p
}
func (p GUID) String() string {
return fmt.Sprintf("%X-%X-%X-%X-%X",
endian.Read32be(p[0:]),
endian.Read32be(p[4:]),
endian.Read32be(p[6:]),
endian.Read32be(p[8:]),
endian.Read4... | {
var (
a uint32
b, c, d uint16
e uint64
p [16]byte
)
n, err := fmt.Sscanf(guid, "%x-%x-%x-%x-%x", &a, &b, &c, &d, &e)
if err != nil {
return p, err
}
if n != 5 {
return p, errors.New("invalid GUID format")
}
endian.Put32le(p[0:], a)
endian.Put16le(p[4:], b)
endian.Put16le(p[6:]... | identifier_body | |
gpt.go |
if d.MBR.Part[0].Type != 0xee {
return ErrHeader
}
d.Header, err = d.readHeader(int64(d.Sectsz))
if err != nil {
return err
}
d.Entries, err = d.readEntry(int64(d.Sectsz * 2))
if err != nil {
return err
}
return nil
}
func (d *decoder) readHeader(off int64) (Header, error) {
var h Header
sr := io.... | } | random_line_split | |
gpt.go | () error {
var err error
d.MBR, err = mbr.Open(d.r)
if err != nil {
return err
}
if d.MBR.Part[0].Type != 0xee {
return ErrHeader
}
d.Header, err = d.readHeader(int64(d.Sectsz))
if err != nil {
return err
}
d.Entries, err = d.readEntry(int64(d.Sectsz * 2))
if err != nil {
return err
}
return n... | decode | identifier_name | |
gpt.go |
d := decoder{
r: r,
Table: Table{Sectsz: o.Sectsz},
}
err := d.decode()
if err != nil {
return nil, err
}
return &d.Table, nil
}
type decoder struct {
Table
r io.ReaderAt
}
func (d *decoder) decode() error {
var err error
d.MBR, err = mbr.Open(d.r)
if err != nil {
return err
}
if d.MBR.Par... | {
o = &Option{Sectsz: 512}
} | conditional_block | |
serving.py | .
Examples:
.. code-block:: python
pid_is_exist(pid=8866)
'''
try:
os.kill(pid, 0)
except:
return False
else:
return True
@register(name='hub.serving', description='Start Module Serving or Bert Service for online predicting.')
class ServingCommand:
name = ... |
else:
if self.args.use_multiprocess:
if platform.system() == "Windows":
log.logger.warning(
"Warning: Windows cannot use multiprocess working mode, PaddleHub Serving will switch to single process mode"
)
... | if self.args.use_multiprocess:
log.logger.warning('`use_multiprocess` will be ignored if specify `use_gpu`.')
self.start_zmq_serving_with_args() | conditional_block |
serving.py | .
Examples:
.. code-block:: python
pid_is_exist(pid=8866)
'''
try:
os.kill(pid, 0)
except:
return False
else:
return True
@register(name='hub.serving', description='Start Module Serving or Bert Service for online predicting.')
class ServingCommand:
name = ... |
if not pid_is_exist(pid):
log.logger.info("PaddleHub Serving has been stopped.")
return
log.logger.info("PaddleHub Serving will stop.")
if platform.system() == "Windows":
os.kill(pid, signal.SIGTERM)
else:
try:
os.killpg(pi... | if os.path.exists(filepath):
os.remove(filepath) | random_line_split |
serving.py | .
Examples:
.. code-block:: python
pid_is_exist(pid=8866)
'''
try:
os.kill(pid, 0)
except:
return False
else:
return True
@register(name='hub.serving', description='Start Module Serving or Bert Service for online predicting.')
class ServingCommand:
name = ... |
@staticmethod
def show_help():
str = "serving <option>\n"
str += "\tManage PaddleHub Serving.\n"
str += "sub command:\n"
str += "1. start\n"
str += "\tStart PaddleHub Serving.\n"
str += "2. stop\n"
str += "\tStop PaddleHub Serving.\n"
str += "3. ... | '''
Start PaddleHub-Serving with flask and gunicorn
'''
if self.args.use_gpu:
if self.args.use_multiprocess:
log.logger.warning('`use_multiprocess` will be ignored if specify `use_gpu`.')
self.start_zmq_serving_with_args()
else:
if self... | identifier_body |
serving.py | .
Examples:
.. code-block:: python
pid_is_exist(pid=8866)
'''
try:
os.kill(pid, 0)
except:
return False
else:
return True
@register(name='hub.serving', description='Start Module Serving or Bert Service for online predicting.')
class ServingCommand:
name = ... | (args):
'''
Start bert serving server.
'''
if platform.system() != "Linux":
log.logger.error("Error. Bert Service only support linux.")
return False
if is_port_occupied("127.0.0.1", args.port) is True:
log.logger.error("Port %s is occupied, pl... | start_bert_serving | identifier_name |
main.rs | () -> Self {
let mut app = App::new("servicemanagement1")
.setting(clap::AppSettings::ColoredHelp)
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("0.1.0-20200619")
.about("Google Service Management allows service producers to publish their services on Go... | default | identifier_name | |
main.rs | , and is subject to mandatory 30-day\ndata retention. You cannot move a service or recreate it within 30 days\nafter deletion.\n\nOne producer project can own no more than 500 services. For security and\nreliability purposes, a production service should be hosted in a\ndedicated producer project.\n\nOperation<response:... | random_line_split | ||
main.rs | managed service. This method will change the service to the\n`Soft-Delete` state for 30 days. Within this period, service producers may\ncall UndeleteService to restore the service.\nAfter 30 days, the service will be permanently deleted.\n\nOperation<response: google.protobuf.Empty>");
services0 = service... | {
// TODO: set homedir afterwards, once the address is unmovable, or use Pin for the very first time
// to allow a self-referential structure :D!
let _home_dir = dirs::config_dir()
.expect("configuration directory can be obtained")
.join("google-service-cli");
let outer = Outer::default_... | identifier_body | |
cert.go | MemCert for more details.
type CertKind int
// Possible kinds of certificates.
const (
CertClient CertKind = iota
CertServer
)
// TestingKeyPair returns CertInfo object initialized with a test keypair. It's
// meant to be used only by tests.
func TestingKeyPair() *CertInfo {
keypair, err := tls.X509KeyPair(testCer... | CertificateTokenDecode | identifier_name | |
cert.go | convenience to return the underlying public key as an *x509.Certificate.
func (c *CertInfo) PublicKeyX509() (*x509.Certificate, error) {
return x509.ParseCertificate(c.KeyPair().Certificate[0])
}
// PrivateKey is a convenience to encode the underlying private key.
func (c *CertInfo) PrivateKey() []byte {
ecKey, ok ... | {
return fmt.Sprintf("%x", sha256.Sum256(cert.Raw))
} | identifier_body | |
cert.go | .Block{Type: "CERTIFICATE", Bytes: data})
}
// PublicKeyX509 is a convenience to return the underlying public key as an *x509.Certificate.
func (c *CertInfo) PublicKeyX509() (*x509.Certificate, error) {
return x509.ParseCertificate(c.KeyPair().Certificate[0])
}
// PrivateKey is a convenience to encode the underlying... | if err != nil {
hostname = "UNKNOWN"
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"LXD"},
CommonName: fmt.Sprintf("%s@%s", username, hostname),
},
NotBefore: validFrom,
NotAfter: validTo,
KeyUsage: x509.KeyUsageKeyEnciphe... | } else {
username = "UNKNOWN"
}
hostname, err := os.Hostname() | random_line_split |
cert.go | .Block{Type: "CERTIFICATE", Bytes: data})
}
// PublicKeyX509 is a convenience to return the underlying public key as an *x509.Certificate.
func (c *CertInfo) PublicKeyX509() (*x509.Certificate, error) {
return x509.ParseCertificate(c.KeyPair().Certificate[0])
}
// PrivateKey is a convenience to encode the underlying... |
dir = filepath.Dir(keyf)
err = os.MkdirAll(dir, 0750)
if err != nil {
return err
}
certBytes, keyBytes, err := GenerateMemCert(certtype, addHosts)
if err != nil {
return err
}
certOut, err := os.Create(certf)
if err != nil {
return fmt.Errorf("Failed to open %s for writing: %w", certf, err)
}
_, e... | {
return err
} | conditional_block |
ycsb.rs | bytes of the key matter, the rest are zero. The value is always zero.
self.workload.borrow_mut().abc(
|tenant, key| {
// First 11 bytes on the payload were already pre-populated with the
// extension name (3 bytes), and the table id (8... | {
error!("Client should be configured with exactly 1 port!");
std::process::exit(1);
} | conditional_block | |
ycsb.rs | out so far.
sent: u64,
// The inverse of the rate at which requests are to be generated. Basically, the time interval
// between two request generations in cycles.
rate_inv: u64,
// The time stamp at which the workload started generating requests in cycles.
start: u64,
// The time stamp ... | let mut p_get = self.payload_get.borrow_mut();
let mut p_put = self.payload_put.borrow_mut();
// XXX Heavily dependent on how `Ycsb` creates a key. Only the first four
// bytes of the key matter, the rest are zero. The value is always zero.
... | {
// Return if there are no more requests to generate.
if self.requests <= self.sent {
return;
}
// Get the current time stamp so that we can determine if it is time to issue the next RPC.
let curr = cycles::rdtsc();
// If it is either time to send out a req... | identifier_body |
ycsb.rs | , &p_put, curr)
},
);
}
// Update the time stamp at which the next request should be generated, assuming that
// the first request was sent out at self.start.
self.sent += 1;
self.next = self.start + self.sent * self.rate_i... | random_line_split | ||
ycsb.rs | out so far.
sent: u64,
// The inverse of the rate at which requests are to be generated. Basically, the time interval
// between two request generations in cycles.
rate_inv: u64,
// The time stamp at which the workload started generating requests in cycles.
start: u64,
// The time stamp ... | (port: T, resps: u64, master: bool, native: bool) -> YcsbRecv<T> {
YcsbRecv {
receiver: dispatch::Receiver::new(port),
responses: resps,
start: cycles::rdtsc(),
recvd: 0,
latencies: Vec::with_capacity(resps as usize),
master: master,
... | new | identifier_name |
workspace.rs | &Ellipsis)
.field("message_locale", &inner.message_locale)
.field("path", &inner.path)
.field("unit", &inner.unit)
.field("document", &inner.document)
.field("span", &inner.span.as_ref().map(|_| Ellipsis))
.field("tokens", &inner.tokens.as_ref().map(|_| Ellipsis))
... | (&mut self, version: u64,
event: protocol::TextDocumentContentChangeEvent) -> WorkspaceResult<()> {
// TODO, there are several ambiguities with offsets?
if event.range.is_some() || event.rangeLength.is_some() {
return Err(WorkspaceError("incremental edits not yet supp... | apply_change | identifier_name |
workspace.rs | ));
diags
}))
},
}
});
inner.tokens = Some(inner.pool.spawn(fut).boxed().shared());
}
inner.tokens.as_ref().unwrap().clone()
}
pub fn ensure_tokens(&self) -> ReportFuture<Arc<Vec<N... | random_line_split | ||
workspace.rs | source: Arc<RwLock<Source>>,
temp_units: Vec<Unit>, // will be gone after checking
temp_files: HashMap<PathBuf, Chunk>,
message_locale: Locale,
root_report: ReportTree,
}
#[derive(Clone)]
struct WorkspaceFsSource {
inner: Rc<RefCell<WorkspaceFsSourceInner>>,
}
impl FsSource for WorkspaceFsSou... | {
if let Ok(path) = uri_to_path(uri) {
let file = self.ensure_file(&path);
file.cancel();
let _ = file.ensure_chunk();
Some(file)
} else {
None
}
} | identifier_body | |
train.py | =0)
parser.add_argument('-mg', '--max_grad_norm', type=float, default=5.)
parser.add_argument('-m', '--model', type=str, choices=['vae', 'ae'], default='vae')
parser.add_argument('-eb', '--embedding_size', type=int, default=300)
parser.add_argument('-rnn', '--rnn_type', type=str, choices=['rnn', 'lstm'... | os.makedirs('dumps/' + ts) | conditional_block | |
train.py |
def loss_fn(NLL, logp, target, length, mean, logv, anneal_function, step, k, x0):
# cut-off unnecessary padding from target, and flatten
target = target[:, :torch.max(length).data[0]].contiguous().view(-1)
logp = logp.view(-1, logp.size(2))
# Negative Log Likelihood
nll_loss = NLL(logp, target)
... | if anneal_function == 'logistic':
return float(1/(1+np.exp(-k*(step-x0))))
elif anneal_function == 'linear':
return min(1, step/x0) | identifier_body | |
train.py | p = logp.view(-1, logp.size(2))
# Negative Log Likelihood
nll_loss = NLL(logp, target)
# KL Divergence
kl_loss = -0.5 * torch.sum(1 + logv - mean.pow(2) - logv.exp())
kl_weight = kl_anneal_function(anneal_function, step, k, x0)
return nll_loss, kl_loss, kl_weight
| parser = argparse.ArgumentParser()
parser.add_argument('--seed', help='random seed', type=int, default=19)
parser.add_argument('-gpu', '--gpu_id', help='GPU ID', type=int, default=0)
parser.add_argument('--run_dir', help='prefix to save ckpts to', type=str,
default=SCR_PREFIX + ... | def main(arguments): | random_line_split |
train.py | (NLL, logp, target, length, mean, logv, anneal_function, step, k, x0):
# cut-off unnecessary padding from target, and flatten
target = target[:, :torch.max(length).data[0]].contiguous().view(-1)
logp = logp.view(-1, logp.size(2))
# Negative Log Likelihood
nll_loss = NLL(logp, target)
# KL Div... | loss_fn | identifier_name | |
menu.rs | (),
cur_language: "en",
}
}
/// Adds the menu to the window - takes XID of window as parameter
pub fn add_to_window(&mut self, window_id: u32) {
self.window_id = Some(window_id);
// todo: notify app menu registrar here
println!("registered window!");
}
/... |
// ????
println!("about_to_show called!");
Ok(3)
}
| identifier_body | |
menu.rs | -> Self {
Self {
revision: Rc::new(RefCell::new(0)),
window_id: None,
menu: HashMap::new(),
cur_language: "en",
}
}
/// Adds the menu to the window - takes XID of window as parameter
pub fn add_to_window(&mut self, window_id: u32) {
s... | et_version( | identifier_name | |
menu.rs | .window_id = Some(window_id);
// todo: notify app menu registrar here
println!("registered window!");
}
/// Removes the menu
pub fn remove_from_window(&mut self) {
self.window_id = None;
// appmenu unregister window
// should also be called on drop
println!("... | random_line_split | ||
poll_evented.rs | @AsyncWrite
/// [`mio::Evented`]: trait@mio::Evented
/// [`Registration`]: struct@Registration
/// [`TcpListener`]: struct@crate::net::TcpListener
/// [`clear_read_ready`]: method@Self::clear_read_ready
/// [`clear_write_ready`]: method@Self::clear_write_ready
/// [`poll_read_ready`]: method@Sel... | poll_flush | identifier_name | |
poll_evented.rs | most two tasks that
/// use a `PollEvented` instance concurrently. One for reading and one for
/// writing. While violating this requirement is "safe" from a Rust memory
/// model point of view, it will result in unexpected behavior in the form
/// of lost notifications and tasks hanging.
///
/... |
/// Returns a shared reference to the underlying I/O object this readiness
/// stream is wrapping.
#[cfg(any(
feature = "process",
feature = "tcp",
feature = "udp",
feature = "uds",
feature = "signal"
))]
pub(crate) fn get_ref(&self) -> &E {
self.io.... | {
let registration = Registration::new_with_ready_and_handle(&io, ready, handle)?;
Ok(Self {
io: Some(io),
registration,
})
} | identifier_body |
poll_evented.rs | implement additional functions. For example,
/// [`TcpListener`] implements poll_accept by using [`poll_read_ready`] and
/// [`clear_read_ready`].
///
/// ## Platform-specific events
///
/// `PollEvented` also allows receiving platform-specific `mio::Ready` events.
/// These events are incl... | {
self.clear_readiness(ev);
continue;
} | conditional_block | |
poll_evented.rs | most two tasks that
/// use a `PollEvented` instance concurrently. One for reading and one for
/// writing. While violating this requirement is "safe" from a Rust memory
/// model point of view, it will result in unexpected behavior in the form
/// of lost notifications and tasks hanging.
///
/... | ///
/// # Warning
///
/// This method may not be called concurrently. It takes `&self` to allow
/// calling it concurrently with `poll_write_ready`.
pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.registration.poll_readiness(cx, Direction... | /// This function panics if:
///
/// * `ready` includes writable.
/// * called from outside of a task context. | random_line_split |
projects.ts | {
year: 2018,
name: {ru: 'Мобильное приложение Emotion Miner', en: 'Emotion Miner mobile app'},
description: {ru: 'Техническая демонстрация мобильного приложения для платформы Emotion Miner. Реализованы ключевые элементы управления приложением, заточенные под мобильные устройства. Проект подготовлен для за... | {
url: 'https://github.com/polyakovin/yourChoice2', | random_line_split | |
api.go | *dapr_pb.DeleteStateEnvelope) (*empty.Empty, error)
}
type api struct {
actor actors.Actors
directMessaging messaging.DirectMessaging
componentsHandler components.ComponentHandler
appChannel channel.AppChannel
stateStores map[string]state.Store
pubSub ... | {
dur, err := duration(in.Options.RetryPolicy.Interval)
if err == nil {
retryPolicy.Interval = dur
}
} | conditional_block | |
api.go | .WriteRequest) error
}
// NewAPI returns a new gRPC API
func NewAPI(daprID string, appChannel channel.AppChannel, stateStores map[string]state.Store, pubSub pubsub.PubSub, directMessaging messaging.DirectMessaging, actor actors.Actors, sendToOutputBindingFn func(name string, req *bindings.WriteRequest) error, componen... | getModifiedStateKey | identifier_name | |
api.go | 4 * 60 * 60)
minSeconds = -maxSeconds
daprSeparator = "||"
)
// API is the gRPC interface for the Dapr gRPC API. It implements both the internal and external proto definitions.
type API interface {
CallActor(ctx context.Context, in *daprinternal_pb.CallActorEnvelope) (*daprinternal_pb.InvokeResponse, error)
Cal... | for _, s := range in.Requests {
req := state.SetRequest{
Key: a.getModifiedStateKey(s.Key),
Metadata: s.Metadata,
Value: s.Value.Value,
}
if s.Options != nil {
req.Options = state.SetStateOption{
Consistency: s.Options.Consistency,
Concurrency: s.Options.Concurrency,
}
if s.Opti... |
reqs := []state.SetRequest{} | random_line_split |
api.go | 4 * 60 * 60)
minSeconds = -maxSeconds
daprSeparator = "||"
)
// API is the gRPC interface for the Dapr gRPC API. It implements both the internal and external proto definitions.
type API interface {
CallActor(ctx context.Context, in *daprinternal_pb.CallActorEnvelope) (*daprinternal_pb.InvokeResponse, error)
Cal... | Consistency: s.Options.Consistency,
Concurrency: s.Options.Concurrency,
}
if s.Options.RetryPolicy != nil {
req.Options.RetryPolicy = state.RetryPolicy{
Threshold: int(s.Options.RetryPolicy.Threshold),
Pattern: s.Options.RetryPolicy.Pattern,
}
if s.Options.RetryPolicy.Interval != n... | {
if a.stateStores == nil || len(a.stateStores) == 0 {
return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED")
}
storeName := in.StoreName
if a.stateStores[storeName] == nil {
return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_FOUND")
}
reqs := []state.SetRequest{}
for _, s := range in.Req... | identifier_body |
relay.py | _PUMP, GD.SYSTEM_UFH_PUMP) : return
# Get the I2C parameters from our system control data.
address = system.systemControl [systemRelay].GetAddress ()
mask = system.systemControl [systemRelay].GetBitMask ()
# Read existing relay status for all relay bits at this address.
relayStatus = I2CPort.... |
################################################################################
##
## Function: ActivateHeatingZoneRelay (I2CPort, relayZone)
##
## Parameters: I2CPort - I2C smbus object
## relayZone - integer - the zone to check if activation required.
##
## Returns:
##
## Globals modified:
##
#... | relayStatus = I2CPort.read_byte (register)
# Set the relay to pulse (active low pulse).
relayStatus &= ~relayBit
# Pulse it low.
I2CPort.write_byte (register, relayStatus)
print 'pulse on ', hex(relayStatus^0xff)
# Give it some time to activate.
time.sleep (0.1)
# Now set up to cl... | identifier_body |
relay.py | _PUMP, GD.SYSTEM_UFH_PUMP) : return
# Get the I2C parameters from our system control data.
address = system.systemControl [systemRelay].GetAddress ()
mask = system.systemControl [systemRelay].GetBitMask ()
# Read existing relay status for all relay bits at this address.
relayStatus = I2CPort.... | (I2CPort) :
for systemOutput in GD.SYSTEM_PULSED_OUTPUTS_GROUP :
if system.systemControl [systemOutput].CheckIfBitTimerFinished () == True :
ActivateSystemRelay (I2CPort, systemOutput, False)
print 'SET IT LOW'
#############################################################... | UpdatePulsedOutputLines | identifier_name |
relay.py | _PUMP, GD.SYSTEM_UFH_PUMP) : return
# Get the I2C parameters from our system control data.
address = system.systemControl [systemRelay].GetAddress ()
mask = system.systemControl [systemRelay].GetBitMask ()
# Read existing relay status for all relay bits at this address.
relayStatus = I2CPort.... |
# Has the status changed or is it time for cleardown on this zone?
if statusChanged or clearDown :
print 'STATUS CHANGED'
# Select the correct I2C status register for UFH or RAD relays.
register = GD.I2C_ADDRESS_0X38 if relayZone >= 14 else GD.I2C_ADDRESS_0X39
# R... | zones.zoneData[relayZone].UpdateCurrentZoneStatus() | conditional_block |
relay.py |
# TEMP TO ALLOW WITHOUT SYSTEM HARDWARE
## if systemRelay not in (GD.SYSTEM_RAD_PUMP, GD.SYSTEM_UFH_PUMP) : return
# Get the I2C parameters from our system control data.
address = system.systemControl [systemRelay].GetAddress ()
mask = system.systemControl [systemRelay].GetBitMask ()
# Re... | random_line_split | ||
util.rs | , v, on_inserted).await?;
}
}
&Ipld::Link(cid) => {
// WASM blocks are stored as IPLD_RAW. They should be loaded but not traversed.
if cid.codec() == crate::shim::crypto::IPLD_RAW {
if !walked.insert(cid) {
return Ok(());
... | }
}
enum Task {
// Yield the block, don't visit it.
Emit(Cid),
// Visit all the elements, recursively.
Iterate(DfsIter),
}
pin_project! {
pub struct ChainStream<DB, T> {
#[pin]
tipset_iter: T,
db: DB,
dfs: VecDeque<Task>, // Depth-first work queue.
seen:... | Ipld::Map(map) => map.into_values().rev().for_each(|elt| self.walk_next(elt)),
other => return Some(other),
}
}
None | random_line_split |
util.rs | v, on_inserted).await?;
}
}
&Ipld::Link(cid) => {
// WASM blocks are stored as IPLD_RAW. They should be loaded but not traversed.
if cid.codec() == crate::shim::crypto::IPLD_RAW {
if !walked.insert(cid) {
return Ok(());
... |
/// Depth-first-search iterator for `ipld` leaf nodes.
///
/// This iterator consumes the given `ipld` structure and returns leaf nodes (i.e.,
/// no list or map) in depth-first order. The iterator can be extended at any
/// point by the caller.
///
/// Consider walking this `ipld` graph:
/// ```text
/// List
/// ├ ... | {
// Don't include identity CIDs.
// We only include raw and dagcbor, for now.
// Raw for "code" CIDs.
if cid.hash().code() == u64::from(cid::multihash::Code::Identity) {
false
} else {
matches!(
cid.codec(),
crate::shim::crypto::IPLD_RAW | fvm_ipld_encoding::... | identifier_body |
util.rs | v, on_inserted).await?;
}
}
&Ipld::Link(cid) => {
// WASM blocks are stored as IPLD_RAW. They should be loaded but not traversed.
if cid.codec() == crate::shim::crypto::IPLD_RAW {
if !walked.insert(cid) {
return Ok(());
... | Yield the block, don't visit it.
Emit(Cid),
// Visit all the elements, recursively.
Iterate(DfsIter),
}
pin_project! {
pub struct ChainStream<DB, T> {
#[pin]
tipset_iter: T,
db: DB,
dfs: VecDeque<Task>, // Depth-first work queue.
seen: CidHashSet,
statero... | // | identifier_name |
octree_gui.rs | ::new()
.with_title("Octree - Config")
.with_decorations(true)
.with_inner_size(glutin::dpi::LogicalSize::new(420f64, 768f64));
let display =
Display::new(builder, context, &nse.event_loop).expect("Failed to initialize display");
let mut platform = WinitP... | (&mut self) -> Vec<Filter> {
vec![
crate::filter!(Octree, Mesh, Transformation),
crate::filter!(Camera, Transformation),
]
}
fn handle_input(&mut self, _event: &Event<()>) {
let platform = &mut self.platform;
let display = self.display.lock().unwrap();
... | get_filter | identifier_name |
octree_gui.rs | ::new()
.with_title("Octree - Config")
.with_decorations(true)
.with_inner_size(glutin::dpi::LogicalSize::new(420f64, 768f64));
let display =
Display::new(builder, context, &nse.event_loop).expect("Failed to initialize display");
let mut platform = WinitP... |
fn handle_input(&mut self, _event: &Event<()>) {
let platform = &mut self.platform;
let display = self.display.lock().unwrap();
let gl_window = display.gl_window();
let mut imgui = self.imgui.lock().unwrap();
match _event {
Event::MainEventsCleared => {
... | {
vec![
crate::filter!(Octree, Mesh, Transformation),
crate::filter!(Camera, Transformation),
]
} | identifier_body |
octree_gui.rs | Builder::new()
.with_title("Octree - Config")
.with_decorations(true)
.with_inner_size(glutin::dpi::LogicalSize::new(420f64, 768f64));
let display =
Display::new(builder, context, &nse.event_loop).expect("Failed to initialize display");
let mut platform =... | view_dir.as_mut(),
).read_only(true).build();
InputFloat3::new(
&ui,
im_str!("Camera Position"),
camera_transform.position.as_mut(),
).build();
camera_transform.update();
}
}
}
impl System for ... | random_line_split | |
lib.rs | ().unwrap();
//! max30102.set_pulse_amplitude(Led::All, 15).unwrap();
//! max30102.set_led_time_slots([
//! TimeSlot::Led1,
//! TimeSlot::Led2,
//! TimeSlot::Led1,
//! TimeSlot::Disabled
//! ]).unwrap();
//! max30102.enable_fifo_rollover().unwrap();
//! let mut data = [0; 2];
//! let samples_read = max3... | ter(()); | identifier_name | |
lib.rs | x.html#method.read_interrupt_status
//! [`enable_fifo_almost_full_interrupt()`]: struct.Max3010x.html#method.enable_fifo_almost_full_interrupt
//! [`enable_alc_overflow_interrupt()`]: struct.Max3010x.html#method.enable_alc_overflow_interrupt
//! [`enable_temperature_ready_interrupt()`]: struct.Max3010x.html#method.enab... | pub alc_overflow: bool,
/// Internal die temperature conversion ready interrupt
pub temperature_ready: bool,
}
| random_line_split | |
grpc.go | GrpcClient, error) {
var descSource grpcurl.DescriptorSource
if addr == "" {
return nil, fmt.Errorf("addr should not be empty")
}
conn, err := grpc.Dial(addr, opts...)
if err != nil {
return nil, fmt.Errorf("did not connect: %v", err)
}
if len(protos) > 0 {
descSource, err := grpcurl.DescriptorSourceFro... | c := rpb.NewServerReflectionClient(conn)
refClient := grpcreflect.NewClient(clientCTX, c)
descSource = grpcurl.DescriptorSourceFromServer(clientCTX, refClient)
return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil
}
func (gc *GrpcClient) ListServices() ([]string, error) {
svcs, err := grpcurl.ListSer... |
// fetch from server reflection RPC | random_line_split |
grpc.go | GrpcClient, error) {
var descSource grpcurl.DescriptorSource
if addr == "" {
return nil, fmt.Errorf("addr should not be empty")
}
conn, err := grpc.Dial(addr, opts...)
if err != nil {
return nil, fmt.Errorf("did not connect: %v", err)
}
if len(protos) > 0 {
descSource, err := grpcurl.DescriptorSourceFro... | (mtd string, handler func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error) error {
if _, exists := gs.handlerM[mtd]; exists {
logger.Warnf("protocols/grpc", "handler for method %s exists, will be overrided", mtd)
}
gs.handlerM[mtd] = handler
return nil
}
// NOTE: thread unsafe, use loc... | SetMethodHandler | identifier_name |
grpc.go | GrpcClient, error) {
var descSource grpcurl.DescriptorSource
if addr == "" {
return nil, fmt.Errorf("addr should not be empty")
}
conn, err := grpc.Dial(addr, opts...)
if err != nil {
return nil, fmt.Errorf("did not connect: %v", err)
}
if len(protos) > 0 {
descSource, err := grpcurl.DescriptorSourceFro... | return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err)
}
sd := dsc.(*desc.ServiceDescriptor)
unaryMethods := []grpc.MethodDesc{}
streamMethods := []grpc.StreamDesc{}
for _, mtd := range sd.GetMethods() {
logger.Debugf("protocols/grpc", "try to add method: %v of service: %s", mtd,... | {
descFromProto, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...)
if err != nil {
return nil, fmt.Errorf("cannot parse proto file: %v", err)
}
gs := &GrpcServer{
addr: addr,
desc: descFromProto,
server: grpc.NewServer(opts...),
handlerM: map[string]func(in *dynamic.Message, o... | identifier_body |
grpc.go | GrpcClient, error) {
var descSource grpcurl.DescriptorSource
if addr == "" {
return nil, fmt.Errorf("addr should not be empty")
}
conn, err := grpc.Dial(addr, opts...)
if err != nil {
return nil, fmt.Errorf("did not connect: %v", err)
}
if len(protos) > 0 {
descSource, err := grpcurl.DescriptorSourceFro... |
return nil
}
func (gs *GrpcServer) ListMethods() ([]string, error) {
methods := []string{}
services, err := grpcurl.ListServices(gs.desc)
if err != nil {
return nil, fmt.Errorf("failed to list services")
}
for _, svcName := range services {
dsc, err := gs.desc.FindSymbol(svcName)
if err != nil {
return... | {
delete(gs.handlerM, mtd)
} | conditional_block |
asn1.rs | pub type MaxSize<C> =
<<<C as elliptic_curve::Curve>::FieldSize as Add>::Output as Add<MaxOverhead>>::Output;
/// Byte array containing a serialized ASN.1 signature
type DocumentBytes<C> = GenericArray<u8, MaxSize<C>>;
/// ASN.1 `INTEGER` tag
const INTEGER_TAG: u8 = 0x02;
/// ASN.1 `SEQUENCE` tag
const SEQUENCE_... | (&self) -> &[u8] {
&self.bytes.as_slice()[..self.len()]
}
/// Serialize this signature as a boxed byte slice
#[cfg(feature = "alloc")]
pub fn to_bytes(&self) -> Box<[u8]> {
self.as_bytes().to_vec().into_boxed_slice()
}
/// Create an ASN.1 DER encoded signature from big endian `... | as_bytes | identifier_name |
asn1.rs | pub type MaxSize<C> =
<<<C as elliptic_curve::Curve>::FieldSize as Add>::Output as Add<MaxOverhead>>::Output;
/// Byte array containing a serialized ASN.1 signature
type DocumentBytes<C> = GenericArray<u8, MaxSize<C>>;
/// ASN.1 `INTEGER` tag
const INTEGER_TAG: u8 = 0x02;
/// ASN.1 `SEQUENCE` tag
const SEQUENCE_... | serialize_int(r, &mut bytes[offset..], r_len, scalar_size);
let r_end = offset.checked_add(2).unwrap().checked_add(r_len).unwrap();
// Second INTEGER (s)
serialize_int(s, &mut bytes[r_end..], s_len, scalar_size);
let s_end = r_end.checked_add(2).unwrap().checked_add(s_len).unwra... | {
let r_len = int_length(r);
let s_len = int_length(s);
let scalar_size = C::FieldSize::to_usize();
let mut bytes = DocumentBytes::<C>::default();
// SEQUENCE header
bytes[0] = SEQUENCE_TAG as u8;
let zlen = r_len.checked_add(s_len).unwrap().checked_add(4).unwrap... | identifier_body |
asn1.rs | C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
{
/// Parse an ASN.1 DER-encoded ECDSA signature from a byte slice
fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
bytes.try_into()
}
}
#[allow(clippy::len_without_is_empty)]
impl<C> Signature<C>
where
C: Curve,
C::Field... | {
return Err(Error::new());
} | conditional_block | |
asn1.rs | pub type MaxSize<C> =
<<<C as elliptic_curve::Curve>::FieldSize as Add>::Output as Add<MaxOverhead>>::Output;
/// Byte array containing a serialized ASN.1 signature
type DocumentBytes<C> = GenericArray<u8, MaxSize<C>>;
/// ASN.1 `INTEGER` tag
const INTEGER_TAG: u8 = 0x02;
/// ASN.1 `SEQUENCE` tag
const SEQUENCE_... | if s_end != bytes.as_ref().len() {
return Err(Error::new());
}
let mut byte_arr = DocumentBytes::<C>::default();
byte_arr[..s_end].copy_from_slice(bytes.as_ref());
Ok(Signature {
bytes: byte_arr,
r_range: Range {
start: r_star... | let s_range = parse_int(&bytes[r_end..], C::FieldSize::to_usize())?;
let s_start = r_end.checked_add(s_range.start).unwrap();
let s_end = r_end.checked_add(s_range.end).unwrap();
| random_line_split |
lsp_plugin.rs | file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS ... | (
&mut self,
language_id: &str,
workspace_root: &Option<Url>,
) -> Option<(String, Arc<Mutex<LanguageServerClient>>)> {
workspace_root
.clone()
.map(|r| r.into_string())
.or_else(|| {
let config = &self.config.language_config[langua... | get_lsclient_from_workspace_root | identifier_name |
lsp_plugin.rs | file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS ... | Err(err) => {
error!(
"Error occured while starting server for Language: {}: {:?}",
language_id, err
);
None
}
... | {
let config = &self.config.language_config[language_id];
let client = start_new_server(
config.start_command.clone(),
config.start_arguments.clone(),
config.extensions.clone(),
langua... | conditional_block |
lsp_plugin.rs | file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS ... | Err(err) => {
error!(
"Error occured while starting server for Language: {}: {:?}",
language_id, err
);
None
}
... | self.language_server_clients
.insert(language_server_identifier.clone(), client);
Some((language_server_identifier, client_clone))
} | random_line_split |
lsp_plugin.rs | except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF AN... |
fn new_view(&mut self, view: &mut View<Self::Cache>) {
trace!("new view {}", view.get_id());
let document_text = view.get_document().unwrap();
let path = view.get_path();
let view_id = view.get_id();
// TODO: Use Language Idenitifier assigned by core when the
// i... | {
trace!("close view {}", view.get_id());
self.with_language_server_for_view(view, |ls_client| {
ls_client.send_did_close(view.get_id());
});
} | identifier_body |
cluster.ts | id: string, props: ClusterProps) {
super(scope, id);
this.vpc = props.vpc;
this.vpcSubnets = props.vpcSubnets ?? {
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
};
this.parameterGroup = props.parameterGroup;
this.roles = props?.roles ? [...props.roles] : [];
const removalPolicy = ... | resourceName: this.clusterName,
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
}),
], | random_line_split | |
cluster.ts |
*/
readonly clusterName: string;
/**
* Cluster endpoint address
*/
readonly clusterEndpointAddress: string;
/**
* Cluster endpoint port
*/
readonly clusterEndpointPort: number;
}
/**
* Properties for a new database cluster
*/
export interface ClusterProps {
/**
* An optional identi... | (): secretsmanager.SecretAttachmentTargetProps {
return {
targetId: this.clusterName,
targetType: secretsmanager.AttachmentTargetType.REDSHIFT_CLUSTER,
};
}
}
/**
* Create a Redshift cluster a given number of nodes.
*
* @resource AWS::Redshift::Cluster
*/
export class Cluster extends ClusterB... | asSecretAttachmentTarget | identifier_name |
cluster.ts | more time to complete, but it can be useful in cases where the change in node count or
* the node type to migrate to doesn't fall within the bounds for elastic resize.
*
* @see https://docs.aws.amazon.com/redshift/latest/mgmt/managing-cluster-operations.html#elastic-resize
*
* @default - Elastic resize ... | {
throw new Error('A single user rotation was already added to this cluster.');
} | conditional_block | |
cluster.ts |
*/
readonly clusterName: string;
/**
* Cluster endpoint address
*/
readonly clusterEndpointAddress: string;
/**
* Cluster endpoint port
*/
readonly clusterEndpointPort: number;
}
/**
* Properties for a new database cluster
*/
export interface ClusterProps {
/**
* An optional identi... |
/**
* Identifier of the cluster
*/
public readonly clusterName: string;
/**
* The endpoint to use for read/write operations
*/
public readonly clusterEndpoint: Endpoint;
/**
* Access to the network connections
*/
public readonly connections: ec2.Connections;
/**
* The secret atta... | {
class Import extends ClusterBase {
public readonly connections = new ec2.Connections({
securityGroups: attrs.securityGroups,
defaultPort: ec2.Port.tcp(attrs.clusterEndpointPort),
});
public readonly clusterName = attrs.clusterName;
public readonly instanceIdentifiers: strin... | identifier_body |
ipProcess.py | of class instances containing recorded data.
a = []
for t in range(len(fileArr)):
a.append(fileClass())
# Read the data in from the files.
for t in range(len(a)):
# Packet choice if saving raw voltages.
rawPkt = 102 # 1-indexed.
filePath = os.path.join(rawFolder, fileA... |
elif lidx == 7:
# Voltage measurement names.
# 0-indexed by channel number.
self.measStr = line.split(',')
elif lidx == 8:
# Construct arrays using the scipy package.
# 5B amplifier maxim... | (self.rCurrentMeas, # (Ohm) resistance.
self.rExtraSeries) = line.split(',') # (Ohm).
# Type casting.
self.rCurrentMeas = float(self.rCurrentMeas)
self.rExtraSeries = float(self.rCurrentMeas) | conditional_block |
ipProcess.py | enumerate(fh, 1):
# Strip off trailing newline characters.
line = line.rstrip('\n')
if s >= 0:
# Read in raw voltage values.
self.raw[:, p, s] = (
sp.fromstring(line, dtype=float, sep=','))
... | phys = sp.zeros_like(pct, dtype=float)
for ch in range(self.chCount):
phys[ch, :] = (pct[ch, :] / 100 *
self.ALoadQHi[ch] * self.In5BHi[ch] /
self.Out5BHi[ch]) # (V)
# Convert the voltage on the current measurement channel to a current.
... | identifier_body | |
ipProcess.py | string(line, dtype=float, sep=','))
if s == self.n - 1:
# Reset the counter to below zero.
s = -1
else:
# Increment the sample counter for the next read.
s += 1
elif li... | postRead | identifier_name | |
ipProcess.py | of class instances containing recorded data.
a = []
for t in range(len(fileArr)):
a.append(fileClass())
# Read the data in from the files.
for t in range(len(a)):
# Packet choice if saving raw voltages.
rawPkt = 102 # 1-indexed.
filePath = os.path.join(rawFolder, fileA... | if qp == 3 or qp == 4 or qp == 5:
typ = float # Means are saved as floats.
else:
typ = int # Counts are saved as integers.
assignArr = sp.fromstring(line, dtype=typ, sep=',')
... | self.longi[p] = float(self.longi[p])
elif qp < 7:
qp += 1 | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.