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 |
|---|---|---|---|---|
control.rs | use cgmath;
use claymore_scene::Transform;
pub type MousePos = (i32, i32);
pub struct Control {
rotate_speed: f32,
move_speed: f32,
zoom_speed: f32,
rotate_base: Option<(MousePos, Transform<f32>)>,
move_base: Option<(MousePos, cgmath::Vector3<f32>)>,
last_pos: MousePos,
space: Transform<f... | match self.move_base {
Some((base_pos, ref base_disp)) => {
use cgmath::{Vector, Rotation};
let local_vector = cgmath::vec3(
-(coords.0 - base_pos.0) as f32,
(coords.1 - base_pos.1) as f32,
0.0).mul_s(self.m... | {
self.last_pos = coords;
match self.rotate_base {
Some((ref base_pos, ref base_transform)) => {
use cgmath::Transform;
// p' = Mp * Tc^ * (Tr * Rz * Tr^) * p
// Tx = (Tr * Rz^ * Tr^) * Tc
let path = (coords.0 - base_pos.0) as f... | identifier_body |
control.rs | use cgmath;
use claymore_scene::Transform;
pub type MousePos = (i32, i32);
pub struct Control {
rotate_speed: f32,
move_speed: f32,
zoom_speed: f32,
rotate_base: Option<(MousePos, Transform<f32>)>,
move_base: Option<(MousePos, cgmath::Vector3<f32>)>,
last_pos: MousePos,
space: Transform<f... | }
}
pub fn rot_capture(&mut self, transform: &Transform<f32>) {
self.rotate_base = Some((self.last_pos, transform.clone()));
}
pub fn rot_release(&mut self) {
self.rotate_base = None;
}
pub fn move_capture(&mut self, transform: &Transform<f32>) {
self.move_base... | random_line_split | |
control.rs | use cgmath;
use claymore_scene::Transform;
pub type MousePos = (i32, i32);
pub struct Control {
rotate_speed: f32,
move_speed: f32,
zoom_speed: f32,
rotate_base: Option<(MousePos, Transform<f32>)>,
move_base: Option<(MousePos, cgmath::Vector3<f32>)>,
last_pos: MousePos,
space: Transform<f... | (rot_speed: f32, move_speed: f32, zoom_speed: f32,
space: Transform<f32>) -> Control {
Control {
rotate_speed: rot_speed,
move_speed: move_speed,
zoom_speed: zoom_speed,
rotate_base: None,
move_base: None,
last_pos: (0, 0),
... | new | identifier_name |
inferno-create-class.js | /*!
* inferno-create-class v1.0.0-beta39
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component')) :
typeof define === 'function' && define.amd ? defin... | (ctx) {
for (var i in ctx) {
var v = ctx[i];
if (typeof v === 'function' && !v.__bound && !AUTOBIND_BLACKLIST[i]) {
(ctx[i] = v.bind(ctx)).__bound = true;
}
}
}
function collateMixins(mixins, keyed) {
if ( keyed === void 0 ) keyed = {};
for (var i = 0; i < mixins.len... | bindAll | identifier_name |
inferno-create-class.js | /*!
* inferno-create-class v1.0.0-beta39
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component')) :
typeof define === 'function' && define.amd ? defin... | }
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
// don't autobind these methods since they already have guaranteed context.
var AUTOBIND_BLACKLIST = {
constructor: 1,
render: 1,
shouldComponentUpdate: 1,
componentWillReceiveProps: 1,
... | }
function isFunction(obj) {
return typeof obj === 'function'; | random_line_split |
inferno-create-class.js | /*!
* inferno-create-class v1.0.0-beta39
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component')) :
typeof define === 'function' && define.amd ? defin... |
}
}
function createClass$1(obj) {
var Cl = (function (Component$$1) {
function Cl(props) {
Component$$1.call(this, props);
this.isMounted = function () {
return !this._unmounted;
};
extend(this, obj);
if (Cl.mixins) {
... | {
var mixin = mixins[key];
if (isFunction(mixin[0])) {
applyMixin(key, inst, mixin);
}
else {
inst[key] = mixin;
}
} | conditional_block |
inferno-create-class.js | /*!
* inferno-create-class v1.0.0-beta39
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component')) :
typeof define === 'function' && define.amd ? defin... |
return Cl;
}(Component));
Cl.displayName = obj.displayName || 'Component';
Cl.propTypes = obj.propTypes;
Cl.defaultProps = obj.getDefaultProps ? obj.getDefaultProps() : undefined;
Cl.mixins = obj.mixins && collateMixins(obj.mixins);
if (obj.statics) {
extend(Cl, obj.statics);
... | {
var Cl = (function (Component$$1) {
function Cl(props) {
Component$$1.call(this, props);
this.isMounted = function () {
return !this._unmounted;
};
extend(this, obj);
if (Cl.mixins) {
applyMixins(this, Cl.mixins);
... | identifier_body |
main.js | .
if (error) {
throw "Error in loading data...";
}
// Assicuriamoci che tutto sia ordinato per numero di albo (e quindi per data di uscita)
// e per ora limitiamoci ai primi 20 albi per non sovraccaricare di richieste il server della Bonelli
// (le immagini sono linkate direttamente dal sito ufficiale).
... | .append("figure")
.append("a")
.attr("href","http://www.sergiobonelli.it/")
.attr("target","_blank") | random_line_split | |
main.js | ") viene dunque inserita come classe all'interno dell'attributo "class" del nodo selezionato ("div").
//
// Creiamo subito un contenitore della pagina, figlio del body per usare al meglio bootstrap.
//
var container = d3.select("body")
.append("div")
.attr("class","container-fluid");
// Inseriamo il titolo i... | ssicuriamoci che tutto sia ordinato per numero di albo (e quindi per data di uscita)
// e per ora limitiamoci ai primi 20 albi per non sovraccaricare di richieste il server della Bonelli
// (le immagini sono linkate direttamente dal sito ufficiale).
//
data = data.sort(function(a,b) { // Il metodo sort() passa ... | ow "Error in loading data...";
}
// A | conditional_block |
mod.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | {
Readable,
Writable,
ReadWrite,
Construct,
ConstructOnly,
LaxValidation,
StaticName,
Private,
StaticNick,
StaticBlurb,
Deprecated
}
pub struct ParamSpec {
g_type_instance: TypeInstance,
name: *mut c_char,
flags: ParamFlags,
value_type: GType,
owner_type:... | ParamFlags | identifier_name |
mod.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | // but 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 rgtk. If not, see <http://www.gnu.org/li... | random_line_split | |
setup.py | # coding: utf-8
import sys
from setuptools import setup, find_packages
NAME = "pollster"
VERSION = "2.0.2"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-da... | packages=find_packages(),
include_package_data=True,
long_description="""Download election-related polling data from Pollster."""
) | random_line_split | |
routes.spec.js | 'use strict';
const test = require('tape'),
routes = require('../lib/app/routes.js');
test('Routes tests', t => {
t.plan(2);
t.test('should use room from params for route redir', st => { | redir = routes.findRedirect(query),
url = 'https://gitter.im/' + query.room;
st.ok(redir.room, 'route has a room');
st.ok(redir.org, 'route has an org');
st.ok(redir.url, 'route has a url');
st.equal(redir.url, url, 'route url is correct');
st.end();
});
t.test('should find... | st.plan(4);
const query = { room: 'random' }, | random_line_split |
expression-016.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
/**
File Name: expression-016.js
Corresponds To: ecma/Expressions/11.2.3-3-n.js
ECMA Section: 11.2.3. Function Calls
Description:
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "expression-016";
var VERSION = "JS1_4";
var TITLE = ... | /* 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/. */
gTestfile = 'expression-016.js'; | random_line_split |
test_wrappers.py | # -*- coding: utf-8 -*-
from werkzeug.contrib import wrappers
from werkzeug import routing
from werkzeug.wrappers import Request, Response
def test_reverse_slash_behavior():
"""Test ReverseSlashBehaviorRequestMixin"""
class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request):
pass
req =... | del resp.headers['content-type']
try:
resp.charset = 'utf-8'
except TypeError, e:
pass
else:
assert False, 'expected type error on charset setting without ct' | assert resp.charset == 'iso-8859-15'
resp.data = u'Hällo Wörld'
assert ''.join(resp.iter_encoded()) == \
u'Hällo Wörld'.encode('iso-8859-15') | random_line_split |
test_wrappers.py | # -*- coding: utf-8 -*-
from werkzeug.contrib import wrappers
from werkzeug import routing
from werkzeug.wrappers import Request, Response
def test_reverse_slash_behavior():
"""Test ReverseSlashBehaviorRequestMixin"""
class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request):
pass
req =... |
env = {'CONTENT_TYPE': 'text/plain; charset=x-weird-charset'}
req = MyRequest(env)
req.unknown_charset = return_ascii
assert req.charset == 'ascii'
assert req.url_charset == 'utf-8'
def test_dynamic_charset_response_mixin():
"""Test DynamicCharsetResponseMixin"""
class MyResponse(wrappers... | return "ascii" | identifier_body |
test_wrappers.py | # -*- coding: utf-8 -*-
from werkzeug.contrib import wrappers
from werkzeug import routing
from werkzeug.wrappers import Request, Response
def test_reverse_slash_behavior():
"""Test ReverseSlashBehaviorRequestMixin"""
class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request):
pass
req =... | rt False, 'expected type error on charset setting without ct'
| conditional_block | |
test_wrappers.py | # -*- coding: utf-8 -*-
from werkzeug.contrib import wrappers
from werkzeug import routing
from werkzeug.wrappers import Request, Response
def test_reverse_slash_behavior():
"""Test ReverseSlashBehaviorRequestMixin"""
class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request):
pass
req =... | (x):
return "ascii"
env = {'CONTENT_TYPE': 'text/plain; charset=x-weird-charset'}
req = MyRequest(env)
req.unknown_charset = return_ascii
assert req.charset == 'ascii'
assert req.url_charset == 'utf-8'
def test_dynamic_charset_response_mixin():
"""Test DynamicCharsetResponseMixin"""
... | return_ascii | identifier_name |
module_with_multiple_exports.js | /**
* @module {Module} utils/math
* @parent utils
*
* The module's description is the first paragraph.
*
* The body of the module's documentation.
*/
import _ from 'lodash';
/**
* @function
*
* This function's description is the first
* paragraph.
*
* This starts the body. This text comes after the sign... | ;
/**
* @property {{}}
*
* This function's description is the first
* paragraph.
*
* @option {Number} pi The description of pi.
*
* @option {Number} e The description of e.
*/
export var constants = {
pi: 3.14159265359,
e: 2.71828
}; | { ... } | identifier_body |
module_with_multiple_exports.js | /**
* @module {Module} utils/math
* @parent utils
*
* The module's description is the first paragraph.
*
* The body of the module's documentation. | * @function
*
* This function's description is the first
* paragraph.
*
* This starts the body. This text comes after the signature.
*
* @param {Number} first This param's description.
* @param {Number} second This param's description.
* @return {Number} This return value's description.
*/
export function... | */
import _ from 'lodash';
/** | random_line_split |
module_with_multiple_exports.js | /**
* @module {Module} utils/math
* @parent utils
*
* The module's description is the first paragraph.
*
* The body of the module's documentation.
*/
import _ from 'lodash';
/**
* @function
*
* This function's description is the first
* paragraph.
*
* This starts the body. This text comes after the sign... | (first, second){ ... };
/**
* @property {{}}
*
* This function's description is the first
* paragraph.
*
* @option {Number} pi The description of pi.
*
* @option {Number} e The description of e.
*/
export var constants = {
pi: 3.14159265359,
e: 2.71828
}; | sum | identifier_name |
Configurator.ts | /// <reference path="FormatterRegistry.ts" />
/// <reference path="OrdinalizerRegistry.ts" />
/// <reference path="CollectionFormatterRegistry.ts" />
/// <reference path="NumberToWordsConverterRegistry.ts" />
/// <reference path="../DateHumanizeStrategy/DefaultDateHumanizeStrategy.ts" />
module Humanizer.Configuratio... | : Localisation.Ordinalizers.IOrdinalizer
{
return ordinalizers.resolveForCulture(Resources.getCurrentCulture());
}
export function getCollectionFormatters(): Localisation.CollectionFormatters.ICollectionFormatter
{
return collections.resolveForCulture(Resources.getCurrentCulture());
... | tOrdinalizer() | identifier_name |
Configurator.ts | /// <reference path="FormatterRegistry.ts" />
/// <reference path="OrdinalizerRegistry.ts" /> | /// <reference path="NumberToWordsConverterRegistry.ts" />
/// <reference path="../DateHumanizeStrategy/DefaultDateHumanizeStrategy.ts" />
module Humanizer.Configuration.Configurator
{
"use strict";
var formatter: LocaliserRegistry<Localisation.Formatter.IFormatter> = new FormatterRegistry();
var ordinali... | /// <reference path="CollectionFormatterRegistry.ts" /> | random_line_split |
Configurator.ts | /// <reference path="FormatterRegistry.ts" />
/// <reference path="OrdinalizerRegistry.ts" />
/// <reference path="CollectionFormatterRegistry.ts" />
/// <reference path="NumberToWordsConverterRegistry.ts" />
/// <reference path="../DateHumanizeStrategy/DefaultDateHumanizeStrategy.ts" />
module Humanizer.Configuratio... | export function getOrdinalizer(): Localisation.Ordinalizers.IOrdinalizer
{
return ordinalizers.resolveForCulture(Resources.getCurrentCulture());
}
export function getCollectionFormatters(): Localisation.CollectionFormatters.ICollectionFormatter
{
return collections.resolveForCulture... | return formatter.resolveForCulture(culture);
}
| identifier_body |
Topography.py | # import system modules
import arcpy
from arcpy import env
# Set environment settings
env.workspace = "C:\Users\Ewan\Desktop\SFTPDST5\MapFiles"
try:
# Set the local variable
in_Table = "Topography.csv"
x_coords = "x"
y_coords = "y"
out_Layer = "Topography_Layer"
saved_Layer = "c:\... | assignmentType = "MOST_FREQUENT"
priorityField = ""
cellSize = 0.000005
# Execute PointToRaster
arcpy.PointToRaster_conversion(inFeatures, valField, outRaster, assignmentType, priorityField, cellSize)
##Assign colormap using clr file
arcpy.AddColormap_management("c:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\Topo... | # Set local variables
inFeatures = "Topography.lyr"
valField = "Topography"
outRaster = "C:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\TopographyR"
| random_line_split |
jsonfile.py | # (c) 2014, Brian Coca, Josh Drake, et al
#
# This file is part of Ansible
#
# Ansible 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, key):
if key in self._cache:
return True
if self.has_expired(key):
return False
try:
st = os.stat("%s/%s" % (self._cache_dir, key))
return True
except (OSError,IOError), e:
if e.errno == errno.ENOENT:
re... | contains | identifier_name |
jsonfile.py | # (c) 2014, Brian Coca, Josh Drake, et al
#
# This file is part of Ansible
#
# Ansible 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.
... |
def delete(self, key):
del self._cache[key]
try:
os.remove("%s/%s" % (self._cache_dir, key))
except (OSError,IOError), e:
pass #TODO: only pass on non existing?
def flush(self):
self._cache = {}
for key in self.keys():
self.delete(ke... | if key in self._cache:
return True
if self.has_expired(key):
return False
try:
st = os.stat("%s/%s" % (self._cache_dir, key))
return True
except (OSError,IOError), e:
if e.errno == errno.ENOENT:
return False
... | identifier_body |
jsonfile.py | # (c) 2014, Brian Coca, Josh Drake, et al
#
# This file is part of Ansible
#
# Ansible 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 ret
| ret[key] = self.get(key) | conditional_block |
jsonfile.py | # (c) 2014, Brian Coca, Josh Drake, et al
#
# This file is part of Ansible
#
# Ansible 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.
... | except (OSError,IOError), e:
utils.warning("error while trying to write to %s : %s" % (cachefile, str(e)))
else:
value = json.load(f)
self._cache[key] = value
return value
finally:
f.close()
def set(self, key, value):
self... | raise KeyError
cachefile = "%s/%s" % (self._cache_dir, key)
try:
f = open( cachefile, 'r') | random_line_split |
ac.rs | //! Actor-critic algorithms.
use crate::{
domains::Transition,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler,
};
pub trait Critic<'t, S: 't, A: 't> {
fn target(&self, t: &'t Transition<S, A>) -> f64;
}
impl<'t, F, S: 't, A: 't> Critic<'t, S, A> for F
where F: Fn(&'t Transition<S, ... |
}
impl<'m, S, C, P> Handler<&'m Transition<S, P::Action>> for ActorCritic<C, P>
where
C: Critic<'m, S, P::Action>,
P: Policy<&'m S> + Handler<StateActionUpdate<&'m S, &'m <P as Policy<&'m S>>::Action, f64>>,
{
type Response = P::Response;
type Error = P::Error;
fn handle(&mut self, t: &'m Transit... | {
ActorCritic {
critic: TDCritic {
gamma,
v_func,
},
policy,
alpha,
}
} | identifier_body |
ac.rs | //! Actor-critic algorithms.
use crate::{
domains::Transition,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler,
};
pub trait Critic<'t, S: 't, A: 't> {
fn target(&self, t: &'t Transition<S, A>) -> f64;
}
impl<'t, F, S: 't, A: 't> Critic<'t, S, A> for F
where F: Fn(&'t Transition<S, ... | (q_func: Q, policy: P, alpha: f64) -> Self {
ActorCritic {
critic: QCritic(q_func),
policy,
alpha,
}
}
}
impl<V, P> ActorCritic<TDCritic<V>, P> {
pub fn tdac(v_func: V, policy: P, alpha: f64, gamma: f64) -> Self {
ActorCritic {
critic: TDC... | qac | identifier_name |
ac.rs | //! Actor-critic algorithms.
use crate::{
domains::Transition,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler,
};
pub trait Critic<'t, S: 't, A: 't> {
fn target(&self, t: &'t Transition<S, A>) -> f64;
}
impl<'t, F, S: 't, A: 't> Critic<'t, S, A> for F
where F: Fn(&'t Transition<S, ... | else {
let v = self.v_func.evaluate((t.from.state(),));
t.reward + self.gamma * nv - v
}
}
}
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct ActorCritic<C, P> {
pub critic: C,
pub... | {
t.reward - nv
} | conditional_block |
ac.rs | //! Actor-critic algorithms.
use crate::{
domains::Transition,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler,
};
pub trait Critic<'t, S: 't, A: 't> {
fn target(&self, t: &'t Transition<S, A>) -> f64;
}
impl<'t, F, S: 't, A: 't> Critic<'t, S, A> for F
where F: Fn(&'t Transition<S, ... | feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct ActorCritic<C, P> {
pub critic: C,
pub policy: P,
pub alpha: f64,
}
impl<C, P> ActorCritic<C, P> {
pub fn new(critic: C, policy: P, alpha: f64) -> Self {
ActorCritic {
critic,
... | }
#[derive(Clone, Debug)]
#[cfg_attr( | random_line_split |
urls.py | from django.conf.urls import patterns, include, url
from django.shortcuts import redirect, render_to_response
from django.template.context import RequestContext
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
# Just redirect / to /blog for now until I can
# co... | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBIL... | slicense = """
Copyright (c) 2012-2013 Justin Crawford <Justasic@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above c... | identifier_body |
urls.py | from django.conf.urls import patterns, include, url
from django.shortcuts import redirect, render_to_response
from django.template.context import RequestContext
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
# Just redirect / to /blog for now until I can
# co... | (request):
slicense = """
Copyright (c) 2012-2013 Justin Crawford <Justasic@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must ret... | sslicense | identifier_name |
urls.py | from django.conf.urls import patterns, include, url
from django.shortcuts import redirect, render_to_response
from django.template.context import RequestContext
| from django.contrib import admin
admin.autodiscover()
# Just redirect / to /blog for now until I can
# come up with something to put on the homepage..
def to_blog(request):
return redirect('/blog/', permanent=False)
# Follow the BSD license and allow the source/binary to reproduce
# the license and copyright mes... | # Uncomment the next two lines to enable the admin: | random_line_split |
testimages.py | #!/usr/bin/env python
from time import sleep
import os
import RPi.GPIO as GPIO
import subprocess
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
count = 0 | up = False
down = False
command = ""
filename = ""
index = 0
camera_pause = "500"
def takepic(imageName):
print("picture")
command = "sudo raspistill -o " + imageName + " -q 100 -t " + camera_pause
print(command)
os.system(command)
while(True):
if(up==True):
if(GPIO.input(24)==False):
now = date... | random_line_split | |
testimages.py | #!/usr/bin/env python
from time import sleep
import os
import RPi.GPIO as GPIO
import subprocess
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
count = 0
up = False
down = False
command = ""
filename = ""
index = 0
camera_pause = "500"
def takepic(imageName):
|
while(True):
if(up==True):
if(GPIO.input(24)==False):
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d_%H%M%S")
filename = "photo-"+timeString+".jpg"
takepic(filename)
subprocess.call(['./processImage.sh', filename, '&'])
up = GPIO.input(24)
count = count+1
... | print("picture")
command = "sudo raspistill -o " + imageName + " -q 100 -t " + camera_pause
print(command)
os.system(command) | identifier_body |
testimages.py | #!/usr/bin/env python
from time import sleep
import os
import RPi.GPIO as GPIO
import subprocess
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
count = 0
up = False
down = False
command = ""
filename = ""
index = 0
camera_pause = "500"
def | (imageName):
print("picture")
command = "sudo raspistill -o " + imageName + " -q 100 -t " + camera_pause
print(command)
os.system(command)
while(True):
if(up==True):
if(GPIO.input(24)==False):
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d_%H%M%S")
filename = "photo... | takepic | identifier_name |
testimages.py | #!/usr/bin/env python
from time import sleep
import os
import RPi.GPIO as GPIO
import subprocess
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
count = 0
up = False
down = False
command = ""
filename = ""
index = 0
camera_pause = "500"
def takepic(imageName):
print("picture")
command = "sudo ras... |
print "done"
| if(up==True):
if(GPIO.input(24)==False):
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d_%H%M%S")
filename = "photo-"+timeString+".jpg"
takepic(filename)
subprocess.call(['./processImage.sh', filename, '&'])
up = GPIO.input(24)
count = count+1
sleep(.1) | conditional_block |
reqpart.py | #
# Chris Lumens <clumens@redhat.com>
#
# Copyright 2015 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. This program is distributed in the hope that it
# will be usef... |
class F23_AutopartReqpart_TestCase(CommandSequenceTest):
def runTest(self):
# fail - can't use both autopart and reqpart
self.assert_parse_error("""
autopart
reqpart""")
RHEL7_TestCase = F23_TestCase
if __name__ == "__main__":
unittest.main()
| self.assert_parse("reqpart", "reqpart\n")
# pass
self.assert_parse("reqpart --add-boot", "reqpart --add-boot\n") | identifier_body |
reqpart.py | #
# Chris Lumens <clumens@redhat.com>
#
# Copyright 2015 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. This program is distributed in the hope that it
# will be usef... | unittest.main() | conditional_block | |
reqpart.py | #
# Chris Lumens <clumens@redhat.com>
#
# Copyright 2015 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. This program is distributed in the hope that it
# will be usef... |
class F23_AutopartReqpart_TestCase(CommandSequenceTest):
def runTest(self):
# fail - can't use both autopart and reqpart
self.assert_parse_error("""
autopart
reqpart""")
RHEL7_TestCase = F23_TestCase
if __name__ == "__main__":
unittest.main() | random_line_split | |
reqpart.py | #
# Chris Lumens <clumens@redhat.com>
#
# Copyright 2015 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. This program is distributed in the hope that it
# will be usef... | (CommandTest):
command = "reqpart"
def runTest(self):
# pass
self.assert_parse("reqpart", "reqpart\n")
# pass
self.assert_parse("reqpart --add-boot", "reqpart --add-boot\n")
class F23_AutopartReqpart_TestCase(CommandSequenceTest):
def runTest(self):
# fail - can't ... | F23_TestCase | identifier_name |
thummer.py | # -*- coding: utf-8 -*-
#
# Copyright 2011-2018 Matt Austin
#
# 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 applicabl... |
def _render(self, context):
url = self.url.resolve(context)
geometry = self.geometry.resolve(context)
options = {}
for key, expr in self.options:
noresolve = {'True': True, 'False': False, 'None': None}
value = noresolve.get('{}'.format(expr), expr.resolve(c... | self.nodelist_empty = parser.parse(('endthummer',))
parser.delete_first_token() | conditional_block |
thummer.py | # -*- coding: utf-8 -*-
#
# Copyright 2011-2018 Matt Austin
#
# 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 applicabl... |
def __iter__(self):
for node in self.nodelist_url:
yield node
for node in self.nodelist_empty:
yield node
| url = self.url.resolve(context)
geometry = self.geometry.resolve(context)
options = {}
for key, expr in self.options:
noresolve = {'True': True, 'False': False, 'None': None}
value = noresolve.get('{}'.format(expr), expr.resolve(context))
if key == 'options':
... | identifier_body |
thummer.py | # -*- coding: utf-8 -*-
#
# Copyright 2011-2018 Matt Austin
#
# 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 applicabl... | (self, parser, token):
bits = token.split_contents()
if len(bits) < 5 or bits[-2] != 'as':
raise TemplateSyntaxError(self.error_msg)
self.url = parser.compile_filter(bits[1])
self.geometry = parser.compile_filter(bits[2])
self.options = []
for bit in bits[3:-2... | __init__ | identifier_name |
thummer.py | # -*- coding: utf-8 -*-
#
# Copyright 2011-2018 Matt Austin
#
# 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 applicabl... | output = self.nodelist_url.render(context)
context.pop()
return output
def __iter__(self):
for node in self.nodelist_url:
yield node
for node in self.nodelist_empty:
yield node | return self.nodelist_empty.render(context)
context.push()
context[self.as_var] = thumbnail | random_line_split |
jsonrpc.py | remote procedure call protocol
designed to be simple.
A remote method is invoked by sending a request to a remote service,
the request is a single object serialised using JSON.
.. _`JSON-RPC 2.0`: http://www.jsonrpc.org/specification
'''
version = '2.0'
def __call__(self, request):
... |
return obj
class JsonBatchProxy(JsonProxy):
"""A python Proxy class for :class:`.JSONRPC` Servers
implementing batch protocol.
:param url: server location
:param version: JSON-RPC server version. Default ``2.0``
:param id: optional request id, generated if not provided.
Default `... | return obj.get('result') | conditional_block |
jsonrpc.py | lightweight remote procedure call protocol
designed to be simple.
A remote method is invoked by sending a request to a remote service,
the request is a single object serialised using JSON.
.. _`JSON-RPC 2.0`: http://www.jsonrpc.org/specification
'''
version = '2.0'
def __call__(self, requ... | 'id' not in data):
raise InvalidRequest(
'jsonrpc must be supplied and equal to "%s"' %
self.version
)
params = data.get('params')
if isinstance(params, dict):
args, kwargs = (), params
... | try:
if (not isinstance(data, dict) or
data.get('jsonrpc') != self.version or | random_line_split |
jsonrpc.py | .get('method'))
result = yield from as_coroutine(proc(request, *args, **kwargs))
except Exception as exc:
result = exc
exc_info = sys.exc_info()
else:
try:
json.dumps(result)
except Exception as exc:
result = exc... | if not isinstance(content, list):
content = [content]
for resp in content:
try:
yield BatchResponse(
id=resp['id'],
result=JsonBatchProxy.loads(resp),
exception=None
)
except Exceptio... | identifier_body | |
jsonrpc.py | remote procedure call protocol
designed to be simple.
A remote method is invoked by sending a request to a remote service,
the request is a single object serialised using JSON.
.. _`JSON-RPC 2.0`: http://www.jsonrpc.org/specification
'''
version = '2.0'
def __call__(self, request):
... | (self):
return self._url
@property
def version(self):
return self._version
@property
def _loop(self):
return self._http._loop
def makeid(self):
'''Can be re-implemented by your own Proxy'''
return gen_unique_id()
def __repr__(self):
return '%s(... | url | identifier_name |
builder_test.py | # coding=utf-8
# Copyright 2022 The Deeplab2 Authors.
#
# 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 ... | tf.test.main() | conditional_block | |
builder_test.py | # coding=utf-8
# Copyright 2022 The Deeplab2 Authors.
#
# 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 ... | (self, model_name):
backbone_options = config_pb2.ModelOptions.BackboneOptions(
name=model_name, use_squeeze_and_excite=True, output_stride=32)
encoder = builder.create_encoder(
backbone_options,
tf.keras.layers.experimental.SyncBatchNormalization)
self.assertIsInstance(encoder, mobi... | test_mobilenet_encoder_creation | identifier_name |
builder_test.py | # coding=utf-8
# Copyright 2022 The Deeplab2 Authors.
#
# 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 ... |
def test_decoder_creation(self):
proto_filename = os.path.join(
_CONFIG_PATH, 'example_kitti-step_motion_deeplab.textproto')
model_options = _read_proto_file(proto_filename, config_pb2.ModelOptions())
motion_decoder = builder.create_decoder(
model_options, tf.keras.layers.experimental.Sy... | backbone_options = config_pb2.ModelOptions.BackboneOptions(
name='max_deeplab_s', output_stride=32)
encoder = builder.create_resnet_encoder(
backbone_options,
bn_layer=tf.keras.layers.experimental.SyncBatchNormalization)
self.assertIsInstance(encoder, axial_resnet_instances.MaXDeepLabS) | identifier_body |
builder_test.py | # coding=utf-8
# Copyright 2022 The Deeplab2 Authors.
#
# 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 ... | import tensorflow as tf
from google.protobuf import text_format
from deeplab2 import config_pb2
from deeplab2.model import builder
from deeplab2.model.decoder import motion_deeplab_decoder
from deeplab2.model.encoder import axial_resnet_instances
from deeplab2.model.encoder import mobilenet
# resources dependency
_C... | random_line_split | |
TestScript.py | # encoding= utf-8
##
# VisibilityCheck.
# <p>
# Description of the test.
#
# @data INSTANCE_ID [String] instance id
##
from qtaste import *
import time
# update in order to cope with the javaGUI extension declared in your testbed configuration.
javaguiMI = testAPI.getJavaGUI(INSTANCE_ID=testData.getValue("JAVAGUI_I... |
doStep(step1)
| """
@step Description of the actions done for this step
@expected Description of the expected result
"""
doSubSteps(TabbedPaneSelection.changeTabByTitle)
subtitler.setSubtitle("Click on the button to make the component invisible")
time.sleep(1)
javaguiMI.clickOnButton("VISIBILITY_BUTTO... | identifier_body |
TestScript.py | # encoding= utf-8
##
# VisibilityCheck.
# <p>
# Description of the test.
#
# @data INSTANCE_ID [String] instance id
##
from qtaste import *
import time
# update in order to cope with the javaGUI extension declared in your testbed configuration.
javaguiMI = testAPI.getJavaGUI(INSTANCE_ID=testData.getValue("JAVAGUI_I... | ():
"""
@step Description of the actions done for this step
@expected Description of the expected result
"""
doSubSteps(TabbedPaneSelection.changeTabByTitle)
subtitler.setSubtitle("Click on the button to make the component invisible")
time.sleep(1)
javaguiMI.clickOnButton("VISIBILI... | step1 | identifier_name |
TestScript.py | # encoding= utf-8
##
# VisibilityCheck.
# <p>
# Description of the test.
#
# @data INSTANCE_ID [String] instance id
##
from qtaste import *
import time |
# update in order to cope with the javaGUI extension declared in your testbed configuration.
javaguiMI = testAPI.getJavaGUI(INSTANCE_ID=testData.getValue("JAVAGUI_INSTANCE_NAME"))
subtitler = testAPI.getSubtitler()
importTestScript("TabbedPaneSelection")
def step1():
"""
@step Description of the actions... | random_line_split | |
TestScript.py | # encoding= utf-8
##
# VisibilityCheck.
# <p>
# Description of the test.
#
# @data INSTANCE_ID [String] instance id
##
from qtaste import *
import time
# update in order to cope with the javaGUI extension declared in your testbed configuration.
javaguiMI = testAPI.getJavaGUI(INSTANCE_ID=testData.getValue("JAVAGUI_I... |
try:
subtitler.setSubtitle("Try to insert a value in the invible text field", 10)
javaguiMI.setText("VISIBILITY_TEXT", "pas bien")
testAPI.stop(Status.FAIL, "The component should not be visible and the setText() should failed")
except :
javaguiMI.clickOnButton("VISIBILITY_BUTTO... | testAPI.stop(Status.FAIL, "The component should not be visible") | conditional_block |
async.js | /*
* Copyright 2014 Google Inc. All rights reserved.
*
* 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 applicabl... |
var value = items.shift();
handler(value, function(error) {
if (error !== undefined) {
callback(error);
return;
}
exports.serialAsyncForEach(items, handler, callback);
});
}
| {
callback();
return;
} | conditional_block |
async.js | /*
* Copyright 2014 Google Inc. All rights reserved.
*
* 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 applicabl... | }
};
// Implementation logic of the JobPool
exports.JobPool.prototype._run = function(id) {
var parent = this;
if (this.queue.length == 0) {
this.available.push(id);
return;
}
var value = this.queue.pop();
this.runner(value, id,
function(error) {
if (error !== undefined) {
p... | if (this.available.length > 0) {
this._run(this.available.pop());
this.running++; | random_line_split |
compiler-calls.rs | // Copyright 2015 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 args = vec!["compiler-calls".to_string(), "foo.rs".to_string()];
rustc_driver::run_compiler(args.as_slice(), &mut tc);
assert!(tc.count == 30);
} | let mut tc = TestCalls { count: 1 };
// we should never get use this filename, but lets make sure they are valid args. | random_line_split |
compiler-calls.rs | // Copyright 2015 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 ... |
fn no_input(&mut self,
_: &getopts::Matches,
_: &config::Options,
_: &Option<PathBuf>,
_: &Option<PathBuf>,
_: &diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)> {
panic!("This shouldn't happ... | {
self.count *= 5;
(input, input_path)
} | identifier_body |
compiler-calls.rs | // Copyright 2015 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 ... | (&mut self, _: &Session) -> driver::CompileController<'a> {
panic!("This shouldn't be called");
}
}
fn main() {
let mut tc = TestCalls { count: 1 };
// we should never get use this filename, but lets make sure they are valid args.
let args = vec!["compiler-calls".to_string(), "foo.rs".to_strin... | build_controller | identifier_name |
PaperSheet.tsx | /**
* Printer Friendly Paper Sheet rendered with CSS directives as Styled Reacts divs
*/
import styled from '@emotion/styled'
interface PaperSheetProps {
internalMargins: {
top: number
bottom: number
left: number
right: number
}
}
interface SectionProps {
heightInMm: number
}
const PaperShee... | height: 297mm;
min-height: 297mm;
padding-top: ${(props: PaperSheetProps) => props.internalMargins.top}mm;
padding-bottom: ${(props: PaperSheetProps) => props.internalMargins.bottom}mm;
padding-left: ${(props: PaperSheetProps) => props.internalMargins.left}mm;
padding-right: ${(props: PaperSheetProps) => pr... | random_line_split | |
index.d.ts | // Type definitions for koa-xml-body 2.0
// Project: https://github.com/creeperyang/koa-xml-body
// Definitions by: Ulf Winkelvos <https://github.com/uwinkelvos>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/* =================== USAGE ===================
import Koa =... | xmlOptions?: Xml2jsOptions
}): Koa.Middleware;
declare namespace bodyParser { }
export = bodyParser; | // options which will be used to parse xml. Default is {}. See xml2js Options for details. | random_line_split |
servicemap.js | autosize) {
if (!elementId && elementId != '') {
log('Map elementId was not provided. Map initialization failed.', 'error', 'ADX.serviceMap.initialize');
return;
}
if (!ADX.settings.mapSettings.key && !(ADX.settings.mapSettings.key === "")) {
throw Error;
}
_searchActionURL = searchActionUrl;
... | {
// clear the inputs
$("#location-query").val('');
$("#dateFrom").val('');
$("#dateTo").val('');
$("#datesFilter").hide();
$("#searchOptions #dates").removeAttr("selected");
$("#searchOptions #status").removeAttr("selected");
$("#searchOptions #priority").removeAttr("selected");
$("#searchOptions #t... | setSearchOptions() | identifier_name |
servicemap.js | , autosize) {
if (!elementId && elementId != '') {
log('Map elementId was not provided. Map initialization failed.', 'error', 'ADX.serviceMap.initialize');
return;
}
if (!ADX.settings.mapSettings.key && !(ADX.settings.mapSettings.key === "")) {
throw Error;
}
_searchActionURL = searchActionUrl;
... | } else {
alert("sorry that address cannot be found");
}
});
}
var dateFilterCode = parseInt($("#searchOptions #dates option:selected").val());
var dateFrom = $("#dateFrom").val();
var dateTo = $("#dateTo").val();
if ($("#searchOptions #dates option[value='3']").is(":checked")) {
... | map.setView({ bounds: viewBoundaries}); | random_line_split |
servicemap.js | , autosize) {
if (!elementId && elementId != '') {
log('Map elementId was not provided. Map initialization failed.', 'error', 'ADX.serviceMap.initialize');
return;
}
if (!ADX.settings.mapSettings.key && !(ADX.settings.mapSettings.key === "")) {
throw Error;
}
_searchActionURL = searchActionUrl;
... | var width = getWidth();
var height = getHeight();
_mapOptions.width = width;
_mapOptions.height = height;
map.setOptions({ height: height, width: width });
}
function getHeight() {
var minHeight = 240;
var setHeight = ADX.settings.mapSettings.height || minHeight;
return setHeight < minHeight ? min... | map = _map;
}
| conditional_block |
servicemap.js | , autosize) {
if (!elementId && elementId != '') {
log('Map elementId was not provided. Map initialization failed.', 'error', 'ADX.serviceMap.initialize');
return;
}
if (!ADX.settings.mapSettings.key && !(ADX.settings.mapSettings.key === "")) {
throw Error;
}
_searchActionURL = searchActionUrl;
... | function reset() {
resetMapView();
resetSearchOptions();
mapIt();
}
function resetMapView() {
var map = null;
if (_map == null) {
map = getMap();
} else {
map = _map;
}
map.entities.clear();
map.setView(_mapViewOptions);
}
function resetSearchOptions() {
// clear the inputs
$("#locat... | $("<div id='mapStatus' style='display:none; border: 1px solid #333; padding: 5px; background: #fff; position: absolute; left: " + left + "px; top: " + top + "px; z-index: 10000;'><img src='~/xrm-adx/samples/images/loader.gif' alt='Loading' /> <span id='statusText'></span></div>").appendTo(element);
}
| identifier_body |
test_decibel.py | from acoustics.decibel import *
def test_dbsum():
assert(abs(dbsum([10.0, 10.0]) - 13.0103) < 1e-5)
def test_dbmean():
assert(dbmean([10.0, 10.0]) == 10.0)
def test_dbadd():
assert(abs(dbadd(10.0, 10.0) - 13.0103) < 1e-5)
def test_dbsub():
assert(abs(dbsub(13.0103, 10.0) - 10.0) < 1e-5)
def tes... | ():
assert(abs(dbdiv(13.0103, 2) - 10.0) < 1e-5) | test_dbdiv | identifier_name |
test_decibel.py | from acoustics.decibel import *
def test_dbsum():
assert(abs(dbsum([10.0, 10.0]) - 13.0103) < 1e-5)
def test_dbmean():
assert(dbmean([10.0, 10.0]) == 10.0)
def test_dbadd():
assert(abs(dbadd(10.0, 10.0) - 13.0103) < 1e-5)
def test_dbsub():
assert(abs(dbsub(13.0103, 10.0) - 10.0) < 1e-5)
def tes... |
def test_dbdiv():
assert(abs(dbdiv(13.0103, 2) - 10.0) < 1e-5) | assert(abs(dbmul(10.0, 2) - 13.0103) < 1e-5) | identifier_body |
test_decibel.py | from acoustics.decibel import *
def test_dbsum():
assert(abs(dbsum([10.0, 10.0]) - 13.0103) < 1e-5)
def test_dbmean():
assert(dbmean([10.0, 10.0]) == 10.0)
def test_dbadd():
assert(abs(dbadd(10.0, 10.0) - 13.0103) < 1e-5)
def test_dbsub():
assert(abs(dbsub(13.0103, 10.0) - 10.0) < 1e-5)
def tes... |
def test_dbdiv():
assert(abs(dbdiv(13.0103, 2) - 10.0) < 1e-5) | random_line_split | |
halo_session.py | import base64
import httplib
import json
import os
import re
import ssl
import urllib
from urlparse import urlunsplit
from exceptions import CloudPassageAuthentication
class HaloSession(object):
"""All Halo API session management happens in this object.
Args:
key(str): Halo API key
secret(str... | (self, endpoint):
"""Build a URL from parts."""
url = urlunsplit(("https", self.api_host, endpoint, "", ""))
return url
@classmethod
def get_sdk_version(cls):
here_dir = os.path.abspath(os.path.dirname(__file__))
init_file_path = os.path.join(here_dir, "__init__.py")
... | build_url | identifier_name |
halo_session.py | import base64
import httplib
import json
import os
import re
import ssl
import urllib
from urlparse import urlunsplit
from exceptions import CloudPassageAuthentication
class HaloSession(object):
"""All Halo API session management happens in this object.
Args:
key(str): Halo API key
secret(str... | self.sdk_version_string = "Halo-Python-SDK-slim/%s" % self.sdk_version
self.integration_string = ''
self.cert_file = None
if "api_host" in kwargs:
self.api_host = kwargs["api_host"]
if "cert_file" in kwargs:
self.cert_file = kwargs["cert_file"]
if ... | self.key = halo_key
self.secret = halo_secret
self.api_host = "api.cloudpassage.com"
self.sdk_version = self.get_sdk_version() | random_line_split |
halo_session.py | import base64
import httplib
import json
import os
import re
import ssl
import urllib
from urlparse import urlunsplit
from exceptions import CloudPassageAuthentication
class HaloSession(object):
"""All Halo API session management happens in this object.
Args:
key(str): Halo API key
secret(str... |
self.user_agent = self.build_ua_string(self.sdk_version_string,
self.integration_string)
self.threads = 10
self.api_token = None
def authenticate(self):
"""Obtain and set an oauth API token."""
headers = self.build_auth_headers... | self.integration_string = kwargs["integration_string"] | conditional_block |
halo_session.py | import base64
import httplib
import json
import os
import re
import ssl
import urllib
from urlparse import urlunsplit
from exceptions import CloudPassageAuthentication
class HaloSession(object):
"""All Halo API session management happens in this object.
Args:
key(str): Halo API key
secret(str... |
@classmethod
def build_ua_string(cls, sdk_version_str, integration_string):
ua = "{sdk} {integration}".format(sdk=sdk_version_str,
integration=integration_string)
return ua
def build_url(self, endpoint):
"""Build a URL from parts."""
... | """This builds the header, required for all API interaction."""
if self.api_token is None:
self.authenticate()
authstring = "Bearer " + self.api_token
header = {"Authorization": authstring,
"Content-Type": "application/json",
"User-Agent": self.use... | identifier_body |
writer.rs | use std::fs::OpenOptions;
use std::io::Result;
use std::path::Path;
use byteorder::{ BigEndian, LittleEndian, WriteBytesExt };
pub fn | (filename: &str, samples: Vec<i16>) -> Result<()> {
let path = Path::new(filename);
let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&path));
for &sample in samples.iter() {
try!(f.write_i16::<LittleEndian>(sample));
}
Ok(())
}
// See: https://ccrma.stanfor... | write_pcm | identifier_name |
writer.rs | use std::fs::OpenOptions;
use std::io::Result;
use std::path::Path;
use byteorder::{ BigEndian, LittleEndian, WriteBytesExt };
pub fn write_pcm(filename: &str, samples: Vec<i16>) -> Result<()> {
let path = Path::new(filename);
let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&p... | let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&path));
// Some WAV header fields
let channels = 1;
let bit_depth = 16;
let subchunk_2_size = samples.len() * channels * bit_depth / 8;
let chunk_size = 36 + subchunk_2_size as i32;
let byte_rate = (sample_rat... | }
// See: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
pub fn write_wav(filename: &str, sample_rate: usize, samples: Vec<i16>) -> Result<()> {
let path = Path::new(filename); | random_line_split |
writer.rs | use std::fs::OpenOptions;
use std::io::Result;
use std::path::Path;
use byteorder::{ BigEndian, LittleEndian, WriteBytesExt };
pub fn write_pcm(filename: &str, samples: Vec<i16>) -> Result<()> |
// See: https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
pub fn write_wav(filename: &str, sample_rate: usize, samples: Vec<i16>) -> Result<()> {
let path = Path::new(filename);
let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&path));
// Some WAV header fields
... | {
let path = Path::new(filename);
let mut f = try!(OpenOptions::new().write(true).truncate(true).create(true).open(&path));
for &sample in samples.iter() {
try!(f.write_i16::<LittleEndian>(sample));
}
Ok(())
} | identifier_body |
loyalty-outlined.js | import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58s1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41s-.23-1.06-.59-1.42zM13 20.01L4... | d: "M8.9 12.55c0 .57.23 1.07.6 1.45l3.5 3.5 3.5-3.5c.37-.37.6-.89.6-1.45 0-1.13-.92-2.05-2.05-2.05-.57 0-1.08.23-1.45.6l-.6.6-.6-.59c-.37-.38-.89-.61-1.45-.61-1.13 0-2.05.92-2.05 2.05z"
})), 'LoyaltyOutlined'); | }), h("circle", {
cx: "6.5",
cy: "6.5",
r: "1.5"
}), h("path", { | random_line_split |
models.py | from django.db import models
from constituencies.models import Constituency
from uk_political_parties.models import Party
from elections.models import Election
class Person(models.Model):
name = models.CharField(blank=False, max_length=255)
remote_id = models.CharField(blank=True, max_length=255, null=True)... | (models.Model):
person = models.ForeignKey(Person)
party = models.ForeignKey(Party)
membership_start = models.DateField()
membership_end = models.DateField(null=True)
class PersonConstituencies(models.Model):
person = models.ForeignKey(Person)
constituency = models.ForeignKey(Constituency)
... | PartyMemberships | identifier_name |
models.py | from django.db import models
from constituencies.models import Constituency
from uk_political_parties.models import Party
from elections.models import Election
class Person(models.Model):
name = models.CharField(blank=False, max_length=255)
remote_id = models.CharField(blank=True, max_length=255, null=True)... |
class PersonConstituencies(models.Model):
person = models.ForeignKey(Person)
constituency = models.ForeignKey(Constituency)
election = models.ForeignKey(Election)
| person = models.ForeignKey(Person)
party = models.ForeignKey(Party)
membership_start = models.DateField()
membership_end = models.DateField(null=True) | identifier_body |
models.py | from django.db import models
from constituencies.models import Constituency
from uk_political_parties.models import Party |
class Person(models.Model):
name = models.CharField(blank=False, max_length=255)
remote_id = models.CharField(blank=True, max_length=255, null=True)
source_url = models.URLField(blank=True, null=True)
source_name = models.CharField(blank=True, max_length=100)
image_url = models.URLField(blank=True... | from elections.models import Election
| random_line_split |
models.py | from django.db import models
from constituencies.models import Constituency
from uk_political_parties.models import Party
from elections.models import Election
class Person(models.Model):
name = models.CharField(blank=False, max_length=255)
remote_id = models.CharField(blank=True, max_length=255, null=True)... |
@property
def current_election(self):
return self.elections.filter(active=True)[0]
@property
def current_constituency(self):
return self.constituencies.filter(
personconstituencies__election=self.current_election)[0]
def __unicode__(self):
return "%s (%s)" % (... | return parties[0] | conditional_block |
toggle.rs | use iup_sys;
use std::ptr;
use std::ffi::CString;
use Element;
| /// [1]: http://webserver2.tecgraf.puc-rio.br/iup/en/elem/iuptoggle.html
pub struct Toggle(*mut iup_sys::Ihandle);
impl Toggle {
/// Creates a toggle with no text.
pub fn new() -> Toggle {
unsafe { Toggle::from_raw(iup_sys::IupToggle(ptr::null_mut(), ptr::null_mut())) }
}
/// Creates a toggle ... | /// See the [IUP Toggle Documentation][1]. | random_line_split |
toggle.rs | use iup_sys;
use std::ptr;
use std::ffi::CString;
use Element;
/// See the [IUP Toggle Documentation][1].
/// [1]: http://webserver2.tecgraf.puc-rio.br/iup/en/elem/iuptoggle.html
pub struct Toggle(*mut iup_sys::Ihandle);
impl Toggle {
/// Creates a toggle with no text.
pub fn new() -> Toggle |
/// Creates a toggle with the specified text.
pub fn with_title<S: Into<String>>(title: S) -> Toggle {
let ctitle = CString::new(title.into()).unwrap();
unsafe { Toggle::from_raw(iup_sys::IupToggle(ctitle.as_ptr(), ptr::null_mut())) }
}
}
impl_widget!(Toggle, "toggle");
impl ::callback::M... | {
unsafe { Toggle::from_raw(iup_sys::IupToggle(ptr::null_mut(), ptr::null_mut())) }
} | identifier_body |
toggle.rs | use iup_sys;
use std::ptr;
use std::ffi::CString;
use Element;
/// See the [IUP Toggle Documentation][1].
/// [1]: http://webserver2.tecgraf.puc-rio.br/iup/en/elem/iuptoggle.html
pub struct Toggle(*mut iup_sys::Ihandle);
impl Toggle {
/// Creates a toggle with no text.
pub fn | () -> Toggle {
unsafe { Toggle::from_raw(iup_sys::IupToggle(ptr::null_mut(), ptr::null_mut())) }
}
/// Creates a toggle with the specified text.
pub fn with_title<S: Into<String>>(title: S) -> Toggle {
let ctitle = CString::new(title.into()).unwrap();
unsafe { Toggle::from_raw(iup_s... | new | identifier_name |
sprited_animation.js | /*
Copyright 2013 The Camlistore Authors
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, soft... | componentWillUnmount: function() {
window.clearInterval(this.timerId_);
},
render: function() {
return cam.SpritedImage(cam.object.extend(this.props, {index: this.state.index}));
}
}); | },
| random_line_split |
reservation.js | import React, {Component} from 'react';
import {View, Text} from 'react-native';
import {xdateToData} from '../../interface';
import XDate from 'xdate';
import dateutils from '../../dateutils';
import styleConstructor from './style';
class ReservationListItem extends Component {
constructor(props) {
super(props)... |
return changed;
}
renderDate(date, item) {
if (this.props.renderDay) {
return this.props.renderDay(date ? xdateToData(date) : undefined, item);
}
const today = dateutils.sameDate(date, XDate()) ? this.styles.today : undefined;
if (date) {
return (
<View style={this.styles.d... | {
if (r1.day.getTime() !== r2.day.getTime()) {
changed = true;
} else if (!r1.reservation && !r2.reservation) {
changed = false;
} else if (r1.reservation && r2.reservation) {
if ((!r1.date && !r2.date) || (r1.date && r2.date)) {
changed = this.props.rowHasChanged(r1.... | conditional_block |
reservation.js | import React, {Component} from 'react';
import {View, Text} from 'react-native';
import {xdateToData} from '../../interface';
import XDate from 'xdate';
import dateutils from '../../dateutils';
import styleConstructor from './style';
class ReservationListItem extends Component {
constructor(props) {
super(props)... | <View style={{flex:1}}>
{content}
</View>
</View>
);
}
}
export default ReservationListItem; | return (
<View style={this.styles.container}>
{this.renderDate(date, reservation)} | random_line_split |
reservation.js | import React, {Component} from 'react';
import {View, Text} from 'react-native';
import {xdateToData} from '../../interface';
import XDate from 'xdate';
import dateutils from '../../dateutils';
import styleConstructor from './style';
class ReservationListItem extends Component {
constructor(props) |
shouldComponentUpdate(nextProps) {
const r1 = this.props.item;
const r2 = nextProps.item;
let changed = true;
if (!r1 && !r2) {
changed = false;
} else if (r1 && r2) {
if (r1.day.getTime() !== r2.day.getTime()) {
changed = true;
} else if (!r1.reservation && !r2.reserva... | {
super(props);
this.styles = styleConstructor(props.theme);
} | identifier_body |
reservation.js | import React, {Component} from 'react';
import {View, Text} from 'react-native';
import {xdateToData} from '../../interface';
import XDate from 'xdate';
import dateutils from '../../dateutils';
import styleConstructor from './style';
class ReservationListItem extends Component {
constructor(props) {
super(props)... | (nextProps) {
const r1 = this.props.item;
const r2 = nextProps.item;
let changed = true;
if (!r1 && !r2) {
changed = false;
} else if (r1 && r2) {
if (r1.day.getTime() !== r2.day.getTime()) {
changed = true;
} else if (!r1.reservation && !r2.reservation) {
changed =... | shouldComponentUpdate | identifier_name |
fc_zone_manager.py | # (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack Foundation
#
# 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, target_wwn_list):
"""SAN lookup for end devices.
Look up each SAN configured and return a map of SAN (fabric IP)
to list of target WWNs visible to the fabric.
"""
fabric_map = self.driver.get_san_context(target_wwn_list)
LOG.debug("Got SAN context: %s", fabric_map... | get_san_context | identifier_name |
fc_zone_manager.py | # (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack Foundation
#
# 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
#
# ... |
# update count = count + 1
else:
if count > 1:
t_list.remove(target)
# update count = count - 1
if t_list:
filtered_i_t_map[initiator] = t_list
else:
LOG.info(_LI(... | t_list.remove(target) | conditional_block |
fc_zone_manager.py | # (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack Foundation
#
# 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
#
# ... |
def add_connection(self, initiator_target_map):
"""Add connection control.
Adds connection control for the given initiator target map.
initiator_target_map - each initiator WWN mapped to a list of one
or more target WWN:
eg:
{
'10008c7cff523b01': ['2024... | """Zone management state check.
Performs state check for given I-T pair to return the current count of
active attach for the pair.
"""
# TODO(sk): ref count state management
count = 0
# check the state for I-T pair
return count | identifier_body |
fc_zone_manager.py | # (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack Foundation
#
# 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
#
# ... |
# get SAN context for the target list
fabric_map = self.get_san_context(target_list)
LOG.debug("Fabric Map after context lookup: %s", fabric_map)
# iterate over each SAN and apply connection control
for fabric in fabric_map.keys():
... | connected_fabric = None
try:
for initiator in initiator_target_map.keys():
target_list = initiator_target_map[initiator]
LOG.debug("Target List: %s", target_list) | random_line_split |
campsites.spec.ts | import * as expect from 'expect'
import * as actions from '../../actions/CampsitesActions'
import { Position, Facilities } from '../../libs/types'
describe('campsites actions', () => {
it('addCampsitesJson', () => {
const facilities: Facilities = {
toilets: "none",
picnicTables: false,
barbecue... | const json = {
campsites: [campsite],
parks: [park]
}
const expectedAction = {
type: 'ADD_CAMPSITES_JSON',
json: json
}
expect(actions.addCampsitesJson(json)).toEqual(expectedAction)
})
}) | id: 1,
name: "A park",
description: "A nice park",
campsite_ids: [1]
} | random_line_split |
main.rs | #![feature(globs)]
extern crate graphics;
extern crate piston;
// extern crate sdl2_game_window;
extern crate glfw_game_window; |
// use Window = sdl2_game_window::GameWindowSDL2;
use Window = glfw_game_window::GameWindowGLFW;
use piston::{
Game,
GameIteratorSettings,
GameWindowSettings,
UpdateArgs,
RenderArgs,
KeyPressArgs,
KeyReleaseArgs,
MousePressArgs,
MouseReleaseArgs,
MouseMoveArgs,
MouseRelative... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.