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 |
|---|---|---|---|---|
trial.py | #! /usr/python
'''
///////////////////////////////////////////////////////////
// Permission is hereby granted, free of charge,
// to any person obtaining a copy of
// this software and associated documentation files
// (the "Software"), to deal in the Software without
// restriction, including without limitation... | (self):
GPIO.output(self.feeder, True) #reset feeder ????
GPIO.output(self.notfeeder, True) #reset notfeeder ????
GPIO.cleanup() #reset all GPIOs
pygame.quit()
exit()
def mainLoop(self, camera):
## hang until assigned start time
while time.time()<self.start:... | safeQuit | identifier_name |
trial.py | #! /usr/python
'''
///////////////////////////////////////////////////////////
// Permission is hereby granted, free of charge,
// to any person obtaining a copy of
// this software and associated documentation files
// (the "Software"), to deal in the Software without
// restriction, including without limitation... |
def mainLoop(self, camera):
## hang until assigned start time
while time.time()<self.start:
print time.time()-self.start
pass
## start timer
self.startT = time.time()
fed = False # feed delay control variable
## start recording
if cam... | GPIO.output(self.feeder, True) #reset feeder ????
GPIO.output(self.notfeeder, True) #reset notfeeder ????
GPIO.cleanup() #reset all GPIOs
pygame.quit()
exit() | identifier_body |
trial.py | #! /usr/python
'''
///////////////////////////////////////////////////////////
// Permission is hereby granted, free of charge,
// to any person obtaining a copy of
// this software and associated documentation files
// (the "Software"), to deal in the Software without
// restriction, including without limitation... |
else:
pass
## start camera recording IF attached to Pi and begin mainloop of Trial
if args["camera"]:
T.mainLoop('record')
else:
T.mainLoop('notrecord')
## stop camera recording IF attached to Pi
if args["camera"]:
T.stopRecording()
else:
pass
... | T.cameraInit() | conditional_block |
test_submit_button.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 McKinsey Academy
#
# Authors:
# Jonathan Piacenti <jonathan@opencraft.com>
#
# This software's license gives you freedom; you can copy, convey,
# propagate, redistribute and/or modify this program under the terms of
# the GNU Affero General Public License (AGPL) a... | submit_button = self.get_submit()
submit_button.click()
# Make sure that submit button is disabled right away
self.assertFalse(submit_button.is_enabled())
self.wait_until_clickable(self.browser.find_element_by_css_selector('.poll-voting-thanks'))
# Wait until the ajax r... | @skip("Flaky test")
def test_submit_button(self):
"""
Goal: We have to make sure that submit button gets disabled right
after it is clicked. We cannot test with 100% assurance by adding a
method in other tests such as test_functions.py because in that case
submit button is an... | identifier_body |
test_submit_button.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 McKinsey Academy
#
# Authors:
# Jonathan Piacenti <jonathan@opencraft.com>
#
# This software's license gives you freedom; you can copy, convey,
# propagate, redistribute and/or modify this program under the terms of
# the GNU Affero General Public License (AGPL) a... | (self):
"""
Goal: We have to make sure that submit button gets disabled right
after it is clicked. We cannot test with 100% assurance by adding a
method in other tests such as test_functions.py because in that case
submit button is anyway disabled after the ajax request.
... | test_submit_button | identifier_name |
test_submit_button.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 McKinsey Academy
#
# Authors:
# Jonathan Piacenti <jonathan@opencraft.com>
#
# This software's license gives you freedom; you can copy, convey,
# propagate, redistribute and/or modify this program under the terms of
# the GNU Affero General Public License (AGPL) a... | # When an answer is selected, make sure submit is enabled.
self.wait_until_exists('input[name=poll-submit]:enabled')
submit_button = self.get_submit()
submit_button.click()
# Make sure that submit button is disabled right away
self.assertFalse(submit_button.is_enabled()... | random_line_split | |
rust_base64.rs | use indy_api_types::errors::prelude::*;
use failure::ResultExt;
pub fn encode(doc: &[u8]) -> String {
base64::encode(doc)
}
pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> {
base64::decode(doc)
.context("Invalid base64 sequence")
.context(IndyErrorKind::InvalidStructure)
.map_er... |
#[test]
fn encode_urlsafe_works() {
let result = encode_urlsafe(&[1, 2, 3]);
assert_eq!("AQID", &result);
}
#[test]
fn decode_urlsafe_works() {
let result = decode_urlsafe("AQID");
assert!(result.is_ok(), "Got error");
assert_eq!(&[1, 2, 3], &result.unwrap... | {
let result = decode("AQID");
assert!(result.is_ok(), "Got error");
assert_eq!(&[1, 2, 3], &result.unwrap()[..]);
} | identifier_body |
rust_base64.rs | use indy_api_types::errors::prelude::*;
use failure::ResultExt;
pub fn encode(doc: &[u8]) -> String {
base64::encode(doc)
}
pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> {
base64::decode(doc)
.context("Invalid base64 sequence")
.context(IndyErrorKind::InvalidStructure) |
pub fn encode_urlsafe(doc: &[u8]) -> String {
base64::encode_config(doc, base64::URL_SAFE) //TODO switch to URL_SAFE_NO_PAD
}
pub fn decode_urlsafe(doc: &str) -> Result<Vec<u8>, IndyError> {
base64::decode_config(doc, base64::URL_SAFE_NO_PAD)
.context("Invalid base64URL_SAFE sequence")
.contex... | .map_err(|err| err.into())
} | random_line_split |
rust_base64.rs | use indy_api_types::errors::prelude::*;
use failure::ResultExt;
pub fn encode(doc: &[u8]) -> String {
base64::encode(doc)
}
pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> {
base64::decode(doc)
.context("Invalid base64 sequence")
.context(IndyErrorKind::InvalidStructure)
.map_er... | (doc: &[u8]) -> String {
base64::encode_config(doc, base64::URL_SAFE) //TODO switch to URL_SAFE_NO_PAD
}
pub fn decode_urlsafe(doc: &str) -> Result<Vec<u8>, IndyError> {
base64::decode_config(doc, base64::URL_SAFE_NO_PAD)
.context("Invalid base64URL_SAFE sequence")
.context(IndyErrorKind::Inval... | encode_urlsafe | identifier_name |
IndexDropdown.tsx | import React, { MouseEventHandler, PureComponent } from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import TextInputControlled from 'src/common-ui/components/TextInputControlled'
import { browser } from 'webextension-polyfill-ts'
const styles = require('./IndexDropdown.css')
const searchImg... | () {
return cx(styles.tagDiv, {
[styles.tagDivFromOverview]: this.props.hover,
[styles.tagDivForAnnotations]: this.props.isForAnnotation,
[styles.tagDivForFilter]: !this.props.url,
[styles.tagDivForFilterSB]: this.props.isForSidebar,
[styles.tagDivForS... | mainClass | identifier_name |
IndexDropdown.tsx | import React, { MouseEventHandler, PureComponent } from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import TextInputControlled from 'src/common-ui/components/TextInputControlled'
import { browser } from 'webextension-polyfill-ts'
const styles = require('./IndexDropdown.css')
const searchImg... | }
return placeholder
}
get unit() {
return this.placeholder.toLowerCase()
}
get errMsg() {
return `ERROR: ${this.props.errMsg}`
}
renderError() {
if (!this.props.showError) {
return null
}
return <p className={styles.errMsg}... | placeholder = 'Users'
break
default: | random_line_split |
platform.rs | use crate::{error::ParseError, Database};
use cfg_if::cfg_if;
use std::{convert::TryFrom, ops::Deref};
use url::Url;
cfg_if! {if #[cfg(feature = "with-postgres")]{
use crate::pg::PostgresDB;
}}
cfg_if! {if #[cfg(feature = "with-sqlite")]{
use crate::sqlite::SqliteDB;
}}
cfg_if! {if #[cfg(feature = "with-mysq... | (&mut self) -> &mut Self::Target {
match *self {
#[cfg(feature = "with-postgres")]
DBPlatform::Postgres(ref mut pg) => pg.deref_mut(),
#[cfg(feature = "with-sqlite")]
DBPlatform::Sqlite(ref mut sq) => sq.deref_mut(),
#[cfg(feature = "with-mysql")]
... | deref_mut | identifier_name |
platform.rs | use crate::{error::ParseError, Database};
use cfg_if::cfg_if;
use std::{convert::TryFrom, ops::Deref};
use url::Url;
cfg_if! {if #[cfg(feature = "with-postgres")]{
use crate::pg::PostgresDB;
}}
cfg_if! {if #[cfg(feature = "with-sqlite")]{
use crate::sqlite::SqliteDB;
}}
cfg_if! {if #[cfg(feature = "with-mysq... |
}
pub(crate) enum Platform {
#[cfg(feature = "with-postgres")]
Postgres,
#[cfg(feature = "with-sqlite")]
Sqlite(String),
#[cfg(feature = "with-mysql")]
Mysql,
Unsupported(String),
}
impl<'a> TryFrom<&'a str> for Platform {
type Error = ParseError;
fn try_from(s: &'a str) -> Resul... | {
match *self {
#[cfg(feature = "with-postgres")]
DBPlatform::Postgres(ref mut pg) => pg.deref_mut(),
#[cfg(feature = "with-sqlite")]
DBPlatform::Sqlite(ref mut sq) => sq.deref_mut(),
#[cfg(feature = "with-mysql")]
DBPlatform::Mysql(ref mut... | identifier_body |
platform.rs | use crate::{error::ParseError, Database};
use cfg_if::cfg_if; | use crate::pg::PostgresDB;
}}
cfg_if! {if #[cfg(feature = "with-sqlite")]{
use crate::sqlite::SqliteDB;
}}
cfg_if! {if #[cfg(feature = "with-mysql")]{
use crate::my::MysqlDB;
}}
pub enum DBPlatform {
#[cfg(feature = "with-postgres")]
Postgres(Box<PostgresDB>),
#[cfg(feature = "with-sqlite")]
... | use std::{convert::TryFrom, ops::Deref};
use url::Url;
cfg_if! {if #[cfg(feature = "with-postgres")]{ | random_line_split |
CryptoPlugin.py | # -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2010 Olle Johansson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use,... |
class CryptoPlugin(Plugin):
name = "CryptoPlugin"
author = "Olle Johansson"
description = "Adds some simple crypto commands."
commands = [
dict(
command = ['!reverse'],
handler = 'cmd_reverse',
onevents = ['Message'],
),
dict(
comm... | from plugins.Plugin import * | random_line_split |
CryptoPlugin.py | # -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2010 Olle Johansson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use,... |
else:
dist = -13
return chr(ord(ch) + dist)
| dist = 13 | conditional_block |
CryptoPlugin.py | # -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2010 Olle Johansson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use,... |
def rot13_char(self, ch):
if ch.lower() <= 'm':
dist = 13
else:
dist = -13
return chr(ord(ch) + dist)
| return ''.join( self.rot13_char(ch) for ch in s ) | identifier_body |
CryptoPlugin.py | # -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2010 Olle Johansson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use,... | (Plugin):
name = "CryptoPlugin"
author = "Olle Johansson"
description = "Adds some simple crypto commands."
commands = [
dict(
command = ['!reverse'],
handler = 'cmd_reverse',
onevents = ['Message'],
),
dict(
command = ['!rot13'],
... | CryptoPlugin | identifier_name |
ListMockService.js | /**
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco 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 ... |
if (pageSize) {
requestParams.pageSize = pageSize;
}
if (filters) {
requestParams.filters = filters;
}
// Make an XHR
var serviceUrl = AlfConstants.URL_SERVICECONTEXT + "mockdata/list";
if (Object.keys(re... | {
requestParams.startIndex = startIndex;
} | conditional_block |
ListMockService.js | /**
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco 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 ... | callbackScope: this
});
}
});
}); | random_line_split | |
jquery.autosize.js | autosizejs',
append: '\n',
callback: false,
resizeDelay: 10,
placeholder: true
},
// border:0 is unnecessary, but avoids a bug in Firefox on OSX
copy = '<textarea tabindex="-1" style="position:absolute; top:-999px; left:0; right:auto; bottom:auto; border:0; padding: 0; -moz-box-sizing:content-box; -webkit-b... | () {
var styles = {};
mirrored = ta;
mirror.className = options.className;
mirror.id = options.id;
maxHeight = parseFloat($ta.css('maxHeight'));
// mirror is a duplicate textarea located off-screen that
// is automatically updated to contain the same text as the
// original textarea. ... | initMirror | identifier_name |
jquery.autosize.js | autosizejs',
append: '\n',
callback: false,
resizeDelay: 10,
placeholder: true
},
// border:0 is unnecessary, but avoids a bug in Firefox on OSX
copy = '<textarea tabindex="-1" style="position:absolute; top:-999px; left:0; right:auto; bottom:auto; border:0; padding: 0; -moz-box-sizing:content-box; -webkit-b... | }
function initMirror() {
var styles = {};
mirrored = ta;
mirror.className = options.className;
mirror.id = options.id;
maxHeight = parseFloat($ta.css('maxHeight'));
// mirror is a duplicate textarea located off-screen that
// is automatically updated to contain the same text as the... | mirror.style.width = Math.max(width,0) + 'px'; | random_line_split |
jquery.autosize.js | autosizejs',
append: '\n',
callback: false,
resizeDelay: 10,
placeholder: true
},
// border:0 is unnecessary, but avoids a bug in Firefox on OSX
copy = '<textarea tabindex="-1" style="position:absolute; top:-999px; left:0; right:auto; bottom:auto; border:0; padding: 0; -moz-box-sizing:content-box; -webkit-b... | }
function initMirror() {
var styles = {};
mirrored = ta;
mirror.className = options.className;
mirror.id = options.id;
maxHeight = parseFloat($ta.css('maxHeight'));
// mirror is a duplicate textarea located off-screen that
// is automatically updated to contain the same text as th... | {
var width;
var style = window.getComputedStyle ? window.getComputedStyle(ta, null) : false;
if (style) {
width = ta.getBoundingClientRect().width;
if (width === 0 || typeof width !== 'number') {
width = parseFloat(style.width);
}
$.each(['paddingLeft', 'paddingRight', 'border... | identifier_body |
jquery.autosize.js | autosizejs',
append: '\n',
callback: false,
resizeDelay: 10,
placeholder: true
},
// border:0 is unnecessary, but avoids a bug in Firefox on OSX
copy = '<textarea tabindex="-1" style="position:absolute; top:-999px; left:0; right:auto; bottom:auto; border:0; padding: 0; -moz-box-sizing:content-box; -webkit-b... |
mirror.style.width = Math.max(width,0) + 'px';
}
function initMirror() {
var styles = {};
mirrored = ta;
mirror.className = options.className;
mirror.id = options.id;
maxHeight = parseFloat($ta.css('maxHeight'));
// mirror is a duplicate textarea located off-screen that
// is ... | {
width = $ta.width();
} | conditional_block |
remote-builder-certs.js |
Object.defineProperty(exports, "__esModule", {
value: true
});
// noinspection SpellCheckingInspection
const ELECTRON_BUILD_SERVICE_LOCAL_CA_CERT = exports.ELECTRON_BUILD_SERVICE_LOCAL_CA_CERT = Buffer.from(`-----BEGIN CERTIFICATE-----
MIIBiDCCAS+gAwIBAgIRAPHSzTRLcN2nElhQdaRP47IwCgYIKoZIzj0EAwIwJDEi
MCAGA1UEAxMZZWxl... | "use strict"; | random_line_split | |
issue-2216.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | 'quux: loop {
if 1 == 2 {
break 'foo;
}
else {
break 'bar;
}
}
continue 'foo;
}
x = 42;
break;
}
println!("{:?}", x);
assert_eq!(x, 42);
} |
'foo: loop {
'bar: loop { | random_line_split |
issue-2216.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert_eq!(x, 42);
}
| {
let mut x = 0;
'foo: loop {
'bar: loop {
'quux: loop {
if 1 == 2 {
break 'foo;
}
else {
break 'bar;
}
}
continue 'foo;
}
x = 42;
break;
... | identifier_body |
issue-2216.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
else {
break 'bar;
}
}
continue 'foo;
}
x = 42;
break;
}
println!("{:?}", x);
assert_eq!(x, 42);
}
| {
break 'foo;
} | conditional_block |
issue-2216.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut x = 0;
'foo: loop {
'bar: loop {
'quux: loop {
if 1 == 2 {
break 'foo;
}
else {
break 'bar;
}
}
continue 'foo;
}
x = 42;
break... | main | identifier_name |
badge.ts | import * as Router from 'koa-router'
import * as moment from 'moment'
import { get } from 'lodash'
import { QueryOptions } from '../route'
import { BlockchainService } from '../../domainService'
import { WorkRoute } from './work'
interface Badge {
readonly workId: string,
readonly datePublished: string
}
export ... | () {
return `
<html><head><style> body,html,div { margin: 0; padding: 0 }</style><link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"></head>
<body> <div style=" width: 165px; height: 50px; background-color: white; font-family: Roboto; font-size: 12px; border: 1px solid #CDCDCD; ... | getBadgeHTMLEmpty | identifier_name |
badge.ts | import * as Router from 'koa-router'
import * as moment from 'moment'
import { get } from 'lodash'
import { QueryOptions } from '../route'
import { BlockchainService } from '../../domainService'
import { WorkRoute } from './work'
interface Badge {
readonly workId: string,
readonly datePublished: string
}
export ... | addRoutes(router: Router): any {
router.get('/badge', this.getBadgeRoute.bind(this))
}
} | random_line_split | |
badge.ts | import * as Router from 'koa-router'
import * as moment from 'moment'
import { get } from 'lodash'
import { QueryOptions } from '../route'
import { BlockchainService } from '../../domainService'
import { WorkRoute } from './work'
interface Badge {
readonly workId: string,
readonly datePublished: string
}
export ... |
}
| {
router.get('/badge', this.getBadgeRoute.bind(this))
} | identifier_body |
dns_sd.rs | // Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed... |
fn service_info(&self, name: Name) -> ServiceInfoFuture {
let this = self.clone();
let ptr_future = async move { this.txt_lookup(name).await };
ServiceInfoFuture(Box::pin(ptr_future))
}
}
/// A DNS Service Discovery future of Services discovered through the list operation
pub struct... | {
let this = self.clone();
let ptr_future = async move {
let options = DnsRequestOptions {
expects_multiple_responses: true,
};
this.inner_lookup(name, RecordType::PTR, options).await
};
ListServicesFuture(Box::pin(ptr_future))
} | identifier_body |
dns_sd.rs | // Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed... | /// https://tools.ietf.org/html/rfc6763#section-6
fn service_info(&self, name: Name) -> ServiceInfoFuture;
}
impl<C: DnsHandle, P: ConnectionProvider<Conn = C>> DnsSdHandle for AsyncResolver<C, P> {
fn list_services(&self, name: Name) -> ListServicesFuture {
let this = self.clone();
let pt... | /// For registered service types, see: https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
fn list_services(&self, name: Name) -> ListServicesFuture;
/// Retrieve service information
/// | random_line_split |
dns_sd.rs | // Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed... | (TxtLookup);
impl ServiceInfo {
/// Returns this as a map, this allocates a new hashmap
///
/// This converts the DNS-SD TXT record into a map following the rules specified in https://tools.ietf.org/html/rfc6763#section-6.4
pub fn to_map<'s>(&'s self) -> HashMap<Cow<'s, str>, Option<Cow<'s, str>>> {
... | ServiceInfo | identifier_name |
basetest_pgt.py | from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import chainer
from chainer import functions as F
from chainer import links as L
from chainer impo... | from __future__ import print_function | random_line_split | |
basetest_pgt.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import chainer
from chainer import functions as F
from chain... | (self, env):
def random_action_func():
a = env.action_space.sample()
if isinstance(a, np.ndarray):
return a.astype(np.float32)
else:
return a
return LinearDecayEpsilonGreedy(1.0, 0.2, 1000, random_action_func)
def make_replay_buffe... | make_explorer | identifier_name |
basetest_pgt.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import chainer
from chainer import functions as F
from chain... |
def make_env_and_successful_return(self, test):
return ABC(discrete=False, deterministic=test), 1
| n_dim_obs = env.observation_space.low.size
n_dim_action = env.action_space.low.size
n_hidden_channels = 50
policy = policies.FCGaussianPolicy(
n_input_channels=n_dim_obs,
n_hidden_layers=2,
n_hidden_channels=n_hidden_channels,
action_size=n_dim_ac... | identifier_body |
basetest_pgt.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import chainer
from chainer import functions as F
from chain... |
return LinearDecayEpsilonGreedy(1.0, 0.2, 1000, random_action_func)
def make_replay_buffer(self, env):
return replay_buffer.ReplayBuffer(10 ** 5)
class _TestPGTOnContinuousPOABC(_TestPGTOnABC):
def make_model(self, env):
n_dim_obs = env.observation_space.low.size
n_dim_actio... | return a | conditional_block |
lto-unwind.rs | // needs-unwind
// no-prefer-dynamic
// ignore-emscripten no processes
// ignore-sgx no processes
use std::process::Command;
use std::env;
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
println!("hurray you ran me");
}
}
fn main() {
let mut args = env::args_os();
let me = args.next()... | // run-pass
#![allow(unused_variables)]
// compile-flags:-C lto -C panic=unwind | random_line_split | |
lto-unwind.rs | // run-pass
#![allow(unused_variables)]
// compile-flags:-C lto -C panic=unwind
// needs-unwind
// no-prefer-dynamic
// ignore-emscripten no processes
// ignore-sgx no processes
use std::process::Command;
use std::env;
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
println!("hurray you ran me");... | {
let mut args = env::args_os();
let me = args.next().unwrap();
if let Some(s) = args.next() {
if &*s == "foo" {
let _bomb = Bomb;
panic!("try to catch me");
}
}
let s = Command::new(env::args_os().next().unwrap()).arg("foo").output();
let s = s.unwrap(... | identifier_body | |
lto-unwind.rs | // run-pass
#![allow(unused_variables)]
// compile-flags:-C lto -C panic=unwind
// needs-unwind
// no-prefer-dynamic
// ignore-emscripten no processes
// ignore-sgx no processes
use std::process::Command;
use std::env;
struct Bomb;
impl Drop for Bomb {
fn | (&mut self) {
println!("hurray you ran me");
}
}
fn main() {
let mut args = env::args_os();
let me = args.next().unwrap();
if let Some(s) = args.next() {
if &*s == "foo" {
let _bomb = Bomb;
panic!("try to catch me");
}
}
let s = Command::new(en... | drop | identifier_name |
lto-unwind.rs | // run-pass
#![allow(unused_variables)]
// compile-flags:-C lto -C panic=unwind
// needs-unwind
// no-prefer-dynamic
// ignore-emscripten no processes
// ignore-sgx no processes
use std::process::Command;
use std::env;
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
println!("hurray you ran me");... |
let s = Command::new(env::args_os().next().unwrap()).arg("foo").output();
let s = s.unwrap();
assert!(!s.status.success());
assert!(String::from_utf8_lossy(&s.stdout).contains("hurray you ran me"));
}
| {
if &*s == "foo" {
let _bomb = Bomb;
panic!("try to catch me");
}
} | conditional_block |
error.js | 'use strict';
const buildType = process.config.target_defaults.default_configuration;
const assert = require('assert');
if (process.argv[2] === 'fatal') {
const binding = require(process.argv[3]);
binding.error.throwFatalError();
return;
}
test(`./build/${buildType}/binding.node`);
test(`./build/${buildType}/bi... | (bindingPath) {
const binding = require(bindingPath);
assert.throws(() => binding.error.throwApiError('test'), function(err) {
return err instanceof Error && err.message.includes('Invalid');
});
assert.throws(() => binding.error.throwJSError('test'), function(err) {
return err instanceof Error && err.... | test | identifier_name |
error.js | 'use strict';
const buildType = process.config.target_defaults.default_configuration;
const assert = require('assert');
if (process.argv[2] === 'fatal') |
test(`./build/${buildType}/binding.node`);
test(`./build/${buildType}/binding_noexcept.node`);
function test(bindingPath) {
const binding = require(bindingPath);
assert.throws(() => binding.error.throwApiError('test'), function(err) {
return err instanceof Error && err.message.includes('Invalid');
});
... | {
const binding = require(process.argv[3]);
binding.error.throwFatalError();
return;
} | conditional_block |
error.js | 'use strict';
const buildType = process.config.target_defaults.default_configuration;
const assert = require('assert');
if (process.argv[2] === 'fatal') {
const binding = require(process.argv[3]);
binding.error.throwFatalError();
return;
}
test(`./build/${buildType}/binding.node`);
test(`./build/${buildType}/bi... | () => binding.error.doNotCatch(
() => {
throw new TypeError('test');
}),
function(err) {
return err instanceof TypeError && err.message === 'test' && !err.caught;
});
assert.throws(
() => binding.error.catchAndRethrowError(
() => {
throw new TypeError('test');
... | {
const binding = require(bindingPath);
assert.throws(() => binding.error.throwApiError('test'), function(err) {
return err instanceof Error && err.message.includes('Invalid');
});
assert.throws(() => binding.error.throwJSError('test'), function(err) {
return err instanceof Error && err.message === 't... | identifier_body |
error.js | 'use strict';
const buildType = process.config.target_defaults.default_configuration;
const assert = require('assert');
if (process.argv[2] === 'fatal') {
const binding = require(process.argv[3]);
binding.error.throwFatalError();
return;
}
test(`./build/${buildType}/binding.node`);
test(`./build/${buildType}/bi... | return err instanceof Error && err.message === 'test' && err.caught;
});
const p = require('./napi_child').spawnSync(
process.execPath, [ __filename, 'fatal', bindingPath ]);
assert.ifError(p.error);
assert.ok(p.stderr.toString().includes(
'FATAL ERROR: Error::ThrowFatalError This is a fatal er... | });
assert.throws(() => binding.error.catchAndRethrowErrorThatEscapesScope('test'), function(err) { | random_line_split |
CharacterScaleChanger.js | してください。
*/
(function() {
'use strict';
var pluginName = 'CharacterScaleChanger';
////=============================================================================
//// Local function
//// These functions checks & formats pluguin's command parameters.
//// I borrowed these functions from Triacontane.Thanks!... | identifier_name | ||
CharacterScaleChanger.js | Scale of the event group for which the "miniCharacter" is specified in the memo filed.
* $gameSystem.changeCharacterScale(0.5, 0.5, 'miniCharacter');
*
* ----symbol----
* In the script $gameSystem.changeCharacterScale(scaleX, scaleY, 'symbol')
* If you do not specify a Symbol Name, "all" is implicitly specified.... | *
* @param ----基本的な設定----
* @desc
* @default
*
*
* @help キャラクターのScaleを一括で変更します。
*
* 【特徴】
* ・キャラクターのScaleを一括で変更します
* ・変更したScaleを取得できます
*
* 【使用方法】
* プラグインの導入後、スクリプトコマンドから使用します。
* また、特定のメモタグが指定されているイベントだけScaleを変更したい場合
* メモ欄の設定が必要になります。
* このメモ欄の指定方法は以下の通りです。
* <scale:区別名>
*
* 例えば「ミニキャラ」で区別したい場合、イベ... | */
/*:ja
* @plugindesc キャラクターのScaleを一括で変更します。
* @author ツミオ | random_line_split |
CharacterScaleChanger.js | してください。
*/
(function() {
'use strict';
var pluginName = 'CharacterScaleChanger';
////=============================================================================
//// Local function
//// These functions checks & formats pluguin's command parameters.
//// I borrowed these functions from Triacontane.Thanks!... | identifier_body | ||
CharacterScaleChanger.js | Scale of the event group for which the "miniCharacter" is specified in the memo filed.
* $gameSystem.changeCharacterScale(0.5, 0.5, 'miniCharacter');
*
* ----symbol----
* In the script $gameSystem.changeCharacterScale(scaleX, scaleY, 'symbol')
* If you do not specify a Symbol Name, "all" is implicitly specified.... | aracterScaleDict()[symbol];
return target ? target.x : 1;
};
//YのScaleを取得する
Game_System.prototype.getCharacterScaleY = function(symbol = Game_Scale.ALL_SYMBOL) {
const target = this.characterScaleDict()[symbol];
return target ? target.y : 1;
};
//Scaleの変更を適用する | _System.prototype.characterScaleDict = function() {
if(!this._characterScaleDict) {
this._characterScaleDict = {};
}
return this._characterScaleDict;
};
//スケールの値の保存と適用を同時におこなう
Game_System.prototype.changeCharacterScale = function(scaleX = 1, scaleY = 1, symbol = Game_Sca... | conditional_block |
lib.rs | // Copyright 2014 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 ... | mod ptr;
mod result;
mod slice;
mod str;
mod tuple; | mod ops;
mod option; | random_line_split |
authentication.guard.spec.ts | import { TestBed, inject } from '@angular/core/testing';
import { Router, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from './authentication.service';
import { MockAuthenticationService } from './authentication.service.mock';
import { AuthenticationGuard } from './authentication.guar... | });
it('should return false and redirect to login if user is not authenticated', () => {
// Arrange
authenticationService.credentials = null;
// Act
const result = authenticationGuard.canActivate(null, mockSnapshot);
// Assert
expect(mockRouter.navigate).toHaveBeenCalledWith(['/login'], {... | it('should return true if user is authenticated', () => {
expect(authenticationGuard.canActivate(null, mockSnapshot)).toBe(true); | random_line_split |
version-branches.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 * as semver from 'semver';
import {GithubClient, GithubRepo} from '../../utils/git/github';
/** Type describi... |
/**
* Gets the version branches for the specified major versions in descending
* order. i.e. latest version branches first.
*/
export async function getBranchesForMajorVersions(
repo: GithubRepoWithApi, majorVersions: number[]): Promise<VersionBranch[]> {
const branchData = await repo.api.paginate(
rep... | {
return semver.parse(branchName.replace(versionBranchNameRegex, '$1.$2.0'));
} | identifier_body |
version-branches.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 * as semver from 'semver';
import {GithubClient, GithubRepo} from '../../utils/git/github';
/** Type describi... |
return parsedVersion;
}
/** Whether the given branch corresponds to a version branch. */
export function isVersionBranch(branchName: string): boolean {
return versionBranchNameRegex.test(branchName);
}
/**
* Converts a given version-branch into a SemVer version that can be used with SemVer
* utilities. e.g. to... | {
throw Error(`Invalid version detected in following branch: ${branchName}.`);
} | conditional_block |
version-branches.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 * as semver from 'semver';
import {GithubClient, GithubRepo} from '../../utils/git/github';
/** Type describi... | * relevant but needed for parsing. SemVer does not allow `x` as patch digit.
*/
export function getVersionForVersionBranch(branchName: string): semver.SemVer|null {
return semver.parse(branchName.replace(versionBranchNameRegex, '$1.$2.0'));
}
/**
* Gets the version branches for the specified major versions in des... | * Converts a given version-branch into a SemVer version that can be used with SemVer
* utilities. e.g. to determine semantic order, extract major digit, compare.
*
* For example `10.0.x` will become `10.0.0` in SemVer. The patch digit is not | random_line_split |
version-branches.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 * as semver from 'semver';
import {GithubClient, GithubRepo} from '../../utils/git/github';
/** Type describi... | (branchName: string): boolean {
return versionBranchNameRegex.test(branchName);
}
/**
* Converts a given version-branch into a SemVer version that can be used with SemVer
* utilities. e.g. to determine semantic order, extract major digit, compare.
*
* For example `10.0.x` will become `10.0.0` in SemVer. The patc... | isVersionBranch | identifier_name |
scripts.js | parent.jQuery(window).load(function() {
parent.jQuery('div.container select', document).change(function () {
change();
});
parent.jQuery('div.container input', document).keyup(function () {
change();
});
});
function change() {
fsi=parseInt(parent.jQuery('#fontsize', document).val(),10);
lh=parseI... | parent.CallBackFont(ff, fs, ss, lh);
} | random_line_split | |
scripts.js |
parent.jQuery(window).load(function() {
parent.jQuery('div.container select', document).change(function () {
change();
});
parent.jQuery('div.container input', document).keyup(function () {
change();
});
});
function | () {
fsi=parseInt(parent.jQuery('#fontsize', document).val(),10);
lh=parseInt(parent.jQuery('#lineheight', document).val(),10);
if (lh==0) lh=Math.round(font_size[fsi][2] * 1.2);
parent.jQuery('div.preview_text', document).html('<p style="font-size:' + font_size[fsi][2] + 'px; line-height:' + lh + 'px; fon... | change | identifier_name |
scripts.js |
parent.jQuery(window).load(function() {
parent.jQuery('div.container select', document).change(function () {
change();
});
parent.jQuery('div.container input', document).keyup(function () {
change();
});
});
function change() {
fsi=parseInt(parent.jQuery('#fontsize', document).val(),10);
lh=pars... | {
ff = parent.jQuery('#fontfamily', document).val();
fsi=parseInt(parent.jQuery('#fontsize', document).val(),10);
fs=font_size[fsi][1];
ss=font_size[fsi][2];
lh=parseInt(parent.jQuery('#lineheight', document).val(),10);
parent.CallBackFont(ff, fs, ss, lh);
} | identifier_body | |
test_expr.rs | use common::util::*;
#[test]
fn test_simple_arithmetic() {
new_ucmd!().args(&["1", "+", "1"]).run().stdout_is("2\n");
new_ucmd!().args(&["1", "-", "1"]).run().stdout_is("0\n");
new_ucmd!().args(&["3", "*", "2"]).run().stdout_is("6\n");
new_ucmd!().args(&["4", "/", "2"]).run().stdout_is("2\n");
} | fn test_parenthesis() {
new_ucmd!().args(&["(", "1", "+", "1", ")", "*", "2"]).run().stdout_is("4\n");
}
#[test]
fn test_or() {
new_ucmd!().args(&["0", "|", "foo"]).run().stdout_is("foo\n");
new_ucmd!().args(&["foo", "|", "bar"]).run().stdout_is("foo\n");
}
#[test]
fn test_and() {
new_ucmd!().args(&[... |
#[test] | random_line_split |
test_expr.rs | use common::util::*;
#[test]
fn | () {
new_ucmd!().args(&["1", "+", "1"]).run().stdout_is("2\n");
new_ucmd!().args(&["1", "-", "1"]).run().stdout_is("0\n");
new_ucmd!().args(&["3", "*", "2"]).run().stdout_is("6\n");
new_ucmd!().args(&["4", "/", "2"]).run().stdout_is("2\n");
}
#[test]
fn test_parenthesis() {
new_ucmd!().args(&["(... | test_simple_arithmetic | identifier_name |
test_expr.rs | use common::util::*;
#[test]
fn test_simple_arithmetic() {
new_ucmd!().args(&["1", "+", "1"]).run().stdout_is("2\n");
new_ucmd!().args(&["1", "-", "1"]).run().stdout_is("0\n");
new_ucmd!().args(&["3", "*", "2"]).run().stdout_is("6\n");
new_ucmd!().args(&["4", "/", "2"]).run().stdout_is("2\n");
}
#... |
#[test]
fn test_and() {
new_ucmd!().args(&["foo", "&", "1"]).run().stdout_is("foo\n");
new_ucmd!().args(&["", "&", "1"]).run().stdout_is("0\n");
}
| {
new_ucmd!().args(&["0", "|", "foo"]).run().stdout_is("foo\n");
new_ucmd!().args(&["foo", "|", "bar"]).run().stdout_is("foo\n");
} | identifier_body |
mod.rs | //! Abstraction of different session APIs.
//!
//! Sessions provide a way for multiple graphical systems to run in parallel by providing
//! mechanisms to switch between and handle device access and permissions for every running
//! instance. They are crucial to allow unprivileged processes to use graphical or input
//... | /// Major number identifying the device
major: u32,
/// Minor number identifying the device
minor: u32,
},
/// The whole session has been activated
ActivateSession,
/// A given device has been activated
ActivateDevice {
/// Major number identifying the device
... | PauseSession,
/// A given device has been paused
PauseDevice { | random_line_split |
mod.rs | //! Abstraction of different session APIs.
//!
//! Sessions provide a way for multiple graphical systems to run in parallel by providing
//! mechanisms to switch between and handle device access and permissions for every running
//! instance. They are crucial to allow unprivileged processes to use graphical or input
//... | (&mut self, path: &Path, flags: OFlag) -> Result<RawFd, Self::Error> {
self.lock().unwrap().open(path, flags)
}
fn close(&mut self, fd: RawFd) -> Result<(), Self::Error> {
self.lock().unwrap().close(fd)
}
fn change_vt(&mut self, vt: i32) -> Result<(), Self::Error> {
self.lock()... | open | identifier_name |
mod.rs | //! Abstraction of different session APIs.
//!
//! Sessions provide a way for multiple graphical systems to run in parallel by providing
//! mechanisms to switch between and handle device access and permissions for every running
//! instance. They are crucial to allow unprivileged processes to use graphical or input
//... |
fn is_active(&self) -> bool {
self.borrow().is_active()
}
fn seat(&self) -> String {
self.borrow().seat()
}
}
impl<S: Session> Session for Arc<Mutex<S>> {
type Error = S::Error;
fn open(&mut self, path: &Path, flags: OFlag) -> Result<RawFd, Self::Error> {
self.lock()... | {
self.borrow_mut().change_vt(vt)
} | identifier_body |
runESLint.js | const { yellow, cyan, gray } = require('chalk');
const EslintCLI = require('eslint').CLIEngine;
const eslintConfig = require('../config/eslint/eslintConfig');
const runESLint = ({ fix = false, paths }) =>
new Promise((resolve, reject) => {
console.log(cyan(`${fix ? 'Fixing' : 'Checking'} code with ESLint`));
... | try {
const report = cli.executeOnFiles(filteredFilePaths);
if (fix) {
EslintCLI.outputFixes(report);
} else {
const { errorCount, warningCount, results } = report;
if (errorCount || warningCount) {
const formatter = cli.getFormatter();
... | console.log(gray(`Paths: ${filteredFilePaths.join(' ')}`)); | random_line_split |
runESLint.js | const { yellow, cyan, gray } = require('chalk');
const EslintCLI = require('eslint').CLIEngine;
const eslintConfig = require('../config/eslint/eslintConfig');
const runESLint = ({ fix = false, paths }) =>
new Promise((resolve, reject) => {
console.log(cyan(`${fix ? 'Fixing' : 'Checking'} code with ESLint`));
... |
if (errorCount > 0) {
reject();
}
}
} catch (e) {
if (e && e.message && e.message.includes('No files matching')) {
console.warn(yellow(`Warning: ${e.message}`));
} else {
reject(e);
}
}
}
resolve();
});
module.... | {
const formatter = cli.getFormatter();
console.log(formatter(results));
} | conditional_block |
ram_filter.py | # Copyright (c) 2011 OpenStack Foundation
# Copyright (c) 2012 Cloudscaling
# 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/l... | (self, host_state, filter_properties):
raise NotImplementedError
def host_passes(self, host_state, filter_properties):
"""Only return hosts with sufficient available RAM."""
instance_type = filter_properties.get('instance_type')
requested_ram = instance_type['memory_mb']
fre... | _get_ram_allocation_ratio | identifier_name |
ram_filter.py | # Copyright (c) 2011 OpenStack Foundation
# Copyright (c) 2012 Cloudscaling
# 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/l... |
# save oversubscription limit for compute node to test against:
host_state.limits['memory_mb'] = memory_mb_limit
return True
class RamFilter(BaseRamFilter):
"""Ram Filter with over subscription flag."""
ram_allocation_ratio = CONF.ram_allocation_ratio
def _get_ram_allocation_rat... | LOG.debug("%(host_state)s does not have %(requested_ram)s MB "
"usable ram, it only has %(usable_ram)s MB usable ram.",
{'host_state': host_state,
'requested_ram': requested_ram,
'usable_ram': usable_ram})
return False | conditional_block |
ram_filter.py | # Copyright (c) 2011 OpenStack Foundation
# Copyright (c) 2012 Cloudscaling
# 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/l... | aggregate_vals = utils.aggregate_values_from_db(
filter_properties['context'],
host_state.host,
'ram_allocation_ratio')
try:
ratio = utils.validate_num_values(
aggregate_vals, CONF.ram_allocation_ratio, cast_to=float)
except ValueError as ... | identifier_body | |
ram_filter.py | # Copyright (c) 2011 OpenStack Foundation
# Copyright (c) 2012 Cloudscaling
# 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/l... | used_ram_mb = total_usable_ram_mb - free_ram_mb
usable_ram = memory_mb_limit - used_ram_mb
if not usable_ram >= requested_ram:
LOG.debug("%(host_state)s does not have %(requested_ram)s MB "
"usable ram, it only has %(usable_ram)s MB usable ram.",
... | random_line_split | |
css.js | var fs = require('fs'),
path = require('path'),
cleanCSS = require('clean-css'),
rjs = require('requirejs');
module.exports = function(grunt) {
// **css* task works pretty much the same as grunt's min task. The task
// target is the destination, data is an array of glob patterns. These
// files are conc... | grunt.registerHelper('mincss', function(files, o) {
o = o || {};
files = grunt.file.expandFiles(files);
return files.map(function(filepath) {
var content = grunt.file.read(filepath);
return o.nocompress ? content : cleanCSS.process(content);
}).join('');
});
// **rjs:optimize:css** is... | //
// **mincss** basic utility to concat CSS files and run them through
// [cleanCSS](https://github.com/GoalSmashers/clean-css), might opt to use
// [https://github.com/jzaefferer/grunt-css] plugin.
// | random_line_split |
css.js |
var fs = require('fs'),
path = require('path'),
cleanCSS = require('clean-css'),
rjs = require('requirejs');
module.exports = function(grunt) {
// **css* task works pretty much the same as grunt's min task. The task
// target is the destination, data is an array of glob patterns. These
// files are con... |
options.cssIn = file;
options.out = options.out || file;
options.optimizeCss = 'standard.keepComments.keepLines';
var before = grunt.file.read(file);
rjs.optimize(options, function() {
grunt.helper('min_max_info', grunt.file.read(file), before);
cb();
});
});
};
| { cb = options; options = {}; } | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
"""
Test suite for django-staticshard.
"""
import uuid
from urlparse import urlparse
from django.conf import settings
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from ..settings import STATICSHARD_HOSTS
from ..utils import get_absolute_url
class S... | urls.append(url)
self.assertEqual(urls[0], urls[1])
self.assertEqual(urls[0], urls[2])
self.assertEqual(urls[0], urls[3])
self.assertEqual(urls[0], urls[4]) | self.assertNotIn(settings.STATIC_URL, url)
parts = urlparse(url)
self.assertIn(parts.netloc, STATICSHARD_HOSTS) | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
"""
Test suite for django-staticshard.
"""
import uuid
from urlparse import urlparse
from django.conf import settings
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from ..settings import STATICSHARD_HOSTS
from ..utils import get_absolute_url
class S... | """Test case for django-staticshard."""
resources = ['img/%s.jpg' % uuid.uuid4() for i in range(0, 20)]
def test_absolute_url(self):
"""
Test the absolute_url method.
"""
for resource in self.resources:
urls = []
for i in range(0, 5):
... | identifier_body | |
__init__.py | # -*- coding: utf-8 -*-
"""
Test suite for django-staticshard.
"""
import uuid
from urlparse import urlparse
from django.conf import settings
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from ..settings import STATICSHARD_HOSTS
from ..utils import get_absolute_url
class S... | urls = []
for i in range(0, 5):
url = get_absolute_url(resource)
self.assertNotIn(settings.STATIC_URL, url)
parts = urlparse(url)
self.assertIn(parts.netloc, STATICSHARD_HOSTS)
urls.append(url)
self.assertEqual(urls[... | conditional_block | |
__init__.py | # -*- coding: utf-8 -*-
"""
Test suite for django-staticshard.
"""
import uuid
from urlparse import urlparse
from django.conf import settings
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from ..settings import STATICSHARD_HOSTS
from ..utils import get_absolute_url
class | (TestCase):
"""Test case for django-staticshard."""
resources = ['img/%s.jpg' % uuid.uuid4() for i in range(0, 20)]
def test_absolute_url(self):
"""
Test the absolute_url method.
"""
for resource in self.resources:
urls = []
for i in range(0, 5):
... | StaticShardTests | identifier_name |
mod.rs | mod time;
pub use self::time::Time;
use crate::switch::{Packet, Status, Switch};
use std::iter::Iterator;
pub struct Simulator<I: Iterator<Item = Packet>> {
input: I,
switch: Switch,
current_time: Time,
next_packet: Option<Packet>,
}
impl<I: Iterator<Item = Packet>> Iterator for Simulator<I> {
ty... |
}
impl<I: Iterator<Item = Packet>> Simulator<I> {
pub fn new(hyst: Time, idle: Time, input: I) -> Simulator<I> {
let switch = Switch::new(hyst, idle);
Simulator::new_internal(input, switch)
}
pub fn new_explicit(
hyst: Time,
idle: Time,
input: I,
ts: Time,... | {
match self.next_packet {
Some(packet) => {
let arrival_time = packet.arrival();
let res = self.process();
if self.current_time >= arrival_time {
self.next_packet = self.input.next();
if self.next_packet.is_som... | identifier_body |
mod.rs | mod time;
pub use self::time::Time;
use crate::switch::{Packet, Status, Switch};
use std::iter::Iterator;
pub struct Simulator<I: Iterator<Item = Packet>> {
input: I,
switch: Switch,
current_time: Time,
next_packet: Option<Packet>,
}
impl<I: Iterator<Item = Packet>> Iterator for Simulator<I> {
ty... |
}
Some(res)
}
None if self.switch.is_empty() => None,
None => Some(self.process()),
}
}
}
impl<I: Iterator<Item = Packet>> Simulator<I> {
pub fn new(hyst: Time, idle: Time, input: I) -> Simulator<I> {
let switch = Switch::new... | {
self.switch.add_packet(&self.next_packet.unwrap());
} | conditional_block |
mod.rs | mod time;
pub use self::time::Time;
use crate::switch::{Packet, Status, Switch};
use std::iter::Iterator;
pub struct Simulator<I: Iterator<Item = Packet>> {
input: I,
switch: Switch,
current_time: Time,
next_packet: Option<Packet>,
}
impl<I: Iterator<Item = Packet>> Iterator for Simulator<I> {
ty... | ts: Time,
tw: Time,
capacity: f64,
) -> Simulator<I> {
let switch = Switch::new_explicit(hyst, idle, ts, tw, capacity);
Simulator::new_internal(input, switch)
}
fn new_internal(mut input: I, switch: Switch) -> Simulator<I> {
let packet = input.next();
... | input: I, | random_line_split |
mod.rs | mod time;
pub use self::time::Time;
use crate::switch::{Packet, Status, Switch};
use std::iter::Iterator;
pub struct Simulator<I: Iterator<Item = Packet>> {
input: I,
switch: Switch,
current_time: Time,
next_packet: Option<Packet>,
}
impl<I: Iterator<Item = Packet>> Iterator for Simulator<I> {
ty... | (mut input: I, switch: Switch) -> Simulator<I> {
let packet = input.next();
let mut s = Simulator {
input,
current_time: Time(0),
switch,
next_packet: packet,
};
if s.next_packet.is_some() {
s.switch.add_packet(&s.next_packet.u... | new_internal | identifier_name |
root.py | '''
Puck: FreeBSD virtualization guest configuration server
Copyright (C) 2011 The Hotel Communication Network inc.
This program 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 Lic... | (Controller):
crumbs = [Crumb("/", "Home")]
def __init__(self, lookup):
Controller.__init__(self, lookup)
self._lookup = lookup
self._routes = {}
@cherrypy.expose
@cherrypy.tools.myauth()
def index(self):
return self.render("index.html", self.crumbs[:-1])
@cher... | RootController | identifier_name |
root.py | '''
Puck: FreeBSD virtualization guest configuration server
Copyright (C) 2011 The Hotel Communication Network inc.
This program 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 Lic... | fields = ['user.username', 'user.password']
for f in fields:
if not f in post:
cherrypy.session['flash'] = "Invalid form data."
return False
hash_password = Users.hash_password(post['user.password'])
user = Users.fi... | def load(self):
[setattr(self, route, self._routes[route](self._lookup)) for route in self._routes]
def _login(self, post): | random_line_split |
root.py | '''
Puck: FreeBSD virtualization guest configuration server
Copyright (C) 2011 The Hotel Communication Network inc.
This program 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 Lic... |
hash_password = Users.hash_password(post['user.password'])
user = Users.first(username=post['user.username'], password=hash_password)
if not user:
cherrypy.session['flash'] = 'Invalid username or password.'
return False
creds = user.gene... | if not f in post:
cherrypy.session['flash'] = "Invalid form data."
return False | conditional_block |
root.py | '''
Puck: FreeBSD virtualization guest configuration server
Copyright (C) 2011 The Hotel Communication Network inc.
This program 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 Lic... |
def load(self):
[setattr(self, route, self._routes[route](self._lookup)) for route in self._routes]
def _login(self, post):
fields = ['user.username', 'user.password']
for f in fields:
if not f in post:
cherrypy.session['flash'] = "Invalid f... | self._routes[route] = cls | identifier_body |
Stores.js | /**
* Copyright Intermesh
*
* This file is part of Group-Office. You should have received a copy of the
* Group-Office license along with Group-Office. See the file /LICENSE.TXT
*
* If you have questions write an e-mail to info@intermesh.nl
*
* @version $Id: Stores.js 22502 2017-08-30 08:33:43Z mschering $
* @... | url : GO.url('tickets/rate/store'),
fields:['id','name','amount','cost_code']
}); | random_line_split | |
im_context_simple.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use IMContextSimple;
use IsA;
use ffi;
use glib::translate::*;
use std::path::Path;
pub trait I... |
/*fn add_table(&self, data: &[u16], max_seq_len: u32, n_seqs: u32) {
assert!(max_seq_len * n_seqs < data.len() as u32);
unsafe {
ffi::gtk_im_context_simple_add_table(self.to_glib_none().0,
data.to_glib_none().0,
... | {
unsafe {
let compose_file = compose_file.as_ref();
ffi::gtk_im_context_simple_add_compose_file(self.to_glib_none().0, compose_file.to_glib_none().0);
}
} | identifier_body |
im_context_simple.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use IMContextSimple;
use IsA;
use ffi;
use glib::translate::*;
use std::path::Path;
pub trait I... | <P: AsRef<Path>>(&self, compose_file: P) {
unsafe {
let compose_file = compose_file.as_ref();
ffi::gtk_im_context_simple_add_compose_file(self.to_glib_none().0, compose_file.to_glib_none().0);
}
}
/*fn add_table(&self, data: &[u16], max_seq_len: u32, n_seqs: u32) {
... | add_compose_file | identifier_name |
im_context_simple.rs | // Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use IMContextSimple;
use IsA;
use ffi;
use glib::translate::*;
use std::path::Path;
| impl<O: IsA<IMContextSimple>> IMContextSimpleExtManual for O {
fn add_compose_file<P: AsRef<Path>>(&self, compose_file: P) {
unsafe {
let compose_file = compose_file.as_ref();
ffi::gtk_im_context_simple_add_compose_file(self.to_glib_none().0, compose_file.to_glib_none().0);
}... | pub trait IMContextSimpleExtManual {
fn add_compose_file<P: AsRef<Path>>(&self, compose_file: P);
//fn add_table(&self, data: &[u16], max_seq_len: u32, n_seqs: u32);
}
| random_line_split |
tranzdump.py | # -*- coding: utf-8 -*-
import os
import os.path
import re
import sys
import string
from django.apps.registry import apps
from django.core.management.base import BaseCommand, CommandError
from python_translate.extractors import base as extractors
from python_translate import operations
from python_translate.translat... |
if options["no_backup"]:
writer.disable_backup()
if options["force"]:
print(("Writing files to {0}".format(output_dir)))
writer.write_translations(operation.get_result(), options['format'], {
"path": output_dir,
"default_locale": opt... | print(("Displaying messages for domain {0}".format(domain)))
new_keys = list(operation.get_new_messages(domain).keys())
all_keys = list(operation.get_messages(domain).keys())
for id in set(all_keys).difference(new_keys):
print(id)
for ... | conditional_block |
tranzdump.py | # -*- coding: utf-8 -*-
import os
import os.path
import re
import sys
import string
from django.apps.registry import apps
from django.core.management.base import BaseCommand, CommandError
from python_translate.extractors import base as extractors
from python_translate import operations
from python_translate.translat... |
class Formatter(string.Formatter):
def __init__(self):
self.used = set()
def get_value(self, key, args, kwargs):
self.used.add(key)
return AnyFormatSpec()
class Command(BaseCommand):
help = """Extract translation strings from templates from a given location. It can display th... | def __format__(self, fmt):
return '' | identifier_body |
tranzdump.py | # -*- coding: utf-8 -*-
import os
import os.path
import re
import sys
import string
from django.apps.registry import apps
from django.core.management.base import BaseCommand, CommandError
from python_translate.extractors import base as extractors
from python_translate import operations
from python_translate.translat... | (string.Formatter):
def __init__(self):
self.used = set()
def get_value(self, key, args, kwargs):
self.used.add(key)
return AnyFormatSpec()
class Command(BaseCommand):
help = """Extract translation strings from templates from a given location. It can display them or merge
... | Formatter | identifier_name |
tranzdump.py | # -*- coding: utf-8 -*-
import os
import os.path
import re
import sys
import string
from django.apps.registry import apps
from django.core.management.base import BaseCommand, CommandError
from python_translate.extractors import base as extractors
from python_translate import operations
from python_translate.translat... | if options["no_backup"]:
writer.disable_backup()
if options["force"]:
print(("Writing files to {0}".format(output_dir)))
writer.write_translations(operation.get_result(), options['format'], {
"path": output_dir,
"default_locale": optio... | print((bcolors.FAIL + id + bcolors.ENDC))
| random_line_split |
self_named_constructors.rs | #![warn(clippy::self_named_constructors)]
struct | ;
struct ShouldNotSpawn;
impl ShouldSpawn {
pub fn should_spawn() -> ShouldSpawn {
ShouldSpawn
}
fn should_not_spawn() -> ShouldNotSpawn {
ShouldNotSpawn
}
}
impl ShouldNotSpawn {
pub fn new() -> ShouldNotSpawn {
ShouldNotSpawn
}
}
struct ShouldNotSpawnWithTrait;
tra... | ShouldSpawn | identifier_name |
self_named_constructors.rs | #![warn(clippy::self_named_constructors)]
struct ShouldSpawn;
struct ShouldNotSpawn;
impl ShouldSpawn {
pub fn should_spawn() -> ShouldSpawn {
ShouldSpawn
}
| }
impl ShouldNotSpawn {
pub fn new() -> ShouldNotSpawn {
ShouldNotSpawn
}
}
struct ShouldNotSpawnWithTrait;
trait ShouldNotSpawnTrait {
type Item;
}
impl ShouldNotSpawnTrait for ShouldNotSpawnWithTrait {
type Item = Self;
}
impl ShouldNotSpawnWithTrait {
pub fn should_not_spawn_with_tra... | fn should_not_spawn() -> ShouldNotSpawn {
ShouldNotSpawn
} | random_line_split |
address.ts | // @ts-ignore
import Fragment from "ember-data-model-fragments/fragment";
import Store from "@ember-data/store";
import { attr } from "@ember-data/model";
import { computed } from "@ember/object";
import { isBlank } from "@ember/utils";
import { task } from "ember-concurrency-decorators";
import { inject as service } f... | if (isBlank(this.get(requiredField))) {
returnValue = false;
return !returnValue;
}
}
});
}
return returnValue;
}
@task
async loadFormat(): Promise<void> {
if (!this.countryCode) {
if (!this.isBlankModel) {
// no country code is... | random_line_split | |
address.ts | // @ts-ignore
import Fragment from "ember-data-model-fragments/fragment";
import Store from "@ember-data/store";
import { attr } from "@ember-data/model";
import { computed } from "@ember/object";
import { isBlank } from "@ember/utils";
import { task } from "ember-concurrency-decorators";
import { inject as service } f... | (): boolean {
return (
isBlank(this.countryCode) &&
isBlank(this.administrativeArea) &&
isBlank(this.locality) &&
isBlank(this.dependentLocality) &&
isBlank(this.postalCode) &&
isBlank(this.sortingCode) &&
isBlank(this.addressLine1) &&
isBlank(this.addressLine2)
)... | isBlankModel | identifier_name |
address.ts | // @ts-ignore
import Fragment from "ember-data-model-fragments/fragment";
import Store from "@ember-data/store";
import { attr } from "@ember-data/model";
import { computed } from "@ember/object";
import { isBlank } from "@ember/utils";
import { task } from "ember-concurrency-decorators";
import { inject as service } f... |
clear() {
this.countryCode = undefined;
this.administrativeArea = undefined;
this.locality = undefined;
this.dependentLocality = undefined;
this.postalCode = undefined;
this.sortingCode = undefined;
this.addressLine1 = undefined;
this.addressLine2 = undefined;
}
/**
* Returns... | {
this.countryCode = address.countryCode;
this.administrativeArea = address.administrativeArea;
this.locality = address.locality;
this.dependentLocality = address.dependentLocality;
this.postalCode = address.postalCode;
this.sortingCode = address.sortingCode;
this.addressLine1 = address.addr... | identifier_body |
address.ts | // @ts-ignore
import Fragment from "ember-data-model-fragments/fragment";
import Store from "@ember-data/store";
import { attr } from "@ember-data/model";
import { computed } from "@ember/object";
import { isBlank } from "@ember/utils";
import { task } from "ember-concurrency-decorators";
import { inject as service } f... |
});
}
return returnValue;
}
@task
async loadFormat(): Promise<void> {
if (!this.countryCode) {
if (!this.isBlankModel) {
// no country code is chosen, the address must be cleared
this.clear();
this.format = undefined;
}
} else {
if (!this.format |... | {
// @ts-ignore
if (isBlank(this.get(requiredField))) {
returnValue = false;
return !returnValue;
}
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.