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
full-site.js
$choicesModal.find('.modal-footer').html(""); var $firstButton; for (var i in buttons) { var btn = buttons[i]; var attrsString = ""; for (var key in btn.attrs) { var value = btn.attrs[key]; attrsString += key + '="' + value + '" '; } var $button ...
} } function showAuthError(error) { if (++failCount >= 3 || error.indexOf("Captcha") != -1) { location.href = loginUrl; } else { showNotification('error',error); // $('.dev-login-li').find('.alert').remove(); // $('.dev-login-li').prepend('<div class="alert alert-danger remov...
{ $('.dev-user-profile').html(""); // $('[type="password"]').val(""); $('.dev-anon-container').removeClass('hide'); $('.dev-login-in').addClass('hide'); $('#dev-material-create').addClass('hide'); $('#dev-backend-control').addClass('hide'); $('#dev-comics-create')....
conditional_block
embeddings.rs
a> PartialOrd for WordSimilarity<'a> { fn partial_cmp(&self, other: &WordSimilarity) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> Eq for WordSimilarity<'a> {} impl<'a> PartialEq for WordSimilarity<'a> { fn eq(&self, other: &WordSimilarity) -> bool { self.cmp(other) == Ordering:...
self.words.push(word.clone()); self.embeddings.push(embedding); Ok(()) } } /// Word embeddings. /// /// This data structure stores word embeddings (also known as *word vectors*) /// and provides some useful methods on the embeddings, such as similarity /// and analogy queries. pub struct E...
Entry::Vacant(vacant) => vacant.insert(self.words.len()), Entry::Occupied(_) => bail!(BuilderError::DuplicateWord { word: word }), };
random_line_split
embeddings.rs
> PartialOrd for WordSimilarity<'a> { fn partial_cmp(&self, other: &WordSimilarity) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> Eq for WordSimilarity<'a> {} impl<'a> PartialEq for WordSimilarity<'a> { fn eq(&self, other: &WordSimilarity) -> bool { self.cmp(other) == Ordering::...
/// Get an iterator over pairs of words and the corresponding embeddings. pub fn iter(&self) -> Iter { Iter { embeddings: self, inner: self.words.iter().enumerate(), } } /// Normalize the embeddings using their L2 (euclidean) norms. /// /// **Note:** wh...
{ &self.indices }
identifier_body
embeddings.rs
} } impl<'a> PartialOrd for WordSimilarity<'a> { fn partial_cmp(&self, other: &WordSimilarity) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> Eq for WordSimilarity<'a> {} impl<'a> PartialEq for WordSimilarity<'a> { fn eq(&self, other: &WordSimilarity) -> bool { self.cmp(oth...
{ self.word.cmp(other.word) }
conditional_block
embeddings.rs
> PartialOrd for WordSimilarity<'a> { fn partial_cmp(&self, other: &WordSimilarity) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> Eq for WordSimilarity<'a> {} impl<'a> PartialEq for WordSimilarity<'a> { fn eq(&self, other: &WordSimilarity) -> bool { self.cmp(other) == Ordering::...
{ #[fail( display = "invalid embedding shape, expected: {}, got: {}", expected_len, len )] InvalidEmbeddingLength { expected_len: usize, len: usize }, #[fail(display = "word not unique: {}", word)] DuplicateWord { word: String }, } /// Builder for word embedding matrices. /// /// T...
BuilderError
identifier_name
utils.rs
Name) -> (JsWord, Span) { match name { ast::ModuleExportName::Ident(id) => (id.sym.clone(), id.span), ast::ModuleExportName::Str(s) => (s.value.clone(), s.span), } } /// Properties like `ExportNamedSpecifier::orig` have to be an Ident if `src` is `None` pub fn match_export_name_ident(name: &ast::ModuleExpo...
"https://parceljs.org/features/scope-hoisting/#dynamic-imports" ),
random_line_split
utils.rs
&& &id.sym == idents.pop().unwrap() && !decls.contains(&id!(id)); } _ => return false, } } false } pub fn
(specifier: swc_core::ecma::atoms::JsWord) -> ast::CallExpr { let mut normalized_specifier = specifier; if normalized_specifier.starts_with("node:") { normalized_specifier = normalized_specifier.replace("node:", "").into(); } ast::CallExpr { callee: ast::Callee::Expr(Box::new(ast::Expr::Ident(ast::Iden...
create_require
identifier_name
utils.rs
} MemberProp::Ident(Ident { ref sym, .. }) => sym, _ => return false, }; if prop != expected { return false; } match &*member.obj { Expr::Member(m) => member = m, Expr::Ident(id) => { return idents.len() == 1 && &id.sym == idents.pop().unwrap() && !decls.co...
{ return false; }
conditional_block
inotify_linux_2.go
of moves, etc. import ( "fmt" "os" "path/filepath" "strings" "sync" "sync/atomic" "syscall" "time" "unsafe" "github.com/ugorji/go-common/errorutil" "github.com/ugorji/go-common/logging" ) var log = logging.PkgLogger() var ClosedErr = errorutil.String("<watcher closed>") // Use select, so read doesn't b...
} if x&syscall.IN_DELETE_SELF != 0 { s = append(s, "IN_DELETE_SELF") } if x&syscall.IN_MOVE_SELF != 0 { s = append(s, "IN_MOVE_SELF") } return fmt.Sprintf("WatchEvent: Path: %s, Name: %s, Wd: %v, Cookie: %v, Mask: %b, %v", e.Path, e.Name, e.Wd, e.Cookie, e.Mask, s) } // Watcher implements a watch service....
{ s := make([]string, 0, 4) x := e.Mask if x&syscall.IN_ISDIR != 0 { s = append(s, "IN_ISDIR") } if x&syscall.IN_CREATE != 0 { s = append(s, "IN_CREATE") } if x&syscall.IN_CLOSE_WRITE != 0 { s = append(s, "IN_CLOSE_WRITE") } if x&syscall.IN_MOVED_TO != 0 { s = append(s, "IN_MOVED_TO") } if x&syscall....
identifier_body
inotify_linux_2.go
handling of moves, etc. import ( "fmt" "os" "path/filepath" "strings" "sync" "sync/atomic" "syscall" "time" "unsafe" "github.com/ugorji/go-common/errorutil" "github.com/ugorji/go-common/logging" ) var log = logging.PkgLogger() var ClosedErr = errorutil.String("<watcher closed>") // Use select, so read ...
const useNonBlock = true type WatchEvent struct { syscall.InotifyEvent Path string Name string } func (e *WatchEvent) String() string { s := make([]string, 0, 4) x := e.Mask if x&syscall.IN_ISDIR != 0 { s = append(s, "IN_ISDIR") } if x&syscall.IN_CREATE != 0 { s = append(s, "IN_CREATE") } if x&syscall.I...
const useSelect = true // Use non-block, so we don't block on read.
random_line_split
inotify_linux_2.go
of moves, etc. import ( "fmt" "os" "path/filepath" "strings" "sync" "sync/atomic" "syscall" "time" "unsafe" "github.com/ugorji/go-common/errorutil" "github.com/ugorji/go-common/logging" ) var log = logging.PkgLogger() var ClosedErr = errorutil.String("<watcher closed>") // Use select, so read doesn't b...
(fpath string, flags uint32) error { if atomic.LoadUint32(&w.closed) != 0 { return ClosedErr } w.mu.Lock() defer w.mu.Unlock() return w.add(fpath, flags) } func (w *Watcher) add(fpath string, flags uint32) error { if flags == 0 { flags = // delete: false syscall.IN_CREATE | syscall.IN_CLOSE_WRITE |...
Add
identifier_name
inotify_linux_2.go
.Duration, fn func([]*WatchEvent), ) (w *Watcher, err error) { fd, err := syscall.InotifyInit() if err != nil { return } if fd == -1 { err = os.NewSyscallError("inotify_init", err) return } if useNonBlock { syscall.SetNonblock(fd, true) } w = &Watcher{ fd: fd, fn: fn, ev: m...
{ bs := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent])) wev.Name = strings.TrimRight(string(bs[0:raw.Len]), "\000") }
conditional_block
utils.go
.Logf("Found agent metadata: %+v", localMetadata) return nil } func (agent *TestAgent) Cleanup() { agent.StopAgent() if agent.t.Failed() { agent.t.Logf("Preserving test dir for failed test %s", agent.TestDir) } else { agent.t.Logf("Removing test dir for passed test %s", agent.TestDir) os.RemoveAll(agent.Test...
WaitRunning
identifier_name
utils.go
(registerRequest) if err != nil { return "", err } return fmt.Sprintf("%s:%d", *registered.TaskDefinition.Family, *registered.TaskDefinition.Revision), nil } type TestAgent struct { Image string DockerID string IntrospectionURL string Version string ContainerInstan...
} if agent.Version == "" { agent.Version = "UNKNOWN" } agent.t.Logf("Found agent metadata: %+v", localMetadata) return nil } func (agent *TestAgent) Cleanup() { agent.StopAgent() if agent.t.Failed() { agent.t.Logf("Preserving test dir for failed test %s", agent.TestDir) } else { agent.t.Logf("Removing t...
{ agent.Version = string(versionNumberStr[1]) }
conditional_block
utils.go
(registerRequest) if err != nil { return "", err } return fmt.Sprintf("%s:%d", *registered.TaskDefinition.Family, *registered.TaskDefinition.Revision), nil } type TestAgent struct { Image string DockerID string IntrospectionURL string Version string ContainerInstan...
func (agent *TestAgent) StartTaskWithOverrides(t *testing.T, task string, overrides []*ecs.ContainerOverride) (*TestTask, error) { td, err := GetTaskDefinition(task) if err != nil { return nil, err } t.Logf("Task definition: %s", td) resp, err := ECS.StartTask(&ecs.StartTaskInput{ Cluster: &agent...
{ tasks, err := agent.StartMultipleTasks(t, task, 1) if err != nil { return nil, err } return tasks[0], nil }
identifier_body
utils.go
= dockerClient _, err = dockerClient.InspectImage(agentImage) if err != nil { err = dockerClient.PullImage(docker.PullImageOptions{Repository: agentImage}, docker.AuthConfiguration{}) if err != nil { t.Fatal("Could not launch agent", err) } } tmpdirOverride := os.Getenv("ECS_FTEST_TMP") agentTempdir, ...
err = json.Unmarshal(*bodyData, &taskResp) if err != nil { return "", err }
random_line_split
script.js
{ if (x % 2 === 1) { myList.removeChild(el); } }); }); // 4 zadanie const button = document.createElement('button'); button.innerText = 'Click to remove'; button.addEventListener('click', (e) => { e.target.remove(); }); document.body.appendChild(button); // 5 za...
lists.forEach((ul, i) => { if (ul.childElementCount <= 1) { buttons[i].disabled = true; } else { buttons[i].disabled = false; } }) } lists.forEach((ul, i) => { buttons[i].innerText = 'MOVE'; buttons[i].addEventListener('click', () => { ...
ButtonDisabled() {
identifier_name
script.js
1: 'to jest div1', span1: 'to jest span1', div2: { div3: 'to jest div3(2)', }, span2: 'to jest span2' } const r00t = document.getElementById('root'); const firstDiv = document.createElement('div'); firstDiv.innerText = myNewObjStr.div1; const firstSpan = document.createElement('s...
ManyLetters[i] = stringArr[i].length; } return h
conditional_block
script.js
{ if (x % 2 === 1) { myList.removeChild(el); } }); }); // 4 zadanie const button = document.createElement('button'); button.innerText = 'Click to remove'; button.addEventListener('click', (e) => { e.target.remove(); }); document.body.appendChild(button); // 5 za...
function moreFields(){ nameTab.push(yourName.value); lastnameTab.push(lastname.value); ageTab.push(age.value); kidsTab.push(howManyKids.value); yourName.value = ''; lastname.value = ''; age.value = ''; howManyKids.value = ''; } document.querySelector('#more').addEventListen...
var kidsTab = [];
random_line_split
script.js
if (x % 2 === 1) { myList.removeChild(el); } }); }); // 4 zadanie const button = document.createElement('button'); button.innerText = 'Click to remove'; button.addEventListener('click', (e) => { e.target.remove(); }); document.body.appendChild(button); // 5 zadani...
nt.querySelector('#more').addEventListener('click', moreFields); function createTable(){ nameTab.push(yourName.value); lastnameTab.push(lastname.value); ageTab.push(age.value); kidsTab.push(howManyKids.value); yourName.value = ''; lastname.value = ''; age.value = ''; howManyKi...
ameTab.push(yourName.value); lastnameTab.push(lastname.value); ageTab.push(age.value); kidsTab.push(howManyKids.value); yourName.value = ''; lastname.value = ''; age.value = ''; howManyKids.value = ''; } docume
identifier_body
main.go
hub.Run() } func Start() { go consume() } func consume() { for { select { case msg, more := <-consumer.Messages(): if more { fmt.Printf("kafka consumer msg: (topic:%s) (partition:%d) (offset:%d) (%s): (%s)\n", msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value) loghub.Input() <- msg // cons...
fmt.Printf("GetLog
random_line_split
main.go
.Run() } func Start() { go consume() } func
() { for { select { case msg, more := <-consumer.Messages(): if more { fmt.Printf("kafka consumer msg: (topic:%s) (partition:%d) (offset:%d) (%s): (%s)\n", msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value) loghub.Input() <- msg // consumer.MarkOffset(msg, "completed") // mark message as proc...
consume
identifier_name
main.go
.Run() } func Start() { go consume() } func consume() { for { select { case msg, more := <-consumer.Messages(): if more { fmt.Printf("kafka consumer msg: (topic:%s) (partition:%d) (offset:%d) (%s): (%s)\n", msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value) loghub.Input() <- msg // consume...
func main() { signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt) Start() select { case s := <-signals: Stop(s) } } type Config struct { Name string LogProject struct { Name string Endpoint string AccessKeyID string AccessKeySecret string } Messa...
{ fmt.Println("Recived kafka consumer stop signal...") sig <- s fmt.Println("kafka consumer stopped!!!") }
identifier_body
main.go
hub.Run() } func Start() { go consume() } func consume() { for { select { case msg, more := <-consumer.Messages(): if more { fmt.Printf("kafka consumer msg: (topic:%s) (partition:%d) (offset:%d) (%s): (%s)\n", msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value) loghub.Input() <- msg // cons...
.dispatch() } func (l *Loghub) Input() chan<- *sarama.ConsumerMessage { return l.messages } // dispatchToTopic func (l *Loghub) dispatchToTopic(logstoreName string) { // TODO: 处理消息, 分配到不同的topic channelBuffer := l.getLogstoreLogsBufferChannel(logstoreName) for { select { case log := <-channelBuffer: l.mlogs...
:= l.getLogstore(lsn) if err != nil { fmt.Printf("Loghub Start failed (logstoreName=%s). err: %v\n", lsn, err) panic(err) } // 分配到topic go l.dispatchToTopic(lsn) for _, tp := range l.topics { go l.processTopicMsg(lsn, tp) } } // 分配消息 go l
conditional_block
projectstate.rs
the project. pub public_keys: HashMap<String, bool>, /// The project's slug if available. pub slug: Option<String>, /// The project's current config pub config: ProjectConfig, /// The project state's revision id. pub rev: Option<Uuid>, } /// A helper enum indicating the public key state. #...
/// Returns the time of the last config fetch. pub fn last_config_fetch(&self) -> Option<DateTime<Utc>> { self.current_snapshot .read() .as_ref() .map(|x| x.last_fetch.clone()) } /// Returns the time of the last config change. pub fn last_config_change(...
{ *self.last_event.read() }
identifier_body
projectstate.rs
{ /// URLs that are permitted for cross original JavaScript requests. pub allowed_domains: Vec<String>, } /// The project state snapshot represents a known server state of /// a project. /// /// This is generally used by an indirection of `ProjectState` which /// manages a view over it which supports concurre...
ProjectConfig
identifier_name
projectstate.rs
in the project. pub public_keys: HashMap<String, bool>, /// The project's slug if available. pub slug: Option<String>, /// The project's current config pub config: ProjectConfig, /// The project state's revision id. pub rev: Option<Uuid>, } /// A helper enum indicating the public key state...
.and_then(|x| x.last_change.clone()) } /// Requests an update to the project config to be fetched. pub fn request_updated_project_config(&self) { if self.requested_new_snapshot .compare_and_swap(false, true, Ordering::Relaxed) { return; } ...
random_line_split
exportAnswersToXLSX.py
Id ): # Delete the WorkloadId try: response=waclient.delete_workload( WorkloadId=workloadId ) except botocore.exceptions.ParamValidationError as e: logger.error("ERROR - Parameter validation error: %s" % e) except botocore.exceptions.ClientError as e: logger....
( waclient, workloadId, lensAlias ): answers = [] # Due to a bug in some lenses, I have to iterate over each pillar in order to # retrieve the correct results. for pillar in PILLAR_PARSE_MAP: logger.debug("Grabbing answers for %s %s" % (lensAlias, pillar)) # Find a quest...
findAllQuestionId
identifier_name
exportAnswersToXLSX.py
and parse for the HTML content if qImprovementPlanUrl: jmesquery = "[?QuestionId=='"+answers['QuestionId']+"'].Choices[].ChoiceId" choiceList = jmespath.search(jmesquery, allQuestionsForLens) ipList = getImprovementPlanItems(WACLIENT,workloadId,lens,answers['...
main()
conditional_block
exportAnswersToXLSX.py
:",json.dumps(response['Workload'], cls=DateTimeEncoder)) workload = response['Workload'] # print("WorkloadId",workloadId) return workload def listLens( waclient ): # List all lenses currently available try: response=waclient.list_lenses() except botocore.exceptions.ParamValidat...
'bg_color': '#E0EBF6', 'align': 'top',
random_line_split
exportAnswersToXLSX.py
logger.error("ERROR - Parameter validation error: %s" % e) except botocore.exceptions.ClientError as e: logger.error("ERROR - Unexpected error: %s" % e) workloadId = response['WorkloadId'] workloadARN = response['WorkloadArn'] return workloadId, workloadARN def FindWorkload( wacli...
try: response=waclient.create_workload( WorkloadName=workloadName, Description=description, ReviewOwner=reviewOwner, Environment=environment, AwsRegions=awsRegions, Lenses=lenses, NonAwsRegions=nonAwsRegions, ArchitecturalDesign=architecturalDesign...
identifier_body
network_context.rs
String>>, semaphore: Arc<Semaphore>, } impl<T> RaceBatch<T> where T: Send + 'static, { pub fn new(max_concurrent_jobs: usize) -> Self { RaceBatch { tasks: JoinSet::new(), semaphore: Arc::new(Semaphore::new(max_concurrent_jobs)), } } pub fn add(&mut self, fu...
.await .is_ok(); match self.db.get_cbor(&content) { Ok(Some(b)) => Ok(b), Ok(None) => Err(format!( "Not found in db, bitswap. success: {success} cid, {content:?}" )), Err(e) => Err(format!( "Error retrieving from db...
{ // Check if what we are fetching over Bitswap already exists in the // database. If it does, return it, else fetch over the network. if let Some(b) = self.db.get_cbor(&content).map_err(|e| e.to_string())? { return Ok(b); } let (tx, rx) = flume::bounded(1); ...
identifier_body
network_context.rs
String>>, semaphore: Arc<Semaphore>, } impl<T> RaceBatch<T> where T: Send + 'static, { pub fn new(max_concurrent_jobs: usize) -> Self { RaceBatch { tasks: JoinSet::new(), semaphore: Arc::new(Semaphore::new(max_concurrent_jobs)), } } pub fn add(&mut self, fu...
( network_send: flume::Sender<NetworkMessage>, peer_manager: Arc<PeerManager>, db: Arc<DB>, ) -> Self { Self { network_send, peer_manager, db, } } /// Returns a reference to the peer manager of the network context. pub fn peer_...
new
identifier_name
network_context.rs
String>>, semaphore: Arc<Semaphore>, } impl<T> RaceBatch<T> where T: Send + 'static, { pub fn new(max_concurrent_jobs: usize) -> Self { RaceBatch { tasks: JoinSet::new(), semaphore: Arc::new(Semaphore::new(max_concurrent_jobs)), } } pub fn add(&mut self, fu...
} } Err(e) => { network_failures.fetch_add(1, Ordering::Relaxed); debug!("Failed chain_exchange request to peer {peer_id:?}: {e}"); Err...
{ lookup_failures.fetch_add(1, Ordering::Relaxed); debug!("Failed chain_exchange response: {e}"); Err(e) }
conditional_block
network_context.rs
use crate::blocks::{FullTipset, Tipset, TipsetKeys}; use crate::libp2p::{ chain_exchange::{ ChainExchangeRequest, ChainExchangeResponse, CompactedMessages, TipsetBundle, HEADERS, MESSAGES, }, hello::{HelloRequest, HelloResponse}, rpc::RequestResponseError, NetworkMessage, PeerId, Pee...
};
random_line_split
model.py
# images from 200 different birds. We will feed the images without applying # the provided bounding boxes from the dataset. The data will only be resized # and normalized. Keras ImageDataGenerator will be used for loading the dataset def load_dataset(aws_access, aws_secret, dataset_path, batch_size, image_shape): ...
(generated_images, epoch, batch_number): plt.figure(figsize=(8, 8), num=2) gs1 = gridspec.GridSpec(8, 8) gs1.update(wspace=0, hspace=0) for i in range(64): ax1 = plt.subplot(gs1[i]) ax1.set_aspect('equal') image = generated_images[i, :, :, :] image += 1 image *=...
save_generated_images
identifier_name
model.py
8 # images from 200 different birds. We will feed the images without applying # the provided bounding boxes from the dataset. The data will only be resized # and normalized. Keras ImageDataGenerator will be used for loading the dataset def load_dataset(aws_access, aws_secret, dataset_path, batch_size, image_shape): ...
# the adversarial models adversarial_loss = np.empty(shape=1) discriminator_loss = np.empty(shape=1) batches = np.empty(shape=1) # Allo plot updates inside for loop plt.ion() current_batch = 0 # Let's train the DCGAN for n epochs for epoch in range(epochs): print("Epoch "...
generator = construct_generator() discriminator = construct_discriminator(image_shape) gan = Sequential() # Only false for the adversarial model discriminator.trainable = False gan.add(generator) gan.add(discriminator) optimizer = Adam(lr=0.00015, beta_1=0.5) gan.compile(loss='binary_c...
identifier_body
model.py
# images from 200 different birds. We will feed the images without applying # the provided bounding boxes from the dataset. The data will only be resized # and normalized. Keras ImageDataGenerator will be used for loading the dataset def load_dataset(aws_access, aws_secret, dataset_path, batch_size, image_shape): ...
time_elapsed = time.time()
save_generated_images(generated_images, epoch, batch_number)
conditional_block
model.py
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import numpy as np from keras.models import Sequential from keras.layers import Conv2D, Conv2DTranspose, Reshape from keras.layers import Flatten, BatchNormalization, Dense, Activation from keras.layers.advanced_activations import LeakyReLU from ke...
import os import boto3 from zipfile import ZipFile
random_line_split
index.d.ts
// the literal value used for the link. If this property is omitted then text is generated from the field values of the document referred to by the link. } export interface IFngSchemaTypeFormOpts { /* The input type to be generated - which must be compatible with the Mongoose type. Common examples...
label: string; options?: any; ids?: any; hidden?: boolean; tab?: string; add? : string; ref? : any; link? : any; linktext?: string; linklabel?: boolean; form?: string; // the form that is linked to select2? : any; // deprecated schema?: IFormInstruc...
rows? : number;
random_line_split
world.py
scale**2) self.bounds = None # if no boundary, then None self.electrode_dict = {} self.rf_electrode_list = [] self.dc_electrode_list = [] def add_electrode(self, e, name, kind, volt): """ Add an electrode to the World. Name it with `name. If kind == 'rf', then add this electrode to the rf elect...
def compute_dc_potential_frequencies(self, r): ''' As always, this is valid only at the trapping position. Return frequency (not angular frequency) ''' H = self.compute_dc_hessian(r) hessdiag, eigvec = eigh(H) hessdiag /= self.__scale**2 # # hessdiag = nd.Hessdiag( self.compute_total...
''' This is only valid if xp, yp, zp is the trapping position. Return frequency (i.e. omega/(2*pi)) ''' hessdiag = nd.Hessdiag(self.compute_pseudopot,step=1e-6)(r)/(self.__scale**2) ''' Now d2Udx2 has units of J/m^2. Then w = sqrt(d2Udx2/(mass)) has units of angular frequency ''' return np.sqrt(qe*...
identifier_body
world.py
class World: ''' A General, Brand New World Units: (potential) energy: eV length: __scale frequency: Hz Axis convention in consistance with <class Electrode> z: axial * It doesn't matter whether z is parallel or vertical to the surface or not Attributes: __scale :: the typical length in meter. L...
from .SH import funcSHexp from .utils import quadru2hess, intersectBounds amu = 1.66054e-27
random_line_split
world.py
**2) self.bounds = None # if no boundary, then None self.electrode_dict = {} self.rf_electrode_list = [] self.dc_electrode_list = [] def
(self, e, name, kind, volt): """ Add an electrode to the World. Name it with `name. If kind == 'rf', then add this electrode to the rf electrode dict as well as to the general electrode dict """ e.volt = volt self.electrode_dict[name] = (kind, e) if kind=='dc': self.dc_electrode_list.append(...
add_electrode
identifier_name
world.py
, bounds=None): """ Search the RF null on a certain axial position xy0: initial guess onyz: whether restrict y=y0 or not bounds: array([[xmin, xmax],[ymin, ymax], ...]) shaped (2,2) or (3,2) """ if bounds is None: self.check_bound() if self.bounds is None: print("Cannot carry out RF null searc...
pos_ctrl_mults = [pos_ctrl_mults]
conditional_block
train.py
t in list(MetricType)]}") parser.add_argument("--dims", default=4, type=int, help="Dimensions for the model.") parser.add_argument("--train_bias", dest='train_bias', action='store_true', default=False, help="Whether to train scaling or not.") parser.add_argument("--use_hrh", default...
model.to(config.DEVICE) model = DistributedDataParallel(model, device_ids=None) if saved_data: model.load_state_dict(saved_data["model_state"]) return model def get_optimizer(model, args, saved_data=None): if args.optim == "sgd": optim = SGD(model.parameters(), lr=args.learning_r...
raise ValueError(f"Unrecognized model argument: {args.model}")
conditional_block
train.py
t in list(MetricType)]}") parser.add_argument("--dims", default=4, type=int, help="Dimensions for the model.") parser.add_argument("--train_bias", dest='train_bias', action='store_true', default=False, help="Whether to train scaling or not.") parser.add_argument("--use_hrh", default...
parser.add_argument("--max_grad_norm", default=50.0, type=float, help="Max gradient norm.") parser.add_argument("--batch_size", default=1000, type=int, help="Batch size.") parser.add_argument("--eval_batch_size", default=100, type=int, help="Eval batch size. Has impact only on memory") parser.add_argume...
parser.add_argument("--weight_decay", default=0.00, type=float, help="L2 Regularization.") parser.add_argument("--val_every", default=5, type=int, help="Runs validation every n epochs.") parser.add_argument("--patience", default=50, type=int, help="Epochs of patience for scheduler and early stop.")
random_line_split
train.py
t in list(MetricType)]}") parser.add_argument("--dims", default=4, type=int, help="Dimensions for the model.") parser.add_argument("--train_bias", dest='train_bias', action='store_true', default=False, help="Whether to train scaling or not.") parser.add_argument("--use_hrh", default...
def build_data_loader(split, batch_size, shuffle, args): """ :param split: torch.LongTensor b x 3 with triples (h, r, t) :param batch_size: int :param shuffle: bool :param args: :return: torch DataLoader set up with distributed sampler """ tensor_dataset = TensorDataset(split) sam...
patience = round(args.patience / args.val_every) factor = 1 / float(args.reduce_factor) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=patience, factor=factor, mode="max") if saved_data: scheduler.load_state_dict(saved_data["scheduler_state"]) return scheduler
identifier_body
train.py
(parser): # Data options parser.add_argument("--data", required=True, type=str, help="Name of data set folder") parser.add_argument("--run_id", required=True, type=str, help="Name of model/run to export") # Model parser.add_argument("--model", default="tgattnspd", type=str, help="Model type: tgspd, ...
config_parser
identifier_name
feffpath.py
def bytes2str(val): if isinstance(val, str): return val if isinstance(val, bytes): return str(val, 'utf-8') return str(val) def str2bytes(val): if isinstance(val, bytes): return val return bytes(val, 'utf-8') def with_phase_file(fcn):...
cdata = arr.ctypes.data_as(POINTER(arr.size*c_int)) setattr(args, attr, cdata) # double arrays self.rat = self.rat/BOHR for attr in ('evec', 'xivec', 'rat', 'ri', 'beta', 'eta', 'kfeff', 'real_phc', 'mag_feff', 'pha_feff', 'red_f...
class args: pass # strings / char*. Note fixed length to match Fortran args.phase_file = (self.phase_file + ' '*256)[:256] args.exch_label = str2bytes(' '*8) args.genfmt_version = str2bytes(' '*30) # integers, including booleans for attr in ('index', 'nleg', 'g...
identifier_body
feffpath.py
def bytes2str(val): if isinstance(val, str): return val if isinstance(val, bytes): return str(val, 'utf-8') return str(val) def str2bytes(val): if isinstance(val, bytes): return val return bytes(val, 'utf-8') def with_phase_file(fcn): ...
""" def __init__(self, phase_file=None): self.phase_file = phase_file self.clear() def clear(self): """reset all path data""" self.index = 1 self.degen = 1. self.nnnn_out = False self.json_out = False self.verbose = False self.i...
# calculate basic (unaltered) XAFS contributions path.calcuate_xafs()
random_line_split
feffpath.py
self.exch_label = "" self.rs = 0. self.vint = 0. self.xmu = 0. self.edge = 0. self.kf = 0. self.rnorman = 0. self.gamach = 0. self.nepts = FEFF_maxpts dargs = dict(dtype=np.float64, order='F') largs = dict(dtype=n...
print("# {:8s} = {:s} ".format(attr, getattr(path, attr)))
conditional_block
feffpath.py
def bytes2str(val): if isinstance(val, str): return val if isinstance(val, bytes): return str(val, 'utf-8') return str(val) def str2bytes(val): if isinstance(val, bytes): return val return bytes(val, 'utf-8') def with_phase_file(fcn): ...
(*args, **keywords): "needs phase_file" phase_file = keywords.get('phase_file', None) if phase_file is None: phase_file = getattr(args[0], 'phase_file', None) if phase_file is None: raise AttributeError(errmsg % fcn.__name__) else: seta...
wrapper
identifier_name
main.rs
10...12 } => println!("Found an id in another range"), MessageNum::Hello { id } => println!("Found some other id: {}", id), } } enum MessageNum { Hello { id: i32 }, } enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ...
random_line_split
main.rs
y: other.y, } } } fn do_trait() { let number_list = vec![34, 50, 25, 100, 65]; let result = get_gt(&number_list); println!("The largest number is {}", result); let char_list = vec!['y', 'm', 'a', 'q']; let result = get_gt(&char_list); println!("The largest char is {}", result); ...
self
identifier_name
main.rs
{ 1...5 => println!("one through five"), _ => println!("something else"), } let x = 'A'; match x { 'a'...'j' => println!("early ASCII letter"), 'k'...'z' => println!("late ASCII letter"), 'A'...'Z' => println!("UP ASCII letter"), _ => println!("something el...
e { width: 10, height: 40, }; let rect3 = Rectangle { width: 60, height: 45, }; println!("rect1 area: {}", rect1.area()); println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); println!("re...
identifier_body
loadtest_types.go
// components. type Server struct { // Name is a string that distinguishes this server from others in the test. // Since tests are currently limited to one server, setting this field is not // recommended. set this field. If no name is explicitly provided, the // operator will assign one. // +optional Name *stri...
// KubernetesError is the reason string when an issue occurs with Kubernetes // that is not known to be directly related to a load test. var KubernetesError = "KubernetesError"
random_line_split
loadtest_types.go
output into the /src/workspace directory for the // run container to access it. // +optional Build *Build `json:"build,omitempty"` // Run describes a list of run containers. The container for the test server is always // the first container on the list. Run []corev1.Container `json:"run"` } // Client defines a...
init
identifier_name
loadtest_types.go
it. // +optional Build *Build `json:"build,omitempty"` // Run describes a list of run containers. The container for the test server is always // the first container on the list. Run []corev1.Container `json:"run"` } // Client defines a component that sends traffic to a server component. type Client struct { //...
{ SchemeBuilder.Register(&LoadTest{}, &LoadTestList{}) }
identifier_body
tgsw.rs
let tlwe_params = params.tlwe_params.clone(); let tlwe_key = TLweKey::generate(&tlwe_params); Self { params: params.clone(), // tlwe_params, tlwe_key, } } pub(crate) fn encrypt(&self, result: &mut TGswSample, message: i32, alpha: f64) { result.encrypt_zero(alpha, self); resul...
{ let n = params.tlwe_params.n; let l = params.l; let bg_bit = params.bg_bit; let mask_mod = params.mask_mod; let half_bg = params.half_bg; let offset = params.offset; // First, add offset to everyone let buf: Vec<i32> = sample .coefs .iter() .map(|c| c.wrapping_add(offset as i32)) .col...
identifier_body
tgsw.rs
{ let new_a: Vec<TorusPolynomial> = js .a .iter() .map(|a: &TorusPolynomial| { let new_coefs = a .coefs .iter() .enumerate() .map(|(coef_idx, coef): (usize, &i32)| { ...
test_add_h
identifier_name
tgsw.rs
dec = new_dec; dec .iter() .flatten() .zip_eq(sample.all_sample.iter().flatten()) .for_each(|(d, a)| result.add_mul_r_(d, a, par)); result // for i in 0..dec.len() as usize { // println!("kpl: {}, k: {}, l: {}, i: {}", kpl, par.k, params.l, i); // // TODO: Figure out if this is supposed...
{ assert!(new_polynomial .coefs .iter() .zip_eq(old_polynomial.coefs.iter()) .all(|(a, b)| a == b)); }
conditional_block
tgsw.rs
allow(clippy::needless_range_loop)] for x in 0..inner { for y in 0..outer { std::mem::swap(&mut new_dec[x][y], &mut dec[y][x]); } } let dec = new_dec; dec .iter() .flatten() .zip_eq(sample.all_sample.iter().flatten()) .for_each(|(d, a)| result.add_mul_r_(d, a, par)); result ...
random_line_split
trie.rs
個までの値を登録できる /// 超えた場合はpanic /// /// # Arguments /// /// * `key` - 追加するキー /// * `value` - キーに対応する値 pub fn set(&mut self, key: &str, value: T) { let mut node = &mut self.root; for &k in key.as_bytes() { match node.nexts.binary_search_by(|probe| probe.key.cmp(&k)) ...
while !stack.is_empty() { let (curr_idx, mut node) = stack.pop().unwrap(); bit_cache.update_start(); // base値を探索・セット if !node.values.is_empty() { // valuesが存在する場合はkey=255のノードとして計算する node.nexts.push(Node { key: u8::max_value(), valu...
let mut stack: Vec<(usize, Node<T>)> = Vec::with_capacity(self.len); if !self.root.nexts.is_empty() { stack.push((1, self.root)); }
random_line_split
trie.rs
までの値を登録できる /// 超えた場合はpanic /// /// # Arguments /// /// * `key` - 追加するキー /// * `value` - キーに対応する値 pub fn set(&mut self, key: &str, value: T) { let mut node = &mut self.root; for &k in key.as_bytes() { match node.nexts.binary_search_by(|probe| probe.key.cmp(&k)) {...
/// /// # Arguments /// /// * `len` - ダブル配列の初期サイズ pub fn to_double_array(self) -> Result<DoubleArray<T>, std::io::Err or> { let max_key = u8::max_value() as usize + 1; // keyが取りうる値のパターン let mut len = if max_key > (4 * self.len) { max_key } else { 4 * self.len }; let mut ...
> { return None; } } } if node.values.is_empty() { None } else { Some(&node.values) } } /// トライ木をダブル配列に変換する /// /// # Panics /// dataをバイト列に変換できなかった場合にpanicする。 /// /// # Errors ///
identifier_body
trie.rs
usize) != 0 { // 空じゃなかった場合はnew_baseを探すとこからやり直し offset += 1; continue 'outer; } } return new_base; } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_trie_1() { let mut trie: T...
identifier_name
trie.rs
個までの値を登録できる /// 超えた場合はpanic /// /// # Arguments /// /// * `key` - 追加するキー /// * `value` - キーに対応する値 pub fn set(&mut self, key: &str, value: T) { let mut node = &mut self.root; for &k in key.as_bytes() { match node.nexts.binary_search_by(|probe| probe.key.cmp(&k)) ...
o::Error> { let max_key = u8::max_value() as usize + 1; // keyが取りうる値のパターン let mut len = if max_key > (4 * self.len) { max_key } else { 4 * self.len }; let mut base_arr: Vec<u32> = vec![0; len]; let mut check_arr: Vec<u32> = vec![0; len]; let mut data_arr: Vec<u8> = Vec::w...
ray(self) -> Result<DoubleArray<T>, std::i
conditional_block
doctype.py
for t in list(set(table_fields)): # Get child doc and its fields table_doclist = webnotes.model.doc.get('DocType', t, 1) table_doclist += self.get_custom_fields(t) doclist += table_doclist self.apply_property_setters(doclist) if form: self.load_select_options(doclist) self.add_code(docl...
for r in res: # Cheat! Mask Custom Field as DocField custom_field = webnotes.model.doc.Document(fielddata=r) self.mask_custom_field(custom_field, doc_type) custom_doclist.append(custom_field) return custom_doclist def mask_custom_field(self, custom_field, doc_type): """ Masks doctype and parent ...
WHERE dt = %s AND docstatus < 2""", doc_type, as_dict=1)
random_line_split
doctype.py
for t in list(set(table_fields)): # Get child doc and its fields table_doclist = webnotes.model.doc.get('DocType', t, 1) table_doclist += self.get_custom_fields(t) doclist += table_doclist self.apply_property_setters(doclist) if form: self.load_select_options(doclist) self.add_code(docl...
docfields.insert(0, cur_field) except ValueError: pass if cur_field in temp_dict: prev_field = cur_field get_next_docfield = False if get_next_docfield: i += 1 if i>=len(docfields): break prev_field = docfields[i] keys, vals = temp_dict.keys(), temp_dict.values() if...
""" """ temp_dict = prev_field_dict.get(doc_type) if not temp_dict: return prev_field = 'None' in temp_dict and 'None' or docfields[0] i = 0 while temp_dict: get_next_docfield = True cur_field = temp_dict.get(prev_field) if cur_field and cur_field in docfields: try: del temp_dict[prev...
identifier_body
doctype.py
for t in list(set(table_fields)): # Get child doc and its fields table_doclist = webnotes.model.doc.get('DocType', t, 1) table_doclist += self.get_custom_fields(t) doclist += table_doclist self.apply_property_setters(doclist) if form: self.load_select_options(doclist) self.add_code(docl...
from webnotes.utils import cint prop_updates = [] for prop in doctype_property_dict.get(cstr(d.fieldname)): if prop.get('property')=='previous_field': continue if prop.get('property_type') == 'Check' or \ prop.get('value') in ['0', '1']: prop_updates.append([prop.get('property'), cint(prop.get(...
return
conditional_block
doctype.py
for t in list(set(table_fields)): # Get child doc and its fields table_doclist = webnotes.model.doc.get('DocType', t, 1) table_doclist += self.get_custom_fields(t) doclist += table_doclist self.apply_property_setters(doclist) if form: self.load_select_options(doclist) self.add_code(docl...
(self, doc_type): """ Gets a list of custom field docs masked as type DocField """ custom_doclist = [] res = webnotes.conn.sql("""SELECT * FROM `tabCustom Field` WHERE dt = %s AND docstatus < 2""", doc_type, as_dict=1) for r in res: # Cheat! Mask Custom Field as DocField custom_field = webnotes.mo...
get_custom_fields
identifier_name
MotionTrackingLK.py
(w, h, lx, ly): devx = lx * w/2 + w/2 devy = ly * h/2 + h/2 return int(devx), int(devy) def device_to_logical(w, h, devx, devy): lx = (devx - w/2)/(w/2) ly = (devy - h/2)/(h/2) return lx, ly def display_tracks(imgs, batch_tracks): imgs = np.copy(imgs) _,_,h,w,c = imgs.shape imgs_...
logical_to_device
identifier_name
MotionTrackingLK.py
= iterations super(MotionTrackingLK, self).__init__(**kwargs) def build(self, input_shape): # grab the dimensions of the image here so we can use them later. also will throw errors early for users self.seq_len = input_shape[1][1] self.h = input_shape[1][2] self.w = input_sh...
VxVy = tf.matmul(ATA_1, ATb) return VxVy def iterative_LK(self, sampler, frames, iterations): out = self.sample_ntracks_from_2frames(sampler, frames) first_frame = out[:, 0] factor = 1.0 VxVy = self.calc_velocity_2frames_ntracks_LK(first_frame, out[:, 1])*factor ...
ATb = tf.matmul(A, b, transpose_a=True)
random_line_split
MotionTrackingLK.py
_pixel_wh]), tf.reshape(y_t, [self.win_pixel_wh*self.win_pixel_wh]), ]) self.sobel_x = tf.constant([ [-1., 0., 1.], [-2., 0., 2.], [-1., 0., 1.], ], shape=[3, 3, 1, 1] ) self.sobel_y = tf.constant(...
sampler, sum_VxVy = self.iterative_LK(sampler, imgs[:, i:i+2], self.iterations) sum_VxVy = tf.reshape(sum_VxVy, [-1, self.num_tracks, 1, 2]) prev = tf.reshape(tot_VxVy[:, :, i], [-1, self.num_tracks, 1, 2]) tot_VxVy = tf.concat([tot_VxVy, sum_VxVy+prev], axis=2) i += 1 ...
identifier_body
MotionTrackingLK.py
imgs_with_tracks.append(img) return np.asfarray(imgs_with_tracks) class MotionTrackingLK(tf.keras.layers.Layer): def __init__(self, num_tracks, window_pixel_wh=21, sigma=2, iterations=5, **kwargs): self.sigma = sigma assert(num_tracks > 1) assert(window_pixel_wh >= 3) s...
for t_seq in range(1, len(track)): lx_p, ly_p = track[t_seq-1] x_p, y_p = logical_to_device(w, h, lx_p, ly_p) lx, ly = track[t_seq] x, y = logical_to_device(w, h, lx, ly) img = cv.arrowedLine(img, (x_p, y_p), (x, y), (255, 0, 0))
conditional_block
main.rs
::Jemalloc; const WORK_BOUND: usize = 4000; const MAX_COMPRESSED_BLOB_SIZE: i32 = 64 * 1024; const MAX_DECOMPRESSED_BLOB_SIZE: i32 = 32 * 1024 * 1024; #[derive(Debug)] struct
{ timestamp_min: i64, timestamp_max: i64, nodes: u64, ways: u64, relations: u64, lon_min: f64, lon_max: f64, lat_min: f64, lat_max: f64, } fn main() { let args: Vec<_> = std::env::args_os().collect(); let filename = &args[1]; let orig_handler = panic::take_hook(); ...
OsmStats
identifier_name
main.rs
::Jemalloc; const WORK_BOUND: usize = 4000; const MAX_COMPRESSED_BLOB_SIZE: i32 = 64 * 1024; const MAX_DECOMPRESSED_BLOB_SIZE: i32 = 32 * 1024 * 1024; #[derive(Debug)] struct OsmStats { timestamp_min: i64, timestamp_max: i64, nodes: u64, ways: u64, relations: u64, lon_min: f64, lon_max: f6...
let (sender, receiver) = bounded::<Blob>(WORK_BOUND); let (return_sender, return_received) = unbounded::<OsmStats>(); thread::scope(|s| { for _ in 0..thread_count { let cloned_receiver = receiver.clone(); let cloned_return_sender = return_sender.clone(); s.spawn(...
random_line_split
main.rs
Jemalloc; const WORK_BOUND: usize = 4000; const MAX_COMPRESSED_BLOB_SIZE: i32 = 64 * 1024; const MAX_DECOMPRESSED_BLOB_SIZE: i32 = 32 * 1024 * 1024; #[derive(Debug)] struct OsmStats { timestamp_min: i64, timestamp_max: i64, nodes: u64, ways: u64, relations: u64, lon_min: f64, lon_max: f64,...
received_messages += 1; } Ok(format!("{:#?}", osm_stats)) }) .unwrap() } fn handle_block(mut osm_stats: &mut OsmStats, blob: &Blob, buffer: &mut Vec<u8>) { let zlib_data_ref = blob.zlib_data.as_ref(); let tried_block = if blob.raw.is_some() { let bytes = blob.raw.as...
{ osm_stats.lon_min = worker_stats.lon_min }
conditional_block
main.rs
Jemalloc; const WORK_BOUND: usize = 4000; const MAX_COMPRESSED_BLOB_SIZE: i32 = 64 * 1024; const MAX_DECOMPRESSED_BLOB_SIZE: i32 = 32 * 1024 * 1024; #[derive(Debug)] struct OsmStats { timestamp_min: i64, timestamp_max: i64, nodes: u64, ways: u64, relations: u64, lon_min: f64, lon_max: f64,...
fn handle_latitude(osm_stats: &mut OsmStats, latitude: i64, primitive: &PrimitiveBlock) { let latitude_f =
{ let millisec_stamp = timestamp * (date_granularity as i64); if millisec_stamp < osm_stats.timestamp_min { osm_stats.timestamp_min = millisec_stamp } if millisec_stamp > osm_stats.timestamp_max { osm_stats.timestamp_max = millisec_stamp } }
identifier_body
provider.go
old state. oldState, err := plugin.UnmarshalProperties(req.GetProperties(), plugin.MarshalOptions{ Label: fmt.Sprintf("%s.olds", label), KeepUnknowns: true, SkipNulls: true, KeepSecrets: true, }) if err != nil { return nil, err } // Read the current state of the resource from the API. newState, err := p.cli...
{ result := p.getConfig("partnerName", "GOOGLE_PARTNER_NAME") if result != "" { return result } else { disablePartner := p.getConfig("disablePartnerName", "GOOGLE_DISABLE_PARTNER_NAME") if disablePartner == "true" { return "" } } return "Pulumi" }
identifier_body
provider.go
has := resp["statusMessage"]; has { err = errors.Errorf("operation failed with %q", statusMessage) } // Extract the resource response, if any. // A partial error could happen, so both response and error could be available. if response, has := resp["response"].(map[string]interface{}); has { return ...
Construct
identifier_name
provider.go
p.waitForResourceOpCompletion(res.BaseUrl, op) if err != nil { if resp == nil { return nil, errors.Wrapf(err, "waiting for completion") } // A partial failure may have occurred because we got an error and a response. // Try reading the resource state and return a partial error if there is some. id, idErr...
inputs, err := plugin.UnmarshalProperties(req.GetNews(), plugin.MarshalOptions{ Label: fmt.Sprintf("%s.properties", label), SkipNulls: true, }) if err != nil {
random_line_split
provider.go
if err = uncompressed.Close(); err != nil { return nil, errors.Wrap(err, "closing uncompress stream for metadata") } return &resourceMap, nil } // Configure configures the resource provider with "globals" that control its behavior. func (p *googleCloudProvider) Configure(ctx context.Context, req *rpc.ConfigureR...
{ return nil, errors.Wrap(err, "unmarshalling resource map") }
conditional_block
fetcher_default.go
_ Fetcher = new(FetcherDefault) type fetcherRegistry interface { x.RegistryLogger RuleRepository() Repository } type FetcherDefault struct { config configuration.Provider registry fetcherRegistry hc *http.Client mux *blob.URLMux cache map[string][]Rule cancelWatchers map[string]context...
// we force reading the files done, err := w.DispatchNow() if err != nil { f.registry.Logger().WithError(err).WithField("file", fp).Error("Unable to read file, ignoring it.") continue } go func() { <-done }() // we do not need to wait here, but we need to clear the channel } else { // keep w...
f.registry.Logger().WithError(err).WithField("file", fp).Error("Unable to watch file, ignoring it.") continue }
conditional_block
fetcher_default.go
_ Fetcher = new(FetcherDefault) type fetcherRegistry interface { x.RegistryLogger RuleRepository() Repository } type FetcherDefault struct { config configuration.Provider registry fetcherRegistry hc *http.Client mux *blob.URLMux cache map[string][]Rule cancelWatchers map[string]context...
if err := f.updateRulesFromCache(ctx); err != nil { f.registry.Logger().WithError(err).WithField("event_source", "local repo change").Error("Unable to update access rules.") } } } func (f *FetcherDefault) Watch(ctx context.Context) error { f.watchLocalFiles(ctx) getRemoteRepos := func() map[url.URL]struct{}...
f.registry.Logger().WithField("repos", f.config.Get(configuration.AccessRuleRepositories)).Info("Detected access rule repository change, processing updates.")
random_line_split
fetcher_default.go
= append(nonFiles, repo) } } return files, nonFiles } // watchLocalFiles watches all files that are configured in the config and are not watched already. // It also cancels watchers for files that are no longer configured. This function is idempotent. func (f *FetcherDefault) watchLocalFiles(ctx context.Context) ...
b, err := io.ReadAll(r) if err != nil { return nil, errors.WithStack(err) } var ks []Rule if json.Valid(b) { d := json.NewDecoder(bytes.NewReader(b)) d.DisallowUnknownFields() if err := d.Decode(&ks); err != nil { return nil, errors.WithStack(err) } return ks, nil } if err := yaml.Unmarshal(b,...
identifier_body
fetcher_default.go
Fetcher = new(FetcherDefault) type fetcherRegistry interface { x.RegistryLogger RuleRepository() Repository } type FetcherDefault struct { config configuration.Provider registry fetcherRegistry hc *http.Client mux *blob.URLMux cache map[string][]Rule cancelWatchers map[string]context.C...
ctx context.Context, oldRepos, newRepos map[url.URL]struct{}) error { repoChanged := false for repo := range newRepos { if _, ok := f.cache[repo.String()]; !ok { repoChanged = true f.registry.Logger().WithField("repo", repo.String()).Info("New repo detected, fetching access rules.") rules, err := f.fetch(...
rocessRemoteRepoUpdate(
identifier_name
tunnel.py
except (StandardError, socket.error) as e: self.logger.error("Could not connect to %s at %d:: %s" % (self.switch, self.port, str(e))) return None def wakeup(self): """ Wake up the event loop, presumably from another thread. """ ...
show
identifier_name
tunnel.py
) return soc except (StandardError, socket.error) as e: self.logger.error("Could not connect to %s at %d:: %s" % (self.switch, self.port, str(e))) return None def wakeup(self): """ Wake up the event loop, presumably from another ...
string = "Controller:\n" string += " state " + self.dbg_state + "\n" string += " switch_addr " + str(self.switch_addr) + "\n" string += " pending pkts " + str(len(self.packets)) + "\n" string += " total pkts " + str(self.packets_total) + "\n" string += "...
identifier_body
tunnel.py
][offset : offset + payload_len] if self.debug: print(pkt[1]) print(util.hex_dump_buffer(rawmsg)) # Now check for message handlers; preference is given to # handlers for a specific packet handled = False # Send to bridge socket if self.bdg_unix_...
(resp, pkt) = (None, None)
conditional_block
tunnel.py
Class abstracting the control interface to the switch. For receiving messages, two mechanism will be implemented. First, query the interface with poll. Second, register to have a function called by message type. The callback is passed the message type as well as the raw packet (or message object...
class VirtualTunnel(Thread): """
random_line_split
data.py
eld_out = int(len(lines)*.1) held_out = lines[:n_held_out] data = lines[n_held_out:] else: data = lines info('Tokenizing...') data_tokens = [['<s>'] + tokenize(l) + ['</s>'] for l in data] if self.interpolate: held_out_tokens = [['<s>'] + ...
s = float(sum(a)) for i in a: a[i] /= s
identifier_body
data.py
= int(l[1]) else: # data line assert current_ngram != 0, 'Invalid n-gram' log_prob, words = l.split('\t', 1) log_prob = float(log_prob) words = tuple(words.split(' ')) lm.set_prob(current_ngram, words, log_prob) ...
else:
random_line_split
data.py
(x, y): x,y = max(x,y), min(x,y) if y <= LOGZERO: return x negdiff = y-x return x + log(1 + exp(negdiff)) class LanguageModel(object): def __init__(self, n): self.smoothing = None self.interpolate = False self.lmbd = 0 self.models = defaultdict(dict) ...
add_log
identifier_name
data.py
) in Witten-Bell smoothing # types_after[w] = set of all types that occur after w types_after = defaultdict(set) # N(w) in Witten-Bell smoothing # num_tokens_after[w] = number of tokens that occur after w num_tokens_after = defaultdict(int) tokens = 0 grams = [d...
if num_types_after == 0: log_prob = LOGZERO else: log_prob = log(num_types_after) - (log(z) + log(num_tokens_after + num_types_after))
conditional_block
lptim.rs
{ /// Drive LPTIM with APB1 clock. Apb1 = 0b00, /// Drive LPTIM with Low-Speed Internal (LSI) clock. /// /// The user has to ensure that the LSI clock is running, or the timer won't /// start counting. Lsi = 0b01, /// Drive LPTIM with Internal 16 MHz clock. Hsi16 = 0b10, /// ...
ClockSrc
identifier_name
lptim.rs
Src) -> Self
} impl LpTimer<Encoder> { /// Initializes the Low-Power Timer in encoder mode. /// /// The `start` method must be called to enable the encoder input. pub fn init_encoder( lptim: LPTIM, pwr: &mut PWR, rcc: &mut Rcc, clk: ClockSrc, (pb5, pb7): (gpiob::PB5<gpio::An...
{ Self::init(lptim, pwr, rcc, clk) }
identifier_body
lptim.rs
Src) -> Self { Self::init(lptim, pwr, rcc, clk) } } impl LpTimer<Encoder> { /// Initializes the Low-Power Timer in encoder mode. /// /// The `start` method must be called to enable the encoder input. pub fn init_encoder( lptim: LPTIM, pwr: &mut PWR, rcc: &mut Rcc, ...
// The slowest LPTIM clock source is LSE at 32768 Hz, the fastest CPU clock is ~80 MHz. At // these conditions, one cycle of the LPTIM clock takes 2500 CPU cycles, so sleep for 5000. cortex_m::asm::delay(5000); // ARR can only be changed while the timer is *en*abled self.lptim.a...
self.lptim.cr.write(|w| w.enable().set_bit()); // "After setting the ENABLE bit, a delay of two counter clock is needed before the LPTIM is // actually enabled."
random_line_split
thread.go
mux sync.Mutex status ThreadStatus closeErr error // Error that caused the thread to stop currentCont Cont // Currently running continuation resumeCh chan valuesError caller *Thread // Who resumed this thread // Depth of GoFunction calls in the thread. This should not exceed // maxGo...
t.caller = caller t.status = ThreadOK t.mux.Unlock() caller.mux.Unlock() t.sendResumeValues(args, nil, nil) return caller.getResumeValues() } // Close a suspended thread. If successful, its status switches to dead. The // boolean returned is true if it was possible to close the thread (i.e. it was // suspende...
{ panic("Caller of thread to resume is not running") }
conditional_block
thread.go
func (t *Thread) CurrentCont() Cont { return t.currentCont } // IsMain returns true if the thread is the runtime's main thread. func (t *Thread) IsMain() bool { return t == t.mainThread } const maxErrorsInMessageHandler = 10 var errErrorInMessageHandler = StringValue("error in error handling") // RunContinuation ...
{ sz := len(s.stack) if sz > h { s.stack = s.stack[:h] } }
identifier_body
thread.go
Runtime mux sync.Mutex status ThreadStatus closeErr error // Error that caused the thread to stop currentCont Cont // Currently running continuation resumeCh chan valuesError caller *Thread // Who resumed this thread // Depth of GoFunction calls in the thread. This should not exceed /...
return } // This is to be able to close a suspended coroutine without completing it, but // still allow cleaning up the to-be-closed variables. If this is put on the // resume channel of a running thread, yield will cause a panic in the goroutine // and that will be caught in the defer() clause below. type threadClo...
} next.Push(t.Runtime, ErrorValue(err)) } c = next }
random_line_split