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 |
|---|---|---|---|---|
invite_coteachers_modal.tsx | import * as React from 'react'
import * as moment from 'moment'
import { Input, DataTable, } from '../../../Shared/index'
import { requestPost, } from '../../../../modules/request/index.js';
interface InviteCoteachersModalProps {
close: () => void;
onSuccess: (event) => void;
classrooms: Array<any>;
classroom... | {this.renderDataTable()}
</div>
)
}
renderDataTable() {
const { classrooms, coteacher, } = this.props
const { selectedClassroomIds, } = this.state
let possibleClassrooms = classrooms
if (coteacher) {
possibleClassrooms = classrooms.filter(classroom => {
return !cla... | <p>Co-teachers can do everything you can except move or merge students, archive classes, edit activity packs, and access your Premium features.</p>
{this.renderEmailInput()} | random_line_split |
ThingData.js | module.exports = {
// Load Mock Product Data Into localStorage
init: function() {
// localStorage.clear();
localStorage.setItem('thing', JSON.stringify([{
_id:'cbus-254-56-61',
parent:null,
label:'much test'
},
{
_id:'mesh-099',
parent:'voltage',
label:'wow'
... | type:'number',
icon: 'scotch-beer.png',
widget:'Slider'
},
{
_id:'mesh-099.voltage',
thing:'mesh-099',
item:'voltage',
label:'wow',
value:2,
type:'number',
icon: 'scotch-beer.png',
widget:'Slider'
}
]));
}... | random_line_split | |
test_radio_boxes.py | from tests.integration.star_wars import star_wars_test_urls, BLOCK_2_DEFAULT_ANSWERS
from tests.integration.star_wars.star_wars_tests import StarWarsTestCase
class TestEmptyRadioBoxes(StarWarsTestCase):
def test_radio_boxes_mandatory_empty(self):
| # We submit the form
resp = self.submit_page(first_page, BLOCK_2_DEFAULT_ANSWERS)
# There are no validation errors
self.assertRegex(resp.location, star_wars_test_urls.STAR_WARS_QUIZ_2)
summary_url = resp.location
resp = self.navigate_to_page(summary_url)
# Check... | self.login()
first_page = self.start_questionnaire_and_navigate_routing()
# We fill in the survey without a mandatory radio box
# We fill in our answers missing one required field
form_data = BLOCK_2_DEFAULT_ANSWERS.copy()
del form_data['a5dc09e8-36f2-4bf4-97be-c9e6ca8cbe0d']
... | identifier_body |
test_radio_boxes.py | from tests.integration.star_wars import star_wars_test_urls, BLOCK_2_DEFAULT_ANSWERS
from tests.integration.star_wars.star_wars_tests import StarWarsTestCase
class TestEmptyRadioBoxes(StarWarsTestCase):
def test_radio_boxes_mandatory_empty(self):
self.login()
first_page = self.start_questionnai... | # We stay on the current page
content = resp.get_data(True)
self.assertRegex(content, 'Star Wars Quiz')
self.assertRegex(content, 'May the force be with you young EQ developer')
self.assertRegex(content, 'This page has 1 errors')
self.assertRegex(content, 'This field is m... | del form_data['a5dc09e8-36f2-4bf4-97be-c9e6ca8cbe0d']
# We submit the form
resp = self.submit_page(first_page, form_data)
| random_line_split |
test_radio_boxes.py | from tests.integration.star_wars import star_wars_test_urls, BLOCK_2_DEFAULT_ANSWERS
from tests.integration.star_wars.star_wars_tests import StarWarsTestCase
class | (StarWarsTestCase):
def test_radio_boxes_mandatory_empty(self):
self.login()
first_page = self.start_questionnaire_and_navigate_routing()
# We fill in the survey without a mandatory radio box
# We fill in our answers missing one required field
form_data = BLOCK_2_DEFAULT... | TestEmptyRadioBoxes | identifier_name |
user_permission.py | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe.permissions import (get_valid_perms, update_permission_property)
from f... |
def get_user_permissions(user=None):
'''Get all users permissions for the user as a dict of doctype'''
if not user:
user = frappe.session.user
out = frappe.cache().hget("user_permissions", user)
if out is None:
out = {}
try:
for perm in frappe.get_all('User Permission',
fields=['allow', 'for_value'... | frappe.cache().delete_value('user_permissions') | identifier_body |
user_permission.py | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe.permissions import (get_valid_perms, update_permission_property)
from f... |
return out | random_line_split | |
user_permission.py | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe.permissions import (get_valid_perms, update_permission_property)
from f... | (Document):
def on_update(self):
frappe.cache().delete_value('user_permissions')
def on_trash(self): # pylint: disable=no-self-use
frappe.cache().delete_value('user_permissions')
def get_user_permissions(user=None):
'''Get all users permissions for the user as a dict of doctype'''
if not user:
user = frappe... | UserPermission | identifier_name |
user_permission.py | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe.permissions import (get_valid_perms, update_permission_property)
from f... |
out[perm.allow].append(perm.for_value)
if meta.is_nested_set():
out[perm.allow].extend(frappe.db.get_descendants(perm.allow, perm.for_value))
frappe.cache().hset("user_permissions", user, out)
except frappe.SQLError as e:
if e.args[0]==1146:
# called from patch
pass
return out | out[perm.allow] = [] | conditional_block |
CG2-compactNav.js | window.addEventListener( 'DOMContentLoaded', function () {
'use strict';
var i, l;
var $navs = document.querySelectorAll( '.CG2-compactNav' );
if ( $navs.length === 0 ) { return; }
for ( i = 0, l = $navs.length; i < l; i = ( i + 1 )|0 ) {
( function () {
var $nav = $navs[ i ... | ( e ) {
if ( CG2.screenType === 'large' ) { return; }
e.preventDefault();
$nav.classList.toggle( modifier );
}
} )();
}
} );
| toggle | identifier_name |
CG2-compactNav.js | window.addEventListener( 'DOMContentLoaded', function () {
'use strict';
var i, l;
var $navs = document.querySelectorAll( '.CG2-compactNav' );
if ( $navs.length === 0 ) { return; }
for ( i = 0, l = $navs.length; i < l; i = ( i + 1 )|0 ) {
( function () {
var $nav = $navs[ i ... |
} )();
}
} ); |
}
| random_line_split |
CG2-compactNav.js | window.addEventListener( 'DOMContentLoaded', function () {
'use strict';
var i, l;
var $navs = document.querySelectorAll( '.CG2-compactNav' );
if ( $navs.length === 0 ) { return; }
for ( i = 0, l = $navs.length; i < l; i = ( i + 1 )|0 ) {
( function () {
var $nav = $navs[ i ... |
} )();
}
} );
| {
if ( CG2.screenType === 'large' ) { return; }
e.preventDefault();
$nav.classList.toggle( modifier );
} | identifier_body |
CG2-compactNav.js | window.addEventListener( 'DOMContentLoaded', function () {
'use strict';
var i, l;
var $navs = document.querySelectorAll( '.CG2-compactNav' );
if ( $navs.length === 0 ) { return; }
for ( i = 0, l = $navs.length; i < l; i = ( i + 1 )|0 ) {
( function () {
var $nav = $navs[ i ... |
e.preventDefault();
$nav.classList.toggle( modifier );
}
} )();
}
} );
| { return; } | conditional_block |
helpers.ts | import * as fs from 'fs';
import * as tl from 'vsts-task-lib/task';
import * as tr from 'vsts-task-lib/toolrunner';
import * as path from 'path';
import * as Q from 'q';
import * as models from './models';
import * as os from 'os';
import * as ci from './cieventlogger';
const str = require('string');
const uuid = requ... |
logFunction(line);
});
}
public static modifyVsTestConsoleArgsForResponseFile(argument: string): string {
if (argument) {
if (!argument.startsWith('/')) {
return '\"' + argument + '\"';
} else {
// we need to add quotes to arg... | {
return;
} | conditional_block |
helpers.ts | import * as fs from 'fs';
import * as tl from 'vsts-task-lib/task';
import * as tr from 'vsts-task-lib/toolrunner';
import * as path from 'path';
import * as Q from 'q';
import * as models from './models';
import * as os from 'os';
import * as ci from './cieventlogger';
const str = require('string');
const uuid = requ... | (result: any, settingsFile: string, fileExt: string): Q.Promise<string> {
const defer = Q.defer<string>();
let runSettingsContent = builder.buildObject(result);
runSettingsContent = str(runSettingsContent).replaceAll('
', '').s;
//This is to fix carriage return any other special char... | writeXmlFile | identifier_name |
helpers.ts | import * as fs from 'fs';
import * as tl from 'vsts-task-lib/task';
import * as tr from 'vsts-task-lib/toolrunner';
import * as path from 'path';
import * as Q from 'q';
import * as models from './models';
import * as os from 'os';
import * as ci from './cieventlogger';
const str = require('string');
const uuid = requ... |
public static writeXmlFile(result: any, settingsFile: string, fileExt: string): Q.Promise<string> {
const defer = Q.defer<string>();
let runSettingsContent = builder.buildObject(result);
runSettingsContent = str(runSettingsContent).replaceAll('
', '').s;
//This is to fix carria... | {
return fs.readFileSync(filePath, encoding);
} | identifier_body |
helpers.ts | import * as fs from 'fs';
import * as tl from 'vsts-task-lib/task';
import * as tr from 'vsts-task-lib/toolrunner';
import * as path from 'path';
import * as Q from 'q';
import * as models from './models';
import * as os from 'os';
import * as ci from './cieventlogger';
const str = require('string');
const uuid = requ... | public static setConsoleCodePage() {
tl.debug("Changing active code page to UTF-8");
const chcp = tl.tool(path.resolve(process.env.windir, "system32", "chcp.com"));
chcp.arg(["65001"]);
chcp.execSync({ silent: true } as tr.IExecSyncOptions);
}
public static stringToBool(inpu... | return argument;
}
// set the console code page to "UTF-8" | random_line_split |
unique-in-vec-copy.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 a = vec!(box 10i);
let b = a.clone();
assert_eq!(**a.get(0), 10);
assert_eq!(**b.get(0), 10);
// This should only modify the value in a, not b
**a.get_mut(0) = 20;
assert_eq!(**a.get(0), 20);
assert_eq!(**b.get(0), 10);
}
| main | identifier_name |
unique-in-vec-copy.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 a = vec!(box 10i);
let b = a.clone();
assert_eq!(**a.get(0), 10);
assert_eq!(**b.get(0), 10);
// This should only modify the value in a, not b
**a.get_mut(0) = 20;
assert_eq!(**a.get(0), 20);
assert_eq!(**b.get(0), 10);
} | identifier_body | |
unique-in-vec-copy.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 a = vec!(box 10i);
let b = a.clone();
assert_eq!(**a.get(0), 10);
assert_eq!(**b.get(0), 10);
// This should only modify the value in a, not b
**a.get_mut(0) = 20;
assert_eq!(**a.get(0), 20);
assert_eq!(**b.get(0), 10);
} | random_line_split | |
rage4.py | """Module provider for rage4"""
import json
import logging
import requests
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAMESERVER_DOMAINS = ["rage4.com"]
def provider_parser(subparser):
"""Configure provide... | (self, identifier, rtype=None, name=None, content=None):
data = {"id": identifier}
if name:
data["name"] = self._full_name(name)
if content:
data["content"] = content
if self._get_lexicon_option("ttl"):
data["ttl"] = self._get_lexicon_option("ttl")
... | _update_record | identifier_name |
rage4.py | """Module provider for rage4"""
import json
import logging
import requests
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAMESERVER_DOMAINS = ["rage4.com"]
def provider_parser(subparser):
"""Configure provide... | if len(existing_records) == 1:
return True
record = {
"id": self.domain_id,
"name": self._full_name(name),
"content": content,
"type": rtype,
}
if self._get_lexicon_option("ttl"):
record["ttl"] = self._get_lexicon_o... | """Provider class for rage4"""
def __init__(self, config):
super(Provider, self).__init__(config)
self.domain_id = None
self.api_endpoint = "https://rage4.com/rapi"
def _authenticate(self):
payload = self._get("/getdomainbyname/", {"name": self.domain})
if not payload... | identifier_body |
rage4.py | """Module provider for rage4"""
import json
import logging
import requests
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAMESERVER_DOMAINS = ["rage4.com"]
def provider_parser(subparser):
"""Configure provide... |
if content:
data["content"] = content
if self._get_lexicon_option("ttl"):
data["ttl"] = self._get_lexicon_option("ttl")
# if rtype:
# raise 'Type updating is not supported by this provider.'
payload = self._put("/updaterecord/", {}, data)
LO... | data["name"] = self._full_name(name) | conditional_block |
rage4.py | """Module provider for rage4"""
import json
import logging
import requests
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAMESERVER_DOMAINS = ["rage4.com"]
def provider_parser(subparser):
"""Configure provide... | delete_record_id = []
if not identifier:
records = self._list_records(rtype, name, content)
delete_record_id = [record["id"] for record in records]
else:
delete_record_id.append(identifier)
LOGGER.debug("delete_records: %s", delete_record_id)
... | # If record does not exist, do nothing.
def _delete_record(self, identifier=None, rtype=None, name=None, content=None): | random_line_split |
dataloader.js | bit so the chart has the chance to build itself
setTimeout( function () {
// preserve animation
if ( 0 > chart.panelsSettings.startDuration ) {
l.startDuration = chart.panelsSettings.startDuration;
chart.panelsSettings.startDuration = 0;
}
// cycle through all of ... | ( msg, noStyles ) {
// remove previous curtain if there is one
removeCurtain();
// did we pass in the message?
if ( undefined === msg )
msg = AmCharts.__( 'Loading data...', chart.language );
// create and populate curtain element
var curtain =document.createElement( 'div' );... | showCurtain | identifier_name |
dataloader.js | so the chart has the chance to build itself
setTimeout( function () {
// preserve animation
if ( 0 > chart.panelsSettings.startDuration ) {
l.startDuration = chart.panelsSettings.startDuration;
chart.panelsSettings.startDuration = 0;
}
// cycle through all of the ... |
/**
* Applies defaults to config object
*/
function applyDefaults ( obj ) {
for ( var x = 0; x < defaults.length; x++ ) {
setDefault( obj, x, defaults[ x ] );
}
}
/**
* Checks if object property is set, sets with a default if it isn't
*/
function setDefault ( obj, ke... | {
return 'function' === typeof( obj );
} | identifier_body |
dataloader.js | so the chart has the chance to build itself
setTimeout( function () {
// preserve animation
if ( 0 > chart.panelsSettings.startDuration ) {
l.startDuration = chart.panelsSettings.startDuration;
chart.panelsSettings.startDuration = 0;
}
// cycle through all of the ... | }
else {
holder[providerKey] = postprocess( holder[providerKey], options );
callFunction( options.load, options );
}
break;
default:
callFunction( options.error, options );
raiseError( AmCharts.__( ... | if ( false === holder[providerKey] ) {
callFunction( options.error, options );
raiseError( AmCharts.__( 'Error parsing CSV file', chart.language ) + ': ' + l.url, false, options );
holder[providerKey] = [];
return;
| random_line_split |
multiselect-config.interface.ts | /**
* Interface to allow for customization of DropdownMultiselect
*
* @export
* @interface IMultiselectConfig
*/
export interface IMultiselectConfig {
/**
* Label to be displayed when dropdown selected is 0 or > maxInline
*
* @type {string}
*/
defaultButtonText?: string;
/**
* Should all optio... | */
uncheckClasses?: string[];
/**
* Height at which the dropdown will start to scroll
* @type {number}
*/
scrollingHeight?: number;
/**
* The default text to be shown in the search box
* @type {string}
*/
searchBoxPlaceHolder?: string;
} | *
* @type {string[]} | random_line_split |
product.py | from qit.base.bool import Bool
from qit.base.struct import Struct
from qit.domains.domain import Domain
from qit.domains.iterator import Iterator
from qit.base.function import Function
from qit.functions.int import multiplication_n
class Product(Domain):
""" Cartesian product of domains """
def __init__(self,... | return false;
}
{%- endfor %}
return true;
""", _iters=iters).uses(objects)
self.value_fn.code("""
return {
{%- for name, i in _iters %}
{{b(i.value_fn)}}(iter.{{name}})
{% if not loop.la... | self.is_valid_fn.code("""
{%- for name, i in _iters %}
if (!({{b(i.is_valid_fn)}}(iter.{{name}}))) { | random_line_split |
product.py |
from qit.base.bool import Bool
from qit.base.struct import Struct
from qit.domains.domain import Domain
from qit.domains.iterator import Iterator
from qit.base.function import Function
from qit.functions.int import multiplication_n
class Product(Domain):
""" Cartesian product of domains """
def __init__(self... |
type = Struct(*struct_args)
super().__init__(
type,
self._make_iterator(type, domains),
self._make_generator(type, domains),
self._make_size(domains),
self._make_indexer(domains))
self.domains = tuple(domains)
... | if isinstance(arg, tuple) and len(arg) == 2:
domain = arg[0]
domains.append(domain)
struct_args.append((domain.type, arg[1]))
else:
domains.append(arg)
struct_args.append(arg.type) | conditional_block |
product.py |
from qit.base.bool import Bool
from qit.base.struct import Struct
from qit.domains.domain import Domain
from qit.domains.iterator import Iterator
from qit.base.function import Function
from qit.functions.int import multiplication_n
class Product(Domain):
""" Cartesian product of domains """
def __init__(self... |
def _make_iterator(self, type, domains):
iterators = [ d.iterator for d in domains ]
if all(iterators):
return ProductIterator(type, iterators)
def _make_generator(self, type, domains):
generators = tuple(d.generator for d in domains)
if all(generators):
... | domains = []
struct_args = []
for arg in args:
if isinstance(arg, tuple) and len(arg) == 2:
domain = arg[0]
domains.append(domain)
struct_args.append((domain.type, arg[1]))
else:
domains.append(arg)
... | identifier_body |
product.py |
from qit.base.bool import Bool
from qit.base.struct import Struct
from qit.domains.domain import Domain
from qit.domains.iterator import Iterator
from qit.base.function import Function
from qit.functions.int import multiplication_n
class Product(Domain):
""" Cartesian product of domains """
def __init__(self... | (self, type, domains):
generators = tuple(d.generator for d in domains)
if all(generators):
generator = Function(("generator", self.name)).returns(type).code("""
return {
{% for g in _generators %}
{{b(g)}}{% if not loop.last %},{% endif %}
... | _make_generator | identifier_name |
edgeMetricData.selector.spec.ts | import { calculateEdgeMetricData, nodeEdgeMetricsMap } from "./edgeMetricData.selector"
import { FILE_STATES, VALID_NODE_WITH_PATH } from "../../../../util/dataMocks"
import { FileState } from "../../../../model/files/files"
import { clone } from "../../../../util/clone"
describe("edgeMetricDataSelector", () => {
let... | calculateEdgeMetricData(fileStates, [])
const pairingRateMapKeys = [...nodeEdgeMetricsMap.get("pairingRate").keys()]
expect(pairingRateMapKeys[0]).toEqual("/root/big leaf")
expect(pairingRateMapKeys[1]).toEqual("/root/Parent Leaf/small leaf")
expect(pairingRateMapKeys[2]).toEqual("/root/Parent Leaf/other sm... | random_line_split | |
wallet.js | (function () {
'use strict';
var module = angular.module('fim.base');
module.config(function($routeProvider) {
$routeProvider
.when('/wallet', {
templateUrl: 'partials/wallet.html',
controller: 'WalletController'
});
});
module.controller('WalletController', function($scope, $rootScope, WalletSe... |
reload();
$scope.remove = function (a) {
plugins.get('alerts').confirm({
title: 'Remove key',
message: "Do you want to remove this encrypted key? (cannot be undone)"
}).then(
function (confirmed) {
if (confirmed) {
var list = login._getList().filter(function (_a) {
... | {
$scope.entries = login._getList().map(function (a) {
return { name: a[0], cipher_key: a[1], account: a[2], engine: a[3] }
});
} | identifier_body |
wallet.js | (function () {
'use strict';
var module = angular.module('fim.base');
module.config(function($routeProvider) {
$routeProvider
.when('/wallet', {
templateUrl: 'partials/wallet.html',
controller: 'WalletController'
});
});
module.controller('WalletController', function($scope, $rootScope, WalletSe... |
}
);
}
$scope.loadBackup = function () {
}
});
})(); | {
var list = login._getList().filter(function (_a) {
return !(a.name == _a[0] && a.cipher_key == _a[1] && a.account == _a[2] && a.engine == _a[3]);
});
login._saveList(list);
$scope.$evalAsync(reload);
} | conditional_block |
wallet.js | (function () {
'use strict';
var module = angular.module('fim.base');
module.config(function($routeProvider) { | });
});
module.controller('WalletController', function($scope, $rootScope, WalletService, plugins) {
var login = new WalletService();
$scope.entries = [];
function reload() {
$scope.entries = login._getList().map(function (a) {
return { name: a[0], cipher_key: a[1], account: a[2], engine: a[3] }
... | $routeProvider
.when('/wallet', {
templateUrl: 'partials/wallet.html',
controller: 'WalletController' | random_line_split |
wallet.js | (function () {
'use strict';
var module = angular.module('fim.base');
module.config(function($routeProvider) {
$routeProvider
.when('/wallet', {
templateUrl: 'partials/wallet.html',
controller: 'WalletController'
});
});
module.controller('WalletController', function($scope, $rootScope, WalletSe... | () {
$scope.entries = login._getList().map(function (a) {
return { name: a[0], cipher_key: a[1], account: a[2], engine: a[3] }
});
}
reload();
$scope.remove = function (a) {
plugins.get('alerts').confirm({
title: 'Remove key',
message: "Do you want to remove this encrypted key? (can... | reload | identifier_name |
test_ChangePassPhraseXmlBuilder.py | from nose.tools import assert_raises
from endicia.builders.ChangePassPhraseXmlBuilder import ChangePassPhraseXmlBuilder
from endicia.builders.EndiciaXmlBuilder import ValueToLongError
def test_ChangePassPhraseXmlBuilder_invalid_values():
"""ChangePassPhraseXmlBuilder should raise ValueToLongError when each value is p... | assert_raises( ValueToLongError, builder.setRequestID, "123456789012345678901234567890123456789012345678901" )
assert_raises( ValueToLongError, builder.setAccountID, "1234567" )
assert_raises( ValueToLongError, builder.setPassPhrase, "12345678901234567890123456789012345678901234567890123456789012345" ) | random_line_split | |
test_ChangePassPhraseXmlBuilder.py | from nose.tools import assert_raises
from endicia.builders.ChangePassPhraseXmlBuilder import ChangePassPhraseXmlBuilder
from endicia.builders.EndiciaXmlBuilder import ValueToLongError
def test_ChangePassPhraseXmlBuilder_invalid_values():
| """ChangePassPhraseXmlBuilder should raise ValueToLongError when each value is pass a value longer than required"""
builder = ChangePassPhraseXmlBuilder()
assert_raises( ValueToLongError, builder.setPartnerID, "123456789012345678901234567890123456789012345678901" )
assert_raises( ValueToLongError, builder.setReque... | identifier_body | |
test_ChangePassPhraseXmlBuilder.py | from nose.tools import assert_raises
from endicia.builders.ChangePassPhraseXmlBuilder import ChangePassPhraseXmlBuilder
from endicia.builders.EndiciaXmlBuilder import ValueToLongError
def | ():
"""ChangePassPhraseXmlBuilder should raise ValueToLongError when each value is pass a value longer than required"""
builder = ChangePassPhraseXmlBuilder()
assert_raises( ValueToLongError, builder.setPartnerID, "123456789012345678901234567890123456789012345678901" )
assert_raises( ValueToLongError, builder.set... | test_ChangePassPhraseXmlBuilder_invalid_values | identifier_name |
status.py | from typing import Type, TypeVar, MutableMapping, Any, Iterable
from datapipelines import DataSource, DataSink, PipelineContext, Query, validate_query | from cassiopeia.dto.status import ShardStatusDto
from cassiopeia.datastores.uniquekeys import convert_region_to_platform
from .common import SimpleKVDiskService
T = TypeVar("T")
class ShardStatusDiskService(SimpleKVDiskService):
@DataSource.dispatch
def get(self, type: Type[T], query: MutableMapping[str, Any... |
from cassiopeia.data import Platform, Region | random_line_split |
status.py | from typing import Type, TypeVar, MutableMapping, Any, Iterable
from datapipelines import DataSource, DataSink, PipelineContext, Query, validate_query
from cassiopeia.data import Platform, Region
from cassiopeia.dto.status import ShardStatusDto
from cassiopeia.datastores.uniquekeys import convert_region_to_platform
f... | (SimpleKVDiskService):
@DataSource.dispatch
def get(self, type: Type[T], query: MutableMapping[str, Any], context: PipelineContext = None) -> T:
pass
@DataSource.dispatch
def get_many(self, type: Type[T], query: MutableMapping[str, Any], context: PipelineContext = None) -> Iterable[T]:
... | ShardStatusDiskService | identifier_name |
status.py | from typing import Type, TypeVar, MutableMapping, Any, Iterable
from datapipelines import DataSource, DataSink, PipelineContext, Query, validate_query
from cassiopeia.data import Platform, Region
from cassiopeia.dto.status import ShardStatusDto
from cassiopeia.datastores.uniquekeys import convert_region_to_platform
f... |
@DataSink.dispatch
def put(self, type: Type[T], item: T, context: PipelineContext = None) -> None:
pass
@DataSink.dispatch
def put_many(self, type: Type[T], items: Iterable[T], context: PipelineContext = None) -> None:
pass
##########
# Status #
##########
_validate_... | pass | identifier_body |
views.py | XE_FILE):
print("PXE file is not available!\nPlease check the configuration")
sys.exit()
if not os.path.isfile("./config.py"):
print("PXEAT Config file is missing!")
sys.exit()
elif sys.argv[1] == '--initdb':
init_db()
... |
def connect_db():
return sqlite3.connect(DATABASE)
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
@app.before_request
def before_request():
g.db = connect_db()
@app.teardow... | if opt_flag == "vnc":
return(DEFAULT_BOOT_OPTS + \
" console=ttyS0 vnc=1 vncpassword=" + \
VNC_PASSWD)
elif opt_flag == "ssh":
return(DEFAULT_BOOT_OPTS + \
" console=ttyS0 usessh=1 sshpassword=" + \
S... | identifier_body |
views.py | XE_FILE):
print("PXE file is not available!\nPlease check the configuration")
sys.exit()
if not os.path.isfile("./config.py"):
print("PXEAT Config file is missing!")
sys.exit()
elif sys.argv[1] == '--initdb':
init_db()
... |
def grab_file(base_url, file_path, saved_file):
errmsg0 = "<br />Something wrong, please contact the administrator."
errmsg1 = "<br />Something wrong, please check the repository link \
and kernel/initrd file path."
dbginfo_local = "Debug info: Configuration error! \
Failed to open/write local kernel&in... | sys.exit("chk_type error!") | conditional_block |
views.py | ():
if len(sys.argv) == 2:
if sys.argv[1] == 'server':
if not os.path.isfile(DATABASE):
print("Database is not available!\nCreate with --initdb")
sys.exit()
if not os.path.isfile(PXE_FILE):
print("PXE file is not available!\nPlease ch... | chk_args | identifier_name | |
views.py | XE_FILE):
print("PXE file is not available!\nPlease check the configuration")
sys.exit()
if not os.path.isfile("./config.py"):
print("PXEAT Config file is missing!")
sys.exit()
elif sys.argv[1] == '--initdb':
init_db()
... | dbginfo_local = "Debug info: Configuration error! \
Failed to open/write local kernel&initrd file. \
Check your \'LOADER_PATH\' setting in config file. \
Make sure the path exist and you have permission to write.\n\
Current path: " + saved_file
file_url = base_url + file_path
try:
f = urllib.reque... |
errmsg0 = "<br />Something wrong, please contact the administrator."
errmsg1 = "<br />Something wrong, please check the repository link \
and kernel/initrd file path." | random_line_split |
hyperbolictangent.rs | use std::f64;
use activation::Activation;
#[derive(Copy, Clone)]
pub struct HyperbolicTangent;
impl HyperbolicTangent {
pub fn new() -> HyperbolicTangent {
return HyperbolicTangent;
}
}
impl Activation for HyperbolicTangent {
/// Calculates the tanh of input `x`
fn calc(&self, x: Vec<f64>) ->... | (&self, x: Vec<f64>) -> Vec<f64> {
x.iter()
.map(|n| {
let tanh_factor = n.tanh();
1f64 - (tanh_factor * tanh_factor)
})
.collect::<Vec<_>>()
}
}
#[cfg(test)]
mod tests {
use super::Activation;
use super::HyperbolicTangent;
#... | derivative | identifier_name |
hyperbolictangent.rs | use std::f64;
use activation::Activation;
#[derive(Copy, Clone)]
pub struct HyperbolicTangent;
impl HyperbolicTangent {
pub fn new() -> HyperbolicTangent |
}
impl Activation for HyperbolicTangent {
/// Calculates the tanh of input `x`
fn calc(&self, x: Vec<f64>) -> Vec<f64> {
x.iter().map(|n| n.tanh()).collect::<Vec<_>>()
}
/// Calculates the Derivative tanh of input `x`
fn derivative(&self, x: Vec<f64>) -> Vec<f64> {
x.iter()
... | {
return HyperbolicTangent;
} | identifier_body |
hyperbolictangent.rs | use std::f64;
use activation::Activation;
#[derive(Copy, Clone)]
pub struct HyperbolicTangent;
impl HyperbolicTangent {
pub fn new() -> HyperbolicTangent {
return HyperbolicTangent;
}
}
impl Activation for HyperbolicTangent {
/// Calculates the tanh of input `x`
fn calc(&self, x: Vec<f64>) ->... | #[test]
fn tanh_derivative_test() {
let activation = HyperbolicTangent::new();
assert_approx_eq!(activation.derivative(vec![3f64])[0], 0.0098660372f64);
}
} | let activation = HyperbolicTangent::new();
assert_approx_eq!(activation.calc(vec![3f64])[0], 0.995054754f64);
}
| random_line_split |
stemmer.rs | use super::{Token, TokenFilter, TokenStream};
use crate::tokenizer::BoxTokenStream;
use rust_stemmers::{self, Algorithm};
use serde::{Deserialize, Serialize};
/// Available stemmer languages.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)]
#[allow(missing_docs)]
pub enum Language {
Arabic,
... | fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
} | random_line_split | |
stemmer.rs | use super::{Token, TokenFilter, TokenStream};
use crate::tokenizer::BoxTokenStream;
use rust_stemmers::{self, Algorithm};
use serde::{Deserialize, Serialize};
/// Available stemmer languages.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)]
#[allow(missing_docs)]
pub enum Language {
Arabic,
... | (&mut self) -> &mut Token {
self.tail.token_mut()
}
}
| token_mut | identifier_name |
stemmer.rs | use super::{Token, TokenFilter, TokenStream};
use crate::tokenizer::BoxTokenStream;
use rust_stemmers::{self, Algorithm};
use serde::{Deserialize, Serialize};
/// Available stemmer languages.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Copy, Clone)]
#[allow(missing_docs)]
pub enum Language {
Arabic,
... |
}
impl TokenFilter for Stemmer {
fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> {
let inner_stemmer = rust_stemmers::Stemmer::create(self.stemmer_algorithm);
BoxTokenStream::from(StemmerTokenStream {
tail: token_stream,
stemmer: inner_stemme... | {
Stemmer::new(Language::English)
} | identifier_body |
windows.rs | //! A collection of window functions.
//!
//! All functions take a size `n` and return vectors with `n` elements.
//!
//! Window calculation can be costly depending on the size and type of window,
//! so it is recommended to precompute windows whenever possible.
use std::f32::consts::PI;
use types::Sample;
/// Retu... |
}
window
}
/// Returns a generalized cosine window of size `n`, with the provided
/// coefficients.
///
/// Hanning, hamming, and blackmann windows are all generalized cosine windows.
pub fn generalized_cosine_window(alphas: &[Sample], n: usize) -> Vec<Sample> {
let mut window = Vec::with_capacity(n);
... | {
window.push(2.0-z);
} | conditional_block |
windows.rs | //! A collection of window functions.
//!
//! All functions take a size `n` and return vectors with `n` elements.
//!
//! Window calculation can be costly depending on the size and type of window,
//! so it is recommended to precompute windows whenever possible.
use std::f32::consts::PI;
use types::Sample;
/// Retu... |
#[test]
fn test_hanning() {
use super::hanning;
check_window(&hanning(8),
&[0.0, 0.1882551, 0.61126047, 0.95048443, 0.95048443,
0.61126047, 0.1882551, 0.0]);
}
#[test]
fn test_hamming() {
use super::hamming;
check_window(... | {
use super::bartlett;
check_window(&bartlett(8),
&[0.0, 0.28571429, 0.57142857, 0.85714286, 0.85714286,
0.57142857, 0.28571429, 0.0])
} | identifier_body |
windows.rs | //! A collection of window functions.
//!
//! All functions take a size `n` and return vectors with `n` elements.
//!
//! Window calculation can be costly depending on the size and type of window,
//! so it is recommended to precompute windows whenever possible.
use std::f32::consts::PI;
use types::Sample;
/// Retu... | (actual: &[Sample], expected: &[Sample]) {
for (a, e) in actual.iter().zip(expected) {
assert!(flt_eq(*a, *e));
}
}
#[test]
fn test_bartlett() {
use super::bartlett;
check_window(&bartlett(8),
&[0.0, 0.28571429, 0.57142857, 0.85714286, 0.8571... | check_window | identifier_name |
windows.rs | //! A collection of window functions.
//!
//! All functions take a size `n` and return vectors with `n` elements.
//!
//! Window calculation can be costly depending on the size and type of window,
//! so it is recommended to precompute windows whenever possible.
use std::f32::consts::PI;
use types::Sample;
/// Retu... | let mut window = Vec::with_capacity(n);
let f0 = 2.0*PI / ((n-1) as f32);
for i in 0..n {
let mut wi = 0.0;
for (k, ak) in alphas.iter().enumerate() {
wi += ak * (f0*k as f32*i as f32).cos();
}
window.push(wi);
}
window
}
/// Returns a hanning window of s... | /// coefficients.
///
/// Hanning, hamming, and blackmann windows are all generalized cosine windows.
pub fn generalized_cosine_window(alphas: &[Sample], n: usize) -> Vec<Sample> { | random_line_split |
snapshots_client.py | # 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, software
# d... |
return status
# NOTE(afazkas): Wait reinvented again. It is not in the correct layer
def wait_for_snapshot_status(self, snapshot_id, status):
"""Waits for a Snapshot to reach a given status."""
start_time = time.time()
old_value = value = self._get_snapshot_status(snapshot_id)... | raise exceptions.SnapshotBuildErrorException(
snapshot_id=snapshot_id) | conditional_block |
snapshots_client.py | # 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, software
# d... | """List the details of all snapshots."""
url = 'snapshots/detail'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
return resp, body['snapshots']
def get_snapshot(self, snapshot_id):
"""Ret... | """Client class to send CRUD Volume API requests."""
def __init__(self, auth_provider):
super(SnapshotsClientJSON, self).__init__(auth_provider)
self.service = CONF.volume.catalog_type
self.build_interval = CONF.volume.build_interval
self.build_timeout = CONF.volume.build_timeout
... | identifier_body |
snapshots_client.py | # 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, software
# d... | (self, snapshot_id, status):
"""Waits for a Snapshot to reach a given status."""
start_time = time.time()
old_value = value = self._get_snapshot_status(snapshot_id)
while True:
dtime = time.time() - start_time
time.sleep(self.build_interval)
if value !... | wait_for_snapshot_status | identifier_name |
snapshots_client.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific lan... | # not use this file except in compliance with the License. You may obtain
# a copy of the License at | random_line_split |
filterMaqMapview.py | #!/usr/bin/env python
"""
filterMapview.py <input mapview file> <output filename>
Author: Tony Papenfuss
Date: Mon Jun 16 14:31:42 EST 2008
"""
import os, sys
from useful import progressMessage
iFilename = sys.argv[1]
oFilename = sys.argv[2]
mQ_cutoff = 40
nSeqs = 280000000
oFile = open(oFilename, 'w')
headers ... |
oFile.close()
| progressMessage('# maq hits %s', i, nSeqs) | conditional_block |
filterMaqMapview.py | """
filterMapview.py <input mapview file> <output filename>
Author: Tony Papenfuss
Date: Mon Jun 16 14:31:42 EST 2008
"""
import os, sys
from useful import progressMessage
iFilename = sys.argv[1]
oFilename = sys.argv[2]
mQ_cutoff = 40
nSeqs = 280000000
oFile = open(oFilename, 'w')
headers = ['name','chrom','star... | #!/usr/bin/env python
| random_line_split | |
model.js | /*!
* Copyright 2013 Apereo Foundation (AF) Licensed under the
* Educational Community 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://opensource.org/licenses/ECL-2.0
*
* Unless required by applicab... | }; | random_line_split | |
ez_setup.py | #!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools... | for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError:
e = sys.exc_info()[1]
if self.errorlevel > 1:
... | directories.reverse()
else:
directories.sort(key=operator.attrgetter('name'), reverse=True)
# Set correct owner, mtime and filemode on directories. | random_line_split |
ez_setup.py | #!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools... | (version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (wh... | download_setuptools | identifier_name |
ez_setup.py | #!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools... |
if __name__ == '__main__':
sys.exit(main())
| """Install or upgrade setuptools and EasyInstall"""
options = _parse_args()
tarball = download_setuptools(download_base=options.download_base)
return _install(tarball, _build_install_args(options)) | identifier_body |
ez_setup.py | #!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools... |
if dst:
dst.close()
return os.path.realpath(saveto)
def _extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a ... | src.close() | conditional_block |
SearchResultButton.js | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import purebem from 'purebem';
import { ref } from 'src/firebase';
import { Button, Spinner, Status } from 'src/core/components';
import { button as update } from 'src/redux/components/search/actions';
const block = purebem.of('search... |
return (
<div className={ block('status') }>
{ content }
</div>
);
},
renderLoader() {
if (!this.isLoading()) {
return null;
}
return (
<Spinner type="circle" />
);
},
render() {
... | {
return null;
} | conditional_block |
SearchResultButton.js | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import purebem from 'purebem';
import { ref } from 'src/firebase';
import { Button, Spinner, Status } from 'src/core/components';
import { button as update } from 'src/redux/components/search/actions';
const block = purebem.of('search... | () {
return this.props.button.status === 'pending';
},
renderButton() {
const { button } = this.props;
const text = this.isPending() ? 'Cancel' : 'Join';
if (button.status === 'member' || this.isLoading()) {
return null;
}
return (
<div ... | isPending | identifier_name |
SearchResultButton.js | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import purebem from 'purebem';
import { ref } from 'src/firebase';
import { Button, Spinner, Status } from 'src/core/components';
import { button as update } from 'src/redux/components/search/actions';
const block = purebem.of('search... | ,
isLoading() {
return this.props.button.loading;
},
isPending() {
return this.props.button.status === 'pending';
},
renderButton() {
const { button } = this.props;
const text = this.isPending() ? 'Cancel' : 'Join';
if (button.status === 'member' || this.i... | {
const status = this.isPending() ? null : 'pending';
this.props.onUpdate({ loading: true, status });
this.projectRef.set({ status });
this.userRef.set({ status });
} | identifier_body |
SearchResultButton.js | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import purebem from 'purebem';
import { ref } from 'src/firebase';
import { Button, Spinner, Status } from 'src/core/components';
import { button as update } from 'src/redux/components/search/actions';
const block = purebem.of('search... | status: PropTypes.string
}),
onUpdate: PropTypes.func
},
getDefaultProps() {
return {
button: {
loading: true,
status: 'undefined'
}
};
},
componentDidMount() {
const { id, uid } = this.props;
... | button: PropTypes.shape({
loading: PropTypes.bool, | random_line_split |
index.tsx | /* eslint jsx-a11y/no-static-element-interactions: 0 */
/* eslint jsx-a11y/click-events-have-key-events: 0 */
import React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { actions, selectors, ContentRef, AppState } from "@nteract/core";
interface ComponentProps... | (prevFocused?: boolean): void {
// Check if the element is being hovered over.
const hovered =
this.el &&
this.el.parentElement &&
this.el.parentElement.querySelector(":hover") === this.el;
if (
this.props.focused &&
prevFocused !== this.props.focused &&
// Don... | scrollIntoViewIfNeeded | identifier_name |
index.tsx | /* eslint jsx-a11y/no-static-element-interactions: 0 */
/* eslint jsx-a11y/click-events-have-key-events: 0 */
import React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { actions, selectors, ContentRef, AppState } from "@nteract/core";
interface ComponentProps... | {this.props.children}
</div>
);
}
}
const makeMapStateToProps = (
initialState: AppState,
ownProps: ComponentProps
) => {
const mapStateToProps = (state: AppState) => {
const { id, contentRef } = ownProps;
const model = selectors.model(state, { contentRef });
let focu... | role="presentation"
ref={(el) => {
this.el = el;
}}
>
| random_line_split |
index.tsx | /* eslint jsx-a11y/no-static-element-interactions: 0 */
/* eslint jsx-a11y/click-events-have-key-events: 0 */
import React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { actions, selectors, ContentRef, AppState } from "@nteract/core";
interface ComponentProps... |
return {
focused,
};
};
return mapStateToProps;
};
const makeMapDispatchToProps = (
initialDispatch: Dispatch,
ownProps: ComponentProps
) => {
const mapDispatchToProps = (dispatch: Dispatch) => ({
selectCell: () =>
dispatch(
actions.focusCell({ id: ownProps.i... | {
focused = model.cellFocused === id;
} | conditional_block |
index.tsx | /* eslint jsx-a11y/no-static-element-interactions: 0 */
/* eslint jsx-a11y/click-events-have-key-events: 0 */
import React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { actions, selectors, ContentRef, AppState } from "@nteract/core";
interface ComponentProps... |
}
const makeMapStateToProps = (
initialState: AppState,
ownProps: ComponentProps
) => {
const mapStateToProps = (state: AppState) => {
const { id, contentRef } = ownProps;
const model = selectors.model(state, { contentRef });
let focused = false;
if (model && model.type === "noteboo... | {
return (
<div
onClick={this.props.selectCell}
role="presentation"
ref={(el) => {
this.el = el;
}}
>
{this.props.children}
</div>
);
} | identifier_body |
coverage.rs | // Copyright 2020, 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 <https://opensource.org/licenses/MIT>
use glib::translate::*;
use pango_sys;
use std::fmt;
use std::mem;
use std::ptr;
use CoverageLeve... |
pub fn set(&self, index_: i32, level: CoverageLevel) {
unsafe {
pango_sys::pango_coverage_set(self.to_glib_none().0, index_, level.to_glib());
}
}
#[cfg_attr(feature = "v1_44", deprecated)]
pub fn to_bytes(&self) -> Vec<u8> {
unsafe {
let mut bytes = pt... | {
unsafe {
pango_sys::pango_coverage_max(self.to_glib_none().0, other.to_glib_none().0);
}
} | identifier_body |
coverage.rs | // Copyright 2020, 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 <https://opensource.org/licenses/MIT>
use glib::translate::*;
use pango_sys;
use std::fmt;
use std::mem;
use std::ptr;
use CoverageLeve... | (&self, other: &Coverage) {
unsafe {
pango_sys::pango_coverage_max(self.to_glib_none().0, other.to_glib_none().0);
}
}
pub fn set(&self, index_: i32, level: CoverageLevel) {
unsafe {
pango_sys::pango_coverage_set(self.to_glib_none().0, index_, level.to_glib());
... | max | identifier_name |
coverage.rs | // Copyright 2020, 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 <https://opensource.org/licenses/MIT>
use glib::translate::*;
use pango_sys;
use std::fmt;
use std::mem;
use std::ptr;
use CoverageLeve... | let mut n_bytes = mem::MaybeUninit::uninit();
pango_sys::pango_coverage_to_bytes(
self.to_glib_none().0,
&mut bytes,
n_bytes.as_mut_ptr(),
);
FromGlibContainer::from_glib_full_num(bytes, n_bytes.assume_init() as usize)
... | let mut bytes = ptr::null_mut(); | random_line_split |
integration.rs | // Copyright 2017 The xi-editor 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 ag... | let exit = rpc_looper.mainloop(|| r, &mut handler);
match exit {
Err(ReadError::Json(_)) => (),
Err(err) => panic!("Incorrect error: {:?}", err),
Ok(()) => panic!("Expected an error"),
}
} | let r = make_reader(r#"this is not valid json"#); | random_line_split |
integration.rs | // Copyright 2017 The xi-editor 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 ag... |
#[test]
fn test_recv_resp() {
// we should reply to a well formed request
let mut handler = EchoHandler;
let (tx, mut rx) = test_channel();
let mut rpc_looper = RpcLoop::new(tx);
let r = make_reader(r#"{"id": 1, "method": "hullo", "params": {"words": "plz"}}"#);
assert!(rpc_looper.mainloop(|| ... | {
// we should not reply to a well formed notification
let mut handler = EchoHandler;
let (tx, mut rx) = test_channel();
let mut rpc_looper = RpcLoop::new(tx);
let r = make_reader(r#"{"method": "hullo", "params": {"words": "plz"}}"#);
assert!(rpc_looper.mainloop(|| r, &mut handler).is_ok());
... | identifier_body |
integration.rs | // Copyright 2017 The xi-editor 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 ag... | ;
#[allow(unused)]
impl Handler for EchoHandler {
type Notification = RpcCall;
type Request = RpcCall;
fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification) {}
fn handle_request(&mut self, ctx: &RpcCtx, rpc: Self::Request) -> Result<Value, RemoteError> {
Ok(rpc.params)
}
... | EchoHandler | identifier_name |
date.rs | use std::fmt::{self, Show};
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::shared::util::from_one_raw_str;
use header::shared::time::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone)]
pub st... | impl FromStr for Date {
fn from_str(s: &str) -> Option<Date> {
tm_from_str(s).map(Date)
}
}
bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime, Date, { vec![b"Su... | random_line_split | |
date.rs | use std::fmt::{self, Show};
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::shared::util::from_one_raw_str;
use header::shared::time::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone)]
pub st... | (_: Option<Date>) -> &'static str {
"Date"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Date> {
from_one_raw_str(raw)
}
}
impl HeaderFormat for Date {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let tm = **self;
match tm.tm_utcoff {
0 =>... | header_name | identifier_name |
date.rs | use std::fmt::{self, Show};
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::shared::util::from_one_raw_str;
use header::shared::time::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone)]
pub st... |
}
impl FromStr for Date {
fn from_str(s: &str) -> Option<Date> {
tm_from_str(s).map(Date)
}
}
bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime, Date, { vec![... | {
let tm = **self;
match tm.tm_utcoff {
0 => tm.rfc822().fmt(fmt),
_ => tm.to_utc().rfc822().fmt(fmt)
}
} | identifier_body |
lifetime-elision-return-type-requires-explicit-lifetime.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 ... | <'a> {
x: &'a int,
}
// Lifetime annotation needed because we have two lifetimes: one as a parameter
// and one on the reference.
fn h(_x: &Foo) -> &int { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from
panic!()
}
fn i(_x: in... | Foo | identifier_name |
lifetime-elision-return-type-requires-explicit-lifetime.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 | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// Lifetime annotation needed because we have no arguments.
fn f() -> &int { //~ ERROR missing lifetime specifier
//~^ HELP there is no value for it to be borrowed from
panic!()
}
// Lifetime annotation needed ... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
lifetime-elision-return-type-requires-explicit-lifetime.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 ... |
// Lifetime annotation needed because we have two by-reference parameters.
fn g(_x: &int, _y: &int) -> &int { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say whether it is borrowed from `_x` or `_y`
panic!()
}
struct Foo<'a> {
x: &'a int,
}
// Lifetime annotation needed because ... | { //~ ERROR missing lifetime specifier
//~^ HELP there is no value for it to be borrowed from
panic!()
} | identifier_body |
assemblaOptionsService.js | // Service to manage the assembla options object. Stored in chrome.sstorage.sync
// so that it syncs across devices
angular.module("app")
.factory("assemblaOptionsService", ['$rootScope', '$filter', '$timeout', function($rootScope, $filter, $timeout) {
// Options Object
var aos = {
options: {},
status: {
... | () {
chrome.storage.sync.get({
secret: '',
key: '',
statusTimeout: 1500,
mentionWatchInterval: '60000',
elapsedTimeInterval: '1000',
badgeColor: '#A8A8A8',
hideEmptyBadge: true,
autoRead: true,
users: [],
}, function(items) {
$timeout(function() {
aos.options.secret = ... | restoreOptions | identifier_name |
assemblaOptionsService.js | // Service to manage the assembla options object. Stored in chrome.sstorage.sync
// so that it syncs across devices
angular.module("app")
.factory("assemblaOptionsService", ['$rootScope', '$filter', '$timeout', function($rootScope, $filter, $timeout) { | status: {
msg: '',
mode: ''
},
saveOptions: saveOptions,
onchange: saveOptions,
setOnReadyHandler: setOnReadyHandler,
restoreOptions: restoreOptions
}
var readyHandler = null;
var isReady = false;
var _delim = "@_@"
// Read the options from storage
restoreOptions();
// initialization com... |
// Options Object
var aos = {
options: {}, | random_line_split |
assemblaOptionsService.js | // Service to manage the assembla options object. Stored in chrome.sstorage.sync
// so that it syncs across devices
angular.module("app")
.factory("assemblaOptionsService", ['$rootScope', '$filter', '$timeout', function($rootScope, $filter, $timeout) {
// Options Object
var aos = {
options: {},
status: {
... |
/**
* Save the options object to storage
* @return {void}
*/
function saveOptions() {
chrome.storage.sync.set({
secret: aos.options.secret,
key: aos.options.key,
statusTimeout: aos.options.statusTimeout,
mentionWatchInterval: aos.options.mentionWatchInterval,
elapsedTimeInterval: a... | {
readyHandler = handler;
if (isReady) handler();
} | identifier_body |
ftlog.py | prev_hash = prev_log_hash # SHA1/3 hash of previous Log
if hashtype == HashTypes.SHA1:
check_hex_node_id_160(self._prev_hash)
else:
check_hex_node_id_256(self._prev_hash)
self._prev_master = prev_master # nodeID of master writing prev log
if hashtype == HashT... |
def flush(self):
"""
Flush the log.
This should write the contents of any internal buffers to disk,
but no particular behavior is guaranteed.
"""
self.fd_.flush()
def close(self):
""" Close the log. """
self.fd_.close()
self.is_open = F... | if not self.is_open:
msg = "log file %s is not open for appending" % self.path_to_log
raise UpaxError(msg)
# XXX NEED TO THINK ABOUT THE ORDER OF OPERATIONS HERE
entry = super(
BoundLog,
self).add_entry(tstamp, key, node_id, src, path)
stringified... | identifier_body |
ftlog.py | prev_hash = prev_log_hash # SHA1/3 hash of previous Log
if hashtype == HashTypes.SHA1:
check_hex_node_id_160(self._prev_hash)
else:
check_hex_node_id_256(self._prev_hash)
self._prev_master = prev_master # nodeID of master writing prev log
if hashtype == HashT... | (self, tstamp, key, node_id, src, path):
if not self.is_open:
msg = "log file %s is not open for appending" % self.path_to_log
raise UpaxError(msg)
# XXX NEED TO THINK ABOUT THE ORDER OF OPERATIONS HERE
entry = super(
BoundLog,
self).add_entry(tst... | add_entry | identifier_name |
ftlog.py | ._prev_hash = prev_log_hash # SHA1/3 hash of previous Log
if hashtype == HashTypes.SHA1:
check_hex_node_id_160(self._prev_hash)
else:
check_hex_node_id_256(self._prev_hash)
self._prev_master = prev_master # nodeID of master writing prev log
if hashtype == Has... | return self._src
@property
def timestamp(self):
""" Return the time at which the LogEntry was created. """
return self._timestamp
@property
def hashtype(self):
""" XXX WRONG should return key length, allowing 64 or 40. """
return len(self._key) == 40
# used... | def src(self):
""" Return the 'src' associated with the LogEntry. """ | random_line_split |
ftlog.py | prev_hash = prev_log_hash # SHA1/3 hash of previous Log
if hashtype == HashTypes.SHA1:
check_hex_node_id_160(self._prev_hash)
else:
check_hex_node_id_256(self._prev_hash)
self._prev_master = prev_master # nodeID of master writing prev log
if hashtype == HashT... |
else:
check_hex_node_id_256(self._prev_master)
self._entries = entries # a list
self._index = index # a map, hash => entry
def __contains__(self, key):
""" Return whether this key is in the Log. """
return key in self._index
def __len__(self)... | check_hex_node_id_160(self._prev_master) | conditional_block |
builder.rs | use std::collections::{HashMap, VecDeque};
use crate::level::{Background, Level};
use crate::position::*;
use crate::util::*;
/// Dynamic part of a cell.
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
pub enum Foreground {
None,
Worker,
Crate,
}
fn char_to_cell(chr: char) -> Option<(Background, Foregroun... | }
// Try to figure out whether a given cell is inside the walls.
if !inside && bg.is_wall() {
inside = true;
}
if inside
&& bg == Background::Empty
&& index >= columns
... | if fg == Foreground::Crate {
crates.push(Position::new(x, y)); | random_line_split |
builder.rs | use std::collections::{HashMap, VecDeque};
use crate::level::{Background, Level};
use crate::position::*;
use crate::util::*;
/// Dynamic part of a cell.
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
pub enum Foreground {
None,
Worker,
Crate,
}
fn char_to_cell(chr: char) -> Option<(Background, Foregroun... | {
columns: usize,
rows: usize,
background: Vec<Background>,
crates: HashMap<Position, usize>,
worker_position: Position,
}
fn is_empty_or_comment(s: &str) -> bool {
s.is_empty() || s.trim().starts_with(';')
}
impl LevelBuilder {
pub fn new(rank: usize, level_string: &str) -> Result<Self, ... | LevelBuilder | identifier_name |
builder.rs | use std::collections::{HashMap, VecDeque};
use crate::level::{Background, Level};
use crate::position::*;
use crate::util::*;
/// Dynamic part of a cell.
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
pub enum Foreground {
None,
Worker,
Crate,
}
fn char_to_cell(chr: char) -> Option<(Background, Foregroun... |
pub(crate) struct LevelBuilder {
columns: usize,
rows: usize,
background: Vec<Background>,
crates: HashMap<Position, usize>,
worker_position: Position,
}
fn is_empty_or_comment(s: &str) -> bool {
s.is_empty() || s.trim().starts_with(';')
}
impl LevelBuilder {
pub fn new(rank: usize, leve... | {
match chr {
'#' => Some((Background::Wall, Foreground::None)),
' ' => Some((Background::Empty, Foreground::None)),
'$' => Some((Background::Floor, Foreground::Crate)),
'@' => Some((Background::Floor, Foreground::Worker)),
'.' => Some((Background::Goal, Foreground::None)),
... | identifier_body |
views.py | """Views fo the node settings page."""
# -*- coding: utf-8 -*-
from flask import request
import logging
from addons.dropbox.serializer import DropboxSerializer
from addons.base import generic_views
from website.project.decorators import must_have_addon, must_be_addon_authorizer
logger = logging.getLogger(__name__)
de... | (node_addon, **kwargs):
""" Returns all the subsequent folders under the folder id passed.
"""
folder_id = request.args.get('folder_id')
return node_addon.get_folders(folder_id=folder_id)
dropbox_get_config = generic_views.get_config(
SHORT_NAME,
DropboxSerializer
)
def _set_folder(node_addon... | dropbox_folder_list | identifier_name |
views.py | """Views fo the node settings page."""
# -*- coding: utf-8 -*-
from flask import request
import logging
from addons.dropbox.serializer import DropboxSerializer
from addons.base import generic_views
from website.project.decorators import must_have_addon, must_be_addon_authorizer
logger = logging.getLogger(__name__)
de... |
dropbox_set_config = generic_views.set_config(
SHORT_NAME,
FULL_NAME,
DropboxSerializer,
_set_folder
)
dropbox_deauthorize_node = generic_views.deauthorize_node(
SHORT_NAME
) | uid = folder['id']
node_addon.set_folder(uid, auth=auth)
node_addon.save() | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.