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
admission_test.go
("", "") if err != nil { t.Fatalf("Unexpected error while creating temporary file: %v", err) } p := tempfile.Name() defer os.Remove(p) kubeconfig := ` clusters: - name: foo cluster: server: https://example.com users: - name: alice user: token: deadbeef contexts: - name: default con...
if err == nil { t.Fatalf("Expected admission controller to fail closed") } } func TestAdmitPolicyDoesNotExist(t *testing.T) { controller, err := newControllerWithTestServer(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }, false) if err != nil { t.Fatalf("Unexpected error while creating...
{ serve := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) } controller, err := newControllerWithTestServer(serve, false) if err != nil { t.Fatalf("Unexpected error while creating test admission controller/server: %v", err) } mockClient := &fake.Clientset{} mockClient.AddReactor("list", "...
identifier_body
admission_test.go
"a valid config", fmt.Sprintf(` { "kubeconfig": %q } `, p), false, }, { "a valid config with retry backoff", fmt.Sprintf(` { "kubeconfig": %q, "retryBackoff": 200 } `, p), false, }, } for _, tc := range tests { var file io.Reader if tc.input == "" { ...
makeKubeConfigFile
identifier_name
precompiled_objects.go
PrecompiledObjects returns stored at the cloud storage bucket precompiled objects for the target category func (cd *CloudStorage) GetPrecompiledObjects(ctx context.Context, targetSdk pb.Sdk, targetCategory, bucketName string) (*SdkToCategories, error) { client, err := storage.NewClient(ctx, option.WithoutAuthenticatio...
isDir
identifier_name
precompiled_objects.go
protobuf:"varint,7,opt,name=multifile,proto3" json:"multifile,omitempty"` ContextLine int32 `protobuf:"varint,7,opt,name=context_line,proto3" json:"context_line,omitempty"` DefaultExample bool `protobuf:"varint,7,opt,name=default_example,json=defaultExample,proto3" json:"de...
// GetPrecompiledObjectOutput returns the run output of the example func (cd *CloudStorage) GetPrecompiledObjectOutput(ctx context.Context, precompiledObjectPath, bucketName string) (string, error) { data, err := cd.getFileFromBucket(ctx, precompiledObjectPath, OutputExtension, bucketName) if err != nil { return ...
{ extension, err := getFileExtensionBySdk(precompiledObjectPath) if err != nil { return "", err } data, err := cd.getFileFromBucket(ctx, precompiledObjectPath, extension, bucketName) if err != nil { return "", err } result := string(data) return result, nil }
identifier_body
precompiled_objects.go
----------- JoinExamples.output // ----------- JoinExamples.log // ----------- JoinExamples.graph // ----------- meta.info // ----PRECOMPILED_OBJECT_TYPE_KATA/ // --------... // ----... // SDK_GO/ // ----defaultPrecompiledObject.info // ----PRECOMPILED_OBJECT_TYPE_EXAMPLE/ // --------MinimalWordCount/ // ----------- M...
} if err != nil {
random_line_split
precompiled_objects.go
WordCount.go // ----------- MinimalWordCount.output // ----------- MinimalWordCount.log // ----------- MinimalWordCount.graph // ----------- meta.info // --------PingPong/ // ----PRECOMPILED_OBJECT_TYPE_KATA/ // --------... // ----... // // defaultPrecompiledObject.info is a file that contains path to the default examp...
{ bucketAttrs, errWithAttrs := bucket.Attrs(ctx) if errWithAttrs != nil { return nil, fmt.Errorf("error during receiving bucket's attributes: %s", err) } return nil, fmt.Errorf("Bucket(%q).Objects: %v", bucketAttrs.Name, err) }
conditional_block
load.py
_indices = shuffled_indices[:test_set_size] train_indices = shuffled_indices[test_set_size:] return data.iloc[train_indices], data.iloc[test_indices] ''' 这里考虑到了一个问题: 如果再次运行程序,就会产生不同的测试集,多次运行后,你就会得到整个数据集 解决方法:1)设置随机种子;2)保存训练集与测试集 但是这两种方法都是一种静态的方法,党员是数据发生变化的时候,这些方法将出现问题 所以最后采用对每个实例赋予识别码,判断实例是否应该放入测试集 新的测试集将包含新实...
housing_tr = pd.DataFrame(X, columns=housing_num.columns) # 6.2 处理文本 from sklearn.preprocessing import LabelEncoder encoder = LabelEncoder() # 这个是用来将字符串编码为数字(数字的选取都在字符串的长度-1) housing_cat = housing["ocean_proximity"] housing_cat_encoded = encoder.fit_transform(housing_cat) # 这里有两个fit,fit+transform就等于fit_transform prin...
random_line_split
load.py
SV文件,返回一个相应的数据类型 ''' csv_path = os.path.join('./', housing_path, "housing.csv") data = pd.read_csv(csv_path) # print(data) return data data = load_housing_data() # df.value_counts() 可以帮助我们统计每一列数据的分布情况 # df.describe() 可以帮助我们整体了解数据集的情况,包含count,mean,min,max,std(标准差)等等 print(data["ocean_proximity"].va...
os.path.join(housing_path, "housing.tgz") urllib.request.urlretrieve(housing_url, tgz_path) housing_tgz = tarfile.open(tgz_path) housing_tgz.extractall(path=housing_path) housing_tgz.close() # fetch_housing_data() import pandas as pd def load_housing_data(housing_path=HOUSING_PATH): ''' 利用pa...
identifier_body
load.py
("id") housing_with_id.insert(0, "id", temp_column) # 这个就是用来在第0列插入一个索引 train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "id") # 2.2 sklearn自带的方法 from sklearn.model_selection import train_test_split # sklearn中内置的数据集取样的方法 train_set, test_set = train_test_split(data, test_size=0.2, random_state=42) ...
r()
identifier_name
load.py
''' 前提是专家告诉我们,收入中位数是预测房价中位数非常重要的属性,故我们进行数据集的划分时要考虑到收入中位数 1)首先创建收入类别属性 2)然后针对收入分层的结果进行划分(每个收入类选择20%作为测试集) ''' data["income_cat"] = np.ceil(data["median_income"] / 1.5) # ceil是进行数据取舍,以产生离散的分类 # 注:inplace的含义就是如果True则是在原DataFrame上面进行相关的操作;如果是False就是新形成一个DataFrame保留原本的DataFrame data["income_cat"].where(data["income_cat"] <...
) housing_prepared = full_pipeline.fit_transform(X=housing) housing_temp = pd.DataFrame(housing_prepared) # 因为这个columns已经更新了不能使用之前的columns print(housing_prepared) # 7. 线性
conditional_block
targets.go
NamedOrString(s *scope, name string, obj pyObject, anon func(core.BuildInput), named func(string, core.BuildInput), systemAllowed, tool bool) { if obj == nil { return } if str, ok := asString(obj); ok { if bi := parseBuildInput(s, str, name, systemAllowed, tool); bi != nil { anon(bi) } return } addMaybe...
Call
identifier_name
targets.go
target.Test.Flakiness = 1 } else { target.Test.Flakiness = uint8(i) target.AddLabel("flaky") } } } else { target.Test.Flakiness = 1 } if testCmd != nil && testCmd != None { target.Test.Command, target.Test.Commands = decodeCommands(s, args[testCMDBuildRuleArgIdx]) } target.Test...
if target.Label.PackageName == "_please" { return nil } for _, whitelist := range state.Config.Sandbox.ExcludeableTargets { if whitelist.Matches(target.Label) { return nil } } for _, dir := range state.Config.Parse.ExperimentalDir { if strings.HasPrefix(target.Label.PackageName, dir) { return nil }...
if target.Sandbox && (target.Test == nil || target.Test.Sandbox) { return nil } }
random_line_split
targets.go
target.Test.Flakiness = 1 } else { target.Test.Flakiness = uint8(i) target.AddLabel("flaky") } } } else { target.Test.Flakiness = 1 } if testCmd != nil && testCmd != None { target.Test.Command, target.Test.Commands = decodeCommands(s, args[testCMDBuildRuleArgIdx]) } target.Test.Tim...
addStrings(s, "requires", args[requiresBuildRuleArgIdx], t.AddRequire) if vis, ok := asList(args[visibilityBuildRuleArgIdx]); ok && len(vis) != 0 { if v, ok := vis[0].(pyString); ok && v == "PUBLIC" { t.Visibility = core.WholeGraph } else { addStrings(s, "visibility", args[visibilityBuildRuleArgIdx], func(s...
{ if t.IsRemoteFile { for _, url := range mustList(args[urlsBuildRuleArgIdx]) { t.AddSource(core.URLLabel(url.(pyString))) } } else if t.IsTextFile { t.FileContent = args[fileContentArgIdx].(pyString).String() } addMaybeNamed(s, "srcs", args[srcsBuildRuleArgIdx], t.AddSource, t.AddNamedSource, false, false...
identifier_body
targets.go
target.Test.Flakiness = 1 } else { target.Test.Flakiness = uint8(i) target.AddLabel("flaky") } } } else { target.Test.Flakiness = 1 } if testCmd != nil && testCmd != None { target.Test.Command, target.Test.Commands = decodeCommands(s, args[testCMDBuildRuleArgIdx]) } target.Test.Tim...
else if cmd, ok := obj.(pyString); ok { return strings.TrimSpace(string(cmd)), nil } cmds, ok := asDict(obj) s.Assert(ok, "Unknown type for command [%s]", obj.Type()) // Have to convert all the keys too m := make(map[string]string, len(cmds)) for k, v := range cmds { if v != None { sv, ok := v.(pyString) ...
{ return "", nil }
conditional_block
tables.py
_keys = [] # List of all rows in dataframe to fill in missing data stream_attributes["Units"] = {} for key, sb in stream_states.items(): stream_attributes[key] = {} if true_state: disp_dict = sb.define_state_vars() else: disp_dict = sb.define_display_vars() ...
for i, a in enumerate(attributes): j = None if isinstance(a, (list, tuple)): # if a is list or tuple, assume index supplied try: assert len(a) > 1 except AssertionError: _log.error(f"An index must be supplide...
conditional_block
tables.py
of a translator block. sb = _get_state_from_port(a.ports[1], time_point) except: # pylint: disable=W0702 sb = _get_state_from_port(a.ports[0], time_point) _stream_dict_add(sb, n, i) elif isinstance(streams[n], Port): sb = _get...
generate_table
identifier_name
tables.py
str): Prepend a string to the arc name joined with a '.'. This can be useful to prevent conflicting names when sub blocks contain Arcs that have the same names when used in combination with descend_into=False. s (dict): Add streams to an existing stream dict. Returns: ...
return DataFrame.from_dict(stream_attributes, orient=orient) def create_stream_table_ui( streams, true_state=False, time_point=0, orient="columns", precision=5 ): """ Method to create a stream table in the form of a pandas dataframe. Method takes a dict with name keys and stream values. Use an Ord...
random_line_split
tables.py
): Prepend a string to the arc name joined with a '.'. This can be useful to prevent conflicting names when sub blocks contain Arcs that have the same names when used in combination with descend_into=False. s (dict): Add streams to an existing stream dict. Returns: ...
stream_attributes = OrderedDict() stream_states = stream_states_dict(streams=streams, time_point=time_point) full_keys = [] # List of all rows in dataframe to fill in missing data stream_attributes["Units"] = {} for key, sb in stream_states.items(): stream_attributes[key] = {} i...
UNFIXED = "unfixed" FIXED = "fixed" PARAMETER = "parameter" EXPRESSION = "expression"
identifier_body
signin.py
['level']} {record['owner']} {record['message']}" G.log_history.append(msg) if G.mainwindow: G.mainwindow.job.log_signal.emit(msg) if G.loading: try: msg1 = json.loads(record['message'].replace("\'", "\"")) G.loading.msg.setText(msg1['ErrorMsg']) e...
self.setTabOrder(self.remember_me, self.sign_in_btn) self.icon.installEventFilter(self) self.icon.setText('快速登录') self.icon.setStyleSheet(""" QLabel{ image: url(:/menu/images/bee_temp_grey.png); } QLabel:hover{ color:#1B89CA; borde...
super(SignInWidget, self).__init__() self.setupUi(self) self.setWindowTitle("ctpbee客户端") # self.setWindowFlag(Qt.FramelessWindowHint) # 去边框 self.setWindowFlags(Qt.WindowCloseButtonHint) self.setStyleSheet(qss) # tab self.setTabOrder(self.userid_sim, self.p...
identifier_body
signin.py
['level']} {record['owner']} {record['message']}" G.log_history.append(msg) if G.mainwindow: G.mainwindow.job.log_signal.emit(msg) if G.loading: try: msg1 = json.loads(record['message'].replace("\'", "\"")) G.loading.msg.setText(msg1['ErrorMsg']) e...
self.common_sign_in() elif self.login_tab.currentIndex() == 1: self.detailed_sign_in() def common_sign_in(self): info = dict( userid=self.userid_sim.currentText(), password=self.password_sim.text(), interface=self.interface_sim.curr...
x() == 0:
identifier_name
signin.py
['level']} {record['owner']} {record['message']}" G.log_history.append(msg) if G.mainwindow: G.mainwindow.job.log_signal.emit(msg) if G.loading: try: msg1 = json.loads(record['message'].replace("\'", "\"")) G.loading.msg.setText(msg1['ErrorMsg']) e...
self.detailed_sign_in() def common_sign_in(self): info = dict( userid=self.userid_sim.currentText(), password=self.password_sim.text(), interface=self.interface_sim.currentText(), ) which_ = self.other.currentText() if which_ == 'si...
Index() == 1:
conditional_block
signin.py
record['level']} {record['owner']} {record['message']}" G.log_history.append(msg) if G.mainwindow: G.mainwindow.job.log_signal.emit(msg) if G.loading: try: msg1 = json.loads(record['message'].replace("\'", "\"")) G.loading.msg.setText(msg1['ErrorMsg']) ...
md_address="tcp://180.168.146.187:10131", td_address="tcp://180.168.146.187:10130", product_info="", appid="simnow_client_test", auth_code="0000000000000000", ) class SignInWidget(QWidget, Ui_SignIn): def __init__(self): super(SignInWidget, self).__init__() self.se...
simnow_24 = dict( brokerid="9999",
random_line_split
context.rs
//!The [`Context`][context] contains all the input data for the request //!handlers, as well as some utilities. This is where request data, like //!headers, client address and the request body can be retrieved from and it //!can safely be picked apart, since its ownership is transferred to the //!handler. //! //!##Acce...
//!Handler context and request body reading extensions. //! //!#Context //!
random_line_split
context.rs
Result<&'static str, &'static str> { Ok("yo") } //!use rustful::{Context, Response}; //!use rustful::StatusCode::InternalServerError; //! //!fn my_handler(context: Context, mut response: Response) { //! match something_that_may_fail() { //! Ok(res) => response.send(res), //! Err(e) => { //! ...
else { None }) }, _ => None }; BodyReader { reader: reader, multipart_boundary: boundary } } } #[cfg(not(feature = "multipart"))] impl<'a, 'b> BodyReader<'a, 'b> { ///Internal method that may c...
{ Some(boundary.clone()) }
conditional_block
context.rs
Result<&'static str, &'static str> { Ok("yo") } //!use rustful::{Context, Response}; //!use rustful::StatusCode::InternalServerError; //! //!fn my_handler(context: Context, mut response: Response) { //! match something_that_may_fail() { //! Ok(res) => response.send(res), //! Err(e) => { //! ...
<'a, 'b: 'a> { reader: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>, #[cfg(feature = "multipart")] multipart_boundary: Option<String> } #[cfg(feature = "multipart")] impl<'a, 'b> BodyReader<'a, 'b> { ///Try to create a `multipart/form-data` reader from the request body. /// ///``` ...
BodyReader
identifier_name
local_cache.rs
Path, manifest_base: &Path, data: &Path, only_cached: bool, status: &mut StatusBackend ) -> Result<LocalCache<B>> { // If the `digest` file exists, we assume that it is valid; this is // *essential* so that we can use a URL as our default IoProvider // without requiring a network con...
return OpenResult::NotAvailable; } }; // OK, we can stream the file to a temporary location on disk, // computing its SHA256 as we go. let mut digest_builder = digest::create(); let mut length = 0; let mut temp_dest = match tempfile::Builder::new(...
{ return OpenResult::Err(e.into()); }
conditional_block
local_cache.rs
Path, manifest_base: &Path, data: &Path, only_cached: bool, status: &mut StatusBackend ) -> Result<LocalCache<B>> { // If the `digest` file exists, we assume that it is valid; this is // *essential* so that we can use a URL as our default IoProvider // without requiring a network con...
(&mut self, name: &OsStr, length: u64, digest: Option<DigestData>) -> Result<()> { let digest_text = match digest { Some(ref d) => d.to_string(), None => "-".to_owned(), }; // Due to a quirk about permissions for file locking on Windows, we // need to add `.read(...
record_cache_result
identifier_name
local_cache.rs
Path, manifest_base: &Path, data: &Path, only_cached: bool, status: &mut StatusBackend ) -> Result<LocalCache<B>> { // If the `digest` file exists, we assume that it is valid; this is // *essential* so that we can use a URL as our default IoProvider // without requiring a network con...
let mut temp_dest = match tempfile::Builder::new() .prefix("download_") .rand_bytes(6) .tempfile_in(&self.data_path) {
// computing its SHA256 as we go. let mut digest_builder = digest::create(); let mut length = 0;
random_line_split
mod.rs
=> self.activate_hint(follow_mode, ctrl_key), ActivateSelection() => self.activate_selection(), ClickNextPage() => self.click_next_page(), ClickPrevPage() => self.click_prev_page(), EnterHintKey(key) => self.enter_hint_key(key), ...
self
identifier_name
mod.rs
_event_listener_with_closure("scroll", &handler, false); } else { let element = self.model.scroll_element.as_ref().unwrap(); element.add_event_listener_with_closure("scroll", &handler, false); } }, MessageRec...
let document = get_document!(self); load_username(&document, username); load_password(&document, password); }
identifier_body
mod.rs
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR ...
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
random_line_split
mod.rs
, ctrl_key) => self.activate_hint(follow_mode, ctrl_key), ActivateSelection() => self.activate_selection(), ClickNextPage() => self.click_next_page(), ClickPrevPage() => self.click_prev_page(), EnterHintKey(key) => self.enter_hint_key(key),...
// FIXME: this is not working. input_file.set_value(file); } }
conditional_block
BRDF_descriptors.py
author__ = "J Gomez-Dans" __copyright__ = "Copyright 2017, 2018 J Gomez-Dans" __license__ = "GPLv3" __email__ = "j.gomez-dans@ucl.ac.uk" GDAL2NUMPY = {gdal.GDT_Byte: np.uint8, gdal.GDT_UInt16: np.uint16, gdal.GDT_Int16: np.int16, gdal.GDT_UInt32: np.uint32, ...
raise IOError("Can't open %s" % fname) if roi is None: data = g.ReadAsArray() else: ulx, uly, lrx, lry = roi xoff = ulx yoff = uly xcount = lrx - ulx ycount = lry - uly data = g.ReadAsArray(xoff, yoff, xcount, ycount).astype( ...
if g is None:
random_line_split
BRDF_descriptors.py
author__ = "J Gomez-Dans" __copyright__ = "Copyright 2017, 2018 J Gomez-Dans" __license__ = "GPLv3" __email__ = "j.gomez-dans@ucl.ac.uk" GDAL2NUMPY = {gdal.GDT_Byte: np.uint8, gdal.GDT_UInt16: np.uint16, gdal.GDT_Int16: np.int16, gdal.GDT_UInt32: np.uint32, ...
(band_no, a1_granule, a2_granule, band_transfer=None, roi=None): if band_transfer is not None: band_no = band_transfer[band_no] fname_a1 = 'HDF4_EOS:EOS_GRID:"%s":MOD_Grid_BRDF:' % (a1_granule) fname_a2 = 'HDF4_EOS:EOS_GRID:"%s":MOD_Grid_BRDF:' % (a2_granule) try: ...
process_masked_kernels
identifier_name
BRDF_descriptors.py
__author__ = "J Gomez-Dans" __copyright__ = "Copyright 2017, 2018 J Gomez-Dans" __license__ = "GPLv3" __email__ = "j.gomez-dans@ucl.ac.uk" GDAL2NUMPY = {gdal.GDT_Byte: np.uint8, gdal.GDT_UInt16: np.uint16, gdal.GDT_Int16: np.int16, gdal.GDT_UInt32: np.uint32, ...
if os.path.exists(mcd43a1_dir): self.mcd43a1_dir = mcd43a1_dir else: raise IOError("mcd43a1_dir does not exist!") self.a1_granules = find_granules(self.mcd43a1_dir, tile, "A1", self.start_time, self.end_time) if mcd43a2_dir...
"""Retrieving BRDF descriptors.""" def __init__(self, tile, mcd43a1_dir, start_time, end_time=None, mcd43a2_dir=None, roi=None): """The class needs to locate the data granules. We assume that these are available somewhere in the filesystem and that we can index them by loca...
identifier_body
BRDF_descriptors.py
author__ = "J Gomez-Dans" __copyright__ = "Copyright 2017, 2018 J Gomez-Dans" __license__ = "GPLv3" __email__ = "j.gomez-dans@ucl.ac.uk" GDAL2NUMPY = {gdal.GDT_Byte: np.uint8, gdal.GDT_UInt16: np.uint16, gdal.GDT_Int16: np.int16, gdal.GDT_UInt32: np.uint32, ...
else: raise ValueError("You can only use a string or a datetime object") return output_time def open_gdal_dataset(fname, roi=None): g = gdal.Open(fname) if g is None: raise IOError("Can't open %s" % fname) if roi is None: data = g.ReadAsArray() else: ulx, uly, ...
try: output_time = datetime.datetime.strptime(timestamp, "%Y-%m-%d") except ValueError: try: output_time = datetime.datetime.strptime(timestamp, "%Y%j") ...
conditional_block
bidirectional.rs
fn render<F: FnMut(Progress<'_>)>( film: &Film, task_runner: TaskRunner, mut on_status: F, renderer: &Renderer, config: &BidirParams, world: &World, camera: &Camera, resources: &Resources, )
index, rng, tile, film, camera, world, resources, renderer, config, progress, ); }, |_, _| { progress += 1; on_status(Progress { progress: ((progress * 100) / num_tiles) as u8, message: &status_message, }); ...
{ fn gen_rng() -> XorShiftRng { XorShiftRng::from_rng(rand::thread_rng()).expect("could not generate RNG") } let tiles = make_tiles(film.width(), film.height(), renderer.tile_size, camera); let status_message = "Rendering"; on_status(Progress { progress: 0, message: &status...
identifier_body
bidirectional.rs
bidir_params: &BidirParams, progress: LocalProgress, ) { let mut lamp_path = Vec::with_capacity(bidir_params.bounces as usize + 1); let mut camera_path = Vec::with_capacity(renderer.bounces as usize); let mut additional_samples = Vec::with_capacity(renderer.spectrum_samples as usize - 1); let mu...
{ &mut *additional }
conditional_block
bidirectional.rs
fn render<F: FnMut(Progress<'_>)>( film: &Film, task_runner: TaskRunner, mut on_status: F, renderer: &Renderer, config: &BidirParams, world: &World, camera: &Camera, resources: &Resources, ) { fn
() -> XorShiftRng { XorShiftRng::from_rng(rand::thread_rng()).expect("could not generate RNG") } let tiles = make_tiles(film.width(), film.height(), renderer.tile_size, camera); let status_message = "Rendering"; on_status(Progress { progress: 0, message: &status_message, })...
gen_rng
identifier_name
bidirectional.rs
use cgmath::{EuclideanSpace, InnerSpace, Point2, Vector3}; use collision::Ray3; use super::{ algorithm::{contribute, make_tiles, Tile}, LocalProgress, Progress, Renderer, TaskRunner, }; use crate::cameras::Camera; use crate::film::{Film, Sample}; use crate::lamp::{RaySample, Surface}; use crate::tracer::{trace...
use rand::{self, Rng, SeedableRng}; use rand_xorshift::XorShiftRng;
random_line_split
parser.go
imports []*ast.ImportSpec // list of imports // Label scopes // (maintained by open/close LabelScope) labelScope *ast.Scope // label scope for current function targetStack [][]*ast.Ident // stack of unresolved labels } // parseOperand may return an expression or a raw type (incl. array...
// Ordinary identifier scopes pkgScope *ast.Scope // pkgScope.Outer == nil topScope *ast.Scope // top-most scope; may be pkgScope unresolved []*ast.Ident // unresolved identifiers
random_line_split
parser.go
imports []*ast.ImportSpec // list of imports // Label scopes // (maintained by open/close LabelScope) labelScope *ast.Scope // label scope for current function targetStack [][]*ast.Ident // stack of unresolved labels } // parseOperand may return an expression or a raw type (incl. array...
(a ...interface{}) { const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " const n = len(dots) pos := p.file.Position(p.pos) fmt.Printf("%5d:%3d: ", pos.Line, pos.Column) i := 2 * p.indent for i > n { fmt.Print(dots) i -= n } // i <= n fmt.Print(dots[0:i]) fmt.Println(a...) } f...
printTrace
identifier_name
parser.go
imports []*ast.ImportSpec // list of imports // Label scopes // (maintained by open/close LabelScope) labelScope *ast.Scope // label scope for current function targetStack [][]*ast.Ident // stack of unresolved labels } // parseOperand may return an expression or a raw type (incl. array...
assert(ident.Obj == nil, "identifier already declared or resolved") if ident.Name == "_" { return } // try to resolve the identifier for s := p.topScope; s != nil; s = s.Outer { if obj := s.Lookup(ident.Name); obj != nil { ident.Obj = obj return } } // all local scopes are known, so any unresolved i...
{ return }
conditional_block
parser.go
imports []*ast.ImportSpec // list of imports // Label scopes // (maintained by open/close LabelScope) labelScope *ast.Scope // label scope for current function targetStack [][]*ast.Ident // stack of unresolved labels } // parseOperand may return an expression or a raw type (incl. array...
func trace(p *parser, msg string) *parser { p.printTrace(msg, "(") p.indent++ return p } // Usage pattern: defer un(trace(p, "...")) func un(p *parser) { p.indent-- p.printTrace(")") } func (p *parser) init(fset *token.FileSet, filename string, src []byte) { p.file = fset.AddFile(filename, -1, len(src)) ...
{ const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " const n = len(dots) pos := p.file.Position(p.pos) fmt.Printf("%5d:%3d: ", pos.Line, pos.Column) i := 2 * p.indent for i > n { fmt.Print(dots) i -= n } // i <= n fmt.Print(dots[0:i]) fmt.Println(a...) }
identifier_body
bindings.go
// switch e := event.(type) { // case KeyEvent: // InfoMapKey(e, v) // case KeySequenceEvent: // InfoMapKey(e, v) // case MouseEvent: // InfoMapMouse(e, v) // case RawEvent: // InfoMapKey(e, v) // } } var r = regexp.MustCompile("<(.+?)>") func findEvents(k string) (b KeySequenceEvent, ok bool, err error...
(k string) (b Event, ok bool) { modifiers := tcell.ModNone // First, we'll strip off all the modifiers in the name and add them to the // ModMask modSearch: for { switch { case strings.HasPrefix(k, "-") && k != "-": // We optionally support dashes between modifiers k = k[1:] case strings.HasPrefix(k, "...
findSingleEvent
identifier_name
bindings.go
for k, v := range parsed { switch val := v.(type) { case string: BindKey(k, val, Binder["buffer"]) case map[string]interface{}: bind, ok := Binder[k] if !ok || bind == nil { screen.TermMessage(fmt.Sprintf("%s is not a valid pane type", k)) continue } for e, a := range val { s, ok := ...
{ defaults := DefaultBindings(p) for k, v := range defaults { BindKey(k, v, bind) } }
conditional_block
bindings.go
// switch e := event.(type) { // case KeyEvent: // InfoMapKey(e, v) // case KeySequenceEvent: // InfoMapKey(e, v) // case MouseEvent: // InfoMapMouse(e, v) // case RawEvent: // InfoMapKey(e, v) // } } var r = regexp.MustCompile("<(.+?)>") func findEvents(k string) (b KeySequenceEvent, ok bool, err error...
"F2": tcell.KeyF2,
"Pause": tcell.KeyPause, "Backtab": tcell.KeyBacktab, "F1": tcell.KeyF1,
random_line_split
bindings.go
// switch e := event.(type) { // case KeyEvent: // InfoMapKey(e, v) // case KeySequenceEvent: // InfoMapKey(e, v) // case MouseEvent: // InfoMapMouse(e, v) // case RawEvent: // InfoMapKey(e, v) // } } var r = regexp.MustCompile("<(.+?)>") func findEvents(k string) (b KeySequenceEvent, ok bool, err error...
modifiers |= tcell.ModShift case strings.HasPrefix(k, "\x1b"): screen.Screen.RegisterRawSeq(k) return RawEvent{ esc: k, }, true default: break modSearch } } if k == "" { return KeyEvent{}, false } // Control is handled in a special way, since the terminal sends explicitly // marked esc...
{ modifiers := tcell.ModNone // First, we'll strip off all the modifiers in the name and add them to the // ModMask modSearch: for { switch { case strings.HasPrefix(k, "-") && k != "-": // We optionally support dashes between modifiers k = k[1:] case strings.HasPrefix(k, "Ctrl") && k != "CtrlH": // ...
identifier_body
ed25519.rs
/// state. /// * `context` is an optional context string, up to 255 bytes inclusive, /// which may be used to provide additional domain separation. If not /// set, this will default to an empty string. /// /// # Returns /// /// An Ed25519ph [`Signature`] on the `prehashed_message...
formatter.write_str("An ed25519 keypair, 64 bytes in total where the secret key is \ the first 32 bytes and is in unexpanded form, and the second \ 32 bytes is a compressed point for a public key.") }
identifier_body
ed25519.rs
.len(), ASSERT_MESSAGE); assert!(signatures.len() == public_keys.len(), ASSERT_MESSAGE); assert!(public_keys.len() == messages.len(), ASSERT_MESSAGE); #[cfg(feature = "alloc")] use alloc::vec::Vec; #[cfg(feature = "std")] use std::vec::Vec; use core::iter::once;
// Select a random 128-bit scalar for each signature. let zs: Vec<Scalar> = signatures .iter() .map(|_| Scalar::from(thread_rng().gen::<u128>())) .collect(); // Compute the basepoint coefficient, ∑ s[i]z[i] (mod l) let B_coefficient: Scalar = signatures .iter() ....
use rand::thread_rng; use curve25519_dalek::traits::IsIdentity; use curve25519_dalek::traits::VartimeMultiscalarMul;
random_line_split
ed25519.rs
(), ASSERT_MESSAGE); assert!(signatures.len() == public_keys.len(), ASSERT_MESSAGE); assert!(public_keys.len() == messages.len(), ASSERT_MESSAGE); #[cfg(feature = "alloc")] use alloc::vec::Vec; #[cfg(feature = "std")] use std::vec::Vec; use core::iter::once; use rand::thread_rn...
es: &'a [u8]) -> Result<Keypair, SignatureError> { if bytes.len() != KEYPAIR_LENGTH { return Err(SignatureError(InternalError::BytesLengthError { name: "Keypair", length: KEYPAIR_LENGTH, })); } let secret = SecretKey::from_bytes(&bytes[..SE...
es<'a>(byt
identifier_name
ed25519.rs
.len(), ASSERT_MESSAGE); assert!(signatures.len() == public_keys.len(), ASSERT_MESSAGE); assert!(public_keys.len() == messages.len(), ASSERT_MESSAGE); #[cfg(feature = "alloc")] use alloc::vec::Vec; #[cfg(feature = "std")] use std::vec::Vec; use core::iter::once; use rand::threa...
Err(SignatureError(InternalError::VerifyError)) } } /// An ed25519 keypair. #[derive(Debug, Default)] // we derive Default in order to use the clear() method in Drop pub struct Keypair { /// The secret half of this keypair. pub secret: SecretKey, /// The public half of this keypair. pub pub...
Ok(()) } else {
conditional_block
describe.go
data types which can be directly used // for printing out type revisionDesc struct { revision *servingv1.Revision // traffic stuff percent int64 tag string latestTraffic *bool configurationGeneration int // status info latestCreated bool latestReady bool } // [REMOVE COMMENT WHEN MOVING ...
client, err := newServingClient(p, namespace, cmd.Flag("target").Value.String()) if err != nil { return err } service, err := client.GetService(cmd.Context(), serviceName) if err != nil { return err } // Print out machine readable output if requested if machineReadablePrintFlags.Output...
if err != nil { return err }
random_line_split
describe.go
data types which can be directly used // for printing out type revisionDesc struct { revision *servingv1.Revision // traffic stuff percent int64 tag string latestTraffic *bool configurationGeneration int // status info latestCreated bool latestReady bool } // [REMOVE COMMENT WHEN MOVING ...
section := revSection.WriteColsLn(formatBullet(revisionDesc.percent, ready.Status), revisionHeader(revisionDesc)) if ready.Status == corev1.ConditionFalse { section.WriteAttribute("Error", ready.Reason) } revision.WriteImage(section, revisionDesc.revision) revision.WriteReplicas(section, revisionDesc.revis...
if cond.Type == apis.ConditionReady { ready = cond break } }
conditional_block
describe.go
(out, "%s\n", extractURL(service)) return nil } printer, err := machineReadablePrintFlags.ToPrinter() if err != nil { return err } return printer.PrintObj(service, out) } printDetails, err = cmd.Flags().GetBool("verbose") if err != nil { return err } revisionDescs, err...
generation, err := strconv.ParseInt(revision.Labels[serving.ConfigurationGenerationLabelKey], 0, 0) if err != nil { return nil, fmt.Errorf("cannot extract configuration generation for revision %s: %w", revision.Name, err) } revisionDesc := revisionDesc{ revision: &revision, configurationGenera...
identifier_body
describe.go
.AllowedFormats(), "url"), "|")) return command } // Main action describing the service func describe(w io.Writer, service *servingv1.Service, revisions []*revisionDesc, printDetails bool) error { dw := printers.NewPrefixWriter(w) // Service info writeService(dw, service) dw.WriteLine() if err := dw.Flush(); er...
xtractURL(
identifier_name
update.go
"k8s.io/apiserver/pkg/audit" "k8s.io/apiserver/pkg/authorization/authorizer" "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" "k8s.io/apiserver/pkg/endpoints/handlers/finisher" requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics" "k8s.io/apiserver/pkg/endpoints/handlers/negotiation" "k8s.io/apis...
(r rest.Updater, scope *RequestScope, admit admission.Interface) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { ctx := req.Context() // For performance tracking purposes. ctx, span := tracing.Start(ctx, "Update", traceFields(req)...) defer span.End(500 * time.Millisecond) namespa...
UpdateResource
identifier_name
update.go
"k8s.io/apiserver/pkg/audit" "k8s.io/apiserver/pkg/authorization/authorizer" "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" "k8s.io/apiserver/pkg/endpoints/handlers/finisher" requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics" "k8s.io/apiserver/pkg/endpoints/handlers/negotiation" "k8s.io/apis...
return } } if err := checkName(obj, name, namespace, scope.Namer); err != nil { scope.err(err, w, req) return } userInfo, _ := request.UserFrom(ctx) transformers := []rest.TransformFunc{} // allows skipping managedFields update if the resulting object is too big shouldUpdateManagedFields :...
if objectMeta, err := meta.Accessor(obj); err == nil { // ensure namespace on the object is correct, or error if a conflicting namespace was set in the object if err := rest.EnsureObjectNamespaceMatchesRequestNamespace(rest.ExpectedNamespaceForResource(namespace, scope.Resource), objectMeta); err != nil { s...
random_line_split
update.go
" "k8s.io/apiserver/pkg/endpoints/handlers/finisher" requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics" "k8s.io/apiserver/pkg/endpoints/handlers/negotiation" "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/apiserver/pkg/registry/rest" "k8s.io/apiserver/pkg/util/dryrun" "k8s.io/component-base/traci...
{ if accessor, accessorErr := meta.Accessor(obj); accessorErr == nil { accessor.SetManagedFields(nil) shouldUpdateManagedFields = false result, err = requestFunc() } }
conditional_block
update.go
.err(err, w, req) return } options.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("UpdateOptions")) s, err := negotiation.NegotiateInputSerializer(req, false, scope.Serializer) if err != nil { scope.err(err, w, req) return } defaultGVK := scope.Kind original := r.New() valida...
{ if uo == nil { return nil } co := &metav1.CreateOptions{ DryRun: uo.DryRun, FieldManager: uo.FieldManager, FieldValidation: uo.FieldValidation, } co.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("CreateOptions")) return co }
identifier_body
plugin.go
for containers var envDefault []core_v1.EnvVar // ASAP public key servers // we want every container to know where to get the public keys // regardless if they're using ASAP or not envDefault = append(envDefault, asapkey.GetPublicKeyRepoEnvVars(context.StateContext.Location)...) // always bind to the common se...
buildKube2iamRoles
identifier_name
plugin.go
Ref) // default env vars for containers var envDefault []core_v1.EnvVar // ASAP public key servers // we want every container to know where to get the public keys // regardless if they're using ASAP or not envDefault = append(envDefault, asapkey.GetPublicKeyRepoEnvVars(context.StateContext.Location)...) // al...
{ metrics := make([]autoscaling_v2b1.MetricSpec, len(spec.Scaling.Metrics)) for i, m := range spec.Scaling.Metrics { metrics[i] = m.ToKubeMetric() } return autoscaling_v2b1.HorizontalPodAutoscalerSpec{ ScaleTargetRef: autoscaling_v2b1.CrossVersionObjectReference{ APIVersion: apps_v1.SchemeGroupVersion.Stri...
identifier_body
plugin.go
nil } func validateScaling(s Scaling) error { // we only need to validate when min & max are both positive; // if one or more are 0, it means we provision a deployment with no HPA if s.MinReplicas > 0 && s.MaxReplicas > 0 && s.MinReplicas > s.MaxReplicas { return errors.Errorf("MaxReplicas (%d) must be great...
Resource: secretResource.Name, Path: metadataNamePath, } falseObj := false envFromSource := core_v1.EnvFromSource{ SecretRef: &core_v1.SecretEnvSource{ LocalObjectReference: core_v1.LocalObjectReference{ Name: secretRef.Ref(), }, Optional: &falseObj, }, } envFrom = append(env...
secretRef := smith_v1.Reference{ Name: wiringutil.ReferenceName(secretResource.Name, metadataElement, nameElement),
random_line_split
plugin.go
nil } func validateScaling(s Scaling) error { // we only need to validate when min & max are both positive; // if one or more are 0, it means we provision a deployment with no HPA if s.MinReplicas > 0 && s.MaxReplicas > 0 && s.MinReplicas > s.MaxReplicas { return errors.Errorf("MaxReplicas (%d) must be great...
} // Reference environment variables retrieved from ServiceBinding objects if len(bindingResult) > 0 { var secretResource smith_v1.Resource var err error if shouldUseSecretPlugin { secretRefs, envVars, err := compute.GenerateEnvVars(spec.RenameEnvVar, bindingResult) if err != nil { return nil, fal...
{ shouldUseSecretPlugin = false }
conditional_block
redData_extFunction.py
1) print() time.sleep(2) for item in line5: sys.stdout.write(item) sys.stdout.flush() time.sleep(0.1) print() time.sleep(2) for item in line6: sys.stdout.write(item) sys.stdout.flush() time.sleep(0.1) print() time.sleep(2) for item in line7: sys.stdout.write(item) sys.s...
connect
identifier_name
redData_extFunction.py
you since you first started looking into this.. Havoc Dynamics company." line4 = "As you've just seen, their final test went critical, and thus far, it's killed many workers." line5 = "We can't let you walk away with you knowing what they were doing there." line6 = "Havoc was meant to silently go under, but with...
print("Incorrect password.") return
conditional_block
redData_extFunction.py
(2) for item in line8: sys.stdout.write(item) sys.stdout.flush() time.sleep(0.1) print() time.sleep(2) for item in line9: sys.stdout.write(item) sys.stdout.flush() time.sleep(0.3) print() time.sleep(2) print("\033[1;37;41m END OF LINE.") sys.exit(0) def formLoad(file): with o...
global currentFolder global connected connected = True if netLocation in netList: loadDot = "..." print("Connecting to address", end='') for item in loadDot: sys.stdout.write(item) sys.stdout.flush() time.sleep(0.8) print() connectMsgcheck = netLocation + "-connectMsg.txt" ...
identifier_body
redData_extFunction.py
: SHTIKH3912\nAMSPEC Temp: 79C\nSystem Status: Stable") time.sleep(3) os.system('clear') print("robertcapluund.security: It's going to go critical! Everyone needs to get the hell out of here!\nCurrent Sample: SHTIKH3912\nAMSPEC Temp: 88C\nSystem Status: WARN") time.sleep(4) os.system('clear') print("simonhe...
"rm":"Deletes a file.",
random_line_split
lib.rs
, Cursor, PTraceState, PTraceStateRef, RegNum}; /// The result type returned by methods in this crate. pub type Result<T> = result::Result<T, Error>;
} /// The error type returned by methods in this crate. #[derive(Debug)] pub struct Error(ErrorInner); impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.0 { ErrorInner::Io(ref e) => fmt::Display::fmt(e, fmt), ErrorInner::Unwind(ref e)...
#[derive(Debug)] enum ErrorInner { Io(io::Error), Unwind(unwind::Error),
random_line_split
lib.rs
, Cursor, PTraceState, PTraceStateRef, RegNum}; /// The result type returned by methods in this crate. pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] enum
{ Io(io::Error), Unwind(unwind::Error), } /// The error type returned by methods in this crate. #[derive(Debug)] pub struct Error(ErrorInner); impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.0 { ErrorInner::Io(ref e) => fmt::Display::f...
ErrorInner
identifier_name
lib.rs
] { &self.threads } } /// Information about a thread of a remote process. #[derive(Debug, Clone)] pub struct Thread { id: u32, name: Option<String>, frames: Vec<Frame>, } impl Thread { /// Returns the thread's ID. #[inline] pub fn id(&self) -> u32 { self.id } /// R...
{ return Err(io::Error::new( io::ErrorKind::Other, format!("unexpected wait status {}", status), )); }
conditional_block
lib.rs
, Cursor, PTraceState, PTraceStateRef, RegNum}; /// The result type returned by methods in this crate. pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] enum ErrorInner { Io(io::Error), Unwind(unwind::Error), } /// The error type returned by methods in this crate. #[derive(Debug)] pub struct Er...
} else { return Err(Error(ErrorInner::Io(e))); }, }; threads.insert(thread); } } Ok(()) } fn get_name(pid: u32, tid: u32) -> Option<String> { let path = format!("/proc/{}/task/{}/comm", pid, tid); let mut name = vec![...
{ for entry in fs::read_dir(dir).map_err(|e| Error(ErrorInner::Io(e)))? { let entry = entry.map_err(|e| Error(ErrorInner::Io(e)))?; let pid = match entry .file_name() .to_str() .and_then(|s| s.parse::<u32>().ok()) { Some(pid) => pid, ...
identifier_body
pyBasic.py
you to catch certain exceptions and also execute certain code depending on the exception print("The number you provided can't divide 1 because it is 0") except ValueError: print("You did not provide a number") except: # You can also have an empty except at the end to catch an unexpec...
= input("Enter a first number: ") intA = int(inpA) inpB = input("Enter a second number: ") intB = int(inpB) added = intA + intB return added # Returns the result of the function pr
identifier_body
pyBasic.py
become False) while True: inp = input("Enter 'yes', 'no' or 'quit': ") if inp == "quit": break print(inp) print("Au revoir") #TRY & EXCEPT x = input("Enter your age: ") try: age=int(x) except: print("Not a number") print("Voilà") a = 1 try: # Python tries to execute the code ...
("I know you !") els
conditional_block
pyBasic.py
a number!") continue print("Have a good day !") #LOOP IDIOMS #FINDING THE LARGEST VALUE largest_so_far = None print("Before",largest_so_far) for num in [89,34,3,5,34,65,23,54,234,54,345]: if largest_so_far is None or largest_so_far < num: largest_so_far = num print(largest_so_far,num) print("After",largest...
Dictionary(**ar
identifier_name
pyBasic.py
cc = str(bb) # to string print(cc) print(type(cc)) dd = int(aa) # to integer print(dd) print(type(dd)) bool("1") # cast to a boolean value bool(1) bool(0) int(True) int(False) my_age = 39 print(my_age) my_age += 1 #shortcut to update a value print(my_age) #NUMERIC EXPRESSIONS a = 3 aa = a**2 # puissance pr...
print(type(aa)) # impression du typage bb = float(aa) # to float print(bb) print(type(bb))
random_line_split
lib.rs
#[derive(Debug, Eq, PartialEq)] /// struct Submarine(usize); /// /// assert!(topo::Env::get::<Submarine>().is_none()); /// /// topo::call!({ /// assert_eq!(&Submarine(1), &*topo::Env::get::<Submarine>().unwrap()); /// /// topo::call!({ /// assert_eq!(&Submarine(2), &*topo::Env::get::<Submarine...
ty: TypeId, count: usize, } impl
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] struct Callsite {
random_line_split
lib.rs
current scope in the call topology. pub fn current() -> Self { fn assert_send_and_sync<T>() where T: Send + Sync, { } assert_send_and_sync::<Id>(); CURRENT_POINT.with(|p| p.borrow().id) } } /// The root of a sub-graph within the overall t...
call_env
identifier_name
lib.rs
#[derive(Debug, Eq, PartialEq)] /// struct Submarine(usize); /// /// assert!(topo::Env::get::<Submarine>().is_none()); /// /// topo::call!({ /// assert_eq!(&Submarine(1), &*topo::Env::get::<Submarine>().unwrap()); /// /// topo::call!({ /// assert_eq!(&Submarine(2), &*topo::Env::get::<Submarine...
; let parent = replace(&mut *parent, child); scopeguard::guard( (parent_initial_state, parent), move |(prev_initial_state, mut prev)| { if reset_on_drop { prev.state = prev_initial_state; } ...
{ parent.child(callsite_ty, add_env) }
conditional_block
lib.rs
The variables `root_ids` and /// `child_ids` observe the identifiers of the /// /// ``` /// # use topo::{self, *}; /// # use std::collections::{HashMap, HashSet}; /// struct LoopCount(usize); /// /// let mut count = 0; /// let mut exit = false; /// let mut root_ids = HashSet::new(); /// let mut child_ids = ...
{ Point::with_current(|current| { current .state .env .inner .get(&TypeId::of::<E>()) .map(|guard| { OwningRef::new(guard.to_owned()).map(|anon| anon.downcast_ref().unwrap()) ...
identifier_body
lib.rs
like they each contain a single number; the bots //! must use some logic to decide what to do with each chip. You access the local control //! computer and download the bots' instructions (your puzzle input). //! //! Some of the instructions specify that a specific-valued microchip should be given to a //! specific bo...
(bot_id: Id, low_dest: Receiver, high_dest: Receiver) -> Instruction { Instruction::Transfer { bot_id, low_dest, high_dest, } } } /// Process a list of instructions. /// /// Be careful--there's no guard currently in place against an incomplete list of instruction...
transfer
identifier_name
lib.rs
they each contain a single number; the bots //! must use some logic to decide what to do with each chip. You access the local control //! computer and download the bots' instructions (your puzzle input). //! //! Some of the instructions specify that a specific-valued microchip should be given to a //! specific bot; th...
} Entry::Vacant(entry) => { entry.insert(value); Ok(()) } }, }; give_to_receiver(low, low_dest)?; ...
{ Ok(()) }
conditional_block
lib.rs
it puts the value-2 chip in output 1 and gives the //! value-3 chip to bot 0. //! - Finally, bot 0 has two microchips; it puts the 3 in output 2 and the 5 in output 0. //! //! In the end, output bin 0 contains a value-5 microchip, output bin 1 contains a value-2 //! microchip, and output bin 2 contains a value-3 micro...
assert_eq!(got, *parsed); } } }
random_line_split
lib.rs
they each contain a single number; the bots //! must use some logic to decide what to do with each chip. You access the local control //! computer and download the bots' instructions (your puzzle input). //! //! Some of the instructions specify that a specific-valued microchip should be given to a //! specific bot; th...
} /// Process a list of instructions. /// /// Be careful--there's no guard currently in place against an incomplete list of instructions /// leading to an infinite loop. pub fn process(instructions: &[Instruction]) -> Result<(Bots, Outputs), Error> { let mut bots = Bots::new(); let mut outputs = Outputs::new(...
{ Instruction::Transfer { bot_id, low_dest, high_dest, } }
identifier_body
detatt_mk.py
Cov matrix will be full-rank #used when the data are centered (because one entry is linear combination # of others) # #ns is the length of the spatial dimension (default is 1) #assumes order s=1,t=1; s=1,t=2;...; s=2,t=1; s=2,t=2;... # if grouped by time instead, change order to 'C' (only if no missing da...
if np.size(np.shape(C))>2: raise ValueError('input C has too many dimensions') if np.shape(C)[0]!=n or np.shape(C)[1]!=n: raise ValueError('dimensions of C must be consistent with dimensions of x0') #if ne is a single value, assume all signals have same ensemble size # and expand ne to size m if np.size(n...
raise ValueError('input x0 has too many dimensions')
conditional_block
detatt_mk.py
= np.eye(n) - 1./n u,s,v1 = linalg.svd(m) p = u[:,:-1].T if ns==1: xr = np.dot(p,x) yr = np.dot(p,y) cn1 = np.dot(p,noise1) cn2 = np.dot(p,noise2) else: yr = np.dot(p,np.reshape(y,(-1,ns),order=order)).flatten(order=order)[:,None] xr = np.zeros(((n-1)*ns,len(x[0,:]))) for j in ran...
import numpy as np from scipy import linalg, stats import warnings if np.shape(x)[0] != np.shape(y)[0]: raise ValueError('x and y must have same first dimension') n,m = np.shape(x) #time dimension, number of signals if np.shape(cn1)[0]!=n: raise ValueError('dimension mismatch: x and cn1') p1 = np.shape(c...
identifier_body
detatt_mk.py
(xL, center_flag=1): # given the control data xL formed into a nxp matrix, calculates the # regularized covariance matrix cl_hat # see Ribes et al. (2009) following Ledoit and Wolf (2004) # # gives the option to center the input matrix first (default); would set # flag to 0 if input matrix has already be...
regC
identifier_name
detatt_mk.py
# # to use: #import detatt_mk as da # #reduce dimensions #model response ensemble mean xem2 and obs y2 should be column data (and centered), so use [:,None] if a single forcing #xcl1 and xcl2 are the climate noise array (n_years x n_realizations) split into two parts #(xr,yr,cn1,cn2) = da.re...
# Megan Kirchmeier-Young # # Many functions adapted from other code as noted.
random_line_split
dtobuilder.go
.MetricFamily), } return b.Build() } type builder struct { Samples map[string]Sample Exemplars map[string]SeriesExemplar Metadata map[string]metadata.Metadata families []*dto.MetricFamily familyLookup map[string]*dto.MetricFamily } // Build converts the dtoBuilder's Samples, Exemplars, and Metadata int...
else if l.Name == model.QuantileLabel && mt == dto.MetricType_SUMMARY { continue } else if l.Name == model.BucketLabel && mt == dto.MetricType_HISTOGRAM { continue } res = append(res, &dto.LabelPair{ Name: pointer.String(l.Name), Value: pointer.String(l.Value), }) } sort.Slice(res, func(i, j i...
{ continue }
conditional_block
dtobuilder.go
.MetricFamily), } return b.Build() } type builder struct { Samples map[string]Sample Exemplars map[string]SeriesExemplar Metadata map[string]metadata.Metadata families []*dto.MetricFamily familyLookup map[string]*dto.MetricFamily } // Build converts the dtoBuilder's Samples, Exemplars, and Metadata int...
} sort.Slice(res, func(i, j int) bool { switch { case *res[i].Name < *res[j].Name: return true case *res[i].Value < *res[j].Value: return true default: return false } }) return res } func labelPairsEqual(a, b []*dto.LabelPair) bool { if len(a)
Name: pointer.String(l.Name), Value: pointer.String(l.Value), })
random_line_split
dtobuilder.go
.MetricFamily), } return b.Build() } type builder struct { Samples map[string]Sample Exemplars map[string]SeriesExemplar Metadata map[string]metadata.Metadata families []*dto.MetricFamily familyLookup map[string]*dto.MetricFamily } // Build converts the dtoBuilder's Samples, Exemplars, and Metadata int...
(a, b []*dto.LabelPair) bool { if len(a
labelPairsEqual
identifier_name
dtobuilder.go
MARY: // Summaries include metrics with the family name (for quantiles), // followed by _sum and _count suffixes. b.familyLookup[familyName] = mf b.familyLookup[familyName+"_sum"] = mf b.familyLookup[familyName+"_count"] = mf case dto.MetricType_HISTOGRAM: // Histograms include metrics for _bucket, ...
{ res := &dto.Exemplar{ Label: toLabelPairs(mt, e.Labels), Value: &e.Value, } if e.HasTs { res.Timestamp = timestamppb.New(time.UnixMilli(e.Ts)) } return res }
identifier_body
jti-grpc-client-python.py
# As per the .proto file, use 0xFFFFFFFF for all subscription identifiers. if INVOKE_GET_SUBSCRIPTIONS_FLAG: logger.info("Invoking 'getTelemetrySubscriptions()' ...") get_subscriptions_request = agent_pb2.GetSubscriptionsRequest(subscription_id = 0xFFFFFFFF) get_subscriptions_reply = stub.g...
setupLogging
identifier_name
jti-grpc-client-python.py
Multiple Sensor Subscriptions ... path1 = agent_pb2.Path(path="/interfaces/interface[name='ge-0/0/0']/state/", sample_frequency=5000) path2 = agent_pb2.Path(path="/junos/events/event[id=\'UI_COMMIT\']", sample_frequency=0) #path2 = agent_pb2.Path(path="/junos/events", sample_frequency=0) # Use Path(s)...
# for debugging purposes. main(sys.argv[1:])
random_line_split
jti-grpc-client-python.py
LECTOR_PORT = 50051 # MX2 - OpenConfig 0.0.0.10 - gRPC #DEVICE_IP = "10.49.126.157" # MX3 - OpenConfig 0.0.0.9 - Native & Syslog DEVICE_IP = "10.49.114.76" # Paul Abbott's Router #DEVICE_IP = "10.49.123.198" DEVICE_PASSWORD = "" DEVICE_PORT = "50051" DEVICE_USERNAME = "" INVOKE_GET_OPERATIONAL_STATE_FLAG = False INV...
producer.send(KAFKA_TOPIC_JUNIPER_INTERFACES, json_data) #producer.send('juniper', json_data)
conditional_block
jti-grpc-client-python.py
88 888 888 Y88888 888 # Y88b d88P 888 888 888 888 Y8888 888 # "Y8888P" 88888888 8888888 8888888888 888 Y888 888 # # # > Script: jti-grpc-client-python.py # > Author: Tech Mocha # > Company: Tech Mocha # > Version: 0.1 # > Revision Date: 20...
# As per the .proto file, use 0xFFFFFFFF for all subscription identifiers including agent-level operational stats. if INVOKE_GET_OPERATIONAL_STATE_FLAG: logger.info("Invoking 'getTelemetryOperationalState()' ...") get_oper_state_request = agent_pb2.GetOperationalStateRequest(subscription_id = 0x...
global args # STEP 1: Setup the logging so we can start to log debug info right away. setupLogging() logger.debug("\n\n\n--------------------[ JTI-GRPC-CLIENT: BEGIN EXECUTION ]--------------------") # STEP 2: Parse the argument list with which this script was invoked and set global variable 'args'. ...
identifier_body
testing.js
Kill monsters within 64 pixels of the strike this.monsterGroup.forEachAlive(function(monster) { if (this.game.math.distance( this.game.input.activePointer.x, this.game.input.activePointer.y, monster.x, monster.y) < 64) { monster.fr...
{ // For a branch y += this.game.rnd.integerInRange(10, 20); }
conditional_block
testing.js
// Show FPS this.game.time.advancedTiming = true; this.highscoreText = this.game.add.text( this.game.width - 240, 20, '', { font: '16px Arial', fill: '#ffffff' } ); this.timerText = this.game.add.text(20, 20, '', { ...
(game) { minutes = Math.floor(game.timer.duration.toFixed(0) / 60000) % 60; seconds = Math.floor(game.timer.duration.toFixed(0) / 1000) % 60; milliseconds = Math.floor(game.timer.duration.toFixed(0)) % 100; //If any of the digits becomes a single digit number, pad it with a zero ...
updateTimer
identifier_name
testing.js
// Show FPS this.game.time.advancedTiming = true; this.highscoreText = this.game.add.text( this.game.width - 240, 20, '', { font: '16px Arial', fill: '#ffffff' } ); this.timerText = this.game.add.text(20, 20, '', { ...
this.cooldownTimer.paused = true; //cooldownText } function timeIsOut() { var codestat = Config.pathed.code; var bugstat = Config.killed.bugs - Config.pathed.bugs;; stateText.text = " Time is up!\n Pathed Code: " + codestat.toString() + "\n Catched Buds: " + bugstat....
function timeCooldownFn() {
random_line_split
testing.js
: -10 }, 40, Phaser.Easing.Sinusoidal.InOut, false, 0, 5, true) .start(); } }; GameState.prototype.createNewMonster = function() { var monster = this.monsterGroup.getFirstDead(); // Recycle a dead monster if (monster) { monster.reset(this.game...
{}
identifier_body