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 |
|---|---|---|---|---|
test_sphinxext_mockcoderefs.py | """Tests for documenteer.sphinext.mockcoderefs."""
from shutil import rmtree
from tempfile import mkdtemp
import pytest
from sphinx.application import Sphinx
import documenteer.sphinxext.mockcoderefs as mockcoderefs
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
@pytest.fix... |
@pytest.mark.parametrize(
"test_input,expected",
[
(("lmod", "lsst.afw"), "lsst.afw"),
(("lmod", "~lsst.afw"), "afw"),
(("lmod", "~lsst"), "lsst"),
],
)
def test_mock_code_ref_role(inliner, test_input, expected):
role_name, role_content = test_input
result = mockcoderefs.m... | return Mock(document=Mock(settings=Mock(env=Mock(app=app)))) | identifier_body |
num_cpus.py | import os
import re
import subprocess
def available_cpu_count():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors... | except ImportError:
pass
# BSD
try:
sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
stdout=subprocess.PIPE)
scStdout = sysctl.communicate()[0]
res = int(scStdout)
if res > 0:
return res
except (OSError, ValueE... | if res > 0:
return res | random_line_split |
num_cpus.py | import os
import re
import subprocess
def available_cpu_count():
| except (ImportError, NotImplementedError):
pass
# http://code.google.com/p/psutil/
try:
import psutil
return psutil.NUM_CPUS
except (ImportError, AttributeError):
pass
# POSIX
try:
res = int(os.sysconf('SC_NPROCESSORS_ONLN'))
if res > 0:
... | """ Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors
try:
m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
... | identifier_body |
num_cpus.py | import os
import re
import subprocess
def available_cpu_count():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors... |
except (OSError, ValueError):
pass
# Linux
try:
res = open('/proc/cpuinfo').read().count('processor\t:')
if res > 0:
return res
except IOError:
pass
# Solaris
try:
pseudoDevices = os.listdir('/devices/pseudo/')
res = 0
for p... | return res | conditional_block |
num_cpus.py | import os
import re
import subprocess
def | ():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors
try:
m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
... | available_cpu_count | identifier_name |
transit-key.js | import { assign } from '@ember/polyfills';
import { decamelize } from '@ember/string';
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
primaryKey: 'name',
keyForAttribute: function(attr) {
return decamelize(attr);
},
normalizeSecrets(payload) {
if (payload.data.keys && Array.is... | else {
return this._super(...arguments);
}
},
});
| {
const min_decryption_version = snapshot.attr('minDecryptionVersion');
const min_encryption_version = snapshot.attr('minEncryptionVersion');
const deletion_allowed = snapshot.attr('deletionAllowed');
return {
min_decryption_version,
min_encryption_version,
deletion_allow... | conditional_block |
transit-key.js | import { assign } from '@ember/polyfills';
import { decamelize } from '@ember/string';
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
primaryKey: 'name',
keyForAttribute: function(attr) {
return decamelize(attr);
},
normalizeSecrets(payload) {
if (payload.data.keys && Array.is... | ,
serialize(snapshot, requestType) {
if (requestType === 'update') {
const min_decryption_version = snapshot.attr('minDecryptionVersion');
const min_encryption_version = snapshot.attr('minEncryptionVersion');
const deletion_allowed = snapshot.attr('deletionAllowed');
return {
min_... | {
const nullResponses = ['updateRecord', 'createRecord', 'deleteRecord'];
const secrets = nullResponses.includes(requestType)
? { name: id, backend: payload.backend }
: this.normalizeSecrets(payload);
const { modelName } = primaryModelClass;
let transformedPayload = { [modelName]: secrets };... | identifier_body |
transit-key.js | import { assign } from '@ember/polyfills';
import { decamelize } from '@ember/string';
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
primaryKey: 'name',
keyForAttribute: function(attr) {
return decamelize(attr);
},
| (payload) {
if (payload.data.keys && Array.isArray(payload.data.keys)) {
const secrets = payload.data.keys.map(secret => ({ name: secret, backend: payload.backend }));
return secrets;
}
assign(payload, payload.data);
delete payload.data;
// timestamps for these two are in seconds...
... | normalizeSecrets | identifier_name |
transit-key.js | import { assign } from '@ember/polyfills';
import { decamelize } from '@ember/string';
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
primaryKey: 'name',
keyForAttribute: function(attr) {
return decamelize(attr);
},
normalizeSecrets(payload) {
if (payload.data.keys && Array.is... | min_decryption_version,
min_encryption_version,
deletion_allowed,
};
} else {
return this._super(...arguments);
}
},
}); | if (requestType === 'update') {
const min_decryption_version = snapshot.attr('minDecryptionVersion');
const min_encryption_version = snapshot.attr('minEncryptionVersion');
const deletion_allowed = snapshot.attr('deletionAllowed');
return { | random_line_split |
optaa_dj_cspp_telemetered_driver.py | """
@package mi.dataset.driver.optaa_dj.cspp
@file mi-dataset/mi/dataset/driver/optaa_dj/cspp/optaa_dj_cspp_telemetered_driver.py
@author Joe Padula
@brief Telemetered driver for the optaa_dj_cspp instrument
Release notes:
Initial Release
"""
__author__ = 'jpadula'
from mi.dataset.dataset_driver import SimpleDatase... | """
The optaa_dj_cspp telemetered driver class extends the SimpleDatasetDriver.
"""
def _build_parser(self, stream_handle):
parser_config = {
DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.optaa_dj_cspp',
DataSetDriverConfigKeys.PARTICLE_CLASS: None,
... | identifier_body | |
optaa_dj_cspp_telemetered_driver.py | """
@package mi.dataset.driver.optaa_dj.cspp
@file mi-dataset/mi/dataset/driver/optaa_dj/cspp/optaa_dj_cspp_telemetered_driver.py
@author Joe Padula
@brief Telemetered driver for the optaa_dj_cspp instrument
Release notes:
Initial Release
"""
__author__ = 'jpadula'
from mi.dataset.dataset_driver import SimpleDatase... | DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.optaa_dj_cspp',
DataSetDriverConfigKeys.PARTICLE_CLASS: None,
DataSetDriverConfigKeys.PARTICLE_CLASSES_DICT: {
METADATA_PARTICLE_CLASS_KEY: OptaaDjCsppMetadataTelemeteredDataParticle,
DATA_PAR... |
def _build_parser(self, stream_handle):
parser_config = { | random_line_split |
optaa_dj_cspp_telemetered_driver.py | """
@package mi.dataset.driver.optaa_dj.cspp
@file mi-dataset/mi/dataset/driver/optaa_dj/cspp/optaa_dj_cspp_telemetered_driver.py
@author Joe Padula
@brief Telemetered driver for the optaa_dj_cspp instrument
Release notes:
Initial Release
"""
__author__ = 'jpadula'
from mi.dataset.dataset_driver import SimpleDatase... | (self, stream_handle):
parser_config = {
DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.optaa_dj_cspp',
DataSetDriverConfigKeys.PARTICLE_CLASS: None,
DataSetDriverConfigKeys.PARTICLE_CLASSES_DICT: {
METADATA_PARTICLE_CLASS_KEY: OptaaDjCsppMetadat... | _build_parser | identifier_name |
conc_update.js | load("jstests/libs/slow_weekly_util.js");
test = new SlowWeeklyMongod("conc_update");
db = test.getDB("concurrency");
db.dropDatabase();
NRECORDS = 3 * 1024 * 1024;
print("loading " + NRECORDS + " documents (progress msg every 1024*1024 documents)");
var bulk = db.conc.initializeUnorderedBulkOp();
for (var i = 0; i <... | NRECORDS +
"}}, false, true)); \
assert.writeOK(db.concflag.update({}, { inprog: false }));");
assert.soon(function() {
var x = db.concflag.findOne();
return x && x.inprog;
}, "wait for fork", 30000, 1);
querycount = 0;
decrements = 0;
misses = 0;
assert.soon(function() ... | random_line_split | |
syntaxEnvironment.js | /**
* syntaxEnvironment.js
* Andrea Tino - 2015
*/
/**
* Main collection point for types to be rendered.
*/
module.exports = function() {
var tsClass = require('./class.js');
var tsInterface = require('./interface.js');
var tsEnum = require('./enum.js');
// Configuration: { classIds = [], interfaceIds ... |
/**
* Builds TypeScript classes.
*/
buildClasses: function() {
},
/**
* Builds TypeScript interfaces.
*/
buildInterfaces: function() {
},
/**
* Build enums.
*/
buildEnums: function() {
}
};
}; | random_line_split | |
syntaxEnvironment.js | /**
* syntaxEnvironment.js
* Andrea Tino - 2015
*/
/**
* Main collection point for types to be rendered.
*/
module.exports = function() {
var tsClass = require('./class.js');
var tsInterface = require('./interface.js');
var tsEnum = require('./enum.js');
// Configuration: { classIds = [], interfaceIds ... |
config = _config;
},
/**
* Builds TypeScript classes.
*/
buildClasses: function() {
},
/**
* Builds TypeScript interfaces.
*/
buildInterfaces: function() {
},
/**
* Build enums.
*/
buildEnums: function() {
}... | {
throw 'Error: Configuration cannot be null or undefined!';
} | conditional_block |
lib.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | // It is often more clear to show that nothing is being moved.
#![allow(clippy::match_ref_pats)]
// Subjective style.
#![allow(
clippy::len_without_is_empty,
clippy::redundant_field_names,
clippy::too_many_arguments
)]
// Default isn't as big a deal as people seem to think it is.
#![allow(clippy::new_without_defa... | // TODO: Falsely triggers for async/await:
// see https://github.com/rust-lang/rust-clippy/issues/5360
// clippy::used_underscore_binding
)] | random_line_split |
tests.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from .models import UserProfile
from imagersite.tests import AuthenticatedTestCase
# Create your tests here.
class ProfileTestCase(TestCase):
"""TestCase for Profile"""
def setUp(self):
"""Set... | (self):
"""Test profile manager."""
self.assertTrue(len(UserProfile.active.all()) > 0)
class UserProfilePageTestCase(AuthenticatedTestCase):
"""Test case for viewing the profile."""
def test_profile_page(self):
self.log_in()
self.assertEqual(self.client.get('/profile/').status... | test_profile_active | identifier_name |
tests.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from .models import UserProfile
from imagersite.tests import AuthenticatedTestCase
# Create your tests here.
class ProfileTestCase(TestCase):
|
def test_profile_repr(self):
"""Test repr function."""
self.assertIn('Cris', repr(self.user.profile))
def test_profile_active(self):
"""Test profile manager."""
self.assertTrue(len(UserProfile.active.all()) > 0)
class UserProfilePageTestCase(AuthenticatedTestCase):
"""Te... | """TestCase for Profile"""
def setUp(self):
"""Set up User Profile"""
self.user = User(username='Cris', first_name='Cris')
self.user.save()
def test_user_has_profile(self):
"""Test User has a profile."""
self.assertTrue(hasattr(self.user, 'profile'))
def test_profi... | identifier_body |
tests.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from .models import UserProfile
from imagersite.tests import AuthenticatedTestCase
# Create your tests here.
class ProfileTestCase(TestCase):
"""TestCase for Profile"""
def setUp(self):
"""Set... | self.client.get('/profile/').content
)
def test_profile_page_has_photo_count(self):
self.log_in()
self.assertIn(
b'Photos uploaded:',
self.client.get('/profile/').content
)
def test_profile_page_has_album_count(self):
self.log_in()
... | def test_profile_page_has_username(self):
self.log_in()
self.assertIn(
self.username.encode('utf-8'), | random_line_split |
testCodeEditor.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
if (!services.has(INotificationService)) {
services.set(INotificationService, new TestNotificationService());
}
if (!services.has(ICommandService)) {
services.set(ICommandService, new TestCommandService(instantiationService));
}
if (!services.has(IThemeService)) {
services.set(IThemeService, new TestThemeSe... | {
services.set(IContextKeyService, new MockContextKeyService());
} | conditional_block |
testCodeEditor.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (event: string): void { }
removeEventListener(event: string): void { }
}
export interface TestCodeEditorCreationOptions extends editorOptions.IEditorOptions {
/**
* The initial model associated with this code editor.
*/
model?: ITextModel;
serviceCollection?: ServiceCollection;
}
export function withTestCodeE... | addEventListener | identifier_name |
testCodeEditor.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | export function withTestCodeEditor(text: string[], options: TestCodeEditorCreationOptions, callback: (editor: TestCodeEditor, cursor: Cursor) => void): void {
// create a model if necessary and remember it in order to dispose it.
if (!options.model) {
options.model = TextModel.createFromString(text.join('\n'));
}
... | random_line_split | |
testCodeEditor.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
addEventListener(event: string): void { }
removeEventListener(event: string): void { }
}
export interface TestCodeEditorCreationOptions extends editorOptions.IEditorOptions {
/**
* The initial model associated with this code editor.
*/
model?: ITextModel;
serviceCollection?: ServiceCollection;
}
export func... | { return undefined; } | identifier_body |
moneybookers.js | });
Moneybookers = Class.create();
Moneybookers.prototype = {
initialize: function(bannerUrl, activateemailUrl, checksecretUrl, checkemailUrl){
this.bannerUrl = bannerUrl;
this.activateemailUrl = activateemailUrl;
this.checksecretUrl = checksecretUrl;
this.checkemailUrl = checkemail... | } | random_line_split | |
moneybookers.js | /osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* @category Phoenix
* @package Phoenix_Moneybookers
* @copyright Copyright (c) 2016 Phoenix... |
}
},
alertSaveChanges: function () {
$("moneybookers_multifuncbutton").style.display = "none";
alert(this.txtNotSavechanges);
},
getHttp: function (url) {
var response;
new Ajax.Request(
url,
{
method: "get",
... | {
alert(this.txtErrStatus2 + "\n("+response+")");
} | conditional_block |
ButtonAppBar.tsx | import * as React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Box from '@material-ui/core/Box';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconBut... | <Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</Box>
);
} | <MenuIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
News
</Typography> | random_line_split |
flag.rs | // Copyright 2016 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 ... |
/// True if status indicates the child continued after a stop.
pub fn wifcontinued(status: usize) -> bool {
status == 0xffff
}
/// True if STATUS indicates termination by a signal.
pub fn wifsignaled(status: usize) -> bool {
((status & 0x7f) + 1) as i8 >= 2
}
/// If wifsignaled(status), the terminating sign... | {
(status >> 8) & 0xff
} | identifier_body |
flag.rs | // Copyright 2016 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 ... | (status: usize) -> bool {
status == 0xffff
}
/// True if STATUS indicates termination by a signal.
pub fn wifsignaled(status: usize) -> bool {
((status & 0x7f) + 1) as i8 >= 2
}
/// If wifsignaled(status), the terminating signal.
pub fn wtermsig(status: usize) -> usize {
status & 0x7f
}
/// True if statu... | wifcontinued | identifier_name |
flag.rs | // Copyright 2016 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 ... | pub const O_TRUNC: usize = 0x0400_0000;
pub const O_EXCL: usize = 0x0800_0000;
pub const O_DIRECTORY: usize = 0x1000_0000;
pub const O_STAT: usize = 0x2000_0000;
pub const O_SYMLINK: usize = 0x4000_0000;
pub const O_NOFOLLOW: usize = 0x8000_0000;
pub const O_ACCMODE: usize = O_RDONLY | O_WRONL... | pub const O_FSYNC: usize = 0x0080_0000;
pub const O_CLOEXEC: usize = 0x0100_0000;
pub const O_CREAT: usize = 0x0200_0000; | random_line_split |
handlers.rs | extern crate libc;
extern crate rustc_serialize;
use std::rc::Rc;
use core::workspaces::Workspaces;
use window_manager::WindowManager;
use window_system::WindowSystem;
use window_system::Window;
use config::{ GeneralConfig, Config };
pub type KeyHandler = Box<Fn(WindowManager, Rc<WindowSystem>, &GeneralConfig) -> Win... | ;
spawn(move || {
debug!("spawning terminal");
let command = if arguments.is_empty() {
Command::new(&terminal).spawn()
} else {
Command::new(&terminal).args(&arguments[..]).spawn()
};
if let Err(_) = command {
... | {
args.split(' ').map(|x| x.to_owned()).collect()
} | conditional_block |
handlers.rs | extern crate libc;
extern crate rustc_serialize;
use std::rc::Rc;
use core::workspaces::Workspaces;
use window_manager::WindowManager;
use window_system::WindowSystem;
use window_system::Window;
use config::{ GeneralConfig, Config };
pub type KeyHandler = Box<Fn(WindowManager, Rc<WindowSystem>, &GeneralConfig) -> Win... | (index: u32, workspace: Workspaces, window: Window) -> Workspaces {
workspace.shift_window(index, window)
}
}
| shift | identifier_name |
handlers.rs | extern crate libc;
extern crate rustc_serialize;
use std::rc::Rc;
use core::workspaces::Workspaces;
use window_manager::WindowManager;
use window_system::WindowSystem;
use window_system::Window;
use config::{ GeneralConfig, Config };
pub type KeyHandler = Box<Fn(WindowManager, Rc<WindowSystem>, &GeneralConfig) -> Win... | };
spawn(move || {
debug!("spawning terminal");
let command = if arguments.is_empty() {
Command::new(&terminal).spawn()
} else {
Command::new(&terminal).args(&arguments[..]).spawn()
};
if let Err(_) = command {... | random_line_split | |
handlers.rs | extern crate libc;
extern crate rustc_serialize;
use std::rc::Rc;
use core::workspaces::Workspaces;
use window_manager::WindowManager;
use window_system::WindowSystem;
use window_system::Window;
use config::{ GeneralConfig, Config };
pub type KeyHandler = Box<Fn(WindowManager, Rc<WindowSystem>, &GeneralConfig) -> Win... | CString::new(resume.as_bytes()).unwrap().as_ptr(),
CString::new(windows.as_bytes()).unwrap().as_ptr(),
null()
];
execvp(filename_c.as_ptr(), slice.as_mut_ptr());
}
window_manager.clone()
}
/// Stop the window manager
... | {
// Get absolute path to binary
let filename = env::current_dir().unwrap().join(&env::current_exe().unwrap());
// Collect all managed windows
let window_ids : String = json::encode(&window_manager.workspaces.all_windows_with_workspaces()).unwrap();
// Create arguments
l... | identifier_body |
hdl_block.py | """
This file is part of xcos-gen.
xcos-gen is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
xcos-gen is distribute... |
def __str__(self):
if not self.gain:
return "{0}: {1}, {2} -> {3}".format(self.block_type, self.block_id, self.in_wire, self.out_wire)
else:
return "{0}: {1}, k = {2}, {3} -> {4}".format(
self.block_type,
self.block_id,
self.g... | self.block_type = hdl_type
self.block_id = block.block_id
self.gain = block.gain
self.inputs = block.inputs
self.outputs = block.outputs
self.in_wire = None
self.out_wire = None | identifier_body |
hdl_block.py | """
This file is part of xcos-gen.
xcos-gen is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
xcos-gen is distribute... | return "{0}: {1}, k = {2}, {3} -> {4}".format(
self.block_type,
self.block_id,
self.gain,
self.in_wire,
self.out_wire
) | conditional_block | |
hdl_block.py | """
This file is part of xcos-gen.
xcos-gen is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
xcos-gen is distribute... | :
def __init__(self, block: Block, hdl_type: str):
self.block_type = hdl_type
self.block_id = block.block_id
self.gain = block.gain
self.inputs = block.inputs
self.outputs = block.outputs
self.in_wire = None
self.out_wire = None
def __str__(self):
... | HdlBlock | identifier_name |
hdl_block.py | """
This file is part of xcos-gen.
xcos-gen is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
xcos-gen is distribute... | You should have received a copy of the GNU General Public License
along with xcos-gen. If not, see <http://www.gnu.org/licenses/>.
Author: Ilia Novikov <ilia.novikov@live.ru>
"""
from block import Block
class HdlBlock:
def __init__(self, block: Block, hdl_type: str):
self.block_type = hdl_t... | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
| random_line_split |
cms.py | from django import template
from django.core.urlresolvers import reverse
from django.utils.http import urlquote_plus
from apps.cms.models import Content
register = template.Library()
@register.simple_tag (takes_context=True)
def cms_content (context, key):
request = context['request']
can_edit = request.user.... |
url = reverse ('content-update', args=[obj.pk])
url += '?next=%s' % urlquote_plus (request.get_full_path())
return obj.content + '<a href="%s" accesskey="e" class="admin-edit-link">Rediger</a>' % url
# Note: returned string is automatically marked as safe
| return obj.content | conditional_block |
cms.py | from django import template
from django.core.urlresolvers import reverse
from django.utils.http import urlquote_plus
from apps.cms.models import Content
register = template.Library()
@register.simple_tag (takes_context=True)
def | (context, key):
request = context['request']
can_edit = request.user.has_perm ('cms.change_content')
try:
obj = Content.objects.get (name=key)
except Content.DoesNotExist:
if not can_edit: return ''
url = reverse ('admin:cms_content_add') + '?name=' + key
return '<div cl... | cms_content | identifier_name |
cms.py | from django import template
from django.core.urlresolvers import reverse
from django.utils.http import urlquote_plus
from apps.cms.models import Content
register = template.Library()
@register.simple_tag (takes_context=True)
def cms_content (context, key):
| request = context['request']
can_edit = request.user.has_perm ('cms.change_content')
try:
obj = Content.objects.get (name=key)
except Content.DoesNotExist:
if not can_edit: return ''
url = reverse ('admin:cms_content_add') + '?name=' + key
return '<div class="small gray"><a h... | identifier_body | |
cms.py | from django import template
from django.core.urlresolvers import reverse
from django.utils.http import urlquote_plus
from apps.cms.models import Content
register = template.Library()
@register.simple_tag (takes_context=True)
def cms_content (context, key):
request = context['request'] | try:
obj = Content.objects.get (name=key)
except Content.DoesNotExist:
if not can_edit: return ''
url = reverse ('admin:cms_content_add') + '?name=' + key
return '<div class="small gray"><a href="%s">[add text]</a></div>' % url
if not can_edit:
return obj.content
... | can_edit = request.user.has_perm ('cms.change_content') | random_line_split |
util.py | import sublime
if int(sublime.version()) < 3000:
import ghci
import ghcmod
import haskell_docs
import hdevtools
import sublime_haskell_common as common
import symbols
else:
import SublimeHaskell.ghci as ghci
import SublimeHaskell.ghcmod as ghcmod
import SublimeHaskell.haskell_docs a... | """
Returns symbols.Module with all declarations
"""
return ghcmod.ghcmod_browse_module(module_name, cabal = cabal) | identifier_body | |
util.py | import sublime
if int(sublime.version()) < 3000:
import ghci
import ghcmod
import haskell_docs
import hdevtools
import sublime_haskell_common as common
import symbols
else:
import SublimeHaskell.ghci as ghci
import SublimeHaskell.ghcmod as ghcmod
import SublimeHaskell.haskell_docs a... | (decl, no_ghci = True):
"""
Refine type for sources decl
"""
if decl.location:
if decl.what == 'function' and not decl.type:
info = symbol_info(decl.location.filename, decl.module.name, decl.name, None, no_ghci = no_ghci)
if info:
decl.type = info.type
de... | refine_type | identifier_name |
util.py | import sublime
if int(sublime.version()) < 3000:
import ghci
import ghcmod
import haskell_docs
import hdevtools
import sublime_haskell_common as common
import symbols
else:
import SublimeHaskell.ghci as ghci
import SublimeHaskell.ghcmod as ghcmod
import SublimeHaskell.haskell_docs a... | return ghcmod.ghcmod_browse_module(module_name, cabal = cabal) |
def browse_module(module_name, cabal = None):
"""
Returns symbols.Module with all declarations
""" | random_line_split |
util.py | import sublime
if int(sublime.version()) < 3000:
import ghci
import ghcmod
import haskell_docs
import hdevtools
import sublime_haskell_common as common
import symbols
else:
import SublimeHaskell.ghci as ghci
import SublimeHaskell.ghcmod as ghcmod
import SublimeHaskell.haskell_docs a... |
def refine_decl(decl):
"""
Refine decl information.
"""
# Symbol from cabal, try to load detailed info with ghci
if not decl.location:
load_docs(decl)
if decl.what == 'declaration':
decl_detailed = ghci.ghci_info(decl.module.name, decl.name)
if decl_detaile... | info = symbol_info(decl.location.filename, decl.module.name, decl.name, None, no_ghci = no_ghci)
if info:
decl.type = info.type | conditional_block |
subs.rs | //! Module for `Finding a Motif in DNA`
use RosalindResult;
use RosalindError::MotifStringsLengthError;
/// This function finds locations of substring `t` in string `s` (finds a motif in DNA)
///
/// ```
/// use rosalind::RosalindError::MotifStringsLengthError;
/// use rosalind::subs::*;
///
/// let s = "GATATATGCAT... |
#[test]
fn it_should_return_error_when_substring_t_is_longer_than_s() {
let s = "ATAT";
let t = "GATATATGCATATACTT";
assert_eq!(motif_lookup(s, t).unwrap_err(), MotifStringsLengthError);
}
}
| {
let s = "GATATATGCATATACTT";
let t = "ATAT";
assert_eq!(motif_lookup(s, t).unwrap(), vec![2, 4, 10]);
} | identifier_body |
subs.rs | //! Module for `Finding a Motif in DNA`
use RosalindResult;
use RosalindError::MotifStringsLengthError;
/// This function finds locations of substring `t` in string `s` (finds a motif in DNA)
///
/// ```
/// use rosalind::RosalindError::MotifStringsLengthError;
/// use rosalind::subs::*;
///
/// let s = "GATATATGCAT... |
}
Ok(motif)
}
#[cfg(test)]
mod tests {
use super::motif_lookup;
use super::super::RosalindError::MotifStringsLengthError;
#[test]
fn it_should_return_all_locations_of_substring_t_in_s() {
let s = "GATATATGCATATACTT";
let t = "ATAT";
assert_eq!(motif_lookup(s, t).unwrap(), vec![2, 4, 10]);
}... | { motif.push(i + 1); } | conditional_block |
subs.rs | //! Module for `Finding a Motif in DNA`
use RosalindResult;
use RosalindError::MotifStringsLengthError;
/// This function finds locations of substring `t` in string `s` (finds a motif in DNA)
///
/// ```
/// use rosalind::RosalindError::MotifStringsLengthError;
/// use rosalind::subs::*;
///
/// let s = "GATATATGCAT... | (s: &str, t: &str) -> RosalindResult<Vec<usize>> {
let (s_len, t_len) = (s.len(), t.len());
if s_len < t_len { return Err(MotifStringsLengthError); }
let mut motif: Vec<usize> = Vec::new();
for i in 0..(s_len - t_len + 1) {
if s[i..].starts_with(t) { motif.push(i + 1); }
}
Ok(motif)
}
#[cfg(test)]
mod ... | motif_lookup | identifier_name |
subs.rs | //! Module for `Finding a Motif in DNA`
use RosalindResult;
use RosalindError::MotifStringsLengthError;
/// This function finds locations of substring `t` in string `s` (finds a motif in DNA)
///
/// ```
/// use rosalind::RosalindError::MotifStringsLengthError;
/// use rosalind::subs::*;
///
/// let s = "GATATATGCAT... | #[test]
fn it_should_return_all_locations_of_substring_t_in_s() {
let s = "GATATATGCATATACTT";
let t = "ATAT";
assert_eq!(motif_lookup(s, t).unwrap(), vec![2, 4, 10]);
}
#[test]
fn it_should_return_error_when_substring_t_is_longer_than_s() {
let s = "ATAT";
let t = "GATATATGCATATACTT";
... | random_line_split | |
evento-detalhe.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import * as $ from 'jquery';
declare var Materialize: any;
@Component({
selector: 'app-evento-detalhe',
templateUrl: './evento-detalhe.component.html',
styleUrl... | implements OnInit, OnDestroy {
inscricao: Subscription;
title: string;
evento: object;
errorMessage: string;
labelTabela = [
{value: 'nome', name: 'Nome'},
{value: 'cpf', name: 'CPF'},
{value: 'email', name: 'Email'},
// {value: 'presenca', name: 'Presença', class: 'center'},
];
optionsT... | EventoDetalheComponent | identifier_name |
evento-detalhe.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import * as $ from 'jquery';
declare var Materialize: any;
@Component({
selector: 'app-evento-detalhe',
templateUrl: './evento-detalhe.component.html',
styleUrl... | ngOnInit() {
this.inscricao = this.route.data.subscribe(
(dados: Object) => {
this.title = dados['title'];
this.evento = dados['evento'];
}
);
if (this.evento['message']){
this.errorMessage = this.evento['message'];
}
}
ngOnDestroy() {
this.inscricao.unsubscr... | }
| identifier_body |
evento-detalhe.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import * as $ from 'jquery';
declare var Materialize: any;
@Component({
selector: 'app-evento-detalhe', | templateUrl: './evento-detalhe.component.html',
styleUrls: ['./evento-detalhe.component.scss']
})
export class EventoDetalheComponent implements OnInit, OnDestroy {
inscricao: Subscription;
title: string;
evento: object;
errorMessage: string;
labelTabela = [
{value: 'nome', name: 'Nome'},
{value:... | random_line_split | |
evento-detalhe.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import * as $ from 'jquery';
declare var Materialize: any;
@Component({
selector: 'app-evento-detalhe',
templateUrl: './evento-detalhe.component.html',
styleUrl... | }
ngOnDestroy() {
this.inscricao.unsubscribe();
}
}
| this.errorMessage = this.evento['message'];
}
| conditional_block |
walltime-data_Asia-Chongqing.js | (function() {
window.WallTime || (window.WallTime = {});
window.WallTime.data = {
rules: {"PRC":[{"name":"PRC","_from":"1986","_to":"only","type":"-","in":"May","on":"4","at":"0:00","_save":"1:00","letter":"D"},{"name":"PRC","_from":"1986","_to":"1991","type":"-","in":"Sep","on":"Sun>=11","at":"0:00","_... | };
window.WallTime.autoinit = true;
}).call(this); | zones: {"Asia/Chongqing":[{"name":"Asia/Chongqing","_offset":"7:06:20","_rule":"-","format":"LMT","_until":"1928"},{"name":"Asia/Chongqing","_offset":"7:00","_rule":"-","format":"LONT","_until":"1980 May"},{"name":"Asia/Chongqing","_offset":"8:00","_rule":"PRC","format":"C%sT","_until":""}]} | random_line_split |
conditional-dispatch.rs | // run-pass |
#![feature(box_syntax)]
trait Get {
fn get(&self) -> Self;
}
trait MyCopy { fn copy(&self) -> Self; }
impl MyCopy for u16 { fn copy(&self) -> Self { *self } }
impl MyCopy for u32 { fn copy(&self) -> Self { *self } }
impl MyCopy for i32 { fn copy(&self) -> Self { *self } }
impl<T:Copy> MyCopy for Option<T> { fn c... | // Test that we are able to resolve conditional dispatch. Here, the
// blanket impl for T:Copy coexists with an impl for Box<T>, because
// Box does not impl Copy. | random_line_split |
conditional-dispatch.rs | // run-pass
// Test that we are able to resolve conditional dispatch. Here, the
// blanket impl for T:Copy coexists with an impl for Box<T>, because
// Box does not impl Copy.
#![feature(box_syntax)]
trait Get {
fn get(&self) -> Self;
}
trait MyCopy { fn copy(&self) -> Self; }
impl MyCopy for u16 { fn copy(&sel... |
}
fn get_it<T:Get>(t: &T) -> T {
(*t).get()
}
fn main() {
assert_eq!(get_it(&1_u32), 1_u32);
assert_eq!(get_it(&1_u16), 1_u16);
assert_eq!(get_it(&Some(1_u16)), Some(1_u16));
assert_eq!(get_it(&Box::new(1)), Box::new(1));
}
| { box get_it(&**self) } | identifier_body |
conditional-dispatch.rs | // run-pass
// Test that we are able to resolve conditional dispatch. Here, the
// blanket impl for T:Copy coexists with an impl for Box<T>, because
// Box does not impl Copy.
#![feature(box_syntax)]
trait Get {
fn get(&self) -> Self;
}
trait MyCopy { fn copy(&self) -> Self; }
impl MyCopy for u16 { fn | (&self) -> Self { *self } }
impl MyCopy for u32 { fn copy(&self) -> Self { *self } }
impl MyCopy for i32 { fn copy(&self) -> Self { *self } }
impl<T:Copy> MyCopy for Option<T> { fn copy(&self) -> Self { *self } }
impl<T:MyCopy> Get for T {
fn get(&self) -> T { self.copy() }
}
impl Get for Box<i32> {
fn get(&s... | copy | identifier_name |
subresource.py | import os, sys, json, urlparse, urllib
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..",
... |
response.add_required_headers = False
response.writer.write_status(status_code)
if access_control_allow_origin != None:
response.writer.write_header("access-control-allow-origin",
access_control_allow_origin)
response.writer.write_header("content-type", co... | return | conditional_block |
subresource.py | import os, sys, json, urlparse, urllib
def get_template(template_basename):
|
# TODO(kristijanburnik): subdomain_prefix is a hardcoded value aligned with
# referrer-policy-test-case.js. The prefix should be configured in one place.
def get_swapped_origin_netloc(netloc, subdomain_prefix = "www1."):
if netloc.startswith(subdomain_prefix):
return netloc[len(subdomain_prefix):]
els... | script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..",
"template"))
template_filename = os.path.join(template_directory, te... | identifier_body |
subresource.py | import os, sys, json, urlparse, urllib
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..", |
# TODO(kristijanburnik): subdomain_prefix is a hardcoded value aligned with
# referrer-policy-test-case.js. The prefix should be configured in one place.
def get_swapped_origin_netloc(netloc, subdomain_prefix = "www1."):
if netloc.startswith(subdomain_prefix):
return netloc[len(subdomain_prefix):]
else... | "template"))
template_filename = os.path.join(template_directory, template_basename);
with open(template_filename, "r") as f:
return f.read() | random_line_split |
subresource.py | import os, sys, json, urlparse, urllib
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..",
... | (url, response):
response.add_required_headers = False
response.writer.write_status(301)
response.writer.write_header("access-control-allow-origin", "*")
response.writer.write_header("location", url)
response.writer.end_headers()
response.writer.write("")
def preprocess_redirection(request, re... | redirect | identifier_name |
gesture_long_press.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use EventController;
use Gesture;
use GestureSingle;
#[cfg(feature = "3.14")]
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct GestureLongPress(Object<ffi::... |
}
| {
skip_assert_initialized!();
unsafe {
Gesture::from_glib_full(ffi::gtk_gesture_long_press_new(widget.to_glib_none().0)).downcast_unchecked()
}
} | identifier_body |
gesture_long_press.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use EventController;
use Gesture;
use GestureSingle;
#[cfg(feature = "3.14")]
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct GestureLongPress(Object<ffi::... | #[cfg(feature = "3.14")]
pub fn new<T: IsA<Widget>>(widget: &T) -> GestureLongPress {
skip_assert_initialized!();
unsafe {
Gesture::from_glib_full(ffi::gtk_gesture_long_press_new(widget.to_glib_none().0)).downcast_unchecked()
}
}
} | }
}
impl GestureLongPress { | random_line_split |
gesture_long_press.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use EventController;
use Gesture;
use GestureSingle;
#[cfg(feature = "3.14")]
use Widget;
use ffi;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct GestureLongPress(Object<ffi::... | <T: IsA<Widget>>(widget: &T) -> GestureLongPress {
skip_assert_initialized!();
unsafe {
Gesture::from_glib_full(ffi::gtk_gesture_long_press_new(widget.to_glib_none().0)).downcast_unchecked()
}
}
}
| new | identifier_name |
throttledlog.py | #
# Copyright 2016-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... |
def throttle(name, interval, timeout=_DEFAULT_TIMEOUT_SEC):
"""
Throttle log messages for `name`, logging at most one message per
`interval` calls or always after `timeout` seconds of silence. Throttling
applies only to logging performed via `log()` function of this module. The
first call of `l... | def __init__(self, interval, timeout):
self._interval = interval
self._timeout = timeout
self._counter = 0
self._last_time = 0
def tick(self):
now = monotonic_time()
result = self._result(now)
self._counter = (self._counter + 1) % self._interval
if re... | identifier_body |
throttledlog.py | #
# Copyright 2016-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | (name, message, *args):
log(name, logging.INFO, message, *args)
def warning(name, message, *args):
log(name, logging.WARNING, message, *args)
| info | identifier_name |
throttledlog.py | #
# Copyright 2016-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... |
class _Periodic(object):
def __init__(self, interval, timeout):
self._interval = interval
self._timeout = timeout
self._counter = 0
self._last_time = 0
def tick(self):
now = monotonic_time()
result = self._result(now)
self._counter = (self._counter + 1... | _periodic = {} | random_line_split |
throttledlog.py | #
# Copyright 2016-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... |
_logger.log(level, message, *args)
def debug(name, message, *args):
log(name, logging.DEBUG, message, *args)
def info(name, message, *args):
log(name, logging.INFO, message, *args)
def warning(name, message, *args):
log(name, logging.WARNING, message, *args)
| if not periodic.tick():
return | conditional_block |
main.py | """ lintswitch lints your code in the background.
http://github.com/grahamking/lintswitch
"""
import sys
import socket
import logging
import os
import os.path
import argparse
from threading import Thread
try:
# python 3
from queue import Queue
except ImportError:
# python 2
from Queue import Queue
fro... | (listener, work_queue):
"""Wait for connections and process them.
@param listener: a socket.socket, open and listening.
"""
while True:
conn, _ = listener.accept()
data = conn.makefile().read()
conn.close()
work_queue.put(data)
def worker(work_queue, args):
"""Tak... | main_loop | identifier_name |
main.py | """ lintswitch lints your code in the background.
http://github.com/grahamking/lintswitch
"""
import sys
import socket
import logging
import os
import os.path
import argparse
from threading import Thread
try:
# python 3
from queue import Queue
except ImportError:
# python 2
from Queue import Queue
fro... |
def worker(work_queue, args):
"""Takes filename from queue, checks them and displays (emit) result.
"""
while 1:
filename = work_queue.get()
filename = filename.strip()
if not filename:
continue
check_result = checkers.check(filename, args)
if not che... | conn, _ = listener.accept()
data = conn.makefile().read()
conn.close()
work_queue.put(data) | conditional_block |
main.py | """ lintswitch lints your code in the background.
http://github.com/grahamking/lintswitch
"""
import sys
import socket
import logging
import os
import os.path
import argparse
from threading import Thread
try:
# python 3
from queue import Queue
except ImportError:
# python 2
from Queue import Queue
fro... | check_proc = Thread(target=worker,
args=(work_queue, args))
check_proc.daemon = True
check_proc.start()
server = Thread(target=http_server.http_server,
args=(args.httpport,))
server.daemon = True
server.start()
# Listen for connections from vim (... | random_line_split | |
main.py | """ lintswitch lints your code in the background.
http://github.com/grahamking/lintswitch
"""
import sys
import socket
import logging
import os
import os.path
import argparse
from threading import Thread
try:
# python 3
from queue import Queue
except ImportError:
# python 2
from Queue import Queue
fro... | '--logfile',
default=None,
help='Full path of log file. Defaults to stdout.')
parser.add_argument(
'--lintport',
type=int,
default=4008,
help='Port to listen for lint requests')
parser.add_argument(
'--httpport',
type=int,
default... | """argparse object which can parse command line arguments,
or print help.
"""
parser = argparse.ArgumentParser(
description=DESC,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-v', '--version',
action='store_true',
help='Print ver... | identifier_body |
helpers.ts | import { expect } from "chai";
import { curry, noop, values } from "lodash";
export function should_equal(expectedScales) |
export const when_filled_with = curry(function when_filled_with(
testFn,
answersCount,
value,
expected,
{
_describe = describe,
_beforeEach = beforeEach,
_it = it,
} = {},
) {
_describe(`when filled with ${value}`, () => {
let answers;
_beforeEach((... | {
if (values(expectedScales).every(isFinite)) {
return `has scales = [${values(expectedScales)}]`;
}
return "should return NaN scales";
} | identifier_body |
helpers.ts | import { expect } from "chai";
import { curry, noop, values } from "lodash";
export function | (expectedScales) {
if (values(expectedScales).every(isFinite)) {
return `has scales = [${values(expectedScales)}]`;
}
return "should return NaN scales";
}
export const when_filled_with = curry(function when_filled_with(
testFn,
answersCount,
value,
expected,
{
_describe... | should_equal | identifier_name |
helpers.ts | import { expect } from "chai";
import { curry, noop, values } from "lodash";
export function should_equal(expectedScales) {
if (values(expectedScales).every(isFinite)) {
return `has scales = [${values(expectedScales)}]`;
}
return "should return NaN scales";
}
export const when_filled_with = curry... | }, 3); | random_line_split | |
helpers.ts | import { expect } from "chai";
import { curry, noop, values } from "lodash";
export function should_equal(expectedScales) {
if (values(expectedScales).every(isFinite)) |
return "should return NaN scales";
}
export const when_filled_with = curry(function when_filled_with(
testFn,
answersCount,
value,
expected,
{
_describe = describe,
_beforeEach = beforeEach,
_it = it,
} = {},
) {
_describe(`when filled with ${value}`, () => {
... | {
return `has scales = [${values(expectedScales)}]`;
} | conditional_block |
32e5974ada25_add_neutron_resources_table.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
# ... | ():
op.create_table(
'standardattributes',
sa.Column('id', sa.BigInteger(), autoincrement=True),
sa.Column('resource_type', sa.String(length=255), nullable=False),
sa.PrimaryKeyConstraint('id')
)
for table in TABLES:
op.add_column(table, sa.Column('standard_attr_id', ... | upgrade | identifier_name |
32e5974ada25_add_neutron_resources_table.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
# ... | op.create_table(
'standardattributes',
sa.Column('id', sa.BigInteger(), autoincrement=True),
sa.Column('resource_type', sa.String(length=255), nullable=False),
sa.PrimaryKeyConstraint('id')
)
for table in TABLES:
op.add_column(table, sa.Column('standard_attr_id', sa.BigIn... | identifier_body | |
32e5974ada25_add_neutron_resources_table.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
# 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 language governing permissions and limitations
# under th... | # | random_line_split |
32e5974ada25_add_neutron_resources_table.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
# ... | op.add_column(table, sa.Column('standard_attr_id', sa.BigInteger(),
nullable=True)) | conditional_block | |
phone.pipe.ts | import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'phone'
})
export class PhonePipe implements PipeTransform {
transform(value: string, args?: any): string {
value = value.replace(/[^\d]/gi, '');
if(value.length <= 8){
value = value.replace(/(\d{4})(\d{1,4})/,'$1-$2');
}
if(... | }
} | parse(value: string) {
value = value
.replace(/[^\d]+/g, '');
return value; | random_line_split |
phone.pipe.ts | import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'phone'
})
export class PhonePipe implements PipeTransform {
transform(value: string, args?: any): string {
value = value.replace(/[^\d]/gi, '');
if(value.length <= 8){
value = value.replace(/(\d{4})(\d{1,4})/,'$1-$2');
}
if(... |
if(value.length <= 11){
value = value.replace(/(\d{2})([9]?)(\d{4})(\d{4})/, '($1) $2 $3-$4');
}
switch (value.length) {
case 13:
value = value.replace(/(\d{2})(\d{2})([9]?)(\d{4})(\d{4})/gi, '+$1 ($2) $3 $4-$5');
break;
case 14:
value = value.replace(/(\d{2})(\d{... | {
value = value.replace(/([9]?)(\d{4})(\d{1,4})/,'$1 $2-$3');
} | conditional_block |
phone.pipe.ts | import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'phone'
})
export class PhonePipe implements PipeTransform {
transform(value: string, args?: any): string | break;
default:
return value;
}
return value;
}
/**
* Parse value to database
* @param value
* @returns {string}
*/
parse(value: string) {
value = value
.replace(/[^\d]+/g, '');
return value;
}
}
| {
value = value.replace(/[^\d]/gi, '');
if(value.length <= 8){
value = value.replace(/(\d{4})(\d{1,4})/,'$1-$2');
}
if(value.length == 9){
value = value.replace(/([9]?)(\d{4})(\d{1,4})/,'$1 $2-$3');
}
if(value.length <= 11){
value = value.replace(/(\d{2})([9]?)(\d{4})(\d{4})/... | identifier_body |
phone.pipe.ts | import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'phone'
})
export class | implements PipeTransform {
transform(value: string, args?: any): string {
value = value.replace(/[^\d]/gi, '');
if(value.length <= 8){
value = value.replace(/(\d{4})(\d{1,4})/,'$1-$2');
}
if(value.length == 9){
value = value.replace(/([9]?)(\d{4})(\d{1,4})/,'$1 $2-$3');
}
if(va... | PhonePipe | identifier_name |
getchangedsrc.py | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 02:10:23 2011
@author: IxxI
@version: v1.0
"""
import sys
import logging
from optparse import OptionParser
from commands import Commands, CLIENT, SERVER
from mcp import getchangedsrc_side
def main():
parser = OptionParser(version='MCP %s' % Commands.fullversion... |
if process_client:
getchangedsrc_side(commands, CLIENT)
if process_server:
getchangedsrc_side(commands, SERVER)
except Exception: # pylint: disable-msg=W0703
logging.exception('FATAL ERROR')
sys.exit(1)
if __name__ == '__main__':
main()
| process_client = False | conditional_block |
getchangedsrc.py | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 02:10:23 2011
@author: IxxI
@version: v1.0
"""
import sys
import logging
from optparse import OptionParser
from commands import Commands, CLIENT, SERVER
from mcp import getchangedsrc_side
def main():
parser = OptionParser(version='MCP %s' % Commands.fullversion... |
if __name__ == '__main__':
main()
| try:
commands = Commands(conffile)
# client or server
process_client = True
process_server = True
if only_client and not only_server:
process_server = False
if only_server and not only_client:
process_client = False
if process_client:
... | identifier_body |
getchangedsrc.py | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 02:10:23 2011
@author: IxxI
@version: v1.0
"""
import sys
import logging
from optparse import OptionParser
from commands import Commands, CLIENT, SERVER
from mcp import getchangedsrc_side
def main():
parser = OptionParser(version='MCP %s' % Commands.fullversion... | if only_client and not only_server:
process_server = False
if only_server and not only_client:
process_client = False
if process_client:
getchangedsrc_side(commands, CLIENT)
if process_server:
getchangedsrc_side(commands, SERVER)
excep... | process_client = True
process_server = True | random_line_split |
getchangedsrc.py | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 02:10:23 2011
@author: IxxI
@version: v1.0
"""
import sys
import logging
from optparse import OptionParser
from commands import Commands, CLIENT, SERVER
from mcp import getchangedsrc_side
def | ():
parser = OptionParser(version='MCP %s' % Commands.fullversion())
parser.add_option('--client', dest='only_client', action='store_true', help='only process client', default=False)
parser.add_option('--server', dest='only_server', action='store_true', help='only process server', default=False)
parser.... | main | identifier_name |
api.js | import isEqual from 'lodash.isequal';
import normalize from '@mapbox/geojson-normalize';
import hat from 'hat';
import featuresAt from './lib/features_at';
import stringSetsAreEqual from './lib/string_sets_are_equal';
import * as Constants from './constants';
import StringSet from './lib/string_set';
import Polygon fr... |
const ids = featureCollection.features.map((feature) => {
feature.id = feature.id || hat();
if (feature.geometry === null) {
throw new Error('Invalid geometry: null');
}
if (ctx.store.get(feature.id) === undefined || ctx.store.get(feature.id).type !== feature.geometry.type) {
... | return newIds;
};
api.add = function (geojson) {
const featureCollection = JSON.parse(JSON.stringify(normalize(geojson))); | random_line_split |
api.js | import isEqual from 'lodash.isequal';
import normalize from '@mapbox/geojson-normalize';
import hat from 'hat';
import featuresAt from './lib/features_at';
import stringSetsAreEqual from './lib/string_sets_are_equal';
import * as Constants from './constants';
import StringSet from './lib/string_set';
import Polygon fr... |
return api;
};
api.deleteAll = function() {
ctx.store.delete(ctx.store.getAllIds(), { silent: true });
// If we were in direct select mode, now our selected feature no longer exists,
// so escape that mode.
if (api.getMode() === Constants.modes.DIRECT_SELECT) {
ctx.events.changeMode(Con... | {
ctx.store.render();
} | conditional_block |
htmldatalistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataLi... |
}
impl<'a> HTMLDataListElementMethods for JSRef<'a, HTMLDataListElement> {
fn Options(self) -> Temporary<HTMLCollection> {
#[jstraceable]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: JSRef<Element>, _root: JSRef<... | {
let element = HTMLDataListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap)
} | identifier_body |
htmldatalistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataLi... | ;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: JSRef<Element>, _root: JSRef<Node>) -> bool {
elem.is_htmloptionelement()
}
}
let node: JSRef<Node> = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilte... | HTMLDataListOptionsFilter | identifier_name |
htmldatalistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataLi... | }
impl HTMLDataListElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDataListElement {
HTMLDataListElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLDataListElement, localName, prefix, document)
}
}
... | random_line_split | |
subst.rs | mut self) -> &'a mut VecPerParamSpace<ty::Region> {
match self.regions {
ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref mut r) => r
}
}
pub fn with_method(self,
m_types: Vec<Ty<'tcx>>,
... |
pub fn replace(&mut self, space: ParamSpace, elems: Vec<T>) {
// FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n).
self.truncate(space, 0);
for t in elems {
self.push(space, t);
}
}
pub fn get_self<'a>(&'a self) -> Option<&'a T> {
let v =... | {
// FIXME (#15435): slow; O(n^2); could enhance vec to make it O(n).
while self.len(space) > len {
self.pop(space);
}
} | identifier_body |
subst.rs | mut self) -> &'a mut VecPerParamSpace<ty::Region> {
match self.regions {
ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref mut r) => r
}
}
pub fn with_method(self,
m_types: Vec<Ty<'tcx>>,
... | (t: Vec<T>, s: Vec<T>, f: Vec<T>) -> VecPerParamSpace<T> {
let type_limit = t.len();
let self_limit = type_limit + s.len();
let mut content = t;
content.extend(s);
content.extend(f);
VecPerParamSpace {
type_limit: type_limit,
self_limit: self_lim... | new | identifier_name |
subst.rs | mut self) -> &'a mut VecPerParamSpace<ty::Region> {
match self.regions {
ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref mut r) => r
}
}
pub fn with_method(self,
m_types: Vec<Ty<'tcx>>,
... | NonerasedRegions(_) => false,
}
}
}
///////////////////////////////////////////////////////////////////////////
// ParamSpace
#[derive(PartialOrd, Ord, PartialEq, Eq, Copy,
Clone, Hash, RustcEncodable, RustcDecodable, Debug)]
pub enum ParamSpace {
TypeSpace, // Type parameters ... |
pub fn is_erased(&self) -> bool {
match *self {
ErasedRegions => true, | random_line_split |
local_image_cache.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*!
An adapter for ImageCacheTask that does local caching to avoid
extra message traffic, it also avoids waiting o... | }
}
let (response_chan, response_port) = channel();
self.image_cache_task.send(GetImage((*url).clone(), response_chan));
let response = response_port.recv();
match response {
ImageNotReady => {
// Need to reflow when the image is availabl... | let (chan, port) = channel();
chan.send(ImageFailed);
return port;
} | random_line_split |
local_image_cache.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*!
An adapter for ImageCacheTask that does local caching to avoid
extra message traffic, it also avoids waiting o... | {
image_cache_task: ImageCacheTask,
round_number: uint,
on_image_available: Option<Box<ImageResponder+Send>>,
state_map: HashMap<Url, ImageState>
}
impl LocalImageCache {
pub fn new(image_cache_task: ImageCacheTask) -> LocalImageCache {
LocalImageCache {
image_cache_task: image... | LocalImageCache | identifier_name |
test.js | 'use strict';
/*jshint expr: true*/
var expect = require('chai').expect;
var path = require('path');
var nodeModulesPath = require('./');
describe('cli/node-module-path.js', function() {
afterEach(function() {
delete process.env.EMBER_NODE_PATH;
});
it('nodeModulesPath() should return the local node_m... |
expect(nodeModulesPath(process.cwd())).to.equal(path.resolve(process.env.EMBER_NODE_PATH));
var addOnPath = path.resolve(process.env.EMBER_NODE_PATH, 'node_modules', 'my-add-on');
var addOnModulesPath = path.resolve(process.env.EMBER_NODE_PATH, 'node_modules', 'my-add-on', 'node_modules');
expect(nod... | {
process.env.EMBER_NODE_PATH = '/tmp/node_modules';
} | conditional_block |
test.js | 'use strict';
/*jshint expr: true*/
var expect = require('chai').expect;
var path = require('path');
var nodeModulesPath = require('./');
describe('cli/node-module-path.js', function() {
afterEach(function() {
delete process.env.EMBER_NODE_PATH;
});
it('nodeModulesPath() should return the local node_m... |
it('nodeModulesPath() should return subdirectories of EMBER_NODE_PATH when set to an absolute path.', function() {
if (process.platform === 'win32') {
process.env.EMBER_NODE_PATH = 'C:\\tmp\node_modules';
} else {
process.env.EMBER_NODE_PATH = '/tmp/node_modules';
}
expect(nodeModulesPat... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.