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 |
|---|---|---|---|---|
HAPServiceNode2.ts | { logger } from '@nrchkb/logger'
import { uuid } from 'hap-nodejs'
import { NodeAPI } from 'node-red'
import NRCHKBError from './NRCHKBError'
import { FlowTypeType } from './types/FlowType'
import HAPHostNodeType from './types/HAPHostNodeType'
import HAPService2ConfigType from './types/HAPService2ConfigType'
import H... |
// Service node properties
self.name = self.config.name
// Find a unique identifier for the current service
if (
self.hasOwnProperty('_flow') &&
self.hasOwnProperty('_alias') &&
self._flow.hasOwnProperty('TYPE') &&
FlowTypeType.Subflow ==... |
self.accessory = self.parentNode.accessory
} | random_line_split |
HAPServiceNode2.ts | { logger } from '@nrchkb/logger'
import { uuid } from 'hap-nodejs'
import { NodeAPI } from 'node-red'
import NRCHKBError from './NRCHKBError'
import { FlowTypeType } from './types/FlowType'
import HAPHostNodeType from './types/HAPHostNodeType'
import HAPService2ConfigType from './types/HAPService2ConfigType'
import H... | else {
resolve(self.config)
}
})
.then((newConfig) => {
init.call(self, newConfig)
})
.catch((error: any) => {
log.error(`Error while starting Service due to ${error}`)
})
}
const init = functio... | {
log.debug(
'Waiting for Setup message. It should be of format {"payload":{"nrchkb":{"setup":{}}}}'
)
self.setupDone = false
self.nodeStatusUtils.setStatus({
fill: 'blue',
shape: 'dot',
... | conditional_block |
fvp.pb.go | XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SendMsg_Slice) Reset() { *m = SendMsg_Slice{} }
func (m *SendMsg_Slice) String() string { return proto.CompactTextString(m) }
func (*SendMsg_Slice) ProtoMessage() {}
func (*SendMsg_Slice) Descriptor() ([]byte, []i... | () int32 {
if m != nil {
return m.Counter
}
return 0
}
type EmptyMessage struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *EmptyMessage) Reset() { *m = EmptyMessage{} }
func (m *EmptyMessage) String() string {... | GetCounter | identifier_name |
fvp.pb.go |
func (m *SendMsg) String() string { return proto.CompactTextString(m) }
func (*SendMsg) ProtoMessage() {}
func (*SendMsg) Descriptor() ([]byte, []int) {
return fileDescriptor_9e36e933c92912d0, []int{0}
}
func (m *SendMsg) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SendMsg.Unmarshal(m, b)
}
func (m *S... | { *m = SendMsg{} } | identifier_body | |
fvp.pb.go | {
// 272 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x91, 0xcf, 0x4e, 0x84, 0x30,
0x10, 0xc6, 0xe5, 0xef, 0xca, 0x2c, 0xd9, 0xc4, 0x89, 0x87, 0x86, 0x68, 0x42, 0x38, 0xe1, 0x85,
0xc3, 0xae, 0xf1, 0x0d, 0xf4, 0xb6, 0x17, 0x78, 0x02, 0xa4, 0xc3, 0x86, 0x28... | var _Server_serviceDesc = grpc.ServiceDesc{
ServiceName: "fvp.Server",
HandlerType: (*ServerServer)(nil), | random_line_split | |
fvp.pb.go | XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SendMsg_Slice) Reset() { *m = SendMsg_Slice{} }
func (m *SendMsg_Slice) String() string { return proto.CompactTextString(m) }
func (*SendMsg_Slice) ProtoMessage() {}
func (*SendMsg_Slice) Descriptor() ([]byte, []in... |
return ""
}
func (m *SendMsg_State) GetVotedFor() []string {
if m != nil {
return m.VotedFor
}
return nil
}
func (m *SendMsg_State) GetAccepted() []string {
if m != nil {
return m.Accepted
}
return nil
}
func (m *SendMsg_State) GetConfirmed() []string {
if m != nil {
return m.Confirmed
}
return nil
... | {
return m.Id
} | conditional_block |
cli.py | already active.
"""
global _activeBar
if _activeBar is not None:
logging.getLogger(__name__).error("Cannot construct a new progress bar, "
"another one is already active.")
raise RuntimeError("A progress bar is already active.")
try:
_... | __call__(self, parser, namespace, values, option_string=None):
if "all" in values:
setattr(namespace, self.dest, reporters)
else:
setattr(namespace, self.dest, values.split(","))
parser.add_argument("input", help="Input file" | identifier_body | |
cli.py | = "] ({:"+str(len(targetStr))+"d}/"+targetStr+") "
else:
self._postFmt = "] ({:3d}/?)"
def advance(self, amount=1):
"""!Advance the bar by a given amount, redraws the bar."""
self._current += amount
self.redraw()
def clear(self):
"""!Clear the current line... | rr`." | identifier_name | |
cli.py | ()` for uniformity with TerminalProgressbar.
When set up correctly (via `setupLogging()`), loggers handle output properly.
"""
def __init__(self, target, message="", updateRate=1):
r"""!
Construct a new progress bar.
\warning Never have more than one active instance at th... | ng a second time."
"This function must be called *exactly* once.")
raise RuntimeError("Logging already set up")
_suppressGoogleLogWarning()
if verbosity | conditional_block | |
cli.py | LEVELNAMES = {
logging.DEBUG: "[94mDEBUG[0m",
logging.INFO: "INFO",
logging.WARNING: "[33mWARNING[0m",
logging.ERROR: "[31mERROR[0m",
logging.CRITICAL: "[91mCRITICAL[0m",
}
def format(self, record):
"!Format a record using colors."
# Hack the col... | if isinstance(argParser, str):
# construct new parser based on command name
args = _makeParser(argParser, **kwargs).parse_args()
else:
# use provided parser | random_line_split | |
report.rs | //! The summary page will be rendered to the file `summary.ext` using this data:
//!
//! ```json
//! {
//! "crate_path": "/path/to/workspace",
//! "files": [
//! {
//! "symbol": 123,
//! "path": "/path/to/workspace/src/lib.rs",
//! "summary": {
//! "li... | eport_path: &Path, report_files: &[ReportFileEntry], tera: &Tera, crate_path: &str, config: &FileConfig) -> Result<PathBuf> {
let path = report_path.join(config.output);
let mut context = Context::new();
let files = report_files
.iter()
.map(|entry| {
json!({
"sy... | ite_summary(r | identifier_name |
report.rs | //!
//! The summary page will be rendered to the file `summary.ext` using this data:
//!
//! ```json
//! {
//! "crate_path": "/path/to/workspace",
//! "files": [
//! {
//! "symbol": 123,
//! "path": "/path/to/workspace/src/lib.rs",
//! "summary": {
//! ... | //! }
//! },
//! ...
//! ]
//! }
//! ```
use error::{Result, ResultExt};
use sourcepath::{SourceType, identify_source_path};
use template::new as new_template;
use utils::{clean_dir, parent_3};
use copy_dir::copy_dir;
use cov::{self, Gcov, Graph, Interner, Report, Symbol};
use serde_js... | //! "branches_count": 250,
//! "branches_executed": 225,
//! "branches_taken": 219 | random_line_split |
report.rs | //!
//! The summary page will be rendered to the file `summary.ext` using this data:
//!
//! ```json
//! {
//! "crate_path": "/path/to/workspace",
//! "files": [
//! {
//! "symbol": 123,
//! "path": "/path/to/workspace/src/lib.rs",
//! "summary": {
//! ... | /// Renders the `report` into `report_path` using a template.
///
/// If the template has a summary page, returns the path of the rendered summary.
fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Interner) -> Result<Option<PathBuf>> {
use toml::de::... | let mut graph = Graph::default();
for extension in &["gcno", "gcda"] {
progress!("Parsing", "*.{} files", extension);
for entry in read_dir(cov_build_path.join(extension))? {
let path = entry?.path();
if path.extension() == Some(OsStr::new(extension)) {
t... | identifier_body |
report.rs | //!
//! The summary page will be rendered to the file `summary.ext` using this data:
//!
//! ```json
//! {
//! "crate_path": "/path/to/workspace",
//! "files": [
//! {
//! "symbol": 123,
//! "path": "/path/to/workspace/src/lib.rs",
//! "summary": {
//! ... | }
}
graph.analyze();
Ok(graph)
}
/// Renders the `report` into `report_path` using a template.
///
/// If the template has a summary page, returns the path of the rendered summary.
fn render(report_path: &Path, template_name: &OsStr, allowed_source_types: SourceType, report: &Report, interner: &Int... | trace!("merging {} {:?}", extension, path);
graph.merge(Gcov::open(path, interner)?)?;
}
| conditional_block |
main.rs | _value(true)
.conflicts_with("print")
);
}
#[cfg(feature = "pulse")] {
clap_app = clap_app
.arg(
Arg::with_name("not-when-audio")
.help("Don't invoke the timer when any audio is playing (PulseAudio specific)")
... | {
Some(match get_idle(self.display, self.info) {
Ok(idle) => idle / 1000, // Convert to seconds
Err(_) => return Some(false)
})
} | conditional_block | |
main.rs | () {
let success = do_main();
std::process::exit(if success { 0 } else { 1 });
}
fn do_main() -> bool {
let clap_app = ClapApp::new(crate_name!())
.author(crate_authors!())
.version(crate_version!())
// Flags
.arg(
Arg::with_name("print")
.help("Pr... | }
#[cfg(feature = "tokio")] {
#[cfg(feature = "pulse")]
let not_when_audio = matches.is_present("not-when-audio");
let socket = matches.value_of("socket");
let app = Rc::new(RefCell::new(app));
let mut core = Core::new().unwrap();
let handle = Rc::new(core.hand... |
thread::sleep(app.delay);
} | random_line_split |
main.rs | {
let success = do_main();
std::process::exit(if success { 0 } else { 1 });
}
fn do_main() -> bool {
let clap_app = ClapApp::new(crate_name!())
.author(crate_authors!())
.version(crate_version!())
// Flags
.arg(
Arg::with_name("print")
.help("Prin... |
let mut playing = 0;
let | {
unsafe {
let state = pa_context_get_state(ctx);
if state == PA_CONTEXT_READY {
pa_context_set_subscribe_callback(ctx, Some(subscribe_callback), userdata);
pa_context_subscribe(ctx, PA_SUBSCRIPT... | identifier_body |
main.rs | 0; 1])
.map_err(|err| {
if err.kind() != ErrorKind::UnexpectedEof {
eprintln!("io error: {}", err);
}
})
.and_then(move |(conn, buf)| {
... | get_idle | identifier_name | |
install.go | "install",
Short: "Set up amp services in swarm environment",
RunE: Install,
}
return installCmd
}
func Install(cmd *cobra.Command, args []string) error {
stdin, stdout, stderr := term.StdStreams()
dockerCli := ampdocker.NewDockerCli(stdin, stdout, stderr)
if err := Docker.Connect(); err != nil {
return ... | if os.IsNotExist(err) {
return false, nil
}
return true, err
}
func createInitialSecrets() error {
// Computing secret path
secretPath := path.Join("/", defaultSecretsPath)
pe, err := pathExists(secretPath)
if err != nil {
return err
}
if !pe {
secretPath = defaultSecretsPath
}
secretPath, err = filep... | return true, nil
} | random_line_split |
install.go | "install",
Short: "Set up amp services in swarm environment",
RunE: Install,
}
return installCmd
}
func Install(cmd *cobra.Command, args []string) error {
stdin, stdout, stderr := term.StdStreams()
dockerCli := ampdocker.NewDockerCli(stdin, stdout, stderr)
if err := Docker.Connect(); err != nil {
return ... | }
func deploy(d *command.DockerCli, stackfile string, namespace string) error {
if namespace == "" {
// use the stackfile basename as the default stack namespace
namespace = filepath.Base(stackfile)
namespace = strings.TrimSuffix(namespace, filepath.Ext(namespace))
}
options := stack.DeployOptions{
Namesp... | {
if path == "" {
path = "./stacks"
}
path += "/" + deploymentMode
// a bit more work but we can't just use filepath.Glob
// since we need to match both *.yml and *.yaml
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
stackfiles := []string{}
for _, f := range files {
name := f.Nam... | identifier_body |
install.go | .NodeList(context.Background(), types.NodeListOptions{})
if err != nil {
return "", err
}
matchingNodes := 0
for _, node := range nodes {
// node is a swarm.Node
for k, v := range node.Spec.Labels {
if k == labelKey {
if labelValue == "" || labelValue == v {
matchingNodes++
}
}
}
}
swit... | {
return nil
} | conditional_block | |
install.go | install",
Short: "Set up amp services in swarm environment",
RunE: Install,
}
return installCmd
}
func Install(cmd *cobra.Command, args []string) error {
stdin, stdout, stderr := term.StdStreams()
dockerCli := ampdocker.NewDockerCli(stdin, stdout, stderr)
if err := Docker.Connect(); err != nil {
return er... | (path string, deploymentMode string) ([]string, error) {
if path == "" {
path = "./stacks"
}
path += "/" + deploymentMode
// a bit more work but we can't just use filepath.Glob
// since we need to match both *.yml and *.yaml
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
stackfiles :... | getStackFiles | identifier_name |
decoder.rs | ::Read::read_exact`, except it never returns `UnexpectedEof` and
/// instead returns the number of bytes read if EOF is seen before filling
/// `buf`.
fn read_full<R: io::Read>(
mut rdr: R,
mut buf: &mut [u8],
) -> io::Result<usize> {
let mut nread = 0;
while !buf.is_empty() {
match rdr.read(buf... | Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(nread)
}
/// A reader that transcodes to UTF-8. The source encoding is determined by
/// inspecting the BOM from the stream read from `R`, if one exists. If a
/// UTF-16 BOM exists, then t... | Ok(n) => {
nread += n;
let tmp = buf;
buf = &mut tmp[n..];
} | random_line_split |
decoder.rs | Read::read_exact`, except it never returns `UnexpectedEof` and
/// instead returns the number of bytes read if EOF is seen before filling
/// `buf`.
fn read_full<R: io::Read>(
mut rdr: R,
mut buf: &mut [u8],
) -> io::Result<usize> {
let mut nread = 0;
while !buf.is_empty() {
match rdr.read(buf) ... |
}
Ok(nwrite)
}
#[inline(never)] // impacts perf...
fn detect(&mut self) -> io::Result<()> {
let bom = self.rdr.peek_bom()?;
self.decoder = bom.decoder();
Ok(())
}
}
impl<R: io::Read, B: AsMut<[u8]>> io::Read for DecodeReader<R, B> {
fn read(&mut self, buf: ... | {
self.pos = 0;
self.last = true;
let (_, _, nout, _) =
self.decoder.as_mut().unwrap().decode_to_utf8(
&[], buf, true);
return Ok(nout);
} | conditional_block |
decoder.rs | . If no encoding of `rdr` is specified, then
/// errors are not handled.
pub fn new(
rdr: R,
buf: B,
enc: Option<&'static Encoding>,
) -> DecodeReader<R, B> {
DecodeReader {
rdr: BomPeeker::new(rdr),
buf: buf,
buflen: 0,
pos: 0,... | trans_utf16_bom | identifier_name | |
decoder.rs |
}
/// `BomPeeker` wraps `R` and satisfies the `io::Read` interface while also
/// providing a peek at the BOM if one exists. Peeking at the BOM does not
/// advance the reader.
struct BomPeeker<R> {
rdr: R,
bom: Option<Bom>,
nread: usize,
}
impl<R: io::Read> BomPeeker<R> {
/// Create a new BomPeeker.... | {
let bom = self.as_slice();
if bom.len() < 3 {
return None;
}
if let Some((enc, _)) = Encoding::for_bom(bom) {
if enc != UTF_8 {
return Some(enc.new_decoder_with_bom_removal());
}
}
None
} | identifier_body | |
action.go | .Chinese: `设置燃气费(单位:10^(-6)IOTX),如果输入为「0」,则使用默认燃气费`,
}
_flagNonceUsages = map[config.Language]string{
config.English: "set nonce (default using pending nonce)",
config.Chinese: "设置 nonce (默认使用 pending nonce)",
}
_flagSignerUsages = map[config.Language]string{
config.English: "choose a signing account",
conf... | }
func registerPasswordFlag(client ioctl.Client, cmd *cobra.Command) {
flag.NewStringVarP(passwordFlagLabel, passwordFlagShortLabel, passwordFlagDefault, selectTranslation(client, _flagPasswordUsages)).RegisterCommand(cmd)
}
func selectTranslation(client ioctl.Client, trls map[config.Language]string) string {
txt, ... |
func registerAssumeYesFlag(client ioctl.Client, cmd *cobra.Command) {
flag.BoolVarP(assumeYesFlagLabel, assumeYesFlagShortLabel, assumeYesFlagDefault, selectTranslation(client, _flagAssumeYesUsages)).RegisterCommand(cmd) | random_line_split |
action.go | .Chinese: `设置燃气费(单位:10^(-6)IOTX),如果输入为「0」,则使用默认燃气费`,
}
_flagNonceUsages = map[config.Language]string{
config.English: "set nonce (default using pending nonce)",
config.Chinese: "设置 nonce (默认使用 pending nonce)",
}
_flagSignerUsages = map[config.Language]string{
config.English: "choose a signing account",
conf... | gisterAssumeYesFlag(client ioctl.Client, cmd *cobra.Command) {
flag.BoolVarP(assumeYesFlagLabel, assumeYesFlagShortLabel, assumeYesFlagDefault, selectTranslation(client, _flagAssumeYesUsages)).RegisterCommand(cmd)
}
func registerPasswordFlag(client ioctl.Client, cmd *cobra.Command) {
flag.NewStringVarP(passwordFlagL... | VarP(bytecodeFlagLabel, bytecodeFlagShortLabel, bytecodeFlagDefault, selectTranslation(client, _flagBytecodeUsages)).RegisterCommand(cmd)
}
func re | identifier_body |
action.go | .Chinese: `设置燃气费(单位:10^(-6)IOTX),如果输入为「0」,则使用默认燃气费`,
}
_flagNonceUsages = map[config.Language]string{
config.English: "set nonce (default using pending nonce)",
config.Chinese: "设置 nonce (默认使用 pending nonce)",
}
_flagSignerUsages = map[config.Language]string{
config.English: "choose a signing account",
conf... | l.Client, cmd *cobra.Command) {
flag.NewUint64VarP(nonceFlagLabel, nonceFlagShortLabel, nonceFlagDefault, selectTranslation(client, _flagNonceUsages)).RegisterCommand(cmd)
}
func registerSignerFlag(client ioctl.Client, cmd *cobra.Command) {
flag.NewStringVarP(signerFlagLabel, signerFlagShortLabel, SignerFlagDefault,... | onceFlag(client ioct | identifier_name |
action.go | }
return client.AddressWithDefaultIfNotExist(signer)
}
func checkNonce(client ioctl.Client, nonce uint64, executor string) (uint64, error) {
if util.AliasIsHdwalletKey(executor) {
// for hdwallet key, get the nonce in SendAction()
return 0, nil
}
if nonce != 0 {
return nonce, nil
}
accountMeta, err := acc... | conditional_block | ||
content_preservation.py | to evaluation -> mask_style_words(texts, mask_style=True)
- View correlations between automated metrics and human scores -> display_correlation_tables()
- Load WMD scores for output texts of examined style transfer models -> load_wmd_scores(...)
- Train a Word2Vec model for your ... | '''
wmd_scores = []
for i in range(len(references)):
wmd = wmd_model.wv.wmdistance(tokenize(references[i]), tokenize(candidates[i]))
wmd_scores.append(wmd)
return wmd_scores
# def load_wmd_scores(model_name, param_val):
# '''
# Load pre-computed WMD scores for input and ... | '''
Calculate Word Mover's Distance for each (reference, candidate)
pair in a list of reference texts and candidate texts.
The lower the distance, the more similar the texts are.
Parameters
----------
references : list
Input texts
candidates : list
Output texts (e.g. fr... | identifier_body |
content_preservation.py | to evaluation -> mask_style_words(texts, mask_style=True)
- View correlations between automated metrics and human scores -> display_correlation_tables()
- Load WMD scores for output texts of examined style transfer models -> load_wmd_scores(...)
- Train a Word2Vec model for your ... | (references, candidates, wmd_model):
'''
Calculate Word Mover's Distance for each (reference, candidate)
pair in a list of reference texts and candidate texts.
The lower the distance, the more similar the texts are.
Parameters
----------
references : list
Input texts
candid... | calculate_wmd_scores | identifier_name |
content_preservation.py | to evaluation -> mask_style_words(texts, mask_style=True)
- View correlations between automated metrics and human scores -> display_correlation_tables()
- Load WMD scores for output texts of examined style transfer models -> load_wmd_scores(...)
- Train a Word2Vec model for your ... | tokenized_texts = []
for text in texts:
tokenized_texts.append(tokenize(text))
model = Word2Vec(tokenized_texts)
model.save(path)
def load_word2vec_model(path):
model = Word2Vec.load(path)
model.init_sims(replace=True) # normalize vectors
return model
def calculate_wmd_scores(refer... | return unmasked_texts, texts_with_style_removed, texts_with_style_masked
## MODELS / SCORING OF WMD
def train_word2vec_model(texts, path): | random_line_split |
content_preservation.py | to evaluation -> mask_style_words(texts, mask_style=True)
- View correlations between automated metrics and human scores -> display_correlation_tables()
- Load WMD scores for output texts of examined style transfer models -> load_wmd_scores(...)
- Train a Word2Vec model for your ... |
edited_texts.append(' '.join(edited_tokens))
return edited_texts
def generate_style_modified_texts(texts, style_lexicon):
# ensure consistent tokenization under different style modification settings
unmasked_texts = mask_style_words(texts, style_tokens={}, mask_style=False)
tex... | if token.lower() in style_tokens:
if mask_style:
edited_tokens.append(CUSTOM_STYLE)
else:
edited_tokens.append(token) | conditional_block |
query.rs | <String, String>`
/// * `HashMap<String, Vec<String>>`
/// * `HashMap<Cow<'static, str>, Cow<'static, str>>`
///
/// You should generally not have to implement this trait yourself, and if you do there are
/// additional requirements on your implementation to guarantee standard conformance. Therefore the
/// trait is ma... | self.0.insert_or_poison(key.into(), value.into())
}
Ok(self.0)
}
}
let visitor = Visitor(NormalizedParameter::default());
deserializer.deserialize_seq(visitor)
}
}
impl<K, V> FromIterator<(K, V)> for NormalizedParameter
where... | while let Some((key, value)) = access.next_element::<(String, String)>()? { | random_line_split |
query.rs | , String>`
/// * `HashMap<String, Vec<String>>`
/// * `HashMap<Cow<'static, str>, Cow<'static, str>>`
///
/// You should generally not have to implement this trait yourself, and if you do there are
/// additional requirements on your implementation to guarantee standard conformance. Therefore the
/// trait is marked as... |
}
/// Return a reference to value in a collection if it is the only one.
///
/// For example, a vector of string like types returns a reference to its first
/// element if there are no other, else it returns `None`.
///
/// If this were done with slices, that would require choosing a particular
/// value type of the ... | {
self.normalize()
} | identifier_body |
query.rs | processing, or simple confusion between different components who parse the
/// query string from different ends.
fn unique_value(&self, key: &str) -> Option<Cow<str>>;
/// Guarantees that one can grab an owned copy.
fn normalize(&self) -> NormalizedParameter;
}
/// The query parameter normal form.
//... | {
None
} | conditional_block | |
query.rs | , String>`
/// * `HashMap<String, Vec<String>>`
/// * `HashMap<Cow<'static, str>, Cow<'static, str>>`
///
/// You should generally not have to implement this trait yourself, and if you do there are
/// additional requirements on your implementation to guarantee standard conformance. Therefore the
/// trait is marked as... | (&self, key: &str) -> Option<Cow<str>> {
self.inner
.get(key)
.and_then(|val| val.as_ref().map(Cow::as_ref).map(Cow::Borrowed))
}
fn normalize(&self) -> NormalizedParameter {
self.clone()
}
}
impl NormalizedParameter {
/// Create an empty map.
pub fn new() -... | unique_value | identifier_name |
Graph.ts | options.treeshake && options.treeshake !== true
? {
annotations: options.treeshake.annotations !== false,
moduleSideEffects: options.treeshake.moduleSideEffects,
propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
pureExternalModules: options.treeshake.pure... | (activeDeprecation || this.strictDeprecations) {
const warning = errDeprecation(deprecation);
if (this.strictDeprecations) {
return error(warning);
}
this.warn(warning);
}
}
pri | identifier_body | |
Graph.ts | (Array.isArray(entryModules)) {
return entryModules.map(id => ({ fileName: null, name: null, id, importer: undefined }));
}
return Object.keys(entryModules).map(name => ({
fileName: null,
id: entryModules[name],
importer: undefined,
name
}));
}
export default class Graph {
acornOptions: acorn.Options;
... | this.pluginDriver = new PluginDriver(this, options.plugins!, this.pluginCache);
if (watcher) {
const handleChange = (id: string) => this.pluginDriver.hookSeqSync('watchChange', [id]);
watcher.on('change', handleChange);
watcher.once('restart', () => {
watcher.removeListener('change', handleChange);
... | random_line_split | |
Graph.ts | Array.isArray(entryModules)) |
return Object.keys(entryModules).map(name => ({
fileName: null,
id: entryModules[name],
importer: undefined,
name
}));
}
export default class Graph {
acornOptions: acorn.Options;
acornParser: typeof acorn.Parser;
cachedModules: Map<string, ModuleJSON>;
contextParse: (code: string, acornOptions?: acorn.O... | {
return entryModules.map(id => ({ fileName: null, name: null, id, importer: undefined }));
} | conditional_block |
Graph.ts | Array.isArray(entryModules)) {
return entryModules.map(id => ({ fileName: null, name: null, id, importer: undefined }));
}
return Object.keys(entryModules).map(name => ({
fileName: null,
id: entryModules[name],
importer: undefined,
name
}));
}
export default class Graph {
acornOptions: acorn.Options;
ac... | (
entryModules: string | string[] | Record<string, string>,
manualChunks: ManualChunksOption | void,
inlineDynamicImports: boolean
): Promise<Chunk[]> {
// Phase 1 – discovery. We load the entry module and find which
// modules it imports, and import those, until we have all
// of the entry module's depend... | build | identifier_name |
reg_adv_train_loop.py | y_class_true
if torch.cuda.is_available():
mark_neglect = torch.cuda.LongTensor(y_class_true.size(0), y_class_true.size(1), y_class_true.size(2)).fill_(1) * neglect == y_class_true
else:
mark_neglect = torch.LongTensor(y_class_true.size(0), y_class_true.size(1), y_class_true.size(2)).fill_(
... | element_same_class = element_same_class.view(-1, y_pred.size(1))
element_same_class = element_same_class / (torch.norm(element_same_class, dim=1, keepdim=True) + epsilon) #TODO: divided , you need epsilon to prevent NAN
matrix = torch.mm(element_same_class,
... | #TODO: check how to reshape this back !!!!!!!!! | random_line_split |
reg_adv_train_loop.py | ():
pass
#TODO: this is a local logdet loss
def log_det_cuda(y_pred, y_class_true, args, neglect = 255): # We need to max Diversity for each class
# TODO: we should first down sampling before move on (like dropout 99%)
delta_det = 1e-3
drop_ratio = 1 - args.drop_ratio
# y_true need to be one ho... | log_det_global_cuda | identifier_name | |
reg_adv_train_loop.py | _class_true
if torch.cuda.is_available():
mark_neglect = torch.cuda.LongTensor(y_class_true.size(0), y_class_true.size(1), y_class_true.size(2)).fill_(1) * neglect == y_class_true
else:
mark_neglect = torch.LongTensor(y_class_true.size(0), y_class_true.size(1), y_class_true.size(2)).fill_(
... |
return det_loss
#TODO: Can we use GAN to align the variance? Use Pang et al? Maximum the overall entropy?
def train_seg_reg(args):
batch_size = args.batch_size
num_workers = args.workers
crop_size = args.crop_size
# print(' '.join(sys.argv))
for k, v in args.__dict__.items():
... | element_same_class = mask_non_y_pred[flat_ind_select]
#TODO: check how to reshape this back !!!!!!!!!
element_same_class = element_same_class.view(-1, y_pred.size(1))
element_same_class = element_same_class / (torch.norm(element_same_class, dim=1, keepdim=True... | conditional_block |
reg_adv_train_loop.py |
# def log_det(y_true, y_pred, num_model=FLAGS.num_models):
# bool_R_y_true = tf.not_equal(tf.ones_like(y_true) - y_true, zero) # batch_size X (num_class X num_models), 2-D
# mask_non_y_pred = tf.boolean_mask(y_pred, bool_R_y_true) # batch_size X (num_class-1) X num_models, 1-D
# mask_non_y_pred = tf.resh... | num_pred = y_pred.size(2) * y_pred.size(3)
entropy_type = "sum_entropy"
if entropy_type == "all_entropy":
flag_pred = y_pred.view(y_pred.size(0), -1)
entropy = torch.sum(-flag_pred * torch.log(flag_pred + log_epsilon)) #TODO: here, even sum the batch dim
elif entropy_type == "sum_entropy": ... | identifier_body | |
resnet_trainer.py | # Training parameters
# architecture = 'resnet34'
# architecture = 'vgg16_bn'
# architecture = 'dense'
lr = 0.1 # densenet default = 0.1,
lr_init = 0.1
momentum = 0.90 # densenet default = 0.9
weight_decay = 1e-3 # densenet default = 1e-4
num_epochs = 125
dummy_text_file = open("dummy_text.txt", "w")
def construct... | fine_size = 224
c = 3
data_mean = np.asarray([0.45834960097,0.44674252445,0.41352266842])
| random_line_split | |
resnet_trainer.py | 0.1,
lr_init = 0.1
momentum = 0.90 # densenet default = 0.9
weight_decay = 1e-3 # densenet default = 1e-4
num_epochs = 125
dummy_text_file = open("dummy_text.txt", "w")
def construct_dataloader_disk():
# Construct DataLoader
opt_data_train = {
#'data_h5': 'miniplaces_128_train.h5',
'data_ro... |
def adjust_learning_rate(lr, optimizer, epoch):
"""Calculates a learning rate of the initial LR decayed by 10 every 30 epochs"""
lr = lr_init * (0.1 ** (epoch // 10))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
# def adjust_learning_rate(lr, optimizer, ... | """Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
... | identifier_body |
resnet_trainer.py | 0.1,
lr_init = 0.1
momentum = 0.90 # densenet default = 0.9
weight_decay = 1e-3 # densenet default = 1e-4
num_epochs = 125
dummy_text_file = open("dummy_text.txt", "w")
def construct_dataloader_disk():
# Construct DataLoader
opt_data_train = {
#'data_h5': 'miniplaces_128_train.h5',
'data_roo... | (filename, lr, momentum, weight_decay):
# filename = "resnet34"
# model = models.__dict__[filename](num_classes=100, | trainer | identifier_name |
resnet_trainer.py | 0.1,
lr_init = 0.1
momentum = 0.90 # densenet default = 0.9
weight_decay = 1e-3 # densenet default = 1e-4
num_epochs = 125
dummy_text_file = open("dummy_text.txt", "w")
def construct_dataloader_disk():
# Construct DataLoader
opt_data_train = {
#'data_h5': 'miniplaces_128_train.h5',
'data_roo... |
train_loader, val_loader = construct_dataloader_disk()
trainval_loader = construct_dataloader_disk_trainval()
def trainer(filename, lr, momentum, weight_decay):
# filename = "resnet34"
# model = models.__dict__[filename](num_classes=100, | criterion = criterion.cuda() | conditional_block |
token.go | obviously not a .crt, but hybrid will treat as blob
keySecretKey = "remote-service.key"
kidSecretKey = "remote-service.properties"
kidSecretPropFormat = "kid=%s" // KID
)
type token struct {
*shared.RootArgs
clientID string
clientSecret string
file string
k... |
if t.ServerConfig != nil {
t.clientID = t.ServerConfig.Tenant.Key
t.clientSecret = t.ServerConfig.Tenant.Secret
}
missingFlagNames := []string{}
if t.clientID == "" {
missingFlagNames = append(missingFlagNames, "key")
}
if t.clientSecret == "" {
missingFlagNames = append(missingFlag... | {
return fmt.Errorf("only valid for legacy or hybrid, use create-secret for hybrid")
} | conditional_block |
token.go | // obviously not a .crt, but hybrid will treat as blob
keySecretKey = "remote-service.key"
kidSecretKey = "remote-service.properties"
kidSecretPropFormat = "kid=%s" // KID
)
type token struct {
*shared.RootArgs
clientID string
clientSecret string
file string... | (t *token, printf shared.FormatFn) *cobra.Command {
c := &cobra.Command{
Use: "create",
Short: "Create a new OAuth token",
Long: "Create a new OAuth token",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
token, err := t.createToken(printf)
if err != nil {
return errors.... | cmdCreateToken | identifier_name |
token.go | missingFlagNames := []string{}
if t.clientID == "" {
missingFlagNames = append(missingFlagNames, "key")
}
if t.clientSecret == "" {
missingFlagNames = append(missingFlagNames, "secret")
}
if err := t.PrintMissingFlags(missingFlagNames); err != nil {
return err
}
t.rotateCert(printf)
... | { return a[i].KeyID() < a[j].KeyID() } | identifier_body | |
token.go | "time"
"github.com/apigee/apigee-remote-service-cli/cmd/provision"
"github.com/apigee/apigee-remote-service-cli/shared"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jws"
"github.com/lestrrat-go/jwx/jwt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"gopkg.i... | "sort" | random_line_split | |
seq2seq_trainer.py | self.input_src = torch.LongTensor(1).to(self.device)
# self.input_src_len = torch.LongTensor(1).to(self.device)
# self.input_trg = torch.LongTensor(1).to(self.device)
# todo: remove it this blocks loading state_dict from checkpoints
# Error(s) in loading state_dict for Seq2SeqCorrector... |
else:
nn.init.constant_(param.data, 0)
def create_mask(self, src):
mask = (src != self.pad_idx).permute(1, 0)
return mask
def forward(self, src, src_len, trg, teacher_forcing_ratio=0.5):
# src = [src len, batch size]
# src_len = [batch size]
... | nn.init.normal_(param.data, mean=0, std=0.01) | conditional_block |
seq2seq_trainer.py | self.input_src = torch.LongTensor(1).to(self.device)
# self.input_src_len = torch.LongTensor(1).to(self.device)
# self.input_trg = torch.LongTensor(1).to(self.device)
# todo: remove it this blocks loading state_dict from checkpoints
# Error(s) in loading state_dict for Seq2SeqCorrector... | (self, logits, target):
return self._loss(logits, target)
def configure_optimizers(self):
# return optim.Adam(self.parameters(), lr=5e-4)
# optimizer = optim.Adam(self.parameters(), lr=1e-3)
# scheduler = optim.LambdaLR(optimizer, ...)
# return [optimizer], [scheduler]
... | loss | identifier_name |
seq2seq_trainer.py | self.enc_hid_dim, # ENC_HID_DIM,
self.dec_hid_dim, # DEC_HID_DIM,
self.dec_dropout, # DEC_DROPOUT,
self.attention,
)
self._init_weights()
def _init_weights(self):
for name, param in self.named_parameters():
if "weight" in name:
... | sync_dist=True,
) | random_line_split | |
seq2seq_trainer.py | self.input_src = torch.LongTensor(1).to(self.device)
# self.input_src_len = torch.LongTensor(1).to(self.device)
# self.input_trg = torch.LongTensor(1).to(self.device)
# todo: remove it this blocks loading state_dict from checkpoints
# Error(s) in loading state_dict for Seq2SeqCorrector... | # output = torch.randn((*trg_seq.size(), self.output_dim), requires_grad=True, device=trg_seq.device)
# output = self.forward(self.input_src, self.input_src_len, self.input_trg)
# old version of forward, with tensors from dataloader
output = self.forward(src_seq, src_lengths, trg_seq)
... | src_batch, trg_batch = batch
src_seq = src_batch["src_ids"]
# change from [batch, seq_len] -> to [seq_len, batch]
src_seq = src_seq.transpose(0, 1)
src_lengths = src_batch["src_lengths"]
trg_seq = trg_batch["trg_ids"]
# change from [batch, seq_len] -> to [seq_len, batch... | identifier_body |
PropDetCode.py | /train.txt", "wb"))
train_txt, train_lbl = pickle.load(open("savedata/train.txt", "rb"))
test_txt, test_lbl = pickle.load(open("savedata/test.txt", "rb"))
dev_txt, dev_lbl = pickle.load(open("savedata/dev.txt", "rb"))
"""### **Dataset+ data_loader**"""
class Vocabulary:
"""
Helper class that maps words to u... | (txt: List[Tuple]):
tokenizer = get_tokenizer("spacy")
list_v = []
for i in txt:
tok = tokenizer(i)
for j in tok:
if list_v.count(j) == 0:
list_v.append(j)
vocab = Vocabulary(tokens=list_v)
return vocab
full_text = train_txt + dev_txt
vocab = fill_vocab(f... | fill_vocab | identifier_name |
PropDetCode.py |
else:
visit[label[0]:label[1]] = 1
res.append(label)
return res
else:
return labels
def clean_text(articles, ids):
texts = []
for article, id in zip(articles, ids):
sentences = article.split('\n')
end = -1
res = []
fo... | label[3] = 1 | conditional_block | |
PropDetCode.py | of this dataset. This is given by the number
of sentences.
"""
return len(self.examples)
def collate_sentences(batch: List[Tuple]):
"""
This function converts a list of batch_size examples to
a Tensor of size batch_size x max_len
batch: [(example_1_tensor, example_1_label),
... | dev_data: torch.LongTensor,
vocab: Vocabulary,
hyperparams: Dict):
self.model = model | random_line_split | |
PropDetCode.py | /train.txt", "wb"))
train_txt, train_lbl = pickle.load(open("savedata/train.txt", "rb"))
test_txt, test_lbl = pickle.load(open("savedata/test.txt", "rb"))
dev_txt, dev_lbl = pickle.load(open("savedata/dev.txt", "rb"))
"""### **Dataset+ data_loader**"""
class Vocabulary:
"""
Helper class that maps words to u... |
def get_token_at_index(self, idx: int):
return self.idx_to_word[idx]
def get_index_of_token(self, token: str):
return self.word_to_idx[token]
def size(self):
return len(self.word_to_idx)
class PropagandaDataset(Dataset):
def __init__(self,
fold: str,
... | self.word_to_idx = {'<PAD>': 0}
for idx, tok in enumerate(tokens, 1):
self.word_to_idx[tok] = idx
# dictionary that maps indices to words
self.idx_to_word = {}
for tok, idx in self.word_to_idx.items():
self.idx_to_word[idx] = tok | identifier_body |
deduction_engine_extended.py | import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, load_from_file
from excut.explanations_mining.explaining_engines_extended import PathBasedClustersExplainerExtended
from excut.explanations_mining.simple_miner.description_miner_extended import DescriptionMinerE... |
def _merge_and_sort_cut(self, per_entity_prediction, threshold=0, topk=-1):
"""
Merge the the inferred facts in case of functional predicates
:param per_entity_prediction:
:return:
"""
def quality_method(p):
return p.get_quality(self.quality, self.qual... | """
Combine predictions from different rules
:param predictions: list of generated predictions
:return: combined single prediction with several sources for equivalent predictions
:rtype: dict
"""
# per_var_predictions = defaultdict(lambda: defaultdict(list))
# f... | identifier_body |
deduction_engine_extended.py | import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, load_from_file
from excut.explanations_mining.explaining_engines_extended import PathBasedClustersExplainerExtended
from excut.explanations_mining.simple_miner.description_miner_extended import DescriptionMinerE... | (self, other):
return other.triple == self.triple
def __hash__(self):
return hash(self.triple)
class DeductionEngine():
"""
Abstract rulebased_deduction/inference engine.
"""
def __init__(self, **kwargs):
pass
def infer(self, descriptions, recursive=False, topk=-1):
... | __eq__ | identifier_name |
deduction_engine_extended.py | import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, load_from_file
from excut.explanations_mining.explaining_engines_extended import PathBasedClustersExplainerExtended
from excut.explanations_mining.simple_miner.description_miner_extended import DescriptionMinerE... |
if target_entities and clear_target_entities:
self.labels_indexer.drop()
return per_entity_predictions
def consolidate(self, predictions):
"""
Combine predictions from different rules
:param predictions: list of generated predictions
:return: combined... | dump_predictions_map(per_entity_predictions, output_filepath, triple_format=True, topk=topk, with_weight=True,
with_description=False, quality=self.quality) | conditional_block |
deduction_engine_extended.py | import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, load_from_file
from excut.explanations_mining.explaining_engines_extended import PathBasedClustersExplainerExtended
from excut.explanations_mining.simple_miner.description_miner_extended import DescriptionMinerE... | :param with_description:
:return:
"""
out_file_parsable = out_filepath + '.parsable'
out_filepath_with_type = out_filepath + ('.%s' % quality if len(quality) > 0 else '')
with open(out_filepath_with_type, 'w') as out_file:
for var, predictions in per_var_predictions.items():
... | random_line_split | |
system.rs | vulkano::instance::{Instance, PhysicalDevice};
use vulkano::swapchain;
use vulkano::swapchain::{
AcquireError, ColorSpace, FullscreenExclusive, PresentMode, Surface, SurfaceTransform,
Swapchain, SwapchainCreationError,
};
use vulkano::sync;
use vulkano::sync::{FlushError, GpuFuture};
use vulkano_win::VkSurface... | sensor_radius: 1,
// In the range [0 - PI]
sensor_angle_spacing: 0.18,
// Seconds per frame. (60fps)
delta_time: 0.016667,
};
let mut fade_parameters: blur_fade_shader::ty::PushConstantData =
blur_fade_shader::ty::PushConstantData ... | random_line_split | |
system.rs | vulkano::instance::{Instance, PhysicalDevice};
use vulkano::swapchain;
use vulkano::swapchain::{
AcquireError, ColorSpace, FullscreenExclusive, PresentMode, Surface, SurfaceTransform,
Swapchain, SwapchainCreationError,
};
use vulkano::sync;
use vulkano::sync::{FlushError, GpuFuture};
use vulkano_win::VkSurface... | .build_vk_surface(&event_loop, instance.clone())
.unwrap();
let queue_family = physical
.queue_families()
.find(|&q|
q.supports_graphics() && q.explicitly_supports_transfers()
&& surface.is_supported(q).unwrap_or(false)
... | {
// Basic commands taken from the vulkano imgui examples:
// https://github.com/Tenebryo/imgui-vulkano-renderer/blob/master/examples/support/mod.rs
let instance = {
let extensions = vulkano_win::required_extensions();
Instance::new(None, &extensions, None).expect("Faile... | identifier_body |
system.rs | vulkano::instance::{Instance, PhysicalDevice};
use vulkano::swapchain;
use vulkano::swapchain::{
AcquireError, ColorSpace, FullscreenExclusive, PresentMode, Surface, SurfaceTransform,
Swapchain, SwapchainCreationError,
};
use vulkano::sync;
use vulkano::sync::{FlushError, GpuFuture};
use vulkano_win::VkSurface... | <
F: FnMut(
&mut bool,
&mut PushConstantData,
&mut blur_fade_shader::ty::PushConstantData,
&mut Ui,
) + 'static,
>(
self,
simulation: Simulation,
mut run_ui: F,
) {
let System {
event_... | main_loop | identifier_name |
dl_ocr_API.py | : <False/True> "valid address or not"
}
'''
def parse_DL(full_text):
print('full text - ', full_text)
## Remove non-ascii characters that are inserted by google vision sometimes.
all_ascii = ''.join(char for char in full_text if ord(char) < 128)
if full_text != all_ascii :
print('### ... | DLN_valid = False if EXP_datetime <= datetime.datetime.now() else True ## check if DL is still valid
else:
imp_DATES = sorted(imp_DATES, key=lambda x: datetime.datetime.strptime(x, '%m-%d-%Y'))
EXP_datetime = datetime.datetime.strptime(imp_DATES[-1], "%m-%d-%Y")
DLN_valid = False if ... | imp_DATES = sorted(imp_DATES, key=lambda x: datetime.datetime.strptime(x, '%m/%d/%Y'))
EXP_datetime = datetime.datetime.strptime(imp_DATES[-1], "%m/%d/%Y") | random_line_split |
dl_ocr_API.py | Address state is:', state)
# get DL number for IL
if state == 'IL':
# IL DLN is 14 digits - X999-999-999
DLN = re.search('\D\d{3}-\d{4}-\d{4}', full_str).group(0)
# get DL number for TX
if state == 'TX':
DLN = re.search('\d{6}9', full_str).group(0)
# get D... | """API Call
Pandas dataframe (sent as a payload) from API Call
"""
#print("\n\n Started processing the GET request..\n")
##################
# REQUEST STRCUTRE
# imgurl
#################
try:
#req = request.json
img_path = request.args.get('imgurl', type=... | identifier_body | |
dl_ocr_API.py | ['components']['state_abbreviation'],
"zip": address['components']['zipcode'] + '-' + address['components']['plus4_code']
}
state = address['components']['state_abbreviation'] # get state code for all other work.
### END OF IF ELSE STRUCT... | get_DL | identifier_name | |
dl_ocr_API.py | <False/True> "valid address or not"
}
'''
def parse_DL(full_text):
print('full text - ', full_text)
## Remove non-ascii characters that are inserted by google vision sometimes.
all_ascii = ''.join(char for char in full_text if ord(char) < 128)
if full_text != all_ascii :
print('### -... |
### END OF IF ELSE STRUCTURE
except Exception as e:
print(e)
print('###@@@@### Error occured while building address from SmartyStreets API response')
sentry.captureMessage(message=e, level=logging.FATAL) #printing all exceptions to the log
## make a continuous string w... | address = SSresp['addresses'][0]['api_output'][0]
## fomulate address
postal_address = {
"add_ln1": address['delivery_line_1'],
"add_ln2": '',
"city": address['components']['city_name'],
... | conditional_block |
LIST.py | 2 == 0]) #第三列的偶数。
print([L[i][i] for i in [0,1,2,3]])# 获取对角元素值。
print([sum(row) for row in L]) # 求每行元素的和。
M = [[1,2,3],[4,5,6],[7,8,9]]
N = [[2,2,2],[3,3,3],[4,4,4]]
print([M[row][i]*N[row][i] for row in range(3) for i in range(3)])
print("M与N对应元素乘积:%s" % [[M[row][i]*N[row][i] for row in range(3)] for i in range(3)])... | identifier_name | ||
LIST.py | 2 == 0]) #第三列的偶数。
print([L[i][i] for i in [0,1,2,3]])# 获取对角元素值。
print([sum(row) for row in L]) # 求每行元素的和。
M = [[1,2,3],[4,5,6],[7,8,9]]
N = [[2,2,2],[3,3,3],[4,4,4]]
print([M[row][i]*N[row][i] for row in range(3) for i in range(3)])
print("M与N对应元素乘积:%s" % [[M[row][i]*N[row][i] for row in range(3)] for i in range(3)])... | identifier_body | ||
LIST.py | ----
# 当第三个参数为负数时,将会进行逆序切片操作
# 例如,获取原列表的完整逆序拷贝
print(L[::-1])
# --------------------
# 这样,获取原列表的方法其实还有不传入第三个参数的办法
print(L[::])
# --------------------
# 注意:与索引操作不同,所有切片操作获得列表元素的浅拷贝
# 例如,以下结果返回False
print(L[0:1] is L[0:1])
print(id(L[0:1]) == id(L[0:1]))
if __name__ == '__mai... | L = [["a","b",["c",[1,[2],"d"],"e"]],[3,'f'],4,"g",5]
# 递归遍历。
def flattenList(L,new_list=[]):
# 展平多重列表 | random_line_split | |
LIST.py | 2 == 0]) #第三列的偶数。
print([L[i][i] for i in [0,1,2,3]])# 获取对角元素值。
print([sum(row) for row in L]) # 求每行元素的和。
M = [[1,2,3],[4,5,6],[7,8,9]]
N = [[2,2,2],[3,3,3],[4,4,4]]
print([M[row][i]*N[row][i] for row in range(3) for i in range(3)])
print("M与N对应元素乘积:%s" % [[M[row][i]*N[row][i] for row in range(3)] for i in range(3)])... | conditional_block | ||
part2.py | _groups, kernel_groups)]
conv = tf.concat(3, output_groups)
return tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape().as_list())
################################################################################
#Read Image
def create_new_input(dataset, datasize, n):
'''This function takes in all... |
train_matrix = create_new_input(train_dir, 70, i)
valid_matrix = create_new_input(valid_dir, 20, i)
test_matrix = create_new_input(test_dir, counter, i)
mdict["train"+str(i)] = train_matrix
mdict["valid"+str(i)] = valid_matrix
mdict["test"+str(i)] = test_matrix
s... | counter += 1 | conditional_block |
part2.py | (input_groups, kernel_groups)]
conv = tf.concat(3, output_groups)
return tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape().as_list())
################################################################################
#Read Image
def create_new_input(dataset, datasize, n):
'''This function takes ... | conv3b = tf.Variable(net_data["conv3"][1])
conv3_in = conv(maxpool2, conv3W, conv3b, k_h, k_w, c_o, s_h, s_w, padding="SAME", group=group)
conv3 = tf.nn.relu(conv3_in)
#conv4
#conv(3, 3, 384, 1, 1, group=2, name='conv4')
k_h = 3; k_w = 3; c_o = 384; s_h = 1; s_w = 1; group = 2
conv4W = t... | #conv(3, 3, 384, 1, 1, name='conv3')
k_h = 3; k_w = 3; c_o = 384; s_h = 1; s_w = 1; group = 1
conv3W = tf.Variable(net_data["conv3"][0]) | random_line_split |
part2.py | _groups, kernel_groups)]
conv = tf.concat(3, output_groups)
return tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape().as_list())
################################################################################
#Read Image
def create_new_input(dataset, datasize, n):
'''This function takes in all... |
def create_M_for_actor(actor, test_dir):
''' This function creates a .mat file which stores all faces
'''
mdict = {}
counter = 0
for i in range(6):
if act[i] == actor:
break
for filename in os.listdir(test_dir+actor+"/"):
counter += 1
test_matrix = creat... | ''' This function creates a .mat file which stores all faces
'''
mdict = {}
i = 0
for actor in act:
counter = 0
for filename in os.listdir(test_dir+actor+"/"):
counter += 1
train_matrix = create_new_input(train_dir, 70, i)
valid_matrix = create_new_input(valid... | identifier_body |
part2.py | _groups, kernel_groups)]
conv = tf.concat(3, output_groups)
return tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape().as_list())
################################################################################
#Read Image
def | (dataset, datasize, n):
'''This function takes in all images in a given data set with given size and n is used to indicate the index of actor from the act list.
'''
actor_dir = act[n]+"/"
x_dummy = (random.random((datasize,)+ xdim)/255.).astype(float32)
i = x_dummy.copy()
if datasize == 70:
... | create_new_input | identifier_name |
action.py | "],
"ylim" : (None,10),
"ylabel" : "Y",
"linewidth" : [1,1.5]
}
kwargs: parameters corresponding to items of option.
"""
list_of_entry = to_flatlist(
{"data":data_source,**default_kwargs, **se... |
default_kwargs = {}
_tick_params_each = {
"labelsize": 12,
"rotation": 0,
"which": "both",
"direction": "in",
"color": "black",
"labelcolor": "black"
}
_tick_params_kwargs = {
**_tick_params_each,
"labelbottom": None,
"labelleft": None,
"labeltop": None,
"labelright": No... | """
Select coordinate transform method for x and y axis.
"""
return matplotlib.transforms.blended_transform_factory(
ax.transAxes if xcoordinate is "axes" else ax.transData,
ax.transAxes if ycoordinate is "axes" else ax.transData
) | identifier_body |
action.py | "],
"ylim" : (None,10),
"ylabel" : "Y",
"linewidth" : [1,1.5]
}
kwargs: parameters corresponding to items of option.
"""
list_of_entry = to_flatlist(
{"data":data_source,**default_kwargs, **se... |
elif type(d) in [list, dict]:
return pd.DataFrame(d)
else:
raise TypeError(f"{type(d)} is not available for data source.")
def generate_arg_and_kwags():
"""
Setup positional arguments and keyword arguments for plotter.
"""
def gen_func(
#df: DataSource,
option:... | return d | conditional_block |
action.py | kwarg_filter = filter_dict(default_kwargs.keys())
def presetting(setting={}, **setting_kwargs):
def set_data(data_source: DataSource, option: dict={}, **option_kwargs):
"""
Parameters
----------
df: pandas.DataFrame | dict
option: dict, option... | arg_filter = get_values_by_keys(["data"]+arg_names, None) | random_line_split | |
action.py | "],
"ylim" : (None,10),
"ylabel" : "Y",
"linewidth" : [1,1.5]
}
kwargs: parameters corresponding to items of option.
"""
list_of_entry = to_flatlist(
{"data":data_source,**default_kwargs, **se... | (_, k, v):
"""
Return value.
"""
return v if v is not None else default
return f
def is_iterable(o):
return type(o) in [list, tuple]
def to_flatlist(d: dict) -> List[dict]:
"""
Usage
-----
d = {
"x" : (0,1,2),
"y" : [1,2],
"z" : 0
}... | f | identifier_name |
transformer.go | ) (nodes.Node, bool) {
nn, ok, err := f(n)
if err != nil {
last = err
return n, false
} else if !ok {
return n, false
}
return nn, ok
})
if ok {
return nn, last
}
return n, last
}
var _ Transformer = (TransformObjFunc)(nil)
// TransformObjFunc is like TransformFunc, but only matches Object no... |
func MapObj(src, dst ObjectOp) ObjMapping {
return objMapping{src: src, dst: dst}
}
func MapPart(vr string, m ObjMapping) ObjMapping {
src, dst := m.ObjMapping()
_, sok := src.Fields()
_, dok := dst.Fields()
if !sok && !dok {
// both contain partial op, ignore current label
return MapObj(src, dst)
} else i... | {
return mapping{src: src, dst: dst}
} | identifier_body |
transformer.go | }
return mp
}
type mappings struct {
all []Mapping
// indexed mappings
byKind map[nodes.Kind][]Mapping // mappings applied to specific node kind
typedObj map[string][]Mapping // mappings for objects with specific type
typedAny []Mapping // mappings for any typed object (operations that does not me... |
// GetStateVar returns a stored sub-state from a named variable.
func (st *State) GetStateVar(name string) ([]*State, bool) {
n, ok := st.states[name]
return n, ok | random_line_split | |
transformer.go | ) (nodes.Node, bool) {
nn, ok, err := f(n)
if err != nil {
last = err
return n, false
} else if !ok {
return n, false
}
return nn, ok
})
if ok {
return nn, last
}
return n, last
}
var _ Transformer = (TransformObjFunc)(nil)
// TransformObjFunc is like TransformFunc, but only matches Object no... | else if !ok {
return n, false
}
nn, err := dst.Construct(st, nil)
if err != nil {
errs = append(errs, errConstruct.Wrap(err))
return n, false
}
return nn, true
})
err := NewMultiError(errs...)
if ok {
return nn, err
}
return root, err
}
// Mappings takes multiple mappings and optimizes the p... | {
errs = append(errs, errCheck.Wrap(err))
return n, false
} | conditional_block |
transformer.go | err := f(n)
if err != nil {
last = err
return n, false
} else if !ok {
return n, false
}
return nn, ok
})
if ok {
return nn, last
}
return n, last
}
var _ Transformer = (TransformObjFunc)(nil)
// TransformObjFunc is like TransformFunc, but only matches Object nodes.
type TransformObjFunc func(... | Reset | identifier_name | |
base-chart.component.ts | 186, 115, 64, 107, 171, 199, 107, 138];
private pointStyles = [
'circle', 'rect', 'triangle', 'cross', 'crossRot', 'rectRot', 'star'
];
private chart: Chart;
private tickStyle = {
autoSkip: false,
fontSize: 16,
fontColor: '#383838',
};
private onDestroy: Subject<boolean> = new Subject<b... | this.onDestroy.next(true);
this.onDestroy.unsubscribe();
}
@HostListener('window:resize')
onResize() {
this.windowWidth = window.innerWidth;
const currentPosition = this.chart.config.options.legend.position;
const newPosition = this.getLegendPosition();
if (currentPosition !== newPositi... | random_line_split | |
base-chart.component.ts | Mode = highContrastMode;
this.alternatePointMode = alternatePointsMode;
this.datasets = this.mapExperimentsToChartData(state);
this.title = graphTitle;
this.Yaxis = yAxis;
this.xAxisLabel = dependency.axisName + ' ' + dependency.variable + ' ' + dependency.bracketedUnit;
... | {
const xyPoints = xVals.map( (e, i) => [e, yVals[i]] ).map( (xs) => {
return { x: xs[0], y: xs[1] };
} );
return this.orderPoints(xyPoints);
} | identifier_body | |
base-chart.component.ts | 186, 115, 64, 107, 171, 199, 107, 138];
private pointStyles = [
'circle', 'rect', 'triangle', 'cross', 'crossRot', 'rectRot', 'star'
];
private chart: Chart;
private tickStyle = {
autoSkip: false,
fontSize: 16,
fontColor: '#383838',
};
private onDestroy: Subject<boolean> = new Subject<b... | () {
return this.windowWidth >= 800 ? 'right' : 'bottom';
}
public updateChartAndMetaData() {
if (this.chart) {
this.switchAxisScale(this.logScaleY, 'y');
this.switchAxisScale(this.logScaleX, 'x');
this.chart.config.options.title.text = this.title;
this.chart.config.options.scales.x... | getLegendPosition | identifier_name |
base-chart.component.ts | 186, 115, 64, 107, 171, 199, 107, 138];
private pointStyles = [
'circle', 'rect', 'triangle', 'cross', 'crossRot', 'rectRot', 'star'
];
private chart: Chart;
private tickStyle = {
autoSkip: false,
fontSize: 16,
fontColor: '#383838',
};
private onDestroy: Subject<boolean> = new Subject<b... |
}
public updateChart() {
if (this.chart) {
this.chart.data.datasets = this.datasets;
this.chart.update({
duration:0});
}
}
public updateChartWidth() {
this.chart.config.options.legend.position = this.getLegendPosition();
this.chart.update({
duration:0});
}
pub... | {
this.switchAxisScale(this.logScaleY, 'y');
this.switchAxisScale(this.logScaleX, 'x');
this.chart.config.options.title.text = this.title;
this.chart.config.options.scales.xAxes[0].scaleLabel.labelString = this.xAxisLabel;
this.chart.config.options.scales.yAxes[0].scaleLabel.labelString = ... | conditional_block |
api.py | select=None)
url = self.BASE_URL + 'journals'
return self._make_get_request(url,models.JournalSearchResult,params,return_type)
def licenses(self,filter=None,n_rows=None,n_random=None,
offset=None,query=None,sort_by=None,order=None,
... | return doi | random_line_split | |
api.py | """
search_keys = ['cursor',
'facet',
'filter',
'n_rows',
'n_random',
'offset',
'order',
'query',
'select',
'sort_by']
#search_examples = {}
def __init__(self,debug=False,session=None):
... |
elif key_name == 'filter':
pass
elif key_name == 'n_rows':
return None
elif key_name == 'n_random':
return None
elif key_name == 'offset':
return None
elif key_name == 'order':
return sv.order
elif key_name == '... | pass | conditional_block |
api.py | """
search_keys = ['cursor',
'facet',
'filter',
'n_rows',
'n_random',
'offset',
'order',
'query',
'select',
'sort_by']
#search_examples = {}
def __init__(self,debug=False,session=None):
... | ua_str = 'st_crossref/%s (https://github.com/ScholarTools/crossref_api_python; mailto:%s)' % (VERSION,user_config.email)
headers = {'user-agent': ua_str}
#TODO Check params and # of results ...
#TODO: Implement rate limits ...
... | """
This function is the entry point for making requests.
"""
if params is None:
params = {}
if extras is None:
extras = {}
#Polite Pool Work
#---------------------------------------
#Example
... | identifier_body |
api.py | """
search_keys = ['cursor',
'facet',
'filter',
'n_rows',
'n_random',
'offset',
'order',
'query',
'select',
'sort_by']
#search_examples = {}
def __init__(self,debug=False,session=None):
... | (self,filter=None,n_rows=None,n_random=None,
offset=None,query=None,sort_by=None,order=None,
facet=None,cursor=None,select=None):
#https://github.com/CrossRef/rest-api-doc#parameters
#I'm not thrilled about order ...
#
params = {
... | _options_to_dict | identifier_name |
scaledobject_controller.go | logr.Logger
Client client.Client
Scheme *runtime.Scheme
scaleClient *scale.ScalesGetter
restMapper meta.RESTMapper
scaledObjectsGenerations *sync.Map
scaleHandler scaling.ScaleHandler
kubeVersion kedautil.K8sVersion
}
// SetupWithManager initializes the Scal... | const labelScaledObjectName = "scaledObjectName"
if scaledObject.Labels == nil {
scaledObject.Labels = map[string]string{labelScaledObjectName: scaledObject.Name}
} else {
value, found := scaledObject.Labels[labelScaledObjectName]
if found && value == scaledObject.Name {
return nil
}
scaledObject.Label... | }
// ensureScaledObjectLabel ensures that scaledObjectName=<scaledObject.Name> label exist in the ScaledObject
// This is how the MetricsAdapter will know which ScaledObject a metric is for when the HPA queries it.
func (r *ScaledObjectReconciler) ensureScaledObjectLabel(logger logr.Logger, scaledObject *kedav1alpha1.... | random_line_split |
scaledobject_controller.go | rest of ScaledObjectReconciler
r.restMapper = mgr.GetRESTMapper()
r.scaledObjectsGenerations = &sync.Map{}
r.scaleHandler = scaling.NewScaleHandler(mgr.GetClient(), r.scaleClient, mgr.GetScheme())
// Start controller
return ctrl.NewControllerManagedBy(mgr).
// predicate.GenerationChangedPredicate{} ignore upda... | {
status.OriginalReplicaCount = &scale.Spec.Replicas
} | conditional_block | |
scaledobject_controller.go | logr.Logger
Client client.Client
Scheme *runtime.Scheme
scaleClient *scale.ScalesGetter
restMapper meta.RESTMapper
scaledObjectsGenerations *sync.Map
scaleHandler scaling.ScaleHandler
kubeVersion kedautil.K8sVersion
}
// SetupWithManager initializes the Scal... | newHPACreated, err := r.ensureHPAForScaledObjectExists(logger, scaledObject, &gvkr)
if err != nil {
return "Failed to ensure HPA is correctly created for ScaledObject", err
}
scaleObjectSpecChanged := false
if !newHPACreated {
// Lets Check whether ScaledObject generation was changed, ie. there were changes in... | {
// Check scale target Name is specified
if scaledObject.Spec.ScaleTargetRef.Name == "" {
err := fmt.Errorf("ScaledObject.spec.scaleTargetRef.name is missing")
return "ScaledObject doesn't have correct scaleTargetRef specification", err
}
// Check the label needed for Metrics servers is present on ScaledObjec... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.