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
azure_logcollector.go
err } // Machine pool can be an AzureManagedMachinePool for AKS clusters. _, err = getAzureManagedMachinePool(ctx, managementClusterClient, mp) if err != nil
} else { isWindows = isAzureMachinePoolWindows(am) } cluster, err := util.GetClusterFromMetadata(ctx, managementClusterClient, mp.ObjectMeta) if err != nil { return err } for i, instance := range mp.Spec.ProviderIDList { if mp.Status.NodeRefs != nil && len(mp.Status.NodeRefs) >= (i+1) { hostname := mp...
{ return err }
conditional_block
azure_logcollector.go
err } // Machine pool can be an AzureManagedMachinePool for AKS clusters. _, err = getAzureManagedMachinePool(ctx, managementClusterClient, mp) if err != nil { return err } } else { isWindows = isAzureMachinePoolWindows(am) } cluster, err := util.GetClusterFromMetadata(ctx, managementClusterClient, ...
(cluster *clusterv1.Cluster, hostname string, isWindows bool, outputPath string) error { nodeOSType := azure.LinuxOS if isWindows { nodeOSType = azure.WindowsOS } Logf("Collecting logs for %s node %s in cluster %s in namespace %s\n", nodeOSType, hostname, cluster.Name, cluster.Namespace) controlPlaneEndpoint :=...
collectLogsFromNode
identifier_name
azure_logcollector.go
", ), } } func windowsK8sLogs(execToPathFn func(outputFileName string, command string, args ...string) func() error) []func() error { return []func() error{ execToPathFn( "hyperv-operation.log", "Get-WinEvent", "-LogName Microsoft-Windows-Hyper-V-Compute-Operational | Select-Object -Property TimeCreated, I...
{ var err error req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, *bootDiagnostics.SerialConsoleLogBlobURI, http.NoBody) if err != nil { return errors.Wrap(err, "failed to create HTTP request") } resp, err := http.DefaultClient.Do(req) if err != nil || resp.StatusCode != 200 { return erro...
identifier_body
drkey.go
error { keys, err := getKeys(ctx, conn, steps, req.SrcHost, req.TimeStamp) if err != nil { return err } // MAC and set authenticators inside request payload := make([]byte, minSizeBaseReq(req)) serializeBaseRequest(payload, req) req.Authenticators, err = computeAuthenticators(payload, keys) return err } ...
(buff []byte, req *E2EReservationSetup) { minSize := minSizeE2ESetupReq(req) assert(len(buff) >= minSize, "buffer too short (actual %d < minimum %d)", len(buff), minSize) offset := minSizeBaseReq(&req.BaseRequest) serializeBaseRequest(buff[:offset], &req.BaseRequest) // steps: req.Steps.Serialize(buff[offset:]...
serializeE2EReservationSetup
identifier_name
drkey.go
{ keys, err := getKeys(ctx, conn, steps, req.SrcHost, req.TimeStamp) if err != nil { return err } // MAC and set authenticators inside request payload := make([]byte, minSizeBaseReq(req)) serializeBaseRequest(payload, req) req.Authenticators, err = computeAuthenticators(payload, keys) return err } func c...
func serializeE2EReservationSetup(buff []byte, req *E2EReservationSetup) { minSize := minSizeE2ESetupReq(req) assert(len(buff) >= minSize, "buffer too short (actual %d < minimum %d)", len(buff), minSize) offset := minSizeBaseReq(&req.BaseRequest) serializeBaseRequest(buff[:offset], &req.BaseRequest) // steps:...
{ minSize := minSizeBaseReq(req) assert(len(buff) >= minSize, "buffer too short (actual %d < minimum %d)", len(buff), minSize) offset := req.Id.Len() // ID, index and timestamp: req.Id.Read(buff[:offset]) // ignore errors (length was already checked) buff[offset] = byte(req.Index) offset++ binary.BigEndian.Pu...
identifier_body
drkey.go
error { keys, err := getKeys(ctx, conn, steps, req.SrcHost, req.TimeStamp) if err != nil { return err } // MAC and set authenticators inside request payload := make([]byte, minSizeBaseReq(req)) serializeBaseRequest(payload, req) req.Authenticators, err = computeAuthenticators(payload, keys) return err } ...
return validateBasic(ctx, conn, payloads, res.Authenticators, steps, srcHost, reqTimestamp) } func getKeys(ctx context.Context, conn DRKeyGetter, steps []base.PathStep, srcHost net.IP, valTime time.Time) ([]drkey.Key, error) { if len(steps) < 2 { return nil, serrors.New("wrong path in request") } return getK...
res.Authenticators = res.Authenticators[:res.FailedAS+1] steps = steps[:res.FailedAS+1] payloads := serializeSetupError(res, reqTimestamp)
random_line_split
drkey.go
.PathSteps, srcHost net.IP, reqTimestamp time.Time) error { if err := checkValidAuthenticatorsAndPath(res, steps); err != nil { return err } if err := checkEqualLength(res.Authenticators, steps); err != nil { return err } // because a failure can originate at any on-path-AS, skip ASes before its origin: ori...
{ return serrors.New("validation failed for response") }
conditional_block
cli.rs
, count: u64, bytes: u128, } impl TopicStat { fn new(topic: &str) -> Self { Self { topic: topic.to_owned(), count: 0, bytes: 0, } } fn count(&mut self, size: usize) { self.bytes += size as u128; self.count += 1; } } //impl Ord...
let mut client = client::Client::connect(&config).await.unwrap();
random_line_split
cli.rs
( id: String, client: client::Client, r_client: Option<client::Client>, data_channel: mpsc::Receiver<psrt::Message>, ) -> Self { Self { id, client, r_client, data_channel: Arc::new(RwLock::new(data_channel)), } } ...
(topic: Option<&String>) -> Vec<String> { topic .expect(ERR_TOPIC_NOT_SPECIFIED) .split(',') .into_iter() .map(ToOwned::to_owned) .collect::<Vec<String>>() } #[tokio::main(worker_threads = 1)] async fn main() { let opts = Opts::parse(); env_logger::Builder::new() ...
parse_topics
identifier_name
cli.rs
client: client::Client, r_client: Option<client::Client>, data_channel: mpsc::Receiver<psrt::Message>, ) -> Self { Self { id, client, r_client, data_channel: Arc::new(RwLock::new(data_channel)), } } fn is_connected(&self) -> bo...
{ let opts = Opts::parse(); env_logger::Builder::new() .target(env_logger::Target::Stdout) .filter_level(if opts.benchmark || opts.top { log::LevelFilter::Info } else { log::LevelFilter::Trace }) .init(); let queue_size = if opts.benchmark { 25...
identifier_body
cli.rs
( id: String, client: client::Client, r_client: Option<client::Client>, data_channel: mpsc::Receiver<psrt::Message>, ) -> Self { Self { id, client, r_client, data_channel: Arc::new(RwLock::new(data_channel)), } } ...
; assert!(client.is_connected()); let bi: u32 = rng.gen(); workers.push(Arc::new(BenchmarkWorker::new( format!("{}/{}", bi, i), client, r_client, data_channel, ))); } let mut futures = Vec::new(); staged_benchmark_start!("subscr...
{ (client.take_data_channel().unwrap(), None) }
conditional_block
deephash_test.go
(b []byte) []byte { return append(b, p...) } func TestHash(t *testing.T) { type tuple [2]interface{} type iface struct{ X interface{} } type scalars struct { I8 int8 I16 int16 I32 int32 I64 int64 I int U8 uint8 U16 uint16 U32 uint32 U64 uint64 U uint UP uintptr F32 float3...
AppendTo
identifier_name
deephash_test.go
tuple{[]appendBytes{{}, {0, 0, 0, 0, 0, 0, 0, 1}}, []appendBytes{{}, {0, 0, 0, 0, 0, 0, 0, 1}}}, wantEq: true}, {in: tuple{[]appendBytes{{}, {0, 0, 0, 0, 0, 0, 0, 1}}, []appendBytes{{0, 0, 0, 0, 0, 0, 0, 1}, {}}}, wantEq: false}, {in: tuple{iface{MyBool(true)}, iface{MyBool(true)}}, wantEq: true}, {in: tuple{ifa...
if len(got) != 1 { t.Errorf("got %d results; want 1", len(got)) } }
random_line_split
deephash_test.go
i1, &i2, &i1} v2 := [3]*int{&i1, &i2, &i2} return tuple{v1, v2} }(), wantEq: false, }, } for _, tt := range tests { gotEq := Hash(tt.in[0]) == Hash(tt.in[1]) if gotEq != tt.wantEq { t.Errorf("(Hash(%v) == Hash(%v)) = %v, want %v", tt.in[0], tt.in[1], gotEq, tt.wantEq) } } } func TestDeepHa...
{ b.ReportAllocs() node := new(tailcfg.Node) for i := 0; i < b.N; i++ { sink = Hash(node) } }
identifier_body
deephash_test.go
gotEq := Hash(tt.in[0]) == Hash(tt.in[1]) if gotEq != tt.wantEq { t.Errorf("(Hash(%v) == Hash(%v)) = %v, want %v", tt.in[0], tt.in[1], gotEq, tt.wantEq) } } } func TestDeepHash(t *testing.T) { // v contains the types of values we care about for our current callers. // Mostly we're just testing that we don't...
{ t.Fatalf("hash collision %v", i) }
conditional_block
record_db.go
DB struct { batchLock sync.Mutex db *store.BadgerDB } type recordKey insolar.ID func (k recordKey) Scope() store.Scope { return store.ScopeRecord } func (k recordKey) DebugString() string { id := insolar.ID(k) return "recordKey. " + id.DebugString() } func (k recordKey) ID() []byte { id := insolar.ID(k) ret...
if err != nil && err != ErrNotFound { return err } lastKnowPulse = rec.ID.Pulse() } position++ err = setPosition(txn, rec.ID, position) if err != nil { return err } } // set position for last record err := setLastKnownPosition(txn, lastKnowPulse, position) if err != nil {...
} // fetch position for a new pulse position, err = getLastKnownPosition(txn, rec.ID.Pulse())
random_line_split
record_db.go
struct { batchLock sync.Mutex db *store.BadgerDB } type recordKey insolar.ID func (k recordKey) Scope() store.Scope { return store.ScopeRecord } func (k recordKey) DebugString() string { id := insolar.ID(k) return "recordKey. " + id.DebugString() } func (k recordKey) ID() []byte { id := insolar.ID(k) retur...
func (k lastKnownRecordPositionKey) Scope() store.Scope { return store.ScopeRecordPosition } func (k lastKnownRecordPositionKey) ID() []byte { return bytes.Join([][]byte{{lastKnownRecordPositionKeyPrefix}, k.pn.Bytes()}, nil) } // NewRecordDB creates new DB storage instance. func NewRecordDB(db *store.BadgerDB) *...
{ return fmt.Sprintf("lastKnownRecordPositionKey. pulse: %d", k.pn) }
identifier_body
record_db.go
Prefix}, k.pn.Bytes(), parsedNum}, nil) } func newRecordPositionKeyFromBytes(raw []byte) recordPositionKey { k := recordPositionKey{} k.pn = insolar.NewPulseNumber(raw[1:]) k.number = binary.BigEndian.Uint32(raw[(k.pn.Size() + 1):]) return k } func (k recordPositionKey) String() string { return fmt.Sprintf("re...
LastKnownPosition
identifier_name
record_db.go
struct { batchLock sync.Mutex db *store.BadgerDB } type recordKey insolar.ID func (k recordKey) Scope() store.Scope { return store.ScopeRecord } func (k recordKey) DebugString() string { id := insolar.ID(k) return "recordKey. " + id.DebugString() } func (k recordKey) ID() []byte { id := insolar.ID(k) retur...
} // set position for last record err := setLastKnownPosition(txn, lastKnowPulse, position) if err != nil { return err } return nil }) if err != nil { return err } return nil } // setRecord is a helper method for storaging record to db in scope of txn. func setRecord(txn *badger.Txn, key stor...
{ return err }
conditional_block
queueing_honey_badger.rs
<SQ, A>, id: NodeId, num_txs: usize, mut rng: &mut TestRng, ) where A: Adversary<SQ>, { for tx in (num_txs / 2)..num_txs { let _ = net.send_input(id, Input::User(tx), &mut rng); } } /// Proposes `num_txs` values and expects nodes to output and order them. fn test_queueing_honey_badger<A...
(node_info: NewNodeInfo<SQ>, seed: TestRngSeed) -> (SQ, Step<QHB>) { let mut rng: TestRng = TestRng::from_seed(seed); let peer_ids = node_info.netinfo.other_ids().cloned(); let netinfo = node_info.netinfo.clone(); let dhb = DynamicHoneyBadger::builder().build(netinfo, node_info.secret_key, node_...
new_queueing_hb
identifier_name
queueing_honey_badger.rs
<SQ, A>, id: NodeId, num_txs: usize, mut rng: &mut TestRng, ) where A: Adversary<SQ>, { for tx in (num_txs / 2)..num_txs { let _ = net.send_input(id, Input::User(tx), &mut rng); } } /// Proposes `num_txs` values and expects nodes to output and order them. fn test_queueing_honey_badger<A...
info!( "{:?} has finished waiting for node removal; still waiting: {:?}", stepped_id, awaiting_removal ); if awaiting_removal.is_empty() { info!("Removing first correct node from the test network"); saved_first_correct ...
random_line_split
queueing_honey_badger.rs
if the node has not output all changes or transactions yet. let node_busy = |node: &Node<SQ>| { !has_remove(node) || !has_add(node) || !node.algorithm().algo().queue().is_empty() }; // All nodes await removal. let mut awaiting_removal: BTreeSet<_> = net.correct_nodes().map(|node| *node.id()).c...
{ test_queueing_honey_badger_different_sizes(ReorderingAdversary::new, 30, seed); }
identifier_body
queueing_honey_badger.rs
Net<SQ, A>, id: NodeId, num_txs: usize, mut rng: &mut TestRng, ) where A: Adversary<SQ>, { for tx in (num_txs / 2)..num_txs { let _ = net.send_input(id, Input::User(tx), &mut rng); } } /// Proposes `num_txs` values and expects nodes to output and order them. fn test_queueing_honey_badge...
stepped_id, awaiting_addition ); if awaiting_addition.is_empty() && !rejoined_first_correct { let node = saved_first_correct .take() .expect("first correct node wasn't saved"); let...
{ // If the stepped node started voting to add the first correct node back, // take a note of that and rejoin it. if let Some(join_plan) = net.get(stepped_id) .unwrap() .outputs() .iter() ...
conditional_block
lru_cache.rs
//! assert_eq!(*cache.get(&2).unwrap(), 22); //! //! cache.put(6, 60); //! assert!(cache.get(&3).is_none()); //! //! cache.change_capacity(1); //! assert!(cache.get(&2).is_none()); //! ``` use std::cast; use std::container::Container; use std::hash::Hash; use std::fmt; use std::ptr; use HashMap; struct KeyRef<K> { k...
(&mut self) { unsafe { let _: ~LruEntry<K, V> = cast::transmute(self.head); let _: ~LruEntry<K, V> = cast::transmute(self.tail); } } } #[cfg(test)] mod tests { use super::LruCache; fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) { assert!(opt.is_some()); ...
drop
identifier_name
lru_cache.rs
//! assert_eq!(*cache.get(&2).unwrap(), 22); //! //! cache.put(6, 60); //! assert!(cache.get(&3).is_none()); //! //! cache.change_capacity(1); //! assert!(cache.get(&2).is_none()); //! ``` use std::cast; use std::container::Container; use std::hash::Hash; use std::fmt; use std::ptr; use HashMap; struct KeyRef<K> { k...
unsafe { cur = (*cur).next; match (*cur).key { // should never print nil None => try!(write!(f.buf, "nil")), Some(ref k) => try!(write!(f.buf, "{}", *k)), } } try!(write!(f.bu...
{ try!(write!(f.buf, ", ")) }
conditional_block
lru_cache.rs
//! assert_eq!(*cache.get(&2).unwrap(), 22); //! //! cache.put(6, 60); //! assert!(cache.get(&3).is_none()); //! //! cache.change_capacity(1); //! assert!(cache.get(&2).is_none()); //! ``` use std::cast; use std::container::Container; use std::hash::Hash; use std::fmt; use std::ptr; use HashMap; struct KeyRef<K> { k...
write!(f.buf, r"\}") } } impl<K: Hash + TotalEq, V> Container for LruCache<K, V> { /// Return the number of key-value pairs in the cache. fn len(&self) -> uint { self.map.len() } } impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> { /// Clear the cache of all key-value pairs. ...
random_line_split
lru_cache.rs
//! assert_eq!(*cache.get(&2).unwrap(), 22); //! //! cache.put(6, 60); //! assert!(cache.get(&3).is_none()); //! //! cache.change_capacity(1); //! assert!(cache.get(&2).is_none()); //! ``` use std::cast; use std::container::Container; use std::hash::Hash; use std::fmt; use std::ptr; use HashMap; struct KeyRef<K> { k...
#[inline] fn detach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*(*node).prev).next = (*node).next; (*(*node).next).prev = (*node).prev; } } #[inline] fn attach(&mut self, node: *mut LruEntry<K, V>) { unsafe { (*node).next = (*self...
{ if self.len() > 0 { let lru = unsafe { (*self.tail).prev }; self.detach(lru); unsafe { match (*lru).key { None => (), Some(ref k) => { self.map.pop(&KeyRef{k: k}); } } } } }
identifier_body
chartdata.py
__allow_access_to_unprotected_subobjects__ = 1 ''' EVENT TYPES ''' # EVENT TYPES CREATION = 1000 # set as attributes for EventBrain instances. metadata = ['date_year', 'date_month', 'date_day', 'related_object_id', 'path', 'patient_id', 'id', 'event_type', 'meta_type'] ...
def Title(self): return self.title # TODO: Remover a partir de 01/04/2013 # def absolute_url_path(self): # chart_folder = self.patient.chartFolder # return chart_folder.absolute_url_path() + self.url_sufix class ChartData(Persistent): __allow_access_to_unprotected_subobjects__ =...
tal = getSite() return getToolByName(portal, 'portal_membership').getAuthenticatedMember()
identifier_body
chartdata.py
__allow_access_to_unprotected_subobjects__ = 1 ''' EVENT TYPES ''' # EVENT TYPES CREATION = 1000 # set as attributes for EventBrain instances. metadata = ['date_year', 'date_month', 'date_day', 'related_object_id', 'path', 'patient_id', 'id', 'event_type', 'meta_type'] ...
elif self.related_obj.portal_type == 'Image': return 'Imagem ' elif self.related_obj.portal_type == 'File': return 'Arquivo ' return '' def posfix(self): ''' called by eprint ''' if self.type == Event.CREATION: ...
return 'Documento '
conditional_block
chartdata.py
__allow_access_to_unprotected_subobjects__ = 1 ''' EVENT TYPES ''' # EVENT TYPES CREATION = 1000 # set as attributes for EventBrain instances. metadata = ['date_year', 'date_month', 'date_day', 'related_object_id', 'path', 'patient_id', 'id', 'event_type', 'meta_type'] ...
def posfix(self): ''' called by eprint ''' if self.type == Event.CREATION: if self.related_obj.meta_type == 'Visit': return self._visit_review_state() else: return ' adicionado.' def getAuthor(self): ''' If ...
return 'Imagem ' elif self.related_obj.portal_type == 'File': return 'Arquivo ' return ''
random_line_split
chartdata.py
__allow_access_to_unprotected_subobjects__ = 1 ''' EVENT TYPES ''' # EVENT TYPES CREATION = 1000 # set as attributes for EventBrain instances. metadata = ['date_year', 'date_month', 'date_day', 'related_object_id', 'path', 'patient_id', 'id', 'event_type', 'meta_type'] ...
(self): ''' function that transform an event instance in a dictionary to be exported. ''' if isinstance(self.related_obj, ChartItemEventWrapper): return {'type': self.type, 'date': self.date, 'author': self.author, 'related_obj' : self.related_obj.meta_type, ...
export_dict
identifier_name
utils.py
hmac import base64 import MySQLdb import os import re import marshal import subprocess from sitescripts.utils import get_config, cached, get_template, anonymizeMail, sendMail def getReportSubscriptions(guid): cursor = get_db().cursor(MySQLdb.cursors.DictCursor) executeQuery(cursor, '''SELECT...
screenshot = reportData.get('screenshot', None) if screenshot != None: reportData['hasscreenshot'] = 2 if reportData.get('screenshotEdited', False) else 1 try: saveScreenshot(guid, screenshot) except (TypeError, UnicodeEncodeError): reportData['hasscreenshot'] = 0...
def saveReport(guid, reportData, isNew=False): cursor = get_db().cursor()
random_line_split
utils.py
, cached, get_template, anonymizeMail, sendMail def getReportSubscriptions(guid): cursor = get_db().cursor(MySQLdb.cursors.DictCursor) executeQuery(cursor, '''SELECT url, hasmatches FROM #PFX#sublists INNER JOIN #PFX#subscriptions ON (#PFX#sublists.list = #PFX#subscriptions.id) ...
getUserId
identifier_name
utils.py
PFX#reports WHERE ctime >= FROM_UNIXTIME(%s) LIMIT %s OFFSET %s''', (startTime, count, offset)) rows = cursor.fetchall() cursor.close() if len(rows) == 0: break for row in rows: yield row offset += len(rows) def getReportsForUser(con...
hash = hashlib.md5() hash.update(get_config().get('reports', 'secret')) hash.update(id) hash.update(str(year)) hash.update(str(week)) return hash.hexdigest()
identifier_body
utils.py
hmac import base64 import MySQLdb import os import re import marshal import subprocess from sitescripts.utils import get_config, cached, get_template, anonymizeMail, sendMail def getReportSubscriptions(guid): cursor = get_db().cursor(MySQLdb.cursors.DictCursor) executeQuery(cursor, '''SELECT...
for row in rows: yield row offset += len(rows) def getReportsForUser(contact): cursor = get_db().cursor(MySQLdb.cursors.DictCursor) executeQuery(cursor, '''SELECT guid, type, UNIX_TIMESTAMP(ctime) AS ctime, status, site, contact, comment, hasscreensh...
break
conditional_block
linux_abi.go
2 iocNrshift = 0 iocTypeshift = (iocNrshift + iocNrbits) iocSizeshift = (iocTypeshift + iocTypebits) iocDirshift = (iocSizeshift + iocSizebits) iocWrite = 1 iocRead = 2 // Linux /dev/sev-guest ioctl interface iocTypeSnpGuestReq = 'S' iocSnpWithoutNr = ((iocWrite | iocRead) << iocDirshift) | ...
() BinaryConversion { var certsAddress unsafe.Pointer if len(r.Certs) != 0 { certsAddress = unsafe.Pointer(&r.Certs[0]) } return &SnpExtendedReportReqABI{ Data: r.Data, CertsAddress: certsAddress, CertsLength: r.CertsLength, } } // SnpUserGuestRequestABI is Linux's sev-guest ioctl abi for issuing...
ABI
identifier_name
linux_abi.go
2 iocNrshift = 0 iocTypeshift = (iocNrshift + iocNrbits) iocSizeshift = (iocTypeshift + iocTypebits) iocDirshift = (iocSizeshift + iocSizebits) iocWrite = 1 iocRead = 2 // Linux /dev/sev-guest ioctl interface iocTypeSnpGuestReq = 'S' iocSnpWithoutNr = ((iocWrite | iocRead) << iocDirshift) | ...
// EsRetry is the code for a retry instruction emulation EsRetry ) // SevEsErr is an error that interprets SEV-ES guest-host communication results. type SevEsErr struct { Result EsResult } func (err *SevEsErr) Error() string { if err.Result == EsUnsupported { return "requested operation not supported" } if er...
EsException
random_line_split
linux_abi.go
msgReportReqHeaderSize = 0x20 SnpReportRespReportSize = snpResportRespSize - msgReportReqHeaderSize ) const ( // EsOk denotes success. EsOk EsResult = iota // EsUnsupported denotes that the requested operation is not supported. EsUnsupported // EsVmmError denotes that the virtual machine monitor was in an une...
{ return fmt.Errorf("Finish argument is %v. Expects a *SnpUserGuestRequestSafe", reflect.TypeOf(b)) }
conditional_block
linux_abi.go
2 iocNrshift = 0 iocTypeshift = (iocNrshift + iocNrbits) iocSizeshift = (iocTypeshift + iocTypebits) iocDirshift = (iocSizeshift + iocSizebits) iocWrite = 1 iocRead = 2 // Linux /dev/sev-guest ioctl interface iocTypeSnpGuestReq = 'S' iocSnpWithoutNr = ((iocWrite | iocRead) << iocDirshift) | (...
// ABI returns the same object since it doesn't need a separate representation across the interface. func (r *SnpReportRespABI) ABI() BinaryConversion { return r } // Pointer returns a pointer to the object itself. func (r *SnpReportRespABI) Pointer() unsafe.Pointer { return unsafe.Pointer(r) } // Finish checks th...
{ return nil }
identifier_body
EachBehavior.ts
validateNotDefinedIf, validateNotEmptyString, validateNotNullIfFieldEquals, validateOneOf, validateValidId } from 'validator/Validations'; import ComponentTransitions from "component/ComponentTransitions"; import AttributeParser from 'validator/AttributeParser'; import EachTemplateAttributes from "behavior/core/each/E...
const tagText: string = validated ? elementAsString(template) : null; const params: EachTemplateAttributes = TEMPLATE_ATTRIBUTE_PARSER.parse(template, prefix, validated, tagText); switch (params.type) { case EachTemplateType.EMPTY: ++emptyCount; this.empty = this.createFactory(template, params...
{ errors.add(`template definitions must only have one top-level tag in repeat on expression: ${ this.getExpression() } and markup: ${ template.innerHTML }`); continue; }
conditional_block
EachBehavior.ts
validateNotDefinedIf, validateNotEmptyString, validateNotNullIfFieldEquals, validateOneOf, validateValidId } from 'validator/Validations'; import ComponentTransitions from "component/ComponentTransitions";
import EachTemplateAttributes from "behavior/core/each/EachTemplateAttributes"; import AttributeParserImpl from "validator/AttributeParserImpl"; import { NodeTypes } from "Constants"; import { ATTRIBUTE_DELIMITER } from "const/HardValues"; import Messages from "util/Messages"; import AbstractContainerBehavior from "beh...
import AttributeParser from 'validator/AttributeParser';
random_line_split
EachBehavior.ts
.getMediator().watch(this, this.onTargetChange); } this.tellChildren(ComponentTransitions.MOUNT); } public onUnmount(): void { this.tellChildren(ComponentTransitions.UNMOUNT); } public onRemount(): void { this.tellChildren(ComponentTransitions.MOUNT); } public requestDigestionSources(sources: Digestab...
tellChildren
identifier_name
EachBehavior.ts
validateNotDefinedIf, validateNotEmptyString, validateNotNullIfFieldEquals, validateOneOf, validateValidId } from 'validator/Validations'; import ComponentTransitions from "component/ComponentTransitions"; import AttributeParser from 'validator/AttributeParser'; import EachTemplateAttributes from "behavior/core/each/E...
public onInit(): void { this.elIsSelect = this.getEl().tagName.toLowerCase() === "select"; } public onMount(): void { this.initFields(); this.initScope(); this.initIdStrategy(); this.parseChildElements(); this.onTargetChange(null, this.getMediator().get()); if (this.isMutable()) { this.getMediat...
{ super(); this.setFlag(BehaviorFlags.CHILD_CONSUMPTION_PROHIBITED); this.setDefaults(DEFAULT_ATTRIBUTES); this.setValidations({ idkey: [validateDefined, validateNotEmptyString], expression: [validateNotEmptyString, validateNotNullIfFieldEquals("mode", "expression")], mode: [validateDefined, validateOn...
identifier_body
submittestevent.go
CaseValidatorFunc function pointer for calling the files RequestParamsCaseValidatorFunc = common.RequestParamsCaseValidator ) // SubmitTestEvent is a helper method to handle the submit test event request. func (e *ExternalInterfaces) SubmitTestEvent(ctx context.Context, req *eventsproto.EventSubRequest) response.RPC...
{ events := getAllowedEventTypes() for _, event := range events { if event == got { return true } } return false }
identifier_body
submittestevent.go
var ( //JSONUnmarshal function pointer for calling the files JSONUnmarshal = json.Unmarshal //RequestParamsCaseValidatorFunc function pointer for calling the files RequestParamsCaseValidatorFunc = common.RequestParamsCaseValidator ) // SubmitTestEvent is a helper method to handle the submit test event request. f...
func validEventType(got string) bool { events := getAllowedEventTypes()
random_line_split
submittestevent.go
have the functionality of // - Create Event Subscription // - Delete Event Subscription // - Get Event Subscription // - Post Event Subscription to destination // - Post TestEvent (SubmitTestEvent) // and corresponding unit test cases package events import ( "context" "encoding/json" "fmt" "net/http" "time" uu...
(reqBody []byte) (*common.Event, string, string, []interface{}) { var testEvent common.Event var req map[string]interface{} json.Unmarshal(reqBody, &req) if val, ok := req["MessageId"]; ok { switch v := val.(type) { case string: testEvent.MessageID = v default: return nil, response.PropertyValueTypeErro...
validAndGenSubTestReq
identifier_name
submittestevent.go
have the functionality of // - Create Event Subscription // - Delete Event Subscription // - Get Event Subscription // - Post Event Subscription to destination // - Post TestEvent (SubmitTestEvent) // and corresponding unit test cases package events import ( "context" "encoding/json" "fmt" "net/http" "time" uu...
// we need common.MessageData to find the correct destination to send test event var message common.MessageData message.Events = append(message.Events, *testEvent) messageBytes, _ := json.Marshal(message) eventUniqueID := uuid.NewV4().String() for _, sub := range subscriptions { for _, origin := range sub.Even...
{ // Internal error errMsg := "error while trying to find the event destination" l.LogWithFields(ctx).Error(errMsg) return common.GeneralError(http.StatusInternalServerError, response.InternalError, errMsg, nil, nil) }
conditional_block
index.js
//////////////////// var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); $scope.changeTo = 'Hungarian'; /* event source that pulls from google.com */ $scope.eventSource = { url: "http://www.google.com/calendar/feeds/usa__e...
}).then(function(popover) { $scope.recado = popover; }); $ionicPopover.fromTemplateUrl('templates/user-filho.html', { scope: $scope, }).then(function(popover) { $scope.UserFilho = popover; }); $scope.scrap = [ { id: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do e...
}); $ionicPopover.fromTemplateUrl('templates/recado.html', { scope: $scope,
random_line_split
index.js
0),allDay: false}, // {title: 'Click for Google',start: new Date(y, m, 28),end: new Date(y, m, 29),url: 'http://google.com/'} // ]; /* event source that calls a function on every view switch */ $scope.eventsF = function (start, end, timezone, callback) { var s = new Date(start).getTime() / 1000; ...
.shownGroup = null; } else {
conditional_block
billing_controller.go
igs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ) const ( UserNamespacePrefix = "ns-" ResourceQuotaPrefix = "quota-" ) const BillingAnnotationLastUpdateTim...
me.Hour).Add(time.Hour); t.Before(currentHourTime) || t.Equal(currentHourTime); t = t.Add(time.Hour) { if err = r.billingWithHourTime(ctx, t.UTC(), nsListStr, ns.Name, dbClient); err != nil { r.Logger.Error(err, "billing with hour time failed", "time", t.Format(time.RFC3339)) return ctrl.Result{}, err } } r...
开右闭 for t := queryTime.Truncate(ti
conditional_block
billing_controller.go
", "err", err) } }() ns := &corev1.Namespace{} if err := r.Get(ctx, req.NamespacedName, ns); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } if ns.DeletionTimestamp != nil { r.Logger.V(1).Info("namespace is deleting", "namespace", ns) return ctrl.Result{}, nil } own := ns.Annotations[v1...
identifier_body
billing_controller.go
reconciliation loop which aims to // move the current state of the cluster closer to the desired state. // TODO(user): Modify the Reconcile function to compare the state specified by // the Billing object against the actual cluster state, and then // perform operations to make the cluster state reflect the state speci...
MongoURI); r.mon
identifier_name
billing_controller.go
igs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ) const ( UserNamespacePrefix = "ns-" ResourceQuotaPrefix = "quota-" ) const BillingAnnotationLastUpdateTim...
//+kubebuilder:rbac:groups=account.sealos.io,resources=accountbalances,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=account.sealos.io,resources=accountbalances/status,verbs=get;list;watch;create;update;patch;delete // Reconcile is part of the main kubernetes reconciliation loop which aims...
//+kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=core,resources=resourcequotas,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=rolebindings,verbs=get;list;watch;create;update;pa...
random_line_split
fetch_places.rs
with position but lacking places. #[structopt(long, short)] auto: bool, /// Image ids to fetch place data for photos: Vec<i32>, } impl Fetchplaces { pub fn run(&self) -> Result<(), super::adm::result::Error> { let db = self.db.connect()?; if self.auto { println!("Should...
Some("station") => Some(18), _ => None, }) .or_else(|| match tag_str(tags, "amenity") { Some("bus_station") => Some(16), Some("exhibition_center") => Some(20), Some("kindergarten") => Some(15), Some("...
Some("pedestrian") => Some(15), // torg Some("rest_area") => Some(16), _ => None, }) .or_else(|| match tag_str(tags, "public_transport") {
random_line_split
fetch_places.rs
with position but lacking places. #[structopt(long, short)] auto: bool, /// Image ids to fetch place data for photos: Vec<i32>, } impl Fetchplaces { pub fn run(&self) -> Result<(), super::adm::result::Error> { let db = self.db.connect()?; if self.auto { println!("Should...
Some("attraction") => Some(16), Some("theme_park") | Some("zoo") => Some(14), _ => None, }) .or_else(|| match tag_str(tags, "boundary") { Some("national_park") => Some(14), Some("historic") => Some(7), // Seems to be...
{ if let Some(tags) = obj.get("tags") { let name = tags .get("name:sv") //.or_else(|| tags.get("name:en")) .or_else(|| tags.get("name")) .and_then(Value::as_str); let level = tags .get("admin_level") .and_then(Value::as_str) ...
identifier_body
fetch_places.rs
with position but lacking places. #[structopt(long, short)] auto: bool, /// Image ids to fetch place data for photos: Vec<i32>, } impl Fetchplaces { pub fn run(&self) -> Result<(), super::adm::result::Error> { let db = self.db.connect()?; if self.auto { println!("Should...
<'a>(tags: &'a Value, name: &str) -> Option<&'a str> { tags.get(name).and_then(Value::as_str) } fn get_or_create_place(
tag_str
identifier_name
inbound.rs
all the inbound SWIM messages. use super::AckSender; use crate::{member::Health, server::{outbound, Server}, swim::{Ack, Ping, PingReq, Swim, SwimKind}}; use habitat_common::liveliness_checker; use...
(server: &Server, socket: &UdpSocket, tx_outbound: &AckSender, addr: SocketAddr, mut msg: Ack) { trace!("Ack from {}@{}", msg.from.id, addr); if msg.forward_to.is_some() && *server.member_id != msg.forwar...
process_ack_mlw_smw_rhw
identifier_name
inbound.rs
all the inbound SWIM messages. use super::AckSender; use crate::{member::Health, server::{outbound, Server}, swim::{Ack, Ping, PingReq, Swim, SwimKind}}; use habitat_common::liveliness_checker; use...
match socket.recv_from(&mut recv_buffer[..]) { Ok((length, addr)) => { let swim_payload = match server.unwrap_wire(&recv_buffer[0..length]) { Ok(swim_payload) => swim_payload, Err(e) => { // NOTE: In the future, we mig...
{ thread::sleep(Duration::from_millis(100)); continue; }
conditional_block
inbound.rs
handles all the inbound SWIM messages. use super::AckSender; use crate::{member::Health, server::{outbound, Server}, swim::{Ack, Ping, PingReq, Swim, SwimKind}}; use habitat_common::liveliness_chec...
addr: SocketAddr, mut msg: Ack) { trace!("Ack from {}@{}", msg.from.id, addr); if msg.forward_to.is_some() && *server.member_id != msg.forward_to.as_ref().unwrap().id { let (forward_to_addr, from_addr) = { let forward_to = msg.forward_to....
fn process_ack_mlw_smw_rhw(server: &Server, socket: &UdpSocket, tx_outbound: &AckSender,
random_line_split
inbound.rs
bound, Server}, swim::{Ack, Ping, PingReq, Swim, SwimKind}}; use habitat_common::liveliness_checker; use habitat_core::util::ToI64; use lazy_static::lazy_static; use log::{debug, error, trace...
{ outbound::ack_mlr_smr_rhw(server, socket, &msg.from, addr, msg.forward_to); // Populate the member for this sender with its remote address msg.from.address = addr.ip().to_string(); trace!("Ping from {}@{}", msg.from.id, addr); if msg.from.departed { server.insert_member_mlw_rhw(msg.from, H...
identifier_body
sandbox_second.py
(mat): empty_array = np.full((30, 30), 0, dtype=np.float32) if(len(mat) != 0): mat = np.asarray(mat, dtype=np.float32) empty_array[:mat.shape[0], : mat.shape[1]] = mat return np.expand_dims(empty_array, axis= 2) #%% train_input = [] cnt = 0 # use all the tasks in train # use inpu...
enhance_mat_30x30
identifier_name
sandbox_second.py
in train # use input and output for task in train_data: for sample in task['train']: _input = sample['input'] _output = sample['output'] if len(_input) > 1: train_input.append(_input) else: cnt += 1 if len(_output) > 1: ...
merge = Dense(128, activation='relu')(merge) merge = Dense(128, activation='relu')(merge) merge = Dropout(0.3)(merge) pretrain.mirror_tasks, pretrain.double_line_with_multiple_colors_tasks, # regression layers out_1 = Dense(128, activation='relu')(merge) out_1 = Dense(1, activation='linear', name='fzn_rows')(out_1) ...
x_2 = MaxPooling2D(pool_size=(2, 2))(x_2) x_2 = Dropout(0.25)(x_2) x_2 = Flatten()(x_2) merge = concatenate([x_1, x_2])
random_line_split
sandbox_second.py
tasks in train # use input and output for task in train_data: for sample in task['train']:
print('Thrown away samples: ') print(cnt) print('Total pretrain samples: ') print(len(train_input)) #%% # generate all the pretrain data # 1. modified output tasks # 2. y_labels PRETRAIN_FUNCTIONS = [ pretrain.rotate_tasks, pretrain.multiply_tasks, pretrain.change_random_color_tasks, pretrain...
_input = sample['input'] _output = sample['output'] if len(_input) > 1: train_input.append(_input) else: cnt += 1 if len(_output) > 1: train_input.append(_output) else: cnt += 1
conditional_block
sandbox_second.py
#%% train_input = [] cnt = 0 # use all the tasks in train # use input and output for task in train_data: for sample in task['train']: _input = sample['input'] _output = sample['output'] if len(_input) > 1: train_input.append(_input) else: ...
empty_array = np.full((30, 30), 0, dtype=np.float32) if(len(mat) != 0): mat = np.asarray(mat, dtype=np.float32) empty_array[:mat.shape[0], : mat.shape[1]] = mat return np.expand_dims(empty_array, axis= 2)
identifier_body
polyres.py
) # No options means an error is going to happen later, but for now, # just return some placeholders so that we can make it to the # error later. if not options: return {k: _SINGLETON for k in set(range(num_args)) | kwargs_names} fts: Dict[Union[int, str], ft.TypeModifier] = {} for...
paramtype = barg.param.get_type(ctx.env.schema) arg_type_dist = barg.valtype.get_common_parent_type_distance( paramtype, ctx.env.schema) call_type_dist += arg_type_dist if type_dist is None: type_dist = call_type_dist ...
if barg.param is None: # Skip injected bitmask argument. continue
random_line_split
polyres.py
) # No options means an error is going to happen later, but for now, # just return some placeholders so that we can make it to the # error later. if not options: return {k: _SINGLETON for k in set(range(num_args)) | kwargs_names} fts: Dict[Union[int, str], ft.TypeModifier] = {} for ch...
ctx.env.schema, ct = ( resolved_poly_base_type.find_common_implicitly_castable_type( resolved, ctx.env.schema, ) ) if ct is not None: # If we found a common implicitly castable type, we ...
return 0
conditional_block
polyres.py
) # No options means an error is going to happen later, but for now, # just return some placeholders so that we can make it to the # error later. if not options: return {k: _SINGLETON for k in set(range(num_args)) | kwargs_names} fts: Dict[Union[int, str], ft.TypeModifier] = {} for...
matched = [call] if len(matched) <= 1: # Unambiguios resolution return matched else: # Ambiguous resolution, try to disambiguate by # checking for total type distance. type_dist = None remaining = [] for call in matched: call_typ...
implicit_cast_distance = None matched = [] candidates = list(candidates) for candidate in candidates: call = try_bind_call_args( args, kwargs, candidate, basic_matching_only, ctx=ctx) if call is None: continue total_cd = sum(barg.cast_distance for barg in c...
identifier_body
polyres.py
(NamedTuple): func: s_func.CallableLike args: List[BoundArg] null_args: Set[str] return_type: s_types.Type has_empty_variadic: bool _VARIADIC = ft.ParameterKind.VariadicParam _NAMED_ONLY = ft.ParameterKind.NamedOnlyParam _POSITIONAL = ft.ParameterKind.PositionalParam _SET_OF = ft.TypeModifier.Se...
BoundCall
identifier_name
httpretty.go
on any *http.Client // // if _, err := http.Get("https://www.google.com/"); err != nil { // fmt.Fprintf(os.Stderr, "%+v\n", err) // os.Exit(1) // } // } // // If you pass nil to the logger.RoundTripper it is going to fallback to http.DefaultTransport. // // You can use the logger quickly to log requests on ...
() Filter { l.mu.Lock() f := l.filter defer l.mu.Unlock() return f } func (l *Logger) getBodyFilter() BodyFilter { l.mu.Lock() f := l.bodyFilter defer l.mu.Unlock() return f } func (l *Logger) cloneSkipHeader() map[string]struct{} { l.mu.Lock() skipped := l.skipHeader l.mu.Unlock() m := map[string]struct...
getFilter
identifier_name
httpretty.go
httpretty.Logger{ // Time: true, // TLS: true, // RequestHeader: true, // RequestBody: true, // ResponseHeader: true, // ResponseBody: true, // } // // logger.Middleware(handler) // // Note: server logs don't include response headers set by the server. // Client logs don't inclu...
{ p.printRequestInfo(req) }
conditional_block
httpretty.go
any *http.Client // // if _, err := http.Get("https://www.google.com/"); err != nil { // fmt.Fprintf(os.Stderr, "%+v\n", err) // os.Exit(1) // } // } // // If you pass nil to the logger.RoundTripper it is going to fallback to http.DefaultTransport. // // You can use the logger quickly to log requests on you...
// RoundTrip implements the http.RoundTrip interface. func (r roundTripper) RoundTrip(req *http.Request) (resp *http.Response, err error) { tripper := r.rt if tripper == nil { // BUG(henvic): net/http data race condition when the client // does concurrent requests using the very same HTTP transport. // See G...
{ return roundTripper{ logger: l, rt: rt, } }
identifier_body
httpretty.go
on any *http.Client // // if _, err := http.Get("https://www.google.com/"); err != nil { // fmt.Fprintf(os.Stderr, "%+v\n", err) // os.Exit(1) // } // } // // If you pass nil to the logger.RoundTripper it is going to fallback to http.DefaultTransport. // // You can use the logger quickly to log requests on ...
"sync" "github.com/henvic/httpretty/internal/color" ) // Formatter can be used to format body. // // If the Format function returns an error, the content is printed in verbatim after a warning. // Match receives a media type from the Content-Type field. The body is formatted if it returns true. type Formatter inter...
"os"
random_line_split
fvs.py
() # Don't try to delete the label. else: # Not a self-loop, but a multiple edge. sole_neighbour = nbr1 sole_nbr_label = sole_neighbour['label'] if sole_nbr_label not in forbidden_set: partial_fvs.append(sole_nbr_label) else: parti...
sole_neighbour.delete() # discard = remove if present small_degree_labels.discard(sole_nbr_label) for neighbour_label in neighbour_labels: if neighbour_label not in forbidden_set: neighbour = H.vs.find(label = ne...
neighbour_labels = list(v['label'] for v in neighbours)
random_line_split
fvs.py
global_lower_bound2 = approx_packing_number(G) global_current_lower_bound = global_lower_bound1 if global_lower_bound2 > global_current_lower_bound: global_current_lower_bound = global_lower_bound2 if global_current_lower_bound == global_current_upper_bound : return global_c...
v_degree = v.degree() if v_degree > max_degree: max_degree = v_degree max_vertex = v
conditional_block
fvs.py
() # Don't try to delete the label. else: # Not a self-loop, but a multiple edge. sole_neighbour = nbr1 sole_nbr_label = sole_neighbour['label'] if sole_nbr_label not in forbidden_set: partial_fvs.append(sole_nbr_label) else: parti...
# Pick a smallest cycle from G and return its vertex list. A # multiple edge counts as a cycle. This function does not modify # its argument. def pick_smallest_cycle(G): if G.has_multiple(): # The girth function does not see multiedges. multi_edge = next(dropwhile(lambda e: not e.is_multiple(), G.es)) ...
H = G.copy() packing_approx = 0 while H.has_multiple(): # The girth function does not see multiedges. multi_edge = next(dropwhile(lambda e: not e.is_multiple(), H.es)) H.delete_vertices(list(multi_edge.tuple)) packing_approx += 1 H_girth_vertices = H.girth(True) while H_girth_v...
identifier_body
fvs.py
() # Don't try to delete the label. else: # Not a self-loop, but a multiple edge. sole_neighbour = nbr1 sole_nbr_label = sole_neighbour['label'] if sole_nbr_label not in forbidden_set: partial_fvs.append(sole_nbr_label) else: parti...
(G): n = G.vcount() if n == 0: # Don't do anything fancy if the graph is already empty return 0 else: max_degree = G.maxdegree() first_lower_bound = int((n + 2)/(max_degree + 1)) degrees = sorted(G.degree(), reverse = True) # Sorted non-increasing mi...
fvs_lower_bound
identifier_name
renderer_go_func.go
BodyRenderer[T Importer] struct { r *GoFuncRenderer[T] } ) // Returns sets up a return tuple of the function. // // We don't divide fmt.Stringer or string here, except stringers from // [types] or ast [libraries // // Arguments are treated almost the same way as for function/method calls, it can be: // - missing a...
switch len(results) { case 0: case 1: switch v := results[0].(type) { case Params: r.checkSeqsUniq("argument", "arguments", v.commasSeq) zeroes = heuristics.ZeroGuesses(v.data, nil) r.results = v.data case *Params: r.checkSeqsUniq("argument", "arguments", v.commasSeq) r.results = v.data zer...
]string
identifier_name
renderer_go_func.go
32, bool, string, etc are supported, // even though they may be shadowed somehow. We just guess // they weren't and this is acceptable for most cases. // - Chans, maps, slices, pointers are supported too. // - Error type is matched by its name, same guess as for builtins // here. func (r *GoFuncRenderer[T]) ...
parameter index %d: expected it to be %T got %T", i, new(types.Var), param, )) } checker.reg(p.Name()) r.takeVarName(what, p.Name()) res = append(res, [2]string{p.Name(), r.r.Type(p.Type())}) zeroes = append(zeroes, zeroValueOfTypesType(r.r, p.Type(), i == len(params)-1)) } return } func ...
conditional_block
renderer_go_func.go
Renderer[T Importer] struct { r *GoFuncRenderer[T] } ) // Returns sets up a return tuple of the function. // // We don't divide fmt.Stringer or string here, except stringers from // [types] or ast [libraries // // Arguments are treated almost the same way as for function/method calls, it can be: // - missing at al...
...any) { checkName(r.kind(), name) r.name = name switch len(params) { case 0: case 1: switch v := params[0].(type) { case Params: r.checkSeqsUniq("argument", "arguments", v.commasSeq) r.params = v.data case *Params: r.checkSeqsUniq("argument", "arguments", v.commasSeq) r.params = v.data case ...
} func (r *GoFuncRenderer[T]) setFuncInfo(name string, params
identifier_body
renderer_go_func.go
// So, the usage of this method will be like // r.M("t", "*Type")("Name")("ctx $ctx.Context").Returns("string", "error, "").Body(func(…) { // r.L(`return $ZeroReturnValue $errs.New("error")`) // }) // Producing this code // func (t *Type) Name(ctx context.Context) (string, error) { // return...
// // The return value is a function with a signature whose semantics matches F. //
random_line_split
compressor_params.rs
struct CompressorParams(pub *mut sys::CompressorParams); impl Default for CompressorParams { fn default() -> Self { Self::new() } } impl CompressorParams { /// Create a compressor with default options pub fn new() -> Self { unsafe { let mut params = CompressorParams(sys::c...
// The default options that are applied when creating a new compressor or calling reset() on it fn set_default_options(&mut self) { // Set a default quality level. Leaving this unset results in undefined behavior, so we set // it to a working value by default self.set_etc1s_quality_lev...
{ unsafe { sys::compressor_params_clear(self.0); self.set_default_options(); self.clear_source_image_list(); } }
identifier_body
compressor_params.rs
pub struct CompressorParams(pub *mut sys::CompressorParams); impl Default for CompressorParams { fn default() -> Self { Self::new() } } impl CompressorParams { /// Create a compressor with default options pub fn new() -> Self { unsafe { let mut params = CompressorParams(sys...
( &mut self, print_status_to_stdout: bool, ) { unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) } } /// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN) /// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALIT...
set_print_status_to_stdout
identifier_name
compressor_params.rs
pub struct CompressorParams(pub *mut sys::CompressorParams); impl Default for CompressorParams { fn default() -> Self { Self::new() } } impl CompressorParams { /// Create a compressor with default options pub fn new() -> Self { unsafe { let mut params = CompressorParams(sys...
} /// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN) /// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALITY_MAX). pub fn set_etc1s_quality_level( &mut self, quality_level: u32, ) { assert!(quality_level >= crate::ETC1S_QUALITY_MIN); ...
print_status_to_stdout: bool, ) { unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) }
random_line_split
manual_map.rs
scrutinee, then_pat, then_body, else_pat, else_body) = match IfLetOrMatch::parse(cx, expr) { Some(IfLetOrMatch::IfLet(scrutinee, pat, body, Some(r#else))) => (scrutinee, pat, body, None, r#else), Some(IfLetOrMatch::Match( scrutinee, [arm1 @ Arm { guard: None, .. }...
{ match pat.kind { PatKind::Wild => Some(OptionPat::Wild), PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt), PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None), PatKind::TupleStruct(ref qpath, [pattern], _) ...
identifier_body
manual_map.rs
/// /// ### Example /// ```rust /// match Some(0) { /// Some(x) => Some(x + 1), /// None => None, /// }; /// ``` /// Use instead: /// ```rust /// Some(0).map(|x| x + 1); /// ``` #[clippy::version = "1.52.0"] pub MANUAL_MAP, style, "reimplementation of...
f
identifier_name
manual_map.rs
use rustc_hir::{ def::Res, Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{sym, SyntaxConte...
}; use rustc_ast::util::parser::PREC_POSTFIX; use rustc_errors::Applicability; use rustc_hir::LangItem::{OptionNone, OptionSome};
random_line_split
util.rs
!("error seeking to offset {} in input file {:?}", offset, path))?; } let r = BufReader::new(f); if let FileRange::Range {len, ..} = range { Ok(Box::new(r.take(len as u64))) } else { Ok(Box::new(r)) } } /// /// Execute a command, pipe the contents of a file to stdin, return the outp...
{ copy_path(path, &to, chown_to) .map_err(context!("failed to copy {:?} to {:?}", path, to))?; }
conditional_block
util.rs
let Some(c) = s.chars().next() { return is_ascii(c) && c.is_alphabetic() } false } fn search_path(filename: &str) -> Result<PathBuf> { let path_var = env::var("PATH").unwrap_or("".into()); for mut path in env::split_paths(&path_var) { path.push(filename); if path.exists() { ...
<P: AsRef<Path>>(path: P) -> Result<()> { let path = path.as_ref(); cmd!("/usr/bin/xz", "-d {}", path.display()) .map_err(context!("failed to decompress {:?}", path)) } pub fn mount<P: AsRef<Path>>(source: impl AsRef<str>, target: P, options: Option<&str>) -> Result<()> { let source = source.as_ref...
xz_decompress
identifier_name
util.rs
) -> Result<String> { let path = path.as_ref(); let output = cmd_with_output!("/usr/bin/sha256sum", "{}", path.display()) .map_err(context!("failed to calculate sha256 on {:?}", path))?; let v: Vec<&str> = output.split_whitespace().collect(); Ok(v[0].trim().to_owned()) } #[derive(Copy,Clone)] ...
{ if to.exists() { bail!("destination path {} already exists which is not expected", to.display()); } let meta = from.metadata() .map_err(context!("failed to read metadata from source file {:?}", from))?; if from.is_dir() { util::create_dir(to)?; } else { util::copy...
identifier_body
util.rs
is_ascii(c) && (c.is_alphanumeric() || c == '-') } fn is_ascii(c: char) -> bool { c as u32 <= 0x7F } pub fn is_first_char_alphabetic(s: &str) -> bool { if let Some(c) = s.chars().next() { return is_ascii(c) && c.is_alphabetic() } false } fn search_path(filename: &str) -> Result<PathBuf> {...
fn is_alphanum_or_dash(c: char) -> bool {
random_line_split
train_test_function.py
# 每隔valid_interval个iterations就在validation set上测试一遍 max_iter, # 最大迭代次数 500k save_interval, # 保存模型的间隔iterations log_path, # 模型保存的路径 num_runner_threads, # 训练向队列塞入数据的线程数量 load_path=None): # 之前训练好的模型所在的路径 tf.reset_default_graph() # train和validation中的runner ...
summary = AverageSummary(accuracy, name='accuracy', num_iterations=float(ds_size) / float(batch_size)) increment_op = tf.group(loss_summary.increment_op, accuracy_summary.increment_op) global_step = tf.get_variable(name='global_step', shape=[], dtype=tf.int32, initializer=tf.c...
acy_
identifier_name
train_test_function.py
', num_iterations=train_interval) train_accuracy_s = AverageSummary(accuracy, name='train_accuracy', num_iterations=train_interval) valid_loss_s = AverageSummary(loss, name='valid_loss', num_iterations=float(valid_ds_size) / float(valid_batch_size)) valid_a...
TFCounter, TCounter, FTCounter, FCounter, TCounter, FCounter, (TTCounter + FFCounter) * 1.0 / step_cnt)) print('\nTOTAL RESULT: ') print('TT: %d/%d, FF: %d/%d, TF: %d/%d, FT: %d/%d || PosCount: %d,...
conditional_block
train_test_function.py
# 每隔valid_interval个iterations就在validation set上测试一遍 max_iter, # 最大迭代次数 500k save_interval, # 保存模型的间隔iterations log_path, # 模型保存的路径 num_runner_threads, # 训练向队列塞入数据的线程数量 load_path=None): # 之前训练好的模型所在的路径 tf.reset_default_graph() # train和validation中的runner ...
for j in range(0, valid_ds_size, valid_batch_size): sess.run([increment_valid]) print('validation cnt: %d || iterations: %d || validation accuracy: %d' % ( valid_cnt, i, sess.run(valid_accuracy_s.mean_variable))) va...
if i % valid_interval == 0: sess.run(disable_training_op)
random_line_split
train_test_function.py
_op = tf.assign(is_training, False) enable_training_op = tf.assign(is_training, True) else: batch_size = tf.get_variable(name='batch_size', dtype=tf.int32, collections=[tf.GraphKeys.LOCAL_VARIABLES], initializer=train_batch_si...
= tf.train.latest_checkpoint(weight_path) saver.restore(sess, model_file) runner.start_threads(sess, num_threads=1) for step in range(0, data_size, batch_size): # 拿出来的图像顺序就是cover, stego, cover, stego 这样的顺序 step_cnt += 1 model_label = sess.run(tf.argmax(model_...
identifier_body
lib.rs
let d = apply_limit(self.d_limit, d_unbounded); // Calculate the final output by adding together the PID terms, then // apply the final defined output limit let output = p + self.integral_term + d; let output = apply_limit(self.output_limit, output); // Return the indiv...
fn signed_integers_zeros() { let mut pid_i8 = Pid::new(10i8, 100); pid_i8.p(0, 100).i(0, 100).d(0, 100);
random_line_split
lib.rs
0, 100.0).i(4.5, 100.0).d(0.25, 100.0); /// /// // Get first output /// let full_output = full_controller.next_control_output(400.0); /// ``` /// /// This [`next_control_output`](Self::next_control_output) method is what's used to input new values into the controller to tell it what the current state of the system is. ...
(&mut self, setpoint: impl Into<T>) -> &mut Self { self.setpoint = setpoint.into(); self } /// Given a new measurement, calculates the next [control output](ControlOutput). /// /// # Panics /// /// - If a setpoint has not been set via `update_setpoint()`. pub fn next_control...
setpoint
identifier_name
cpu.py
-tile', False), default=16) # CIRE o['min-storage'] = oo.pop('min-storage', False) o['cire-rotate'] = oo.pop('cire-rotate', False) o['cire-maxpar'] = oo.pop('cire-maxpar', False) o['cire-ftemps'] = oo.pop('cire-ftemps', False) o['cire-mingain'] = oo.pop('cire-mingain', c...
_Target = OmpTarget
identifier_body
cpu.py
'Cpu64AdvOmpOperator', 'Cpu64FsgCOperator', 'Cpu64FsgOmpOperator', 'Cpu64CustomOperator'] class Cpu64OperatorMixin(object): @classmethod def _normalize_kwargs(cls, **kwargs): o = {} oo = kwargs['options'] # Execution modes o['openmp'] = oo.pop('openmp') ...
return { 'buffering': lambda i: buffering(i, callback, sregistry, options), 'blocking': lambda i: blocking(i, sregistry, options), 'factorize': factorize, 'fission': fission, 'fuse': lambda i: fuse(i, options=options), 'lift': lambda i: L...
return None
conditional_block
cpu.py
False), default=16) # CIRE o['min-storage'] = oo.pop('min-storage', False) o['cire-rotate'] = oo.pop('cire-rotate', False) o['cire-maxpar'] = oo.pop('cire-maxpar', False) o['cire-ftemps'] = oo.pop('cire-ftemps', False) o['cire-mingain'] = oo.pop('cire-mingain', cls.CIRE...
class Cpu64AdvOmpOperator(Cpu64AdvOperator): _Target = OmpTarget
random_line_split
cpu.py
'Cpu64AdvOmpOperator', 'Cpu64FsgCOperator', 'Cpu64FsgOmpOperator', 'Cpu64CustomOperator'] class Cpu64OperatorMixin(object): @classmethod def _normalize_kwargs(cls, **kwargs): o = {} oo = kwargs['options'] # Execution modes o['openmp'] = oo.pop('openmp') ...
(f): if f.is_TimeFunction and f.save is not None: return f.time_dim else: return None return { 'buffering': lambda i: buffering(i, callback, sregistry, options), 'blocking': lambda i: blocking(i, sregistry, options), 'f...
callback
identifier_name