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
client.ts
Attempts) { attempts++ try { const res = await new Promise<request.Response>((resolve, reject) => { request(options, (error: any, response: request.Response, _body: any) => { if (error != null) { reject(error) } else { resolve(response) ...
/**
random_line_split
client.ts
? Math.floor(options.retryDelay) : 2000 const maxAttempts = options.maxAttempts != null ? Math.floor(options.maxAttempts) : 3 const retryErrorCodes = Array.isArray(options.retryErrorCodes) ? options.retryErrorCodes : RETRIABLE_ERRORS // default to `false` options.followRedirect = options.followRedirec...
const forwardHeaders: { [key: string]: string | string[] } = {} for (const header of headers) { if (req.headers[header] != null) { forwardHeaders[header] = req.headers[header] } } return this.withHeaders(forwardHeaders) } /** * Creates (by Object.create) a **new client** ins...
{ headers = FORWARD_HEADERS }
conditional_block
cluster.go
use the same node labels as the primary spec.UserLabels[config.LABEL_NODE_LABEL_KEY] = "" spec.UserLabels[config.LABEL_NODE_LABEL_VALUE] = "" labels := make(map[string]string) labels[config.LABEL_PG_CLUSTER] = cl.Spec.Name spec.ClusterName = cl.Spec.Name uniqueName := util.RandStringBytesRmndr(4) ...
random_line_split
cluster.go
{} // now, simply deep copy the values from the CRD if cluster.Spec.Resources != nil { deployment.Spec.Template.Spec.Containers[0].Resources.Requests = cluster.Spec.Resources.DeepCopy() } if cluster.Spec.Limits != nil { deployment.Spec.Template.Spec.Containers[0].Resources.Limits = cluster.Spec.Limits.D...
publishClusterCreateFailure
identifier_name
cluster.go
through the tablespace mount map that is present in the // new cluster. func UpdateTablespaces(clientset kubernetes.Interface, restConfig *rest.Config, cluster *crv1.Pgcluster, newTablespaces map[string]crv1.PgStorageSpec) error { // first, get a list of all of the instance deployments for the cluster deployments, ...
{ clusterName := cluster.Name //capture the cluster creation event topics := make([]string, 1) topics[0] = events.EventTopicCluster f := events.EventShutdownClusterFormat{ EventHeader: events.EventHeader{ Namespace: cluster.Namespace, Username: cluster.Spec.UserLabels[config.LABEL_PGOUSER], Topic: ...
identifier_body
cluster.go
, WorkflowID: cl.ObjectMeta.Labels[config.LABEL_WORKFLOW_ID], } err = events.Publish(f) if err != nil { log.Error(err.Error()) } //add replicas if requested if cl.Spec.Replicas != "" { replicaCount, err := strconv.Atoi(cl.Spec.Replicas) if err != nil { log.Error("error in replicas value " + err.Erro...
dataVolume, walVolume, tablespaceVolumes, err := pvc.CreateMissingPostgreSQLVolumes( clientset, cluster, namespace, replica.Spec.Name, replica.Spec.ReplicaStorage) if err != nil { log.Error(err) publishScaleError(namespace, replica.ObjectMeta.Labels[config.LABEL_PGOUSER], cluster) return } //update the r...
{ return }
conditional_block
train.py
': False, 'random_crop': False, 'random_brightness': False, 'repeat_dataset': None, # model params 'model_name': 'ganomaly', 'latent_size': 100, 'intermediate_size': 0, # only valid for cvae 'n_filters': 64, 'n_extra_layers': 0, 'w_adv': 1, # only valid for GAN...
if args.random_flip: image = tf.image.random_flip_left_right(image) image = tf.image.random_flip_up_down(image) if args.random_crop: image_shape = (args.image_size, args.image_size, args.image_channels) ...
def augment_image(image, label):
random_line_split
train.py
False, 'random_crop': False, 'random_brightness': False, 'repeat_dataset': None, # model params 'model_name': 'ganomaly', 'latent_size': 100, 'intermediate_size': 0, # only valid for cvae 'n_filters': 64, 'n_extra_layers': 0, 'w_adv': 1, # only valid for GANom...
if args.random_brightness: image = tf.image.random_brightness(image, max_delta=0.5) image = tf.clip_by_value(image, 0, 1) return image, label train_ds = train_ds.map( augment_image, num_parallel_calls=tf.data.experimental.AUTOTUNE) if arg...
image_shape = (args.image_size, args.image_size, args.image_channels) image = tf.image.resize_with_crop_or_pad( image, image_shape[-3] + 6, image_shape[-2] + 6) image = tf.image.random_crop(image, size=image_shape)
conditional_block
train.py
False, 'random_crop': False, 'random_brightness': False, 'repeat_dataset': None, # model params 'model_name': 'ganomaly', 'latent_size': 100, 'intermediate_size': 0, # only valid for cvae 'n_filters': 64, 'n_extra_layers': 0, 'w_adv': 1, # only valid for GANom...
def compile_default(model): model.compile( optimizer=tf.keras.optimizers.Adam( learning_rate=args.learning_rate), loss=tf.keras.losses.MeanSquaredError(), metrics=[ tf.keras.losses.MeanAbsoluteError(), tf.keras.losses.Bina...
return model_class( input_shape=image_shape, latent_size=args.latent_size, n_filters=args.n_filters, n_extra_layers=args.n_extra_layers, **kwargs )
identifier_body
train.py
False, 'random_crop': False, 'random_brightness': False, 'repeat_dataset': None, # model params 'model_name': 'ganomaly', 'latent_size': 100, 'intermediate_size': 0, # only valid for cvae 'n_filters': 64, 'n_extra_layers': 0, 'w_adv': 1, # only valid for GANom...
(args) -> tf.keras.Model: image_shape = (args.image_size, args.image_size, args.image_channels) def build_default(model_class, **kwargs): return model_class( input_shape=image_shape, latent_size=args.latent_size, n_filters=args.n_filters, n_extra_layers=a...
build_model
identifier_name
lib.rs
. * **arbitrary** - Enabling this feature introduces a public dependency on the [`arbitrary`](https://crates.io/crates/arbitrary) crate. Namely, it implements the `Arbitrary` trait from that crate for the [`Ast`](crate::ast::Ast) type. This feature is disabled by default. */ #![no_std] #![forbid(unsafe_code)] ...
unicode::is_word_character(c) }
identifier_body
lib.rs
to the size of the original pattern string (in bytes). This includes the type's corresponding destructors. (One exception to this is literal extraction, but this will eventually get fixed.) # Error reporting The `Display` implementations on all `Error` types exposed in this library provide nice human readable...
(c: char) -> bool { match c { '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' |
is_meta_character
identifier_name
lib.rs
. # Literal extraction This crate provides limited support for [literal extraction from `Hir` values](hir::literal). Be warned that literal extraction uses recursion, and therefore, stack size proportional to the size of the `Hir`. The purpose of literal extraction is to speed up searches. That is, if you know a re...
/// /// This returns true in all cases that `is_meta_character` returns true, but /// also returns true in some cases where `is_meta_character` returns false.
random_line_split
main.rs
())?; if args.debug { log::set_max_level(log::LevelFilter::Debug); } // Forcefully update the data and re-index if requested. if args.update_data { args.download_all_update()?; args.create_index()?; return Ok(()); } // Ensure that the necessary data exists. i...
fn download_all_update(&self) -> Result<()> { download::update_all(&self.data_dir) } } fn app() -> clap::App<'static, 'static> { use clap::{App, AppSettings, Arg}; lazy_static! { // clap wants all of its strings tied to a particular lifetime, but // we'd really like to determ...
{ download::download_all(&self.data_dir) }
identifier_body
main.rs
())?; if args.debug { log::set_max_level(log::LevelFilter::Debug); } // Forcefully update the data and re-index if requested. if args.update_data { args.download_all_update()?; args.create_index()?; return Ok(()); } // Ensure that the necessary data exists. i...
let mut searcher = args.searcher()?; let results = match args.query { None => None, Some(ref query) => Some(searcher.search(&query.parse()?)?), }; if args.files.is_empty() { let results = match results { None => failure::bail!("run with a file to rename or --query")...
{ args.create_index()?; }
conditional_block
main.rs
_matches())?; if args.debug { log::set_max_level(log::LevelFilter::Debug); } // Forcefully update the data and re-index if requested. if args.update_data { args.download_all_update()?; args.create_index()?; return Ok(()); } // Ensure that the necessary data exist...
.help("Choose the ngram size for indexing names. This is only \ used at index time and otherwise ignored.")) .arg(Arg::with_name("ngram-type") .long("ngram-type") .default_value("window") .possible_values(NgramType::possible_names()) ...
random_line_split
main.rs
())?; if args.debug { log::set_max_level(log::LevelFilter::Debug); } // Forcefully update the data and re-index if requested. if args.update_data { args.download_all_update()?; args.create_index()?; return Ok(()); } // Ensure that the necessary data exists. i...
(matches: &clap::ArgMatches) -> Result<Args> { let files = collect_paths( matches .values_of_os("file") .map(|it| it.collect()) .unwrap_or(vec![]), matches.is_present("follow"), ); let query = matches .value_of_l...
from_matches
identifier_name
models.py
_size = random.randrange(height // 25, height // 10) font = ImageFont.truetype("app/static/arial.ttf", size=font_size) txt = Image.new('RGB', (16 * font_size, int(1.1 * font_size)), color=(192, 192, 192)) d = ImageDraw.Draw(txt) d.text((0, 0), "New image mock, generated by PIL", font=font, fill=0) r...
else: criteria[axis] = 1000000 return min(criteria) print('basic image: ', image.size) if angle is None: # turn auto-rotating off # search optimal angle to rotate # current_resize_level = 0 # angles = [-45.0] # angles += [0] * (ROTAT...
criteria[axis] = sum_over_axis[-1] - sum_over_axis[0]
conditional_block
models.py
_size = random.randrange(height // 25, height // 10) font = ImageFont.truetype("app/static/arial.ttf", size=font_size) txt = Image.new('RGB', (16 * font_size, int(1.1 * font_size)), color=(192, 192, 192)) d = ImageDraw.Draw(txt) d.text((0, 0), "New image mock, generated by PIL", font=font, fill=0) r...
arkdown is saved here (redirection to database)""" return db[self.basic_image_id] @markdown.setter def markdown(self, value): db[self.image_id] = value # update hash set: there is an marked image with that hash image_hash = self.hash marked_images = marked_hashes.get(im...
anning m
identifier_name
models.py
img = Image.new('RGB', size=(width, height), color='white') rotate_direction = random.randint(0, 3) if rotate_direction in (0, 2): font_size = random.randrange(width // 25, width // 10) else: font_size = random.randrange(height // 25, height // 10) font = ImageFont.truetype("app/stat...
def random_image(seed): random.seed(seed) width = random.randint(128, 1024 + 1) height = random.randint(128, 1024 + 1)
random_line_split
models.py
(rotated, box=(random.randrange(width // 2), random.randrange(height // 2))) d = ImageDraw.Draw(img) n_steps = random.randrange(10, 20) prev_point = [random.randrange(width), random.randrange(height)] prev_horizontal = True for _ in range(n_steps): next_dir = rand...
image_id)['url'] @property def dupli
identifier_body
rpc_test.go
) defer cl.close() var err error snd := func(chunk string) { if err == nil { err = cl.send(chunk) } } // Send the command "write teststream 10\r\nabcdefghij\r\n" in multiple chunks // Nagle's algorithm is disabled on a write, so the server should get these in separate TCP packets. snd("wr") time.Sleep(1...
m, err = cl.write("cs733", str, 2) expect(t, m, &Msg{Kind: 'O'}, "file recreated", err) // Overwrite the file with expiry time of 4. This should be the new time. m, err = cl.write("cs733", str, 3) expect(t, m, &Msg{Kind: 'O'}, "file overwriten with exptime=4", err) // The last expiry time was 3 seconds. We shou...
{ cl := mkClientUrl(t, leaderUrl) defer cl.close() // Write file cs733, with expiry time of 2 seconds str := "Cloud fun" m, err := cl.write("cs733", str, 2) expect(t, m, &Msg{Kind: 'O'}, "write success", err) // Expect to read it back immediately. m, err = cl.read("cs733") expect(t, m, &Msg{Kind: 'C', Conten...
identifier_body
rpc_test.go
) defer cl.close() var err error snd := func(chunk string) { if err == nil { err = cl.send(chunk) } } // Send the command "write teststream 10\r\nabcdefghij\r\n" in multiple chunks // Nagle's algorithm is disabled on a write, so the server should get these in separate TCP packets. snd("wr") time.Sleep(1...
m, err := cl.cas("concCas", ver, str, 0) if err != nil { errorCh <- err return } else if m.Kind == 'O' { break } else if m.Kind != 'V' { errorCh <- errors.New(fmt.Sprintf("Expected 'V' msg, got %c", m.Kind)) return } ver = m.Version // retry with latest versio...
str := fmt.Sprintf("cl %d %d", i, j) for {
random_line_split
rpc_test.go
clients) for i := 0; i < nclients; i++ { cl := mkClientUrl(t, leaderUrl) if cl == nil { t.Fatalf("Unable to create client #%d", i) } defer cl.close() clients[i] = cl } var sem sync.WaitGroup // Used as a semaphore to coordinate goroutines to *begin* concurrently sem.Add(1) m, _ := clients[0].write("...
{ t.Fatal(err) }
conditional_block
rpc_test.go
(t *testing.T) { // Should be able to accept a few bytes at a time cl := mkClientUrl(t, leaderUrl) defer cl.close() var err error snd := func(chunk string) { if err == nil { err = cl.send(chunk) } } // Send the command "write teststream 10\r\nabcdefghij\r\n" in multiple chunks // Nagle's algorithm is di...
TestRPC_Chunks
identifier_name
dcy.go
{"192.168.0.1", 12345}, {"10.0.13.0", 12347}, } cache["syslog"] = []Address{ {"127.0.0.1", 9514}, } cache["statsd"] = []Address{ {"127.0.0.1", 8125}, } cache["mongo"] = []Address{ {"127.0.0.1", 27017}, {"192.168.10.123", 27017}, } cache["nsqlookupd-http"] = []Address{ {"127.0.0.1", 4161}, } // ad...
{ return ServicesByTag(name, "") }
identifier_body
dcy.go
.SetNodeName(nodeName) } } func noConsulTestMode() { domain = "sd" dc = "dev" nodeName = "node01" federatedDcs = []string{dc} cache["test1"] = []Address{ {"127.0.0.1", 12345}, {"127.0.0.1", 12348}, } cache["test2"] = []Address{ {"10.11.12.13", 1415}, } cache["test3"] = []Address{ {"192.168.0.1", 1234...
srvs := parseConsulServiceEntries(ses) if len(srvs) == 0 { return nil, ErrNotFound } updateCache(tag, name, dc, srvs) return srvs, nil } func srvQuery(tag, name string, dc string) (Addresses, error) { l.RLock() srvs, ok := cache[cacheKey(tag, name, dc)] l.RUnlock() if ok && len(srvs) > 0 { return srvs, n...
{ serviceExists := len(ses) != 0 // initialize cache key and start goroutine initializeCacheKey(tag, name, dc) go func() { monitor(tag, name, dc, qm.LastIndex, serviceExists) }() }
conditional_block
dcy.go
{ continue } updateCache(tag, name, dc, parseConsulServiceEntries(ses)) } } func service(service, tag string, qo *api.QueryOptions) ([]*api.ServiceEntry, *api.QueryMeta, error) { ses, qm, err := consul.Health().Service(service, tag, false, qo) if err != nil { return nil, nil, err } // izbacujem servise ...
shouldDiscoverHost
identifier_name
dcy.go
federatedDcs []string ) // Address is service address returned from Consul. type Address struct { Address string Port int } // String return address in host:port string. func (a Address) String() string { return fmt.Sprintf("%s:%d", a.Address, a.Port) } func (a Address) Equal(a2 Address) bool { return a.Addr...
consulAddr = localConsulAdr
random_line_split
opendocument_html_xslt.py
from plone.transforms.interfaces import ITransform, IRankedTransform from plone.transforms.message import PloneMessageFactory as _ from plone.transforms.transform import TransformResult from plone.transforms.log import log import plone.opendocument.utils as utils HAS_LXML = True try: from lxml import etree exc...
random_line_split
opendocument_html_xslt.py
HtmlXsltTransform(object): """ XSL transform which transforms OpenDocument files into XHTML """ implements(ITransform, IRankedTransform) inputs = ('application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.text-template', 'application/vnd.oasis.open...
self._dataFiles['content'] = content continue if (fileName == 'styles.xml'): styles = tempfile.NamedTemporaryFile() shutil.copyfileobj(fileContent, styles) styles.seek(0) self._dataFil...
''' Extracts required files from data (opendocument file). They are stored in self.subobjects and self._dataFiles. ''' try: #transform data to zip file object data_ = tempfile.NamedTemporaryFile() for chunk in data: data_.write(chu...
identifier_body
opendocument_html_xslt.py
HtmlXsltTransform(object): """ XSL transform which transforms OpenDocument files into XHTML """ implements(ITransform, IRankedTransform) inputs = ('application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.text-template', 'application/vnd.oasis.open...
data_.seek(0) dataZip = zipfile.ZipFile(data_) dataIterator = utils.zipIterator(dataZip) #extract content for fileName, fileContent in dataIterator: #getting data files if (fileName == 'content.xml'): cont...
data_.write(chunk)
conditional_block
opendocument_html_xslt.py
HtmlXsltTransform(object): """ XSL transform which transforms OpenDocument files into XHTML """ implements(ITransform, IRankedTransform) inputs = ('application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.text-template', 'application/vnd.oasis.open...
(self, data, options=None): ''' Transforms data (OpenDocument file) to XHTML. It returns an TransformResult object. ''' if not self.available: log(DEBUG, "The LXML library is required to use the %s transform " % (self.name)) retu...
transform
identifier_name
event.go
("Etag"); etag == "" { return nil, fmt.Errorf("Missing ETag header.") } else if parts := strings.Split(etag, `"`); len(parts) != 3 { return nil, fmt.Errorf("Malformed ETag header.") } else { event.Ref = parts[1] } // Success return event, nil } // // DeleteEvent // // Removes an event from the collection....
{ if opts.StartOrdinal != 0 { query.Add("startEvent", fmt.Sprintf("%d/%d", opts.Start.UnixNano()/1000000, opts.StartOrdinal)) } else { query.Add("startEvent", strconv.FormatInt(opts.Start.UnixNano()/1000000, 10)) } }
conditional_block
event.go
a new Ordinal value. To update and existing // Event use UpdateEvent() instead. // // Note that the key should exist otherwise this call will have unpredictable // results. func (c *Collection) AddEvent( key, typ string, value interface{}, ) (*Event, error) { return c.innerAddEvent(key, typ, nil, value) } // Like A...
( key, typ string, ts time.Time, ordinal int64, value interface{}, ) (*Event, error) { event := &Event{ Collection: c, Key: key, Ordinal: ordinal, Timestamp: ts, Type: typ, } // Perform the actual GET path := fmt.Sprintf("%s/%s/events/%s/%d/%d", c.Name, key, typ, ts.UnixNano()/1000000...
GetEvent
identifier_name
event.go
given a new Ordinal value. To update and existing // Event use UpdateEvent() instead. // // Note that the key should exist otherwise this call will have unpredictable // results. func (c *Collection) AddEvent( key, typ string, value interface{}, ) (*Event, error) { return c.innerAddEvent(key, typ, nil, value) } // ...
if rawMsg, err := json.Marshal(value); err != nil { return nil, err } else { event.Value = json.RawMessage(rawMsg) } // Perform the actual POST headers := map[string]string{"Content-Type": "application/json"} var path string if ts != nil { path = fmt.Sprintf("%s/%s/events/%s/%d", c.Name, key, typ, ts.U...
Type: typ, } // Encode the JSON message into a raw value that we can return to the // client if necessary.
random_line_split
event.go
a new Ordinal value. To update and existing // Event use UpdateEvent() instead. // // Note that the key should exist otherwise this call will have unpredictable // results. func (c *Collection) AddEvent( key, typ string, value interface{}, ) (*Event, error)
// Like AddEvent() except this lets you specify the timestamp that will be // attached to the event. func (c *Collection) AddEventWithTimestamp( key, typ string, ts time.Time, value interface{}, ) (*Event, error) { return c.innerAddEvent(key, typ, &ts, value) } // Inner implementation of AddEvent* func (c *Collect...
{ return c.innerAddEvent(key, typ, nil, value) }
identifier_body
day15.js
those, the Goblin first in reading order (the one to the right of the Elf) is selected. The selected Goblin's hit points (2) are reduced by the Elf's attack power (3), reducing its hit points to -1, killing it. After attacking, the unit's turn ends. Regardless of how the unit's turn ends, the next unit in the round t...
getPath
identifier_name
day15.js
19) #...G.# G(200) ####### After 28 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(116) #...#E# E(113) #....G# G(200) ####### More combat ensues; eventually, the bottom Elf dies: After 47 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(59) #...#.# #....G# G(200) ####### Before th...
{ super(x, y, map); this.enemy = Goblin; }
identifier_body
day15.js
# #!G.#G# #.G.#G# ####### ####### ####### ####### ####### In the above scenario, the Elf has three targets (the three Goblins): Each of the Goblins has open, adjacent squares which are in range (marked with a ? on the map). Of those squares, four are reachable (marked @); the other ...
####### ####### #G..#E# #...#E# E(200) #E#E.E# #E#...# E(
####### Before the 48th round can finish, the top-left Goblin finds that there are no targets remaining, and so combat ends. So, the number of full rounds that were completed is 47, and the sum of the hit points of all remaining units is 200+131+59+200 = 590. From these, the outcome of the battle is 47 * 590 = 27730. ...
random_line_split
producer.rs
connectors::tests::free_port::find_free_tcp_port; use crate::{connectors::impls::kafka, errors::Result, Event}; use futures::StreamExt; use rdkafka::{ admin::{AdminClient, AdminOptions, NewTopic, TopicReplication}, config::FromClientConfig, consumer::{CommitMode, Consumer, StreamConsumer}, message::Head...
() -> Result<()> { let _: std::result::Result<_, _> = env_logger::try_init(); let docker = DockerCli::default(); let container = redpanda_container(&docker).await?; let port = container.get_host_port_ipv4(9092); let mut admin_config = ClientConfig::new(); let broker = format!("127.0.0.1:{port}"...
connector_kafka_producer
identifier_name
producer.rs
connectors::tests::free_port::find_free_tcp_port; use crate::{connectors::impls::kafka, errors::Result, Event}; use futures::StreamExt; use rdkafka::{ admin::{AdminClient, AdminOptions, NewTopic, TopicReplication}, config::FromClientConfig, consumer::{CommitMode, Consumer, StreamConsumer}, message::Head...
"field1": 0.1, "field3": [] }, "meta": { "kafka_producer": { "key": "nananananana: batchman!" } } } }, { "data": { "value": { "field2": "just a string" ...
let batched_data = literal!([{ "data": { "value": {
random_line_split
producer.rs
connectors::tests::free_port::find_free_tcp_port; use crate::{connectors::impls::kafka, errors::Result, Event}; use futures::StreamExt; use rdkafka::{ admin::{AdminClient, AdminOptions, NewTopic, TopicReplication}, config::FromClientConfig, consumer::{CommitMode, Consumer, StreamConsumer}, message::Head...
num_partitions, TopicReplication::Fixed(num_replicas), )], &options, ) .await?; for r in res { match r { Err((topic, err)) => { error!("Error creating topic {}: {}", &topic, err); } Ok...
{ let _: std::result::Result<_, _> = env_logger::try_init(); let docker = DockerCli::default(); let container = redpanda_container(&docker).await?; let port = container.get_host_port_ipv4(9092); let mut admin_config = ClientConfig::new(); let broker = format!("127.0.0.1:{port}"); let topic ...
identifier_body
producer.rs
ors::tests::free_port::find_free_tcp_port; use crate::{connectors::impls::kafka, errors::Result, Event}; use futures::StreamExt; use rdkafka::{ admin::{AdminClient, AdminOptions, NewTopic, TopicReplication}, config::FromClientConfig, consumer::{CommitMode, Consumer, StreamConsumer}, message::Headers, ...
Ok(topic) => { info!("Created topic {}", topic); } } } let connector_config = literal!({ "reconnect": { "retry": { "interval_ms": 1000_u64, "max_retries": 10_u64 } }, "codec": {"name...
{ error!("Error creating topic {}: {}", &topic, err); }
conditional_block
enforsbot.py
and connected.", "hello" : "Hello there!", "hi" : "Hi there!", "LocationUpdate .*" : self.handle_incoming_location_update, "locate" : self.respond_location, "syscond" : self.respond_syscond, "st...
# If no pattern match found, check commands # ========================================= if response == "": response, choices = self.cmd_parser.parse(text, user) # Handle any ongoing activities # ============================= if user.current_...
pat = re.compile(pattern) if pat.match(text): response = pattern_response if callable(response): response = response(text)
conditional_block
enforsbot.py
and connected.", "hello" : "Hello there!", "hi" : "Hi there!", "LocationUpdate .*" : self.handle_incoming_location_update, "locate" : self.respond_location, "syscond" : self.respond_syscond, "st...
message = eb_message.Message("Main", eb_message.MSG_TYPE_USER_MESSAGE, {"user": user_name, "text": response, "choices": choices}) self.config.send_message...
# Send response # ============= response = response.strip() + "\n" print(" - Response: %s" % response.replace("\n", " "))
random_line_split
enforsbot.py
and connected.", "hello" : "Hello there!", "hi" : "Hi there!", "LocationUpdate .*" : self.handle_incoming_location_update, "locate" : self.respond_location, "syscond" : self.respond_syscond, "st...
(user, text): """Send user input to ongoing activity.""" activity = user.current_activity() if not activity: return None status = activity.handle_text(text) if status.done: user.remove_activity() return status @staticmethod def start_ask_...
handle_activity
identifier_name
enforsbot.py
"The main loop of the bot." try: while True: message = self.config.recv_message("Main") if message.msg_type == \ eb_message.MSG_TYPE_THREAD_STARTED: print("Thread started: %s" % message.sender) self.config.s...
"Return threads status." output = "" for thread in self.config.threads: output += "%s: %s\n" % (thread, self.config.get_thread_state(thread)) return output
identifier_body
index.ts
string into name param * @param api The api * @param name The name will be replaced */ export function getProfileByNameUrl(api: API, name: string) { return api.profileByName.replace("${name}", name); } /** * Replace uuid string into `${uuid}`, an...
(uuid: string, option: { api?: API } = {}) { const api = option.api || API_MOJANG; return fetchProfile(API.getProfileUrl(api, uuid) + "?" + queryString.stringify({ unsigned: false, }), api.publicKey).then((p) => p as GameProfile); } /** * Look up the GameProfile by usern...
fetch
identifier_name
index.ts
string into name param * @param api The api * @param name The name will be replaced */ export function getProfileByNameUrl(api: API, name: string) { return api.profileByName.replace("${name}", name); } /** * Replace uuid string into `${uuid}`, an...
/** * Fetch the GameProfile by uuid. * * @param uuid The unique id of user/player * @param option the options for this function */ export function fetch(uuid: string, option: { api?: API } = {}) { const api = option.api || API_MOJANG; return fetchProfile(API.getProfil...
{ const texture = parseTexturesInfo(profile); if (texture) { return cache ? cacheTextures(texture) : texture; } return Promise.reject(`No texture for user ${profile.id}.`); }
identifier_body
index.ts
f/VAjh5FFJnjS+7bE +bZEV0qwax1CEoPPJL1fIQjOS8zj086gjpGRCtSy9+bTPTfTR/SJ+VUB5G2IeCIt kNHpJX2ygojFZ9n5Fnj7R9ZnOM+L8nyIjPu3aePvtcrXlyLhH/hvOfIOjPxOlqW+ O5QwSFP4OEcyLAUgDdUgyW36Z5mB285uKW/ighzZsOTevVUG2QwDItObIV6i8RCx FbN2oDHyPaO5j1tTaBNyVt8CAwEAAQ== -----END PUBLIC KEY-----`, texture: "https://api.mojang.com/user/p...
buff.writeUTF8String("\r\n"); buff = buff.append(payload); buff.writeUTF8String("\r\n");
random_line_split
index.ts
string into name param * @param api The api * @param name The name will be replaced */ export function getProfileByNameUrl(api: API, name: string) { return api.profileByName.replace("${name}", name); } /** * Replace uuid string into `${uuid}`, an...
if (tex.textures.CAPE) { tex.textures.CAPE = await cache(tex.textures.CAPE); } if (tex.textures.ELYTRA) { tex.textures.ELYTRA = await cache(tex.textures.ELYTRA); } return tex; } /** * Cache the texture into the url as data-uri * @param ...
{ tex.textures.SKIN = await cache(tex.textures.SKIN); }
conditional_block
weginfos.js
", "Berg": "Seebensee", "Beschreibung": "Um das Panorama eines bekannten Berges zu genießen, muss man sich bekanntermaßen in den umliegenden Bergen aufhalten. So auch bei dieser Wanderung mit Zugspitzpanorama. ", "Tourname": "Seebensee", "Schwierigkeit": "mittel/schwer", "Dauer": "5", "KM": "13...
"Berg": "Innsbruck Citytour", "Beschreibung": "Innsbruck ist keine überwältigend große Metropole. Ihre Einzigartigkeit besteht dafür in ihrer alpinen Lage. Blicke aus der Innenstadt gen Himmel bleiben an den prominenten, die Stadt umrahmenden Bergketten hängen.", "Tourname": "Die Hauptstadt der ...
"Abstieg": 740 }, { "Nummer": "13", "Land": "Österreich",
random_line_split
process.go
if i == 0 { // there were no items in log, happens when last processed commit was in a branch that is no longer recent and is skipped in incremental // no need to write checkpoints <-done return nil } writer := repo.NewCheckpointWriter(s.opts.Logger) err = writer.Write(s.repo, s.checkpointsDir, s.lastProce...
type Timing struct { RegularCommitsCount int RegularCommitsTime time.Duration MergesCount int MergesTime time.Duration SlowestCommits []CommitWithDuration } type CommitWithDuration struct { Commit string Duration time.Duration } const maxSlowestCommits = 10 func (s *Timing) UpdateSl...
{ res, err := s.processMergeCommit(s.mergePartsCommit, s.mergeParts) if err != nil { panic(err) } s.trimGraphAfterCommitProcessed(s.mergePartsCommit) s.mergeParts = nil resChan <- res }
identifier_body
process.go
} if len(s.mergeParts) > 0 { s.processGotMergeParts(resChan) } if i == 0 { // there were no items in log, happens when last processed commit was in a branch that is no longer recent and is skipped in incremental // no need to write checkpoints <-done return nil } writer := repo.NewCheckpointWriter(s...
{ drainAndExit() return err }
conditional_block
process.go
, h := range parentHashes { hashToParOrd[h] = i } for parHash, part := range parts { for _, ch := range part.Changes { diff := incblame.Parse(ch.Diff) key := "" if diff.Path != "" { key = diff.Path } else { key = deletedPrefix + diff.PathPrev } par, ok := diffs[key] if !ok { par ...
func (s *Process) gitLogPatches() (io.ReadCloser, error) {
random_line_split
process.go
() Timing { return *s.timing } func (s *Process) initCheckpoints() error { if s.opts.CommitFromIncl == "" { s.repo = repo.New() } else { expectedCommit := "" if s.opts.NoStrictResume { // validation disabled } else { expectedCommit = s.opts.CommitFromIncl } reader := repo.NewCheckpointReader(s.op...
Timing
identifier_name
lstm.py
valid_size:] train_size = len(train_text) print(train_size, train_text[:64]) print(valid_size, valid_text[:64]) # Utility functions to map characters to vocabulary IDs and back. vocabulary_size = len(string.ascii_lowercase) + 1 # [a-z] + ' ' # ascii code for character first_letter = ord(string.ascii_lowercase[0]) d...
ollings] train_labels = train_data[1:] # labels are inputs shifted by one time step. # Unrolled LSTM loop. outputs = list() output = saved_output state = saved_state for i in train_inputs: output, state = lstm_cell(i, output, state) outputs.append(output) # State saving ac...
holder(tf.float32, shape=[batch_size, vocabulary_size])) train_inputs = train_data[:num_unr
conditional_block
lstm.py
valid_size:] train_size = len(train_text) print(train_size, train_text[:64]) print(valid_size, valid_text[:64]) # Utility functions to map characters to vocabulary IDs and back. vocabulary_size = len(string.ascii_lowercase) + 1 # [a-z] + ' ' # ascii code for character first_letter = ord(string.ascii_lowercase[0]) d...
def next(self): """Generate the next array of batches from the data. The array consists of the last batch of the previous array, followed by num_unrollings new ones. """ batches = [self._last_batch] for step in range(self._num_unrollings): batches.append(self._ne...
""Generate a single batch from the current cursor position in the data.""" batch = np.zeros(shape=(self._batch_size, vocabulary_size), dtype=np.float) for b in range(self._batch_size): # same id, same index of second dimension batch[b, char2id(self._text[self._cursor[b]])] = 1.0 ...
identifier_body
lstm.py
valid_size:] train_size = len(train_text) print(train_size, train_text[:64]) print(valid_size, valid_text[:64]) # Utility functions to map characters to vocabulary IDs and back. vocabulary_size = len(string.ascii_lowercase) + 1 # [a-z] + ' ' # ascii code for character first_letter = ord(string.ascii_lowercase[0]) d...
batches): """Convert a sequence of batches back into their (most likely) string representation.""" s = [''] * batches[0].shape[0] for b in batches: s = [''.join(x) for x in zip(s, characters(b))] return s train_batches = BatchGenerator(train_text, batch_size, num_unrollings) valid_batches ...
atches2string(
identifier_name
lstm.py
[valid_size:] train_size = len(train_text) print(train_size, train_text[:64]) print(valid_size, valid_text[:64]) # Utility functions to map characters to vocabulary IDs and back. vocabulary_size = len(string.ascii_lowercase) + 1 # [a-z] + ' ' # ascii code for character first_letter = ord(string.ascii_lowercase[0]) ...
"""Log-probability of the true labels in a predicted batch.""" predictions[predictions < 1e-10] = 1e-10 return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0] def sample_distribution(distribution): """Sample one element from a distribution assumed to be an array of normalized p...
def logprob(predictions, labels): # prevent negative probability
random_line_split
dataset.py
train_or_test, dataset_path): dataset_file_name = dataset_name[6:] + '_%s_*.tfrecord' if dataset_name == 'pascalvoc_2007': train_test_sizes = { 'train': FLAGS.pascalvoc_2007_train_size, 'test': FLAGS.pascalvoc_2007_test_size, } ...
float_feature
identifier_name
dataset.py
box/ymax': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/label': tf.VarLenFeature(dtype=tf.int64), 'image/object/bbox/difficult': tf.VarLenFeature(dtype=tf.int64), } # Items in Pascal VOC TFRecords. self.items = { 'image': slim.tfexample_decoder.Image...
return '%s/%s_%03d.tfrecord' % (output_dir, name, idx)
identifier_body
dataset.py
tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(d...
if dataset_name == 'pascalvoc_2007' or dataset_name == 'pascalvoc_2012': dataset = self.load_dataset(dataset_name, train_or_test, dataset_path) return dataset # This function is used to load pascalvoc2007 or psaclvoc2012 datasets # Inputs: # dataset_name: pascal...
with tf.name_scope(None, "read_dataset_from_tfrecords") as scope:
random_line_split
dataset.py
tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(d...
dataset_file_name = os.path.join(dataset_path, dataset_file_name % train_or_test) reader = tf.TFRecordReader decoder = slim.tfexample_decoder.TFExampleDecoder(self.features, self.items) return slim.dataset.Dataset( data_sources=dataset_file_name, ...
train_test_sizes = { 'train': FLAGS.pascalvoc_2012_train_size, }
conditional_block
exec.rs
binary.hash().as_str(), compiler); #[cfg(not(feature = "sys"))] let module = compiled_modules.get_compiled_module(binary.hash().as_str(), compiler); let module = match (module, binary.entry.as_ref()) { (Some(a), _) => a, (None, Some(entry)) => { let module = Module::new(&store,...
{ if self.commands.exists(name.as_str()) { return self .commands .exec(parent_ctx, name.as_str(), store, builder); } }
conditional_block
exec.rs
BusSpawnedProcess, VirtualBusError> { // Load the module #[cfg(feature = "sys")] let compiler = store.engine().name(); #[cfg(not(feature = "sys"))] let compiler = "generic"; #[cfg(feature = "sys")] let module = compiled_modules.get_compiled_module(&store, binary.hash().as_str(), compiler); ...
( module: Module, store: Store, env: WasiEnv, runtime: &Arc<dyn WasiRuntime + Send + Sync + 'static>, ) -> Result<BusSpawnedProcess, VirtualBusError> { // Create a new task manager let tasks = runtime.task_manager(); // Create the signaler let pid = env.pid(); let signaler = Box::ne...
spawn_exec_module
identifier_name
exec.rs
BusSpawnedProcess, VirtualBusError> { // Load the module #[cfg(feature = "sys")] let compiler = store.engine().name(); #[cfg(not(feature = "sys"))] let compiler = "generic"; #[cfg(feature = "sys")] let module = compiled_modules.get_compiled_module(&store, binary.hash().as_str(), compiler); ...
unsafe impl Send for UnsafeWrapper {} let inner = UnsafeWrapper { inner: Box::new(task), }; move || { (inner.inner)(); } }; tasks_outer.task_wasm(Box::new(task)).map_err(|err| { error!("wasi[{}]::...
struct UnsafeWrapper { inner: Box<dyn FnOnce() + 'static>, }
random_line_split
lib.rs
#[cfg(feature = "std")] use std::fmt::Debug; use sp_std::prelude::*; pub mod abi; pub mod contract_metadata; pub mod gateway_inbound_protocol; pub mod transfers; pub use gateway_inbound_protocol::GatewayInboundProtocol; pub type ChainId = [u8; 4]; #[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Encode, Decode, De...
use serde::{Deserialize, Serialize}; #[cfg(feature = "no_std")] use sp_runtime::RuntimeDebug as Debug;
random_line_split
lib.rs
_runtime::RuntimeDebug as Debug; #[cfg(feature = "std")] use std::fmt::Debug; use sp_std::prelude::*; pub mod abi; pub mod contract_metadata; pub mod gateway_inbound_protocol; pub mod transfers; pub use gateway_inbound_protocol::GatewayInboundProtocol; pub type ChainId = [u8; 4]; #[derive(Clone, Eq, PartialEq, Pa...
{ /// The contract returned successfully. /// /// There is a status code and, optionally, some data returned by the contract. Success { /// Flags that the contract passed along on returning to alter its exit behaviour. /// Described in `pallet_contracts::exec::ReturnFlags`. flag...
ComposableExecResult
identifier_name
monitors_test.go
", err) } { m, ok := monitors[0].(*MonitorConnectivity) if !ok || m.Type != "connectivity" { t.Error("request sends json including type but: ", m) } if m.Memo != "connectivity monitor" { t.Error("request sends json including memo but: ", m) } } { m, ok := monitors[1].(*MonitorExternalHTTP) if...
{ if got := decodeMonitorsJSON(t); !reflect.DeepEqual(got, wantMonitors) { t.Errorf("fail to get correct data: diff: (-got +want)\n%v", pretty.Compare(got, wantMonitors)) } }
identifier_body
monitors_test.go
m) } if m.CertificationExpirationCritical != 15 { t.Error("request sends json including certificationExpirationCritical but: ", m) } if m.CertificationExpirationWarning != 30 { t.Error("request sends json including certificationExpirationWarning but: ", m) } if m.ContainsString != "Foo Bar Baz" { ...
TestEncodeMonitor
identifier_name
monitors_test.go
"responseTimeDuration": 5, "certificationExpirationCritical": 15, "certificationExpirationWarning": 30, "containsString": "Foo Bar Baz", "skipCertificateVerification": true, "headers": []map[string]interface{}{ {"name": "Cache-Control", "value": "no-cache"...
var wantMonitors = []Monitor{ &MonitorConnectivity{ ID: "2cSZzK3XfmA", Name: "", Type: "connectivity", IsMute: false, NotificationInterval: 0, Scopes: []string{}, ExcludeScopes: []string{}, }, &MonitorHostMetric{ ID...
"notificationInterval": 60 } ] } `
random_line_split
monitors_test.go
"responseTimeDuration": 5, "certificationExpirationCritical": 15, "certificationExpirationWarning": 30, "containsString": "Foo Bar Baz", "skipCertificateVerification": true, "headers": []map[string]interface{}{ {"name": "Cache-Control", "value": "no-cache"...
if m.ResponseTimeDuration != 5 { t.Error("request sends json including responseTimeDuration but: ", m) } if m.CertificationExpirationCritical != 15 { t.Error("request sends json including certificationExpirationCritical but: ", m) } if m.CertificationExpirationWarning != 30 { t.Error("request sen...
{ t.Error("request sends json including responseTimeWarning but: ", m) }
conditional_block
impl.go
.`, Value: fmt.Sprintf("0.0.0.0:%d", params.INITIAL_PORT), }, cli.StringFlag{ Name: "rpccorsdomain", Usage: `Comma separated list of domains to accept cross origin requests. (localhost enabled by default)`, Value: "http://localhost:* /*", }, cli.IntFlag{Name: "max-unresponsive-time", Usage: `...
return nil } app.After = func(ctx *cli.Context) error { debug.Exit() return nil } app.Run(os.Args) } func MainCtx(ctx *cli.Context) error { var pms *network.PortMappedSocket var err error fmt.Printf("Welcom to smartraiden,version %s\n", ctx.App.Version) if ctx.String("nat") != "ice" { host, port := ne...
{ return err }
conditional_block
impl.go
.`, Value: fmt.Sprintf("0.0.0.0:%d", params.INITIAL_PORT), }, cli.StringFlag{ Name: "rpccorsdomain", Usage: `Comma separated list of domains to accept cross origin requests. (localhost enabled by default)`, Value: "http://localhost:* /*", }, cli.IntFlag{Name: "max-unresponsive-time", Usage: `...
log.Error(fmt.Sprintf("start server on %s error:%s", ctx.String("listen-address"), err)) utils.SystemExit(1) } cfg := config(ctx, pms) log.Debug(fmt.Sprintf("Config:%s", utils.StringInterface(cfg, 2))) ethEndpoint := ctx.String("eth-rpc-endpoint") client, err := helper.NewSafeClient(ethEndpoint) if err != nil...
{ var pms *network.PortMappedSocket var err error fmt.Printf("Welcom to smartraiden,version %s\n", ctx.App.Version) if ctx.String("nat") != "ice" { host, port := network.SplitHostPort(ctx.String("listen-address")) pms, err = network.SocketFactory(host, port, ctx.String("nat")) if err != nil { log.Crit(fmt....
identifier_body
impl.go
.`, Value: fmt.Sprintf("0.0.0.0:%d", params.INITIAL_PORT), }, cli.StringFlag{ Name: "rpccorsdomain", Usage: `Comma separated list of domains to accept cross origin requests. (localhost enabled by default)`, Value: "http://localhost:* /*", }, cli.IntFlag{Name: "max-unresponsive-time", Usage: `...
(cfg *params.Config, pms *network.PortMappedSocket, bcs *rpc.BlockChainService) (transport network.Transporter, discovery network.DiscoveryInterface) { var err error /* use ice and doesn't work as route node,means this node runs on a mobile phone. */ if cfg.NetworkMode == params.ICEOnly && cfg.IgnoreMediatedNode...
buildTransportAndDiscovery
identifier_name
impl.go
.`, Value: fmt.Sprintf("0.0.0.0:%d", params.INITIAL_PORT), }, cli.StringFlag{ Name: "rpccorsdomain", Usage: `Comma separated list of domains to accept cross origin requests. (localhost enabled by default)`, Value: "http://localhost:* /*", }, cli.IntFlag{Name: "max-unresponsive-time", Usage: `...
cli.BoolFlag{ Name: "debugcrash", Usage: "enable debug crash feature", }, cli.StringFlag{ Name: "conditionquit", Usage: "quit at specified point for test", Value: "", }, cli.StringFlag{ Name: "turn-server", Usage: "tur server for ice", Value: params.DefaultTurnServer, }, cli.Str...
"ice"- Use ice framework for nat punching [default: ice]`, Value: "ice", },
random_line_split
evaluation_confidence_mask_sinmul.py
/aist/pspicker/training_plan" EVAL_DIR="/home/aab10867zc/work/aist/pspicker/evaluation/confidence_mask_sinmul_easy" #weighted by station class MultiInferenceConfig(config.Config): #multi std 0110 # Set batch size to 1 since we'll be running inference on # one image at a time. Batch size =...
else: super(self.__class__).window_reference(self, window_id) def load_mask(self, window_id): """Generate instance masks for shapes of the given image ID. """ streams = self.load_streams(window_id) info=self.window_info[window_id] shape=info["shape"] ...
return info["station"]
conditional_block
evaluation_confidence_mask_sinmul.py
/work/aist/pspicker/training_plan" EVAL_DIR="/home/aab10867zc/work/aist/pspicker/evaluation/confidence_mask_sinmul_easy" #weighted by station class MultiInferenceConfig(config.Config): #multi std 0110 # Set batch size to 1 since we'll be running inference on # one image at a time. Batch s...
else: return o class Evaluation_confidence_mask(): def __init__(self,single_model,multi_model,dataset,overlap_threshold=0.3): self.single_model=single_model self.multi_model=multi_model self.dataset=dataset self.overlap_threshold=overlap_threshold def evaluate(self,...
return o.__str__() elif type(o).__module__ == np.__name__: return o.__str__()
random_line_split
evaluation_confidence_mask_sinmul.py
/aist/pspicker/training_plan" EVAL_DIR="/home/aab10867zc/work/aist/pspicker/evaluation/confidence_mask_sinmul_easy" #weighted by station class MultiInferenceConfig(config.Config): #multi std 0110 # Set batch size to 1 since we'll be running inference on # one image at a time. Batch size =...
streams.append(stream) index=np.argsort(dist)[:10] streams = [streams[i] for i in index] return streams def load_window(self, window_id): """Generate an image from the specs of the given image ID. Typically this function loads the image from a file, but...
info = self.window_info[window_id] shape=info["shape"] streams=[] dist = [] for event in info["path"]: paths=list(event.values()) traces=[] for path in paths: trace=read(path)[0] traces.append(trace) stream...
identifier_body
evaluation_confidence_mask_sinmul.py
/aist/pspicker/training_plan" EVAL_DIR="/home/aab10867zc/work/aist/pspicker/evaluation/confidence_mask_sinmul_easy" #weighted by station class MultiInferenceConfig(config.Config): #multi std 0110 # Set batch size to 1 since we'll be running inference on # one image at a time. Batch size =...
(self,single_model,multi_model,dataset,overlap_threshold=0.3): self.single_model=single_model self.multi_model=multi_model self.dataset=dataset self.overlap_threshold=overlap_threshold def evaluate(self,window_id=None): test_results
__init__
identifier_name
lib.rs
6-F1idHcFN3Mc6-qXDHj-IeV67w1ngQrk8M12v1UgS2sQnqaTxdFpoYKOoGH-JgwxojgF7g5dvIxamd6fWC2sSWuumpAcr9TZKwES5r5Fcq2U", "https://www.reddit.com/r/DnD/comments/bzi1oq/art_two_dragons_and_adopted_kobold_son/?") ), }, CleanInformation { domain: "www.google.com", ...
let cleaner = UrlCleaner::default(); let clean = cleaner.clean_url(&parsed).unwrap(); assert_eq!(clean, url_clean); } #[test] fn clean_facebook2() { let url_dirty ="https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.banggood.com%2FXT30-V3-ParaBoard-Parallel-Charging-Board-Ban...
let parsed = Url::parse(&url_dirty).unwrap();
random_line_split
lib.rs
-F1idHcFN3Mc6-qXDHj-IeV67w1ngQrk8M12v1UgS2sQnqaTxdFpoYKOoGH-JgwxojgF7g5dvIxamd6fWC2sSWuumpAcr9TZKwES5r5Fcq2U", "https://www.reddit.com/r/DnD/comments/bzi1oq/art_two_dragons_and_adopted_kobold_son/?") ), }, CleanInformation { domain: "www.google.com", ...
(&self, url: &url::Url) -> Option<String> { if let Some(domain) = url.domain() { // Check all rules that matches this domain, but return on the first clean for domaininfo in self.cleaning_info.iter().filter(|&x| x.domain == domain) { if domaininfo.path == url.path() { ...
clean_url
identifier_name
lib.rs
-F1idHcFN3Mc6-qXDHj-IeV67w1ngQrk8M12v1UgS2sQnqaTxdFpoYKOoGH-JgwxojgF7g5dvIxamd6fWC2sSWuumpAcr9TZKwES5r5Fcq2U", "https://www.reddit.com/r/DnD/comments/bzi1oq/art_two_dragons_and_adopted_kobold_son/?") ), }, CleanInformation { domain: "www.google.com", ...
else { newurl.query_pairs_mut().append_pair(&key, &value); } } (newurl, modified) } /// try to extract the destination url from the link if possible and also try to remove the click-id /// query parameters that are available, if the content has been modified ret...
{ println!("key found: {:?}", key); modified = true; }
conditional_block
lib.rs
-F1idHcFN3Mc6-qXDHj-IeV67w1ngQrk8M12v1UgS2sQnqaTxdFpoYKOoGH-JgwxojgF7g5dvIxamd6fWC2sSWuumpAcr9TZKwES5r5Fcq2U", "https://www.reddit.com/r/DnD/comments/bzi1oq/art_two_dragons_and_adopted_kobold_son/?") ), }, CleanInformation { domain: "www.google.com", ...
// Check if there is a click identifier, and return if there is one let (url, modified) = self.clean_query(&url); if modified { return Some(url.to_string()); } } None } pub fn try_clean_string(&self, url_string: String) -> String ...
{ if let Some(domain) = url.domain() { // Check all rules that matches this domain, but return on the first clean for domaininfo in self.cleaning_info.iter().filter(|&x| x.domain == domain) { if domaininfo.path == url.path() { println!("{}", url); ...
identifier_body
generate-map.ts
] = d; prev[to] = from; } } } const path: number[] = []; let current = end; if (prev[current] !== null || current === start) { while (current !== null) { path.push(current); current = prev[current]; } } path.reverse(); return path; } class MapBuilder { map: Map;...
() { const addedGrasses = []; for (let x = 0; x < width; x++) { for (let y = 0; y < height; y++) { const t = this.map.get(x, y); if (t === Tile.Ground) { const pastureNeighbors = (x > 0 && this.map.get(x - 1, y) === Tile.Grass ? 1 : 0) + (x < width - 1 &&...
iterateGrass
identifier_name
generate-map.ts
] = d; prev[to] = from; } } } const path: number[] = []; let current = end; if (prev[current] !== null || current === start) { while (current !== null) { path.push(current); current = prev[current]; } } path.reverse(); return path; } class MapBuilder { map: Map;...
iterateGrass() { const addedGrasses = []; for (let x = 0; x < width; x++) { for (let y = 0; y < height; y++) { const t = this.map.get(x, y); if (t === Tile.Ground) { const pastureNeighbors = (x > 0 && this.map.get(x - 1, y) === Tile.Grass ? 1 : 0) + (...
{ [x, y] = [x, y].map(Math.round); if (this.map.get(x, y) === Tile.Ground) { this.map.set(x, y, Tile.Grass); } }
identifier_body
generate-map.ts
y, Tile.Wall); } } addStream(x0: number, y0: number, x1: number, y1: number, brushSize = 2) { [x0, y0, x1, y1] = [x0, y0, x1, y1].map(Math.round); const bs2 = ~~(brushSize / 2); for (const [x, y] of line([x0, y0], [x1, y1])) { for (let bx = 0; bx < brushSize; bx++) { for (let by = 0...
random_line_split
generate-map.ts
] = d; prev[to] = from; } } } const path: number[] = []; let current = end; if (prev[current] !== null || current === start) { while (current !== null) { path.push(current); current = prev[current]; } } path.reverse(); return path; } class MapBuilder { map: Map;...
} // calculate a triangulation of the points const triangulation = Delaunay.from(points); // pick a subset of points forming a circle in the center to be our playable area const interior: number[] = []; const sorted = points .slice() .sort((p0, p1) => distSq(p0, [w / 2, h / 2]) - distSq(p1, [w / ...
{ points.push([x, y]); }
conditional_block
callback.go
allows hand-crafted code to add middleware to the router AddMiddleware(ctx context.Context, r chi.Router) // BasePath allows hand-crafted code to set the base path for the Router BasePath() string // Config returns a structure representing the server config // This is returned from the status endpoint Config() i...
type Hooks struct { // Logger returns the common.Logger instance to set use within Sysl-go. // By default, if this Logger hook is not set then an instance of the pkg logger is used. // This hook can also be used to define a custom logger. // For more information about logging see log/README.md within this project....
random_line_split
callback.go
allows hand-crafted code to add middleware to the router AddMiddleware(ctx context.Context, r chi.Router) // BasePath allows hand-crafted code to set the base path for the Router BasePath() string // Config returns a structure representing the server config // This is returned from the status endpoint Config() i...
(ctx context.Context, h *Hooks, endpointName string, authRuleExpression string) (authrules.Rule, error) { return resolveAuthorizationRule(ctx, h, endpointName, authRuleExpression, authrules.MakeGRPCJWTAuthorizationRule) } func ResolveRESTAuthorizationRule(ctx context.Context, h *Hooks, endpointName string, authRuleEx...
ResolveGRPCAuthorizationRule
identifier_name
callback.go
) } // Hooks can be used to customise the behaviour of an autogenerated sysl-go service. type Hooks struct { // Logger returns the common.Logger instance to set use within Sysl-go. // By default, if this Logger hook is not set then an instance of the pkg logger is used. // This hook can also be used to define a cu...
{ return nil, fmt.Errorf("method/endpoint %s requires a JWT-based authorization rule, but there is no config for library.authentication.jwtauth", endpointName) }
conditional_block
callback.go
hand-crafted code to add middleware to the router AddMiddleware(ctx context.Context, r chi.Router) // BasePath allows hand-crafted code to set the base path for the Router BasePath() string // Config returns a structure representing the server config // This is returned from the status endpoint Config() interfac...
func ResolveGrpcServerOptions(ctx context.Context, h *Hooks, grpcPublicServerConfig *config.CommonServerConfig) ([]grpc.ServerOption, error) { switch { case len(h.AdditionalGrpcServerOptions) > 0 && h.OverrideGrpcServerOptions != nil: return nil, fmt.Errorf("Hooks.AdditionalGrpcServerOptions and Hooks.OverrideGrp...
{ switch { case len(h.AdditionalGrpcDialOptions) > 0 && h.OverrideGrpcDialOptions != nil: return nil, fmt.Errorf("Hooks.AdditionalGrpcDialOptions and Hooks.OverrideGrpcDialOptions cannot both be set") case h.OverrideGrpcDialOptions != nil: return h.OverrideGrpcDialOptions(serviceName, grpcDownstreamConfig) defa...
identifier_body
gdb.rs
(&self) -> usize { // self.buffer.len() // } // pub fn len(&self) -> usize { // self.head.wrapping_sub(self.tail) % N // } pub fn is_full(&self) -> bool { (self.tail.wrapping_sub(1) % N) == self.head } pub fn try_push(&mut self, val: u8) -> Result<(), ()> { if s...
{ let mut uart = GdbUart::new(receive_irq).unwrap(); uart.enable(); let mut target = XousTarget::new(); let server = GdbStubBuilder::new(uart) .with_packet_buffer(unsafe { &mut GDB_BUFFER }) .build() .expect("unable to build gdb server") .run_state_machine(&mut target) ...
identifier_body
gdb.rs
#[path = "gdb/riscv.rs"] mod cpu; pub struct XousTarget { pid: Option<xous_kernel::PID>, inner: cpu::XousTargetInner, } pub struct XousDebugState<'a> { pub target: XousTarget, pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::precursor::gdbuart::GdbUart>, } static mut GDB_STATE: Optio...
} } _ => { println!("GDB is in an unexpected state!"); return; } }; // If the user just hit Ctrl-C, then remove the pending interrupt that may or may not exist. if let GdbStubStateMachine::CtrlCInterrupt(_) = &new_server { target.unpatch...
{ println!("gdbstub error in DeferredStopReason.pump: {:?}", e); return; }
conditional_block
gdb.rs
#[path = "gdb/riscv.rs"] mod cpu; pub struct XousTarget { pid: Option<xous_kernel::PID>, inner: cpu::XousTargetInner, } pub struct XousDebugState<'a> { pub target: XousTarget,
pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::precursor::gdbuart::GdbUart>, } static mut GDB_STATE: Option<XousDebugState> = None; static mut GDB_BUFFER: [u8; 4096] = [0u8; 4096]; trait ProcessPid { fn pid(&self) -> Option<xous_kernel::PID>; fn take_pid(&mut self) -> Option<xous_kernel:...
random_line_split
gdb.rs
#[path = "gdb/riscv.rs"] mod cpu; pub struct XousTarget { pid: Option<xous_kernel::PID>, inner: cpu::XousTargetInner, } pub struct XousDebugState<'a> { pub target: XousTarget, pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::precursor::gdbuart::GdbUart>, } static mut GDB_STATE: Optio...
() -> Self { MicroRingBuf { buffer: [0u8; N], head: 0, tail: 0, } } } impl<const N: usize> MicroRingBuf<N> { // pub fn capacity(&self) -> usize { // self.buffer.len() // } // pub fn len(&self) -> usize { // self.head.wrapping_sub(self....
default
identifier_name
tls.go
traffic comes in, the gateway on which the rule is being // bound, etc. All these can be checked statically, since we are generating the configuration for a proxy // with predefined labels, on a specific port. func matchTCP(match *v1alpha3.L4MatchAttributes, proxyLabels labels.Collection, gateways map[string]bool, por...
metadata: util.BuildConfigInfoMetadataV2(cfg.ConfigMeta), destinationCIDRs: destinationCIDRs, networkFilters: buildOutboundNetworkFilters(node, tcp.Route, push, listenPort, cfg.ConfigMeta), }) defaultRouteAdded = true break TcpLoop } // Use the service's virtual address first...
{ if listenPort.Protocol.IsTLS() { return nil } out := make([]*filterChainOpts, 0) // very basic TCP // break as soon as we add one network filter with no destination addresses to match // This is the terminating condition in the filter chain match list defaultRouteAdded := false TcpLoop: for _, cfg := ran...
identifier_body
tls.go
traffic comes in, the gateway on which the rule is being // bound, etc. All these can be checked statically, since we are generating the configuration for a proxy // with predefined labels, on a specific port. func matchTCP(match *v1alpha3.L4MatchAttributes, proxyLabels labels.Collection, gateways map[string]bool, por...
// HTTPS or TLS ports without associated virtual service if !hasTLSMatch { var sniHosts []string // In case of a sidecar config with user defined port, if the user specified port is not the same as the // service's port, then pick the service port if and only if the service has only one port. If service // h...
random_line_split