file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
simpleLSTM.py
# -*- coding: utf-8 -*- from collections import OrderedDict import numpy import theano import theano.tensor as T import time import sys import matplotlib.pyplot as plt SEED = 123 numpy.random.seed(SEED) def numpy_floatX(data): return numpy.asarray(data, dtype=theano.config.floatX) def _p(pp, name): return '...
U weights. lrate=0.0001, # Learning rate for sgd (not used for adadelta and rmsprop) n_words=10000, # Vocabulary size optimizer=adadelta, # sgd, adadelta and rmsprop available, sgd very hard to use, not recommanded (probably need momentum and decaying learning rate). encoder='lstm', # TODO: can be ...
ied to the
identifier_name
simpleLSTM.py
# -*- coding: utf-8 -*- from collections import OrderedDict import numpy import theano import theano.tensor as T import time import sys import matplotlib.pyplot as plt SEED = 123 numpy.random.seed(SEED) def numpy_floatX(data): return numpy.asarray(data, dtype=theano.config.floatX) def _p(pp, name): return '...
r applied to the U weights. lrate=0.0001, # Learning rate for sgd (not used for adadelta and rmsprop) n_words=10000, # Vocabulary size optimizer=adadelta, # sgd, adadelta and rmsprop available, sgd very hard to use, not recommanded (probably need momentum and decaying learning rate). encoder='lstm', ...
sk: Theano variable Sequence mask y: Theano variable Targets cost: Theano variable Objective fucntion to minimize Notes ----- For more information, see [ADADELTA]_. .. [ADADELTA] Matthew D. Zeiler, *ADADELTA: An Adaptive Learning Rate Method*, arXiv:1212.5701. ...
identifier_body
general.rs
extern crate serenity; use serenity::{framework::standard::{ help_commands, macros::{ command, group, help}, Args, CommandGroup, CommandResult, HelpOptions, }, model::{channel::{Message,ReactionType}, id::UserId }, prelude::*}; use serenity::utils::Colour; // use serenity::model::appli...
ODO mehhhh // #[command] // #[checks(Bot)] // #[description = "Talk with your self\n"] // #[aliases(talk)] // async fn talk_to_self(ctx: &Context, msg: &Message) -> CommandResult { // msg.reply(&ctx, "Hello, myself!").await?; // Ok(()) // } // #[check] // #[name = "Bot"] // async fn bot_check(ctx: &Context, ms...
et guild = match ctx.cache.guild(&msg.guild_id.unwrap()).await { Some(guild) => guild, None => { msg.reply(ctx, "Error" ).await; return Ok(()); } }; let number_users = guild.member_count; // let number_msgs = channel.message_count; let number_cha...
identifier_body
general.rs
extern crate serenity; use serenity::{framework::standard::{ help_commands, macros::{ command, group, help}, Args, CommandGroup, CommandResult, HelpOptions, }, model::{channel::{Message,ReactionType}, id::UserId }, prelude::*}; use serenity::utils::Colour; // use serenity::model::appli...
atar_url().unwrap()); }; e }); m }); msg.await.unwrap(); Ok(()) }
ap()); } else { e.title(&person[0].name); e.image(person[0].av
conditional_block
general.rs
extern crate serenity; use serenity::{framework::standard::{ help_commands, macros::{ command, group, help}, Args, CommandGroup, CommandResult, HelpOptions, }, model::{channel::{Message,ReactionType}, id::UserId }, prelude::*}; use serenity::utils::Colour; // use serenity::model::appli...
// } // #[check] // #[name = "Bot"] // async fn bot_check(ctx: &Context, msg: &Message) -> CheckResult { // if let Some(member) = msg.member(&ctx.cache) { // let user = member.user.read(); // user.bot.into() // } else { // false.into() // } // } #[command] #[description = "Bot will...
random_line_split
general.rs
extern crate serenity; use serenity::{framework::standard::{ help_commands, macros::{ command, group, help}, Args, CommandGroup, CommandResult, HelpOptions, }, model::{channel::{Message,ReactionType}, id::UserId }, prelude::*}; use serenity::utils::Colour; // use serenity::model::appli...
&Context, msg: &Message) -> CommandResult { let phrase = format!("HIIII {}",&msg.author.name); msg.reply(&ctx, phrase).await?; // msg.reply(&ctx, msg.author_nick(&ctx).await.unwrap()).await?; // msg.reply(&ctx, &msg.author.name).await?; // msg.reply(&ctx, &msg.member.unwrap().nick.unwrap()).await?;...
x:
identifier_name
xmlReportBuilder.go
/*---------------------------------------------------------------- * Copyright (c) ThoughtWorks, Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE in the project root for license information. *----------------------------------------------------------------*/ package builder import ( "encodi...
(time int) string { return fmt.Sprintf("%.3f", float64(time)/1000.0) }
formatTime
identifier_name
xmlReportBuilder.go
/*---------------------------------------------------------------- * Copyright (c) ThoughtWorks, Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE in the project root for license information. *----------------------------------------------------------------*/ package builder import ( "encodi...
func (x *XmlBuilder) getFailureFromExecutionResult(name string, preHookFailure *gauge_messages.ProtoHookFailure, postHookFailure *gauge_messages.ProtoHookFailure, stepExecutionResult *gauge_messages.ProtoExecutionResult, prefix string) StepFailure { if len(name) > 0 { name = fmt.Sprintf("%s\n", name) } if preHo...
{ errInfo := []StepFailure{} for _, item := range items { stepInfo := StepFailure{Message: "", Err: ""} if item.GetItemType() == gauge_messages.ProtoItem_Step { preHookFailure := item.GetStep().GetStepExecutionResult().GetPreHookFailure() postHookFailure := item.GetStep().GetStepExecutionResult().GetPostHoo...
identifier_body
xmlReportBuilder.go
/*---------------------------------------------------------------- * Copyright (c) ThoughtWorks, Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE in the project root for license information. *----------------------------------------------------------------*/ package builder import ( "encodi...
ts := x.getTestSuite(result, hostName) if hasParseErrors(result.Errors) { ts.Failures++ ts.TestCases = append(ts.TestCases, getErrorTestCase(result)) } else { s := result.GetProtoSpec() ts.Failures += len(s.GetPreHookFailures()) + len(s.GetPostHookFailures()) for _, test := range result.GetProtoSpec().GetI...
hostName = hostname }
random_line_split
xmlReportBuilder.go
/*---------------------------------------------------------------- * Copyright (c) ThoughtWorks, Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE in the project root for license information. *----------------------------------------------------------------*/ package builder import ( "encodi...
failures = append(failures, fmt.Sprintf("[%s Error] %s", t, e.Message)) } return JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: getSpecName(result.GetProtoSpec()), Time: formatTime(int(result.GetExecutionTime())), Failure: &JUnitFailure{ Message: "Parse/Validation Errors"...
{ t = "Validation" }
conditional_block
index.js
// Xword, interactive Crossword app // Author: John Lynch // Date: May 2021 // File: xword/scripts/index.js // First, handle display of "About" data in a fixed modal overlay const aboutBox = document.getElementById(`about-box`); const aboutHideButton = document.getElementById(`hide-about`); const aboutLink = document....
0, 0, 0, 0, 0, false, false, false, false, 0, null); target.dispatchEvent(ev); }
let ev = document.createEvent("MouseEvents"); ev.initMouseEvent(eventType, true, true, window,
random_line_split
index.js
// Xword, interactive Crossword app // Author: John Lynch // Date: May 2021 // File: xword/scripts/index.js // First, handle display of "About" data in a fixed modal overlay const aboutBox = document.getElementById(`about-box`); const aboutHideButton = document.getElementById(`hide-about`); const aboutLink = document....
// Code to populate code block display of palette as // CSS vars and an array of hex colours as strings. const varSlots = codeBlock.getElementsByClassName(`code-list-item`); const varArray = document.getElementById(`code-item`); // ========================================================================== // Grid...
{ let [x0, y0, x1, y1] = [0, 0, 0, 0]; dragBar.onmousedown = dragMouseDown; function dragMouseDown(ev) { ev = ev || window.event; ev.preventDefault(); // get the mouse cursor position at startup: x1 = ev.clientX; y1 = ev.clientY; document.onmouseup = closeDr...
identifier_body
index.js
// Xword, interactive Crossword app // Author: John Lynch // Date: May 2021 // File: xword/scripts/index.js // First, handle display of "About" data in a fixed modal overlay const aboutBox = document.getElementById(`about-box`); const aboutHideButton = document.getElementById(`hide-about`); const aboutLink = document....
() { dragBar.innerText = `Contrast Info`; const col0 = palette[selectedColours[0]].style.backgroundColor; const col1 = palette[selectedColours[1]].style.backgroundColor; col0Box.style.backgroundColor = col0; col1Box.style.backgroundColor = col1; col0Box.style.color = getLuminance(col0) > 0.3 ? B...
displayContrastInfo
identifier_name
index.js
// Xword, interactive Crossword app // Author: John Lynch // Date: May 2021 // File: xword/scripts/index.js // First, handle display of "About" data in a fixed modal overlay const aboutBox = document.getElementById(`about-box`); const aboutHideButton = document.getElementById(`hide-about`); const aboutLink = document....
} // We only want the two most recent, or one if user changed between RGB and HSL groups. function setSwitches() { for (let i = 0; i < 6; i++) { let sliderIsActive = activeSliders.has(i); onSwitches[i].checked = sliderIsActive; offSwitches[i].checked = !sliderIsActive; switchboxes[...
{ for (let i = 0; i < W; i++) { let cell = document.createElement("div"); cell.x = i; cell.y = j; // Set some initial colours for the cells... cell.style.backgroundColor = setCellColour(i, j); colourGrid.appendChild(cell); } ...
conditional_block
haystack.rs
//! Haystacks. //! //! A *haystack* refers to any linear structure which can be split or sliced //! into smaller, non-overlapping parts. Examples are strings and vectors. //! //! ```rust //! let haystack: &str = "hello"; // a string slice (`&str`) is a haystack. //! let (a, b) = haystack.split_at(4); // it can b...
&'h str> { /// Reinterprets the string span as a byte-array span. #[inline] pub fn as_bytes(self) -> Span<&'h [u8]> { Span { haystack: self.haystack.as_bytes(), range: self.range, } } } impl<H: Haystack> Span<H> where H::Target: Hay // FIXME: RFC 2089 or 2289 { ...
aystack, range } } } impl<'h> Span<
identifier_body
haystack.rs
//! Haystacks. //! //! A *haystack* refers to any linear structure which can be split or sliced //! into smaller, non-overlapping parts. Examples are strings and vectors. //! //! ```rust //! let haystack: &str = "hello"; // a string slice (`&str`) is a haystack. //! let (a, b) = haystack.split_at(4); // it can b...
A::empty() } #[inline] unsafe fn split_around(self, range: Range<A::Index>) -> [Self; 3] { [ self.slice_unchecked(self.start_index()..range.start), self.slice_unchecked(range.clone()), self.slice_unchecked(range.end..self.end_index()), ] } #[i...
identifier_name
haystack.rs
//! Haystacks. //! //! A *haystack* refers to any linear structure which can be split or sliced //! into smaller, non-overlapping parts. Examples are strings and vectors. //! //! ```rust //! let haystack: &str = "hello"; // a string slice (`&str`) is a haystack. //! let (a, b) = haystack.split_at(4); // it can b...
&self, range: Range<<Self::Target as Hay>::Index>, subrange: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index>; } impl<H: Haystack> SpanBehavior for H where H::Target: Hay // FIXME: RFC 2089 or 2289 { #[inline] default fn take(&mut self) -> Self { ...
&self, range: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index>; fn do_restore_range(
random_line_split
googleMapsImplementation.ts
//autor janis dähne ///<reference path="../mapInterface.ts"/> ///<reference path="google.maps.d.ts"/> /* * some events a marker can listen for (many can also be used for the map too! e.g. mouse...) * see https://developers.google.com/maps/documentation/javascript/reference#Marker for all events */ class GoogleMapsEv...
private getNewEventId(): number { return this.eventCounter++; } }
random_line_split
googleMapsImplementation.ts
//autor janis dähne ///<reference path="../mapInterface.ts"/> ///<reference path="google.maps.d.ts"/> /* * some events a marker can listen for (many can also be used for the map too! e.g. mouse...) * see https://developers.google.com/maps/documentation/javascript/reference#Marker for all events */ class GoogleMapsEv...
/** * sets the new zoom of/for the map * @param newZoom the new zoom */ setZoom(newZoom: number): void { this.map.setZoom(newZoom); } /** * returns the current zoom */ getZoom(): number { return this.map.getZoom(); } /** * sets the center of the map * @param lat the latit...
this.parentElement.innerHTML = ""; this.parentElement.removeAttribute("style") this.map = null; this.markers = {}; //this.eventTokens = []; this.isDeleted = true; this.isDisplayed = false; this.isInitialized = false; }
identifier_body
googleMapsImplementation.ts
//autor janis dähne ///<reference path="../mapInterface.ts"/> ///<reference path="google.maps.d.ts"/> /* * some events a marker can listen for (many can also be used for the map too! e.g. mouse...) * see https://developers.google.com/maps/documentation/javascript/reference#Marker for all events */ class GoogleMapsEv...
ocation: LatLng, iconPath: string = "", displayOnMap: boolean = true, data: any = null): GoogleMapsMarker { var googleMarker: google.maps.Marker = new google.maps.Marker ({ position: new google.maps.LatLng(location.lat, location.lng), map: this.map, visible: displayOnMap, icon: ic...
dMarkerFromGeoLocation(l
identifier_name
context.go
package app import ( "context" "encoding/json" "net/url" "strings" "time" "github.com/google/uuid" "github.com/maxence-charriere/go-app/v9/pkg/errors" ) // Context is the interface that describes a context tied to a UI element. // // A context provides mechanisms to deal with the browser, the current page, //...
func (ctx uiContext) IsAppInstallable() bool { if Window().Get("goappIsAppInstallable").Truthy() { return Window().Call("goappIsAppInstallable").Bool() } return false } func (ctx uiContext) IsAppInstalled() bool { if Window().Get("goappIsAppInstalled").Truthy() { return Window().Call("goappIsAppInstalled").Boo...
}
random_line_split
context.go
package app import ( "context" "encoding/json" "net/url" "strings" "time" "github.com/google/uuid" "github.com/maxence-charriere/go-app/v9/pkg/errors" ) // Context is the interface that describes a context tied to a UI element. // // A context provides mechanisms to deal with the browser, the current page, //...
} func (ctx uiContext) Page() Page { return ctx.page } func (ctx uiContext) Dispatch(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Update, Source: ctx.Src(), Function: fn, }) } func (ctx uiContext) Defer(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Defer, Sou...
{ Window().Call("goappShowInstallPrompt") }
conditional_block
context.go
package app import ( "context" "encoding/json" "net/url" "strings" "time" "github.com/google/uuid" "github.com/maxence-charriere/go-app/v9/pkg/errors" ) // Context is the interface that describes a context tied to a UI element. // // A context provides mechanisms to deal with the browser, the current page, //...
func (ctx uiContext) Handle(actionName string, h ActionHandler) { ctx.Dispatcher().Handle(actionName, ctx.Src(), h) } func (ctx uiContext) NewAction(name string, tags ...Tagger) { ctx.NewActionWithValue(name, nil, tags...) } func (ctx uiContext) NewActionWithValue(name string, v any, tags ...Tagger) { var tagMap...
{ ctx.Dispatcher().Dispatch(Dispatch{ Mode: Defer, Source: ctx.Src(), Function: fn, }) }
identifier_body
context.go
package app import ( "context" "encoding/json" "net/url" "strings" "time" "github.com/google/uuid" "github.com/maxence-charriere/go-app/v9/pkg/errors" ) // Context is the interface that describes a context tied to a UI element. // // A context provides mechanisms to deal with the browser, the current page, //...
(fn func()) { ctx.Dispatcher().Emit(ctx.Src(), fn) } func (ctx uiContext) Reload() { if IsServer { return } ctx.Defer(func(ctx Context) { Window().Get("location").Call("reload") }) } func (ctx uiContext) Navigate(rawURL string) { ctx.Defer(func(ctx Context) { navigate(ctx.Dispatcher(), rawURL) }) } func...
Emit
identifier_name
tokio_ct.rs
use { crate :: { SpawnHandle, LocalSpawnHandle, JoinHandle, BlockingHandle } , std :: { fmt, rc::Rc, future::Future, convert::TryFrom } , tokio :: { task::LocalSet, runtime::{ Builder, Runtime, Handle, RuntimeFlavor } } , futures_task :: { FutureObj, LocalFut...
( &self, future: FutureObj<'static, ()> ) -> Result<(), SpawnError> { // We drop the tokio JoinHandle, so the task becomes detached. // drop( self.local.spawn_local(future) ); Ok(()) } } impl LocalSpawn for TokioCt { fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()> ) -> Result<(), SpawnErro...
spawn_obj
identifier_name
tokio_ct.rs
use { crate :: { SpawnHandle, LocalSpawnHandle, JoinHandle, BlockingHandle } , std :: { fmt, rc::Rc, future::Future, convert::TryFrom } , tokio :: { task::LocalSet, runtime::{ Builder, Runtime, Handle, RuntimeFlavor } } , futures_task :: { FutureObj, LocalFut...
} #[ cfg(all( feature = "timer", not(feature="tokio_timer" )) ) ] // #[ cfg_attr( nightly, doc(cfg(all( feature = "timer", feature = "tokio_ct" ))) ) ] // impl crate::Timer for TokioCt { fn sleep( &self, dur: std::time::Duration ) -> futures_core::future::BoxFuture<'static, ()> { Box::pin( futures_timer::Delay::...
let handle = self.local.spawn_local( future ); Ok( JoinHandle::tokio(handle) ) }
random_line_split
tokio_ct.rs
use { crate :: { SpawnHandle, LocalSpawnHandle, JoinHandle, BlockingHandle } , std :: { fmt, rc::Rc, future::Future, convert::TryFrom } , tokio :: { task::LocalSet, runtime::{ Builder, Runtime, Handle, RuntimeFlavor } } , futures_task :: { FutureObj, LocalFut...
} impl TokioCt { /// Create a new `TokioCt`. Uses a default current thread [`Runtime`] setting timers and io depending /// on the features enabled on _async_executors_. // pub fn new() -> Result<Self, TokioCtErr> { let mut builder = Builder::new_current_thread(); #[ cfg( feature = "tokio_io" ) ] // b...
{ match handle.runtime_flavor() { RuntimeFlavor::CurrentThread => Ok( Self { spawner: Spawner::Handle( handle ) , local: Rc::new( LocalSet::new() ) , }), _ => Err( handle ), } }
identifier_body
lib.rs
/*! Faster, growable buffering reader for when there's little to no need to modify data, nor to keep it alive past next read. `std::io::BufReader` works by copying data from its internal buffer into user-provided `Vec`/`String`, or, in case of `.lines()`, by emitting new heap-allocated `String` for each iteration. Whi...
} impl<R: Read, B: Buffer> BufRefReader<R, B> where Error: From<B::Error> { /// Creates buffered reader with default options. Look for [`BufRefReaderBuilder`](struct.BufRefReaderBuilder.html) for tweaks. pub fn new(src: R) -> Result<BufRefReader<R, B>, B::Error> { BufRefReaderBuilder::new(src) .build() } //...
{ unimplemented!() }
identifier_body
lib.rs
/*! Faster, growable buffering reader for when there's little to no need to modify data, nor to keep it alive past next read. `std::io::BufReader` works by copying data from its internal buffer into user-provided `Vec`/`String`, or, in case of `.lines()`, by emitting new heap-allocated `String` for each iteration. Whi...
Error: From<B::Error>, { // two spaces, three spaces, two spaces let mut r = BufRefReaderBuilder::new(&b" lorem ipsum "[..]) .capacity(4) .build::<B>() .unwrap(); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.re...
use std::fmt::Debug; fn read_until_empty_lines<B: Buffer>() where B::Error: Debug,
random_line_split
lib.rs
/*! Faster, growable buffering reader for when there's little to no need to modify data, nor to keep it alive past next read. `std::io::BufReader` works by copying data from its internal buffer into user-provided `Vec`/`String`, or, in case of `.lines()`, by emitting new heap-allocated `String` for each iteration. Whi...
() { read::<MmapBuffer>() } fn read_words<B: Buffer>(cap: usize, read: usize) where B::Error: Debug, Error: From<B::Error>, { let mut r = BufRefReaderBuilder::new(WORDS) .capacity(cap) .build::<B>() .unwrap(); let mut words = WORDS.chunks(read); while let Ok(Some(slice_buf)) = r.read(read) { l...
read_mmap
identifier_name
lrp_processor.go
package bulk import ( "crypto/tls" "errors" "net" "net/http" "os" "sync" "sync/atomic" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_3/typed/core/v1" "k8s.io/kubernetes/pkg/labels" "github.com/cloudfoundry-incubator/b...
func organizeSchedulingInfosByProcessGuid(list []*models.DesiredLRPSchedulingInfo) map[string]*models.DesiredLRPSchedulingInfo { result := make(map[string]*models.DesiredLRPSchedulingInfo) for _, l := range list { lrp := l result[lrp.ProcessGuid] = lrp } return result } func updateDesiredRequestDebugData(pr...
{ out := make(chan error) wg := sync.WaitGroup{} for _, ch := range channels { wg.Add(1) go func(c <-chan error) { for e := range c { out <- e } wg.Done() }(ch) } go func() { wg.Wait() close(out) }() return out }
identifier_body
lrp_processor.go
package bulk import ( "crypto/tls" "errors" "net" "net/http" "os" "sync" "sync/atomic" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_3/typed/core/v1" "k8s.io/kubernetes/pkg/labels" "github.com/cloudfoundry-incubator/b...
return dest, count } func mergeErrors(channels ...<-chan error) <-chan error { out := make(chan error) wg := sync.WaitGroup{} for _, ch := range channels { wg.Add(1) go func(c <-chan error) { for e := range c { out <- e } wg.Done() }(ch) } go func() { wg.Wait() close(out) }() return ...
count <- errorCount close(count) }()
random_line_split
lrp_processor.go
package bulk import ( "crypto/tls" "errors" "net" "net/http" "os" "sync" "sync/atomic" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_3/typed/core/v1" "k8s.io/kubernetes/pkg/labels" "github.com/cloudfoundry-incubator/b...
opts := api.ListOptions{ LabelSelector: pguidSelector, } logger.Debug("opts to list replication controller", lager.Data{"data": opts.LabelSelector.String()}) rcList, err := l.k8sClient.ReplicationControllers(api.NamespaceAll).List(opts) if err != nil { logger.Error("failed-getting-desired-lrps-from-kube", er...
{ logger.Error("failed-getting-desired-lrps-from-kube", err) return nil, err }
conditional_block
lrp_processor.go
package bulk import ( "crypto/tls" "errors" "net" "net/http" "os" "sync" "sync/atomic" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" v1core "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_3/typed/core/v1" "k8s.io/kubernetes/pkg/labels" "github.com/cloudfoundry-incubator/b...
( logger lager.Logger, cancel <-chan struct{}, missing <-chan []cc_messages.DesireAppRequestFromCC, invalidCount *int32, ) <-chan error { logger = logger.Session("create-missing-desired-lrps") errc := make(chan error, 1) go func() { defer close(errc) for { var desireAppRequests []cc_messages.DesireAppR...
createMissingDesiredLRPs
identifier_name
Main.go
// Однострочный комментарий /* Много строчный комментарий*/ package main import ( "fmt" // пакет в стандартной библиотеке Go "io/ioutil" // реализация функция ввода/вывода m "math" // импортировать math под локальным именем m "net/http" //веб сервер "strconv" // конвертирование типов в строки и обрат...
identifier_name
Main.go
// Однострочный комментарий /* Много строчный комментарий*/ package main import ( "fmt" // пакет в стандартной библиотеке Go "io/ioutil" // реализация функция ввода/вывода m "math" // импортировать math под локальным именем m "net/http" //веб сервер "strconv" // конвертирование типов в строки и обрат...
fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { // синтаксис с фигурными скобками это "литерал структуры". Он возвращает // проинициализированную структуру, а оператор := присваивает её p p := pair{3, 4} fmt.Println(p.String()) // вызов метода String у переменной p типа pair var i Stringer /...
полям p через точчку return
conditional_block
Main.go
// Однострочный комментарий /* Много строчный комментарий*/ package main import ( "fmt" // пакет в стандартной библиотеке Go "io/ioutil" // реализация функция ввода/вывода m "math" // импортировать math под локальным именем m "net/http" //веб сервер "strconv" // конвертирование типов в строки и обрат...
с Stringer func (p pair) String() string { // p в данном случае называют receiver-ом // Sprintf - ещё одна функция из пакета fmt // Обращение к полям p через точчку return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { // синтаксис с фигурными скобками это "литерал структуры". Он возвращает // проин...
ir реализует интерфей
identifier_body
Main.go
// Однострочный комментарий /* Много строчный комментарий*/ package main import ( "fmt" // пакет в стандартной библиотеке Go "io/ioutil" // реализация функция ввода/вывода m "math" // импортировать math под локальным именем m "net/http" //веб сервер "strconv" // конвертирование типов в строки и обрат...
learnVariadicParams("Learn", "learn", "learn again") } // функции могут иметь варьируемое количество параметров func learnVariadicParams(myStrings ...interface{}) { // вывести все параметры с помощью итерации for _, param := range myStrings { fmt.Println("param:", param) } // передать все варьируемые параметр...
// Функция в пакете fmt сами всегда вызывают метод String у объектов для // получения их строкового представления fmt.Println(p) // вывод такой-же, как и выше fmt.Println(i) // вывод такой-же, как и выше
random_line_split
descriptive_stats_04022018.py
# -*- coding: utf-8 -*- """ Created on Tue Mar 20 11:20:23 2018 @author: wyatt """ import pandas as pd import numpy as np import feather import matplotlib.pyplot as plt # Assemble data # Load national file of all single-family parcels that have ever transacted Main = feather.read_dataframe(r'G:\Zillow\...
isol.to_csv(r'G:\Zillow\Created\Figures\isolation_index.csv') # PROPERTY CHARACTERISTICS ############################################################################### ############################################################################### # Load transactions used for regressions trans = feather.r...
chars['{}_hoa_wt'.format(color)] = chars['{}'.format(color)] * chars['hoa_geoid'] chars['{}_nonhoa_wt'.format(color)] = chars['{}'.format(color)] * (1-chars['hoa_geoid']) isol_hoa = np.average(chars[colors_geoid], axis=0, weights=chars['{}_hoa_wt'.format(color)]) isol_nonhoa = np.average(c...
conditional_block
descriptive_stats_04022018.py
# -*- coding: utf-8 -*- """ Created on Tue Mar 20 11:20:23 2018 @author: wyatt """ import pandas as pd import numpy as np import feather import matplotlib.pyplot as plt # Assemble data # Load national file of all single-family parcels that have ever transacted Main = feather.read_dataframe(r'G:\Zillow\...
chars = Main[['geoid', 'hoa_geoid', 'records_n']].dropna().drop_duplicates() chars = chars[chars['records_n']>=30] # Merge to Census data # Load data census_chars = pd.read_csv(r'C:\Users\wyatt\Research\Zillow\IPUMS_blockgrp_07012017.csv') census_chars = census_chars[census_chars['total_pop']>0] # Ref...
# Create summary measures by geoid Main['geoid'] = Main['PropertyAddressCensusTractAndBlock'].astype(str).str[:9] + Main['PropertyAddressCensusTractAndBlock'].astype(str).str[10:13] Main['records_n'] = Main.groupby(['geoid'])['RowID'].transform(pd.Series.count) Main['hoa_geoid'] = Main.groupby(['geoid'])['hoa'].tr...
random_line_split
game_engine.py
# standard libraries import os import csv import random import json # game # 3rd party libraries import pygame from pygame.locals import * from pygame.compat import geterror # my libraries from game_NPCs import Enemy from game_NPCs import Friendly from game_entities import Chest from game_entities...
(y - self.player.y_pos + self.screen_y_buffer) * 32)) elif self.current_map[y][x] > 20: self.screen.blit(self.floor_2[0], ((x - self.player.x_pos + self.screen_x_buffer) * 32, (y - self.player.y_pos + self.screen_y_buffer) * 32)) elif self.current_map[y][x] > 0: s...
(y - self.player.y_pos + self.screen_y_buffer) * 32)) elif self.current_map[y][x] > 60: self.screen.blit(self.wall[0], ((x - self.player.x_pos + self.screen_x_buffer) * 32,
random_line_split
game_engine.py
# standard libraries import os import csv import random import json # game # 3rd party libraries import pygame from pygame.locals import * from pygame.compat import geterror # my libraries from game_NPCs import Enemy from game_NPCs import Friendly from game_entities import Chest from game_entities...
# adjust game to new resolution self.screen_resolution = (self.screen_size[0] * 32, self.screen_size[1] * 32) self.screen_x_buffer = int((self.screen_size[0]-1)/2) self.screen_y_buffer = int((self.screen_size[1]-1)/2) self.screen = pygame.display.set_mode(self.screen_resolution) ...
if event.key == K_1: self.screen_size = resolution_672_480 res_menu = False elif event.key == K_2: self.screen_size = resolution_1056_608 res_menu = False elif event.key == K_3: self.screen_size = resolution_1440_736 res_menu = False
conditional_block
game_engine.py
# standard libraries import os import csv import random import json # game # 3rd party libraries import pygame from pygame.locals import * from pygame.compat import geterror # my libraries from game_NPCs import Enemy from game_NPCs import Friendly from game_entities import Chest from game_entities...
# Class Level # this stores the information for a level in one class # this class should be treated like a singleton class Level(object): _map_name = None _map = [] _object_matrix = [] object_list = [] _json = {} def __init__(self): self._map = None def __load_json(self, file_name): with o...
__instance = None @staticmethod def getInstance(): if Wall.__instance == None: Wall() return Wall.__instance def __init__(self): if Wall.__instance != None: raise Exception("this class is a singleton. use getinstance() instead") else: Wall.__instance = self
identifier_body
game_engine.py
# standard libraries import os import csv import random import json # game # 3rd party libraries import pygame from pygame.locals import * from pygame.compat import geterror # my libraries from game_NPCs import Enemy from game_NPCs import Friendly from game_entities import Chest from game_entities...
(self): pygame.init() self.font_1 = pygame.font.Font('fonts/victor-pixel.ttf', 32) pygame.key.set_repeat(self.key_delay, self.key_repeat) flags = DOUBLEBUF | HWACCEL self.screen = pygame.display.set_mode(self.screen_resolution,flags) pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP]) # setup disp...
__init__
identifier_name
mod.rs
use std::collections::HashMap; use std::ptr::NonNull; use std::fmt::Debug; use once_cell::sync::OnceCell; use bit_vec::BitVec; use crate::tag::{TagType, TagTypeKey}; use crate::util::OpaquePtr; mod state; mod property; mod util; pub use state::*; pub use property::*; pub use util::*; /// A basic block defined by ...
/// Get the block state from the given save ID. pub fn get_state_from(&self, sid: u32) -> Option<&'static BlockState> { self.ordered_states.get(sid as usize).copied() } /// Get the default state from the given block name. pub fn get_block_from_name(&self, name: &str) -> Option<&'static Blo...
/// Get the save ID from the given state. pub fn get_sid_from(&self, state: &'static BlockState) -> Option<u32> { let (_, block_offset) = *self.block_to_indices.get(&state.get_block().get_key())?; Some(block_offset + state.get_index() as u32) }
random_line_split
mod.rs
use std::collections::HashMap; use std::ptr::NonNull; use std::fmt::Debug; use once_cell::sync::OnceCell; use bit_vec::BitVec; use crate::tag::{TagType, TagTypeKey}; use crate::util::OpaquePtr; mod state; mod property; mod util; pub use state::*; pub use property::*; pub use util::*; /// A basic block defined by ...
(&mut self, tag_type: &'static TagType) { self.tag_stores.insert(tag_type.get_key(), TagStore::Small(Vec::new())); } /// Set or unset a tag to some blocks. pub fn set_blocks_tag<I>(&mut self, tag_type: &'static TagType, enabled: bool, blocks: I) -> Result<(), ()> where I: IntoIterator<I...
register_tag_type
identifier_name
mod.rs
use std::collections::HashMap; use std::ptr::NonNull; use std::fmt::Debug; use once_cell::sync::OnceCell; use bit_vec::BitVec; use crate::tag::{TagType, TagTypeKey}; use crate::util::OpaquePtr; mod state; mod property; mod util; pub use state::*; pub use property::*; pub use util::*; /// A basic block defined by ...
/// Get the tag state on specific block, returning false if unknown block or tag type. pub fn has_block_tag(&self, block: &'static Block, tag_type: &'static TagType) -> bool { match self.tag_stores.get(&tag_type.get_key()) { None => false, Some(store) => { match...
{ const MAX_SMALL_LEN: usize = 8; let store = self.tag_stores.get_mut(&tag_type.get_key()).ok_or(())?; for block in blocks { if let TagStore::Small(vec) = store { let idx = vec.iter().position(move |&b| b == block); if enabled { ...
identifier_body
convert.py
#!/usr/bin/env python3 import argparse import docx2pdf # type: ignore import docx # type: ignore import fnmatch import logging import os import pyqrcode # type: ignore import re import shutil import sys import yaml import zipfile import xml.etree.ElementTree as ElTree from typing import Any, Dict, Generator, List, T...
def sort_keys_longest_to_shortest(replacement_dict: Dict[str, str]) -> List[Tuple[str, str]]: new_list = list((k, v) for k, v in replacement_dict.items()) return sorted(new_list, key=lambda s: len(s[0]), reverse=True) def remove_short_keys(replacement_dict: Dict[str, str], min_length: int = 8) -> Dict[str, s...
gging.basicConfig( format="%(asctime)s %(filename)s | %(levelname)s | %(funcName)s | %(message)s", ) if convert_vars.args.debug: logging.getLogger().setLevel(logging.DEBUG) else: logging.getLogger().setLevel(logging.INFO)
identifier_body
convert.py
#!/usr/bin/env python3 import argparse import docx2pdf # type: ignore import docx # type: ignore import fnmatch import logging import os import pyqrcode # type: ignore import re import shutil import sys import yaml import zipfile import xml.etree.ElementTree as ElTree from typing import Any, Dict, Generator, List, T...
styles = [] if convert_vars.args.style.lower() == "all": for style in convert_vars.STYLE_CHOICES: if style != "all": styles.append(style) elif convert_vars.args.style == "": styles.append("static") else: styles.append(convert_vars.args.style) retur...
def get_valid_styles() -> List[str]:
random_line_split
convert.py
#!/usr/bin/env python3 import argparse import docx2pdf # type: ignore import docx # type: ignore import fnmatch import logging import os import pyqrcode # type: ignore import re import shutil import sys import yaml import zipfile import xml.etree.ElementTree as ElTree from typing import Any, Dict, Generator, List, T...
(k: str, v: str, el_text: str) -> str: reg_str: str = "^(OWASP SCP|OWASP ASVS|OWASP AppSensor|CAPEC|SAFECODE)\u2028" + k.replace("$", "\\$").strip() + "$" if re.match(reg_str, el_text.strip()): pretext = el_text[: el_text.find("\u2028")] v_new = v if len(v) + len(pretext) > 60: ...
get_replacement_mapping_value
identifier_name
convert.py
#!/usr/bin/env python3 import argparse import docx2pdf # type: ignore import docx # type: ignore import fnmatch import logging import os import pyqrcode # type: ignore import re import shutil import sys import yaml import zipfile import xml.etree.ElementTree as ElTree from typing import Any, Dict, Generator, List, T...
p.runs[0].text = runs_text logging.debug(" --- finished replacing text in doc") return doc def replace_text_in_xml_file(filename: str, replacement_dict: Dict[str, str]) -> None: if convert_vars.making_template: replacement_values = sort_keys_longest_to_shortest(replacement_dict...
runs[i].text = ""
conditional_block
lib.rs
extern crate num_bigint; use num_bigint::BigInt; use poseidon_rs::Poseidon; use wasm_bindgen::prelude::*; /////////////////////////////////////////////////////////////////////////////// // EXPORTED FUNCTIONS FUNCTIONS /////////////////////////////////////////////////////////////////////////////// #[wasm_bindgen] pub ...
/////////////////////////////////////////////////////////////////////////////// // TESTS /////////////////////////////////////////////////////////////////////////////// #[cfg(test)] mod tests { use super::*; use num_bigint::{Sign, ToBigInt}; #[test] fn should_hash_strings() { let str_claim =...
{ let mut claim_bytes = num.to_bytes_be().1; while claim_bytes.len() < 32 { claim_bytes = [&[0], &claim_bytes[..]].concat(); } claim_bytes }
identifier_body
lib.rs
extern crate num_bigint; use num_bigint::BigInt; use poseidon_rs::Poseidon; use wasm_bindgen::prelude::*; /////////////////////////////////////////////////////////////////////////////// // EXPORTED FUNCTIONS FUNCTIONS /////////////////////////////////////////////////////////////////////////////// #[wasm_bindgen] pub ...
() { let hex_claim = "0x045a126cbbd3c66b6d542d40d91085e3f2b5db3bbc8cda0d59615deb08784e4f833e0bb082194790143c3d01cedb4a9663cb8c7bdaaad839cb794dd309213fcf30"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "nGOYvS4aqqUVAT9YjWcUzA89DlHPWaooNpBTStOaHRA="); let hex_claim = ...
should_hash_hex_claims
identifier_name
lib.rs
extern crate num_bigint; use num_bigint::BigInt; use poseidon_rs::Poseidon; use wasm_bindgen::prelude::*; /////////////////////////////////////////////////////////////////////////////// // EXPORTED FUNCTIONS FUNCTIONS /////////////////////////////////////////////////////////////////////////////// #[wasm_bindgen] pub ...
let hex_claim = "0x043f10ff1b295bf4d2f24c40c93cce04210ae812dd5ad1a06d5dafd9a2e18fa1247bdf36bef6a9e45e97d246cfb8a0ab25c406cf6fe7569b17e83fd6d33563003a"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "CCxtK0qT7cTxCS7e4uONSHcPQdbQzBqrC3GQvFz4KwA="); let len = base64::deco...
assert_eq!(len, 32);
random_line_split
OutMMOperationCtrl.js
define([ 'app/app','service/Purc','service/SupportServices' ], function(app) { app.register.controller('OutMMOperationCtrl',['$scope', '$http', '$rootScope', '$location', '$filter','$stateParams','$modal','toaster', 'SupportUtil','OutOper','Ring', 'Online','ngTableParams', '$q','BatchOper', function($scope, $http, $ro...
e};} } }); modalInstance.result.then(function(s){ if(s) {//判断数量是否需要拆分 OutOper.ifNeedBatch({},{bar_code:$scope.bi_barcode,pr_fbzs:$scope.pr_fbzs, whcode:$scope.order.PI_WHCODE},function(data){ },function(res){ if(res.data.exceptionInfo.indexOf('拆批') >=0){ ...
boxcode,"bi_outboxcode")){ toaster.pop('error',"条码所在的箱号在已采集列表中存在!"); return ; } }else if(message.isMsd){//湿敏元件弹出显示湿敏元件的相关记录 MSDlog //拆分湿敏元件提示剩余寿命等信息 var modalInstance = $modal.open({ templateUrl: 'resources/tpl/output/msdConfirm.html', controller: 'SplitModalCtrl', ...
conditional_block
OutMMOperationCtrl.js
define([ 'app/app','service/Purc','service/SupportServices' ], function(app) { app.register.controller('OutMMOperationCtrl',['$scope', '$http', '$rootScope', '$location', '$filter','$stateParams','$modal','toaster', 'SupportUtil','OutOper','Ring', 'Online','ngTableParams', '$q','BatchOper', function($scope, $http, $ro...
defer.reject(data.exceptionInfo); }else defer.resolve(data.message); }, function(response){ if(response.status == 0){ //无网络错误 Online.setOnline(false);//修改网络状态 toaster.pop('error', '失败',"网络连接不可用,请稍后再试"); } defer.reject(response.data.exceptionInfo); }); }; v...
} var checkBar = function(defer) { OutOper.checkOutqty({},{pi_id:$scope.order.PI_ID,pd_id:$scope.pd_id,pr_fbzs:$scope.pr_fbzs, barcode:$scope.bi_barcode, whcode:$scope.order.PI_WHCODE,prodcode:$scope.bi_prodcode}, function(data){ if(data.exceptionInfo){
random_line_split
cronjob.go
package cronjob import ( "context" "encoding/json" "strconv" "time" "github.com/douyu/juno/internal/app/core" "github.com/douyu/juno/internal/pkg/service/clientproxy" "github.com/douyu/juno/pkg/model/db" "github.com/douyu/juno/pkg/model/view" "github.com/douyu/jupiter/pkg/store/gorm" "github.com/douyu/jupit...
Job var timers = make([]db.CronJobTimer, len(params.Timers)) var oldTimers []db.CronJobTimer for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, ...
b.Cron
identifier_name
cronjob.go
package cronjob import ( "context" "encoding/json" "strconv" "time" "github.com/douyu/juno/internal/app/core" "github.com/douyu/juno/internal/pkg/service/clientproxy" "github.com/douyu/juno/pkg/model/db" "github.com/douyu/juno/pkg/model/view" "github.com/douyu/jupiter/pkg/store/gorm" "github.com/douyu/jupit...
page = 1 // from 1 on } pageSize := params.PageSize if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize query := j.db.Model(&db.CronJob{}) if params.Enable != nil { query = query.Where("enable = ?", *params.Enable) } if params.Name != nil { query = query.Where("name like ?", "%"+*para...
if page == 0 {
random_line_split
cronjob.go
package cronjob import ( "context" "encoding/json" "strconv" "time" "github.com/douyu/juno/internal/app/core" "github.com/douyu/juno/internal/pkg/service/clientproxy" "github.com/douyu/juno/pkg/model/db" "github.com/douyu/juno/pkg/model/view" "github.com/douyu/jupiter/pkg/store/gorm" "github.com/douyu/jupit...
obPayload, node) if err != nil { tx.Rollback() return err } } return tx.Commit().Error } // ListTask 任务列表 func (j *CronJob) ListTask(params view.ReqQueryTasks) (list []view.CronTask, pagination view.Pagination, err error) { var tasks []db.CronTask page := params.Page if page == 0 { page = 1 } page...
err = j.dispatcher.dispatchOnceJob(j
conditional_block
cronjob.go
package cronjob import ( "context" "encoding/json" "strconv" "time" "github.com/douyu/juno/internal/app/core" "github.com/douyu/juno/internal/pkg/service/clientproxy" "github.com/douyu/juno/pkg/model/db" "github.com/douyu/juno/pkg/model/view" "github.com/douyu/jupiter/pkg/store/gorm" "github.com/douyu/jupit...
uint, params view.CronJob) (err error) { var timers = make([]db.CronJobTimer, len(params.Timers)) var job = db.CronJob{ Uid: uid, Name: params.Name, AppName: params.AppName, Env: params.Env, Zone: params.Zone, Timeout: params.Timeout, RetryCount: para...
if page == 0 { page = 1 // from 1 on } pageSize := params.PageSize if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize query := j.db.Model(&db.CronJob{}) if params.Enable != nil { query = query.Where("enable = ?", *params.Enable) } if params.Name != nil { query = query.Where("name lik...
identifier_body
config.go
package configlib import ( "bytes" "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" homedir "github.com/mitchellh/go-homedir" log "github.com/sirupsen/logrus" "github.com/spf13/afero" "github.com/spf13/viper" "github.com/metrumresearchgroup/pkgr/cran" "github.com/metrumres...
// IsCustomizationSet ... func IsCustomizationSet(key string, elems []interface{}, elem string) bool { for _, v := range elems { for k, iv := range v.(map[interface{}]interface{}) { if k == elem { for k2 := range iv.(map[interface{}]interface{}) { if k2 == key { return true } } } } ...
{ // should be one of Debug,Info,Warn,Error,Fatal,Panic viper.SetDefault("loglevel", "info") // path to R on system, defaults to R in path viper.SetDefault("rpath", "R") // setting this to GOMAXPROCS(0) because NumCPU() won't work well with the scheduler. viper.SetDefault("threads", runtime.GOMAXPROCS(0)) }
identifier_body
config.go
package configlib import ( "bytes" "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" homedir "github.com/mitchellh/go-homedir" log "github.com/sirupsen/logrus" "github.com/spf13/afero" "github.com/spf13/viper" "github.com/metrumresearchgroup/pkgr/cran" "github.com/metrumres...
return expanded } /// For a list of repos, expand the ~ at the beginning of each path to the home directory. /// consider any problems a fatal error. func expandTildes(paths []string) []string { var expanded []string for _, p := range paths { newPath := expandTilde(p) expanded = append(expanded, newPath) } r...
{ log.WithFields(log.Fields{ "path": p, "error": err, }).Fatal("problem parsing config file -- could not expand path") }
conditional_block
config.go
package configlib import ( "bytes" "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" homedir "github.com/mitchellh/go-homedir" log "github.com/sirupsen/logrus" "github.com/spf13/afero" "github.com/spf13/viper" "github.com/metrumresearchgroup/pkgr/cran" "github.com/metrumres...
return library } // loadConfigFromPath loads pkc configuration into the global Viper func loadConfigFromPath(configFilename string) error { if configFilename == "" { configFilename = "pkgr.yml" } viper.SetEnvPrefix("pkgr") err := viper.BindEnv("rpath") if err != nil { log.Fatalf("error binding env: %s\n", er...
if library == "" { log.Fatal("must specify either a Lockfile Type or Library path") }
random_line_split
config.go
package configlib import ( "bytes" "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" homedir "github.com/mitchellh/go-homedir" log "github.com/sirupsen/logrus" "github.com/spf13/afero" "github.com/spf13/viper" "github.com/metrumresearchgroup/pkgr/cran" "github.com/metrumres...
(lockfileType string, rpath string, rversion cran.RVersion, platform string, library string) string { switch lockfileType { case "packrat": library = filepath.Join("packrat", "lib", packratPlatform(platform), rversion.ToFullString()) case "renv": var err error library, err = getRenvLibrary(rpath) if err != n...
getLibraryPath
identifier_name
groups.component.ts
import { HttpErrorResponse } from '@angular/common/http'; import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { MessageService } from 'primeng/api'; import { Subscription } from 'rxjs'; import { ThemeDataS...
primaryColor: string = ''; accentColor: string = ''; warnColor = ''; sheetMode: SheetMode = SheetMode.Closed; fields: DetailedField[]; title: string = 'Group'; userName: string; userToken: any; private memberID: string; sysAdmin: boolean = false; disableSaveButton: boolean = false; showBlocks: ...
name: string, description: string }; deletionState: boolean = false;
random_line_split
groups.component.ts
import { HttpErrorResponse } from '@angular/common/http'; import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { MessageService } from 'primeng/api'; import { Subscription } from 'rxjs'; import { ThemeDataS...
(): void { this.sheetMode = SheetMode.Closed; this.disableSaveButton = false; } editSheet(): void { this.sheetMode = SheetMode.Edit; } ngOnDestroy(): void { this.filterService.ClearSelectionEmitter.emit(true); this.subscriptions.unsubscribe(); this.subscriptionHotkey.forEach((sub: Subs...
closeSheet
identifier_name
groups.component.ts
import { HttpErrorResponse } from '@angular/common/http'; import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { MessageService } from 'primeng/api'; import { Subscription } from 'rxjs'; import { ThemeDataS...
}); this.subscriptions.add(this.route.paramMap.subscribe((params: ParamMap) => { this.memberID = this.authService.getUserID(); if (params.get('showBlocks') && params.get('showBlocks').toLowerCase() === 'true') { this.groupDataService.getAllBlockingGroupsOfUser(this.memberID).then((value: B...
{ this.themeDataService.getThemeByID(value).then(value => { if (value !== null) { let color: string = value.colors; let parts = color.split('_'); this.primaryColor = parts[0]; this.accentColor = parts[1]; this.warnColor = parts[2]; ...
conditional_block
groups.component.ts
import { HttpErrorResponse } from '@angular/common/http'; import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { MessageService } from 'primeng/api'; import { Subscription } from 'rxjs'; import { ThemeDataS...
closeSheet(): void { this.sheetMode = SheetMode.Closed; this.disableSaveButton = false; } editSheet(): void { this.sheetMode = SheetMode.Edit; } ngOnDestroy(): void { this.filterService.ClearSelectionEmitter.emit(true); this.subscriptions.unsubscribe(); this.subscriptionHotkey.forE...
{ this.disableSaveButton = false; let id: string; if (this.group) { id = this.group.id; } this.sheetMode = DetailedSheetUtils.toggle(id, data.entity.id, this.sheetMode, data.mode); this.group = { id: data.entity.id, description: data.entity.description, name: data.entity.name }; ...
identifier_body
genjobs.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
func main() { flag.Parse() // default to $PWD/prow/config.yaml pwd, err := os.Getwd() if err != nil { log.Fatalf("Failed to get $PWD: %v", err) } if *configPath == "" { *configPath = pwd + "/../../prow/config.yaml" } if *jobsPath == "" { *jobsPath = pwd + "/../" } if *outputPath == "" { *outputPath ...
{ // fallback to copying the file instead src, err := os.Open(srcPath) if err != nil { return err } dst, err := os.OpenFile(destPath, os.O_WRONLY, 0666) if err != nil { return err } _, err = io.Copy(dst, src) if err != nil { return err } dst.Sync() dst.Close() src.Close() return nil }
identifier_body
genjobs.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
// NOTE: this needs to be before the bare -- and then bootstrap args so we prepend it container.Args = append([]string{"--ssh=/etc/ssh-security/ssh-security"}, container.Args...) // check for scenario specific tweaks // NOTE: jobs are remapped to their original name in bootstrap to de-dupe config scenario ...
{ if arg == "--" { endsWithScenarioArgs = true // handle --repo substitution for main repo } else if arg == "--repo=k8s.io/kubernetes" || strings.HasPrefix(arg, "--repo=k8s.io/kubernetes=") || arg == "--repo=k8s.io/$(REPO_NAME)" || strings.HasPrefix(arg, "--repo=k8s.io/$(REPO_NAME)=") { container.Arg...
conditional_block
genjobs.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
needStagingFlag := false isGCPe2e := false for i, arg := range container.Args { if arg == "--" { endsWithScenarioArgs = true // handle --repo substitution for main repo } else if arg == "--repo=k8s.io/kubernetes" || strings.HasPrefix(arg, "--repo=k8s.io/kubernetes=") || arg == "--repo=k8s.io/$(REPO...
random_line_split
genjobs.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
() { flag.Parse() // default to $PWD/prow/config.yaml pwd, err := os.Getwd() if err != nil { log.Fatalf("Failed to get $PWD: %v", err) } if *configPath == "" { *configPath = pwd + "/../../prow/config.yaml" } if *jobsPath == "" { *jobsPath = pwd + "/../" } if *outputPath == "" { *outputPath = pwd + "/g...
main
identifier_name
UserRole.ts
class UserRole extends BaseSystem { /** 可更换的装备 */ private canChangeEquips: boolean[][]; public static oneKeyOpenLevel: number = 60; public constructor() { super(); //待改 this.canChangeEquips = [[], [], []]; this.observe(UserBag.ins().postItemChange, this.startCheckHaveCan);//道具变更 this.observe(UserBag.in...
= role.getExRingsData(0); let ring0Config: ExRing0Config = GlobalConfig[`ExRing${0}Config`][lv]; if (lv >= 1) return false; if (ring0Config) { costNum = ring0Config.cost; itemId = GlobalConfig.ExRingConfig[0].costItem; } break; case 1: lv = role.getExRingsData(1); let ring1...
lv
identifier_name
UserRole.ts
class UserRole extends BaseSystem { /** 可更换的装备 */ private canChangeEquips: boolean[][]; public static oneKeyOpenLevel: number = 60; public constructor() { super(); //待改 this.canChangeEquips = [[], [], []]; this.observe(UserBag.ins().postItemChange, this.startCheckHaveCan);//道具变更 this.observe(UserBag.in...
ber = 0; switch (type) { case 0: lv = role.getExRingsData(0); let ring0Config: ExRing0Config = GlobalConfig[`ExRing${0}Config`][lv]; if (lv >= 1) return false; if (ring0Config) { costNum = ring0Config.cost; itemId = GlobalConfig.ExRingConfig[0].costItem; } break; case 1: ...
break; } } return isReturn; } /** * 角色提示 */ public roleHint(type: number): boolean { let len: number = SubRoles.ins().subRolesLen; let flag: boolean = false; for (let i: number = 0; i < len; i++) { let role: Role = SubRoles.ins().getSubRoleByIndex(i); flag = this.roleHintCheck(role, type)...
identifier_body
UserRole.ts
class UserRole extends BaseSystem { /** 可更换的装备 */ private canChangeEquips: boolean[][]; public static oneKeyOpenLevel: number = 60; public constructor() { super(); //待改 this.canChangeEquips = [[], [], []]; this.observe(UserBag.ins().postItemChange, this.startCheckHaveCan);//道具变更 this.observe(UserBag.in...
let shieldStageConfig: LoongSoulStageConfig = GlobalConfig.ShieldStageConfig[role.loongSoulData.stage]; if (shieldConfig) { costNum = shieldStageConfig.normalCost; itemId = shieldConfig.itemId; } break; case 5: lv = role.jingMaiData.level; let jingMaiConfig: JingMaiLevelConfig = GlobalC...
le.shieldData.level; let shieldConfig: ShieldConfig = GlobalConfig.ShieldConfig[lv];
conditional_block
UserRole.ts
class UserRole extends BaseSystem { /** 可更换的装备 */ private canChangeEquips: boolean[][]; public static oneKeyOpenLevel: number = 60; public constructor() { super(); //待改 this.canChangeEquips = [[], [], []]; this.observe(UserBag.ins().postItemChange, this.startCheckHaveCan);//道具变更 this.observe(UserBag.in...
itemId = shieldConfig.itemId; } break; case 5: lv = role.jingMaiData.level; let jingMaiConfig: JingMaiLevelConfig = GlobalConfig.JingMaiLevelConfig[lv]; if (jingMaiConfig) { costNum = jingMaiConfig.count; itemId = jingMaiConfig.itemId; } break; } if (costNum) { itemN...
lv += role.shieldData.level; let shieldConfig: ShieldConfig = GlobalConfig.ShieldConfig[lv]; let shieldStageConfig: LoongSoulStageConfig = GlobalConfig.ShieldStageConfig[role.loongSoulData.stage]; if (shieldConfig) { costNum = shieldStageConfig.normalCost;
random_line_split
reader.rs
//a Imports use crate::{Char, Error, Result, StreamPosition}; //a Constants /// [BUFFER_SIZE] is the maximum number of bytes held in the UTF-8 /// character reader from the incoming stream. The larger the value, /// the larger the data read requests from the stream. This value must be larger than `BUFFER_SLACK`. /// ...
}, } } } //zz All done } //ip Iterator for Reader - iterate over characters // // allow missing doc code examples for this as it *has* an example but // rustdoc does not pick it up. #[allow(missing_doc_code_examples)] impl <'a, R:std::io::Read> Iterator for &'a mut Reader...
{ // no valid data - check it is just incomplete, or an actual error match e.error_len() { None => { // incomplete UTF-8 fetch more match self.fetch_input()? { 0 => { // ... and eof reached when incom...
conditional_block
reader.rs
//a Imports use crate::{Char, Error, Result, StreamPosition}; //a Constants /// [BUFFER_SIZE] is the maximum number of bytes held in the UTF-8 /// character reader from the incoming stream. The larger the value, /// the larger the data read requests from the stream. This value must be larger than `BUFFER_SLACK`. /// ...
type Item = Result<char>; //mp next - return next character or None if end of file fn next(&mut self) -> Option<Self::Item> { match self.next_char() { Ok(Char::Char(ch)) => Some(Ok(ch)), Ok(_) => None, Err(x) => Some(Err(x)), } ...
impl <'a, R:std::io::Read> Iterator for &'a mut Reader<R> { // we will be counting with usize
random_line_split
reader.rs
//a Imports use crate::{Char, Error, Result, StreamPosition}; //a Constants /// [BUFFER_SIZE] is the maximum number of bytes held in the UTF-8 /// character reader from the incoming stream. The larger the value, /// the larger the data read requests from the stream. This value must be larger than `BUFFER_SLACK`. /// ...
(&self) -> bool { self.start == self.end } //mp borrow_buffer /// Borrow the data held in the [Reader]'s buffer. pub fn borrow_buffer(&self) -> &[u8] { &self.current[self.start..self.end] } //mp borrow_pos /// Borrow the stream position of the next character to be returned ...
buffer_is_empty
identifier_name
reader.rs
//a Imports use crate::{Char, Error, Result, StreamPosition}; //a Constants /// [BUFFER_SIZE] is the maximum number of bytes held in the UTF-8 /// character reader from the incoming stream. The larger the value, /// the larger the data read requests from the stream. This value must be larger than `BUFFER_SLACK`. /// ...
//zz All done }
{ match self.next_char() { Ok(Char::Char(ch)) => Some(Ok(ch)), Ok(_) => None, Err(x) => Some(Err(x)), } }
identifier_body
address.rs
use bech32::{u5, FromBase32, ToBase32}; use extended_primitives::Buffer; use handshake_encoding::{Decodable, DecodingError, Encodable}; use std::fmt; use std::str::FromStr; #[cfg(feature = "json")] use encodings::ToHex; #[cfg(feature = "json")] use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Vis...
} struct AddressVisitor; impl<'de> Visitor<'de> for AddressVisitor { type Value = Address; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct Address") } fn visit_seq<V>(self, mut s...
{ struct FieldVisitor; impl<'de> Visitor<'de> for FieldVisitor { type Value = Field; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("`version` or `hash`") } ...
identifier_body
address.rs
use bech32::{u5, FromBase32, ToBase32}; use extended_primitives::Buffer; use handshake_encoding::{Decodable, DecodingError, Encodable}; use std::fmt; use std::str::FromStr; #[cfg(feature = "json")] use encodings::ToHex; #[cfg(feature = "json")] use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Vis...
#[cfg(feature = "json")] impl serde::Serialize for Address { fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> { let mut state = s.serialize_struct("Address", 2)?; state.serialize_field("version", &self.version)?; state.serialize_field("hash", &self.hash...
} (version[0].to_u8(), hash) }
random_line_split
address.rs
use bech32::{u5, FromBase32, ToBase32}; use extended_primitives::Buffer; use handshake_encoding::{Decodable, DecodingError, Encodable}; use std::fmt; use std::str::FromStr; #[cfg(feature = "json")] use encodings::ToHex; #[cfg(feature = "json")] use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Vis...
version = Some(map.next_value()?); } Field::Hash => { if hash.is_some() { return Err(de::Error::duplicate_field("hash")); } has...
{ return Err(de::Error::duplicate_field("version")); }
conditional_block
address.rs
use bech32::{u5, FromBase32, ToBase32}; use extended_primitives::Buffer; use handshake_encoding::{Decodable, DecodingError, Encodable}; use std::fmt; use std::str::FromStr; #[cfg(feature = "json")] use encodings::ToHex; #[cfg(feature = "json")] use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Vis...
(&self) -> bool { self.version == 31 } pub fn is_unspendable(&self) -> bool { self.is_null_data() } pub fn to_bech32(&self) -> String { //Also todo this should probably just be in toString, and should use writers so that we //don't allocate. //@todo this should ...
is_null_data
identifier_name
path.py
""" path finding implementation 1) For each position on the map, create a node representing the position. 2) For each NPC/item, mark nearby nodes as members of that NPC's threat zone (note that they can be members of multiple zones simultaneously). """ import pokemontools.configuration config = pokemontools.config...
map_image = pokemontools.map_gfx.draw_map(self.map_group_id, self.map_id, palettes, show_sprites=True, config=self.config) for coordinates in path: y = coordinates[0] x = coordinates[1] some_image = Image.new("RGBA", (32, 32)) draw = ImageDraw.Draw(some_...
iterable of nodes to visit in (y, x) format. """ palettes = pokemontools.map_gfx.read_palettes(self.config)
random_line_split
path.py
""" path finding implementation 1) For each position on the map, create a node representing the position. 2) For each NPC/item, mark nearby nodes as members of that NPC's threat zone (note that they can be members of multiple zones simultaneously). """ import pokemontools.configuration config = pokemontools.config...
return penalty def create_graph(some_map): """ Creates the array of nodes representing the in-game map. """ map_height = some_map.height map_width = some_map.width map_obstacles = some_map.obstacles nodes = [[None] * map_width] * map_height # create a node representing each...
penalty += PENALTIES["THREAT_ZONE"] if consider_sight_range: if self.is_node_in_sight_range(y, x, skip_range_check=True): penalty += PENALTIES["SIGHT_RANGE"] params = { "skip_sight_range_check": True, "...
conditional_block
path.py
""" path finding implementation 1) For each position on the map, create a node representing the position. 2) For each NPC/item, mark nearby nodes as members of that NPC's threat zone (note that they can be members of multiple zones simultaneously). """ import pokemontools.configuration config = pokemontools.config...
def _get_movement(self): """ Figures out the "movement" variable. Also, this converts from the internal game's format into True or False for whether or not the object is capable of moving. """ raise NotImplementedError @property def movement(self): ...
""" Get the current facing direction of the map_obstacle. """ if not self.simulation: self.facing_direction = self._get_current_facing_direction(DIRECTIONS=DIRECTIONS) return self.facing_direction
identifier_body
path.py
""" path finding implementation 1) For each position on the map, create a node representing the position. 2) For each NPC/item, mark nearby nodes as members of that NPC's threat zone (note that they can be members of multiple zones simultaneously). """ import pokemontools.configuration config = pokemontools.config...
(self, y, x): """ Applies a boundary of one around the threat zone, then checks if the player is inside. This is how the threatzone activates to calculate an updated graph or set of penalties for each step. """ y_condition = (self.top_left_y - 1) <= y < (self.bottom_right...
is_player_near
identifier_name
time_driver.rs
use core::cell::Cell; use core::convert::TryInto; use core::sync::atomic::{compiler_fence, Ordering}; use core::{mem, ptr}; use atomic_polyfill::{AtomicU32, AtomicU8}; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::blocking_mutex::Mutex; use embassy_time::driver::{AlarmHandle, Driver...
(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) { critical_section::with(|cs| { let alarm = self.get_alarm(cs, alarm); alarm.callback.set(callback as *const ()); alarm.ctx.set(ctx); }) } fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64...
set_alarm_callback
identifier_name
time_driver.rs
use core::cell::Cell; use core::convert::TryInto; use core::sync::atomic::{compiler_fence, Ordering}; use core::{mem, ptr}; use atomic_polyfill::{AtomicU32, AtomicU8}; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::blocking_mutex::Mutex; use embassy_time::driver::{AlarmHandle, Driver...
#[cfg(time_driver_tim15)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; } // Clock timekeeping works with something we call "periods", which are time intervals // of 2^15 ticks. The Clock counter value is 16 bits, so one "overflow cycle" is 2 periods. // // A `peri...
random_line_split
time_driver.rs
use core::cell::Cell; use core::convert::TryInto; use core::sync::atomic::{compiler_fence, Ordering}; use core::{mem, ptr}; use atomic_polyfill::{AtomicU32, AtomicU8}; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::blocking_mutex::Mutex; use embassy_time::driver::{AlarmHandle, Driver...
fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()) { critical_section::with(|cs| { let alarm = self.get_alarm(cs, alarm); alarm.callback.set(callback as *const ()); alarm.ctx.set(ctx); }) } fn set_alarm(&self, alarm: ...
{ let id = self.alarm_count.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| { if x < ALARM_COUNT as u8 { Some(x + 1) } else { None } }); match id { Ok(id) => Some(AlarmHandle::new(id)), Err(_) => N...
identifier_body
mathMode.ts
const mathjs = require('mathjs'); interface PluginState { scope: object; }; interface Block { start: number; end: number; } const inline_math_regex = /^=/; const equation_result_separator = " => "; const equation_result_collapsed = " |> "; function plugin(CodeMirror) { CodeMirror.defineMode('joplin-literate-mat...
(line: string): string { return line.replace(inline_math_regex, ''); } function process_block(cm: any, block: Block, noteConfig: any) { // scope is global to the note let scope = cm.state.mathMode.scope; let config = Object.assign({}, noteConfig); const math = mathjs.create(mathjs.all, { number: 'BigNumber...
get_line_equation
identifier_name
mathMode.ts
const mathjs = require('mathjs'); interface PluginState { scope: object; }; interface Block { start: number; end: number; } const inline_math_regex = /^=/; const equation_result_separator = " => "; const equation_result_collapsed = " |> "; function plugin(CodeMirror) { CodeMirror.defineMode('joplin-literate-mat...
// On each change we're going to scan for function on_change(cm: any, change: any) { clean_up(cm); // Most changes are the user typing a single character // If this doesn't happen inside a math block, we shouldn't re-process // +input means the user input the text (as opposed to joplin/plugin) // +delet...
{ for (let i = cm.firstLine(); i < cm.lineCount(); i++) { if (!find_math(cm, i)) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); } } }
identifier_body
mathMode.ts
const mathjs = require('mathjs'); interface PluginState { scope: object; }; interface Block { start: number; end: number; } const inline_math_regex = /^=/; const equation_result_separator = " => "; const equation_result_collapsed = " |> "; function plugin(CodeMirror) { CodeMirror.defineMode('joplin-literate-mat...
continue; } // Process one line let result = ''; try { const p = math.parse(get_line_equation(line)); if (falsey(config.simplify)) result = p.evaluate(scope); else result = math.simplify(p) result = math.format(result, { precision: Number(config.precision), notat...
{ math.config({ number: 'number' }); }
conditional_block
mathMode.ts
const mathjs = require('mathjs'); interface PluginState { scope: object; }; interface Block { start: number; end: number; } const inline_math_regex = /^=/; const equation_result_separator = " => "; const equation_result_collapsed = " |> "; function plugin(CodeMirror) { CodeMirror.defineMode('joplin-literate-mat...
// This is necessary to get the cursor to be placed in the right location ofter // clicking on a widget // The downside is that it breaks copying of widget text (for textareas, it never // works on contenteditable) // I'm okay with this because I want the user to be able to select a block // without a...
if (lineData.alignRight) res.setAttribute('class', 'math-result-right'); // handleMouseEvents gives control of mouse handling for the widget to codemirror
random_line_split
activity.go
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package arc import ( "context" "fmt" "math" "regexp" "strconv" "time" "chromiumos/tast/errors" "chromiumos/tast/local/input" "chromiumos/tas...
bounds.Width = right - bounds.Left bounds.Height = bottom - bounds.Top return bounds, nil }
{ *dst, err = strconv.Atoi(s[i]) if err != nil { return Rect{}, errors.Wrapf(err, "could not parse %q", s[i]) } }
conditional_block
activity.go
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package arc import ( "context" "fmt" "math" "regexp" "strconv" "time" "chromiumos/tast/errors" "chromiumos/tast/local/input" "chromiumos/tas...
(ctx context.Context, to Point, t time.Duration) error { task, err := ac.getTaskInfo(ctx) if err != nil { return errors.Wrap(err, "could not get task info") } if task.windowState != WindowStateNormal && task.windowState != WindowStatePIP { return errors.Errorf("cannot move window in state %d", int(task.windowS...
MoveWindow
identifier_name
activity.go
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package arc import ( "context" "fmt" "math" "regexp" "strconv" "time" "chromiumos/tast/errors" "chromiumos/tast/local/input" "chromiumos/tas...
// initTouchscreenLazily lazily initializes the touchscreen. // Touchscreen initialization is not needed, unless swipe() is called. func (ac *Activity) initTouchscreenLazily(ctx context.Context) error { if ac.tew != nil { return nil } var err error ac.tew, err = input.Touchscreen(ctx) if err != nil { return ...
{ if err := ac.initTouchscreenLazily(ctx); err != nil { return errors.Wrap(err, "could not initialize touchscreen device") } stw, err := ac.tew.NewSingleTouchWriter() if err != nil { return errors.Wrap(err, "could not get a new TouchEventWriter") } defer stw.Close() // TODO(ricardoq): Fetch stableSize dire...
identifier_body
activity.go
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package arc import ( "context" "fmt" "math" "regexp" "strconv" "time" "chromiumos/tast/errors" "chromiumos/tast/local/input" "chromiumos/tas...
// ResizeWindow resizes the activity's window. // border represents from where the resize should start. // to represents the coordinates for for the new border's position, in pixels. // t represents the duration of the resize. // ResizeWindow only works with WindowStateNormal and WindowStatePIP windows. Will fail othe...
return ac.swipe(ctx, from, to, t) }
random_line_split
planner.go
// Copyright 2016 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
() *tree.EvalContext { return &p.extendedEvalCtx.EvalContext } func (p *planner) Descriptors() *descs.Collection { return p.extendedEvalCtx.Descs } // ExecCfg implements the PlanHookState interface. func (p *planner) ExecCfg() *ExecutorConfig { return p.extendedEvalCtx.ExecCfg } // GetOrInitSequenceCache returns ...
EvalContext
identifier_name