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
index.js
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
chart_tools.format_axis_y(ax=ax, p_dict=P_DICT, k_dict=K_DICT, logger=LOG) for area in range(1, 9, 1): suppress_area = P_DICT.get(f"suppressArea{area}", False) # If the area is suppressed, remind the user they suppressed it. if suppress_area: LOG['Info'].append( ...
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
(): ... 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
=K_DICT, logger=LOG) chart_tools.format_axis_y(ax=ax, p_dict=P_DICT, k_dict=K_DICT, logger=LOG) for area in range(1, 9, 1): suppress_area = P_DICT.get(f"suppressArea{area}", False) # If the area is suppressed, remind the user they suppressed it.
# ============================== 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
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
. 有新audioId if (audioId && audioId != this.getId()){ this.change(audioId) return } //2. 当前播放音频地址未定义 if (_util.isUndefined(this._audio.audioUrl)) { this._setState("error", { code: -1, error: "暂无播放内容" }) return } //3.从分享直接进入播放页面,如果有在其他小程序播放音频,重新加载播放 if (_util.isUndefi...
音频数据 _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
:'play', 暂停:'pause', 停止:'stop', 结束:'end', 加载:'loading' getState() { return this._state; } // 是否正在播放 isPlaying() { return !this._isPaused } // 音频是否在播放 isCurrentId(audioId){ return audioId && audioId === this.getId() } //获取暂停的时间 getProgress() { return this._currTime } //获取当前音频时长 ...
identifier_name
AudioManager.js
this._setState("stop") this._resetAudioData() }) //完成 this._am.onEnded(() => { this._setState("end") this._resetAudioData() this.next() }) //出错 this._am.onError((error) => { this._resetAudioData() let errCode = error.errCode; let errMsg = errorList[errC...
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
(Model): #NUEVA CLASE CREADA @saving.allow_read_from_gcs def load_weights_new(self, filepath, skip_mismatch=False, reshape=False): """Loads all layer weights from a HDF5 save file. If `by_name` is False (default) weights are loaded based on the network's topolo...
(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
Aux(Model): #NUEVA CLASE CREADA @saving.allow_read_from_gcs def load_weights_new(self, filepath, skip_mismatch=False, reshape=False): """Loads all layer weights from a HDF5 save file. If `by_name` is False (default) weights are loaded based on the network's top...
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
Aux(Model): #NUEVA CLASE CREADA @saving.allow_read_from_gcs def load_weights_new(self, filepath, skip_mismatch=False, reshape=False): """Loads all layer weights from a HDF5 save file. If `by_name` is False (default) weights are loaded based on the network's top...
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
Aux(Model): #NUEVA CLASE CREADA @saving.allow_read_from_gcs def load_weights_new(self, filepath, skip_mismatch=False, reshape=False): """Loads all layer weights from a HDF5 save file. If `by_name` is False (default) weights are loaded based on the network's top...
Y_fix = preprocess_fixmaps(fixs[counter:counter + b_s], shape_r_out, shape_c_out) yield [preprocess_images(images[counter:counter + b_s], shape_r, shape_c), gaussian], [Y, Y, Y_fix] counter = (counter + b_s) % len(images) def generator_test(b_s, imgs_test_path): images = [imgs_test_path +...
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
pub fetched_at: Option<DateTime<Utc>>, // Link to use to download the above version pub downloadable_url: Url, } impl UpdateInfo { pub fn new(v: Version, url: Url) -> Self { UpdateInfo { version: v, fetched_at: None, downloadable_url: url, } } ...
} if let Some(ref updater_info) = *self.state.avail_release.borrow() { if *self.current_version() < updater_info.version {
random_line_split
imp.rs
.avail_release .borrow() .as_ref() .map(|ui| ui.version().clone()) } pub(super) fn
(&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
.avail_release .borrow() .as_ref() .map(|ui| ui.version().clone()) } pub(super) fn borrow_worker(&self) -> Ref<'_, Option<MPSCState>> { self.worker_state.borrow() } pub(super) fn borrow_worker_mut(&self) -> RefMut<'_, Option<MPSCState>> { self.worker...
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
.avail_release .borrow() .as_ref() .map(|ui| ui.version().clone()) } pub(super) fn borrow_worker(&self) -> Ref<'_, Option<MPSCState>> { self.worker_state.borrow() } pub(super) fn borrow_worker_mut(&self) -> RefMut<'_, Option<MPSCState>> { self.worker...
} 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
product bundle")?; fetch_data_for_product_bundle_v1(&product_bundle, &url, local_repo_dir, auth_flow, ui).await } /// Helper for `get_product_data()`, see docs there. pub async fn fetch_data_for_product_bundle_v1<I>( product_bundle: &sdk_metadata::ProductBundleV1, product_url: &url::Url, local_repo_di...
// 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
add_dir: &str, dir: bool, sdk_root: &Path, ) -> Result<PathBuf> { assert!(!product_url.fragment().is_none()); if let Some(path) = &path_from_file_url(product_url) { if dir { // TODO(fxbug.dev/98009): Unify the file layout between local and remote // product bundles to...
/// 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
paths. pub(crate) fn pb_dir_name(gcs_url: &url::Url) -> String { let mut gcs_url = gcs_url.to_owned(); gcs_url.set_fragment(None); use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; let mut s = DefaultHasher::new(); gcs_url.as_str().hash(&mut s); ...
test_local_path_helper
identifier_name
lib.rs
will be substituted with `{ RAW TEXT }`. Braces in `RAW TEXT` will be ignored by the transpiler. //! This is especially useful when surrounding blocks of CSS. extern crate proc_macro; use proc_macro2::TokenStream; use quote::quote; use syn; use syn::parse::Parse; use syn::parse_macro_input; use std::borrow::Cow; use ...
{ Self { src, chars: src.char_indices().peekable(), } }
identifier_body
lib.rs
//! This is especially useful when surrounding blocks of CSS. extern crate proc_macro; use proc_macro2::TokenStream; use quote::quote; use syn; use syn::parse::Parse; use syn::parse_macro_input; use std::borrow::Cow; use std::str::FromStr; /// Generates functions for rendering a template. /// Should be applied to a `...
next
identifier_name
lib.rs
placed inside of an `if` block. //! - `{:end}` ends an `if` block. //! //! #### `match` //! - `{:match EXPR}` begins an `match` block. //! - `{:case PATTERN}` begins a `case` block and must be placed inside of a `match` block. //! `PATTERN` can be any pattern that is accepted by rust inside of a `match` statement. ...
, _ => 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
/// Subsequent attributes must be in `key=value` format. Currently, /// the following keys are supported: /// /// | Key | Possible Values | Default Value | Description | /// |---|---|---|---| /// | `escape` | `"txt", "html"` | `"txt"` | What escaping mode to use. If `"html"` is selected, `<`, `>`, and `&` will be chang...
None => { break (idx, chr); }, Some(x) => *x, };
random_line_split
driver.rs
2"))] 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 = SimpleJITBuilder::with_isa( crate::build_isa(tcx.sess, false), cranelift_module::...
{ 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
it(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> { use rustc::middle::dependency_format::Linkage; let mut dylib_paths = Vec::new(); let crate_info = CrateInfo::new(tcx); let formats = tcx.sess.dependency_formats.borrow(); let data = formats.get(&CrateType::Executable).unwrap(); for &(cnum, _) i...
time
identifier_name
driver.rs
32")] panic!("jit not supported on wasm"); } 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_impor...
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
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
3_7393515027707347534_n.jpg?_nc_ht=scontent-frt3-2.cdninstagram.com", * "__v": 0, * "createdAt": 1558791065, * "group": "memes", * "mediaSource": "instagram", * "mediaSourceUri": "officialsoccermemes", * "profileAvatar": "https://scontent-frt3-2.cdninstagram.com/vp/92d40c8cf638...
tionHeaders(res, mod
identifier_name
server.js
instagram.com/vp/9b249cc679a62edd00eed68a563f89ed/5D7D74C1/t51.2885-15/e35/60600023_2336658259943893_7393515027707347534_n.jpg?_nc_ht=scontent-frt3-2.cdninstagram.com", * "__v": 0, * "createdAt": 1558791065, * "group": "memes", * "mediaSource": "instagram", * "mediaSourceUri": "offici...
errors = validationResult(req); if(!errors.isEmpty()) { res.status(422).json({errors: errors.array()}); } else { next(); } } /** *
identifier_body
server.js
"country": "France", * "country_code": "FR", * "name": "Ligue 1", * "season": "2018", * "season_end": "2019-05-25", * "season_start": "2018-08-10" * } * } * ] * * @apiErrorExample Error-Response: * HTTP/1.1 422 Unprocessable entity * * ...
* @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
_2.xml', 252: 'asterix_cat252_7_0.xml'} # , #252: 'asterix_cat252_6_1.xml'} def load_asterix_category_format(k): """ Return a Document object representing the content of the document from the given input. Args: k (int): The ASTERIX category. Returns: xml.dom.minidom: The Doc...
""" 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
', 10: 'asterix_cat010_1_1.xml', 19: 'asterix_cat019_1_2.xml', 20: 'asterix_cat020_1_7.xml', #21: 'asterix_cat021_0_23.xml', 21: 'asterix_cat021_0_26.xml', #21: 'asterix_cat021_1_8.xml', 23: 'asterix_cat023_0_13.xml', 30: 'asterix_cat030_6_2.xml', 31: 'asterix_cat031_6_2.xml', #3...
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
', 10: 'asterix_cat010_1_1.xml', 19: 'asterix_cat019_1_2.xml', 20: 'asterix_cat020_1_7.xml', #21: 'asterix_cat021_0_23.xml', 21: 'asterix_cat021_0_26.xml', #21: 'asterix_cat021_1_8.xml', 23: 'asterix_cat023_0_13.xml', 30: 'asterix_cat030_6_2.xml', 31: 'asterix_cat031_6_2.xml', #3...
(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
', 10: 'asterix_cat010_1_1.xml', 19: 'asterix_cat019_1_2.xml', 20: 'asterix_cat020_1_7.xml', #21: 'asterix_cat021_0_23.xml', 21: 'asterix_cat021_0_26.xml', #21: 'asterix_cat021_1_8.xml', 23: 'asterix_cat023_0_13.xml', 30: 'asterix_cat030_6_2.xml', 31: 'asterix_cat031_6_2.xml', #3...
# 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
Matrix<T> for ndarray::Array2<T> { #[inline] fn nrows(&self) -> usize { self.nrows() } #[inline] fn ncols(&self) -> usize { self.ncols() } #[inline] fn index(&self, row: usize, column: usize) -> T { self[[row, column]] } } /// Compute row minima in O(*m* + *...
sult[i] = (i - 1, diag); base = i - 1; tentative = i; finished = i; continue; } // Thi
conditional_block
lib.rs
/// /// It is an error to call this on a matrix with zero columns. pub fn smawk_row_minima<T: PartialOrd + Copy, M: Matrix<T>>(matrix: &M) -> Vec<usize> { // Benchmarking shows that SMAWK performs roughly the same on row- // and column-major matrices. let mut minima = vec![0; matrix.nrows()]; smawk_inn...
let
identifier_name
lib.rs
//! 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
inputs, it can use [`monge::is_monge`] to verify that a //! matrix is a Monge matrix. #![doc(html_root_url = "https://docs.rs/smawk/0.3.1")] #[cfg(feature = "ndarray")] pub mod brute_force; pub mod monge; #[cfg(feature = "ndarray")] pub mod recursive; /// Minimal matrix trait for two-dimensional arrays. /// /// Thi...
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
created, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format. // Example: `2018-04-03T21:10:29.600Z` TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"` // The OCID of the vault that contains this key. VaultId *string `mandatory:"true" json:"vaultId"` // Defined tags for t...
{ enum, ok := mappingKeyLifecycleStateEnumLowerCase[strings.ToLower(val)] return enum, ok }
identifier_body
key.go
// Example: `ENABLED` LifecycleState KeyLifecycleStateEnum `mandatory:"true" json:"lifecycleState"` // The date and time the key was created, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format. // Example: `2018-04-03T21:10:29.600Z` TimeCreated *common.SDKTime `mandatory:"true" json:"time...
GetMappingKeyLifecycleStateEnum
identifier_name
key.go
secrets, see the Vault Service // Secret Management API. For the API for retrieving secrets, see the Vault Service Secret Retrieval API.) // package keymanagement import ( "fmt" "github.com/oracle/oci-go-sdk/v60/common" "strings" ) // Key The representation of Key type Key struct { // The OCID of the compartme...
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
, see the Vault Service // Secret Management API. For the API for retrieving secrets, see the Vault Service Secret Retrieval API.) // package keymanagement import ( "fmt" "github.com/oracle/oci-go-sdk/v60/common" "strings" ) // Key The representation of Key type Key struct { // The OCID of the compartment that ...
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
// Else, we only have 1 location part, we cant reduce this, so return the initial location return position_location } } } else if move_y != 0 { last_part := parts[len(parts)-1] last_part_int, _ := strconv.Atoi(last_part) if move_y == 1 { fmt.Printf("DDD Move: DOWN\n") // Moving down, incremen...
{ //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
track of them processed_parts = append(processed_parts, cur_pos) // Pop off the first element, so we keep going if len(cur_parts) > 1 { cur_parts = cur_parts[1:len(cur_parts)] } else { cur_parts = make([]string, 0) } // If we have nothing left to process, return the result if len(cur_parts) == 0 ...
{ // 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
T\n", cur_data["list"]) cur_data_list := cur_data["list"].([]interface{}) // Using the cur_pos as the index offset, this works up until the "variadic" node (if present) if cur_pos >= 0 && cur_pos < len(cur_data_list) { result_cur_data := cur_data_list[cur_pos].(map[string]interface{}) var result_cur_recor...
"label": ddd_label, "name": html_element_name,
random_line_split
ddd.go
"nil", nil, nil } selected_key := keys[cur_pos] fmt.Printf("DddGetNodeCurrent: keydict: Selected Key: %s\n", selected_key) result_cur_data := cur_data["keydict"].(map[string]interface{})[selected_key].(map[string]interface{}) cur_record_data_map := GetResult(cur_record_data, type_map).(map[string]interfa...
DddRenderNode
identifier_name
sh_commands.py
> 0] def make_output_processor(buff): def process_output(line): print(line.rstrip()) buff.append(line) return process_output def device_lock_path(serialno): return "/tmp/device-lock-%s" % serialno def device_lock(serialno, timeout=3600): return filelock.FileLock(device_lock_path(...
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
> 0] def make_output_processor(buff): def process_output(line): print(line.rstrip()) buff.append(line) return process_output def device_lock_path(serialno): return "/tmp/device-lock-%s" % serialno def device_lock(serialno, timeout=3600): return filelock.FileLock(device_lock_path(...
(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
()) > 0] def make_output_processor(buff): def process_output(line): print(line.rstrip()) buff.append(line) return process_output def device_lock_path(serialno): return "/tmp/device-lock-%s" % serialno def device_lock(serialno, timeout=3600): return filelock.FileLock(device_lock_pa...
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
nos(target_socs=None): soc_serialnos_map = get_soc_serialnos_map() serialnos = [] if target_socs is None: target_socs = soc_serialnos_map.keys() for target_soc in target_socs: serialnos.extend(soc_serialnos_map[target_soc]) return serialnos def download_file(configs, file_name, out...
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
.Method != http.MethodGet { // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest // Authorization Servers MUST support the use of the HTTP GET and POST methods defined in // RFC 2616 [RFC2616] at the Authorization Endpoint. return httperr.Newf(http.StatusMethodNotAllowed, "%s (try GET or POS...
{ upstreamIDPNames = append(upstreamIDPNames, idp.GetName()) }
conditional_block
auth_handler.go
credential ) func NewHandler( downstreamIssuer string, idpLister oidc.UpstreamIdentityProvidersLister, oauthHelperWithoutStorage fosite.OAuth2Provider, oauthHelperWithStorage fosite.OAuth2Provider, generateCSRF func() (csrftoken.CSRFToken, error), generatePKCE func() (pkce.Code, error), generateNonce func() (n...
csrfValue, nonceValue, pkceValue, err := generateValues(generateCSRF, generateNonce, generatePKCE) if err != nil { plog.Error("authorize generate error", err) return err } csrfFromCookie := readCSRFCookie(r, cookieCodec) if csrfFromCookie != "" { csrfValue = csrfFromCookie } upstreamOAuthConfig := oauth2...
{ 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
a credential ) func NewHandler( downstreamIssuer string, idpLister oidc.UpstreamIdentityProvidersLister, oauthHelperWithoutStorage fosite.OAuth2Provider, oauthHelperWithStorage fosite.OAuth2Provider, generateCSRF func() (csrftoken.CSRFToken, error), generatePKCE func() (pkce.Code, error), generateNonce func() ...
( 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
a credential ) func NewHandler( downstreamIssuer string, idpLister oidc.UpstreamIdentityProvidersLister, oauthHelperWithoutStorage fosite.OAuth2Provider, oauthHelperWithStorage fosite.OAuth2Provider, generateCSRF func() (csrftoken.CSRFToken, error), generatePKCE func() (pkce.Code, error), generateNonce func() ...
} 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
.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
o_order.iter(); if let Some(&start) = iter.next() { ret.insert(start, self.cctx.mk_true()); for &n in iter { let reach_cond = self.cctx.mk_or_from_iter( // manually restrict to slice self.graph .edges_directe...
CfgNode::Code(AstNodeC::BasicBlock(block))
random_line_split
mod.rs
.cctx, region_graph, old_new_map[&header], ); let ast = dedup_conds::run(&mut self.actx, self.cctx, &region_conditions, ast); let ast = RegionAstContext::<A>::export(ast); refinement::simplify_ast_node::<A>(self.cctx, ast).unwrap_or_default() } /// Compu...
export
identifier_name
mod.rs
.edges.len()); let mut old_new_map = HashMap::with_capacity(slice.topo_order.len()); let mut region_conditions = Vec::new(); // move all region nodes into `region_graph`. for &old_n in &slice.topo_order { let cfg_node = mem::replace(&mut self.graph[old_n], CfgNode::Dummy("sa...
{ // 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
0],[5.000, 0.000, 0.000],[3.750, 0.000, -1.250],[3.750, 0.000, -0.624], [3.110, 0.000, -0.615],[2.928, 0.000, -1.211],[2.639, 0.000, -1.761],[2.242, 0.000, -2.240], [1.766, 0.000, -2.641],[1.211, 0.000, -2.920],[0.620, 0.000, -3.119],[0.626, 0.000, -3.750], [1.250, 0.000, -3.750],[0.000, 0.000, -5.000]] ctrlName = ...
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
.630],[-1.222, 0.000, 2.928],[-0.624, 0.000, 3.106],[-0.626, 0.000, 3.750], [-1.250, 0.000, 3.750],[0.000, 0.000, 5.000],[1.250, 0.000, 3.750],[0.626, 0.000, 3.750], [0.612, 0.000, 3.108],[1.210, 0.000, 2.932],[1.754, 0.000, 2.637],[2.245, 0.000, 2.249], [2.629, 0.000, 1.764],[2.930, 0.000, 1.216],[3.106, 0.000, 0.6...
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
.630],[-1.222, 0.000, 2.928],[-0.624, 0.000, 3.106],[-0.626, 0.000, 3.750], [-1.250, 0.000, 3.750],[0.000, 0.000, 5.000],[1.250, 0.000, 3.750],[0.626, 0.000, 3.750], [0.612, 0.000, 3.108],[1.210, 0.000, 2.932],[1.754, 0.000, 2.637],[2.245, 0.000, 2.249], [2.629, 0.000, 1.764],[2.930, 0.000, 1.216],[3.106, 0.000, 0.6...
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
.630],[-1.222, 0.000, 2.928],[-0.624, 0.000, 3.106],[-0.626, 0.000, 3.750], [-1.250, 0.000, 3.750],[0.000, 0.000, 5.000],[1.250, 0.000, 3.750],[0.626, 0.000, 3.750], [0.612, 0.000, 3.108],[1.210, 0.000, 2.932],[1.754, 0.000, 2.637],[2.245, 0.000, 2.249], [2.629, 0.000, 1.764],[2.930, 0.000, 1.216],[3.106, 0.000, 0.6...
(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
room this.duration_end = "-"; //end time duration this.mark = false; //mark variable used to check if a closed room has already been printed to section (avoid repeats) this.booker = "-"; } //Declaring each new room var room020 = new Room("020", "Basement", 6); var room120 = new Room("120", ...
() { 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
room this.duration_end = "-"; //end time duration this.mark = false; //mark variable used to check if a closed room has already been printed to section (avoid repeats) this.booker = "-"; } //Declaring each new room var room020 = new Room("020", "Basement", 6); var room120 = new Room("120", ...
} //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
room this.duration_end = "-"; //end time duration this.mark = false; //mark variable used to check if a closed room has already been printed to section (avoid repeats) this.booker = "-"; } //Declaring each new room var room020 = new Room("020", "Basement", 6);
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
Accéder au lien : " lang.linktext="Lien" lang.nofollow="Nofollow" lang.accesskey="Clé d\x27accès" lang.tabindex="Index de tabulation" lang.other="Autre" lang.cssclass="Classe" lang.internallink="Pages du site" lang.browse="Parcourir" lang.existinganchor="Sélectionner une ancre nommée de la page courante" lang.attr_tar...
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
grafana administrator password.") parser.add_option("-e", "--editor", dest="editor", help="Create a user with editing authority. You need to enter username, password and email address \ (this mailbox will be used to receive alarm messages) in order and separated the...
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
]: %s \33[0m' % msg) def error(msg, logout=True): print('\n\33[35m***[ERROR]: %s \33[0m' % msg) if logout: logger.error(msg) sys.exit(1) def load_user(): if os.path.exists(TMP_USERINFO): with open(TMP_USERINFO, "r") as user_info: userinfo = json.load(user_info) else: ...
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
grafana administrator password.") parser.add_option("-e", "--editor", dest="editor", help="Create a user with editing authority. You need to enter username, password and email address \ (this mailbox will be used to receive alarm messages) in order and separated the...
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
grafana administrator password.") parser.add_option("-e", "--editor", dest="editor", help="Create a user with editing authority. You need to enter username, password and email address \ (this mailbox will be used to receive alarm messages) in order and separated the...
(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
object, // D extends Diff<Data, Action> = Diff<Data, Action> // >(a: D, b: D) { // if (a.timestamp < b.timestamp) { // return 1; // } else if (a.timestamp > b.timestamp) { // return -1; // } else { // return 0; // } // } interface BaseDBMessage { type: string; } interface SendUpdate<Data exte...
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
object, // D extends Diff<Data, Action> = Diff<Data, Action> // >(a: D, b: D) { // if (a.timestamp < b.timestamp) { // return 1; // } else if (a.timestamp > b.timestamp) { // return -1; // } else { // return 0; // } // } interface BaseDBMessage { type: string; } interface SendUpdate<Data exte...
( 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
object, // D extends Diff<Data, Action> = Diff<Data, Action> // >(a: D, b: D) { // if (a.timestamp < b.timestamp) { // return 1; // } else if (a.timestamp > b.timestamp) { // return -1; // } else { // return 0; // } // } interface BaseDBMessage { type: string; } interface SendUpdate<Data exte...
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
BaseDBMessage { type: string; } interface SendUpdate<Data extends object, Action extends object> extends BaseDBMessage { type: "sendUpdate"; updates: Diff<Data, Action>[]; } interface SendInternals<Data extends object, Action extends object> { type: "sendInternals"; connectionIDs: string[]; diffStack: ...
{ 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
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
26268-26046+1 223 >>> pf(223) Counter({223: 1}) >>> np(223) 48 >>> John.vc() 879 >>> (Matthew-John).vc() 3779 >>> pf(_) Counter({3779: 1}) >>> np(3779) 526 >>> John[6:4].vn() 26262 >>> John[1:1]-John[6:4] John 1:1-6:4 (217 verses) >>> Matthew-John[6:4] Matthew 1:1-John 6:4 (3117 verses) >>> pf(26262) Counter({3: 2, 2: ...
>>> 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
""" self.stopped = True class LabelTracker: def __init__(self, camera_index, trackerType, webCam, video=None): self.tracker = None # initialize the bounding box coordinates of the object we are going to track self.initBB = None self.vs = None # initialize...
self.video_stream.stop()
conditional_block
label_tracking.py
""" 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 self.stopped: ...
"medianflow": cv2.TrackerMedianFlow_create, "mosse": cv2.TrackerMOSSE_create } # grab the appropriate object tracker using our dictionary of # OpenCV object tracker objects self.tracker = OPENCV_OBJECT_TRACKERS[self.trackerType]() ...
""" 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
(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
4: 'High', 5: 'Critical' } def get_scan_types(self): return ["Veracode Scan"] def get_label_for_scan_types(self, scan_type): return "Veracode Scan" def
(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
4: 'High', 5: 'Critical' } def get_scan_types(self): return ["Veracode Scan"] def get_label_for_scan_types(self, scan_type): return "Veracode Scan" def get_description_for_scan_types(self, scan_type): return "Detailed XML Report" def get_findings(self, fil...
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
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 SAST findings # This assumes `<category/>` only exists within the `<severity/>` nodes. for category_node in root.findall('x:sever...
random_line_split
parser.py
4: 'High', 5: 'Critical' } def get_scan_types(self): return ["Veracode Scan"] def get_label_for_scan_types(self, scan_type): return "Veracode Scan" def get_description_for_scan_types(self, scan_type): return "Detailed XML Report" def get_findings(self, fil...
@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
, kubeRegistry, &options, configCluster } // initializeCluster initializes the cluster by setting various handlers. func (m *Multicluster) initializeCluster(cluster *multicluster.Cluster, kubeController *kubeController, kubeRegistry *Controller, options Options, configCluster bool, clusterStopCh <-chan struct{}, ) { ...
createWleConfigStore
identifier_name
multicluster.go
Options // client for reading remote-secrets to initialize multicluster registries client kubernetes.Interface s server.Instance closing bool serviceEntryController *serviceentry.Controller configController model.ConfigStoreController XDSUpdater model.XDSUpdater m ...
// 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
opts Options // client for reading remote-secrets to initialize multicluster registries client kubernetes.Interface s server.Instance closing bool serviceEntryController *serviceentry.Controller configController model.ConfigStoreController XDSUpdater model.XDSUpdater m ...
} // 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
Options // client for reading remote-secrets to initialize multicluster registries client kubernetes.Interface s server.Instance closing bool serviceEntryController *serviceentry.Controller configController model.ConfigStoreController XDSUpdater model.XDSUpdater m ...
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
_service_port_internal", "8443") viper.SetDefault("env_injector_exec_dir", "/azure-keyvault/") viper.AutomaticEnv() } func init() { flag.StringVar(&params.version, "version", "", "Version of this component.") flag.StringVar(&params.versionEnvImage, "versionenvimage", "", "Version of the env image component.") fla...
} func createServerWithMTLS(caCert []byte, router http.Handler, url string) *http.Server { clientCertPool := x509.NewCertPool()
random_line_split
main.go
lsKeyFile string caCert []byte caKey []byte authType string useAuthService bool dockerImageInspectionTimeout int useAksCredentialsWithAcr bool authServiceName string authServicePort str...
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
lsKeyFile string caCert []byte caKey []byte authType string useAuthService bool dockerImageInspectionTimeout int useAksCredentialsWithAcr bool authServiceName string authServicePort str...
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
lsKeyFile string caCert []byte caKey []byte authType string useAuthService bool dockerImageInspectionTimeout int useAksCredentialsWithAcr bool authServiceName string authServicePort str...
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
_abi::proto::oak::application::{ node_configuration::ConfigType, ApplicationConfiguration, CryptoConfiguration, LogConfiguration, NodeConfiguration, }; use std::net::AddrParseError; use tokio::sync::oneshot; mod crypto; pub mod grpc; pub mod http; mod invocation; mod logger; mod roughtime; mod storage; mod was...
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
oak_abi::proto::oak::application::{ node_configuration::ConfigType, ApplicationConfiguration, CryptoConfiguration, LogConfiguration, NodeConfiguration, }; use std::net::AddrParseError; use tokio::sync::oneshot; mod crypto; pub mod grpc; pub mod http; mod invocation; mod logger; mod roughtime; mod storage; mod...
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
_abi::proto::oak::application::{ node_configuration::ConfigType, ApplicationConfiguration, CryptoConfiguration, LogConfiguration, NodeConfiguration, }; use std::net::AddrParseError; use tokio::sync::oneshot; mod crypto; pub mod grpc; pub mod http; mod invocation; mod logger; mod roughtime; mod storage; mod was...
{ 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
_abi::proto::oak::application::{ node_configuration::ConfigType, ApplicationConfiguration, CryptoConfiguration, LogConfiguration, NodeConfiguration, }; use std::net::AddrParseError; use tokio::sync::oneshot; mod crypto; pub mod grpc; pub mod http; mod invocation; mod logger; mod roughtime; mod storage; mod was...
}), Some(ConfigType::LogConfig(LogConfiguration {})) => Ok(CreatedNode { instance: Box::new(logger::LogNode::new(node_name)), // Allow the logger Node to declassify log messages in debug builds only. #[cfg(feature = "oak-unsafe")] ...
{ 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
Parameters contains parameters for list command. type ListParameters struct { Filters string PageLimit int64 PageMarker string Detail bool Count bool Shared bool ExcludeHRefs bool ParentFQName string ParentType string ParentUUIDs string BackrefUUIDs string // TODO(Daniel): ha...
{ _, 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
(*CLI, error) { return NewCLI( &HTTPConfig{ ID: viper.GetString("client.id"), Password: viper.GetString("client.password"), Endpoint: viper.GetString("client.endpoint"), AuthURL: viper.GetString("keystone.authurl"), Scope: keystone.NewScope( viper.GetString("client.domain_id"), viper.G...
// 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
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
"), Scope: keystone.NewScope( viper.GetString("client.domain_id"), viper.GetString("client.domain_name"), viper.GetString("client.project_id"), viper.GetString("client.project_name"), ), Insecure: viper.GetBool("insecure"), }, viper.GetString("client.schema_root"), ) } // NewCLI returns n...
DeleteResources
identifier_name
Payment-temp.js
return new Promise((resolve) => { const script = document.createElement("script"); script.src = src; script.onload = () => { resolve(true); }; script.onerror = () => { resolve(false); }; document.body.appendChild(script); }); }; const _DEV_ = document.domain === "localhost";...
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