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 |
|---|---|---|---|---|
buffer_tests.rs | //! Tests for `IBuffer`.
use buffer::IBuffer;
use std::io::Read;
#[test]
fn read_from_string() {
let mut in_buf = IBuffer::from_str("Hello world");
let mut buf = [0u8; 6];
let res = in_buf.read(&mut buf);
assert_eq!(6, res.expect("read must be ok"));
assert_eq!([b'H', b'e', b'l', b'l', b'o', b' ... | }
#[test]
fn read_from_string_eof() {
let mut in_buf = IBuffer::from_str("Hello world");
let mut buf = [0u8; 6];
let _ = in_buf.read(&mut buf);
let _ = in_buf.read(&mut buf);
let res = in_buf.read(&mut buf);
assert_eq!(0, res.expect("read must be ok"));
} | assert_eq!(5, res.expect("read must be ok"));
assert_eq!([b'w', b'o', b'r', b'l', b'd'], buf[0..5]); | random_line_split |
buffer_tests.rs | //! Tests for `IBuffer`.
use buffer::IBuffer;
use std::io::Read;
#[test]
fn read_from_string() |
#[test]
fn read_from_string_overflow() {
let mut in_buf = IBuffer::from_str("Hello world");
let mut buf = [0u8; 6];
let _ = in_buf.read(&mut buf);
let res = in_buf.read(&mut buf);
assert_eq!(5, res.expect("read must be ok"));
assert_eq!([b'w', b'o', b'r', b'l', b'd'], buf[0..5]);
}
#[test]
... | {
let mut in_buf = IBuffer::from_str("Hello world");
let mut buf = [0u8; 6];
let res = in_buf.read(&mut buf);
assert_eq!(6, res.expect("read must be ok"));
assert_eq!([b'H', b'e', b'l', b'l', b'o', b' '], buf);
} | identifier_body |
topics.test.js | const test = require('tape')
const nlp = require('./_lib')
test('topics:', function(t) {
let list = [
['Tony Hawk lives in Toronto. Tony Hawk is cool.', 'tony hawk'],
['I live Toronto. I think Toronto is cool.', 'toronto'],
['The EACD united in 1972. EACD must follow regulations.', 'eacd'],
// ['The ... | t.deepEqual(arr, ['Gloop University', 'Paris, France,', 'John H. Smith'], 'found all three topics')
t.end()
})
test('misc entities', function(t) {
let doc = nlp('The Children are right to laugh at you, Ralph')
let m = doc.people()
t.equal(m.length, 1, 'one person')
m = doc.places()
t.equal(m.length, 0, ... | random_line_split | |
api-call-wikipedia.js | define([
"knockout",
// mappoint needs to be here first for addEventListener
"../modules/mappoint",
], function (ko) {
// create result object
var result = {
cityname : ko.observable(''),
citydata : ko.observableArray([])
};
// subscribe to custom event
window.addEventListener("getTitle", getWikipedia, fa... | script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
// simple error handling (works in firefox and chrome)
window.onerror = function (errorMsg, url, lineNumber) {
alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber);
};
document.body.app... | var script = document.createElement('script'); | random_line_split |
api-call-wikipedia.js | define([
"knockout",
// mappoint needs to be here first for addEventListener
"../modules/mappoint",
], function (ko) {
// create result object
var result = {
cityname : ko.observable(''),
citydata : ko.observableArray([])
};
// subscribe to custom event
window.addEventListener("getTitle", getWikipedia, fa... |
});
};
return result;
}); | {
// store city object with data array
localStorage[data[0]] = JSON.stringify(data[1]);
} | conditional_block |
api-call-wikipedia.js | define([
"knockout",
// mappoint needs to be here first for addEventListener
"../modules/mappoint",
], function (ko) {
// create result object
var result = {
cityname : ko.observable(''),
citydata : ko.observableArray([])
};
// subscribe to custom event
window.addEventListener("getTitle", getWikipedia, fa... |
// get localstorage item and store it
data = JSON.parse(localStorage[city]);
// populate observables
result.citydata([data]);
result.cityname(city);
}
else {
// if no localstorage, sent request
sentJSONPRequest(city);
}
// set city to old value
oldValue = city;
}
}
... | {
// listen to custom event
city = e.detail.title;
// store data object
var data = '';
// if city equals old value do nothing
if (city === oldValue) {
// do something when element is clicked twice
console.log("you have allready clicked this " + city + " marker");
}
// if city contains new ... | identifier_body |
api-call-wikipedia.js | define([
"knockout",
// mappoint needs to be here first for addEventListener
"../modules/mappoint",
], function (ko) {
// create result object
var result = {
cityname : ko.observable(''),
citydata : ko.observableArray([])
};
// subscribe to custom event
window.addEventListener("getTitle", getWikipedia, fa... | (e) {
// listen to custom event
city = e.detail.title;
// store data object
var data = '';
// if city equals old value do nothing
if (city === oldValue) {
// do something when element is clicked twice
console.log("you have allready clicked this " + city + " marker");
}
// if city contains... | getWikipedia | identifier_name |
admin-controllers.js |
var basePath = '/api';
var app = angular.module('adminApp');
app.controller('AccountController', [
'$routeParams', '$location', 'AuthService', 'ReferenceResource', 'AccountResource', 'RelationResource'
, function($routeParams, $location, AuthService, ReferenceResource, AccountResource, RelationResource)
{
... |
}
}]);
| {
json[i]
} | conditional_block |
admin-controllers.js |
var basePath = '/api';
var app = angular.module('adminApp');
app.controller('AccountController', [
'$routeParams', '$location', 'AuthService', 'ReferenceResource', 'AccountResource', 'RelationResource'
, function($routeParams, $location, AuthService, ReferenceResource, AccountResource, RelationResource)
{
... | ;
/**
* Normalizes the resut (list of relations) such that includes
* properties:
* thisRole : the role of the account in session
* counterpartAccount : the other account
* counterpartRole : the role of the other account
*/
function normalizeResult(thisUuid, result)
{
... | {
var qparms = $location.search();
var queryArgs = {
accountId: self.session.uuid,
_meta: 'true',
_page: qparms._page,
_limit: qparms._limit,
_q: ''
};
// Fetch from remote
RelationResource.query2(queryArgs, function(da... | identifier_body |
admin-controllers.js |
var basePath = '/api';
var app = angular.module('adminApp');
app.controller('AccountController', [
'$routeParams', '$location', 'AuthService', 'ReferenceResource', 'AccountResource', 'RelationResource'
, function($routeParams, $location, AuthService, ReferenceResource, AccountResource, RelationResource)
{
... | (thisUuid, result)
{
for(i=0; i < result.length; i++) {
if (thisUuid == result[i].account1Uuid) {
result[i].thisRole = result[i].role1;
result[i].counterpartAccount = result[i].account2;
result[i].counterpartRole = result[i].role2;
} el... | normalizeResult | identifier_name |
admin-controllers.js | var basePath = '/api';
var app = angular.module('adminApp');
app.controller('AccountController', [
'$routeParams', '$location', 'AuthService', 'ReferenceResource', 'AccountResource', 'RelationResource'
, function($routeParams, $location, AuthService, ReferenceResource, AccountResource, RelationResource)
{
... | .then(function(account) {
self.session = account;
retrieveRelations();
})
.catch(function(error) {
});
/**
* Retrieve relations
*/
function retrieveRelations(criteria) {
var qparms = $location.search();
var queryArgs = {
accountId: self.session... | AuthService.fetchMyAccount() | random_line_split |
no.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use base::prelude::*;
use base::{error};
use {MemPool};
/// Heap without memory backing it
///
/// = Remarks
///
///... |
unsafe fn free(&mut self, _: *mut d8, _: usize, _: usize) { }
unsafe fn realloc(&mut self, _: *mut d8, _: usize, _: usize,
_: usize) -> Result<*mut d8> {
Err(error::NoMemory)
}
}
| {
Err(error::NoMemory)
} | identifier_body |
no.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use base::prelude::*;
use base::{error};
use {MemPool};
/// Heap without memory backing it
///
/// = Remarks
///
///... | (&mut self, _: usize, _: usize) -> Result<*mut d8> {
Err(error::NoMemory)
}
unsafe fn free(&mut self, _: *mut d8, _: usize, _: usize) { }
unsafe fn realloc(&mut self, _: *mut d8, _: usize, _: usize,
_: usize) -> Result<*mut d8> {
Err(error::NoMemory)
}
}
| alloc | identifier_name |
no.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use base::prelude::*;
use base::{error};
use {MemPool};
/// Heap without memory backing it
/// | /// memory is available.
pub struct Dummy<'a>(PhantomData<&'a ()>);
impl<'a> OutOf for Dummy<'a> {
fn out_of(_: ()) -> Dummy<'a> {
Dummy(PhantomData)
}
}
impl<'a> MemPool for Dummy<'a> {
unsafe fn alloc(&mut self, _: usize, _: usize) -> Result<*mut d8> {
Err(error::NoMemory)
}
unsa... | /// = Remarks
///
/// This allocator does not inspect the arguments passed to it and always returns that no | random_line_split |
Physics 2.0.py | from functools import reduce
from operator import add
from pygame.math import Vector2 as V2
import pygame as pg, os
from src.display.tkinter_windows import create_menu
from src.core import constants
def init_display():
pg.init()
info = pg.display.Info()
dims = (int(info.current_w * 0.6), int(info.current_... | main() | conditional_block | |
Physics 2.0.py | from functools import reduce
from operator import add
from pygame.math import Vector2 as V2
import pygame as pg, os
from src.display.tkinter_windows import create_menu
from src.core import constants
def init_display():
pg.init()
info = pg.display.Info()
dims = (int(info.current_w * 0.6), int(info.current_... | (*args):
G, COR, time_factor, collision, walls, g_field, gravity, scroll, bodies, camera, dims, frame_count, settings_window = args
for body in bodies: # Reset previous calculations
body.acceleration = V2(0, 0)
for b, body in enumerate(bodies): # Calculate forces and set acceleration, if mutual gr... | handle_bodies | identifier_name |
Physics 2.0.py | from functools import reduce
from operator import add
from pygame.math import Vector2 as V2
import pygame as pg, os
from src.display.tkinter_windows import create_menu
from src.core import constants
def init_display():
pg.init()
info = pg.display.Info()
dims = (int(info.current_w * 0.6), int(info.current_... | return arr
def handle_mouse(*args):
settings_window, camera, event, bodies, dims, G, COR, scroll = args
if event.button == 1:
pos = camera.position + (pg.mouse.get_pos() - dims / 2) / camera.scale + dims / 2
for b in bodies:
if b.click_collision(pos) and b not in [win.body for w... | if window.alive: window.update()
else: settings_window.properties_windows.remove(window) | random_line_split |
Physics 2.0.py | from functools import reduce
from operator import add
from pygame.math import Vector2 as V2
import pygame as pg, os
from src.display.tkinter_windows import create_menu
from src.core import constants
def init_display():
pg.init()
info = pg.display.Info()
dims = (int(info.current_w * 0.6), int(info.current_... |
def key_up(self, key):
if key in self.map:
self.velocity = self.velocity.elementwise() * ((0,1) if key in self.map[:2] else (1,0))
def move_to_com(self, bodies):
total_mass = sum(b.mass for b in bodies)
self.position = reduce(add, (b.position * b.mass for b in bodies)) / t... | if key in self.map:
self.velocity = V2((3/self.scale,0) if key in self.map[:2] else (0,3/self.scale)).elementwise() * ((self.map.index(key) not in (1,2)) * 2 - 1) | identifier_body |
config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
... | (Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
| ProductionConfig | identifier_name |
config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
... |
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
| TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data-test.sqlite') | identifier_body |
config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
... | 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
} |
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ | random_line_split |
mjpegger.py | #===========================================================================
# mjpegger.py
#
# Runs a MJPG stream on provided port.
#
# 2016-07-25
# Carter Nelson
#===========================================================================
import threading
import SimpleHTTPServer
import SocketServer
import io
keepStre... |
self.wfile.write("--picameramjpg")
self.send_header('Content-type','image/jpeg')
self.send_header('Content-length',len(stream.getvalue()))
self.end_headers()
self.wfile.write(stream.getvalue())
stream.seek(0)
stream.truncate() | break | conditional_block |
mjpegger.py | #===========================================================================
# mjpegger.py
#
# Runs a MJPG stream on provided port.
#
# 2016-07-25
# Carter Nelson
#===========================================================================
import threading
import SimpleHTTPServer
import SocketServer
import io
keepStre... |
def stop(self, ):
global keepStreaming
keepStreaming = False
self.keepRunning = False
class MJPEGStreamHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""Handler for MJPEG stream."""
def do_GET(self, ):
print "MJPEGStreamHandler GET"
gl... | print "MJPEGThread starting"
self.server = SocketServer.TCPServer(("",self.port), MJPEGStreamHandler,
bind_and_activate=False)
self.server.allow_reuse_address = True
self.server.timeout = 0.1
self.server.server_bind()
self.server.server_activate()
self.keepRun... | identifier_body |
mjpegger.py | #===========================================================================
# mjpegger.py
#
# Runs a MJPG stream on provided port.
#
# 2016-07-25
# Carter Nelson
#===========================================================================
import threading
import SimpleHTTPServer
import SocketServer
import io
keepStre... | (SimpleHTTPServer.SimpleHTTPRequestHandler):
"""Handler for MJPEG stream."""
def do_GET(self, ):
print "MJPEGStreamHandler GET"
global keepStreaming
keepStreaming = True
stream = io.BytesIO()
self.send_response(200)
self.send_header('Content... | MJPEGStreamHandler | identifier_name |
mjpegger.py | #===========================================================================
# mjpegger.py
#
# Runs a MJPG stream on provided port.
#
# 2016-07-25
# Carter Nelson
#===========================================================================
import threading
import SimpleHTTPServer
import SocketServer
import io
keepStre... | camera = kwargs['camera']
resize = kwargs['resize']
self.port = kwargs['port']
self.keepRunnning = False
self.streamRunning = False
self.server = None
def run(self, ):
print "MJPEGThread starting"
self.server = SocketServer.TCPServer(("",self.port... |
global camera, resize | random_line_split |
appListModel.js | /*
* Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller
*
* 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... | () {
return {
'apps': [],
'detail': {}
};
}
return {
// State
state: init(),
handlers: {
'appDetail': 'detail',
'appList': 'list'
},
detail: function (r) {
// Sort in descending by deploy id
... | init | identifier_name |
appListModel.js | /*
* Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller
*
* 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... |
return {
// State
state: init(),
handlers: {
'appDetail': 'detail',
'appList': 'list'
},
detail: function (r) {
// Sort in descending by deploy id
this.state.detail[r.id.toString()] = _.sortByOrder(r.data, ['Id'], [false])... | {
return {
'apps': [],
'detail': {}
};
} | identifier_body |
appListModel.js | /*
* Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller
*
* 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... |
var ret = this.state.detail[id.toString()];
return ret ? ret : {};
}
}
};
}
module.exports = appListModel;
| {
return this.state.detail;
} | conditional_block |
appListModel.js | /*
* Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller
*
* 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... | }
module.exports = appListModel; | };
| random_line_split |
whisper.py | (self,bytes):
self.readCount += 1
debug('READ %d bytes #%d' % (bytes,self.readCount))
return file.read(self,bytes)
def debug(message):
print 'DEBUG :: %s' % message
__timingBlocks = {}
def startBlock(name):
__timingBlocks[name] = time.time()
def endBlock(name):
debug("%s took %... | read | identifier_name | |
whisper.py | 0) #Based on assumption that first field is lastUpdate
now = int( time.time() )
packedTime = struct.pack(timestampFormat,now)
fh.write(packedTime)
fh.seek(originalOffset)
endBlock('__changeLastUpdate()')
def create(path,archiveList,xFilesFactor=0.5):
"""create(path,archiveList,xFilesFactor=0.5)
path is a... | else: #We do wrap the archive
higherEnd = higher['offset'] + higher['size']
seriesString = fh.read(higherEnd - higherFirstOffset)
fh.seek(higher['offset'])
seriesString += fh.read(higherLastOffset - higher['offset'])
#Now we unpack the series data we just read
byteOrder,pointTypes = pointFormat[0]... | lowerIntervalStart = timestamp - (timestamp % lower['secondsPerPoint'])
lowerIntervalEnd = lowerIntervalStart + lower['secondsPerPoint']
fh.seek(higher['offset'])
packedPoint = fh.read(pointSize)
(higherBaseInterval,higherBaseValue) = struct.unpack(pointFormat,packedPoint)
if higherBaseInterval == 0:
high... | identifier_body |
whisper.py | ) #Based on assumption that first field is lastUpdate
now = int( time.time() )
packedTime = struct.pack(timestampFormat,now)
fh.write(packedTime)
fh.seek(originalOffset)
endBlock('__changeLastUpdate()')
def create(path,archiveList,xFilesFactor=0.5):
"""create(path,archiveList,xFilesFactor=0.5)
path is a ... |
higher = lower
#endBlock('update propagation')
__changeLastUpdate(fh)
fh.close()
def update_many(path,points):
"""update_many(path,points)
path is a string
points is a list of (timestamp,value) points
"""
if not points: return
points = [ (int(t),float(v)) for (t,v) in points]
points.sort(key=lambd... | break | conditional_block |
whisper.py | 0) #Based on assumption that first field is lastUpdate
now = int( time.time() )
packedTime = struct.pack(timestampFormat,now)
fh.write(packedTime)
fh.seek(originalOffset)
endBlock('__changeLastUpdate()')
def create(path,archiveList,xFilesFactor=0.5):
"""create(path,archiveList,xFilesFactor=0.5)
path is a... | byteDistance = pointDistance * pointSize
higherFirstOffset = higher['offset'] + (byteDistance % higher['size'])
higherPoints = lower['secondsPerPoint'] / higher['secondsPerPoint']
higherSize = higherPoints * pointSize
relativeFirstOffset = higherFirstOffset - higher['offset']
relativeLastOffset = (relat... | random_line_split | |
schemeValues.js | /**
* All the special characters.
*
* @constant
*/
var Characters = {
/**
* The character used to escape meta-characters in a string.
*/
ESCAPE : "\\",
/**
* The character used to delimit strings.
*/
STRING_QUOTE : "\"",
/**
* The character used to quote expressions.
... | LAMBDA : "λ",
/**
* The character that separates the two elements of a pair which isn't a list.
*/
PAIR_SEPARATOR : ".",
/**
* The character that denotes the rest of the line as a comment.
*/
COMMENT : ";"
};
/**
* All the special Scheme literals.
*
* @const
*/
var Sche... | */
NO_ESCAPE_QUOTE : "`",
/**
* A pretty lambda symbol for the web.
*/ | random_line_split |
variables.js | /**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* 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.apa... | else {
return '';
}
};
Blockly.JavaScript['local_var_set'] = function(block) {
if(block.isFromAnyDef()) {
return Blockly.JavaScript['variables_set'](block);
} else {
return '';
}
};
| {
return Blockly.JavaScript['variables_get'](block);
} | conditional_block |
variables.js | /**
* @license
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* 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.apa... |
Blockly.JavaScript['local_var_get'] = function(block) {
if(block.isFromAnyDef()) {
return Blockly.JavaScript['variables_get'](block);
} else {
return '';
}
};
Blockly.JavaScript['local_var_set'] = function(block) {
if(block.isFromAnyDef()) {
return Blockly.JavaScript['variables_set'](block);
} e... | block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
return varName + ' = ' + argument0 + ';\n';
}; | random_line_split |
interactive_interface.py | #
# DBus interface for the interactive partitioning module
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.... | from pyanaconda.modules.storage.partitioning.base_interface import PartitioningInterface
@dbus_interface(INTERACTIVE_PARTITIONING.interface_name)
class InteractivePartitioningInterface(PartitioningInterface):
"""DBus interface for the interactive partitioning module.""" | # Red Hat, Inc.
#
from dasbus.server.interface import dbus_interface
from pyanaconda.modules.common.constants.objects import INTERACTIVE_PARTITIONING | random_line_split |
interactive_interface.py | #
# DBus interface for the interactive partitioning module
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.... | """DBus interface for the interactive partitioning module.""" | identifier_body | |
interactive_interface.py | #
# DBus interface for the interactive partitioning module
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.... | (PartitioningInterface):
"""DBus interface for the interactive partitioning module."""
| InteractivePartitioningInterface | identifier_name |
form_builder.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
imp... | (
controlsConfig: {[key: string]: any},
options: AbstractControlOptions|{[key: string]: any}|null = null): FormGroup {
const controls = this._reduceControls(controlsConfig);
let validators: ValidatorFn|ValidatorFn[]|null = null;
let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = nu... | group | identifier_name |
form_builder.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
imp... | else if (Array.isArray(controlConfig)) {
const value = controlConfig[0];
const validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null;
const asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncVal... | {
return controlConfig;
} | conditional_block |
form_builder.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
imp... | * Creates an `AbstractControl` from a user-specified configuration.
*
* The `FormBuilder` provides syntactic sugar that shortens creating instances of a `FormControl`,
* `FormGroup`, or `FormArray`. It reduces the amount of boilerplate needed to build complex
* forms.
*
* @see [Reactive Forms Guide](/guide/react... | random_line_split | |
form_builder.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
imp... |
/**
* @description
* Creates an `AbstractControl` from a user-specified configuration.
*
* The `FormBuilder` provides syntactic sugar that shortens creating instances of a `FormControl`,
* `FormGroup`, or `FormArray`. It reduces the amount of boilerplate needed to build complex
* forms.
*
* @see [Reactive For... | {
return (<AbstractControlOptions>options).asyncValidators !== undefined ||
(<AbstractControlOptions>options).validators !== undefined ||
(<AbstractControlOptions>options).updateOn !== undefined;
} | identifier_body |
validation.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-validation',
templateUrl: './validation.component.html',
styleUrls: ['./validation.component.scss']
})
export class ValidationComponent implements OnInit {
... | & control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
if (Object.prototype.hasOwnProperty.call(control.errors, key)) {
this.formErrors[field] += messages[key] + ' ';
}
}
... | conditional_block | |
validation.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-validation',
templateUrl: './validation.component.html',
styleUrls: ['./validation.component.scss']
})
export class ValidationComponent implements OnInit {
... | Length(32)]],
email: ['', [Validators.required, Validators.email]],
password: [
'',
[
Validators.pattern('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$'),
Validators.minLength(6),
Validators.maxLength(16)
]
],
password_confirm: '',
... | tors.max | identifier_name |
validation.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-validation',
templateUrl: './validation.component.html',
styleUrls: ['./validation.component.scss']
})
export class ValidationComponent implements OnInit {
... | = this.registerFrom;
for (const field in this.formErrors) {
if (Object.prototype.hasOwnProperty.call(this.formErrors, field)) {
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validati... | terFrom) {
return;
}
const form | identifier_body |
validation.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-validation',
templateUrl: './validation.component.html',
|
registerFrom: FormGroup;
formErrors = {
username: '',
email: '',
password: ''
};
validationMessages = {
username: {
required: '',
minlength: '请输入大于4个字符',
maxlength: '请输入小于32个字符'
},
email: {
required: '',
email: '请输入正确的邮箱'
},
passwor... | styleUrls: ['./validation.component.scss']
})
export class ValidationComponent implements OnInit {
hide = true;
| random_line_split |
user.module.ts | import {NgModule} from "@angular/core";
import {UserComponent} from "./user.component";
import {BrowserModule} from "@angular/platform-browser";
import {HttpModule} from "@angular/http";
import {CommonModule} from "@angular/common";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {RouterModule} ... | {
} | UserModule | identifier_name |
user.module.ts | import {NgModule} from "@angular/core";
import {UserComponent} from "./user.component";
import {BrowserModule} from "@angular/platform-browser";
import {HttpModule} from "@angular/http";
import {CommonModule} from "@angular/common";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {RouterModule} ... | @NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule,
HttpModule,
ReactiveFormsModule,
CommonModule,
UserRoutingModule,
TranslateModule.forRoot()
],
declarations: [
UserComponent,
UserCreateComponent,
UserUpda... | import {UserService} from "./user.service";
import {UserAboutEditComponent} from "./me/user-about-edit.component";
import {NotificationService} from "../notification/notification.service";
| random_line_split |
lib.rs | 4 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://opensourc... |
}
}
/// Terminal color definitions
pub mod color {
/// Number for a terminal color
pub type Color = u16;
pub const BLACK: Color = 0;
pub const RED: Color = 1;
pub const GREEN: Color = 2;
pub const YELLOW: Color = 3;
pub const BLUE: Color = 4;
pub const MAGENTA: Color ... | {
WinConsole::new(WriterWrapper {
wrapped: box std::old_io::stderr() as Box<Writer + Send>,
})
} | conditional_block |
lib.rs | 4 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://opensourc... | {
wrapped: Box<Writer + Send>,
}
impl Writer for WriterWrapper {
#[inline]
fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
self.wrapped.write_all(buf)
}
#[inline]
fn flush(&mut self) -> IoResult<()> {
self.wrapped.flush()
}
}
#[cfg(not(windows))]
/// Return a Termin... | WriterWrapper | identifier_name |
lib.rs | 14 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://opensour... | pub const BRIGHT_GREEN: Color = 10;
pub const BRIGHT_YELLOW: Color = 11;
pub const BRIGHT_BLUE: Color = 12;
pub const BRIGHT_MAGENTA: Color = 13;
pub const BRIGHT_CYAN: Color = 14;
pub const BRIGHT_WHITE: Color = 15;
}
/// Terminal attributes
pub mod attr {
pub use self::Attr::*;... | random_line_split | |
oscilloscope.py | import wave
import struct
BPM = 320.0
BEAT_LENGTH = 60.0 / BPM
START_BEAT = 80.0 # beat 80 is the 'huh' of the first 'uuh-huh'
START_TIME = START_BEAT * BEAT_LENGTH
BEAT_COUNT = 16.0
CLIP_LENGTH = BEAT_LENGTH * BEAT_COUNT
FRAME_RATE = 50.0
FRAME_LENGTH = 1 / FRAME_RATE
FRAME_COUNT = int(FRAME_RATE * CLIP_LENGTH)
PIC... | frame_offset = START_TIME + (frame * FRAME_LENGTH)
for pick in range(0, 32):
pick_offset = frame_offset + (pick * PICK_INTERVAL)
wav.setpos(int(pick_offset * SAMPLE_RATE))
v1, v2 = struct.unpack('<hh', wav.readframes(1))
v = (v1 + v2) / 2
print "\tdb %d" % ((v / 5000) + 12)
print | conditional_block | |
oscilloscope.py | import wave
import struct
BPM = 320.0
BEAT_LENGTH = 60.0 / BPM
START_BEAT = 80.0 # beat 80 is the 'huh' of the first 'uuh-huh'
START_TIME = START_BEAT * BEAT_LENGTH
BEAT_COUNT = 16.0
CLIP_LENGTH = BEAT_LENGTH * BEAT_COUNT
FRAME_RATE = 50.0 | FRAME_LENGTH = 1 / FRAME_RATE
FRAME_COUNT = int(FRAME_RATE * CLIP_LENGTH)
PICK_RANGE = 0.008 # the duration of the span over which we pick our 32 samples each frame
PICK_INTERVAL = PICK_RANGE / 32
wav = wave.open('clips/kisskill_wipmix2_leadin.wav')
SAMPLE_RATE = wav.getframerate()
for frame in range(0, FRAME_COUNT)... | random_line_split | |
local.rs | //! UDP relay local server
use std::{
io::{self, Cursor, ErrorKind, Read},
net::{IpAddr, Ipv4Addr, SocketAddr},
sync::{Arc, Mutex},
time::Duration,
};
use futures::{self, Future, Stream};
use log::{debug, error, info};
use tokio::{self, net::UdpSocket, util::FutureExt};
use crate::{
config::{Serv... | Err(err)
} else {
Ok((cur, header.address))
}
})
.and_then(|(mut cur, addr)| {
let svr_cfg = svr_cfg_cloned_cloned;
let mut payload = Vec::new();
cur.read_to_end(&mut payload)... | {
let socket = Arc::new(Mutex::new(l));
let mut balancer = RoundRobin::new(context.config());
PacketStream::new(socket.clone()).for_each(move |(pkt, src)| {
let svr_cfg = balancer.pick_server();
let svr_cfg_cloned = svr_cfg.clone();
let svr_cfg_cloned_cloned = svr_cfg.clone();
... | identifier_body |
local.rs | //! UDP relay local server
use std::{
io::{self, Cursor, ErrorKind, Read},
net::{IpAddr, Ipv4Addr, SocketAddr},
sync::{Arc, Mutex},
time::Duration,
};
use futures::{self, Future, Stream};
use log::{debug, error, info};
use tokio::{self, net::UdpSocket, util::FutureExt};
use crate::{
config::{Serv... |
let mut payload = Vec::new();
cur.read_to_end(&mut payload).unwrap();
resolve_server_addr(context, svr_cfg)
.and_then(|remote_addr| {
let local_addr = SocketAddr::new(IpAddr::from(Ipv4Addr::new(0, 0, 0, 0)), 0);
... | Ok((cur, header.address))
}
})
.and_then(|(mut cur, addr)| {
let svr_cfg = svr_cfg_cloned_cloned; | random_line_split |
local.rs | //! UDP relay local server
use std::{
io::{self, Cursor, ErrorKind, Read},
net::{IpAddr, Ipv4Addr, SocketAddr},
sync::{Arc, Mutex},
time::Duration,
};
use futures::{self, Future, Stream};
use log::{debug, error, info};
use tokio::{self, net::UdpSocket, util::FutureExt};
use crate::{
config::{Serv... | (
context: SharedContext,
svr_cfg: Arc<ServerConfig>,
) -> impl Future<Item = SocketAddr, Error = io::Error> + Send {
match *svr_cfg.addr() {
// Return directly if it is a SocketAddr
ServerAddr::SocketAddr(ref addr) => boxed_future(futures::finished(*addr)),
// Resolve domain name to... | resolve_server_addr | identifier_name |
match-static-const-lc.rs | // Copyright 2012-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-MI... |
fn main () {
f();
g();
h();
}
| {
use self::n::OKAY as not_okay;
let r = match (0,0) {
(0, not_okay) => 0,
//~^ ERROR static constant in pattern `not_okay` should have an uppercase name such as `NOT_OKAY`
(x, y) => 1 + x + y,
};
assert!(r == 1);
} | identifier_body |
match-static-const-lc.rs | // Copyright 2012-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-MI... | () {
use self::m::aha;
let r = match (0,0) {
(0, aha) => 0,
//~^ ERROR static constant in pattern `aha` should have an uppercase name such as `AHA`
(x, y) => 1 + x + y,
};
assert!(r == 1);
}
mod n {
pub const OKAY : int = 8;
}
fn h() {
use self::n::OKAY as not_okay;
... | g | identifier_name |
match-static-const-lc.rs | // Copyright 2012-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-MI... | assert!(r == 1);
}
mod m {
#[allow(non_uppercase_statics)]
pub const aha : int = 7;
}
fn g() {
use self::m::aha;
let r = match (0,0) {
(0, aha) => 0,
//~^ ERROR static constant in pattern `aha` should have an uppercase name such as `AHA`
(x, y) => 1 + x + y,
};
as... | let r = match (0,0) {
(0, a) => 0,
//~^ ERROR static constant in pattern `a` should have an uppercase name such as `A`
(x, y) => 1 + x + y,
}; | random_line_split |
NaiveBayes.py | from __future__ import print_function
import math, nltk
from termcolor import colored
from analyze import generate_stopwords, sanitize
from vector import Vector
class NaiveBayesClassifier():
def __init__(self):
"""
Creates:
"""
self.c = {"+" : Vector(), "-" : Vector()}
... | (self, sentiment, tweets):
"""
@param {string} sentiment = "+" || "-"
{iterable} tweets = file_with_tagged_tweets
@return None
"""
freq = self.c[sentiment]
total = 0.0
for tweet in tweets:
total += 1
words = sanitize(tweet, ... | train | identifier_name |
NaiveBayes.py | from __future__ import print_function
import math, nltk
from termcolor import colored
from analyze import generate_stopwords, sanitize
from vector import Vector
class NaiveBayesClassifier():
def __init__(self):
"""
Creates:
"""
self.c = {"+" : Vector(), "-" : Vector()}
... | t += 1.0
totalp += 1.0
e = self.classify(tweet, False, eval=True)
if e != "+":
if e == "-": fn += 1
w += 1.0
tp = t - w # true positive
print(colored('Positive', 'green'), end="")
print(" - accuracy: %.2f%%" % self.a... | t = w = 0 # total = 0, wrong = 0
fp = fn = 0 # false positive = 0, false negative = 0
for tweet in open("data/verify_pos.txt"): | random_line_split |
NaiveBayes.py | from __future__ import print_function
import math, nltk
from termcolor import colored
from analyze import generate_stopwords, sanitize
from vector import Vector
class NaiveBayesClassifier():
def __init__(self):
"""
Creates:
"""
self.c = {"+" : Vector(), "-" : Vector()}
... |
c = NaiveBayesClassifier()
| pass | identifier_body |
NaiveBayes.py | from __future__ import print_function
import math, nltk
from termcolor import colored
from analyze import generate_stopwords, sanitize
from vector import Vector
class NaiveBayesClassifier():
def __init__(self):
"""
Creates:
"""
self.c = {"+" : Vector(), "-" : Vector()}
... |
w += 1.0
tn = t - w # true negative
print(colored('Negative', 'red'), end="")
print(" - accuracy: %.2f%%" % self.accuracy(w, t))
w = t = 0
for tweet in open("data/verify_neutral.txt"):
t += 1.0
if "~" != self.classify(tweet, verbose=Fals... | fp += 1 | conditional_block |
ble_live_read_graphical.py | from bluepy.btle import *
import time
import serial
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
start_time = time.time()
data = []
data2 = []
data3 = []
data4 = []
angles = []
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
pen = pg.mkPen('k', width=8)
app = QtGui.QAppl... |
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_() | global curve, data, angles2
if per.waitForNotifications(1):
t.append(time.time() - start_time)
x = list(range(0, len(angles), 1))
angles2 = [float(i) for i in angles]
curve.setData(x[-50:-1], angles2[-50:-1])
app.processEvents() | identifier_body |
ble_live_read_graphical.py | from bluepy.btle import *
import time
import serial
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
start_time = time.time()
data = []
data2 = []
data3 = []
data4 = []
angles = []
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
pen = pg.mkPen('k', width=8)
app = QtGui.QAppl... | angle = 180 - (float(data4[-1]) - arm_straight) / (arm_bent - arm_straight) * 135
print(data4[-1])
angles.append(angle)
# print(data4[-1], angle)
else:
print('received an unexpected handle')
print('Attempting to connect...')
mac1 = 'a4:d5:78:0d:1c:53'... | data3 = ''.join(data2)
data4 = data3.splitlines() | random_line_split |
ble_live_read_graphical.py | from bluepy.btle import *
import time
import serial
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
start_time = time.time()
data = []
data2 = []
data3 = []
data4 = []
angles = []
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
pen = pg.mkPen('k', width=8)
app = QtGui.QAppl... | (self, cHandle, data):
global data2, data3, data4, angle
if cHandle == 37:
data = data.decode("utf-8")
data2.append(data)
data3 = ''.join(data2)
data4 = data3.splitlines()
angle = 180 - (float(data4[-1]) - arm_straight) / (arm_bent - arm_straig... | handleNotification | identifier_name |
ble_live_read_graphical.py | from bluepy.btle import *
import time
import serial
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
start_time = time.time()
data = []
data2 = []
data3 = []
data4 = []
angles = []
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
pen = pg.mkPen('k', width=8)
app = QtGui.QAppl... |
else:
print('received an unexpected handle')
print('Attempting to connect...')
mac1 = 'a4:d5:78:0d:1c:53'
mac2 = 'a4:d5:78:0d:2e:fc'
per = Peripheral(mac1, "public")
per.setDelegate(MyDelegate())
print("Connected")
def update():
global curve, data, angles2
if per.waitForNotifications(1):... | data = data.decode("utf-8")
data2.append(data)
data3 = ''.join(data2)
data4 = data3.splitlines()
angle = 180 - (float(data4[-1]) - arm_straight) / (arm_bent - arm_straight) * 135
print(data4[-1])
angles.append(angle)
# print(data4[-1], ... | conditional_block |
github-search.test.js | import assert from 'assert';
import sinon from 'sinon';
import githubSearch from '../../lib/resolver/github-search.js';
describe('github-search', () => {
const sandbox = sinon.sandbox.create();
const fetchStub = sinon.stub(window, 'fetch');
const path = '/octo/foo.txt';
const target = 'bar.txt';
afterEach(... |
it('returns a function', () => {
assert.deepEqual(
typeof githubSearch({ path, target }),
'function',
);
});
it('calls the github search api', () => {
githubSearch({ path, target })();
assert.deepEqual(
fetchStub.args[0][0],
'https://api.github.com/search/code?q=bar.txt+... | });
after(() => {
sandbox.restore();
}); | random_line_split |
mythril_leveldb_test.py | import io
import pytest
from contextlib import redirect_stdout
from mock import patch
from mythril.mythril import MythrilLevelDB, MythrilConfig
from mythril.exceptions import CriticalError
@patch("mythril.ethereum.interface.leveldb.client.EthLevelDB.search")
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB",... |
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB", return_value=None)
@patch("mythril.ethereum.interface.leveldb.client.LevelDBReader", return_value=None)
@patch("mythril.ethereum.interface.leveldb.client.LevelDBWriter", return_value=None)
def test_leveldb_hash_search_incorrect_input(f1, f2, f3):
config ... | config = MythrilConfig()
config.set_api_leveldb("some path")
leveldb_search = MythrilLevelDB(leveldb=config.eth_db)
leveldb_search.search_db("code#PUSH#")
mock_leveldb.assert_called() | identifier_body |
mythril_leveldb_test.py | import io
import pytest
from contextlib import redirect_stdout
from mock import patch
from mythril.mythril import MythrilLevelDB, MythrilConfig
from mythril.exceptions import CriticalError
@patch("mythril.ethereum.interface.leveldb.client.EthLevelDB.search")
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB",... |
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB", return_value=None)
@patch("mythril.ethereum.interface.leveldb.client.LevelDBReader", return_value=None)
@patch("mythril.ethereum.interface.leveldb.client.LevelDBWriter", return_value=None)
def test_leveldb_hash_search_incorrect_input(f1, f2, f3):
config =... | mock_leveldb.assert_called() | random_line_split |
mythril_leveldb_test.py | import io
import pytest
from contextlib import redirect_stdout
from mock import patch
from mythril.mythril import MythrilLevelDB, MythrilConfig
from mythril.exceptions import CriticalError
@patch("mythril.ethereum.interface.leveldb.client.EthLevelDB.search")
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB",... | (mock_leveldb, f1, f2, f3):
config = MythrilConfig()
config.set_api_leveldb("some path")
leveldb_search = MythrilLevelDB(leveldb=config.eth_db)
leveldb_search.search_db("code#PUSH#")
mock_leveldb.assert_called()
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB", return_value=None)
@patch("... | test_leveldb_code_search | identifier_name |
test_summary.py | # -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
"""Tests for studydocuments summaries."""
import json
from amivapi.tests.utils import WebTestNoAuth
class | (WebTestNoAuth):
"""Studycos Test class."""
def _load_data(self):
"""Load some test fixtures."""
self.load_fixture({
'studydocuments': [{
'title': 'first',
'lecture': 'a',
'professor': 'a',
}, {
'title': 'se... | StudydocsSummaryTest | identifier_name |
test_summary.py | # -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
"""Tests for studydocuments summaries."""
import json
from amivapi.tests.utils import WebTestNoAuth
class StudydocsSummaryTest(WebTestNoAuth):
... |
def test_full_summary(self):
"""Test returning a summary."""
self._load_data()
response = self.api.get("/studydocuments",
status_code=200).json
assert '_summary' in response
assert response['_summary'] == {
'lecture': {
... | """Load some test fixtures."""
self.load_fixture({
'studydocuments': [{
'title': 'first',
'lecture': 'a',
'professor': 'a',
}, {
'title': 'second',
'lecture': 'a',
'professor': 'b',
... | identifier_body |
test_summary.py | # -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
"""Tests for studydocuments summaries."""
import json
from amivapi.tests.utils import WebTestNoAuth
class StudydocsSummaryTest(WebTestNoAuth):
... |
response = self.api.get("/studydocuments",
status_code=200).json
assert '_summary' in response
assert response['_summary'] == {
'lecture': {
'a': 2,
},
'professor': {
'a': 1,
'b'... |
def test_full_summary(self):
"""Test returning a summary."""
self._load_data() | random_line_split |
categories.js | var _ = require('underscore');
var express = require('express');
var router = express.Router();
var Autocomplete = require('autocomplete');
var autocomplete = Autocomplete.connectAutocomplete();
var categoryNames = [];
var categories = require('../data/categories.json');
_.each(categories, function (category) {
if(... | return false
});
return {label:found.name, value:found.id};
})
res.send(categoryResults);
});
router.get('/', function(req, res, next) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(categories));
});
module.exports = router; | var categoryResults = _.map(results, function(result){
var found = _.find(categories,function(category){
if( category.name!=undefined || category.name!=null )
return category.name.toLowerCase() === result;
else | random_line_split |
unignore-child.js | // ignore most things
var IgnoreFile = require("../")
, path = require('path')
// set the ignores just for this test
var c = require("./common.js")
c.ignores({ ".ignore": ["*", "a", "c", "!a/b/c/.abc", "!/c/b/a/cba"] })
// the only files we expect to see
var expected =
[ "/a/b/c/.abc"
, "/a"
, "/a/b"
, "/a/b/... | t.pass("start")
IgnoreFile({ path: __dirname + "/fixtures"
, ignoreFiles: [".ignore"] })
.on("child", function (e) {
var p = e.path.substr(e.root.path.length)
var i = expected.indexOf(p)
if (i === -1) {
t.fail("unexpected file found", {f: p})
} else {
t.pass... | require("tap").test("basic ignore rules", function (t) { | random_line_split |
unignore-child.js | // ignore most things
var IgnoreFile = require("../")
, path = require('path')
// set the ignores just for this test
var c = require("./common.js")
c.ignores({ ".ignore": ["*", "a", "c", "!a/b/c/.abc", "!/c/b/a/cba"] })
// the only files we expect to see
var expected =
[ "/a/b/c/.abc"
, "/a"
, "/a/b"
, "/a/b/... | else {
t.pass(p)
expected.splice(i, 1)
}
})
.on("close", function () {
t.notOk(expected.length, "all expected files should be seen")
t.end()
})
})
| {
t.fail("unexpected file found", {f: p})
} | conditional_block |
service.py | import logging
import os
import re
import select
import subprocess
import threading
import time
__all__ = [
'ExternalService',
'SpawnedService',
]
log = logging.getLogger(__name__)
class ExternalService(object):
def __init__(self, host, port):
log.info("Using already running service at %s:%d",... |
if re.search(pattern, '\n'.join(self.captured_stderr), re.IGNORECASE) is not None:
log.info("Found pattern %r in %d seconds via stderr", pattern, (t2 - t1))
return True
time.sleep(0.1)
def start(self):
threading.Thread.start(self)
def stop(self)... | log.info("Found pattern %r in %d seconds via stdout", pattern, (t2 - t1))
return True | conditional_block |
service.py | import logging
import os
import re
import select
import subprocess
import threading
import time
__all__ = [
'ExternalService',
'SpawnedService',
]
log = logging.getLogger(__name__)
class ExternalService(object):
def __init__(self, host, port):
log.info("Using already running service at %s:%d",... | (self):
self._spawn()
while True:
(rds, _, _) = select.select([self.child.stdout, self.child.stderr], [], [], 1)
if self.child.stdout in rds:
line = self.child.stdout.readline()
self.captured_stdout.append(line.decode('utf-8'))
if sel... | run_with_handles | identifier_name |
service.py | import logging
import os
import re
import select
import subprocess
import threading
import time
__all__ = [
'ExternalService',
'SpawnedService',
]
log = logging.getLogger(__name__)
class ExternalService(object):
def __init__(self, host, port):
log.info("Using already running service at %s:%d",... |
def open(self):
pass
def close(self):
pass
class SpawnedService(threading.Thread):
def __init__(self, args=None, env=None):
threading.Thread.__init__(self)
if args is None:
raise TypeError("args parameter is required")
self.args = args
self.en... | random_line_split | |
service.py | import logging
import os
import re
import select
import subprocess
import threading
import time
__all__ = [
'ExternalService',
'SpawnedService',
]
log = logging.getLogger(__name__)
class ExternalService(object):
|
class SpawnedService(threading.Thread):
def __init__(self, args=None, env=None):
threading.Thread.__init__(self)
if args is None:
raise TypeError("args parameter is required")
self.args = args
self.env = env
self.captured_stdout = []
self.captured_stde... | def __init__(self, host, port):
log.info("Using already running service at %s:%d", host, port)
self.host = host
self.port = port
def open(self):
pass
def close(self):
pass | identifier_body |
polygon.rs | use crate::Direction;
use crate::{
fragment::{
marker_line::{Marker, MarkerLine},
Bounds,
},
Cell, Point,
};
use nalgebra::Point2;
use ncollide2d::shape::{shape::Shape, Polyline};
use sauron::{
svg::{attributes::*, *},
Node,
};
use std::{cmp::Ordering, fmt, ops::Deref};
#[derive(Deb... | (&self, other: &Self) -> Ordering {
if self.points == other.points {
Ordering::Equal
} else {
self.first()
.cmp(&other.first())
.then(self.last().cmp(&other.last()))
.then(self.is_filled.cmp(&other.is_filled))
.then(... | cmp | identifier_name |
polygon.rs | use crate::Direction;
use crate::{
fragment::{
marker_line::{Marker, MarkerLine},
Bounds,
},
Cell, Point,
};
use nalgebra::Point2;
use ncollide2d::shape::{shape::Shape, Polyline};
use sauron::{
svg::{attributes::*, *},
Node,
};
use std::{cmp::Ordering, fmt, ops::Deref};
#[derive(Deb... | impl PartialEq for Polygon {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
} | random_line_split | |
polygon.rs | use crate::Direction;
use crate::{
fragment::{
marker_line::{Marker, MarkerLine},
Bounds,
},
Cell, Point,
};
use nalgebra::Point2;
use ncollide2d::shape::{shape::Shape, Polyline};
use sauron::{
svg::{attributes::*, *},
Node,
};
use std::{cmp::Ordering, fmt, ops::Deref};
#[derive(Deb... |
}
impl Polygon {
pub(in crate) fn new(points: Vec<Point>, is_filled: bool, tags: Vec<PolygonTag>) -> Self {
Polygon {
points,
is_filled,
tags,
}
}
pub(in crate) fn absolute_position(&self, cell: Cell) -> Self {
let points: Vec<Point> = self
... | {
if let Some(direction) = self.direction() {
direction == arg
} else {
// DiamondBullet just match any direction
true
}
} | identifier_body |
PC_newscontainer.js | import React from 'react'
import {Row, Col, Tabs, Carousel} from 'antd'
const TabPane = Tabs.TabPane
import PCNewsBlock from './PC_news_block'
import PCNewsImageBlock from './PC_news_image_block'
export default class PCNewsContainer extends React.Component {
render() | <img src="../../../../static/images/carousel_2.jpg"/>
</div>
<div>
<img src="../../../../static/images/carousel_3.jpg"/>
</div>
<div>
<img src="../../../../static/images/carousel_4.jpg"/>
... | {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
autoplay: true,
}
return(
<div>
<Row>
<Col span={2}></Col>
<Col span={20} className="container">
<div className="leftContainer">
<div classN... | identifier_body |
PC_newscontainer.js | import React from 'react'
import {Row, Col, Tabs, Carousel} from 'antd'
const TabPane = Tabs.TabPane
import PCNewsBlock from './PC_news_block'
import PCNewsImageBlock from './PC_news_image_block'
export default class PCNewsContainer extends React.Component {
| () {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
autoplay: true,
}
return(
<div>
<Row>
<Col span={2}></Col>
<Col span={20} className="container">
<div className="leftContainer">
<div cla... | render | identifier_name |
PC_newscontainer.js | import React from 'react'
import {Row, Col, Tabs, Carousel} from 'antd'
const TabPane = Tabs.TabPane
import PCNewsBlock from './PC_news_block'
import PCNewsImageBlock from './PC_news_image_block'
export default class PCNewsContainer extends React.Component {
render() {
const settings = {
dots: true,
... | <PCNewsImageBlock count={6} type='yule' width="400px" cartTitle="娱乐头条" width="400px" imageWidth='112px' />
</div>
<Tabs className="tabs_news">
<TabPane tab='新闻' key="1">
<PCNewsBlock count={22} type="top" width="100%" bordered="false"></PCNewsBlock>
... | </div>
<PCNewsImageBlock count={6} type='guoji' width="400px" cartTitle="国际头条" width="400px" imageWidth='112px' /> | random_line_split |
attrs-debug.js | define("#base/0.9.2/attrs-debug", ["./util"], function(require, exports) {
// Attrs
// -----------------
// Thanks to: | // - http://yuilibrary.com/yui/docs/api/classes/AttributeCore.html
// - https://github.com/berzniz/backbone.getters.setters
var Util = require('./util');
// 负责 attributes 的初始化
// attributes 是与实例相关的状态信息,可读可写,发生变化时,会自动触发相关事件
exports.initAttrs = function(config) {
// Keep existed attr... | // - http://documentcloud.github.com/backbone/#Model | random_line_split |
attrs-debug.js | define("#base/0.9.2/attrs-debug", ["./util"], function(require, exports) {
// Attrs
// -----------------
// Thanks to:
// - http://documentcloud.github.com/backbone/#Model
// - http://yuilibrary.com/yui/docs/api/classes/AttributeCore.html
// - https://github.com/berzniz/backbone.getters.sett... | arAt(0).toUpperCase() + key.substring(1);
}
});
| if (object.hasOwnProperty(properties[i])) {
return true;
}
}
return false;
}
function getChangeEventKey(key) {
return '_onChange' + key.ch | identifier_body |
attrs-debug.js | define("#base/0.9.2/attrs-debug", ["./util"], function(require, exports) {
// Attrs
// -----------------
// Thanks to:
// - http://documentcloud.github.com/backbone/#Model
// - http://yuilibrary.com/yui/docs/api/classes/AttributeCore.html
// - https://github.com/berzniz/backbone.getters.sett... | S = ['value', 'getter', 'setter', 'validator'];
// normalize `attrs` to
//
// {
// value: 'xx',
// getter: fn,
// setter: fn,
// validator: fn
// }
//
function normalize(attrs) {
// clone it
attrs = Util.merge({}, attrs);
for (var... | }
}
};
// Helpers
// -------
var ATTR_SPECIAL_KEY | conditional_block |
attrs-debug.js | define("#base/0.9.2/attrs-debug", ["./util"], function(require, exports) {
// Attrs
// -----------------
// Thanks to:
// - http://documentcloud.github.com/backbone/#Model
// - http://yuilibrary.com/yui/docs/api/classes/AttributeCore.html
// - https://github.com/berzniz/backbone.getters.sett... | ring(1);
}
});
| ase() + key.subst | identifier_name |
FaceDetection+BackgroundReduction.py | import numpy as np
import cv2
from matplotlib import pyplot as plt
face_cascade = cv2.CascadeClassifier('/home/tianyiz/user/601project/c/haarcascade_frontalface_alt.xml')
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY... | print(x,y,w,h)
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows() | random_line_split | |
FaceDetection+BackgroundReduction.py | import numpy as np
import cv2
from matplotlib import pyplot as plt
face_cascade = cv2.CascadeClassifier('/home/tianyiz/user/601project/c/haarcascade_frontalface_alt.xml')
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
while 1:
|
cap.release()
cv2.destroyAllWindows()
| ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#Background reduce
fgmask = fgbg.apply(img)
cv2.imshow('Reduce',fgmask)
for (x,y,w,h) in faces:
print(x,y,w,h)
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x... | conditional_block |
fatdbmut.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... | (&mut self, key: &[u8]) -> super::Result<()> {
let hash = key.sha3();
self.raw.db_mut().remove(&Self::to_aux_key(&hash));
self.raw.remove(&hash)
}
}
#[test]
fn fatdb_to_trie() {
use memorydb::MemoryDB;
use super::TrieDB;
use super::Trie;
let mut memdb = MemoryDB::new();
let mut root = H256::default();
{
... | remove | identifier_name |
fatdbmut.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... |
fn insert(&mut self, key: &[u8], value: &[u8]) -> super::Result<()> {
let hash = key.sha3();
try!(self.raw.insert(&hash, value));
let db = self.raw.db_mut();
db.emplace(Self::to_aux_key(&hash), DBValue::from_slice(key));
Ok(())
}
fn remove(&mut self, key: &[u8]) -> super::Result<()> {
let hash = key.s... | {
self.raw.get(&key.sha3())
} | identifier_body |
fatdbmut.rs |
// Parity 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.
// Parity is distributed in the hope that it will be useful,
// but WITH... | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity. | random_line_split | |
min_max.rs | extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::MinMaxResult::{self, NoElements, OneElement, MinMax};
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Optio... | #![feature(core)] | random_line_split | |
min_max.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::MinMaxResult::{self, NoElements, OneElement, MinMax};
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&... | () {
let a: A<T> = A { begin: 3, end: 9 };
let min_max: MinMaxResult<Item> = a.min_max();
assert_eq!(min_max, MinMax::<Item>(3, 8));
}
}
| min_max_test3 | identifier_name |
artifacts.py | import re
from django import template
from django.template.loader import get_template
from django.template import RequestContext
register = template.Library()
INSTALLED_ARTIFACTS = dict()
def install(artifact_class):
INSTALLED_ARTIFACTS[artifact_class.key] = artifact_class
def find(data):
from fir_artifa... | class AbstractArtifact:
case_sensitive = False
template = 'fir_artifacts/default.html'
@classmethod
def find(cls, data):
results = []
for i in re.finditer(cls.regex, data):
if cls.case_sensitive:
results.append(i.group('search'))
else:
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.