file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
runtests.py | #!/usr/bin/env python
"""
Custom test runner
If args or options, we run the testsuite as quickly as possible.
If args but no options, we default to using the spec plugin and aborting on
first error/failure.
If options, we ignore defaults and pass options onto Nose.
Examples:
Run all tests (as fast as possible)
$ .... |
if __name__ == '__main__':
args = sys.argv[1:]
verbosity = 1
if not args:
# If run with no args, try and run the testsuite as fast as possible.
# That means across all cores and with no high-falutin' plugins.
import multiprocessing
try:
num_cores = multiproces... | from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=verbosity)
if not test_args:
test_args = ['tests']
num_failures = test_runner.run_tests(test_args)
if num_failures:
sys.exit(num_failures) | identifier_body |
url-path.ts | export class UrlPath {
static ADMIN = 'admin';
static FILTERED_MAP = 'filteredMap';
static INSPECTOR = 'inspector';
static MAIN = 'main';
static REAL_TIME = 'realtime';
static SCATTER_FULL_SCREEN_MODE = 'scatterFullScreenMode';
static THREAD_DUMP = 'threadDump';
static TRANSACTION_DETAIL... | (): string[] {
return [
UrlPath.CONFIG,
UrlPath.ADMIN,
UrlPath.ERROR,
UrlPath.FILTERED_MAP,
UrlPath.INSPECTOR,
UrlPath.MAIN,
UrlPath.REAL_TIME,
UrlPath.SCATTER_FULL_SCREEN_MODE,
UrlPath.THREAD_DUMP,
... | getParamList | identifier_name |
url-path.ts | export class UrlPath {
static ADMIN = 'admin';
static FILTERED_MAP = 'filteredMap';
static INSPECTOR = 'inspector';
static MAIN = 'main';
static REAL_TIME = 'realtime';
static SCATTER_FULL_SCREEN_MODE = 'scatterFullScreenMode';
static THREAD_DUMP = 'threadDump';
static TRANSACTION_DETAIL... | UrlPath.ADMIN,
UrlPath.ERROR,
UrlPath.FILTERED_MAP,
UrlPath.INSPECTOR,
UrlPath.MAIN,
UrlPath.REAL_TIME,
UrlPath.SCATTER_FULL_SCREEN_MODE,
UrlPath.THREAD_DUMP,
UrlPath.TRANSACTION_DETAIL,
UrlPath.TRANS... | static getParamList(): string[] {
return [
UrlPath.CONFIG, | random_line_split |
url-path.ts | export class UrlPath {
static ADMIN = 'admin';
static FILTERED_MAP = 'filteredMap';
static INSPECTOR = 'inspector';
static MAIN = 'main';
static REAL_TIME = 'realtime';
static SCATTER_FULL_SCREEN_MODE = 'scatterFullScreenMode';
static THREAD_DUMP = 'threadDump';
static TRANSACTION_DETAIL... |
static getParamList(): string[] {
return [
UrlPath.CONFIG,
UrlPath.ADMIN,
UrlPath.ERROR,
UrlPath.FILTERED_MAP,
UrlPath.INSPECTOR,
UrlPath.MAIN,
UrlPath.REAL_TIME,
UrlPath.SCATTER_FULL_SCREEN_MODE,
Ur... | {} | identifier_body |
db.py | # Copyright 2015-2016 Hewlett Packard Enterprise Development Company, LP
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/li... | (self, context, tenant_id):
tenant_id = self._validate(context, tenant_id)
topology = self._get_auto_allocated_topology(context, tenant_id)
if topology:
subnets = self.core_plugin.get_subnets(
context,
filters={'network_id': [topology['network_id']]})
... | delete_auto_allocated_topology | identifier_name |
db.py | # Copyright 2015-2016 Hewlett Packard Enterprise Development Company, LP
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/li... |
if len(default_external_networks) > 1:
LOG.error("Multiple external default networks detected. "
"Network %s is true 'default'.",
default_external_networks[0]['network_id'])
return default_external_networks[0].network_id
def _get_supported_su... | LOG.error("Unable to find default external network "
"for deployment, please create/assign one to "
"allow auto-allocation to work correctly.")
raise exceptions.AutoAllocationFailure(
reason=_("No default router:external network")) | conditional_block |
db.py | # Copyright 2015-2016 Hewlett Packard Enterprise Development Company, LP
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/li... |
def _provision_tenant_private_network(self, context, tenant_id):
"""Create a tenant private network/subnets."""
network = None
try:
network_args = {
'name': 'auto_allocated_network',
'admin_state_up': False,
'tenant_id': tenant_id... | """Return the default subnet pools available."""
default_subnet_pools = [
self.core_plugin.get_default_subnetpool(
context, ver) for ver in (4, 6)
]
available_pools = [
s for s in default_subnet_pools if s
]
if not available_pools:
... | identifier_body |
db.py | # Copyright 2015-2016 Hewlett Packard Enterprise Development Company, LP
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/li... | except n_exc.NotFound:
pass | return func(*args, **kwargs) | random_line_split |
index.tsx | import React from 'react';
import { parse } from 'qs'; | import { withStyles } from '../../helpers/withStylesHelper';
import { setActiveFilterButton } from '../../actions/searchFilter';
import { SearchActions } from '../../actions/actionTypes';
import FilterButton, { FILTER_BUTTON_TYPE } from '../filterButton';
import { AppState } from '../../reducers';
import SearchQueryMan... | import { Dispatch } from 'redux';
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import Popover from '@material-ui/core/Popover';
import { Button } from '@pluto_network/pluto-design-elements'; | random_line_split |
index.tsx | import React from 'react';
import { parse } from 'qs';
import { Dispatch } from 'redux';
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import Popover from '@material-ui/core/Popover';
import { Button } from '@pluto_network/pluto-design-elements';
import { wit... | (sortOption: Scinapse.ArticleSearch.SEARCH_SORT_OPTIONS) {
return {
pathname: '/search',
search: SearchQueryManager.stringifyPapersQuery({
query: props.query,
page: 1,
sort: sortOption,
filter,
}),
};
}
const sortingButtons = SORTING_TYPES.map(types => {
... | getNextLocation | identifier_name |
index.tsx | import React from 'react';
import { parse } from 'qs';
import { Dispatch } from 'redux';
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import Popover from '@material-ui/core/Popover';
import { Button } from '@pluto_network/pluto-design-elements';
import { wit... |
const SortingDropdown: React.FC<
SortingDropdownProps & ReturnType<typeof mapStateToProps> & RouteComponentProps
> = React.memo(props => {
const anchorEl = React.useRef(null);
const queryParams = parse(location.search, { ignoreQueryPrefix: true });
const filter = SearchQueryManager.objectifyPaperFilter(queryP... | {
switch (sortOption) {
case 'RELEVANCE': {
return 'Relevance';
}
case 'NEWEST_FIRST': {
return 'Newest';
}
case 'MOST_CITATIONS': {
return 'Most Citations';
}
default:
return 'Relevance';
}
} | identifier_body |
roman_numerals.py | # https://www.codeeval.com/open_challenges/106/
import sys
from collections import namedtuple
test_cases = open(sys.argv[1], 'r')
# test_cases = open('roman_numerals.txt', 'r')
test_lines = (line.rstrip() for line in test_cases)
def num_to_components(num):
num_comp = namedtuple('NumComponents', ('thousands', 'hundre... |
if __name__ == '__main__':
for test in test_lines:
components = num_to_components(int(test))
to_roman(components)
test_cases.close()
| r_thousands = 'M'*num_components.thousands
r_hundreds = ''
r_tens = ''
r_singles = ''
# for hundreds
if num_components.hundreds == 4:
r_hundreds = 'CD'
elif num_components.hundreds == 9:
r_hundreds = 'CM'
elif num_components.hundreds == 5:
r_hundreds = 'D'
elif num_components.hundreds <= 3:
r_hundreds =... | identifier_body |
roman_numerals.py | # https://www.codeeval.com/open_challenges/106/
import sys
from collections import namedtuple
test_cases = open(sys.argv[1], 'r')
# test_cases = open('roman_numerals.txt', 'r')
test_lines = (line.rstrip() for line in test_cases)
def num_to_components(num):
num_comp = namedtuple('NumComponents', ('thousands', 'hundre... | elif num_components.tens in range(6, 9):
r_tens = 'L' + 'X' * (num_components.tens - 5)
# for singles
if num_components.singles == 4:
r_singles = 'IV'
elif num_components.singles == 9:
r_singles = 'IX'
elif num_components.singles == 5:
r_singles = 'V'
elif num_components.singles <= 3:
r_singles = 'I'*n... | r_tens = 'XC'
elif num_components.tens == 5:
r_tens = 'L'
elif num_components.tens <= 3:
r_tens = 'X'*num_components.tens | random_line_split |
roman_numerals.py | # https://www.codeeval.com/open_challenges/106/
import sys
from collections import namedtuple
test_cases = open(sys.argv[1], 'r')
# test_cases = open('roman_numerals.txt', 'r')
test_lines = (line.rstrip() for line in test_cases)
def num_to_components(num):
num_comp = namedtuple('NumComponents', ('thousands', 'hundre... | (num_components):
r_thousands = 'M'*num_components.thousands
r_hundreds = ''
r_tens = ''
r_singles = ''
# for hundreds
if num_components.hundreds == 4:
r_hundreds = 'CD'
elif num_components.hundreds == 9:
r_hundreds = 'CM'
elif num_components.hundreds == 5:
r_hundreds = 'D'
elif num_components.hundreds <... | to_roman | identifier_name |
roman_numerals.py | # https://www.codeeval.com/open_challenges/106/
import sys
from collections import namedtuple
test_cases = open(sys.argv[1], 'r')
# test_cases = open('roman_numerals.txt', 'r')
test_lines = (line.rstrip() for line in test_cases)
def num_to_components(num):
num_comp = namedtuple('NumComponents', ('thousands', 'hundre... |
test_cases.close()
| components = num_to_components(int(test))
to_roman(components) | conditional_block |
KIconDialog.py | # encoding: utf-8
# module PyKDE4.kio
# from /usr/lib/python3/dist-packages/PyKDE4/kio.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdeui as __PyKDE4_kdeui
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
class KIconDialog(__PyKDE4_kdeui.KDialog):
... |
def strictIconSize(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
| pass | identifier_body |
KIconDialog.py | # encoding: utf-8
# module PyKDE4.kio
# from /usr/lib/python3/dist-packages/PyKDE4/kio.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdeui as __PyKDE4_kdeui
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
class | (__PyKDE4_kdeui.KDialog):
# no doc
def getIcon(self, *args, **kwargs): # real signature unknown
pass
def iconSize(self, *args, **kwargs): # real signature unknown
pass
def newIconName(self, *args, **kwargs): # real signature unknown
pass
def openDialog(self, *args, **kwarg... | KIconDialog | identifier_name |
KIconDialog.py | # encoding: utf-8
# module PyKDE4.kio | # by generator 1.135
# no doc
# imports
import PyKDE4.kdeui as __PyKDE4_kdeui
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
class KIconDialog(__PyKDE4_kdeui.KDialog):
# no doc
def getIcon(self, *args, **kwargs): # real signature unknown
pass
def iconSize(self, *args, ... | # from /usr/lib/python3/dist-packages/PyKDE4/kio.cpython-34m-x86_64-linux-gnu.so | random_line_split |
karma.conf.js | // Karma configuration
// Generated on Thu Jul 03 2014 13:23:26 GMT+0530 (India Standard Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/... |
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
}; |
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'], | random_line_split |
TypeTextAtCefTest.ts | import { Keys } from '@ephox/agar';
import { describe, it } from '@ephox/bedrock-client';
import { TinyAssertions, TinyContentActions, TinyHooks, TinySelections } from '@ephox/mcagar';
import Editor from 'tinymce/core/api/Editor';
import Theme from 'tinymce/themes/silver/Theme';
describe('browser.tinymce.core.keyboar... | it('Type after cef inline element', () => {
const editor = hook.editor();
editor.setContent('<p><span contenteditable="false">a</span></p>');
TinySelections.select(editor, 'p', [ 1 ]);
TinyContentActions.keystroke(editor, Keys.right());
TinyContentActions.type(editor, 'bc');
TinyAssertions.ass... | TinyAssertions.assertCursor(editor, [ 0, 0 ], 2);
TinyAssertions.assertContent(editor, '<p>bc<span contenteditable="false">a</span></p>');
});
| random_line_split |
process.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (arr: &[u8]) -> i32 {
let a = arr[0] as u32;
let b = arr[1] as u32;
let c = arr[2] as u32;
let d = arr[3] as u32;
((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32
}
... | combine | identifier_name |
process.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
out_fd: Option<P>, err_fd: Option<P>)
-> IoResult<Process>
where C: ProcessConfig<K, V>, P: AsInner<FileDesc>,
K: BytesContainer + Eq + Hash, V: BytesContainer
{
use li... | {
let r = libc::funcs::posix88::signal::kill(pid, signal as c_int);
mkerr_libc(r)
} | identifier_body |
process.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // FIXME: sure would be nice to not have to scan the entire
// array...
active.retain(|&(pid, ref tx, _)| {
let pr = Process { pid: pid };
match pr.try_wait() {
Some(msg) => { t... | random_line_split | |
process.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
None => {}
}
match cfg.uid() {
Some(u) => {
// When dropping privileges from root, the `setgroups` call
// will remove any extraneous groups. If we don't call this,
// then ev... | {
if libc::setgid(u as libc::gid_t) != 0 {
fail(&mut output);
}
} | conditional_block |
fs.rs | use std::{iter};
use std::collections::{HashMap, HashSet, VecDeque};
use prelude::*;
pub struct Filesystem {
pub volume: Box<Volume>,
pub superblock: Superblock,
pub superblock_bytes: Vec<u8>,
pub superblock_dirty: bool,
pub groups: Vec<Group>,
pub inode_cache: HashMap<u64, Inode>,
pub dirty_inos: HashSe... | (&self) -> u64 {
let a = self.superblock.blocks_count as u64;
let b = self.superblock.blocks_per_group as u64;
(a + b - 1) / b
}
}
pub fn mount_fs(mut volume: Box<Volume>) -> Result<Filesystem> {
let mut superblock_bytes = make_buffer(1024);
try!(volume.read(1024, &mut superblock_bytes[..]));
let s... | group_count | identifier_name |
fs.rs | use std::{iter};
use std::collections::{HashMap, HashSet, VecDeque};
use prelude::*;
pub struct Filesystem {
pub volume: Box<Volume>,
pub superblock: Superblock,
pub superblock_bytes: Vec<u8>,
pub superblock_dirty: bool,
pub groups: Vec<Group>,
pub inode_cache: HashMap<u64, Inode>,
pub dirty_inos: HashSe... |
Ok(())
}
pub fn make_buffer(size: u64) -> Vec<u8> {
iter::repeat(0).take(size as usize).collect()
}
| {
try!(encode_superblock(&fs.superblock, &mut fs.superblock_bytes[..]));
try!(fs.volume.write(1024, &fs.superblock_bytes[..]));
fs.superblock_dirty = false;
} | conditional_block |
fs.rs | use std::{iter};
use std::collections::{HashMap, HashSet, VecDeque};
use prelude::*;
pub struct Filesystem {
pub volume: Box<Volume>,
pub superblock: Superblock,
pub superblock_bytes: Vec<u8>,
pub superblock_dirty: bool,
pub groups: Vec<Group>,
pub inode_cache: HashMap<u64, Inode>,
pub dirty_inos: HashSe... |
pub fn flush_fs(fs: &mut Filesystem) -> Result<()> {
let dirty_inos = fs.dirty_inos.clone();
for dirty_ino in dirty_inos {
try!(flush_ino(fs, dirty_ino));
}
for group_idx in 0..fs.group_count() {
try!(flush_group(fs, group_idx));
}
flush_superblock(fs, true)
}
fn flush_superblock(fs: &mut Files... | {
let mut superblock_bytes = make_buffer(1024);
try!(volume.read(1024, &mut superblock_bytes[..]));
let superblock = try!(decode_superblock(&superblock_bytes[..], true));
let mut fs = Filesystem {
volume: volume,
superblock: superblock,
superblock_bytes: superblock_bytes,
superblock_dirty: fals... | identifier_body |
fs.rs | use std::{iter};
use std::collections::{HashMap, HashSet, VecDeque};
use prelude::*;
pub struct Filesystem {
pub volume: Box<Volume>,
pub superblock: Superblock,
pub superblock_bytes: Vec<u8>,
pub superblock_dirty: bool,
pub groups: Vec<Group>,
pub inode_cache: HashMap<u64, Inode>,
pub dirty_inos: HashSe... | try!(flush_group(fs, group_idx));
}
flush_superblock(fs, true)
}
fn flush_superblock(fs: &mut Filesystem, clean: bool) -> Result<()> {
let state = if clean { 1 } else { 2 };
fs.superblock_dirty = fs.superblock_dirty || fs.superblock.state != state;
fs.superblock.state = state;
if fs.superblock_dirty ... | try!(flush_ino(fs, dirty_ino));
}
for group_idx in 0..fs.group_count() { | random_line_split |
enrollmentTermsApi.js | //
// Copyright (C) 2016 - present Instructure, Inc.
//
// This file is part of Canvas.
//
// Canvas is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License as published by the Free
// Software Foundation, version 3 of the License.
//
// Canvas is distribut... |
}
| {
return new Promise((resolve, reject) => {
Depaginate(listUrl())
.then(response => resolve(deserializeTerms(response)))
.fail(error => reject(error))
})
} | identifier_body |
enrollmentTermsApi.js | //
// Copyright (C) 2016 - present Instructure, Inc.
//
// This file is part of Canvas.
//
// Canvas is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License as published by the Free
// Software Foundation, version 3 of the License.
//
// Canvas is distribut... | (terms) {
return new Promise((resolve, reject) => {
Depaginate(listUrl())
.then(response => resolve(deserializeTerms(response)))
.fail(error => reject(error))
})
}
}
| list | identifier_name |
enrollmentTermsApi.js | //
// Copyright (C) 2016 - present Instructure, Inc.
//
// This file is part of Canvas.
//
// Canvas is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License as published by the Free
// Software Foundation, version 3 of the License.
//
// Canvas is distribut... | return new Promise((resolve, reject) => {
Depaginate(listUrl())
.then(response => resolve(deserializeTerms(response)))
.fail(error => reject(error))
})
}
} | export default {
list (terms) { | random_line_split |
yaml_generator.py |
YAML_OUTPUT = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s
table: %s"""
YAML_OUTPUT_NO_TABLE = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s"""
class YamlGenerator(object):
"""docstring for yaml_generator"""... | from ll1_symbols import * | random_line_split | |
yaml_generator.py | from ll1_symbols import *
YAML_OUTPUT = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s
table: %s"""
YAML_OUTPUT_NO_TABLE = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s"""
class YamlGenerator(object):
"""docs... |
def convert_dict_dict_str(a_dict):
return "\n %s" % ("\n ".join(["%s: %s" % (key, convert_dict_str(value))
for key, value in a_dict.items()]))
def convert_dict_list_str(a_dict):
return "{%s}" % (", \n ".join(["%s: %s" % (key, convert_list_str(value))
for key, value in a_dict.items()]))
def c... | return "{%s}" % ", ".join(["%s: %s" % (key, value)
for key, value in a_dict.items()]) | identifier_body |
yaml_generator.py | from ll1_symbols import *
YAML_OUTPUT = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s
table: %s"""
YAML_OUTPUT_NO_TABLE = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s"""
class YamlGenerator(object):
"""docs... |
else:
return YAML_OUTPUT_NO_TABLE % (convert_list_str(list(self.grammar.term)),
convert_list_str(list(self.grammar.non_term)),
EOF,
ERROR_MARKER,
self.grammar.goal,
convert_dict_dict_list_str(self.convert_production()))
def convert_production(self):
return {... | return YAML_OUTPUT % (convert_list_str(list(self.grammar.term)),
convert_list_str(list(self.grammar.non_term)),
EOF,
ERROR_MARKER,
self.grammar.goal,
convert_dict_dict_list_str(self.convert_production()),
convert_dict_dict_str(ll1_table)) | conditional_block |
yaml_generator.py | from ll1_symbols import *
YAML_OUTPUT = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s
table: %s"""
YAML_OUTPUT_NO_TABLE = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s"""
class YamlGenerator(object):
"""docs... | (a_list):
return "[%s]" % (", ".join(a_list))
def convert_dict_str(a_dict):
return "{%s}" % ", ".join(["%s: %s" % (key, value)
for key, value in a_dict.items()])
def convert_dict_dict_str(a_dict):
return "\n %s" % ("\n ".join(["%s: %s" % (key, convert_dict_str(value))
for key, value in a_dict... | convert_list_str | identifier_name |
misc.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | {
(THIS_TRACK, env!["CARGO_PKG_VERSION"], sha())
} | identifier_body | |
misc.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | ;
format!("Parity/v{}-{}{}{}{}{}/{}/rustc{}", env!("CARGO_PKG_VERSION"), THIS_TRACK, sha3_dash, sha3, date_dash, commit_date, platform(), rustc_version())
}
/// Get the standard version data for this software.
pub fn version_data() -> Bytes {
let mut s = RlpStream::new_list(4);
let v = (env!("CARGO_PKG_VER... | { "-" } | conditional_block |
misc.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Diff misc.
use Bytes;
use rlp::RlpStream;
use target_info::Target;
include!(concat!(env!("OUT_DIR"), "/version.rs"));
include!(concat!(env!("OUT_DIR"), "/rustc_version.rs"));
... | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. | random_line_split |
misc.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | () -> (&'static str, &'static str, &'static str) {
(THIS_TRACK, env!["CARGO_PKG_VERSION"], sha())
}
| raw_package_info | identifier_name |
bp.py | import math
import net
SIGMOID = 0
TANH = 1
class bp:
def __init__(self, net, learning_rate, momentum):
self.type = net.getType()
self.net = net
self.lr = learning_rate
self.m = momentum
self.layer = net.getLayer()
self.lc = [[[0]*max(self.layer)]*max(self.layer)]*len(self.layer)
def _dfu... |
def setMomentum(self, x):
self.m = x
def backPropagate(self, input, target):
if len(target)!=self.layer[-1]:
print len(target)
print self.layer[-1]
raise ValueError('Wrong number of target values')
self.net.process(input)
nlayer = len(self.layer)
delta = []
for i in r... | self.lr = x | identifier_body |
bp.py | import math
import net
SIGMOID = 0
TANH = 1
class | :
def __init__(self, net, learning_rate, momentum):
self.type = net.getType()
self.net = net
self.lr = learning_rate
self.m = momentum
self.layer = net.getLayer()
self.lc = [[[0]*max(self.layer)]*max(self.layer)]*len(self.layer)
def _dfunc(self, y):
if self.type==SIGMOID:
return y... | bp | identifier_name |
bp.py | import math
import net
SIGMOID = 0
TANH = 1
class bp:
def __init__(self, net, learning_rate, momentum):
self.type = net.getType()
self.net = net | self.lc = [[[0]*max(self.layer)]*max(self.layer)]*len(self.layer)
def _dfunc(self, y):
if self.type==SIGMOID:
return y * (1.0 - y)
else:
return 1.0 - y**2
def setLearningRate(self,x):
self.lr = x
def setMomentum(self, x):
self.m = x
def backPropagate(self, input, target):
... | self.lr = learning_rate
self.m = momentum
self.layer = net.getLayer() | random_line_split |
bp.py | import math
import net
SIGMOID = 0
TANH = 1
class bp:
def __init__(self, net, learning_rate, momentum):
self.type = net.getType()
self.net = net
self.lr = learning_rate
self.m = momentum
self.layer = net.getLayer()
self.lc = [[[0]*max(self.layer)]*max(self.layer)]*len(self.layer)
def _dfu... |
error = 0.0
for i in range(0, len(target)):
error = error + 0.5 * (target[i] - self.net.getNode(nlayer-1, i))**2
return error
| for i in range(0, self.layer[l]):
for j in range(0, self.layer[l+1]):
change = delta[l+1][j] * self.net.getNode(l, i)
w = self.net.getWeight(l+1, i, j) + self.lr * change + self.m * self.lc[l+1][i][j]
self.net.setWeight(l+1, i, j, w)
self.lc[l+1][i][j] = change
for... | conditional_block |
conf.py | # -*- coding: utf-8 -*-
#
# Total Open Station documentation build configuration file, created by
# sphinx-quickstart on Sat Feb 28 23:03:04 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated ... | # A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
rst_prolog = """
.. include:: /global.rst
"""
# -- Options for HTML output ----------------------------------------------
# The t... | pygments_style = 'sphinx'
| random_line_split |
gdocsbackend.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2011 Carlos Abalde <carlos.abalde@gmail.com>
#
# This file is part of duplicity.
#
# Duplicity 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 Foundat... |
def _put(self, source_path, remote_filename):
self._delete(remote_filename)
# Set uploader instance. Note that resumable uploads are required in order to
# enable uploads for all file types.
# (see http://googleappsdeveloper.blogspot.com/2011/05/upload-all-file-types-to-any-google... | duplicity.backend.Backend.__init__(self, parsed_url)
# Import Google Data APIs libraries.
try:
global atom
global gdata
import atom.data
import gdata.client
import gdata.docs.client
import gdata.docs.data
except ImportError... | identifier_body |
gdocsbackend.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2011 Carlos Abalde <carlos.abalde@gmail.com>
#
# This file is part of duplicity.
#
# Duplicity 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 Foundat... | (self, remote_filename, local_path):
entries = self._fetch_entries(self.folder.resource_id.text,
GDocsBackend.BACKUP_DOCUMENT_TYPE,
remote_filename)
if len(entries) == 1:
entry = entries[0]
self.client.Do... | _get | identifier_name |
gdocsbackend.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2011 Carlos Abalde <carlos.abalde@gmail.com>
#
# This file is part of duplicity.
#
# Duplicity 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 Foundat... |
elif len(entry.in_collections()) == 0:
result.append(entry)
else:
result = entries
# Done!
return result
""" gdata is an alternate way to access gdocs, currently 05/2015 lacking OAuth support """
duplicity.backend.register_backend('gdat... | for link in entry.in_collections():
folder_entry = self.client.get_entry(link.href, None, None,
desired_class=gdata.docs.data.Resource)
if folder_entry and (folder_entry.resource_id.text == folder_id... | conditional_block |
gdocsbackend.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2011 Carlos Abalde <carlos.abalde@gmail.com>
#
# This file is part of duplicity.
#
# Duplicity 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 Foundat... | folder = gdata.docs.data.Resource(type='folder', title=folder_name)
parent_folder = self.client.create_resource(folder, collection=parent_folder)
else:
parent_folder = None
if parent_folder:
parent_folder_id ... | random_line_split | |
color.js | // We can't use goog.color or goog.color.alpha because they interally use a hex
// string representation that encodes each channel in a single byte. This
// causes occasional loss of precision and rounding errors, especially in the
// alpha channel.
goog.provide('ol.Color');
goog.provide('ol.color');
goog.require('g... | else if ((match = ol.color.rgbaColorRe_.exec(s))) { // rgba()
r = Number(match[1]);
g = Number(match[2]);
b = Number(match[3]);
a = Number(match[4]);
color = [r, g, b, a];
return ol.color.normalize(color, color);
} else if ((match = ol.color.rgbColorRe_.exec(s))) { // rgb()
r = Number(mat... | { // hex
var n = s.length - 1; // number of hex digits
goog.asserts.assert(n == 3 || n == 6,
'Color string length should be 3 or 6');
var d = n == 3 ? 1 : 2; // number of digits per channel
r = parseInt(s.substr(1 + 0 * d, d), 16);
g = parseInt(s.substr(1 + 1 * d, d), 16);
b = parseInt(s... | conditional_block |
color.js | // We can't use goog.color or goog.color.alpha because they interally use a hex
// string representation that encodes each channel in a single byte. This
// causes occasional loss of precision and rounding errors, especially in the
// alpha channel.
goog.provide('ol.Color');
goog.provide('ol.color');
goog.require('g... | cache[s] = color;
++cacheSize;
}
return color;
});
})();
/**
* @param {string} s String.
* @private
* @return {ol.Color} Color.
*/
ol.color.fromStringInternal_ = function(s) {
var isHex = false;
if (ol.ENABLE_NAMED_COLORS && goog.color.names.... | }
color = ol.color.fromStringInternal_(s); | random_line_split |
server.js | // NPM Modules
var low = require("lowdb");
var url = require("url");
var async = require("async");
var fs = require("fs");
var _ = require("underscore");
var _s = require("underscore.string");
var request = require('request');
var twitter = require('twitter');
// Custom Modules
var yans = require("./node_modules-custo... |
var topicFunctions = _.map(r.topics, function(topic) {
return function(callback) {
dataer.getData(topic, function(data) {
callback(null, data);
})
};
})
async.parallel(
topicFunctions,
function(err, topics) {
res.send({
... | {
server.jsonError("There's no data for this screen name. Stop hacking.", res);
return;
} | conditional_block |
server.js | // NPM Modules
var low = require("lowdb");
var url = require("url");
var async = require("async");
var fs = require("fs");
var _ = require("underscore");
var _s = require("underscore.string");
var request = require('request');
var twitter = require('twitter');
// Custom Modules
var yans = require("./node_modules-custo... | var museums = server.db("museums");
var r = museums.find({
id: id
});
var rValue = r.value();
if (!rValue) {
res.redirect(302, "/twitter/" + id);
return;
}
res.render(
"process",
{ "twitter": id }
);
});
server.app.get("/mu... | res.redirect(302, "/museum/" + id);
});
server.app.get("/process/*/", function(req, res) {
var id = req.params[0]; | random_line_split |
server.js | // NPM Modules
var low = require("lowdb");
var url = require("url");
var async = require("async");
var fs = require("fs");
var _ = require("underscore");
var _s = require("underscore.string");
var request = require('request');
var twitter = require('twitter');
// Custom Modules
var yans = require("./node_modules-custo... |
function generateId() {
var id = _.times(16, function(n) {
return _.random(0, 10);
}).join("");
return id;
}
var id = generateId();
while (doesIdExist(id)) {
var id = generateId();
}
var museum = {
"id": id,
"name": name,
... | {
var r = museums.find({ id: id });
return (r.value() ? true : false);
} | identifier_body |
server.js | // NPM Modules
var low = require("lowdb");
var url = require("url");
var async = require("async");
var fs = require("fs");
var _ = require("underscore");
var _s = require("underscore.string");
var request = require('request');
var twitter = require('twitter');
// Custom Modules
var yans = require("./node_modules-custo... | (string, cutOff) {
var cleanString = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,""),
words = cleanString.split(' '),
frequencies = {},
word, frequency, i;
for( i=0; i<words.length; i++ ) {
word = words[i];
frequencies[word] = frequencies[word] || 0;
frequencies[word]++;
}
... | getFrequency2 | identifier_name |
datasource-view.spec.tsx | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file | * to you 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 u... | random_line_split | |
windowactivatable.py | # -*- coding: UTF-8 -*-
# Gedit External Tools plugin
# Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net>
#
# 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 versi... | self, tool):
if self._manager:
self._manager.tool_changed(tool, True)
def on_manager_destroy(self, dialog):
self._manager_default_size = self._manager.get_final_size()
self._manager = None
def on_manager_tools_updated(self, manager):
for window in Gio.Application.ge... | pdate_manager( | identifier_name |
windowactivatable.py | # -*- coding: UTF-8 -*-
# Gedit External Tools plugin
# Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net>
#
# 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 versi... |
def remove(self):
self._menu.remove_all()
for name, tool in self._action_tools.items():
self._window.remove_action(name)
if tool.shortcut:
app = Gio.Application.get_default()
app.remove_accelerator(tool.shortcut)
self._action_tools =... |
def deactivate(self):
self.remove() | random_line_split |
windowactivatable.py | # -*- coding: UTF-8 -*-
# Gedit External Tools plugin
# Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net>
#
# 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 versi... |
# FIXME: restore the launch of the manager on configure using PeasGtk.Configurable
class WindowActivatable(GObject.Object, Gedit.WindowActivatable):
__gtype_name__ = "ExternalToolsWindowActivatable"
window = GObject.property(type=Gedit.Window)
def __init__(self):
GObject.Object.__init__(self)
... | f document is None:
titled = False
remote = False
language = None
else:
titled = document.get_location() is not None
remote = not document.is_local()
language = document.get_language()
states = {
'always': True,
... | identifier_body |
windowactivatable.py | # -*- coding: UTF-8 -*-
# Gedit External Tools plugin
# Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net>
#
# 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 versi... |
for tool in sorted(directory.tools, key=lambda x: x.name.lower()):
action_name = 'external-tool_%X_%X' % (id(tool), id(tool.name))
self._action_tools[action_name] = tool
action = Gio.SimpleAction(name=action_name)
action.connect('activate', capture_menu_action, ... | ubmenu = Gio.Menu()
menu.append_submenu(d.name.replace('_', '__'), submenu)
section = Gio.Menu()
submenu.append_section(None, section)
self._insert_directory(d, section)
| conditional_block |
macro_parser.rs | // Copyright 2012-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-MI... | erTtFrame>,
top_elts: TokenTreeOrTokenTreeVec,
sep: Option<Token>,
idx: usize,
up: Option<Box<MatcherPos>>,
matches: Vec<Vec<Rc<NamedMatch>>>,
match_lo: usize,
match_cur: usize,
match_hi: usize,
sp_lo: BytePos,
}
pub fn count_names(ms: &[TokenTree]) -> usize {
ms.iter().fold(0, ... | Vec<Match | identifier_name |
macro_parser.rs | // Copyright 2012-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-MI... | HashMap::new();
let mut idx = 0;
for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) }
ret_val
}
pub enum ParseResult<T> {
Success(T),
Failure(codemap::Span, String),
Error(codemap::Span, String)
}
pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
pub type Positiona... | &TtSequence(_, ref seq) => {
for next_m in &seq.tts {
n_rec(p_s, next_m, res, ret_val, idx)
}
}
&TtDelimited(_, ref delim) => {
for next_m in &delim.tts {
n_rec(p_s, next_m, res, ret_val, idx)
... | identifier_body |
macro_parser.rs | // Copyright 2012-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-MI... | :NtMeta(p.parse_meta_item()),
_ => {
panic!(p.span_fatal_help(sp,
&format!("invalid fragment specifier `{}`", name),
"valid fragment specifiers are `ident`, `block`, \
`stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \... | (Box::new(panictry!(p.parse_path(LifetimeAndTypesWithoutColons))))
}
"meta" => token: | conditional_block |
macro_parser.rs | // Copyright 2012-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-MI... | TtToken(_, MatchNt(..)) => {
// Built-in nonterminals never start with these tokens,
// so we can eliminate them from consideration.
match tok {
token::CloseDelim(_) => {},
... | random_line_split | |
flo2_pid.py | #!/usr/bin/env python
#--------------------------------------------------------------------------
# flo2_pid.py
# Rick Kauffman a.k.a. Chewie
#
# Hewlett Packard Company Revision: 1.0
# ~~~~~~~~~ WookieWare ~~~~~~~~~~~~~
# Change history....09/03/201... | imc_user = form.getvalue('imc_user')
imc_passw = form.getvalue('imc_passw')
pid_list = form.getvalue('list_o_pids')
imc = form.getvalue('imc')
if pid_list == None:
print "Content-type:text/html\r\n\r\n"
print "<!DOCTYPE html>"
print "<html>"
print "<head>"
print "<title> Wookieware.com</title>"
print "<lin... | form = cgi.FieldStorage()
server = form.getvalue('server')
user = form.getvalue('user')
passw = form.getvalue('passw')
imc_server = form.getvalue('imc_server') | random_line_split |
flo2_pid.py | #!/usr/bin/env python
#--------------------------------------------------------------------------
# flo2_pid.py
# Rick Kauffman a.k.a. Chewie
#
# Hewlett Packard Company Revision: 1.0
# ~~~~~~~~~ WookieWare ~~~~~~~~~~~~~
# Change history....09/03/201... |
print "</table>"
#--------------------------------------------------------------------------
# Finish manual or go home
#---------------------------------------------------------------------------
#print "Content-type:text/html\r\n\r\n"
#print "<!DOCTYPE html>"
#print "<html>"
#print "<head>"
#print ... | eth_src = f.match.eth_src
eth_dst = f.match.eth_dst
action = f.actions.output
print "<tr> <td> %s </td> <td> %s </td> <td> %s </td> </tr>" % (eth_src, eth_dst, action) | conditional_block |
stamplay-js-sdk-tests.ts | Stamplay.init('sample');
const userFn = Stamplay.User();
const user = new userFn.Model();
const colTags = Stamplay.Cobject('tag');
const tags = new colTags.Collection();
// Signing up
const registrationData = {
email : 'user@provider.com',
password: 'mySecret'
};
user.signup(registrationData).then(() => {
us... | () => {
// success callback
}, (err: any) => {
// error callback
}
); | const fooMod = new colFoo.Model();
fooMod.fetch(5)
.then(() => fooMod.upVote())
.then( | random_line_split |
commands.rs | use std::process::{Command, Child, ExitStatus, Output, Stdio};
use std::io::{Read, Write, Error as IOError};
use std::collections::BTreeSet;
use branches::Branches;
use error::Error;
use options::Options;
pub fn spawn_piped(args: &[&str]) -> Child {
Command::new(&args[0])
.args(&args[1..])
.stdin(... | }
let intersection: Vec<_> = b_tree_remotes.intersection(&b_tree_branches).cloned().collect();
{
xargs.stdin.unwrap().write_all(intersection.join("\n").as_bytes()).unwrap()
}
let mut stderr = String::new();
xargs.stderr.unwrap().read_to_string(&mut stderr).unwrap();
// Everything... |
let mut b_tree_branches = BTreeSet::new();
for branch in branches.vec.clone() {
b_tree_branches.insert(branch); | random_line_split |
commands.rs | use std::process::{Command, Child, ExitStatus, Output, Stdio};
use std::io::{Read, Write, Error as IOError};
use std::collections::BTreeSet;
use branches::Branches;
use error::Error;
use options::Options;
pub fn spawn_piped(args: &[&str]) -> Child {
Command::new(&args[0])
.args(&args[1..])
.stdin(... |
}
output.join("\n")
}
#[cfg(test)]
mod test {
use super::spawn_piped;
use std::io::{Read, Write};
#[test]
fn test_spawn_piped() {
let echo = spawn_piped(&["grep", "foo"]);
{
echo.stdin.unwrap().write_all("foo\nbar\nbaz".as_bytes()).unwrap()
}
le... | {
output.push(s.to_owned());
} | conditional_block |
commands.rs | use std::process::{Command, Child, ExitStatus, Output, Stdio};
use std::io::{Read, Write, Error as IOError};
use std::collections::BTreeSet;
use branches::Branches;
use error::Error;
use options::Options;
pub fn spawn_piped(args: &[&str]) -> Child {
Command::new(&args[0])
.args(&args[1..])
.stdin(... |
}
| {
let echo = spawn_piped(&["grep", "foo"]);
{
echo.stdin.unwrap().write_all("foo\nbar\nbaz".as_bytes()).unwrap()
}
let mut stdout = String::new();
echo.stdout.unwrap().read_to_string(&mut stdout).unwrap();
assert_eq!(stdout, "foo\n");
} | identifier_body |
commands.rs | use std::process::{Command, Child, ExitStatus, Output, Stdio};
use std::io::{Read, Write, Error as IOError};
use std::collections::BTreeSet;
use branches::Branches;
use error::Error;
use options::Options;
pub fn | (args: &[&str]) -> Child {
Command::new(&args[0])
.args(&args[1..])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("Error with child process: {}", e))
}
pub fn run_command_with_no_output(args: &[&str]) {
... | spawn_piped | identifier_name |
kanban-value-attribute-config.component.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | } |
public onValueTypeSelected(valueType: KanbanValueType) {
const valueAttribute: KanbanValueAttribute = {...this.kanbanAttribute, valueType};
this.attributeChange.emit(valueAttribute);
} | random_line_split |
kanban-value-attribute-config.component.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | (private i18n: I18n) {
this.aggregationPlaceholder = i18n({id: 'aggregation', value: 'Aggregation'});
}
public onAggregationSelect(aggregation: DataAggregationType) {
const newAttribute = {...this.kanbanAttribute, aggregation};
this.attributeChange.emit(newAttribute);
}
public onAttributeSelected(... | constructor | identifier_name |
kanban-value-attribute-config.component.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... |
}
| {
const valueAttribute: KanbanValueAttribute = {...this.kanbanAttribute, valueType};
this.attributeChange.emit(valueAttribute);
} | identifier_body |
javax.swing.plaf.multi.MultiLabelUI.d.ts | declare namespace javax {
namespace swing {
namespace plaf {
namespace multi {
class | extends javax.swing.plaf.LabelUI {
protected uis: java.util.Vector<javax.swing.plaf.ComponentUI>
public constructor()
public getUIs(): javax.swing.plaf.ComponentUI[]
public contains(arg0: javax.swing.JComponent, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer)... | MultiLabelUI | identifier_name |
javax.swing.plaf.multi.MultiLabelUI.d.ts | declare namespace javax {
namespace swing {
namespace plaf {
namespace multi {
class MultiLabelUI extends javax.swing.plaf.LabelUI {
protected uis: java.util.Vector<javax.swing.plaf.ComponentUI>
public constructor()
public getUIs(): javax.swing.plaf.ComponentUI[]
... | }
} | public getAccessibleChild(arg0: javax.swing.JComponent, arg1: number | java.lang.Integer): javax.accessibility.Accessible
}
}
} | random_line_split |
snapshot.js | 'use strict';
var fs = require('fs'),
_ = require('lodash'),
colors = require('cli-color'),
utils = require('./utils.js');
function doSnapShot(roadMapPath, urlPrefix) {
var target,
payload,
response,
url;
var roadMap = utils.getRoadMapFromPath(roadMapPath);
console.log... |
var targetFilePath = utils.getSouvenirPathForTarget(souvenirPath, target);
fs.writeFileSync(targetFilePath, JSON.stringify(response));
let code = response.statusCode;
if ((code >= 400) && (code < 500)) {
code = colors.magenta(code);
bad.push(no);
} else... | {
failed++;
fail.push(no);
console.log('ERROR! Request timed out!');
continue;
} | conditional_block |
snapshot.js | 'use strict';
var fs = require('fs'),
_ = require('lodash'),
colors = require('cli-color'),
utils = require('./utils.js');
function | (roadMapPath, urlPrefix) {
var target,
payload,
response,
url;
var roadMap = utils.getRoadMapFromPath(roadMapPath);
console.log('Processing road map file "' + roadMapPath + '":');
var bootInfo = utils.getBootInfo();
var souvenirPath = utils.getSouvenirPathForRoadMapPath(ro... | doSnapShot | identifier_name |
snapshot.js | 'use strict';
var fs = require('fs'),
_ = require('lodash'),
colors = require('cli-color'),
utils = require('./utils.js');
function doSnapShot(roadMapPath, urlPrefix) |
var args = utils.getArguments();
if (args.hasOwnProperty('args') || args.length === 1) {
var roadMapPath = utils.getRoadMapPath();
var baseUrl = utils.getBaseUrlFromArguments();
doSnapShot(roadMapPath, baseUrl);
} else {
args.printHelp();
} | {
var target,
payload,
response,
url;
var roadMap = utils.getRoadMapFromPath(roadMapPath);
console.log('Processing road map file "' + roadMapPath + '":');
var bootInfo = utils.getBootInfo();
var souvenirPath = utils.getSouvenirPathForRoadMapPath(roadMapPath);
var fixTe... | identifier_body |
snapshot.js | 'use strict';
var fs = require('fs'),
_ = require('lodash'),
colors = require('cli-color'),
utils = require('./utils.js');
function doSnapShot(roadMapPath, urlPrefix) {
var target,
payload,
response,
url;
var roadMap = utils.getRoadMapFromPath(roadMapPath);
console.log... | console.log(colors.magenta(' Bad requests: ' + bad.join(',')));
}
}
var args = utils.getArguments();
if (args.hasOwnProperty('args') || args.length === 1) {
var roadMapPath = utils.getRoadMapPath();
var baseUrl = utils.getBaseUrlFromArguments();
doSnapShot(roadMapPath, baseUrl);
} else {
... | random_line_split | |
Cleaner.ts | import { Arr } from '@ephox/katamari';
type Task = () => void;
export interface Cleaner {
readonly add: (task: Task) => void;
readonly run: () => void;
readonly wrap: <T extends any[], U>(fn: (...a: T) => U) => (...args: T) => U;
}
export const Cleaner = (): Cleaner => {
let tasks: Task[] = [];
const add ... | wrap
};
}; | run, | random_line_split |
JsxProcessor.ts | import {omit} from './util';
import {getCurrentLine} from './util-stacktrace';
import {attributesWithoutListener, registerListenerAttributes} from './Listeners';
import {toValueString} from './Console';
import Color from './Color';
import Font from './Font';
import * as symbols from './symbols';
import checkType from '... | } else {
throw new Error(`Element "${el}" does not support attribute "${attribute}"`);
}
}
try {
encoded[attribute] = encoder(attributes[attribute]);
} catch(ex) {
throw new Error(`Element "${el}" attribute "${attribute}" can not bet set: ${ex.... | random_line_split | |
JsxProcessor.ts | import {omit} from './util';
import {getCurrentLine} from './util-stacktrace';
import {attributesWithoutListener, registerListenerAttributes} from './Listeners';
import {toValueString} from './Console';
import Color from './Color';
import Font from './Font';
import * as symbols from './symbols';
import checkType from '... |
export default class JsxProcessor {
createElement(Type: ElementFn | string, attributes?: any, ...children: any[]) {
if (!(Type instanceof Function) && typeof Type !== 'string') {
throw new Error(`JSX: Unsupported type ${toValueString(Type)}`);
}
const typeName = Type instanceof Function ? Type.na... | {
return new JsxProcessor();
} | identifier_body |
JsxProcessor.ts | import {omit} from './util';
import {getCurrentLine} from './util-stacktrace';
import {attributesWithoutListener, registerListenerAttributes} from './Listeners';
import {toValueString} from './Console';
import Color from './Color';
import Font from './Font';
import * as symbols from './symbols';
import checkType from '... | else {
return this.createFunctionalComponent(Type, finalAttributes);
}
}
createCustomComponent(Type: ElementFn, attributes: any) {
return Type.prototype[JSX.jsxFactory].call(this, Type, attributes);
}
createFunctionalComponent(Type: ElementFn, attributes: any) {
try {
const result = T... | {
return this.createCustomComponent(Type, finalAttributes);
} | conditional_block |
JsxProcessor.ts | import {omit} from './util';
import {getCurrentLine} from './util-stacktrace';
import {attributesWithoutListener, registerListenerAttributes} from './Listeners';
import {toValueString} from './Console';
import Color from './Color';
import Font from './Font';
import * as symbols from './symbols';
import checkType from '... | (Type: ElementFn, attributes: any) {
return Type.prototype[JSX.jsxFactory].call(this, Type, attributes);
}
createFunctionalComponent(Type: ElementFn, attributes: any) {
try {
const result = Type.call(this, attributes);
Type[symbols.jsxType] = true;
if (result instanceof Object) {
... | createCustomComponent | identifier_name |
java.io.PipedInputStream.d.ts | declare namespace java {
namespace io {
class PipedInputStream extends java.io.InputStream {
closedByWriter: boolean
closedByReader: boolean
connected: boolean
readSide: java.lang.Thread
writeSide: java.lang.Thread
protected static readonly PIPE_SIZE: int
protected buffe... | }
}
} | public close(): void | random_line_split |
java.io.PipedInputStream.d.ts | declare namespace java {
namespace io {
class | extends java.io.InputStream {
closedByWriter: boolean
closedByReader: boolean
connected: boolean
readSide: java.lang.Thread
writeSide: java.lang.Thread
protected static readonly PIPE_SIZE: int
protected buffer: byte[]
protected in: int
protected out: int
stat... | PipedInputStream | identifier_name |
controllers.py | from application import CONFIG, app
from .models import *
from flask import current_app, session
from flask.ext.login import login_user, logout_user, current_user
from flask.ext.principal import Principal, Identity, AnonymousIdentity, identity_changed, identity_loaded, RoleNeed
import bcrypt
import re
import sendgrid
i... | account.lastname = lastname
account.save()
login(email) #To update navbar
def change_password(email, password):
account = get_user(email)
if account is None:
raise UserDoesNotExistError
hashed = str(bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()))[2:-1]
account.hashed = hashed
account.... | random_line_split | |
controllers.py | from application import CONFIG, app
from .models import *
from flask import current_app, session
from flask.ext.login import login_user, logout_user, current_user
from flask.ext.principal import Principal, Identity, AnonymousIdentity, identity_changed, identity_loaded, RoleNeed
import bcrypt
import re
import sendgrid
i... | (sender, identity):
identity.user = current_user
if hasattr(current_user, 'roles'):
for role in current_user.roles:
identity.provides.add(RoleNeed(role))
def get_user(email):
entries = StaffUserEntry.objects(email = email)
if entries.count() == 1:
return entries[0]
return None
def verify_use... | on_identity_loaded | identifier_name |
controllers.py | from application import CONFIG, app
from .models import *
from flask import current_app, session
from flask.ext.login import login_user, logout_user, current_user
from flask.ext.principal import Principal, Identity, AnonymousIdentity, identity_changed, identity_loaded, RoleNeed
import bcrypt
import re
import sendgrid
i... |
else:
raise UserDoesNotExistError
def logout():
logout_user()
for key in ('identity.name', 'identity.auth_type'):
session.pop(key, None)
identity_changed.send(current_app._get_current_object(), identity = AnonymousIdentity())
def tokenize_email(email):
return ts.dumps(email, salt = CONFIG["EMAI... | login_user(user)
identity_changed.send(current_app._get_current_object(), identity = Identity(user.uid)) | conditional_block |
controllers.py | from application import CONFIG, app
from .models import *
from flask import current_app, session
from flask.ext.login import login_user, logout_user, current_user
from flask.ext.principal import Principal, Identity, AnonymousIdentity, identity_changed, identity_loaded, RoleNeed
import bcrypt
import re
import sendgrid
i... |
def login(email):
user = load_user(get_user(email).id)
if user != None:
login_user(user)
identity_changed.send(current_app._get_current_object(), identity = Identity(user.uid))
else:
raise UserDoesNotExistError
def logout():
logout_user()
for key in ('identity.name', 'identity.auth_type'):
... | currUser = get_user(email)
if currUser is None:
return None
hashed = currUser.hashed
if bcrypt.hashpw(password.encode("utf-8"), hashed.encode("utf-8")) == hashed.encode("utf-8"):
return load_user(currUser.id)
else:
return None | identifier_body |
router.js | import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
// Auth
this.route('activation', { path: 'activation/' }, function() {
this.route('activate', { path: ':user_id/:token/' }); | });
// Options
this.route('options', { path: 'options/' }, function() {
this.route('forum', { path: 'forum-options/' });
this.route('signature', { path: 'edit-signature/' });
this.route('username', { path: 'change-username/' });
this.route('password', { path: 'change-password/' }, function() {
... | });
this.route('forgotten-password', { path: 'forgotten-password/' }, function() {
this.route('change-form', { path: ':user_id/:token/' }); | random_line_split |
validate-lab.ts | import isEmpty from 'lodash/isEmpty'
import Lab from '../../shared/model/Lab'
export class LabError extends Error {
message: string
result?: string
patient?: string
type?: string
constructor(message: string, result: string, patient: string, type: string) {
super(message)
this.message = message
... | const labError = {} as LabError
if (!lab.patient) {
labError.patient = 'labs.requests.error.patientRequired'
}
if (!lab.type) {
labError.type = 'labs.requests.error.typeRequired'
}
if (!isEmpty(labError)) {
labError.message = 'labs.requests.error.unableToRequest'
}
return labError
}
expo... |
export function validateLabRequest(lab: Partial<Lab>): LabError { | random_line_split |
validate-lab.ts | import isEmpty from 'lodash/isEmpty'
import Lab from '../../shared/model/Lab'
export class LabError extends Error {
message: string
result?: string
patient?: string
type?: string
| (message: string, result: string, patient: string, type: string) {
super(message)
this.message = message
this.result = result
this.patient = patient
this.type = type
}
}
export function validateLabRequest(lab: Partial<Lab>): LabError {
const labError = {} as LabError
if (!lab.patient) {
... | constructor | identifier_name |
validate-lab.ts | import isEmpty from 'lodash/isEmpty'
import Lab from '../../shared/model/Lab'
export class LabError extends Error {
message: string
result?: string
patient?: string
type?: string
constructor(message: string, result: string, patient: string, type: string) {
super(message)
this.message = message
... | {
const labError = {} as LabError
if (!lab.result) {
labError.result = 'labs.requests.error.resultRequiredToComplete'
labError.message = 'labs.requests.error.unableToComplete'
}
return labError
} | identifier_body | |
validate-lab.ts | import isEmpty from 'lodash/isEmpty'
import Lab from '../../shared/model/Lab'
export class LabError extends Error {
message: string
result?: string
patient?: string
type?: string
constructor(message: string, result: string, patient: string, type: string) {
super(message)
this.message = message
... |
if (!lab.type) {
labError.type = 'labs.requests.error.typeRequired'
}
if (!isEmpty(labError)) {
labError.message = 'labs.requests.error.unableToRequest'
}
return labError
}
export function validateLabComplete(lab: Partial<Lab>): LabError {
const labError = {} as LabError
if (!lab.result) {
... | {
labError.patient = 'labs.requests.error.patientRequired'
} | conditional_block |
test.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 ... |
_ => {
debug!("this is a test function");
let test = Test {
span: i.span,
path: self.cx.path.clone(),
bench: is_bench_fn(i),
ignore: is_ignored(self.cx, i),
... | {
let sess = self.cx.sess;
sess.span_fatal(i.span,
"unsafe functions cannot be used for \
tests");
} | conditional_block |
test.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Code that genera... | // 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.
// | random_line_split | |
test.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 ... |
return has_bench_attr && has_test_signature(i);
}
fn is_ignored(cx: @mut TestCtxt, i: @ast::item) -> bool {
i.attrs.iter().any(|attr| {
// check ignore(cfg(foo, bar))
"ignore" == attr.name() && match attr.meta_item_list() {
Some(ref cfgs) => attr::test_cfg(cx.config, cfgs.iter().m... | {
match i.node {
ast::item_fn(ref decl, _, _, ref generics, _) => {
let input_cnt = decl.inputs.len();
let no_output = match decl.output.node {
ast::ty_nil => true,
_ => false
};
let tparm_cnt = g... | identifier_body |
test.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 ... | (ids: ~[ast::Ident]) -> ast::Path {
ast::Path {
span: dummy_sp(),
global: false,
segments: ids.move_iter().map(|identifier| ast::PathSegment {
identifier: identifier,
lifetimes: opt_vec::Empty,
types: opt_vec::Empty,
}).collect()
}
}
fn path_n... | path_node | identifier_name |
roulette.component.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... |
_this.addPlayerRouletteFade(++i);
}
}, 500);
};
RouletteComponent.prototype.rotate = function (i) {
$("#roulette").css("transition", "transform 20s cubic-bezier(0.2, 0, 0.000000000000000000000000000000000000000001, 1)");
$("#roulette").css("transform", "rotat... | {
$("#roulette" + i).css("text-shadow", "0 0 10px #fff");
$("#roulette" + i).css("font-weight", "bold");
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.