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 |
|---|---|---|---|---|
index.js | const Discord = require('discord.js');
const config = require('./config.json');
const nodemailer = require("nodemailer");
const showdown = require('showdown');
const randtoken = require('rand-token');
const Keyv = require('keyv');
const crypto = require('crypto');
const os = require("os");
const hostname = os.hostname... |
const HOURS_TO_MILLISECONDS = 3600 * 1000;
const client = new Discord.Client();
const converter = new showdown.Converter();
// use Keyv with sqlite storage
const sqlite_uri = "sqlite://db.sqlite3";
const discordUserId2token = new Keyv(sqlite_uri, { namespace: "discord_user_id_to_token" }); // Discord User-ID / token... | {
// The id is the first and only match found by the RegEx.
const matches = mention.match(/^<@!?(\d+)>$/);
// If supplied variable was not a mention, matches will be null instead of an array.
if (!matches) return;
// However the first element in the matches array will be the entire mention, not just the ID, so use... | identifier_body |
chart_area.py | # noqa pylint: disable=too-many-lines, line-too-long, invalid-name, unused-argument, redefined-builtin, broad-except, fixme
"""
Creates the Area charts
All steps required to generate area charts.
"""
# Built-in Modules
import itertools
import json
import sys
import traceback
# Third-party Modules
from matplotlib impo... |
chart_tools.format_custom_line_segments(
ax=ax,
plug_dict=PLUG_DICT,
p_dict=P_DICT,
k_dict=K_DICT,
logger=LOG,
orient="horiz"
)
chart_tools.format_grids(p_dict=P_DICT, k_dict=K_DICT, logger=LOG)
chart_tools.format_title(p_dict=P_DICT, k_dict=K_DICT, loc=... | suppress_area = P_DICT.get(f'suppressArea{area}', False)
if P_DICT[f'area{area}Source'] not in ("", "None") and not suppress_area:
# Note that we do these after the legend is drawn so that these areas don't affect the
# legend.
# We need to reload the dates to ensure that t... | conditional_block |
chart_area.py | # noqa pylint: disable=too-many-lines, line-too-long, invalid-name, unused-argument, redefined-builtin, broad-except, fixme
"""
Creates the Area charts
All steps required to generate area charts.
"""
# Built-in Modules
import itertools
import json
import sys
import traceback
# Third-party Modules
from matplotlib impo... | ():
...
try:
ax = chart_tools.make_chart_figure(
width=P_DICT['chart_width'], height=P_DICT['chart_height'], p_dict=P_DICT
)
chart_tools.format_axis_x_ticks(ax=ax, p_dict=P_DICT, k_dict=K_DICT, logger=LOG)
chart_tools.format_axis_y(ax=ax, p_dict=P_DICT, k_dict=K_DICT, logger=LOG)
for... | __init__ | identifier_name |
chart_area.py | # noqa pylint: disable=too-many-lines, line-too-long, invalid-name, unused-argument, redefined-builtin, broad-except, fixme
"""
Creates the Area charts
All steps required to generate area charts.
"""
# Built-in Modules
import itertools
import json
import sys
import traceback
# Third-party Modules
from matplotlib impo... |
# ============================== Plot the Areas ===============================
# Plot the areas. If suppress_area is True, we skip it.
if P_DICT[f'area{area}Source'] not in ("", "None") and not suppress_area:
# If area color is the same as the background color, alert the user.
... | if suppress_area:
LOG['Info'].append(
f"[{CHART_NAME}] Area {area} is suppressed by user setting. You can re-enable it "
f"in the device configuration menu."
) | random_line_split |
chart_area.py | # noqa pylint: disable=too-many-lines, line-too-long, invalid-name, unused-argument, redefined-builtin, broad-except, fixme
"""
Creates the Area charts
All steps required to generate area charts.
"""
# Built-in Modules
import itertools
import json
import sys
import traceback
# Third-party Modules
from matplotlib impo... |
try:
ax = chart_tools.make_chart_figure(
width=P_DICT['chart_width'], height=P_DICT['chart_height'], p_dict=P_DICT
)
chart_tools.format_axis_x_ticks(ax=ax, p_dict=P_DICT, k_dict=K_DICT, logger=LOG)
chart_tools.format_axis_y(ax=ax, p_dict=P_DICT, k_dict=K_DICT, logger=LOG)
for area in ra... | ... | identifier_body |
AudioManager.js | import { Dialog } from "Dialog.js";
import makeCancelable from "Cancelable.js";
const _network = require('network.js')
let _util = require("utils.js")
const AUDIO_URL = "/lesson/lessonDetail"
const UPLOAD_URL = "/lesson/lessonListenRs"
const errorList = {
"10001": "系统错误",
"10002": "网络错误",
"10003": "文件错误",
"1000... | ayPage = _util.currPageRoute() == "audio/pages/lesson_audio/lesson_audio"
//上次已播放结束
// if (isPlayPage && learnTime + 1 >= totalTime) {
// Dialog.showPlayEnd(audio.title,
// {
// comfirm: () => { this._setAudio(audio) },
// cancel: () => { this._audio = a... | 音频数据
_play(_lessonId) {
this._loadData(_lessonId)
.then(audio => {
if (_util.isUndefined(audio)) return
//暂停正在播放音频
// if (!this._am.paused) this._am.stop()
let learnTime = _util.isRealNum(audio.learnTime) ? parseInt(audio.learnTime) : 0
let totalTime = _util.isRealNum... | identifier_body |
AudioManager.js | import { Dialog } from "Dialog.js";
import makeCancelable from "Cancelable.js";
const _network = require('network.js')
let _util = require("utils.js")
const AUDIO_URL = "/lesson/lessonDetail"
const UPLOAD_URL = "/lesson/lessonListenRs"
const errorList = {
"10001": "系统错误",
"10002": "网络错误",
"10003": "文件错误",
"1000... | identifier_name | ||
AudioManager.js | import { Dialog } from "Dialog.js";
import makeCancelable from "Cancelable.js";
const _network = require('network.js')
let _util = require("utils.js")
const AUDIO_URL = "/lesson/lessonDetail"
const UPLOAD_URL = "/lesson/lessonListenRs"
const errorList = {
"10001": "系统错误",
"10002": "网络错误",
"10003": "文件错误",
"1000... | this._setState("error", { code: -1, error: "暂无播放内容" })
return
}
//3.从分享直接进入播放页面,如果有在其他小程序播放音频,重新加载播放
let src = this._am.src
if (_util.isUndefined(src)) {
this._play(this.getId())
return
}
// 4. 暂停
if (!this._am.paused) {
this._am.pause()
return
}
/... | if (_util.isUndefined(audioUrl)) { | random_line_split |
main.py | from __future__ import division
import os
os.chdir("C:\\Users\\alebj\\Documents\\Python Scripts\\CNN Eye-Tracking")
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from tensorflow.keras.models import Model
from tensorflow.keras import Input #Ag... | (b_s, phase_gen='train'):
if phase_gen == 'train':
images = [imgs_train_path + f for f in os.listdir(imgs_train_path) if f.endswith(('.jpg', '.jpeg', '.png'))]
maps = [maps_train_path + f for f in os.listdir(maps_train_path) if f.endswith(('.jpg', '.jpeg', '.png'))]
fixs = [fixs_train_path +... | generator | identifier_name |
main.py | from __future__ import division
import os
os.chdir("C:\\Users\\alebj\\Documents\\Python Scripts\\CNN Eye-Tracking")
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from tensorflow.keras.models import Model
from tensorflow.keras import Input #Ag... | print("Compilado")
else:
raise NotImplementedError
if phase == 'train':
if nb_imgs_train % b_s != 0 or nb_imgs_val % b_s != 0:
print("The number of training and validation images should be a multiple of the batch size. Please change your batch size in... | m.compile(RMSprop(lr=1e-4),
loss=[kl_divergence, correlation_coefficient, nss]) | random_line_split |
main.py | from __future__ import division
import os
os.chdir("C:\\Users\\alebj\\Documents\\Python Scripts\\CNN Eye-Tracking")
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from tensorflow.keras.models import Model
from tensorflow.keras import Input #Ag... |
imgs_test_path = listaArg[2]
file_names = [f for f in os.listdir(imgs_test_path) if f.endswith(('.jpg', '.jpeg', '.png'))]
file_names.sort()
nb_imgs_test = len(file_names)
if nb_imgs_test % b_s != 0:
print("The number of test ima... | raise SyntaxError | conditional_block |
main.py | from __future__ import division
import os
os.chdir("C:\\Users\\alebj\\Documents\\Python Scripts\\CNN Eye-Tracking")
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from tensorflow.keras.models import Model
from tensorflow.keras import Input #Ag... |
def generator_test(b_s, imgs_test_path):
images = [imgs_test_path + "\\" + f for f in os.listdir(imgs_test_path) if f.endswith(('.jpg', '.jpeg', '.png'))]
images.sort()
gaussian = np.zeros((b_s, nb_gaussian, shape_r_gt, shape_c_gt))
#counter = 0
#while True:
# yield [preprocess_images(im... | if phase_gen == 'train':
images = [imgs_train_path + f for f in os.listdir(imgs_train_path) if f.endswith(('.jpg', '.jpeg', '.png'))]
maps = [maps_train_path + f for f in os.listdir(maps_train_path) if f.endswith(('.jpg', '.jpeg', '.png'))]
fixs = [fixs_train_path + f for f in os.listdir(fixs_tr... | identifier_body |
imp.rs | use super::{
anyhow, env, env_logger, remove_file, DateTime, PathBuf, Receiver, RefCell, Releaser, Result,
Url, Utc, Version, UPDATE_INTERVAL,
};
use crate::Updater;
use std::cell::Cell;
use std::cell::Ref;
use std::cell::RefMut;
use std::path::Path;
use std::sync::mpsc;
pub(super) const LATEST_UPDATE_INFO_CAC... | Ok(true)
} else {
Ok(false)
}
} else {
Ok(false)
}
}
#[allow(dead_code)]
#[deprecated(note = "update_ready_sync is deprecated. use init()")]
pub(super) fn _update_ready_sync(&self) -> Result<bool> {
// A None va... | }
if let Some(ref updater_info) = *self.state.avail_release.borrow() {
if *self.current_version() < updater_info.version { | random_line_split |
imp.rs | use super::{
anyhow, env, env_logger, remove_file, DateTime, PathBuf, Receiver, RefCell, Releaser, Result,
Url, Utc, Version, UPDATE_INTERVAL,
};
use crate::Updater;
use std::cell::Cell;
use std::cell::Ref;
use std::cell::RefMut;
use std::path::Path;
use std::sync::mpsc;
pub(super) const LATEST_UPDATE_INFO_CAC... | (&self) -> Ref<'_, Option<MPSCState>> {
self.worker_state.borrow()
}
pub(super) fn borrow_worker_mut(&self) -> RefMut<'_, Option<MPSCState>> {
self.worker_state.borrow_mut()
}
pub(super) fn download_url(&self) -> Option<Url> {
self.avail_release
.borrow()
... | borrow_worker | identifier_name |
imp.rs | use super::{
anyhow, env, env_logger, remove_file, DateTime, PathBuf, Receiver, RefCell, Releaser, Result,
Url, Utc, Version, UPDATE_INTERVAL,
};
use crate::Updater;
use std::cell::Cell;
use std::cell::Ref;
use std::cell::RefMut;
use std::path::Path;
use std::sync::mpsc;
pub(super) const LATEST_UPDATE_INFO_CAC... |
fn load() -> Result<UpdaterState> {
let data_file_path = Self::build_data_fn()?;
crate::Data::load_from_file(data_file_path)
.ok_or_else(|| anyhow!("cannot load cached state of updater"))
}
// Save updater's state
pub(super) fn save(&self) -> Result<()> {
let data_... | {
self.state.update_interval = t;
} | identifier_body |
imp.rs | use super::{
anyhow, env, env_logger, remove_file, DateTime, PathBuf, Receiver, RefCell, Releaser, Result,
Url, Utc, Version, UPDATE_INTERVAL,
};
use crate::Updater;
use std::cell::Cell;
use std::cell::Ref;
use std::cell::RefMut;
use std::path::Path;
use std::sync::mpsc;
pub(super) const LATEST_UPDATE_INFO_CAC... |
}
pub(super) fn last_check(&self) -> Option<DateTime<Utc>> {
self.state.last_check.get()
}
pub(super) fn set_last_check(&self, t: DateTime<Utc>) {
self.state.last_check.set(Some(t));
}
pub(super) fn update_interval(&self) -> i64 {
self.state.update_interval
}
... | {
let current_version = env::workflow_version()
.map_or_else(|| Ok(Version::new(0, 0, 0)), |v| Version::parse(&v))?;
let state = UpdaterState {
current_version,
last_check: Cell::new(None),
avail_release: RefCell::new(None),
... | conditional_block |
pbms.rs | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Private functionality for pbms lib.
use {
crate::{
gcs::{exists_in_gcs, fetch_from_gcs},
repo::fetch_package_repository_from_mirro... | let mut throttle = Throttle::from_duration(std::time::Duration::from_millis(500));
let url = product_uri.to_string();
while let Some(chunk) =
stream.try_next().await.with_context(|| format!("Downloading {}", product_uri))?
{
file.write_all(&chunk).await.with_context(|| format!("Writing {... | // the user will have trouble seeing anyway. Without throttling,
// around 20% of the execution time can be spent updating the
// progress UI. The throttle makes the overhead negligible. | random_line_split |
pbms.rs | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Private functionality for pbms lib.
use {
crate::{
gcs::{exists_in_gcs, fetch_from_gcs},
repo::fetch_package_repository_from_mirro... |
/// Separate the URL on the last "#" character.
///
/// If no "#" is found, use the whole input as the url.
///
/// "file://foo#bar" -> "file://foo"
/// "file://foo" -> "file://foo"
pub(crate) fn url_sans_fragment(product_url: &url::Url) -> Result<url::Url> {
let mut product_url = product_url.to_owned();
prod... | {
Ok(get_storage_dir().await?.join(pb_dir_name(product_url)))
} | identifier_body |
pbms.rs | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Private functionality for pbms lib.
use {
crate::{
gcs::{exists_in_gcs, fetch_from_gcs},
repo::fetch_package_repository_from_mirro... | () {
let sdk_prefix = PathBuf::from("/"); // this is only used for file paths
let url = url::Url::parse("fake://foo#bar").expect("url");
let path =
local_path_helper(&url, "foo", /*dir=*/ true, &sdk_prefix).await.expect("dir helper");
assert!(path.to_string_lossy().ends_with(... | test_local_path_helper | identifier_name |
lib.rs | //! `litem` is a compile-time templating library.
//!
//! At compile time, the `#[template]` attribute will read a template file,
//! parse it, and generate the rendering functions.
//!
//! ## Template Syntax
//! ### Expressions
//! - `{EXPR}` will expand to value of `EXPR`, which
//! can be any Rust expression that ... |
}
impl<'i> Iterator for TokenIterator<'i> {
type Item = Token<'i>;
fn next(&mut self) -> Option<Token<'i>> {
let (first_idx, first) = match self.chars.peek() {
None => return None,
Some(v) => *v,
};
let mut n_braces = 0;
let (final_idx, final_) = loop ... | {
Self {
src,
chars: src.char_indices().peekable(),
}
} | identifier_body |
lib.rs | //! `litem` is a compile-time templating library.
//!
//! At compile time, the `#[template]` attribute will read a template file,
//! parse it, and generate the rendering functions.
//!
//! ## Template Syntax
//! ### Expressions
//! - `{EXPR}` will expand to value of `EXPR`, which
//! can be any Rust expression that ... | (&mut self) -> Option<Token<'i>> {
let (first_idx, first) = match self.chars.peek() {
None => return None,
Some(v) => *v,
};
let mut n_braces = 0;
let (final_idx, final_) = loop {
let (idx, chr) = self.chars.next().unwrap();
let (next_idx... | next | identifier_name |
lib.rs | //! `litem` is a compile-time templating library.
//!
//! At compile time, the `#[template]` attribute will read a template file,
//! parse it, and generate the rendering functions.
//!
//! ## Template Syntax
//! ### Expressions
//! - `{EXPR}` will expand to value of `EXPR`, which
//! can be any Rust expression that ... | ,
_ => panic!("#[template]: expected name = value")
}
}
let escape_func = match escape.as_str() {
"txt" => |s: syn::Expr| -> TokenStream { (quote! { #s }) },
"html" => |s: syn::Expr| -> TokenStream {
let q = quote! {
::std::string::ToString::to_st... | {
let ident = val.path.get_ident().expect("#[template]: expected name = value; name must be identifier, not path");
match ident.to_string().as_str() {
"escape" => {
let type_ = match &val.lit {
syn::Lit::Str(s) => s.... | conditional_block |
lib.rs | //! `litem` is a compile-time templating library.
//!
//! At compile time, the `#[template]` attribute will read a template file,
//! parse it, and generate the rendering functions.
//!
//! ## Template Syntax
//! ### Expressions
//! - `{EXPR}` will expand to value of `EXPR`, which
//! can be any Rust expression that ... | if first != '{' && next_chr == '{' {
break (idx, chr);
}
if first == '{' {
if next_chr == '{' {
n_braces += 1;
}
if next_chr == '}' {
if n_braces == 0 {
se... | None => { break (idx, chr); },
Some(x) => *x,
};
| random_line_split |
driver.rs | use std::any::Any;
use std::ffi::CString;
use std::fs::File;
use std::os::raw::{c_char, c_int};
use rustc::middle::cstore::EncodedMetadata;
use rustc::mir::mono::{Linkage as RLinkage, Visibility};
use rustc::session::config::{DebugInfo, OutputType};
use rustc_codegen_ssa::back::linker::LinkerInfo;
use rustc_codegen_ss... |
fn codegen_mono_items<'tcx>(
tcx: TyCtxt<'tcx>,
module: &mut Module<impl Backend + 'static>,
debug_context: Option<&mut DebugContext<'tcx>>,
log: &mut Option<File>,
mono_items: FxHashMap<MonoItem<'tcx>, (RLinkage, Visibility)>,
) {
let mut cx = CodegenCx::new(tcx, module, debug_context);
t... | {
let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
let mono_items = cgus
.iter()
.map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
.flatten()
.collect::<FxHashMap<_, (_, _)>>();
codegen_mono_items(tcx, module, debug.as_mut(), log, mono_items);
... | identifier_body |
driver.rs | use std::any::Any;
use std::ffi::CString;
use std::fs::File;
use std::os::raw::{c_char, c_int};
use rustc::middle::cstore::EncodedMetadata;
use rustc::mir::mono::{Linkage as RLinkage, Visibility};
use rustc::session::config::{DebugInfo, OutputType};
use rustc_codegen_ssa::back::linker::LinkerInfo;
use rustc_codegen_ss... | <R>(name: &str, f: impl FnOnce() -> R) -> R {
println!("[{}] start", name);
let before = std::time::Instant::now();
let res = f();
let after = std::time::Instant::now();
println!("[{}] end time: {:?}", name, after - before);
res
}
| time | identifier_name |
driver.rs | use std::any::Any;
use std::ffi::CString;
use std::fs::File;
use std::os::raw::{c_char, c_int};
use rustc::middle::cstore::EncodedMetadata;
use rustc::mir::mono::{Linkage as RLinkage, Visibility};
use rustc::session::config::{DebugInfo, OutputType};
use rustc_codegen_ssa::back::linker::LinkerInfo;
use rustc_codegen_ss... | jit_module.finalize_definitions();
tcx.sess.abort_if_errors();
let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
println!("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set");
let f: extern "C" fn(c_int, *const *const c_char... | .unwrap();
codegen_cgus(tcx, &mut jit_module, &mut None, log);
crate::allocator::codegen(tcx.sess, &mut jit_module); | random_line_split |
driver.rs | use std::any::Any;
use std::ffi::CString;
use std::fs::File;
use std::os::raw::{c_char, c_int};
use rustc::middle::cstore::EncodedMetadata;
use rustc::mir::mono::{Linkage as RLinkage, Visibility};
use rustc::session::config::{DebugInfo, OutputType};
use rustc_codegen_ssa::back::linker::LinkerInfo;
use rustc_codegen_ss... |
run_aot(tcx, metadata, need_metadata_module, &mut log)
}
#[cfg(not(target_arch = "wasm32"))]
fn run_jit(tcx: TyCtxt<'_>, log: &mut Option<File>) -> ! {
use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
let imported_symbols = load_imported_symbols_for_jit(tcx);
let mut jit_builder = Sim... | {
#[cfg(not(target_arch = "wasm32"))]
let _: ! = run_jit(tcx, &mut log);
#[cfg(target_arch = "wasm32")]
panic!("jit not supported on wasm");
} | conditional_block |
server.js | const express = require('express');
const fileUpload = require('express-fileupload');
const { check, validationResult } = require('express-validator/check');
const moment = require('moment');
const config = require('../config');
const db = require('../db/db');
const Fixture = require('../db/models/fixture');
const Lea... | el, totalCountCondition, page) {
const totalCount = await model.countDocuments(totalCountCondition).catch(handleDbError(res));
let pageLast = Math.floor(totalCount / config.ITEMS_PER_PAGE);
if(totalCount % config.ITEMS_PER_PAGE === 0) pageLast -= 1;
res.set({
'X-Total-Count': totalCount,
'X-Limit': config.ITEMS... | tionHeaders(res, mod | identifier_name |
server.js | const express = require('express');
const fileUpload = require('express-fileupload');
const { check, validationResult } = require('express-validator/check');
const moment = require('moment');
const config = require('../config');
const db = require('../db/db');
const Fixture = require('../db/models/fixture');
const Lea... | Adds http pagination headers to server response
* @param {Object} res Express response object
* @param {Object} model Mongoose model
* @param {Object} totalCountCondition Condtition to get total number of records for model
* @param {Number} page Current page
* @returns {Object} Express response object
*/
asyn... | errors = validationResult(req);
if(!errors.isEmpty()) {
res.status(422).json({errors: errors.array()});
} else {
next();
}
}
/**
* | identifier_body |
server.js | const express = require('express');
const fileUpload = require('express-fileupload');
const { check, validationResult } = require('express-validator/check');
const moment = require('moment');
const config = require('../config');
const db = require('../db/db');
const Fixture = require('../db/models/fixture');
const Lea... | * @apiSuccessExample Success-Response:
* [
* {
* "_id": "5c81b165986149a3f58060e9",
* "id": 289,
* "__v": 0,
* "country": "Australia",
* "country_code": "AU",
* "name": "National Premier Leagues",
* "season": "2019",
* "season_end": "2019-08-18",
* "sea... | * @apiVersion 1.0.0
* @apiName GetLeagues
* @apiGroup League
* | random_line_split |
asterix_utils.py | """@package asterix
EUROCONTROL ASTERIX encoder
A library that encodes in the EUROCONTROL ASTERIX format as
specified in the document EUROCONTROL-SPEC-0149.
Edition Number: 2.1
Edition Date: 14/04/2013
Category specifications Xml files in the "config/" directory were taken from
https://github.com/CroatiaControlLtd/as... |
def encode_repetitive(db, tree):
"""
Returns the encoded Data Item as a repetitive Data Field.
Args:
dfd (dict): The dictionary with Data Item values.
tree (Document object): The rules to encode Data Item.
Returns:
(length, value) (tuples): The Data Field size and Data Field... | """
Returns the encoded Data Item as a variable length Data Field.
Args:
dfd (dict): The dictionary with Data Item values.
tree (Document object): The rules to encode Data Item.
Returns:
(length, value) (tuples): The Data Field size and Data Field.
"""
variable = None
... | identifier_body |
asterix_utils.py | """@package asterix
EUROCONTROL ASTERIX encoder
A library that encodes in the EUROCONTROL ASTERIX format as
specified in the document EUROCONTROL-SPEC-0149.
Edition Number: 2.1
Edition Date: 14/04/2013
Category specifications Xml files in the "config/" directory were taken from
https://github.com/CroatiaControlLtd/as... |
cat = k
for cat_tree in ctf.getElementsByTagName('Category'):
if k != int(cat_tree.getAttribute('id')):
continue
for data_record in v:
ll_db, db = encode_category(k, data_record, cat_tree)
#TODO: use maximum datablock size
... | print 'encoding cat', k | conditional_block |
asterix_utils.py | """@package asterix
EUROCONTROL ASTERIX encoder
A library that encodes in the EUROCONTROL ASTERIX format as
specified in the document EUROCONTROL-SPEC-0149.
Edition Number: 2.1
Edition Date: 14/04/2013
Category specifications Xml files in the "config/" directory were taken from
https://github.com/CroatiaControlLtd/as... | (bd, tree):
"""
Returns the encoded Data Item as a fixed length Data Field.
Args:
dfd (dict): The dictionary with Data Item values.
tree (Document object): The rules to encode Data Item.
Returns:
(length, value) (tuples): The Data Field size and Data Field.
"""
length ... | encode_fixed | identifier_name |
asterix_utils.py | """@package asterix
EUROCONTROL ASTERIX encoder
A library that encodes in the EUROCONTROL ASTERIX format as
specified in the document EUROCONTROL-SPEC-0149.
Edition Number: 2.1
Edition Date: 14/04/2013
Category specifications Xml files in the "config/" directory were taken from
https://github.com/CroatiaControlLtd/as... | # Look for file in current executing directory
path_filename1 = filenames[k]
# On default directory (absolute)
path_filename2 = __basePath__ + "/" +filenames[k]
# On default directory (relative)
path_filename3 = os.path.dirname(os.path.realpath(__file__)) + "/xml/" + fi... | """
global filenames
try:
__basePath__ = os.path.abspath(os.path.join(os.getcwd(), '../../../..'))
| random_line_split |
lib.rs | //! This crate implements various functions that help speed up dynamic
//! programming, most importantly the SMAWK algorithm for finding row
//! or column minima in a totally monotone matrix with *m* rows and
//! *n* columns in time O(*m* + *n*). This is much better than the
//! brute force solution which would take O(... | rd case: row i-1 does not supply a column minimum in any
// column up to tentative. We simply advance finished while
// maintaining the invariant.
if m![i - 1, tentative] >= result[tentative].1 {
finished = i;
continue;
}
// Fourth and final case: a new c... | sult[i] = (i - 1, diag);
base = i - 1;
tentative = i;
finished = i;
continue;
}
// Thi | conditional_block |
lib.rs | //! This crate implements various functions that help speed up dynamic
//! programming, most importantly the SMAWK algorithm for finding row
//! or column minima in a totally monotone matrix with *m* rows and
//! *n* columns in time O(*m* + *n*). This is much better than the
//! brute force solution which would take O(... | matrix = vec![
vec![3], //
vec![2],
];
assert_eq!(smawk_row_minima(&matrix), vec![0, 0]);
assert_eq!(smawk_column_minima(&matrix), vec![1]);
}
#[test]
fn smawk_1x2() {
let matrix = vec![vec![2, 1]];
assert_eq!(smawk_row_minima(&matrix), vec![... | let | identifier_name |
lib.rs | //! This crate implements various functions that help speed up dynamic
//! programming, most importantly the SMAWK algorithm for finding row
//! or column minima in a totally monotone matrix with *m* rows and
//! *n* columns in time O(*m* + *n*). This is much better than the
//! brute force solution which would take O(... | //! vec![2, 1, 3, 3, 4],
//! vec![2, 1, 3, 3, 4],
//! vec![3, 2, 4, 3, 4],
//! vec![4, 3, 2, 1, 1],
//! ];
//! let minima = vec![1, 1, 4, 4, 4];
//! assert_eq!(smawk_column_minima(&matrix), minima);
//! ```
//!
//! The `minima` vector gives the index of the minimum value per
//! column, so `minima[0] ==... | //! ```
//! use smawk::{Matrix, smawk_column_minima};
//!
//! let matrix = vec![
//! vec![3, 2, 4, 5, 6], | random_line_split |
lib.rs | //! This crate implements various functions that help speed up dynamic
//! programming, most importantly the SMAWK algorithm for finding row
//! or column minima in a totally monotone matrix with *m* rows and
//! *n* columns in time O(*m* + *n*). This is much better than the
//! brute force solution which would take O(... | lumn minima in the given area of the matrix. The
/// `minima` slice is updated inplace.
fn smawk_inner<T: PartialOrd + Copy, M: Fn(usize, usize) -> T>(
matrix: &M,
rows: &[usize],
cols: &[usize],
mut minima: &mut [usize],
) {
if cols.is_empty() {
return;
}
let mut stack = Vec::with_... | nima = vec![0; matrix.ncols()];
smawk_inner(
&|i, j| matrix.index(i, j),
&(0..matrix.nrows()).collect::<Vec<_>>(),
&(0..matrix.ncols()).collect::<Vec<_>>(),
&mut minima,
);
minima
}
/// Compute co | identifier_body |
key.go | // Copyright (c) 2016, 2018, 2022, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose ei... | {
enum, ok := mappingKeyLifecycleStateEnumLowerCase[strings.ToLower(val)]
return enum, ok
} | identifier_body | |
key.go | // Copyright (c) 2016, 2018, 2022, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose ei... | (val string) (KeyLifecycleStateEnum, bool) {
enum, ok := mappingKeyLifecycleStateEnumLowerCase[strings.ToLower(val)]
return enum, ok
}
| GetMappingKeyLifecycleStateEnum | identifier_name |
key.go | // Copyright (c) 2016, 2018, 2022, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose ei... | if _, ok := GetMappingKeyLifecycleStateEnum(string(m.LifecycleState)); !ok && m.LifecycleState != "" {
errMessage = append(errMessage, fmt.Sprintf("unsupported enum value for LifecycleState: %s. Supported values are: %s.", m.LifecycleState, strings.Join(GetKeyLifecycleStateEnumStringValues(), ",")))
}
if _, ok :=... | random_line_split | |
key.go | // Copyright (c) 2016, 2018, 2022, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose ei... |
if len(errMessage) > 0 {
return true, fmt.Errorf(strings.Join(errMessage, "\n"))
}
return false, nil
}
// KeyProtectionModeEnum Enum with underlying type: string
type KeyProtectionModeEnum string
// Set of constants representing the allowable values for KeyProtectionModeEnum
const (
KeyProtectionModeHsm K... | {
errMessage = append(errMessage, fmt.Sprintf("unsupported enum value for ProtectionMode: %s. Supported values are: %s.", m.ProtectionMode, strings.Join(GetKeyProtectionModeEnumStringValues(), ",")))
} | conditional_block |
ddd.go | package ddd
import (
"strings"
"fmt"
"strconv"
"sort"
. "github.com/ghowland/yudien/yudienutil"
)
const (
type_int = iota
type_float = iota
type_string = iota
type_string_force = iota // This forces it to a string, even if it will be ugly, will print the type of the non-string data too. Testing t... |
func DddGet(position_location string, data_location string, ddd_data map[string]interface{}, udn_data map[string]interface{}) interface{} {
// Get the DDD Node that describes this position
//ddd_node := DddGetNode(position_location, ddd_data, udn_data)
//TODO(g): SECOND! We know the DDD information, so we navi... | {
//NOTE(g): This function doesnt check if the new position is valid, that is done by DddGet() which returns the DDD info at the current position (if valid, or nil
parts := strings.Split(position_location, ".")
fmt.Printf("DDD Move: Parts: %v\n", parts)
// Only allow X or Y movement, not both. This isnt a video... | identifier_body |
ddd.go | package ddd
import (
"strings"
"fmt"
"strconv"
"sort"
. "github.com/ghowland/yudien/yudienutil"
)
const (
type_int = iota
type_float = iota
type_string = iota
type_string_force = iota // This forces it to a string, even if it will be ugly, will print the type of the non-string data too. Testing t... | else {
unsorted = append(unsorted, new_item)
}
}
fmt.Printf("DddRenderNode: RowDict: Layout: %s\n\n", JsonDump(layout))
// Get the Y keys
y_keys := make([]int, len(layout))
i := 0
for key := range layout {
y_keys[i] = key
i++
}
sort.Ints(y_keys)
// Loop over our rows
max_y := ArrayI... | {
// Put them in Y first, because we care about ordering by rows first, then columns once in a specific row
if layout[int(value_map["y"].(float64))] == nil {
layout[int(value_map["y"].(float64))] = make(map[int]map[string]interface{})
}
layout[int(value_map["y"].(float64))][int(value_map["x"].(floa... | conditional_block |
ddd.go | package ddd
import (
"strings"
"fmt"
"strconv"
"sort"
. "github.com/ghowland/yudien/yudienutil"
)
const (
type_int = iota
type_float = iota
type_string = iota
type_string_force = iota // This forces it to a string, even if it will be ugly, will print the type of the non-string data too. Testing t... | "placeholder": "",
"size": "12",
"type": "select",
"value": "",
"value_match":"select_option_match",
"value_nomatch":"select_option_nomatch",
"null_message": "- Select to Navigate -",
"items": fmt.Sprintf("__input.%s", MapKeysToUdnMapForHtmlSelect(position_location, ddd_node["keydict"].(map[stri... | "label": ddd_label,
"name": html_element_name, | random_line_split |
ddd.go | package ddd
import (
"strings"
"fmt"
"strconv"
"sort"
. "github.com/ghowland/yudien/yudienutil"
)
const (
type_int = iota
type_float = iota
type_string = iota
type_string_force = iota // This forces it to a string, even if it will be ugly, will print the type of the non-string data too. Testing t... | (position_location string, ddd_id int64, temp_id int64, ddd_label string, ddd_node map[string]interface{}, ddd_cursor_data interface{}) []interface{} {
rows := make([]interface{}, 0)
//// Add the current row, so we work with them
//cur_row := make([]interface{}, 0)
//rows = append(rows, cur_row)
if ddd_node["typ... | DddRenderNode | identifier_name |
sh_commands.py | # Copyright 2018 Xiaomi, Inc. All rights reserved.
#
# 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... |
def bazel_build(target,
abi="armeabi-v7a", frameworks=None):
print("* Build %s with ABI %s" % (target, abi))
if abi == "host":
bazel_args = (
"build",
target,
)
else:
bazel_args = (
"build",
target,
"--con... | file_path = download_file(configs, "tensorflow-1.9.0-rc1.zip", output_dir)
sh.unzip("-o", file_path, "-d", "third_party/tflite") | identifier_body |
sh_commands.py | # Copyright 2018 Xiaomi, Inc. All rights reserved.
#
# 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... | (src_file, dst_dir, serialno):
src_checksum = file_checksum(src_file)
dst_file = os.path.join(dst_dir, os.path.basename(src_file))
stdout_buff = []
sh.adb("-s", serialno, "shell", "md5sum", dst_file,
_out=lambda line: stdout_buff.append(line))
dst_checksum = stdout_buff[0].split()[0]
... | adb_push_file | identifier_name |
sh_commands.py | # Copyright 2018 Xiaomi, Inc. All rights reserved.
#
# 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... | abis = [abi.strip() for abi in abilist_str.split(',')]
return abis
def file_checksum(fname):
hash_func = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_func.update(chunk)
return hash_func.hexdigest()
def adb_push_file(src_file, d... | props = adb_getprop_by_serialno(serialno)
abilist_str = props["ro.product.cpu.abilist"] | random_line_split |
sh_commands.py | # Copyright 2018 Xiaomi, Inc. All rights reserved.
#
# 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... |
return "".join(stdout_buff)
| for model_name in model_names:
print(framework, runtime, model_name)
args = "--run_interval=%d --num_threads=%d " \
"--framework=%s --runtime=%s --model_name=%s " \
"--product_soc=%s.%s" % \
(run_int... | conditional_block |
auth_handler.go | // Copyright 2020-2021 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package auth provides a handler for the OIDC authorization endpoint.
package auth
import (
"fmt"
"net/http"
"time"
coreosoidc "github.com/coreos/go-oidc/v3/oidc"
"github.com/ory/fosite"
"github.com/... |
for _, idp := range ldapUpstreams {
upstreamIDPNames = append(upstreamIDPNames, idp.GetName())
}
plog.Warning("Too many upstream providers are configured (found: %s)", upstreamIDPNames)
return nil, nil, httperr.New(
http.StatusUnprocessableEntity,
"Too many upstream providers are configured (support f... | {
upstreamIDPNames = append(upstreamIDPNames, idp.GetName())
} | conditional_block |
auth_handler.go | // Copyright 2020-2021 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package auth provides a handler for the OIDC authorization endpoint.
package auth
import (
"fmt"
"net/http"
"time"
coreosoidc "github.com/coreos/go-oidc/v3/oidc"
"github.com/ory/fosite"
"github.com/... |
func newAuthorizeRequest(r *http.Request, w http.ResponseWriter, oauthHelper fosite.OAuth2Provider) (fosite.AuthorizeRequester, bool) {
authorizeRequester, err := oauthHelper.NewAuthorizeRequest(r.Context(), r)
if err != nil {
plog.Info("authorize request error", oidc.FositeErrorForLog(err)...)
oauthHelper.Writ... | {
authorizeRequester, created := newAuthorizeRequest(r, w, oauthHelper)
if !created {
return nil
}
now := time.Now()
_, err := oauthHelper.NewAuthorizeResponse(r.Context(), authorizeRequester, &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
// Temporary claim values to allow `NewAuthorizeResponse` to p... | identifier_body |
auth_handler.go | // Copyright 2020-2021 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package auth provides a handler for the OIDC authorization endpoint.
package auth
import (
"fmt"
"net/http"
"time"
coreosoidc "github.com/coreos/go-oidc/v3/oidc"
"github.com/ory/fosite"
"github.com/... | (
r *http.Request,
w http.ResponseWriter,
oauthHelper fosite.OAuth2Provider,
generateCSRF func() (csrftoken.CSRFToken, error),
generateNonce func() (nonce.Nonce, error),
generatePKCE func() (pkce.Code, error),
oidcUpstream provider.UpstreamOIDCIdentityProviderI,
downstreamIssuer string,
upstreamStateEncoder oi... | handleAuthRequestForOIDCUpstream | identifier_name |
auth_handler.go | // Copyright 2020-2021 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package auth provides a handler for the OIDC authorization endpoint.
package auth
import (
"fmt"
"net/http"
"time"
coreosoidc "github.com/coreos/go-oidc/v3/oidc"
"github.com/ory/fosite"
"github.com/... | }
username := r.Header.Get(CustomUsernameHeaderName)
password := r.Header.Get(CustomPasswordHeaderName)
if username == "" || password == "" {
// Return an error according to OIDC spec 3.1.2.6 (second paragraph).
err := errors.WithStack(fosite.ErrAccessDenied.WithHintf("Missing or blank username or password."))... | authorizeRequester, created := newAuthorizeRequest(r, w, oauthHelper)
if !created {
return nil | random_line_split |
constants.js | /**
* Copyright (c) 2018 GrowthFile
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish... | .set('number', 'number')
.set('string', 'string')
.set('weekday', 'weekday')
.set('phoneNumber', 'phoneNumber')
.set('HH:MM', 'HH:MM')
.set('base64', 'base64');
/** Weekdays accepted in the attachment for the field `type` of `weekday`. */
const weekdays = new Map()
.set('monday', 'monday')
.set('tuesda... | .set('email', 'email') | random_line_split |
mod.rs | //! Recovers high-level control-flow constructs from a control-flow graph.
//! Implements the algorithm described in
//! [*No More Gotos*](https://doi.org/10.14722/ndss.2015.23185)
#![allow(dead_code)]
pub mod ast_context;
pub mod condition;
pub mod export;
mod ast;
mod dedup_conds;
mod graph_utils;
mod refinement;
... | }
pub fn mk_cond_node<'cd, A: AstContext>(
cctx: CondContext<'cd, A>,
cond: A::Condition,
) -> CfgNode<'cd, A> {
CfgNode::Condition(cctx.new_var(cond))
}
pub fn empty_node<A: AstContext>() -> CfgNode<'static, A> {
CfgNode::Code(AstNodeC::default())
}
impl<'cd, A> fmt::Debug for ControlFlowGraph<'cd, ... | CfgNode::Code(AstNodeC::BasicBlock(block)) | random_line_split |
mod.rs | //! Recovers high-level control-flow constructs from a control-flow graph.
//! Implements the algorithm described in
//! [*No More Gotos*](https://doi.org/10.14722/ndss.2015.23185)
#![allow(dead_code)]
pub mod ast_context;
pub mod condition;
pub mod export;
mod ast;
mod dedup_conds;
mod graph_utils;
mod refinement;
... | (ast: AstNode<'cd, Self>) -> AstNode<'cd, A> {
use self::AstNodeC::*;
match ast {
BasicBlock(b) => b,
Seq(seq) => Seq(seq.into_iter().map(Self::export).collect()),
Cond(c, t, oe) => Cond(
c,
Box::new(Self::export(*t)),
o... | export | identifier_name |
mod.rs | //! Recovers high-level control-flow constructs from a control-flow graph.
//! Implements the algorithm described in
//! [*No More Gotos*](https://doi.org/10.14722/ndss.2015.23185)
#![allow(dead_code)]
pub mod ast_context;
pub mod condition;
pub mod export;
mod ast;
mod dedup_conds;
mod graph_utils;
mod refinement;
... |
}
struct RegionAstContext<'cd, A>(PhantomData<(&'cd (), A)>);
impl<'cd, A: AstContext> AstContext for RegionAstContext<'cd, A> {
type Block = AstNode<'cd, A>;
type Condition = A::Condition;
type BoolVariable = A::BoolVariable;
type Variable = A::Variable;
}
impl<'cd, A: AstContext> RegionAstContext<... | {
// replace "normal" exit edges with "break"
{
let exit_edges: Vec<_> =
graph_utils::edges_from_region_to_node(&self.graph, &loop_nodes, final_succ)
.collect();
for exit_edge in exit_edges {
let break_node = self.graph.add_node... | identifier_body |
splineIK_FK.py | # -*- coding: UTF-8 -*-
import pymel.core as pm
def addAttributes(ctrlName,*attrs):
for attr in attrs:
pm.addAttr(ctrlName,ln = attr,at='double',min=0,max=10,keyable = 1)
def createTransform(**kwargs):
transformName = pm.createNode(kwargs['type'],name = kwargs['name'], ss = 1)
if 'p' in... |
def connectAttributes(source,target,sourceAttrList,targetAttrList):
for sourcAttr,targetAttr in zip(sourceAttrList,targetAttrList):
sAttr = pm.PyNode('%s.%s'%(source,sourcAttr))
tAttr = pm.PyNode('%s.%s'%(target,targetAttr))
sAttr.connect(tAttr,f = True)
name = 'Test'
number = 4
joints = pm.l... | position = ikConTr.t.get()
setRangeName = createTransform(type = 'setRange',name = '%s_SR'%(ikConTr))
conditionName = createTransform(type = 'condition',name = '%s_Condition'%(ikConTr))
range.outValueX.connect(setRangeName.valueX)
range.outValueX.connect(setRangeName.valueY)
range.outValueX.conn... | identifier_body |
splineIK_FK.py | # -*- coding: UTF-8 -*-
import pymel.core as pm
def addAttributes(ctrlName,*attrs):
for attr in attrs:
pm.addAttr(ctrlName,ln = attr,at='double',min=0,max=10,keyable = 1)
def createTransform(**kwargs):
transformName = pm.createNode(kwargs['type'],name = kwargs['name'], ss = 1)
if 'p' in... | pos = []
for num in range(number):
parameter = curveShapeName.findParamFromLength(length*num)
position = curveShapeName.getPointAtParam(parameter,space = 'world')
pos.append(position)
pm.refresh()
ikCtrlCrv,ikCtrlCrvShape= createCurve(pos,d = dergee,name = '%s_spineIKCtrlCurv... | length,curveLength = getIncrement(curveShapeName,number) | random_line_split |
splineIK_FK.py | # -*- coding: UTF-8 -*-
import pymel.core as pm
def addAttributes(ctrlName,*attrs):
for attr in attrs:
pm.addAttr(ctrlName,ln = attr,at='double',min=0,max=10,keyable = 1)
def createTransform(**kwargs):
transformName = pm.createNode(kwargs['type'],name = kwargs['name'], ss = 1)
if 'p' in... |
elif number >= 4:
dergee = 3
curveName,curveShapeName = createCurve(positions,d = 3,name = '%s_solCurve'%(name))
ctrlGrp.addChild(curveName)
cvList = curveShapeName.cv[:]
indices = cvList.indices()
pocNumber = len(indices)
length,curveLength = getIncrement(curveShapeName,nu... | dergee = 2 | conditional_block |
splineIK_FK.py | # -*- coding: UTF-8 -*-
import pymel.core as pm
def addAttributes(ctrlName,*attrs):
for attr in attrs:
pm.addAttr(ctrlName,ln = attr,at='double',min=0,max=10,keyable = 1)
def createTransform(**kwargs):
transformName = pm.createNode(kwargs['type'],name = kwargs['name'], ss = 1)
if 'p' in... | (name = 'name', num = 1,multiply = 1):
curveCtrl = pm.circle(c=(0, 0, 0), nr=(1, 0, 0), sw=360, d=3, name='{0}{2}{1:03d}'.format(name, num, 'Ctrl'))[0]
shape = curveCtrl.getShape()
shape.overrideEnabled.set(1)
shape.overrideColor.set(18)
pm.scale(shape.cv[:],multiply,multiply,multiply)
... | createcurveCube | identifier_name |
mainAdmin.js | //Fill with classes for rooms
//Rooms: 020, 120, 214, 216, 220, 222, 224, 226, 230, 301, 302, 306, 308, 310, 312, 314
//Variable declarations
var create_rn, tdirs, tdire, info, break_rn, tbr, cancel_rn, para, person;
//Room constructor function
var Room = function(number, floor, capacity) {
//Fields of Room class
... | () {
for(var i = 0; i < closed_rooms.length; i++) { //loop through closed_rooms array to find closed rooms to print
if(closed_rooms[i].mark == false) {
para = document.createElement("P"); //create new paragraph element
//update text content
para.innerHTML = "Room: " + closed_rooms[i... | update_listing | identifier_name |
mainAdmin.js | //Fill with classes for rooms
//Rooms: 020, 120, 214, 216, 220, 222, 224, 226, 230, 301, 302, 306, 308, 310, 312, 314
//Variable declarations
var create_rn, tdirs, tdire, info, break_rn, tbr, cancel_rn, para, person;
//Room constructor function
var Room = function(number, floor, capacity) {
//Fields of Room class
... |
//Call loadRooms() function to render content to page
loadRooms();
//Function to add closed rooms to "closed rooms" section at bottom
function update_listing() {
for(var i = 0; i < closed_rooms.length; i++) { //loop through closed_rooms array to find closed rooms to print
if(closed_rooms[i].mark == false) {... | {
for(var i = 0; i < rooms.length; i++) {
//if state checking if rooms are open to print availability in green
if(rooms[i].open == "Open") {
info = document.getElementsByClassName('a_room'); //get each <p> in html file to be able to print
info[i].innerHTML = "Room: " + rooms[i].number + " &ems... | identifier_body |
mainAdmin.js | //Fill with classes for rooms
//Rooms: 020, 120, 214, 216, 220, 222, 224, 226, 230, 301, 302, 306, 308, 310, 312, 314
//Variable declarations
var create_rn, tdirs, tdire, info, break_rn, tbr, cancel_rn, para, person;
//Room constructor function
var Room = function(number, floor, capacity) {
//Fields of Room class
... | var room120 = new Room("120", "First", 4);
var room214 = new Room("214", "Second", 6);
var room216 = new Room("216", "Second", 5);
var room220 = new Room("220", "Second", 6);
var room222 = new Room("222", "Second", 4);
var room224 = new Room("224", "Second", 8);
var room226 = new Room("226", "Second", 4);
var room230 =... | random_line_split | |
more-fr.js |
lang.rows="Lignes"
lang.cols="Colonnes"
lang.hotspot="Zone sensible"
lang.addhotspot="Créer une zone sensible"
lang.edithotspot="Modifier une zone sensible"
lang.deletehotspot="Supprimer une zone sensible"
lang.mapname="Nom de la carte"
lang.style="Style"
lang.box="Boîte"
lang.boxshadow="Ombre portée"
lang.color="C... | lang.msg_overwrite="Écraser"
lang.msg_rename="Renommer"
lang.msg_skip="Sauter"
lang.msg_requireselecteditems="S\x27il vous plaît sélectionner des dossiers ou des fichiers puis essayez à nouveau."
lang.msg_namebeused="Il existe déjà un fichier ou un dossier portant le même nom ({0}) à cet endroit."
lang.msg_sameforitems... | lang.msg_itemexists="Il existe déjà un fichier portant le même nom ({0}) à cet endroit. \x5C N \x5C nVoulez-vous remplacer le fichier existant?" | random_line_split |
grafana.py | #!/usr/bin/python
import os
import requests
import json
import logging
import time
import sys
import socket
import subprocess
import ConfigParser
from optparse import OptionParser
logger = logging.getLogger()
TMP_USERINFO = "/tmp/grafana_userinfo"
GRA_CONFILE = "/etc/grafana/grafana.ini"
log_file = '/var/log/grafana/I... | return options
def format_output(text):
num = len(text) + 4
print ('*' * num)
print (' ' + text)
print ('*' * num)
def log_output(msg):
logger.info("****%s****" % msg)
format_output(msg)
def skip(msg):
print('\33[32m***[SKIP]: %s \33[0m' % msg)
def info(msg):
print('\33[33m*... | help="Set the mailbox to send the alarm message. You need to enter email address, smtp server \
and password in order and separated them by comma. i.e. \"esgyn@qq.com,smtp.qq.com,password\"")
options, args = parser.parse_args() | random_line_split |
grafana.py | #!/usr/bin/python
import os
import requests
import json
import logging
import time
import sys
import socket
import subprocess
import ConfigParser
from optparse import OptionParser
logger = logging.getLogger()
TMP_USERINFO = "/tmp/grafana_userinfo"
GRA_CONFILE = "/etc/grafana/grafana.ini"
log_file = '/var/log/grafana/I... |
if __name__ == "__main__":
run()
| try:
set_logger(logger)
option = get_options()
print("\33[32m[Log file location]: %s \33[0m" % log_file)
admin_user, admin_psword = load_user()
grafana = Grafana(admin_user, admin_psword)
if option.admin_psword:
grafana.set_admin_psw(option.admin_psword)
... | identifier_body |
grafana.py | #!/usr/bin/python
import os
import requests
import json
import logging
import time
import sys
import socket
import subprocess
import ConfigParser
from optparse import OptionParser
logger = logging.getLogger()
TMP_USERINFO = "/tmp/grafana_userinfo"
GRA_CONFILE = "/etc/grafana/grafana.ini"
log_file = '/var/log/grafana/I... |
def set_editor(self, editor, editor_psword, email):
log_output("Create Editor")
editor_api = ':3000/api/admin/users'
data = {"name": editor, "email": email, "login": editor, "password": editor_psword}
editor = self.switch_request("post", editor_api, data)
if editor.status_c... | error("Password Update Error %s %s" % (put_psw, put_psw.text)) | conditional_block |
grafana.py | #!/usr/bin/python
import os
import requests
import json
import logging
import time
import sys
import socket
import subprocess
import ConfigParser
from optparse import OptionParser
logger = logging.getLogger()
TMP_USERINFO = "/tmp/grafana_userinfo"
GRA_CONFILE = "/etc/grafana/grafana.ini"
log_file = '/var/log/grafana/I... | (self):
log_output("Start Dashboard")
search_api = ':3000/api/search'
search = self.switch_request("get", search_api)
data = search.text.encode()
data = json.loads(data)
for d in data:
if d["uid"] == "esgyndb":
db_id = d["id"]
b... | start_db | identifier_name |
WebRTCDatabase.ts | /**
* This is a cool WebRTC Database. Basically, if you have
* a state you want to maintain across multiple clients, you
* can use this to handle updates
*
* @METEORCITY_CANDIDATE
*/
import PeerJS, { DataConnection } from "peerjs";
import base64 from "base-64";
interface Conn {
// this should be calculated usi... | updates: Diff<Data, Action>[];
}
interface SendInternals<Data extends object, Action extends object> {
type: "sendInternals";
connectionIDs: string[];
diffStack: Diff<Data, Action>[];
}
interface RequestInternals {
type: "requestInternals";
}
interface SendConnections {
type: "sendConnections";
connect... | type: "sendUpdate"; | random_line_split |
WebRTCDatabase.ts | /**
* This is a cool WebRTC Database. Basically, if you have
* a state you want to maintain across multiple clients, you
* can use this to handle updates
*
* @METEORCITY_CANDIDATE
*/
import PeerJS, { DataConnection } from "peerjs";
import base64 from "base-64";
interface Conn {
// this should be calculated usi... | (
diffs: Diff<Data, Action>[]
): Diff<Data, Action>[] {
return diffs.sort(sortDiffLeastToGreatest);
}
/**
* Utility function for getting diffs if there is at least
* one diff in the diff stack. Used as part of `applyDiffs`
*/
private getDiffsToApplyMany(
diffs: Diff<Data, Action>[]
): Di... | getDiffsToApplyEmpty | identifier_name |
WebRTCDatabase.ts | /**
* This is a cool WebRTC Database. Basically, if you have
* a state you want to maintain across multiple clients, you
* can use this to handle updates
*
* @METEORCITY_CANDIDATE
*/
import PeerJS, { DataConnection } from "peerjs";
import base64 from "base-64";
interface Conn {
// this should be calculated usi... | else {
diffsToApply = this.getDiffsToApplyMany(diffs);
}
// now that we have a list of diffs to apply:
// 1. cycle through them and apply the action to the reducer
// 2. add the diff back to the diffStack
let prevState = this.getState();
diffsToApply.forEach((diff) => {
diff.prevS... | {
diffsToApply = this.getDiffsToApplyEmpty(diffs);
} | conditional_block |
WebRTCDatabase.ts | /**
* This is a cool WebRTC Database. Basically, if you have
* a state you want to maintain across multiple clients, you
* can use this to handle updates
*
* @METEORCITY_CANDIDATE
*/
import PeerJS, { DataConnection } from "peerjs";
import base64 from "base-64";
interface Conn {
// this should be calculated usi... |
/**
* Just a utility function to handle messaging connections
*/
private message(conn: Conn, message: Message<Data, Action>) {
conn.lastUpdated = new Date().getTime();
conn.connection.send(message);
}
/**
* Connect to a database with a given Peer ID
*/
async connect(id: string): Promise... | {
this.connections.forEach((conn) => {
let diffs: Diff<Data, Action>[] = [];
if (conn.lastUpdated) {
diffs = this.getAllDiffsSince(conn.lastUpdated);
} else {
diffs = [...this.diffStack].reverse();
}
this.message(conn, { type: "sendUpdate", updates: diffs });
});
... | identifier_body |
john64.py | >>> from bible import *
>>> John[6]
John 6:1-71 (71 verses)
>>> p(_)
John 6
1 After these things Jesus went over the sea of Galilee, which is the sea of Tiberias.
2 And a great multitude followed him, because they saw his miracles which he did on them that were diseased.
3 And Jesus went up into a mountain, and there h... | there, save that one whereinto his disciples were entered, and that Jesus went not with his disciples into the boat, but that his disciples were gone away alone;
23 (Howbeit there came other boats from Tiberias nigh unto the place where they did eat bread, after that the Lord had given thanks:)
24 When the people ther... | them, It is I; be not afraid.
21 Then they willingly received him into the ship: and immediately the ship was at the land whither they went.
22 The day following, when the people which stood on the other side of the sea saw that there was none other boat | conditional_block |
john64.py | >>> from bible import *
>>> John[6]
John 6:1-71 (71 verses)
>>> p(_)
John 6
1 After these things Jesus went over the sea of Galilee, which is the sea of Tiberias.
2 And a great multitude followed him, because they saw his miracles which he did on them that were diseased.
3 And Jesus went up into a mountain, and there h... | 48
>>> 77+48
125
>>> b.count('Hebrew')
48
>>> b.count('Heber')
15
>>> b.count('Eber')
13
>>> b.count('circumcise')
49
>>> b.count('circumcision')
36
>>> b/'Jehovah'
Genesis 22:14;Exodus 6:3;17:15;Judges 6:24;Psalms 83:18;Isaiah 12:2;26:4 (7 verses)
>>> John[6].wc()
1506
>>> pf(_)
Counter({2: 1, 3: 1, 251: 1})
>>>
>>> ... | >>> b/'passover'
Exodus 12:11,21,27,43,48;34:25;Leviticus 23:5;Numbers 9:2,4-6,10,12-14;28:16;33:3;Deuteronomy 16:1-2,5-6;Joshua 5:10-11;2 Kings 23:21-23;2 Chronicles 30:1-2,5,15,17-18;35:1,6-9,11,13,16-19;Ezra 6:19-20;Ezekiel 45:21;Matthew 26:2,17-19;Mark 14:1,12,14,16;Luke 2:41;22:1,7-8,11,13,15;John 2:13,23;6:4;11:5... | random_line_split |
label_tracking.py | # Based on code from https://www.pyimagesearch.com/2018/07/30/opencv-object-tracking/
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
import cv2
from findSpine import findSpineBoundaries, findBookBoundaries
from utils import... |
# otherwise, release the file pointer
else:
self.vs.release()
# close all windows
cv2.destroyAllWindows()
return True
def center_spine(label_rectangle, camera_index, debug=False):
"""
Takes the rectangle around the label and
will adjust the robots posit... | self.video_stream.stop() | conditional_block |
label_tracking.py | # Based on code from https://www.pyimagesearch.com/2018/07/30/opencv-object-tracking/
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
import cv2
from findSpine import findSpineBoundaries, findBookBoundaries
from utils import... |
def track(self, label, debug=False):
"""
Takes a label and tracks it in a video or webcam stram.
Displays the video with the tracked objects.
Returns false if the label is lost
"""
prev_speed = 0
count_frames_speed_0 = 0
mv = MoveRobot()
# lo... | """
Set up everything for the video stream and tracking
"""
# extract the OpenCV version info
(major, minor) = cv2.__version__.split(".")[:2]
# if we are using OpenCV 3.2 OR BEFORE, we can use a special factory
# function to create our object tracker
if int(major)... | identifier_body |
label_tracking.py | # Based on code from https://www.pyimagesearch.com/2018/07/30/opencv-object-tracking/
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
import cv2
from findSpine import findSpineBoundaries, findBookBoundaries
from utils import... | (self):
"""
Starts the thread to read frames from the video stream
"""
Thread(target=self.update, args=()).start()
return self
def update(self):
"""
Loops indefinitely and reads frames until the thread is stopped
"""
while True:
if... | start | identifier_name |
parser.py | import re
import uuid
from datetime import datetime
from defusedxml import ElementTree
from dojo.models import Finding
from dojo.models import Endpoint
XML_NAMESPACE = {'x': 'https://www.veracode.com/schema/reports/export/1.0'}
class VeracodeParser(object):
"""This parser is written for Veracode Detailed XML r... | (self, scan_type):
return "Detailed XML Report"
def get_findings(self, filename, test):
root = ElementTree.parse(filename).getroot()
app_id = root.attrib['app_id']
report_date = datetime.strptime(root.attrib['last_update_time'], '%Y-%m-%d %H:%M:%S %Z')
dupes = dict()
... | get_description_for_scan_types | identifier_name |
parser.py | import re
import uuid
from datetime import datetime
from defusedxml import ElementTree
from dojo.models import Finding
from dojo.models import Endpoint
XML_NAMESPACE = {'x': 'https://www.veracode.com/schema/reports/export/1.0'}
class VeracodeParser(object):
"""This parser is written for Veracode Detailed XML r... |
finding.false_p = _false_positive
return finding
@classmethod
def __xml_static_flaw_to_finding(cls, app_id, xml_node, mitigation_text, test):
finding = cls.__xml_flaw_to_finding(app_id, xml_node, mitigation_text, test)
finding.static_finding = True
finding.dynamic_find... | _false_positive = True | conditional_block |
parser.py | import re
import uuid
from datetime import datetime
from defusedxml import ElementTree
from dojo.models import Finding
from dojo.models import Endpoint
XML_NAMESPACE = {'x': 'https://www.veracode.com/schema/reports/export/1.0'}
class VeracodeParser(object):
"""This parser is written for Veracode Detailed XML r... | "\n\n-----\n\n".format(
xml_node.attrib['cve_id'],
xml_node.attrib.get('first_found_date'),
xml_node.attrib['cvss_score'],
cls.vc_severity_mapping.get(int(xml_node.attrib['severity']), 'Info'),
xml_node.a... | random_line_split | |
parser.py | import re
import uuid
from datetime import datetime
from defusedxml import ElementTree
from dojo.models import Finding
from dojo.models import Endpoint
XML_NAMESPACE = {'x': 'https://www.veracode.com/schema/reports/export/1.0'}
class VeracodeParser(object):
"""This parser is written for Veracode Detailed XML r... |
@classmethod
def __xml_sca_flaw_to_finding(cls, test, report_date, vendor, library, version, xml_node):
# Defaults
finding = Finding()
finding.test = test
finding.static_finding = True
finding.dynamic_finding = False
# Report values
cvss_score = float(x... | cweSearch = re.search("CWE-(\\d+)", val, re.IGNORECASE)
if cweSearch:
return int(cweSearch.group(1))
else:
return None | identifier_body |
multicluster.go | // Copyright Istio 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 wri... | (client kubelib.Client, revision string, opts Options) model.ConfigStoreController {
log.Infof("Creating WorkloadEntry only config store for %s", opts.ClusterID)
workloadEntriesSchemas := collection.NewSchemasBuilder().
MustAdd(collections.WorkloadEntry).
Build()
crdOpts := crdclient.Option{Revision: revision, D... | createWleConfigStore | identifier_name |
multicluster.go | // Copyright Istio 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 wri... |
// ClusterDeleted is passed to the secret controller as a callback to be called
// when a remote cluster is deleted. Also must clear the cache so remote resources
// are removed.
func (m *Multicluster) ClusterDeleted(clusterID cluster.ID) {
m.m.Lock()
m.deleteCluster(clusterID)
m.m.Unlock()
if m.XDSUpdater != ni... | {
m.m.Lock()
m.deleteCluster(cluster.ID)
kubeController, kubeRegistry, options, configCluster := m.addCluster(cluster)
if kubeController == nil {
// m.closing was true, nothing to do.
m.m.Unlock()
return
}
m.m.Unlock()
// clusterStopCh is a channel that will be closed when this cluster removed.
m.initiali... | identifier_body |
multicluster.go | // Copyright Istio 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 wri... | }
// ClusterDeleted is passed to the secret controller as a callback to be called
// when a remote cluster is deleted. Also must clear the cache so remote resources
// are removed.
func (m *Multicluster) ClusterDeleted(clusterID cluster.ID) {
m.m.Lock()
m.deleteCluster(clusterID)
m.m.Unlock()
if m.XDSUpdater != n... | random_line_split | |
multicluster.go | // Copyright Istio 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 wri... |
if m.configController != nil && features.EnableAmbientControllers {
m.configController.RegisterEventHandler(gvk.AuthorizationPolicy, kubeRegistry.AuthorizationPolicyHandler)
m.configController.RegisterEventHandler(gvk.PeerAuthentication, kubeRegistry.PeerAuthenticationHandler)
}
if configCluster && m.serviceEn... | {
// Add an instance handler in the kubernetes registry to notify service entry store about pod events
kubeRegistry.AppendWorkloadHandler(m.serviceEntryController.WorkloadInstanceHandler)
} | conditional_block |
main.go | // Copyright © 2020 Sparebanken Vest
//
// 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... | clientCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCertPool,
PreferServerCipherSuites: true,
MinVersion: tls.VersionTLS12,
}
tlsConfig.BuildNameToCertificate()
return createServer(rou... | }
func createServerWithMTLS(caCert []byte, router http.Handler, url string) *http.Server {
clientCertPool := x509.NewCertPool() | random_line_split |
main.go | // Copyright © 2020 Sparebanken Vest
//
// 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... |
func initConfig() {
viper.SetDefault("azurekeyvault_env_image", "spvest/azure-keyvault-env:latest")
viper.SetDefault("docker_image_inspection_timeout", 20)
viper.SetDefault("docker_image_inspection_use_acs_credentials", true)
viper.SetDefault("auth_type", "cloudConfig")
viper.SetDefault("use_auth_service", true)
... |
if r.Method == "GET" {
w.WriteHeader(http.StatusOK)
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}
| identifier_body |
main.go | // Copyright © 2020 Sparebanken Vest
//
// 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... | ctx context.Context, obj metav1.Object) (bool, error) {
req := whcontext.GetAdmissionRequest(ctx)
var pod *corev1.Pod
switch v := obj.(type) {
case *corev1.Pod:
klog.InfoS("found pod to mutate", "pod", klog.KRef(req.Namespace, req.Name))
pod = v
default:
return false, nil
}
podsInspectedCounter.Inc()
e... | aultSecretsMutator( | identifier_name |
main.go | // Copyright © 2020 Sparebanken Vest
//
// 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... | else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}
func initConfig() {
viper.SetDefault("azurekeyvault_env_image", "spvest/azure-keyvault-env:latest")
viper.SetDefault("docker_image_inspection_timeout", 20)
viper.SetDefault("docker_image_inspection_use_acs_credentials", true)
viper.... |
w.WriteHeader(http.StatusOK)
} | conditional_block |
mod.rs | //
// Copyright 2020 The Project Oak 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 o... |
Some(ConfigType::GrpcClientConfig(config)) => {
let grpc_client_root_tls_certificate = self
.secure_server_configuration
.clone()
.grpc_config
.expect("no gRPC identity provided to Oak Runtime")
... | {
let wasm_module_bytes = self
.application_configuration
.wasm_modules
.get(&config.wasm_module_name)
.ok_or(ConfigurationError::IncorrectWebAssemblyModuleName)?;
Ok(CreatedNode {
instanc... | conditional_block |
mod.rs | //
// Copyright 2020 The Project Oak 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 o... | privilege: NodePrivilege::default(),
}),
Some(ConfigType::StorageConfig(_config)) => Ok(CreatedNode {
instance: Box::new(storage::StorageNode::new(node_name)),
privilege: NodePrivilege::default(),
}),
Some(ConfigType::HttpSe... | })
}
Some(ConfigType::RoughtimeClientConfig(config)) => Ok(CreatedNode {
instance: Box::new(roughtime::RoughtimeClientNode::new(node_name, config)), | random_line_split |
mod.rs | //
// Copyright 2020 The Project Oak 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 o... | {
pub application_configuration: ApplicationConfiguration,
pub permissions_configuration: PermissionsConfiguration,
pub secure_server_configuration: SecureServerConfiguration,
pub signature_table: SignatureTable,
pub kms_credentials: Option<std::path::PathBuf>,
}
impl NodeFactory<NodeConfiguration... | ServerNodeFactory | identifier_name |
mod.rs | //
// Copyright 2020 The Project Oak 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 o... |
}
/// A holder struct containing a [`Node`] instance, together with the [`NodePrivilege`] that is
/// assigned to it.
///
/// The reason the privilege is returned here and not by the node itself is that it should be
/// determined by the [`NodeFactory`] instance, so that an untrusted Node may not be able to
/// singl... | {
if !self
.permissions_configuration
.allowed_creation(node_configuration)
// TODO(#1027): Use anyhow or an improved ConfigurationError
.map_err(|_| ConfigurationError::InvalidNodeConfiguration)?
{
return Err(ConfigurationError::NodeCreationNo... | identifier_body |
cli.go | package client
import (
"context"
"net/http"
"net/url"
"path/filepath"
"strconv"
"time"
"github.com/Juniper/asf/pkg/fileutil"
"github.com/Juniper/asf/pkg/keystone"
"github.com/Juniper/asf/pkg/logutil"
"github.com/Juniper/asf/pkg/models"
"github.com/Juniper/asf/pkg/schema"
"github.com/Juniper/asf/pkg/servi... |
return &api, nil
}
func encodeToYAML(data interface{}) (string, error) {
o, err := yaml.Marshal(data)
if err != nil {
return "", err
}
return string(o), nil
}
| {
_, err := c.Read(context.Background(), serverSchema, &api)
if err == nil {
break
}
logrus.WithError(err).Warn("Failed to connect API Server - reconnecting")
time.Sleep(time.Second)
} | conditional_block |
cli.go | package client
import (
"context"
"net/http"
"net/url"
"path/filepath"
"strconv"
"time"
"github.com/Juniper/asf/pkg/fileutil"
"github.com/Juniper/asf/pkg/keystone"
"github.com/Juniper/asf/pkg/logutil"
"github.com/Juniper/asf/pkg/models"
"github.com/Juniper/asf/pkg/schema"
"github.com/Juniper/asf/pkg/servi... |
// SyncResources synchronizes state of resources specified in given file.
func (c *CLI) SyncResources(filePath string) (string, error) {
var req syncListRequest
if err := fileutil.LoadFile(filePath, &req); err != nil {
return "", err
}
for i := range req.Resources {
req.Resources[i].Data = fileutil.YAMLtoJSON... | {
r := Resources{}
for _, rawList := range response {
list, ok := rawList.([]interface{})
if !ok {
return nil, errors.Errorf("response should contain list of resources: %v", rawList)
}
for _, object := range list {
r[ResourcesKey] = append(r[ResourcesKey], map[string]interface{}{
KindKey: schemaID,... | identifier_body |
cli.go | package client
import (
"context"
"net/http"
"net/url"
"path/filepath"
"strconv"
"time"
"github.com/Juniper/asf/pkg/fileutil"
"github.com/Juniper/asf/pkg/keystone"
"github.com/Juniper/asf/pkg/logutil"
"github.com/Juniper/asf/pkg/models"
"github.com/Juniper/asf/pkg/schema"
"github.com/Juniper/asf/pkg/servi... | ResourcesKey = "resources"
)
const (
retryMax = 5
serverSchemaFile = "schema.json"
)
// CLI represents API Server's command line interface.
type CLI struct {
HTTP
schemaRoot string
log *logrus.Entry
}
// NewCLIByViper returns new logged in CLI client using Viper configuration.
func NewCLIByVipe... |
// YAML key names
const (
DataKey = "data"
KindKey = "kind" | random_line_split |
cli.go | package client
import (
"context"
"net/http"
"net/url"
"path/filepath"
"strconv"
"time"
"github.com/Juniper/asf/pkg/fileutil"
"github.com/Juniper/asf/pkg/keystone"
"github.com/Juniper/asf/pkg/logutil"
"github.com/Juniper/asf/pkg/models"
"github.com/Juniper/asf/pkg/schema"
"github.com/Juniper/asf/pkg/servi... | (filePath string) (string, error) {
var request deleteListRequest
if err := fileutil.LoadFile(filePath, &request); err != nil {
return "", nil
}
for _, r := range request.List {
if _, err := c.DeleteResource(r.Kind, r.Data.UUID); err != nil {
return "", err
}
}
return "", nil
}
func urlPath(schemaID, ... | DeleteResources | identifier_name |
Payment-temp.js | import React, { useState, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Stepper from "@material-ui/core/Stepper";
import Step from "@material-ui/core/Step";
import StepLabel from "@material-ui/core/StepLabel";
import Button from "@material-ui/core/Button";
import Typography fro... |
function getStepContent(stepIndex, buyerData) {
switch (stepIndex) {
case 0:
return (
<div>
{buyerData && (
<div style={{ background: "#ecf0f1", margin: "auto", width: 630 }}>
<font color="red" style={{ color: "red", fontWieght: "bold" }}>
<b>Deli... | </div>
);
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.