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 |
|---|---|---|---|---|
main.go | (), repoOwner, repoName, &ref)
if err != nil {
return errors.Wrap(err, "error creating tag ref")
}
return nil
}
type bottleDefinition struct {
Hash string
TargetOS string
}
type formulaTemplateData struct {
Tag string
CommitSHA string
HomebrewRevision uint
BaseDownloadURL string
B... | {
return nil, nil, errors.Wrap(err, "error executing bottle filename template: "+d.OS)
} | conditional_block | |
main.go | expected [owner]/[repo]): %v", taprepo)
}
if rname == "" {
ferr("release name is required")
}
trowner = trs[0]
trname = trs[1]
osvs = strings.Split(targetoslist, ",")
if len(osvs) == 0 {
ferr("At least one MacOS version is required")
}
ghtoken = os.Getenv("GITHUB_TOKEN")
if ghtoken == "" {
ferr("GITHUB_... | (paths ...string) error {
for _, p := range paths {
if _, err := os.Stat(p); err != nil {
return errors.Wrap(err, "file error")
}
}
return nil
}
func createGitTag() error {
msg := fmt.Sprintf("release %v", rname)
ot := "commit"
tag := github.Tag{
Tag: &rname,
Message: &msg,
Object: &github.GitOb... | checkFiles | identifier_name |
shard_consumer.go | this RecordProcessor (resharding use case).
* Indicates that the shard is closed and all records from the shard have been delivered to the application.
* Applications SHOULD checkpoint their progress to indicate that they have successfully processed all records
* from this shard and processing of child shards ca... | input := &ProcessRecordsInput{
Records: getResp.Records, | random_line_split | |
shard_consumer.go | KMSThrottlingException is defined in the API Reference https://docs.aws.amazon.com/sdk-for-go/api/service/kinesis/#Kinesis.GetRecords
// But it's not a constant?
ErrCodeKMSThrottlingException = "KMSThrottlingException"
/**
* Indicates that the entire application is being shutdown, and if desired the record proces... | (ctx context.Context) error {
defer sc.releaseLease(ctx)
log := sc.cfg.Log
shard := sc.shard
// If the shard is child shard, need to wait until the parent finished.
if err := sc.waitOnParentShard(ctx); err != nil {
// If parent shard has been deleted by Kinesis system already, just ignore the error.
if err !=... | run | identifier_name |
shard_consumer.go |
}
func (ss *ShardStatus) SetLeaseOwner(owner string) {
ss.Mux.Lock()
defer ss.Mux.Unlock()
ss.AssignedTo = owner
}
//type ShardConsumerState int
// ShardConsumer is responsible for consuming data records of a (specified) shard.
type ShardConsumer struct {
streamName string
shard *ShardStatus
kc... | {
return nil, err
} | conditional_block | |
shard_consumer.go | KMSThrottlingException is defined in the API Reference https://docs.aws.amazon.com/sdk-for-go/api/service/kinesis/#Kinesis.GetRecords
// But it's not a constant?
ErrCodeKMSThrottlingException = "KMSThrottlingException"
/**
* Indicates that the entire application is being shutdown, and if desired the record proces... | // Start processing events and notify record processor on shard and starting checkpoint
sc.recordProcessor.Initialize(ctx, &InitializationInput{
ShardID: shard.ID,
ExtendedSequenceNumber: &ExtendedSequenceNumber{SequenceNumber: aws.String(shard.Checkpoint)},
})
recordCheckpointer := NewRecordPro... | {
defer sc.releaseLease(ctx)
log := sc.cfg.Log
shard := sc.shard
// If the shard is child shard, need to wait until the parent finished.
if err := sc.waitOnParentShard(ctx); err != nil {
// If parent shard has been deleted by Kinesis system already, just ignore the error.
if err != ErrSequenceIDNotFound {
... | identifier_body |
cursor.rs | pos: u64,
}
impl<T> Cursor<T> {
/// Creates a new cursor wrapping the provided underlying in-memory buffer.
///
/// Cursor initial position is `0` even if underlying buffer (e.g., [`Vec`])
/// is not empty. So writing to cursor starts with overwriting [`Vec`]
/// content, not with appending to it.... | T: Clone,
{
#[inline]
fn clone(&self) -> Self {
Cursor { inner: self.inner.clone(), pos: self.pos }
}
#[inline]
fn clone_from(&mut self, other: &Self) {
self.inner.clone_from(&other.inner);
self.pos = other.pos;
}
}
impl<T> io::Seek for Cursor<T>
where
T: AsRef<... | where | random_line_split |
cursor.rs | n),
SeekFrom::Current(n) => (self.pos, n),
};
match base_pos.checked_add_signed(offset) {
Some(n) => {
self.pos = n;
Ok(self.pos)
}
None => Err(io::const_io_error!(
ErrorKind::InvalidInput,
"... | flush | identifier_name | |
cursor.rs | a reference to the underlying value in this cursor.
///
/// # Examples
///
/// ```
/// use std::io::Cursor;
///
/// let buff = Cursor::new(Vec::new());
/// # fn force_inference(_: &Cursor<Vec<u8>>) {}
/// # force_inference(&buff);
///
/// let reference = buff.get_ref();
... | {
// We want our vec's total capacity
// to have room for (pos+buf_len) bytes. Reserve allocates
// based on additional elements from the length, so we need to
// reserve the difference
vec.reserve(desired_cap - vec.len());
} | conditional_block | |
cursor.rs | ),
};
match base_pos.checked_add_signed(offset) {
Some(n) => {
self.pos = n;
Ok(self.pos)
}
None => Err(io::const_io_error!(
ErrorKind::InvalidInput,
"invalid seek to a negative or overflowing position",
... | {
Ok(())
} | identifier_body | |
lib.rs | _macro_back_compat,
proc_macro_derive_resolution_fallback,
pub_use_of_private_extern_crate,
redundant_semicolons,
repr_transparent_external_private_fields,
rust_2021_incompatible_closure_captures,
rust_2021_incompatible_or_patterns,
rust_2021_prefixes_incompatible_syntax,
rust_2021_prelu... | {
client::create(connection_string)
} | identifier_body | |
lib.rs | path_statements,
patterns_in_fns_without_body,
pointer_structural_match,
private_in_public,
proc_macro_back_compat,
proc_macro_derive_resolution_fallback,
pub_use_of_private_extern_crate,
redundant_semicolons,
repr_transparent_external_private_fields,
rust_2021_incompatible_closure_... | create | identifier_name | |
lib.rs | _generic_items,
non_ascii_idents,
non_camel_case_types,
non_fmt_panics,
non_shorthand_field_patterns,
non_snake_case,
non_upper_case_globals,
nontrivial_structural_match,
noop_method_call,
opaque_hidden_inferred_bound,
order_dependent_trait_objects,
overflowing_literals,
... | ///
/// ``` | random_line_split | |
pc_v0.py | 1/f1.cdb',
'USER': 'sysdba',
'PASSWORD': DBPASS_F1,
'HOST': 'localhost',
'PORT': 23050,
# 'HOST': '192.168.1.98',
# 'PORT': 3050,
'OPTIONS': {'charset': 'WIN1252'},
'TIME_ZONE': None,
'CONN_MAX_AGE': None,
'AUTOCOMMIT': None,
'DIALE... |
def set_cursor(self):
self.cursor = self.con.cursor()
# help(self.cursor)
# raise SystemExit
def close(self):
self.con.close()
def execute(self, sql):
self.cursor.execute(sql)
def executemany(self, sql, list_tuples):
# "insert into languages (name, ye... | raise e | conditional_block |
pc_v0.py | 1/f1.cdb',
'USER': 'sysdba',
'PASSWORD': DBPASS_F1,
'HOST': 'localhost',
'PORT': 23050,
# 'HOST': '192.168.1.98',
# 'PORT': 3050,
'OPTIONS': {'charset': 'WIN1252'},
'TIME_ZONE': None,
'CONN_MAX_AGE': None,
'AUTOCOMMIT': None,
'DIALE... | def dictlist(cursor):
return custom_dictlist(cursor)
def dictlist_lower(cursor):
return custom_dictlist(cursor, name_case=str.lower)
def tira_acento(texto):
process = unicodedata.normalize("NFD", texto)
process = process.encode("ascii", "ignore")
return process.decode("utf-8")
def tira_acento_up... | return dictlist_zip_columns(cursor, columns)
| random_line_split |
pc_v0.py | /f1.cdb',
'USER': 'sysdba',
'PASSWORD': DBPASS_F1,
'HOST': 'localhost',
'PORT': 23050,
# 'HOST': '192.168.1.98',
# 'PORT': 3050,
'OPTIONS': {'charset': 'WIN1252'},
'TIME_ZONE': None,
'CONN_MAX_AGE': None,
'AUTOCOMMIT': None,
'DIALEC... |
def exec_pg(self, sql, dados):
# pprint(sql)
# pprint(dados)
self.connect_pg('persona')
self.set_cursor_pg()
self.pgcursor.execute(sql, dados)
self.pgcon.commit()
self.pgcursor.close()
self.pgcon.close()
def testa_insert_pg(self):
self.... | ata = self.fetch_pg("""
select
p.codigo
, p.descricao
from contabil.planosauxiliares p
where p.codigo = 'SCC ANSELMO'
""")
pprint(data)
| identifier_body |
pc_v0.py | /f1.cdb',
'USER': 'sysdba',
'PASSWORD': DBPASS_F1,
'HOST': 'localhost',
'PORT': 23050,
# 'HOST': '192.168.1.98',
# 'PORT': 3050,
'OPTIONS': {'charset': 'WIN1252'},
'TIME_ZONE': None,
'CONN_MAX_AGE': None,
'AUTOCOMMIT': None,
'DIALEC... | self, sql):
self.connect_pg('persona')
self.set_cursor_pg()
self.pgcursor.execute(sql)
# data = self.pgcursor.fetchall()
data = dictlist_lower(self.pgcursor)
self.pgcon.close()
return data
def testa_pg(self):
data = self.fetch_pg("""
s... | etch_pg( | identifier_name |
structs.rs | , eg: sending
/// the same message using multiple Middleman structs.
///
/// Note that this function does NOT check for internal consistency of the packed message.
/// So, if this message was constructed by a means other than `Packed::new`, then the
/// results may be unpredictable.
pub fn send... | return Ok(Some(msg));
} else {
poll.poll(events, timeout).expect("poll() failed inside `recv_blocking()`");
if let Some(t) = timeout {
// update remaining timeout
let since = started_at.elapsed();
if ... | // message ready to go. Exiting loop | random_line_split |
structs.rs | eg: sending
/// the same message using multiple Middleman structs.
///
/// Note that this function does NOT check for internal consistency of the packed message.
/// So, if this message was constructed by a means other than `Packed::new`, then the
/// results may be unpredictable.
pub fn send_... |
let started_at = time::Instant::now();
let mut res = None;
loop {
for event in events.iter() {
let tok = event.token();
if res.is_none() && tok == my_tok {
if ! event.readiness().is_readable() {
continue;
... | {
// trivial case.
// message was already sitting in the buffer.
return Ok(Some(msg));
} | conditional_block |
structs.rs | : &mut Vec<Event>,
mut timeout: Option<time::Duration>) -> Result<Option<M>, RecvError> {
if let Some(msg) = self.recv::<M>()? {
// trivial case.
// message was already sitting in the buffer.
return Ok(Some(msg));
}
let starte... | reregister | identifier_name | |
structs.rs | /// loop with a drain() on the same vector passed here as extra_events (using the iterator chain function, for example.)
pub fn recv_blocking<M: Message>(&mut self,
poll: &Poll,
events: &mut Events,
my_tok: Token,... | { &mut self.0 } | identifier_body | |
quicksearch.js | + "' class='' href='#'>"+noResultMsg+" <strong>%{query}<strong></span> \
</td> \
</tr> \
";
var IMAGE_AVATAR_TEMPLATE = " \
<span class='avatar pull-left'> \
<img src='%{imageSrc}'> \
</span> \
";
var CSS_AVATAR_TEMPLATE = " \
<span class='avatar pull-l... |
function getRegistry(callback) {
$.getJSON("/rest/search/registry", function(registry){
if(callback) callback(registry);
});
}
function getQuicksearchSetting(callback) {
$.getJSON("/rest/search/setting/quicksearch", function(setting){
if(callback) callback(setting);
... | {
var specials = '`~!@#$%^&*()-=+{}[]\|;:\'"<>,./?';
for(var i = 0; i < specials.length; i++) {
if(c == specials.charAt(i)) {
return true;
}
}
return false;
} | identifier_body |
quicksearch.js | + "' class='' href='#'>"+noResultMsg+" <strong>%{query}<strong></span> \
</td> \
</tr> \
";
var IMAGE_AVATAR_TEMPLATE = " \
<span class='avatar pull-left'> \
<img src='%{imageSrc}'> \
</span> \
";
var CSS_AVATAR_TEMPLATE = " \
<span class='avatar pull-l... | (callback) {
$.getJSON("/rest/search/setting/quicksearch", function(setting){
if(callback) callback(setting);
});
}
function setWaitingStatus(status) {
if (status){
window['isSearching'] = true;
$(txtQuickSearchQuery_id).addClass("loadding");
if ($.browser... | getQuicksearchSetting | identifier_name |
quicksearch.js |
var QUICKSEARCH_TABLE_ROW_TEMPLATE=" \
<tr> \
<th> \
%{type} \
</th> \
<td> \
%{results} \
</td> \
</tr> \
";
var QUICKSEARCH_SEE_ALL=" \
<tr> \
<td colspan='2' class='message'> \
... | <col width='70%'> \
%{resultRows} \
%{messageRow} \
</table> \
"; | random_line_split | |
quicksearch.js | ) {
if (status){
window['isSearching'] = true;
$(txtQuickSearchQuery_id).addClass("loadding");
if ($.browser.msie && parseInt($.browser.version, 10) == 8) {
$(quickSearchResult_id).show();
}else{
var width = Math.min($(quickSearchRe... | {
var link = $("#"+focusedId+" .name").attr('href');
window.open(link,"_self");
} | conditional_block | |
utils.py | msg_keys_in_exp_but_not_act = ""
if expected_dict.keys() == actual_dict.keys():
pass
else:
set_exp_keys = set(expected_dict.keys())
set_actual_keys = set(actual_dict.keys())
#Deal with actual keys not seen in expected
exp_keys_not_in_act = set_exp_keys - set_actual_keys... | fn = getattr(requests, method.lower())
kwargs = {}
if hasattr(context, 'request_headers'):
kwargs['headers'] = context.request_headers
if body:
kwargs['data'] = body
if hasattr(context, 'request_files'):
kwargs['files'] = context.request_files
context.response = fn(make_u... | identifier_body | |
utils.py | try:
string_type = basestring
except NameError: # Python 3, basestring causes NameError
string_type = str
def make_url(context, endingpoint):
BASE_URL = dereference_variables(context, '$BASE_URL')
if 'http' not in BASE_URL:
BASE_URL = 'http://{0}'.format(BASE_URL)
return '{0}{1}'.format(... |
NULL_SUFFIX = '''_or_null'''
| random_line_split | |
utils.py | (item, actual_value, path=path)
def compare_dicts_structure(expected_dict, actual_dict):
'''
Make a comparison of the keys of the two dictionaries passed
and if they are not the same prepare an assertion message on
how they differ and raise the AssertionError
'''
msg_assert = "Keys/Properties... | do_request | identifier_name | |
utils.py | value):
var_name = key[1:]
value = value.replace(
key,
variables.get(
var_name,
os.environ.get(var_name, key)
)
)
return value
def dereference_arguments(f):
@wraps(f)
def wrapper(context, *args, **kwargs):
... |
if validator == 'numeric_true_false':
return ((type(value) == int) and ((value==0) or (value==1)))
if validator == 'iso_date_time':
return validate_value_iso_datetime(value)
if validator == 'iso_date_time_at_eoe':
return validate_value_iso_datetime_at_eoe(value)
raise Exceptio... | return (type(value) == str and (len(value) > 0)) | conditional_block |
main.rs | () -> Self {
Time(fasync::Time::now())
}
fn after(time: Self, duration: zx::Duration) -> Self {
Self(time.0 + duration)
}
}
struct AppRuntime;
impl NodeRuntime for AppRuntime {
type Time = Time;
type LinkId = AppLinkId;
const IMPLEMENTATION: fidl_fuchsia_overnet_protocol::Impl... | () -> App {
let node = Node::new(
AppRuntime,
NodeOptions::new()
.set_quic_server_key_file(Box::new("/pkg/data/cert.key".to_string()))
.set_quic_server_cert_file(Box::new("/pkg/data/cert.crt".to_string())),
)
.unwrap();
App { node_i... | new | identifier_name |
main.rs | () -> Self {
Time(fasync::Time::now())
}
fn after(time: Self, duration: zx::Duration) -> Self {
Self(time.0 + duration)
}
}
struct AppRuntime;
impl NodeRuntime for AppRuntime {
type Time = Time;
type LinkId = AppLinkId;
const IMPLEMENTATION: fidl_fuchsia_overnet_protocol::Impl... |
async fn at(when: fasync::Time, f: impl FnOnce()) {
fasync::Timer::new(when).await;
f();
}
impl App {
/// Create a new instance of App
fn new() -> App {
let node = Node::new(
AppRuntime,
NodeOptions::new()
.set_quic_server_key_file(Box::new("/pkg/data/c... | {
APP.with(|rcapp| f(&mut rcapp.borrow_mut()))
} | identifier_body |
main.rs | => {
app.udp_link_ids.get(&addr).copied().unwrap_or(LinkId::invalid())
}
})
}
fn send_on_link(&mut self, id: Self::LinkId, packet: &mut [u8]) -> Result<(), Error> {
match id {
AppLinkId::Udp(addr) => {
println!("UDP_SEND to:{} len:{}", ad... | {
fasync::spawn_local(run_list_peers(responder));
Ok(())
} | conditional_block | |
main.rs | now() -> Self {
Time(fasync::Time::now())
}
fn after(time: Self, duration: zx::Duration) -> Self {
Self(time.0 + duration)
}
}
struct AppRuntime;
impl NodeRuntime for AppRuntime {
type Time = Time;
type LinkId = AppLinkId;
const IMPLEMENTATION: fidl_fuchsia_overnet_protocol::... | trait ListPeersResponder {
fn respond(
self,
peers: &mut dyn ExactSizeIterator<Item = &mut fidl_fuchsia_overnet::Peer>,
) -> Result<(), fidl::Error>;
}
impl ListPeersResponder for ServiceConsumerListPeersResponder {
fn respond(
self,
peers: &mut dyn ExactSizeIterator<Item = ... | }
| random_line_split |
init.go |
ParamEnable
ParamDisable
)
const (
_ Location = iota
CHINA //中国 1
TAIWAN //台湾 2
XIANGGANG //香港 3
US //美国 4
VIETNAM //越南 5
THAILAND //泰国 6
KOREA //韩国 7
)
const (
_ BankAccountState = io... | annel Channel) ToChannelType() ChannelType {
if c | identifier_body | |
init.go | ��入 1
TransferTypeOut //转出 2
)
const (
_ Online = iota
POnline // 在线 1
POffline // 离线 2
PDropline // 掉线 3
)
const (
_ ParamType = iota
BizParam //业务参数
SysParam //系统参数
)
const (
_ ParamState = iota
ParamEnable
ParamDisable
)
cons... | PINGAN: "PINGAN",
CMB: "CMB",
ABC: "ABC",
CCB: "CCB",
PSBC: "PSBC",
CEBB: "CEBB",
CIB: "CIB",
SPDB: "SPDB",
CGB: "CGB",
CITIC: "CITIC",
HXB: "HXB",
BCCB: "BCCB",
BOSC: "BOSC",
GZCB: "GZCB",
CZB: "CZB",
UNIONPAY... | ICBC: "ICBC",
BOC: "BOC",
BOCOM: "BOCOM", | random_line_split |
init.go | //付客接单冻结 11
FundSourceTypePayerAssignedOrderPUF //付客接单解冻 12
FundSourceTypePayerReceivedMoneySuccessPBD //付客收款成功 13
FundSourceTypeDepositPayerProfitPBI //付客接单收益 14
FundSourceTypeDepositPayerAgentProfitPBI //付客代理收益 15
FundSourceTypeMatchExeptionFailedPFR //流水未匹配 16
FundSourceType... | identifier_name | ||
init.go |
RateStateEnable //启用 1
RateStateDisable //禁用 2
)
const (
_ ChannelType = iota
ChannelTypeWeChat //微信
ChannelTypeAlipay //支付宝
ChannelTypeBank //银行
ChannelTypeJy //金燕E商
ChannelTypeYSF //云闪付
)
const (
Alipa... | PayerType = iot | conditional_block | |
lwp_nav.js | Builder",
'ch09_03', "Processing",
'ch09_04', "Example: BBC News",
'ch09_05', "Example: Fresh Air",
'ch10_01', "Modifying HTML with Trees",
'ch10_02', "Deleting Images",
'ch10_03', "Detaching and Reattaching",
'ch10_04', "Attaching in Another Tree",
'ch10_05', "Creating New Elements",
'ch11_01', "Cookies, Auth... | make_bottom_navbar | identifier_name | |
lwp_nav.js | ",
'ch05_06', "POST Example: ABEBooks.com",
'ch05_07', "File Uploads",
'ch05_08', "Limits on Forms",
'ch06_01', "Simple HTML Processing with Regular Expressions",
'ch06_02', "Regular Expression Techniques",
'ch06_03', "Troubleshooting",
'ch06_04', "When Regular Expressions Aren't Enough",
'ch06_05', "Example: E... |
} else {
if( pid_is_indexy(pid) ) {
url = "index/" + url;
} else {
; // we're both not in ./index
}
}
url = url.replace( /\bindex\.htm$/, 'index.html' );
return url;
}
function pid_is_chapter (pid) {
//if( (/^i-/).test(pid) ) return false;
if( ( /_01$/ ).test(pid) ) return true;
... | {
url = "../" + url;
} | conditional_block |
lwp_nav.js | 'copyrght', "Copyright",
'i-index', "Perl & LWP: Index",
'i-idx_0', "Index: Symbols & Numbers",
'i-idx_a', "Index: A",
'i-idx_b', "Index: B",
'i-idx_c', "Index: C",
'i-idx_d', "Index: D",
'i-idx_e', "Index: E",
'i-idx_f', "Index: F",
'i-idx_g', "Index: G",
'i-idx_h', "Index: H",
'i-idx_i', "Index: I",
'i-... | function graft (parent, t, doc) {
// graft( somenode, [ "I like ", ['em', { 'class':"stuff" },"stuff"], " oboy!"] )
//if(!doc) doc = parent.ownerDocument ? parent.ownerDocument : document; | random_line_split | |
lwp_nav.js | ",
'ch05_06', "POST Example: ABEBooks.com",
'ch05_07', "File Uploads",
'ch05_08', "Limits on Forms",
'ch06_01', "Simple HTML Processing with Regular Expressions",
'ch06_02', "Regular Expression Techniques",
'ch06_03', "Troubleshooting",
'ch06_04', "When Regular Expressions Aren't Enough",
'ch06_05', "Example: E... |
function pid_is_chapter (pid) {
//if( (/^i-/).test(pid) ) return false;
if( ( /_01$/ ).test(pid) ) return true;
if( ( /_/ ).test(pid) ) return false;
return true;
}
function pid_is_indexy (pid) {
return( (/^i-/).test(pid) );
}
//======================================================================
va... | {
var url = pid.toString().replace(/^i-/,"") + ".htm";
if( pid_is_indexy( lwp_pageid || '') ) {
if( pid_is_indexy(pid) ) {
; // we're both in ./index
} else {
url = "../" + url;
}
} else {
if( pid_is_indexy(pid) ) {
url = "index/" + url;
} else {
; // we're both not in... | identifier_body |
lib.rs | 0;
/// # let expr = 0;
///
/// let expanded = quote! {
/// // The generated impl.
/// impl heapsize::HeapSize for #name {
/// fn heap_size_of_children(&self) -> usize {
/// #expr
/// }
/// }
/// };
///
/// // Hand the output tokens back to... | let s: TokenStream = s.parse().expect("invalid token stream");
stream.extend(s.into_iter().map(|mut t| {
t.set_span(span);
t
}));
}
pu | identifier_body | |
lib.rs | ///
/// use proc_macro::TokenStream;
/// use quote::quote;
///
/// # const IGNORE_TOKENS: &'static str = stringify! {
/// #[proc_macro_derive(HeapSize)]
/// # };
/// pub fn derive_heap_size(input: TokenStream) -> TokenStream {
/// // Parse the input and figure out what implementation to generate...
/// # const ... | unct(stream: | identifier_name | |
lib.rs | Performs variable interpolation against the input and produces it as
/// [`TokenStream`]. For returning tokens to the compiler in a procedural macro, use
/// `into()` to build a `TokenStream`.
///
/// [`TokenStream`]: https://docs.rs/proc-macro2/0/proc_macro2/struct.TokenStream.html
///
/// # Interpolation
///
/// Var... | /// # ;
/// ```
///
/// The solution is to perform token-level manipulations using the APIs provided
/// by Syn and proc-macro2.
///
/// ```edition2018
/// # use proc_macro2::{self as syn, Span};
/// # use quote::quote;
/// #
/// # let ident = syn::Ident::new("i", Span::call_site());
/// #
/// let concatenated = format... | /// quote! {
/// let mut _#ident = 0;
/// } | random_line_split |
miningManager.go | ,
database: database,
ethClient: client,
toMineInput: make(chan *pow.Work),
solutionOutput: make(chan *pow.Result),
submitCount: promauto.NewCounter(prometheus.CounterOpts{
Namespace: "telliot",
Subsystem: "mining",
Name: "submit_total",
Help: "The total number of s... | {
return nil, errors.New("the db doesn't have the trb price")
} | conditional_block | |
miningManager.go | (err, "creating client")
}
contractInstance, err := contracts.NewITellor(client)
if err != nil {
return nil, errors.Wrap(err, "getting addresses")
}
logger, err = logging.ApplyFilter(*cfg, ComponentName, logger)
if err != nil {
return nil, errors.Wrap(err, "apply filter logger")
}
submitter := NewSubmitte... | // any of the checks below fail and will be retried
// when there is no new challenge.
mgr.solutionPending = solution
profitPercent, err := mgr.profit() // Call it regardless of whether we use so that is sets the exposed metrics.
if mgr.cfg.Mine.ProfitThreshold > 0 {
if err != nil {
level.Error... | }
level.Debug(mgr.logger).Log("msg", "re-submitting a pending solution", "reqIDs", fmt.Sprintf("%+v", ids))
}
// Set this solution as pending so that if | random_line_split |
miningManager.go | , "creating client")
}
contractInstance, err := contracts.NewITellor(client)
if err != nil {
return nil, errors.Wrap(err, "getting addresses")
}
logger, err = logging.ApplyFilter(*cfg, ComponentName, logger)
if err != nil {
return nil, errors.Wrap(err, "apply filter logger")
}
submitter := NewSubmitter(lo... | () (time.Duration, error) {
address := "000000000000000000000000" + mgr.cfg.PublicAddress[2:]
decoded, err := hex.DecodeString(address)
if err != nil {
return 0, errors.Wrapf(err, "decoding address")
}
last, err := mgr.contractInstance.GetUintVar(nil, rpc.Keccak256(decoded))
if err != nil {
return 0, errors.... | lastSubmit | identifier_name |
miningManager.go | ) {
level.Debug(mgr.logger).Log("msg", "transaction not profitable, so will wait for the next cycle")
continue
}
}
lastSubmit, err := mgr.lastSubmit()
if err != nil {
level.Error(mgr.logger).Log("msg", "checking last submit time", "err", err)
} else if lastSubmit < mgr.cfg.Mine.MinSubmitP... | {
go func(tx *types.Transaction) {
receipt, err := bind.WaitMined(ctx, mgr.ethClient, tx)
if err != nil {
level.Error(mgr.logger).Log("msg", "transaction result for calculating transaction cost", "err", err)
}
if receipt.Status != 1 {
mgr.submitFailCount.Inc()
level.Error(mgr.logger).Log("msg", "unsuc... | identifier_body | |
spell_parser.py | self.files[fileIndex].ReadFile()
m = re.search(r'"(.+?)(?<!\\)"', contents[lineIndex])
if(m is not None):
return m.group(0)
return '""'
def ReplaceNameFromLine(self, fileIndex, lineIndex, newText):
contents = self.files[fileIndex].ReadFile()
self.files[fileIndex].ReplacePattern(contents[lineIndex], newT... | if type == "E": | random_line_split | |
spell_parser.py | = lines
return lines
def InsertInLine(self, index, value):
f = open(self.path, "r", encoding="utf8")
contents = f.readlines()
f.close()
contents.insert(index, value)
contents = "".join(contents)
self.Write(contents)
class Parser():
def __init__(self, args):
from colorama import init
init()
#... |
if len(args) >= 3:
if args[2] is not None:
self.rangeEnd = int(args[2])
if len(args) >= 4:
if args[3] is not None:
self.minimumPrints = args[3].lower() == 'true'
def SaveIndexes(self):
dbFilename = "spell_parser";
self.Command = "%s.py %i %i" % (dbFilename, self.lastItemID, self.rangeEnd)
... | if args[1] is not None:
self.rangeStart = int(args[1]) | conditional_block |
spell_parser.py | " % (guessed_ID, item))
return self.FindInContents(item, guess + 1, maxI, contents)
else:
#print ("ID: %d > item: %s" % (guessed_ID, item))
return self.FindInContents(item, minI, guess - 1, contents)
else:
#print ("END | %d NOT FOUND at pos %d" % (item, guess))
return [guess-1, False]
def GetNa... | if os.path.isfile(self.client_id_file):
fa = open(self.client_id_file,'r', encoding="utf8")
client_id = fa.readline()
fa.close()
return client_id | identifier_body | |
spell_parser.py | = lines
return lines
def InsertInLine(self, index, value):
f = open(self.path, "r", encoding="utf8")
contents = f.readlines()
f.close()
contents.insert(index, value)
contents = "".join(contents)
self.Write(contents)
class | ():
def __init__(self, args):
from colorama import init
init()
#If Windows then prevent sleep
self.osSleep = None
if os.name == 'nt':
self.osSleep = WindowsInhibitor()
self.osSleep.Inhibit()
# INIT
print("--------------------------")
print(" \033[33mSpellNameLocalized WoW Api Parser\033[0m")
... | Parser | identifier_name |
tpl.rs | pt]{article}\n\
//! \\begin{document}\n\
//! \\section{Hello, world}\n\
//! This is fun \\& easy.\n\
//! \\end{document}\n");
//! ```
//!
//! While this form uses no macros, it is rather inconvenient to write. Luckily there is an
//! alternative:
//!
//! ## "Hello, world"... |
}
impl TexElement for OptArgs {
fn write_tex(&self, writer: &mut dyn Write) -> io::Result<()> {
if !self.0.is_empty() {
writer.write_all(b"[")?;
write_list(writer, ",", self.0.iter())?;
writer.write_all(b"]")?;
}
Ok(())
}
}
/// A set of arguments.
... | {
OptArgs(vec![elem.into_tex_element()])
} | identifier_body |
tpl.rs | <()>;
}
/// Conversion trait for various types.
///
/// Used for primitive conversions of various types directly into tex elements. Implementations
/// include:
///
/// * `Box<dyn TexElement>` are passed through unchanged.
/// * Any other `TexElement` will be boxed.
/// * `str` and `String` are converted to escaped `T... | write_tex | identifier_name | |
tpl.rs | //!
//! While this form uses no macros, it is rather inconvenient to write. Luckily there is an
//! alternative:
//!
//! ## "Hello, world" using elements and macros.
//!
//! ```rust
//! use texrender::elems;
//! use texrender::tpl::TexElement;
//! use texrender::tpl::elements::{N, doc, document, documentclass, section}... | args, | random_line_split | |
tpl.rs | pt]{article}\n\
//! \\begin{document}\n\
//! \\section{Hello, world}\n\
//! This is fun \\& easy.\n\
//! \\end{document}\n");
//! ```
//!
//! While this form uses no macros, it is rather inconvenient to write. Luckily there is an
//! alternative:
//!
//! ## "Hello, world"... |
arg.write_tex(writer)?;
}
Ok(())
}
/// A raw, unescaped piece of tex code.
///
/// Tex is not guaranteed to be UTF-8 encoded, thus `RawTex` internally keeps bytes. The value will
/// be inserted into the document without any escaping. The value is unchecked, thus it is possible
/// to create syntacti... | {
writer.write_all(separator.as_bytes())?;
} | conditional_block |
parser.go | lexer *lexer
// Pointer to the current token
currToken *token
// Tree of parse nodes
rule *ParsedRule
}
// ParserError represents errors hit during rule parsing
type ParserError struct {
msg string
pos int
kind tokenKind
val string
// TODO: Add line
}
func (err *ParserError) Error() string {
return fmt... | ToString | identifier_name | |
parser.go | can only be used once; to re-use a parser, make sure to call the
// Reset() method.
type parseNode struct {
kind nodeKind
op tokenKind
rule *RuleTweet
left *parseNode
right *parseNode
}
func (node *parseNode) String() string {
return fmt.Sprintf("Kind: %d, Op: %d, Rule: %+v", node.kind, node.op, node.rule... |
parser.currToken = token
return currToken, nil
}
func (parser *Parser) expr() (*parseNode, error) {
var node *parseNode
var err error
for {
token := parser.currToken
// TODO(aksiksi): Handle the case of a non-logical expression that follows
// an expression or cond
switch token.kind {
// Nested exp... | {
return nil, err
} | conditional_block |
parser.go | can only be used once; to re-use a parser, make sure to call the
// Reset() method.
type parseNode struct {
kind nodeKind
op tokenKind
rule *RuleTweet
left *parseNode
right *parseNode
}
func (node *parseNode) String() string {
return fmt.Sprintf("Kind: %d, Op: %d, Rule: %+v", node.kind, node.op, node.rule... |
// Eval walks the parse tree and evaluates each condition against
// the given Tweet. Returns true if the Tweet matches all of the rules.
func (rule *ParsedRule) Eval(tweet *Tweet) bool {
return evalInternal(tweet, rule.root)
}
// Parser is a simple parser for tweet deletion rule strings.
//
// Examples:
//
// - ag... | {
switch node.kind {
case nodeCond:
return tweet.IsMatch(node.rule)
case nodeLogical:
left := evalInternal(tweet, node.left)
right := evalInternal(tweet, node.right)
switch node.op {
case tokenAnd:
return left && right
case tokenOr:
return left || right
default:
panic(fmt.Sprintf("Unexpected ... | identifier_body |
parser.go | arsers can only be used once; to re-use a parser, make sure to call the
// Reset() method.
type parseNode struct {
kind nodeKind
op tokenKind
rule *RuleTweet
left *parseNode
right *parseNode
}
func (node *parseNode) String() string {
return fmt.Sprintf("Kind: %d, Op: %d, Rule: %+v", node.kind, node.op, nod... | }
// ParserError represents errors hit during rule parsing
type ParserError struct {
msg string
pos int
kind tokenKind
val string
// TODO: Add line
}
func (err *ParserError) Error() string {
return fmt.Sprintf("%s: \"%s\" (%s) (at col %d)", err.msg, err.val, err.kind.ToString(), err.pos+1)
}
func newParserE... | // Tree of parse nodes
rule *ParsedRule | random_line_split |
all_13.js | _ARCH',['../structconnection.html#a06fc87d81c62e9abb8790b6e5713c55ba752653bedd6abb27e63c5f22a85359bb',1,'connection']]],
['telnet_5finfo',['telnet_info',['../structtelnet__info.html',1,'']]],
['telnet_5finfo_2ec',['telnet_info.c',['../telnet__info_8c.html',1,'']]],
['telnet_5finfo_2eh',['telnet_info.h',['../telne... | ['token',['TOKEN',['../single__load_8c.html#a5c3a83864bf5991d09aa5c2abb911bf0',1,'single_load.c']]],
['token_5fquery',['TOKEN_QUERY',['../loader_2src_2headers_2includes_8h.html#a5584596b6561bf1ef1c462d5032c6e12',1,'includes.h']]], | random_line_split | |
battle.js | of seconds it takes to reload the cannon.
*/
Pond.Battle.RELOAD_TIME = .5;
/**
* The avatar currently executing code.
* @type Pond.Avatar
*/
Pond.Battle.currentAvatar = null;
/**
* Speed of avatar movement.
*/
Pond.Battle.AVATAR_SPEED = 1;
/**
* Speed of missile movement.
*/
Pond.Battle.MISSILE_SPEED = 3;
... | }
}
}
};
/**
* Let the avatars think.
* @private
*/
Pond.Battle.updateInterpreters_ = function() {
for (let i = 0; i < Pond.Battle.STATEMENTS_PER_FRAME; i++) {
Pond.Battle.ticks++;
for (const avatar of Pond.Battle.AVATARS) {
if (avatar.dead) {
continue;
}
Pond.Battle... | {
const tuple = Pond.Battle.closestNeighbour(avatar);
const [neighbour, closestAfter] = tuple;
if (closestAfter < Pond.Battle.COLLISION_RADIUS &&
closestBefore > closestAfter) {
// Collision with another avatar.
avatar.loc.x -= dx;
avatar.loc.y -= dy;
... | conditional_block |
battle.js | ;
Pond.Battle.endTime_ = Date.now() + Pond.Battle.TIME_LIMIT;
console.log('Starting battle with ' + Pond.Battle.AVATARS.length +
' avatars.');
for (const avatar of Pond.Battle.AVATARS) {
try {
avatar.initInterpreter();
} catch (e) {
console.log(avatar + ' fails to load: ' + e);
... | wrapMath | identifier_name | |
battle.js | milliseconds).
*/
Pond.Battle.TIME_LIMIT = 5 * 60 * 1000;
/**
* Callback function for end of game.
* @type Function
*/
Pond.Battle.doneCallback_ = null;
/**
* Stop and reset the battle.
*/
Pond.Battle.reset = function() {
clearTimeout(Pond.Battle.pid);
Pond.Battle.EVENTS.length = 0;
Pond.Battle.MISSILES.... | {
interpreter.setProperty(globalObject, name,
interpreter.createNativeFunction(wrapper, false));
} | identifier_body | |
battle.js | Number of seconds it takes to reload the cannon.
*/
Pond.Battle.RELOAD_TIME = .5;
/**
* The avatar currently executing code.
* @type Pond.Avatar
*/
Pond.Battle.currentAvatar = null;
/**
* Speed of avatar movement.
*/
Pond.Battle.AVATAR_SPEED = 1;
/**
* Speed of missile movement.
*/
Pond.Battle.MISSILE_SPEED... | * @param {!Interpreter} interpreter The JS-Interpreter.
* @param {!Interpreter.Object} globalObject Global object.
*/
Pond.Battle.initInterpreter = function(interpreter, globalObject) {
// API
let wrapper;
wrapper = function(value) {
// Restrict logging to just numbers so that the console doesn't fill up
... | }
};
/**
* Inject the Pond API into a JavaScript interpreter. | random_line_split |
0_gatherer.go | {function, false}
}
func failable(function gatherFunction) gathering {
return gathering{function, true}
}
const gatherAll = "ALL"
var gatherFunctions = map[string]gathering{
"pdbs": important(GatherPodDisruptionBudgets),
"metrics": failable(GatherMostRecentMe... | {
sort.Strings(errors)
errors = utils.UniqueStrings(errors)
return fmt.Errorf("%s", strings.Join(errors, ", "))
} | identifier_body | |
0_gatherer.go | `json:"status_reports"`
MemoryAlloc uint64 `json:"memory_alloc_bytes"`
Uptime float64 `json:"uptime_seconds"`
// shows if obfuscation(hiding IPs and cluster domain) is enabled
IsGlobalObfuscationEnabled bool `json:"is_global_obfuscation_enabled"`
}
// gathererStatusReport c... | (function gatherFunction) gathering {
return gathering{function, false}
}
func failable(function gatherFunction) gathering {
return gathering{function, true}
}
const gatherAll = "ALL"
var gatherFunctions = map[string]gathering{
"pdbs": important(GatherPodDisruptionBudgets),
"metrics"... | important | identifier_name |
0_gatherer.go | `json:"status_reports"`
MemoryAlloc uint64 `json:"memory_alloc_bytes"`
Uptime float64 `json:"uptime_seconds"`
// shows if obfuscation(hiding IPs and cluster domain) is enabled
IsGlobalObfuscationEnabled bool `json:"is_global_obfuscation_enabled"`
}
// gathererStatusReport c... | "openshift_sdn_controller_logs": failable(GatherOpenshiftSDNControllerLogs),
"openshift_authentication_logs": failable(GatherOpenshiftAuthenticationLogs),
"sap_config": failable(GatherSAPConfig),
"sap_license_management_logs": failable(GatherSAPVsystemIptablesLogs),
"sap_pods":... | "container_runtime_configs": important(GatherContainerRuntimeConfig),
"netnamespaces": important(GatherNetNamespace),
"openshift_apiserver_operator_logs": failable(GatherOpenShiftAPIServerOperatorLogs),
"openshift_sdn_logs": failable(GatherOpenshiftSDNLogs), | random_line_split |
0_gatherer.go | `json:"status_reports"`
MemoryAlloc uint64 `json:"memory_alloc_bytes"`
Uptime float64 `json:"uptime_seconds"`
// shows if obfuscation(hiding IPs and cluster domain) is enabled
IsGlobalObfuscationEnabled bool `json:"is_global_obfuscation_enabled"`
}
// gathererStatusReport c... |
} else {
errors = extractErrors(gather.result.errors)
}
errors = append(errors, recordStatusReport(rec, gather.result.records)...)
klog.V(5).Infof("Read from %s's channel and received %s\n", gather.name, gather.rvString)
return statusReport, errors
}
func recordStatusReport(rec recorder.Interface, records []... | {
klog.V(5).Infof("Couldn't gather %s' received following error: %s\n", gather.name, err.Error())
} | conditional_block |
delegated_credentials.go | // The certificate must contains the digitalSignature KeyUsage.
if (cert.KeyUsage & x509.KeyUsageDigitalSignature) == 0 {
return false
}
// Check that the certificate has the DelegationUsage extension and that
// it's marked as non-critical (See Section 4.2 of RFC5280).
for _, extension := range cert.Extension... | // isValidForDelegation returns true if a certificate can be used for Delegated
// Credentials.
func isValidForDelegation(cert *x509.Certificate) bool {
// Check that the digitalSignature key usage is set. | random_line_split | |
delegated_credentials.go | h := hash.New()
h.Write(header)
io.WriteString(h, context)
h.Write(dCert)
h.Write(rawCred)
h.Write(rawAlgo[:])
return h.Sum(nil), nil
}
// Extract the algorithm used to sign the Delegated Credential from the
// end-entity (leaf) certificate.
func getSignatureAlgorithm(cert *Certificate) (SignatureScheme, error)... | {
return nil, errors.New("tls: Delegated Credential is not valid")
} | conditional_block | |
delegated_credentials.go | DelegatedCredential) invalidTTL(start, now time.Time) bool |
// credential stores the public components of a Delegated Credential.
type credential struct {
// The amount of time for which the credential is valid. Specifically, the
// the credential expires 'validTime' seconds after the 'notBefore' of the
// delegation certificate. The delegator shall not issue Delegated
//... | {
return dc.cred.validTime > (now.Sub(start) + dcMaxTTL).Round(time.Second)
} | identifier_body |
delegated_credentials.go | *DelegatedCredential) | (start, now time.Time) bool {
return dc.cred.validTime > (now.Sub(start) + dcMaxTTL).Round(time.Second)
}
// credential stores the public components of a Delegated Credential.
type credential struct {
// The amount of time for which the credential is valid. Specifically, the
// the credential expires 'validTime' se... | invalidTTL | identifier_name |
run.py | format put in curly braces item from ()
# print("{} is a file".format(item))
# elif os.path.isdir("."):
# print("{} is a folder".format(item))
# else:
# print("{} is not a folder or file".format(item))
# # creating folder
# import os
# os.mkdir("newFolder")
# # rename folder
# os.renam... | random_line_split | ||
minijail.rs | ();
let mut lines = io::BufReader::new(pipe).lines();
// Spawn a task that forwards logs from minijail to the rust logger.
task::spawn(async move {
while let Ok(Some(line)) = lines.next_line().await {
let l = line.split_whitespace().skip(2).collect::<String>();
... |
// Configure UID
jail.change_uid(self.uid);
// Configure PID
jail.change_gid(self.gid);
// Update the capability mask if specified
if let Some(capabilities) = &manifest.capabilities {
// TODO: the capabilities should be passed as an array
jail.u... | {
let seccomp_config = tmpdir_path.join("seccomp");
let mut f = fs::File::create(&seccomp_config)
.await
.map_err(|e| Error::Io("Failed to create seccomp configuraiton".to_string(), e))?;
let s = itertools::join(seccomp.iter().map(|(k, v)| format!("{}:... | conditional_block |
minijail.rs | ();
let mut lines = io::BufReader::new(pipe).lines();
// Spawn a task that forwards logs from minijail to the rust logger.
task::spawn(async move {
while let Ok(Some(line)) = lines.next_line().await {
let l = line.split_whitespace().skip(2).collect::<String>();
... | (&self) -> Result<(), Error> {
// Just make clippy happy
if false {
Err(Error::Stop)
} else {
Ok(())
}
}
pub(crate) async fn start(&self, container: &Container) -> Result<Process, Error> {
let root = &container.root;
let manifest = &contai... | shutdown | identifier_name |
minijail.rs |
}
#[derive(Debug)]
pub struct Minijail {
log_fd: i32,
event_tx: EventTx,
run_dir: PathBuf,
data_dir: PathBuf,
uid: u32,
gid: u32,
}
impl Minijail {
pub(crate) fn new(
event_tx: EventTx,
run_dir: &Path,
data_dir: &Path,
uid: u32,
gid: u32,
) -> R... | {
&mut self.0
} | identifier_body | |
minijail.rs | ();
let mut lines = io::BufReader::new(pipe).lines();
// Spawn a task that forwards logs from minijail to the rust logger.
task::spawn(async move {
while let Ok(Some(line)) = lines.next_line().await {
let l = line.split_whitespace().skip(2).collect::<String>();
... | let proc = Path::new("/proc");
jail.mount_bind(&proc, &proc, false)
.map_err(Error::Minijail)?;
jail.remount_proc_readonly();
// If there's no explicit mount for /dev add a minimal variant
if !container
.manifest
.mounts
.contains_... | async fn setup_mounts(
&self,
jail: &mut MinijailHandle,
container: &Container,
) -> Result<(), Error> { | random_line_split |
mod.rs | ;
pub mod container;
pub mod mount;
pub struct ContainerImage {
file: PathBuf,
mounts: Vec<(PathBuf, PathBuf)>,
}
impl ContainerImage {
pub fn start(&self) -> io::Result<Void> {
return Err(io::Error::new(io::ErrorKind::Other, "containers not yet implemented"));
}
}
#[derive(Debug)]
pub struct... | io::Error::new(io::ErrorKind::Other, e)
}
impl SandboxingStrategy for UserChangeStrategy {
fn preexec(&self) -> io::Result<()> {
if let Some(ref wd) = self.workdir {
std::fs::create_dir_all(wd)?;
nix::unistd::chown(wd, self.set_user, self.set_group)
.map_err(|er... | E: Into<Box<dyn StdError + Send + Sync>>,
{ | random_line_split |
mod.rs | pub mod container;
pub mod mount;
pub struct ContainerImage {
file: PathBuf,
mounts: Vec<(PathBuf, PathBuf)>,
}
impl ContainerImage {
pub fn start(&self) -> io::Result<Void> {
return Err(io::Error::new(io::ErrorKind::Other, "containers not yet implemented"));
}
}
#[derive(Debug)]
pub struct E... | (self) -> ContainerImage {
assert!(self.disk_linked, "must be disk-linked");
ContainerImage {
file: self.expected_path,
mounts: Vec::new(),
}
}
pub fn finalize_executable(self) -> Executable {
Executable {
file: self.storage.into_owned_fd(),
... | finalize_container | identifier_name |
mod.rs | full_path.push(name);
let storage = File::create(&full_path)?;
Ok(ExecutableFactory {
storage,
expected_path: full_path,
disk_linked: true,
})
}
pub fn finalize_container(self) -> ContainerImage {
assert!(self.disk_linked, "must be d... | {
if let Err(err) = exec_artifact_child(e, &c) {
event!(Level::WARN, "failed to execute: {:?}", err);
std::process::exit(1);
} else {
unreachable!();
}
} | conditional_block | |
mod.rs | pub mod container;
pub mod mount;
pub struct ContainerImage {
file: PathBuf,
mounts: Vec<(PathBuf, PathBuf)>,
}
impl ContainerImage {
pub fn start(&self) -> io::Result<Void> {
return Err(io::Error::new(io::ErrorKind::Other, "containers not yet implemented"));
}
}
#[derive(Debug)]
pub struct E... |
pub fn new_on_disk(name: &str, capacity: i64, root: &Path) -> io::Result<ExecutableFactory> {
let mut full_path = root.to_owned();
full_path.push(name);
let storage = File::create(&full_path)?;
Ok(ExecutableFactory {
storage,
expected_path: full_path,
... | {
let mut mem_fd = MemFdOptions::new()
.cloexec(true)
.allow_sealing(true)
.with_capacity(capacity)
.set_mode(Mode::S_IRWXU | Mode::S_IRGRP | Mode::S_IXGRP | Mode::S_IROTH | Mode::S_IXOTH)
.open(name)
.map_err(|e| nix_error_to_io_error(e))?... | identifier_body |
expressDataHandling.js | , 2020 18:37"或者"Monday, November 02, 2020 " ,定义getDate函数方便转化
let getDate = (dateStr)=>{
let monthList={"January":0,"February":1,"March":2,"April":3,"May":4,"June":5,"July":6,"August":7,"September":8,"October":9,"November":10,"December":11};
let Y = dateStr.split(",")[2].sp... | result.status = "已送达";
result.ata = new Date(ups.Package.Activity[0].GMTDate["#text"]+"T"+ups.Package.Activity[0].GMTTime["#text"]+ups.Package.Activity[0].GMTOffset["#text"])
}else{
result.status = "正在运送"
}
... | random_line_split | |
expressDataHandling.js | 2020 18:37"或者"Monday, November 02, 2020 " ,定义getDate函数方便转化
let getDate = (dateStr)=>{
let monthList={"January":0,"February":1,"March":2,"April":3,"May":4,"June":5,"July":6,"August":7,"September":8,"October":9,"November":10,"December":11};
let Y = dateStr.split(",")[2].spl... | ext"]} ${ups.ShipTo.Address.CountryCode["#text"]} `;
result.atd = upsGetDate(ups.PickupDate["#text"]);
result.eta = ups.Package.hasOwnProperty("RescheduledDeliveryDate")?
// ups.Package.RescheduledDeliveryDate 20201130
// ups.Package.Reschedul... | result.tracking = ups.ShipmentIdentificationNumber["#text"];
result.origin = `${ups.Shipper.Address.City["#text"]} ${ups.Shipper.Address.CountryCode["#text"]}`;
result.destination = `${ups.ShipTo.Address.City["#t | conditional_block |
preprocess.py | secureConnectionStart', # this entry was not tested
'requestStart',
'responseStart', 'responseEnd', 'domLoading',
'domInteractive', 'domContentLoadedEventStart',
'domContentLoadedEventEnd', 'domComplete',
'load... | websiteData[coreConfig][govConfig][site][phase]['energy'][iteration] = -100
continue
start,end = timestampInterval(int(jsonData['timestamps'][site][0][phase][0]),
int(jsonData['timestamps'][site][0][loadType... | if loadtime == 0: # don't waste time on 0 energies | random_line_split |
preprocess.py | secureConnectionStart', # this entry was not tested
'requestStart',
'responseStart', 'responseEnd', 'domLoading',
'domInteractive', 'domContentLoadedEventStart',
'domContentLoadedEventEnd', 'domComplete',
'load... | maxIterations = 0
warnedIterations = False
for coreConfig in coreConfigs:
pmcFile = pmcPrefix + coreConfig + "-"
jsonFilePrefix = jsonPrefix + coreConfig + "-"
for govConfig in govConfigs:
pmcFilePrefix = pmcPrefix + coreConfig + "-" + govConfig + "-"
jsonFi... | global verboseGlobal
verboseGlobal = verbose
if filePrefix[-1] != '-': # some quick error checking
filePrefix += "-"
pmcDir = "powmon-data/"
jsonDir = "json-data/"
pmcPrefix = pmcDir + filePrefix
jsonPrefix = jsonDir + filePrefix
# Layout for the data: # TODO fix this --- really b... | identifier_body |
preprocess.py | ][matrixType] = \
cleanupEntry(data[coreConfig][govConfig][site][phase][matrixType],maxStds)
def parseAndCalcEnergy(filePrefix="sim-data-", iterations=10,cleanData=False,verbose=False):
global verboseGlobal
verboseGlobal = verbose
if filePrefix[-1] != '-': # some quick error ch... | readData | identifier_name | |
preprocess.py | secureConnectionStart', # this entry was not tested
'requestStart',
'responseStart', 'responseEnd', 'domLoading',
'domInteractive', 'domContentLoadedEventStart',
'domContentLoadedEventEnd', 'domComplete',
'load... |
pmcFile = pmcFiles[fileIndex]
jsonFile = jsonFilePrefix + fileID + ".json" # look at same id'd json file
printv("on file " + pmcFile)
printv("with file " + jsonFile)
try:
pmcData = pmc.readPMCData(pmcFile) # ndarray
... | if (not(warnedIterations)):
print("Warning: additional iteration data found, skipping.")
warnedIterations = True
break # stop if we can't hold anymore data, TODO allow for dynamic number of files | conditional_block |
Terminals.js | LegendList.innerHTML = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">" + ListContents + "</table>";
if (term_ddlist != null) {
//clear dropdown options values because they are being added below...
removeAllOptions(term_ddlist);
addOption(term_ddl... | (zoomLevel) {
// clear the terminal layer or we'll get duplicate graphic objects stacked up on top of each other
terminalLayer.clear();
// set up terminal icon
var iconJSON = { "icon": currentTerminalsIcon, "h": 16, "w": 16, "xOffSet": 0, "yOffSet": 0 };
if ((currentTerminalsJson != null) && (curr... | RebuildTerminalLayer | identifier_name |
Terminals.js | Vessels) before plotting the terminals
setTimeout("RebuildTerminalLayer(map.getLevel())", 500);
}
});
}
/**
* terminals are rebuild when ajax call is made or when user zooms in
*/
function RebuildTerminalLayer(zoomLevel) {
// clear the terminal layer or we'll get duplicate graphic objects... | {
InfoTemplateContents += "<div id='camlayer" + MapMarkerAsJSON.TerminalID.toString() + "' class='infolayeractive'>";
// iterate through and show cams for each terminal in the popup
for (var count = 0; count < CamArrayAsJSON.length; count++) {
var currentCam = CamArrayAsJSON[count];
... | conditional_block | |
Terminals.js | if (term_ddlist != null) {
//clear dropdown options values because they are being added below...
removeAllOptions(term_ddlist);
addOption(term_ddlist, "For a Terminal...", "0");
for (var count = 0; count < responseObject.FeedContentList.lengt... | {
dojo.xhrGet({
url: "Terminals.ashx",
preventCache: 1,
handleAs: "json",
error: function() { console.error('Error retrieving terminal data.'); },
load: function (responseObject, ioArgs) {
dojo.empty("TerminalLegendListDiv");
var TerminalLegendList = d... | identifier_body | |
Terminals.js | LegendList.innerHTML = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">" + ListContents + "</table>";
if (term_ddlist != null) {
//clear dropdown options values because they are being added below...
removeAllOptions(term_ddlist);
addOption(term_ddl... |
/**
* builds out the html for the template Title and Contents - when you click a vessel on the map, this displays in the window that pops open.
*/
function CreateInfoTemplateJSONTerm(MapMarkerAsJSON, CamArrayAsJSON) {
var InfoTemplateContents = CreateInfoTemplateContentsTerm(MapMarkerAsJSON, CamArrayAsJSON);
... | InfoLinkClickedTerm(waittimelinkid, MapMarkerAsJSON.TerminalID);
}
}
} | random_line_split |
simulate.py | """Routines for running the scheduler in simulation mode."""
import os.path
import configparser
import logging
import numpy as np
import astropy.coordinates as coord
from astropy.time import Time
import astropy.units as u
from .TelescopeStateMachine import TelescopeStateMachine
from .Scheduler import Scheduler
from .Q... |
else:
weather_year = int(weather_year)
survey_duration = \
sim_config['simulation'].getfloat('survey_duration_days') * u.day
# set up Scheduler
scheduler_config_file_fullpath = \
os.path.join(scheduler_config_path, scheduler_config_file)
scheduler = Scheduler(scheduler_... | weather_year = None | conditional_block |
simulate.py | """Routines for running the scheduler in simulation mode."""
import os.path
import configparser
import logging
import numpy as np
import astropy.coordinates as coord
from astropy.time import Time
import astropy.units as u
from .TelescopeStateMachine import TelescopeStateMachine
from .Scheduler import Scheduler
from .Q... |
# try to expose
if not tel.start_exposing(next_obs['target_exposure_time']):
tel.set_cant_observe()
logger.info("Exposure failure! Waiting...")
scheduler.obs_log.prev_obs = None
tel.wait()
continue
else... | logger.info("Failure slewing to {}, {}! Waiting...".format
(next_obs['target_ra'] * u.deg, next_obs['target_dec'] * u.deg))
scheduler.obs_log.prev_obs = None
tel.wait()
continue | random_line_split |
simulate.py | """Routines for running the scheduler in simulation mode."""
import os.path
import configparser
import logging
import numpy as np
import astropy.coordinates as coord
from astropy.time import Time
import astropy.units as u
from .TelescopeStateMachine import TelescopeStateMachine
from .Scheduler import Scheduler
from .Q... | (scheduler_config_file, sim_config_file,
scheduler_config_path = BASE_DIR + '../../ztf_survey_configuration/',
sim_config_path = BASE_DIR+'../config/',
output_path = BASE_DIR+'../sims/',
profile=False, raise_queue_empty=False, fallback=True,
time_limit = 30*u.second):
if pr... | simulate | identifier_name |
simulate.py | """Routines for running the scheduler in simulation mode."""
import os.path
import configparser
import logging
import numpy as np
import astropy.coordinates as coord
from astropy.time import Time
import astropy.units as u
from .TelescopeStateMachine import TelescopeStateMachine
from .Scheduler import Scheduler
from .Q... | weather_year = int(weather_year)
survey_duration = \
sim_config['simulation'].getfloat('survey_duration_days') * u.day
# set up Scheduler
scheduler_config_file_fullpath = \
os.path.join(scheduler_config_path, scheduler_config_file)
scheduler = Scheduler(scheduler_config_file... | if profile:
try:
from pyinstrument import Profiler
except ImportError:
print('Error importing pyinstrument')
profile = False
sim_config = configparser.ConfigParser()
sim_config_file_fullpath = os.path.join(sim_config_path, sim_config_file)
sim_config.read... | identifier_body |
systems.rs | поведения каждого дочернего узла до тех пор,
пока один из них не выдаст значение «Успех», «В работе» или «Ошибка».
Если этого не произошло, возвращает значение «Неудача».
Условия содержат критерий, по которому определяется исход, и переменную.
Например, условие «Есть ли в этой комнате человек?» перебирает все объ... | conditional_block | ||
systems.rs | поведения каждого дочернего узла до тех пор,
пока один из них не выдаст значение «Успех», «В работе» или «Ошибка».
Если этого не произошло, возвращает значение «Неудача».
Условия содержат критерий, по которому определяется исход, и переменную.
Например, условие «Есть ли в этой комнате человек?» перебирает все объ... | identifier_body | ||
systems.rs | ому на уровень выше.
Дерево просматривается с самого верхнего узла – корня. От него производится поиск в глубину начиная
с левой ветви дерева. Если у одного узла есть несколько подзадач, они исполняются слева направо.
Среди узлов выделяют следующие типы:
-действие (action),
-узел исполнения последователь... | жда.
| identifier_name | |
systems.rs | селектор (selector),
-условие (condition),
-инвертор (inverter).
Действие представляет собой запись переменных или какое-либо движение.
Узлы последовательностей поочередно исполняют поведения каждого дочернего узла до тех пор,
пока один из них не выдаст значение «Неудача», «В работе» или «Ошибка».
Если это... | if self.event_time.to(PreciseTime::now()) > Duration::seconds(WORLD_SPEED) {
let mut behaviour_event = entity.get_component::<BehaviourEvent>(); // события
let monster_attr = entity.get_component::<MonsterAttributes>(); // события
if behaviour_event.event == 0 {
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.