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 |
|---|---|---|---|---|
api.go | package cli
import (
"errors"
"fmt"
"os"
"strings"
multierror "github.com/hashicorp/go-multierror"
wso2am "github.com/uphy/go-wso2am"
"github.com/urfave/cli"
)
func (c *CLI) api() cli.Command {
return cli.Command{
Name: "api",
Aliases: []string{"a"},
Usage: "API management command",
Subcommands:... | var productionURL = ctx.String("production-url")
var sandboxURL = ctx.String("sandbox-url")
endpointConfig.ProductionEndpoints = &wso2am.APIEndpoint{
URL: productionURL,
}
if sandboxURL != "" {
endpointConfig.SandboxEndpoints = &wso2am.APIEndpoint{
URL: sandboxURL,
}
}
a... | random_line_split | |
api.go | package cli
import (
"errors"
"fmt"
"os"
"strings"
multierror "github.com/hashicorp/go-multierror"
wso2am "github.com/uphy/go-wso2am"
"github.com/urfave/cli"
)
func (c *CLI) api() cli.Command {
return cli.Command{
Name: "api",
Aliases: []string{"a"},
Usage: "API management command",
Subcommands:... | () cli.Command {
return cli.Command{
Name: "thumbnail",
Usage: "Download the thumbnail",
Action: func(ctx *cli.Context) error {
if ctx.NArg() != 1 {
return errors.New("ID is required")
}
id := ctx.Args().Get(0)
return c.client.Thumbnail(id, os.Stdout)
},
}
}
func (c *CLI) apiUploadThumbnail(... | apiThumbnail | identifier_name |
main.rs | use clap::Parser;
use dicom_core::{dicom_value, header::Tag, DataElement, VR};
use dicom_dictionary_std::tags;
use dicom_encoding::transfer_syntax;
use dicom_object::{mem::InMemDicomObject, open_file, StandardDataDictionary};
use dicom_transfer_syntax_registry::TransferSyntaxRegistry;
use dicom_ul::{
association::C... | (
file: &DicomFile,
pcs: &[dicom_ul::pdu::PresentationContextResult],
) -> Result<(dicom_ul::pdu::PresentationContextResult, String), Error> {
let file_ts = TransferSyntaxRegistry
.get(&file.file_transfer_syntax)
.whatever_context("Unsupported file transfer syntax")?;
// TODO(#106) trans... | check_presentation_contexts | identifier_name |
main.rs | use clap::Parser;
use dicom_core::{dicom_value, header::Tag, DataElement, VR};
use dicom_dictionary_std::tags;
use dicom_encoding::transfer_syntax;
use dicom_object::{mem::InMemDicomObject, open_file, StandardDataDictionary};
use dicom_transfer_syntax_registry::TransferSyntaxRegistry;
use dicom_ul::{
association::C... |
}
}
if let Some(pb) = progress_bar.as_ref() {
pb.inc(1)
};
}
if let Some(pb) = progress_bar {
pb.finish_with_message("done")
};
scu.release()
.whatever_context("Failed to release SCU association")?;
Ok(())
}
fn store_req_command(
... | {
error!("Unexpected SCP response: {:?}", pdu);
let _ = scu.abort();
std::process::exit(-2);
} | conditional_block |
main.rs | use clap::Parser;
use dicom_core::{dicom_value, header::Tag, DataElement, VR};
use dicom_dictionary_std::tags;
use dicom_encoding::transfer_syntax;
use dicom_object::{mem::InMemDicomObject, open_file, StandardDataDictionary};
use dicom_transfer_syntax_registry::TransferSyntaxRegistry;
use dicom_ul::{
association::C... | let nbytes = cmd_data.len() + object_data.len();
if verbose {
info!(
"Sending file {} (~ {} kB), uid={}, sop={}, ts={}",
file.file.display(),
nbytes / 1_000,
&file.sop_instance_uid,
... | .whatever_context("Unsupported file transfer syntax")?;
dicom_file
.write_dataset_with_ts(&mut object_data, ts_selected)
.whatever_context("Could not write object dataset")?;
| random_line_split |
args.rs | //! Handle `cargo add` arguments
use cargo_edit::{find, registry_url, Dependency};
use cargo_edit::{get_latest_dependency, CrateName};
use semver;
use std::path::PathBuf;
use structopt::StructOpt;
use crate::errors::*;
#[derive(Debug, StructOpt)]
#[structopt(bin_name = "cargo")]
pub enum | {
/// Add dependency to a Cargo.toml manifest file.
#[structopt(name = "add")]
#[structopt(
after_help = "This command allows you to add a dependency to a Cargo.toml manifest file. If <crate> is a github
or gitlab repository URL, or a local path, `cargo add` will try to automatically get the crate ... | Command | identifier_name |
args.rs | //! Handle `cargo add` arguments
use cargo_edit::{find, registry_url, Dependency};
use cargo_edit::{get_latest_dependency, CrateName};
use semver;
use std::path::PathBuf;
use structopt::StructOpt;
use crate::errors::*;
#[derive(Debug, StructOpt)]
#[structopt(bin_name = "cargo")]
pub enum Command {
/// Add depend... |
}
/// Build dependencies from arguments
pub fn parse_dependencies(&self) -> Result<Vec<Dependency>> {
if self.crates.len() > 1
&& (self.git.is_some() || self.path.is_some() || self.vers.is_some())
{
return Err(ErrorKind::MultipleCratesWithGitOrPathOrVers.into());
... | {
assert_eq!(self.git.is_some() && self.vers.is_some(), false);
assert_eq!(self.git.is_some() && self.path.is_some(), false);
assert_eq!(self.git.is_some() && self.registry.is_some(), false);
assert_eq!(self.path.is_some() && self.registry.is_some(), false);
... | conditional_block |
args.rs | //! Handle `cargo add` arguments
use cargo_edit::{find, registry_url, Dependency};
use cargo_edit::{get_latest_dependency, CrateName};
use semver;
use std::path::PathBuf;
use structopt::StructOpt;
use crate::errors::*;
#[derive(Debug, StructOpt)]
#[structopt(bin_name = "cargo")]
pub enum Command {
/// Add depend... |
fn get_upgrade_prefix(&self) -> &'static str {
match self.upgrade.as_ref() {
"default" => "",
"none" => "=",
"patch" => "~",
"minor" => "^",
"all" => ">=",
_ => unreachable!(),
}
}
}
#[cfg(test)]
impl Default for Args {
... | {
if self.crates.len() > 1
&& (self.git.is_some() || self.path.is_some() || self.vers.is_some())
{
return Err(ErrorKind::MultipleCratesWithGitOrPathOrVers.into());
}
if self.crates.len() > 1 && self.rename.is_some() {
return Err(ErrorKind::MultipleCra... | identifier_body |
args.rs | //! Handle `cargo add` arguments
use cargo_edit::{find, registry_url, Dependency};
use cargo_edit::{get_latest_dependency, CrateName};
use semver;
use std::path::PathBuf;
use structopt::StructOpt;
use crate::errors::*;
#[derive(Debug, StructOpt)]
#[structopt(bin_name = "cargo")]
pub enum Command {
/// Add depend... | #[structopt(long = "target", conflicts_with = "dev", conflicts_with = "build")]
pub target: Option<String>,
/// Add as an optional dependency (for use in features).
#[structopt(long = "optional", conflicts_with = "dev", conflicts_with = "build")]
pub optional: bool,
/// Path to the manifest to... |
/// Add as dependency to the given target platform. | random_line_split |
DOMHelper.ts | /**
* this helper helps manipulating DOM
*/
import { raiseError } from 'analytics'
import * as NProgress from 'nprogress'
import * as PJAX from 'pjax'
NProgress.configure({ showSpinner: false })
/**
* when gitako is ready, make page's header narrower
*/
function markGitakoReadyState() {
const readyClassName = ... | * change inner text of copy file button to give feedback
* @param {element} copyFileBtn
* @param {string} text
*/
function setTempCopyFileBtnText(copyFileBtn: HTMLButtonElement, text: string) {
copyFileBtn.innerText = text
window.setTimeout(() => (copyFileBtn.innerText = 'Copy file'), 1000)
}
... | /** | random_line_split |
DOMHelper.ts | /**
* this helper helps manipulating DOM
*/
import { raiseError } from 'analytics'
import * as NProgress from 'nprogress'
import * as PJAX from 'pjax'
NProgress.configure({ showSpinner: false })
/**
* when gitako is ready, make page's header narrower
*/
function markGitakoReadyState() {
const readyClassName = ... | }),
() => {
const plainReadmeSelector = '.repository-content div#readme .plain'
$(plainReadmeSelector, undefined, () =>
raiseError(
new Error('cannot find mount point for copy snippet button while readme exists'),
),
)
},
)
})
}
/**
* fo... | if (currentCodeSnippetElement !== target) {
currentCodeSnippetElement = target
/**
* <article>
* <pre></pre> <!-- case A -->
* <div class="highlight">
* <pre></pre> <!-- case B -->
* <... | conditional_block |
DOMHelper.ts | /**
* this helper helps manipulating DOM
*/
import { raiseError } from 'analytics'
import * as NProgress from 'nprogress'
import * as PJAX from 'pjax'
NProgress.configure({ showSpinner: false })
/**
* when gitako is ready, make page's header narrower
*/
function markGitakoReadyState() {
const readyClassName = ... | if (getCurrentPageType() === PAGE_TYPES.RAW_TEXT) {
const btnGroupSelector = [
// the button group next to navigation bar
'.repository-content .file-navigation.js-zeroclipboard-container .BtnGroup',
// the button group in file content header
'.repository-content .file .file-header .file-ac... | copyFileBtn.innerText = text
window.setTimeout(() => (copyFileBtn.innerText = 'Copy file'), 1000)
}
| identifier_body |
DOMHelper.ts | /**
* this helper helps manipulating DOM
*/
import { raiseError } from 'analytics'
import * as NProgress from 'nprogress'
import * as PJAX from 'pjax'
NProgress.configure({ showSpinner: false })
/**
* when gitako is ready, make page's header narrower
*/
function markGitakoReadyState() {
const readyClassName = ... | {
const sideBarContentSelector = '.gitako-side-bar .file-explorer'
$(sideBarContentSelector, sideBarElement => {
if (sideBarElement instanceof HTMLElement) sideBarElement.focus()
})
}
function focusSearchInput() {
const searchInputSelector = '.search-input'
$(searchInputSelector, searchInputElement => {... | cusFileExplorer() | identifier_name |
libvirt_driver.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
groups = match.groups()
ip_address = groups[0]
mac_address = groups[1]
arp_table[mac_address].append(ip_address)
return arp_table
| continue | conditional_block |
libvirt_driver.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
def reboot_node(self, node):
domain = self._get_domain_for_node(node=node)
return domain.reboot(flags=0) == 0
def destroy_node(self, node):
domain = self._get_domain_for_node(node=node)
return domain.destroy() == 0
def start_node(self, node):
domain = self._get_do... | domains = self.connection.listAllDomains()
nodes = self._to_nodes(domains=domains)
return nodes | identifier_body |
libvirt_driver.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, _ = child.communicate()
arp_table = self._parse_ip_table_neigh(ip_output=stdout)
for mac_address in mac_addresses:
if mac_address in arp_table:
ip_ad... | random_line_split | |
libvirt_driver.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | (self, name):
"""
Retrieve Node object for a domain with a provided name.
:param name: Name of the domain.
:type name: ``str``
"""
domain = self._get_domain_for_name(name=name)
node = self._to_node(domain=domain)
return node
def ex_take_node_scree... | ex_get_node_by_name | identifier_name |
cache.rs | use crate::address_map::{ModuleAddressMap, ValueLabelsRanges};
use crate::compilation::{Compilation, Relocations};
use crate::module::Module;
use crate::module_environ::FunctionBodyData;
use core::hash::Hasher;
use cranelift_codegen::{ir, isa};
use cranelift_entity::PrimaryMap;
use cranelift_wasm::DefinedFuncIndex;
use... | (dir: &Path, compression_level: i32) -> Self {
// On Windows, if we want long paths, we need '\\?\' prefix, but it doesn't work
// with relative paths. One way to get absolute path (the only one?) is to use
// fs::canonicalize, but it requires that given path exists. The extra advant... | new_step2 | identifier_name |
cache.rs | use crate::address_map::{ModuleAddressMap, ValueLabelsRanges};
use crate::compilation::{Compilation, Relocations};
use crate::module::Module;
use crate::module_environ::FunctionBodyData;
use core::hash::Hasher;
use cranelift_codegen::{ir, isa};
use cranelift_entity::PrimaryMap;
use cranelift_wasm::DefinedFuncIndex;
use... |
pub fn get_data(&self) -> Option<ModuleCacheData> {
let path = self.mod_cache_path.as_ref()?;
trace!("get_data() for path: {}", path.display());
let compressed_cache_bytes = fs::read(path).ok()?;
let cache_bytes = zstd::decode_all(&compressed_cache_bytes[..])
.map_err(|... | {
let mod_cache_path = if conf::cache_enabled() {
let hash = Sha256Hasher::digest(module, function_body_inputs);
let compiler_dir = if cfg!(debug_assertions) {
format!(
"{comp_name}-{comp_ver}-{comp_mtime}",
comp_name = compiler_nam... | identifier_body |
cache.rs | use crate::address_map::{ModuleAddressMap, ValueLabelsRanges};
use crate::compilation::{Compilation, Relocations};
use crate::module::Module;
use crate::module_environ::FunctionBodyData;
use core::hash::Hasher;
use cranelift_codegen::{ir, isa};
use cranelift_entity::PrimaryMap;
use cranelift_wasm::DefinedFuncIndex;
use... | }
// Private static, so only internal function can access it.
static CONFIG: Once<Config> = Once::new();
static INIT_CALLED: AtomicBool = AtomicBool::new(false);
static DEFAULT_COMPRESSION_LEVEL: i32 = 0; // 0 for zstd means "use default level"
/// Returns true if and only if the cache is enab... |
struct Config {
pub cache_enabled: bool,
pub cache_dir: PathBuf,
pub compression_level: i32, | random_line_split |
analyze_sample_captures.py | import pickle
import numpy as np
import PySimpleGUI as sg
import matplotlib.pyplot as plt
from WiPHY.utils import search_sequence_cv2
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
raw_samples_layout = [[sg.Canvas(key='-raw-canvas-')]]
filtered_samples_layout = [[sg.Canvas(key='-filtered-canvas-')]]
t... | raw_samples_fig = None
time_sync_fig = None
time_sync_const_fig = None
baseband_sig_fig = None
while True:
event, values = window.read()
if event == '--FRAME_NUM--' or event == '_CAPTURE_FILE_LOAD_':
if event == '_CAPTURE_FILE_LOAD_':
... | conditional_block | |
analyze_sample_captures.py | import pickle
import numpy as np
import PySimpleGUI as sg
import matplotlib.pyplot as plt
from WiPHY.utils import search_sequence_cv2
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
raw_samples_layout = [[sg.Canvas(key='-raw-canvas-')]]
filtered_samples_layout = [[sg.Canvas(key='-filtered-canvas-')]]
t... |
window = sg.Window('Sample Captures Analyzer', layout, default_element_size=(40,40), finalize=True)
frames_detected_capture_indxs = []
if __name__ == '__main__':
raw_samples_fig = None
time_sync_fig = None
time_sync_const_fig = None
baseband_sig_fig = None
while True:
eve... | figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
return figure_canvas_agg | identifier_body |
analyze_sample_captures.py | import pickle
import numpy as np
import PySimpleGUI as sg
import matplotlib.pyplot as plt
from WiPHY.utils import search_sequence_cv2
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
raw_samples_layout = [[sg.Canvas(key='-raw-canvas-')]]
filtered_samples_layout = [[sg.Canvas(key='-filtered-canvas-')]]
t... | data = pickle.load(fileHandler)
fileHandler.close()
# Find capture indexs where the frames were detected.
for capture_idx, frames in enumerate(data['frame_detection']):
if len(frames) > 0:
frames... | if event == '--FRAME_NUM--' or event == '_CAPTURE_FILE_LOAD_':
if event == '_CAPTURE_FILE_LOAD_':
fileHandler = open(values['_CAPTURE_FILE_'], "rb") | random_line_split |
analyze_sample_captures.py | import pickle
import numpy as np
import PySimpleGUI as sg
import matplotlib.pyplot as plt
from WiPHY.utils import search_sequence_cv2
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
raw_samples_layout = [[sg.Canvas(key='-raw-canvas-')]]
filtered_samples_layout = [[sg.Canvas(key='-filtered-canvas-')]]
t... | (canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
return figure_canvas_agg
window = sg.Window('Sample Captures Analyzer', layout, default_element_size=(40,40), finalize=True)
frame... | draw_figure | identifier_name |
app2mosaic_full_display.py | #!/usr/bin/env python
# Create plots from Apprentice2 mosaic trace file or pat_report ap2-xml file
#
# Copyright Cray UK Ltd,
# Harvey Richardson and Michael Bareford, Copyright 2017
# v1.0
import sys
import re
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.widgets impor... | ():
print """usage: app2mosaic_full_display file
Arguments:
-d id [-point-size ps] Choose dataset (and plot point size)
-node [-inter-node-only] Display node-to-node mosaic
-node-summary Display summary of off/on-node communications
-display-output file Filename used to ou... | help | identifier_name |
app2mosaic_full_display.py | #!/usr/bin/env python
# Create plots from Apprentice2 mosaic trace file or pat_report ap2-xml file
#
# Copyright Cray UK Ltd,
# Harvey Richardson and Michael Bareford, Copyright 2017
# v1.0
import sys
import re
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.widgets impor... | def calculate_network_distances():
global nranks
global pe_node_xyz
global pe_node_id
global data_dict
data_2d = np.zeros((nranks,nranks))
counts_2d = data_dict["Data_P2P_Count"]
for i in range(nranks):
for j in range(nranks):
if counts_2d[i,j] == 0:
continue
dx,dy,dz... | random_line_split | |
app2mosaic_full_display.py | #!/usr/bin/env python
# Create plots from Apprentice2 mosaic trace file or pat_report ap2-xml file
#
# Copyright Cray UK Ltd,
# Harvey Richardson and Michael Bareford, Copyright 2017
# v1.0
import sys
import re
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.widgets impor... |
repeat = 1
for val in row_data[1::]:
if val[0] == '*':
repeat = int(val[1:])
continue
v = int(val)
for ij in range(repeat):
pe_node_id[j] = v
if v not in node_ids:
node_ids.append(v)
j += 1
... | row_data += line.rstrip().split(' ') | conditional_block |
app2mosaic_full_display.py | #!/usr/bin/env python
# Create plots from Apprentice2 mosaic trace file or pat_report ap2-xml file
#
# Copyright Cray UK Ltd,
# Harvey Richardson and Michael Bareford, Copyright 2017
# v1.0
import sys
import re
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.widgets impor... |
def collate_node_data():
global nranks, nnodes
global pe_node_xyz
global pe_node_id
global data_dict
global node_data_dict
global node_summary_dict
node_data_dict = {}
for key in data_dict:
n2n_data = np.zeros((nnodes,nnodes))
p2p_data = data_dict[key]
min_key = "min" in key.lower()
... | global nranks
global pe_node_xyz
global pe_node_id
global data_dict
data_2d = np.zeros((nranks,nranks))
counts_2d = data_dict["Data_P2P_Count"]
for i in range(nranks):
for j in range(nranks):
if counts_2d[i,j] == 0:
continue
dx,dy,dz = dist_xyz(pe_node_xyz[i], pe_node_x... | identifier_body |
main.rs | // vim:set et sw=4 ts=4 foldmethod=marker:
#![warn(clippy::all, clippy::pedantic)]
#![warn(missing_docs)]
#![recursion_limit="512"]
// starting doc {{{
//! ARES: Automatic REcord System.
//!
//! A Kubernetes-native system to automatically create and manage DNS records
//! meant to run in parallel with External DNS.... | () -> Result<()> {
let opts: cli::Opts = cli::Opts::parse();
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let root_logger = slog::Logger::root(
drain,
... | main | identifier_name |
main.rs | // vim:set et sw=4 ts=4 foldmethod=marker:
#![warn(clippy::all, clippy::pedantic)]
#![warn(missing_docs)]
#![recursion_limit="512"]
// starting doc {{{
//! ARES: Automatic REcord System.
//!
//! A Kubernetes-native system to automatically create and manage DNS records
//! meant to run in parallel with External DNS.... |
info!(sub_logger, "Finished syncing");
info!(sub_logger, "Spawning watcher");
let res = collector.watch_values(&record.metadata, &sub_ac.provider,
&mut builder).await;
... | {
crit!(sub_logger, "Error! {}", e);
break
} | conditional_block |
main.rs | // vim:set et sw=4 ts=4 foldmethod=marker:
#![warn(clippy::all, clippy::pedantic)]
#![warn(missing_docs)]
#![recursion_limit="512"]
// starting doc {{{
//! ARES: Automatic REcord System.
//!
//! A Kubernetes-native system to automatically create and manage DNS records
//! meant to run in parallel with External DNS.... | //! ```yaml
//! apiVersion: v1
//! kind: Pod
//! metadata:
//! name: nginx-hello-world
//! app: nginx
//! spec:
//! containers:
//! - name: nginx
//! image: nginxdemos/hello
//! ---
//! apiVersion: syntixi.io/v1alpha1
//! kind: Record
//! metadata:
//! name: example-selector
//! spec:
//! fqdn: selector... | //! however, useful for making SPF records point to an outbound mail record,
//! where the mail can be sent from one of many Nodes.
//! | random_line_split |
main.rs | // vim:set et sw=4 ts=4 foldmethod=marker:
#![warn(clippy::all, clippy::pedantic)]
#![warn(missing_docs)]
#![recursion_limit="512"]
// starting doc {{{
//! ARES: Automatic REcord System.
//!
//! A Kubernetes-native system to automatically create and manage DNS records
//! meant to run in parallel with External DNS.... | {
let opts: cli::Opts = cli::Opts::parse();
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let root_logger = slog::Logger::root(
drain,
o!("secret" =>... | identifier_body | |
core.rs | // Copyright (c) 2016-2021 Fabian Schuiki
use crate::lexer::token::*;
use crate::parser::rules::{Parser, Recovered, RecoveredResult, Reported, ReportedResult};
use moore_common::errors::*;
use moore_common::name::*;
use moore_common::source::*;
use std;
use std::fmt::Display;
use std::marker::PhantomData;
/// A predi... | <P: Parser>(p: &mut P) -> Option<Spanned<Name>> {
let Spanned { value, span } = p.peek(0);
match value {
Ident(n) => {
p.bump();
Some(Spanned::new(n, span))
}
_ => None,
}
}
/// Determine the earliest occurring token from a set. Useful to determine which
/// ... | try_ident | identifier_name |
core.rs | // Copyright (c) 2016-2021 Fabian Schuiki
use crate::lexer::token::*;
use crate::parser::rules::{Parser, Recovered, RecoveredResult, Reported, ReportedResult};
use moore_common::errors::*;
use moore_common::name::*;
use moore_common::source::*;
use std;
use std::fmt::Display;
use std::marker::PhantomData;
/// A predi... | Ok(x) => v.push(x),
Err(_) => {
term.recover(p, false);
return Err(Recovered);
}
}
}
Ok(v)
}
/// Parse a list of items separated with a specific token, until a terminator
/// oktne has been reached. The terminator is not consumed.
pub ... | match parse(p) { | random_line_split |
core.rs | // Copyright (c) 2016-2021 Fabian Schuiki
use crate::lexer::token::*;
use crate::parser::rules::{Parser, Recovered, RecoveredResult, Reported, ReportedResult};
use moore_common::errors::*;
use moore_common::name::*;
use moore_common::source::*;
use std;
use std::fmt::Display;
use std::marker::PhantomData;
/// A predi... |
}
impl<P, T> Predicate<P> for TokenPredicate<P, T>
where
P: Parser,
T: Predicate<P>,
{
fn matches(&mut self, p: &mut P) -> bool {
self.inner.matches(p) || p.peek(0).value == self.token
}
fn recover(&mut self, p: &mut P, consume: bool) {
self.inner.recover(p, consume)
}
}
impl... | {
TokenPredicate {
inner: inner,
token: token,
_marker: PhantomData,
}
} | identifier_body |
core.rs | // Copyright (c) 2016-2021 Fabian Schuiki
use crate::lexer::token::*;
use crate::parser::rules::{Parser, Recovered, RecoveredResult, Reported, ReportedResult};
use moore_common::errors::*;
use moore_common::name::*;
use moore_common::source::*;
use std;
use std::fmt::Display;
use std::marker::PhantomData;
/// A predi... |
}
/// Consume a specific token, or emit an error if the next token in the stream
/// does not match the expected one.
pub fn require<P: Parser>(p: &mut P, expect: Token) -> ReportedResult<()> {
let Spanned {
value: actual,
span,
} = p.peek(0);
if actual == expect {
p.bump();
... | {
false
} | conditional_block |
bot.py | import discord
from discord.ext import commands, menus
import config
from cogs.help import HelpCommand
from utils.jsonfile import JSONList, JSONDict
from utils.context import Context
from collections import Counter
import datetime
from contextlib import suppress
import traceback
import re
import os
exte... |
async def on_message(self, message):
if message.guild is None:
return
await self.process_commands(message)
async def on_message_edit(self, before, after):
if before.content != after.content:
await self.on_message(after)
async def process_command... | if self.launched_at is None:
self.launched_at = datetime.datetime.utcnow()
for guild in self.guilds:
for channel in guild.voice_channels:
await self.on_voice_leave(channel)
print('Logged in as', self.user) | identifier_body |
bot.py | import discord
from discord.ext import commands, menus
import config
from cogs.help import HelpCommand
from utils.jsonfile import JSONList, JSONDict
from utils.context import Context
from collections import Counter
import datetime
from contextlib import suppress
import traceback
import re
import os
exte... | return
else:
ctx.command.reset_cooldown(ctx)
if isinstance(error, commands.CommandInvokeError) and not isinstance(error.original, menus.MenuError):
error = error.original
traceback.print_exception(error.__class__.__name__, error, error.__t... | if guild.id in self.blacklist:
await guild.leave()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
| random_line_split |
bot.py | import discord
from discord.ext import commands, menus
import config
from cogs.help import HelpCommand
from utils.jsonfile import JSONList, JSONDict
from utils.context import Context
from collections import Counter
import datetime
from contextlib import suppress
import traceback
import re
import os
exte... | (self, message):
ctx = await self.get_context(message, cls=Context)
if ctx.command is None:
return
if ctx.author.id in self.blacklist:
return
if not ctx.channel.permissions_for(ctx.guild.me).send_messages:
return
bucket = self.text_spam... | process_commands | identifier_name |
bot.py | import discord
from discord.ext import commands, menus
import config
from cogs.help import HelpCommand
from utils.jsonfile import JSONList, JSONDict
from utils.context import Context
from collections import Counter
import datetime
from contextlib import suppress
import traceback
import re
import os
exte... |
else:
settings = self.configs[str(channel.id)]
name = settings.get('name', '@user')
limit = settings.get('limit', 0)
bitrate = settings.get('bitrate', 64000)
top = settings.get('top', False)
try:
category = member.g... | self.voice_spam_counter[member.id] += 1
if self.voice_spam_counter[member.id] >= 5:
del self.text_spam_counter[member.id]
self.blacklist.append(member.id)
await self.blacklist.save()
with suppress(discord.Forbidden):
await mem... | conditional_block |
entity_test.go | package message
import (
"bytes"
"errors"
"io"
"io/ioutil"
"math"
"reflect"
"strings"
"testing"
)
func testMakeEntity() *Entity {
var h Header
h.Set("Content-Type", "text/plain; charset=US-ASCII")
h.Set("Content-Transfer-Encoding", "base64")
r := strings.NewReader("Y2Mgc2F2YQ==")
e, _ := New(h, r)
ret... |
if !IsUnknownCharset(err) {
t.Fatal("New(unknown charset): expected an error that verifies IsUnknownCharset")
}
if b, err := ioutil.ReadAll(e.Body); err != nil {
t.Error("Expected no error while reading entity body, got", err)
} else if s := string(b); s != expected {
t.Errorf("Expected %q as entity body bu... | {
t.Fatal("New(unknown charset): expected an error")
} | conditional_block |
entity_test.go | package message
import (
"bytes"
"errors"
"io"
"io/ioutil"
"math"
"reflect"
"strings"
"testing"
)
func testMakeEntity() *Entity {
var h Header
h.Set("Content-Type", "text/plain; charset=US-ASCII")
h.Set("Content-Transfer-Encoding", "base64")
r := strings.NewReader("Y2Mgc2F2YQ==")
e, _ := New(h, r)
ret... | () *Entity {
var h1 Header
h1.Set("Content-Type", "text/plain")
r1 := strings.NewReader("Text part")
e1, _ := New(h1, r1)
var h2 Header
h2.Set("Content-Type", "text/html")
r2 := strings.NewReader("<p>HTML part</p>")
e2, _ := New(h2, r2)
var h Header
h.Set("Content-Type", "multipart/alternative; boundary=IMT... | testMakeMultipart | identifier_name |
entity_test.go | package message
import (
"bytes"
"errors"
"io"
"io/ioutil"
"math"
"reflect"
"strings"
"testing"
)
func testMakeEntity() *Entity {
var h Header
h.Set("Content-Type", "text/plain; charset=US-ASCII")
h.Set("Content-Transfer-Encoding", "base64")
r := strings.NewReader("Y2Mgc2F2YQ==")
e, _ := New(h, r)
ret... |
func TestNewEntity_MultipartReader_notMultipart(t *testing.T) {
e := testMakeEntity()
mr := e.MultipartReader()
if mr != nil {
t.Fatal("(non-multipart).MultipartReader() != nil")
}
}
type testWalkPart struct {
path []int
mediaType string
body string
err error
}
func walkCollect(e *Entity) (... | } | random_line_split |
entity_test.go | package message
import (
"bytes"
"errors"
"io"
"io/ioutil"
"math"
"reflect"
"strings"
"testing"
)
func testMakeEntity() *Entity {
var h Header
h.Set("Content-Type", "text/plain; charset=US-ASCII")
h.Set("Content-Transfer-Encoding", "base64")
r := strings.NewReader("Y2Mgc2F2YQ==")
e, _ := New(h, r)
ret... |
func TestEntity_WriteTo_multipart(t *testing.T) {
e := testMakeMultipart()
var b bytes.Buffer
if err := e.WriteTo(&b); err != nil {
t.Fatal("Expected no error while writing entity, got", err)
}
if s := b.String(); s != testMultipartText {
t.Errorf("Expected written entity to be:\n%s\nbut got:\n%s", testMul... | {
var h Header
h.Set("Content-Type", "text/plain; charset=utf-8")
h.Set("Content-Transfer-Encoding", "base64")
r := strings.NewReader("Qm9uam91ciDDoCB0b3Vz")
e, _ := New(h, r)
e.Header.Set("Content-Transfer-Encoding", "quoted-printable")
var b bytes.Buffer
if err := e.WriteTo(&b); err != nil {
t.Fatal("Expe... | identifier_body |
main.py | from typing import List, Tuple
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
from scipy.io import loadmat
import os
import shutil
from urllib.request import urlopen
COLOR1 = 'steelblue'
def find_or_create_dir(dir_n... |
return marble_path
def plot_marble_path(title: str, marble_path: np.ndarray,
filename: str) -> None:
"""
Plots the 3D path of the marble.
"""
print(f'Plotting marble path...')
fig = go.Figure()
fig.add_trace(
go.Scatter3d(
x=marble_path[:, 0], y=marble_path[:, 1... | ut_slice_cube = np.reshape(u_denoised[row, :], (n, n, n))
argmax = np.argmax(np.abs(ut_slice_cube))
[index_x, index_y, index_z] = np.unravel_index(argmax, (n, n, n))
marble_path[row][0] = domain_values[index_x]
marble_path[row][1] = domain_values[index_y]
marble_path[row][2] = do... | conditional_block |
main.py | from typing import List, Tuple
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
from scipy.io import loadmat
import os
import shutil
from urllib.request import urlopen
COLOR1 = 'steelblue'
def find_or_create_dir(dir_n... | return np.abs(my_array)/np.max(np.abs(my_array))
def plot_spatial_isosurfaces(description: str, domain_values: np.ndarray,
u: np.ndarray, filename: str) -> None:
"""
Plots a few slices of the the data using isosurfaces.
"""
print(f'Plotting spatial isosurfaces: {description}...')
(x_gri... | """
| random_line_split |
main.py | from typing import List, Tuple
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
from scipy.io import loadmat
import os
import shutil
from urllib.request import urlopen
COLOR1 = 'steelblue'
def find_or_create_dir(dir_n... | (omega_x: float, omega_y: float,
omega_z: float) -> None:
"""
Prints the peak frequency.
"""
print(f'The peak frequency is: ({omega_x}, {omega_y}, {omega_z})')
def get_filter(omega_x: float, omega_y: float, omega_z: float,
omega: np.ndarray) -> np.ndarray:
"""
Creates the filter used... | print_peak_frequency | identifier_name |
main.py | from typing import List, Tuple
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
from scipy.io import loadmat
import os
import shutil
from urllib.request import urlopen
COLOR1 = 'steelblue'
def find_or_create_dir(dir_n... |
def print_marble_position(marble_path) -> None:
"""
Prints the 3D coordinates of the marble.
"""
num_slices = marble_path.shape[0]
slices = [0, num_slices//2, num_slices-1]
for slice in slices:
(x, y, z) = marble_path[slice,:]
print(f"Position of marble at time {slice}: {x}, ... | """
Plots the 3D path of the marble.
"""
print(f'Plotting marble path...')
fig = go.Figure()
fig.add_trace(
go.Scatter3d(
x=marble_path[:, 0], y=marble_path[:, 1], z=marble_path[:, 2],
mode="lines+markers",
line_color=COLOR1,
line_width=3,
... | identifier_body |
ship_parser.rs | use log::{error, warn, debug, trace};
use serde_json::Value;
use serde_json::map::Map;
use crate::ballistics::{Ballistics, Dispersion};
use crate::gun::*;
use crate::download::{download, download_with_params};
use serde_derive::Deserialize;
use std::collections::HashMap;
use cgmath::{Matrix4, Point3};
use std::io::pr... | (faces: &Vec<ArmorFace>) -> [f64; 3] {
let mins = [
faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.x}).fold(1./0., f64::min),
faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.y}).fold(1./0., f64::min),
faces.iter().map(|face| { face.vertices.iter... | find_size | identifier_name |
ship_parser.rs | use log::{error, warn, debug, trace};
use serde_json::Value;
use serde_json::map::Map;
use crate::ballistics::{Ballistics, Dispersion};
use crate::gun::*;
use crate::download::{download, download_with_params};
use serde_derive::Deserialize;
use std::collections::HashMap;
use cgmath::{Matrix4, Point3};
use std::io::pr... | }
faces
}
fn find_size(faces: &Vec<ArmorFace>) -> [f64; 3] {
let mins = [
faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.x}).fold(1./0., f64::min),
faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.y}).fold(1./0., f64::min),
faces.iter().... | } | random_line_split |
ship_parser.rs | use log::{error, warn, debug, trace};
use serde_json::Value;
use serde_json::map::Map;
use crate::ballistics::{Ballistics, Dispersion};
use crate::gun::*;
use crate::download::{download, download_with_params};
use serde_derive::Deserialize;
use std::collections::HashMap;
use cgmath::{Matrix4, Point3};
use std::io::pr... | else if ammotype == "AP" {
Ammo::new(
AmmoType::Ap(ApAmmo::new(
ammo["bulletDiametr"].as_f64().expect("Couldn't find bulletDiametr"),
ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"),
ammo["bulletDetonator"].as_f64().expect("Couldn't f... | {
Ammo::new(
AmmoType::He(HeAmmo::new(
ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"),
ammo["alphaPiercingHE"].as_f64().expect("Couldn't find alphaPiercingHE"),
)),
ballistics,
)
} | conditional_block |
ship_parser.rs | use log::{error, warn, debug, trace};
use serde_json::Value;
use serde_json::map::Map;
use crate::ballistics::{Ballistics, Dispersion};
use crate::gun::*;
use crate::download::{download, download_with_params};
use serde_derive::Deserialize;
use std::collections::HashMap;
use cgmath::{Matrix4, Point3};
use std::io::pr... |
#[derive(Deserialize)]
struct ArmorMaterial {
#[serde(alias = "type")]
armor_type: usize,
thickness: usize, // mm
}
#[derive(Deserialize)]
struct ArmorGroup {
material: String,
indices: Vec<usize>,
}
#[derive(Deserialize)]
struct ArmorObject {
vertices: Vec<f64>,
groups: Vec<ArmorGroup>,... | {
//debug!("{:#?}", artillery_spec);
let guns = artillery_spec["guns"].as_object().unwrap();
/*for (key,gun) in guns {
debug!("{}: {:?}", key, gun);
}*/
let dispersion = Dispersion::new(
artillery_spec["minDistH"].as_f64().expect("Couldn't find horizontal"),
artillery_spec["minDi... | identifier_body |
main.py | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 21:25:43 2020
@author: test
"""
#init libs
print("Please wait. Packages initialization...")
import csv
import numpy as np
from tensorflow.python.keras.models import model_from_json
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QA... |
def Start_function(self):
#init variables
elements=[]
formulas=[]
fromulas_processed=[]
nums_custom_formulas=0
#----------------------------
self.log_listWidget.addItem("--INFO-- Files checking")
#set temperatures
try:
... | source_path = QFileDialog.getOpenFileName(self, "Select Source File", "", "Text Files (*.txt *.csv)")
if source_path[0]!="":
source_path=source_path[0]
self.Source_file_lineEdit.setText(source_path) | identifier_body |
main.py | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 21:25:43 2020
@author: test
"""
#init libs
print("Please wait. Packages initialization...")
import csv
import numpy as np
from tensorflow.python.keras.models import model_from_json
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QA... |
csv_chemestry_table.close()
except FileNotFoundError:
self.error_flag=True
self.log_listWidget.addItem("--ERROR-- Progam can not find file with chemestry table.")
self.log_listWidget.addItem("--ERROR-- File PTE_adapted.txt must be in defalut folder.")
... | read_row = next(reader_chemestry_table)
for j in range(len(read_row)):
read_row[j]=float(read_row[j])
elements.append(read_row) | conditional_block |
main.py | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 21:25:43 2020
@author: test
"""
#init libs
print("Please wait. Packages initialization...")
import csv
import numpy as np
from tensorflow.python.keras.models import model_from_json
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QA... | (string):
previous_character = string[0]
groups = []
newword = string[0]
for x, i in enumerate(string[1:]):
if i.isalpha() and previous_character.isalpha():
newword += i
elif i.isnumeric() and previous_character.isnumeric():
newword += i
else:
... | seperate_string_number | identifier_name |
main.py | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 21:25:43 2020
@author: test
"""
#init libs
print("Please wait. Packages initialization...")
import csv
import numpy as np
from tensorflow.python.keras.models import model_from_json
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QA... |
try:
result_path=str(self.Result_path_lineEdit.text())
result_cs_writer=open(result_path, 'a', newline='')
result_writer = csv.writer(result_cs_writer, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
except FileNotFoundError:
self.error_fla... | random_line_split | |
LoginForm.js | import React, { Component } from "react";
import {
View,
Text,
SafeAreaView,
TouchableOpacity,
Animated,
Easing,
Dimensions
} from "react-native";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { Actions } from "react-native-router-flux";
import { connect } fr... | }}
>
<Text style={titleTextStyle}>
is a journey
</Text>
</Animated.View>
</View>
<View style={loginCardStyle}>
<TextField
ref={this.emailRef}
label='Email address'
value={email}
... | random_line_split | |
LoginForm.js | import React, { Component } from "react";
import {
View,
Text,
SafeAreaView,
TouchableOpacity,
Animated,
Easing,
Dimensions
} from "react-native";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { Actions } from "react-native-router-flux";
import { connect } fr... | (nextProps) {
const {error} = this.props;
if (nextProps.error && nextProps.error !== error) {
this.dropdown.alertWithType('error', 'Error' , nextProps.error);
}
}
// Text Input handlers
updateRef(name, ref) {
this[name] = ref;
}
onMailChangeText(text) {
this.props.emailChanged(tex... | componentWillReceiveProps | identifier_name |
LoginForm.js | import React, { Component } from "react";
import {
View,
Text,
SafeAreaView,
TouchableOpacity,
Animated,
Easing,
Dimensions
} from "react-native";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { Actions } from "react-native-router-flux";
import { connect } fr... |
onPasswordChangeText(text) {
this.props.passwordChanged(text);
this.onChangeText(text);
}
onChangeText(text) {
['email', 'password']
.map((name) => ({ name, ref: this[name] }))
.forEach(({ name, ref }) => {
if (ref.isFocused()) {
this.setState({ [name]: text });
... | {
this.props.emailChanged(text);
this.onChangeText(text);
} | identifier_body |
LoginForm.js | import React, { Component } from "react";
import {
View,
Text,
SafeAreaView,
TouchableOpacity,
Animated,
Easing,
Dimensions
} from "react-native";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { Actions } from "react-native-router-flux";
import { connect } fr... |
return (
<KeyboardAwareScrollView
style={{ backgroundColor: primaryWhiteColor }}
resetScrollToCoords={{ x: 0, y: 0 }}
contentContainerStyle={pageStyle}
scrollEnabled={true}
>
<SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
<View style={logoStyle}>... | {
(children.profile && children.profile.journey) ? Actions.main(): Actions.journey();
return (<View />);
} | conditional_block |
provision.go | // Copyright 2018 Google LLC
//
// 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 ... |
// verify GET /certs
// verify GET /products
// verify POST /verifyApiKey
// verify POST /quotas
func (p *provision) verifyRemoteServiceProxy(client *http.Client, printf shared.FormatFn) error {
verifyGET := func(targetURL string) error {
req, err := http.NewRequest(http.MethodGet, targetURL, nil)
if err != nil... | {
client, err := p.createAuthorizedClient(config)
if err != nil {
return err
}
var verifyErrors error
if p.IsLegacySaaS || p.IsOPDK {
verbosef("verifying internal proxy...")
verifyErrors = p.verifyInternalProxy(client, verbosef)
}
verbosef("verifying remote-service proxy...")
verifyErrors = errorset.Ap... | identifier_body |
provision.go | // Copyright 2018 Google LLC
//
// 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 ... | // extracts the key id from the map
keyID, ok = m[server.SecretPropsKIDKey]
if !ok {
err = fmt.Errorf("kid not found in remote-service propertyset")
return
}
return
}
func (p *provision) createAuthorizedClient(config *server.Config) (*http.Client, error) {
// add authorization to transport
tr := http.Defa... | privateKey, err = server.LoadPrivateKey([]byte(strings.ReplaceAll(pkStr, `\n`, "\n")))
if err != nil {
return
}
| random_line_split |
provision.go | // Copyright 2018 Google LLC
//
// 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 ... | (config *server.Config) (*http.Client, error) {
// add authorization to transport
tr := http.DefaultTransport
if config.Tenant.TLS.AllowUnverifiedSSLCert {
tr = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
... | createAuthorizedClient | identifier_name |
provision.go | // Copyright 2018 Google LLC
//
// 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 ... |
// return possible errors if not hybrid
if !p.IsGCPManaged || p.isCloud() {
return verifyErrors
}
// output this warning for hybrid
if p.rotate > 0 {
shared.Errorf("\nIMPORTANT: Provisioned config with rotated secrets needs to be applied onto the k8s cluster to take effect.")
} else {
shared.Errorf("\nIM... | {
verbosef("provisioning verified OK")
} | conditional_block |
bighosts.py |
import re, os
class Address:
'''Class with two attributes and a repr : an IPV4 or IPV6 address
and a list of hostnames'''
# Lazy: every valid address matches, some incorrect address will match
format=re.compile('(\d{1,3}\.){3}\d{1,3}')
# Here is another that re matches ipv4 and ipv6 but I woul... |
class Hosts(dict):
'''This class features two dictionnaries addresses and hostnames
pointing to Address instances. The dict accessors are overriden
for the object to appear as a dictionnary which can be accessed
both ways, depending on whether the parameter matches the address
format'''
... | '''Common /etc/hosts start the hostname columns at the 24th
character and separate the two columns by as much tabs as
needed'''
sep="\t"*((col1width*8-1-len(self.address))/8+1)
return repr("%s%s%s\n" % ( self.address, sep, self.hostnames )) | identifier_body |
bighosts.py |
import re, os
class Address:
'''Class with two attributes and a repr : an IPV4 or IPV6 address
and a list of hostnames'''
# Lazy: every valid address matches, some incorrect address will match
format=re.compile('(\d{1,3}\.){3}\d{1,3}')
# Here is another that re matches ipv4 and ipv6 but I woul... |
else: h, a = item, value
if not a in self.addresses and ( not h in self.hostnames or h=='~del~' ):
# New address and new hostname
# Create an instance, and 2 references
new=Address(a,h)
self.addresses[a] = new
self.hostnames[h] = new
e... | a, h = item, value | conditional_block |
bighosts.py | import re, os
class Address:
'''Class with two attributes and a repr : an IPV4 or IPV6 address
and a list of hostnames'''
# Lazy: every valid address matches, some incorrect address will match
format=re.compile('(\d{1,3}\.){3}\d{1,3}')
# Here is another that re matches ipv4 and ipv6 but I would ... |
# else:
# f.write(l)
# if a and h:
# i=[ i for i in h.split(), a if i in c and c[i]!='~del~'].pop():
# if i:
# f.write( self.line.sub( repr(c.hostnames[i])[:-1], l ))
# ... | # if a in c.addresses:
# if c[a][0]!='~del~':
# f.write( self.__address.sub( repr(c.addresses[a])[:-1], l ))
# del c[a] | random_line_split |
bighosts.py |
import re, os
class Address:
'''Class with two attributes and a repr : an IPV4 or IPV6 address
and a list of hostnames'''
# Lazy: every valid address matches, some incorrect address will match
format=re.compile('(\d{1,3}\.){3}\d{1,3}')
# Here is another that re matches ipv4 and ipv6 but I woul... | (self,item):
'''Removes a whole line 'address - hostnames'. Can be called
by address or hostname'''
if self.__address.match(item):
a, h = item, self.addresses[item].hostnames
else:
a, h = self.hostnames[item].address, self.hostnames[item].hostnames
# The... | __delitem__ | identifier_name |
ReturnRefundFooter.js | import React, { Component } from 'react'
import { View, Dimensions, Text, TouchableOpacity, FlatList, TextInput } from 'react-native'
import { connect } from 'react-redux'
import { Container, FontSizeM, Input, FormS, BR, DistributeSpaceBetween, Bold, ButtonFilledTextDisabled, ButtonFilledText, ButtonFilledPrimary, Butt... | () {
const { showData, totalItemSelected, address } = this.props
const { name, selectedAddress, addressName, phone, postalCode, fullAddress, selectedProvince, selectedCity, selectedKecamatan } = this.state
let obj = {
province: {
province_id: selectedProvince
},
city: {
ci... | render | identifier_name |
ReturnRefundFooter.js | import React, { Component } from 'react'
import { View, Dimensions, Text, TouchableOpacity, FlatList, TextInput } from 'react-native'
import { connect } from 'react-redux'
import { Container, FontSizeM, Input, FormS, BR, DistributeSpaceBetween, Bold, ButtonFilledTextDisabled, ButtonFilledText, ButtonFilledPrimary, Butt... | import HeaderSearchComponent from './HeaderSearchComponent'
import PickerLocation from './PickerLocation'
class ReturnRefundFooter extends Component {
constructor () {
super()
this.state = {
selectedAddress: 'Tambah alamat penjemputan',
addressName: '',
name: '',
phone: '',
post... | random_line_split | |
ReturnRefundFooter.js | import React, { Component } from 'react'
import { View, Dimensions, Text, TouchableOpacity, FlatList, TextInput } from 'react-native'
import { connect } from 'react-redux'
import { Container, FontSizeM, Input, FormS, BR, DistributeSpaceBetween, Bold, ButtonFilledTextDisabled, ButtonFilledText, ButtonFilledPrimary, Butt... |
}
})
let itemQtyIndex = itemQty.findIndex(qtyData => qtyData.salesOrderItemId === invoices[data.invoiceIndex].items[data.itemIndex].sales_order_item_id)
let qty = 1
if (itemQtyIndex >= 0) {
qty = itemQty[itemQtyIndex].qty
}
if (!isEmpty(invoices[data.invoiceIndex])) ... | {
shippingCost.shippingAmount += invoices[data.invoiceIndex].items[data.itemIndex].shipping_amount * qtyData.qty
shippingCost.handlingFee += invoices[data.invoiceIndex].items[data.itemIndex].handling_fee_adjust * qtyData.qty
} | conditional_block |
decode_test.go | package osmpbf
import (
"fmt"
"io"
"net/http"
"os"
"reflect"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
)
const (
// Test files are stored at https://gist.github.com/AlekSi/d4369aa13cf1fc5ddfac3e91b67b2f7b
// 8604f36a7357adfbd6b5292c2ea4972d9d0bfd3d is the latest commit.
GistURL = "https:... | (b *testing.B) {
file := os.Getenv("OSMPBF_BENCHMARK_FILE")
if file == "" {
file = London
}
f, err := os.Open(file)
if err != nil {
b.Fatal(err)
}
defer f.Close()
fileInfo, err := f.Stat()
if err != nil {
b.Fatal(err)
}
blobBufferSize, _ := strconv.Atoi(os.Getenv("OSMPBF_BENCHMARK_BUFFER"))
b.ResetT... | BenchmarkDecode | identifier_name |
decode_test.go | package osmpbf
import (
"fmt"
"io"
"net/http"
"os"
"reflect"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
)
const (
// Test files are stored at https://gist.github.com/AlekSi/d4369aa13cf1fc5ddfac3e91b67b2f7b
// 8604f36a7357adfbd6b5292c2ea4972d9d0bfd3d is the latest commit.
GistURL = "https:... |
var (
IDsExpectedOrder = []string{
// Start of dense nodes.
"node/44", "node/47", "node/52", "node/58", "node/60",
"node/79", // Just because way/79 is already there
"node/2740703694", "node/2740703695", "node/2740703697",
"node/2740703699", "node/2740703701",
// End of dense nodes.
// Start of ways.
... | {
t, err := time.Parse(time.RFC3339, s)
if err != nil {
panic(err)
}
return t
} | identifier_body |
decode_test.go | package osmpbf
import (
"fmt"
"io"
"net/http"
"os"
"reflect"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
)
const (
// Test files are stored at https://gist.github.com/AlekSi/d4369aa13cf1fc5ddfac3e91b67b2f7b
// 8604f36a7357adfbd6b5292c2ea4972d9d0bfd3d is the latest commit.
GistURL = "https:... | }
d := NewDecoder(f)
if blobBufferSize > 0 {
d.SetBufferSize(blobBufferSize)
}
err = d.Start(runtime.GOMAXPROCS(-1))
if err != nil {
b.Fatal(err)
}
var nc, wc, rc uint64
start := time.Now()
for {
if v, err := d.Decode(); err == io.EOF {
break
} else if err != nil {
b.Fatal(err)... |
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err = f.Seek(0, 0); err != nil {
b.Fatal(err) | random_line_split |
decode_test.go | package osmpbf
import (
"fmt"
"io"
"net/http"
"os"
"reflect"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
)
const (
// Test files are stored at https://gist.github.com/AlekSi/d4369aa13cf1fc5ddfac3e91b67b2f7b
// 8604f36a7357adfbd6b5292c2ea4972d9d0bfd3d is the latest commit.
GistURL = "https:... |
}
func checkHeader(a *Header) bool {
if a == nil || a.BoundingBox == nil || a.RequiredFeatures == nil {
return false
}
// check bbox
if a.BoundingBox.Right != eh.BoundingBox.Right || a.BoundingBox.Left != eh.BoundingBox.Left || a.BoundingBox.Top != eh.BoundingBox.Top || a.BoundingBox.Bottom != eh.BoundingBox.B... | {
t.Fatal(err)
} | conditional_block |
satAverage.py | #!/usr/bin/env python
#python
import os
import math
import sys
import time
import re
import cPickle
import random
#eman
try:
import EMAN
except:
print "EMAN module did not get imported"
#scipy
import numpy
#appion
from appionlib import appionScript
from appionlib import appiondata
from appionlib import apDisplay
fro... | nodd=0
for i in range(0, len(lines)):
if i%2:
nodd+=1
oddf.write(lines[i])
else:
neven+=1
evenf.write(lines[i])
evenf.close()
oddf.close()
if neven>0:
self.makeClassAverages(evenfile, self.params['evenstack'], classdata, maskrad)
if nodd>0:
self.makeClassAverages(oddfile, self.p... | random_line_split | |
satAverage.py | #!/usr/bin/env python
#python
import os
import math
import sys
import time
import re
import cPickle
import random
#eman
try:
import EMAN
except:
print "EMAN module did not get imported"
#scipy
import numpy
#appion
from appionlib import appionScript
from appionlib import appiondata
from appionlib import apDisplay
fro... |
#=====================
def start(self):
self.rootname = self.params['stackname'].split(".")[0]
self.params['outputstack'] = os.path.join(self.params['rundir'], self.params['stackname'])
if os.path.isfile(self.params['outputstack']):
apFile.removeStack(self.params['outputstack'])
if self.params['eotest']... | refdata = appiondata.ApRefineRunData.direct_query(self.params['reconid'])
if not refdata:
apDisplay.printError("reconid "+str(self.params['reconid'])+" does not exist in the database")
refpath = refdata['path']['path']
rundir = os.path.join(refpath, "../../satEuler/sat-recon%d/volumes"%(self.params['reconid'])... | identifier_body |
satAverage.py | #!/usr/bin/env python
#python
import os
import math
import sys
import time
import re
import cPickle
import random
#eman
try:
import EMAN
except:
print "EMAN module did not get imported"
#scipy
import numpy
#appion
from appionlib import appionScript
from appionlib import appiondata
from appionlib import apDisplay
fro... | (self):
"""
Removes particles by reading a list of particle numbers generated externally.
Requirements:
the input file has one particle per line
the first piece of data is the particle number from the db
"""
keeplist = []
f = open(self.params['keeplist'], 'r')
lines = f.readlines()
f.close()
fo... | procKeepList | identifier_name |
satAverage.py | #!/usr/bin/env python
#python
import os
import math
import sys
import time
import re
import cPickle
import random
#eman
try:
import EMAN
except:
print "EMAN module did not get imported"
#scipy
import numpy
#appion
from appionlib import appionScript
from appionlib import appiondata
from appionlib import apDisplay
fro... |
class_stats['meanquality']=quality.mean()
class_stats['stdquality']=quality.std()
class_stats['max']=quality.max()
class_stats['min']=quality.min()
apDisplay.printMsg("sorted %d particles into %d classes"%(len(particles), len(classes)))
### print stats
print "-- quality factor stats --"
print ("mean/st... | quality[partnum] = particles[partnum]['quality_factor']
key = ("%.3f_%.3f"%(particles[partnum]['euler1'], particles[partnum]['euler2']))
if key not in classes.keys():
classes[key]={}
classes[key]['particles']=[]
classes[key]['euler1'] = particles[partnum]['euler1']
classes[key]['euler2'] = particl... | conditional_block |
editor.rs | use ansi_term::Color;
use lazy_static::lazy_static;
use rustyline::{highlight::Highlighter as HiTrait, Helper};
use rustyline_derive::{Completer, Hinter, Validator};
use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::json;
use std::{cell::RefCell, collections::HashMap, fmt... | }
HighlightEvent::Source { start, end } => {
let style = style_stack.last().unwrap();
stylings.insert(*style, start..end, 1);
}
}
}
let parsed = hi.parser().parse(line, None);
if let Some(parsed)... | style_stack.pop(); | random_line_split |
editor.rs | use ansi_term::Color;
use lazy_static::lazy_static;
use rustyline::{highlight::Highlighter as HiTrait, Helper};
use rustyline_derive::{Completer, Hinter, Validator};
use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::json;
use std::{cell::RefCell, collections::HashMap, fmt... | {
pub ansi: ansi_term::Style,
pub css: Option<String>,
}
#[derive(Debug)]
pub struct Theme {
pub styles: Vec<Style>,
pub highlight_names: Vec<String>,
}
#[derive(Default, Deserialize, Serialize)]
pub struct ThemeConfig {
#[serde(default)]
pub theme: Theme,
}
impl Theme {
/* pub fn load(p... | Style | identifier_name |
editor.rs | use ansi_term::Color;
use lazy_static::lazy_static;
use rustyline::{highlight::Highlighter as HiTrait, Helper};
use rustyline_derive::{Completer, Hinter, Validator};
use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::json;
use std::{cell::RefCell, collections::HashMap, fmt... | }
if len > 0 {
let mut start = HashMap::new();
let mut end = HashMap::new();
for (i, r) in self.current.iter().enumerate() {
start
.entry(r.range.start)
.or_insert_with(Vec::new)
.push((i, &r.st... | self.backing[0].1
}
| identifier_body |
calendar_appointment.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar as cal
import random
import pytz
from datetime import datetime, timedelta, time
from dateutil import rrule
from dateutil.relativedelta import relativedelta
from babel.dates import format_datetime
from od... | _name = "calendar.appointment.answer"
_description = "Online Appointment : Answers"
question_id = fields.Many2many('calendar.appointment.question', 'calendar_appointment_question_answer_rel', 'answer_id', 'question_id', string='Questions')
name = fields.Char('Answer', translate=True, required=True) | identifier_body | |
calendar_appointment.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar as cal
import random
import pytz
from datetime import datetime, timedelta, time
from dateutil import rrule
from dateutil.relativedelta import relativedelta
from babel.dates import format_datetime
from od... |
slot_weekday = [int(weekday) - 1 for weekday in self.slot_ids.mapped('weekday')]
for day in rrule.rrule(rrule.DAILY,
dtstart=first_day.date() + timedelta(days=1),
until=last_day.date(),
byweekday=slot_weekday):... | if slot.hour > first_day.hour + first_day.minute / 60.0:
append_slot(first_day.date(), slot) | conditional_block |
calendar_appointment.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar as cal
import random
import pytz
from datetime import datetime, timedelta, time
from dateutil import rrule
from dateutil.relativedelta import relativedelta
from babel.dates import format_datetime
from od... | (self, slots, first_day, last_day, employee=None):
""" Fills the slot stucture with an available employee
:param slots: slots structure generated by _slots_generate
:param first_day: start datetime in UTC
:param last_day: end datetime in UTC
:param employee: if s... | _slots_available | identifier_name |
calendar_appointment.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar as cal
import random
import pytz
from datetime import datetime, timedelta, time
from dateutil import rrule
from dateutil.relativedelta import relativedelta
from babel.dates import format_datetime
from od... | index = (upper_bound + lower_bound) // 2
if intervals[index][0] <= start_dt:
return recursive_find_index(index, upper_bound)
else:
return recursive_find_index(lower_bound, index)
if start_dt <= i... | return lower_bound | random_line_split |
graphs.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 19:15:41 2018
@author: DK
"""
import collections
from collections import defaultdict
### Graphs ###
class graph:
def __init__(self,vertices):
#defaultdict holds an empty list at each index; using adjecency list to create graph
... |
class egde:
def __init__(self,x,y):
self.v1 = x
self.v2 = y
def add_edge(self,u,v):
#for directed graphs
self.graph[u].append(v)
#for undirected graphs
#self.graph[u].append(v)
#self.graph[v].append(u)
#e = edge(... | self.graph = defaultdict(list)
self.V = vertices
self.E = edges | identifier_body |
graphs.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 19:15:41 2018
@author: DK
"""
import collections
from collections import defaultdict
### Graphs ###
class graph:
def __init__(self,vertices):
#defaultdict holds an empty list at each index; using adjecency list to create graph
... | (grid):
visited = set() # keep track of visited vertices
shapes = set() # final set to keep track of distinct island shapes
for row in len(grid):
for col in len(grid[0]):
shape = set()
dfs(grid, visited, shape, row, col)
if shape:
shapes.add(cano... | numIslands | identifier_name |
graphs.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 19:15:41 2018
@author: DK
"""
import collections
from collections import defaultdict
### Graphs ###
class graph:
def __init__(self,vertices):
#defaultdict holds an empty list at each index; using adjecency list to create graph
... | #Naive implementations take O(n)
#parents list should maintain tuples (parent,rank) for each index(which is the vertex)
#parents = [(-1,0)] for _ in range(len(self.graph))] will initialse each vertex's parent as itself and rank as 0
def find_parent_pc(parents,v):
if parents[v][0] == -1:
return v
else... | random_line_split | |
graphs.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 19:15:41 2018
@author: DK
"""
import collections
from collections import defaultdict
### Graphs ###
class graph:
def __init__(self,vertices):
#defaultdict holds an empty list at each index; using adjecency list to create graph
... |
# After collection of the x coordinates in rows (which by the nature of collection are in sorted order) and y in cols(need to be sorted,
# we take the median of the two as the origin
row = rows[len(rows//2)]
cols.sort()
col = cols[len(cols//2)]
# the point they should meet on is the median o... | for j in range(len(grid2D[0])):
if grid2D[i][j] == 1:
rows.append(i)
cols.append(j) | conditional_block |
restconf.py | """
Copyright 2015, Cisco Systems, Inc
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 agree... |
def add_list(seg, msg):
kdict = OrderedDict()
for key in seg.keys:
kdict[key.name] = set_type(key)
for leaf in seg.leaves:
kdict[leaf.name] = set_type(leaf)
return kdict
def build_msg(segs, msg=OrderedDict()):
for seg in segs:
if seg.type == 'container':
cont... | cont = OrderedDict()
if seg.presence == 'true':
return cont
for leaf in seg.leaves:
cont[leaf.name] = set_type(leaf)
return cont | identifier_body |
restconf.py | """
Copyright 2015, Cisco Systems, Inc
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 agree... | if not isinstance(val, (str, unicode)):
return val
return val.replace("/", "%2F").replace(":", "%3A").replace(" ", "%20")
def set_type(val):
'''
Using json.dumps() to convert dict to JSON strings requires that
actual Python values are correct in dict
TODO: Not sure if all correct datat... | ''' | random_line_split |
restconf.py | """
Copyright 2015, Cisco Systems, Inc
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 agree... | (keyvalue, mode):
'''
Return option and path depth of option to use for URL.
URL should extend to where option is placed and message body
should contain everything beyond.
'''
for child in keyvalue:
op = child.attrib.get("option", "")
if mode in ["get", "get-config"]:
... | get_op | identifier_name |
restconf.py | """
Copyright 2015, Cisco Systems, Inc
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 agree... |
return False
def __str__(self):
return self.name
def parse_url(username, request, mode):
'''
Main function that creates a URL and message body that uses the cxml (lxml)
Element nodes from a defined test from the YangExplorer GUI
Rules:
https://tools.ietf.org/html/draft-ietf-... | return self.name == x.attrib.get('name') | conditional_block |
invsim.py | import sys
sys.path.append('/Users/aabir/anaconda/envs/pca/simulations')
from invmgmt import *
import matplotlib.ticker as mtick
def setup_results_dirs():
cwd = '/Users/aabir/anaconda/envs/pca/'
os.makedirs(cwd + 'sim_results/delay', exist_ok=True)
class Inventory_MGMT:
def __init__(self, product_name='product1'... |
else:
raise ValueError("exiting parse_steps() : invalid argument steps")
def get_strategy_desc(self):
try:
strat = self.strategy
self.strategy_desc = ' '.join(strat.split('_'))
if 'ROP' in self.strategy: self.strategy_desc = r'ROP$(R_0={},R={})$'.format(self.ROP, self.ROO)#+ r', $I_0={}$'.format(sel... | strategy = kwargs.pop('strategy', None)
if strategy is None:
raise ValueError("exiting parse_steps() : no strategy or steps given")
elif isinstance(strategy, str):
strategy = ' '.join(strategy.split('_'))
if strategy == 'simple strategy':
self.I0 = kwargs.pop('I0', self.I0)
steps = default_s... | conditional_block |
invsim.py | import sys
sys.path.append('/Users/aabir/anaconda/envs/pca/simulations')
from invmgmt import *
import matplotlib.ticker as mtick
def setup_results_dirs():
cwd = '/Users/aabir/anaconda/envs/pca/'
os.makedirs(cwd + 'sim_results/delay', exist_ok=True)
class Inventory_MGMT:
def __init__(self, product_name='product1'... | def func():
old = {k : get_largest_key_val(self.logs[k])[1]
for k in self.logs.keys()}
current_inv = old['inventory']
if int(self.timer)%delay==0:
if current_inv >= self.I0:
new_inv, production = current_inv, 0
else:
new_inv, production = self.I0, self.I0 - current_inv
return ... | new_inv, production = self.I0, self.I0 - current_inv
return {'inventory' : new_inv, 'production' : production}
def bulk_production_step(self, delay): | random_line_split |
invsim.py | import sys
sys.path.append('/Users/aabir/anaconda/envs/pca/simulations')
from invmgmt import *
import matplotlib.ticker as mtick
def setup_results_dirs():
cwd = '/Users/aabir/anaconda/envs/pca/'
os.makedirs(cwd + 'sim_results/delay', exist_ok=True)
class Inventory_MGMT:
def __init__(self, product_name='product1'... | (self):
d = self.d_gen()
return {'demand' : d}
def all_or_nothing_supply_step(self):
old = {k : get_largest_key_val(self.logs[k])[1]
for k in self.logs.keys()}
if old['inventory'] >= old['demand']:
supply = old['demand']
new_inv = old['inventory'] - old['demand']
shortage = 0
excess = old... | simple_demand_step | identifier_name |
invsim.py | import sys
sys.path.append('/Users/aabir/anaconda/envs/pca/simulations')
from invmgmt import *
import matplotlib.ticker as mtick
def setup_results_dirs():
cwd = '/Users/aabir/anaconda/envs/pca/'
os.makedirs(cwd + 'sim_results/delay', exist_ok=True)
class Inventory_MGMT:
def __init__(self, product_name='product1'... |
def roundup(x, unit = 100):
return int(np.ceil(x / unit)) * int(unit)
def hist_roundup(x, multiple = 0.2):
newx = np.ceil(np.round(x*20, decimals = 2))/10
return newx
###################################################
"""
i = Inventory_MGMT(I0 = 100, d_gen = get_powerlaw_DemandGenerator(1.05, 500))
i.run_s... | t = float("{0:.2f}".format(t))
r = float("{0:.2f}".format(r))
res = float("{0:.10f}".format((t%1)-r))
return res == 0.0 | identifier_body |
lib.rs | //! # docker-bisect
//! `docker-bisect` create assumes that the docker daemon is running and that you have a
//! docker image with cached layers to probe.
extern crate colored;
extern crate dockworker;
extern crate indicatif;
extern crate rand;
use std::clone::Clone;
use std::fmt;
use std::io::{prelude::*, Error, Erro... | <T>(layers: Vec<Layer>, action: &T) -> Result<Vec<Transition>, Error>
where
T: ContainerAction + 'static,
{
let first_layer = layers.first().expect("no first layer");
let last_layer = layers.last().expect("no last layer");
let first_image_name: String = first_layer.image_name.clone();
let last_imag... | get_changes | identifier_name |
lib.rs | //! # docker-bisect
//! `docker-bisect` create assumes that the docker daemon is running and that you have a
//! docker image with cached layers to probe.
extern crate colored;
extern crate dockworker;
extern crate indicatif;
extern crate rand;
use std::clone::Clone;
use std::fmt;
use std::io::{prelude::*, Error, Erro... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.before {
Some(be) => write!(f, "({} -> {})", be, self.after),
None => write!(f, "-> {}", self.after),
}
}
}
/// Starts the bisect operation. Calculates highest and lowest layer result and if they have
///... |
impl fmt::Display for Transition { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.