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 |
|---|---|---|---|---|
struct-base-wrong-type.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo { a: isi... | random_line_split | |
struct-base-wrong-type.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let b = Bar { x: 5 };
let f = Foo { a: 2, ..b }; //~ ERROR mismatched types
//~| expected `Foo`
//~| found `Bar`
//~| expected struct `Foo`
//~| found struct `Bar`
let f__isize = Fo... | identifier_body | |
struct-base-wrong-type.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { x: isize }
static bar: Bar = Bar { x: 5 };
static foo: Foo = Foo { a: 2, ..bar }; //~ ERROR mismatched types
//~| expected `Foo`
//~| found `Bar`
//~| expected struct `Foo`
... | Bar | identifier_name |
pipelines_as_code.tsx | 021 ThoughtWorks, 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 agreed to in writing... | (isSupportedScm: boolean, updated: boolean) {
const vm = this.model;
if (updated) {
if (this.useSameRepoForPaC() && isSupportedScm) {
this.configRepo().material(cloneMaterialForPaC(vm.material));
}
this.configRepo().pluginId(this.pluginId());
vm.preview(this.pluginId()).then((... | onContentChange | identifier_name |
pipelines_as_code.tsx | 21 ThoughtWorks, 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 agreed to in writing,... |
result.do((res) => {
this.mimeType(result.header("content-type")!.split(";").shift()!);
this.content(res.body);
}, (err) => console.error(err)); // tslint:disable-line no-console
});
}
}
componentToDisplay(vnode: m.Vnode) {
const vm = this.model;
const isSupp... | {
return;
} | conditional_block |
pipelines_as_code.tsx | 021 ThoughtWorks, 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 agreed to in writing... | }
// tests if we can use a given material for config repos
function pacSupportedMaterial(material: Material) {
const type = material.type();
return !!type && !["dependency", "package", "plugin"].includes(type);
}
// duplicates a material for use with config repos; this removes the material
// name and destination... | random_line_split | |
pipelines_as_code.tsx | 21 ThoughtWorks, 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 agreed to in writing,... |
pageName() {
return "Add a New Pipeline as Code";
}
onContentChange(isSupportedScm: boolean, updated: boolean) {
const vm = this.model;
if (updated) {
if (this.useSameRepoForPaC() && isSupportedScm) {
this.configRepo().material(cloneMaterialForPaC(vm.material));
}
this.c... | {
this.pageState = PageState.OK;
const group = queryParamAsString(window.location.search, "group").trim();
if ("" !== group) {
this.model.pipeline.group(group);
}
} | identifier_body |
macro_rules.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ], Some(SEMI), false, 0u, 2u)),
//to phase into semicolon-termination instead of
//semicolon-separation
ms(match_seq(~[ms(match_tok(SEMI))], None, true, 2u, 2u))];
// Parse the macro_rules! invocation (`none` is for no interpolations):
let arg_reader = new_tt_reader(copy cx.par... | ms(match_tok(FAT_ARROW)),
ms(match_nonterminal(rhs_nm, special_idents::tt, 1u)), | random_line_split |
macro_rules.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let lhs_nm = cx.parse_sess().interner.gensym("lhs");
let rhs_nm = cx.parse_sess().interner.gensym("rhs");
// The grammar for macro_rules! is:
// $( $lhs:mtcs => $rhs:tt );+
// ...quasiquoting this would be nice.
let argument_gram = ~[
ms(match_seq(~[
ms(match_nonterminal... | {
spanned { node: copy m, span: dummy_sp() }
} | identifier_body |
macro_rules.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (m: matcher_) -> matcher {
spanned { node: copy m, span: dummy_sp() }
}
let lhs_nm = cx.parse_sess().interner.gensym("lhs");
let rhs_nm = cx.parse_sess().interner.gensym("rhs");
// The grammar for macro_rules! is:
// $( $lhs:mtcs => $rhs:tt );+
// ...quasiquoting this would be nice.
... | ms | identifier_name |
chop.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use std::any::Any;
use std::sync::Arc;
use rustc_serialize::json::{Json, Decoder, ToJson, encode};
us... |
if members.len() <= MAX_CHOP {
vec![Chop { members: members } ]
} else {
Vec::new()
}
}
}
#[derive(Debug, Clone, Hash, PartialEq)]
pub struct ChopType;
impl TypeT for ChopType {
fn name(&self) -> Option<&'static str> {
Some("chop")
}
fn extract(&... | {
members.push(func.clone());
members.sort();
} | conditional_block |
chop.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use std::any::Any;
use std::sync::Arc;
use rustc_serialize::json::{Json, Decoder, ToJson, encode};
us... |
typet_boiler!();
}
impl ValueT for Chop {
fn type_(&self) -> Type {
Arc::new(ChopType)
}
fn get(&self) -> &Any {
self as &Any
}
fn to_sql(&self) -> Vec<&ToSql> {
vec![self]
}
valuet_boiler!();
}
impl ToSql for Chop {
accepts!(::postgres::types::JSONB, ::pos... | {
"jsonb"
} | identifier_body |
chop.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use holmes::pg::RowIter;
use holmes::pg::dyn::{Type, Value};
use std::any::Any;
use std::sync::Arc;
use rustc_serialize::json::{Json, Decoder, ToJson, encode};
us... | (
&self,
ty: &::postgres::types::Type,
out: &mut Vec<u8>,
) -> ::std::result::Result<IsNull, Box<::std::error::Error + Send + Sync>> {
self.to_json().to_sql(ty, out)
}
}
impl ToValue for Chop {
fn to_value(self) -> Value {
Arc::new(self)
}
}
// TODO placeholder
... | to_sql | identifier_name |
chop.rs | use bap::high::bitvector::BitVector;
use holmes::pg::dyn::values::{ValueT, ToValue};
use holmes::pg::dyn::types::TypeT;
use postgres::types::{ToSql, IsNull};
use holmes::pg::RowIter; | use std::any::Any;
use std::sync::Arc;
use rustc_serialize::json::{Json, Decoder, ToJson, encode};
use rustc_serialize::Decodable;
#[derive(Debug, Clone, Hash, PartialOrd, PartialEq, RustcDecodable, RustcEncodable, Eq)]
pub struct Chop {
members: Vec<BitVector>,
}
impl ToJson for Chop {
fn to_json(&self) -> J... | use holmes::pg::dyn::{Type, Value}; | random_line_split |
column-manager-view.js | define(function(require) {
'use strict';
var ColumnManagerView;
var _ = require('underscore');
var BaseView = require('oroui/js/app/views/base/view');
ColumnManagerView = BaseView.extend({
template: require('tpl!orodatagrid/templates/column-manager/column-manager.html'),
autoRender... | this.$('[data-role="column-manager-select-all"]').toggleClass('disabled', !hasUnrenderable);
},
/**
* Handles renderable change of column models
* - updates the view
*/
onRenderableChange: function() {
this.updateView();
},
on... | updateView: function() {
var models = this._getFilteredModels();
var hasUnrenderable = Boolean(_.find(models, function(model) {return !model.get('renderable');})); | random_line_split |
ftpmirror.py | for o, a in opts:
if o == '-l': login = a
if o == '-p': passwd = a
if o == '-a': account = a
if o == '-v': verbose = verbose + 1
if o == '-q': verbose = 0
if o == '-i': interactive = 1
if o == '-m': mac = 1; nologin = 1; skippats.append('*.o')
if o == ... | global verbose, interactive, mac, rmok, nologin
try:
opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v')
except getopt.error as msg:
usage(msg)
login = ''
passwd = ''
account = ''
if not args: usage('hostname missing')
host = args[0]
port = 0
if ':' in host:
... | identifier_body | |
ftpmirror.py | :
text = open(infofilename, 'r').read()
except IOError as msg:
text = '{}'
try:
info = eval(text)
except (SyntaxError, NameError):
print('Bad mirror info in', repr(infofilename))
info = {}
subdirs = []
listing = []
if verbose: print('Listing remote directo... | if dirname: makedir(dirname)
os.mkdir(pathname, 0o777)
| random_line_split | |
ftpmirror.py | 1: print('cwd(%s)' % repr(remotedir))
f.cwd(remotedir)
if verbose > 1: print('OK.')
pwd = f.pwd()
if verbose > 1: print('PWD =', repr(pwd))
#
mirrorsubdir(f, localdir)
# Core logic: mirror one subdirectory (recursively)
def mirrorsubdir(f, localdir):
pwd = f.pwd()
if loc... | askabout | identifier_name | |
ftpmirror.py | ologin
try:
opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v')
except getopt.error as msg:
usage(msg)
login = ''
passwd = ''
account = ''
if not args: usage('hostname missing')
host = args[0]
port = 0
if ':' in host:
host, port = host.split(':', 1)
... |
else:
fp1 = fp
t0 = time.time()
try:
f.retrbinary('RETR ' + filename,
fp1.write, 8*1024)
except ftplib.error_perm as msg:
print(msg)
t1 = time.time()
bytes = fp.tell()
... | fp1 = LoggingFile(fp, 1024, sys.stdout) | conditional_block |
timer.rs | extern crate coio;
use std::sync::Arc;
fn invoke_every_ms<F>(ms: u64, f: F)
where F: Fn() + Sync + Send + 'static
{
let f = Arc::new(f);
coio::spawn(move|| {
loop {
coio::sleep_ms(ms);
let f = f.clone();
coio::spawn(move|| (*f)());
}
});
}
fn invoke... | {
coio::spawn(|| {
for i in 0..10 {
println!("Qua {}", i);
coio::sleep_ms(2000);
}
});
invoke_every_ms(1000, || println!("Purr :P"));
invoke_after_ms(10000, || println!("Tadaaaaaaa"));
coio::run(2);
} | identifier_body | |
timer.rs | extern crate coio;
use std::sync::Arc;
fn invoke_every_ms<F>(ms: u64, f: F)
where F: Fn() + Sync + Send + 'static
{
let f = Arc::new(f); | let f = f.clone();
coio::spawn(move|| (*f)());
}
});
}
fn invoke_after_ms<F>(ms: u64, f: F)
where F: FnOnce() + Send + 'static
{
coio::spawn(move|| {
coio::sleep_ms(ms);
f();
});
}
fn main() {
coio::spawn(|| {
for i in 0..10 {
pri... | coio::spawn(move|| {
loop {
coio::sleep_ms(ms); | random_line_split |
timer.rs | extern crate coio;
use std::sync::Arc;
fn | <F>(ms: u64, f: F)
where F: Fn() + Sync + Send + 'static
{
let f = Arc::new(f);
coio::spawn(move|| {
loop {
coio::sleep_ms(ms);
let f = f.clone();
coio::spawn(move|| (*f)());
}
});
}
fn invoke_after_ms<F>(ms: u64, f: F)
where F: FnOnce() + Send + ... | invoke_every_ms | identifier_name |
py3kcompat.py | # -*- coding: utf-8 -*-
#
# This file is part of the Shiboken Python Bindings Generator project.
#
# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
#
# Contact: PySide team <contact@pyside.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Le... | def b(s):
return s
def l(n):
return long(n)
unicode = unicode
long = long | conditional_block | |
py3kcompat.py | # -*- coding: utf-8 -*-
#
# This file is part of the Shiboken Python Bindings Generator project.
#
# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
#
# Contact: PySide team <contact@pyside.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Le... | # WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# ... | # review the following information to ensure the GNU Lesser General
# Public License version 2.1 requirements will be met:
# http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
# #
# This program is distributed in the hope that it will be useful, but | random_line_split |
py3kcompat.py | # -*- coding: utf-8 -*-
#
# This file is part of the Shiboken Python Bindings Generator project.
#
# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
#
# Contact: PySide team <contact@pyside.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Le... | (n):
return n
long = int
else:
def b(s):
return s
def l(n):
return long(n)
unicode = unicode
long = long
| l | identifier_name |
py3kcompat.py | # -*- coding: utf-8 -*-
#
# This file is part of the Shiboken Python Bindings Generator project.
#
# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
#
# Contact: PySide team <contact@pyside.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Le... |
unicode = unicode
long = long
| return long(n) | identifier_body |
rpc.py | 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implie... |
else:
return "{}({}) {}".format(func.name, params_t)
def load_contract_file():
return contract_from_file(CONTRACTFILE)
def generate_contract_file():
"""
Generate the IDL -> JSON Contract file
main interface into barrister parser
"""
if not os.path.exists(IDLFILE):
raise ... | return "{}({}) {}".format(func.name, params_t, render_params(func.returns)) | conditional_block |
rpc.py | 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implie... | (d):
"""add id to json rpc if not present"""
if 'id' not in d:
d['id'] = str(uuid.uuid4())
return d['id']
class StackHutRPC:
"""
Alt. implementation of Barrister.server modified for StackHut needs
Performs
* 'Type'-checking of requests and responces per interface def
* loading t... | add_get_id | identifier_name |
rpc.py | 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implie... |
def exc_to_json_error(e, req_id=None):
return err_response(req_id, e.code, e.msg, e.data)
from enum import Enum
class SHCmds(Enum):
startup = 1
shutdown = 2
preBatch = 3
postBatch = 4
def add_get_id(d):
"""add id to json rpc if not present"""
if 'id' not in d:
d['id'] = str(uuid... | data = dict(exit_code=exit_code, stderr=stderr)
super().__init__(-32001, 'Sub-command returned a non-zero exit', data) | identifier_body |
rpc.py | 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implie... |
class InternalError(RpcException):
def __init__(self, msg='', data=None):
super().__init__(ERR_INTERNAL, 'Internal Error - {}'.format(msg), data)
class ServiceError(RpcException):
def __init__(self, msg, data=None):
super().__init__(ERR_SERVICE, 'Service Error - {}'.format(msg), data)
class C... | def __init__(self, data=None):
super().__init__(ERR_METHOD_NOT_FOUND, 'Method Not Found', data) | random_line_split |
emberdataformat.py | # This file is part of the Universal Schema.
#
# The Universal Schema is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#... | return "'boolean'"
elif isinstance(field, Binary):
return "'string'"
elif isinstance(field, DateTime):
return "'date'"
| """ EmberDataFormat allows you to plug in Universal Schema into the Ember.Data libary: http://emberjs.com/guides/models/"""
def __init__(self):
self.template = Template(filename=data_file('/templates/emberdata.mako'))
def schema(self, model, **kwargs):
""" Generates a Python Class ... | identifier_body |
emberdataformat.py | # This file is part of the Universal Schema.
#
# The Universal Schema is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#... | return "'date'" | conditional_block | |
emberdataformat.py | # This file is part of the Universal Schema.
#
# The Universal Schema is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#... | return "'string'"
elif isinstance(field, DateTime):
return "'date'" | elif isinstance(field, Float):
return "'number'"
elif isinstance(field, Boolean):
return "'boolean'"
elif isinstance(field, Binary): | random_line_split |
emberdataformat.py | # This file is part of the Universal Schema.
#
# The Universal Schema is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#... | (self, field):
if isinstance(field, String):
return "'string'"
elif isinstance(field, Integer):
return "'number'"
elif isinstance(field, Float):
return "'number'"
elif isinstance(field, Boolean):
return "'boolean'"
elif isinstance(f... | emberdata_type | identifier_name |
inheritance1.js | //// [inheritance1.ts]
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {
select() { }
}
class TextBox extends Control {
select() { }
}
class ImageBase extends Control implements SelectableCo... |
Locations.prototype.select = function () {
};
return Locations;
})();
var Locations1 = (function () {
function Locations1() {
}
Locations1.prototype.select = function () {
};
return Locations1;
})();
var sc;
var c;
var b;
sc = b;
c = b;
b = sc;
b = c;
var t;
sc = t;
... | {
} | identifier_body |
inheritance1.js | //// [inheritance1.ts]
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {
select() { }
}
class TextBox extends Control {
select() { }
}
class ImageBase extends Control implements SelectableCo... | c = b;
b = sc;
b = c;
var t: TextBox;
sc = t;
c = t;
t = sc;
t = c;
var i: ImageBase;
sc = i;
c = i;
i = sc;
i = c;
var i1: Image1;
sc = i1;
c = i1;
i1 = sc;
i1 = c;
var l: Locations;
sc = l;
c = l;
l = sc;
l = c;
var l1: Locations1;
sc = l1;
c = l1;
l1 = sc;
l1 = c;
//// [inheritance1.js]
var __extends = this... | random_line_split | |
inheritance1.js | //// [inheritance1.ts]
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {
select() { }
}
class TextBox extends Control {
select() { }
}
class ImageBase extends Control implements SelectableCo... | () { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Control = (function () {
function Control() {
}
return Control;
})();
var Button = (function (_super) {
__extends(Button, _super);
function Button() {
_super.apply(this, arguments);
... | __ | identifier_name |
tlp.py | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import stix
from stix.data_marking import MarkingStructure
import stix.bindings.extensions.marking.tlp as tlp_binding
@stix.register_extension
class TLPMarkingStructure(MarkingStructure):
| def to_dict(self):
d = MarkingStructure.to_dict(self)
if self.color:
d['color'] = self.color
return d
@classmethod
def from_obj(cls, obj, return_obj=None):
if not obj:
return None
if not return_obj:
return_obj = cls()
Ma... | _binding = tlp_binding
_binding_class = tlp_binding.TLPMarkingStructureType
_namespace = 'http://data-marking.mitre.org/extensions/MarkingStructure#TLP-1'
_XSI_TYPE = "tlpMarking:TLPMarkingStructureType"
def __init__(self, color=None):
super(TLPMarkingStructure, self).__init__()
self.co... | identifier_body |
tlp.py | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import stix
from stix.data_marking import MarkingStructure
import stix.bindings.extensions.marking.tlp as tlp_binding
@stix.register_extension
class TLPMarkingStructure(MarkingStructure):
_binding = tlp_bindin... | self.color = color
def to_obj(self, return_obj=None, ns_info=None):
super(TLPMarkingStructure, self).to_obj(return_obj=return_obj, ns_info=ns_info)
if not return_obj:
return_obj = self._binding_class()
MarkingStructure.to_obj(self, return_obj=return_obj, ns_info=ns_inf... | _namespace = 'http://data-marking.mitre.org/extensions/MarkingStructure#TLP-1'
_XSI_TYPE = "tlpMarking:TLPMarkingStructureType"
def __init__(self, color=None):
super(TLPMarkingStructure, self).__init__() | random_line_split |
tlp.py | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import stix
from stix.data_marking import MarkingStructure
import stix.bindings.extensions.marking.tlp as tlp_binding
@stix.register_extension
class TLPMarkingStructure(MarkingStructure):
_binding = tlp_bindin... | (self):
d = MarkingStructure.to_dict(self)
if self.color:
d['color'] = self.color
return d
@classmethod
def from_obj(cls, obj, return_obj=None):
if not obj:
return None
if not return_obj:
return_obj = cls()
MarkingStructure.... | to_dict | identifier_name |
tlp.py | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import stix
from stix.data_marking import MarkingStructure
import stix.bindings.extensions.marking.tlp as tlp_binding
@stix.register_extension
class TLPMarkingStructure(MarkingStructure):
_binding = tlp_bindin... |
if not return_obj:
return_obj = cls()
MarkingStructure.from_obj(obj, return_obj=return_obj)
return_obj.color = obj.color
return return_obj
@classmethod
def from_dict(cls, d, return_obj=None):
if not d:
return None
if not return_obj:
... | return None | conditional_block |
nadeo.js | var gbxremote = require('gbxremote'),
async = require('async');
module.exports = require('./core').extend({
init: function() {
this._super();
this.options.port = 2350;
this.options.port_query = 5000;
this.gbxclient = false;
},
reset: function() {
this._super();
if(this.gbxclient) {
this.gbxclient.te... |
state.name = self.stripColors(results[3].Name);
state.password = (results[3].Password != 'No password');
state.maxplayers = results[3].CurrentMaxPlayers;
state.map = self.stripColors(results[4].Name);
state.raw.gametype = gamemode;
results[2].forEach(function(player) {
state.players.push({name:s... | random_line_split | |
config.py | #-*- coding: utf-8 -*-
import argparse
import numpy as np
parser = argparse.ArgumentParser(description='Configuration file')
arg_lists = []
def add_argument_group(name):
|
def str2bool(v):
return v.lower() in ('true', '1')
# Network
net_arg = add_argument_group('Network')
net_arg.add_argument('--hidden_dim', type=int, default=128, help='actor LSTM num_neurons')
net_arg.add_argument('--num_heads', type=int, default=16, help='actor input embedding') ###
net_arg.add_argument('--num_... | arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg | identifier_body |
config.py | #-*- coding: utf-8 -*-
import argparse
import numpy as np
parser = argparse.ArgumentParser(description='Configuration file')
arg_lists = []
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg
def | (v):
return v.lower() in ('true', '1')
# Network
net_arg = add_argument_group('Network')
net_arg.add_argument('--hidden_dim', type=int, default=128, help='actor LSTM num_neurons')
net_arg.add_argument('--num_heads', type=int, default=16, help='actor input embedding') ###
net_arg.add_argument('--num_stacks', type=i... | str2bool | identifier_name |
config.py | #-*- coding: utf-8 -*-
import argparse
import numpy as np
parser = argparse.ArgumentParser(description='Configuration file')
arg_lists = []
| def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg
def str2bool(v):
return v.lower() in ('true', '1')
# Network
net_arg = add_argument_group('Network')
net_arg.add_argument('--hidden_dim', type=int, default=128, help='actor LSTM num_neurons')
net_arg.add_arg... | random_line_split | |
config.py | #-*- coding: utf-8 -*-
import argparse
import numpy as np
parser = argparse.ArgumentParser(description='Configuration file')
arg_lists = []
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg
def str2bool(v):
return v.lower() in ('true', '1')
# Network
net... |
else:
print('Testing Config:')
print('* Summary writer log dir:',config.log_dir)
print('\n') | print('Training Config:')
print('* Nb epoch:',config.nb_epoch)
print('* Temperature:',config.temperature)
print('* Actor learning rate (init,decay_step,decay_rate):',config.lr1_start,config.lr1_decay_step,config.lr1_decay_rate) | conditional_block |
test.js | /**
* Module dependencies.
*/
var request = require('superagent');
var util = require('util');
var http = require('http');
var https = require('https');
var assert = require('assert');
var Request = request.Request;
/**
* Expose `Test`.
*/
module.exports = Test;
/**
* Initialize a new `Test` with the given `ap... | (app, method, path, host) {
Request.call(this, method.toUpperCase(), path);
this.redirects(0);
this.buffer();
this.app = app;
this._asserts = [];
this.url = typeof app === 'string'
? app + path
: this.serverAddress(app, path, host);
}
/**
* Inherits from `Request.prototype`.
*/
Object.setPrototy... | Test | identifier_name |
test.js | /**
* Module dependencies.
*/
var request = require('superagent');
var util = require('util');
var http = require('http');
var https = require('https');
var assert = require('assert');
var Request = request.Request;
/**
* Expose `Test`.
*/
module.exports = Test;
/**
* Initialize a new `Test` with the given `ap... | function localAssert() {
self.assert(err, res, fn);
}
});
return this;
};
/**
* Perform assertions and invoke `fn(err, res)`.
*
* @param {?Error} resError
* @param {Response} res
* @param {Function} fn
* @api private
*/
Test.prototype.assert = function(resError, res, fn) {
var error;
var... | random_line_split | |
test.js | /**
* Module dependencies.
*/
var request = require('superagent');
var util = require('util');
var http = require('http');
var https = require('https');
var assert = require('assert');
var Request = request.Request;
/**
* Expose `Test`.
*/
module.exports = Test;
/**
* Initialize a new `Test` with the given `ap... |
// set unexpected superagent error if no other error has occurred.
if (!error && resError instanceof Error && (!res || resError.status !== res.status)) {
error = resError;
}
fn.call(this, error || null, res);
};
/**
* Perform assertions on a response body and return an Error upon failure.
*
* @param ... | {
error = this._assertFunction(this._asserts[i], res);
} | conditional_block |
test.js | /**
* Module dependencies.
*/
var request = require('superagent');
var util = require('util');
var http = require('http');
var https = require('https');
var assert = require('assert');
var Request = request.Request;
/**
* Expose `Test`.
*/
module.exports = Test;
/**
* Initialize a new `Test` with the given `ap... |
});
return this;
};
/**
* Perform assertions and invoke `fn(err, res)`.
*
* @param {?Error} resError
* @param {Response} res
* @param {Function} fn
* @api private
*/
Test.prototype.assert = function(resError, res, fn) {
var error;
var i;
// check for unexpected network errors or server not running... | {
self.assert(err, res, fn);
} | identifier_body |
test_wait_for_digit.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 PolyBeacon, Inc.
#
# Author: Paul Belanger <paul.belanger@polybeacon.com>
#
# 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
#
#... | # limitations under the License.
import cStringIO
import mock
from sarlacc.tests.asterisk.agi import test
class TestCase(test.TestCase):
@mock.patch('sys.stdin', cStringIO.StringIO("200 result=-1"))
def test_wait_for_digit_failure(self):
with mock.patch(
'sys.stdout', new_callable=c... | # See the License for the specific language governing permissions and | random_line_split |
test_wait_for_digit.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 PolyBeacon, Inc.
#
# Author: Paul Belanger <paul.belanger@polybeacon.com>
#
# 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
#
#... | (self):
with mock.patch(
'sys.stdout', new_callable=cStringIO.StringIO) as mock_stdout:
res, dtmf = self.agi.wait_for_digit(timeout='25000')
self.assertEqual(mock_stdout.getvalue(), 'WAIT FOR DIGIT 25000\n')
self.assertTrue(res)
self.assertEqual(dt... | test_wait_for_digit_success | identifier_name |
test_wait_for_digit.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 PolyBeacon, Inc.
#
# Author: Paul Belanger <paul.belanger@polybeacon.com>
#
# 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
#
#... | with mock.patch(
'sys.stdout', new_callable=cStringIO.StringIO) as mock_stdout:
res, dtmf = self.agi.wait_for_digit(timeout='5000')
self.assertEqual(mock_stdout.getvalue(), 'WAIT FOR DIGIT 5000\n')
self.assertTrue(res)
self.assertEqual(dtmf, '') | identifier_body | |
specest_mtm.py | #!/usr/bin/env python
#
# Copyright 2010 Communications Engineering Lab, KIT
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This softwar... | """ Computes the eigenspectra for the multitaper spectrum estimator:
data --> multiplication dpss --> FFT --> mag-square --> output eigenspectrum """
def __init__(self, dpss, fftshift=False):
gr.hier_block2.__init__(self, "eigenspectrum",
gr.io_signature(1, 1, gr.sizeof_gr_complex*len(dp... | identifier_body | |
specest_mtm.py | #!/usr/bin/env python
#
# Copyright 2010 Communications Engineering Lab, KIT
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This softwar... |
elif weighting == 'eigenvalues':
self.eigvalmulti = []
self.lambdasum = 0
for i in xrange(K):
self.eigvalmulti.append(blocks.multiply_const_vff([dpss.lambdas[i]]*N))
self.lambdasum += dpss.lambdas[i]
self.divide = blocks.multiply_c... | self.sum = blocks.add_ff(N)
self.divide = blocks.multiply_const_vff([1./K]*N)
self.connect_mtm(K)
self.connect(self.sum, self.divide, self) | conditional_block |
specest_mtm.py | #!/usr/bin/env python
#
# Copyright 2010 Communications Engineering Lab, KIT
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This softwar... | raise ValueError, 'weighting-type should be: adaptive, unity or eigenvalues'
def connect_mtm(self, K):
""" Connects up all the eigenspectrum calculators. """
for i in xrange(K):
self.connect(self.s2v, self.mtm[i])
self.connect(self.mtm[i], (self.sum, i))
#... | self.connect(self.sum, self.divide, self)
else: | random_line_split |
specest_mtm.py | #!/usr/bin/env python
#
# Copyright 2010 Communications Engineering Lab, KIT
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This softwar... | (gr.hier_block2):
""" Estimates PSD using Thomson's multitaper method. """
def __init__(self, N=512 , NW=3 , K=5, weighting='adaptive', fftshift=False):
gr.hier_block2.__init__(self, "mtm",
gr.io_signature(1, 1, gr.sizeof_gr_complex),
gr.io_signature(1, 1, gr.sizeof_float... | mtm | identifier_name |
test_phonon.py | from cstool.parse_input import (read_input, check_settings, cstool_model)
from cstool.phonon import (phonon_cs_fn)
from cslib import (units)
import numpy as np
def test_phonon_cs_fn_single():
"""Tests that the phonon subroutine returns a function that
can handle arrays and returns correct units."""
settin... | ""Tests that the phonon subroutine returns a function that
can handle arrays and returns correct units."""
settings = read_input('data/materials/pmma.yaml')
if not check_settings(settings, cstool_model):
raise ValueError("Parsed settings do not conform the model.")
fn = phonon_cs_fn(settings)
... | identifier_body | |
test_phonon.py | from cstool.parse_input import (read_input, check_settings, cstool_model)
from cstool.phonon import (phonon_cs_fn)
from cslib import (units)
import numpy as np
| can handle arrays and returns correct units."""
settings = read_input('data/materials/pmma.yaml')
settings.phonon.model = 'single'
if not check_settings(settings, cstool_model):
raise ValueError("Parsed settings do not conform the model.")
fn = phonon_cs_fn(settings)
W = np.logspace(-2,... | def test_phonon_cs_fn_single():
"""Tests that the phonon subroutine returns a function that | random_line_split |
test_phonon.py | from cstool.parse_input import (read_input, check_settings, cstool_model)
from cstool.phonon import (phonon_cs_fn)
from cslib import (units)
import numpy as np
def test_phonon_cs_fn_single():
"""Tests that the phonon subroutine returns a function that
can handle arrays and returns correct units."""
settin... |
fn = phonon_cs_fn(settings)
W = np.logspace(-2, 3, 100) * units.eV
theta = np.linspace(0, np.pi, 100) * units.rad
cs = fn(theta, W[:, None])
assert cs.shape == (100, 100)
assert cs.dimensionality == units('m²/sr').dimensionality
def test_phonon_cs_fn_dual():
"""Tests that the phonon sub... | raise ValueError("Parsed settings do not conform the model.") | conditional_block |
test_phonon.py | from cstool.parse_input import (read_input, check_settings, cstool_model)
from cstool.phonon import (phonon_cs_fn)
from cslib import (units)
import numpy as np
def | ():
"""Tests that the phonon subroutine returns a function that
can handle arrays and returns correct units."""
settings = read_input('data/materials/pmma.yaml')
settings.phonon.model = 'single'
if not check_settings(settings, cstool_model):
raise ValueError("Parsed settings do not conform t... | test_phonon_cs_fn_single | identifier_name |
app.interface.ts | 'use strict';
/**
* Express imports
*/
import { Application } from "express-serve-static-core";
/**
* Third-party imports ( https://www.npmjs.com/~types )
*/
import * as debug from "debug";
/**
* SubApp interface designed for all *Express classes,
* actually describing a sub-app, from the Express point of view... | debug: debug.IDebugger;
init(): void;
configureEnv(): void;
configureLocals(): void;
configureMiddleware(): void;
configureRouting(): void;
configureErrorHandler(): void;
}
/**
* App interface designed for the only *Express class,
* actually describing the main app, from the Express poin... | app: Application; | random_line_split |
test_screenshot.py | # -*- coding: utf-8 -*-
from os import getcwd, listdir
from os.path import abspath, dirname, isdir, join as path_join
from shutil import rmtree
from sys import exc_info
from tempfile import mkdtemp
from unittest import TestCase
from mock import patch, MagicMock
from robot.libraries.BuiltIn import BuiltIn
CURDIR = abs... |
def test_take_a_screenshot(self):
self._take_screenshot_many_times('ImageHorizon-screenshot-%d.png')
def test_take_a_screenshot_inside_robot(self):
with patch.object(BuiltIn, 'get_variable_value',
return_value='Suite Name'):
self._take_screenshot_many_tim... | self.lib.take_a_screenshot()
self.mock.screenshot.assert_called_once_with(
path_join(folder, expected_filename % i))
self.mock.reset_mock() | conditional_block |
test_screenshot.py | # -*- coding: utf-8 -*-
from os import getcwd, listdir
from os.path import abspath, dirname, isdir, join as path_join
from shutil import rmtree
from sys import exc_info
from tempfile import mkdtemp
from unittest import TestCase
from mock import patch, MagicMock
from robot.libraries.BuiltIn import BuiltIn
CURDIR = abs... | (self):
self.mock.reset_mock()
self.patcher.stop()
def _take_screenshot_many_times(self, expected_filename):
folder = path_join(CURDIR, 'reference_folder')
self.lib.set_screenshot_folder(folder)
for i in range(1, 15):
self.lib.take_a_screenshot()
self... | tearDown | identifier_name |
test_screenshot.py | # -*- coding: utf-8 -*-
from os import getcwd, listdir
from os.path import abspath, dirname, isdir, join as path_join
from shutil import rmtree
from sys import exc_info
from tempfile import mkdtemp
from unittest import TestCase
from mock import patch, MagicMock
from robot.libraries.BuiltIn import BuiltIn
CURDIR = abs... | from ImageHorizonLibrary import ScreenshotFolderException
for index, invalid_folder in enumerate((None, 0, False), 1):
self.lib.screenshot_folder = invalid_folder
expected = path_join(getcwd(),
'ImageHorizon-screenshot-%d.png' % index)
self.l... | identifier_body | |
test_screenshot.py | # -*- coding: utf-8 -*-
from os import getcwd, listdir
from os.path import abspath, dirname, isdir, join as path_join
from shutil import rmtree
from sys import exc_info
from tempfile import mkdtemp
from unittest import TestCase
from mock import patch, MagicMock
from robot.libraries.BuiltIn import BuiltIn
CURDIR = abs... | self.mock.reset_mock()
for invalid_folder in (123, object()):
self.lib.screenshot_folder = invalid_folder
with self.assertRaises(ScreenshotFolderException):
self.lib.take_a_screenshot() | random_line_split | |
templates.py | # Copyright (C) 2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your opt... | self.mlist = mlist
self.template = template
self.language = language
self.content_type = content_type
@resource.GET()
def find_template(self, request):
# XXX We currently only support .txt and .html files.
extension = EXTENSIONS.get(self.content_type)
if ... | random_line_split | |
templates.py | # Copyright (C) 2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your opt... | fp.close() | conditional_block | |
templates.py | # Copyright (C) 2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your opt... | extension = EXTENSIONS.get(self.content_type)
if extension is None:
return http.not_found()
template = self.template + extension
fp = None
try:
try:
path, fp = find(template, self.mlist, self.language)
except TemplateNotFoundError:
... | identifier_body | |
templates.py | # Copyright (C) 2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your opt... | (self, mlist, template, language, content_type):
self.mlist = mlist
self.template = template
self.language = language
self.content_type = content_type
@resource.GET()
def find_template(self, request):
# XXX We currently only support .txt and .html files.
extensio... | __init__ | identifier_name |
database.rs | Safe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" ... |
}
pub fn get_available_space(&self) -> u64 {
self.space_available.clone()
}
pub fn get_data_stored(&self) -> u64 {
self.data_stored.clone()
}
}
pub struct MaidManagerDatabase {
storage: collections::HashMap<Identity, MaidManagerAccount>,
}
impl MaidManagerDatabase {
pub fn ... | {
self.data_stored -= size;
self.space_available += size;
} | conditional_block |
database.rs | Safe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" ... | () -> MaidManagerDatabase {
MaidManagerDatabase { storage: collections::HashMap::with_capacity(10000), }
}
pub fn exist(&mut self, name : &Identity) -> bool {
self.storage.contains_key(name)
}
pub fn put_data(&mut self, name: &Identity, size: u64) -> bool {
let entry = self.storage.entry(na... | new | identifier_name |
database.rs | Safe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" ... |
fn serialised_contents(&self) -> Vec<u8> {
let mut e = cbor::Encoder::from_memory();
e.encode(&[&self]).unwrap();
e.into_bytes()
}
fn refresh(&self)->bool {
true
}
fn merge(&self, responses: Vec<Box<Sendable>>) -> Option<Box<Sendable>> {
let mut tmp_wrappe... | {
MAID_MANAGER_ACCOUNT_TAG
} | identifier_body |
database.rs | Safe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" ... | let name = routing::test_utils::Random::generate_random();
db.delete_data(&name, 0);
assert_eq!(db.exist(&name), false);
assert_eq!(db.put_data(&name, 0), true);
assert_eq!(db.exist(&name), true);
db.delete_data(&name, 1);
assert_eq!(db.exist(&name), true);
... | }
#[test]
fn delete_data() {
let mut db = MaidManagerDatabase::new(); | random_line_split |
Image.py | # -*- coding: UTF-8 -*-
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of Wammu <https://wammu.eu/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ve... | bitmaps.append(bitmap)
wx.lib.throbber.Throbber.__init__(self, parent, -1, bitmaps, frameDelay=delay)
self.SetToolTipString(tooltip)
| = wx.ImageFromBitmap(bitmap)
bitmap = wx.BitmapFromImage(img.Scale(bitmap.GetWidth() * scale, bitmap.GetHeight() * scale))
| conditional_block |
Image.py | # -*- coding: UTF-8 -*-
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of Wammu <https://wammu.eu/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ve... |
class EncodedBitmap(wx.StaticBitmap):
def __init__(self, parent, tooltip='Image', image=None, size=None, scale=1):
if image is None:
image = defaultbmp
image = wx.ImageFromStream(MemoryInputStream(base64.b64decode(image)))
if scale > 1:
bitmap = wx.BitmapFromImage(im... | class MemoryInputStream(wx.InputStream):
def __init__(self, data):
wx.InputStream.__init__(self, io.StringIO(data)) | random_line_split |
Image.py | # -*- coding: UTF-8 -*-
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of Wammu <https://wammu.eu/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ve... | .InputStream):
def __init__(self, data):
wx.InputStream.__init__(self, io.StringIO(data))
class EncodedBitmap(wx.StaticBitmap):
def __init__(self, parent, tooltip='Image', image=None, size=None, scale=1):
if image is None:
image = defaultbmp
image = wx.ImageFromStream(Memory... | oryInputStream(wx | identifier_name |
Image.py | # -*- coding: UTF-8 -*-
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of Wammu <https://wammu.eu/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ve... | lass Bitmap(wx.StaticBitmap):
def __init__(self, parent, tooltip='Image', image=None, size=None, scale=1):
if image is None:
image = defaultbmp
bitmap = wx.BitmapFromXPMData(image)
if scale > 1:
img = wx.ImageFromBitmap(bitmap)
bitmap = wx.BitmapFromImage(... | __init__(self, parent, tooltip='Image', image=None, size=None, scale=1):
if image is None:
image = defaultbmp
image = wx.ImageFromStream(MemoryInputStream(base64.b64decode(image)))
if scale > 1:
bitmap = wx.BitmapFromImage(image.Scale(image.GetWidth() * scale, image.GetH... | identifier_body |
rule.py | import cPickle
def dump_rules(filename, rules):
with open(filename, 'w') as f:
cPickle.dump(rules, f, cPickle.HIGHEST_PROTOCOL)
def load_rules(filename):
with open(filename, 'r') as f:
rules = cPickle.load(f)
return rules
class Rule():
APPLY_ACTION = 0
CLEAR_ACTION = 1
WRITE_A... | def get_prefix(self):
return self.prefix
def get_header_space(self):
return self.header_space
def get_all_pair_path_index(self):
return self.all_pair_path_index;
def __str__(self):
string = 'Rule ID: ' + str(self.id) + ', ' + "Switch ID: " + str(self.switch_id) + ', ' ... |
def set_prefix(self, prefix):
self.prefix = prefix
self.header_space, self.ip, self.match_length = self.to_header_space(prefix)
| random_line_split |
rule.py | import cPickle
def dump_rules(filename, rules):
with open(filename, 'w') as f:
cPickle.dump(rules, f, cPickle.HIGHEST_PROTOCOL)
def load_rules(filename):
with open(filename, 'r') as f:
rules = cPickle.load(f)
return rules
class Rule():
APPLY_ACTION = 0
CLEAR_ACTION = 1
WRITE_A... | pass | conditional_block | |
rule.py | import cPickle
def dump_rules(filename, rules):
with open(filename, 'w') as f:
cPickle.dump(rules, f, cPickle.HIGHEST_PROTOCOL)
def load_rules(filename):
with open(filename, 'r') as f:
rules = cPickle.load(f)
return rules
class Rule():
APPLY_ACTION = 0
CLEAR_ACTION = 1
WRITE_A... |
def get_prefix(self):
return self.prefix
def get_header_space(self):
return self.header_space
def get_all_pair_path_index(self):
return self.all_pair_path_index;
def __str__(self):
string = 'Rule ID: ' + str(self.id) + ', ' + "Switch ID: " + str(self.switch_id) + ', ... | self.prefix = prefix
self.header_space, self.ip, self.match_length = self.to_header_space(prefix) | identifier_body |
rule.py | import cPickle
def dump_rules(filename, rules):
with open(filename, 'w') as f:
cPickle.dump(rules, f, cPickle.HIGHEST_PROTOCOL)
def load_rules(filename):
with open(filename, 'r') as f:
rules = cPickle.load(f)
return rules
class Rule():
APPLY_ACTION = 0
CLEAR_ACTION = 1
WRITE_A... | (self, last_rule):
return self.header_space[:self.header_space.index('x')] == last_rule.get_header_sapce()[:self.header_space.index('x')]
def serialize(self):
return cPickle.dumps(self)
def get_id(self):
return self.id
def get_switch_id(self):
return self.switch_id
de... | is_match | identifier_name |
app.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | (self):
"""
Calls the actions that was specified via command line arguments.
This involves loading the relevant module file.
"""
module_name = "%s.%s" % ('avocado.core.restclient.cli.actions',
self.args.top_level_action)
try:
... | dispatch_action | identifier_name |
app.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | module = importlib.import_module(module_name)
except ImportError:
return
# Filter out the attributes out of the loaded module that look
# like command line actions, based on type and 'is_action' attribute
module_actions = {}
for attribute_name in module._... | self.args.top_level_action)
try: | random_line_split |
app.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | """
Main entry point for application
"""
action_result = None
try:
self.args = self.parser.parse_args()
action_result = self.dispatch_action()
except KeyboardInterrupt:
print 'Interrupted'
if isinstance(action_result, int):
... | identifier_body | |
app.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... |
kallable = module_actions.get(chosen_action, None)
if kallable is not None:
self.initialize_connection()
return kallable(self)
else:
self.view.notify(event="error",
msg="Action specified is not implemented")
def run(self):
... | chosen_action = action
break | conditional_block |
gumshoe.js | = {
// Active classes
navClass: 'active',
contentClass: 'active',
// Nested navigation
nested: false,
nestedClass: 'active',
// Offset & reflow
offset: 0,
reflow: false,
// Event support
events: true
};
//
// Methods
//
/** | * @param {Object} objects The objects to merge together
* @returns {Object} Merged values of defaults and options
*/
var extend = function () {
var merged = {};
Array.prototype.forEach.call(arguments, (function (obj) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) return;
me... | * Merge two or more objects together. | random_line_split |
LocLogs.ts | import * as levelup from "levelup";
import * as leveldown from "leveldown";
// probably not a great way to store this stuff...
export class LocLogs {
_db: any;
_cachedGet: any;
constructor(storePath: string) {
this._db = levelup(leveldown(storePath));
}
getLogs(locId) {
return new Promise(resolve ... | (locId, logIndices) {
return new Promise(resolve => {
this._db.get(locId, (err, value) => {
if (value) {
value = JSON.parse(value);
} else {
value = [];
}
value.push.apply(value, logIndices);
this._db.put(locId, JSON.stringify(value), () => {
... | addLogs | identifier_name |
LocLogs.ts | import * as levelup from "levelup";
import * as leveldown from "leveldown";
// probably not a great way to store this stuff...
export class LocLogs {
_db: any;
_cachedGet: any;
constructor(storePath: string) {
this._db = levelup(leveldown(storePath));
}
getLogs(locId) |
addLog(locId, logIndex) {
return new Promise(resolve => {
this._db.get(locId, (err, value) => {
if (value) {
value = JSON.parse(value);
} else {
value = [];
}
try {
value.push(logIndex);
} catch (err) {
console.log(err, { valu... | {
return new Promise(resolve => {
this._db.get(locId, (err, value) => {
if (value) {
value = JSON.parse(value);
} else {
value = [];
}
resolve(value);
});
});
} | identifier_body |
LocLogs.ts | import * as levelup from "levelup";
import * as leveldown from "leveldown";
// probably not a great way to store this stuff...
export class LocLogs {
_db: any;
_cachedGet: any;
constructor(storePath: string) {
this._db = levelup(leveldown(storePath));
}
getLogs(locId) {
return new Promise(resolve ... | } | });
} | random_line_split |
LocLogs.ts | import * as levelup from "levelup";
import * as leveldown from "leveldown";
// probably not a great way to store this stuff...
export class LocLogs {
_db: any;
_cachedGet: any;
constructor(storePath: string) {
this._db = levelup(leveldown(storePath));
}
getLogs(locId) {
return new Promise(resolve ... | else {
value = [];
}
resolve(value);
});
});
}
addLog(locId, logIndex) {
return new Promise(resolve => {
this._db.get(locId, (err, value) => {
if (value) {
value = JSON.parse(value);
} else {
value = [];
}
try {
... | {
value = JSON.parse(value);
} | conditional_block |
main.rs | to the server
/// 2. Running tests through the server
///
/// The server supports running tests concurrently and also supports tests
/// themselves having support libraries. All data over the TCP sockets is in a
/// basically custom format suiting our needs.
use std::cmp;
use std::env;
use std::fs::{self, File, Permi... | <'a> {
inner: &'a Path,
}
impl<'a> Drop for RemoveOnDrop<'a> {
fn drop(&mut self) {
t!(fs::remove_dir_all(self.inner));
}
}
fn handle_run(socket: TcpStream, work: &Path, lock: &Mutex<()>) {
let mut arg = Vec::new();
let mut reader = BufReader::new(socket);
// Allocate ourselves a dire... | RemoveOnDrop | identifier_name |
main.rs | 15:12345"
};
let (listener, work) = if cfg!(target_os = "android") {
(t!(TcpListener::bind(bind_addr)), "/data/tmp/work")
} else {
(t!(TcpListener::bind(bind_addr)), "/tmp/work")
};
println!("listening!");
let work = Path::new(work);
t!(fs::create_dir_all(work));
let l... | {
let mut len = [0; 4];
t!(r.read_exact(&mut len));
((len[0] as u32) << 24) |
((len[1] as u32) << 16) |
((len[2] as u32) << 8) |
((len[3] as u32) << 0)
} | identifier_body | |
main.rs | to the server
/// 2. Running tests through the server
///
/// The server supports running tests concurrently and also supports tests
/// themselves having support libraries. All data over the TCP sockets is in a
/// basically custom format suiting our needs.
use std::cmp;
use std::env;
use std::fs::{self, File, Permi... | else if &buf[..] == b"run " {
let lock = lock.clone();
thread::spawn(move || handle_run(socket, work, &lock));
} else {
panic!("unknown command {:?}", buf);
}
}
}
fn handle_push(socket: TcpStream, work: &Path) {
let mut reader = BufReader::new(socket);
r... | {
handle_push(socket, work);
} | conditional_block |
main.rs | libraries to the server
/// 2. Running tests through the server
///
/// The server supports running tests concurrently and also supports tests
/// themselves having support libraries. All data over the TCP sockets is in a
/// basically custom format suiting our needs.
use std::cmp;
use std::env;
use std::fs::{self, F... | let mut env = Vec::new();
arg.truncate(0);
while t!(reader.read_until(0, &mut arg)) > 1 {
let key_len = arg.len() - 1;
let val_len = t!(reader.read_until(0, &mut arg)) - 1;
{
let key = &arg[..key_len];
let val = &arg[key_len + 1..][..val_len];
let ... | arg.truncate(0);
}
// Next we'll get a bunch of env vars in pairs delimited by 0s as well | random_line_split |
ws_util.py | not found see regex above
class BadWorkspaceID(Exception):
pass
class PermissionsError(WorkspaceClient.ServerError):
"""Raised if user does not have permission to
access the workspace.
"""
@staticmethod
def is_permissions_error(err):
"""Try to guess if the error string is a permission-... | try:
ws_meta = wsclient.save_objects({ 'id' : ws_id,
'objects' : [obj] })
except:
raise
return dict(zip(list_objects_fields,ws_meta[0]))
# Tag a workspace as a project, if there is an error, let it propagate up
def check_project_tag(wsclient, ws_id)... | return dict(zip(list_objects_fields, obj_info))
def put_wsobj(wsclient, ws_id, obj): | random_line_split |
ws_util.py | not found see regex above
class BadWorkspaceID(Exception):
|
class PermissionsError(WorkspaceClient.ServerError):
"""Raised if user does not have permission to
access the workspace.
"""
@staticmethod
def is_permissions_error(err):
"""Try to guess if the error string is a permission-denied error
for the narrative (i.e. the workspace the narra... | pass | identifier_body |
ws_util.py | not found see regex above
class BadWorkspaceID(Exception):
pass
class PermissionsError(WorkspaceClient.ServerError):
"""Raised if user does not have permission to
access the workspace.
"""
@staticmethod
def is_permissions_error(err):
"""Try to guess if the error string is a permission-... |
wsclient.alter_workspace_metadata({'wsi':{'id':ws_id}, 'new':new_metadata})
def get_wsobj(wsclient, ws_id, objtype=None):
"""
This is just a wrapper for the workspace get_objects call.
Takes an initialized workspace client and a workspace ID
of the form "ws.{ws_id}.obj.{object id}" and returns ... | raise BadWorkspaceID("No workspace id or object reference given!") | conditional_block |
ws_util.py | not found see regex above
class BadWorkspaceID(Exception):
pass
class PermissionsError(WorkspaceClient.ServerError):
"""Raised if user does not have permission to
access the workspace.
"""
@staticmethod
def is_permissions_error(err):
"""Try to guess if the error string is a permission-... | (wsclient, ref, new_metadata={}, ws_id=None):
"""
This is just a wrapper for the workspace get_objects call.
Takes an initialized workspace client and a workspace ID
of the form "ws.{ws_id}.obj.{object id}" and returns the following:
{
'data' : {actual data contained in the object},
'me... | alter_workspace_metadata | identifier_name |
network.py | import numpy as np
from vanilla_neural_nets.neural_network.training_batch_generator import MiniBatchGenerator
from vanilla_neural_nets.neural_network.optimization_algorithm import GradientDescent
from vanilla_neural_nets.neural_network.loss_function import MeanSquaredError
from vanilla_neural_nets.neural_network.activ... | (self, x):
activation_matrix = x
for layer in self.parameters.layers:
activation_function_class = self.output_layer_activation_function_class if layer.is_output_layer\
else self.activation_function_class
linear_combination = np.dot(activation_matrix, layer.weight... | predict | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.